-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinterval.py
More file actions
472 lines (389 loc) · 14.2 KB
/
interval.py
File metadata and controls
472 lines (389 loc) · 14.2 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
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
import sys
from z3 import And, IntVal, Int, BoolVal
MINF = "minf"
INF = "inf"
MAXINT = sys.maxsize
MININT = -sys.maxsize - 1
# _UBOT = u'\u27d8'.encode("utf-8")
# _UTOP = u'\u27d9'.encode("utf-8")
# _UINF = u'\u221E'.encode("utf-8")
# _UIN = u'\u220A'.encode("utf-8")
_UBOT = "<bottom>"
_UTOP = "<top>"
_UINF = "<infinity>"
_UIN = "in"
def inf_str_to_number(st):
assert isinstance(st, str) and (st == INF or st == MINF)
if st == INF:
return MAXINT
else:
return MININT
class IntervalBorder:
def __init__(self, n):
assert (isinstance(n, int) or n == MINF or n == INF)
self.n = n
def __str__(self):
if isinstance(self.n, int):
return str(self.n)
if self.n == MINF:
return "-" + _UINF
return _UINF
def __repr__(self):
return str(self)
def __eq__(self, other):
if isinstance(self.n, int):
if isinstance(other, int):
return self.n == other
elif isinstance(other, IntervalBorder) and isinstance(other.n, int):
return self.n == other.n
else:
return False
else:
assert self.n == MINF or self.n == INF
if isinstance(other, str):
return self.n == other
elif isinstance(other, IntervalBorder) and isinstance(other.n, str):
return self.n == other.n
else:
return False
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
assert (isinstance(other, int) or isinstance(other, IntervalBorder) or other == MINF or other == INF)
if (isinstance(other, str) and other == MINF) or (isinstance(other, IntervalBorder) and other.n == MINF):
return False
if isinstance(self.n, str) and self.n == MINF:
return True
if isinstance(self.n, str) and self.n == INF:
return False
if (isinstance(other, str) and other == INF) or (isinstance(other, IntervalBorder) and other.n == INF):
return True
assert isinstance(self.n, int) and (isinstance(other, int) or isinstance(other, IntervalBorder))
if isinstance(other, int):
return self.n < other
else:
return self.n < other.n
def __gt__(self, other):
assert (isinstance(other, int) or isinstance(other, IntervalBorder) or other == MINF or other == INF)
if (isinstance(other, str) and other == INF) or (isinstance(other, IntervalBorder) and other.n == INF):
return False
if isinstance(self.n, str) and self.n == INF:
return True
if isinstance(self.n, str) and self.n == MINF:
return False
if (isinstance(other, str) and other == MINF) or (isinstance(other, IntervalBorder) and other.n == MINF):
return True
assert isinstance(self.n, int) and (isinstance(other, int) or isinstance(other, IntervalBorder))
if isinstance(other, int):
return self.n > other
else:
return self.n > other.n
def __le__(self, other):
return self.__lt__(other) or self.__eq__(other)
def __ge__(self, other):
return self.__gt__(other) or self.__eq__(other)
def is_inf(self):
return isinstance(self.n, str) and self.n == INF
def is_minf(self):
return isinstance(self.n, str) and self.n == MINF
def __radd__(self, other):
other_is_int = isinstance(other, int)
self_is_int = isinstance(self.n, int)
assert (other_is_int or other == MINF or other == INF)
# Can't add MINF to INF and vice versa
assert not (not other_is_int and not self_is_int and self.n == INF and other == MINF)
assert not (not other_is_int and not self_is_int and self.n == MINF and other == INF)
if (not self_is_int and self.n == MINF) or (not other_is_int and other == MINF):
return inf_str_to_number(MINF)
if (not self_is_int and self.n == INF) or (not other_is_int and other == INF):
return inf_str_to_number(INF)
else:
return self.n + other
def __sub__(self, other):
other_is_int = isinstance(other, int)
self_is_int = isinstance(self.n, int)
assert (other_is_int or other == MINF or other == INF)
# Can't subtract INF from INF or MINF from MINF
assert not (not other_is_int and not self_is_int and self.n == INF and other == INF)
assert not (not other_is_int and not self_is_int and self.n == MINF and other == MINF)
if (not other_is_int and other == MINF) or (not self_is_int and self.n == INF):
return inf_str_to_number(INF)
elif (not other_is_int and other == INF) or (not self_is_int and self.n == MINF):
return inf_str_to_number(MINF)
else:
return self.n - other
def __add__(self, other):
return self.__radd__(other)
def add(self, other):
assert isinstance(other, IntervalBorder)
return self.n + other
def __neg__(self):
if isinstance(self.n, int):
return -self.n
elif self.n == INF:
return -inf_str_to_number(INF)
else:
return inf_str_to_number(INF)
def get_value(self):
assert not self.is_inf() and not self.is_minf()
return self.n
class Interval:
# def __init__(self, low, high):
# assert (isinstance(low, int) or isinstance(low, IntervalBorder) or low == MINF)
# assert (isinstance(high, int) or isinstance(high, IntervalBorder) or high == INF)
# if isinstance(low, IntervalBorder):
# self.low = IntervalBorder(low.n)
# else:
# self.low = IntervalBorder(low)
# if isinstance(high, IntervalBorder):
# self.high = IntervalBorder(high.n)
# else:
# self.high = IntervalBorder(high)
def __init__(self, low, high):
assert (isinstance(low, int) or low == MINF)
assert (isinstance(high, int) or high == INF)
self.low = IntervalBorder(low)
self.high = IntervalBorder(high)
def __str__(self):
l = str(self.low)
h = str(self.high)
if self.is_bottom():
return _UBOT
return "[" + l + "," + h + "]"
def __repr__(self):
return str(self)
def is_bottom(self):
return self.high < self.low
def is_top(self):
return self.low.is_minf() and self.high.is_inf()
@staticmethod
def get_bottom():
return Interval(1,-1)
@staticmethod
def get_top():
return Interval(MINF,INF)
def is_infinite(self):
return self.low.is_minf() or self.high.is_inf()
def is_high_inf(self):
return self.high.is_inf()
def is_low_minf(self):
return self.low.is_minf()
def __len__(self):
if self.is_bottom():
return 0
elif self.is_infinite():
return inf_str_to_number(INF)
else:
assert isinstance(self.low.n, int) and isinstance(self.high.n, int)
return self.high.n - self.low.n
def len_string(self):
if self.is_infinite():
return INF
else:
return str(len(self))
@staticmethod
def intersection(intervals):
max_low = max([i.low for i in intervals])
min_high = min([i.high for i in intervals])
return Interval(max_low.n, min_high.n)
def intersect(self, other):
"""Returns a new interval which is the result of the intersection of self and other."""
return Interval.intersection([self,other])
def __eq__(self, other):
assert isinstance(other, Interval)
if self.is_bottom() and other.is_bottom():
return True
return self.low == other.low and self.high == other.high
def __ne__(self, other):
return not self == other
def get_all_values_generator(self):
assert not self.is_top()
if self.is_high_inf():
n = self.low
while True:
yield n
n = n + 1
elif self.is_low_minf():
n = self.high
while True:
yield n
n = n - 1
else:
n = self.low
while n <= self.high:
yield n
n = n + 1
def is_value_in_range(self, value):
assert isinstance(value, int)
# Chained operators in Python: https://www.geeksforgeeks.org/chaining-comparison-operators-python/
return self.low <= value <= self.high
def get_high_value(self):
assert not self.is_high_inf()
return self.high.get_value()
def get_low_value(self):
assert not self.is_low_minf()
return self.low.get_value()
class IntervalSet:
def __init__(self, intervals):
self.dict = intervals
def __str__(self):
if self.is_top():
return _UTOP
if self.is_bottom():
return _UBOT
res = ""
for k in self.dict.keys():
v = self.dict[k]
res = res + str(k) + ":" + str(v) + " "
return res
def __repr__(self):
return str(self)
def __contains__(self, item):
return item.get_id() in self.dict
def get_interval(self, var):
if var.get_id() in self.dict:
return self.dict[var.get_id()]
else:
return IntervalSet.get_top()
def is_top(self):
return len(self.dict) == 0
def is_bottom(self):
return any([v.is_bottom() for v in self.dict.values()])
@staticmethod
def get_top():
return IntervalSet({})
@staticmethod
def get_bottom():
return IntervalSet({"bottom_var":Interval(4, 3)})
def intersect(self, other):
"""
The result of the intersection of self and other is stored in self
:param other: another @IntervalSet to perform intersection with
:return: None
"""
for var in other.dict.keys():
if var in self.dict.keys():
self.dict[var] = Interval.intersection([self.dict[var],other.dict[var]])
else:
self.dict[var] = other.dict[var]
@staticmethod
def intersection(intervalsets):
res = IntervalSet.get_top()
for intervalset in intervalsets:
res.intersect(intervalset)
return res
def __eq__(self, other):
return self.dict == other.dict
def __ne__(self, other):
return not self.__eq__(other)
def add_interval(self, var, interval):
var_key = var.get_id()
if interval.is_top():
return
elif var_key not in self.dict.keys():
self.dict[var_key] = interval
else: #var in self.dict.keys()
self.dict[var_key] = self.dict[var_key].intersect(interval)
def print_all_values(self, limit = 100):
if self.is_bottom():
print("No solutions available.")
return
if self.is_top():
print("All variables can obtain all values.")
return
res = []
limit_fake_list = [limit]
remaining_vars = self.dict.keys()
remaining_len = len(self.dict.keys())
self._print_all_values_aux(limit_fake_list, res, remaining_vars, remaining_len)
return limit - limit_fake_list[0]
def _print_all_values_aux(self, limit, res, remaining_vars, remaining_len):
if remaining_len == 0:
limit[0] = limit[0] - 1
print res
if limit[0] == 0:
print("Max number of solutions reached")
return
v = remaining_vars[0]
for val in self.dict[v].get_all_values_generator():
res.append(str(v)+"=="+str(val))
self._print_all_values_aux(limit, res, remaining_vars[1:], remaining_len - 1)
if limit[0] == 0:
return
res.pop()
def as_formula(self):
if self.is_top():
return BoolVal(True)
if self.is_bottom():
return BoolVal(False)
constraints = []
for var in self.dict.keys():
interval = self.dict[var]
if not interval.is_high_inf():
constraints.append(Int(var) <= IntVal(interval.high.n))
if not interval.is_low_minf():
constraints.append(Int(var) >= IntVal(interval.low.n))
return And(constraints)
def evaluate_under_model_using_formula(self, model):
return model.evaluate(self.as_formula())
def evaluate_under_model_using_intervals(self, model):
if self.is_bottom():
return False
if self.is_top():
return True
for var in model.decls():
if var.name() in self.dict.keys():
if not self.dict[var.name()].is_value_in_range(model[var].as_long()):
return False
return True
# Var should be the variable itself and not its name (e.g., x in "x=Int('x')")
def is_variable_in_range(self, var, value):
if self.is_bottom():
return False
if var.get_id() in self.dict.keys():
interval = self.dict[var.get_id()]
return interval.is_value_in_range(value)
else:
return True
# Var should be the variable itself and not its name (e.g., x in "x=Int('x')")
def delete_interval(self, var):
if self.is_bottom():
return
if var.get_id() in self.dict:
del self.dict[var.get_id()]
def max_of_two_with_minf(n, m):
if isinstance(n, str):
assert n == MINF
return m
elif isinstance(m, str):
assert m == MINF
return n
else:
assert isinstance(n, int) and isinstance(m, int)
if n > m:
return n
else:
return m
def max_with_minf(numbers):
max = MINF
for n in numbers:
max = max_of_two_with_minf(max, n)
return max
def min_of_two_with_inf(n, m):
if isinstance(n, str):
assert n == INF
return m
elif isinstance(m, str):
assert m == INF
return n
else:
# assert isinstance(n, int) and isinstance(m, int)
if n < m:
return n
else:
return m
def min_with_inf(numbers):
min = INF
for n in numbers:
min = min_of_two_with_inf(min, n)
return min