Skip to content

Commit a24c33e

Browse files
committed
Implements W.from_WSP
1 parent 390c5c4 commit a24c33e

File tree

2 files changed

+68
-1
lines changed

2 files changed

+68
-1
lines changed

libpysal/weights/tests/test_weights.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -689,6 +689,11 @@ def test_trcWtW_WW(self):
689689
def test_s0(self):
690690
self.assertEqual(self.w3x3.s0, 24.0)
691691

692+
def test_from_WSP(self):
693+
w = W.from_WSP(self.wsp)
694+
self.assertEqual(w.n, 100)
695+
self.assertEqual(w.pct_nonzero, 4.62)
696+
692697

693698
if __name__ == "__main__":
694699
unittest.main()

libpysal/weights/weights.py

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,69 @@ def from_shapefile(cls, *args, **kwargs):
232232

233233
@classmethod
234234
def from_WSP(cls, WSP, silence_warnings=True):
235-
return WSP2W(WSP, silence_warnings=silence_warnings)
235+
"""Create a pysal W from a pysal WSP object (thin weights matrix).
236+
237+
Parameters
238+
----------
239+
wsp : WSP
240+
PySAL sparse weights object
241+
242+
silence_warnings : bool
243+
By default ``libpysal`` will print a warning if the dataset contains
244+
any disconnected components or islands. To silence this warning set this
245+
parameter to ``True``.
246+
247+
248+
Returns
249+
-------
250+
w : W
251+
PySAL weights object
252+
253+
Examples
254+
--------
255+
>>> from libpysal.weights import lat2W, WSP, W
256+
257+
Build a 10x10 scipy.sparse matrix for a rectangular 2x5 region of cells
258+
(rook contiguity), then construct a PySAL sparse weights object (wsp).
259+
260+
>>> sp = lat2SW(2, 5)
261+
>>> wsp = WSP(sp)
262+
>>> wsp.n
263+
10
264+
>>> wsp.sparse[0].todense()
265+
matrix([[0, 1, 0, 0, 0, 1, 0, 0, 0, 0]], dtype=int8)
266+
267+
Create a standard PySAL W from this sparse weights object.
268+
269+
>>> w = W.from_WSP(wsp)
270+
>>> w.n
271+
10
272+
>>> print(w.full()[0][0])
273+
[0 1 0 0 0 1 0 0 0 0]
274+
"""
275+
WSP.sparse
276+
indices = WSP.sparse.indices
277+
data = WSP.sparse.data
278+
indptr = WSP.sparse.indptr
279+
id_order = WSP.id_order
280+
if id_order:
281+
# replace indices with user IDs
282+
indices = [id_order[i] for i in indices]
283+
else:
284+
id_order = list(range(WSP.n))
285+
neighbors, weights = {}, {}
286+
start = indptr[0]
287+
for i in range(WSP.n):
288+
oid = id_order[i]
289+
end = indptr[i + 1]
290+
neighbors[oid] = indices[start:end]
291+
weights[oid] = data[start:end]
292+
start = end
293+
ids = copy.copy(WSP.id_order)
294+
w = W(neighbors, weights, ids, silence_warnings=silence_warnings)
295+
w._sparse = copy.deepcopy(WSP.sparse)
296+
w._cache["sparse"] = w._sparse
297+
return w
236298

237299
@classmethod
238300
def from_adjlist(

0 commit comments

Comments
 (0)