Faiss
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends
test_binary_flat.cpp
1 /**
2  * Copyright (c) 2015-present, Facebook, Inc.
3  * All rights reserved.
4  *
5  * This source code is licensed under the BSD+Patents license found in the
6  * LICENSE file in the root directory of this source tree.
7  */
8 
9 #include <cstdio>
10 #include <cstdlib>
11 
12 #include <gtest/gtest.h>
13 
14 #include <faiss/IndexBinaryFlat.h>
15 #include <faiss/hamming.h>
16 
17 TEST(BinaryFlat, accuracy) {
18  // dimension of the vectors to index
19  int d = 64;
20 
21  // size of the database we plan to index
22  size_t nb = 1000;
23 
24  // make the index object and train it
25  faiss::IndexBinaryFlat index(d);
26 
27  srand(35);
28 
29  std::vector<uint8_t> database(nb * (d / 8));
30  for (size_t i = 0; i < nb * (d / 8); i++) {
31  database[i] = rand() % 0x100;
32  }
33 
34  { // populating the database
35  index.add(nb, database.data());
36  }
37 
38  int nq = 200;
39 
40  { // searching the database
41 
42  std::vector<uint8_t> queries(nq * (d / 8));
43  for (size_t i = 0; i < nq * (d / 8); i++) {
44  queries[i] = rand() % 0x100;
45  }
46 
47  int k = 5;
48  std::vector<faiss::IndexBinary::idx_t> nns(k * nq);
49  std::vector<int> dis(k * nq);
50 
51  index.search(nq, queries.data(), k, dis.data(), nns.data());
52 
53  for (size_t i = 0; i < nq; ++i) {
54  faiss::HammingComputer8 hc(queries.data() + i * (d / 8), d / 8);
55  hamdis_t dist_min = hc.hamming(database.data());
56  for (size_t j = 1; j < nb; ++j) {
57  hamdis_t dist = hc.hamming(database.data() + j * (d / 8));
58  if (dist < dist_min) {
59  dist_min = dist;
60  }
61  }
62  EXPECT_EQ(dist_min, dis[k * i]);
63  }
64  }
65 }