-
Notifications
You must be signed in to change notification settings - Fork 22
/
solver.py
208 lines (176 loc) · 7.04 KB
/
solver.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
"""Constraint solver allows to define constraint between two or more different
variables and keep this constraint always true when one or more of the
constrained variables change. For example, one may want to keep two variables
always equal.
Variables change and at some point of time we want to make all
constraints valid again. This process is called solving constraints.
Gaphas' solver allows to define constraints between Variable
instances. Constraint classes are defined in `gaphas.constraint`
module.
How It Works
------------
Every constraint contains list of variables and has to be registered
in solver object. Variables change (`Variable.dirty()`,
`Solver.request_resolve()` methods) and their constraints are marked
by solver as dirty. To solve constraints, solver loops through dirty
constraints and asks constraint for
a variable (called weakest variable), which
- has the lowest strength
- or if there are many variables with the same, lowest strength value
return first unchanged variable with lowest strength
- or if there is no unchanged, then return the first changed with the
lowest strength
(weakest variable invariants defined above)
Having weakest variable (`constraint.Constraint.weakest()` method)
every constraint is being asked to solve itself
(`constraint.Constraint.solve_for()` method) changing appropriate
variables to make the constraint valid again.
"""
import functools
from typing import Callable, Collection, List, Optional, Set
from gaphas.solver.constraint import Constraint, ContainsConstraints
class Solver:
"""Solve constraints.
A constraint should have accompanying variables.
"""
def __init__(self, resolve_limit: int = 16) -> None:
# a dict of constraint -> name/variable mappings
self._constraints: Set[Constraint] = set()
self._marked_cons: List[Constraint] = []
self._solving = False
self._resolve_limit = resolve_limit
self._handlers: Set[Callable[[Constraint], None]] = set()
def add_handler(self, handler: Callable[[Constraint], None]) -> None:
"""Add a callback handler, triggered when a constraint is resolved."""
self._handlers.add(handler)
def remove_handler(self, handler: Callable[[Constraint], None]) -> None:
"""Remove a previously assigned handler."""
self._handlers.discard(handler)
def _notify(self, constraint: Constraint) -> None:
my_constraint = self._find_containing_constraint(constraint)
for handler in self._handlers:
handler(my_constraint)
@functools.lru_cache()
def _find_containing_constraint(self, constraint: Constraint) -> Constraint:
return find_containing_constraint(constraint, self._constraints) or constraint
@property
def constraints(self) -> Collection[Constraint]:
return self._constraints
def add_constraint(self, constraint: Constraint) -> Constraint:
"""Add a constraint. The actual constraint is returned, so the
constraint can be removed later on.
Example:
>>> from gaphas.constraint import EquationConstraint
>>> s = Solver()
>>> a, b = Variable(), Variable(2.0)
>>> s.add_constraint(EquationConstraint(lambda a, b: a -b, a=a, b=b))
EquationConstraint(<lambda>, a=Variable(0, 20), b=Variable(2, 20))
>>> len(s._constraints)
1
>>> a.value
0.0
>>> b.value
2.0
>>> len(s._constraints)
1
"""
assert constraint, f"No constraint ({constraint})"
self._constraints.add(constraint)
self._marked_cons.append(constraint)
constraint.add_handler(self.request_resolve_constraint)
return constraint
def remove_constraint(self, constraint: Constraint) -> None:
"""Remove a constraint from the solver.
>>> from gaphas.constraint import EquationConstraint
>>> s = Solver()
>>> a, b = Variable(), Variable(2.0)
>>> c = s.add_constraint(EquationConstraint(lambda a, b: a -b, a=a, b=b))
>>> c
EquationConstraint(<lambda>, a=Variable(0, 20), b=Variable(2, 20))
>>> s.remove_constraint(c)
>>> s._marked_cons
[]
>>> s._constraints
set()
Removing a constraint twice has no effect:
>>> s.remove_constraint(c)
"""
assert constraint, f"No constraint ({constraint})"
constraint.remove_handler(self.request_resolve_constraint)
self._constraints.discard(constraint)
while constraint in self._marked_cons:
self._marked_cons.remove(constraint)
def request_resolve_constraint(self, c: Constraint) -> None:
"""Request resolving a constraint."""
if not self._solving:
if c in self._marked_cons:
self._marked_cons.remove(c)
self._marked_cons.append(c)
elif self._marked_cons.count(c) < self._resolve_limit:
self._marked_cons.append(c)
@property
def needs_solving(self) -> bool:
"""Return if there are constraints that need solving."""
return bool(self._marked_cons)
def solve(self) -> None: # sourcery skip: while-to-for
"""
Example:
>>> from gaphas.constraint import EquationConstraint
>>> a, b, c = Variable(1.0), Variable(2.0), Variable(3.0)
>>> s = Solver()
>>> s.add_constraint(EquationConstraint(lambda a,b: a+b, a=a, b=b))
EquationConstraint(<lambda>, a=Variable(1, 20), b=Variable(2, 20))
>>> a.value = 5.0
>>> s.solve()
>>> len(s._marked_cons)
0
>>> b._value
-5.0
>>> s.add_constraint(EquationConstraint(lambda a,b: a+b, a=b, b=c))
EquationConstraint(<lambda>, a=Variable(-5, 20), b=Variable(3, 20))
>>> len(s._constraints)
2
>>> len(s._marked_cons)
1
>>> b._value
-5.0
>>> s.solve()
>>> b._value
-3.0
>>> a.value = 10
>>> s.solve()
>>> c._value
10.0
"""
# NB. marked_cons is updated during the solving process
marked_cons = self._marked_cons
notify = self._notify
try:
self._solving = True
# Solve each constraint. Using a counter makes it
# possible to also solve constraints that are marked as
# a result of other variables being solved.
# sourcery: skip
n = 0
while n < len(marked_cons):
c = marked_cons[n]
c.solve()
notify(c)
n += 1
self._marked_cons = []
finally:
self._solving = False
def find_containing_constraint(
constraint: Constraint, constraints: Collection[Constraint]
) -> Optional[Constraint]:
if constraint in constraints:
return constraint
return next(
(
find_containing_constraint(cs, constraints)
for cs in constraints
if isinstance(cs, ContainsConstraints)
and find_containing_constraint(constraint, cs.constraints)
),
None,
)