felupe-studio 0.6.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. felupe_studio/__about__.py +1 -0
  2. felupe_studio/__init__.py +24 -0
  3. felupe_studio/__main__.py +5 -0
  4. felupe_studio/_helpers.py +361 -0
  5. felupe_studio/benchmark.py +74 -0
  6. felupe_studio/bridge.py +254 -0
  7. felupe_studio/bytecode.py +42 -0
  8. felupe_studio/checks.py +290 -0
  9. felupe_studio/cli.py +67 -0
  10. felupe_studio/codegen.py +1123 -0
  11. felupe_studio/commands.py +716 -0
  12. felupe_studio/commands.schema.json +2084 -0
  13. felupe_studio/data/app/assets/archive-EtgZMgZY.js +1 -0
  14. felupe_studio/data/app/assets/client-7iqL7BQO.js +1 -0
  15. felupe_studio/data/app/assets/client-Bue05veK.css +1 -0
  16. felupe_studio/data/app/assets/files-mnN9zsH0.js +1 -0
  17. felupe_studio/data/app/assets/main-CBztJLPH.js +115 -0
  18. felupe_studio/data/app/assets/main-CiV2hAUy.css +1 -0
  19. felupe_studio/data/app/assets/project-BAAuI0wz.js +10 -0
  20. felupe_studio/data/app/assets/pyodide.worker-DGW69R0Q.js +7345 -0
  21. felupe_studio/data/app/assets/schema-CduYFcoF.js +1 -0
  22. felupe_studio/data/app/assets/spike-BYSp08uE.js +2 -0
  23. felupe_studio/data/app/assets/spike-CZYcQnWM.css +1 -0
  24. felupe_studio/data/app/index.html +17 -0
  25. felupe_studio/data/app/spike.html +76 -0
  26. felupe_studio/data/app/sw.js +59 -0
  27. felupe_studio/data/app/version.json +1 -0
  28. felupe_studio/data/docs/commands.md +407 -0
  29. felupe_studio/data/docs/guide.md +299 -0
  30. felupe_studio/data/docs/reference.md +607 -0
  31. felupe_studio/data/samples/bushing/bushing.py +54 -0
  32. felupe_studio/data/samples/bushing/model.felupe.json +260 -0
  33. felupe_studio/data/samples/bushing/thumbnail.svg +292 -0
  34. felupe_studio/data/samples/engine-mount/air.vtu +4680 -0
  35. felupe_studio/data/samples/engine-mount/metal.vtu +5861 -0
  36. felupe_studio/data/samples/engine-mount/model.felupe.json +219 -0
  37. felupe_studio/data/samples/engine-mount/rubber.vtu +10401 -0
  38. felupe_studio/data/samples/engine-mount/thumbnail.svg +2096 -0
  39. felupe_studio/data/samples/glued-plate/block.vtu +3799 -0
  40. felupe_studio/data/samples/glued-plate/model.felupe.json +155 -0
  41. felupe_studio/data/samples/glued-plate/thumbnail.svg +132 -0
  42. felupe_studio/data/samples/hex-tet-gmsh/bar.msh +1006 -0
  43. felupe_studio/data/samples/hex-tet-gmsh/model.felupe.json +106 -0
  44. felupe_studio/data/samples/hex-tet-gmsh/thumbnail.svg +196 -0
  45. felupe_studio/data/samples/hyperelastic-spring/model.felupe.json +194 -0
  46. felupe_studio/data/samples/hyperelastic-spring/spring.vtu +20292 -0
  47. felupe_studio/data/samples/hyperelastic-spring/thumbnail.svg +538 -0
  48. felupe_studio/data/samples/material-test/cube.vtu +486 -0
  49. felupe_studio/data/samples/material-test/model.felupe.json +59 -0
  50. felupe_studio/data/samples/material-test/thumbnail.svg +31 -0
  51. felupe_studio/data/samples/metacone/metacone.py +64 -0
  52. felupe_studio/data/samples/metacone/model.felupe.json +124 -0
  53. felupe_studio/data/samples/metacone/thumbnail.svg +464 -0
  54. felupe_studio/data/samples/plastic-plate/model.felupe.json +132 -0
  55. felupe_studio/data/samples/plastic-plate/plate_with_hole.py +40 -0
  56. felupe_studio/data/samples/plastic-plate/thumbnail.svg +132 -0
  57. felupe_studio/data/samples/plate-with-hole/model.felupe.json +114 -0
  58. felupe_studio/data/samples/plate-with-hole/plate_with_hole.py +40 -0
  59. felupe_studio/data/samples/plate-with-hole/thumbnail.svg +132 -0
  60. felupe_studio/data/samples/sandwich-spring/model.felupe.json +195 -0
  61. felupe_studio/data/samples/sandwich-spring/sandwich_spring.py +37 -0
  62. felupe_studio/data/samples/sandwich-spring/thumbnail.svg +232 -0
  63. felupe_studio/data/samples/sandwich-spring-axisymmetric/model.felupe.json +194 -0
  64. felupe_studio/data/samples/sandwich-spring-axisymmetric/sandwich_spring_2d.py +36 -0
  65. felupe_studio/data/samples/sandwich-spring-axisymmetric/thumbnail.svg +164 -0
  66. felupe_studio/data/samples/shear-mount/model.felupe.json +106 -0
  67. felupe_studio/data/samples/shear-mount/mount.vtu +5954 -0
  68. felupe_studio/data/samples/shear-mount/thumbnail.svg +164 -0
  69. felupe_studio/data/samples/two-materials/bar.vtu +3116 -0
  70. felupe_studio/data/samples/two-materials/model.felupe.json +119 -0
  71. felupe_studio/data/samples/two-materials/thumbnail.svg +116 -0
  72. felupe_studio/data/samples.json +183 -0
  73. felupe_studio/expressions.py +488 -0
  74. felupe_studio/loadcases.py +138 -0
  75. felupe_studio/materials.py +187 -0
  76. felupe_studio/mcp.py +727 -0
  77. felupe_studio/meshes.py +270 -0
  78. felupe_studio/project.py +205 -0
  79. felupe_studio/results.py +785 -0
  80. felupe_studio/runner.py +424 -0
  81. felupe_studio/runtime.py +334 -0
  82. felupe_studio/scene.py +126 -0
  83. felupe_studio/serve.py +316 -0
  84. felupe_studio-0.6.0.dist-info/METADATA +101 -0
  85. felupe_studio-0.6.0.dist-info/RECORD +88 -0
  86. felupe_studio-0.6.0.dist-info/WHEEL +4 -0
  87. felupe_studio-0.6.0.dist-info/entry_points.txt +3 -0
  88. felupe_studio-0.6.0.dist-info/licenses/LICENSE +674 -0
@@ -0,0 +1 @@
1
+ __version__ = "0.6.0"
@@ -0,0 +1,24 @@
1
+ """Command interpretation and code generation for FElupe Studio.
2
+
3
+ The command list of the GUI is turned into a readable FElupe script by this
4
+ package. It runs unchanged in Pyodide (browser) and in CPython (tests).
5
+ """
6
+
7
+ from .__about__ import __version__
8
+ from .codegen import codegen
9
+
10
+ __all__ = ["__version__", "codegen", "versions"]
11
+
12
+
13
+ def versions():
14
+ """Return the versions of felupe-studio and of the packages it builds on."""
15
+ import felupe
16
+ import numpy
17
+ import scipy
18
+
19
+ return {
20
+ "felupe-studio": __version__,
21
+ "felupe": felupe.__version__,
22
+ "numpy": numpy.__version__,
23
+ "scipy": scipy.__version__,
24
+ }
@@ -0,0 +1,5 @@
1
+ """``python -m felupe_studio serve``, see :mod:`felupe_studio.cli`."""
2
+
3
+ from .cli import main
4
+
5
+ main()
@@ -0,0 +1,361 @@
1
+ """Helpers of the generated scripts.
2
+
3
+ The part below the marker is copied verbatim into every generated script (see
4
+ :mod:`felupe_studio.codegen`), so a script runs without FElupe Studio. The same code
5
+ is used by :mod:`felupe_studio.checks`.
6
+ """
7
+
8
+ from types import SimpleNamespace
9
+
10
+ import felupe as fem
11
+ import meshio
12
+ import numpy as np
13
+
14
+ # --- embedded in generated scripts ---
15
+ # regions by cell type of the solid cells: of 3D models, and of 2D models (plane
16
+ # strain or axisymmetric, #175)
17
+ REGIONS = {
18
+ "tetra": fem.RegionTetra,
19
+ "tetra10": fem.RegionQuadraticTetra,
20
+ "hexahedron": fem.RegionHexahedron,
21
+ "hexahedron20": fem.RegionQuadraticHexahedron,
22
+ "hexahedron27": fem.RegionTriQuadraticHexahedron,
23
+ "triangle": fem.RegionTriangle,
24
+ "triangle6": fem.RegionQuadraticTriangle,
25
+ "quad": fem.RegionQuad,
26
+ "quad8": fem.RegionQuadraticQuad,
27
+ "quad9": fem.RegionBiQuadraticQuad,
28
+ }
29
+
30
+ # topological dimension of meshio cell types (wedges and pyramids are solid cells
31
+ # without a region in FElupe)
32
+ DIMENSIONS = {
33
+ **dict.fromkeys(["line", "line3"], 1),
34
+ **dict.fromkeys(["triangle", "triangle6", "quad", "quad8", "quad9"], 2),
35
+ **dict.fromkeys(["wedge", "wedge15", "pyramid", "pyramid13"], 3),
36
+ **dict.fromkeys(["tetra", "tetra10", "hexahedron", "hexahedron20"], 3),
37
+ "hexahedron27": 3,
38
+ }
39
+
40
+
41
+ def solid_types(mesh):
42
+ """Return the types of the solid cells of a meshio mesh, in the order of blocks:
43
+ the cells of the highest dimension, e.g. the quads of a 2D mesh but not the
44
+ quads of the faces of a mesh of hexahedrons."""
45
+ dimension = max((DIMENSIONS.get(b.type, 0) for b in mesh.cells), default=0)
46
+ if dimension < 2:
47
+ return []
48
+ types = [b.type for b in mesh.cells if DIMENSIONS.get(b.type) == dimension]
49
+ return list(dict.fromkeys(types))
50
+
51
+
52
+ def volume_cells(mesh, tag=None, cell_type=None, scale=1.0, dim=3):
53
+ """Return the points (multiplied by the scale), the cell type, the solid cells and
54
+ their tags (optional) of a meshio mesh. Lower-dimensional cell blocks (e.g.
55
+ boundary faces) are ignored. A mesh with more than one type of solid cells needs
56
+ the cell type to take. The cells are 3D cells, or 2D cells for a 2D model (plane
57
+ strain or axisymmetric) with ``dim=2``. The points of 2D cells have the
58
+ coordinates x and y only (the z of a mesh file is dropped)."""
59
+ types = solid_types(mesh)
60
+ if cell_type is None and len(types) == 1:
61
+ cell_type = types[0]
62
+ if cell_type not in types:
63
+ raise ValueError(f"Expected the type of solid cells to take, one of {types}.")
64
+ if dim == 3 and DIMENSIONS[cell_type] == 2:
65
+ raise ValueError(
66
+ f"The mesh has {cell_type} cells, which are 2D cells: set the analysis "
67
+ "of the model settings to plane strain or axisymmetric."
68
+ )
69
+ if dim == 2 and DIMENSIONS[cell_type] == 3:
70
+ raise ValueError(
71
+ f"The mesh has {cell_type} cells, which are 3D cells: a 2D model (plane "
72
+ "strain or axisymmetric) has 2D cells."
73
+ )
74
+ blocks = [i for i, b in enumerate(mesh.cells) if b.type == cell_type]
75
+ cells = np.vstack([mesh.cells[i].data for i in blocks])
76
+ tags = None
77
+ if tag is not None:
78
+ tags = np.concatenate([np.ravel(mesh.cell_data[tag][i]) for i in blocks])
79
+ points = mesh.points if scale == 1 else mesh.points * scale
80
+ if DIMENSIONS[cell_type] == 2:
81
+ points = np.asarray(points)[:, :2]
82
+ return SimpleNamespace(points=points, cell_type=cell_type, cells=cells, tags=tags)
83
+
84
+
85
+ def single_point(mask, name):
86
+ """Return the index of the only point of a mask, e.g. of a center point. A mask
87
+ of another number of points raises a ``ValueError``."""
88
+ (indices,) = np.nonzero(mask)
89
+ if len(indices) != 1:
90
+ raise ValueError(f"'{name}' has {len(indices)} points, not one.")
91
+ return indices[0]
92
+
93
+
94
+ def vertex_region(points):
95
+ """Return a region of vertices at the given points, e.g. of control points that
96
+ are not nodes of the meshes of the sections."""
97
+ points = np.atleast_2d(np.asarray(points, dtype=float))
98
+ cells = np.arange(len(points)).reshape(-1, 1)
99
+ return fem.RegionVertex(fem.Mesh(points, cells, "vertex"))
100
+
101
+
102
+ def points_at(points, coordinates, atol=1e-8):
103
+ """Return a mask of the points at the given coordinates (like ``np.isclose``).
104
+ Every coordinate needs a point, otherwise a ``ValueError`` is raised."""
105
+ coordinates = np.atleast_2d(np.asarray(coordinates, dtype=float))
106
+ close = np.isclose(points[:, None], coordinates, atol=atol).all(axis=2)
107
+ missing = coordinates[~close.any(axis=0)]
108
+ if len(missing):
109
+ raise ValueError(f"There is no point at {missing.tolist()}.")
110
+ return close.any(axis=1)
111
+
112
+
113
+ # --- embedded in generated scripts with u-p-J sections ---
114
+ def mixed_region(mesh):
115
+ """Return the region of the mixed fields (u-p-J) of a mesh. Linear tetrahedra and
116
+ triangles get a bubble point in every cell (MINI element), the dual fields are
117
+ linear.
118
+
119
+ Only the points of the cells are kept: the dual fields of tetrahedra are fields of
120
+ the points, and a point of another section would be a free degree of freedom
121
+ without stiffness. ``fem.field.merge`` merges the points of the sections again."""
122
+ used, cells = np.unique(mesh.cells, return_inverse=True)
123
+ mesh = fem.Mesh(mesh.points[used], cells.reshape(mesh.cells.shape), mesh.cell_type)
124
+ if mesh.cell_type == "tetra":
125
+ bubble = fem.mesh.add_midpoints_volumes(mesh, cell_type_new="tetra5")
126
+ return fem.RegionTetraMINI(bubble)
127
+ if mesh.cell_type == "triangle":
128
+ bubble = fem.mesh.add_midpoints_faces(mesh, cell_type_new="triangle4")
129
+ return fem.RegionTriangleMINI(bubble)
130
+ return REGIONS[mesh.cell_type](mesh)
131
+
132
+
133
+ def mixed_field(region, **kwargs):
134
+ """Return the field container of a section with the u-p-J formulation. Linear
135
+ hexahedrons and quads have the displacements only: their pressure and volume
136
+ ratio are constant in every cell and condensed by
137
+ ``fem.SolidBodyNearlyIncompressible`` (see ``nearly_incompressible``). Other cells
138
+ get the mixed fields of the displacements, the pressure and the volume ratio,
139
+ ``fem.FieldsMixed`` (with ``planestrain=True`` or ``axisymmetric=True`` of 2D
140
+ models)."""
141
+ if region.mesh.cell_type in ("hexahedron", "quad"):
142
+ # the precision of a model in single precision (#297)
143
+ dtype = kwargs.get("dtype")
144
+ if kwargs.get("axisymmetric"):
145
+ field = fem.FieldAxisymmetric(region, dim=2, dtype=dtype)
146
+ elif kwargs.get("planestrain"):
147
+ field = fem.FieldPlaneStrain(region, dim=2, dtype=dtype)
148
+ else:
149
+ field = fem.Field(region, dim=3, dtype=dtype)
150
+ return fem.FieldContainer([field])
151
+ return fem.FieldsMixed(region, n=3, **kwargs)
152
+
153
+
154
+ def nearly_incompressible(umat, field, bulk, volumetric="volume-ratio"):
155
+ """Return the solid body of a section with the u-p-J formulation: of a field of the
156
+ displacements only (``mixed_field`` of linear hexahedrons and quads)
157
+ ``fem.SolidBodyNearlyIncompressible``, which condenses the pressure and the volume
158
+ ratio of every cell, else ``fem.SolidBody`` with ``fem.NearlyIncompressible`` on
159
+ the mixed fields. Both are the same three-field formulation."""
160
+ if len(field.fields) == 1:
161
+ return fem.SolidBodyNearlyIncompressible(
162
+ umat, field, bulk=bulk, volumetric=volumetric
163
+ )
164
+ umat = fem.NearlyIncompressible(umat, bulk=bulk, volumetric=volumetric)
165
+ return fem.SolidBody(umat, field)
166
+
167
+
168
+ # --- embedded in generated scripts with face sets ---
169
+ # boundary regions by cell type of the solid cells (no tetrahedrons and triangles in
170
+ # FElupe 12); the faces of the 2D cells of 2D models are their edges
171
+ BOUNDARY_REGIONS = {
172
+ "hexahedron": fem.RegionHexahedronBoundary,
173
+ "hexahedron20": fem.RegionQuadraticHexahedronBoundary,
174
+ "hexahedron27": fem.RegionTriQuadraticHexahedronBoundary,
175
+ "quad": fem.RegionQuadBoundary,
176
+ "quad8": fem.RegionQuadraticQuadBoundary,
177
+ "quad9": fem.RegionBiQuadraticQuadBoundary,
178
+ }
179
+
180
+
181
+ def boundary_faces(mesh, plane=None, centers=None, atol=None):
182
+ """Return the boundary region of faces of the outer surface of a mesh: the faces
183
+ on a plane ``(axis, value)``, or the faces with the given centers (the mean of
184
+ the points of a face, the nearest face within ``atol``, by default 1e-6 of the
185
+ size of the mesh). Picked faces are selected by the points of their faces on
186
+ their cells; a ``ValueError`` is raised if these select more faces, e.g. both
187
+ sides of a plate that is one cell thick. The faces of 2D cells are their edges,
188
+ with the normals of the edges in the xy-plane (``ensure_3d=True``)."""
189
+ if mesh.cell_type not in BOUNDARY_REGIONS:
190
+ raise NotImplementedError(
191
+ f"Faces of {mesh.cell_type} cells have no boundary region in FElupe."
192
+ )
193
+ region = BOUNDARY_REGIONS[mesh.cell_type]
194
+ options = {"ensure_3d": True} if mesh.dim == 2 else {}
195
+ points = mesh.points
196
+ if plane is not None:
197
+ axis, value = plane
198
+ tolerance = 1e-8 if atol is None else atol
199
+ mask = np.isclose(points[:, axis], value, atol=tolerance)
200
+ return region(mesh, mask=mask, **options)
201
+
202
+ # the nearest outer face of every center
203
+ outer = region(mesh, grad=False, **options)
204
+ faces = outer.mesh.cells_faces
205
+ centers = np.atleast_2d(np.asarray(centers, dtype=float))
206
+ if atol is None:
207
+ atol = 1e-6 * np.linalg.norm(np.ptp(points[np.unique(mesh.cells)], axis=0))
208
+ distance = np.linalg.norm(
209
+ points[faces].mean(axis=1)[:, None] - centers[None], axis=2
210
+ )
211
+ nearest = distance.argmin(axis=0)
212
+ missing = centers[distance[nearest, np.arange(len(centers))] > atol]
213
+ if len(missing):
214
+ raise ValueError(f"There is no face with the center {missing.tolist()}.")
215
+ chosen = np.unique(nearest)
216
+
217
+ # the boundary region of the cells of the chosen faces (each cell once) and of
218
+ # the points of these faces
219
+ cells = {tuple(c): i for i, c in enumerate(np.sort(mesh.cells, axis=1))}
220
+ owners = sorted(
221
+ {cells[tuple(c)] for c in np.sort(outer.mesh.cells[chosen], axis=1)}
222
+ )
223
+ selected = mesh.copy()
224
+ selected.update(cells=mesh.cells[owners])
225
+ mask = np.zeros(len(points), dtype=bool)
226
+ mask[faces[chosen]] = True
227
+ result = region(selected, mask=mask, **options)
228
+ if len(result.mesh.cells) != len(chosen):
229
+ raise ValueError(
230
+ f"The points of the {len(chosen)} faces select {len(result.mesh.cells)} "
231
+ "faces; take the faces of one side, or a plane."
232
+ )
233
+ return result
234
+
235
+
236
+ # --- embedded in generated scripts with surface point sets ---
237
+ # the edges of 2D cells: their corners and their mid point (2D cells of the MINI
238
+ # element have a bubble point inside)
239
+ EDGES = {
240
+ "triangle": [[0, 1], [1, 2], [2, 0]],
241
+ "triangle4": [[0, 1], [1, 2], [2, 0]],
242
+ "triangle6": [[0, 1, 3], [1, 2, 4], [2, 0, 5]],
243
+ "quad": [[0, 1], [1, 2], [2, 3], [3, 0]],
244
+ "quad8": [[0, 1, 4], [1, 2, 5], [2, 3, 6], [3, 0, 7]],
245
+ "quad9": [[0, 1, 4], [1, 2, 5], [2, 3, 6], [3, 0, 7]],
246
+ }
247
+
248
+
249
+ def surface_points(meshes, points):
250
+ """Return a mask of the points on the outer surface of meshes with the given
251
+ points, e.g. the meshes of the sections with the merged points (#222): the points
252
+ of the faces which belong to one cell, like the surface of ``mesh.plot()``, or of
253
+ the edges which belong to one cell of 2D cells. Faces or edges of two meshes at
254
+ an interface are inside."""
255
+ from felupe.view._surface import triangulate_surface
256
+
257
+ mask = np.zeros(len(points), dtype=bool)
258
+ if all(mesh.cell_type in EDGES for mesh in meshes):
259
+ blocks = [m.cells[:, edge] for m in meshes for edge in EDGES[m.cell_type]]
260
+ corners = np.vstack([np.sort(block[:, :2], axis=1) for block in blocks])
261
+ _, inverse, counts = np.unique(
262
+ corners, axis=0, return_inverse=True, return_counts=True
263
+ )
264
+ once = np.split(
265
+ counts[inverse.ravel()] == 1, np.cumsum([len(b) for b in blocks])[:-1]
266
+ )
267
+ for block, outer in zip(blocks, once, strict=True):
268
+ mask[block[outer]] = True
269
+ return mask
270
+ # the cells of the MINI element without their bubble points
271
+ corners = {"tetra5": ("tetra", 4)}
272
+ solids = []
273
+ for mesh in meshes:
274
+ cell_type, npoints = corners.get(mesh.cell_type, (mesh.cell_type, None))
275
+ solids.append(fem.Mesh(points, mesh.cells[:, :npoints], cell_type))
276
+ surface = triangulate_surface(solids)
277
+ mask[np.unique(surface.interpolation.tocsr().indices)] = True
278
+ return mask
279
+
280
+
281
+ # --- embedded in generated scripts with meshes of scripts ---
282
+ def script_mesh(file, parameters, item=None):
283
+ """Run a Python script that makes a mesh, with the parameters as variables, and
284
+ return its variable ``mesh`` as a meshio mesh. The mesh is a ``fem.Mesh``, a
285
+ ``fem.MeshContainer``, a ``meshio.Mesh`` or a dict of names and meshes, of which
286
+ ``item`` is taken."""
287
+ import runpy
288
+
289
+ namespace = runpy.run_path(str(file), init_globals=dict(parameters))
290
+ if "mesh" not in namespace:
291
+ raise ValueError(f"The script '{file}' makes no variable 'mesh'.")
292
+ mesh = namespace["mesh"]
293
+ if isinstance(mesh, dict):
294
+ if item not in mesh:
295
+ raise ValueError(
296
+ f"The mesh of '{file}' is a dict of {list(mesh)}: take one of them, "
297
+ f"not {item!r}."
298
+ )
299
+ mesh = mesh[item]
300
+ elif item is not None:
301
+ raise ValueError(f"The mesh of '{file}' is not a dict with an item {item!r}.")
302
+ if isinstance(mesh, (fem.Mesh, fem.MeshContainer)):
303
+ mesh = mesh.as_meshio()
304
+ if not isinstance(mesh, meshio.Mesh):
305
+ raise TypeError(
306
+ f"The mesh of '{file}' is a {type(mesh).__name__}, not a fem.Mesh, a "
307
+ "fem.MeshContainer, a meshio.Mesh or a dict of them."
308
+ )
309
+ return mesh
310
+
311
+
312
+ def run_mesh_script(file, parameters, item=None, tag=None, cell_type=None, dim=3):
313
+ """Return the solid cells of the mesh of a script, like ``volume_cells()``."""
314
+ mesh = script_mesh(file, parameters, item)
315
+ return volume_cells(mesh, tag=tag, cell_type=cell_type, dim=dim)
316
+
317
+
318
+ # --- embedded in generated scripts with linear solvers ---
319
+ def spsolve(A, b):
320
+ """Solve a linear system with ``scipy.sparse.linalg.spsolve``, the linear solver
321
+ of FElupe before v12."""
322
+ from scipy.sparse import linalg
323
+
324
+ return linalg.spsolve(A, b)
325
+
326
+
327
+ def iterative_solver(method, rtol, maxiter=None):
328
+ """Return a linear solver ``solver(A, b)`` with an iterative method of
329
+ ``scipy.sparse.linalg`` (``minres``, ``cg``, ``gmres`` or ``bicgstab``) and a
330
+ relative tolerance of the norm of the residual. It raises if the method does not
331
+ converge, so that the Newton iteration fails instead of continuing with a poor
332
+ solution."""
333
+ from scipy.sparse import linalg
334
+
335
+ solve = getattr(linalg, method)
336
+
337
+ def solver(A, b):
338
+ x, info = solve(A, b, rtol=rtol, maxiter=maxiter)
339
+ if info != 0:
340
+ within = f" within maxiter={maxiter}" if maxiter else ""
341
+ raise RuntimeError(
342
+ f"The linear solver {method} did not converge to rtol={rtol}"
343
+ f"{within} (info={info}). Allow more iterations (maxiter) or take a "
344
+ "direct solver (SuperLU or spsolve)."
345
+ )
346
+ return x
347
+
348
+ return solver
349
+
350
+
351
+ def single_precision(solver):
352
+ """Return a linear solver ``solver(A, b)`` which solves in single precision
353
+ (``float32``): the matrix, the right-hand side and the factorization need half the
354
+ memory. The increment is returned in the precision of the right-hand side, so the
355
+ residual forces and the convergence check of the Newton iteration stay in double
356
+ precision (ADR 0016)."""
357
+
358
+ def solve(A, b):
359
+ return solver(A.astype(np.float32), b.astype(np.float32)).astype(b.dtype)
360
+
361
+ return solve
@@ -0,0 +1,74 @@
1
+ """Benchmark of FElupe for the Pyodide spike (#9).
2
+
3
+ The same module runs in CPython (tests, native reference) and in Pyodide (browser).
4
+ It times a uniaxial tension test of a hyperelastic cube for several mesh sizes, in
5
+ double precision, with the linear equation system in single precision, or with the
6
+ model in single precision (ADR 0016).
7
+ """
8
+
9
+ from time import perf_counter
10
+
11
+ import numpy as np
12
+
13
+
14
+ def benchmark(n=5, num=5, precision="double"):
15
+ r"""Run a uniaxial tension test of a unit cube with ``n`` points per edge.
16
+
17
+ Parameters
18
+ ----------
19
+ n : int, optional
20
+ Number of points per edge of the cube (default is 5).
21
+ num : int, optional
22
+ Number of load increments (default is 5).
23
+ precision : str, optional
24
+ ``"double"`` (default), ``"single"`` for the linear equation system in single
25
+ precision (``float32``, the model in double precision) or ``"model"`` for the
26
+ model in single precision (the region and the field in ``float32``, #297),
27
+ see ADR 0016.
28
+
29
+ Returns
30
+ -------
31
+ dict
32
+ Number of points, cells and degrees of freedom, the precision, timings in
33
+ seconds for the model setup and the solution, and the final reaction force.
34
+ """
35
+ import felupe as fem
36
+
37
+ t0 = perf_counter()
38
+ mesh = fem.Cube(n=n)
39
+ region = fem.RegionHexahedron(mesh)
40
+ dtype = None
41
+ if precision == "model":
42
+ dtype = np.float32
43
+ region = region.astype(dtype)
44
+ field = fem.FieldContainer([fem.Field(region, dim=3, dtype=dtype)])
45
+ boundaries = fem.dof.uniaxial(field, clamped=True)
46
+ umat = fem.NeoHookeCompressible(mu=1.0, lmbda=2.0)
47
+ solid = fem.SolidBody(umat, field)
48
+ move = fem.math.linsteps([0, 1], num=num)
49
+ step = fem.Step(
50
+ items=[solid], ramp={boundaries["move"]: move}, boundaries=boundaries
51
+ )
52
+ job = fem.CharacteristicCurve(steps=[step], boundary=boundaries["move"])
53
+
54
+ solver = fem.solve.SuperLUSolver()
55
+ if precision == "single":
56
+ from ._helpers import single_precision
57
+
58
+ solver = single_precision(solver)
59
+
60
+ t1 = perf_counter()
61
+ job.evaluate(verbose=0, solver=solver)
62
+ t2 = perf_counter()
63
+
64
+ return {
65
+ "n": n,
66
+ "points": int(mesh.npoints),
67
+ "cells": int(mesh.ncells),
68
+ "dofs": int(field[0].values.size),
69
+ "increments": num,
70
+ "precision": precision,
71
+ "setup": t1 - t0,
72
+ "solve": t2 - t1,
73
+ "force": float(np.array(job.y)[-1, 0]),
74
+ }