-
Notifications
You must be signed in to change notification settings - Fork 0
/
csp.py
139 lines (120 loc) · 5.71 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
#!/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
from heuristics import variable_heuristic, value_heuristic
from constraint import Solver
class HeuristicRecursiveBacktrackingSolver(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, value_heuristic_id=None, variable_heuristic_id=None, forwardcheck=True):
"""
@param variable_heuristic: string identifier of the variable heuristic to use
choose from {degree, mrv, random, deg+mrv, mrv+random}
leave blank for no variable heuristic
@param value_heuristic: string identifier of the value heruistic to use
choose from {random, lcv, least_used}
leave blank for no value heuristic
@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
self._variable_heuristic_id = variable_heuristic_id
self._value_heuristic_id = value_heuristic_id
def recursiveBacktracking(
self, solutions, domains, vconstraints, assignments, single
):
# assignments is a dictionary of {variable: value, ...}
##############################################################
# Use different heuristics for selecting unassigned variable #
##############################################################
lst = variable_heuristic(domains, vconstraints, self._variable_heuristic_id)
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 #
################################################
newlst = value_heuristic(assignments, domains, domains[variable], self._value_heuristic_id)
for value in newlst:
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)