Krotos Modules 3
Loading...
Searching...
No Matches
NearestNeighbourSearch2D.cpp
Go to the documentation of this file.
2
3namespace krotos
4{
5
7{
8 // dataset.data.reserve(dataset.dim * max_elements);
9
10 // m_spaceInstance = std::make_unique <hnswlib::L2Space>(dataset.dim);
11 // The line below is for compatability with hnswlib. space is a ptr to hnswlib::SpaceInterface,
12 // an abstract class which can't be instantiated as is - it is used as an interface class
13 // Assigning m_spaceInstance raw pointer here should be safe because m_spaceInstance
14 // will persist until owning class is destroyed
15 // If anyone can see a better way to do this outside of re-factoring hnswlib, please do !
16 space = m_spaceInstance.get();
17 alg = std::make_unique<hnswlib::BruteforceSearch<float>>(space, 2 * max_elements);
18}
19
25
27{
28 dataset.data.push_back(x);
29 dataset.data.push_back(y);
30 alg->addPoint(dataset.data.data() + dataset.index * dataset.dim, dataset.index);
31 ++dataset.index;
32}
33
35{
36 assert(!dataset.data.empty());
37
38 std::array<float, 2> features = {x, y};
39 auto result = alg->searchKnn(features.data(), 1);
40 return static_cast<int>(result.top().second);
41}
42
43std::vector<int> NearestNeighbourSearch2D::knnQuery(float x, float y, int k)
44{
45 assert(k <= dataset.index);
46
47 std::array<float, 2> features = {x, y};
48
49 // avoid k larger than dataset
50 k = k <= dataset.index ? k : dataset.index;
51
52 std::vector<int> indices;
53 auto results = alg->searchKnnCloserFirst(features.data(), k);
54 for (const auto& result : results)
55 indices.push_back(static_cast<int>(result.second));
56
57 return indices;
58}
59} // namespace krotos
std::unique_ptr< hnswlib::L2Space > m_spaceInstance
Definition NearestNeighbourSearch2D.h:35
void addDatasetItem(float x, float y)
Definition NearestNeighbourSearch2D.cpp:26
Dataset2D dataset
Definition NearestNeighbourSearch2D.h:31
int knnQuery(float x, float y)
Definition NearestNeighbourSearch2D.cpp:34
hnswlib::SpaceInterface< float > * space
Definition NearestNeighbourSearch2D.h:33
~NearestNeighbourSearch2D()
Definition NearestNeighbourSearch2D.cpp:20
NearestNeighbourSearch2D(int max_elements)
Definition NearestNeighbourSearch2D.cpp:6
std::unique_ptr< hnswlib::BruteforceSearch< float > > alg
Definition NearestNeighbourSearch2D.h:32
Definition AirAbsorptionFilter.cpp:2
static constexpr int dim
Definition NearestNeighbourSearch2D.h:14
int index
Definition NearestNeighbourSearch2D.h:13
std::vector< float > data
Definition NearestNeighbourSearch2D.h:12