Skip to content

Commit f4dde19

Browse files
committed
Fixed handling of duplicates for SciPy sparse arrays - fixes #162
1 parent c451fb0 commit f4dde19

2 files changed

Lines changed: 15 additions & 0 deletions

File tree

‎pgvector/sparsevec.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,11 @@ def _from_dict(self, d: dict[int, float], dim: int) -> None:
105105
def _from_sparse(self, arr: sparray | spmatrix, /) -> None:
106106
value: coo_array | coo_matrix = arr.tocoo(copy=False) # type: ignore
107107

108+
# has_canonical_format added in scipy 1.12+
109+
if not hasattr(value, 'has_canonical_format') or not value.has_canonical_format:
110+
value = value.copy()
111+
value.sum_duplicates()
112+
108113
shape = cast(tuple[int, ...], value.shape)
109114
if len(shape) == 1:
110115
self._dim = shape[0]

‎tests/test_sparse_vector.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,16 @@ def test_coo_array(self) -> None:
6060
assert vec.indices() == [0, 2, 4]
6161
assert isinstance(vec.values()[0], float)
6262

63+
def test_coo_array_duplicates(self) -> None:
64+
if np is None or sparse is None:
65+
pytest.skip('NumPy and SciPy required')
66+
67+
arr = sparse.coo_array(([1, 2], ([1, 1],)), shape=(3,))
68+
assert arr.todense().tolist() == [0, 3, 0]
69+
vec = SparseVector(arr)
70+
assert vec.to_list() == [0, 3, 0]
71+
assert vec.indices() == [1]
72+
6373
def test_coo_array_dimensions(self) -> None:
6474
if np is None or sparse is None:
6575
pytest.skip('NumPy and SciPy required')

0 commit comments

Comments
 (0)