-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgorithms.py
More file actions
369 lines (290 loc) · 11.4 KB
/
algorithms.py
File metadata and controls
369 lines (290 loc) · 11.4 KB
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
from collections import defaultdict
from itertools import permutations
from typing import Generator
from naive import normalForm
from model import *
from utils import *
Solution = dict[Variable, Variable]
SizeClassMap = defaultdict[int, list[Type]]
def comparePlain(t: Type, s: Type) -> Renaming | None:
t = normalForm(t)
s = normalForm(s)
solution = PlainSolve([Constraint(t, s)], {})
if solution is None:
return None
return Renaming([[a, b] for a, b in solution.items()])
def compareSizeCount(t: Type, s: Type) -> Renaming | None:
t = normalForm(t)
s = normalForm(s)
solution = SizeCountSolve([Constraint(t, s)], {})
if solution is None:
return None
return Renaming([[a, b] for a, b in solution.items()])
def compareConstrProp(t: Type, s: Type) -> Renaming | None:
t = normalForm(t)
s = normalForm(s)
solution = ConstrPropSolve([Constraint(t, s)], {})
if solution is None:
return None
return Renaming([[a, b] for a, b in solution.items()])
def compareConstrPropSizeCount(t: Type, s: Type) -> Renaming | None:
t = normalForm(t)
s = normalForm(s)
solution = SizeCountConstrPropSolve([Constraint(t, s)], {})
if solution is None:
return None
return Renaming([[a, b] for a, b in solution.items()])
def applySolution(C: list[VariableConstraint], S: Solution) -> bool:
for c in C:
for a in list(c.left):
if a in S:
try: c.right.remove(S[a])
except ValueError: return False
c.left.remove(a)
return True
@dataclass
class Occurrence:
var: Variable
used: bool = False
# constraint: VariableConstraint
@dataclass
class AllowedVariable:
var: Variable
evidence: list[Occurrence]
def __eq__(self, other: 'AllowedVariable') -> bool:
return self.var == other.var
def __hash__(self) -> int:
return hash(self.var)
AllowedMap = dict[Variable, set[Variable]]
AllowedList = list[tuple[Variable, set[AllowedVariable]]]
def propagationCase(c: VariableConstraint, C: list[Constraint], S: Solution) -> Solution | None:
allowed: dict[Variable, set[AllowedVariable]] = {}
if not applySolution([c] + C, S): #type: ignore
return None
occurrences: list[list[Occurrence]] = []
# constraints: list[tuple[set[Variable], set[AllowedVariable]]] = []
for constr in c, *C:
assert isinstance(constr, VariableConstraint)
occurrences.append([Occurrence(var) for var in constr.right])
# for v in c.left:
# # guaranteed that v was never here before
# allowed[v] = set(AllowedVariable(var, ) for var in c.right)
for constr, occs in zip([c] + C, occurrences):
assert isinstance(constr, VariableConstraint)
for v in constr.left:
if v not in allowed:
allowed[v] = set(AllowedVariable(occ.var, [occ]) for occ in occs)
else:
# find intersection
for allowedVar in allowed[v].copy():
if allowedVar.var not in constr.right:
allowed[v].remove(allowedVar)
else:
for occ in occs:
if occ.var == allowedVar.var:
allowedVar.evidence.append(occ)
break
else: assert False
# allowed[v].intersection(varConstr.right)
# allowed[v].intersection_update(varConstr.right)
allowedList = sorted(allowed.items(), key=lambda item: len(item[1]))
solution = solveVariableConstraints(allowedList) # type: ignore
if solution is None: return None
assert len(solution) == len(allowedList)
S.update({k[0]: v for k, v in zip(allowedList, solution)})
return S
def solveVariableConstraints(allowed: AllowedList) -> list[Variable] | None:
if not allowed:
return []
(a, allowedVars), *allowed = allowed
if not allowedVars:
# conflicting constraints on v
return None
def isTaken(allowedVar: AllowedVariable) -> bool:
for occ in allowedVar.evidence:
if occ.used:
return True
return False
for allowedVar in allowedVars:
if isTaken(allowedVar):
continue
for occ in allowedVar.evidence:
occ.used = True
solution = solveVariableConstraints(allowed)
if solution is not None:
return [allowedVar.var] + solution
for occ in allowedVar.evidence:
occ.used = False
return None
def SizeCountConstrPropSolve(C: list[Constraint], S: Solution) -> Solution | None:
if not C:
return S
c, *C1 = C
# propagation step
if isinstance(c, VariableConstraint):
return propagationCase(c, C1, S)
match c.left, c.right:
case Variable(_) as a, Variable(_) as b:
if a not in S:
S1 = dict(S)
S1[a] = b
return SizeCountConstrPropSolve(C1, S1)
elif S[a] == b:
return SizeCountConstrPropSolve(C1, S)
else:
return None
case Arrow(l1, r1), Arrow(l2, r2):
return SizeCountConstrPropSolve([Constraint(l1, l2), Constraint(r1, r2)] + C1, S)
case Intersection(types1), Intersection(types2):
if len(types1) != len(types2):
return None
if not types1:
return SizeCountConstrPropSolve(C1, S)
varBound = getVarBound(types1, types2)
if varBound is None: return None
if varBound != 0:
varConstr = VariableConstraint(types1[:varBound], types2[:varBound]) # type: ignore
C1.append(varConstr)
if varBound == len(types1):
return SizeCountConstrPropSolve(C1, S)
types1 = types1[varBound:]
types2 = types2[varBound:]
gen = sizeSplit(types1, types2)
if gen is None: return None
for constraints in gen:
S1 = SizeCountConstrPropSolve(constraints + C1, S)
if S1 is not None:
return S1
return None
def ConstrPropSolve(C: list[Constraint], S: Solution) -> Solution | None:
if not C:
return S
c, *C1 = C
# propagation step
if isinstance(c, VariableConstraint):
return propagationCase(c, C1, S)
match c.left, c.right:
case Variable(_) as a, Variable(_) as b:
if a not in S:
S1 = dict(S)
S1[a] = b
return ConstrPropSolve(C1, S1)
elif S[a] == b:
return ConstrPropSolve(C1, S)
else:
return None
case Arrow(l1, r1), Arrow(l2, r2):
return ConstrPropSolve([Constraint(l1, l2), Constraint(r1, r2)] + C1, S)
case Intersection(types1), Intersection(types2):
if len(types1) != len(types2):
return None
if not types1:
return ConstrPropSolve(C1, S)
varBound = getVarBound(types1, types2)
if varBound is None: return None
if varBound != 0:
varConstr = VariableConstraint(types1[:varBound], types2[:varBound]) # type: ignore
C1.append(varConstr)
if varBound == len(types1):
return ConstrPropSolve(C1, S)
types1 = types1[varBound:]
types2 = types2[varBound:]
# constr = [Constraint(
# Intersection(types1[varBound:]),
# Intersection(types2[varBound:])
# )] if varBound != len(types1) else []
# return solveWithConstraintProp(constr + C1 + [varConstr], S)
for p in permutations(types2):
S1 = ConstrPropSolve([Constraint(t1, t2) for t1, t2 in zip(types1, p)] + C1, S)
if S1 is not None:
return S1
return None
def getVarBound(types1: list[Type], types2: list[Type]) -> int | None:
varBound = 0
for v1, v2 in zip(types1, types2):
if isinstance(v1, Variable) and isinstance(v2, Variable):
varBound += 1
elif not isinstance(v1, Variable) and not isinstance(v2, Variable):
return varBound
else:
return None
return varBound
def sizeSplit(types1: list[Type], types2: list[Type]) -> Generator[list[Constraint], None, None]:
sizeClasses1: SizeClassMap = defaultdict(list)
for t in types1:
sizeClasses1[typeSize(t)].append(t)
sizeClasses2: SizeClassMap = defaultdict(list)
for t in types2:
sizeClasses2[typeSize(t)].append(t)
# first big divider
if sizeClasses1.keys() != sizeClasses2.keys():
return None
# second big divider
for s, types in sizeClasses1.items():
if len(types) != len(sizeClasses2[s]):
return None
def getConstraints(sizes: list[int]) -> Generator[list[Constraint], None, None]:
if not sizes:
yield []
return
size, *sizes = sizes
class1 = sizeClasses1[size]
for p in permutations(sizeClasses2[size]):
for constraints in getConstraints(sizes):
yield [Constraint(t1, t2) for t1, t2 in zip(class1, p)] \
+ constraints
yield from getConstraints(list(sizeClasses1.keys()))
def SizeCountSolve(C: list[Constraint], S: Solution) -> Solution | None:
if not C:
return S
c, *C1 = C
match c.left, c.right:
case Variable(_) as a, Variable(_) as b:
if a not in S:
S1 = dict(S)
S1[a] = b
return SizeCountSolve(C1, S1)
elif S[a] == b:
return SizeCountSolve(C1, S)
else:
return None
case Arrow(l1, r1), Arrow(l2, r2):
return SizeCountSolve([Constraint(l1, l2), Constraint(r1, r2)] + C1, S)
case Intersection(types1), Intersection(types2):
if len(types1) != len(types2):
return None
if not types1:
return SizeCountSolve(C1, S)
gen = sizeSplit(types1, types2)
if gen is None: return None
for constraints in gen:
S1 = SizeCountSolve(constraints + C1, S)
if S1 is not None:
return S1
return None
def PlainSolve(C: list[Constraint], S: Solution) -> Solution | None:
if not C:
return S
c, *C1 = C
match c.left, c.right:
case Variable(_) as a, Variable(_) as b:
if a not in S:
S1 = dict(S)
S1[a] = b
return PlainSolve(C1, S1)
elif S[a] == b:
return PlainSolve(C1, S)
else:
return None
case Arrow(l1, r1), Arrow(l2, r2):
return PlainSolve([Constraint(l1, l2), Constraint(r1, r2)] + C1, S)
case Intersection(types1), Intersection(types2):
if len(types1) != len(types2):
return None
if not types1:
return PlainSolve(C1, S)
for p in permutations(types2):
S1 = PlainSolve([Constraint(t1, t2) for t1, t2 in zip(types1, p)] + C1, S)
if S1 is not None:
return S1
return None