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,1423 @@
1
+ """Conforming tetrahedral meshes of implicit morphologies.
2
+
3
+ The level-set function of a microstructure (negative inside phase 1) is sampled at the
4
+ nodes of a background mesh of the box: a Kuhn triangulation of a regular grid (six
5
+ tetrahedra per cube, so that the faces of the box are exactly represented). MMG
6
+ (``mmg3d -ls``, LGPL; installed by the ``pymmg`` package or found on the ``PATH``)
7
+ discretizes the zero level set into a conforming interface between the two phases and
8
+ remeshes the result: elements are adapted to the curvature of the interface within a
9
+ Hausdorff distance, graded, and of good quality, while the faces of the box stay plane.
10
+
11
+ For periodic microstructures, opposite faces get matching nodes, so that periodic
12
+ boundary conditions are exact: the level set takes the same values on opposite faces of
13
+ the background mesh, MMG first discretizes it without remeshing (the cut faces match),
14
+ then remeshes the volume and the interface while keeping the faces of the box
15
+ unchanged (along all the axes, or some of them). Elsewhere, the faces are remeshed
16
+ freely.
17
+
18
+ Mirrored meshes (:func:`mirrored_mesh`): a microstructure symmetric about the mid-planes
19
+ of its box is meshed in the irreducible part of the box and reflected across them, so
20
+ that the mesh has the symmetries exactly (an unstructured mesh of the whole box has
21
+ none), which the analyses by group theory need (:mod:`morphogen.homogenization.
22
+ bifurcation`); a periodic microstructure symmetric about its mid-planes is symmetric
23
+ about the faces of its box too, so that the reflected faces match: periodic conditions
24
+ apply. With the diagonal planes of a square or cubic box among its mirrors (the groups
25
+ of the square, 4/mmm, and of the cube, m-3m), the irreducible part is the chamber of the
26
+ group (a triangular prism, a tetrahedron), a union of tetrahedra of the background mesh,
27
+ meshed and mapped by every operation of the group. :class:`ImplicitBody` makes a
28
+ microstructure of a level-set function.
29
+
30
+ Sharp edges. The function of a union of spheres or segments has a fold where two of
31
+ them meet, and its surface a sharp edge there (a groove), which a function sampled on a
32
+ grid rounds. The structures made of such primitives give the smooth *pieces* of their
33
+ phases (:mod:`morphogen.models.pieces`: primitives that do not overlap); the box is then
34
+ cut by the surface of each piece in turn, the function of the piece taken at the
35
+ vertices themselves, and the lines where two cuts meet — the sharp edges — are edges of
36
+ the mesh, given to MMG as ridges and kept through the remeshing (``sharp_edges``;
37
+ :attr:`~morphogen.mesh.tetra.TetMesh.sharp`).
38
+
39
+ Element sizes: ``size`` bounds the edge length (``-hmax``); the interface is refined to
40
+ follow its curvature within the Hausdorff distance ``hausdorff``. Thin features must be
41
+ resolved by the background grid (``background``, default ``size / 2``) and by a few
42
+ elements: a sheet of thickness ``t`` needs ``size`` of the order of ``t`` with 10-node
43
+ elements, smaller with 4-node elements.
44
+ """
45
+
46
+ from __future__ import annotations
47
+
48
+ import importlib.util
49
+ import itertools
50
+ import logging
51
+ import os
52
+ import platform
53
+ import shutil
54
+ import subprocess
55
+ import tempfile
56
+ import time
57
+ from pathlib import Path
58
+
59
+ import numpy as np
60
+
61
+ from morphogen.domain import Domain, Grid
62
+ from morphogen.io import medit
63
+ from morphogen.mesh.tetra import TET_FACES, TetMesh, tet_volumes
64
+
65
+ log = logging.getLogger("morphogen")
66
+
67
+ #: MMG references of the subdomains created by the level-set discretization
68
+ REF_INSIDE, REF_OUTSIDE, REF_INTERFACE = 3, 2, 10
69
+ #: The references of the tetrahedra of a mesh of several phases: this plus their phase
70
+ REF_PHASE = 20
71
+ #: Level-set values closer to zero than this fraction of an edge of the background mesh
72
+ #: (times the gradient) are moved away from zero: the interface then never cuts an edge
73
+ #: close to a node, which avoids slivers and halves the remeshing time; the interface
74
+ #: moves by at most this fraction of the background spacing.
75
+ SNAP = 0.2
76
+ #: The references of the tetrahedra of the pieces of a mesh cut piece by piece (the
77
+ #: meshes that follow sharp edges): this plus the number of their piece
78
+ REF_PIECE = 1000
79
+ #: The references of the edges of MMG's mesh along the sharp edges of an interface:
80
+ #: this plus a number of the two pieces that meet there
81
+ REF_SHARP = 1000
82
+ #: :data:`SNAP` for the cuts of the pieces: the lines where two cuts meet are the sharp
83
+ #: edges, which a smaller share keeps within the Hausdorff distance of the remeshing
84
+ SNAP_SHARP = 0.05
85
+
86
+
87
+ def mmg_executable(path: str | None = None, program: str = "mmg3d") -> str:
88
+ """Path of an MMG executable (``mmg3d`` or ``mmg2d``): explicit,
89
+ ``$MORPHOGEN_MMG3D`` (``$MORPHOGEN_MMG2D``), the ``pymmg`` package, or
90
+ ``mmg3d_O3`` / ``mmg3d`` on the ``PATH``."""
91
+ if program not in ("mmg3d", "mmg2d"):
92
+ raise ValueError("program: 'mmg3d' or 'mmg2d'")
93
+ explicit = path or os.environ.get(f"MORPHOGEN_{program.upper()}")
94
+ if explicit:
95
+ if Path(explicit).is_file() and os.access(explicit, os.X_OK):
96
+ return str(explicit)
97
+ raise FileNotFoundError(f"{program} executable not found: {explicit}")
98
+ candidates = []
99
+ spec = importlib.util.find_spec(program) # the pymmg package
100
+ if spec is not None and spec.submodule_search_locations:
101
+ folder = Path(next(iter(spec.submodule_search_locations)))
102
+ names = (
103
+ [f"{program}.exe", f"{program}_O3.exe"]
104
+ if platform.system() == "Windows"
105
+ else [f"{program}_O3", program]
106
+ )
107
+ for name in names:
108
+ exe = folder / name
109
+ if exe.is_file() and not os.access(exe, os.X_OK):
110
+ try: # a wheel unpacked without its permission bits
111
+ exe.chmod(exe.stat().st_mode | 0o111)
112
+ except OSError:
113
+ pass
114
+ candidates.append(str(exe))
115
+ candidates += [shutil.which(f"{program}_O3"), shutil.which(program)]
116
+ for c in candidates:
117
+ if c and Path(c).is_file() and os.access(c, os.X_OK):
118
+ return c
119
+ raise ImportError(
120
+ f"conforming meshes need the MMG mesher ({program}): pip install pymmg "
121
+ f"(or install {program} and set MORPHOGEN_{program.upper()})"
122
+ )
123
+
124
+
125
+ def has_mmg() -> bool:
126
+ """Whether the MMG mesher is available."""
127
+ try:
128
+ mmg_executable()
129
+ except (ImportError, FileNotFoundError):
130
+ return False
131
+ return True
132
+
133
+
134
+ def background_mesh(shape, lower, upper):
135
+ """Triangulation of the box in six tetrahedra per cube: nodes, positive tetrahedra,
136
+ boundary triangles and their references (1-6 for the faces x0, x1, y0, y1, z0, z1).
137
+
138
+ Each cube is split along a main diagonal (Kuhn triangulation), reflected along the
139
+ axes where the cube index is odd: the triangulation stays conforming, its opposite
140
+ faces match, and it is symmetric with respect to the planes of the grid (a single
141
+ diagonal direction would bias the discretized interfaces and make the apparent
142
+ stiffness of cubic structures slightly anisotropic).
143
+ """
144
+ n = np.asarray(shape, dtype=np.int64)
145
+ lower = np.asarray(lower, dtype=float)
146
+ upper = np.asarray(upper, dtype=float)
147
+ g = n + 1
148
+ axes = [np.linspace(lower[d], upper[d], g[d]) for d in range(3)]
149
+ gx, gy, gz = np.meshgrid(*axes, indexing="ij")
150
+ nodes = np.stack([gx, gy, gz], axis=-1).reshape(-1, 3)
151
+ for d in range(3): # exact faces
152
+ nodes[:, d] = np.where(np.isclose(nodes[:, d], lower[d]), lower[d], nodes[:, d])
153
+ nodes[:, d] = np.where(np.isclose(nodes[:, d], upper[d]), upper[d], nodes[:, d])
154
+ cubes = np.stack(np.meshgrid(*(np.arange(k) for k in n), indexing="ij"), axis=-1).reshape(-1, 3)
155
+ odd = cubes % 2 == 1
156
+ strides = np.array([g[1] * g[2], g[2], 1])
157
+ tets = []
158
+ for perm in itertools.permutations(range(3)):
159
+ corner = np.zeros(3, dtype=np.int64)
160
+ path = [corner.copy()]
161
+ for axis in perm:
162
+ corner[axis] += 1
163
+ path.append(corner.copy())
164
+ tets.append(np.stack([(cubes + np.where(odd, 1 - p, p)) @ strides for p in path], axis=1))
165
+ tets = np.concatenate(tets)
166
+ flip = tet_volumes(nodes, tets) < 0
167
+ tets[flip] = tets[flip][:, [0, 2, 1, 3]]
168
+ faces = np.concatenate(
169
+ [tets[:, [0, 2, 1]], tets[:, [0, 1, 3]], tets[:, [1, 2, 3]], tets[:, [0, 3, 2]]]
170
+ )
171
+ tri, refs = [], []
172
+ for axis in range(3):
173
+ for side, value in ((0, lower[axis]), (1, upper[axis])):
174
+ on = np.all(nodes[faces][:, :, axis] == value, axis=1)
175
+ tri.append(faces[on])
176
+ refs.append(np.full(int(on.sum()), 1 + 2 * axis + side))
177
+ return nodes, tets, np.concatenate(tri), np.concatenate(refs)
178
+
179
+
180
+ def node_level_set(
181
+ micro, spacing: float, phase: int | None = None
182
+ ) -> tuple[np.ndarray, tuple[int, int, int]]:
183
+ """Level-set values at the nodes of a regular grid covering the box exactly: those of
184
+ the phase 1, or of the implicit function of ``phase``
185
+ (:meth:`~morphogen.models.base.Microstructure.phase_level_set`)."""
186
+ domain: Domain = micro.domain
187
+ n = np.maximum(1, np.ceil(domain.lengths / spacing - 1e-9)).astype(int)
188
+ h = domain.lengths / n
189
+ sampling = Domain(
190
+ size=tuple(domain.lengths + h), origin=tuple(domain.lower - h / 2), periodic=False
191
+ )
192
+ grid = Grid(sampling, tuple(int(k) + 1 for k in n))
193
+ try:
194
+ if phase is None:
195
+ field = micro.level_set(grid=grid)
196
+ else:
197
+ field = micro.phase_level_set(phase, grid=grid)
198
+ except NotImplementedError:
199
+ raise ValueError(
200
+ f"{type(micro).__name__}: no level-set function, so no conforming mesh; "
201
+ "use the FFT solver on voxel images instead"
202
+ ) from None
203
+ return np.asarray(field.data, dtype=np.float64), tuple(int(k) for k in n)
204
+
205
+
206
+ def background_interpolation(values: np.ndarray, lower, upper, points) -> np.ndarray:
207
+ """The values at ``points`` of the function that is linear in each tetrahedron of the
208
+ background mesh (:func:`background_mesh`) and takes ``values`` at its nodes (an array
209
+ over the nodes of the grid): in the cube of a point, mirrored along the axes where its
210
+ index is odd, the tetrahedron is that of the order of its coordinates."""
211
+ values = np.asarray(values, dtype=float)
212
+ lower, upper = np.asarray(lower, dtype=float), np.asarray(upper, dtype=float)
213
+ n = np.array(values.shape) - 1
214
+ u = (np.asarray(points, dtype=float).reshape(-1, 3) - lower) / (upper - lower) * n
215
+ cube = np.clip(np.floor(u).astype(np.int64), 0, n - 1)
216
+ odd = cube % 2 == 1
217
+ xi = np.clip(u - cube, 0.0, 1.0)
218
+ xi = np.where(odd, 1.0 - xi, xi)
219
+ order = np.argsort(-xi, axis=1, kind="stable") # the largest coordinate first
220
+ rows = np.arange(len(u))
221
+ corner = np.zeros((len(u), 3), dtype=np.int64)
222
+
223
+ def at(c):
224
+ node = cube + np.where(odd, 1 - c, c)
225
+ return values[node[:, 0], node[:, 1], node[:, 2]]
226
+
227
+ out = at(corner)
228
+ previous = out.copy()
229
+ for k in range(3):
230
+ axis = order[:, k]
231
+ corner[rows, axis] = 1
232
+ current = at(corner)
233
+ out += xi[rows, axis] * (current - previous)
234
+ previous = current
235
+ return out
236
+
237
+
238
+ def _snap_level_set(values: np.ndarray, fraction: float) -> np.ndarray:
239
+ """Move values close to zero away from it, so that the zero level set never cuts
240
+ an edge of the background mesh very close to a node (which would create slivers).
241
+
242
+ The threshold at a node is ``fraction`` times the largest variation of the level set
243
+ along the grid edges at that node (``|grad phi| h`` for a smooth function, and still
244
+ positive at the bottom of thin valleys, where the gradient vanishes).
245
+ """
246
+ variation = np.zeros_like(values)
247
+ for axis in range(values.ndim):
248
+ d = np.abs(np.diff(values, axis=axis))
249
+ lo = [slice(None)] * values.ndim
250
+ hi = [slice(None)] * values.ndim
251
+ lo[axis] = slice(0, -1)
252
+ hi[axis] = slice(1, None)
253
+ variation[tuple(lo)] = np.maximum(variation[tuple(lo)], d)
254
+ variation[tuple(hi)] = np.maximum(variation[tuple(hi)], d)
255
+ threshold = fraction * variation
256
+ near = np.abs(values) < threshold
257
+ out = values.copy()
258
+ out[near] = np.where(values[near] < 0, -threshold[near], threshold[near])
259
+ return out
260
+
261
+
262
+ def _snap_on_mesh(values: np.ndarray, tets: np.ndarray, fraction) -> np.ndarray:
263
+ """:func:`_snap_level_set` at the vertices of a mesh: the values closer to zero than
264
+ ``fraction`` (one value, or one per vertex) times their largest variation along the
265
+ edges at the vertex are moved away from it, so that the zero level set never cuts an
266
+ edge close to a vertex (those of a previous cut among them: the lines where three
267
+ phases meet)."""
268
+ values = np.asarray(values, dtype=float)
269
+ variation = np.zeros_like(values)
270
+ for a, b in ((0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)):
271
+ d = np.abs(values[tets[:, a]] - values[tets[:, b]])
272
+ np.maximum.at(variation, tets[:, a], d)
273
+ np.maximum.at(variation, tets[:, b], d)
274
+ threshold = fraction * variation
275
+ near = np.abs(values) < threshold
276
+ out = values.copy()
277
+ out[near] = np.where(values[near] < 0, -threshold[near], threshold[near])
278
+ return out
279
+
280
+
281
+ def _matched_vertices(values: np.ndarray, vertices: np.ndarray, box, axes) -> np.ndarray:
282
+ """The values of the vertices of the upper faces of the matching axes taken from the
283
+ vertices that face them on the lower ones (a mesh whose faces match)."""
284
+ from scipy.spatial import cKDTree
285
+
286
+ lower, upper = np.asarray(box[0], dtype=float), np.asarray(box[1], dtype=float)
287
+ tol = 1e-9 * float((upper - lower).max())
288
+ out = np.asarray(values, dtype=float).copy()
289
+ for d in range(3):
290
+ if not axes[d]:
291
+ continue
292
+ low = np.flatnonzero(np.abs(vertices[:, d] - lower[d]) <= tol)
293
+ high = np.flatnonzero(np.abs(vertices[:, d] - upper[d]) <= tol)
294
+ if not (len(low) and len(high)):
295
+ continue
296
+ others = [a for a in range(3) if a != d]
297
+ dist, index = cKDTree(vertices[low][:, others]).query(vertices[high][:, others])
298
+ found = dist <= 1e-6 * float((upper - lower).max())
299
+ out[high[found]] = out[low[index[found]]]
300
+ return out
301
+
302
+
303
+ def _run_mmg(exe, mesh_in, sol_in, mesh_out, args, timeout):
304
+ cmd = [exe, str(mesh_in)]
305
+ if sol_in is not None:
306
+ cmd += ["-sol", str(sol_in)]
307
+ cmd += ["-out", str(mesh_out), *args]
308
+ res = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
309
+ if res.returncode != 0 or not Path(mesh_out).exists():
310
+ tail = (res.stdout + res.stderr)[-2000:]
311
+ raise RuntimeError(f"{Path(exe).name} failed (exit code {res.returncode}):\n{tail}")
312
+ return medit.read_mesh(mesh_out)
313
+
314
+
315
+ def _second_order(mesh: TetMesh, micro, curved: bool | None) -> TetMesh:
316
+ """The 10-node elements of a 4-node mesh: curved onto the implicit surfaces of the
317
+ phases (:func:`morphogen.mesh.curved.curved_mesh`), or with their mid-edge nodes at
318
+ the middles of the straight edges (``curved`` false)."""
319
+ if curved or curved is None:
320
+ from morphogen.mesh.curved import curved_mesh
321
+
322
+ return curved_mesh(mesh, micro)
323
+ return mesh.quadratic()
324
+
325
+
326
+ def conforming_mesh(
327
+ micro,
328
+ *,
329
+ size: float,
330
+ min_size: float | None = None,
331
+ hausdorff: float | None = None,
332
+ gradation: float = 2.0,
333
+ background: float | None = None,
334
+ phases: str = "all",
335
+ order: int = 1,
336
+ curved: bool | None = None,
337
+ periodic: bool | None = None,
338
+ remove_islands: float | None = 1e-5,
339
+ sharp_edges: bool | None = None,
340
+ grains: bool | None = None,
341
+ min_feature: float | None = None,
342
+ cells: str = "whole",
343
+ method: str = "auto",
344
+ executable: str | None = None,
345
+ workdir=None,
346
+ timeout: float | None = None,
347
+ ) -> TetMesh:
348
+ """Tetrahedral mesh of a microstructure, conforming to the interface of its phases.
349
+
350
+ By default from its exact geometry, without a background grid, when the
351
+ microstructure knows it (``method``; :mod:`morphogen.mesh.exact`). Voronoi and Laguerre
352
+ tessellations are meshed grain by grain from their cells
353
+ (:func:`morphogen.mesh.polycrystal.polycrystal_mesh`): every grain boundary is
354
+ conforming, and each element knows its grain (``mesh.cell``) and its crystal
355
+ orientation (``mesh.orientations``).
356
+
357
+ Parameters
358
+ ----------
359
+ size
360
+ Largest element size (``-hmax``).
361
+ min_size, hausdorff
362
+ Smallest element size (default ``size / 10``) and Hausdorff distance between the
363
+ meshed and the discrete interfaces (default ``size / 20``).
364
+ gradation
365
+ Maximal ratio of the sizes of neighbouring elements (``-hgrad``).
366
+ background
367
+ Spacing of the grid sampling the level set (default ``size / 2``): it bounds the
368
+ geometric accuracy of the interface. Give at least three samples across the
369
+ thinnest feature (sheet, strut, fibre): an under-resolved level set biases the
370
+ volume fraction and the apparent properties (by a few percent for two samples).
371
+ phases
372
+ ``"all"`` meshes both phases (composites); ``"solid"`` meshes phase 1 only
373
+ (porous media: the pores carry no stress), ``"matrix"`` phase 0 only (the pores
374
+ are phase 1, e.g. spherical pores in a matrix). Structures of more than two
375
+ phases, or of other phases than 0 and 1 (coated inclusions, inclusions in a
376
+ polycrystal, cells of several phases, osteons...), are meshed conforming to the
377
+ interfaces of all their phases, each cut by its implicit function
378
+ (:meth:`~morphogen.models.base.Microstructure.phase_level_sets_at` on the exact
379
+ route, :meth:`~morphogen.models.base.Microstructure.phase_level_set` on the grid) in
380
+ the part of the box that the previous ones left: ``"all"``, or the phases to keep
381
+ (a list, of any structure).
382
+ order
383
+ 1 (4-node tetrahedra) or 2 (10-node tetrahedra).
384
+ curved
385
+ 10-node elements: put the nodes of the interfaces, corners and mid-edge nodes, on
386
+ the implicit surfaces of the phases, so that the elements along the interfaces
387
+ have curved edges (isoparametric elements,
388
+ :func:`morphogen.mesh.curved.curved_mesh`) and the phases their volumes: by
389
+ default; false keeps the flat faces that MMG makes, with the mid-edge nodes at the
390
+ middles of their edges. The grain boundaries of tessellations are plane.
391
+ periodic
392
+ Opposite faces with matching nodes, for periodic boundary conditions (default:
393
+ when the microstructure is periodic), or three booleans: along those axes only.
394
+ The level set is cut on the background mesh, whose faces match, then MMG remeshes
395
+ the inside and the interface while the faces of the box along those axes stay
396
+ unchanged.
397
+ remove_islands
398
+ Relative volume below which MMG removes isolated components (``-rmc``;
399
+ non-periodic meshes only).
400
+ sharp_edges
401
+ Follow the sharp edges of the phases with edges of the mesh: the grooves where
402
+ the spheres or the segments of a union overlap, those of their coatings and of
403
+ their bores. The structure gives the smooth pieces of its phases
404
+ (:meth:`~morphogen.models.base.Microstructure.implicit_pieces`), the box is cut
405
+ by the surface of each in turn, and the lines where two cuts meet are kept as
406
+ ridges through the remeshing (``mesh.sharp``: these edges; the curved elements
407
+ then put their nodes on both surfaces). By default, when the structure gives
408
+ pieces that meet; false cuts the box by the function of each phase, which
409
+ rounds its sharp edges over an element. The overlaps shallower than the
410
+ ``hausdorff`` distance (exact route) or half the ``background`` spacing (grid) are
411
+ not followed. The cells and convex pieces of the exact route keep the edges of
412
+ their facets.
413
+ grains
414
+ Mesh the grains of a tessellation (default: for Voronoi and Laguerre
415
+ tessellations without a grain-boundary phase); ``False`` meshes only the
416
+ interface between its phases (the grains and their boundary phase).
417
+ min_feature
418
+ Grains: features of the tessellation smaller than this length are removed
419
+ before meshing (default ``size / 4``).
420
+ cells
421
+ Grains of a periodic tessellation: ``"whole"`` (default) meshes the whole grains,
422
+ periodized at the design (their union fills the volume of the box, their boundary
423
+ is made of translated pairs of faces); ``"box"`` cuts them by the faces of the box.
424
+ method
425
+ ``"exact"``: the exact geometry, without a grid
426
+ (:func:`morphogen.mesh.exact.exact_mesh`: the cells of tessellations, exact
427
+ convex pieces, or the adaptive mesh of the exact level set, refined to
428
+ ``hausdorff`` and ``min_size``; ``background`` unused); ``"grid"``: the level set
429
+ sampled on a background grid of spacing ``background``; ``"auto"`` (default):
430
+ ``"exact"`` when the microstructure has an exact route
431
+ (:func:`morphogen.mesh.exact.exact_route`: every structure that gives the
432
+ functions of its phases at any point, of two phases or more, the phases kept by a
433
+ list and the sharp edges of smooth pieces included; not transparent dead leaves,
434
+ the coatings of structures that are not unions of spheres and segments, nor cells
435
+ carrying crystal orientations but tessellations), ``"grid"`` otherwise, and should
436
+ the exact mesh fail (MMG) or its periodic faces not match. The 10-node elements of
437
+ a level set are those of its 4-node mesh on either route, curved by
438
+ :func:`morphogen.mesh.curved.curved_mesh`.
439
+ """
440
+ if method not in ("auto", "exact", "grid"):
441
+ raise ValueError(
442
+ "method: 'auto' (exact when possible), 'exact' (no background grid) or 'grid' "
443
+ "(level set on a background grid)"
444
+ )
445
+ listed = not isinstance(phases, str)
446
+ if listed:
447
+ phases = tuple(int(k) for k in phases)
448
+ elif phases not in ("all", "solid", "matrix"):
449
+ raise ValueError(
450
+ "phases: 'all', 'solid' (phase 1), 'matrix' (phase 0) or the phases to keep"
451
+ )
452
+ from morphogen.models.tessellation import Tessellation
453
+
454
+ tessellation = isinstance(micro, Tessellation)
455
+ if grains is None:
456
+ grains = tessellation and not micro.boundary_thickness > 0
457
+ if grains and tessellation and micro.boundary_thickness > 0:
458
+ raise ValueError("grains: the grain-boundary phase is meshed through its level set")
459
+ if grains and phases == "matrix":
460
+ raise ValueError("phases: 'matrix' meshes phase 0 of a two-phase structure, not grains")
461
+ if cells not in ("whole", "box"):
462
+ raise ValueError("cells: 'whole' or 'box'")
463
+ if order not in (1, 2):
464
+ raise ValueError("order: 1 or 2")
465
+ if curved and order == 1:
466
+ raise ValueError("curved: the edges of 10-node elements (order 2)")
467
+ size = float(size)
468
+ if not size > 0:
469
+ raise ValueError("size: must be positive")
470
+ if method != "grid":
471
+ from morphogen.mesh.exact import exact_mesh, exact_route
472
+
473
+ route = exact_route(micro, grains)
474
+ if grains and route != "cells": # the grains of a structure that is no tessellation
475
+ if method == "exact":
476
+ raise ValueError(
477
+ "grains: the exact meshes by grains are those of tessellations without "
478
+ "a boundary phase"
479
+ )
480
+ route = ""
481
+ if route or method == "exact":
482
+ options = {}
483
+ if route == "cells":
484
+ options = {"cells": cells, "min_feature": min_feature}
485
+ # the 10-node elements of a level set: those of its 4-node mesh, curved as on
486
+ # the grid (the same mesh at both orders)
487
+ curve = route == "level_set" and order == 2
488
+ try:
489
+ mesh = exact_mesh(micro, size=size, min_size=min_size, hausdorff=hausdorff,
490
+ gradation=gradation, phases=phases,
491
+ order=1 if curve else order, periodic=periodic,
492
+ grains=grains, sharp_edges=sharp_edges,
493
+ executable=executable, workdir=workdir, timeout=timeout,
494
+ **options) # fmt: skip
495
+ except (RuntimeError, subprocess.TimeoutExpired) as error: # MMG failed
496
+ if method == "exact":
497
+ raise
498
+ log.warning("conforming mesh: the exact mesh failed (%s); on a grid instead",
499
+ str(error).splitlines()[0]) # fmt: skip
500
+ else:
501
+ axes = _periodic_axes(micro.domain.periodic if periodic is None else periodic)
502
+ if method == "exact" or not all(axes) or mesh.matching_faces():
503
+ return _second_order(mesh, micro, curved) if curve else mesh
504
+ log.warning("conforming mesh: the faces of the exact mesh do not match; on a "
505
+ "grid instead") # fmt: skip
506
+ if grains:
507
+ from morphogen.mesh.polycrystal import polycrystal_mesh
508
+
509
+ return polycrystal_mesh(
510
+ micro,
511
+ size=size,
512
+ min_size=min_size,
513
+ hausdorff=hausdorff,
514
+ gradation=gradation,
515
+ min_feature=min_feature,
516
+ phases=phases,
517
+ order=order,
518
+ periodic=periodic,
519
+ cells=cells,
520
+ executable=executable,
521
+ workdir=workdir,
522
+ timeout=timeout,
523
+ )
524
+ domain: Domain = micro.domain
525
+ axes = _periodic_axes(domain.periodic if periodic is None else periodic)
526
+ periodic = all(axes)
527
+ exe = mmg_executable(executable)
528
+ t0 = time.perf_counter()
529
+ spacing = float(background) if background is not None else size / 2.0
530
+ present = list(micro.implicit_phases()) if hasattr(micro, "implicit_phases") else [0, 1]
531
+ several = present != [0, 1]
532
+ pieces = None
533
+ if sharp_edges is None or sharp_edges:
534
+ found = getattr(micro, "implicit_pieces", lambda depth: None)(0.5 * spacing)
535
+ if found is None and sharp_edges:
536
+ raise ValueError(
537
+ f"sharp_edges: {type(micro).__name__} does not give the smooth pieces of its "
538
+ "phases (the unions of spheres and segments and their coatings do)"
539
+ )
540
+ if found is not None:
541
+ counts: dict[int, int] = {}
542
+ for piece in found[0]:
543
+ counts[piece.phase] = counts.get(piece.phase, 0) + 1
544
+ # by default, only where two pieces of a phase can meet
545
+ if sharp_edges or max(counts.values(), default=0) > 1:
546
+ pieces, rest = found
547
+ if listed and not several:
548
+ if phases not in ((1,), (0,), (0, 1)):
549
+ raise ValueError("phases: this structure has the phases 0 and 1")
550
+ phases = {(1,): "solid", (0,): "matrix"}.get(phases, "all")
551
+ if several:
552
+ if phases in ("solid", "matrix"):
553
+ raise ValueError(
554
+ f"phases: 'all' or the phases to keep among {present} (a structure of "
555
+ "several phases)"
556
+ )
557
+ unknown = sorted(set(phases) - set(present)) if listed else []
558
+ if unknown:
559
+ raise ValueError(f"phases: {unknown} are not phases of this structure ({present})")
560
+ data = None
561
+ sizes = {"size": size, "min_size": min_size, "hausdorff": hausdorff, "gradation": gradation}
562
+ shape = tuple(int(k) for k in np.maximum(1, np.ceil(domain.lengths / spacing - 1e-9)))
563
+ h = domain.lengths / np.array(shape)
564
+ nodes, tets, tri, tri_refs = background_mesh(shape, domain.lower, domain.upper)
565
+ if pieces is not None:
566
+ # the box cut by the surface of each piece in turn: the sharp edges are followed
567
+ t_bg = time.perf_counter() - t0
568
+ t1 = time.perf_counter()
569
+ try:
570
+ data, sharp, sharp_pieces = _mmg_pieces(
571
+ exe,
572
+ nodes,
573
+ tets,
574
+ tri,
575
+ tri_refs,
576
+ pieces,
577
+ rest,
578
+ (domain.lower, domain.upper),
579
+ axes,
580
+ _on_faces(axes, domain.lower, domain.upper),
581
+ 4.0 * float(h.max()),
582
+ **sizes,
583
+ workdir=workdir,
584
+ timeout=timeout,
585
+ )
586
+ except (RuntimeError, subprocess.TimeoutExpired) as error:
587
+ if sharp_edges:
588
+ raise
589
+ log.warning(
590
+ "conforming mesh: the sharp edges could not be followed (%s); they are "
591
+ "rounded instead",
592
+ str(error).splitlines()[0],
593
+ )
594
+ pieces = None
595
+ if data is None and several:
596
+ # each phase but one is cut in what the previous ones left: the largest index last.
597
+ # A phase is where its function is the smallest of all: the same set where the
598
+ # functions are resolved (one of them negative), and still a partition where they
599
+ # are not (thin layers, the lines where three phases meet)
600
+ sampled = {k: node_level_set(micro, spacing, k)[0] for k in present}
601
+ fields = []
602
+ for k in present[:-1]:
603
+ others = np.minimum.reduce([sampled[q] for q in present if q != k])
604
+ fields.append((k, _matched(_snap_level_set(sampled[k] - others, SNAP), axes)))
605
+ t_bg = time.perf_counter() - t0
606
+ t1 = time.perf_counter()
607
+ data = _mmg_phases(
608
+ exe,
609
+ nodes,
610
+ tets,
611
+ tri,
612
+ tri_refs,
613
+ fields,
614
+ present[-1],
615
+ (domain.lower, domain.upper),
616
+ axes,
617
+ _on_faces(axes, domain.lower, domain.upper),
618
+ **sizes,
619
+ workdir=workdir,
620
+ timeout=timeout,
621
+ )
622
+ elif data is None:
623
+ values = _matched(_snap_level_set(node_level_set(micro, spacing)[0], SNAP), axes)
624
+ t_bg = time.perf_counter() - t0
625
+ t1 = time.perf_counter()
626
+ data = _mmg_level_set(
627
+ exe,
628
+ nodes,
629
+ tets,
630
+ tri,
631
+ tri_refs,
632
+ values.ravel(),
633
+ _matching_refs(axes),
634
+ _on_faces(axes, domain.lower, domain.upper),
635
+ **sizes,
636
+ phases=phases,
637
+ remove_islands=remove_islands,
638
+ workdir=workdir,
639
+ timeout=timeout,
640
+ )
641
+ t_mmg = time.perf_counter() - t1
642
+ xyz = data["Vertices"]
643
+ tol = 1e-9 * float(domain.lengths.max())
644
+ for d in range(3): # nodes of the faces exactly on the faces
645
+ xyz[:, d] = np.where(np.abs(xyz[:, d] - domain.lower[d]) <= tol, domain.lower[d], xyz[:, d])
646
+ xyz[:, d] = np.where(np.abs(xyz[:, d] - domain.upper[d]) <= tol, domain.upper[d], xyz[:, d])
647
+ elements = data["Tetrahedra"]
648
+ refs = data["Tetrahedra_refs"]
649
+ if several or pieces is not None:
650
+ phase = refs - REF_PHASE
651
+ named = isinstance(phases, str) # 'all', or 'solid' and 'matrix' of two phases
652
+ wanted = {"solid": (1,), "matrix": (0,)}.get(phases) if named else phases
653
+ if wanted is not None: # the phases kept
654
+ kept = np.isin(phase, wanted)
655
+ elements, phase = elements[kept], phase[kept]
656
+ else:
657
+ phase = np.where(refs == REF_INSIDE, 1, 0)
658
+ flip = tet_volumes(xyz, elements) < 0
659
+ elements[flip] = elements[flip][:, [0, 2, 1, 3]]
660
+ used, inverse = np.unique(elements, return_inverse=True)
661
+ metadata = {
662
+ "mesher": "mmg3d -ls",
663
+ "size": size,
664
+ "background_spacing": [float(x) for x in h],
665
+ "background_elements": len(tets),
666
+ "phases": phases if isinstance(phases, str) else list(phases),
667
+ "matching_faces": [d for d in range(3) if axes[d]],
668
+ "time_background_s": round(t_bg, 3),
669
+ "time_mmg_s": round(t_mmg, 3),
670
+ }
671
+ followed = {}
672
+ if pieces is not None: # the sharp edges, between the nodes of the mesh
673
+ numbers = np.full(len(xyz), -1, dtype=np.int64)
674
+ numbers[used] = np.arange(len(used))
675
+ there = (numbers[sharp] >= 0).all(axis=1)
676
+ followed = {"sharp": numbers[sharp[there]], "sharp_pieces": sharp_pieces[there]}
677
+ metadata["sharp_edges"] = {
678
+ "pieces": len(pieces),
679
+ "edges": int(there.sum()),
680
+ "depth": 0.5 * spacing,
681
+ }
682
+ mesh = TetMesh(
683
+ nodes=xyz[used],
684
+ elements=inverse.reshape(elements.shape),
685
+ phase=phase,
686
+ lower=domain.lower,
687
+ upper=domain.upper,
688
+ periodic=periodic,
689
+ metadata=metadata,
690
+ **followed,
691
+ )
692
+ q = mesh.quality()
693
+ if q.size and q.min() < 1e-6:
694
+ log.warning(
695
+ "conforming mesh: %d degenerate elements; the background grid (spacing %.3g) "
696
+ "may not resolve thin features of the microstructure: decrease 'background'",
697
+ int((q < 1e-6).sum()),
698
+ float(h.max()),
699
+ )
700
+ if order == 2:
701
+ mesh = _second_order(mesh, micro, curved)
702
+ log.info(
703
+ "conforming mesh: %d elements, %d nodes (MMG %.1f s)",
704
+ mesh.n_elements,
705
+ mesh.n_nodes,
706
+ t_mmg,
707
+ )
708
+ return mesh
709
+
710
+
711
+ def _matching_refs(axes) -> list[int]:
712
+ """The references of the faces of the background mesh along the matching axes."""
713
+ return [1 + 2 * d + side for d in range(3) if axes[d] for side in (0, 1)]
714
+
715
+
716
+ def _on_faces(axes, lower, upper):
717
+ """A mask of the vertices on the faces of the box along the matching axes."""
718
+ lower, upper = np.asarray(lower, float), np.asarray(upper, float)
719
+ tol = 1e-9 * float((upper - lower).max())
720
+
721
+ def mask(vtx):
722
+ on = np.zeros(len(vtx), dtype=bool)
723
+ for d in range(3):
724
+ if axes[d]:
725
+ on |= np.abs(vtx[:, d] - lower[d]) <= tol
726
+ on |= np.abs(vtx[:, d] - upper[d]) <= tol
727
+ return on
728
+
729
+ return mask
730
+
731
+
732
+ def _mmg_level_set(
733
+ exe,
734
+ nodes,
735
+ tets,
736
+ tri,
737
+ tri_refs,
738
+ values,
739
+ required,
740
+ required_vertices,
741
+ *,
742
+ size,
743
+ min_size=None,
744
+ hausdorff=None,
745
+ gradation=2.0,
746
+ phases="all",
747
+ remove_islands=1e-5,
748
+ workdir=None,
749
+ timeout=None,
750
+ ):
751
+ """MMG's discretization of the zero level set of ``values`` (at the nodes) on a
752
+ background mesh, and its remeshing: in one pass, or, when the boundary triangles of
753
+ the references ``required`` must stay (matching faces), a cut without remeshing, then a
754
+ remeshing that keeps them and the vertices of ``required_vertices`` (a mask of the
755
+ vertices of the cut mesh, a function of their positions). Returns MMG's mesh."""
756
+ sizing = [
757
+ "-hmax",
758
+ f"{size:.10g}",
759
+ "-hmin",
760
+ f"{(min_size if min_size is not None else size / 10):.10g}",
761
+ "-hausd",
762
+ f"{(hausdorff if hausdorff is not None else size / 20):.10g}",
763
+ "-hgrad",
764
+ f"{float(gradation):.10g}",
765
+ "-v",
766
+ "-1",
767
+ ]
768
+ keep = {"solid": ["-nsd", str(REF_INSIDE)], "matrix": ["-nsd", str(REF_OUTSIDE)]}.get(
769
+ phases, []
770
+ )
771
+ with tempfile.TemporaryDirectory(dir=workdir) as tmp:
772
+ folder = Path(tmp)
773
+ medit.write_mesh(folder / "bg.mesh", nodes, tets, tri, tri_refs=tri_refs)
774
+ medit.write_sol(folder / "bg.sol", np.asarray(values, dtype=float).ravel())
775
+ if not required:
776
+ args = ["-ls", "0", *sizing, *keep]
777
+ if remove_islands:
778
+ args += ["-rmc", f"{float(remove_islands):.10g}"]
779
+ return _run_mmg(
780
+ exe, folder / "bg.mesh", folder / "bg.sol", folder / "out.mesh", args, timeout
781
+ )
782
+ cut = _run_mmg(
783
+ exe,
784
+ folder / "bg.mesh",
785
+ folder / "bg.sol",
786
+ folder / "cut.mesh",
787
+ ["-ls", "0", "-nosurf", "-noinsert", "-noswap", "-nomove", "-v", "-1"],
788
+ timeout,
789
+ )
790
+ refs = cut["Triangles_refs"]
791
+ vtx = cut["Vertices"]
792
+ medit.write_mesh(
793
+ folder / "cut2.mesh",
794
+ vtx,
795
+ cut["Tetrahedra"],
796
+ cut["Triangles"],
797
+ tet_refs=cut["Tetrahedra_refs"],
798
+ tri_refs=refs,
799
+ required_triangles=np.flatnonzero(np.isin(refs, required)),
800
+ required_vertices=np.flatnonzero(required_vertices(vtx)),
801
+ )
802
+ return _run_mmg(
803
+ exe, folder / "cut2.mesh", None, folder / "out.mesh", [*sizing, *keep], timeout
804
+ )
805
+
806
+
807
+ def _matched(values: np.ndarray, axes) -> np.ndarray:
808
+ """Identical values on the opposite faces of the matching axes: the cut faces match."""
809
+ if axes[0]:
810
+ values[-1, :, :] = values[0, :, :]
811
+ if axes[1]:
812
+ values[:, -1, :] = values[:, 0, :]
813
+ if axes[2]:
814
+ values[:, :, -1] = values[:, :, 0]
815
+ return values
816
+
817
+
818
+ def _mmg_phases(
819
+ exe,
820
+ nodes,
821
+ tets,
822
+ tri,
823
+ tri_refs,
824
+ fields,
825
+ last: int,
826
+ box,
827
+ matching,
828
+ required_vertices,
829
+ *,
830
+ size,
831
+ min_size=None,
832
+ hausdorff=None,
833
+ gradation=2.0,
834
+ workdir=None,
835
+ timeout=None,
836
+ ):
837
+ """MMG's mesh of a box of several phases: the tetrahedra of the background mesh, all
838
+ of the phase ``last`` at first, are cut by the zero level set of each of ``fields``
839
+ (a phase and its values at the nodes of the grid) where they are not of a phase cut
840
+ before (MMG's level sets of several materials: the references that a level set splits
841
+ and those it leaves), without remeshing; the level set of a cut is the function linear
842
+ in the tetrahedra of the background mesh, taken at the vertices that the previous cuts
843
+ made (:func:`background_interpolation`). The mesh is then remeshed, its interfaces
844
+ kept, with the triangles of the faces along the ``matching`` axes and the vertices of
845
+ ``required_vertices`` unchanged (matching faces). The references of the tetrahedra of
846
+ MMG's mesh are :data:`REF_PHASE` plus their phase."""
847
+ required = _matching_refs(matching)
848
+ sizing = [
849
+ "-hmax",
850
+ f"{size:.10g}",
851
+ "-hmin",
852
+ f"{(min_size if min_size is not None else size / 10):.10g}",
853
+ "-hausd",
854
+ f"{(hausdorff if hausdorff is not None else size / 20):.10g}",
855
+ "-hgrad",
856
+ f"{float(gradation):.10g}",
857
+ "-v",
858
+ "-1",
859
+ ]
860
+ rest = REF_PHASE + int(last)
861
+ with tempfile.TemporaryDirectory(dir=workdir) as tmp:
862
+ folder = Path(tmp)
863
+ mesh = {
864
+ "Vertices": nodes,
865
+ "Tetrahedra": tets,
866
+ "Tetrahedra_refs": np.full(len(tets), rest),
867
+ "Triangles": tri,
868
+ "Triangles_refs": tri_refs,
869
+ }
870
+ done: list[int] = []
871
+ for step, (phase, values) in enumerate(fields):
872
+ name = folder / f"cut{step}.mesh"
873
+ if step: # the vertices of the previous cut: numbered alike on opposite faces
874
+ mesh = _in_order(mesh, box)
875
+ medit.write_mesh(
876
+ name,
877
+ mesh["Vertices"],
878
+ mesh["Tetrahedra"],
879
+ mesh["Triangles"],
880
+ tet_refs=mesh["Tetrahedra_refs"],
881
+ tri_refs=mesh["Triangles_refs"],
882
+ )
883
+ if step == 0:
884
+ at = values.ravel()
885
+ else:
886
+ at = background_interpolation(values, box[0], box[1], mesh["Vertices"])
887
+ at = _snap_on_mesh(at, mesh["Tetrahedra"], SNAP)
888
+ at = _matched_vertices(at, mesh["Vertices"], box, matching)
889
+ medit.write_sol(folder / f"cut{step}.sol", at)
890
+ lines = ["LSReferences", str(1 + len(done)), f"{rest} {REF_PHASE + phase} {rest}"]
891
+ lines += [f"{REF_PHASE + k} nosplit" for k in done]
892
+ (folder / f"cut{step}.mmg3d").write_text("\n".join(lines) + "\n", encoding="ascii")
893
+ mesh = _run_mmg(
894
+ exe,
895
+ name,
896
+ folder / f"cut{step}.sol",
897
+ folder / f"cut{step + 1}_in.mesh",
898
+ ["-ls", "0", "-nosurf", "-noinsert", "-noswap", "-nomove", "-v", "-1"],
899
+ timeout,
900
+ )
901
+ done.append(int(phase))
902
+ refs = mesh["Triangles_refs"]
903
+ vtx = mesh["Vertices"]
904
+ keep = {}
905
+ if required:
906
+ keep = {
907
+ "required_triangles": np.flatnonzero(np.isin(refs, required)),
908
+ "required_vertices": np.flatnonzero(required_vertices(vtx)),
909
+ }
910
+ medit.write_mesh(
911
+ folder / "cut.mesh",
912
+ vtx,
913
+ mesh["Tetrahedra"],
914
+ mesh["Triangles"],
915
+ tet_refs=mesh["Tetrahedra_refs"],
916
+ tri_refs=refs,
917
+ **keep,
918
+ )
919
+ return _run_mmg(exe, folder / "cut.mesh", None, folder / "out.mesh", sizing, timeout)
920
+
921
+
922
+ def _mmg_pieces(
923
+ exe,
924
+ nodes,
925
+ tets,
926
+ tri,
927
+ tri_refs,
928
+ pieces,
929
+ last: int,
930
+ box,
931
+ matching,
932
+ required_vertices,
933
+ band: float,
934
+ *,
935
+ size,
936
+ min_size=None,
937
+ hausdorff=None,
938
+ gradation=2.0,
939
+ workdir=None,
940
+ timeout=None,
941
+ ):
942
+ """MMG's mesh of a box whose phases are given by their smooth pieces
943
+ (:mod:`morphogen.models.pieces`), which follows the sharp edges of their surfaces.
944
+
945
+ The tetrahedra of the background mesh, all of the phase ``last`` at first, are cut
946
+ by the surface of each piece in turn where no piece cut before holds them, without
947
+ remeshing; the function of a piece is taken at the vertices that the previous cuts
948
+ made, exactly. The line where the surfaces of two pieces of the same phase meet — a
949
+ sharp edge of the phase — is then made of edges of the mesh. These edges are given
950
+ to MMG as ridges, with the edges of the box and the lines where an interface meets a
951
+ face of the box, and the detection of ridges by their angle is turned off (the
952
+ facets that the cuts leave on the smooth surfaces are no edges); the pieces of a
953
+ phase are merged, and the mesh is remeshed as in :func:`_mmg_phases`.
954
+
955
+ Returns MMG's mesh (the references of its tetrahedra: :data:`REF_PHASE` plus their
956
+ phase), the sharp edges among its edges (pairs of vertices) and the two pieces
957
+ that meet along each."""
958
+ required = _matching_refs(matching)
959
+ sizing = [
960
+ "-hmax",
961
+ f"{size:.10g}",
962
+ "-hmin",
963
+ f"{(min_size if min_size is not None else size / 10):.10g}",
964
+ "-hausd",
965
+ f"{(hausdorff if hausdorff is not None else size / 20):.10g}",
966
+ "-hgrad",
967
+ f"{float(gradation):.10g}",
968
+ "-nr",
969
+ "-v",
970
+ "-1",
971
+ ]
972
+ rest = REF_PHASE + int(last)
973
+ count = len(pieces)
974
+ with tempfile.TemporaryDirectory(dir=workdir) as tmp:
975
+ folder = Path(tmp)
976
+ mesh = {
977
+ "Vertices": nodes,
978
+ "Tetrahedra": tets,
979
+ "Tetrahedra_refs": np.full(len(tets), rest),
980
+ "Triangles": tri,
981
+ "Triangles_refs": tri_refs,
982
+ }
983
+ done: list[int] = []
984
+ for step, piece in enumerate(pieces):
985
+ if done: # the vertices of the previous cuts: numbered alike on opposite faces
986
+ mesh = _in_order(mesh, box)
987
+ at = piece.at(mesh["Vertices"], band)
988
+ # on the faces of the box, whose triangles the remeshing may have to keep, the
989
+ # share of the other meshes
990
+ on_box = _on_faces((True,) * 3, box[0], box[1])(mesh["Vertices"])
991
+ at = _snap_on_mesh(at, mesh["Tetrahedra"], np.where(on_box, SNAP, SNAP_SHARP))
992
+ at = _matched_vertices(at, mesh["Vertices"], box, matching)
993
+ if at.min() >= 0.0: # a piece that is not in the box
994
+ continue
995
+ name = folder / f"cut{step}.mesh"
996
+ medit.write_mesh(
997
+ name,
998
+ mesh["Vertices"],
999
+ mesh["Tetrahedra"],
1000
+ mesh["Triangles"],
1001
+ tet_refs=mesh["Tetrahedra_refs"],
1002
+ tri_refs=mesh["Triangles_refs"],
1003
+ )
1004
+ medit.write_sol(folder / f"cut{step}.sol", at)
1005
+ lines = ["LSReferences", str(1 + len(done)), f"{rest} {REF_PIECE + step} {rest}"]
1006
+ lines += [f"{REF_PIECE + k} nosplit" for k in done]
1007
+ (folder / f"cut{step}.mmg3d").write_text("\n".join(lines) + "\n", encoding="ascii")
1008
+ mesh = _run_mmg(
1009
+ exe,
1010
+ name,
1011
+ folder / f"cut{step}.sol",
1012
+ folder / f"cut{step + 1}_in.mesh",
1013
+ ["-ls", "0", "-nosurf", "-noinsert", "-noswap", "-nomove", "-v", "-1"],
1014
+ timeout,
1015
+ )
1016
+ done.append(step)
1017
+ vtx, elements, refs = mesh["Vertices"], mesh["Tetrahedra"], mesh["Tetrahedra_refs"]
1018
+ # the piece and the phase of each tetrahedron (what is left: after all the pieces)
1019
+ cut = np.where(refs >= REF_PIECE, refs - REF_PIECE, count)
1020
+ phase_of = np.array([int(piece.phase) for piece in pieces] + [int(last)])
1021
+ phase = phase_of[cut]
1022
+ # the faces between two phases: their piece is the first of the two that was cut
1023
+ faces = elements[:, TET_FACES].reshape(-1, 3)
1024
+ owner = np.repeat(np.arange(len(elements)), 4)
1025
+ key = np.sort(faces, axis=1)
1026
+ order = np.lexsort((key[:, 2], key[:, 1], key[:, 0]))
1027
+ key, faces, owner = key[order], faces[order], owner[order]
1028
+ twin = np.flatnonzero(np.all(key[1:] == key[:-1], axis=1))
1029
+ a, b = owner[twin], owner[twin + 1]
1030
+ between = phase[a] != phase[b]
1031
+ a, b = a[between], b[between]
1032
+ inner = faces[twin[between]]
1033
+ low, high = np.minimum(phase[a], phase[b]), np.maximum(phase[a], phase[b])
1034
+ label = np.minimum(cut[a], cut[b])
1035
+ surface = 7 + (low * (int(phase_of.max()) + 1) + high) * (count + 1) + label
1036
+ # the faces of the box, as MMG kept them through the cuts
1037
+ on_box = np.isin(mesh["Triangles_refs"], np.arange(1, 7))
1038
+ triangles = np.concatenate([mesh["Triangles"][on_box], inner])
1039
+ tri_surface = np.concatenate([mesh["Triangles_refs"][on_box], surface])
1040
+ tri_out = np.concatenate(
1041
+ [mesh["Triangles_refs"][on_box], np.full(len(inner), REF_INTERFACE)]
1042
+ )
1043
+ # the edges between two surfaces: ridges; between two pieces of an interface: sharp
1044
+ edges = np.sort(
1045
+ np.concatenate([triangles[:, [0, 1]], triangles[:, [1, 2]], triangles[:, [0, 2]]]),
1046
+ axis=1,
1047
+ )
1048
+ of = np.tile(tri_surface, 3)
1049
+ order = np.lexsort((of, edges[:, 1], edges[:, 0]))
1050
+ edges, of = edges[order], of[order]
1051
+ same = np.all(edges[1:] == edges[:-1], axis=1)
1052
+ change = np.flatnonzero(same & (of[1:] != of[:-1]))
1053
+ ridge, inverse = np.unique(edges[change], axis=0, return_inverse=True)
1054
+ ridge_refs = np.zeros(len(ridge), dtype=np.int64)
1055
+ s1, s2 = of[change], of[change + 1] # two surfaces around the edge, s1 < s2
1056
+ both = (s1 >= 7) & ((s1 - 7) // (count + 1) == (s2 - 7) // (count + 1))
1057
+ code = ((s1 - 7) % (count + 1)) * (count + 1) + (s2 - 7) % (count + 1)
1058
+ ridge_refs[inverse.ravel()[both]] = REF_SHARP + code[both]
1059
+ keep = {}
1060
+ if required:
1061
+ keep = {
1062
+ "required_triangles": np.flatnonzero(np.isin(tri_out, required)),
1063
+ "required_vertices": np.flatnonzero(required_vertices(vtx)),
1064
+ }
1065
+ medit.write_mesh(
1066
+ folder / "cut.mesh",
1067
+ vtx,
1068
+ elements,
1069
+ triangles,
1070
+ tet_refs=REF_PHASE + phase,
1071
+ tri_refs=tri_out,
1072
+ edges=ridge,
1073
+ edge_refs=ridge_refs,
1074
+ ridges=np.arange(len(ridge)),
1075
+ **keep,
1076
+ )
1077
+ out = _run_mmg(exe, folder / "cut.mesh", None, folder / "out.mesh", sizing, timeout)
1078
+ edge_refs = out.get("Edges_refs", np.zeros(0, dtype=np.int64))
1079
+ along = edge_refs >= REF_SHARP
1080
+ codes = edge_refs[along] - REF_SHARP
1081
+ pairs = np.stack([codes // (count + 1), codes % (count + 1)], axis=1)
1082
+ return out, out.get("Edges", np.zeros((0, 2), dtype=np.int64))[along], pairs
1083
+
1084
+
1085
+ def _in_order(mesh: dict, box) -> dict:
1086
+ """MMG's mesh with its vertices numbered in the order of their coordinates. MMG
1087
+ chooses the diagonal along which it splits a face that a level set cuts from the
1088
+ numbers of its vertices: the vertices that a first cut made are numbered as they were
1089
+ made, not alike on opposite faces, and a second cut could then split two matching
1090
+ faces along different diagonals (the same nodes, another edge: mid-edge nodes of
1091
+ 10-node elements without an image). In the order of their coordinates, the vertices
1092
+ of a face and their images on the opposite face follow each other alike."""
1093
+ vertices = mesh["Vertices"]
1094
+ scale = 1e-9 * float(np.max(np.asarray(box[1]) - np.asarray(box[0])))
1095
+ keys = np.round((vertices - np.asarray(box[0])) / scale).astype(np.int64)
1096
+ order = np.lexsort((keys[:, 2], keys[:, 1], keys[:, 0]))
1097
+ rank = np.empty(len(order), dtype=np.int64)
1098
+ rank[order] = np.arange(len(order))
1099
+ out = dict(mesh)
1100
+ out["Vertices"] = vertices[order]
1101
+ out["Tetrahedra"] = rank[mesh["Tetrahedra"]]
1102
+ out["Triangles"] = rank[mesh["Triangles"]]
1103
+ return out
1104
+
1105
+
1106
+ def _periodic_axes(periodic) -> tuple[bool, bool, bool]:
1107
+ """The axes along which the faces match: all of them, none, or three booleans."""
1108
+ if np.ndim(periodic) == 0:
1109
+ return (bool(periodic),) * 3
1110
+ axes = tuple(bool(p) for p in periodic)
1111
+ if len(axes) != 3:
1112
+ raise ValueError("periodic: a boolean or three booleans")
1113
+ return axes
1114
+
1115
+
1116
+ class ImplicitBody:
1117
+ """A microstructure given by its level-set function in ``domain``: ``function(points)``
1118
+ of points (rows) negative inside phase 1, positive outside (for instance the distance
1119
+ to the nearest hole less its radius, for the solid of a porous plate)."""
1120
+
1121
+ def __init__(self, domain: Domain, function):
1122
+ self.domain, self.function = domain, function
1123
+
1124
+ def level_set(self, shape=None, *, voxel_size=None, grid: Grid | None = None):
1125
+ from morphogen.image import VoxelImage
1126
+
1127
+ if grid is None:
1128
+ grid = Grid.for_domain(self.domain, shape=shape, voxel_size=voxel_size)
1129
+ values = np.asarray(self.function(grid.center_points()), dtype=float)
1130
+ return VoxelImage(values.reshape(grid.shape), spacing=tuple(grid.spacing),
1131
+ origin=tuple(grid.origin)) # fmt: skip
1132
+
1133
+
1134
+ class _Part:
1135
+ """A microstructure seen in a part of its box (its own level set)."""
1136
+
1137
+ def __init__(self, micro, domain: Domain):
1138
+ self.micro, self.domain = micro, domain
1139
+
1140
+ def level_set(self, shape=None, *, voxel_size=None, grid: Grid | None = None):
1141
+ return self.micro.level_set(grid=grid)
1142
+
1143
+
1144
+ def _merge(nodes: np.ndarray, elements: np.ndarray, tol: float):
1145
+ """The nodes closer than ``tol`` merged (the first of each group kept), the elements
1146
+ renumbered."""
1147
+ from scipy.spatial import cKDTree
1148
+
1149
+ pairs = cKDTree(nodes).query_pairs(tol, output_type="ndarray")
1150
+ parent = np.arange(len(nodes))
1151
+ for a, b in pairs[np.argsort(pairs.max(axis=1))]:
1152
+ ra, rb = a, b
1153
+ while parent[ra] != ra:
1154
+ ra = parent[ra]
1155
+ while parent[rb] != rb:
1156
+ rb = parent[rb]
1157
+ parent[max(ra, rb)] = min(ra, rb)
1158
+ for i in range(len(parent)): # flatten
1159
+ parent[i] = parent[parent[i]]
1160
+ used, inverse = np.unique(parent, return_inverse=True)
1161
+ return nodes[used], inverse[elements]
1162
+
1163
+
1164
+ def _components(pairs) -> list[list[int]]:
1165
+ """The axes joined by diagonal mirrors (sorted groups, singletons included)."""
1166
+ parent = list(range(3))
1167
+
1168
+ def find(a):
1169
+ while parent[a] != a:
1170
+ a = parent[a]
1171
+ return a
1172
+
1173
+ for a, b in pairs:
1174
+ parent[find(a)] = find(b)
1175
+ groups: dict[int, list[int]] = {}
1176
+ for a in range(3):
1177
+ groups.setdefault(find(a), []).append(a)
1178
+ return [sorted(g) for g in groups.values()]
1179
+
1180
+
1181
+ def point_group(mirrors, diagonals=()) -> list[np.ndarray]:
1182
+ """The operations (3 x 3 matrices about the centre of the box) of the group generated by
1183
+ the reflections across the mid-planes of the axes ``mirrors`` and across the diagonal
1184
+ planes ``x_i - c_i = x_j - c_j`` of the pairs ``diagonals`` (axes among the mirrors):
1185
+ signed permutations, 16 for the square of 4/mmm (mirrors x, y, z and the diagonal of x
1186
+ and y), 48 for the cube of m-3m (two diagonals)."""
1187
+ mirrors = sorted({int(k) for k in np.atleast_1d(mirrors)})
1188
+ components = _components(diagonals)
1189
+ out = []
1190
+ for parts in itertools.product(*(itertools.permutations(c) for c in components)):
1191
+ perm = np.arange(3)
1192
+ for c, image in zip(components, parts, strict=True):
1193
+ perm[c] = image
1194
+ for signs in itertools.product((1.0, -1.0), repeat=len(mirrors)):
1195
+ m = np.zeros((3, 3))
1196
+ m[np.arange(3), perm] = 1.0
1197
+ m[mirrors] *= np.asarray(signs)[:, None]
1198
+ out.append(m)
1199
+ return out
1200
+
1201
+
1202
+ def _chamber_background(shape, lower, upper, pairs):
1203
+ """The background mesh of the box restricted to the chamber ``u_a >= u_b`` of each pair
1204
+ (``u = x - lower``; the diagonal planes through the corner are unions of faces of the
1205
+ Kuhn triangulation, reflected or not, when the grid has equal steps along the axes of
1206
+ a pair): its nodes (and their indices in the box's), tetrahedra, boundary triangles and
1207
+ their references (1-6 the faces of the box, 7 + k the plane of the pair k)."""
1208
+ nodes, tets, _, _ = background_mesh(shape, lower, upper)
1209
+ lower, upper = np.asarray(lower, float), np.asarray(upper, float)
1210
+ u = nodes - lower
1211
+ centroids = u[tets].mean(axis=1)
1212
+ inside = np.ones(len(tets), dtype=bool)
1213
+ for a, b in pairs:
1214
+ inside &= centroids[:, a] > centroids[:, b]
1215
+ tets = tets[inside]
1216
+ faces = np.concatenate(
1217
+ [tets[:, [0, 2, 1]], tets[:, [0, 1, 3]], tets[:, [1, 2, 3]], tets[:, [0, 3, 2]]]
1218
+ )
1219
+ _, first, counts = np.unique(np.sort(faces, axis=1), axis=0, return_index=True,
1220
+ return_counts=True) # fmt: skip
1221
+ boundary = faces[first[counts == 1]]
1222
+ points = u[boundary]
1223
+ tol = 1e-9 * float((upper - lower).max())
1224
+ refs = np.zeros(len(boundary), dtype=np.int64)
1225
+ for d in range(3):
1226
+ refs[np.all(np.abs(points[:, :, d]) <= tol, axis=1)] = 1 + 2 * d
1227
+ refs[np.all(np.abs(points[:, :, d] - (upper[d] - lower[d])) <= tol, axis=1)] = 2 + 2 * d
1228
+ for k, (a, b) in enumerate(pairs):
1229
+ refs[np.all(np.abs(points[:, :, a] - points[:, :, b]) <= tol, axis=1)] = 7 + k
1230
+ if np.any(refs == 0):
1231
+ raise RuntimeError("chamber: boundary faces off its planes (unequal grid steps?)")
1232
+ used = np.unique(tets)
1233
+ index = np.full(len(nodes), -1, dtype=np.int64)
1234
+ index[used] = np.arange(len(used))
1235
+ return nodes[used], used, index[tets], index[boundary], refs
1236
+
1237
+
1238
+ def _project_planes(xyz, triangles, refs, lower, upper, pairs, rounds: int = 60):
1239
+ """The vertices of the boundary triangles moved exactly onto the planes of their
1240
+ references (alternating projections where planes meet)."""
1241
+ xyz = xyz.copy()
1242
+ groups = []
1243
+ for d in range(3):
1244
+ for side, value in ((0, lower[d]), (1, upper[d])):
1245
+ v = np.unique(triangles[refs == 1 + 2 * d + side])
1246
+ if v.size:
1247
+ groups.append(("box", d, value, v))
1248
+ for k, (a, b) in enumerate(pairs):
1249
+ v = np.unique(triangles[refs == 7 + k])
1250
+ if v.size:
1251
+ groups.append(("diagonal", a, b, v))
1252
+ for _ in range(rounds):
1253
+ for kind, a, b, v in groups:
1254
+ if kind == "box":
1255
+ xyz[v, a] = b
1256
+ else:
1257
+ mean = 0.5 * ((xyz[v, a] - lower[a]) + (xyz[v, b] - lower[b]))
1258
+ xyz[v, a] = lower[a] + mean
1259
+ xyz[v, b] = lower[b] + mean
1260
+ return xyz
1261
+
1262
+
1263
+ def _chamber_mesh(micro, lower, upper, pairs, matching, *, size, phases, background=None,
1264
+ executable=None, **mmg) -> TetMesh: # fmt: skip
1265
+ """A conforming mesh of the chamber of the box ``[lower, upper]`` (see
1266
+ :func:`_chamber_background`), its faces along the ``matching`` axes matching."""
1267
+ lower, upper = np.asarray(lower, float), np.asarray(upper, float)
1268
+ part = _Part(micro, Domain(size=tuple(upper - lower), origin=tuple(lower), periodic=False))
1269
+ spacing = float(background) if background is not None else size / 2.0
1270
+ values, shape = node_level_set(part, spacing)
1271
+ values = _snap_level_set(values, SNAP)
1272
+ if matching[0]:
1273
+ values[-1, :, :] = values[0, :, :]
1274
+ if matching[1]:
1275
+ values[:, -1, :] = values[:, 0, :]
1276
+ if matching[2]:
1277
+ values[:, :, -1] = values[:, :, 0]
1278
+ nodes, used, tets, tri, tri_refs = _chamber_background(shape, lower, upper, pairs)
1279
+ data = _mmg_level_set(mmg_executable(executable), nodes, tets, tri, tri_refs,
1280
+ values.ravel()[used], _matching_refs(matching),
1281
+ _on_faces(matching, lower, upper), size=size, phases=phases,
1282
+ **mmg) # fmt: skip
1283
+ xyz = _project_planes(data["Vertices"], data["Triangles"], data["Triangles_refs"], lower,
1284
+ upper, pairs) # fmt: skip
1285
+ elements = data["Tetrahedra"]
1286
+ flip = tet_volumes(xyz, elements) < 0
1287
+ elements[flip] = elements[flip][:, [0, 2, 1, 3]]
1288
+ used_nodes, inverse = np.unique(elements, return_inverse=True)
1289
+ phase = np.where(data["Tetrahedra_refs"] == REF_INSIDE, 1, 0)
1290
+ return TetMesh(xyz[used_nodes], inverse.reshape(elements.shape), phase, lower, upper,
1291
+ periodic=False, metadata={"mesher": "mmg3d -ls, chamber", "size": size,
1292
+ "phases": phases}) # fmt: skip
1293
+
1294
+
1295
+ def mirrored_mesh(
1296
+ micro,
1297
+ *,
1298
+ size: float,
1299
+ mirrors=(0, 1, 2),
1300
+ diagonals=(),
1301
+ cells=(1, 1, 1),
1302
+ order: int = 1,
1303
+ phases: str = "all",
1304
+ check: bool = True,
1305
+ **options,
1306
+ ) -> TetMesh:
1307
+ """A conforming tetrahedral mesh of a microstructure symmetric about the mid-planes of
1308
+ its box along the axes ``mirrors`` (see the module): the irreducible part of the box,
1309
+ halved along each of them, meshed by MMG (:func:`conforming_mesh`: ``size``,
1310
+ ``phases`` and the other ``options``; matching faces along the other axes), then
1311
+ reflected across the mid-planes, the nodes of each plane shared by its two halves. The
1312
+ mesh has these mirrors exactly, and its opposite faces match along every axis (the
1313
+ reflected ones, a periodic microstructure being symmetric about the faces of its box
1314
+ as well). ``diagonals``: pairs of mirrored axes of equal edges whose diagonal planes
1315
+ through the centre, ``x_i - c_i = x_j - c_j``, are mirrors too (``((0, 1),)`` for the
1316
+ square of 4/mmm, ``((0, 1), (1, 2))`` for the cube of m-3m): the chamber of the group
1317
+ (:func:`point_group`) is meshed and mapped by each of its operations. ``cells``: copies
1318
+ of the box side by side (a cell of several primitive cells, whose translations are
1319
+ exact symmetries of the mesh). ``check``: the level set is sampled to verify its
1320
+ symmetry. Elements of ``order`` 1 or 2."""
1321
+ domain: Domain = micro.domain
1322
+ lower, upper = np.asarray(domain.lower, float), np.asarray(domain.upper, float)
1323
+ mirrors = sorted({int(k) for k in np.atleast_1d(mirrors)})
1324
+ if any(k not in (0, 1, 2) for k in mirrors):
1325
+ raise ValueError("mirrors: axes 0, 1 or 2")
1326
+ counts = np.asarray(cells, dtype=int)
1327
+ if counts.shape != (3,) or np.any(counts < 1):
1328
+ raise ValueError("cells: three positive counts")
1329
+ mid = 0.5 * (lower + upper)
1330
+ span = float((upper - lower).max())
1331
+ diagonals = [tuple(sorted((int(a), int(b)))) for a, b in diagonals]
1332
+ for a, b in diagonals:
1333
+ if a == b or a not in mirrors or b not in mirrors:
1334
+ raise ValueError("diagonals: pairs of two mirrored axes")
1335
+ if abs((upper - lower)[a] - (upper - lower)[b]) > 1e-9 * span:
1336
+ raise ValueError("diagonals: axes of equal edges")
1337
+ if check and mirrors:
1338
+ n = 16
1339
+ sample = Grid(
1340
+ Domain(size=tuple(upper - lower), origin=tuple(lower), periodic=False), (n,) * 3
1341
+ )
1342
+ values = np.asarray(micro.level_set(grid=sample).data, dtype=float)
1343
+ scale = float(np.abs(values).max()) or 1.0
1344
+ for k in mirrors:
1345
+ if np.abs(values - np.flip(values, axis=k)).max() > 1e-6 * scale:
1346
+ raise ValueError(
1347
+ f"mirrored_mesh: the microstructure is not symmetric along axis {k}"
1348
+ )
1349
+ for a, b in diagonals:
1350
+ if np.abs(values - np.swapaxes(values, a, b)).max() > 1e-6 * scale:
1351
+ raise ValueError(
1352
+ f"mirrored_mesh: the microstructure is not symmetric about the diagonal "
1353
+ f"of axes {a} and {b}"
1354
+ )
1355
+ if diagonals:
1356
+ return _mirrored_chambers(micro, lower, upper, mirrors, diagonals, counts, size=size,
1357
+ order=order, phases=phases, **options) # fmt: skip
1358
+ top = upper.copy()
1359
+ top[mirrors] = mid[mirrors]
1360
+ part = _Part(micro, Domain(size=tuple(top - lower), origin=tuple(lower), periodic=False))
1361
+ matching = tuple(k not in mirrors for k in range(3))
1362
+ mesh = conforming_mesh(part, size=size, phases=phases, order=1, periodic=matching, **options)
1363
+ nodes, tets, phase = mesh.nodes.copy(), mesh.elements.copy(), mesh.phase.copy()
1364
+ for k in mirrors:
1365
+ on = np.abs(nodes[:, k] - mid[k]) <= 1e-9 * span
1366
+ nodes[on, k] = mid[k]
1367
+ index = np.empty(len(nodes), dtype=np.int64)
1368
+ index[on] = np.flatnonzero(on)
1369
+ index[~on] = len(nodes) + np.arange(int((~on).sum()))
1370
+ image = nodes[~on].copy()
1371
+ image[:, k] = 2.0 * mid[k] - image[:, k]
1372
+ nodes = np.vstack([nodes, image])
1373
+ tets = np.vstack([tets, index[tets][:, [0, 2, 1, 3]]]) # reflected, turned back
1374
+ phase = np.concatenate([phase, phase])
1375
+ length = upper - lower
1376
+ if np.any(counts > 1):
1377
+ blocks, shifted = [], []
1378
+ for offset, shift in enumerate(itertools.product(*(range(c) for c in counts))):
1379
+ blocks.append(nodes + np.asarray(shift) * length)
1380
+ shifted.append(tets + offset * len(nodes))
1381
+ nodes, tets = _merge(np.vstack(blocks), np.vstack(shifted), 1e-9 * span)
1382
+ phase = np.tile(phase, int(np.prod(counts)))
1383
+ out = TetMesh(nodes, tets, phase, lower, lower + counts * length, periodic=True,
1384
+ metadata={**mesh.metadata, "mesher": "mmg3d -ls, mirrored",
1385
+ "mirrors": mirrors, "cells": counts.tolist(),
1386
+ "matching_faces": [0, 1, 2]}) # fmt: skip
1387
+ return out.quadratic() if order == 2 else out
1388
+
1389
+
1390
+ def _mirrored_chambers(micro, lower, upper, mirrors, diagonals, counts, *, size, order,
1391
+ phases, **options) -> TetMesh: # fmt: skip
1392
+ """The mirrored mesh of a group with diagonal mirrors (see :func:`mirrored_mesh`)."""
1393
+ mid = 0.5 * (lower + upper)
1394
+ span = float((upper - lower).max())
1395
+ top = upper.copy()
1396
+ top[mirrors] = mid[mirrors]
1397
+ chamber_pairs = [(c[i], c[i + 1]) for c in _components(diagonals) for i in range(len(c) - 1)]
1398
+ matching = tuple(k not in mirrors for k in range(3))
1399
+ chamber = _chamber_mesh(micro, lower, top, chamber_pairs, matching, size=size,
1400
+ phases=phases, **options) # fmt: skip
1401
+ group = point_group(mirrors, diagonals)
1402
+ blocks, shifted, phases_out = [], [], []
1403
+ for k, m in enumerate(group):
1404
+ blocks.append(mid + (chamber.nodes - mid) @ m.T)
1405
+ tets = chamber.elements if np.linalg.det(m) > 0 else chamber.elements[:, [0, 2, 1, 3]]
1406
+ shifted.append(tets + k * chamber.n_nodes)
1407
+ phases_out.append(chamber.phase)
1408
+ nodes, tets = _merge(np.vstack(blocks), np.vstack(shifted), 1e-9 * span)
1409
+ phase = np.concatenate(phases_out)
1410
+ length = upper - lower
1411
+ if np.any(counts > 1):
1412
+ blocks, shifted = [], []
1413
+ for offset, shift in enumerate(itertools.product(*(range(c) for c in counts))):
1414
+ blocks.append(nodes + np.asarray(shift) * length)
1415
+ shifted.append(tets + offset * len(nodes))
1416
+ nodes, tets = _merge(np.vstack(blocks), np.vstack(shifted), 1e-9 * span)
1417
+ phase = np.tile(phase, int(np.prod(counts)))
1418
+ out = TetMesh(nodes, tets, phase, lower, lower + counts * length, periodic=True,
1419
+ metadata={**chamber.metadata, "mesher": "mmg3d -ls, mirrored chambers",
1420
+ "mirrors": mirrors, "diagonals": [list(d) for d in diagonals],
1421
+ "group_order": len(group), "cells": counts.tolist(),
1422
+ "matching_faces": [0, 1, 2]}) # fmt: skip
1423
+ return out.quadratic() if order == 2 else out