-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
329 lines (276 loc) · 8.92 KB
/
utils.py
File metadata and controls
329 lines (276 loc) · 8.92 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
import sage.all
import sage.symbolic.expression as sym_expr
# Workaround for get() for dictionaries. This function also works for unhashable keys.
# The problem is that Python dictionaries generally require hashable keys.
# If unhashable values are used as keys, they cannot be found again in the dictionary.
# Therefore, the methods provided by Python to get a value corresponding to a key do not work and this workaround is used instead.
def get_helper(key, d):
"""
Takes a possibly unhashable key and a dictionary.
Returns the key and corresponding value if it is in the dictionary, None, None otherwise.
"""
for k in d:
if k == key:
return k, d[k]
return None, None
def zeta(val):
"""Takes a value and returns it divided by its absolute value."""
return val / abs(val)
def to_complex_tuple(z):
"""Takes a number z and returns its real and imaginary part as a 2-tuple."""
if z.is_real() or "x" in str(z) or "g" in str(z):
return (z, 0)
else:
return (z.real(), z.imag())
def add_list_elts(ops):
"""Takes a list of operands, calls s_add on the operands and returns the result."""
if(len(ops)==1):
return ops[0]
else:
return s_add(ops[0], add_list_elts(ops[1::]))
def mult_list_elts(ops):
"""Takes a list of operands, calls s_mult on the operands and returns the result."""
if(len(ops)==1):
return ops[0]
else:
return s_mult(ops[0], mult_list_elts(ops[1::]))
def to_complex_tuples_expr(expr):
"""Takes an expression and returns it as an expression using complex tuples."""
expr = sage.all.expand(expr)
if("x" not in str(expr)): return to_complex_tuple(sym_expr.new_Expression(sage.all.SR, expr))
def go(expr):
ops = expr.operands()
if len(ops) == 0:
return to_complex_tuple(expr)
for i in range(len(ops)):
ops[i] = go(ops[i])
res = None
if expr.operator() == sage.symbolic.operators.mul_vararg:
res = mult_list_elts(ops)
if expr.operator() == sage.symbolic.operators.add_vararg:
res = add_list_elts(ops)
return res
return go(expr)
def conj(z):
"""Takes a value z and returns its conjugate if z is not a variable x_i, otherwise it returns z."""
if "x" in str(z):
return z
else:
return sage.all.conjugate(z)
def s_add(x, y):
"""Takes two complex tuples and returns their sum as a complex tuple."""
xr = x[0]
xi = x[1]
yr = y[0]
yi = y[1]
return (xr + yr, xi + yi)
def s_mult(x, y):
"""Takes two complex tuples and returns their product as a complex tuple."""
xr = x[0]
xi = x[1]
yr = y[0]
yi = y[1]
return (xr * yr - xi * yi, xr * yi + xi * yr)
def s_eq(x, y):
"""
Takes two 2-tuples.
Returns a list of two Booleans where the nth value is True iff the nth component of x and y are equal, otherwise False.
"""
return [x[0]==y[0], x[1]==y[1]]
def s_gr(x, y):
"""
Takes two 2-tuples x and y.
Returns True if the first component of x is greater than the first component of y, otherwise False.
"""
if(x[1] != 0):
print("value should be real")
exit(-1)
return (x[0] > y[0])
def coefficient_to_s_expr(coeff, var):
"""Takes a coefficient and variable name of a polynomial and returns it as an s-expression in form of a string."""
exp = "1"
if coeff[1] > 0:
exp = "(* 1"
for i in range(coeff[1]):
exp += f" {var}"
exp += ")"
negative = False
coeff_smt = coeff[0]
if coeff[0] < 0:
negative = True
coeff_smt = abs(coeff[0])
if not coeff[0].is_integer():
fraction = str(coeff_smt).split("/")
coeff_smt = f"(/ {fraction[0]} {fraction[1]})"
if negative:
return f"(* 1 (- {coeff_smt}) "+ exp +") "
else:
return f"(* 1 {coeff_smt} "+ exp + ") "
def polynomial_to_s_expr(pol, var):
"""Takes a polynomial and a variable name and returns the polynomial as an s-expression in form of a string."""
res = "(+ 0 "
coefficients = pol.coefficients()
for c in coefficients:
res += coefficient_to_s_expr(c, var)
res += ")"
return res
def num_to_s_expr(coeff):
"""Takes a value and returns it as an s-expression in form of a string."""
negative = False
coeff_smt = coeff
if coeff_smt < 0:
negative = True
coeff_smt = abs(coeff_smt)
if coeff_smt in sage.all.QQ:
numerator, denominator = sage.all.QQ(coeff_smt).numerator(), sage.all.QQ(coeff_smt).denominator()
else:
denominator = 1
numerator = sage.all.RR(coeff_smt).str(no_sci=2)
abs_res = f"(/ {numerator} {denominator})"
if negative:
return f"(- {abs_res}) "
else:
return abs_res
def to_s_expr(exprList, operator):
"""Takes an expression list and an encoded arithmetic operator and returns these as an s-expression in form of a string."""
res = "("
match operator:
case 0:
res += "+ 0 "
case 1:
res += "-"
case 2:
res += "* 1 "
case 3:
res += "/"
for e in exprList:
res += " " + str(e)
res += ")"
return res
def get_str_arg_list(str):
"""
Takes string of multiple values seperated by spaces.
Returns list of values while respecting parentheses around values.
E.g., '5 28 (+ 5 8)' -> ['5', '28', '(+ 5 8)']
"""
start = 0
parentheses_counter = 0
arg_without_parantheses = False
res = list()
for i, char in enumerate(str):
if char == '(':
parentheses_counter += 1
if (parentheses_counter == 1):
start = i
elif char == ')':
parentheses_counter -= 1
if (parentheses_counter == 0):
res.append(str[start:i+1])
elif char != ' ' and parentheses_counter == 0 and (str[i-1]==' ' or i==0):
arg_without_parantheses = True
start = i
elif char == ' ' and parentheses_counter == 0 and arg_without_parantheses:
res.append(str[start:i+1])
arg_without_parantheses = False
if (arg_without_parantheses):
res.append(str[start:i+1])
res = [arg.strip() for arg in res]
return res
def s_expr_str_to_value(expr):
"""Takes an s-expression string and returns its corresponding value."""
expr = expr.strip()
if (not expr[0] == "("):
if expr == "true":
return True
elif expr == "false":
return False
else:
return eval("sage.all.QQbar("+expr+")")
else:
str_arg_list = get_str_arg_list(expr[1:-1])
operator = str_arg_list[0]
operands = [s_expr_str_to_value(x) for x in str_arg_list[1::]]
value = 0
match operator:
case "+":
for o in operands:
value += o
case "-":
if len(operands) == 1:
value = -operands[0]
elif len(operands) > 1:
value = operands[0]
for o in operands[1:]:
value -= o
case "*":
if len(operands) > 0: value = 1
for o in operands:
value *= o
case "/":
if len(operands) > 1:
value = operands[0]
for o in operands[1:]:
value /= o
case "^":
if len(operands) > 1:
value = operands[0]
for o in operands[1:]:
value = value ** o
return value
def resolve_root_of_with_interval(val):
"""
Takes a smtrat root-of-with-interval value and returns its value.
A root-of-with-interval value has the form (root-of-with-interval (coeffs a_0 ... a_n) lower_bound upper_bound).
E.g., (root-of-with-interval (coeffs (- 13) (- 14) 2) (/ 31 4) 8) -> 5/2*sqrt(3) + 7/2
"""
root_obj_str_list = get_str_arg_list(val[1:-1]) # slicing to remove parentheses
coeff_str_list = get_str_arg_list(root_obj_str_list[1][1:-1])
# get polynomial
x = sage.all.SR.var('x')
polynomial = sym_expr.new_Expression(sage.all.SR, 0)
for i, c in enumerate(coeff_str_list[1::]): # without first element "coeffs"
coeff = s_expr_str_to_value(c)
polynomial = sym_expr.new_Expression(sage.all.SR, polynomial + x**i * coeff)
# get bounds
lower_bound = s_expr_str_to_value(root_obj_str_list[2])
upper_bound = s_expr_str_to_value(root_obj_str_list[3])
# find root in interval
res = None
for r in polynomial.roots():
if lower_bound <= r[0] <= upper_bound:
res = r[0]
if res == None:
print("root object could not be resolved")
exit(-1)
return sage.all.QQbar(res)
def model_expression_to_value(expr):
expr = expr.strip()
"""Takes a model value string and returns the corresponding value."""
if "root-of-with-interval" in str(expr):
return resolve_root_of_with_interval(expr)
else:
return s_expr_str_to_value(expr)
def mk_or(expr_list):
"""Takes a list of expressions and returns an s-expression as a string with logical or applied on expressions."""
if len(expr_list) > 0:
res = " (or"
for e in expr_list:
res += " " + str(e)
res += ")"
return res
elif len(expr_list) == 1:
return str(expr_list[0])
else:
return ""
def mk_and(expr_list):
"""Takes a list of expressions and returns an s-expression as a string with logical and applied on expressions."""
if len(expr_list) > 0:
res = " (and"
for e in expr_list:
res += " " + str(e)
res += ")"
return res
elif len(expr_list) == 1:
return str(expr_list[0])
else:
return ""