morphogen 1.0.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 (381) hide show
  1. morphogen/__init__.py +60 -0
  2. morphogen/__main__.py +7 -0
  3. morphogen/_platform.py +55 -0
  4. morphogen/_public.py +153 -0
  5. morphogen/_utils.py +80 -0
  6. morphogen/_version.py +1 -0
  7. morphogen/analysis/__init__.py +174 -0
  8. morphogen/analysis/anisotropy.py +135 -0
  9. morphogen/analysis/basic.py +38 -0
  10. morphogen/analysis/cells.py +54 -0
  11. morphogen/analysis/connectivity.py +156 -0
  12. morphogen/analysis/correlation.py +195 -0
  13. morphogen/analysis/covariance.py +80 -0
  14. morphogen/analysis/fractal.py +54 -0
  15. morphogen/analysis/measures.py +188 -0
  16. morphogen/analysis/morphology.py +265 -0
  17. morphogen/analysis/particles.py +160 -0
  18. morphogen/analysis/percolation.py +2034 -0
  19. morphogen/analysis/power_laws.py +143 -0
  20. morphogen/analysis/random_sets.py +351 -0
  21. morphogen/analysis/stereology.py +289 -0
  22. morphogen/analysis/surface.py +107 -0
  23. morphogen/analysis/topology.py +92 -0
  24. morphogen/automata/__init__.py +74 -0
  25. morphogen/automata/engine.py +211 -0
  26. morphogen/automata/growth.py +686 -0
  27. morphogen/automata/lattice.py +143 -0
  28. morphogen/automata/reaction.py +255 -0
  29. morphogen/automata/rules.py +353 -0
  30. morphogen/automata/tilings.py +1715 -0
  31. morphogen/cli.py +3526 -0
  32. morphogen/config.py +2167 -0
  33. morphogen/contact/__init__.py +113 -0
  34. morphogen/contact/experiments.py +368 -0
  35. morphogen/contact/hertz.py +104 -0
  36. morphogen/contact/kernels.py +827 -0
  37. morphogen/contact/periodic.py +278 -0
  38. morphogen/contact/problem.py +578 -0
  39. morphogen/contact/surfaces.py +310 -0
  40. morphogen/coupling/__init__.py +43 -0
  41. morphogen/coupling/ageing.py +143 -0
  42. morphogen/coupling/diffusion.py +226 -0
  43. morphogen/coupling/fenicsx.py +484 -0
  44. morphogen/coupling/oxidation.py +447 -0
  45. morphogen/coupling/plates.py +247 -0
  46. morphogen/design/__init__.py +51 -0
  47. morphogen/design/csp.py +616 -0
  48. morphogen/design/frames.py +277 -0
  49. morphogen/design/search.py +287 -0
  50. morphogen/design/tiles.py +336 -0
  51. morphogen/distributions.py +312 -0
  52. morphogen/domain.py +203 -0
  53. morphogen/dynamics/__init__.py +179 -0
  54. morphogen/dynamics/model.py +638 -0
  55. morphogen/dynamics/openradioss.py +643 -0
  56. morphogen/dynamics/results.py +515 -0
  57. morphogen/fracture/__init__.py +170 -0
  58. morphogen/fracture/bulk.py +349 -0
  59. morphogen/fracture/cohesive.py +1614 -0
  60. morphogen/fracture/ductile.py +557 -0
  61. morphogen/fracture/lefm.py +1168 -0
  62. morphogen/fracture/mixed.py +1178 -0
  63. morphogen/fracture/periodic.py +733 -0
  64. morphogen/fracture/phasefield.py +714 -0
  65. morphogen/fracture/phasefield_finite.py +368 -0
  66. morphogen/fracture/surface.py +572 -0
  67. morphogen/fracture/toughness.py +566 -0
  68. morphogen/gpu.py +108 -0
  69. morphogen/gui/__init__.py +8 -0
  70. morphogen/gui/api.py +1927 -0
  71. morphogen/gui/desktop.py +387 -0
  72. morphogen/gui/icon.png +0 -0
  73. morphogen/gui/index.html +1909 -0
  74. morphogen/gui/server.py +229 -0
  75. morphogen/gui/tools/__init__.py +629 -0
  76. morphogen/gui/tools/compare.py +149 -0
  77. morphogen/gui/tools/contact.py +391 -0
  78. morphogen/gui/tools/couplings.py +1085 -0
  79. morphogen/gui/tools/crackfront.py +245 -0
  80. morphogen/gui/tools/design.py +224 -0
  81. morphogen/gui/tools/dynamics.py +824 -0
  82. morphogen/gui/tools/fracture.py +2586 -0
  83. morphogen/gui/tools/interop.py +1654 -0
  84. morphogen/gui/tools/learning.py +595 -0
  85. morphogen/gui/tools/mechanics.py +3881 -0
  86. morphogen/gui/tools/nonlocal_damage.py +1321 -0
  87. morphogen/gui/tools/phasefield.py +215 -0
  88. morphogen/gui/tools/physics.py +597 -0
  89. morphogen/gui/tools/stability.py +1756 -0
  90. morphogen/gui/tools/statistics.py +1408 -0
  91. morphogen/gui/viewer.js +1100 -0
  92. morphogen/homogenization/__init__.py +210 -0
  93. morphogen/homogenization/acoustics.py +566 -0
  94. morphogen/homogenization/amg.py +1005 -0
  95. morphogen/homogenization/apparent.py +1046 -0
  96. morphogen/homogenization/behaviours.cu +2285 -0
  97. morphogen/homogenization/behaviours.py +944 -0
  98. morphogen/homogenization/beremin.py +263 -0
  99. morphogen/homogenization/bifurcation.py +1085 -0
  100. morphogen/homogenization/bloch.py +507 -0
  101. morphogen/homogenization/bounds.py +226 -0
  102. morphogen/homogenization/core.py +458 -0
  103. morphogen/homogenization/coupled.py +1135 -0
  104. morphogen/homogenization/crystal.py +2967 -0
  105. morphogen/homogenization/dilatation.py +454 -0
  106. morphogen/homogenization/elements.py +157 -0
  107. morphogen/homogenization/fatigue.py +768 -0
  108. morphogen/homogenization/fe.py +1739 -0
  109. morphogen/homogenization/fenicsx.py +307 -0
  110. morphogen/homogenization/fft.py +499 -0
  111. morphogen/homogenization/fft_nonlinear.py +391 -0
  112. morphogen/homogenization/finite.py +613 -0
  113. morphogen/homogenization/flow.py +361 -0
  114. morphogen/homogenization/frames.py +1125 -0
  115. morphogen/homogenization/gpu.py +1241 -0
  116. morphogen/homogenization/harmonic.py +427 -0
  117. morphogen/homogenization/identification.py +579 -0
  118. morphogen/homogenization/kernels.py +760 -0
  119. morphogen/homogenization/laws.py +2061 -0
  120. morphogen/homogenization/materials.py +1080 -0
  121. morphogen/homogenization/mfront.py +589 -0
  122. morphogen/homogenization/networks.py +880 -0
  123. morphogen/homogenization/nonlinear.py +2612 -0
  124. morphogen/homogenization/ntfa.py +577 -0
  125. morphogen/homogenization/paths.py +476 -0
  126. morphogen/homogenization/photonic.py +467 -0
  127. morphogen/homogenization/poroelastic.py +212 -0
  128. morphogen/homogenization/porous.py +1120 -0
  129. morphogen/homogenization/postprocess.py +290 -0
  130. morphogen/homogenization/solvers.py +1140 -0
  131. morphogen/homogenization/tensors.py +240 -0
  132. morphogen/homogenization/voxel_fe.py +457 -0
  133. morphogen/homogenization/xfem.py +1016 -0
  134. morphogen/homogenization/zmat.py +1258 -0
  135. morphogen/iga/__init__.py +48 -0
  136. morphogen/iga/analysis.py +508 -0
  137. morphogen/iga/basis.py +214 -0
  138. morphogen/iga/geometry.py +501 -0
  139. morphogen/iga/homogenization.py +219 -0
  140. morphogen/iga/optimization.py +700 -0
  141. morphogen/iga/shapes.py +331 -0
  142. morphogen/image.py +128 -0
  143. morphogen/io/__init__.py +246 -0
  144. morphogen/io/amitex.py +741 -0
  145. morphogen/io/ebsd.py +881 -0
  146. morphogen/io/export.py +196 -0
  147. morphogen/io/geometry.py +158 -0
  148. morphogen/io/medit.py +147 -0
  149. morphogen/io/meshes.py +844 -0
  150. morphogen/io/metaimage.py +97 -0
  151. morphogen/io/mfront.py +1104 -0
  152. morphogen/io/native.py +57 -0
  153. morphogen/io/radioss.py +764 -0
  154. morphogen/io/solvers.py +371 -0
  155. morphogen/io/tables.py +278 -0
  156. morphogen/io/tiff.py +66 -0
  157. morphogen/io/vtk.py +701 -0
  158. morphogen/io/xdmf.py +200 -0
  159. morphogen/kernels/__init__.py +5 -0
  160. morphogen/kernels/annealing.py +192 -0
  161. morphogen/kernels/cells.py +69 -0
  162. morphogen/kernels/collective.py +87 -0
  163. morphogen/kernels/force_biased.py +595 -0
  164. morphogen/kernels/implicit.py +145 -0
  165. morphogen/kernels/leaves.py +132 -0
  166. morphogen/kernels/packing.py +304 -0
  167. morphogen/kernels/raster.py +279 -0
  168. morphogen/kernels/rsa.py +371 -0
  169. morphogen/kernels/union.py +135 -0
  170. morphogen/kernels/watershed.py +190 -0
  171. morphogen/laser/__init__.py +234 -0
  172. morphogen/laser/architectures.py +375 -0
  173. morphogen/laser/bending.py +216 -0
  174. morphogen/laser/cells.py +1694 -0
  175. morphogen/laser/design.py +940 -0
  176. morphogen/laser/figures.py +227 -0
  177. morphogen/laser/heat.py +804 -0
  178. morphogen/laser/materials.py +691 -0
  179. morphogen/laser/mechanics.py +1670 -0
  180. morphogen/laser/metallurgy.py +615 -0
  181. morphogen/laser/patterns.py +828 -0
  182. morphogen/laser/periodic.py +392 -0
  183. morphogen/laser/process.py +362 -0
  184. morphogen/laser/run.py +534 -0
  185. morphogen/laser/solid.py +216 -0
  186. morphogen/laser/specimen.py +200 -0
  187. morphogen/laser/structures.py +708 -0
  188. morphogen/learning/__init__.py +81 -0
  189. morphogen/learning/behaviour.py +398 -0
  190. morphogen/learning/data.py +328 -0
  191. morphogen/learning/learned.cpp +668 -0
  192. morphogen/learning/logarithmic.py +202 -0
  193. morphogen/learning/mfront.py +409 -0
  194. morphogen/learning/networks.py +767 -0
  195. morphogen/learning/run.py +212 -0
  196. morphogen/learning/standard.py +814 -0
  197. morphogen/learning/training.py +235 -0
  198. morphogen/mesh/__init__.py +29 -0
  199. morphogen/mesh/conforming.py +1423 -0
  200. morphogen/mesh/curved.py +600 -0
  201. morphogen/mesh/exact.py +1717 -0
  202. morphogen/mesh/octree.py +350 -0
  203. morphogen/mesh/polycrystal.py +1041 -0
  204. morphogen/mesh/polyhedra.py +677 -0
  205. morphogen/mesh/regularize.py +570 -0
  206. morphogen/mesh/surface.py +97 -0
  207. morphogen/mesh/tetra.py +512 -0
  208. morphogen/mesh/voxel.py +124 -0
  209. morphogen/micromorphic/__init__.py +31 -0
  210. morphogen/micromorphic/damage.py +359 -0
  211. morphogen/micromorphic/ductile.py +534 -0
  212. morphogen/micromorphic/finite.py +220 -0
  213. morphogen/micromorphic/microfoam.py +787 -0
  214. morphogen/micromorphic/space.py +341 -0
  215. morphogen/models/__init__.py +195 -0
  216. morphogen/models/affine.py +384 -0
  217. morphogen/models/automata.py +592 -0
  218. morphogen/models/base.py +500 -0
  219. morphogen/models/boolean.py +310 -0
  220. morphogen/models/bouligand.py +331 -0
  221. morphogen/models/branching.py +241 -0
  222. morphogen/models/combination.py +430 -0
  223. morphogen/models/deadleaves.py +766 -0
  224. morphogen/models/design.py +289 -0
  225. morphogen/models/ebsd.py +206 -0
  226. morphogen/models/fibers.py +1476 -0
  227. morphogen/models/foam.py +594 -0
  228. morphogen/models/gaussian.py +314 -0
  229. morphogen/models/growth.py +459 -0
  230. morphogen/models/hardcore.py +317 -0
  231. morphogen/models/hierarchical.py +269 -0
  232. morphogen/models/honeycomb.py +749 -0
  233. morphogen/models/implicit.py +177 -0
  234. morphogen/models/laminate.py +470 -0
  235. morphogen/models/lattice.py +351 -0
  236. morphogen/models/lattice_field.py +345 -0
  237. morphogen/models/levelset_foam.py +563 -0
  238. morphogen/models/nacre.py +411 -0
  239. morphogen/models/nested.py +924 -0
  240. morphogen/models/osteons.py +374 -0
  241. morphogen/models/pieces.py +167 -0
  242. morphogen/models/planar.py +126 -0
  243. morphogen/models/reconstruction.py +203 -0
  244. morphogen/models/scale_rich.py +1409 -0
  245. morphogen/models/scale_rich_3d.py +1616 -0
  246. morphogen/models/tessellation.py +735 -0
  247. morphogen/models/tiling_field.py +302 -0
  248. morphogen/models/tpms.py +197 -0
  249. morphogen/models/transparent.py +406 -0
  250. morphogen/models/union.py +141 -0
  251. morphogen/optimization/__init__.py +43 -0
  252. morphogen/optimization/cell.py +295 -0
  253. morphogen/optimization/filters.py +115 -0
  254. morphogen/optimization/mma.py +226 -0
  255. morphogen/optimization/run.py +219 -0
  256. morphogen/optimization/topology.py +632 -0
  257. morphogen/orientations.py +568 -0
  258. morphogen/parallel.py +599 -0
  259. morphogen/pipeline.py +978 -0
  260. morphogen/primitives.py +188 -0
  261. morphogen/results.py +564 -0
  262. morphogen/rve/__init__.py +73 -0
  263. morphogen/rve/report.py +627 -0
  264. morphogen/rve/scaling.py +363 -0
  265. morphogen/rve/study.py +1054 -0
  266. morphogen/rve/windows.py +345 -0
  267. morphogen/seeding.py +51 -0
  268. morphogen/settings.py +118 -0
  269. morphogen/stopping.py +48 -0
  270. morphogen/symmetry.py +384 -0
  271. morphogen/templates/activator_inhibitor.yaml +22 -0
  272. morphogen/templates/aggregation.yaml +23 -0
  273. morphogen/templates/boolean_cylinders.yaml +20 -0
  274. morphogen/templates/boolean_spheres.yaml +22 -0
  275. morphogen/templates/bouligand.yaml +28 -0
  276. morphogen/templates/cellular_automaton.yaml +25 -0
  277. morphogen/templates/coated_spheres.yaml +26 -0
  278. morphogen/templates/contact_fibers.yaml +27 -0
  279. morphogen/templates/cox_nanocomposite.yaml +22 -0
  280. morphogen/templates/cross_linked_fibers.yaml +26 -0
  281. morphogen/templates/curved_arcs.yaml +28 -0
  282. morphogen/templates/curved_fibers.yaml +24 -0
  283. morphogen/templates/dead_leaves.yaml +22 -0
  284. morphogen/templates/delaunay_network.yaml +22 -0
  285. morphogen/templates/dense_packing.yaml +22 -0
  286. morphogen/templates/diffusion.yaml +33 -0
  287. morphogen/templates/ebsd.yaml +34 -0
  288. morphogen/templates/ebsd_map.ctf +3087 -0
  289. morphogen/templates/fracture_composite.yaml +42 -0
  290. morphogen/templates/fracture_rubber.yaml +47 -0
  291. morphogen/templates/gaussian_excursion.yaml +17 -0
  292. morphogen/templates/graded_lattice.yaml +24 -0
  293. morphogen/templates/hardcore_fibers.yaml +22 -0
  294. morphogen/templates/hardcore_spheres.yaml +22 -0
  295. morphogen/templates/hierarchical_lattice.yaml +22 -0
  296. morphogen/templates/homogenization_acoustic_foam.yaml +36 -0
  297. morphogen/templates/homogenization_beremin.yaml +50 -0
  298. morphogen/templates/homogenization_cleavage.yaml +51 -0
  299. morphogen/templates/homogenization_cleavage_band.yaml +55 -0
  300. morphogen/templates/homogenization_contact.yaml +43 -0
  301. morphogen/templates/homogenization_crack_closure.yaml +49 -0
  302. morphogen/templates/homogenization_crystal_plasticity.yaml +50 -0
  303. morphogen/templates/homogenization_crystal_plasticity_fft.yaml +52 -0
  304. morphogen/templates/homogenization_crystallization.yaml +30 -0
  305. morphogen/templates/homogenization_debonding.yaml +43 -0
  306. morphogen/templates/homogenization_detwinning.yaml +58 -0
  307. morphogen/templates/homogenization_ductile_damage.yaml +47 -0
  308. morphogen/templates/homogenization_fatigue.yaml +40 -0
  309. morphogen/templates/homogenization_grain_fracture.yaml +56 -0
  310. morphogen/templates/homogenization_gyroid.yaml +30 -0
  311. morphogen/templates/homogenization_intergranular.yaml +43 -0
  312. morphogen/templates/homogenization_interphase.yaml +42 -0
  313. morphogen/templates/homogenization_mixed_loading.yaml +33 -0
  314. morphogen/templates/homogenization_ntfa.yaml +56 -0
  315. morphogen/templates/homogenization_piezoelectric.yaml +27 -0
  316. morphogen/templates/homogenization_polycrystal.yaml +30 -0
  317. morphogen/templates/homogenization_polycrystal_inclusions.yaml +30 -0
  318. morphogen/templates/homogenization_poroelastic.yaml +26 -0
  319. morphogen/templates/homogenization_rubber.yaml +40 -0
  320. morphogen/templates/homogenization_slip_cleavage.yaml +50 -0
  321. morphogen/templates/homogenization_spheres.yaml +31 -0
  322. morphogen/templates/homogenization_transport.yaml +29 -0
  323. morphogen/templates/homogenization_twinning.yaml +54 -0
  324. morphogen/templates/homogenization_viscoelastic.yaml +34 -0
  325. morphogen/templates/homogenization_viscoplastic.yaml +42 -0
  326. morphogen/templates/homogenization_voronoi.yaml +26 -0
  327. morphogen/templates/homogenization_xfem.yaml +23 -0
  328. morphogen/templates/hyperuniform_cells.yaml +24 -0
  329. morphogen/templates/laguerre.yaml +18 -0
  330. morphogen/templates/laser_bending.yaml +35 -0
  331. morphogen/templates/laser_cells.yaml +38 -0
  332. morphogen/templates/laser_corrugated.yaml +36 -0
  333. morphogen/templates/level_set_foam.yaml +29 -0
  334. morphogen/templates/menger_sponge.yaml +17 -0
  335. morphogen/templates/nacre.yaml +25 -0
  336. morphogen/templates/nucleation_growth.yaml +25 -0
  337. morphogen/templates/optimize_auxetic.yaml +29 -0
  338. morphogen/templates/optimize_auxetic_3d.yaml +27 -0
  339. morphogen/templates/optimize_bulk.yaml +23 -0
  340. morphogen/templates/optimize_conductivity.yaml +20 -0
  341. morphogen/templates/osteons.yaml +28 -0
  342. morphogen/templates/penetrable_spheres.yaml +21 -0
  343. morphogen/templates/poisson_fibers.yaml +21 -0
  344. morphogen/templates/random_laminate.yaml +26 -0
  345. morphogen/templates/random_lattice.yaml +27 -0
  346. morphogen/templates/random_walk_fibers.yaml +26 -0
  347. morphogen/templates/reaction_diffusion.yaml +22 -0
  348. morphogen/templates/reconstruction.yaml +22 -0
  349. morphogen/templates/rve_cellular_automaton.yaml +23 -0
  350. morphogen/templates/rve_crystal_plasticity_fft.yaml +51 -0
  351. morphogen/templates/rve_multiphysics.yaml +43 -0
  352. morphogen/templates/rve_poisson_fibers.yaml +22 -0
  353. morphogen/templates/rve_poisson_fibers_fe.yaml +33 -0
  354. morphogen/templates/rve_voronoi_windows.yaml +20 -0
  355. morphogen/templates/scale_rich_network.yaml +29 -0
  356. morphogen/templates/scale_rich_plates.yaml +30 -0
  357. morphogen/templates/sequential_dead_leaves.yaml +25 -0
  358. morphogen/templates/strut_lattice.yaml +21 -0
  359. morphogen/templates/tile_assembly.yaml +28 -0
  360. morphogen/templates/tpms.yaml +19 -0
  361. morphogen/templates/trabecular_bone.yaml +29 -0
  362. morphogen/templates/transparent_dead_leaves.yaml +23 -0
  363. morphogen/templates/vascular_tree.yaml +23 -0
  364. morphogen/templates/voronoi.yaml +20 -0
  365. morphogen/templates/wood.yaml +34 -0
  366. morphogen/templates/workflow.yaml +56 -0
  367. morphogen/texture.py +665 -0
  368. morphogen/theory.py +162 -0
  369. morphogen/viz/__init__.py +12 -0
  370. morphogen/viz/export.py +244 -0
  371. morphogen/viz/figures.py +707 -0
  372. morphogen/viz/png.py +148 -0
  373. morphogen/viz/sections.py +696 -0
  374. morphogen/viz/surfaces.py +1352 -0
  375. morphogen/viz/video.py +904 -0
  376. morphogen/viz/workflow.py +488 -0
  377. morphogen-1.0.0.dist-info/METADATA +2316 -0
  378. morphogen-1.0.0.dist-info/RECORD +381 -0
  379. morphogen-1.0.0.dist-info/WHEEL +4 -0
  380. morphogen-1.0.0.dist-info/entry_points.txt +5 -0
  381. morphogen-1.0.0.dist-info/licenses/LICENSE +674 -0
@@ -0,0 +1,600 @@
1
+ """Quadratic tetrahedra whose nodes lie on the interfaces of the phases.
2
+
3
+ A conforming mesh (:func:`morphogen.mesh.conforming.conforming_mesh`) follows the
4
+ interfaces with flat triangles, whose corners lie on the level set as the background
5
+ mesh interpolates it: the phases of the mesh are polyhedra, which lose the volume
6
+ between the chords and the interface (a few percent of an inclusion meshed with a few
7
+ elements per radius). Ten-node tetrahedra made of them by adding the middles of their
8
+ edges (:meth:`~morphogen.mesh.tetra.TetMesh.quadratic`) keep that geometry: their
9
+ quadratic displacements are then more accurate than the domain they are computed on.
10
+
11
+ :func:`curved_mesh` puts the nodes of the interfaces on the implicit surfaces of the
12
+ microstructure (:meth:`~morphogen.models.base.Microstructure.phase_level_set`), the
13
+ corner nodes and the mid-edge nodes: each face of an interface becomes the quadratic
14
+ patch through six points of the surface, and the elements on both sides isoparametric
15
+ elements with curved edges (the other edges stay straight). The distance of the mesh to
16
+ the interface then falls as the cube of the size of the elements instead of its square,
17
+ and the volumes of the phases as its fourth power.
18
+
19
+ The surface between the phases ``a`` and ``b`` is the zero of ``φ_a - φ_b``, as for the
20
+ mesher; the wall of a pore left out of the mesh, that of the function of its solid. The
21
+ structures that give the functions of their phases at any point
22
+ (:meth:`~morphogen.models.base.Microstructure.phase_level_sets_at`: the unions of spheres
23
+ and of segments and their coatings, the fields, the leaves, the cells, the combinations of
24
+ these...) have their nodes put on their surfaces exactly; the functions of the others are
25
+ sampled on a grid finer than the elements and interpolated by cubic splines (which round
26
+ the folds of these functions over a cell or two: a layer thinner than a few cells loses or
27
+ gains some volume). This is the one curvature of the 10-node elements, of the meshes made
28
+ on a grid and of the exact ones (:mod:`morphogen.mesh.exact`) alike. A node is moved to
29
+ the zero along the gradient (Newton's method), within the
30
+ faces of the box for the nodes that lie on them (so that the faces stay plane, and
31
+ opposite faces keep matching nodes). Nodes where more than two phases meet stay where
32
+ they are, as do the nodes of whole periodic cells of polycrystals, whose faces are
33
+ plane. A move is bounded by a share of the edges around the node, and reduced where it
34
+ would flatten an element (the straight tetrahedra after the moves of the corners) or
35
+ where the volume element of a curved one would fall below a share of that of its
36
+ straight tetrahedron: the node of the element that moves most gives half of its move
37
+ away, until the element holds; the corner nodes held back start again from where they
38
+ are, in three steps at most.
39
+
40
+ Sharp edges. A mesh that follows the sharp edges of its phases (the grooves where the
41
+ spheres or segments of a union overlap; ``sharp_edges`` of
42
+ :func:`~morphogen.mesh.conforming.conforming_mesh`) has edges along them
43
+ (:attr:`~morphogen.mesh.tetra.TetMesh.sharp`), and knows the two smooth pieces of the
44
+ structure that meet along each (:mod:`morphogen.models.pieces`). The nodes of these
45
+ edges, corners and middles, are put where the surfaces of the two pieces meet — the
46
+ smallest move that brings them on both, by Newton's method — and on the three surfaces
47
+ where three sharp edges join: the curved edges of the elements follow the sharp edge.
48
+
49
+ What the curved elements do not mend is what the mesher did not resolve: the sharp edges
50
+ of the structures that do not give their smooth pieces are rounded over about an
51
+ element, as in the mesh of 4-node elements, and the gaps and layers thinner than the
52
+ grid of the mesher (``background``) are bridged or pinched. The nodes there stay off
53
+ their surfaces (``mesh.metadata["curved"]`` counts those that lie on them).
54
+ """
55
+
56
+ from __future__ import annotations
57
+
58
+ import logging
59
+ import time
60
+ from functools import partial
61
+
62
+ import numpy as np
63
+ from scipy import ndimage
64
+
65
+ from morphogen.mesh.tetra import (
66
+ TET10_NODES,
67
+ TET_EDGES,
68
+ TET_FACE_MIDS,
69
+ TET_FACES,
70
+ TetMesh,
71
+ corner_gradients,
72
+ jacobian_ratios,
73
+ tet_quality,
74
+ tet_volumes,
75
+ )
76
+
77
+ log = logging.getLogger("morphogen")
78
+
79
+ #: Cells of the grid of the implicit functions per size of the elements, the cells added
80
+ #: around the box for the splines, and the largest number of nodes of the grid along an
81
+ #: axis (a coarser sampling beyond it)
82
+ SAMPLES_PER_ELEMENT = 8
83
+ _PAD = 6
84
+ MAX_SAMPLES = 256
85
+ #: The steps of the corner nodes towards their surfaces, and the rounds of each way of
86
+ #: reducing the moves that an element does not bear (see :func:`_give_way`)
87
+ _STEPS = 3
88
+ _ROUNDS = 12
89
+ #: The four integration points of the 10-node tetrahedron (barycentric coordinates)
90
+ _GAUSS = np.full((4, 4), 0.1381966011250105) + (0.5854101966249685 - 0.1381966011250105) * np.eye(4)
91
+
92
+
93
+ class _Implicit:
94
+ """The implicit functions of the phases of a microstructure at any point: those of
95
+ the structure itself where it gives them there
96
+ (:meth:`~morphogen.models.base.Microstructure.phase_level_sets_at`; an object with a
97
+ ``level_set_at`` and no functions on grids: its two phases), exact; otherwise the
98
+ functions sampled at the nodes of a regular grid of the box and interpolated by cubic
99
+ splines (periodic along the ``axes`` where the mesh has matching faces)."""
100
+
101
+ def __init__(self, micro, spacing: float, axes, phases, reach: float):
102
+ from morphogen.mesh.conforming import node_level_set
103
+ from morphogen.models.implicit import functions_at, implicit_phases_of, point_functions
104
+
105
+ present = implicit_phases_of(micro)
106
+ lengths = np.asarray(micro.domain.lengths, dtype=float)
107
+ self.lower = np.asarray(micro.domain.lower, dtype=float)
108
+ self.coefficients: dict[int, np.ndarray] = {}
109
+ self.exact = None
110
+ two = present == [0, 1]
111
+ for k in phases:
112
+ if k not in present:
113
+ raise ValueError(f"phase {k}: the phases of this structure are {present}")
114
+ at = getattr(micro, "implicit_at", None)
115
+ centre = (self.lower + 0.5 * lengths)[None, :]
116
+ if at is not None:
117
+ exact = all(at(k, centre, 2.0 * reach) is not None for k in phases)
118
+ else: # an object with point-wise functions only
119
+ exact = not hasattr(micro, "level_set") and point_functions(micro)
120
+ if exact:
121
+ # the functions of the structure at the points themselves, within the size of
122
+ # the elements (the moves are a share of their edges; the functions of many
123
+ # objects, leaves or cells, cost as the cube of that reach)
124
+ self.exact = partial(functions_at, micro, reach=reach)
125
+ self.band = reach
126
+ self.spacing = np.full(3, 1e-3 * reach) # the step of the differences
127
+ self.sampling = 0.0
128
+ return
129
+ for k in sorted(phases):
130
+ if two and (1 - k) in self.coefficients: # the other phase: the opposite
131
+ self.coefficients[k] = -self.coefficients[1 - k]
132
+ continue
133
+ values, shape = node_level_set(micro, spacing, None if two else k)
134
+ if two and k == 0:
135
+ values = -values
136
+ self.spacing = lengths / np.array(shape)
137
+ for d in range(3):
138
+ width = [(0, 0)] * 3
139
+ width[d] = (_PAD, _PAD)
140
+ if axes[d]: # the last nodes are the first ones, one period further
141
+ values = np.pad(np.take(values, range(shape[d]), axis=d), width, mode="wrap")
142
+ else:
143
+ values = np.pad(values, width, mode="reflect", reflect_type="odd")
144
+ self.coefficients[k] = ndimage.spline_filter(values, order=3, mode="nearest")
145
+ self.sampling = float(self.spacing.max())
146
+
147
+ def _values(self, phases, points: np.ndarray) -> dict[int, np.ndarray]:
148
+ """The functions of ``phases`` at the points."""
149
+ if self.exact is not None:
150
+ out = self.exact(points)
151
+ return {k: np.clip(out[k], -self.band, self.band) for k in phases}
152
+ index = ((points - self.lower) / self.spacing + _PAD).T
153
+ return {
154
+ k: ndimage.map_coordinates(
155
+ self.coefficients[k], index, order=3, mode="nearest", prefilter=False
156
+ )
157
+ for k in phases
158
+ }
159
+
160
+ def gap(self, a: int, b: int, points: np.ndarray):
161
+ """The function whose zero is the interface of the phases ``a`` and ``b`` (``b``
162
+ negative: the boundary of ``a``) at ``points``, and its gradient (central
163
+ differences over half a cell of the grid)."""
164
+
165
+ def at(where):
166
+ if b < 0:
167
+ return self._values((a,), where)[a]
168
+ out = self._values((a, b), where)
169
+ return out[a] - out[b]
170
+
171
+ value = at(points)
172
+ gradient = np.empty_like(points)
173
+ for d in range(3):
174
+ shift = np.zeros(3)
175
+ shift[d] = 0.5 * self.spacing[d]
176
+ gradient[:, d] = (at(points + shift) - at(points - shift)) / self.spacing[d]
177
+ return value, gradient
178
+
179
+
180
+ def _interfaces(mesh: TetMesh) -> tuple[np.ndarray, np.ndarray]:
181
+ """The faces of a 10-node mesh between two phases, or between a phase and a pore left
182
+ out of the mesh (the free faces inside the box): their six nodes (corners, then
183
+ mid-edge nodes) and their two phases, the second -1 for a pore."""
184
+ elements = mesh.elements
185
+ corners = np.sort(elements[:, TET_FACES].reshape(-1, 3), axis=1)
186
+ _, inverse, counts = np.unique(corners, axis=0, return_inverse=True, return_counts=True)
187
+ order = np.argsort(inverse.ravel(), kind="stable")
188
+ start = np.concatenate([[0], np.cumsum(counts)[:-1]])
189
+ first = order[start] # one (element, face) of each face of the mesh
190
+ e1, f1 = first // 4, first % 4
191
+ shared = counts == 2
192
+ p1 = mesh.phase[e1]
193
+ p2 = np.full(len(counts), -1, dtype=np.int64)
194
+ p2[shared] = mesh.phase[order[start[shared] + 1] // 4]
195
+ x = mesh.nodes[elements[e1[:, None], TET_FACES[f1]]] # (faces, 3 corners, 3)
196
+ tol = mesh.tolerance()
197
+ on_box = np.zeros(len(counts), dtype=bool)
198
+ for d in range(3):
199
+ for target in (mesh.lower[d], mesh.upper[d]):
200
+ on_box |= np.all(np.abs(x[:, :, d] - target) <= tol, axis=1)
201
+ keep = (shared & (p1 != p2)) | (~shared & ~on_box)
202
+ e1, f1, p1, p2 = e1[keep], f1[keep], p1[keep], p2[keep]
203
+ faces = np.concatenate(
204
+ [elements[e1[:, None], TET_FACES[f1]], elements[e1[:, None], TET_FACE_MIDS[f1]]], axis=1
205
+ )
206
+ low, high = np.minimum(p1, p2), np.maximum(p1, p2)
207
+ pairs = np.where((p2 < 0)[:, None], np.stack([p1, p2], 1), np.stack([low, high], 1))
208
+ return faces, pairs
209
+
210
+
211
+ def _matched_pairs(mesh: TetMesh, axes) -> list[np.ndarray]:
212
+ """The pairs (node of a lower face, its image on the upper face) along the axes
213
+ where the faces of the mesh match."""
214
+ return [
215
+ mesh.periodic_pairs(d) if axes[d] else np.zeros((0, 2), dtype=np.int64) for d in range(3)
216
+ ]
217
+
218
+
219
+ def _representatives(n: int, pairs) -> np.ndarray:
220
+ """The node that stands for each node and its images across the box (itself, for a
221
+ node without images)."""
222
+ rep = np.arange(n)
223
+ for _ in range(3):
224
+ for pair in pairs:
225
+ if len(pair):
226
+ rep[pair[:, 1]] = rep[pair[:, 0]]
227
+ while True:
228
+ further = rep[rep]
229
+ if np.array_equal(further, rep):
230
+ return rep
231
+ rep = further
232
+
233
+
234
+ def _give_way(scale: np.ndarray, at: np.ndarray, far: np.ndarray, round_: int) -> None:
235
+ """Reduce the moves of the nodes ``at`` of the elements that do not bear them (a row
236
+ per element): in the first rounds the node of each element that moves most (``far``)
237
+ gives half of its move away; in the next ones all of its nodes do; in the last ones
238
+ they stay where they were."""
239
+ if round_ < _ROUNDS:
240
+ worst = at[np.arange(len(at)), np.argmax(scale[at] * far[at], axis=1)]
241
+ scale[worst] *= 0.5
242
+ elif round_ < 2 * _ROUNDS:
243
+ scale[at.ravel()] *= 0.5
244
+ else:
245
+ scale[at.ravel()] = 0.0
246
+
247
+
248
+ def _share(scale: np.ndarray, pairs) -> None:
249
+ """The smallest factor of a node and of its images across the box, for both."""
250
+ for _ in range(3): # the nodes of the edges and corners of the box have several images
251
+ for pair in pairs:
252
+ if len(pair):
253
+ least = np.minimum(scale[pair[:, 0]], scale[pair[:, 1]])
254
+ scale[pair[:, 0]] = scale[pair[:, 1]] = least
255
+
256
+
257
+ def _copy_images(nodes: np.ndarray, pairs) -> None:
258
+ """The nodes of the upper faces at the places of their images of the lower faces."""
259
+ for _ in range(3):
260
+ for axis, pair in enumerate(pairs):
261
+ if len(pair):
262
+ others = [d for d in range(3) if d != axis]
263
+ nodes[np.ix_(pair[:, 1], others)] = nodes[np.ix_(pair[:, 0], others)]
264
+
265
+
266
+ def _project(implicit, points, a, b, free, cap) -> tuple[np.ndarray, np.ndarray]:
267
+ """``points`` moved to the zero of the function of their pair of phases along its
268
+ gradient (Newton's method), within the directions ``free`` and by ``cap`` at most;
269
+ the points that find no zero closer than where they started stay there. Returns the
270
+ points and those that reached the surface."""
271
+ out = points.copy()
272
+ start, _ = implicit.gap(a, b, points)
273
+ scale = float(implicit.spacing.min())
274
+ value = start
275
+ for _ in range(12):
276
+ value, gradient = implicit.gap(a, b, out)
277
+ gradient = gradient * free
278
+ norm2 = (gradient**2).sum(axis=1)
279
+ slope = np.sqrt(np.maximum(norm2, 1e-300))
280
+ if np.all(np.abs(value) <= 1e-7 * scale * slope):
281
+ break
282
+ step = np.where(
283
+ (norm2 > 1e-12)[:, None],
284
+ -value[:, None] * gradient / np.maximum(norm2, 1e-300)[:, None],
285
+ 0.0,
286
+ )
287
+ move = out + step - points
288
+ length = np.linalg.norm(move, axis=1)
289
+ over = length > cap
290
+ move[over] *= (cap[over] / length[over])[:, None]
291
+ out = points + move
292
+ value, gradient = implicit.gap(a, b, out)
293
+ slope = np.sqrt(np.maximum(((gradient * free) ** 2).sum(axis=1), 1e-300))
294
+ reached = np.abs(value) <= 1e-4 * scale * slope
295
+ closer = np.abs(value) < np.abs(start)
296
+ out[~closer] = points[~closer]
297
+ return out, reached & closer
298
+
299
+
300
+ def _project_sharp(pieces, points, free, cap, step: float, band: float):
301
+ """``points`` moved to where the surfaces of ``pieces`` meet — two pieces: the sharp
302
+ edge along which they meet; three: the point where sharp edges join — by Newton's
303
+ method on the functions of the pieces, the smallest move at each step, within the
304
+ directions ``free`` and by ``cap`` at most. Returns the points and those that reached
305
+ all the surfaces (the others are left where they were)."""
306
+ out = points.copy()
307
+ count = len(pieces)
308
+
309
+ def functions(where):
310
+ return np.stack([piece.at(where, band) for piece in pieces], axis=1)
311
+
312
+ for _ in range(12):
313
+ value = functions(out)
314
+ if np.abs(value).max(initial=0.0) <= 1e-7 * step:
315
+ break
316
+ jacobian = np.empty((len(out), count, 3))
317
+ for d in range(3):
318
+ shift = np.zeros(3)
319
+ shift[d] = step
320
+ jacobian[:, :, d] = (functions(out + shift) - functions(out - shift)) / (2.0 * step)
321
+ jacobian *= free[:, None, :]
322
+ move = out - np.einsum("ndk,nk->nd", np.linalg.pinv(jacobian), value) - points
323
+ length = np.linalg.norm(move, axis=1)
324
+ over = length > cap
325
+ move[over] *= (cap[over] / length[over])[:, None]
326
+ out = points + move
327
+ reached = np.abs(functions(out)).max(axis=1, initial=0.0) <= 1e-3 * step
328
+ out[~reached] = points[~reached]
329
+ return out, reached
330
+
331
+
332
+ def _sharp_nodes(quad: TetMesh, rep: np.ndarray) -> dict[int, tuple[int, ...]]:
333
+ """The nodes of the sharp edges of a 10-node mesh (:attr:`~morphogen.mesh.tetra.
334
+ TetMesh.sharp`) and the pieces that meet at each: the two of its edges for a corner
335
+ node or the node of the middle of a sharp edge, more where sharp edges join; for
336
+ the nodes that stand for them and their images across the box."""
337
+ found: dict[int, set[int]] = {}
338
+ if quad.sharp is None or quad.sharp_pieces is None or not len(quad.sharp):
339
+ return {}
340
+ ends = np.sort(quad.elements[:, TET_EDGES].reshape(-1, 2), axis=1)
341
+ keys = ends[:, 0] * quad.n_nodes + ends[:, 1]
342
+ keys, first = np.unique(keys, return_index=True)
343
+ middles = quad.elements[:, 4:].reshape(-1)[first]
344
+ edges = np.sort(quad.sharp, axis=1)
345
+ wanted = edges[:, 0] * quad.n_nodes + edges[:, 1]
346
+ place = np.clip(np.searchsorted(keys, wanted), 0, len(keys) - 1)
347
+ there = keys[place] == wanted
348
+ rows = zip(edges.tolist(), quad.sharp_pieces.tolist(), middles[place].tolist(),
349
+ there.tolist(), strict=True) # fmt: skip
350
+ for (a, b), pair, middle, known in rows:
351
+ for node in (a, b, middle) if known else (a, b):
352
+ found.setdefault(int(rep[node]), set()).update(pair)
353
+ return {node: tuple(sorted(pieces)) for node, pieces in found.items()}
354
+
355
+
356
+ def curved_mesh(
357
+ mesh: TetMesh,
358
+ micro,
359
+ *,
360
+ sampling: float | None = None,
361
+ corners: bool = True,
362
+ max_move: float = 0.3,
363
+ min_jacobian: float = 0.3,
364
+ ) -> TetMesh:
365
+ """The 10-node mesh of ``mesh`` (4 or 10 nodes) whose nodes on the interfaces of the
366
+ phases lie on the implicit surfaces of the microstructure ``micro``: isoparametric
367
+ elements with curved edges along the interfaces (see the module).
368
+
369
+ The mesh of a microstructure without curved interfaces (polycrystals meshed by their
370
+ cells) comes back with straight edges. ``mesh.metadata["curved"]`` counts the nodes
371
+ of the interfaces and those that lie on their surfaces in the end (``nodes``), and
372
+ gives the largest departure of a mid-edge node from the middle of its edge. The
373
+ nodes that stay off their surfaces are those of the lines where three phases meet,
374
+ and those that an element holds back: at the sharp edges of a phase (the grooves
375
+ where two overlapping spheres meet), which the mesher rounds, and in the gaps and
376
+ layers that the grid of the mesher does not resolve (``background``).
377
+
378
+ Parameters
379
+ ----------
380
+ sampling
381
+ Spacing of the grid on which the implicit functions are sampled, for the
382
+ structures that do not give them at any point (by default an eighth of the size
383
+ of the elements, coarser for very fine meshes of large boxes).
384
+ corners
385
+ Move the corner nodes of the interfaces to the surfaces too (default); false
386
+ moves only the mid-edge nodes.
387
+ max_move
388
+ The largest move of a node, as a share of the shortest edge around it (corner
389
+ nodes, in each of their three steps at most) or of its edge (mid-edge nodes).
390
+ min_jacobian
391
+ The smallest ratio allowed between the volume element of a curved element (at
392
+ its nodes and integration points) and that of its straight tetrahedron; the
393
+ most bent edge of an element below it is straightened by half, until it holds.
394
+ """
395
+ quad = mesh.straight() if mesh.order == 2 else mesh.quadratic()
396
+ if quad.whole or quad.n_elements == 0:
397
+ return quad
398
+ t0 = time.perf_counter()
399
+ faces, pairs = _interfaces(quad)
400
+ if not len(faces):
401
+ return quad
402
+ n = quad.n_nodes
403
+ matching = quad.metadata.get("matching_faces", [0, 1, 2] if quad.periodic else [])
404
+ axes = tuple(d in matching for d in range(3))
405
+ images = _matched_pairs(quad, axes)
406
+ rep = _representatives(n, images)
407
+ # the pair of phases of each node of the interfaces, the same for its images across
408
+ # the box: the nodes of one pair move
409
+ width = int(pairs.max()) + 2
410
+ code = pairs[:, 0] * width + (pairs[:, 1] + 1)
411
+ lowest = np.full(n, np.iinfo(np.int64).max)
412
+ highest = np.full(n, -1)
413
+ np.minimum.at(lowest, rep[faces.ravel()], np.repeat(code, 6))
414
+ np.maximum.at(highest, rep[faces.ravel()], np.repeat(code, 6))
415
+ lowest, highest = lowest[rep], highest[rep]
416
+ single = (highest >= 0) & (lowest == highest)
417
+ tol = quad.tolerance()
418
+ free = np.ones((n, 3))
419
+ for d in range(3):
420
+ on_face = (np.abs(quad.nodes[:, d] - quad.lower[d]) <= tol) | (
421
+ np.abs(quad.nodes[:, d] - quad.upper[d]) <= tol
422
+ )
423
+ free[on_face, d] = 0.0
424
+ movable = single & free.any(axis=1)
425
+ is_corner = np.zeros(n, dtype=bool)
426
+ is_corner[quad.elements[:, :4]] = True
427
+
428
+ size = float(quad.metadata.get("size", 0.0)) or float(
429
+ np.median(np.linalg.norm(np.diff(quad.nodes[quad.elements[:, TET_EDGES]], axis=2), axis=-1))
430
+ )
431
+ lengths = np.asarray(micro.domain.lengths, dtype=float)
432
+ spacing = float(sampling) if sampling else size / SAMPLES_PER_ELEMENT
433
+ spacing = max(spacing, float(lengths.max()) / MAX_SAMPLES)
434
+ used = np.unique(pairs[np.isin(faces, np.flatnonzero(movable)).any(axis=1)])
435
+ implicit = _Implicit(micro, spacing, axes, [int(k) for k in used if k >= 0], size)
436
+
437
+ nodes = quad.nodes.copy()
438
+ edges = quad.elements[:, TET_EDGES].reshape(-1, 2)
439
+ # the nodes of the sharp edges that the mesh follows, and the pieces that meet there
440
+ sharp = _sharp_nodes(quad, rep)
441
+ pieces = None
442
+ if sharp:
443
+ depth = float(quad.metadata.get("sharp_edges", {}).get("depth", 0.0))
444
+ found = getattr(micro, "implicit_pieces", lambda depth: None)(depth)
445
+ pieces = None if found is None else found[0]
446
+ if pieces is None or max(max(group) for group in sharp.values()) >= len(pieces):
447
+ sharp, pieces = {}, None # another structure than that of the mesh
448
+
449
+ def groups(chosen: np.ndarray):
450
+ """The nodes ``chosen`` by pair of phases: their places in ``chosen``, the pair."""
451
+ for value in np.unique(lowest[chosen]):
452
+ yield lowest[chosen] == value, int(value // width), int(value % width) - 1
453
+
454
+ def project(chosen: np.ndarray, cap: np.ndarray, edges_too: bool = True) -> np.ndarray:
455
+ """The places on their surfaces of the nodes ``chosen`` (those found): on the
456
+ surface of their two phases, or (``edges_too``) where the pieces of a sharp edge
457
+ meet."""
458
+ target = nodes[chosen].copy()
459
+ for sel, a, b in groups(chosen):
460
+ target[sel], _ = _project(
461
+ implicit, nodes[chosen[sel]], a, b, free[chosen[sel]], cap[sel]
462
+ )
463
+ if sharp and edges_too:
464
+ along: dict[tuple, list[int]] = {}
465
+ for place, node in enumerate(chosen.tolist()):
466
+ if node in sharp:
467
+ along.setdefault(sharp[node], []).append(place)
468
+ for group, places in along.items():
469
+ at = np.array(places)
470
+ moved, reached = _project_sharp(
471
+ [pieces[k] for k in group], nodes[chosen[at]], free[chosen[at]], cap[at],
472
+ 1e-3 * size, 2.0 * size,
473
+ ) # fmt: skip
474
+ target[at[reached]] = moved[reached]
475
+ return target
476
+
477
+ # 1. the corner nodes, as far as the straight tetrahedra keep their shape: in a few
478
+ # steps, the nodes that an element held back starting again from where they are
479
+ own = rep == np.arange(n) # one node for a node and its images
480
+ chosen = np.flatnonzero(movable & is_corner & own)
481
+ if corners and chosen.size:
482
+ volume0 = tet_volumes(nodes, quad.elements)
483
+ quality0 = tet_quality(nodes, quad.elements)
484
+ # a last step without the sharp edges: a node that the elements hold back from
485
+ # its sharp edge goes to the surface of its two phases, a shorter way
486
+ for step in range(_STEPS + bool(sharp)):
487
+ edge_length = np.linalg.norm(nodes[edges[:, 0]] - nodes[edges[:, 1]], axis=1)
488
+ shortest = np.full(n, np.inf)
489
+ np.minimum.at(shortest, edges[:, 0], edge_length)
490
+ np.minimum.at(shortest, edges[:, 1], edge_length)
491
+ move = np.zeros((n, 3))
492
+ cap = max_move * shortest[chosen]
493
+ move[chosen] = project(chosen, cap, step < _STEPS) - nodes[chosen]
494
+ move = move[rep] # the images of a node across the box move as it does
495
+ far = np.linalg.norm(move, axis=1)
496
+ if far.max() <= 1e-9 * size:
497
+ if step < _STEPS and sharp:
498
+ continue
499
+ break
500
+ scale = np.ones(n)
501
+ bad = np.zeros(quad.n_elements, dtype=bool)
502
+ check = np.flatnonzero((far[quad.elements[:, :4]] > 0.0).any(axis=1))
503
+ for round_ in range(3 * _ROUNDS):
504
+ trial = nodes + scale[:, None] * move
505
+ part = quad.elements[check]
506
+ bad[check] = (tet_volumes(trial, part) < 0.5 * volume0[check]) | (
507
+ tet_quality(trial, part) < 0.5 * quality0[check]
508
+ )
509
+ if not bad.any():
510
+ break
511
+ before = scale.copy()
512
+ _give_way(scale, quad.elements[bad, :4], far, round_)
513
+ _share(scale, images)
514
+ # the elements of the nodes whose moves changed are checked again
515
+ check = np.flatnonzero((scale != before)[quad.elements[:, :4]].any(axis=1))
516
+ else: # an element still does not hold: no node moves in this step
517
+ if step < _STEPS and sharp:
518
+ continue
519
+ break
520
+ nodes += scale[:, None] * move
521
+ _copy_images(nodes, images)
522
+ # 2. the mid-edge nodes: the middles of the straight edges, then those of the
523
+ # interfaces on their surfaces
524
+ ends = quad.elements[:, TET_EDGES]
525
+ nodes[quad.elements[:, 4:]] = 0.5 * (nodes[ends[..., 0]] + nodes[ends[..., 1]])
526
+ middles = nodes.copy()
527
+ chosen = np.flatnonzero(movable & ~is_corner & own)
528
+ if chosen.size:
529
+ length = np.ones(n)
530
+ length[quad.elements[:, 4:].ravel()] = np.linalg.norm(
531
+ nodes[ends[..., 0]] - nodes[ends[..., 1]], axis=-1
532
+ ).ravel()
533
+ move = np.zeros((n, 3))
534
+ cap = max_move * length[chosen]
535
+ move[chosen] = project(chosen, cap) - nodes[chosen]
536
+ move = move[rep]
537
+ scale = np.ones(n)
538
+ mids = quad.elements[:, 4:]
539
+ points = np.concatenate([TET10_NODES, _GAUSS])
540
+ gradients = np.zeros((quad.n_elements, 4, 3))
541
+ bent = np.flatnonzero((np.abs(move[mids]).max(axis=2) > 0.0).any(axis=1))
542
+ gradients[bent] = corner_gradients(nodes, quad.elements[bent])
543
+
544
+ def hold() -> None:
545
+ """Reduce the moves of the mid-edge nodes until every element bears them."""
546
+ far = np.linalg.norm(move, axis=1) / length
547
+ bad = np.zeros(quad.n_elements, dtype=bool)
548
+ check = np.flatnonzero((far[mids] > 0.0).any(axis=1)) # the elements with a bent edge
549
+ for round_ in range(3 * _ROUNDS):
550
+ # the departures of the mid-edge nodes from the middles of their edges
551
+ deviation = scale[mids[check], None] * move[mids[check]]
552
+ ratio = jacobian_ratios(gradients[check], deviation, points).min(axis=1)
553
+ bad[check] = ratio < min_jacobian
554
+ if not bad.any():
555
+ return
556
+ before = scale.copy()
557
+ _give_way(scale, mids[bad], far, round_)
558
+ _share(scale, images)
559
+ check = np.flatnonzero((scale != before)[mids].any(axis=1))
560
+ scale[:] = 0.0 # an element still does not hold: straight edges everywhere
561
+
562
+ hold()
563
+ # the middles of sharp edges that the elements hold back: to the surface of their
564
+ # two phases instead, a shorter way
565
+ late = np.array([k for k in chosen.tolist() if k in sharp and scale[k] < 1.0], dtype=int)
566
+ if late.size:
567
+ cap = max_move * length[late]
568
+ again = np.zeros((n, 3))
569
+ again[late] = project(late, cap, False) - nodes[late]
570
+ again = again[rep]
571
+ moved = np.flatnonzero(np.isin(rep, late))
572
+ move[moved] = again[moved]
573
+ scale[moved] = 1.0
574
+ _share(scale, images)
575
+ hold()
576
+ nodes = middles + scale[:, None] * move
577
+ _copy_images(nodes, images)
578
+ out = quad._derived(nodes, quad.elements)
579
+ # the nodes that lie on their surfaces in the end
580
+ chosen = np.flatnonzero(movable)
581
+ reached = 0
582
+ for sel, a, b in groups(chosen):
583
+ value, gradient = implicit.gap(a, b, nodes[chosen[sel]])
584
+ slope = np.sqrt(np.maximum(((gradient * free[chosen[sel]]) ** 2).sum(axis=1), 1e-300))
585
+ reached += int(np.count_nonzero(np.abs(value) <= 1e-6 * size * slope))
586
+ out.metadata["curved"] = {
587
+ "nodes": reached,
588
+ "sharp_nodes": len(sharp),
589
+ "interface_nodes": int(np.count_nonzero(highest >= 0)),
590
+ "max_deviation": float(np.linalg.norm(nodes - middles, axis=1).max()),
591
+ "sampling": implicit.sampling, # 0: the functions of the model itself
592
+ "time_s": round(time.perf_counter() - t0, 3),
593
+ }
594
+ log.info(
595
+ "curved mesh: %d of %d nodes of the interfaces on their surfaces (%.1f s)",
596
+ reached,
597
+ int(np.count_nonzero(highest >= 0)),
598
+ time.perf_counter() - t0,
599
+ )
600
+ return out