Skip to content

Commit 996652b

Browse files
committed
Count constraint checks in CSP via self.nchecks (#1112)
The CSP class tracked nassigns but not the number of consistency checks, so the constraint-check benchmarks from Figure 6.1 (BT, BT+MRV, FC, ...) could not be reproduced. Expose the constraint relation through a constraints() method that tallies every call in self.nchecks (the raw relation is kept as self.constraint_relation). All callers - nconflicts, count_lost_values, forward_checking, AC3/AC3b/AC4 - go through it, so nchecks measures the total checks across backtracking and propagation. Add a test.
1 parent 8c4a1cb commit 996652b

2 files changed

Lines changed: 27 additions & 1 deletion

File tree

‎csp.py‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,20 @@ def __init__(self, variables, domains, neighbors, constraints):
5858
self.variables = variables
5959
self.domains = domains
6060
self.neighbors = neighbors
61-
self.constraints = constraints
61+
# store the constraint relation privately and expose it through the
62+
# constraints() method below, which counts every consistency check
63+
self.constraint_relation = constraints
6264
self.curr_domains = None
6365
self.nassigns = 0
66+
self.nchecks = 0
67+
68+
def constraints(self, A, a, B, b):
69+
"""Return True if neighbors A, B satisfy the constraint when A=a, B=b.
70+
Every call is tallied in self.nchecks, so callers can measure the number
71+
of consistency checks performed (e.g. to reproduce the benchmarks in
72+
Figure 6.1), just as self.nassigns tallies the assignments made."""
73+
self.nchecks += 1
74+
return self.constraint_relation(A, a, B, b)
6475

6576
def assign(self, var, val, assignment):
6677
"""Add {var: val} to assignment; Discard the old value if any."""

‎tests/test_csp.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -701,5 +701,20 @@ def test_zebra():
701701
'Winston': 3, 'LuckyStrike': 4, 'Parliaments': 5}
702702

703703

704+
def test_constraint_check_count():
705+
csp = MapColoringCSP(list('RGB'), 'SA: WA NT Q NSW V; NT: WA Q; NSW: Q V; T: ')
706+
# before solving, no assignments or checks have been made
707+
assert csp.nassigns == 0 and csp.nchecks == 0
708+
solution = backtracking_search(csp)
709+
assert solution is not None
710+
# solving performs both variable assignments and constraint (consistency) checks
711+
assert csp.nassigns > 0
712+
assert csp.nchecks > 0
713+
# every constraints() call is tallied
714+
before = csp.nchecks
715+
csp.constraints('WA', 'R', 'NT', 'G')
716+
assert csp.nchecks == before + 1
717+
718+
704719
if __name__ == "__main__":
705720
pytest.main()

0 commit comments

Comments
 (0)