Exemple #1
0
        private void OptimalIndexTestCase(
            int hilbertTries, int minClusterSize, int maxClusterSize, int dimensions, int clusterCount, int acceptableClusterCount,
            int bitsPerDimension, int outlierSize, int noiseSkipBy)
        {
            var data = new GaussianClustering
            {
                ClusterCount   = clusterCount,
                Dimensions     = dimensions,
                MaxCoordinate  = 1000,
                MinClusterSize = minClusterSize,
                MaxClusterSize = maxClusterSize
            };
            var clusters = data.MakeClusters();
            var points   = clusters.Points().Select(p => HilbertPoint.CastOrConvert(p, bitsPerDimension, true)).ToList();
            var results  = OptimalIndex.Search(
                points,
                outlierSize,
                noiseSkipBy,
                hilbertTries,     // maxTrials
                4                 // maxIterationsWithoutImprovement
                );
            var message = $"Estimated cluster count = {results.EstimatedClusterCount}, actual = {clusterCount}, acceptable = {acceptableClusterCount}";

            Console.WriteLine(message);
            Assert.LessOrEqual(results.EstimatedClusterCount, acceptableClusterCount, $"HilbertIndex fragmented by more than 50%: {message}");
        }
Exemple #2
0
        public void AllColorPairsClosestClusterTest(int nPoints, int dimensions, int numClusters, int numCurvesToTry)
        {
            var rankHistogram = new int[numClusters + 1];             // We will skip the first element so as to have a one-based array.
            var data          = new GaussianClustering
            {
                ClusterCount   = numClusters,
                Dimensions     = dimensions,
                MaxCoordinate  = 1000,
                MinClusterSize = nPoints,
                MaxClusterSize = nPoints
            };
            var worstDistanceRatio = 1.0;
            var ratioSum           = 0.0;
            var ratioCount         = 0;
            var clusters           = data.MakeClusters();

            var bitsPerDimension = (1 + data.MaxCoordinate).SmallestPowerOfTwo();
            var results          = OptimalIndex
                                   .Search(
                clusters.Points().Select(up => HilbertPoint.CastOrConvert(up, bitsPerDimension, true)).ToList(),
                5 /*outlier size */, 10 /* NoiseSkipBy */, 1 /* ReducedNoiseSkipBy */, numCurvesToTry
                );

            var pccp1         = new PolyChromaticClosestPoint <string>(clusters, results.Index);
            var allColorPairs = pccp1.FindAllClustersApproximately();

            foreach (var color1 in clusters.ClassLabels())
            {
                var exact       = pccp1.FindClusterExhaustively(color1).Swap(color1);
                var color1Pairs = allColorPairs
                                  .Where(cp => cp.Color1.Equals(color1) || cp.Color2.Equals(color1))
                                  .Select(cp => cp.Swap(color1))
                                  .ToList();
                var approximateColor2Distance = color1Pairs.First(cp => cp.Color2.Equals(exact.Color2)).SquareDistance;
                var approximateRank           = color1Pairs.Count(cp => cp.SquareDistance < approximateColor2Distance) + 1;
                rankHistogram[approximateRank]++;
#pragma warning disable RECS0018 // Comparison of floating point numbers with equality operator
                var ratio = exact.SquareDistance == 0.0 ? 0 : approximateColor2Distance / (double)exact.SquareDistance;
#pragma warning restore RECS0018 // Comparison of floating point numbers with equality operator
                ratioSum += ratio;
                ratioCount++;
                worstDistanceRatio = Math.Max(worstDistanceRatio, ratio);
            }
            Debug.WriteLine(string.Format("Worst distance overage   = {0:N3}%", (worstDistanceRatio - 1.0) * 100.0));
            Debug.WriteLine(string.Format("Average distance overage = {0:N3}%", ((ratioSum / ratioCount) - 1.0) * 100.0));
            for (var iRank = 1; iRank <= numClusters; iRank++)
            {
                if (rankHistogram[iRank] > 0 || iRank < 4)
                {
                    Debug.WriteLine(string.Format("For {0} Clusters the closest cluster found was Ranked #{1}.", rankHistogram[iRank], iRank));
                }
            }
            // Accept a win, place or show: the true closest cluster shows up as no worse than the 3rd ranked cluster according to the approximate measure.
            Assert.IsTrue(rankHistogram[1] + rankHistogram[2] + rankHistogram[3] == numClusters,
                          string.Format("Found the closest cluster for {0} colors", rankHistogram[1])
                          );
        }
        /// <summary>
        /// Create an index of all the points in a Classification, optionally adding a new dimension to each point to hold
        /// that point's classification index.
        /// </summary>
        /// <param name="clusters">Clusters of points, which could be UnsignedPoints or HilbertPoints.</param>
        /// <param name="bitsPerDimension">Bits per dimension to use when transforming UnsignedPoints into HilbertPoints,
        /// should that be necessary.
        /// If a non-positive number, compute the value by studying the data, using the smallest number capable of accommodating
        /// the largest coordinate values.</param>
        /// <param name="addClassificationDimension">If set to <c>true</c> add a classification dimension to the end of each point.
        /// The value will be the index of that point's cluster. Cluster ordering is arbitrary and dependent on the order that
        /// the set Classification.LabelToPoints.Values iterates over them.</param>
        public HilbertIndex(Classification <UnsignedPoint, string> clusters, int bitsPerDimension = 0, bool addClassificationDimension = false)
        {
            if (bitsPerDimension <= 0)
            {
                bitsPerDimension = FindBitsPerDimension(clusters.Points());
            }

            UnsortedPoints = new List <HilbertPoint>();
            foreach (var clusterWithNumber in clusters.LabelToPoints.Values.Select((c, i) => new { Cluster = c, Index = (uint)i }))
            {
                UnsortedPoints.AddRange(
                    clusterWithNumber.Cluster
                    .Select(p => addClassificationDimension ? p.AppendCoordinate(clusterWithNumber.Index) : p)
                    .Select(p => HilbertPoint.CastOrConvert(p, bitsPerDimension, true))
                    );
            }
            InitIndexing();
        }
Exemple #4
0
        public void ClosestOfFiftyClusters()
        {
            int hilbertTries           = 1000;
            var correctColorCount      = 0;
            var correctCrosscheckCount = 0;
            var correctDistanceCount   = 0;
            var nPoints      = 100;
            var dimensions   = 100;
            var clusterCount = 50;
            var data         = new GaussianClustering
            {
                ClusterCount   = clusterCount,
                Dimensions     = dimensions,
                MaxCoordinate  = 1000,
                MinClusterSize = nPoints,
                MaxClusterSize = nPoints
            };

            var closestExact = new PolyChromaticClosestPoint <string> .ClosestPair();

            var closestApproximate = new PolyChromaticClosestPoint <string> .ClosestPair();

            var bitsPerDimension = (1 + data.MaxCoordinate).SmallestPowerOfTwo();

            var clusters = data.MakeClusters();

            Assert.AreEqual(clusterCount, clusters.NumPartitions, "Test data are grouped into fewer clusters than requested.");

            PolyChromaticClosestPoint <string> pccp;

            if (hilbertTries <= 1)
            {
                pccp = new PolyChromaticClosestPoint <string>(clusters);
            }
            else
            {
                var reducedNoiseSkipBy = 1;
                var results            = OptimalIndex.Search(
                    clusters.Points().Select(up => HilbertPoint.CastOrConvert(up, bitsPerDimension, true)).ToList(),
                    5 /*outlier size */, 10 /* NoiseSkipBy */, reducedNoiseSkipBy, hilbertTries
                    );
                pccp = new PolyChromaticClosestPoint <string>(clusters, results.Index);
            }
            foreach (var color in pccp.Clusters.ClassLabels())
            {
                var exact       = pccp.FindClusterExhaustively(color);
                var approximate = pccp.FindClusterApproximately(color);
                var crosscheck  = pccp.FindClusterIteratively(color);

                if (exact.SquareDistance >= approximate.SquareDistance)
                {
                    correctDistanceCount++;
                }

                if (exact.Color2.Equals(approximate.Color2))
                {
                    correctColorCount++;
                }

                if (exact.Color2.Equals(crosscheck.Color2))
                {
                    correctCrosscheckCount++;
                }

                if (exact.SquareDistance < closestExact.SquareDistance)
                {
                    closestExact = exact;
                }

                if (approximate.SquareDistance < closestApproximate.SquareDistance)
                {
                    closestApproximate = approximate;
                }

                var ratio = approximate.SquareDistance / (double)exact.SquareDistance;
                Console.WriteLine(string.Format("Exact {0} vs Approx. {1} vs Cross {2}. Over by {3:N3}%", exact, approximate, crosscheck, (ratio - 1.0) * 100.0));
            }

            if (closestExact.SquareDistance >= closestApproximate.SquareDistance)
            {
                Console.WriteLine("DID FIND the closest pair of points overall. Exact {0}. Approx {1}", closestExact, closestApproximate);
            }
            else
            {
                Console.WriteLine("DID NOT FIND the closest pair of points overall. Exact {0}. Approx {1}", closestExact, closestApproximate);
            }

            Assert.IsTrue(correctColorCount == clusterCount && correctDistanceCount == clusterCount,
                          string.Format("Of {0} clusters, only {1} searches found the closest cluster and {2} found the shortest distance. Crosscheck = {3}",
                                        clusterCount,
                                        correctColorCount,
                                        correctDistanceCount,
                                        correctCrosscheckCount
                                        )
                          );
        }
Exemple #5
0
        public void ClosestClusterTest(int nPoints, int dimensions, int numClusters, int numCurvesToTry, int numCurvesToKeep)
        {
            var correctColorCount    = 0;
            var correctDistanceCount = 0;
            var data = new GaussianClustering
            {
                ClusterCount   = numClusters,
                Dimensions     = dimensions,
                MaxCoordinate  = 1000,
                MinClusterSize = nPoints,
                MaxClusterSize = nPoints
            };

            var closestExact = new PolyChromaticClosestPoint <string> .ClosestPair();

            var closestApproximate = new PolyChromaticClosestPoint <string> .ClosestPair();

            var clusters = data.MakeClusters();
            var pccps    = new List <PolyChromaticClosestPoint <string> >();

            var bitsPerDimension = (1 + data.MaxCoordinate).SmallestPowerOfTwo();

            var bestIndices = OptimalIndex.SearchMany(
                clusters.Points().Select(up => HilbertPoint.CastOrConvert(up, bitsPerDimension, true)).ToList(),
                numCurvesToKeep,
                5 /*outlier size */, 10 /* NoiseSkipBy */, 1 /* ReducedNoiseSkipBy */, numCurvesToTry
                );

            //var pointLists = bestIndices.Select(result => result.Index.SortedPoints).ToList();
            //foreach (var pList in pointLists)
            //	pccps.Add(new PolyChromaticClosestPoint<string>(clusters, pList));

            var indices = bestIndices.Select(result => result.Index).ToList();

            foreach (var index in indices)
            {
                pccps.Add(new PolyChromaticClosestPoint <string>(clusters, index));
            }

            var pccp1 = pccps[0];

            foreach (var color in pccp1.Clusters.ClassLabels())
            {
                var exact       = pccp1.FindClusterExhaustively(color);
                var approximate = pccps.Select(pccp => pccp.FindClusterApproximately(color)).OrderBy(cp => cp).First();

                if (exact.SquareDistance >= approximate.SquareDistance)
                {
                    correctDistanceCount++;
                }

                if (exact.Color2.Equals(approximate.Color2))
                {
                    correctColorCount++;
                }

                if (exact.SquareDistance < closestExact.SquareDistance)
                {
                    closestExact = exact;
                }

                if (approximate.SquareDistance < closestApproximate.SquareDistance)
                {
                    closestApproximate = approximate;
                }

                var ratio = approximate.SquareDistance / (double)exact.SquareDistance;
                Console.WriteLine(string.Format("Exact {0} vs Approx. {1}. Over by {2:N3}%", exact, approximate, (ratio - 1.0) * 100.0));
            }

            if (closestExact.SquareDistance >= closestApproximate.SquareDistance)
            {
                Console.WriteLine("DID FIND the closest pair of points overall. Exact {0}. Approx {1}", closestExact, closestApproximate);
            }
            else
            {
                Console.WriteLine("DID NOT FIND the closest pair of points overall. Exact {0}. Approx {1}", closestExact, closestApproximate);
            }

            Assert.IsTrue(correctColorCount == numClusters && correctDistanceCount == numClusters,
                          string.Format("Of {0} clusters, only {1} searches found the closest cluster and {2} found the shortest distance.",
                                        numClusters,
                                        correctColorCount,
                                        correctDistanceCount
                                        )
                          );
        }
Exemple #6
0
        /// <summary>
        /// A test case for PolyChromaticClosestPoint.FindPairApproximately where clusters conform to a Gaussian distribution.
        /// </summary>
        /// <param name="nPoints">Number of points in each cluster.</param>
        /// <param name="dimensions">Number of Dimensions in each point.</param>
        /// <param name="numClusters">Number of clusters to create.</param>
        /// <param name="hilbertsToTry">Number of randomly generated Hilbert curves to try.</param>
        public void GaussianPolyChromaticPairTestCase(int nPoints, int dimensions, int numClusters, int hilbertsToTry = 1)
        {
            var successes  = 0;
            var worstRatio = 1.0;
            var color1     = "0";

            var data = new GaussianClustering
            {
                ClusterCount   = numClusters,
                Dimensions     = dimensions,
                MaxCoordinate  = 1000,
                MinClusterSize = nPoints,
                MaxClusterSize = nPoints
            };
            var clusters = data.MakeClusters();
            PolyChromaticClosestPoint <string> pccp;

            if (hilbertsToTry <= 1)
            {
                pccp = new PolyChromaticClosestPoint <string>(clusters);
            }
            else
            {
                var bitsPerDimension = (1 + data.MaxCoordinate).SmallestPowerOfTwo();
                var results          = OptimalIndex.Search(
                    clusters.Points().Select(up => HilbertPoint.CastOrConvert(up, bitsPerDimension, true)).ToList(),
                    5 /*outlier size */, 10 /* NoiseSkipBy */, 1 /* ReducedNoiseSkipBy */, hilbertsToTry
                    );
                pccp = new PolyChromaticClosestPoint <string>(clusters, results.Index);
            }
            for (var iColor2 = 1; iColor2 < numClusters; iColor2++)
            {
                var color2 = iColor2.ToString();

                var exact       = pccp.FindPairExhaustively(color1, color2);
                var approximate = pccp.FindPairApproximately(color1, color2);

                var expectedDistance = exact.SquareDistance;
                var actualDistance   = approximate.SquareDistance;

                if (actualDistance <= expectedDistance)
                {
                    successes++;
                }
                else
                {
                    worstRatio = Math.Max(worstRatio, actualDistance / (double)expectedDistance);
                }

                if (exact.SquareDistance >= approximate.SquareDistance)
                {
                    Console.WriteLine("FindPairApproximately CORRECT.   Exact {0}. Approx {1}", exact, approximate);
                }
                else
                {
                    Console.WriteLine("FindPairApproximately INCORRECT. Exact {0}. Approx {1}. Too high by {2:N3}%",
                                      exact, approximate, 100.0 * (approximate.SquareDistance / (double)exact.SquareDistance - 1.0));
                }
            }

            Assert.AreEqual(numClusters - 1, successes,
                            string.Format("Did not succeed every time. Failed {0} of {1} times. Worst distance ratio is {2:N4}. {3} points of {4} dimensions.",
                                          numClusters - successes - 1,
                                          numClusters - 1,
                                          worstRatio,
                                          nPoints,
                                          dimensions
                                          )
                            );
        }
Exemple #7
0
        public void DistanceDistribution()
        {
            /*
             *      Percentile,By Index,By Random
             *      -----------------------------
             *      0%,111.35,146.55
             *      1%,142.06,255.96
             *      2%,147.21,2163.43
             *      3%,151.2,2214.15
             *      4%,154.06,2245.2
             *      5%,156.24,2271.37
             *      6%,158.38,2292.29
             *      7%,160.42,2313.55
             *      8%,162.29,2327.14
             *      9%,164.07,2345.25
             *      10%,165.41,2359.95
             *      11%,166.72,2372.83
             *      12%,167.99,2386.15
             *      13%,169.29,2398.47
             *      14%,170.43,2410.01
             *      15%,171.53,2422.34
             *      16%,172.48,2432.43
             *      17%,173.58,2443.08
             *      18%,174.73,2454.27
             *      19%,175.56,2463.71
             *      20%,176.35,2472.97
             *      21%,177.35,2483.24
             *      22%,178.3,2491.9
             *      23%,179.1,2501.44
             *      24%,179.82,2510.26
             *      25%,180.64,2517.73
             *      26%,181.55,2524.97
             *      27%,182.33,2531.58
             *      28%,182.98,2538.08
             *      29%,183.67,2543.83
             *      30%,184.33,2550.93
             *      31%,185.09,2556.59
             *      32%,185.7,2563.37
             *      33%,186.41,2570.29
             *      34%,187.09,2577.29
             *      35%,187.7,2583.56
             *      36%,188.43,2589.95
             *      37%,189.07,2596.13
             *      38%,189.71,2602.24
             *      39%,190.46,2608.28
             *      40%,191.08,2615.25
             *      41%,191.79,2620.81
             *      42%,192.46,2626.02
             *      43%,193.09,2632.7
             *      44%,193.71,2638.18
             *      45%,194.31,2643.35
             *      46%,194.98,2648.69
             *      47%,195.65,2655.47
             *      48%,196.3,2660.26
             *      49%,196.96,2666.37
             *      50%,197.66,2670.94
             *      51%,198.34,2677.09
             *      52%,199.07,2681.9
             *      53%,199.72,2687.11
             *      54%,200.3,2692.42
             *      55%,201.06,2697.92
             *      56%,201.71,2703.76
             *      57%,202.4,2710.17
             *      58%,203.16,2715.06
             *      59%,203.82,2720.25
             *      60%,204.51,2725.99
             *      61%,205.32,2731.6
             *      62%,206.08,2736.59
             *      63%,206.79,2741.72
             *      64%,207.58,2746.59
             *      65%,208.29,2754.03
             *      66%,209.07,2760.81
             *      67%,209.8,2766.65
             *      68%,210.68,2771.98
             *      69%,211.71,2778.27
             *      70%,212.38,2784.23
             *      71%,213.19,2790.71
             *      72%,213.92,2796.42
             *      73%,214.82,2802.84
             *      74%,215.68,2809.36
             *      75%,216.54,2814.55
             *      76%,217.48,2821.32
             *      77%,218.43,2827.56
             *      78%,219.35,2833.35
             *      79%,220.28,2840.72
             *      80%,221.33,2848.87
             *      81%,222.31,2856.89
             *      82%,223.42,2864
             *      83%,224.46,2872.51
             *      84%,225.83,2881.09
             *      85%,227.06,2891.57
             *      86%,228.27,2900.46
             *      87%,229.63,2910.46
             *      88%,231.55,2919.5
             *      89%,233.59,2933.76
             *      90%,235.6,2944.88
             *      91%,237.25,2959.45
             *      92%,239.83,2976.08
             *      93%,241.88,2990.4
             *      94%,244.97,3010.08
             *      95%,248.23,3029.15
             *      96%,252.34,3052.37
             *      97%,260.68,3074.84
             *      98%,282.76,3112.43      *** Note the jump from 282 to 2550, which shows that the characteristic distance is about 282.
             *      99%,2550.87,3170.93
             *      100%,3114.89,3412.57
             */
            var data = new GaussianClustering
            {
                ClusterCount   = 100,
                Dimensions     = 50,
                MaxCoordinate  = 1000,
                MinClusterSize = 50,
                MaxClusterSize = 150
            };
            var clusters         = data.MakeClusters();
            var bitsPerDimension = 10;
            var points           = clusters.Points().Select(p => HilbertPoint.CastOrConvert(p, bitsPerDimension, true)).ToList();
            var results          = OptimalIndex.Search(
                points,
                5,                     // outlierSize
                10,                    // noiseSkipBy
                1000,                  // maxTrials
                4                      // maxIterationsWithoutImprovement
                );
            var pointsFromIndex  = results.Index.SortedPoints;
            var distancesRandom  = new List <long>();
            var distancesHilbert = new List <long>();
            var n   = pointsFromIndex.Count;
            var rng = new FastRandom();

            for (var i = 0; i < n - 1; i++)
            {
                var p1 = pointsFromIndex[i];
                var p2 = pointsFromIndex[i + 1];
                distancesHilbert.Add(p1.Measure(p2));

                var p3 = pointsFromIndex[rng.Next(n)];
                var p4 = pointsFromIndex[rng.Next(n)];
                distancesRandom.Add(p3.Measure(p4));
            }
            distancesHilbert.Sort();
            distancesRandom.Sort();
            Console.WriteLine("Percentile,By Index,By Random");
            for (var percentile = 0; percentile <= 100; percentile++)
            {
                var i           = Math.Min(n - 2, (n - 1) * percentile / 100);
                var distHilbert = Math.Round(Math.Sqrt(distancesHilbert[i]), 2);
                var distRandom  = Math.Round(Math.Sqrt(distancesRandom[i]), 2);
                Console.Write($"{percentile}%,{distHilbert},{distRandom}");
            }
        }