forked from xinranhe/HNSW
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhnsw.h
69 lines (60 loc) · 1.68 KB
/
hnsw.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#ifndef HNSW_H
#define HNSW_H
#include <random>
#include <vector>
#include <unordered_map>
#include <iostream>
using namespace std;
struct Item {
vector<double> values;
Item(vector<double> _values):values(_values) {}
// Assume L2 distance
double dist(Item& other) {
double result = 0.0;
for (int i = 0; i < values.size(); i++) result += (values[i] - other.values[i]) * (values[i] - other.values[i]);
return result;
}
};
struct HNSWGraph {
HNSWGraph(int _M, int _MMax, int _MMax0, int _efConstruction, int _ml,int _testing):M(_M),MMax(_MMax),MMax0(_MMax0),efConstruction(_efConstruction),ml(_ml), testing(_testing){
layerEdgeLists.push_back(unordered_map<int, vector<int>>());
}
// Number of neighbors
int M;
// Max number of neighbors in layers >= 1
int MMax;
// Max number of neighbors in layers 0
int MMax0;
// Search numbers in construction
int efConstruction;
// Max number of layers
int ml;
// number of items
int itemNum;
// actual vector of the items
vector<Item> items;
// adjacent edge lists in each layer
vector<unordered_map<int, vector<int>>> layerEdgeLists;
// enter node id
int enterNode;
default_random_engine generator;
// testing
int testing;
// methods
void addEdge(int st, int ed, int lc);
vector<int> searchLayer(Item& q, int ep, int ef, int lc);
void Insert(Item& q);
vector<int> KNNSearch(Item& q, int K);
void printGraph() {
for (int l = layerEdgeLists.size()-1; l < layerEdgeLists.size(); l++) {
cout << "Layer:" << l << endl;
for (auto it = layerEdgeLists[l].begin(); it != layerEdgeLists[l].end(); ++it) {
cout << it->first << ":";
for (auto ed: it->second) cout << ed << " ";
cout << endl;
}
exit(0);
}
}
};
#endif