Skip to content

Commit 91d3fe3

Browse files
authored
Implement least-constraining-value heuristic correctly (#1192)
lcv previously sorted by nconflicts (conflicts with already-assigned neighbours), which is degenerate during a consistent search. Add CSP.count_lost_values - the number of values ruled out in unassigned neighbours' domains - and order lcv by it, per the AIMA definition. Closes #1089.
1 parent b536e6d commit 91d3fe3

2 files changed

Lines changed: 18 additions & 4 deletions

File tree

‎csp.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,14 @@ def conflict(var2):
8383

8484
return count(conflict(v) for v in self.neighbors[var])
8585

86+
def count_lost_values(self, var, val, assignment):
87+
"""Return how many values would be ruled out in the domains of the
88+
unassigned neighbours of var if var were assigned val (the count used
89+
by the least-constraining-value heuristic)."""
90+
return count(not self.constraints(var, val, neighbor, dval)
91+
for neighbor in self.neighbors[var] if neighbor not in assignment
92+
for dval in self.domains[neighbor])
93+
8694
def display(self, assignment):
8795
"""Show a human-readable representation of the CSP."""
8896
# Subclasses can print in a prettier way, or display with a GUI
@@ -371,7 +379,7 @@ def unordered_domain_values(var, assignment, csp):
371379

372380
def lcv(var, assignment, csp):
373381
"""Least-constraining-values heuristic."""
374-
return sorted(csp.choices(var), key=lambda val: csp.nconflicts(var, val, assignment))
382+
return sorted(csp.choices(var), key=lambda val: csp.count_lost_values(var, val, assignment))
375383

376384

377385
# Inference

‎tests/test_csp.py‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,12 @@ def test_csp_nconflicts():
3535
val = 'B'
3636
assert map_coloring_test.nconflicts(var, val, assignment) == 0
3737

38+
def test_csp_count_lost_values():
39+
map_coloring_test = MapColoringCSP(list('RGB'), 'A: B C; B: C; C: ')
40+
assignment = {'A': 'G'}
41+
var = 'C'
42+
val = 'R'
43+
assert map_coloring_test.count_lost_values(var, val, assignment) == 1
3844

3945
def test_csp_actions():
4046
map_coloring_test = MapColoringCSP(list('123'), 'A: B C; B: C; C: ')
@@ -332,13 +338,13 @@ def test_lcv():
332338

333339
var = 'B'
334340

335-
assert lcv(var, assignment, csp) == [4, 0, 1, 2, 3, 5]
336-
assignment = {'A': 1, 'C': 3}
341+
assert lcv(var, assignment, csp) == [0, 2, 4, 1, 3, 5]
342+
assignment = {'A': 1}
337343

338344
constraints = lambda X, x, Y, y: (x + y) % 2 == 0 and (x + y) < 5
339345
csp = CSP(variables=None, domains=domains, neighbors=neighbors, constraints=constraints)
340346

341-
assert lcv(var, assignment, csp) == [1, 3, 0, 2, 4, 5]
347+
assert lcv(var, assignment, csp) == [0, 1, 2, 3, 4, 5]
342348

343349

344350
def test_forward_checking():

0 commit comments

Comments
 (0)