knncolle_hnsw
knncolle bindings for HNSW
Loading...
Searching...
No Matches
distances.hpp
Go to the documentation of this file.
1#ifndef KNNCOLLE_HNSW_DISTANCES_HPP
2#define KNNCOLLE_HNSW_DISTANCES_HPP
3
4#include <cmath>
5#include <functional>
6
12namespace knncolle_hnsw {
13
20template<typename Dim_, typename InternalData_>
27 std::function<hnswlib::SpaceInterface<InternalData_>*(Dim_)> create;
28
34 std::function<InternalData_(InternalData_)> normalize;
35};
36
42template<typename InternalData_>
43class ManhattanDistance : public hnswlib::SpaceInterface<InternalData_> {
44private:
45 size_t my_data_size;
46 size_t my_dim;
47
48public:
52 ManhattanDistance(size_t dim) : my_data_size(dim * sizeof(InternalData_)), my_dim(dim) {}
53
57public:
58 size_t get_data_size() {
59 return my_data_size;
60 }
61
62 hnswlib::DISTFUNC<InternalData_> get_dist_func() {
63 return L1;
64 }
65
66 void * get_dist_func_param() {
67 return &my_dim;
68 }
69
70private:
71 static InternalData_ L1(const void *pVect1v, const void *pVect2v, const void *qty_ptr) {
72 const InternalData_* pVect1 = static_cast<const InternalData_*>(pVect1v);
73 const InternalData_* pVect2 = static_cast<const InternalData_*>(pVect2v);
74 size_t qty = *((size_t *) qty_ptr);
75 InternalData_ res = 0;
76 for (; qty > 0; --qty, ++pVect1, ++pVect2) {
77 res += std::abs(*pVect1 - *pVect2);
78 }
79 return res;
80 }
84};
85
91template<typename InternalData_>
92class SquaredEuclideanDistance : public hnswlib::SpaceInterface<InternalData_> {
93private:
94 size_t my_data_size;
95 size_t my_dim;
96
97public:
101 SquaredEuclideanDistance(size_t dim) : my_data_size(dim * sizeof(InternalData_)), my_dim(dim) {}
102
106public:
107 size_t get_data_size() {
108 return my_data_size;
109 }
110
111 hnswlib::DISTFUNC<InternalData_> get_dist_func() {
112 return L2;
113 }
114
115 void * get_dist_func_param() {
116 return &my_dim;
117 }
118
119private:
120 static InternalData_ L2(const void *pVect1v, const void *pVect2v, const void *qty_ptr) {
121 const InternalData_* pVect1 = static_cast<const InternalData_*>(pVect1v);
122 const InternalData_* pVect2 = static_cast<const InternalData_*>(pVect2v);
123 size_t qty = *((size_t *) qty_ptr);
124 InternalData_ res = 0;
125 for (; qty > 0; --qty, ++pVect1, ++pVect2) {
126 auto delta = *pVect1 - *pVect2;
127 res += delta * delta;
128 }
129 return res;
130 }
134};
135
136}
137
138#endif
Manhattan distance.
Definition distances.hpp:43
ManhattanDistance(size_t dim)
Definition distances.hpp:52
Squared Euclidean distance.
Definition distances.hpp:92
SquaredEuclideanDistance(size_t dim)
Definition distances.hpp:101
knncolle bindings for HNSW search.
Definition distances.hpp:12
Distance options for the HNSW index.
Definition distances.hpp:21
std::function< hnswlib::SpaceInterface< InternalData_ > *(Dim_)> create
Definition distances.hpp:27
std::function< InternalData_(InternalData_)> normalize
Definition distances.hpp:34