From 9e873a9ae66a6b00d025c320504e3a48414341bb Mon Sep 17 00:00:00 2001 From: Joseph Weston <joseph.weston@cea.fr> Date: Fri, 7 Aug 2015 19:58:04 +0200 Subject: [PATCH] fix sparse matrix creation for Python 3 + memoryviews Under Python 3, `scipy.sparse.coo_matrix` fails when passed memoryviews. We coerce the memoryviews to numpy arrays before passing them to the `coo_matrix`. Even though this is kind of a hack it shouldn't be very inefficient as no data is actually copied. See https://github.com/scipy/scipy/issues/5123 for details. --- kwant/_system.pyx | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/kwant/_system.pyx b/kwant/_system.pyx index 396b9175..beebd946 100644 --- a/kwant/_system.pyx +++ b/kwant/_system.pyx @@ -85,8 +85,15 @@ def make_sparse(ham, args, CGraph gr, diag, rows_cols[1, k] = j + from_off[n_fs] k += 1 - return sp.coo_matrix((data[:k], rows_cols[:, :k]), - shape=(to_off[-1], from_off[-1])) + # hack around a bug in Scipy + Python 3 + memoryviews + # see https://github.com/scipy/scipy/issues/5123 for details + np_data = np.asarray(data) + np_rows_cols = np.asarray(rows_cols) + np_to_off = np.asarray(to_off) + np_from_off = np.asarray(from_off) + + return sp.coo_matrix((np_data[:k], np_rows_cols[:, :k]), + shape=(np_to_off[-1], np_from_off[-1])) @cython.boundscheck(False) @@ -148,8 +155,15 @@ def make_sparse_full(ham, args, CGraph gr, diag, rows_cols[0, k + 1] = rows_cols[1, k] = j + from_off[fs] k += 2 - return sp.coo_matrix((data[:k], rows_cols[:, :k]), - shape=(to_off[-1], from_off[-1])) + # hack around a bug in Scipy + Python 3 + memoryviews + # see https://github.com/scipy/scipy/issues/5123 for details + np_data = np.asarray(data) + np_rows_cols = np.asarray(rows_cols) + np_to_off = np.asarray(to_off) + np_from_off = np.asarray(from_off) + + return sp.coo_matrix((np_data[:k], np_rows_cols[:, :k]), + shape=(np_to_off[-1], np_from_off[-1])) @cython.boundscheck(False) -- GitLab