Skip to content

Commit

Permalink
Merge pull request #383 from mggg/perf-assignment-flows-opt
Browse files Browse the repository at this point in the history
Refactor out Assignment.update (replace with Assignment.update_flows) to prevent double-calculating flows
  • Loading branch information
gabeschoenbach committed Feb 10, 2022
2 parents 881e2e6 + b1054af commit 61ca3f3
Show file tree
Hide file tree
Showing 4 changed files with 7 additions and 10 deletions.
7 changes: 2 additions & 5 deletions gerrychain/partition/assignment.py
Expand Up @@ -4,8 +4,6 @@

import pandas

from ..updaters.flows import flows_from_changes


class Assignment(Mapping):
"""An assignment of nodes into parts.
Expand Down Expand Up @@ -58,10 +56,9 @@ def copy(self):
"""
return Assignment(self.parts.copy(), self.mapping.copy(), validate=False)

def update(self, mapping):
"""Update the assignment for some nodes using the given mapping.
def update_flows(self, flows):
"""Update the assignment for some nodes using the given flows.
"""
flows = flows_from_changes(self, mapping)
for part, flow in flows.items():
# Union between frozenset and set returns an object whose type
# matches the object on the left, which here is a frozenset
Expand Down
6 changes: 3 additions & 3 deletions gerrychain/partition/partition.py
Expand Up @@ -75,14 +75,14 @@ def _from_parent(self, parent, flips):
self.parent = parent
self.flips = flips

self.assignment = parent.assignment.copy()
self.assignment.update(flips)

self.graph = parent.graph
self.updaters = parent.updaters

self.flows = flows_from_changes(parent.assignment, flips)

self.assignment = parent.assignment.copy()
self.assignment.update_flows(self.flows)

if "cut_edges" in self.updaters:
self.edge_flows = compute_edge_flows(self)

Expand Down
2 changes: 1 addition & 1 deletion tests/constraints/test_validity.py
Expand Up @@ -169,6 +169,6 @@ def test_no_vanishing_districts_works():
partition = MagicMock()
partition.parent = parent
partition.assignment = parent.assignment.copy()
partition.assignment.update({2: 1})
partition.assignment.update_flows({1: {"out": set(), "in": {2}}, 2: {"out": {2}, "in": set()}})

assert not no_vanishing_districts(partition)
2 changes: 1 addition & 1 deletion tests/partition/test_assignment.py
Expand Up @@ -12,7 +12,7 @@ def assignment():

class TestAssignment:
def test_assignment_can_be_updated(self, assignment):
assignment.update({2: 1})
assignment.update_flows({1: {"out": set(), "in": {2}}, 2: {"out": {2}, "in": set()}})
assert assignment[2] == 1

def test_assignment_copy_does_not_copy_the_node_sets(self, assignment):
Expand Down

0 comments on commit 61ca3f3

Please sign in to comment.