PolyFEM
Loading...
Searching...
No Matches
pretty_print.py
Go to the documentation of this file.
1from sympy import *
2from sympy.matrices import *
3from sympy.printing import ccode
4import numpy as np
5
6
7# pretty print
8def C99_print(expr):
9 CSE_results = cse(expr, numbered_symbols("helper_"), optimizations='basic')
10 lines = []
11 for helper in CSE_results[0]:
12 if isinstance(helper[1], MatrixSymbol):
13 lines.append(
14 'const auto ' + str(helper[0]) + '[' + str(helper[1].rows * helper[1].cols) + '];')
15 lines.append(ccode(helper[1], helper[0]))
16 else:
17 lines.append('const auto ' + ccode(helper[1], helper[0]))
18
19 for i, result in enumerate(CSE_results[1]):
20 lines.append(ccode(result, "result_%d" % i))
21 return '\n'.join(lines)
22
23# Pretty print a matrix or tensor expression.
24def C99_print_tensor(expr, result_name="result"):
25 # If a tensor expression, the result is reshaped into a 2d matrix for printing.
26 lines = []
27 subs, result = cse(expr, numbered_symbols(
28 "helper_"), optimizations='basic')
29 if len(result) == 1:
30 result = result[0]
31
32 for k, v in subs:
33 lines.append(f"const double {ccode(v, k)}")
34
35 result_shape = np.array(result).shape
36 if len(result_shape) == 2:
37 for i in range(result_shape[0]):
38 for j in range(result_shape[1]):
39 s = ccode(result[i, j], f"{result_name}[{i}, {j}]")
40 lines.append(f"{s}")
41 elif len(result_shape) == 4:
42 for i in range(result_shape[0]):
43 for j in range(result_shape[1]):
44 for k in range(result_shape[2]):
45 for l in range(result_shape[3]):
46 s = ccode(result[i, j, k, l],
47 f"{result_name}[{i * result_shape[1] + j}, {k * result_shape[3] + l}]")
48 lines.append(f"{s}")
49
50 return "\n".join(lines)