python-constraint2 2.7.0__cp313-cp313-win_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
constraint/problem.py ADDED
@@ -0,0 +1,304 @@
1
+ """Module containing the code for problem definitions."""
2
+
3
+ import copy
4
+ from collections.abc import Callable, Hashable, Sequence
5
+ from operator import itemgetter
6
+ from warnings import warn
7
+
8
+ from constraint.constraints import CompilableFunctionConstraint, Constraint, FunctionConstraint
9
+ from constraint.domain import Domain
10
+ from constraint.parser import compile_to_constraints
11
+ from constraint.solvers import OptimizedBacktrackingSolver, ParallelSolver, Solver
12
+
13
+ try:
14
+ from sys import _is_gil_enabled
15
+ freethreading = _is_gil_enabled()
16
+ except ImportError:
17
+ freethreading = False
18
+
19
+
20
+ class Problem:
21
+ """Class used to define a problem and retrieve solutions."""
22
+
23
+ def __init__(self, solver: Solver=None):
24
+ """Initialization method.
25
+
26
+ Args:
27
+ solver (instance of a :py:class:`Solver`): Problem solver (default :py:class:`OptimizedBacktrackingSolver`)
28
+ """
29
+ self._solver = solver or OptimizedBacktrackingSolver()
30
+ self._constraints: list[tuple[Constraint, any]] = []
31
+ self._str_constraints: list[str] = []
32
+ self._variables: dict[Hashable, Domain] = {}
33
+
34
+ # check if solver is instance instead of class
35
+ assert isinstance(self._solver, Solver), f"`solver` is not instance of Solver class (is {type(self._solver)})."
36
+
37
+ # warn for experimental parallel solver
38
+ if isinstance(self._solver, ParallelSolver):
39
+ warn("ParallelSolver is currently experimental, and unlikely to be faster than OptimizedBacktrackingSolver. Please report any issues.") # future: remove # noqa E501
40
+ if not self._solver._process_mode and not freethreading:
41
+ warn("Using the ParallelSolver in ThreadPool mode without freethreading will cause poor performance.")
42
+
43
+ def reset(self):
44
+ """Reset the current problem definition.
45
+
46
+ Example:
47
+ >>> problem = Problem()
48
+ >>> problem.addVariable("a", [1, 2])
49
+ >>> problem.reset()
50
+ >>> problem.getSolution()
51
+ >>>
52
+ """
53
+ del self._constraints[:]
54
+ self._variables.clear()
55
+
56
+ def setSolver(self, solver):
57
+ """Change the problem solver currently in use.
58
+
59
+ Example:
60
+ >>> solver = OptimizedBacktrackingSolver()
61
+ >>> problem = Problem(solver)
62
+ >>> problem.getSolver() is solver
63
+ True
64
+
65
+ Args:
66
+ solver (instance of a :py:class:`Solver`): New problem
67
+ solver
68
+ """
69
+ self._solver = solver
70
+
71
+ def getSolver(self):
72
+ """Obtain the problem solver currently in use.
73
+
74
+ Example:
75
+ >>> solver = OptimizedBacktrackingSolver()
76
+ >>> problem = Problem(solver)
77
+ >>> problem.getSolver() is solver
78
+ True
79
+
80
+ Returns:
81
+ instance of a :py:class:`Solver` subclass: Solver currently in use
82
+ """
83
+ return self._solver
84
+
85
+ def addVariable(self, variable: Hashable, domain):
86
+ """Add a variable to the problem.
87
+
88
+ Example:
89
+ >>> problem = Problem()
90
+ >>> problem.addVariable("a", [1, 2])
91
+ >>> problem.getSolution() in ({'a': 1}, {'a': 2})
92
+ True
93
+
94
+ Args:
95
+ variable (hashable object): Object representing a problem
96
+ variable
97
+ domain (list, tuple, set, or instance of :py:class:`Domain`): Set of items
98
+ defining the possible values that the given variable may
99
+ assume
100
+ """
101
+ if variable in self._variables:
102
+ msg = f"Tried to insert duplicated variable {repr(variable)}"
103
+ raise ValueError(msg)
104
+ if not isinstance(variable, (list, tuple, Domain)) and not hasattr(domain, "__getitem__"):
105
+ domain = list(domain)
106
+ if isinstance(domain, Domain):
107
+ domain = copy.deepcopy(domain)
108
+ elif hasattr(domain, "__getitem__"):
109
+ domain = Domain(domain)
110
+ else:
111
+ msg = "Domains must be instances of subclasses of the Domain class"
112
+ raise TypeError(msg)
113
+ if not domain:
114
+ raise ValueError("Domain is empty")
115
+ self._variables[variable] = domain
116
+
117
+ def addVariables(self, variables: Sequence, domain):
118
+ """Add one or more variables to the problem.
119
+
120
+ Example:
121
+ >>> problem = Problem()
122
+ >>> problem.addVariables(["a", "b"], [1, 2, 3])
123
+ >>> solutions = problem.getSolutions()
124
+ >>> len(solutions)
125
+ 9
126
+ >>> {'a': 3, 'b': 1} in solutions
127
+ True
128
+
129
+ Args:
130
+ variables (sequence of hashable objects): Any object
131
+ containing a sequence of objects represeting problem
132
+ variables
133
+ domain (list, tuple, or instance of :py:class:`Domain`): Set of items
134
+ defining the possible values that the given variables
135
+ may assume
136
+ """
137
+ for variable in variables:
138
+ self.addVariable(variable, domain)
139
+
140
+ def addConstraint(self, constraint: Constraint | Callable | str, variables: Sequence | None = None):
141
+ """Add a constraint to the problem.
142
+
143
+ Example:
144
+ >>> problem = Problem()
145
+ >>> problem.addVariables(["a", "b"], [1, 2, 3])
146
+ >>> problem.addConstraint(lambda a, b: b == a+1, ["a", "b"])
147
+ >>> problem.addConstraint("b == a+1 and a+b >= 2") # experimental string format, automatically parsed, preferable over callables
148
+ >>> solutions = problem.getSolutions()
149
+ >>>
150
+
151
+ Args:
152
+ constraint (instance of :py:class:`Constraint`, function to be wrapped by :py:class:`FunctionConstraint`, or string expression):
153
+ Constraint to be included in the problem. Can be either a Constraint, a callable (function or lambda), or Python-evaluable string expression that will be parsed automatically.
154
+ variables (set or sequence of variables): :py:class:`Variables` affected
155
+ by the constraint (default to all variables). Depending
156
+ on the constraint type the order may be important.
157
+ """ # noqa: E501
158
+ # compile string constraints (variables argument ignored as it is inferred from the string and may be reordered)
159
+ if isinstance(constraint, str):
160
+ self._str_constraints.append(constraint)
161
+ return
162
+ elif isinstance(constraint, list):
163
+ assert all(isinstance(c, str) for c in constraint), f"Expected constraints to be strings, got {constraint}"
164
+ self._str_constraints.extend(constraint)
165
+ return
166
+
167
+ # add regular constraints
168
+ if not isinstance(constraint, Constraint):
169
+ if callable(constraint):
170
+ # future warn("A function or lambda has been used for a constraint, consider using string constraints")
171
+ constraint = FunctionConstraint(constraint)
172
+ elif isinstance(constraint, str):
173
+ constraint = CompilableFunctionConstraint(constraint)
174
+ else:
175
+ msg = "Constraints must be instances of subclasses " "of the Constraint class"
176
+ raise ValueError(msg)
177
+ self._constraints.append((constraint, variables))
178
+
179
+ def getSolution(self):
180
+ """Find and return a solution to the problem.
181
+
182
+ Example:
183
+ >>> problem = Problem()
184
+ >>> problem.getSolution() is None
185
+ True
186
+ >>> problem.addVariables(["a"], [42])
187
+ >>> problem.getSolution()
188
+ {'a': 42}
189
+
190
+ Returns:
191
+ dictionary mapping variables to values: Solution for the problem
192
+ """
193
+ domains, constraints, vconstraints = self._getArgs(picklable=self._solver.requires_pickling)
194
+ if not domains:
195
+ return None
196
+ return self._solver.getSolution(domains, constraints, vconstraints)
197
+
198
+ def getSolutions(self):
199
+ """Find and return all solutions to the problem.
200
+
201
+ Example:
202
+ >>> problem = Problem()
203
+ >>> problem.getSolutions() == []
204
+ True
205
+ >>> problem.addVariables(["a"], [42])
206
+ >>> problem.getSolutions()
207
+ [{'a': 42}]
208
+
209
+ Returns:
210
+ list of dictionaries mapping variables to values: All solutions for the problem
211
+ """
212
+ domains, constraints, vconstraints = self._getArgs(picklable=self._solver.requires_pickling)
213
+ if not domains:
214
+ return []
215
+ return self._solver.getSolutions(domains, constraints, vconstraints)
216
+
217
+ def getSolutionIter(self):
218
+ """Return an iterator to the solutions of the problem.
219
+
220
+ Example:
221
+ >>> problem = Problem()
222
+ >>> list(problem.getSolutionIter()) == []
223
+ True
224
+ >>> problem.addVariables(["a"], [42])
225
+ >>> iter = problem.getSolutionIter()
226
+ >>> next(iter)
227
+ {'a': 42}
228
+ >>> next(iter)
229
+ Traceback (most recent call last):
230
+ ...
231
+ StopIteration
232
+ """
233
+ domains, constraints, vconstraints = self._getArgs(picklable=self._solver.requires_pickling)
234
+ if not domains:
235
+ return iter(())
236
+ return self._solver.getSolutionIter(domains, constraints, vconstraints)
237
+
238
+ def getSolutionsOrderedList(self, order: list[str] = None) -> list[tuple]:
239
+ """Returns the solutions as a list of tuples, with each solution tuple ordered according to `order`."""
240
+ solutions: list[dict] = self.getSolutions()
241
+ if order is None or len(order) == 1:
242
+ return list(tuple(solution.values()) for solution in solutions)
243
+ get_in_order = itemgetter(*order)
244
+ return list(get_in_order(params) for params in solutions)
245
+
246
+ def getSolutionsAsListDict(
247
+ self, order: list[str] = None, validate: bool = True
248
+ ) -> tuple[list[tuple], dict[tuple, int], int]: # noqa: E501
249
+ """Returns the searchspace as a list of tuples, a dict of the searchspace for fast lookups and the size."""
250
+ solutions_list = self.getSolutionsOrderedList(order)
251
+ size_list = len(solutions_list)
252
+ solutions_dict: dict = dict(zip(solutions_list, range(size_list)))
253
+ if validate:
254
+ # check for duplicates
255
+ size_dict = len(solutions_dict)
256
+ if size_list != size_dict:
257
+ raise ValueError(
258
+ f"{size_list - size_dict} duplicate parameter configurations out of {size_dict} unique.",
259
+ f"Duplicate configs: {list(set([c for c in solutions_list if solutions_list.count(c) > 1]))}",
260
+ f"Constraints: {self._constraints}, {self._str_constraints}"
261
+ )
262
+ return (
263
+ solutions_list,
264
+ solutions_dict,
265
+ size_list,
266
+ )
267
+
268
+ def _getArgs(self, picklable=False):
269
+ domains = self._variables.copy()
270
+ allvariables = domains.keys()
271
+ constraints: list[tuple[Constraint, list]] = []
272
+
273
+ # parse string constraints
274
+ if len(self._str_constraints) > 0:
275
+ # warn("String constraints are a beta feature, please report issues experienced.") # future: remove
276
+ for constraint in self._str_constraints:
277
+ parsed = compile_to_constraints([constraint], domains, picklable=picklable)
278
+ for c, v, _ in parsed:
279
+ self.addConstraint(c, v)
280
+
281
+ # add regular constraints
282
+ for constraint, variables in self._constraints:
283
+ if not variables:
284
+ variables = list(allvariables)
285
+ constraints.append((constraint, variables))
286
+
287
+ # check if there are any precompiled FunctionConstraints when there shouldn't be
288
+ if picklable:
289
+ assert not any(isinstance(c, FunctionConstraint) for c, _ in constraints), f"You have used FunctionConstraints with ParallelSolver(process_mode=True). Please use string constraints instead (see https://python-constraint.github.io/python-constraint/reference.html#constraint.ParallelSolver docs as to why)" # noqa E501
290
+
291
+ vconstraints = {}
292
+ for variable in domains:
293
+ vconstraints[variable] = []
294
+ for constraint, variables in constraints:
295
+ for variable in variables:
296
+ vconstraints[variable].append((constraint, variables))
297
+ for constraint, variables in constraints[:]:
298
+ constraint.preProcess(variables, domains, constraints, vconstraints)
299
+ for domain in domains.values():
300
+ domain.resetState()
301
+ if not domain:
302
+ return None, None, None
303
+ # doArc8(getArcs(domains, constraints), domains, {})
304
+ return domains, constraints, vconstraints