Skip to content

Commit ed6eb00

Browse files
authored
Merge pull request #276 from ljwolf/weight-to-file
add weights writing as a method on weights.
2 parents 5757563 + 6f9d87a commit ed6eb00

File tree

2 files changed

+47
-3
lines changed

2 files changed

+47
-3
lines changed

libpysal/weights/tests/test_weights.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,12 @@ def test_connected_components(self):
254254
disco = W(disco)
255255
assert disco.n_components == 2
256256

257+
def test_roundtrip_write(self):
258+
self.w.to_file('./tmp.gal')
259+
new = W.from_file('./tmp.gal')
260+
np.testing.assert_array_equal(self.w.sparse.toarray(),
261+
new.sparse.toarray())
262+
257263
class Test_WSP_Back_To_W(unittest.TestCase):
258264
# Test to make sure we get back to the same W functionality
259265
def setUp(self):

libpysal/weights/weights.py

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -175,10 +175,48 @@ def _reset(self):
175175
"""Reset properties."""
176176
self._cache = {}
177177

178+
def to_file(self, path='', format=None):
179+
"""
180+
Write a weights to a file. The format is guessed automatically
181+
from the path, but can be overridden with the format argument.
182+
183+
See libpysal.io.FileIO for more information.
184+
185+
Arguments
186+
---------
187+
path : string
188+
location to save the file
189+
format : string
190+
string denoting the format to write the weights to.
191+
192+
193+
Returns
194+
-------
195+
None
196+
"""
197+
f = popen(dataPath=path, mode='w', dataFormat=format)
198+
f.write(self)
199+
f.close()
200+
201+
178202
@classmethod
179-
def from_file(cls, path="", format=None, **kwargs):
180-
f = popen(dataPath=path, mode="r", dataFormat=format)
181-
w = f.read(**kwargs)
203+
def from_file(cls, path='', format=None):
204+
"""
205+
Read a weights file into a W object.
206+
207+
Arguments
208+
---------
209+
path : string
210+
location to save the file
211+
format : string
212+
string denoting the format to write the weights to.
213+
214+
Returns
215+
-------
216+
W object
217+
"""
218+
f = popen(dataPath=path, mode='r', dataFormat=format)
219+
w = f.read()
182220
f.close()
183221
return w
184222

0 commit comments

Comments
 (0)