Skip to content

Commit efcf434

Browse files
committed
add to_file method to weights to wrap io.FileIO.open
1 parent 65e08c3 commit efcf434

File tree

2 files changed

+46
-2
lines changed

2 files changed

+46
-2
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: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -174,10 +174,48 @@ def _reset(self):
174174
"""
175175
self._cache = {}
176176

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

0 commit comments

Comments
 (0)