public KDNode(int index, KDNode parent = null, KDNode left = null, KDNode right = null) { this.ElementIndex = index; this.Left = left; this.Right = right; this.Parent = parent; }
public KDTreeNavigator(KDTree <TNode> tree, KDNode node) { this.tree = tree; this.node = node; }
/// <summary> /// A top-down recursive method to find the nearest neighbors of a given point. /// </summary> /// <param name="node">The index of the node for the current recursion branch.</param> /// <param name="target">The point whose neighbors we are trying to find.</param> /// <param name="rect">The <see cref="HyperRect{T}"/> containing the possible nearest neighbors.</param> /// <param name="dimension">The current splitting dimension for this recursion branch.</param> /// <param name="nearestNeighbors">The <see cref="BoundedPriorityList{TElement,TPriority}"/> containing the nearest neighbors already discovered.</param> /// <param name="maxSearchRadius">The radius of the current largest distance to search from the <paramref name="target"/></param> private void SearchForNearestNeighbors( KDNode node, double[] target, HyperRect <double> rect, int dimension, BoundablePriorityList <int, double> nearestNeighbors, double maxSearchRadius) { if (node == null) { return; } // Work out the current dimension var dim = dimension % this.Dimensions; // Get the coordinate of the current node. var coordinate = this.PointSelector(this.InternalList[node.ElementIndex]); // Split our hyper-rectangle into 2 sub rectangles along the current // node's point on the current dimension var leftRect = rect.Clone(); leftRect.MaxPoint[dim] = coordinate[dim]; var rightRect = rect.Clone(); rightRect.MinPoint[dim] = coordinate[dim]; // Determine which side the target resides in var comparison = target[dim] <= coordinate[dim]; var nearerRect = comparison ? leftRect : rightRect; var furtherRect = comparison ? rightRect : leftRect; var nearerNode = comparison ? node.Left : node.Right; var furtherNode = comparison ? node.Right : node.Left; // Move down into the nearer branch this.SearchForNearestNeighbors( nearerNode, target, nearerRect, dimension + 1, nearestNeighbors, maxSearchRadius); // Walk down into the further branch but only if our capacity hasn't been reached // OR if there's a region in the further rectangle that's closer to the target than our // current furtherest nearest neighbor var closestPointInFurtherRect = furtherRect.GetClosestPoint(target); var distanceToTarget = this.Metric(closestPointInFurtherRect, target); if (distanceToTarget.CompareTo(maxSearchRadius) <= 0) { if (nearestNeighbors.IsFull) { if (distanceToTarget.CompareTo(nearestNeighbors.MaxPriority) < 0) { this.SearchForNearestNeighbors( furtherNode, target, furtherRect, dimension + 1, nearestNeighbors, maxSearchRadius); } } else { this.SearchForNearestNeighbors( furtherNode, target, furtherRect, dimension + 1, nearestNeighbors, maxSearchRadius); } } // Try to add the current node to our nearest neighbors list distanceToTarget = this.Metric(coordinate, target); if (distanceToTarget.CompareTo(maxSearchRadius) <= 0) { nearestNeighbors.Add(node.ElementIndex, distanceToTarget); } }
/// <summary> /// Grows a KD tree recursively via median splitting. We find the median by doing a full sort. /// </summary> /// <param name="currentNode">The array index for the current node.</param> /// <param name="dim">The current splitting dimension.</param> /// <param name="points">The set of points remaining to be added to the KDTree.</param> /// <param name="nodes">The set of nodes RE</param> private void GenerateTree( ref KDNode currentNode, KDNode previousNode, int dim, IReadOnlyCollection <CoordinateWithIndex> points) { // See wikipedia for a good explanation KDTree construction. // https://en.wikipedia.org/wiki/K-d_tree // sort the points along the current dimension var sortedPoints = points.OrderBy(z => z.Coordinate[dim]).ToArray(); // get the point which has the median value of the current dimension. var medianPoint = sortedPoints[points.Count / 2]; var medianPointIdx = sortedPoints.Length / 2; // The point with the median value all the current dimension now becomes the value of the current tree node // The previous node becomes the parents of the current node. currentNode = new KDNode(medianPoint.Index, previousNode); previousNode = currentNode; // We now split the sorted points into 2 groups // 1st group: points before the median var leftPoints = new CoordinateWithIndex[medianPointIdx]; Array.Copy(sortedPoints, leftPoints, leftPoints.Length); // 2nd group: Points after the median var rightPoints = new CoordinateWithIndex[sortedPoints.Length - (medianPointIdx + 1)]; Array.Copy( sortedPoints, medianPointIdx + 1, rightPoints, 0, rightPoints.Length); // We new recurse, passing the left and right arrays for arguments. // The current node's left and right values become the "roots" for // each recursion call. We also forward cycle to the next dimension. var nextDim = (dim + 1) % this.Dimensions; // select next dimension // We only need to recurse if the point array contains more than one point // If the array has no points then the node stay a null value if (leftPoints.Length <= 1) { if (leftPoints.Length == 1) { currentNode.Left = new KDNode(leftPoints[0].Index, previousNode); } } else { this.GenerateTree(ref currentNode.Left, currentNode, nextDim, leftPoints); } // Do the same for the right points if (rightPoints.Length <= 1) { if (rightPoints.Length == 1) { currentNode.Right = new KDNode(rightPoints[0].Index, previousNode); } } else { this.GenerateTree(ref currentNode.Right, currentNode, nextDim, rightPoints); } }