Skip to content

Commit 455f0fc

Browse files
committed
[eigen] sparse.h : use scipy's API to sort indices for Eigen<3.4.90
1 parent 7fe844e commit 455f0fc

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed

include/nanobind/eigen/sparse.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,12 @@ template <typename T> struct type_caster<T, enable_if_t<is_eigen_sparse_matrix_v
6262
return false;
6363
}
6464

65+
#if !EIGEN_VERSION_AT_LEAST(3, 4, 90)
66+
bool indices_sorted = cast<bool>(obj.attr("has_sorted_indices"));
67+
if (!indices_sorted)
68+
obj.attr("sort_indices")();
69+
#endif
70+
6571
if (object data_o = obj.attr("data"); !data_caster.from_python(data_o, flags, cleanup))
6672
return false;
6773
ScalarNDArray& values = data_caster.value;

tests/test_eigen.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -264,9 +264,6 @@ def test08_sparse():
264264
assert type(t.sparse_copy_r(t.sparse_c())) is scipy.sparse.csr_matrix
265265
assert type(t.sparse_copy_c(t.sparse_r())) is scipy.sparse.csc_matrix
266266

267-
# construct scipy matrix with unsorted indices
268-
assert type(t.sparse_copy_c(create_spmat_unsorted())) is scipy.sparse.csc_matrix
269-
270267

271268
def assert_sparse_equal_ref(sparse_mat):
272269
ref = np.array(
@@ -286,7 +283,11 @@ def assert_sparse_equal_ref(sparse_mat):
286283
assert_sparse_equal_ref(t.sparse_copy_c(t.sparse_c()))
287284
assert_sparse_equal_ref(t.sparse_copy_r(t.sparse_c()))
288285
assert_sparse_equal_ref(t.sparse_copy_c(t.sparse_r()))
289-
assert_sparse_equal_ref(t.sparse_copy_c(create_spmat_unsorted()))
286+
287+
# construct scipy matrix with unsorted indices
288+
assert type(t.sparse_copy_c(create_spmat_unsorted())) is scipy.sparse.csc_matrix
289+
mat_unsort = create_spmat_unsorted()
290+
assert_array_equal(t.sparse_copy_c(mat_unsort).toarray(), create_spmat_unsorted().toarray())
290291

291292

292293
@needs_numpy_and_eigen

0 commit comments

Comments
 (0)