From 8cafda35775944c84211f8daa28133428bddb169 Mon Sep 17 00:00:00 2001 From: BobLd Date: Mon, 9 Mar 2020 11:10:33 +0000 Subject: [PATCH] handle nearest neighbour not found --- .../ClusteringAlgorithms.cs | 7 +++++-- .../KdTree.cs | 15 ++++++++++++--- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/src/UglyToad.PdfPig.DocumentLayoutAnalysis/ClusteringAlgorithms.cs b/src/UglyToad.PdfPig.DocumentLayoutAnalysis/ClusteringAlgorithms.cs index 58bc2d5e..072469a5 100644 --- a/src/UglyToad.PdfPig.DocumentLayoutAnalysis/ClusteringAlgorithms.cs +++ b/src/UglyToad.PdfPig.DocumentLayoutAnalysis/ClusteringAlgorithms.cs @@ -63,9 +63,12 @@ { var paired = kdTree.FindNearestNeighbours(pivot, pivotPoint, distMeasure, out int index, out double dist); - if (filterFinal(pivot, paired) && dist < maxDistanceFunction(pivot, paired)) + if (index != -1) { - indexes[e] = index; + if (filterFinal(pivot, paired) && dist < maxDistanceFunction(pivot, paired)) + { + indexes[e] = index; + } } } }); diff --git a/src/UglyToad.PdfPig.DocumentLayoutAnalysis/KdTree.cs b/src/UglyToad.PdfPig.DocumentLayoutAnalysis/KdTree.cs index 1652ea9f..50a41bdc 100644 --- a/src/UglyToad.PdfPig.DocumentLayoutAnalysis/KdTree.cs +++ b/src/UglyToad.PdfPig.DocumentLayoutAnalysis/KdTree.cs @@ -66,12 +66,21 @@ } #region NN + /// + /// + /// + /// + /// + /// + /// The nearest neighbour's index (returns -1 if not found). + /// The distance between the pivot and the nearest neighbour (returns if not found). + /// The nearest neighbour's element. public T FindNearestNeighbours(T pivot, Func pivotPointFunc, Func distanceMeasure, out int index, out double distance) { var result = FindNearestNeighbours(Root, pivot, pivotPointFunc, distanceMeasure); - index = result.Item1.Index; - distance = result.Item2.Value; - return result.Item1.Element; + index = result.Item1 != null ? result.Item1.Index : -1; + distance = result.Item2.HasValue ? result.Item2.Value : double.NaN; + return result.Item1 != null ? result.Item1.Element : default; } private static (KdTreeNode, double?) FindNearestNeighbours(KdTreeNode node, T pivot, Func pivotPointFunc, Func distance)