nn.h
1/*
2Copyright (c) 2004, Tim Bailey
3All rights reserved.
4
5Redistribution and use in source and binary forms, with or without
6modification, are permitted provided that the following conditions are met:
7
8 * Redistributions of source code must retain the above copyright notice,
9 this list of conditions and the following disclaimer.
10 * Redistributions in binary form must reproduce the above copyright notice,
11 this list of conditions and the following disclaimer in the documentation
12 and/or other materials provided with the distribution.
13 * Neither the name of the Player Project nor the names of its contributors
14 may be used to endorse or promote products derived from this software
15 without specific prior written permission.
16
17THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
18ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
21ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
24ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27*/
28
29
30/* Nearest-neighbours algorithm for 2D point-sets.
31 * Compute the single nearest-neighbour of a point, or the set of k-nearest neighbours.
32 *
33 * This is a very simple algorithm that is reasonably efficient for planar
34 * points. However much faster algorithms are possible.
35 *
36 * Tim Bailey 2004.
37 */
38
39#ifndef NN_HEADER
40#define NN_HEADER
41
42#include "geometry2D.h"
43#include <vector>
44
45namespace Geom2D {
46
47// Simple 2D k-nearest-neighbours search
48//
50public:
51 enum { NOT_FOUND = -1 };
52
53 SweepSearch(const std::vector<Point> &p, double dmax);
54
55 int query(const Point &q) const;
56 std::vector<double>& query(const Point &q, std::vector<int> &idx);
57
58private:
59 struct PointIdx {
60 PointIdx() {}
61 PointIdx(const Point &p_, const int& i_) : p(p_), i(i_) {}
62 Point p;
63 int i;
64 };
65
66 const double limit;
67 std::vector<PointIdx> dataset;
68 std::vector<double> nndists;
69
70 bool is_nearer(double &d2min, int &idxmin, const Point &q, const PointIdx &pi) const;
71
72 bool insert_neighbour(const Point &q, const PointIdx &pi,
73 std::vector<double> &nndists, std::vector<int> &idx);
74
75 static bool yorder (const PointIdx& p, const PointIdx& q) {
76 return p.p.y < q.p.y;
77 }
78};
79
80}
81
82#endif
Definition nn.h:49
Definition geometry2D.h:51