Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lint & format weights/*.py part 8 #658

Merged
merged 8 commits into from
Nov 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 17 additions & 14 deletions libpysal/weights/tests/test_Wsets.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
"""Unit test for set_operations module."""

# ruff: noqa: N999

import numpy as np

from .. import set_operations
Expand All @@ -14,48 +17,48 @@ def test_w_union(self):
w2 = lat2W(6, 4)
w3 = set_operations.w_union(w1, w2)
assert w1[0] == w3[0]
assert set(w1.neighbors[15]) == set([11, 14])
assert set(w2.neighbors[15]) == set([11, 14, 19])
assert set(w3.neighbors[15]) == set([19, 11, 14])
assert set(w1.neighbors[15]) == {11, 14}
assert set(w2.neighbors[15]) == {11, 14, 19}
assert set(w3.neighbors[15]) == {19, 11, 14}

def test_w_intersection(self):
"""Unit test"""
w1 = lat2W(4, 4)
w2 = lat2W(6, 4)
w3 = set_operations.w_union(w1, w2)
assert w1[0] == w3[0]
assert set(w1.neighbors[15]) == set([11, 14])
assert set(w2.neighbors[15]) == set([11, 14, 19])
assert set(w3.neighbors[15]) == set([19, 11, 14])
assert set(w1.neighbors[15]) == {11, 14}
assert set(w2.neighbors[15]) == {11, 14, 19}
assert set(w3.neighbors[15]) == {19, 11, 14}

def test_w_difference(self):
"""Unit test"""
w1 = lat2W(4, 4, rook=False)
w2 = lat2W(4, 4, rook=True)
w3 = set_operations.w_difference(w1, w2, constrained=False)
assert w1[0] != w3[0]
assert set(w1.neighbors[15]) == set([10, 11, 14])
assert set(w2.neighbors[15]) == set([11, 14])
assert set(w3.neighbors[15]) == set([10])
assert set(w1.neighbors[15]) == {10, 11, 14}
assert set(w2.neighbors[15]) == {11, 14}
assert set(w3.neighbors[15]) == {10}

def test_w_symmetric_difference(self):
"""Unit test"""
w1 = lat2W(4, 4, rook=False)
w2 = lat2W(6, 4, rook=True)
w3 = set_operations.w_symmetric_difference(w1, w2, constrained=False)
assert w1[0] != w3[0]
assert set(w1.neighbors[15]) == set([10, 11, 14])
assert set(w2.neighbors[15]) == set([11, 14, 19])
assert set(w3.neighbors[15]) == set([10, 19])
assert set(w1.neighbors[15]) == {10, 11, 14}
assert set(w2.neighbors[15]) == {11, 14, 19}
assert set(w3.neighbors[15]) == {10, 19}

def test_w_subset(self):
"""Unit test"""
w1 = lat2W(6, 4)
ids = list(range(16))
w2 = set_operations.w_subset(w1, ids)
assert w1[0] == w2[0]
assert set(w1.neighbors[15]) == set([11, 14, 19])
assert set(w2.neighbors[15]) == set([11, 14])
assert set(w1.neighbors[15]) == {11, 14, 19}
assert set(w2.neighbors[15]) == {11, 14}

def test_w_clip(self):
"""Unit test for w_clip"""
Expand Down
2 changes: 1 addition & 1 deletion libpysal/weights/tests/test_user.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from ... import examples
from .. import user
from ..contiguity import Rook, Voronoi
from ..contiguity import Rook


class Testuser:
Expand Down
27 changes: 12 additions & 15 deletions libpysal/weights/tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import pytest

from ... import examples
from ...io.fileio import FileIO as psopen
from ...io.fileio import FileIO
from .. import util
from ..contiguity import Queen, Rook
from ..distance import KNN, DistanceBand
Expand Down Expand Up @@ -104,11 +104,11 @@ def test_block_weights(self):

def test_comb(self):
x = list(range(4))
l = []
l_ = []
for i in util.comb(x, 2):
l.append(i)
l_.append(i)
lo = [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]
assert l == lo
assert l_ == lo

def test_order(self):
w3 = util.order(self.w, kmax=3)
Expand Down Expand Up @@ -162,9 +162,9 @@ def test_higher_order_classes(self):
util.higher_order(wsparse, 2)
util.higher_order(ww, 2)
ww.transform = "r"
wsparse_notbinary = wrook.sparse
_ = wrook.sparse
util.higher_order(wsparse, 2)
jGaboardi marked this conversation as resolved.
Show resolved Hide resolved
with pytest.raises(ValueError):
util.higher_order(wsparse, 2)
util.higher_order(ww, 3)

def test_shimbel(self):
Expand Down Expand Up @@ -200,7 +200,6 @@ def test_full2_w(self):
ids = ["myID0", "myID1", "myID2", "myID3"]
w = util.full2W(a, ids=ids)
np.testing.assert_array_equal(w.full()[0], a)
w.full()[0] == a
jGaboardi marked this conversation as resolved.
Show resolved Hide resolved

def test_wsp2_w(self):
sp = util.lat2SW(2, 5)
Expand All @@ -210,7 +209,7 @@ def test_wsp2_w(self):
assert w[0] == {1: 1, 5: 1}
for weights in w.weights.values():
assert isinstance(weights, list)
w = psopen(examples.get_path("sids2.gal"), "r").read()
w = FileIO(examples.get_path("sids2.gal"), "r").read()
wsp = WSP(w.sparse, w.id_order)
w = util.WSP2W(wsp)
assert w.n == 100
Expand Down Expand Up @@ -332,14 +331,12 @@ def test_fuzzy_contiguity(self):
rs_df = gpd.read_file(rs)
wf = fuzzy_contiguity(rs_df)
assert wf.islands == []
assert set(wf.neighbors[0]) == set([239, 59, 152, 23])
assert set(wf.neighbors[0]) == {239, 59, 152, 23}
buff = fuzzy_contiguity(rs_df, buffering=True, buffer=0.2)
assert set(buff.neighbors[0]) == set([175, 119, 239, 59, 152, 246, 23, 107])
assert set(buff.neighbors[0]) == {175, 119, 239, 59, 152, 246, 23, 107}
rs_index = rs_df.set_index("NM_MUNICIP")
index_w = fuzzy_contiguity(rs_index)
assert set(index_w.neighbors["TAVARES"]) == set(
["SÃO JOSÉ DO NORTE", "MOSTARDAS"]
)
assert set(index_w.neighbors["TAVARES"]) == {"SÃO JOSÉ DO NORTE", "MOSTARDAS"}
wf_pred = fuzzy_contiguity(rs_df, predicate="touches")
assert set(wf_pred.neighbors[0]) == set([])
assert set(wf_pred.neighbors[1]) == set([142, 82, 197, 285, 386, 350])
assert set(wf_pred.neighbors[0]) == set()
assert set(wf_pred.neighbors[1]) == {142, 82, 197, 285, 386, 350}
14 changes: 7 additions & 7 deletions libpysal/weights/tests/test_weights.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import scipy.sparse

from ... import examples
from ...io.fileio import FileIO as psopen
from ...io.fileio import FileIO
from .. import util
from ..contiguity import Rook
from ..distance import KNN
Expand Down Expand Up @@ -102,7 +102,7 @@ def test_asymmetry(self):
w = lat2W(3, 3)
assert w.asymmetry() == []
w.transform = "r"
assert not w.asymmetry() == []
assert w.asymmetry() != []

def test_asymmetry_string_index(self):
neighbors = {
Expand Down Expand Up @@ -427,8 +427,8 @@ def test_to_sparse(self):
assert isinstance(sparse, scipy.sparse.coo_array)

def test_sparse_fmt(self):
with pytest.raises(ValueError) as exc_info:
sparse = self.w_islands.to_sparse("dog")
with pytest.raises(ValueError):
self.w_islands.to_sparse("dog")

def test_from_sparse(self):
sparse = self.w_islands.to_sparse()
Expand All @@ -438,7 +438,7 @@ def test_from_sparse(self):
assert w.neighbors[3] == [3]


class Test_WSP_Back_To_W:
class TestWSPBackToW:
# Test to make sure we get back to the same W functionality
def setup_method(self):
self.w = Rook.from_shapefile(
Expand Down Expand Up @@ -528,7 +528,7 @@ def test_asymmetry(self):
w = util.lat2W(3, 3)
assert w.asymmetry() == []
w.transform = "r"
assert not w.asymmetry() == []
assert w.asymmetry() != []

def test_cardinalities(self):
w = util.lat2W(3, 3)
Expand Down Expand Up @@ -742,7 +742,7 @@ def test_trc_wt_w_ww(self):

class TestWSP:
def setup_method(self):
self.w = psopen(examples.get_path("sids2.gal")).read()
self.w = FileIO(examples.get_path("sids2.gal")).read()
self.wsp = WSP(self.w.sparse, self.w.id_order)
w3x3 = util.lat2W(3, 3)
self.w3x3 = WSP(w3x3.sparse)
Expand Down
2 changes: 2 additions & 0 deletions libpysal/weights/tests/test_weights_IO.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# ruff: noqa: N999

import os
import tempfile

Expand Down
30 changes: 15 additions & 15 deletions libpysal/weights/weights.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
Weights.
"""

# ruff: noqa: N802
# ruff: noqa: N802, N803

__author__ = "Sergio J. Rey <srey@asu.edu>"

Expand Down Expand Up @@ -375,8 +375,8 @@ def from_adjlist(
adjlist = adjlist.copy(deep=True)
adjlist["weight"] = 1
grouper = adjlist.groupby(focal_col)
neighbors = dict()
weights = dict()
neighbors = {}
weights = {}
for ix, chunk in grouper:
neighbors_to_ix = chunk[neighbor_col].values
weights_to_ix = chunk[weight_col].values
Expand Down Expand Up @@ -474,8 +474,8 @@ def to_networkx(self):
raise ImportError(
"NetworkX 2.7+ is required to use this function."
) from None
G = nx.DiGraph() if len(self.asymmetries) > 0 else nx.Graph()
return nx.from_scipy_sparse_array(self.sparse, create_using=G)
g = nx.DiGraph() if len(self.asymmetries) > 0 else nx.Graph()
return nx.from_scipy_sparse_array(self.sparse, create_using=g)

@classmethod
def from_networkx(cls, graph, weight_col="weight"): # noqa ARG003
Expand Down Expand Up @@ -1191,16 +1191,16 @@ def set_transform(self, value="B"):
weights = {}
q = {}
s = {}
Q = 0.0
big_q = 0.0
self.weights = self.transformations["O"]
for i in self.weights:
wijs = self.weights[i]
q[i] = math.sqrt(sum([wij * wij for wij in wijs]))
s[i] = [wij / q[i] for wij in wijs]
Q += sum(s[i])
nQ = self.n / Q
big_q += sum(s[i])
nq = self.n / big_q
for i in self.weights:
weights[i] = [w * nQ for w in s[i]]
weights[i] = [w * nq for w in s[i]]
weights = weights
self.transformations[value] = weights
self.weights = weights
Expand Down Expand Up @@ -1293,17 +1293,17 @@ def symmetrize(self, inplace=False):
if not inplace:
neighbors = copy.deepcopy(self.neighbors)
weights = copy.deepcopy(self.weights)
out_W = W(neighbors, weights, id_order=self.id_order)
out_W.symmetrize(inplace=True)
return out_W
out_w = W(neighbors, weights, id_order=self.id_order)
out_w.symmetrize(inplace=True)
return out_w
else:
for focal, fneighbs in list(self.neighbors.items()):
for j, neighbor in enumerate(fneighbs):
neighb_neighbors = self.neighbors[neighbor]
if focal not in neighb_neighbors:
self.neighbors[neighbor].append(focal)
self.weights[neighbor].append(self.weights[focal][j])
self._cache = dict()
self._cache = {}
return

def full(self):
Expand Down Expand Up @@ -1466,12 +1466,12 @@ def plot(
if "color" not in node_kws:
node_kws["color"] = color
else:
node_kws = dict(color=color)
node_kws = {"color": color}
if edge_kws is not None:
if "color" not in edge_kws:
edge_kws["color"] = color
else:
edge_kws = dict(color=color)
edge_kws = {"color": color}

for idx, neighbors in self.neighbors.items():
if idx in self.islands:
Expand Down