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

ENH: Graph.eliminate_zeros, refactor isolates #634

Merged
merged 3 commits into from
Nov 19, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
26 changes: 24 additions & 2 deletions libpysal/graph/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -972,9 +972,13 @@ def isolates(self):
pandas.Index
Index with a subset of observations that do not have any neighbor
"""
nulls = self._adjacency[self._adjacency == 0].reset_index(level=1)
nulls = self._adjacency[self._adjacency == 0]
# since not all zeros are necessarily isolates, do the focal == neighbor check
return nulls[nulls.index == nulls.neighbor].index.unique()
return (
nulls[nulls.index.codes[0] == nulls.index.codes[1]]
Copy link
Member Author

@martinfleis martinfleis Nov 9, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is indeed faster than the original solution. On exploded geoda tampa1 dataset and basic contiguity 84.8 µs ± 5.65 µs vs 253 µs ± 6.75 µs.

.index.get_level_values(0)
.unique()
)

@cached_property
def unique_ids(self):
Expand Down Expand Up @@ -1337,6 +1341,24 @@ def explore(
**kwargs,
)

def eliminate_zeros(self):
"""Remove graph edges with zero weight

Eliminates edges with weight == 0 that do not encode an
isolate. This is useful to clean-up edges that will make
no effect in operations like :meth:`lag`.

Returns
-------
Graph
subset of Graph with zero-weight edges eliminated
"""
# get a mask for isolates
isolates = self._adjacency.index.codes[0] == self._adjacency.index.codes[1]
# substract isolates from mask of zeros
zeros = (self._adjacency == 0) != isolates
return Graph(self._adjacency[~zeros])
martinfleis marked this conversation as resolved.
Show resolved Hide resolved


def _arrange_arrays(heads, tails, weights, ids=None):
"""
Expand Down
8 changes: 8 additions & 0 deletions libpysal/graph/tests/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -941,3 +941,11 @@ def test_component_labels(self):
pd.testing.assert_series_equal(
expected, nybb.component_labels, check_dtype=False
)

def test_eliminate_zeros(self):
adj = self.adjacency_str_binary.copy()
adj["Bronx", "Queens"] = 0
adj["Queens", "Manhattan"] = 0
with_zero = graph.Graph(adj)
expected = adj.drop([("Bronx", "Queens"), ("Queens", "Manhattan")])
pd.testing.assert_series_equal(with_zero.eliminate_zeros()._adjacency, expected)