Debian Codegraph @

openTSNE/dependencies/annoy/annoymodule.cc

raw
1 // Copyright (c) 2013 Spotify AB
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14
15 #include "annoylib.h"
16 #include "kissrandom.h"
17 #include "Python.h"
18 #include "structmember.h"
19 #include <exception>
20 #if defined(_MSC_VER) && _MSC_VER == 1500
21 typedef signed __int32 int32_t;
22 #else
23 #include <stdint.h>
24 #endif
25
26
27 #if defined(USE_AVX512)
28 #define AVX_INFO "Using 512-bit AVX instructions"
29 #elif defined(USE_AVX128)
30 #define AVX_INFO "Using 128-bit AVX instructions"
31 #else
32 #define AVX_INFO "Not using AVX instructions"
33 #endif
34
35 #if defined(_MSC_VER)
36 #define COMPILER_INFO "Compiled using MSC"
37 #elif defined(__GNUC__)
38 #define COMPILER_INFO "Compiled on GCC"
39 #else
40 #define COMPILER_INFO "Compiled on unknown platform"
41 #endif
42
43 #define ANNOY_DOC (COMPILER_INFO ". " AVX_INFO ".")
44
45 #if PY_MAJOR_VERSION >= 3
46 #define IS_PY3K
47 #endif
48
49 #ifndef Py_TYPE
50 #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
51 #endif
52
53 #ifdef IS_PY3K
54 #define PyInt_FromLong PyLong_FromLong
55 #endif
56
57 #ifdef ANNOYLIB_MULTITHREADED_BUILD
58 typedef AnnoyIndexMultiThreadedBuildPolicy AnnoyIndexThreadedBuildPolicy;
59 #else
60 typedef AnnoyIndexSingleThreadedBuildPolicy AnnoyIndexThreadedBuildPolicy;
61 #endif
62
63 template class AnnoyIndexInterface<int32_t, float>;
64
65 class HammingWrapper : public AnnoyIndexInterface<int32_t, float> {
66 // Wrapper class for Hamming distance, using composition.
67 // This translates binary (float) vectors into packed uint64_t vectors.
68 // This is questionable from a performance point of view. Should reconsider this solution.
69 private:
70 int32_t _f_external, _f_internal;
71 AnnoyIndex<int32_t, uint64_t, Hamming, Kiss64Random, AnnoyIndexThreadedBuildPolicy> _index;
72 void _pack(const float* src, uint64_t* dst) const {
73 for (int32_t i = 0; i < _f_internal; i++) {
74 dst[i] = 0;
75 for (int32_t j = 0; j < 64 && i*64+j < _f_external; j++) {
76 dst[i] |= (uint64_t)(src[i * 64 + j] > 0.5) << j;
77 }
78 }
79 };
80 void _unpack(const uint64_t* src, float* dst) const {
81 for (int32_t i = 0; i < _f_external; i++) {
82 dst[i] = (src[i / 64] >> (i % 64)) & 1;
83 }
84 };
85 public:
86 HammingWrapper(int f) : _f_external(f), _f_internal((f + 63) / 64), _index((f + 63) / 64) {};
87 bool add_item(int32_t item, const float* w, char**error) {
88 vector<uint64_t> w_internal(_f_internal, 0);
89 _pack(w, &w_internal[0]);
90 return _index.add_item(item, &w_internal[0], error);
91 };
92 bool build(int q, int n_threads, char** error) { return _index.build(q, n_threads, error); };
93 bool unbuild(char** error) { return _index.unbuild(error); };
94 bool save(const char* filename, bool prefault, char** error) { return _index.save(filename, prefault, error); };
95 void unload() { _index.unload(); };
96 bool load(const char* filename, bool prefault, char** error) { return _index.load(filename, prefault, error); };
97 float get_distance(int32_t i, int32_t j) const { return _index.get_distance(i, j); };
98 void get_nns_by_item(int32_t item, size_t n, int search_k, vector<int32_t>* result, vector<float>* distances) const {
99 if (distances) {
100 vector<uint64_t> distances_internal;
101 _index.get_nns_by_item(item, n, search_k, result, &distances_internal);
102 distances->insert(distances->begin(), distances_internal.begin(), distances_internal.end());
103 } else {
104 _index.get_nns_by_item(item, n, search_k, result, NULL);
105 }
106 };
107 void get_nns_by_vector(const float* w, size_t n, int search_k, vector<int32_t>* result, vector<float>* distances) const {
108 vector<uint64_t> w_internal(_f_internal, 0);
109 _pack(w, &w_internal[0]);
110 if (distances) {
111 vector<uint64_t> distances_internal;
112 _index.get_nns_by_vector(&w_internal[0], n, search_k, result, &distances_internal);
113 distances->insert(distances->begin(), distances_internal.begin(), distances_internal.end());
114 } else {
115 _index.get_nns_by_vector(&w_internal[0], n, search_k, result, NULL);
116 }
117 };
118 int32_t get_n_items() const { return _index.get_n_items(); };
119 int32_t get_n_trees() const { return _index.get_n_trees(); };
120 void verbose(bool v) { _index.verbose(v); };
121 void get_item(int32_t item, float* v) const {
122 vector<uint64_t> v_internal(_f_internal, 0);
123 _index.get_item(item, &v_internal[0]);
124 _unpack(&v_internal[0], v);
125 };
126 void set_seed(int q) { _index.set_seed(q); };
127 bool on_disk_build(const char* filename, char** error) { return _index.on_disk_build(filename, error); };
128 };
129
130 // annoy python object
131 typedef struct {
132 PyObject_HEAD
133 int f;
134 AnnoyIndexInterface<int32_t, float>* ptr;
135 } py_annoy;
136
137
138 static PyObject *
139 py_an_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) {
140 py_annoy *self = (py_annoy *)type->tp_alloc(type, 0);
141 if (self == NULL) {
142 return NULL;
143 }
144 const char *metric = NULL;
145
146 static char const * kwlist[] = {"f", "metric", NULL};
147 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|s", (char**)kwlist, &self->f, &metric))
148 return NULL;
149 if (!metric) {
150 // This keeps coming up, see #368 etc
151 PyErr_WarnEx(PyExc_FutureWarning, "The default argument for metric will be removed "
152 "in future version of Annoy. Please pass metric='angular' explicitly.", 1);
153 self->ptr = new AnnoyIndex<int32_t, float, Angular, Kiss64Random, AnnoyIndexThreadedBuildPolicy>(self->f);
154 } else if (!strcmp(metric, "angular")) {
155 self->ptr = new AnnoyIndex<int32_t, float, Angular, Kiss64Random, AnnoyIndexThreadedBuildPolicy>(self->f);
156 } else if (!strcmp(metric, "euclidean")) {
157 self->ptr = new AnnoyIndex<int32_t, float, Euclidean, Kiss64Random, AnnoyIndexThreadedBuildPolicy>(self->f);
158 } else if (!strcmp(metric, "manhattan")) {
159 self->ptr = new AnnoyIndex<int32_t, float, Manhattan, Kiss64Random, AnnoyIndexThreadedBuildPolicy>(self->f);
160 } else if (!strcmp(metric, "hamming")) {
161 self->ptr = new HammingWrapper(self->f);
162 } else if (!strcmp(metric, "dot")) {
163 self->ptr = new AnnoyIndex<int32_t, float, DotProduct, Kiss64Random, AnnoyIndexThreadedBuildPolicy>(self->f);
164 } else {
165 PyErr_SetString(PyExc_ValueError, "No such metric");
166 return NULL;
167 }
168
169 return (PyObject *)self;
170 }
171
172
173 static int
174 py_an_init(py_annoy *self, PyObject *args, PyObject *kwargs) {
175 // Seems to be needed for Python 3
176 const char *metric = NULL;
177 int f;
178 static char const * kwlist[] = {"f", "metric", NULL};
179 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|s", (char**)kwlist, &f, &metric))
180 return (int) NULL;
181 return 0;
182 }
183
184
185 static void
186 py_an_dealloc(py_annoy* self) {
187 delete self->ptr;
188 Py_TYPE(self)->tp_free((PyObject*)self);
189 }
190
191
192 static PyMemberDef py_annoy_members[] = {
193 {(char*)"f", T_INT, offsetof(py_annoy, f), 0,
194 (char*)""},
195 {NULL} /* Sentinel */
196 };
197
198
199 static PyObject *
200 py_an_load(py_annoy *self, PyObject *args, PyObject *kwargs) {
201 char *filename, *error;
202 bool prefault = false;
203 if (!self->ptr)
204 return NULL;
205 static char const * kwlist[] = {"fn", "prefault", NULL};
206 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|b", (char**)kwlist, &filename, &prefault))
207 return NULL;
208
209 if (!self->ptr->load(filename, prefault, &error)) {
210 PyErr_SetString(PyExc_IOError, error);
211 free(error);
212 return NULL;
213 }
214 Py_RETURN_TRUE;
215 }
216
217
218 static PyObject *
219 py_an_save(py_annoy *self, PyObject *args, PyObject *kwargs) {
220 char *filename, *error;
221 bool prefault = false;
222 if (!self->ptr)
223 return NULL;
224 static char const * kwlist[] = {"fn", "prefault", NULL};
225 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|b", (char**)kwlist, &filename, &prefault))
226 return NULL;
227
228 if (!self->ptr->save(filename, prefault, &error)) {
229 PyErr_SetString(PyExc_IOError, error);
230 free(error);
231 return NULL;
232 }
233 Py_RETURN_TRUE;
234 }
235
236
237 PyObject*
238 get_nns_to_python(const vector<int32_t>& result, const vector<float>& distances, int include_distances) {
239 PyObject* l = PyList_New(result.size());
240 for (size_t i = 0; i < result.size(); i++)
241 PyList_SetItem(l, i, PyInt_FromLong(result[i]));
242 if (!include_distances)
243 return l;
244
245 PyObject* d = PyList_New(distances.size());
246 for (size_t i = 0; i < distances.size(); i++)
247 PyList_SetItem(d, i, PyFloat_FromDouble(distances[i]));
248
249 PyObject* t = PyTuple_New(2);
250 PyTuple_SetItem(t, 0, l);
251 PyTuple_SetItem(t, 1, d);
252
253 return t;
254 }
255
256
257 bool check_constraints(py_annoy *self, int32_t item, bool building) {
258 if (item < 0) {
259 PyErr_SetString(PyExc_IndexError, "Item index can not be negative");
260 return false;
261 } else if (!building && item >= self->ptr->get_n_items()) {
262 PyErr_SetString(PyExc_IndexError, "Item index larger than the largest item index");
263 return false;
264 } else {
265 return true;
266 }
267 }
268
269 static PyObject*
270 py_an_get_nns_by_item(py_annoy *self, PyObject *args, PyObject *kwargs) {
271 int32_t item, n, search_k=-1, include_distances=0;
272 if (!self->ptr)
273 return NULL;
274
275 static char const * kwlist[] = {"i", "n", "search_k", "include_distances", NULL};
276 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "ii|ii", (char**)kwlist, &item, &n, &search_k, &include_distances))
277 return NULL;
278
279 if (!check_constraints(self, item, false)) {
280 return NULL;
281 }
282
283 vector<int32_t> result;
284 vector<float> distances;
285
286 Py_BEGIN_ALLOW_THREADS;
287 self->ptr->get_nns_by_item(item, n, search_k, &result, include_distances ? &distances : NULL);
288 Py_END_ALLOW_THREADS;
289
290 return get_nns_to_python(result, distances, include_distances);
291 }
292
293
294 bool
295 convert_list_to_vector(PyObject* v, int f, vector<float>* w) {
296 if (PyObject_Size(v) == -1) {
297 char buf[256];
298 snprintf(buf, 256, "Expected an iterable, got an object of type \"%s\"", v->ob_type->tp_name);
299 PyErr_SetString(PyExc_ValueError, buf);
300 return false;
301 }
302 if (PyObject_Size(v) != f) {
303 char buf[128];
304 snprintf(buf, 128, "Vector has wrong length (expected %d, got %ld)", f, PyObject_Size(v));
305 PyErr_SetString(PyExc_IndexError, buf);
306 return false;
307 }
308 for (int z = 0; z < f; z++) {
309 PyObject *key = PyInt_FromLong(z);
310 PyObject *pf = PyObject_GetItem(v, key);
311 (*w)[z] = PyFloat_AsDouble(pf);
312 Py_DECREF(key);
313 Py_DECREF(pf);
314 }
315 return true;
316 }
317
318 static PyObject*
319 py_an_get_nns_by_vector(py_annoy *self, PyObject *args, PyObject *kwargs) {
320 PyObject* v;
321 int32_t n, search_k=-1, include_distances=0;
322 if (!self->ptr)
323 return NULL;
324
325 static char const * kwlist[] = {"vector", "n", "search_k", "include_distances", NULL};
326 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Oi|ii", (char**)kwlist, &v, &n, &search_k, &include_distances))
327 return NULL;
328
329 vector<float> w(self->f);
330 if (!convert_list_to_vector(v, self->f, &w)) {
331 return NULL;
332 }
333
334 vector<int32_t> result;
335 vector<float> distances;
336
337 Py_BEGIN_ALLOW_THREADS;
338 self->ptr->get_nns_by_vector(&w[0], n, search_k, &result, include_distances ? &distances : NULL);
339 Py_END_ALLOW_THREADS;
340
341 return get_nns_to_python(result, distances, include_distances);
342 }
343
344
345 static PyObject*
346 py_an_get_item_vector(py_annoy *self, PyObject *args) {
347 int32_t item;
348 if (!self->ptr)
349 return NULL;
350 if (!PyArg_ParseTuple(args, "i", &item))
351 return NULL;
352
353 if (!check_constraints(self, item, false)) {
354 return NULL;
355 }
356
357 vector<float> v(self->f);
358 self->ptr->get_item(item, &v[0]);
359 PyObject* l = PyList_New(self->f);
360 for (int z = 0; z < self->f; z++) {
361 PyList_SetItem(l, z, PyFloat_FromDouble(v[z]));
362 }
363
364 return l;
365 }
366
367
368 static PyObject*
369 py_an_add_item(py_annoy *self, PyObject *args, PyObject* kwargs) {
370 PyObject* v;
371 int32_t item;
372 if (!self->ptr)
373 return NULL;
374 static char const * kwlist[] = {"i", "vector", NULL};
375 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "iO", (char**)kwlist, &item, &v))
376 return NULL;
377
378 if (!check_constraints(self, item, true)) {
379 return NULL;
380 }
381
382 vector<float> w(self->f);
383 if (!convert_list_to_vector(v, self->f, &w)) {
384 return NULL;
385 }
386 char* error;
387 if (!self->ptr->add_item(item, &w[0], &error)) {
388 PyErr_SetString(PyExc_Exception, error);
389 free(error);
390 return NULL;
391 }
392
393 Py_RETURN_NONE;
394 }
395
396 static PyObject *
397 py_an_on_disk_build(py_annoy *self, PyObject *args, PyObject *kwargs) {
398 char *filename, *error;
399 if (!self->ptr)
400 return NULL;
401 static char const * kwlist[] = {"fn", NULL};
402 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s", (char**)kwlist, &filename))
403 return NULL;
404
405 if (!self->ptr->on_disk_build(filename, &error)) {
406 PyErr_SetString(PyExc_IOError, error);
407 free(error);
408 return NULL;
409 }
410 Py_RETURN_TRUE;
411 }
412
413 static PyObject *
414 py_an_build(py_annoy *self, PyObject *args, PyObject *kwargs) {
415 int q;
416 int n_jobs = -1;
417 if (!self->ptr)
418 return NULL;
419 static char const * kwlist[] = {"n_trees", "n_jobs", NULL};
420 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|i", (char**)kwlist, &q, &n_jobs))
421 return NULL;
422
423 bool res;
424 char* error;
425 Py_BEGIN_ALLOW_THREADS;
426 res = self->ptr->build(q, n_jobs, &error);
427 Py_END_ALLOW_THREADS;
428 if (!res) {
429 PyErr_SetString(PyExc_Exception, error);
430 free(error);
431 return NULL;
432 }
433
434 Py_RETURN_TRUE;
435 }
436
437
438 static PyObject *
439 py_an_unbuild(py_annoy *self) {
440 if (!self->ptr)
441 return NULL;
442
443 char* error;
444 if (!self->ptr->unbuild(&error)) {
445 PyErr_SetString(PyExc_Exception, error);
446 free(error);
447 return NULL;
448 }
449
450 Py_RETURN_TRUE;
451 }
452
453
454 static PyObject *
455 py_an_unload(py_annoy *self) {
456 if (!self->ptr)
457 return NULL;
458
459 self->ptr->unload();
460
461 Py_RETURN_TRUE;
462 }
463
464
465 static PyObject *
466 py_an_get_distance(py_annoy *self, PyObject *args) {
467 int32_t i, j;
468 if (!self->ptr)
469 return NULL;
470 if (!PyArg_ParseTuple(args, "ii", &i, &j))
471 return NULL;
472
473 if (!check_constraints(self, i, false) || !check_constraints(self, j, false)) {
474 return NULL;
475 }
476
477 double d = self->ptr->get_distance(i,j);
478 return PyFloat_FromDouble(d);
479 }
480
481
482 static PyObject *
483 py_an_get_n_items(py_annoy *self) {
484 if (!self->ptr)
485 return NULL;
486
487 int32_t n = self->ptr->get_n_items();
488 return PyInt_FromLong(n);
489 }
490
491 static PyObject *
492 py_an_get_n_trees(py_annoy *self) {
493 if (!self->ptr)
494 return NULL;
495
496 int32_t n = self->ptr->get_n_trees();
497 return PyInt_FromLong(n);
498 }
499
500 static PyObject *
501 py_an_verbose(py_annoy *self, PyObject *args) {
502 int verbose;
503 if (!self->ptr)
504 return NULL;
505 if (!PyArg_ParseTuple(args, "i", &verbose))
506 return NULL;
507
508 self->ptr->verbose((bool)verbose);
509
510 Py_RETURN_TRUE;
511 }
512
513
514 static PyObject *
515 py_an_set_seed(py_annoy *self, PyObject *args) {
516 int q;
517 if (!self->ptr)
518 return NULL;
519 if (!PyArg_ParseTuple(args, "i", &q))
520 return NULL;
521
522 self->ptr->set_seed(q);
523
524 Py_RETURN_NONE;
525 }
526
527
528 static PyMethodDef AnnoyMethods[] = {
529 {"load", (PyCFunction)py_an_load, METH_VARARGS | METH_KEYWORDS, "Loads (mmaps) an index from disk."},
530 {"save", (PyCFunction)py_an_save, METH_VARARGS | METH_KEYWORDS, "Saves the index to disk."},
531 {"get_nns_by_item",(PyCFunction)py_an_get_nns_by_item, METH_VARARGS | METH_KEYWORDS, "Returns the `n` closest items to item `i`.\n\n:param search_k: the query will inspect up to `search_k` nodes.\n`search_k` gives you a run-time tradeoff between better accuracy and speed.\n`search_k` defaults to `n_trees * n` if not provided.\n\n:param include_distances: If `True`, this function will return a\n2 element tuple of lists. The first list contains the `n` closest items.\nThe second list contains the corresponding distances."},
532 {"get_nns_by_vector",(PyCFunction)py_an_get_nns_by_vector, METH_VARARGS | METH_KEYWORDS, "Returns the `n` closest items to vector `vector`.\n\n:param search_k: the query will inspect up to `search_k` nodes.\n`search_k` gives you a run-time tradeoff between better accuracy and speed.\n`search_k` defaults to `n_trees * n` if not provided.\n\n:param include_distances: If `True`, this function will return a\n2 element tuple of lists. The first list contains the `n` closest items.\nThe second list contains the corresponding distances."},
533 {"get_item_vector",(PyCFunction)py_an_get_item_vector, METH_VARARGS, "Returns the vector for item `i` that was previously added."},
534 {"add_item",(PyCFunction)py_an_add_item, METH_VARARGS | METH_KEYWORDS, "Adds item `i` (any nonnegative integer) with vector `v`.\n\nNote that it will allocate memory for `max(i)+1` items."},
535 {"on_disk_build",(PyCFunction)py_an_on_disk_build, METH_VARARGS | METH_KEYWORDS, "Build will be performed with storage on disk instead of RAM."},
536 {"build",(PyCFunction)py_an_build, METH_VARARGS | METH_KEYWORDS, "Builds a forest of `n_trees` trees.\n\nMore trees give higher precision when querying. After calling `build`,\nno more items can be added. `n_jobs` specifies the number of threads used to build the trees. `n_jobs=-1` uses all available CPU cores."},
537 {"unbuild",(PyCFunction)py_an_unbuild, METH_NOARGS, "Unbuilds the tree in order to allows adding new items.\n\nbuild() has to be called again afterwards in order to\nrun queries."},
538 {"unload",(PyCFunction)py_an_unload, METH_NOARGS, "Unloads an index from disk."},
539 {"get_distance",(PyCFunction)py_an_get_distance, METH_VARARGS, "Returns the distance between items `i` and `j`."},
540 {"get_n_items",(PyCFunction)py_an_get_n_items, METH_NOARGS, "Returns the number of items in the index."},
541 {"get_n_trees",(PyCFunction)py_an_get_n_trees, METH_NOARGS, "Returns the number of trees in the index."},
542 {"verbose",(PyCFunction)py_an_verbose, METH_VARARGS, ""},
543 {"set_seed",(PyCFunction)py_an_set_seed, METH_VARARGS, "Sets the seed of Annoy's random number generator."},
544 {NULL, NULL, 0, NULL} /* Sentinel */
545 };
546
547
548 static PyTypeObject PyAnnoyType = {
549 PyVarObject_HEAD_INIT(NULL, 0)
550 "annoy.Annoy", /*tp_name*/
551 sizeof(py_annoy), /*tp_basicsize*/
552 0, /*tp_itemsize*/
553 (destructor)py_an_dealloc, /*tp_dealloc*/
554 0, /*tp_print*/
555 0, /*tp_getattr*/
556 0, /*tp_setattr*/
557 0, /*tp_compare*/
558 0, /*tp_repr*/
559 0, /*tp_as_number*/
560 0, /*tp_as_sequence*/
561 0, /*tp_as_mapping*/
562 0, /*tp_hash */
563 0, /*tp_call*/
564 0, /*tp_str*/
565 0, /*tp_getattro*/
566 0, /*tp_setattro*/
567 0, /*tp_as_buffer*/
568 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
569 ANNOY_DOC, /* tp_doc */
570 0, /* tp_traverse */
571 0, /* tp_clear */
572 0, /* tp_richcompare */
573 0, /* tp_weaklistoffset */
574 0, /* tp_iter */
575 0, /* tp_iternext */
576 AnnoyMethods, /* tp_methods */
577 py_annoy_members, /* tp_members */
578 0, /* tp_getset */
579 0, /* tp_base */
580 0, /* tp_dict */
581 0, /* tp_descr_get */
582 0, /* tp_descr_set */
583 0, /* tp_dictoffset */
584 (initproc)py_an_init, /* tp_init */
585 0, /* tp_alloc */
586 py_an_new, /* tp_new */
587 };
588
589 static PyMethodDef module_methods[] = {
590 {NULL} /* Sentinel */
591 };
592
593 #if PY_MAJOR_VERSION >= 3
594 static struct PyModuleDef moduledef = {
595 PyModuleDef_HEAD_INIT,
596 "annoylib", /* m_name */
597 ANNOY_DOC, /* m_doc */
598 -1, /* m_size */
599 module_methods, /* m_methods */
600 NULL, /* m_reload */
601 NULL, /* m_traverse */
602 NULL, /* m_clear */
603 NULL, /* m_free */
604 };
605 #endif
606
607 PyObject *create_module(void) {
608 PyObject *m;
609
610 if (PyType_Ready(&PyAnnoyType) < 0)
611 return NULL;
612
613 #if PY_MAJOR_VERSION >= 3
614 m = PyModule_Create(&moduledef);
615 #else
616 m = Py_InitModule("annoylib", module_methods);
617 #endif
618
619 if (m == NULL)
620 return NULL;
621
622 Py_INCREF(&PyAnnoyType);
623 PyModule_AddObject(m, "Annoy", (PyObject *)&PyAnnoyType);
624 return m;
625 }
626
627 #if PY_MAJOR_VERSION >= 3
628 PyMODINIT_FUNC PyInit_annoylib(void) {
629 return create_module(); // it should return moudule object in py3
630 }
631 #else
632 PyMODINIT_FUNC initannoylib(void) {
633 create_module();
634 }
635 #endif
636
637
638 // vim: tabstop=2 shiftwidth=2