Exemple #1
0
        public static int GetManhattanDistance(Hero hero, Tile mine)
        {
            uint key = (uint)((hero.Dimensions >> Hero.PositionX) | (mine.Dimensions << (16 - Hero.PositionX)));

            byte distance;

            lock (locker)
            {
                if (!ManhattanDistance.TryGetValue(key, out distance))
                {
                    distance = (byte)(Math.Abs(hero.X - mine.X) + Math.Abs(hero.Y - mine.Y));
                    ManhattanDistance[key] = distance;
                }
            }
            return(distance);
        }
Exemple #2
0
        public void Test_model_Evaluator_correction_averaging()
        {
            // arrange
            var    distance       = new ManhattanDistance();
            var    classifier     = new BasicClassifier(distance);
            string trainingPath   = Path.Combine(TestContext.DeploymentDirectory, "digits", "trainingsample.csv");
            string validationPath = Path.Combine(TestContext.DeploymentDirectory, "digits", "validationsample.csv");
            var    trainingData   = DataReader.ReadObservations(trainingPath);
            var    validationData = DataReader.ReadObservations(validationPath);

            classifier.Train(trainingData);
            // act
            var result = Evaluator.Correct(validationData, classifier);

            // assert
            Assert.AreEqual(result, 0.934);
        }
Exemple #3
0
        static void Main(string[] args)
        {
            var distance   = new ManhattanDistance();
            var classifier = new BasicClassifier(distance);

            var trainingPath = "./data/train_truncated.csv";
            var training     = DataReader.ReadObservations(trainingPath);

            classifier.Train(training);

            var validationPath = "./data/validate_truncated.csv";
            var validation     = DataReader.ReadObservations(validationPath);

            var correct = Evaluator.Correct(validation, classifier);

            Console.WriteLine("Correctly classified {0:P2}", correct);
        }
        static void Main(string[] args)
        {
            var tiles           = new TilesInWrongPlace(new BoardEqualityComparer());
            var manhattan       = new ManhattanDistance(new BoardEqualityComparer());
            var manhattanSquare = new SquareOfManhattanDistance(new BoardEqualityComparer());

            var start = new SearchNode()
            {
                Status = new int[9] {
                    0, 1, 3, 4, 2, 5, 7, 8, 6
                },
                Steps = 0
            };

            var goal = new SearchNode()
            {
                Status = new int[9] {
                    1, 2, 3, 4, 5, 6, 7, 8, 0
                },
                Steps = 0
            };

            Console.WriteLine("Missing Tiles");
            var path = tiles.GetPath(start, goal);

            foreach (var s in path)
            {
                PrintMatrix(s.Status);
            }

            Console.WriteLine("Manhattan");
            path = manhattan.GetPath(start, goal);
            foreach (var s in path)
            {
                PrintMatrix(s.Status);
            }

            Console.WriteLine("Square Manhattan");
            path = manhattanSquare.GetPath(start, goal);
            foreach (var s in path)
            {
                PrintMatrix(s.Status);
            }
        }
Exemple #5
0
        static void Main(string[] args)
        {
            var distance   = new ManhattanDistance();
            var classifier = new BasicClassifier(distance);

            var trainingPath = @"C:\Users\ifeanyi\Documents\visual studio 2013\Projects\MLImageDigitizer\MLImageDigitizer\Data\trainingdata.csv";
            var training     = DataReader.ReadObservations(trainingPath);

            classifier.Train(training);

            var validationPath = @"C:\Users\ifeanyi\Documents\visual studio 2013\Projects\MLImageDigitizer\MLImageDigitizer\Data\validationdata.csv";
            var validation     = DataReader.ReadObservations(validationPath);

            var correct = Evaluator.Correct(validation, classifier);

            Console.WriteLine("Correctly classified: {0:P2}", correct);

            Console.ReadLine();
        }
    static void Main(string[] args)
    {
        var distance   = new ManhattanDistance();
        var classifier = new BasicClassifier(distance);

        var dataPath     = @"/Users/espen/git/ML-book-experiments/DigitsRecognizer/data/";
        var trainingPath = dataPath + "trainingsample.csv";
        var trainingSet  = DataReader.ReadObservations(trainingPath);

        classifier.Train(trainingSet);

        var validationPath = dataPath + "validationsample.csv";
        var validationSet  = DataReader.ReadObservations(validationPath);

        var correct = Evaluator.Correct(validationSet, classifier);

        Console.WriteLine($"Correctly classified: {correct:P2}");

        Console.WriteLine("Press enter to exit.");
        Console.ReadLine();
    }
Exemple #7
0
        protected void ChooseTarget(Unit[] potentialTargets)
        {
            if (potentialTargets.Length > 0)
            {
                //order units by their manhattan distance from the units coord.
                IEnumerable <Unit> iter = potentialTargets.OrderBy(unit => ManhattanDistance.GetDistance(cubeCoordinate, unit.CubeCoordinate));
                //choose the lowest distance (first item)
                Unit closestTarget = iter.First();

                //choose the closest unit as the target if
                //  1. unit currently has no target
                //  OR 2. target has died
                //  OR 3. current target is further away than the closest potential target
                if (target == null ||
                    !target.IsAlive() ||
                    ManhattanDistance.GetDistance(cubeCoordinate, closestTarget.CubeCoordinate)
                    < ManhattanDistance.GetDistance(cubeCoordinate, target.CubeCoordinate))
                {
                    target = iter.First();
                }
            }
        }
        static void Main(string[] args)
        {
            var distance   = new ManhattanDistance();
            var classifier = new BasicClassifier(distance);

            //@:写路径字符串可以让字符串不需要转义,否则需要写两个\\
            //读取训练集
            var trainingPath = @"D:\SojS\machine-learning\machine-learning-projects-for-dot-net-developers\chapter-1\DigitsRecognizer\Data\trainingsample.csv";
            var training     = DataReader.ReadObservations(trainingPath);

            //训练基本分类器
            classifier.Train(training);

            //读取验证集
            var validationPath = @"D:\SojS\machine-learning\machine-learning-projects-for-dot-net-developers\chapter-1\DigitsRecognizer\Data\validationsample.csv";
            var validation     = DataReader.ReadObservations(validationPath);

            //验证分类器
            var correct = Evaluator.Correct(validation, classifier);

            Console.WriteLine("{0:P2}", correct);

            Console.ReadLine();
        }
Exemple #9
0
 public int CompareTo(object obj)
 {
     return(ManhattanDistance.CompareTo(((GraphVertex)obj).ManhattanDistance));
 }
Exemple #10
0
        /// <summary>
        /// Called on awake.
        /// </summary>
        protected sealed override void OnAwake()
        {
            //Determine the cost and path smoothing providers to use
            ISmoothPaths pathSmoother;
            var          pathSmoothProvider = this.As <IPathSmootherFactory>();

            if (pathSmoothProvider == null)
            {
                pathSmoother = new PathSmoother();
            }
            else
            {
                pathSmoother = pathSmoothProvider.CreateSmoother();
            }

            IMoveCost moveCostProvider;
            var       moveCostProviderFactory = this.As <IMoveCostFactory>();

            if (moveCostProviderFactory == null)
            {
                if (this.moveCost == CostProviderType.Custom)
                {
                    this.moveCost = CostProviderType.Diagonal;
                }

                switch (this.moveCost)
                {
                case CostProviderType.Euclidean:
                {
                    moveCostProvider = new EuclideanDistance(10);
                    break;
                }

                case CostProviderType.Cardinal:
                {
                    moveCostProvider = new CardinalDistance(10);
                    break;
                }

                case CostProviderType.Manhattan:
                {
                    moveCostProvider = new ManhattanDistance(10);
                    break;
                }

                default:
                {
                    moveCostProvider = new DiagonalDistance(10);
                    break;
                }
                }
            }
            else
            {
                this.moveCost    = CostProviderType.Custom;
                moveCostProvider = moveCostProviderFactory.CreateMoveCostProvider();
            }

            //Setup the pathing engine to use
            IPathingEngine engine;

            if (this.engineType == PathingEngineType.Astar)
            {
                engine = new PathingAStar(this.initialHeapSize, moveCostProvider, GameServices.cellCostStrategy, pathSmoother);
            }
            else
            {
                engine = new PathingJumpPointSearch(this.initialHeapSize, moveCostProvider, GameServices.cellCostStrategy, pathSmoother);
            }

            _pathService             = new PathService(engine, new ThreadFactory(), this.useThreadPoolForAsyncOperations);
            _pathService.runAsync    = this.runAsync;
            GameServices.pathService = _pathService;
        }
        private void Init()
        {
            if (unit == null)
            {
                Debug.LogWarning("The Path Finder Visualizer must have a unit set.");
                return;
            }

            _unit = this.unit.GetUnitFacade();

            var g = GridManager.instance.GetGrid(_unit.position);

            _cellSize  = g.cellSize;
            _gizmoSize = new Vector3(_cellSize, 0.2f, _cellSize);

            IMoveCost moveCostProvider;

            if (this.moveCost == CostProviderType.Custom)
            {
                var moveCostProviderFactory = this.As <IMoveCostFactory>();
                if (moveCostProviderFactory == null)
                {
                    moveCostProvider = new DiagonalDistance(10);
                    Debug.LogWarning("Path Service Component: Cost Provider set to Custom but no Cost Provider Factory found!.");
                }
                else
                {
                    moveCostProvider = moveCostProviderFactory.CreateMoveCostProvider();
                }
            }
            else
            {
                switch (this.moveCost)
                {
                case CostProviderType.Euclidean:
                {
                    moveCostProvider = new EuclideanDistance(10);
                    break;
                }

                case CostProviderType.Cardinal:
                {
                    moveCostProvider = new CardinalDistance(10);
                    break;
                }

                case CostProviderType.Manhattan:
                {
                    moveCostProvider = new ManhattanDistance(10);
                    break;
                }

                default:
                {
                    moveCostProvider = new DiagonalDistance(10);
                    break;
                }
                }
            }

            var preProcessors = this.GetComponents(typeof(IRequestPreProcessor)).Cast <IRequestPreProcessor>().OrderByDescending(p => p.priority).ToArray();

            //Setup the pathing engine to use
            if (this.engineType == PathingEngineType.Astar)
            {
                _engine = new VisualizedAStar(this.initialHeapSize, moveCostProvider, GameServices.cellCostStrategy, new PathSmoother(), preProcessors);
            }
            else
            {
                _engine = new VisualizedJPS(this.initialHeapSize, moveCostProvider, GameServices.cellCostStrategy, new PathSmoother(), preProcessors);
            }

            var tmp = new BasicPathRequest
            {
                requester           = this,
                requesterProperties = _unit,
                pathFinderOptions   = _unit.pathFinderOptions
            };

            if (_req != null)
            {
                tmp.from = _req.from;
                tmp.to   = _req.to;
            }

            _req = tmp;
        }
Exemple #12
0
 public void Setup()
 {
     ed = new EuclideanDistance();
     md = new ManhattanDistance();
 }
Exemple #13
0
        /// <summary>
        /// display a GUI and generate the WEKA based clusterer
        /// </summary>
        /// <param name="InstancesList">list of the weka instance</param>
        /// <returns>weka clusterer</returns>
        public Clusterer BuildClusterer(cParamAlgo ClusteringAlgo, cExtendedTable Input)
        {
            this.InputTable = Input;

            foreach (var item in Input)
            {
                this.ListDescriptors.Add(item.Name);
            }

            cListValuesParam Parameters = ClusteringAlgo.GetListValuesParam();

            Clusterer ClustererToReturn = null;
            Instances ListInstancesWithoutClasses = CreateInstancesWithoutClass(Input);
            #region EM
            if (ClusteringAlgo.Name == "EM")
            {
                ClustererToReturn = new EM();

                if (Parameters.ListCheckValues.Get("checkBoxAutomatedClassNum").Value)
                    ((EM)ClustererToReturn).setNumClusters(-1);
                else
                    ((EM)ClustererToReturn).setNumClusters((int)Parameters.ListDoubleValues.Get("numericUpDownNumClasses").Value);

                ((EM)ClustererToReturn).setMaxIterations((int)Parameters.ListDoubleValues.Get("numericUpDownMaxIterations").Value);
                ((EM)ClustererToReturn).setMinStdDev((double)Parameters.ListDoubleValues.Get("numericUpDownMinStdev").Value);
                ((EM)ClustererToReturn).setSeed((int)Parameters.ListDoubleValues.Get("numericUpDownSeedNumber").Value);
                ClustererToReturn.buildClusterer(ListInstancesWithoutClasses);
                this.NumberOfClusters = ClustererToReturn.numberOfClusters();
            }
            #endregion
            #region K Means
            else if (ClusteringAlgo.Name == "K-Means")
            {
                ClustererToReturn = new SimpleKMeans();
                ((SimpleKMeans)ClustererToReturn).setNumClusters((int)Parameters.ListDoubleValues.Get("numericUpDownNumClasses").Value);
                ((SimpleKMeans)ClustererToReturn).setSeed((int)Parameters.ListDoubleValues.Get("numericUpDownSeedNumber").Value);

                string DistanceType = (string)Parameters.ListTextValues.Get("comboBoxDistance").Value;

                if (DistanceType == "Euclidean")
                {
                    EuclideanDistance ED = new EuclideanDistance();
                    ED.setDontNormalize(!(bool)Parameters.ListCheckValues.Get("checkBoxNormalize").Value);
                    ((SimpleKMeans)ClustererToReturn).setDistanceFunction(ED);
                }
                else if (DistanceType == "Manhattan")
                {
                    ManhattanDistance MD = new ManhattanDistance();
                    MD.setDontNormalize(!(bool)Parameters.ListCheckValues.Get("checkBoxNormalize").Value);
                    ((SimpleKMeans)ClustererToReturn).setDistanceFunction(MD);
                }
                else return null;
                ClustererToReturn.buildClusterer(ListInstancesWithoutClasses);
                this.NumberOfClusters = ClustererToReturn.numberOfClusters();
            }
            #endregion
            //#region K Means++
            //else if (ClusteringAlgo.Name == "K-Means++")
            //{
            //    ClustererToReturn = new SimpleKMeans();
            //    ((SimpleKMeans)ClustererToReturn).setNumClusters((int)Parameters.ListDoubleValues.Get("numericUpDownNumClasses").Value);
            //    ((SimpleKMeans)ClustererToReturn).setSeed((int)Parameters.ListDoubleValues.Get("numericUpDownSeedNumber").Value);

            //    string DistanceType = (string)Parameters.ListTextValues.Get("comboBoxDistance").Value;

            //    if (DistanceType == "Euclidean")
            //    {
            //        EuclideanDistance ED = new EuclideanDistance();
            //        ED.setDontNormalize(!(bool)Parameters.ListCheckValues.Get("checkBoxNormalize").Value);
            //        ((SimpleKMeans)ClustererToReturn).setDistanceFunction(ED);
            //    }
            //    else if (DistanceType == "Manhattan")
            //    {
            //        ManhattanDistance MD = new ManhattanDistance();
            //        MD.setDontNormalize(!(bool)Parameters.ListCheckValues.Get("checkBoxNormalize").Value);
            //        ((SimpleKMeans)ClustererToReturn).setDistanceFunction(MD);
            //    }
            //    else return null;
            //    ClustererToReturn.buildClusterer(ListInstancesWithoutClasses);
            //    this.NumberOfClusters = ClustererToReturn.numberOfClusters();
            //}
            //#endregion

            #region hierarchical
            else if (ClusteringAlgo.Name == "Hierarchical")
            {
                ClustererToReturn = new weka.clusterers.HierarchicalClusterer();
                string OptionDistance = " -N " + (int)Parameters.ListDoubleValues.Get("numericUpDownNumClasses").Value;

                string DistanceType = (string)Parameters.ListTextValues.Get("comboBoxDistance").Value;
                OptionDistance += " -A \"weka.core.";
                switch (DistanceType)
                {
                    case "Euclidean":
                        OptionDistance += "EuclideanDistance";
                        break;
                    case "Manhattan":
                        OptionDistance += "ManhattanDistance";
                        break;
                    case "Chebyshev":
                        OptionDistance += "ChebyshevDistance";
                        break;
                    default:
                        break;
                }

                if (!(bool)Parameters.ListCheckValues.Get("checkBoxNormalize").Value)
                    OptionDistance += " -D";
                OptionDistance += " -R ";

                OptionDistance += "first-last\"";
                string WekaOption = "-L " + (string)Parameters.ListTextValues.Get("comboBoxLinkType").Value + OptionDistance;
                ((HierarchicalClusterer)ClustererToReturn).setOptions(weka.core.Utils.splitOptions(WekaOption));

                ClustererToReturn.buildClusterer(ListInstancesWithoutClasses);
                this.NumberOfClusters = ClustererToReturn.numberOfClusters();
            }
            #endregion
            #region Farthest First
            else if (ClusteringAlgo.Name == "FarthestFirst")
            {
                ClustererToReturn = new weka.clusterers.FarthestFirst();

                ((FarthestFirst)ClustererToReturn).setNumClusters((int)Parameters.ListDoubleValues.Get("numericUpDownNumClasses").Value);
                ((FarthestFirst)ClustererToReturn).setSeed((int)Parameters.ListDoubleValues.Get("numericUpDownSeedNumber").Value);
                ClustererToReturn.buildClusterer(ListInstancesWithoutClasses);
                this.NumberOfClusters = ClustererToReturn.numberOfClusters();
            }
            #endregion
            #region CobWeb
            else if (ClusteringAlgo.Name == "CobWeb")
            {
                ClustererToReturn = new weka.clusterers.Cobweb();

                ((Cobweb)ClustererToReturn).setSeed((int)Parameters.ListDoubleValues.Get("numericUpDownSeedNumber").Value);
                ((Cobweb)ClustererToReturn).setAcuity((double)Parameters.ListDoubleValues.Get("numericUpDownAcuity").Value);
                ((Cobweb)ClustererToReturn).setCutoff((double)Parameters.ListDoubleValues.Get("numericUpDownCutOff").Value);
                ClustererToReturn.buildClusterer(ListInstancesWithoutClasses);

                this.NumberOfClusters = ClustererToReturn.numberOfClusters();
            }
            #endregion
            #region Manual
            else if (ClusteringAlgo.Name == "Manual")
            {
                string DescriptorName = (string)Parameters.ListTextValues.Get("comboBoxForDescriptorManualClustering").Value;

                //  this.Classes = new double[ListInstancesWithoutClasses.numInstances()];

                for (int IdxPt = 0; IdxPt < this.Classes.Count / 2; IdxPt++)
                {
                    this.Classes[IdxPt] = 2;
                }
                this.NumberOfClusters = 2;
                //    break;

                //int IdxDesc = -1;
                //foreach (string item in this.ListDescriptors)
                //{
                //    IdxDesc++;
                //    if (item == DescriptorName) break;
                //}

                //int Idx=0;

                //foreach (Instance item in ListInstancesWithoutClasses)
                //{
                //    this.Classes.Add(((int)item.value(IdxDesc)) % cGlobalInfo.ListCellularPhenotypes.Count);
                //}

                //// re - ordonner les valeurs du discripteur afin que les classes se suivent sans laisser de classe vide !!
                //this.NumberOfClusters =  cGlobalInfo.ListCellularPhenotypes.Count;
            }
            #endregion

            else
            {
                System.Windows.Forms.MessageBox.Show("Clustering method not implemented !", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
            return ClustererToReturn;
        }
        /// <summary>
        /// Called on awake.
        /// </summary>
        protected sealed override void OnAwake()
        {
            //Determine the cost and path smoothing providers to use
            ISmoothPaths pathSmoother;
            var          pathSmoothProvider = this.As <IPathSmootherFactory>();

            if (pathSmoothProvider == null)
            {
                pathSmoother = new PathSmoother();
            }
            else
            {
                pathSmoother = pathSmoothProvider.CreateSmoother();
            }

            IMoveCost moveCostProvider;

            if (this.moveCost == CostProviderType.Custom)
            {
                var moveCostProviderFactory = this.As <IMoveCostFactory>();
                if (moveCostProviderFactory == null)
                {
                    moveCostProvider = new DiagonalDistance(10);
                    Debug.LogWarning("Path Service Component: Cost Provider set to Custom but no Cost Provider Factory found!.");
                }
                else
                {
                    moveCostProvider = moveCostProviderFactory.CreateMoveCostProvider();
                }
            }
            else
            {
                switch (this.moveCost)
                {
                case CostProviderType.Euclidean:
                {
                    moveCostProvider = new EuclideanDistance(10);
                    break;
                }

                case CostProviderType.Cardinal:
                {
                    moveCostProvider = new CardinalDistance(10);
                    break;
                }

                case CostProviderType.Manhattan:
                {
                    moveCostProvider = new ManhattanDistance(10);
                    break;
                }

                default:
                {
                    moveCostProvider = new DiagonalDistance(10);
                    break;
                }
                }
            }

            var preProcessors = this.GetComponents(typeof(IRequestPreProcessor)).Cast <IRequestPreProcessor>().OrderByDescending(p => p.priority).ToArray();

            //Setup the pathing engine to use
            IPathingEngine engine;

            if (this.engineType == PathingEngineType.Astar)
            {
                engine = new PathingAStar(this.initialHeapSize, moveCostProvider, GameServices.cellCostStrategy, pathSmoother, preProcessors);
            }
            else
            {
                engine = new PathingJumpPointSearch(this.initialHeapSize, moveCostProvider, GameServices.cellCostStrategy, pathSmoother, preProcessors);
            }

            _pathService             = new PathService(engine, new ThreadFactory(), this.useThreadPoolForAsyncOperations);
            _pathService.runAsync    = this.runAsync;
            GameServices.pathService = _pathService;
        }
Exemple #15
0
        public void Test1(string wire1, string wire2, int expectedDistance)
        {
            var actualDistance = ManhattanDistance.Calculate(wire1, wire2);

            actualDistance.Should().Be(expectedDistance, because: "It should");
        }
 public RandomColorBehaviour()
 {
     _manhattanDistance = new ManhattanDistance();
 }
 public void SetupBase()
 {
     Subject = new ManhattanDistance(MemoryWriter);
 }