-
Notifications
You must be signed in to change notification settings - Fork 0
/
csp.py
1394 lines (1268 loc) · 49.7 KB
/
csp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
#
# Copyright (c) 2005-2014 - Gustavo Niemeyer <gustavo@niemeyer.net>
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from __future__ import absolute_import, division, print_function
import random
import copy
__all__ = [
"Problem",
"Variable",
"Domain",
"Unassigned",
"Solver",
"BacktrackingSolver",
"RecursiveBacktrackingSolver",
"MinConflictsSolver",
"Constraint",
"FunctionConstraint",
"AllDifferentConstraint",
"AllEqualConstraint",
"MaxSumConstraint",
"ExactSumConstraint",
"MinSumConstraint",
"InSetConstraint",
"NotInSetConstraint",
"SomeInSetConstraint",
"SomeNotInSetConstraint",
]
class Problem(object):
"""
Class used to define a problem and retrieve solutions
"""
def __init__(self, solver=None):
"""
@param solver: Problem solver used to find solutions
(default is L{BacktrackingSolver})
@type solver: instance of a L{Solver} subclass
"""
self._solver = solver or BacktrackingSolver()
self._constraints = []
self._variables = {}
def reset(self):
"""
Reset the current problem definition
Example:
>>> problem = Problem()
>>> problem.addVariable("a", [1, 2])
>>> problem.reset()
>>> problem.getSolution()
>>>
"""
del self._constraints[:]
self._variables.clear()
def setSolver(self, solver):
"""
Change the problem solver currently in use
Example:
>>> solver = BacktrackingSolver()
>>> problem = Problem(solver)
>>> problem.getSolver() is solver
True
@param solver: New problem solver
@type solver: instance of a C{Solver} subclass
"""
self._solver = solver
def getSolver(self):
"""
Obtain the problem solver currently in use
Example:
>>> solver = BacktrackingSolver()
>>> problem = Problem(solver)
>>> problem.getSolver() is solver
True
@return: Solver currently in use
@rtype: instance of a L{Solver} subclass
"""
return self._solver
def addVariable(self, variable, domain):
"""
Add a variable to the problem
Example:
>>> problem = Problem()
>>> problem.addVariable("a", [1, 2])
>>> problem.getSolution() in ({'a': 1}, {'a': 2})
True
@param variable: Object representing a problem variable
@type variable: hashable object
@param domain: Set of items defining the possible values that
the given variable may assume
@type domain: list, tuple, or instance of C{Domain}
"""
if variable in self._variables:
msg = "Tried to insert duplicated variable %s" % repr(variable)
raise ValueError(msg)
if isinstance(domain, Domain):
domain = copy.deepcopy(domain)
elif hasattr(domain, "__getitem__"):
domain = Domain(domain)
else:
msg = "Domains must be instances of subclasses of the Domain class"
raise TypeError(msg)
if not domain:
raise ValueError("Domain is empty")
self._variables[variable] = domain
def addVariables(self, variables, domain):
"""
Add one or more variables to the problem
Example:
>>> problem = Problem()
>>> problem.addVariables(["a", "b"], [1, 2, 3])
>>> solutions = problem.getSolutions()
>>> len(solutions)
9
>>> {'a': 3, 'b': 1} in solutions
True
@param variables: Any object containing a sequence of objects
represeting problem variables
@type variables: sequence of hashable objects
@param domain: Set of items defining the possible values that
the given variables may assume
@type domain: list, tuple, or instance of C{Domain}
"""
for variable in variables:
self.addVariable(variable, domain)
def addConstraint(self, constraint, variables=None):
"""
Add a constraint to the problem
Example:
>>> problem = Problem()
>>> problem.addVariables(["a", "b"], [1, 2, 3])
>>> problem.addConstraint(lambda a, b: b == a+1, ["a", "b"])
>>> solutions = problem.getSolutions()
>>>
@param constraint: Constraint to be included in the problem
@type constraint: instance a L{Constraint} subclass or a
function to be wrapped by L{FunctionConstraint}
@param variables: Variables affected by the constraint (default to
all variables). Depending on the constraint type
the order may be important.
@type variables: set or sequence of variables
"""
if not isinstance(constraint, Constraint):
if callable(constraint):
constraint = FunctionConstraint(constraint)
else:
msg = "Constraints must be instances of subclasses " "of the Constraint class"
raise ValueError(msg)
self._constraints.append((constraint, variables))
def getSolution(self):
"""
Find and return a solution to the problem
Example:
>>> problem = Problem()
>>> problem.getSolution() is None
True
>>> problem.addVariables(["a"], [42])
>>> problem.getSolution()
{'a': 42}
@return: Solution for the problem
@rtype: dictionary mapping variables to values
"""
domains, constraints, vconstraints = self._getArgs()
if not domains:
return None
return self._solver.getSolution(domains, constraints, vconstraints)
def getSolutions(self):
"""
Find and return all solutions to the problem
Example:
>>> problem = Problem()
>>> problem.getSolutions() == []
True
>>> problem.addVariables(["a"], [42])
>>> problem.getSolutions()
[{'a': 42}]
@return: All solutions for the problem
@rtype: list of dictionaries mapping variables to values
"""
domains, constraints, vconstraints = self._getArgs()
if not domains:
return []
return self._solver.getSolutions(domains, constraints, vconstraints)
def getSolutionIter(self):
"""
Return an iterator to the solutions of the problem
Example:
>>> problem = Problem()
>>> list(problem.getSolutionIter()) == []
True
>>> problem.addVariables(["a"], [42])
>>> iter = problem.getSolutionIter()
>>> next(iter)
{'a': 42}
>>> next(iter)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
StopIteration
"""
domains, constraints, vconstraints = self._getArgs()
if not domains:
return iter(())
return self._solver.getSolutionIter(domains, constraints, vconstraints)
def _getArgs(self):
domains = self._variables.copy()
allvariables = domains.keys()
constraints = []
for constraint, variables in self._constraints:
if not variables:
variables = list(allvariables)
constraints.append((constraint, variables))
vconstraints = {}
for variable in domains:
vconstraints[variable] = []
for constraint, variables in constraints:
for variable in variables:
vconstraints[variable].append((constraint, variables))
for constraint, variables in constraints[:]:
constraint.preProcess(variables, domains, constraints, vconstraints)
for domain in domains.values():
domain.resetState()
if not domain:
return None, None, None
# doArc8(getArcs(domains, constraints), domains, {})
return domains, constraints, vconstraints
# ----------------------------------------------------------------------
# Solvers
# ----------------------------------------------------------------------
def getArcs(domains, constraints):
"""
Return a dictionary mapping pairs (arcs) of constrained variables
@attention: Currently unused.
"""
arcs = {}
for x in constraints:
constraint, variables = x
if len(variables) == 2:
variable1, variable2 = variables
arcs.setdefault(variable1, {}).setdefault(variable2, []).append(x)
arcs.setdefault(variable2, {}).setdefault(variable1, []).append(x)
return arcs
def doArc8(arcs, domains, assignments):
"""
Perform the ARC-8 arc checking algorithm and prune domains
@attention: Currently unused.
"""
check = dict.fromkeys(domains, True)
while check:
variable, _ = check.popitem()
if variable not in arcs or variable in assignments:
continue
domain = domains[variable]
arcsvariable = arcs[variable]
for othervariable in arcsvariable:
arcconstraints = arcsvariable[othervariable]
if othervariable in assignments:
otherdomain = [assignments[othervariable]]
else:
otherdomain = domains[othervariable]
if domain:
# changed = False
for value in domain[:]:
assignments[variable] = value
if otherdomain:
for othervalue in otherdomain:
assignments[othervariable] = othervalue
for constraint, variables in arcconstraints:
if not constraint(
variables, domains, assignments, True
):
break
else:
# All constraints passed. Value is safe.
break
else:
# All othervalues failed. Kill value.
domain.hideValue(value)
# changed = True
del assignments[othervariable]
del assignments[variable]
# if changed:
# check.update(dict.fromkeys(arcsvariable))
if not domain:
return False
return True
class Solver(object):
"""Abstract base class for solvers
"""
def getSolution(self, domains, constraints, vconstraints):
"""
Return one solution for the given problem
@param domains: Dictionary mapping variables to their domains
@type domains: dict
@param constraints: List of pairs of (constraint, variables)
@type constraints: list
@param vconstraints: Dictionary mapping variables to a list of
constraints affecting the given variables.
@type vconstraints: dict
"""
msg = "%s is an abstract class" % self.__class__.__name__
raise NotImplementedError(msg)
def getSolutions(self, domains, constraints, vconstraints):
"""
Return all solutions for the given problem
@param domains: Dictionary mapping variables to domains
@type domains: dict
@param constraints: List of pairs of (constraint, variables)
@type constraints: list
@param vconstraints: Dictionary mapping variables to a list of
constraints affecting the given variables.
@type vconstraints: dict
"""
msg = "%s provides only a single solution" % self.__class__.__name__
raise NotImplementedError(msg)
def getSolutionIter(self, domains, constraints, vconstraints):
"""
Return an iterator for the solutions of the given problem
@param domains: Dictionary mapping variables to domains
@type domains: dict
@param constraints: List of pairs of (constraint, variables)
@type constraints: list
@param vconstraints: Dictionary mapping variables to a list of
constraints affecting the given variables.
@type vconstraints: dict
"""
msg = "%s doesn't provide iteration" % self.__class__.__name__
raise NotImplementedError(msg)
class BacktrackingSolver(Solver):
"""
Problem solver with backtracking capabilities
Examples:
>>> result = [[('a', 1), ('b', 2)],
... [('a', 1), ('b', 3)],
... [('a', 2), ('b', 3)]]
>>> problem = Problem(BacktrackingSolver())
>>> problem.addVariables(["a", "b"], [1, 2, 3])
>>> problem.addConstraint(lambda a, b: b > a, ["a", "b"])
>>> solution = problem.getSolution()
>>> sorted(solution.items()) in result
True
>>> for solution in problem.getSolutionIter():
... sorted(solution.items()) in result
True
True
True
>>> for solution in problem.getSolutions():
... sorted(solution.items()) in result
True
True
True
"""
def __init__(self, forwardcheck=True):
"""
@param forwardcheck: If false forward checking will not be requested
to constraints while looking for solutions
(default is true)
@type forwardcheck: bool
"""
self._forwardcheck = forwardcheck
def getSolutionIter(self, domains, constraints, vconstraints):
forwardcheck = self._forwardcheck
assignments = {}
queue = []
while True:
# Mix the Degree and Minimum Remaing Values (MRV) heuristics
lst = [
(-len(vconstraints[variable]), len(domains[variable]), variable)
for variable in domains
]
lst.sort()
for item in lst:
if item[-1] not in assignments:
# Found unassigned variable
variable = item[-1]
values = domains[variable][:]
if forwardcheck:
pushdomains = [
domains[x]
for x in domains
if x not in assignments and x != variable
]
else:
pushdomains = None
break
else:
# No unassigned variables. We've got a solution. Go back
# to last variable, if there's one.
yield assignments.copy()
if not queue:
return
variable, values, pushdomains = queue.pop()
if pushdomains:
for domain in pushdomains:
domain.popState()
while True:
# We have a variable. Do we have any values left?
if not values:
# No. Go back to last variable, if there's one.
del assignments[variable]
while queue:
variable, values, pushdomains = queue.pop()
if pushdomains:
for domain in pushdomains:
domain.popState()
if values:
break
del assignments[variable]
else:
return
# Got a value. Check it.
assignments[variable] = values.pop()
if pushdomains:
for domain in pushdomains:
domain.pushState()
for constraint, variables in vconstraints[variable]:
if not constraint(variables, domains, assignments, pushdomains):
# Value is not good.
break
else:
break
if pushdomains:
for domain in pushdomains:
domain.popState()
# Push state before looking for next variable.
queue.append((variable, values, pushdomains))
raise RuntimeError("Can't happen")
def getSolution(self, domains, constraints, vconstraints):
iter = self.getSolutionIter(domains, constraints, vconstraints)
try:
return next(iter)
except StopIteration:
return None
def getSolutions(self, domains, constraints, vconstraints):
return list(self.getSolutionIter(domains, constraints, vconstraints))
class RecursiveBacktrackingSolver(Solver):
"""
Recursive problem solver with backtracking capabilities
Examples:
>>> result = [[('a', 1), ('b', 2)],
... [('a', 1), ('b', 3)],
... [('a', 2), ('b', 3)]]
>>> problem = Problem(RecursiveBacktrackingSolver())
>>> problem.addVariables(["a", "b"], [1, 2, 3])
>>> problem.addConstraint(lambda a, b: b > a, ["a", "b"])
>>> solution = problem.getSolution()
>>> sorted(solution.items()) in result
True
>>> for solution in problem.getSolutions():
... sorted(solution.items()) in result
True
True
True
>>> problem.getSolutionIter()
Traceback (most recent call last):
...
NotImplementedError: RecursiveBacktrackingSolver doesn't provide iteration
"""
def __init__(self, forwardcheck=True):
"""
@param forwardcheck: If false forward checking will not be requested
to constraints while looking for solutions
(default is true)
@type forwardcheck: bool
"""
self._forwardcheck = forwardcheck
def recursiveBacktracking(
self, solutions, domains, vconstraints, assignments, single
):
##############################################################
# Use different heuristics for selecting unassigned variable #
##############################################################
# Mix the Degree and Minimum Remaing Values (MRV) heuristics
lst = [
(-len(vconstraints[variable]), len(domains[variable]), variable)
for variable in domains
]
lst.sort()
# double-check how python sorts tuples
# assignments is a dictionary of {variable: value, ...}
# domains is a dictionary of {variables: [remaining possible values], ...}
# vconstraints is an array of tuples [(constraintObject, [vars in constraint]), ...]
for item in lst:
if item[-1] not in assignments:
# Found an unassigned variable. Let's go.
break
else:
# No unassigned variables. We've got a solution.
solutions.append(assignments.copy())
return solutions
variable = item[-1]
assignments[variable] = None
forwardcheck = self._forwardcheck
if forwardcheck:
pushdomains = [domains[x] for x in domains if x not in assignments]
else:
pushdomains = None
################################################
# Change heuristics for order of domain values #
################################################
for value in domains[variable]:
assignments[variable] = value
if pushdomains:
for domain in pushdomains:
domain.pushState()
for constraint, variables in vconstraints[variable]:
if not constraint(variables, domains, assignments, pushdomains):
# Value is not good.
break
else:
# Value is good. Recurse and get next variable.
self.recursiveBacktracking(
solutions, domains, vconstraints, assignments, single
)
if solutions and single:
return solutions
if pushdomains:
for domain in pushdomains:
domain.popState()
del assignments[variable]
return solutions
def getSolution(self, domains, constraints, vconstraints):
solutions = self.recursiveBacktracking([], domains, vconstraints, {}, True)
return solutions and solutions[0] or None
def getSolutions(self, domains, constraints, vconstraints):
return self.recursiveBacktracking([], domains, vconstraints, {}, False)
class MinConflictsSolver(Solver):
"""
Problem solver based on the minimum conflicts theory
Examples:
>>> result = [[('a', 1), ('b', 2)],
... [('a', 1), ('b', 3)],
... [('a', 2), ('b', 3)]]
>>> problem = Problem(MinConflictsSolver())
>>> problem.addVariables(["a", "b"], [1, 2, 3])
>>> problem.addConstraint(lambda a, b: b > a, ["a", "b"])
>>> solution = problem.getSolution()
>>> sorted(solution.items()) in result
True
>>> problem.getSolutions()
Traceback (most recent call last):
...
NotImplementedError: MinConflictsSolver provides only a single solution
>>> problem.getSolutionIter()
Traceback (most recent call last):
...
NotImplementedError: MinConflictsSolver doesn't provide iteration
"""
def __init__(self, steps=1000):
"""
@param steps: Maximum number of steps to perform before giving up
when looking for a solution (default is 1000)
@type steps: int
"""
self._steps = steps
def getSolution(self, domains, constraints, vconstraints):
assignments = {}
# Initial assignment
for variable in domains:
assignments[variable] = random.choice(domains[variable])
for _ in xrange(self._steps):
conflicted = False
lst = list(domains.keys())
random.shuffle(lst)
for variable in lst:
# Check if variable is not in conflict
for constraint, variables in vconstraints[variable]:
if not constraint(variables, domains, assignments):
break
else:
continue
# Variable has conflicts. Find values with less conflicts.
mincount = len(vconstraints[variable])
minvalues = []
for value in domains[variable]:
assignments[variable] = value
count = 0
for constraint, variables in vconstraints[variable]:
if not constraint(variables, domains, assignments):
count += 1
if count == mincount:
minvalues.append(value)
elif count < mincount:
mincount = count
del minvalues[:]
minvalues.append(value)
# Pick a random one from these values.
assignments[variable] = random.choice(minvalues)
conflicted = True
if not conflicted:
return assignments
return None
# ----------------------------------------------------------------------
# Variables
# ----------------------------------------------------------------------
class Variable(object):
"""
Helper class for variable definition
Using this class is optional, since any hashable object,
including plain strings and integers, may be used as variables.
"""
def __init__(self, name):
"""
@param name: Generic variable name for problem-specific purposes
@type name: string
"""
self.name = name
def __repr__(self):
return self.name
Unassigned = Variable("Unassigned") #: Helper object instance representing unassigned values
# ----------------------------------------------------------------------
# Domains
# ----------------------------------------------------------------------
class Domain(list):
"""
Class used to control possible values for variables
When list or tuples are used as domains, they are automatically
converted to an instance of that class.
"""
def __init__(self, set):
"""
@param set: Set of values that the given variables may assume
@type set: set of objects comparable by equality
"""
list.__init__(self, set)
self._hidden = []
self._states = []
def resetState(self):
"""
Reset to the original domain state, including all possible values
"""
self.extend(self._hidden)
del self._hidden[:]
del self._states[:]
def pushState(self):
"""
Save current domain state
Variables hidden after that call are restored when that state
is popped from the stack.
"""
self._states.append(len(self))
def popState(self):
"""
Restore domain state from the top of the stack
Variables hidden since the last popped state are then available
again.
"""
diff = self._states.pop() - len(self)
if diff:
self.extend(self._hidden[-diff:])
del self._hidden[-diff:]
def hideValue(self, value):
"""
Hide the given value from the domain
After that call the given value won't be seen as a possible value
on that domain anymore. The hidden value will be restored when the
previous saved state is popped.
@param value: Object currently available in the domain
"""
list.remove(self, value)
self._hidden.append(value)
# ----------------------------------------------------------------------
# Constraints
# ----------------------------------------------------------------------
class Constraint(object):
"""
Abstract base class for constraints
"""
def __call__(self, variables, domains, assignments, forwardcheck=False):
"""
Perform the constraint checking
If the forwardcheck parameter is not false, besides telling if
the constraint is currently broken or not, the constraint
implementation may choose to hide values from the domains of
unassigned variables to prevent them from being used, and thus
prune the search space.
@param variables: Variables affected by that constraint, in the
same order provided by the user
@type variables: sequence
@param domains: Dictionary mapping variables to their domains
@type domains: dict
@param assignments: Dictionary mapping assigned variables to their
current assumed value
@type assignments: dict
@param forwardcheck: Boolean value stating whether forward checking
should be performed or not
@return: Boolean value stating if this constraint is currently
broken or not
@rtype: bool
"""
return True
def preProcess(self, variables, domains, constraints, vconstraints):
"""
Preprocess variable domains
This method is called before starting to look for solutions,
and is used to prune domains with specific constraint logic
when possible. For instance, any constraints with a single
variable may be applied on all possible values and removed,
since they may act on individual values even without further
knowledge about other assignments.
@param variables: Variables affected by that constraint, in the
same order provided by the user
@type variables: sequence
@param domains: Dictionary mapping variables to their domains
@type domains: dict
@param constraints: List of pairs of (constraint, variables)
@type constraints: list
@param vconstraints: Dictionary mapping variables to a list of
constraints affecting the given variables.
@type vconstraints: dict
"""
if len(variables) == 1:
variable = variables[0]
domain = domains[variable]
for value in domain[:]:
if not self(variables, domains, {variable: value}):
domain.remove(value)
constraints.remove((self, variables))
vconstraints[variable].remove((self, variables))
def forwardCheck(self, variables, domains, assignments, _unassigned=Unassigned):
"""
Helper method for generic forward checking
Currently, this method acts only when there's a single
unassigned variable.
@param variables: Variables affected by that constraint, in the
same order provided by the user
@type variables: sequence
@param domains: Dictionary mapping variables to their domains
@type domains: dict
@param assignments: Dictionary mapping assigned variables to their
current assumed value
@type assignments: dict
@return: Boolean value stating if this constraint is currently
broken or not
@rtype: bool
"""
unassignedvariable = _unassigned
for variable in variables:
if variable not in assignments:
if unassignedvariable is _unassigned:
unassignedvariable = variable
else:
break
else:
if unassignedvariable is not _unassigned:
# Remove from the unassigned variable domain's all
# values which break our variable's constraints.
domain = domains[unassignedvariable]
if domain:
for value in domain[:]:
assignments[unassignedvariable] = value
if not self(variables, domains, assignments):
domain.hideValue(value)
del assignments[unassignedvariable]
if not domain:
return False
return True
class FunctionConstraint(Constraint):
"""
Constraint which wraps a function defining the constraint logic
Examples:
>>> problem = Problem()
>>> problem.addVariables(["a", "b"], [1, 2])
>>> def func(a, b):
... return b > a
>>> problem.addConstraint(func, ["a", "b"])
>>> problem.getSolution()
{'a': 1, 'b': 2}
>>> problem = Problem()
>>> problem.addVariables(["a", "b"], [1, 2])
>>> def func(a, b):
... return b > a
>>> problem.addConstraint(FunctionConstraint(func), ["a", "b"])
>>> problem.getSolution()
{'a': 1, 'b': 2}
"""
def __init__(self, func, assigned=True):
"""
@param func: Function wrapped and queried for constraint logic
@type func: callable object
@param assigned: Whether the function may receive unassigned
variables or not
@type assigned: bool
"""
self._func = func
self._assigned = assigned
def __call__(
self,
variables,
domains,
assignments,
forwardcheck=False,
_unassigned=Unassigned,
):
parms = [assignments.get(x, _unassigned) for x in variables]
missing = parms.count(_unassigned)
if missing:
return (self._assigned or self._func(*parms)) and (
not forwardcheck or
missing != 1 or
self.forwardCheck(variables, domains, assignments)
)
return self._func(*parms)
class AllDifferentConstraint(Constraint):
"""
Constraint enforcing that values of all given variables are different
Example:
>>> problem = Problem()
>>> problem.addVariables(["a", "b"], [1, 2])
>>> problem.addConstraint(AllDifferentConstraint())
>>> sorted(sorted(x.items()) for x in problem.getSolutions())
[[('a', 1), ('b', 2)], [('a', 2), ('b', 1)]]
"""
def __call__(
self,
variables,
domains,
assignments,
forwardcheck=False,
_unassigned=Unassigned,
):
seen = {}
for variable in variables:
value = assignments.get(variable, _unassigned)
if value is not _unassigned:
if value in seen:
return False
seen[value] = True
if forwardcheck:
for variable in variables:
if variable not in assignments:
domain = domains[variable]
for value in seen:
if value in domain:
domain.hideValue(value)
if not domain:
return False
return True
class AllEqualConstraint(Constraint):
"""
Constraint enforcing that values of all given variables are equal
Example:
>>> problem = Problem()
>>> problem.addVariables(["a", "b"], [1, 2])
>>> problem.addConstraint(AllEqualConstraint())
>>> sorted(sorted(x.items()) for x in problem.getSolutions())
[[('a', 1), ('b', 1)], [('a', 2), ('b', 2)]]
"""
def __call__(
self,
variables,
domains,
assignments,
forwardcheck=False,
_unassigned=Unassigned,
):
singlevalue = _unassigned
for variable in variables:
value = assignments.get(variable, _unassigned)
if singlevalue is _unassigned:
singlevalue = value
elif value is not _unassigned and value != singlevalue:
return False
if forwardcheck and singlevalue is not _unassigned:
for variable in variables:
if variable not in assignments:
domain = domains[variable]
if singlevalue not in domain:
return False
for value in domain[:]:
if value != singlevalue:
domain.hideValue(value)
return True
class MaxSumConstraint(Constraint):
"""
Constraint enforcing that values of given variables sum up to
a given amount
Example:
>>> problem = Problem()
>>> problem.addVariables(["a", "b"], [1, 2])
>>> problem.addConstraint(MaxSumConstraint(3))
>>> sorted(sorted(x.items()) for x in problem.getSolutions())
[[('a', 1), ('b', 1)], [('a', 1), ('b', 2)], [('a', 2), ('b', 1)]]
"""