public double CalculateFunctionalValue(List <GridValueInterpolator> muValueInterpolators)
        {
            var value = GaussLegendreRule.Integrate((x, y) =>
            {
                var functionValue = 0d;
                var densityValue  = 1d;
                var point         = VectorUtils.CreateVector(x, y);

                for (var centerIndex = 0; centerIndex < Settings.CentersSettings.CentersCount; centerIndex++)
                {
                    var centerData    = Settings.CentersSettings.CenterDatas[centerIndex];
                    var center        = centerData.Position;
                    var w             = centerData.W;
                    var a             = centerData.A;
                    var distanceValue = (point - center).L2Norm();
                    var muValue       = muValueInterpolators[centerIndex].GetGridValueAtPoint(x, y);
                    functionValue    += Math.Pow(muValue, 2) * (distanceValue / w + a) * densityValue;
                }

                return(functionValue);
            },
                                                    Settings.SpaceSettings.MinCorner[0],
                                                    Settings.SpaceSettings.MaxCorner[0],
                                                    Settings.SpaceSettings.MinCorner[1],
                                                    Settings.SpaceSettings.MaxCorner[1],
                                                    Settings.FuzzyPartitionPlacingCentersSettings.GaussLegendreIntegralOrder
                                                    );

            return(value);
        }
        public void Test1()
        {
            var matrix = Matrix <double> .Build.SparseOfArray(new double[, ]
            {
                { 1, 2, 3 },
                { 4, 5, 6 },
                { 7, 8, 9 },
            });

            var spaceSettings = new SpaceSettings
            {
                GridSize = new List <int> {
                    3, 3
                },
                MinCorner   = VectorUtils.CreateVector(0, 0),
                MaxCorner   = VectorUtils.CreateVector(10, 10),
                MetricsType = MetricsType.Euclidean,
                DensityType = DensityType.Everywhere1
            };

            var getter       = new MatrixGridValueGetter(matrix);
            var interpolator = new GridValueInterpolator(spaceSettings, getter);

            Assert.AreEqual(1, interpolator.GetGridValueAtPoint(0, 0));
            Assert.AreEqual(9, interpolator.GetGridValueAtPoint(10, 10));


            //#TODO add more cases
        }
예제 #3
0
        public double CalculateFunctionalValue()
        {
            var integralValue = GaussLegendreRule.Integrate((x, y) =>
            {
                var functionValue = 0d;
                var densityValue  = 1d;
                var psi           = _psiGridValueGetter.GetGridValueAtPoint(x, y);
                var point         = VectorUtils.CreateVector(x, y);

                for (var centerIndex = 0; centerIndex < _settings.CentersSettings.CentersCount; centerIndex++)
                {
                    var data       = _settings.CentersSettings.CenterDatas[centerIndex];
                    var position   = data.Position;
                    var distance   = (point - position).L2Norm();
                    var a          = data.A;
                    var w          = data.W;
                    var value      = (psi * psi) / ((distance / w + a) * densityValue);
                    functionValue += value;
                }

                return(functionValue);
            },
                                                            _settings.SpaceSettings.MinCorner[0],
                                                            _settings.SpaceSettings.MaxCorner[0],
                                                            _settings.SpaceSettings.MinCorner[1],
                                                            _settings.SpaceSettings.MaxCorner[1],
                                                            _settings.FuzzyPartitionPlacingCentersSettings.GaussLegendreIntegralOrder
                                                            );

            var functionalValue = 0.25d * integralValue;

            return(functionalValue);
        }
 public static PartitionSettings GetPartitionSettings()
 {
     return(new PartitionSettings
     {
         IsCenterPlacingTask = true,
         SpaceSettings = new SpaceSettings
         {
             MinCorner = VectorUtils.CreateVector(0, 0),
             MaxCorner = VectorUtils.CreateVector(10, 10),
             GridSize = new List <int> {
                 128, 128
             },
             DensityType = DensityType.Everywhere1,
             MetricsType = MetricsType.Euclidean,
             CustomDensityFunction = null,
             CustomDistanceFunction = null
         },
         CentersSettings = new CentersSettings
         {
             CentersCount = 2,
             CenterDatas = new List <CenterData>
             {
                 new CenterData
                 {
                     A = 0,
                     W = 1,
                     Position = VectorUtils.CreateVector(3.33, 5),
                     IsFixed = false
                 },
                 new CenterData
                 {
                     A = 0,
                     W = 1,
                     Position = VectorUtils.CreateVector(6.66, 5),
                     IsFixed = false
                 },
             }
         },
         FuzzyPartitionFixedCentersSettings = new FuzzyPartitionFixedCentersSettings
         {
             GradientEpsilon = 0.01,
             GradientStep = 10,
             MaxIterationsCount = 400
         },
         FuzzyPartitionPlacingCentersSettings = new FuzzyPartitionPlacingCentersSettings
         {
             CentersDeltaEpsilon = 0.01,
             GaussLegendreIntegralOrder = 32
         },
         RAlgorithmSettings = new RAlgorithmSettings
         {
             SpaceStretchFactor = 2,
             H0 = 9,
             MaxIterationsCount = 40
         }
     });
 }
예제 #5
0
        private Vector <double> GetPoint(int xIndex, int yIndex)
        {
            var xRatio     = (double)xIndex / (WidthX - 1d);
            var yRatio     = (double)yIndex / (WidthY - 1d);
            var ratioPoint = VectorUtils.CreateVector(xRatio, yRatio);
            var point      = _settings.SpaceSettings.MinCorner + ratioPoint.PointwiseMultiply(_settings.SpaceSettings.MaxCorner - _settings.SpaceSettings.MinCorner);

            return(point);
        }
        public void RAlgorithmTest1()
        {
            var function = 0;
            var gradient = new Func <Vector <double>, Vector <double> >(vector =>
            {
                return(null);
            });
            var initialX = VectorUtils.CreateVector(0, 0);

            var rAlgorithm = new RAlgorithmSolverBForm(initialX, gradient);

            rAlgorithm.DoIteration();
        }
        private List <Vector <double> > GetZeroIterationCentersPositions(PartitionSettings settings)
        {
            var zeroTaus = new List <Vector <double> >();

            var p1 = settings.SpaceSettings.MinCorner;
            var p2 = VectorUtils.CreateVector(p1[0], settings.SpaceSettings.MaxCorner[1]);

            for (var i = 0; i < settings.CentersSettings.CentersCount; i++)
            {
                //var zeroTau = settings.SpaceSettings.MinCorner.Clone();
                //
                var zeroTau = p1 + ((i + 1) / (settings.CentersSettings.CentersCount + 1d)) * (p2 - p1);
                //zeroTau += VectorUtils.CreateVector(Random.value - 0.5f, Random.value - 0.5f);
                //var zeroTau = VectorUtils.CreateVector(_zeroTau[0], _zeroTau[1]);
                zeroTaus.Add(zeroTau);
            }

            //zeroTaus = _zeroTausManual.Select(v => VectorUtils.CreateVector(v.x, v.y)).ToList();
            return(zeroTaus);
        }
        /// <summary>
        /// Calculated gradient.
        /// </summary>
        /// <param name="centerPosition">Current optimal center position, τ*.</param>
        /// <returns>Gradient vector</returns>
        public Vector <double> CalculateGradientForCenter(Vector <double> centerPosition, GridValueInterpolator muValueInterpolator)
        {
            _centerPosition = centerPosition;

            if (Settings.SpaceSettings.MetricsType != MetricsType.Euclidean)
            {
                throw new NotImplementedException($"Визначення градієнту для метрики {Settings.SpaceSettings.MetricsType} не реалізовано");
            }

            var vector = Vector <double> .Build.Sparse(Settings.SpaceSettings.DimensionsCount);

            for (var i = 0; i < Settings.SpaceSettings.DimensionsCount; i++)
            {
                var dimensionIndex = i;

                var value = GaussLegendreRule.Integrate(
                    (x, y) =>
                {
                    var densityValue = 1d;
                    var mu           = muValueInterpolator.GetGridValueAtPoint(x, y);

                    var point = VectorUtils.CreateVector(x, y);
                    var distanceGradientValue = CalculateDistanceGradientValue(point, dimensionIndex);

                    var integralFunctionValue = distanceGradientValue * densityValue * mu * mu;

                    return(integralFunctionValue);
                },
                    Settings.SpaceSettings.MinCorner[0],
                    Settings.SpaceSettings.MaxCorner[0],
                    Settings.SpaceSettings.MinCorner[1],
                    Settings.SpaceSettings.MaxCorner[1],
                    Settings.FuzzyPartitionPlacingCentersSettings.GaussLegendreIntegralOrder
                    );

                vector[i] = value;
            }

            return(vector);
        }
        public void MuGridsFixedPartition8x8Test()
        {
            const string f = "Logs.txt";

            if (File.Exists(f))
            {
                File.Delete(f);
            }
            Trace.Listeners.Add(new TextWriterTraceListener(f));

            var settings = new PartitionSettings
            {
                SpaceSettings = new SpaceSettings
                {
                    MinCorner = VectorUtils.CreateVector(0, 0),
                    MaxCorner = VectorUtils.CreateVector(10, 10),
                    GridSize  = new List <int> {
                        80, 80
                    },
                    DensityType            = DensityType.Everywhere1,
                    MetricsType            = MetricsType.Euclidean,
                    CustomDensityFunction  = null,
                    CustomDistanceFunction = null
                },
                CentersSettings = new CentersSettings
                {
                    CentersCount = 2,
                    CenterDatas  = new List <CenterData>
                    {
                        new CenterData
                        {
                            A        = 0,
                            W        = 1,
                            Position = VectorUtils.CreateVector(1, 1),
                            IsFixed  = true
                        },
                        new CenterData
                        {
                            A = 0,
                            W = 1,
                            //Position = VectorUtils.CreateVector(2, 4),
                            Position = VectorUtils.CreateVector(9, 1),
                            IsFixed  = true
                        },
                    }
                },
                FuzzyPartitionFixedCentersSettings = new FuzzyPartitionFixedCentersSettings
                {
                    GradientEpsilon    = 0.001,
                    GradientStep       = 10,
                    MaxIterationsCount = 400
                },
                FuzzyPartitionPlacingCentersSettings = new FuzzyPartitionPlacingCentersSettings
                {
                    GaussLegendreIntegralOrder = 4
                }
            };

            var calculator = new FuzzyPartitionFixedCentersAlgorithm(settings);
            var partition  = calculator.BuildPartition(out var psiGrid);

            Trace.WriteLine($"PerformedIterationsCount = {calculator.PerformedIterationsCount}");
            var muValueGetters = partition.Select(v => new GridValueInterpolator(settings.SpaceSettings, new MatrixGridValueGetter(v))).ToList();

            var targetFunctionalCalculator = new TargetFunctionalCalculator(settings);
            var targetFunctionalValue      = targetFunctionalCalculator.CalculateFunctionalValue(muValueGetters);

            Trace.WriteLine($"Target functional value = {targetFunctionalValue}\n");

            var dualFunctionalCalculator = new DualFunctionalCalculator(settings, psiGrid.ToGridValueInterpolator(settings));
            var dualFunctionalValue      = dualFunctionalCalculator.CalculateFunctionalValue();

            Trace.WriteLine($"Dual functional value = {dualFunctionalValue}\n");

            Trace.WriteLine("Center #1 Mu matrix:");
            MatrixUtils.WriteMatrix(partition[0], WriteLine, 3);

            Trace.WriteLine("Center #2 Mu matrix:");
            MatrixUtils.WriteMatrix(partition[1], WriteLine, 3);

            var sum = partition.Aggregate((a, b) => a + b);

            Trace.WriteLine("Sum mu matrix:");
            MatrixUtils.WriteMatrix(sum, WriteLine, 3);
            Trace.Flush();

            Assert.AreEqual(targetFunctionalValue, dualFunctionalValue, 1d);

            var q = 5;
        }
예제 #10
0
        public void Grid3x3PlacingPartitionTest()
        {
            var f = "Logs.txt";

            if (File.Exists(f))
            {
                File.Delete(f);
            }
            Trace.Listeners.Add(new TextWriterTraceListener(f));

            var settings = new PartitionSettings
            {
                IsCenterPlacingTask = false,
                SpaceSettings       = new SpaceSettings
                {
                    MinCorner = VectorUtils.CreateVector(0, 0),
                    MaxCorner = VectorUtils.CreateVector(10, 10),
                    GridSize  = new List <int> {
                        8, 8
                    },
                    DensityType            = DensityType.Everywhere1,
                    MetricsType            = MetricsType.Euclidean,
                    CustomDensityFunction  = null,
                    CustomDistanceFunction = null
                },
                CentersSettings = new CentersSettings
                {
                    CentersCount = 2,
                    CenterDatas  = new List <CenterData>
                    {
                        new CenterData
                        {
                            A        = 0,
                            W        = 1,
                            Position = VectorUtils.CreateVector(2, 5),
                            IsFixed  = true
                        },
                        new CenterData
                        {
                            A        = 0,
                            W        = 1,
                            Position = VectorUtils.CreateVector(8, 5),
                            IsFixed  = true
                        },
                    }
                },
                FuzzyPartitionFixedCentersSettings = new FuzzyPartitionFixedCentersSettings
                {
                    GradientEpsilon    = 0.01,
                    GradientStep       = 0.1,
                    MaxIterationsCount = 400
                },
                FuzzyPartitionPlacingCentersSettings = new FuzzyPartitionPlacingCentersSettings
                {
                    CentersDeltaEpsilon        = 0.1,
                    GaussLegendreIntegralOrder = 32
                },
                RAlgorithmSettings = new RAlgorithmSettings
                {
                    SpaceStretchFactor = 2,
                    H0 = 1,
                    MaxIterationsCount = 30
                }
            };

            var zeroTaus = new List <Vector <double> >
            {
                //VectorUtils.CreateVector(2, 5),
                //VectorUtils.CreateVector(8, 5)
                VectorUtils.CreateVector(1, 1),
                VectorUtils.CreateVector(10, 10)
            };

            var calculator       = new FuzzyPartitionFixedCentersAlgorithm(settings);
            var partition        = calculator.BuildPartition();
            var muValueGetters   = partition.Select(v => new GridValueInterpolator(settings.SpaceSettings, new MatrixGridValueGetter(v))).ToList();
            var placingAlgorithm = new FuzzyPartitionPlacingCentersAlgorithm(settings, zeroTaus, muValueGetters);

            while (true)
            {
                placingAlgorithm.DoIteration(muValueGetters);

                var centers = placingAlgorithm.GetCenters();

                var targetFunctionalCalculator = new TargetFunctionalCalculator(settings);
                var targetFunctionalValue      = targetFunctionalCalculator.CalculateFunctionalValue(muValueGetters);
                Trace.WriteLine($"Target functional value = {targetFunctionalValue}\n");

                for (int i = 0; i < settings.CentersSettings.CentersCount; i++)
                {
                    settings.CentersSettings.CenterDatas[i].Position = centers[i].Clone();
                    Trace.WriteLine($"Center #{i + 1}: {centers[i][0]:0.00} {centers[i][1]:0.00}");
                }

                calculator = new FuzzyPartitionFixedCentersAlgorithm(settings);
                partition  = calculator.BuildPartition();

                if (placingAlgorithm.IsStopConditionSatisfied())
                {
                    break;
                }
            }

            var list = placingAlgorithm.GetCenters();

            for (var index = 0; index < list.Count; index++)
            {
                var center = list[index];

                Trace.WriteLine($"Center #{index + 1}: {center[0]:0.00} {center[1]:0.00}");
            }

            Trace.Flush();

            var vec = VectorUtils.CreateVector(44, 4, 4, 4, 4);
            var x   = 4;
        }
예제 #11
0
        private void ShowMuGridsInfo()//IList<IGridCellValueGetter> muGrids, IGridCellValueGetter psiGrid)
        {
            if (!_showMuGridsInfo)
            {
                return;
            }

            List <Matrix <double> > muGridsCPU = null;

            if (_compareWithCpuMuGrid)
            {
                muGridsCPU = new FuzzyPartitionFixedCentersAlgorithm(Settings).BuildPartition(out var psiGrid);
                //var muGrids2 = algorithm.BuildPartition().Select(v => new MatrixGridValueGetter(v)).ToList();rg

                var targetFunctionalValueFromCpu = new TargetFunctionalCalculator(Settings)
                                                   .CalculateFunctionalValue(muGridsCPU.Select(v => new GridValueInterpolator(Settings.SpaceSettings, new MatrixGridValueGetter(v))).ToList());
                Logger.Trace($"Target functional value by CPU: {targetFunctionalValueFromCpu}");

                var dualFunctionalValueFromCpu = new DualFunctionalCalculator(Settings, new GridValueInterpolator(Settings.SpaceSettings, new MatrixGridValueGetter(psiGrid))).CalculateFunctionalValue();
                Logger.Trace($"Dual functional value by CPU: {dualFunctionalValueFromCpu}");
            }

            var muGrids = _textureToGridConverter.GetGridCellsGetters(_muGridsTexture, Settings);

            for (var index = 0; index < muGrids.Count; index++)
            {
                if (_compareWithCpuMuGrid)
                {
                    var muGridCPU = muGridsCPU[index];
                    Logger.Trace($"Mu Matrix by CPU for the center #{index + 1}");
                    MatrixUtils.WriteMatrix(
                        Settings.SpaceSettings.GridSize[0],
                        Settings.SpaceSettings.GridSize[1],
                        (i, i1) => muGridCPU[i, i1],
                        Logger.Trace,
                        3);
                }

                var muGrid = muGrids[index];

                Logger.Trace($"Mu Matrix by GPU for the center #{index + 1}");
                MatrixUtils.WriteMatrix(
                    Settings.SpaceSettings.GridSize[0],
                    Settings.SpaceSettings.GridSize[1],
                    (i, i1) => muGrid.GetValue(i, i1),
                    Logger.Trace,
                    3);
            }

            Logger.Trace("Sum mu matrix:");
            MatrixUtils.WriteMatrix(
                Settings.SpaceSettings.GridSize[0],
                Settings.SpaceSettings.GridSize[1],
                (i, i1) =>
            {
                var v = 0d;
                foreach (var t in muGrids)
                {
                    v += t.GetValue(i, i1);
                }
                return(v);
            },
                Logger.Trace,
                3);

            var psiGridCalculator = _textureToGridConverter.GetGridValueTextureCalculator(_psiGridTexture, Settings);

            Logger.Trace("Psi matrix:");
            MatrixUtils.WriteMatrix(
                Settings.SpaceSettings.GridSize[0],
                Settings.SpaceSettings.GridSize[1],
                (i, i1) => psiGridCalculator.GetValue(i, i1),
                Logger.Trace,
                3);

            for (var i = 0; i < Settings.CentersSettings.CentersCount; i++)
            {
                Logger.Trace($"Computed Mu grid #{i + 1} from Psi grid:");
                MatrixUtils.WriteMatrix(
                    Settings.SpaceSettings.GridSize[0],
                    Settings.SpaceSettings.GridSize[1],
                    (xIndex, yIndex) =>
                {
                    var psiValue     = psiGridCalculator.GetValue(xIndex, yIndex);
                    var xRatio       = (double)xIndex / (Settings.SpaceSettings.GridSize[0] - 1d);
                    var yRatio       = (double)yIndex / (Settings.SpaceSettings.GridSize[1] - 1d);
                    var ratioPoint   = VectorUtils.CreateVector(xRatio, yRatio);
                    var point        = Settings.SpaceSettings.MinCorner + ratioPoint.PointwiseMultiply(Settings.SpaceSettings.MaxCorner - Settings.SpaceSettings.MinCorner);
                    var densityValue = 1d;
                    var distance     = (Settings.CentersSettings.CenterDatas[i].Position - point).L2Norm();
                    var newMuValue   = -psiValue / (2d * densityValue * (distance / 1d + 0d));
                    return(newMuValue);
                },
                    Logger.Trace,
                    3);
            }
        }