1#! /usr/bin/env python2
2
3# Copyright (c) Facebook, Inc. and its affiliates.
4#
5# This source code is licensed under the MIT license found in the
6# LICENSE file in the root directory of this source tree.
7
8from __future__ import print_function
9import numpy as np
10import faiss
11import time
12
13swig_ptr = faiss.swig_ptr
14
15if False:
16    a = np.arange(10, 14).astype('float32')
17    b = np.arange(20, 24).astype('float32')
18
19    faiss.fvec_inner_product (swig_ptr(a), swig_ptr(b), 4)
20
21    1/0
22
23xd = 100
24yd = 1000000
25
26np.random.seed(1234)
27
28faiss.omp_set_num_threads(1)
29
30print('xd=%d yd=%d' % (xd, yd))
31
32print('Running inner products test..')
33for d in 3, 4, 12, 36, 64:
34
35    x = faiss.rand(xd * d).reshape(xd, d)
36    y = faiss.rand(yd * d).reshape(yd, d)
37
38    distances = np.empty((xd, yd), dtype='float32')
39
40    t0 = time.time()
41    for i in range(xd):
42        faiss.fvec_inner_products_ny(swig_ptr(distances[i]),
43                                     swig_ptr(x[i]),
44                                     swig_ptr(y),
45                                     d, yd)
46    t1 = time.time()
47
48    # sparse verification
49    ntry = 100
50    num, denom = 0, 0
51    for t in range(ntry):
52        xi = np.random.randint(xd)
53        yi = np.random.randint(yd)
54        num += abs(distances[xi, yi] - np.dot(x[xi], y[yi]))
55        denom += abs(distances[xi, yi])
56
57    print('d=%d t=%.3f s diff=%g' % (d, t1 - t0, num / denom))
58
59
60print('Running L2sqr test..')
61for d in 3, 4, 12, 36, 64:
62
63    x = faiss.rand(xd * d).reshape(xd, d)
64    y = faiss.rand(yd * d).reshape(yd, d)
65
66    distances = np.empty((xd, yd), dtype='float32')
67
68    t0 = time.time()
69    for i in range(xd):
70        faiss.fvec_L2sqr_ny(swig_ptr(distances[i]),
71                            swig_ptr(x[i]),
72                            swig_ptr(y),
73                            d, yd)
74    t1 = time.time()
75
76    # sparse verification
77    ntry = 100
78    num, denom = 0, 0
79    for t in range(ntry):
80        xi = np.random.randint(xd)
81        yi = np.random.randint(yd)
82        num += abs(distances[xi, yi] - np.sum((x[xi] - y[yi]) ** 2))
83        denom += abs(distances[xi, yi])
84
85    print('d=%d t=%.3f s diff=%g' % (d, t1 - t0, num / denom))
86