|
| 1 | +// This is a test file for testing the interface |
| 2 | +// >>> virtual std::vector<std::pair<dist_t, labeltype>> |
| 3 | +// >>> searchKnnCloserFirst(const void* query_data, size_t k) const; |
| 4 | +// of class AlgorithmInterface |
| 5 | + |
| 6 | +#include "../hnswlib/hnswlib.h" |
| 7 | + |
| 8 | +#include <assert.h> |
| 9 | + |
| 10 | +#include <vector> |
| 11 | +#include <iostream> |
| 12 | + |
| 13 | +namespace |
| 14 | +{ |
| 15 | + |
| 16 | +using idx_t = hnswlib::labeltype; |
| 17 | + |
| 18 | +void test() { |
| 19 | + int d = 4; |
| 20 | + idx_t n = 100; |
| 21 | + idx_t nq = 10; |
| 22 | + size_t k = 10; |
| 23 | + |
| 24 | + std::vector<float> data(n * d); |
| 25 | + std::vector<float> query(nq * d); |
| 26 | + |
| 27 | + std::mt19937 rng; |
| 28 | + rng.seed(47); |
| 29 | + std::uniform_real_distribution<> distrib; |
| 30 | + |
| 31 | + for (idx_t i = 0; i < n * d; ++i) { |
| 32 | + data[i] = distrib(rng); |
| 33 | + } |
| 34 | + for (idx_t i = 0; i < nq * d; ++i) { |
| 35 | + query[i] = distrib(rng); |
| 36 | + } |
| 37 | + |
| 38 | + |
| 39 | + hnswlib::L2Space space(d); |
| 40 | + hnswlib::AlgorithmInterface<float>* alg_brute = new hnswlib::BruteforceSearch<float>(&space, 2 * n); |
| 41 | + hnswlib::AlgorithmInterface<float>* alg_hnsw = new hnswlib::HierarchicalNSW<float>(&space, 2 * n); |
| 42 | + |
| 43 | + for (size_t i = 0; i < n; ++i) { |
| 44 | + alg_brute->addPoint(data.data() + d * i, i); |
| 45 | + alg_hnsw->addPoint(data.data() + d * i, i); |
| 46 | + } |
| 47 | + |
| 48 | + // test searchKnnCloserFirst of BruteforceSearch |
| 49 | + for (size_t j = 0; j < nq; ++j) { |
| 50 | + const void* p = query.data() + j * d; |
| 51 | + auto gd = alg_brute->searchKnn(p, k); |
| 52 | + auto res = alg_brute->searchKnnCloserFirst(p, k); |
| 53 | + assert(gd.size() == res.size()); |
| 54 | + size_t t = gd.size(); |
| 55 | + while (!gd.empty()) { |
| 56 | + assert(gd.top() == res[--t]); |
| 57 | + gd.pop(); |
| 58 | + } |
| 59 | + } |
| 60 | + for (size_t j = 0; j < nq; ++j) { |
| 61 | + const void* p = query.data() + j * d; |
| 62 | + auto gd = alg_hnsw->searchKnn(p, k); |
| 63 | + auto res = alg_hnsw->searchKnnCloserFirst(p, k); |
| 64 | + assert(gd.size() == res.size()); |
| 65 | + size_t t = gd.size(); |
| 66 | + while (!gd.empty()) { |
| 67 | + assert(gd.top() == res[--t]); |
| 68 | + gd.pop(); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + delete alg_brute; |
| 73 | + delete alg_hnsw; |
| 74 | +} |
| 75 | + |
| 76 | +} // namespace |
| 77 | + |
| 78 | +int main() { |
| 79 | + std::cout << "Testing ..." << std::endl; |
| 80 | + test(); |
| 81 | + std::cout << "Test ok" << std::endl; |
| 82 | + |
| 83 | + return 0; |
| 84 | +} |
0 commit comments