Loading [MathJax]/extensions/tex2jax.js
PolyFEM
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
p_bases.py
Go to the documentation of this file.
1# https://raw.githubusercontent.com/sympy/sympy/master/examples/advanced/fem.py
2from sympy import *
3import os
4import numpy as np
5import argparse
6from sympy.printing import ccode
7
8
9import pretty_print
10
11x, y, z = symbols('x,y,z')
12
13
15 def __init__(self, nsd):
16 self.nsd = nsd
17 if nsd <= 3:
18 coords = symbols('x,y,z')[:nsd]
19 else:
20 coords = [Symbol("x_%d" % d) for d in range(nsd)]
21 self.coords = coords
22
23 def integrate(self, f):
24 coords = self.coords
25 nsd = self.nsd
26
27 limit = 1
28 for p in coords:
29 limit -= p
30
31 intf = f
32 for d in range(0, nsd):
33 p = coords[d]
34 limit += p
35 intf = integrate(intf, (p, 0, limit))
36 return intf
37
38
39def bernstein_space(order, nsd):
40 if nsd > 3:
41 raise RuntimeError("Bernstein only implemented in 1D, 2D, and 3D")
42 sum = 0
43 basis = []
44 coeff = []
45
46 if nsd == 2:
47 b1, b2, b3 = x, y, 1 - x - y
48 for o1 in range(0, order + 1):
49 for o2 in range(0, order + 1):
50 for o3 in range(0, order + 1):
51 if o1 + o2 + o3 == order:
52 aij = Symbol("a_%d_%d_%d" % (o1, o2, o3))
53 fac = factorial(order) / (factorial(o1) *
54 factorial(o2) * factorial(o3))
55 sum += aij * fac * pow(b1, o1) * \
56 pow(b2, o2) * pow(b3, o3)
57 basis.append(fac * pow(b1, o1) *
58 pow(b2, o2) * pow(b3, o3))
59 coeff.append(aij)
60
61 if nsd == 3:
62 b1, b2, b3, b4 = x, y, z, 1 - x - y - z
63 for o1 in range(0, order + 1):
64 for o2 in range(0, order + 1):
65 for o3 in range(0, order + 1):
66 for o4 in range(0, order + 1):
67 if o1 + o2 + o3 + o4 == order:
68 aij = Symbol("a_%d_%d_%d_%d" % (o1, o2, o3, o4))
69 fac = factorial(
70 order) / (factorial(o1) * factorial(o2) * factorial(o3) * factorial(o4))
71 sum += aij * fac * \
72 pow(b1, o1) * pow(b2, o2) * \
73 pow(b3, o3) * pow(b4, o4)
74 basis.append(fac * pow(b1, o1) * pow(b2, o2) *
75 pow(b3, o3) * pow(b4, o4))
76 coeff.append(aij)
77
78 return sum, coeff, basis
79
80
81def create_point_set(order, nsd):
82 h = Rational(1, order)
83 set = []
84
85 if nsd == 2:
86 for i in range(0, order + 1):
87 x = i * h
88 for j in range(0, order + 1):
89 y = j * h
90 if x + y <= 1:
91 set.append((x, y))
92
93 if nsd == 3:
94 for i in range(0, order + 1):
95 x = i * h
96 for j in range(0, order + 1):
97 y = j * h
98 for k in range(0, order + 1):
99 z = k * h
100 if x + y + z <= 1:
101 set.append((x, y, z))
102
103 return set
104
105
106def create_matrix(equations, coeffs):
107 A = zeros(len(equations))
108 i = 0
109 j = 0
110 for j in range(0, len(coeffs)):
111 c = coeffs[j]
112 for i in range(0, len(equations)):
113 e = equations[i]
114 d, _ = reduced(e, [c])
115 A[i, j] = d[0]
116 return A
117
118
120 def __init__(self, nsd, order, bernstein):
121 self.nsd = nsd
122 self.bernstein = bernstein
123 self.order = order
124 self.points = []
125 self.compute_basis()
126
127 def nbf(self):
128 return len(self.N)
129
130 def compute_basis(self):
131 order = self.order
132 nsd = self.nsd
133 N = []
134 pol, coeffs, basis = bernstein_space(order, nsd)
135 self.points = create_point_set(order, nsd)
136
137 equations = []
138 for p in self.points:
139 ex = pol.subs(x, p[0])
140 if nsd > 1:
141 ex = ex.subs(y, p[1])
142 if nsd > 2:
143 ex = ex.subs(z, p[2])
144 equations.append(ex)
145
146 b = eye(len(equations))
147 if self.bernstein:
148 xx = b
149 else:
150 A = create_matrix(equations, coeffs)
151
152 # if A.shape[0] > 25:
153 # A = A.evalf()
154
155 Ainv = A.inv()
156 xx = Ainv * b
157
158 for i in range(0, len(equations)):
159 Ni = pol
160 for j in range(0, len(coeffs)):
161 Ni = Ni.subs(coeffs[j], xx[j, i])
162 N.append(Ni)
163
164 self.N = N
165
166
168 parser = argparse.ArgumentParser(
169 description=__doc__,
170 formatter_class=argparse.RawDescriptionHelpFormatter)
171 parser.add_argument("output", type=str, help="path to the output folder")
172 parser.add_argument("--bernstein", default=False, action='store_true',
173 help="use Bernstein basis instead of Lagrange basis")
174 return parser.parse_args()
175
176
177if __name__ == "__main__":
178 args = parse_args()
179
180 dims = [2, 3]
181
182 orders = [0, 1, 2, 3, 4]
183 # orders = [4]
184
185 bletter = "b" if args.bernstein else "p"
186
187 cpp = f"#include \"auto_{bletter}_bases.hpp\""
188 if not args.bernstein:
189 cpp = cpp + "\n#include \"auto_b_bases.hpp\""
190 cpp = cpp + "\n#include \"p_n_bases.hpp\""
191 cpp = cpp + "\n\n\n" \
192 "namespace polyfem {\nnamespace autogen " + "{\nnamespace " + "{\n"
193
194 hpp = "#pragma once\n\n#include <Eigen/Dense>\n#include <cassert>\n"
195
196 hpp = hpp + "\nnamespace polyfem {\nnamespace autogen " + "{\n"
197
198 for dim in dims:
199 print(str(dim) + "D " + bletter)
200 suffix = "2d" if dim == 2 else "3d"
201
202 unique_nodes = f"void {bletter}_nodes_{suffix}" + \
203 f"(const int {bletter}, Eigen::MatrixXd &val)"
204
205 if args.bernstein:
206 unique_fun = f"void {bletter}_basis_value_{suffix}" + \
207 f"(const int {bletter}, const int local_index, const Eigen::MatrixXd &uv, Eigen::MatrixXd &val)"
208 dunique_fun = f"void {bletter}_grad_basis_value_{suffix}" + \
209 f"(const int {bletter}, const int local_index, const Eigen::MatrixXd &uv, Eigen::MatrixXd &val)"
210 else:
211 unique_fun = f"void {bletter}_basis_value_{suffix}" + \
212 f"(const bool bernstein, const int {bletter}, const int local_index, const Eigen::MatrixXd &uv, Eigen::MatrixXd &val)"
213 dunique_fun = f"void {bletter}_grad_basis_value_{suffix}" + \
214 f"(const bool bernstein, const int {bletter}, const int local_index, const Eigen::MatrixXd &uv, Eigen::MatrixXd &val)"
215
216 if not args.bernstein:
217 hpp = hpp + unique_nodes + ";\n\n"
218
219 hpp = hpp + unique_fun + ";\n\n"
220 hpp = hpp + dunique_fun + ";\n\n"
221
222 unique_nodes = unique_nodes + f"{{\nswitch({bletter})" + "{\n"
223
224 unique_fun = unique_fun + "{\n"
225 dunique_fun = dunique_fun + "{\n"
226
227 if not args.bernstein:
228 unique_fun = unique_fun + \
229 f"if(bernstein) {{ b_basis_value_{suffix}(p, local_index, uv, val); return; }}\n\n"
230 dunique_fun = dunique_fun + \
231 f"if(bernstein) {{ b_grad_basis_value_{suffix}(p, local_index, uv, val); return; }}\n\n"
232
233 unique_fun = unique_fun + f"\nswitch({bletter})" + "{\n"
234 dunique_fun = dunique_fun + f"\nswitch({bletter})" + "{\n"
235
236 if dim == 2:
237 vertices = [[0, 0], [1, 0], [0, 1]]
238 elif dim == 3:
239 vertices = [[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]]
240
241 for order in orders:
242 print("\t-processing " + str(order))
243
244 if order == 0:
245 def fe(): return None
246 fe.nbf = lambda: 1
247
248 fe.N = [1]
249
250 if dim == 2:
251 fe.points = [[1./3., 1./3.]]
252 else:
253 fe.points = [[1./3., 1./3., 1./3.]]
254 else:
255 fe = Lagrange(dim, order, args.bernstein)
256
257 current_indices = list(range(0, len(fe.points)))
258 indices = []
259
260 # vertex coordinate
261 for i in range(0, dim + 1):
262 vv = vertices[i]
263 for ii in current_indices:
264 norm = 0
265 for dd in range(0, dim):
266 norm = norm + (vv[dd] - fe.points[ii][dd]) ** 2
267
268 if norm < 1e-10:
269 indices.append(ii)
270 current_indices.remove(ii)
271 break
272
273 # edge 1 coordinate
274 for i in range(0, order - 1):
275 for ii in current_indices:
276 if fe.points[ii][1] != 0 or (dim == 3 and fe.points[ii][2] != 0):
277 continue
278
279 if abs(fe.points[ii][0] - (i + 1) / order) < 1e-10:
280 indices.append(ii)
281 current_indices.remove(ii)
282 break
283
284 # edge 2 coordinate
285 for i in range(0, order - 1):
286 for ii in current_indices:
287 if fe.points[ii][0] + fe.points[ii][1] != 1 or (dim == 3 and fe.points[ii][2] != 0):
288 continue
289
290 if abs(fe.points[ii][1] - (i + 1) / order) < 1e-10:
291 indices.append(ii)
292 current_indices.remove(ii)
293 break
294
295 # edge 3 coordinate
296 for i in range(0, order - 1):
297 for ii in current_indices:
298 if fe.points[ii][0] != 0 or (dim == 3 and fe.points[ii][2] != 0):
299 continue
300
301 if abs(fe.points[ii][1] - (1 - (i + 1) / order)) < 1e-10:
302 indices.append(ii)
303 current_indices.remove(ii)
304 break
305
306 if dim == 3:
307 # edge 4 coordinate
308 for i in range(0, order - 1):
309 for ii in current_indices:
310 if fe.points[ii][0] != 0 or fe.points[ii][1] != 0:
311 continue
312
313 if abs(fe.points[ii][2] - (i + 1) / order) < 1e-10:
314 indices.append(ii)
315 current_indices.remove(ii)
316 break
317
318 # edge 5 coordinate
319 for i in range(0, order - 1):
320 for ii in current_indices:
321 if fe.points[ii][0] + fe.points[ii][2] != 1 or fe.points[ii][1] != 0:
322 continue
323
324 if abs(fe.points[ii][0] - (1 - (i + 1) / order)) < 1e-10:
325 indices.append(ii)
326 current_indices.remove(ii)
327 break
328
329 # edge 6 coordinate
330 for i in range(0, order - 1):
331 for ii in current_indices:
332 if fe.points[ii][1] + fe.points[ii][2] != 1 or fe.points[ii][0] != 0:
333 continue
334
335 if abs(fe.points[ii][1] - (1 - (i + 1) / order)) < 1e-10:
336 indices.append(ii)
337 current_indices.remove(ii)
338 break
339
340 if dim == 3:
341 nn = max(0, order - 2)
342 npts = int(nn * (nn + 1) / 2)
343
344 # bottom: z = 0
345 for i in range(0, npts):
346 for ii in current_indices:
347 if abs(fe.points[ii][2]) > 1e-10:
348 continue
349
350 indices.append(ii)
351 current_indices.remove(ii)
352 break
353
354 # front: y = 0
355 for i in range(0, npts):
356 for ii in current_indices:
357 if abs(fe.points[ii][1]) > 1e-10:
358 continue
359
360 indices.append(ii)
361 current_indices.remove(ii)
362 break
363
364 # diagonal: none equal to zero and sum 1
365 tmp = []
366 for i in range(0, npts):
367 for ii in current_indices:
368 if (abs(fe.points[ii][0]) < 1e-10) | (abs(fe.points[ii][1]) < 1e-10) | (abs(fe.points[ii][2]) < 1e-10):
369 continue
370
371 if abs((fe.points[ii][0] + fe.points[ii][1] + fe.points[ii][2]) - 1) > 1e-10:
372 continue
373
374 tmp.append(ii)
375 current_indices.remove(ii)
376 break
377 for i in range(0, len(tmp)):
378 indices.append(tmp[(i + 2) % len(tmp)])
379
380 # side: x = 0
381 tmp = []
382 for i in range(0, npts):
383 for ii in current_indices:
384 if abs(fe.points[ii][0]) > 1e-10:
385 continue
386
387 tmp.append(ii)
388 current_indices.remove(ii)
389 break
390 tmp.sort(reverse=True)
391 indices.extend(tmp)
392
393 # either face or volume indices, order do not matter
394 for ii in current_indices:
395 indices.append(ii)
396
397 # nodes code gen
398 nodes = f"void {bletter}_{order}_nodes_{suffix}(Eigen::MatrixXd &res) {{\n res.resize(" + str(
399 len(indices)) + ", " + str(dim) + "); res << \n"
400 unique_nodes = unique_nodes + f"\tcase {order}: " + \
401 f"{bletter}_{order}_nodes_{suffix}(val); break;\n"
402
403 for ii in indices:
404 nodes = nodes + ccode(fe.points[ii][0]) + ", " + ccode(fe.points[ii][1]) + (
405 (", " + ccode(fe.points[ii][2])) if dim == 3 else "") + ",\n"
406 nodes = nodes[:-2]
407 nodes = nodes + ";\n}"
408
409 # bases code gen
410 func = f"void {bletter}_{order}_basis_value_{suffix}" + \
411 "(const int local_index, const Eigen::MatrixXd &uv, Eigen::MatrixXd &result_0)"
412 dfunc = f"void {bletter}_{order}_basis_grad_value_{suffix}" + \
413 "(const int local_index, const Eigen::MatrixXd &uv, Eigen::MatrixXd &val)"
414
415 unique_fun = unique_fun + \
416 f"\tcase {order}: {bletter}_{order}_basis_value_{suffix}(local_index, uv, val); break;\n"
417 dunique_fun = dunique_fun + \
418 f"\tcase {order}: {bletter}_{order}_basis_grad_value_{suffix}(local_index, uv, val); break;\n"
419
420 # hpp = hpp + func + ";\n"
421 # hpp = hpp + dfunc + ";\n"
422
423 if not args.bernstein:
424 default_base = "p_n_basis_value_3d(p, local_index, uv, val);" if dim == 3 else "p_n_basis_value_2d(p, local_index, uv, val);"
425 default_dbase = "p_n_basis_grad_value_3d(p, local_index, uv, val);" if dim == 3 else "p_n_basis_grad_value_2d(p, local_index, uv, val);"
426 default_nodes = "p_n_nodes_3d(p, val);" if dim == 3 else "p_n_nodes_2d(p, val);"
427
428 base = "auto x=uv.col(0).array();\nauto y=uv.col(1).array();"
429 if dim == 3:
430 base = base + "\nauto z=uv.col(2).array();"
431 base = base + "\n\n"
432 dbase = base
433
434 if order == 0:
435 base = base + "result_0.resize(x.size(),1);\n"
436
437 base = base + "switch(local_index){\n"
438 dbase = dbase + \
439 "val.resize(uv.rows(), uv.cols());\n Eigen::ArrayXd result_0(uv.rows());\n" + \
440 "switch(local_index){\n"
441
442 for i in range(0, fe.nbf()):
443 real_index = indices[i]
444 # real_index = i
445
446 base = base + "\tcase " + str(i) + ": {" + pretty_print.C99_print(
447 simplify(fe.N[real_index])).replace(" = 1;", ".setOnes();") + "} break;\n"
448 dbase = dbase + "\tcase " + str(i) + ": {" + \
449 "{" + pretty_print.C99_print(simplify(diff(fe.N[real_index], x))).replace(" = 0;", ".setZero();").replace(" = 1;", ".setOnes();").replace(" = -1;", ".setConstant(-1);") + "val.col(0) = result_0; }" \
450 "{" + pretty_print.C99_print(simplify(diff(fe.N[real_index], y))).replace(" = 0;", ".setZero();").replace(
451 " = 1;", ".setOnes();").replace(" = -1;", ".setConstant(-1);") + "val.col(1) = result_0; }"
452
453 if dim == 3:
454 dbase = dbase + "{" + pretty_print.C99_print(simplify(diff(fe.N[real_index], z))).replace(" = 0;", ".setZero();").replace(
455 " = 1;", ".setOnes();").replace(" = -1;", ".setConstant(-1);") + "val.col(2) = result_0; }"
456
457 dbase = dbase + "} break;\n"
458
459 base = base + "\tdefault: assert(false);\n}"
460 dbase = dbase + "\tdefault: assert(false);\n}"
461
462 cpp = cpp + func + "{\n\n"
463 cpp = cpp + base + "}\n"
464
465 cpp = cpp + dfunc + "{\n\n"
466 cpp = cpp + dbase + "}\n\n\n"
467
468 if not args.bernstein:
469 cpp = cpp + nodes + "\n\n\n"
470
471 if args.bernstein:
472 unique_nodes = ""
473 else:
474 unique_nodes = unique_nodes + "\tdefault: "+default_nodes+"\n}}"
475
476 if args.bernstein:
477 unique_fun = unique_fun + "\tdefault: assert(false); \n}}"
478 dunique_fun = dunique_fun + "\tdefault: assert(false); \n}}"
479 else:
480 unique_fun = unique_fun + "\tdefault: "+default_base+"\n}}"
481 dunique_fun = dunique_fun + "\tdefault: "+default_dbase+"\n}}"
482
483 cpp = cpp + "}\n\n" + unique_nodes + "\n" + unique_fun + \
484 "\n\n" + dunique_fun + "\n" + "\nnamespace " + "{\n"
485 hpp = hpp + "\n"
486
487 hpp = hpp + \
488 f"\nstatic const int MAX_{bletter.capitalize()}_BASES = {max(orders)};\n"
489
490 cpp = cpp + "\n}}}\n"
491 hpp = hpp + "\n}}\n"
492
493 path = os.path.abspath(args.output)
494
495 print("saving...")
496 with open(os.path.join(path, f"auto_{bletter}_bases.cpp"), "w") as file:
497 file.write(cpp)
498
499 with open(os.path.join(path, f"auto_{bletter}_bases.hpp"), "w") as file:
500 file.write(hpp)
501
502 print("done!")
__init__(self, nsd, order, bernstein)
Definition p_bases.py:120
compute_basis(self)
Definition p_bases.py:130
create_matrix(equations, coeffs)
Definition p_bases.py:106
create_point_set(order, nsd)
Definition p_bases.py:81
bernstein_space(order, nsd)
Definition p_bases.py:39
parse_args()
Definition p_bases.py:167
C99_print(expr)