Browse code

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.

Joseph Weston authored on 07/08/2015 19:58:04
Showing 1 changed files
... ...
@@ -85,8 +85,15 @@ def make_sparse(ham, args, CGraph gr, diag,
85 85
                         rows_cols[1, k] = j + from_off[n_fs]
86 86
                         k += 1
87 87
 
88
-    return sp.coo_matrix((data[:k], rows_cols[:, :k]),
89
-                         shape=(to_off[-1], from_off[-1]))
88
+    # hack around a bug in Scipy + Python 3 + memoryviews
89
+    # see https://github.com/scipy/scipy/issues/5123 for details
90
+    np_data = np.asarray(data)
91
+    np_rows_cols = np.asarray(rows_cols)
92
+    np_to_off = np.asarray(to_off)
93
+    np_from_off = np.asarray(from_off)
94
+
95
+    return sp.coo_matrix((np_data[:k], np_rows_cols[:, :k]),
96
+                         shape=(np_to_off[-1], np_from_off[-1]))
90 97
 
91 98
 
92 99
 @cython.boundscheck(False)
... ...
@@ -148,8 +155,15 @@ def make_sparse_full(ham, args, CGraph gr, diag,
148 155
                         rows_cols[0, k + 1] = rows_cols[1, k] = j + from_off[fs]
149 156
                         k += 2
150 157
 
151
-    return sp.coo_matrix((data[:k], rows_cols[:, :k]),
152
-                         shape=(to_off[-1], from_off[-1]))
158
+    # hack around a bug in Scipy + Python 3 + memoryviews
159
+    # see https://github.com/scipy/scipy/issues/5123 for details
160
+    np_data = np.asarray(data)
161
+    np_rows_cols = np.asarray(rows_cols)
162
+    np_to_off = np.asarray(to_off)
163
+    np_from_off = np.asarray(from_off)
164
+
165
+    return sp.coo_matrix((np_data[:k], np_rows_cols[:, :k]),
166
+                         shape=(np_to_off[-1], np_from_off[-1]))
153 167
 
154 168
 
155 169
 @cython.boundscheck(False)