Example #1
0
        /// <summary>Predicts the given o.</summary>
        /// <param name="y">The Vector to process.</param>
        /// <returns>An object.</returns>
        public override double Predict(Vector y)
        {
            var distances = new Tuple<int, double>[this.X.Rows];

            // happens per slot so we are good to parallelize
            Parallel.For(0, this.X.Rows, i => distances[i] = new Tuple<int, double>(i, (y - this.X.Row(i)).Norm(2)));

            var slice = distances.OrderBy(t => t.Item2).Take(this.K).Select(i => i.Item1);

            return this.Y.Slice(slice).Mode();
        }
Example #2
0
        public override double Predict(Vector y)
        {
            Tuple<int, double>[] distances = new Tuple<int, double>[y.Length];

            //for (int i = 0; i < X.RowCount; i++) // distance (y - x[i]).Norm
            //    distances[i] = new Tuple<int, double>(i, (y - X.Row(i)).Norm(2));

            // happens per slot so we are good to parallelize
            Parallel.For(0, X.Rows, i => distances[i] = new Tuple<int, double>(i, (y - X.Row(i)).Norm(2)));

            var slice = distances
                            .OrderBy(t => t.Item2)
                            .Take(K)
                            .Select(i => i.Item1);

            return Y.Slice(slice).Mode();
        }
Example #3
0
        /// <summary>Predicts the given o.</summary>
        /// <param name="y">The Vector to process.</param>
        /// <returns>An object.</returns>
        public override double Predict(Vector y)
        {
            this.Preprocess(y);

            Tuple<int, double>[] distances = new Tuple<int, double>[X.Rows];

            // happens per slot so we are good to parallelize
            for (int i = 0; i < X.Rows; i++)
            {
                distances[i] = new Tuple<int, double>(i, (y - X.Row(i)).Norm(2));
            }

            var slice = distances
                            .OrderBy(t => t.Item2)
                            .Take(K)
                            .Select(i => i.Item1);

            return Y.Slice(slice).Mode();
        }
        protected virtual RgbSpectrum SamplePath1(int x, int y)
        {
            float lambda;
            Tuple<float, float>[] c = new Tuple<float, float>[MaxSpectralSamples];
            float dLambda = (SampledSpectrum.sampledLambdaEnd - SampledSpectrum.sampledLambdaStart) / ((float)MaxSpectralSamples + 1f);

            for (int l = 0; l < MaxSpectralSamples; l++)
            {
                lambda = SampleWavelength(rnd.NextFloat());
                RayData cameraRay;
                Scene.GenerateCameraRay(x, y, out cameraRay);
                var pix = EvalRadiance(ref cameraRay, lambda, 0);
                totalSamples++;
                c[l] = new Tuple<float, float>(lambda, pix);
                //lambda += dLambda;
            }
            c = c.OrderBy(item => item.Item1).ToArray();
            var lms = c.Select(p => p.Item1).ToArray();
            var vals = c.Select(p => p.Item2).ToArray();
            var spd = new IrregularSPD(lms, vals, MaxSpectralSamples, dLambda);
            //RegularSPD spd = new RegularSPD(vals, SampledSpectrum.sampledLambdaStart, SampledSpectrum.sampledLambdaEnd, MaxSpectralSamples);
            var pixV = spd.ToRgb();
            return pixV;
        }
        public override sealed void Advance(RayBuffer rayBuffer, SampleBuffer consumer)
        {
            int currentTriangleIndex = 0;
#if VERBOSE

            try {
#endif

            if (((PathState == PathTracerPathState.ShadowRaysOnly) || (PathState == PathTracerPathState.NextVertex)) &&
                (tracedShadowRayCount > 0))
            {
                for (int i = 0; i < tracedShadowRayCount; ++i)
                {
                    RayHit shadowRayHit = rayBuffer.rayHits[secRays[i].ShadowRayIndex];
                    RgbSpectrum attenuation;
                    bool continueTrace;
                    if (this.ShadowRayTest(ref shadowRayHit, ref secRays[i].ShadowRay, out attenuation, out continueTrace))
                    {
                        //                            Radiance.MADD()
                        Radiance += attenuation * ((secRays[i].Throughput) / secRays[i].Pdf);
                        pathWeight *= secRays[i].Pdf;
                    }
                }

                if (PathState == PathTracerPathState.ShadowRaysOnly)
                {
                    Splat(consumer);
                    return;
                }
                tracedShadowRayCount = 0;
            }
            RayHit rayHit = rayBuffer.rayHits[RayIndex];
            Vector wo = -PathRay.Dir;

            depth++;
            bool missed = rayHit.Index == 0xffffffffu;
            if (missed || PathState == PathTracerPathState.ShadowRaysOnly || depth > scene.MaxPathDepth)
            {
                if (missed)
                {
                    Radiance += this.scene.SampleEnvironment(ref wo) * Throughput;
                }
                Splat(consumer);

                return;
            }

            // Something was hit
            if (hitInfo == null)
            {
                hitInfo = SurfaceSampler.GetIntersection(ref PathRay, ref rayHit);
            }
            else
            {
                SurfaceSampler.GetIntersection(ref PathRay, ref rayHit, ref hitInfo);
            }
            currentTriangleIndex = (int)rayHit.Index;

            if (hitInfo == null)
            {
                Debugger.Break();
            }
            //If Hit light)

            if (hitInfo.IsLight)
            {
                if (specularBounce || depth == 1)
                {
                    var lt = scene.GetLightByIndex(currentTriangleIndex);
                    if (lt != null)
                    {
                        var le = (RgbSpectrum)(lt.Le(ref wo));
                        Radiance += Throughput * le;
                    }
                }
                Splat(consumer);

                return;
            }

            var hitPoint = PathRay.Point(rayHit.Distance);

            tracedShadowRayCount = 0;
            var bsdf = hitInfo.MMaterial;

            if (!hitInfo.TextureData.Alpha.IsBlack())
            {
                Throughput *= (RgbSpectrum.UnitSpectrum() - (RgbSpectrum) hitInfo.TextureData.Alpha);
                PathRay = new RayData(hitPoint, -wo);
                return;
            }

            if (bsdf.IsDiffuse())
            {
                float lightStrategyPdf = LightSampler.StrategyPdf;
                //scene.ShadowRaysPerSample/(float)scene.Lights.Length;
                RgbSpectrum lightTroughtput = Throughput * hitInfo.Color;
                int rs = 0;
            @lstart:
                LightSampler.EvaluateShadow(ref hitPoint, ref hitInfo.Normal, Sample.GetLazyValue(),
                                            Sample.GetLazyValue(), Sample.GetLazyValue(), ref ls);
                for (int index = 0; index < ls.Length; index++)
                {

                    if (ls[index].Pdf <= 0f)
                        continue;
                    secRays[tracedShadowRayCount].Throughput = (RgbSpectrum)(ls[index].Spectrum);
                    secRays[tracedShadowRayCount].Pdf = ls[index].Pdf;
                    secRays[tracedShadowRayCount].ShadowRay = ls[index].LightRay;
                    Vector lwi = secRays[tracedShadowRayCount].ShadowRay.Dir;
                    RgbSpectrum fs;
                    hitInfo.MMaterial.f(ref secRays[tracedShadowRayCount].ShadowRay.Dir, ref wo, ref hitInfo.ShadingNormal, ref Throughput, out fs, types: BrdfType.Diffuse);
                    secRays[tracedShadowRayCount].Throughput *= lightTroughtput *
                                                                Vector.AbsDot(ref hitInfo.Normal, ref lwi) *
                                                                fs;
                    if (!secRays[tracedShadowRayCount].Throughput.IsBlack())
                    {
                        secRays[tracedShadowRayCount].Pdf /= lightStrategyPdf;
                        tracedShadowRayCount++;
                    }
                }
                if (tracedShadowRayCount == 0 && rs < lightResampling)
                {
                    rs++;
                    goto @lstart;
                }

                if (rs > 0)
                {
                    for (int index = 0; index < secRays.Length; index++)
                    {
                        secRays[index].Pdf /= (1f+rs);
                    }
                }
            }

            float fPdf = 0f;
            var wi = new Vector();
            RgbSpectrum f;

            if (depth > 1)
            {

                f = bsdf.Sample_f(ref wo, out wi, ref hitInfo.Normal, ref hitInfo.ShadingNormal, ref Throughput,
                                  Sample.GetLazyValue(), Sample.GetLazyValue(),
                                  Sample.GetLazyValue(), ref hitInfo.TextureData,
                                  out fPdf, out specularBounce);
            }
            else
            {
                int samplesCount = 4;
                var bsdfData = new Tuple<Vector, float, RgbSpectrum>[samplesCount];
                var totalF = new RgbSpectrum();
                float totalPdf =0;
                for (int i = 0; i < samplesCount; i++)
                {
                    Vector Wi;
                    float pdf;
                    var Fr = bsdf.Sample_f(ref wo, out Wi, ref hitInfo.Normal, ref hitInfo.ShadingNormal, ref Throughput,
                           Sample.GetLazyValue(), Sample.GetLazyValue(),
                           Sample.GetLazyValue(), ref hitInfo.TextureData,
                           out pdf, out specularBounce);
                    totalF += Fr;
                    totalPdf += pdf;

                    bsdfData[i] = new Tuple<Vector, float, RgbSpectrum>(Wi, pdf, Fr);
                }

                var bsdfSamples = bsdfData.OrderBy(i => i.Item2).ToArray();
                fPdf = bsdfSamples[0].Item2;
                wi = bsdfSamples[0].Item1;
                f = totalF/4f;
            }

            if ((fPdf <= 0.0f) || f.IsBlack())
            {
                if (tracedShadowRayCount > 0)
                    PathState = PathTracerPathState.ShadowRaysOnly;
                else
                {
                    Splat(consumer);

                }
                return;
            }
            pathWeight *= fPdf;
            Throughput *= (f * hitInfo.Color) / fPdf;

            if (depth > scene.MaxPathDepth)
            {
                float prob = Math.Max(Throughput.Filter(), scene.RussianRuletteImportanceCap);
                if (prob >= Sample.GetLazyValue())
                {
                    Throughput /= prob;
                    pathWeight *= prob;
                }
                else
                {
                    if (tracedShadowRayCount > 0)
                        PathState = PathTracerPathState.ShadowRaysOnly;
                    else
                    {
                        Splat(consumer);

                    }

                    return;
                }
            }

            PathRay.Org = hitPoint;
            PathRay.Dir = wi.Normalize();
            PathState = PathTracerPathState.NextVertex;

#if VERBOSE
            }
            catch (Exception ex) {
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine("Advance path exception");
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine("Error triangle {0}", currentTriangleIndex);
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine(ex.Message);
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine(ex.StackTrace);

            }
#endif
        }
        private static void DrawNNOutputs(UniformGrid panel, Tuple<LifeEventType, double>[] outputs)
        {
            // Keep them sorted so that it's consistent frame to frame (make sure they don't jump around)
            outputs = outputs.
                OrderBy(o => o.Item1.ToString()).
                ToArray();

            foreach (var nnout in outputs)
            {
                #region OLD

                //Grid grid = new Grid()
                //{
                //    Margin = new Thickness(2),
                //};
                //grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(nnout.Item2, GridUnitType.Star) });
                //grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1 - nnout.Item2, GridUnitType.Star) });

                //// Filled %
                //Border border = new Border()
                //{
                //    Background = Brushes.DarkTurquoise,
                //    CornerRadius = new CornerRadius(0),
                //    HorizontalAlignment = HorizontalAlignment.Stretch,
                //    VerticalAlignment = VerticalAlignment.Stretch,
                //};
                //Grid.SetColumn(border, 0);
                //grid.Children.Add(border);

                //// Remainder
                //border = new Border()
                //{
                //    Background = Brushes.Teal,
                //    CornerRadius = new CornerRadius(0),
                //    HorizontalAlignment = HorizontalAlignment.Stretch,
                //    VerticalAlignment = VerticalAlignment.Stretch,
                //};
                //Grid.SetColumn(border, 1);
                //grid.Children.Add(border);

                //// Outline
                //border = new Border()
                //{
                //    BorderBrush = Brushes.Coral,
                //    BorderThickness = new Thickness(1),
                //    CornerRadius = new CornerRadius(0),
                //    HorizontalAlignment = HorizontalAlignment.Stretch,
                //    VerticalAlignment = VerticalAlignment.Stretch,
                //};
                //Grid.SetColumn(border, 0);
                //Grid.SetColumnSpan(border, 2);
                //grid.Children.Add(border);

                //// Text
                //TextBlock text = new TextBlock()
                //{
                //    Text = string.Format("{0} {1}", nnout.Item1, (nnout.Item2 * 100).ToInt_Round()),
                //    Padding = new Thickness(6, 4, 6, 4),
                //    HorizontalAlignment = HorizontalAlignment.Center,
                //    VerticalAlignment = VerticalAlignment.Center,
                //};
                //Grid.SetColumn(text, 0);
                //Grid.SetColumnSpan(text, 2);
                //grid.Children.Add(text);

                #endregion

                panel.Children.Add(GetNNOutputBar(nnout.Item1.ToString(), nnout.Item2));
            }
        }
        private Expression BuildIndexExpression(SqlTableExpression table, string indexName, Tuple<IndexAttribute, PropertyDescriptor>[] properties)
        {
            var unique = properties.Select(c => c.Item1).Any(c => c.Unique);
            var lowercaseIndex = properties.Select(c => c.Item1).Any(c => c.LowercaseIndex);
            var indexType = properties.Select(c => c.Item1.IndexType).FirstOrDefault(c => c != IndexType.Default);

            var sorted = properties.OrderBy(c => c.Item1.CompositeOrder, Comparer<int>.Default);

            var indexedColumns = new List<SqlIndexedColumnExpression>();

            foreach (var attributeAndProperty in sorted)
            {
                foreach (var columnInfo in QueryBinder.GetColumnInfos(this.model.TypeDescriptorProvider, attributeAndProperty.Item2))
                {
                    indexedColumns.Add(new SqlIndexedColumnExpression(new SqlColumnExpression(columnInfo.DefinitionProperty.PropertyType, null, columnInfo.ColumnName), attributeAndProperty.Item1.SortOrder, attributeAndProperty.Item1.LowercaseIndex));
                }
            }

            return new SqlCreateIndexExpression(indexName, table, unique, lowercaseIndex, indexType, false, indexedColumns);
        }
Example #8
-1
        private void SetClosestIndex(Color color)
        {
            ColorMine.ColorSpaces.Rgb rgbColorStop = new ColorMine.ColorSpaces.Rgb() { R = color.R, G = color.G, B = color.B };
            Tuple<Color, double, int>[] colorWeights = new Tuple<Color, double, int>[Width];

            // Create a color weight for every cell compared to the color stop
            for (int x = 0; x < Width; x++)
            {
                ColorMine.ColorSpaces.Rgb rgbColor = new ColorMine.ColorSpaces.Rgb() { R = this[x, 0].Foreground.R, G = this[x, 0].Foreground.G, B = this[x, 0].Foreground.B };
                ColorMine.ColorSpaces.Cmy cmyColor = rgbColor.To<ColorMine.ColorSpaces.Cmy>();

                colorWeights[x] = new Tuple<Color, double, int>(this[x, 0].Foreground, rgbColorStop.Compare(cmyColor, new ColorMine.ColorSpaces.Comparisons.Cie1976Comparison()), x);

            }

            var foundColor = colorWeights.OrderBy(t => t.Item2).First();
            _selectedPosition = foundColor.Item3;
            this.IsDirty = true;
        }
Example #9
-1
        public override void Compose()
        {
            if (this.IsDirty)
            {
                this.Fill(Color.White, Color.Black, 0, null);

                _positions = Width;
                ColorGradient gradient = new ColorGradient(Color.Red, Color.Yellow, Color.Green, Color.Turquoise, Color.Blue, Color.Purple, Color.Red);

                for (int x = 0; x < Width; x++)
                {
                    this[x, 0].GlyphIndex = 219;
                    this[x, 0].Foreground = gradient.Lerp((float)x / (float)(Width - 1));
                }

                this[_selectedPosition, 1].GlyphIndex = 30;
                this[_selectedPosition, 1].Foreground = Color.LightGray;//this[_selectedPosition, 0].Foreground;

                // Build an array of all the colors
                Color[] colors = new Color[Width];
                for (int x = 0; x < Width; x++)
                    colors[x] = this[x, 0].Foreground;

                List<int> colorIndexesFinished = new List<int>(Width);

                foreach (var stop in gradient.Stops)
                {
                    ColorMine.ColorSpaces.Rgb rgbColorStop = new ColorMine.ColorSpaces.Rgb() { R = stop.Color.R, G = stop.Color.G, B = stop.Color.B };
                    Tuple<Color, double, int>[] colorWeights = new Tuple<Color, double, int>[Width];

                    // Create a color weight for every cell compared to the color stop
                    for (int x = 0; x < Width; x++)
                    {
                        if (!colorIndexesFinished.Contains(x))
                        {
                            ColorMine.ColorSpaces.Rgb rgbColor = new ColorMine.ColorSpaces.Rgb() { R = colors[x].R, G = colors[x].G, B = colors[x].B };
                            ColorMine.ColorSpaces.Cmy cmyColor = rgbColor.To<ColorMine.ColorSpaces.Cmy>();

                            colorWeights[x] = new Tuple<Color, double, int>(colors[x], rgbColorStop.Compare(cmyColor, new ColorMine.ColorSpaces.Comparisons.Cie1976Comparison()), x);
                        }
                        else
                            colorWeights[x] = new Tuple<Color, double, int>(colors[x], 10000, x);
                    }

                    var foundColor = colorWeights.OrderBy(t => t.Item2).First();

                    this[foundColor.Item3, 0].Foreground = stop.Color;
                    colorIndexesFinished.Add(foundColor.Item3);
                }

                this.IsDirty = false;
            }
        }
Example #10
-1
        private void SetClosestIndex(Color color)
        {
            ColorMine.ColorSpaces.Rgb rgbColorStop = new ColorMine.ColorSpaces.Rgb() { R = color.R, G = color.G, B = color.B };
            Tuple<Color, double, int>[] colorWeights = new Tuple<Color, double, int>[textSurface.Cells.Length];

            // Create a color weight for every cell compared to the color stop
            for (int x = 0; x < textSurface.Cells.Length; x++)
            {
                ColorMine.ColorSpaces.Rgb rgbColor = new ColorMine.ColorSpaces.Rgb() { R = this[x].Background.R, G = this[x].Background.G, B = this[x].Background.B };
                ColorMine.ColorSpaces.Cmy cmyColor = rgbColor.To<ColorMine.ColorSpaces.Cmy>();

                colorWeights[x] = new Tuple<Color, double, int>(this[x].Background, rgbColorStop.Compare(cmyColor, new ColorMine.ColorSpaces.Comparisons.Cie1976Comparison()), x);

            }

            var foundColor = colorWeights.OrderBy(t => t.Item2).First();

            this[_selectedColorPosition.X, _selectedColorPosition.Y].GlyphIndex = 0;
            _selectedColorPosition = SadConsole.Consoles.TextSurface.GetPointFromIndex(foundColor.Item3, Width);
            this[_selectedColorPosition.X, _selectedColorPosition.Y].GlyphIndex = 4;

            this.IsDirty = true;
        }