pyvsag 1.2.0.dev241__py3-none-macosx_15_0_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pyvsag/__init__.py ADDED
@@ -0,0 +1,43 @@
1
+
2
+ # Copyright 2024-present the vsag project
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from ._index import Index, _check
17
+ from ._lib import lib as _lib
18
+ from ._version import __version__
19
+
20
+ _LOG_LEVELS = {"off": _lib.VSAG_LOG_OFF, "info": _lib.VSAG_LOG_INFO, "debug": _lib.VSAG_LOG_DEBUG}
21
+
22
+
23
+ def _set_log_level(name):
24
+ _check(_lib.vsag_set_log_level(_LOG_LEVELS[name]), "set log level failed")
25
+
26
+
27
+ def set_logger_off():
28
+ """Disable all logging output from the VSAG library."""
29
+ _set_log_level("off")
30
+
31
+
32
+ def set_logger_info():
33
+ """Set logger level to INFO. Only important information will be logged."""
34
+ _set_log_level("info")
35
+
36
+
37
+ def set_logger_debug():
38
+ """Set logger level to DEBUG. Detailed debug information will be logged."""
39
+ _set_log_level("debug")
40
+
41
+
42
+ __all__ = ["Index", "set_logger_off", "set_logger_info", "set_logger_debug", "__version__"]
43
+
pyvsag/_index.py ADDED
@@ -0,0 +1,518 @@
1
+ # Copyright 2024-present the vsag project
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of 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,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import json
16
+ import os
17
+
18
+ import numpy as np
19
+
20
+ from ._lib import ffi, lib
21
+
22
+ _DENSE_DTYPES = {
23
+ # index dtype -> (numpy dtype name, description)
24
+ "float32": ("float32", "numpy.float32"),
25
+ "float16": ("float16", "numpy.float16"),
26
+ "bfloat16": ("uint16", "numpy.uint16 (raw bfloat16 bits)"),
27
+ }
28
+
29
+ _FLOAT32 = np.dtype(np.float32)
30
+ _MAX_ENCODED_PARAMETERS = 64
31
+
32
+ _CREATE_ERRORS = {
33
+ lib.VSAG_UNSUPPORTED_INDEX: "error type: UNSUPPORTED_INDEX",
34
+ lib.VSAG_INVALID_ARGUMENT: "error type: invalid_parameter",
35
+ }
36
+
37
+
38
+ def _take_error(err):
39
+ """Return (code, message) of a vsag_error_t* and release it; (0, "") for NULL."""
40
+ if err == ffi.NULL:
41
+ return lib.VSAG_SUCCESS, ""
42
+ code = lib.vsag_error_code(err)
43
+ message = ffi.string(lib.vsag_error_message(err)).decode("utf-8", "replace")
44
+ lib.vsag_error_destroy(err)
45
+ return code, message
46
+
47
+
48
+ def _check(err, prefix):
49
+ code, message = _take_error(err)
50
+ if code != lib.VSAG_SUCCESS:
51
+ raise RuntimeError("%s: %s" % (prefix, message))
52
+
53
+
54
+ def _ok(err):
55
+ return _take_error(err)[0] == lib.VSAG_SUCCESS
56
+
57
+
58
+ def _int_array(values, dtype, name):
59
+ """Convert to a contiguous integer array, rejecting input that would be altered."""
60
+ array = np.asarray(values)
61
+ if array.size == 0:
62
+ return np.empty(array.shape, dtype=dtype)
63
+ if array.dtype.kind not in "iu":
64
+ raise ValueError("%s must be an integer array" % name)
65
+ info = np.iinfo(dtype)
66
+ if int(array.min()) < info.min or int(array.max()) > info.max:
67
+ raise ValueError("%s has values outside the %s range" % (name, np.dtype(dtype).name))
68
+ return np.ascontiguousarray(array, dtype=dtype)
69
+
70
+
71
+ def _parse_dtype(parameters):
72
+ try:
73
+ dtype = json.loads(parameters).get("dtype", "float32")
74
+ except (ValueError, AttributeError):
75
+ return "float32"
76
+ return dtype if isinstance(dtype, str) else "float32"
77
+
78
+
79
+ def _ptr(array, ctype="void*"):
80
+ return ffi.cast(ctype, array.ctypes.data)
81
+
82
+
83
+ def _is_contiguous_1d(array):
84
+ # numpy's own flag, so the validating path and the single-query fast path agree on one-element
85
+ # views, whose stride is irrelevant.
86
+ return array.flags.c_contiguous
87
+
88
+
89
+ def _int64_ids(ids, expected_size=None):
90
+ array = _int_array(ids, np.int64, "ids")
91
+ if array.ndim != 1:
92
+ raise ValueError("ids must be 1-dimensional")
93
+ if expected_size is not None and array.shape[0] != expected_size:
94
+ raise ValueError(
95
+ "ids length (%d) must equal num_elements (%d)" % (array.shape[0], expected_size)
96
+ )
97
+ return array
98
+
99
+
100
+ def _csr(index_pointers, indices, values):
101
+ ptrs = _int_array(index_pointers, np.uint32, "index_pointers")
102
+ idx = _int_array(indices, np.uint32, "indices")
103
+ vals = np.ascontiguousarray(values, dtype=np.float32)
104
+ if ptrs.ndim != 1 or idx.ndim != 1 or vals.ndim != 1:
105
+ raise ValueError("all inputs must be 1-dimensional")
106
+ if ptrs.shape[0] < 2:
107
+ raise ValueError("index_pointers length must be at least 2")
108
+ nnz = int(ptrs[-1])
109
+ if idx.shape[0] != nnz:
110
+ raise ValueError(
111
+ "Size of 'indices'(%d) must equal index_pointers[last](%d)" % (idx.shape[0], nnz)
112
+ )
113
+ if vals.shape[0] != nnz:
114
+ raise ValueError(
115
+ "Size of 'values'(%d) must equal index_pointers[last](%d)" % (vals.shape[0], nnz)
116
+ )
117
+ if ptrs[0] != 0:
118
+ raise ValueError("index_pointers[0] must be 0")
119
+ bad = np.nonzero(ptrs[1:] < ptrs[:-1])[0]
120
+ if bad.size:
121
+ i = int(bad[0]) + 1
122
+ raise ValueError(
123
+ "index_pointers[%d](%d) > index_pointers[%d](%d)" % (i - 1, ptrs[i - 1], i, ptrs[i])
124
+ )
125
+ return ptrs, idx, vals
126
+
127
+
128
+ class _Dataset:
129
+ """A vsag_dataset_t that borrows numpy buffers; it keeps them alive with the handle."""
130
+
131
+ def __init__(self, num_elements, dim=None, ids=None):
132
+ out = ffi.new("vsag_dataset_t**")
133
+ _check(lib.vsag_dataset_create(out), "dataset failed")
134
+ self.handle = ffi.gc(out[0], lib.vsag_dataset_destroy)
135
+ self._keep = []
136
+ _check(lib.vsag_dataset_set_num_elements(self.handle, num_elements), "dataset failed")
137
+ if dim is not None:
138
+ _check(lib.vsag_dataset_set_dim(self.handle, dim), "dataset failed")
139
+ if ids is not None:
140
+ self._keep.append(ids)
141
+ _check(lib.vsag_dataset_set_ids(self.handle, _ptr(ids, "int64_t*")), "dataset failed")
142
+
143
+ def dense(self, array):
144
+ self._keep.append(array)
145
+ if array.dtype == np.float32:
146
+ err = lib.vsag_dataset_set_float32_vectors(self.handle, _ptr(array, "float*"))
147
+ else:
148
+ err = lib.vsag_dataset_set_float16_vectors(self.handle, _ptr(array, "uint16_t*"))
149
+ _check(err, "dataset failed")
150
+ return self
151
+
152
+ def sparse(self, ptrs, idx, vals):
153
+ self._keep.extend((ptrs, idx, vals))
154
+ err = lib.vsag_dataset_set_sparse_vectors(
155
+ self.handle, _ptr(ptrs, "uint32_t*"), _ptr(idx, "uint32_t*"), _ptr(vals, "float*")
156
+ )
157
+ _check(err, "dataset failed")
158
+ return self
159
+
160
+
161
+ def _take_result(out):
162
+ return ffi.gc(out[0], lib.vsag_search_result_destroy)
163
+
164
+
165
+ def _result_arrays(result):
166
+ count = int(lib.vsag_search_result_count(result))
167
+ if count == 0:
168
+ return np.empty(0, dtype=np.int64), np.empty(0, dtype=np.float32)
169
+ ids = np.frombuffer(
170
+ ffi.buffer(lib.vsag_search_result_ids(result), count * 8), dtype=np.int64
171
+ ).copy()
172
+ dists = np.frombuffer(
173
+ ffi.buffer(lib.vsag_search_result_distances(result), count * 4), dtype=np.float32
174
+ ).copy()
175
+ return ids, dists
176
+
177
+
178
+ def _statistics(result):
179
+ return ffi.string(lib.vsag_search_result_statistics(result)).decode("utf-8")
180
+
181
+
182
+ class Index:
183
+ """Vector search index for efficient similarity search.
184
+
185
+ Supported dense input types:
186
+ - float32 indexes accept numpy.float32 vectors
187
+ - float16 indexes accept numpy.float16 vectors
188
+ - bfloat16 indexes accept numpy.uint16 arrays containing raw bfloat16 bits
189
+
190
+ The methods are thread-safe in the same way as the underlying C++ index; the GIL is
191
+ released while the C++ library runs.
192
+ """
193
+
194
+ def __init__(self, name, parameters):
195
+ out = ffi.new("vsag_index_t**")
196
+ code, _ = _take_error(lib.vsag_index_create(name.encode(), parameters.encode(), out))
197
+ if code != lib.VSAG_SUCCESS:
198
+ raise RuntimeError(_CREATE_ERRORS.get(code, "error type: unexpectedError"))
199
+ self._handle = ffi.gc(out[0], lib.vsag_index_destroy)
200
+ self._name = name
201
+ self._parameters = parameters
202
+ self._dtype = _parse_dtype(parameters)
203
+ self._encoded_parameters = {}
204
+
205
+ def _dense_kind(self, operation):
206
+ kind = _DENSE_DTYPES.get(self._dtype)
207
+ if kind is None:
208
+ raise ValueError(
209
+ "%s only supports indexes with dtype in [float32, float16, bfloat16]" % operation
210
+ )
211
+ return kind
212
+
213
+ def _dense_array(self, array, operation, arg_name, expected_size=0, expected_dim=0):
214
+ np_name, description = self._dense_kind(operation)
215
+ array = np.asarray(array)
216
+ # Comparing dtype objects also rejects non-native byte order, which dtype.name hides.
217
+ if array.dtype != np.dtype(np_name):
218
+ raise ValueError("%s must be %s array" % (arg_name, description))
219
+ if expected_size == 0:
220
+ if array.ndim != 1:
221
+ raise ValueError("%s must be 1-dimensional" % arg_name)
222
+ if not _is_contiguous_1d(array):
223
+ raise ValueError("%s must be contiguous" % arg_name)
224
+ return array
225
+ if array.ndim == 1:
226
+ if not _is_contiguous_1d(array):
227
+ raise ValueError("%s must be contiguous" % arg_name)
228
+ size = array.shape[0]
229
+ elif array.ndim == 2:
230
+ if array.strides[1] != array.itemsize or (
231
+ array.strides[0] != array.itemsize * array.shape[1]
232
+ ):
233
+ raise ValueError("%s must be contiguous in row-major order" % arg_name)
234
+ if expected_dim != 0 and array.shape[1] != expected_dim:
235
+ raise ValueError(
236
+ "%s second dimension (%d) must equal dim (%d)"
237
+ % (arg_name, array.shape[1], expected_dim)
238
+ )
239
+ size = array.shape[0] * array.shape[1]
240
+ else:
241
+ raise ValueError(
242
+ "%s must be a 1-dimensional array or a 2-dimensional contiguous matrix"
243
+ % arg_name
244
+ )
245
+ if size != expected_size:
246
+ raise ValueError("%s size (%d) must equal %d" % (arg_name, size, expected_size))
247
+ return array
248
+
249
+ def _dense_dataset(self, operation, vectors, ids, num_elements, dim):
250
+ num_elements, dim = int(num_elements), int(dim)
251
+ array = self._dense_array(vectors, operation, "vectors", num_elements * dim, dim)
252
+ ids = _int64_ids(ids, num_elements)
253
+ return _Dataset(num_elements, dim, ids).dense(array)
254
+
255
+ @staticmethod
256
+ def _sparse_dataset(index_pointers, indices, values, ids):
257
+ ptrs, idx, vals = _csr(index_pointers, indices, values)
258
+ ids_arr = _int_array(ids, np.int64, "ids")
259
+ if ids_arr.ndim != 1:
260
+ raise ValueError("all inputs must be 1-dimensional")
261
+ count = ptrs.shape[0] - 1
262
+ if ids_arr.shape[0] != count:
263
+ raise ValueError(
264
+ "Length of 'ids'(%d) must match number of vectors(%d)" % (ids_arr.shape[0], count)
265
+ )
266
+ return _Dataset(count, None, ids_arr).sparse(ptrs, idx, vals)
267
+
268
+ @staticmethod
269
+ def _bind(args, kwargs, dense, sparse):
270
+ """Pick the dense or sparse overload from the argument names."""
271
+ if "index_pointers" in kwargs:
272
+ use_sparse = True
273
+ elif len(dense) != len(sparse):
274
+ use_sparse = len(args) + len(kwargs) == len(sparse)
275
+ else:
276
+ use_sparse = len(args) >= 3 and not isinstance(args[2], (int, np.integer))
277
+ use_sparse = use_sparse or ("values" in kwargs)
278
+ names = sparse if use_sparse else dense
279
+ if len(args) > len(names):
280
+ raise TypeError("too many positional arguments")
281
+ bound = dict(zip(names, args))
282
+ bound.update(kwargs)
283
+ missing = [n for n in names if n not in bound]
284
+ extra = [n for n in bound if n not in names]
285
+ if missing or extra:
286
+ raise TypeError("invalid arguments (missing %s, unexpected %s)" % (missing, extra))
287
+ return names is sparse, [bound[n] for n in names]
288
+
289
+ _DENSE_WRITE = ("vectors", "ids", "num_elements", "dim")
290
+ _SPARSE_WRITE = ("index_pointers", "indices", "values", "ids")
291
+
292
+ def build(self, *args, **kwargs):
293
+ """Build the index from dense vectors or from sparse vectors in CSR format.
294
+
295
+ Dense: build(vectors, ids, num_elements, dim)
296
+ Sparse: build(index_pointers, indices, values, ids)
297
+ """
298
+ is_sparse, values = self._bind(args, kwargs, self._DENSE_WRITE, self._SPARSE_WRITE)
299
+ if is_sparse:
300
+ dataset = self._sparse_dataset(*values)
301
+ else:
302
+ dataset = self._dense_dataset("build", *values)
303
+ _check(lib.vsag_index_build(self._handle, dataset.handle), "build failed")
304
+
305
+ def add(self, *args, **kwargs):
306
+ """Add dense vectors or sparse vectors in CSR format; same arguments as build."""
307
+ is_sparse, values = self._bind(args, kwargs, self._DENSE_WRITE, self._SPARSE_WRITE)
308
+ if is_sparse:
309
+ dataset = self._sparse_dataset(*values)
310
+ else:
311
+ dataset = self._dense_dataset("add", *values)
312
+ _check(lib.vsag_index_add(self._handle, dataset.handle, ffi.NULL), "add failed")
313
+
314
+ def remove(self, ids):
315
+ """Remove ids from the index and return the number of removed vectors."""
316
+ ids = _int_array(ids, np.int64, "ids")
317
+ if ids.ndim != 1:
318
+ raise ValueError("ids must be 1-dimensional")
319
+ removed = ffi.new("uint64_t*")
320
+ err = lib.vsag_index_remove(self._handle, _ptr(ids, "int64_t*"), ids.shape[0], removed)
321
+ return int(removed[0]) if _ok(err) else 0
322
+
323
+ _DENSE_KNN = ("vector", "k", "parameters")
324
+ _SPARSE_KNN = ("index_pointers", "indices", "values", "k", "parameters")
325
+
326
+ def _dense_knn(self, vector, k, parameters, operation):
327
+ """Search one vector; return (ids, dists, result, error) with -1 filled on failure."""
328
+ vector = self._dense_array(vector, operation, "vector")
329
+ k = int(k)
330
+ dataset = _Dataset(1, vector.shape[0]).dense(vector)
331
+ out = ffi.new("vsag_search_result_t**")
332
+ err = lib.vsag_index_knn_search(
333
+ self._handle, dataset.handle, k, parameters.encode(), ffi.NULL, out
334
+ )
335
+ ids = np.full(k, -1, dtype=np.int64)
336
+ dists = np.full(k, -1.0, dtype=np.float32)
337
+ if out[0] == ffi.NULL:
338
+ return ids, dists, None, err
339
+ result = _take_result(out)
340
+ found_ids, found_dists = _result_arrays(result)
341
+ count = min(k, found_ids.shape[0])
342
+ ids[:count] = found_ids[:count]
343
+ dists[:count] = found_dists[:count]
344
+ return ids, dists, result, err
345
+
346
+ def _encode(self, parameters):
347
+ """UTF-8 encode a parameters string; callers pass the same few strings repeatedly."""
348
+ encoded = self._encoded_parameters.get(parameters)
349
+ if encoded is None:
350
+ encoded = parameters.encode()
351
+ if len(self._encoded_parameters) < _MAX_ENCODED_PARAMETERS:
352
+ self._encoded_parameters[parameters] = encoded
353
+ return encoded
354
+
355
+ def _flat_knn(self, vector, k, parameters):
356
+ """Single float32 query through the allocation-free C entry point."""
357
+ ids = np.empty(k, dtype=np.int64)
358
+ dists = np.empty(k, dtype=np.float32)
359
+ found = ffi.new("int64_t[1]")
360
+ err = lib.vsag_index_knn_search_float32(
361
+ self._handle,
362
+ ffi.from_buffer("float[]", vector),
363
+ 1,
364
+ vector.shape[0],
365
+ k,
366
+ self._encode(parameters),
367
+ ffi.NULL,
368
+ ffi.from_buffer("int64_t[]", ids, require_writable=True),
369
+ ffi.from_buffer("float[]", dists, require_writable=True),
370
+ found,
371
+ )
372
+ # Slots the search did not fill, or all of them after a failure, read as "no result".
373
+ count = 0 if err != ffi.NULL else int(found[0])
374
+ _take_error(err)
375
+ if count < k:
376
+ ids[count:] = -1
377
+ dists[count:] = -1.0
378
+ return ids, dists
379
+
380
+ def knn_search(self, *args, **kwargs):
381
+ """k-nearest-neighbor search.
382
+
383
+ Dense: knn_search(vector, k, parameters) -> (ids, distances), each of shape (k,)
384
+ Sparse: knn_search(index_pointers, indices, values, k, parameters)
385
+ """
386
+ if len(args) == 3 and not kwargs and self._dtype == "float32":
387
+ # The common call, kept free of argument binding and re-validation.
388
+ vector, k, parameters = args
389
+ if (
390
+ type(vector) is np.ndarray
391
+ and vector.dtype == _FLOAT32
392
+ and vector.ndim == 1
393
+ and vector.flags.c_contiguous
394
+ and type(k) is int
395
+ and k > 0
396
+ and type(parameters) is str
397
+ ):
398
+ return self._flat_knn(vector, k, parameters)
399
+ is_sparse, values = self._bind(args, kwargs, self._DENSE_KNN, self._SPARSE_KNN)
400
+ if is_sparse:
401
+ return self._sparse_knn(*values, statistics=False)
402
+ vector, k, parameters = values
403
+ if self._dtype == "float32" and int(k) > 0:
404
+ array = self._dense_array(vector, "knn_search", "vector")
405
+ return self._flat_knn(array, int(k), parameters)
406
+ ids, dists, _, err = self._dense_knn(vector, k, parameters, "knn_search")
407
+ _take_error(err)
408
+ return ids, dists
409
+
410
+ def knn_search_with_statistics(self, *args, **kwargs):
411
+ """Same as knn_search, but also returns the statistics JSON of the search."""
412
+ is_sparse, values = self._bind(args, kwargs, self._DENSE_KNN, self._SPARSE_KNN)
413
+ if is_sparse:
414
+ return self._sparse_knn(*values, statistics=True)
415
+ ids, dists, result, err = self._dense_knn(*values, "knn_search_with_statistics")
416
+ _check(err, "knn search failed")
417
+ return ids, dists, _statistics(result)
418
+
419
+ def _sparse_knn(self, index_pointers, indices, values, k, parameters, statistics):
420
+ ptrs, idx, vals = _csr(index_pointers, indices, values)
421
+ k = int(k)
422
+ count = ptrs.shape[0] - 1
423
+ ids = np.full((count, k), -1, dtype=np.int64)
424
+ dists = np.full((count, k), -1.0, dtype=np.float32)
425
+ stats = []
426
+ params = parameters.encode()
427
+ for i in range(count):
428
+ start, end = int(ptrs[i]), int(ptrs[i + 1])
429
+ row_ptrs = np.array([0, end - start], dtype=np.uint32)
430
+ dataset = _Dataset(1).sparse(row_ptrs, idx[start:end], vals[start:end])
431
+ out = ffi.new("vsag_search_result_t**")
432
+ err = lib.vsag_index_knn_search(self._handle, dataset.handle, k, params, ffi.NULL, out)
433
+ if out[0] != ffi.NULL:
434
+ result = _take_result(out)
435
+ found_ids, found_dists = _result_arrays(result)
436
+ n = min(k, found_ids.shape[0])
437
+ ids[i, :n] = found_ids[:n]
438
+ dists[i, :n] = found_dists[:n]
439
+ if statistics:
440
+ stats.append(_statistics(result))
441
+ if statistics:
442
+ _check(err, "sparse knn search failed")
443
+ else:
444
+ _take_error(err)
445
+ if statistics:
446
+ return ids, dists, stats
447
+ return ids, dists
448
+
449
+ def _range(self, point, threshold, parameters, operation):
450
+ point = self._dense_array(point, operation, "point")
451
+ dataset = _Dataset(1, point.shape[0]).dense(point)
452
+ out = ffi.new("vsag_search_result_t**")
453
+ err = lib.vsag_index_range_search(
454
+ self._handle, dataset.handle, float(threshold), -1, parameters.encode(), ffi.NULL, out
455
+ )
456
+ return (_take_result(out) if out[0] != ffi.NULL else None), err
457
+
458
+ def range_search(self, point, threshold, parameters):
459
+ """Return (ids, distances) of all vectors within the distance threshold."""
460
+ result, err = self._range(point, threshold, parameters, "range_search")
461
+ if not _ok(err) or result is None:
462
+ return np.empty(0, dtype=np.int64), np.empty(0, dtype=np.float32)
463
+ return _result_arrays(result)
464
+
465
+ def range_search_with_statistics(self, point, threshold, parameters):
466
+ """Same as range_search, but also returns the statistics JSON of the search."""
467
+ result, err = self._range(point, threshold, parameters, "range_search_with_statistics")
468
+ _check(err, "range search failed")
469
+ ids, dists = _result_arrays(result)
470
+ return ids, dists, _statistics(result)
471
+
472
+ def calc_distances_by_id(self, query, ids):
473
+ """Return the distances between the query and the vectors with the given ids."""
474
+ query = np.ascontiguousarray(query, dtype=np.float32)
475
+ ids = _int_array(ids, np.int64, "ids")
476
+ if query.ndim != 1 or ids.ndim != 1:
477
+ raise ValueError("query and ids must be 1-dimensional")
478
+ if query.shape[0] == 0:
479
+ raise RuntimeError("calc_distances_by_id failed: query must not be empty")
480
+ dists = np.empty(ids.shape[0], dtype=np.float32)
481
+ dataset = _Dataset(1, query.shape[0]).dense(query)
482
+ err = lib.vsag_index_calc_distances_by_ids(
483
+ self._handle, dataset.handle, _ptr(ids, "int64_t*"), ids.shape[0], _ptr(dists, "float*")
484
+ )
485
+ _check(err, "calc_distances_by_id failed")
486
+ return dists
487
+
488
+ cal_distance_by_id = calc_distances_by_id
489
+
490
+ def get_num_elements(self):
491
+ value = ffi.new("int64_t*")
492
+ _check(lib.vsag_index_get_num_elements(self._handle, value), "get_num_elements failed")
493
+ return int(value[0])
494
+
495
+ def get_memory_usage(self):
496
+ value = ffi.new("int64_t*")
497
+ _check(lib.vsag_index_get_memory_usage(self._handle, value), "get_memory_usage failed")
498
+ return int(value[0])
499
+
500
+ def check_id_exist(self, id):
501
+ exist = ffi.new("int32_t*")
502
+ _check(lib.vsag_index_check_id_exist(self._handle, int(id), exist), "check_id_exist failed")
503
+ return bool(exist[0])
504
+
505
+ def get_min_max_id(self):
506
+ """Return (min_id, max_id), or (-1, -1) if the index has no ids."""
507
+ min_id, max_id = ffi.new("int64_t*"), ffi.new("int64_t*")
508
+ if not _ok(lib.vsag_index_get_min_max_id(self._handle, min_id, max_id)):
509
+ return -1, -1
510
+ return int(min_id[0]), int(max_id[0])
511
+
512
+ def save(self, filename):
513
+ """Save the index to a file."""
514
+ _check(lib.vsag_index_serialize_file(self._handle, os.fsencode(filename)), "save failed")
515
+
516
+ def load(self, filename):
517
+ """Load the index from a file written by save."""
518
+ _check(lib.vsag_index_deserialize_file(self._handle, os.fsencode(filename)), "load failed")
pyvsag/_lib.py ADDED
@@ -0,0 +1,75 @@
1
+ # Copyright 2024-present the vsag project
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of 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,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Loads libvsag_c through cffi (ABI mode) using the public C header."""
16
+
17
+ import os
18
+ import re
19
+ import sys
20
+
21
+ import cffi
22
+
23
+ _PKG_DIR = os.path.dirname(os.path.realpath(__file__))
24
+ _HEADER_NAME = "vsag_c_api.h"
25
+ EXPECTED_C_API_VERSION = 1
26
+
27
+
28
+ def _find_header():
29
+ candidates = [
30
+ os.path.join(_PKG_DIR, "_" + _HEADER_NAME),
31
+ os.path.join(_PKG_DIR, "..", "..", "include", "vsag", _HEADER_NAME),
32
+ ]
33
+ for path in candidates:
34
+ if os.path.exists(path):
35
+ return path
36
+ raise ImportError("pyvsag cannot find the C API header " + _HEADER_NAME)
37
+
38
+
39
+ def _find_library():
40
+ override = os.environ.get("PYVSAG_LIBRARY")
41
+ if override:
42
+ return override
43
+ suffix = "dylib" if sys.platform == "darwin" else "so"
44
+ path = os.path.join(_PKG_DIR, "libvsag_c." + suffix)
45
+ if os.path.exists(path):
46
+ return path
47
+ raise ImportError(
48
+ "pyvsag cannot find libvsag_c; set PYVSAG_LIBRARY to its path when running from a "
49
+ "source tree"
50
+ )
51
+
52
+
53
+ def _cdef_from_header(path):
54
+ with open(path, encoding="utf-8") as header:
55
+ text = header.read()
56
+ # The C++ guards around extern "C" are not valid cdef input.
57
+ text = re.sub(r"#ifdef __cplusplus.*?#endif", "", text, flags=re.DOTALL)
58
+ # cffi understands integer #define constants but not other preprocessor lines.
59
+ lines = [
60
+ line
61
+ for line in text.splitlines()
62
+ if not line.startswith("#") or re.match(r"#define\s+\w+\s+-?\d+\s*$", line)
63
+ ]
64
+ return "\n".join(lines)
65
+
66
+
67
+ ffi = cffi.FFI()
68
+ ffi.cdef(_cdef_from_header(_find_header()))
69
+ lib = ffi.dlopen(_find_library())
70
+
71
+ if lib.vsag_c_api_version() != EXPECTED_C_API_VERSION:
72
+ raise ImportError(
73
+ "pyvsag is incompatible with the loaded libvsag_c (C API version %d, expected %d)"
74
+ % (lib.vsag_c_api_version(), EXPECTED_C_API_VERSION)
75
+ )
pyvsag/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "1.2.0.dev241"