Esempio n. 1
0
	public static Vector3 NearestPointOnMesh(Vector3 pt, Vector3[] verts, KDTree vertProx, int[] tri, VertTriList vt)
	{
		//	First, find the nearest vertex (the nearest point must be on one of the triangles
		//	that uses this vertex if the mesh is convex).
		int nearest = vertProx.FindNearest(pt);

		//	Get the list of triangles in which the nearest vert "participates".
		VertList nearTris = vt.list[nearest];

		Vector3 nearestPt = Vector3.zero;
		float nearestSqDist = float.MaxValue;

		for ( int i = 0; i < nearTris.t.Length; i++ )
		{
			int triOff = nearTris.t[i] * 3;
			Vector3 a = verts[tri[triOff]];
			Vector3 b = verts[tri[triOff + 1]];
			Vector3 c = verts[tri[triOff + 2]];

			Vector3 possNearestPt = NearestPointOnTri(pt, a, b, c);
			float possNearestSqDist = (pt - possNearestPt).sqrMagnitude;

			if ( possNearestSqDist < nearestSqDist )
			{
				nearestPt = possNearestPt;
				nearestSqDist = possNearestSqDist;
			}
		}

		return nearestPt;
	}
Esempio n. 2
0
//	Recursively build a tree by separating points at plane boundaries.
	static KDTree MakeFromPointsInner(
					int depth,
					int stIndex, int enIndex,
					Vector3[] points,
					int[] inds
					) {
		
		KDTree root = new KDTree();
		root.axis = depth % numDims;
		int splitPoint = FindPivotIndex(points, inds, stIndex, enIndex, root.axis);

		root.pivotIndex = inds[splitPoint];
		root.pivot = points[root.pivotIndex];
		
		int leftEndIndex = splitPoint - 1;
		
		if (leftEndIndex >= stIndex) {
			root.lr[0] = MakeFromPointsInner(depth + 1, stIndex, leftEndIndex, points, inds);
		}
		
		int rightStartIndex = splitPoint + 1;
		
		if (rightStartIndex <= enIndex) {
			root.lr[1] = MakeFromPointsInner(depth + 1, rightStartIndex, enIndex, points, inds);
		}
		
		return root;
	}
Esempio n. 3
0
    // Update is called once per frame
    void Update()
    {
        tree = KDTree.MakeFromPoints(pointsArray);
        for (int i = 0; i < enemies.Length; i++) {
            pointsArray[i] = enemies[i].transform.position;
        }
        nearest = tree.FindNearest(player.transform.position);

        enemies[nearest].GetComponent<Move>().enabled = true;
        //enemies[nearest].GetComponent<Shoot>().enabled = true;
        Debug.Log(nearest);
    }
Esempio n. 4
0
 internal static void readStopFile(out KDTree.KDTree rootNode)
 {
     rootNode = new KDTree.KDTree(2);
     Stream reader = getFileStream("stops.txt");
     StreamReader streamReader = new StreamReader(reader);
     while (!streamReader.EndOfStream)
     {
         Stop stop = readStopLine(streamReader.ReadLine());
         if (stop != null)
         {
             rootNode.insert(new double[] { stop.stop_lat, stop.stop_lon }, stop);
         }
     }
 }
Esempio n. 5
0
        private void Initialize(Stream Input, bool MajorPlacesOnly)
        {
            List<GeoName> Places = new List<GeoName>();
            using (StreamReader db = new StreamReader(Input))
            {
                string Line;
                while (!db.EndOfStream && (Line = db.ReadLine()) != null)
                {
                    var Place = new GeoName(Line);
                    if (!MajorPlacesOnly || Place.FeatureClass != GeoFeatureClass.City)
                        Places.Add(Place);
                }
            }

            Tree = new KDTree<GeoName>(Places.ToArray());
        }
Esempio n. 6
0
        public void BuildTest()
        {
            Console.WriteLine("Current Directory: " + System.IO.Directory.GetCurrentDirectory());
            List<Vector3> vertices;
            List<Face> faces;
            List<Color> colors;
            if (!ObjIO.Read(@"D:\Libraries\KDTree2\KDTree_UnitTest\bin\Debug\test.obj", out vertices, out colors, out faces))
            {
                Console.WriteLine("Failed to find test.obj");
            }

            KDTree tree = new KDTree();
            tree.AddPoints(vertices);
            bool build_result = tree.Build();
            Assert.IsTrue(build_result);
        }
        public PatternFinder(int BarsCount = 1000  )
        {
            Index_Date = new Dictionary<int, DateTime>();
            Open = new List<double>();
            High = new List<double>();
            Low = new List<double>();
            Close = new List<double>();
            AdjClose = new List<double>();
            Date_Time = new List<DateTime>();

            returns = new List<double>();
            stDev = new List<double>();

            this.CurrentBar = 0;
            this.PatternLength = 3;
            this.MatchCount = 50;
            this.MinimumWindowSize = 500;
            this.VolatilityAdjusted = false;
            this.Overnight = false;
            this.WeighExpectancyByDistance = false;
            Classification = false;
            ClassificationLimit = 0.002;

            _tree = new KDTree<double>(PatternLength * 4 - 1);

            switch (DistanceType)
            {
                case "Euclidean":
                    _tree.Distance = Accord.Math.Distance.Euclidean;
                    break;
                case "Absolute":
                    _tree.Distance = AbsDistance;
                    break;
                case "Chebyshev":
                    _tree.Distance = Accord.Math.Distance.Chebyshev;
                    break;
                default:
                    _tree.Distance = Accord.Math.Distance.Euclidean;
                    break;
            }
        }
 public override void UpdateSoldierPos(Vector3[] soldierPos)
 {
     if (soldierPos.Length > 0)
     {
         soldierPosTree = KDTree.MakeFromPoints(soldierPos);
         foreach (SwarmSpawner spawner in spawners)
         {
             int nearestIndex = soldierPosTree.FindNearest(spawner.transform.position);
             Soldier nearest = soldierManager.soldiers[nearestIndex];
             if (!spawner.nearestSoldier || spawner.nearestSoldier != nearest)
             {
                 spawner.UpdateDronesTarget(nearest.transform);
             }
         }
     }
     else
     {
         foreach (SwarmSpawner spawner in spawners)
         {
             spawner.UpdateDronesTarget(null);
         }
     }
 }
Esempio n. 9
0
        public void TraverseTest1()
        {
            double[][] points =
            {
                new double[] { 2, 3 },
                new double[] { 5, 4 },
                new double[] { 9, 6 },
                new double[] { 4, 7 },
                new double[] { 8, 1 },
                new double[] { 7, 2 },
            };


            // To create a tree from a set of points, we use
            KDTree <int> tree = KDTree.FromData <int>(points);

            double[][] breadth =
            {
                new double[] { 7, 2 },
                new double[] { 5, 4 },
                new double[] { 9, 6 },
                new double[] { 2, 3 },
                new double[] { 4, 7 },
                new double[] { 8, 1 },
            };

            double[][] inOrder =
            {
                new double[] { 2, 3 },
                new double[] { 5, 4 },
                new double[] { 4, 7 },
                new double[] { 7, 2 },
                new double[] { 8, 1 },
                new double[] { 9, 6 },
            };

            double[][] postOrder =
            {
                new double[] { 2, 3 },
                new double[] { 4, 7 },
                new double[] { 5, 4 },
                new double[] { 8, 1 },
                new double[] { 9, 6 },
                new double[] { 7, 2 },
            };

            double[][] preOrder =
            {
                new double[] { 7, 2 },
                new double[] { 5, 4 },
                new double[] { 2, 3 },
                new double[] { 4, 7 },
                new double[] { 9, 6 },
                new double[] { 8, 1 },
            };


            AreEqual(tree, breadth, KDTreeTraversal.BreadthFirst);
            AreEqual(tree, preOrder, KDTreeTraversal.PreOrder);
            AreEqual(tree, inOrder, KDTreeTraversal.InOrder);
            AreEqual(tree, postOrder, KDTreeTraversal.PostOrder);
        }
Esempio n. 10
0
        /// <summary>
        ///   Divides the input data into clusters.
        /// </summary>
        ///
        /// <param name="points">The data where to compute the algorithm.</param>
        /// <param name="weights">The weight associated with each data point.</param>
        ///
        public int[] Compute(double[][] points, int[] weights)
        {
            if (points.Length != weights.Length)
            {
                throw new DimensionMismatchException("weights",
                                                     "The weights and points vector must have the same dimension.");
            }

            // First of all, construct map of the original points. We will
            // be saving the weight of every point in the node of the tree.
            KDTree <int> tree = KDTree.FromData(points, weights, Distance);

            // Let's sample some points in the problem surface
            double[][] seeds = createSeeds(points, 2 * Bandwidth);

            // Now, we will duplicate those points and make them "move"
            // into this surface in the direction of the surface modes.
            double[][] current = seeds.MemberwiseClone();

            // We will store any modes that we find here
            var maxima = new ConcurrentStack <double[]>();

            // Optimization for uniform kernel
            Action <ICollection <KDTreeNodeDistance <int> >, double[]> func;

            if (kernel is UniformKernel)
            {
                func = uniform;
            }
            else
            {
                func = general;
            }

            // For each seed
            if (UseParallelProcessing)
            {
                Parallel.For(0, current.Length, i =>
                             move(tree, current, i, maxima, func));

                for (int i = 0; i < current.Length; i++)
                {
                    supress(current, i, maxima);
                }
            }
            else
            {
                for (int i = 0; i < current.Length; i++)
                {
                    move(tree, current, i, maxima, func);
                }
            }

            var modes = maxima.ToArray();

            // At this point, the current points have moved into
            // the location of the modes of the surface. Now we
            // have to backtrack and check, for each mode, from
            // where those points departed from.

            int[] labels = classify(modes: modes, points: current);

            // Now we create a decision map using the original seed positions
            tree = KDTree.FromData(seeds, labels, Distance, inPlace: true);


            clusters = new MeanShiftClusterCollection(this, modes.Length, tree, modes);

            if (ComputeLabels || ComputeProportions)
            {
                int   sum    = 0;
                int[] counts = new int[modes.Length];
                labels = new int[points.Length];
                for (int i = 0; i < labels.Length; i++)
                {
                    int j = tree.Nearest(points[i]).Value;
                    labels[i]  = j;
                    counts[j] += weights[i];
                    sum       += weights[i];
                }

                for (int i = 0; i < counts.Length; i++)
                {
                    clusters.Proportions[i] = counts[i] / (double)sum;
                }

                return(labels);
            }

            return(null);
        }
Esempio n. 11
0
 private KDTree buildVertexIndex(List<SDMinVertex> weightedVertices, Polyline polyline)
 { 
     BoundingRectangle br = polyline.GetBoundingRectangle();
     br.Grow(PlanimetryAlgorithms.Tolerance);
     KDTree result = new KDTree(br);
     result.MaxDepth = 14;
     result.MinObjectCount = 10;
     result.BoxSquareThreshold = br.Width * br.Height / 10000;
     result.Build(weightedVertices);
     return result;
 }
Esempio n. 12
0
 void UpdateDroneKDTree()
 {
     dronesInSightPosArr = new Vector3[dronesInSight.Count];
     for (int i = 0; i < dronesInSightPosArr.Length; i++)
     {
         dronesInSightPosArr[i] = dronesInSight[i].transform.position;
     }
     dronesInSightTree = KDTree.MakeFromPoints(dronesInSightPosArr);
 }
Esempio n. 13
0
 /// <summary>
 ///   Creates a new <see cref="KNearestNeighbors"/>.
 /// </summary>
 ///
 /// <param name="k">The number of nearest neighbors to be used in the decision.</param>
 /// <param name="classes">The number of classes in the classification problem.</param>
 /// <param name="inputs">The input data points.</param>
 /// <param name="outputs">The associated labels for the input points.</param>
 /// <param name="distance">The distance measure to use.</param>
 ///
 public KNearestNeighbors(int k, int classes, double[][] inputs, int[] outputs, IMetric <double[]> distance)
     : base(k, classes, inputs, outputs, distance)
 {
     this.tree = KDTree.FromData(inputs, outputs, distance);
 }
Esempio n. 14
0
        private KDTree getCrossPointsIndex(Polyline polyline)
        {
            List<MonotoneChain> chains = new List<MonotoneChain>();
            foreach (LinePath path in polyline.Paths)
                path.AppendMonotoneChains(chains);

            List<SDMinCrossPoint> crossPoints = new List<SDMinCrossPoint>();

            for (int i = 0; i < chains.Count - 1; i++)
                for (int j = i + 1; j < chains.Count; j++)
                    if (chains[i].BoundsIntersect(chains[j]))
                    {
                        List<ICoordinate> points = chains[i].GetCrossPoints(chains[j]);
                        foreach (ICoordinate p in points)
                        {
                            bool isChainIBoundsPoint = p.ExactEquals(chains[i].FirstPoint) ||
                                 p.ExactEquals(chains[i].LastPoint);

                            bool isChainJBoundsPoint = p.ExactEquals(chains[j].FirstPoint) ||
                                 p.ExactEquals(chains[j].LastPoint);

                            if (!(isChainIBoundsPoint && isChainJBoundsPoint))
                            {
                                SDMinCrossPoint cp = new SDMinCrossPoint();
                                cp.Point = p;
                                cp.BoundingRectangle = new PointD(p).GetBoundingRectangle();
                                cp.BoundingRectangle.Grow(PlanimetryAlgorithms.Tolerance);
                                crossPoints.Add(cp);
                            }
                        }
                    }

            BoundingRectangle br = new BoundingRectangle();
            foreach (SDMinCrossPoint p in crossPoints)
                br.Join(p.BoundingRectangle);

            KDTree result = new KDTree(br);
            result.MaxDepth = 10;
            result.MinObjectCount = 10;
            if (br.IsEmpty())
                br.Join(PlanimetryEnvironment.NewCoordinate(0, 0));
            result.BoxSquareThreshold = br.Width * br.Height / 10000;
            result.Build(crossPoints);
            return result;
        }
Esempio n. 15
0
        protected override void Initialize()
        {
            base.Initialize();

            camera.Position = new Vector3(100.0f, 100.0f, 100.0f);
            camera.LookAt(Vector3.Zero);

            cameraHandler.Camera = camera;

            Random random = new Random(0);

            for (int i = 0; i < 10; i++)
            {
                Cubes.Add(
                    new Vector3((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble()) * 100.0f,
                    new Vector3((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble()),
                    new Vector3((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble()) * 10.0f,
                    true);
            }

            kdTree = new KDTree(this, Cubes.Triangles);
            Components.Add(kdTree);

            GraphicsDevice.RasterizerState = RasterizerState.CullNone;

            effect = new BasicEffect(GraphicsDevice);
            effect.VertexColorEnabled = true;
        }
Esempio n. 16
0
        /// <summary>
        /// Populates |EditVertex.AdjacentVertices|.
        /// </summary>
        private void ComputeAdjacentVertices()
        {
            // Put all vertices into a KDTree.
            try
            {
                KDTree<EditVertex> tree = new KDTree<EditVertex>(3);
                foreach (var face in Faces)
                {
                    foreach (var vert in face.Vertices)
                    {
                        var pos = vert.Position;
                        tree.AddPoint(new double[] {pos.X, pos.Y, pos.Z}, vert);
                    }
                }
                // For each vertices, retrieve adjacent/identical vertices by looking
                // up neighbors within a very small (epsilon'ish) radius.
                Faces.ParallelDo(
                    face =>
                    {
                        foreach (var vert in face.Vertices)
                        {
                            var pos = vert.Position;
                            var neighbors = tree.NearestNeighbors(new double[] { pos.X, pos.Y, pos.Z },
                                new SquareEuclideanDistanceFunction(),
                                int.MaxValue, 1e-5f);
                            foreach (var neighbor in neighbors)
                            {
                                vert.AdjacentVertices.Add(neighbor);
                            }
                        }
                    });
            }
            catch (Exception ex)
            {
                // TODO: Log.
                // Unfortunately, KDTree rarely crashes.
                // Long-term: fix KDTree.
                // Short-term: O(n^2) brute force workaround.
                Faces.ParallelDo(
                    face =>
                    {
                        foreach (var vert in face.Vertices)
                        {
                            var pos = vert.Position;
                            foreach (var otherVert in Vertices)
                            {
                                if (vert.IsApproximatelySamePosition(otherVert))
                                {
                                    vert.AdjacentVertices.Add(otherVert);
                                }
                            }
                        }
                    });

            }
            // Vertices being adjacent should be a transitive relation, yet this is
            // not guaranteed if implemented through a search radius.
            HashSet<EditVertex> seen = new HashSet<EditVertex>();
            foreach (var face in Faces)
            {
                foreach (var vert in face.Vertices)
                {
                    if (seen.Contains(vert))
                    {
                        continue;
                    }
                    foreach (var adjacentVert in vert.AdjacentVertices)
                    {
                        vert.AdjacentVertices.UnionWith(vert.AdjacentVertices);                
                    }
                    foreach (var adjacentVert in vert.AdjacentVertices)
                    {
                        adjacentVert.AdjacentVertices = vert.AdjacentVertices;
                        seen.Add(adjacentVert);
                    }
                }
            }
        }
 //base(k, classes, inputs, outputs, distance)
 public KNearestNeighborsss(int k, int classes, double[][] inputs, int[] outputs, Func<double[], double[], double> distance)
 {
     this.tree = KDTree.FromData(inputs, outputs, distance);
 }
 //base(k, classes, inputs, outputs, Accord.Math.Distance.Euclidean)
 /// 
 public KNearestNeighborsss(int k, int classes, double[][] inputs, int[] outputs)
 {
     this.tree = KDTree.FromData(inputs, outputs);
 }
 void ComputeRepulsiveForces(FiNode[] vs) {
     int n = vs.Length;
     if (n > 16 && settings.ApproximateRepulsion) {
         var ps = new KDTree.Particle[vs.Length];
         // before calculating forces we perturb each center by a small vector in a unique
         // but deterministic direction (by walking around a circle in n steps) - this allows
         // the KD-tree to decompose even when some nodes are at exactly the same position
         double angle = 0, angleDelta = 2.0*Math.PI/n;
         for (int i = 0; i < n; ++i) {
             ps[i] = new KDTree.Particle(vs[i].Center + 1e-5*new Point(Math.Cos(angle), Math.Sin(angle)));
             angle += angleDelta;
         }
         var kdTree = new KDTree(ps, 8);
         kdTree.ComputeForces(5);
         for (int i = 0; i < vs.Length; ++i) {
             AddRepulsiveForce(vs[i], ps[i].force);
         }
     }
     else {
         foreach (FiNode u in vs) {
             var fu = new Point();
             foreach (FiNode v in vs) {
                 if (u != v) {
                     fu += MultipoleCoefficients.Force(u.Center, v.Center);
                 }
             }
             AddRepulsiveForce(u, fu);
         }
     }
 }
Esempio n. 20
0
 void Update()
 {
     Tree = new KDTree(4, squares);
 }
Esempio n. 21
0
 void twoConstructor()
 {
     KDTree test = new KDTree(createList(2));
 }
Esempio n. 22
0
        /// <summary>
        ///   Creates a new <see cref="KNearestNeighbors"/> algorithm from an existing
        ///   <see cref="KDTree{T}"/>. The tree must have been created using the input
        ///   points and the point's class labels as the associated node information.
        /// </summary>
        ///
        /// <param name="tree">The <see cref="KDTree{T}"/> containing the input points and their integer labels.</param>
        /// <param name="k">The number of nearest neighbors to be used in the decision.</param>
        /// <param name="classes">The number of classes in the classification problem.</param>
        /// <param name="inputs">The input data points.</param>
        /// <param name="outputs">The associated labels for the input points.</param>
        ///
        /// <returns>A <see cref="KNearestNeighbors"/> algorithm initialized from the tree.</returns>
        ///
        public static KNearestNeighbors FromTree(KDTree <int> tree, int k, int classes, double[][] inputs, int[] outputs)
        {
            var knn = new KNearestNeighbors(tree, k, classes, inputs, outputs, tree.Distance);

            return(knn);
        }
Esempio n. 23
0
        public Accord2DNeighborslist(IEnumerable <PrimaryParticle> primaryParticles) : base(primaryParticles)
        {
            var particles = primaryParticles.ToArray();

            _kdTree = KDTree.FromData(primaryParticles.ToXYPositionArray(), particles);
        }
Esempio n. 24
0
		/**
		 *	Similar to Merge vertices, expect that this method only collapses vertices within
		 *	a specified distance of one another (typically epsilon).  Returns true if any action
		 * 	was taken, false otherwise.  Outputs indices that have been welded in the @welds var.
		 */
		public static bool WeldVertices(this pb_Object pb, int[] indices, float delta, out int[] welds)
		{
			List<int> universal = pb.sharedIndices.GetUniversalIndices(indices).ToList();
			Vector3[] v = pb.vertices;

			HashSet<int> used = new HashSet<int>();
			KDTree<int> tree = new KDTree<int>(3, 48);	// dimensions (xyz), node size

			for(int i = 0; i < universal.Count; i++)
			{
				Vector3 vert = v[pb.sharedIndices[universal[i]][0]];
				tree.AddPoint( new double[] { vert.x, vert.y, vert.z }, universal[i]);
			}

			List<List<int>> groups = new List<List<int>>();

			double[] point = new double[3] { 0, 0, 0 };

			int[][] si = pb.sharedIndices.ToArray();
			for(int i = 0; i < universal.Count; i++)
			{
				if(used.Contains(universal[i]))
				{
					continue;
				}

				int tri = si[universal[i]][0];
				
				point[0] = v[tri].x;
				point[1] = v[tri].y;
				point[2] = v[tri].z;

				NearestNeighbour<int> neighborIterator = tree.NearestNeighbors( point, 64, delta );

				List<int> neighbors = new List<int>();

				while(neighborIterator.MoveNext())
				{
					if( used.Contains(neighborIterator.Current) )
						continue;
	
					used.Add( neighborIterator.Current );
					neighbors.Add( neighborIterator.Current );
				}

				used.Add( universal[i] );
				groups.Add( neighbors );
			}

			pb_IntArray[] rebuilt = new pb_IntArray[groups.Count];// + remainingCount ];
			welds = new int[groups.Count];

			for(int i = 0; i < groups.Count; i++)
			{
				rebuilt[i] = new pb_IntArray( groups[i].SelectMany(x => pb.sharedIndices[x].array).ToArray() );
				welds[i] = rebuilt[i][0];
			}

			foreach(pb_IntArray arr in rebuilt)
			{
				Vector3 avg = pb_Math.Average(pbUtil.ValuesWithIndices(v, arr.array));
				foreach(int i in arr.array)
					v[i] = avg;
			}

			pb.SetVertices(v);
			// profiler.EndSample();

			pb_IntArray[] remaining = pb.sharedIndices.Where( (val, index) => !used.Contains(index) ).ToArray();

			rebuilt = pbUtil.Concat(rebuilt, remaining);

			pb.SetSharedIndices(rebuilt);

			return true;	
		}
Esempio n. 25
0
        public StructuresViewModel Get(string id)
        {
            var context = _contextManager.GetServer(id);

            if (context == null)
            {
                return(null);
            }

            var demoMode = IsDemoMode() ? new DemoMode() : null;
            var result   = new StructuresViewModel
            {
                MapName = context.SaveState?.MapName
            };

            var ids    = new ConcurrentDictionary <string, int>();
            var types  = new ConcurrentDictionary <string, StructureTypeViewModel>(StringComparer.OrdinalIgnoreCase);
            var owners = new ConcurrentDictionary <int, StructureOwnerViewModel>();

            var addStructureToArea = new Action <Area, ArkStructure, MinMaxCoords>((area, x, minmax) =>
            {
                //todo: this method may call the update callback even when the key ends up already being in the dict
                var type = types.GetOrAdd(x.ClassName, (key) =>
                {
                    return(new StructureTypeViewModel(new Lazy <int>(() => ids.AddOrUpdate("typeId", 0, (key2, value) => value + 1)))
                    {
                        ClassName = x.ClassName,
                        Name = x.ClassName //todo: we do not have names for structures yet
                    });
                });
                type.Id = type._generateId.Value;

                bool isCrapTier = false;
                if (_trashTier.TryGetValue(type.ClassName, out isCrapTier) && isCrapTier)
                {
                    area.TrashTierCount += 1;
                }
                area.Structures.Add(Tuple.Create(type.Id, x));

                var loc = x.Location;
                if (minmax.MinY == null || loc.Y < minmax.MinY.Y)
                {
                    minmax.MinY = loc;
                }
                if (minmax.MaxY == null || loc.Y > minmax.MaxY.Y)
                {
                    minmax.MaxY = loc;
                }
                if (minmax.MinX == null || loc.X < minmax.MinX.X)
                {
                    minmax.MinX = loc;
                }
                if (minmax.MaxX == null || loc.X > minmax.MaxX.X)
                {
                    minmax.MaxX = loc;
                }
                if (minmax.MinZ == null || loc.Z < minmax.MinZ.Z)
                {
                    minmax.MinZ = loc;
                }
                if (minmax.MaxZ == null || loc.Z > minmax.MaxZ.Z)
                {
                    minmax.MaxZ = loc;
                }
            });

            if (context.Structures != null)
            {
                // make fake structure objects out of rafts to include them in the clustering
                var rafts = context.Rafts.Select(x => new ArkStructure
                {
                    ClassName      = x.ClassName,
                    Location       = x.Location,
                    OwnerName      = x.OwningPlayerName ?? x.TribeName,
                    OwningPlayerId = x.OwningPlayerId,
                    TargetingTeam  = x.TargetingTeam
                }).ToArray();

                var structureAreas = context.Structures.Concat(rafts).Where(x => (x.TargetingTeam.HasValue || x.OwningPlayerId.HasValue) && x.Location?.Latitude != null && x.Location?.Longitude != null)
                                     .GroupBy(x => x.TargetingTeam ?? x.OwningPlayerId ?? 0)
                                     .AsParallel()
                                     .SelectMany(x =>
                {
                    var first      = x.First();
                    var arkOwnerId = first.TargetingTeam ?? first.OwningPlayerId ?? 0;
                    var isTribe    = first.TargetingTeam.HasValue && (!first.OwningPlayerId.HasValue || first.TargetingTeam.Value != first.OwningPlayerId.Value);
                    var owner      = owners.GetOrAdd(arkOwnerId, (key) =>
                    {
                        var tribe          = isTribe ? context.Tribes.FirstOrDefault(y => y.Id == first.TargetingTeam.Value) : null;
                        var player         = !isTribe ? context.Players.FirstOrDefault(y => y.Id == first.OwningPlayerId) : null;
                        var lastActiveTime = isTribe ? tribe?.LastActiveTime : player?.LastActiveTime;

                        //check saved player last active times for cross server activity
                        var externalLastActiveTime = (DateTime?)null;
                        if (isTribe && tribe != null && tribe.Members.Length > 0)
                        {
                            //for tribes check all last active times for member steamIds (across all servers/clusters)
                            var memberIds = tribe.Members.Select(y => y.SteamId).ToList();
                            var states    = _savedState.PlayerLastActive.Where(y =>
                                                                               y.SteamId != null && memberIds.Contains(y.SteamId, StringComparer.OrdinalIgnoreCase)).ToArray();
                            if (states?.Length > 0)
                            {
                                externalLastActiveTime = states.Max(y => y.LastActiveTime);
                            }
                        }
                        else if (!isTribe && player != null)
                        {
                            //for players check all last active times for player steamid (across all servers/clusters)
                            var states = _savedState.PlayerLastActive.Where(y =>
                                                                            y.SteamId != null && y.SteamId.Equals(player.SteamId, StringComparison.OrdinalIgnoreCase)).ToArray();
                            if (states?.Length > 0)
                            {
                                externalLastActiveTime = states.Max(y => y.LastActiveTime);
                            }
                        }

                        //set last active time to cross server time if it is more recent
                        if ((externalLastActiveTime.HasValue && !lastActiveTime.HasValue) ||
                            (externalLastActiveTime.HasValue && lastActiveTime.HasValue && externalLastActiveTime.Value > lastActiveTime.Value))
                        {
                            lastActiveTime = externalLastActiveTime;
                        }

                        return(new StructureOwnerViewModel(new Lazy <int>(() => ids.AddOrUpdate("ownerId", 0, (key2, value) => value + 1)))
                        {
                            OwnerId = arkOwnerId,
                            Name = demoMode != null ? isTribe ? demoMode.GetTribeName(arkOwnerId) : demoMode.GetPlayerName(arkOwnerId) : first.OwnerName,
                            Type = isTribe ? "tribe" : "player",
                            LastActiveTime = lastActiveTime,
                            CreatureCount = (isTribe ? tribe?.Creatures.Count() : player?.Creatures.Count()) ?? 0
                        });
                    });
                    owner.Id = owner._generateId.Value;

                    var areas      = new List <StructureAreaViewModel>();
                    var structures = new HashSet <ArkStructure>(x);
                    var tree       = KDTree.FromData(x.Select(y => new double[] { y.Location.Latitude.Value, y.Location.Longitude.Value }).ToArray(), x.ToArray());
                    do
                    {
                        var structure = structures.First();
                        structures.Remove(structure);

                        var area   = new Area();
                        var minmax = new MinMaxCoords();
                        addStructureToArea(area, structure, minmax);

                        var n = 0;
                        FindNearbyStructuresRecursive(new double[] { structure.Location.Latitude.Value, structure.Location.Longitude.Value }, structures, tree, area, minmax, ref n, addStructureToArea);

                        //var minLat = area.Min(y => y.Item2.Location.Latitude.Value);
                        //var maxLat = area.Max(y => y.Item2.Location.Latitude.Value);
                        //var minLng = area.Min(y => y.Item2.Location.Longitude.Value);
                        //var maxLng = area.Max(y => y.Item2.Location.Longitude.Value);
                        var dLat   = (minmax.MaxY.Latitude.Value - minmax.MinY.Latitude.Value) / 2f;
                        var dLng   = (minmax.MaxX.Longitude.Value - minmax.MinX.Longitude.Value) / 2f;
                        var avgLat = minmax.MinY.Latitude.Value + dLat;
                        var avgLng = minmax.MinX.Longitude.Value + dLng;

                        var dY   = (minmax.MaxY.Y - minmax.MinY.Y) / 2f;
                        var dX   = (minmax.MaxX.X - minmax.MinX.X) / 2f;
                        var dZ   = (minmax.MaxZ.Z - minmax.MinZ.Z) / 2f;
                        var avgY = minmax.MinY.Y + dY;
                        var avgX = minmax.MinX.X + dX;
                        var avgZ = minmax.MinZ.Z + dZ;

                        var dTopoMapY   = (minmax.MaxY.TopoMapY.Value - minmax.MinY.TopoMapY.Value) / 2f;
                        var dTopoMapX   = (minmax.MaxX.TopoMapX.Value - minmax.MinX.TopoMapX.Value) / 2f;
                        var avgTopoMapY = minmax.MinY.TopoMapY.Value + dTopoMapY;
                        var avgTopoMapX = minmax.MinX.TopoMapX.Value + dTopoMapX;

                        var structureGroups = area.Structures.GroupBy(y => y.Item1).Select(y => new StructureViewModel
                        {
                            TypeId = y.Key,
                            Count  = y.Count()
                        }).OrderByDescending(y => y.Count).ToList();

                        areas.Add(new StructureAreaViewModel
                        {
                            OwnerId        = owner.Id,
                            Structures     = structureGroups,
                            StructureCount = area.Structures.Count,
                            Latitude       = (float)Math.Round(avgLat, 2),
                            Longitude      = (float)Math.Round(avgLng, 2),
                            Radius         = (float)Math.Round(Math.Sqrt(dLat * dLat + dLng * dLng), 2),
                            TopoMapX       = (float)Math.Round(avgTopoMapX, 2),
                            TopoMapY       = (float)Math.Round(avgTopoMapY, 2),
                            RadiusPx       = (float)Math.Round(Math.Sqrt(dTopoMapX * dTopoMapX + dTopoMapY * dTopoMapY), 2),
                            X          = (float)Math.Round(avgX, 2),
                            Y          = (float)Math.Round(avgY, 2),
                            Z          = (float)Math.Round(avgZ, 2),
                            RadiusUu   = (float)Math.Round(Math.Sqrt(dX * dX + dY * dY), 2),
                            TrashQuota = area.TrashTierCount / (float)area.Structures.Count
                        });
                    } while (structures.Count > 0);

                    owner.AreaCount      = areas.Count;
                    owner.StructureCount = areas.Sum(y => y.StructureCount);

                    return(areas);
                }).ToArray();

                result.Areas  = structureAreas.OrderByDescending(x => x.Radius).ThenByDescending(x => x.StructureCount).ToList();
                result.Owners = owners.Values.OrderBy(x => x.Id).ToList();
                result.Types  = types.Values.OrderBy(x => x.Id).ToList();
            }

            return(result);
        }
Esempio n. 26
0
 void UpdateStructsKDTree()
 {
     structsInSightPosArr = new Vector3[structsInSight.Count];
     for (int i = 0; i < structsInSightPosArr.Length; i++)
     {
         structsInSightPosArr[i] = structsInSight[i].transform.position;
     }
     structsInSightTree = KDTree.MakeFromPoints(structsInSightPosArr);
 }
Esempio n. 27
0
        public void gh_784()
        {
            Accord.Math.Random.Generator.Seed = 0;
            var rnd = Accord.Math.Random.Generator.Random;

            // This is the same example found in Wikipedia page on
            // k-d trees: http://en.wikipedia.org/wiki/K-d_tree

            var image = UnmanagedImage.Create(800, 600, PixelFormat.Format24bppRgb);

            // Suppose we have the following set of points:
            var points     = new double[300000][];
            var listPoints = new List <IntPoint>(points.Length);

            for (int i = 0; i < points.Length; i++)
            {
                var point = new IntPoint(rnd.Next(0, image.Width), rnd.Next(0, image.Height));

                points[i] = new double[] { point.X, point.Y };

                listPoints.Add(point);
            }

            var region = new Rectangle(676, 441, 70, 55);

            var sw1 = new Stopwatch();

            sw1.Restart();
            var query1 = listPoints.FindAll((obj) =>
            {
                return(obj.X > region.Left && obj.X < region.Right && obj.Y > region.Top && obj.Y < region.Bottom);
            });

            sw1.Stop();

            listPoints.Clear();

            var sw2 = new Stopwatch();

            sw2.Restart();
            // To create a tree from a set of points, we can use
            var tree = KDTree.FromData <int>(points, new Accord.Math.Distances.Manhattan(), inPlace: true);

            sw2.Stop();

            var sw3 = new Stopwatch();

            sw3.Restart();
            var actual = tree.GetNodesInsideRegion(region.ToHyperrectangle()).Apply(x => new IntPoint((int)x.Position[0], (int)x.Position[1]));

            sw3.Stop();


            var sw4 = new Stopwatch();

            sw4.Restart();
            var expected = QueryKDTree2D(tree.Root, region);

            sw4.Stop();

            Assert.AreEqual(actual, expected);
        }
        // GET: JobsPage
        public ActionResult Index()
        {
            string id = User.Identity.GetUserId();
            var user = (from s in db.Users
                        where s.Id == id
                        select s).FirstOrDefault();
            if (user != null)
            {
                if (user.Role == Role.Seeker &&
                 user.SeekerAccount != null)
                {
                    SeekerAccount account = user.SeekerAccount;
                    if (account.CultureId != null &&
                        account.SkillRequirementId != null)
                    {
                        Culture culture = (from s in db.Cultures
                                           where s.Id == account.CultureId
                                           select s).FirstOrDefault();

                        SkillRequirement skill = (from sk in db.SkillRequirements
                                                  where sk.Id == account.SkillRequirementId
                                                  select sk).FirstOrDefault();

                        List<JobPosting> jobs = (from j in db.JobPostings
                                                 where j.Culture != null &&
                                                 j.SkillRequirement != null
                                                 select j).ToList();

                        int cultureSize = culture.MapSize;
                        double[] cultureMap = culture.Map;

                        int skillSize = skill.MapSize;
                        double[] skillMap = skill.Map;

                        KDTree<JobPosting> cultureTree = new KDTree<JobPosting>(cultureSize);
                        KDTree<JobPosting> skillTree = new KDTree<JobPosting>(skillSize);

                        foreach(JobPosting job in jobs)
                        {
                            Culture jobCulture = (from c in db.Cultures
                                              where c.Id == job.CultureId
                                              select c).FirstOrDefault();
                            if (culture == null)
                                continue;

                            cultureTree.AddPoint(jobCulture.Map, job);
                        }
                
                        List<JobPosting> results = new List<JobPosting>();

                        var closest = cultureTree.NearestNeighbors(cultureMap, 5);
                        for (; closest.MoveNext();)
                        {
                            SkillRequirement jobSkill = (from js in db.SkillRequirements
                                                         where js.Id == closest.Current.SkillRequirementId
                                                         select js).FirstOrDefault();
                            if (jobSkill == null) continue;
                            if(closest.CurrentDistance < 500)
                                skillTree.AddPoint(jobSkill.Map, closest.Current);
                        }

                        var sorted = skillTree.NearestNeighbors(skillMap, 5);
                        for (; sorted.MoveNext();)
                        {
                            results.Add(sorted.Current);
                        }

                        return View(results);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Seeker");
                    }
                }
                else if (user.Role == Role.Poster)
                {
                    var jobs = (from j in db.JobPostings
                               where j.UserId.Equals(user.Id)
                               select j).ToList();
                    return View("JobListPartialView", jobs);
                }
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
            var jobPostings = db.JobPostings.Include(j => j.Culture).Include(j => j.SkillRequirement).Include(j => j.User);
            return View(jobPostings.ToList());
        }
Esempio n. 29
0
 public LeaveOneOutCrossValidation(List <GISDataPoint> listGISDataPoints, KDTree tree, string outputDirectory)
 {
     this.listGISDataPoints = listGISDataPoints;
     this.tree             = tree;
     this._outputDirectory = outputDirectory;
 }
Esempio n. 30
0
        /// <summary>
        ///   Divides the input data into clusters.
        /// </summary>
        ///
        /// <param name="points">The data where to compute the algorithm.</param>
        /// <param name="threshold">The relative convergence threshold
        /// for the algorithm. Default is 1e-3.</param>
        /// <param name="maxIterations">The maximum number of iterations. Default is 100.</param>
        ///
        public int[] Compute(double[][] points, double threshold, int maxIterations = 100)
        {
            // first, select initial points
            double[][] seeds         = createSeeds(points, 2 * Bandwidth);
            var        maxcandidates = new ConcurrentStack <double[]>();

            // construct map of the data
            tree = KDTree.FromData <int>(points, distance);

            // now, for each initial point
            global::Accord.Threading.Tasks.Parallel.For(0, seeds.Length,
#if DEBUG
                                                        new ParallelOptions()
            {
                MaxDegreeOfParallelism = 1
            },
#endif

                                                        (index) =>
            {
                double[] point = seeds[index];
                double[] mean  = new double[point.Length];
                double[] delta = new double[point.Length];

                // we will keep moving it in the
                // direction of the density modes

                int iterations = 0;

                // until convergence or max iterations reached
                while (iterations < maxIterations)
                {
                    iterations++;

                    // compute the shifted mean
                    computeMeanShift(point, mean);

                    // extract the mean shift vector
                    for (int j = 0; j < mean.Length; j++)
                    {
                        delta[j] = point[j] - mean[j];
                    }

                    // update the point towards a mode
                    for (int j = 0; j < mean.Length; j++)
                    {
                        point[j] = mean[j];
                    }

                    // Check if we are already near any maximum point
                    if (cut && nearest(point, maxcandidates) != null)
                    {
                        break;
                    }

                    // check for convergence: magnitude of the mean shift
                    // vector converges to zero (Comaniciu 2002, page 606)
                    if (Norm.Euclidean(delta) < threshold * Bandwidth)
                    {
                        break;
                    }
                }

                if (cut)
                {
                    double[] match = nearest(point, maxcandidates);

                    if (match != null)
                    {
                        seeds[index] = match;
                    }

                    else
                    {
                        maxcandidates.Push(point);
                    }
                }
            });


            // suppress non-maximum points
            double[][] maximum = cut ? maxcandidates.ToArray() : supress(seeds);

            // create a decision map using seeds
            int[] seedLabels = classifySeeds(seeds, maximum);
            tree = KDTree.FromData(seeds, seedLabels, distance);

            // create the cluster structure
            clusters = new MeanShiftClusterCollection(tree, maximum);

            // label each point
            return(clusters.Nearest(points));
        }
Esempio n. 31
0
        private bool checkWeightedVertex(Polyline polyline, KDTree vertexIndex, SDMinVertex currentVertex, KDTree crossPointIndex)
        {
            // probably not an internal vertex
            if (currentVertex.Previous == null || currentVertex.Next == null)
                return true;

            // top with infinite weight ("do not remove")
            if (double.IsPositiveInfinity(currentVertex.Weight))
                return true;


            SDMinVertex previous = currentVertex.Previous;
            SDMinVertex next = currentVertex.Next;

            // One of the segments formed by the vertex in question may be one of the intersection points.
            // If so, you can not remove the top, as point of self-intersection, it may be removed.
            Segment s1 = new Segment(pointOfWeightedVertex(polyline, currentVertex),
                                     pointOfWeightedVertex(polyline, previous));
            Segment s2 = new Segment(pointOfWeightedVertex(polyline, currentVertex),
                                     pointOfWeightedVertex(polyline, next));

            List<SDMinCrossPoint> crossPoints = new List<SDMinCrossPoint>();
            crossPointIndex.QueryObjectsInRectangle(s1.GetBoundingRectangle(), crossPoints);
            crossPointIndex.QueryObjectsInRectangle(s2.GetBoundingRectangle(), crossPoints);
            foreach (SDMinCrossPoint point in crossPoints)
            {
                if (PlanimetryAlgorithms.LiesOnSegment(point.Point, s1))
                {
                    currentVertex.IsCrossSegmentVertex = true;
                    currentVertex.Previous.IsCrossSegmentVertex = true;
                    return false;
                }
                if(PlanimetryAlgorithms.LiesOnSegment(point.Point, s2))
                {
                    currentVertex.IsCrossSegmentVertex = true;
                    currentVertex.Next.IsCrossSegmentVertex = true;
                    return false;
                }
            }

            //One of the polyline vertices can belong to a triangle, 
            //the apex of which is considered the top. In this case,
            //the top can not be deleted because will be a new point of self-intersection.
            Polygon triangle = new Polygon(new ICoordinate[] { pointOfWeightedVertex(polyline, previous), 
                                                          pointOfWeightedVertex(polyline, currentVertex),
                                                          pointOfWeightedVertex(polyline, next) });

            List<SDMinVertex> vertices = new List<SDMinVertex>();
            vertexIndex.QueryObjectsInRectangle<SDMinVertex>(triangle.GetBoundingRectangle(), vertices);

            foreach (SDMinVertex vertex in vertices)
            {
                ICoordinate p = pointOfWeightedVertex(polyline, vertex);

                //point should not be the top of the triangle
                if (p.ExactEquals(triangle.Contours[0].Vertices[0]) ||
                   p.ExactEquals(triangle.Contours[0].Vertices[1]) ||
                   p.ExactEquals(triangle.Contours[0].Vertices[2]))
                    continue;

                if (triangle.ContainsPoint(p))
                    return false;
            }

            return true;
        }
Esempio n. 32
0
        public void NearestTest2()
        {
            double[][] points =
            {
                new double[] { 2, 3 },
                new double[] { 3, 2 },new double[]  { 3, 3 }, new double[] { 3, 4 },
                new double[] { 4, 3 },
            };

            var tree = KDTree.FromData <int>(points);

            tree.Distance = new Manhattan();

            Assert.AreEqual(3, tree.Root.Position[0]);
            Assert.AreEqual(3, tree.Root.Position[1]);

            if (tree.Root.Left.Position[0] == 2)
            {
                Assert.AreEqual(2, tree.Root.Left.Position[0]);
                Assert.AreEqual(3, tree.Root.Left.Position[1]);

                Assert.AreEqual(3, tree.Root.Right.Position[0]);
                Assert.AreEqual(4, tree.Root.Right.Position[1]);

                Assert.AreEqual(3, tree.Root.Left.Left.Position[0]);
                Assert.AreEqual(2, tree.Root.Left.Left.Position[1]);

                Assert.AreEqual(4, tree.Root.Right.Left.Position[0]);
                Assert.AreEqual(3, tree.Root.Right.Left.Position[1]);
            }
            else
            {
                Assert.AreEqual(3, tree.Root.Left.Position[0]);
                Assert.AreEqual(4, tree.Root.Left.Position[1]);

                Assert.AreEqual(4, tree.Root.Right.Position[0]);
                Assert.AreEqual(3, tree.Root.Right.Position[1]);

                Assert.AreEqual(2, tree.Root.Left.Left.Position[0]);
                Assert.AreEqual(3, tree.Root.Left.Left.Position[1]);

                Assert.AreEqual(3, tree.Root.Right.Left.Position[0]);
                Assert.AreEqual(2, tree.Root.Right.Left.Position[1]);
            }



            var result = tree.Nearest(new double[] { 3, 3 }, 5);

            double[][] expected =
            {
                new double[] { 2, 3 },
                new double[] { 3, 2 },new double[]  { 3, 3 }, new double[] { 3, 4 },
                new double[] { 4, 3 },
            };

            Assert.AreEqual(expected.Length, result.Count);

            double[][] actual = (from node in result select node.Node.Position).ToArray();

            for (int i = 0; i < expected.Length; i++)
            {
                Assert.IsTrue(actual.Contains(expected[i], new CustomComparer <double[]>((a, b) => a.IsEqual(b) ? 0 : 1)));
            }
        }
Esempio n. 33
0
 /// <summary>
 /// Construct an empty map.
 /// </summary>
 /// <param name="dimensions">Number of dimensions for each landmark.</param>
 public Map(int dimensions)
 {
     landmarks  = new KDTree <Gaussian>(dimensions);
     Dimensions = dimensions;
 }
Esempio n. 34
0
        private static void FindNearbyStructuresRecursive(double[] pt, HashSet <ArkStructure> points, KDTree <ArkStructure> tree, Area area, MinMaxCoords minmax, ref int pointsRemoved, Action <Area, ArkStructure, MinMaxCoords> addStructureToArea)
        {
            var near = tree.Nearest(pt, _coordRadius).Where(y => points.Contains(y.Node.Value)).ToArray();

            foreach (var item in near)
            {
                addStructureToArea(area, item.Node.Value, minmax);
                points.Remove(item.Node.Value);
            }
            pointsRemoved += near.Length;

            if (points.Count == 0)
            {
                return;
            }
            if (pointsRemoved >= 50)
            {
                tree          = KDTree.FromData(points.Select(y => new double[] { y.Location.Latitude.Value, y.Location.Longitude.Value }).ToArray(), points.ToArray());
                pointsRemoved = 0;
            }

            foreach (var item in near)
            {
                FindNearbyStructuresRecursive(item.Node.Position, points, tree, area, minmax, ref pointsRemoved, addStructureToArea);
            }
        }
        public bool Execute(IFeatureSet input, string zField, double cellSize, double power, int neighborType, int pointCount, double distance, IRaster output)
        {
            if (input == null || output == null)
            {
                return(false);
            }
            if (cellSize == 0)
            {
                cellSize = input.Extent.Width / 255;
            }
            int numColumns = Convert.ToInt32(Math.Round(input.Extent.Width / cellSize));
            int numRows    = Convert.ToInt32(Math.Round(input.Extent.Height / cellSize));

            output            = Raster.CreateRaster(output.Filename, string.Empty, numColumns, numRows, 1, typeof(double), new[] { string.Empty });//error
            output.CellHeight = cellSize;
            output.CellWidth  = cellSize;
            output.Xllcenter  = input.Extent.MinX + (cellSize / 2);
            output.Yllcenter  = input.Extent.MinY + (cellSize / 2);
            progress.Maximum  = numColumns * numRows;
            progress.Value    = 0;
            #region 构建KD树
            List <KD_Point> lists = new List <KD_Point>();//构建KD-Tree的点集列表
            foreach (var p in input.Features)
            {
                KD_Point kd = new KD_Point(p.BasicGeometry.Coordinates[0].X, p.BasicGeometry.Coordinates[0].Y, Convert.ToDouble(p.DataRow[zField]));
                lists.Add(kd);
            }
            KDTree kDTree = new KDTree();
            kDTree.CreateByPointList(lists);

            /*
             * double gdistance = input.Features[0].BasicGeometry.Coordinates[0].Distance(input.Features[1].BasicGeometry.Coordinates[0]);
             * double tdistance = Math.Sqrt(Math.Pow(input.Features[0].BasicGeometry.Coordinates[0].X- input.Features[1].BasicGeometry.Coordinates[0].X, 2) + Math.Pow(input.Features[0].BasicGeometry.Coordinates[0].Y- input.Features[1].BasicGeometry.Coordinates[0].Y, 2));
             * Console.WriteLine("gdistance: " + gdistance + " , tdistance: " + tdistance);
             */
            #endregion
            if (neighborType == 0)//固定数目
            {
                for (int x = 0; x < numColumns; x++)
                {
                    for (int y = 0; y < numRows; y++)
                    {
                        //IDW算法的分子和分母
                        double top    = 0;
                        double bottom = 0;
                        if (pointCount > 0)
                        {
                            Coordinate      coord    = output.CellToProj(y, x);
                            KD_Point        kD_Point = new KD_Point(coord.X, coord.Y);
                            List <KD_Point> points   = kDTree.K_Nearest(kD_Point, pointCount);
                            //Console.WriteLine("KDTree points count: " + points.Count);
                            for (int i = 0; i < points.Count; i++)
                            {
                                if (points[i] != null)
                                {
                                    Coordinate kd             = new Coordinate(points[i].X, points[i].Y);
                                    double     distanceToCell = kd.Distance(coord);
                                    if (distanceToCell <= distance || distance == 0)
                                    {
                                        //Console.WriteLine(points[i].Z);
                                        if (power == 2)
                                        {
                                            top    += (1 / (distanceToCell * distanceToCell)) * points[i].Z;
                                            bottom += 1 / (distanceToCell * distanceToCell);
                                        }
                                        else
                                        {
                                            top    += (1 / Math.Pow(distanceToCell, power)) * points[i].Z;
                                            bottom += 1 / Math.Pow(distanceToCell, power);
                                        }
                                    }
                                }
                            }
                        }

                        else
                        {
                            for (int i = 0; i < input.Features.Count; i++)
                            {
                                Coordinate cellCenter = output.CellToProj(y, x);
                                //Coordinate coord = output.CellToProj(y, x);
                                var featurePt = input.Features[i];
                                if (featurePt != null)
                                {
                                    double distanceToCell = cellCenter.Distance(featurePt.BasicGeometry.Coordinates[0]);
                                    if (distanceToCell <= distance || distance == 0)
                                    {
                                        try
                                        {
                                            Convert.ToDouble(featurePt.DataRow[zField]);
                                        }
                                        catch
                                        {
                                            continue;
                                        }
                                        if (power == 2)
                                        {
                                            top    += (1 / (distanceToCell * distanceToCell)) * Convert.ToDouble(featurePt.DataRow[zField]);
                                            bottom += 1 / (distanceToCell * distanceToCell);
                                        }
                                        else
                                        {
                                            top    += (1 / Math.Pow(distanceToCell, power)) * Convert.ToDouble(featurePt.DataRow[zField]);
                                            bottom += 1 / Math.Pow(distanceToCell, power);
                                        }
                                    }
                                }
                            }
                        }
                        //Console.WriteLine("top: " + top + " , bottom: " +bottom);
                        output.Value[y, x] = top / bottom;
                        //Console.WriteLine(y + " , " + x + " : " + output.Value[y, x]);
                        //richText.Text += output.Value[y, x] + "\n";
                        progress.Value++;
                    }
                }
            }
            output.Save();
            return(true);
        }
Esempio n. 36
0
 public void LoadObj(string path)
 {
     ISceneObject[] objs = _reader.Read(path);
     _tree = new KDTree <ISceneObject>(objs);
 }
Esempio n. 37
0
        public void GenerateGeometry(ref byte[] DensityField, byte IsoValue, int DensityFieldWidth, int DensityFieldHeight, int DensityFieldDepth, int Width, int Height, int Depth, int xOrigin, int yOrigin, int zOrigin, Vector3 ratio, Matrix transform)
        {
            DestroyBuffers();

            List<VertexPN> _vertices = new List<VertexPN>();
            List<ushort> _indices = new List<ushort>();
            SortedList<int, ushort> _edgeToIndices = new SortedList<int, ushort>();
            collisionGraph.Clear();

            int width = DensityFieldWidth;
            int sliceArea = width * DensityFieldHeight;

            byte[] DensityCache = new byte[8];
            Vector3[] VectorCache = new Vector3[8];
            for (int z = zOrigin; z < zOrigin + Depth; z++)
            {
                for (int y = yOrigin; y < yOrigin + Height; y++)
                {

                    int dIdx = z * sliceArea + y * width + xOrigin;

                    VectorCache[0] = new Vector3(xOrigin, y, z) * ratio - Vector3.One;
                    VectorCache[3] = new Vector3(xOrigin, y + 1, z) * ratio - Vector3.One;
                    VectorCache[4] = new Vector3(xOrigin, y, z + 1) * ratio - Vector3.One;
                    VectorCache[7] = new Vector3(xOrigin, y + 1, z + 1) * ratio - Vector3.One;
                    DensityCache[0] = DensityField[dIdx];
                    DensityCache[3] = DensityField[dIdx + width];
                    DensityCache[4] = DensityField[dIdx + sliceArea];
                    DensityCache[7] = DensityField[dIdx + sliceArea + width];

                    for (int x = xOrigin + 1; x <= xOrigin + Width; x++)
                    {
                        dIdx = z * sliceArea + y * width + x;

                        VectorCache[1] = new Vector3(x, y, z) * ratio - Vector3.One;
                        VectorCache[2] = new Vector3(x, y + 1, z) * ratio - Vector3.One;
                        VectorCache[5] = new Vector3(x, y, z + 1) * ratio - Vector3.One;
                        VectorCache[6] = new Vector3(x, y + 1, z + 1) * ratio - Vector3.One;
                        DensityCache[1] = DensityField[dIdx];
                        DensityCache[2] = DensityField[dIdx + width];
                        DensityCache[5] = DensityField[dIdx + sliceArea];
                        DensityCache[6] = DensityField[dIdx + sliceArea + width];
                        /*
                           Determine the index into the edge table which
                           tells us which vertices are inside of the surface
                        */
                        int cubeindex = 0;
                        if (DensityCache[0] > IsoValue) cubeindex |= 1;
                        if (DensityCache[1] > IsoValue) cubeindex |= 2;
                        if (DensityCache[2] > IsoValue) cubeindex |= 4;
                        if (DensityCache[3] > IsoValue) cubeindex |= 8;
                        if (DensityCache[4] > IsoValue) cubeindex |= 16;
                        if (DensityCache[5] > IsoValue) cubeindex |= 32;
                        if (DensityCache[6] > IsoValue) cubeindex |= 64;
                        if (DensityCache[7] > IsoValue) cubeindex |= 128;

                        /* Cube is entirely in/out of the surface */
                        if (cubeindex != 0 && cubeindex != 255)
                        {
                            /*0-r
                            1-r+x
                            2-r+x+y
                            3-r+y
                            4-r+z
                            5-r+x+z
                            6-r+x+y+z
                            7-r+y+z
                            */
                            //Now lets generate some normal vectors!
                            Vector3[] NormalCache = new Vector3[8];
                            NormalCache[0] = ComputeNormal(ref DensityField, DensityFieldWidth, DensityFieldHeight, DensityFieldDepth, x - 1, y, z);
                            NormalCache[1] = ComputeNormal(ref DensityField, DensityFieldWidth, DensityFieldHeight, DensityFieldDepth, x, y, z);
                            NormalCache[2] = ComputeNormal(ref DensityField, DensityFieldWidth, DensityFieldHeight, DensityFieldDepth, x, y + 1, z);
                            NormalCache[3] = ComputeNormal(ref DensityField, DensityFieldWidth, DensityFieldHeight, DensityFieldDepth, x - 1, y + 1, z);
                            NormalCache[4] = ComputeNormal(ref DensityField, DensityFieldWidth, DensityFieldHeight, DensityFieldDepth, x - 1, y, z + 1);
                            NormalCache[5] = ComputeNormal(ref DensityField, DensityFieldWidth, DensityFieldHeight, DensityFieldDepth, x, y, z + 1);
                            NormalCache[6] = ComputeNormal(ref DensityField, DensityFieldWidth, DensityFieldHeight, DensityFieldDepth, x, y + 1, z + 1);
                            NormalCache[7] = ComputeNormal(ref DensityField, DensityFieldWidth, DensityFieldHeight, DensityFieldDepth, x - 1, y + 1, z + 1);
                            for (int i = 0; VoxelHelper.NewTriangleTable2[cubeindex, i] != -1; i += 3)
                            {
                                int[] edgeIndices = new int[3];
                                for (int j = 0; j < 3; j++)
                                {
                                    int idx = GetEdgeId(DensityFieldWidth, DensityFieldHeight, x, y, z, VoxelHelper.NewTriangleTable2[cubeindex, i + j]);
                                    edgeIndices[j] = idx;
                                    if(!collisionGraph.ContainsKey(idx))
                                        collisionGraph.Add(idx, new List<TriangleGraph>());
                                    if (!_edgeToIndices.ContainsKey(idx))
                                    {
                                        _edgeToIndices.Add(idx, (ushort)_vertices.Count);

                                        _vertices.Add(GenerateVertex(VoxelHelper.NewTriangleTable2[cubeindex, i + j], VectorCache, NormalCache, DensityCache, IsoValue));
                                    }
                                    _indices.Add(_edgeToIndices[idx]);
                                }
                                ushort id0 = _indices[_indices.Count - 3];
                                ushort id1 = _indices[_indices.Count - 2];
                                ushort id2 = _indices[_indices.Count - 1];
                                Vector3 v0 = Vector3.Transform(_vertices[id0].Position, transform);
                                Vector3 v1 = Vector3.Transform(_vertices[id1].Position, transform);
                                Vector3 v2 = Vector3.Transform(_vertices[id2].Position, transform);
                                TriangleGraph graph = new TriangleGraph(id0, id1, id2, v0, v1, v2);
                                for (int j = 0; j < edgeIndices.Length; j++)
                                    collisionGraph[edgeIndices[j]].Add(graph);

                                PrimitiveCount++;
                            }
                        }
                        //Swap our caches
                        VectorCache[0] = VectorCache[1];
                        VectorCache[3] = VectorCache[2];
                        VectorCache[4] = VectorCache[5];
                        VectorCache[7] = VectorCache[6];
                        DensityCache[0] = DensityCache[1];
                        DensityCache[3] = DensityCache[2];
                        DensityCache[4] = DensityCache[5];
                        DensityCache[7] = DensityCache[6];
                    }
                }
            }

            verts = _vertices.ToArray();
            ib = _indices.ToArray();
            if (verts.Length > 0)
            {
                renderElement.VertexCount = verts.Length;
                renderElement.VertexBuffer = new VertexBuffer(GFX.Device, verts.Length * VertexPN.SizeInBytes, BufferUsage.WriteOnly);
                renderElement.VertexBuffer.SetData<VertexPN>(verts);
            }
            if (ib.Length > 0)
            {
                renderElement.IndexBuffer = new IndexBuffer(GFX.Device, ib.Length * sizeof(ushort), BufferUsage.WriteOnly, IndexElementSize.SixteenBits);
                renderElement.IndexBuffer.SetData<ushort>(ib);
                renderElement.PrimitiveCount = PrimitiveCount;
            }

            collisionTree = new KDTree<TriangleGraph>(TriangleCompareFunction);
            for (int i = 0; i < collisionGraph.Values.Count; i++)
            {
                List<TriangleGraph> entries = collisionGraph.Values[i];
                collisionTree.AddElementRange(entries.ToArray(), false);
            }
            collisionTree.BuildTree();

            CanRender = (PrimitiveCount > 0);
        }
Esempio n. 38
0
 public void KDTreeClearTest()
 {
     this.tree2D = new KDTree(this.coords2D, 2);
     this.tree2D.Clear();
     this.tree2D.NumberOfGeometries.ShouldBe(0);
 }
Esempio n. 39
0
    // Internal recursive algorithm for the kd-tree nearest neighbour search.
    private IKDTreeDomain NearestNeighbourI(IKDTreeDomain target, HyperRectangle hr, double maxDistSq, out double resDistSq)
    {
        resDistSq = Double.PositiveInfinity;

        IKDTreeDomain pivot = dr;

        HyperRectangle leftHr  = hr;
        HyperRectangle rightHr = leftHr.SplitAt(splitDim, pivot.GetDimensionElement(splitDim));

        HyperRectangle nearerHr, furtherHr;
        KDTree         nearerKd, furtherKd;

        // step 5-7
        if (target.GetDimensionElement(splitDim) <=
            pivot.GetDimensionElement(splitDim))
        {
            nearerKd  = left;
            nearerHr  = leftHr;
            furtherKd = right;
            furtherHr = rightHr;
        }
        else
        {
            nearerKd  = right;
            nearerHr  = rightHr;
            furtherKd = left;
            furtherHr = leftHr;
        }

        // step 8
        IKDTreeDomain nearest = null;
        double        distSq;

        if (nearerKd == null)
        {
            distSq = Double.PositiveInfinity;
        }
        else
        {
            nearest = nearerKd.NearestNeighbourI(target, nearerHr,
                                                 maxDistSq, out distSq);
        }

        // step 9
        maxDistSq = Math.Min(maxDistSq, distSq);

        // step 10
        if (furtherHr.IsInReach(target, Math.Sqrt(maxDistSq)))
        {
            double ptDistSq = KDTree.DistanceSq(pivot, target);
            if (ptDistSq < distSq)
            {
                // steps 10.1.1 to 10.1.3
                nearest   = pivot;
                distSq    = ptDistSq;
                maxDistSq = distSq;
            }

            // step 10.2
            double        tempDistSq;
            IKDTreeDomain tempNearest = null;
            if (furtherKd == null)
            {
                tempDistSq = Double.PositiveInfinity;
            }
            else
            {
                tempNearest = furtherKd.NearestNeighbourI(target,
                                                          furtherHr, maxDistSq, out tempDistSq);
            }

            // step 10.3
            if (tempDistSq < distSq)
            {
                nearest = tempNearest;
                distSq  = tempDistSq;
            }
        }

        resDistSq = distSq;
        return(nearest);
    }
Esempio n. 40
0
        private double[] move(KDTree <int> tree, double[][] points, int index,
                              ConcurrentStack <double[]> modes,
                              Action <ICollection <KDTreeNodeDistance <int> >, double[]> computeMean)
        {
            double[] current = points[index];
            double[] mean    = new double[current.Length];
            double[] shift   = new double[current.Length];

            // we will keep moving it in the
            // direction of the density modes

            int iterations = 0;

            // until convergence or max iterations reached
            while (iterations < MaxIterations)
            {
                iterations++;

                // Get points near the current point
                var neighbors = tree.Nearest(current, Bandwidth * 3, maximum);

                // compute the mean on the region
                computeMean(neighbors, mean);

                // extract the mean shift vector
                for (int j = 0; j < mean.Length; j++)
                {
                    shift[j] = current[j] - mean[j];
                }

                // move the point towards a mode
                for (int j = 0; j < mean.Length; j++)
                {
                    current[j] = mean[j];
                }

                // Check if we are near to a maximum point
                if (cut)
                {
                    // Check if we are near a known mode
                    foreach (double[] mode in modes)
                    {
                        // compute the distance between points
                        // if they are near, they are duplicates
                        if (Distance.Distance(points[index], mode) < Bandwidth)
                        {
                            // Yes, we are close to a known mode. Let's substitute
                            // this point with a reference to this nearest mode
                            return(points[index] = mode); // and stop moving this point
                        }
                    }
                }

                // check for convergence: magnitude of the mean shift
                // vector converges to zero (Comaniciu 2002, page 606)
                if (Norm.Euclidean(shift) < Tolerance * Bandwidth)
                {
                    return(supress(points, index, modes));
                }
            }

            throw new NotImplementedException();
        }
Esempio n. 41
0
    private IKDTreeDomain NearestNeighbourListI(SortedLimitedList best, int q, IKDTreeDomain target, HyperRectangle hr, double maxDistSq, out double resDistSq)
    {
        resDistSq = Double.PositiveInfinity;

        IKDTreeDomain pivot = dr;

        best.Add(new BestEntry(dr, KDTree.DistanceSq(target, dr)));

        HyperRectangle leftHr  = hr;
        HyperRectangle rightHr = leftHr.SplitAt(splitDim,
                                                pivot.GetDimensionElement(splitDim));

        HyperRectangle nearerHr, furtherHr;
        KDTree         nearerKd, furtherKd;

        // step 5-7
        if (target.GetDimensionElement(splitDim) <=
            pivot.GetDimensionElement(splitDim))
        {
            nearerKd  = left;
            nearerHr  = leftHr;
            furtherKd = right;
            furtherHr = rightHr;
        }
        else
        {
            nearerKd  = right;
            nearerHr  = rightHr;
            furtherKd = left;
            furtherHr = leftHr;
        }

        // step 8
        IKDTreeDomain nearest = null;
        double        distSq;

        // No child, bottom reached!
        if (nearerKd == null)
        {
            distSq = Double.PositiveInfinity;
        }
        else
        {
            nearest = nearerKd.NearestNeighbourListI(best, q, target, nearerHr,
                                                     maxDistSq, out distSq);
        }

        // step 9
        //maxDistSq = Math.Min (maxDistSq, distSq);
        if (best.Count >= q)
        {
            maxDistSq = ((BestEntry)best[q - 1]).Distance;
        }
        else
        {
            maxDistSq = Double.PositiveInfinity;
        }

        // step 10
        if (furtherHr.IsInReach(target, Math.Sqrt(maxDistSq)))
        {
            double ptDistSq = KDTree.DistanceSq(pivot, target);
            if (ptDistSq < distSq)
            {
                // steps 10.1.1 to 10.1.3
                nearest = pivot;
                distSq  = ptDistSq;

                // TODO: use k-element list

                /*
                 * best.Add (new BestEntry (pivot, ptDistSq));
                 * best.Sort ();
                 */

                maxDistSq = distSq;
            }

            // step 10.2
            double        tempDistSq;
            IKDTreeDomain tempNearest = null;
            if (furtherKd == null)
            {
                tempDistSq = Double.PositiveInfinity;
            }
            else
            {
                tempNearest = furtherKd.NearestNeighbourListI(best, q, target,
                                                              furtherHr, maxDistSq, out tempDistSq);
            }

            // step 10.3
            if (tempDistSq < distSq)
            {
                nearest = tempNearest;
                distSq  = tempDistSq;
            }
        }

        resDistSq = distSq;
        return(nearest);
    }
Esempio n. 42
0
        public void FromDataTest()
        {
            // This is the same example found in Wikipedia page on
            // k-d trees: http://en.wikipedia.org/wiki/K-d_tree

            // Suppose we have the following set of points:

            double[][] points =
            {
                new double[] { 2, 3 },
                new double[] { 5, 4 },
                new double[] { 9, 6 },
                new double[] { 4, 7 },
                new double[] { 8, 1 },
                new double[] { 7, 2 },
            };


            // To create a tree from a set of points, we use
            KDTree <int> tree = KDTree.FromData <int>(points);

            // Now we can manually navigate the tree
            KDTreeNode <int> node = tree.Root.Left.Right;

            // Or traverse it automatically
            foreach (KDTreeNode <int> n in tree)
            {
                double[] location = n.Position;
                Assert.AreEqual(2, location.Length);
            }

            // Given a query point, we can also query for other
            // points which are near this point within a radius

            double[] query = new double[] { 5, 3 };

            // Locate all nearby points within an Euclidean distance of 1.5
            // (answer should be a single point located at position (5,4))
            List <KDTreeNodeDistance <int> > result = tree.Nearest(query, radius: 1.5);

            // We can also use alternate distance functions
            tree.Distance = Accord.Math.Distance.Manhattan;

            // And also query for a fixed number of neighbor points
            // (answer should be the points at (5,4), (7,2), (2,3))
            KDTreeNodeCollection <int> neighbors = tree.Nearest(query, neighbors: 3);


            Assert.IsTrue(node.IsLeaf);
            Assert.IsFalse(tree.Root.IsLeaf);

            Assert.AreEqual(1, result.Count);
            Assert.AreEqual("(5,4)", result[0].Node.ToString());

            Assert.AreEqual(3, neighbors.Count);
            Assert.AreEqual("(5,4)", neighbors[2].Node.ToString());
            Assert.AreEqual("(7,2)", neighbors[1].Node.ToString());
            Assert.AreEqual("(2,3)", neighbors[0].Node.ToString());

            Assert.AreEqual(7, tree.Root.Position[0]);
            Assert.AreEqual(2, tree.Root.Position[1]);
            Assert.AreEqual(0, tree.Root.Axis);

            Assert.AreEqual(5, tree.Root.Left.Position[0]);
            Assert.AreEqual(4, tree.Root.Left.Position[1]);
            Assert.AreEqual(1, tree.Root.Left.Axis);

            Assert.AreEqual(9, tree.Root.Right.Position[0]);
            Assert.AreEqual(6, tree.Root.Right.Position[1]);
            Assert.AreEqual(1, tree.Root.Right.Axis);

            Assert.AreEqual(2, tree.Root.Left.Left.Position[0]);
            Assert.AreEqual(3, tree.Root.Left.Left.Position[1]);
            Assert.AreEqual(0, tree.Root.Left.Left.Axis);

            Assert.AreEqual(4, tree.Root.Left.Right.Position[0]);
            Assert.AreEqual(7, tree.Root.Left.Right.Position[1]);
            Assert.AreEqual(0, tree.Root.Left.Right.Axis);

            Assert.AreEqual(8, tree.Root.Right.Left.Position[0]);
            Assert.AreEqual(1, tree.Root.Right.Left.Position[1]);
            Assert.AreEqual(0, tree.Root.Right.Left.Axis);

            Assert.IsNull(tree.Root.Right.Right);
        }
Esempio n. 43
0
    private IKDTreeDomain NearestNeighbourListBBFI(SortedLimitedList best,
                                                   int q, IKDTreeDomain target, HyperRectangle hr, float maxDistSq,
                                                   out float resDistSq, SortedLimitedList searchHr, ref int searchSteps)
    {
        resDistSq = float.MaxValue;

        IKDTreeDomain pivot = dr;

        best.Add(new BestEntry(dr, KDTree.DistanceSq(target, dr), true));

        HyperRectangle leftHr  = hr;
        HyperRectangle rightHr = leftHr.SplitAt(splitDim,
                                                pivot.GetDimensionElement(splitDim));

        HyperRectangle nearerHr, furtherHr;
        KDTree         nearerKd, furtherKd;

        // step 5-7
        if (target.GetDimensionElement(splitDim) <= pivot.GetDimensionElement(splitDim))
        {
            nearerKd  = left;
            nearerHr  = leftHr;
            furtherKd = right;
            furtherHr = rightHr;
        }
        else
        {
            nearerKd  = right;
            nearerHr  = rightHr;
            furtherKd = left;
            furtherHr = leftHr;
        }

        // step 8
        IKDTreeDomain nearest = null;
        float         distSq;

        searchHr.Add(new HREntry(furtherHr, furtherKd, pivot, furtherHr.Distance(target)));

        // No child, bottom reached!
        if (nearerKd == null)
        {
            distSq = float.MaxValue;
        }
        else
        {
            nearest = nearerKd.NearestNeighbourListBBFI(best, q, target, nearerHr, maxDistSq, out distSq, searchHr, ref searchSteps);
        }

        // step 9
        if (best.Count >= q)
        {
            maxDistSq = ((BestEntry)best[q - 1]).DistanceSq;
        }
        else
        {
            maxDistSq = float.MaxValue;
        }

        if (searchHr.Count > 0)
        {
            HREntry hre = (HREntry)searchHr[0];
            searchHr.RemoveAt(0);

            furtherHr = hre.HR;
            furtherKd = hre.Tree;
            pivot     = hre.Pivot;
        }

        // step 10
        searchSteps -= 1;
        if (searchSteps > 0 && furtherHr.IsInReach(target, Math.Sqrt(maxDistSq)))
        {
            float ptDistSq = KDTree.DistanceSq(pivot, target);
            if (ptDistSq < distSq)
            {
                // steps 10.1.1 to 10.1.3
                nearest = pivot;
                distSq  = ptDistSq;

                maxDistSq = distSq;
            }

            // step 10.2
            float         tempDistSq;
            IKDTreeDomain tempNearest = null;
            if (furtherKd == null)
            {
                tempDistSq = float.MaxValue;
            }
            else
            {
                tempNearest = furtherKd.NearestNeighbourListBBFI(best, q, target, furtherHr, maxDistSq, out tempDistSq, searchHr,
                                                                 ref searchSteps);
            }

            // step 10.3
            if (tempDistSq < distSq)
            {
                nearest = tempNearest;
                distSq  = tempDistSq;
            }
        }

        resDistSq = distSq;
        return(nearest);
    }
Esempio n. 44
0
        private LevelRangePolygon[] assignLevelsToPolygons(double surfaceMin, double surfaceMax, IList<Polygon> polygons, List<Triangle> triangles, double[] zLevels, BoundingRectangle bounds)
        {
            List<Feature> triangularFeatures = new List<Feature>();

            foreach (Triangle t in triangles)
            {
                Polygon p = new Polygon(new ICoordinate[] 
                { 
                    new Coordinate3D(t.Cell1.DataPoint.Values()),
                    new Coordinate3D(t.Cell2.DataPoint.Values()),
                    new Coordinate3D(t.Cell3.DataPoint.Values())
                });
                triangularFeatures.Add(new Feature(p));
            }

            triangles = null;

            KDTree index = new KDTree(bounds);
            index.MinObjectCount = 10;
            index.MaxDepth = 20;
            index.BoxSquareThreshold = index.IndexedSpace.Width * index.IndexedSpace.Height / 10000;

            index.Build(triangularFeatures);

            LevelRange[] ranges = getRanges(surfaceMin, surfaceMax, zLevels);

            List<LevelRangePolygon> result = new List<LevelRangePolygon>();

            foreach (Polygon p in polygons)
            {
                ICoordinate c = p.PointOnSurface();
                List<Feature> t = new List<Feature>();
                index.QueryObjectsContainingPoint(c, t);
                foreach (Feature f in t)
                {
                    Polygon triangle = f.Polygon;
                    if (triangle.ContainsPoint(c))
                    {
                        double z =
                            getZ(c,
                                 new Coordinate3D(triangle.Contours[0].Vertices[0].Values()),
                                 new Coordinate3D(triangle.Contours[0].Vertices[1].Values()),
                                 new Coordinate3D(triangle.Contours[0].Vertices[2].Values()));

                        LevelRange range = getRange(z, ranges);
                        result.Add(new LevelRangePolygon(range, p));
                        break;
                    }
                }
            }

            return result.ToArray();
        }
Esempio n. 45
0
 void Awake()
 {
     KDTreeOfPoints = KDTree.MakeFromPoints(Positions.ToArray());
 }
Esempio n. 46
0
 /// <summary>
 ///   Creates a new <see cref="KNearestNeighbors"/>.
 /// </summary>
 ///
 /// <param name="k">The number of nearest neighbors to be used in the decision.</param>
 /// <param name="classes">The number of classes in the classification problem.</param>
 ///
 /// <param name="inputs">The input data points.</param>
 /// <param name="outputs">The associated labels for the input points.</param>
 ///
 public KNearestNeighbors(int k, int classes, double[][] inputs, int[] outputs)
     : base(k, classes, inputs, outputs, new Accord.Math.Distances.Euclidean())
 {
     this.tree = KDTree.FromData(inputs, outputs, new Accord.Math.Distances.Euclidean());
 }
Esempio n. 47
0
 /// <summary>
 ///   Creates a new <see cref="KNearestNeighbors"/>.
 /// </summary>
 ///
 /// <param name="k">The number of nearest neighbors to be used in the decision.</param>
 /// <param name="classes">The number of classes in the classification problem.</param>
 ///
 /// <param name="inputs">The input data points.</param>
 /// <param name="outputs">The associated labels for the input points.</param>
 ///
 public KNearestNeighbors(int k, int classes, double[][] inputs, int[] outputs)
     : base(k, classes, inputs, outputs, BestCS.Math.Distance.Euclidean)
 {
     this.tree = KDTree.FromData(inputs, outputs, BestCS.Math.Distance.Euclidean);
 }
Esempio n. 48
0
 private KNearestNeighbors(KDTree <int> tree, int k, int classes,
                           double[][] inputs, int[] outputs, IMetric <double[]> distance)
     : base(k, classes, inputs, outputs, distance)
 {
     this.tree = tree;
 }
Esempio n. 49
0
        public List <Node> Compute(int startX, int startY, int endX, int endY, int attemps, float speed, Cell[][][] matrix, bool smooth = false)
        {
            // Initialization
            tree       = new KDTree(3);
            explored   = new List <Node> ();
            nodeMatrix = matrix;

            //Start and ending node
            Node start = GetNode(0, startX, startY);

            start.visited = true;
            start.parent  = null;

            // Prepare start and end node
            Node end = GetNode(0, endX, endY);

            tree.insert(start.GetArray(), start);
            explored.Add(start);

            // Prepare the variables
            Node nodeVisiting     = null;
            Node nodeTheClosestTo = null;

            float tan = speed / 1;

            angle = 90f - Mathf.Atan(tan) * Mathf.Rad2Deg;

            List <Distribution.Pair> pairs = new List <Distribution.Pair> ();

            for (int x = 0; x < matrix[0].Length; x++)
            {
                for (int y = 0; y < matrix[0].Length; y++)
                {
                    if (((Cell)matrix [0] [x] [y]).waypoint)
                    {
                        pairs.Add(new Distribution.Pair(x, y));
                    }
                }
            }

            pairs.Add(new Distribution.Pair(end.x, end.y));

            //Distribution rd = new Distribution(matrix[0].Length, pairs.ToArray());

            //RRT algo
            for (int i = 0; i <= attemps; i++)
            {
                //Get random point
                int rt = Random.Range(1, nodeMatrix.Length);
                //Distribution.Pair p = rd.NextRandom();
                int rx = Random.Range(0, nodeMatrix [rt].Length);
                int ry = Random.Range(0, nodeMatrix [rt] [rx].Length);
                //int rx = p.x, ry = p.y;
                nodeVisiting = GetNode(rt, rx, ry);
                if (nodeVisiting.visited || !nodeVisiting.cell.IsWalkable())
                {
                    i--;
                    continue;
                }

                explored.Add(nodeVisiting);

                nodeTheClosestTo = (Node)tree.nearest(new double[] { rx, rt, ry });

                // Skip downwards movement
                if (nodeTheClosestTo.t > nodeVisiting.t)
                {
                    continue;
                }

                // Only add if we are going in ANGLE degrees or higher
                Vector3 p1 = nodeVisiting.GetVector3();
                Vector3 p2 = nodeTheClosestTo.GetVector3();
                Vector3 pd = p1 - p2;
                if (Vector3.Angle(pd, new Vector3(pd.x, 0f, pd.z)) < angle)
                {
                    continue;
                }

                // And we have line of sight
                if (!nodeVisiting.cell.IsWalkable() || Extra.Collision.CheckCollision(nodeVisiting, nodeTheClosestTo, this, SpaceState.Editor, true))
                {
                    continue;
                }

                try {
                    tree.insert(nodeVisiting.GetArray(), nodeVisiting);
                } catch (KeyDuplicateException) {
                }

                nodeVisiting.parent  = nodeTheClosestTo;
                nodeVisiting.visited = true;

                // Attemp to connect to the end node
                if (Random.Range(0, 1000) > 0)
                {
                    p1   = nodeVisiting.GetVector3();
                    p2   = end.GetVector3();
                    p2.y = p1.y;
                    float dist = Vector3.Distance(p1, p2);

                    float t = dist * Mathf.Tan(angle);
                    pd    = p2;
                    pd.y += t;

                    if (pd.y <= nodeMatrix.GetLength(0))
                    {
                        Node endNode = GetNode((int)pd.y, (int)pd.x, (int)pd.z);
                        if (!Extra.Collision.CheckCollision(nodeVisiting, endNode, this, SpaceState.Editor, true))
                        {
                            //Debug.Log ("Done3");
                            endNode.parent = nodeVisiting;
                            return(ReturnPath(endNode, smooth));
                        }
                    }
                }

                //Might be adding the neighboor as a the goal
                if (nodeVisiting.x == end.x & nodeVisiting.y == end.y)
                {
                    //Debug.Log ("Done2");
                    return(ReturnPath(nodeVisiting, smooth));
                }
            }

            return(new List <Node> ());
        }
Esempio n. 50
0
        void InitializeVoxels()
        {
            int voxelCountX = (DensityFieldWidth - 1) / VoxelGridSize;
            int voxelCountY = (DensityFieldHeight - 1) / VoxelGridSize;
            int voxelCountZ = (DensityFieldDepth - 1) / VoxelGridSize;
            Voxels = new VoxelGeometry[voxelCountX * voxelCountY * voxelCountZ];
            VoxelBounds = new BoundingBox[Voxels.Length];
            voxelKDTree = new KDTree<VoxelElement>(VoxelCompareFunction, VoxelBoundsFunction, false, true);
            Vector3 ratio = Vector3.One * 2.0f * (float)VoxelGridSize / new Vector3(DensityFieldWidth-1,DensityFieldHeight-1,DensityFieldDepth-1);

            for (int z = 0; z < voxelCountZ; z++)
            {
                int zOff = voxelCountX * voxelCountY * z;
                for (int y = 0; y < voxelCountY; y++)
                {
                    int yOff = voxelCountX * y;

                    for (int x = 0; x < voxelCountX; x++)
                    {
                        int idx = x + yOff + zOff;
                        /*
                        VoxelBounds[idx] = new BoundingBox(new Vector3(x, y, z) * ratio - Vector3.One, new Vector3(x + 1, y + 1, z + 1) * ratio - Vector3.One);
                        VoxelBounds[idx].Min = Vector3.Transform(VoxelBounds[idx].Min, Transformation.GetTransform());
                        VoxelBounds[idx].Max = Vector3.Transform(VoxelBounds[idx].Max, Transformation.GetTransform());
                        */
                        Voxels[idx] = new VoxelGeometry((ushort)idx);
                        Voxels[idx].renderElement.Transform = new Matrix[1] { Transformation.GetTransform() };
                        Vector3 geometryRatio = 2.0f*Vector3.One / new Vector3(DensityFieldWidth-1,DensityFieldHeight-1,DensityFieldDepth-1);
                        Voxels[idx].GenerateGeometry(ref DensityField, IsoValue, DensityFieldWidth, DensityFieldHeight, DensityFieldDepth, VoxelGridSize, VoxelGridSize, VoxelGridSize, x * VoxelGridSize, y * VoxelGridSize, z * VoxelGridSize, geometryRatio, this.Transformation.GetTransform());

                        VoxelBounds[idx] = MathUtils.TransformBounds(Voxels[idx].GetBounds(), Transformation.GetTransform());
                        if(Voxels[idx].CanRender)
                            voxelKDTree.AddElement(new VoxelElement(Voxels[idx], VoxelBounds[idx]), false);
                    }
                }
            }
            voxelKDTree.BuildTree();
            RecursivelyBuildBounds(voxelKDTree.GetRoot());

            terrainQuadMaterial = ResourceManager.Inst.GetMaterial("TerrainQuadMaterial");
            giantQuadElement = GFXPrimitives.Decal.GetRenderElement();
            Matrix quadMatrix = Matrix.CreateScale(1.5f) * Matrix.CreateRotationX(MathHelper.Pi) * this.Transformation.GetTransform();
            quadMatrix.Translation = Vector3.Up * this.Transformation.GetBounds().Min.Y;
            giantQuadElement.Transform = new Matrix[1] { quadMatrix };
        }
Esempio n. 51
0
 public KDTreeContour(Direct3DSurface surface) : base(surface)
 {
     _data = new KDTree <float>(2);
 }
Esempio n. 52
0
 void UpdateEnemyKDTree()
 {
     enemiesInSightPosArr = new Vector3[enemiesInSight.Count];
     for (int i = 0; i < enemiesInSightPosArr.Length; i++)
     {
         enemiesInSightPosArr[i] = enemiesInSight[i].transform.position;
     }
     enemiesInSightTree = KDTree.MakeFromPoints(enemiesInSightPosArr);
 }
Esempio n. 53
0
    public void SplitDestroy(Vector3 hitPoint, float hitForce, PhysicalProperties physicalProperties)
    {
        messages.Add("Starting");
        float time      = Time.realtimeSinceStartup;
        float startTime = time;

        voxelisationDriver.StartVoxelise(gameObject);


        messages.Add("Voxelisation: " + (Time.realtimeSinceStartup - time));
        csvList.Add((Time.realtimeSinceStartup - time) + " ");
        time = Time.realtimeSinceStartup;

        grid = voxelisationDriver.GetGrid();

        fragments = destruction.Fragment(grid, hitPoint, hitForce, physicalProperties);

        messages.Add("Destruction: " + (Time.realtimeSinceStartup - time));
        csvList.Add((Time.realtimeSinceStartup - time) + " ");
        time = Time.realtimeSinceStartup;

        colouring = destruction.getVoronoiDiagram();

        foreach (Fragment c in fragments.Values)
        {
            c.vertices.Clear();
        }

        short[, ,] borderColouring = new short[colouring.GetLength(0), colouring.GetLength(1), colouring.GetLength(2)];

        List <Vector3> vectors = new List <Vector3>();

        for (int i = 0; i < colouring.GetLength(0); i++)
        {
            for (int j = 0; j < colouring.GetLength(1); j++)
            {
                for (int k = 0; k < colouring.GetLength(2); k++)
                {
                    short c          = colouring[i, j, k];
                    bool  neighbours = false;
                    bool  exterior   = false;
                    if (c == 0)
                    {
                        continue;
                    }
                    for (int x = -1; x <= 1; x++)
                    {
                        for (int y = -1; y <= 1; y++)
                        {
                            for (int z = -1; z <= 1; z++)
                            {
                                if (i + x < 0 || j + y < 0 || k + z < 0)
                                {
                                    continue;
                                }
                                if (i + x >= colouring.GetLength(0) || j + y >= colouring.GetLength(1) || k + z >= colouring.GetLength(2))
                                {
                                    continue;
                                }
                                if (colouring[i + x, j + y, k + z] != c && colouring[i + x, j + y, k + z] != 0)
                                {
                                    neighbours = true;
                                }
                                if (colouring[i + x, j + y, k + z] == 0)
                                {
                                    exterior = true;
                                }
                            }
                        }
                    }
                    if (exterior)
                    {
                        vectors.Add(new Vector3(i, j, k));
                    }
                    if (neighbours)
                    {
                        borderColouring[i, j, k] = c;
                    }
                    if (neighbours && exterior)
                    {
                        Fragment colour;
                        if (fragments.TryGetValue(c, out colour))
                        {
                            colour.vertices.Add(new Vector3(i, j, k));
                        }
                    }
                }
            }
        }

        KDTree tree = KDTree.MakeFromPoints(vectors.ToArray());

        messages.Add("KDTree: " + (Time.realtimeSinceStartup - time));
        time = Time.realtimeSinceStartup;

        MeshInfo original = new MeshInfo(gameObject.GetComponent <MeshFilter>().mesh.vertices, gameObject.GetComponent <MeshFilter>().mesh.triangles, new Fragment(0));

        Dictionary <short, MeshInfo> meshes = splitMesh.Split(original, tree, vectors, colouring, grid.GetSize());

        messages.Add("Split: " + (Time.realtimeSinceStartup - time));
        csvList.Add((Time.realtimeSinceStartup - time) + " ");
        time = Time.realtimeSinceStartup;


        if (!hollow)
        {
            csvList.Add("Meshing ");

            foreach (Fragment colour in fragments.Values)
            {
                if (colour == null)
                {
                    continue;
                }

                MeshInfo meshinfo, march;

                MeshInfo parent;
                bool     found = meshes.TryGetValue(colour.colour, out parent);

                colors.Add(colour.colour, new Color(Random.value, Random.value, Random.value));

                if (found)
                {
                    List <Vector3> edges    = parent.colour.vertices;
                    List <Vector3> exterior = new List <Vector3>();
                    foreach (Vector3 v in colour.vertices)
                    {
                        exterior.Add(toWorldSpace(v));
                    }

                    Vector3 voxelMid = new Vector3((colour.maxX - colour.minX) / 2, (colour.maxY - colour.minY) / 2, (colour.maxZ - colour.minZ) / 2);
                    voxelMid.x = voxelMid.x / grid.GetSize().x;
                    voxelMid.y = voxelMid.y / grid.GetSize().y;
                    voxelMid.z = voxelMid.z / grid.GetSize().z;
                    voxelMid  *= 2;

                    KDTree surface = KDTree.MakeFromPoints(edges.ToArray());
                    //meshinfo = holefill.Stitch(edges, colour, exterior);

                    meshinfo = marchingDriver.StartMarchingClamp(borderColouring, colour, grid, surface, edges);
                }
                else
                {
                    meshinfo = marchingDriver.StartMarching(borderColouring, colour, grid);
                    march    = marchingDriver.StartMarching(borderColouring, colour, grid);
                }
                //meshinfo = convexDriver.StartMeshing(colour);

                /*for (int c = 0; c < meshinfo.verts.Length; c++) {
                 *  meshinfo.verts[c] = new Vector3(meshinfo.verts[c].x / transform.lossyScale.x, meshinfo.verts[c].y / transform.lossyScale.y, meshinfo.verts[c].z / transform.lossyScale.z);
                 * }*/

                messages.Add("Meshing " + colour.colour + ": " + (Time.realtimeSinceStartup - time));
                csvList.Add((Time.realtimeSinceStartup - time) + " ");
                time = Time.realtimeSinceStartup;

                if (colour.colour == 0)
                {
                    continue;
                }
                else
                {
                    if (found)
                    {
                        List <Vector3> verts = new List <Vector3>(parent.verts);
                        int            count = verts.Count;
                        verts.AddRange(meshinfo.verts);

                        List <int> indices = new List <int>(parent.index);
                        foreach (int i in meshinfo.index)
                        {
                            indices.Add(i + count);
                        }

                        /*count = verts.Count;
                         * verts.AddRange(march.verts);
                         *
                         * foreach (int i in march.index) {
                         *  indices.Add(i + count);
                         * }*/

                        parent.verts       = verts.ToArray();
                        parent.index       = indices.ToArray();
                        parent.colour.mass = meshinfo.colour.mass;
                    }
                    else
                    {
                        meshes.Add(colour.colour, meshinfo);
                    }
                }
            }
        }

        csvList.Add("Building ");

        foreach (MeshInfo meshinfo in meshes.Values)
        {
            Mesh     mesh     = new Mesh();
            Fragment coloured = meshinfo.colour;

            fragments.TryGetValue(coloured.colour, out coloured);

            if (coloured.colour == 0)
            {
                continue;
            }

            mesh.vertices  = meshinfo.verts;
            mesh.triangles = meshinfo.index;

            //The diffuse shader wants uvs so just fill with a empty array, they're not actually used
            mesh.uv = new Vector2[mesh.vertices.Length];
            mesh.RecalculateNormals();
            mesh.RecalculateBounds();

            Mesh mesh1 = new Mesh();

            if (hollow)
            {
                List <int> indices = new List <int>(meshinfo.index);

                for (int i = 0; i < meshinfo.index.Length; i += 3)
                {
                    indices.Add(meshinfo.index[i + 2]);
                    indices.Add(meshinfo.index[i + 1]);
                    indices.Add(meshinfo.index[i + 0]);
                }

                meshinfo.index = indices.ToArray();

                /*List<Vector3> normals = new List<Vector3>(mesh.normals);
                 * for (int i = 0; i < mesh.normals.Length; i++)
                 *  normals.Add(-normals[i]);*/

                mesh1.vertices  = meshinfo.verts;
                mesh1.triangles = meshinfo.index;

                //The diffuse shader wants uvs so just fill with a empty array, they're not actually used
                mesh1.uv = new Vector2[mesh.vertices.Length];

                mesh1.normals = mesh.normals;
            }

            GameObject m_mesh = new GameObject("Fragment" + coloured.colour);
            m_mesh.AddComponent <MeshFilter>();
            m_mesh.AddComponent <MeshRenderer>();
            //MeshCollider col1 = m_mesh.AddComponent<MeshCollider>();
            MeshCollider col2 = m_mesh.AddComponent <MeshCollider>();

            m_mesh.AddComponent <Rigidbody>();
            //m_mesh.rigidbody.isKinematic = true;
            m_mesh.rigidbody.collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic;
            m_mesh.rigidbody.mass    = coloured.mass;
            m_mesh.renderer.material = m_material;

            //col1.sharedMesh = mesh;
            col2.sharedMesh = mesh;
            col2.convex     = true;

            m_mesh.GetComponent <MeshFilter>().mesh = hollow ? mesh1 : mesh;

            m_mesh.transform.localScale = transform.localScale;

            messages.Add("Built " + coloured.colour + ": " + (Time.realtimeSinceStartup - time));
            csvList.Add((Time.realtimeSinceStartup - time) + " ");
            time = Time.realtimeSinceStartup;
        }

        messages.Add("Done:" + (Time.realtimeSinceStartup - startTime));

        string csv = "";

        foreach (string str in csvList)
        {
            csv += str;
        }

        foreach (string str in messages)
        {
            Debug.Log(str);
        }

        //Debug.Log(csv);

        done = true;

        GameObject.Destroy(gameObject);
        if (breakP)
        {
            Debug.Break();
        }
    }
Esempio n. 54
0
        private static void AreEqual(KDTree<int> tree, double[][] expected, Func<KDTree<int>, IEnumerator<KDTreeNode<int>>> method)
        {
            double[][] actual = tree.Traverse(method.Invoke).Select(p => p.Position).ToArray();

            Assert.AreEqual(expected.Length, actual.Length);

            for (int i = 0; i < actual.Length; i++)
            {
                Assert.AreEqual(expected[i][0], actual[i][0]);
                Assert.AreEqual(expected[i][1], actual[i][1]);
            }
        }
Esempio n. 55
0
        private Task CreateTask(List <GISDataPoint>[] partitions, InverseDistanceWeightedExtension idwFunction, KDTree tree, int indx, int numOutputs)
        {
            var task = Task.Factory.StartNew(() =>
            {
                _outputLists[indx] = new List <string>();

                int partSize = partitions[indx].Count;
                for (int i = 0; i < partSize; i++)
                {
                    GISDataPoint dp = partitions[indx][i];
                    dp.measurement  = idwFunction.Interpolate(tree, dp, _listGISDataPoints);

                    //_outputLists[indx].Add(dp.ToString());
                    _outputLists[indx].Add(dp.ToStringForOutputFile());

                    // Increment Progress Bar here.
                    percentComplete = ((double)progress / (double)numOutputs) * 100;
                    //Console.Write("\r{0}" + " calculations done. [{1:#.##}% Complete]", progress, percentComplete);
                    GISLocationProcessed(string.Format("\r{0}" + " calculations done. [{1:#.##}% Complete]", progress, percentComplete));
                    progress++;
                }
            });

            return(task);
        }
Esempio n. 56
0
        public void FindClosestPointTest()
        {
            Console.WriteLine("Current Directory: " + System.IO.Directory.GetCurrentDirectory());
            List<Vector3> vertices;
            List<Face> faces;
            List<Color> colors;
            KDTree tree = new KDTree();
            {	//Build KDTree from a Wavefront .obj file
                if (!ObjIO.Read(@"D:\Libraries\KDTree2\KDTree_UnitTest\bin\Debug\test2.obj", out vertices, out colors, out faces))
                {
                    Assert.Fail("Failed to find test.obj");
                }
                tree.AddPoints(vertices);
                bool build_result = tree.Build();
                Assert.IsTrue(build_result);
            }

            {	// First test that loaded points can refind themselves.
                Stopwatch st = new Stopwatch();
                st.Start();

                bool match_result = true;
                for (int i = 0; i < vertices.Count; i++)
                {
                    int index = i;
                    int nearest_index = 0;
                    Vector3 tmp = tree.FindClosestPoint(vertices[index], 0.00f, ref nearest_index);
                    if (nearest_index != index)
                    {
                        Console.WriteLine("Vertex: " + vertices[index].ToString());
                        Console.WriteLine("Mis-Match: " + vertices[nearest_index].ToString());
                        Assert.Fail("Mismatched closest pair: " + index.ToString() + "," + nearest_index.ToString());
                    }
                }
                st.Stop();
                Console.WriteLine("Elapsed Exact Set = {0}", st.Elapsed.ToString());
                Assert.IsTrue(match_result);
            }

            {	// Next test that a completely random set of data can find a closest point, compare to brute force.
                Vector3 min,max,center,centroid,range;
                Vector3.Metrics(vertices,out min, out max, out center, out centroid, out range);
                Random random = new Random(42);
                Stopwatch st = new Stopwatch();
                st.Start();
                for (int i = 0; i < 1500; i++)
                {
                    float x = (float)random.Next((int)(min.X * 1000.0f), (int)(max.X * 1000.0f)); x /= 1000.0f;
                    float y = (float)random.Next((int)(min.Y * 1000.0f), (int)(max.Y * 1000.0f)); y /= 1000.0f;
                    float z = (float)random.Next((int)(min.Z * 1000.0f), (int)(max.Z * 1000.0f)); z /= 1000.0f;

                    int closest_index = 0;
                    int closest_index2 = 0;
                    Vector3 vertex = new Vector3(x, y, z);

                    Vector3 closest_vertex = tree.FindClosestPoint(vertex, 1.1f, ref closest_index);
                    Vector3 closest_vertex2 = tree.FindClosestPointBrute(vertex, ref closest_index2);

                    if (closest_vertex2.Distance(vertex) < closest_vertex.Distance(vertex))
                    {
                        st.Stop();
                        Console.WriteLine("Vertex: " + vertex.ToString());
                        Console.WriteLine("Match1: " + closest_vertex.ToString() + ": d=" + closest_vertex.Distance(vertex).ToString());
                        Console.WriteLine("Match2: " + closest_vertex2.ToString() + ": d=" + closest_vertex2.Distance(vertex).ToString());
                        //Assert.Fail("Incorrect matching vertex");
                        st.Start();
                    }
                }
                st.Stop();
                Console.WriteLine("Elapsed Random Set = {0}", st.Elapsed.ToString());
            }
        }
Esempio n. 57
0
 public override void Initialize()
 {
     base.Initialize();
     _entities = new KDTree.KDTree <VectorEntity>(2);
 }
Esempio n. 58
0
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt = readCSV("C:\\Users\\Vic\\Dropbox\\Data\\3day\\10in_1.csv");
            //dt = readCSV("C:\\Users\\Vic\\Desktop\\ewj.csv");

            //Console.WriteLine( dt.Columns.Count  );
            //Console.WriteLine(dt.Rows.Count);

            Stopwatch timer = new Stopwatch();  //碼表
            int Training_count = 20000;         //訓練資料的使用長度
            int MatchCount = 70;               //KNN裡的K值的大小
            //KDTree<double> _tree = new KDTree<double>(11);
            KDTree<double> _tree2 = new KDTree<double>(11);

            List<double> trade_list = new List<double>();
            List<double> EC1 = new List<double>();

            StreamWriter file = new System.IO.StreamWriter("C:\\001.csv");  //輸出觀察用的Log檔案
            double Long_Threshold = 0.1;
            double Short_Threshold = -0.2;
            int L_vote = 0;
            int S_vote = 0;
            double nodes_avg=0;
            double totalprofit;
            double mdd;

            timer.Reset();
            timer.Start();

            List<HistoricalStock>  data = HistoricalStockDownloader.DownloadData("SPY", 1962);
            Console.WriteLine("Get SPY from Yahoo : {0}ticks ,{1}msec", timer.ElapsedTicks, timer.ElapsedMilliseconds);
            timer.Reset();
            timer.Start();

            //把上面的資料想辦法用來計算 coodrs

            PatternFinder PF = new PatternFinder(data);

            for (int i = 10; i < 1000; i++)
            {
                PF.CalcHistorical();   //<<<<<<<-------------------------- 卡關 _tree.Add 傳入參數跟型態都沒問題,但是就是沒法加入節點
                PF.CurrentBar++;

                Console.WriteLine("CurrentBar={0} ,DateT={1},E={2} ",PF.CurrentBar,PF.Date_Time[i],PF.Expectancy  );

                //Console.Write(PF.Date_Time[i].ToShortDateString()  +","  );
                //Console.WriteLine("data.Count:" + data.Count() );
            }

            Console.WriteLine("Tree Nodes Count:"+PF._tree.Count    );
            Console.WriteLine("共使用記憶體: {0}MB", Environment.WorkingSet / 1000000);

            Console.ReadLine();
            return;  // 使用返回  中斷程式,直到上面的做好

            // 舊的流程
            for (int CurrentBar = 1; CurrentBar < dt.Rows.Count; CurrentBar++)
            {

                DataRow row = dt.Rows[CurrentBar];
                Double[] coords = new double[11];

                    //Get 11 dimentions into Array
                    for (int i2 = 4; i2 < row.ItemArray.Count() ; i2++)
                    {   coords[i2-4] = Convert.ToDouble(row.ItemArray[4])  ;   }

                    if (CurrentBar <= Training_count)
                    {   //將陣列做為index值,報酬率作為value存入KD二元樹
                        //_tree.Add(coords, Convert.ToDouble(row.ItemArray[3]));
                        //_tree2.Add(coords, Convert.ToDouble(row.ItemArray[3]));

                    }
                    else   //CurrentBar大於Training_count以後,開始Testing運算,模擬交易開始
                    {
                        L_vote = 0;
                        S_vote = 0;
                        Long_Threshold = 0.3;
                        Short_Threshold = -0.3;

                        //string s = SiteHelper.Serialize(_tree2);

                        for (int i3 = 1; i3 <= 7; i3++ )
                        {
                            //nodes_avg = _tree.Nearest(coords, MatchCount*i3  ).Average(x => x.Node.Value);
                            if (nodes_avg >= Long_Threshold) { L_vote += 1; }
                            if (nodes_avg <= Short_Threshold) { S_vote += 1; }
                        }

                        //型態比對找出群組的平均值以後 如果大於 Long_Threshold 的投票數就模擬買進
                        if (L_vote>=6 )
                        {

                            trade_list.Add(Convert.ToDouble(row.ItemArray[3]) /100 * 1000000);
                            EC1.Add(trade_list.Sum());

                            string s_out = string.Format("{0},{1},{2},{3},{4}", Convert.ToDouble(row.ItemArray[1]), row.ItemArray[2], trade_list.Last(), EC1.Last(), Math.Round( nodes_avg,2) );

                            /*
                            Console.Write("" + Convert.ToDouble(row.ItemArray[1]) + " ");
                            Console.Write("" + row.ItemArray[2] + " ");
                            Console.Write(" " + trade_list.Last() );
                            Console.WriteLine(" "+ EC1.Last() );
                            */
                            Console.WriteLine(s_out);

                            /*
                            file.Write(Convert.ToDouble(row.ItemArray[1]) + ",");
                            file.Write(row.ItemArray[2] + ",");
                            file.Write(trade_list.Last()+"," );
                            file.WriteLine(EC1.Last()  );
                            */

                            file.WriteLine(s_out);

                        }

                        /*  Take Short trades
                        if (S_vote >= 6)
                        {
                            trade_list.Add(Convert.ToDouble(row.ItemArray[3]) / 100 * -1000000  );
                            EC1.Add(trade_list.Sum());
                            //trade_list.Add(Convert.ToDouble(row.ItemArray[1]) );
                            Console.Write("" + Convert.ToDouble(row.ItemArray[1]) + " ");
                            Console.Write("" + row.ItemArray[2] + " ");
                            Console.Write(" " + trade_list.Last());
                            Console.WriteLine(" " + EC1.Last());

                            file.Write(Convert.ToDouble(row.ItemArray[1]) + ",");
                            file.Write(row.ItemArray[2] + ",");
                            file.Write(" " + trade_list.Last());
                            file.WriteLine(" " + EC1.Last());

                        }
                        */

                        /*
                        //Console.Write(CurrentBar );
                        Console.Write(row.ItemArray[1]);
                        Console.Write(" Forecast is:" + _tree.Nearest(coords, MatchCount).Average(x => x.Node.Value));
                        Console.WriteLine(" True Return is:" + Convert.ToDouble(row.ItemArray[3]) + "  ");
                        */

                        //Console.WriteLine(row.ItemArray.Count());
                    }
            }

            file.Close();

            totalprofit = trade_list.Sum();
            mdd = MaxDrawdown(EC1.ToArray());

            Console.WriteLine();
            Console.WriteLine("trade_list Profit: " + totalprofit );
            Console.WriteLine("MDD: " + mdd);
            Console.WriteLine("Profit/MDD: " +  Math.Round( totalprofit/mdd ,2)  );
            Console.WriteLine("Trades: " + trade_list.Count );
            Console.WriteLine("EC1 Count: " + EC1.Count);
            Console.WriteLine( "Total Rows: "+ dt.Rows.Count );
            //Console.WriteLine( "Tree Count(Training Count): " + _tree.Count() );

            /*
            //KDTree<double> _tree2 =
            KDTreeNodeCollection<double>  kd_nodes;
            Dictionary<KDTreeNodeCollection<double>  , int>   Dict= new Dictionary<KDTreeNodeCollection<double>,int>()  ;

            foreach (var nodes in _tree2 ){

            kd_nodes=  _tree.Nearest(nodes.Position , MatchCount) ;

            //Console.WriteLine(nodes.Position +"  "  );
            //Console.WriteLine(nodes.GetType() );

                if (Dict.ContainsKey( kd_nodes )  )
                {

                }
                else
                {
                    Dict.Add(kd_nodes, 1);

                }

            }

            Console.WriteLine("Dict count:" + Dict.Count );
             */

            // EC1 畫圖輸出來觀察 create the chart
            var chart = new Chart();
            chart.Size = new Size(600, 600);

            var chartArea = new ChartArea();
            //chartArea.AxisX.LabelStyle.Format = "dd/MMM\nhh:mm";
            chartArea.AxisX.Interval = 1;
            chartArea.AxisX.MajorGrid.LineColor = Color.LightGray;
            chartArea.AxisY.MajorGrid.LineColor = Color.LightGray;
            chartArea.AxisX.LabelStyle.Font = new Font("Consolas", 8);
            chartArea.AxisY.LabelStyle.Font = new Font("Consolas", 8);
            chart.ChartAreas.Add(chartArea);

            var series = new Series();
            series.Name = "Series1";
            series.ChartType = SeriesChartType.FastLine;
            series.XValueType = ChartValueType.DateTime;
            chart.Series.Add(series);

            /*
            foreach (int i4 in EC1) {
            series.Points.AddY(i4  );
            } */

            foreach (HistoricalStock stock in data)
            {
                //Console.WriteLine(string.Format("Date={0} High={1} Low={2} Open={3} Close={4}", stock.Date.ToShortDateString() , stock.High, stock.Low, stock.Open, stock.Close)  );
                //Console.WriteLine(stock.Date.ToShortDateString()+",");

                series.Points.AddXY( stock.Date ,stock.Close );
            }

            // draw!
            chart.Invalidate();

            // write out a file
            chart.SaveImage("c:\\chart.png", ChartImageFormat.Png);

            Process.Start(@"c:\\chart.png");

            Console.ReadLine();
        }
        private void buildAndSaveIndex(MapAround.Mapping.FeatureType featureType, 
                               BoundingRectangle b,
                               IndexSettings settings, 
                               IEnumerable<Feature> features)
        {
            ISpatialIndex index = null;

            if (b.IsEmpty())
                b = new BoundingRectangle(0, 0, 0, 0);

            if (settings.IndexType == "QuadTree")
                index = new QuadTree(b);
            if (index == null)
                index = new KDTree(b);

            index.MaxDepth = settings.MaxDepth;
            index.BoxSquareThreshold = settings.BoxSquareThreshold;
            index.MinObjectCount = settings.MinFeatureCount;

            index.Build(features);

            _cacheAccessor.SaveFeaturesIndex(index, featureType);
        }