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,1041 @@
1
+ """Conforming tetrahedral meshes of polycrystals (Voronoi and Laguerre tessellations).
2
+
3
+ The exact cells of the tessellation (:mod:`morphogen.mesh.polyhedra`) are convex
4
+ polyhedra with planar facets; the features smaller than ``min_feature`` are removed
5
+ first (:mod:`morphogen.mesh.regularize`). Each piece is then split into tetrahedra, a cone
6
+ from its centroid over its triangulated facets: a valid mesh of the whole complex,
7
+ conforming at the grain boundaries, with poor elements. MMG (``mmg3d``) remeshes it to
8
+ the requested size, keeping the grain boundaries (interfaces between subdomains of
9
+ different references), their triple lines (non-manifold edges) and quadruple points.
10
+
11
+ Periodic polycrystals get matching opposite faces. The edges of the box are subdivided
12
+ once for the four parallel edges; each pair of opposite faces is meshed in two
13
+ dimensions from the traces of the grain boundaries (the faces of the regularized complex
14
+ are translates of each other), subdivided at the element size: ``mmg2d`` remeshes their
15
+ constrained Delaunay triangulation, keeping the traces. The same triangles are used on
16
+ both faces and the volume remeshing keeps them unchanged.
17
+
18
+ Quality: on Voronoi tessellations of 30 to 300 cells, the mean quality of the elements
19
+ is 0.72-0.74 and 0.1 % of them are below 0.05-0.1; the few worst ones (down to 0.004)
20
+ sit in the thin wedges between grain boundaries and faces of the box that remain.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import itertools
26
+ import logging
27
+ import tempfile
28
+ import time
29
+ from pathlib import Path
30
+
31
+ import numpy as np
32
+ from scipy.spatial import cKDTree
33
+
34
+ from morphogen.domain import Domain
35
+ from morphogen.io import medit
36
+ from morphogen.mesh.conforming import _run_mmg, mmg_executable
37
+ from morphogen.mesh.polyhedra import CellComplex, _merge_points
38
+ from morphogen.mesh.regularize import regularize
39
+ from morphogen.mesh.tetra import TetMesh, tet_volumes
40
+
41
+ log = logging.getLogger("morphogen")
42
+
43
+ #: Reference of the grain-boundary triangles (the faces of the box are 1-6).
44
+ REF_GRAIN_BOUNDARY = 7
45
+
46
+
47
+ def _others(axis: int) -> tuple[int, int]:
48
+ return tuple(d for d in range(3) if d != axis) # type: ignore[return-value]
49
+
50
+
51
+ class _Points:
52
+ """Growing array of vertices."""
53
+
54
+ def __init__(self, xyz: np.ndarray):
55
+ self.blocks = [np.asarray(xyz, dtype=float)]
56
+ self.n = len(xyz)
57
+
58
+ def add(self, xyz) -> np.ndarray:
59
+ xyz = np.asarray(xyz, dtype=float).reshape(-1, 3)
60
+ ids = np.arange(self.n, self.n + len(xyz))
61
+ self.blocks.append(xyz)
62
+ self.n += len(xyz)
63
+ return ids
64
+
65
+ def array(self) -> np.ndarray:
66
+ if len(self.blocks) > 1:
67
+ self.blocks = [np.concatenate(self.blocks)]
68
+ return self.blocks[0]
69
+
70
+
71
+ def _fan(loop, centre: int) -> np.ndarray:
72
+ """Triangles of a polygon: a fan from its centre (one triangle for three vertices)."""
73
+ loop = np.asarray(loop, dtype=np.int64)
74
+ if len(loop) == 3:
75
+ return loop[None, :].copy()
76
+ return np.column_stack([np.full(len(loop), centre), loop, np.roll(loop, -1)])
77
+
78
+
79
+ def _point_in_polygon(points: np.ndarray, poly: np.ndarray) -> np.ndarray:
80
+ """Winding-number test of 2D points against a closed polygon."""
81
+ x, y = points[:, 0][:, None], points[:, 1][:, None]
82
+ x0, y0 = poly[:, 0][None, :], poly[:, 1][None, :]
83
+ x1, y1 = np.roll(poly[:, 0], -1)[None, :], np.roll(poly[:, 1], -1)[None, :]
84
+ cross = (x1 - x0) * (y - y0) - (x - x0) * (y1 - y0)
85
+ up = (y0 <= y) & (y1 > y) & (cross > 0)
86
+ down = (y0 > y) & (y1 <= y) & (cross < 0)
87
+ return (up.sum(axis=1) - down.sum(axis=1)) != 0
88
+
89
+
90
+ def _split_segments(points: np.ndarray, segments: list, tol: float) -> tuple[np.ndarray, list]:
91
+ """Planar straight-line graph without crossings: segments split at the points lying
92
+ on them and at their intersections."""
93
+ pts = [p for p in points]
94
+ segs = {tuple(sorted(s)) for s in segments if s[0] != s[1]}
95
+ changed = True
96
+ while changed:
97
+ changed = False
98
+ arr = np.array(pts)
99
+ tree = cKDTree(arr)
100
+ out = set()
101
+ for a, b in segs:
102
+ pa, pb = arr[a], arr[b]
103
+ ab = pb - pa
104
+ length = float(np.hypot(*ab))
105
+ near = tree.query_ball_point(0.5 * (pa + pb), 0.5 * length + tol)
106
+ inside = []
107
+ for k in near:
108
+ if k in (a, b):
109
+ continue
110
+ t = float((arr[k] - pa) @ ab) / length**2
111
+ if (
112
+ 0.0 < t < 1.0
113
+ and abs(ab[0] * (arr[k] - pa)[1] - ab[1] * (arr[k] - pa)[0]) <= tol * length
114
+ ):
115
+ inside.append((t, k))
116
+ if inside:
117
+ chain = [a] + [k for _, k in sorted(inside)] + [b]
118
+ out.update(tuple(sorted(s)) for s in itertools.pairwise(chain))
119
+ changed = True
120
+ else:
121
+ out.add((a, b))
122
+ segs = out
123
+ # proper crossings
124
+ seg_list = sorted(segs)
125
+ sa = np.array([arr[a] for a, _ in seg_list])
126
+ sb = np.array([arr[b] for _, b in seg_list])
127
+ lo, hi = np.minimum(sa, sb), np.maximum(sa, sb)
128
+ crossings = []
129
+ for i in range(len(seg_list)):
130
+ cand = (
131
+ np.flatnonzero(
132
+ np.all(lo[i + 1 :] <= hi[i] + tol, axis=1)
133
+ & np.all(hi[i + 1 :] >= lo[i] - tol, axis=1)
134
+ )
135
+ + i
136
+ + 1
137
+ )
138
+ for j in cand:
139
+ if set(seg_list[i]) & set(seg_list[j]):
140
+ continue
141
+ d1, d2 = sb[i] - sa[i], sb[j] - sa[j]
142
+ den = d1[0] * d2[1] - d1[1] * d2[0]
143
+ if abs(den) <= 1e-14:
144
+ continue
145
+ w = sa[j] - sa[i]
146
+ t = (w[0] * d2[1] - w[1] * d2[0]) / den
147
+ u = (w[0] * d1[1] - w[1] * d1[0]) / den
148
+ if 1e-9 < t < 1 - 1e-9 and 1e-9 < u < 1 - 1e-9:
149
+ crossings.append(sa[i] + t * d1)
150
+ if crossings:
151
+ pts.extend(crossings)
152
+ changed = True
153
+ return np.array(pts), sorted(segs)
154
+
155
+
156
+ def _periodic_faces(cx: CellComplex, pts: _Points, size, sizing2d, exe2d, folder, timeout):
157
+ """Matching triangulations of opposite faces of the box (triangles of each box facet,
158
+ in global vertex ids)."""
159
+ lo, hi = cx.lower, cx.upper
160
+ length = hi - lo
161
+ tol = 1e-9 * float(length.max())
162
+ xyz = pts.array()
163
+ n0 = len(xyz)
164
+ side = np.stack([np.abs(xyz - lo) <= tol, np.abs(xyz - hi) <= tol]) # (2, n, 3)
165
+ # 1. the twelve edges of the box, subdivided alike along parallel edges
166
+ for d in range(3):
167
+ b, c = _others(d)
168
+ params = []
169
+ for sb in (0, 1):
170
+ for sc in (0, 1):
171
+ on = np.flatnonzero(side[sb, :n0, b] & side[sc, :n0, c])
172
+ params.extend(xyz[on, d] - lo[d])
173
+ t = np.unique(np.round(np.array([*params, 0.0, length[d]]) / tol) * tol)
174
+ full = [t[0]]
175
+ for t0, t1 in itertools.pairwise(t):
176
+ m = int(np.ceil((t1 - t0) / size - 1e-9))
177
+ full += [t0 + (t1 - t0) * j / m for j in range(1, m)] + [t1]
178
+ full = np.array(full)
179
+ for sb in (0, 1):
180
+ for sc in (0, 1):
181
+ on = np.flatnonzero(side[sb, :n0, b] & side[sc, :n0, c])
182
+ have = xyz[on, d] - lo[d]
183
+ missing = [s for s in full if not np.any(np.abs(have - s) <= 1e3 * tol)]
184
+ if missing:
185
+ p = np.zeros((len(missing), 3))
186
+ p[:, d] = lo[d] + np.array(missing)
187
+ p[:, b] = (lo, hi)[sb][b]
188
+ p[:, c] = (lo, hi)[sc][c]
189
+ pts.add(p)
190
+ xyz = pts.array()
191
+ face_tris: dict[int, list] = {}
192
+ for axis in range(3):
193
+ b, c = _others(axis)
194
+ uvw = [b, c]
195
+ on_face = [np.flatnonzero(np.abs(xyz[:, axis] - (lo, hi)[s][axis]) <= tol) for s in (0, 1)]
196
+ facets = [np.flatnonzero(cx.facet_box == 2 * axis + 1 + s) for s in (0, 1)]
197
+ # 2D points of both faces (merged), and the segments of their polygons
198
+ all2d = np.concatenate([xyz[on_face[0]][:, uvw], xyz[on_face[1]][:, uvw]])
199
+ inverse = _merge_points(all2d, 100 * tol)
200
+ first = np.zeros(int(inverse.max()) + 1, dtype=np.int64)
201
+ first[inverse[::-1]] = np.arange(len(inverse))[::-1]
202
+ pts2d = all2d[first]
203
+ local = [
204
+ dict(zip(on_face[0].tolist(), inverse[: len(on_face[0])].tolist(), strict=True)),
205
+ dict(zip(on_face[1].tolist(), inverse[len(on_face[0]) :].tolist(), strict=True)),
206
+ ]
207
+ segments = []
208
+ for s in (0, 1):
209
+ for f in facets[s]:
210
+ loop = [local[s][int(v)] for v in cx.facets[f]]
211
+ segments += list(zip(loop, loop[1:] + loop[:1], strict=True))
212
+ pts2d, segments = _split_segments(pts2d, segments, 1e3 * tol)
213
+ bnd = set()
214
+ for k in range(len(pts2d)):
215
+ p = pts2d[k]
216
+ if (
217
+ (abs(p[0] - lo[b]) <= 1e3 * tol)
218
+ or (abs(p[0] - hi[b]) <= 1e3 * tol)
219
+ or (abs(p[1] - lo[c]) <= 1e3 * tol)
220
+ or (abs(p[1] - hi[c]) <= 1e3 * tol)
221
+ ):
222
+ bnd.add(k)
223
+ # boundary edges: consecutive points along each side of the square
224
+ box_segs = []
225
+ for coord, value in ((0, lo[b]), (0, hi[b]), (1, lo[c]), (1, hi[c])):
226
+ on = [k for k in bnd if abs(pts2d[k][coord] - value) <= 1e3 * tol]
227
+ on.sort(key=lambda k: pts2d[k][1 - coord])
228
+ box_segs += [tuple(sorted(e)) for e in itertools.pairwise(on)]
229
+ box_set = set(box_segs)
230
+ inner = [
231
+ s
232
+ for s in segments
233
+ if s not in box_set
234
+ and not (s[0] in bnd and s[1] in bnd and _same_side(pts2d, s, lo, hi, b, c, 1e3 * tol))
235
+ ]
236
+ # the traces subdivided at the element size: mmg2d keeps them straight (it would
237
+ # place the points it inserts on a curve through their vertices)
238
+ pts2d, inner = _subdivide(pts2d, inner, size)
239
+ edges = np.array(box_segs + inner, dtype=np.int64)
240
+ # mmg2d remeshes a triangulation of the traces: building one itself (inserting
241
+ # the segments in a triangulation of their points) fails on some inputs
242
+ medit.write_mesh(
243
+ folder / f"face{axis}.mesh",
244
+ pts2d,
245
+ triangles=_triangulate_pslg(pts2d, edges),
246
+ edges=edges,
247
+ edge_refs=np.array([1] * len(box_segs) + [2] * len(inner)),
248
+ required_edges=np.arange(len(edges)),
249
+ required_vertices=np.arange(len(pts2d)),
250
+ )
251
+ out = _run_mmg(
252
+ exe2d,
253
+ folder / f"face{axis}.mesh",
254
+ None,
255
+ folder / f"face{axis}.o.mesh",
256
+ [*sizing2d, "-nosurf"],
257
+ timeout,
258
+ )
259
+ ov, ot = out["Vertices"], out["Triangles"]
260
+ oe = out.get("Edges", np.zeros((0, 2), dtype=np.int64))
261
+ if len(oe):
262
+ dist, _ = cKDTree(pts2d).query(ov[np.unique(oe)])
263
+ if dist.max() > 1e3 * tol:
264
+ raise RuntimeError(
265
+ "polycrystal mesh: mmg2d moved the traces of the grain boundaries"
266
+ )
267
+ # mmg2d is not deterministic (its triangles differ by a few flips from one run to
268
+ # the next): the constrained Delaunay triangulation of its points is
269
+ dist, where = cKDTree(ov).query(pts2d)
270
+ if dist.max() > 1e3 * tol:
271
+ raise RuntimeError("polycrystal mesh: mmg2d lost points of the traces")
272
+ ot = _constrained_delaunay(ov, ot, where[edges])
273
+ kept = {tuple(sorted(e)) for t in ot.tolist() for e in itertools.combinations(t, 2)}
274
+ if not all(tuple(sorted(e)) in kept for e in where[edges].tolist()):
275
+ raise RuntimeError("polycrystal mesh: mmg2d lost segments of the traces")
276
+ centres = ov[ot].mean(axis=1)
277
+ for s in (0, 1):
278
+ plane = (lo, hi)[s][axis]
279
+ # global ids of the output vertices on this face: existing vertices or new ones
280
+ existing = on_face[s]
281
+ tree = cKDTree(xyz[existing][:, uvw])
282
+ dist, near = tree.query(ov)
283
+ gid = np.where(dist <= 1e3 * tol, existing[near], -1)
284
+ new = np.flatnonzero(gid < 0)
285
+ if new.size:
286
+ p = np.zeros((new.size, 3))
287
+ p[:, axis] = plane
288
+ p[:, b], p[:, c] = ov[new, 0], ov[new, 1]
289
+ gid[new] = pts.add(p)
290
+ xyz = pts.array()
291
+ # each region of the face mesh lies in one polygon of this face
292
+ for f in facets[s]:
293
+ poly = xyz[cx.facets[f]][:, uvw]
294
+ inside = _point_in_polygon(centres, poly)
295
+ tris = gid[ot[inside]]
296
+ face_tris.setdefault(int(f), []).append(tris)
297
+ covered = sum(len(np.concatenate(face_tris[int(f)])) for s in (0, 1) for f in facets[s])
298
+ if covered != 2 * len(ot):
299
+ raise RuntimeError(
300
+ "polycrystal mesh: the face meshes do not cover the polygons of the faces"
301
+ )
302
+ return {f: np.concatenate(t) for f, t in face_tris.items()}
303
+
304
+
305
+ def _orient(pa, pb, pc) -> float:
306
+ """Twice the signed area of the triangle ``(pa, pb, pc)``, positive when it is
307
+ counter-clockwise; its sign is exact (recomputed in rational arithmetic when rounding
308
+ could change it, with the error bound of Shewchuk 1997)."""
309
+ left = (pa[0] - pc[0]) * (pb[1] - pc[1])
310
+ right = (pa[1] - pc[1]) * (pb[0] - pc[0])
311
+ det = left - right
312
+ if abs(det) > 1e-15 * (abs(left) + abs(right)):
313
+ return det
314
+ from fractions import Fraction
315
+
316
+ ax, ay, bx, by, cx, cy = map(Fraction, (*pa, *pb, *pc))
317
+ return float((ax - cx) * (by - cy) - (ay - cy) * (bx - cx))
318
+
319
+
320
+ def _triangulate_pslg(points: np.ndarray, segments) -> np.ndarray:
321
+ """Constrained Delaunay triangulation of a planar straight-line graph whose segments
322
+ meet only at their ends and include the boundary of the convex hull of the points:
323
+ the Delaunay triangulation of the points, the missing segments recovered by edge
324
+ flips (Sloan 1993), then Lawson's flips. Exact orientation tests make the flips
325
+ valid whatever the input; a segment through a point is split there."""
326
+ from collections import deque
327
+
328
+ from scipy.spatial import Delaunay
329
+
330
+ points = np.asarray(points, dtype=float)
331
+ dt = Delaunay(points)
332
+ if len(dt.coplanar):
333
+ raise RuntimeError("polycrystal mesh: points of a face too close to triangulate")
334
+ pts = [tuple(p) for p in points.tolist()]
335
+ tris = [list(map(int, t)) for t in dt.simplices]
336
+ owner: dict = {} # directed edge -> triangle (counter-clockwise) holding it
337
+ adj = [set() for _ in pts]
338
+ for k, t in enumerate(tris):
339
+ if _orient(pts[t[0]], pts[t[1]], pts[t[2]]) < 0:
340
+ t[1], t[2] = t[2], t[1]
341
+ a, b, c = t
342
+ owner[(a, b)] = owner[(b, c)] = owner[(c, a)] = k
343
+ adj[a] |= {b, c}
344
+ adj[b] |= {a, c}
345
+ adj[c] |= {a, b}
346
+
347
+ def third(k, a, b):
348
+ return next(v for v in tris[k] if v != a and v != b)
349
+
350
+ def crossed(a, b):
351
+ """Edges crossed by the segment from ``a`` to ``b`` (right end first), up to a
352
+ point lying on it (or ``b``)."""
353
+ pa, pb = pts[a], pts[b]
354
+ for p in adj[a]:
355
+ pp = pts[p]
356
+ ahead = (pp[0] - pa[0]) * (pb[0] - pa[0]) + (pp[1] - pa[1]) * (pb[1] - pa[1]) > 0
357
+ if ahead and _orient(pa, pb, pp) == 0:
358
+ return [], p # along an edge of the triangulation
359
+ for p in adj[a]:
360
+ k = owner.get((a, p))
361
+ if k is None:
362
+ continue
363
+ q = third(k, a, p)
364
+ if _orient(pa, pts[p], pb) > 0 and _orient(pa, pts[q], pb) < 0:
365
+ break
366
+ else:
367
+ raise RuntimeError("polycrystal mesh: a segment of a face leaves its square")
368
+ out = [(p, q)]
369
+ while True:
370
+ r = third(owner[(q, p)], p, q)
371
+ if r == b:
372
+ return out, b
373
+ side = _orient(pa, pb, pts[r])
374
+ if side == 0:
375
+ return out, r
376
+ if side > 0:
377
+ q = r
378
+ else:
379
+ p = r
380
+ out.append((p, q))
381
+
382
+ fixed: set = set()
383
+ todo = [tuple(map(int, s)) for s in np.asarray(segments).tolist()]
384
+ while todo:
385
+ a, b = todo.pop()
386
+ if a == b:
387
+ continue
388
+ if b in adj[a]:
389
+ fixed.add((min(a, b), max(a, b)))
390
+ continue
391
+ edges, end = crossed(a, b)
392
+ if end != b: # through a point: two segments
393
+ todo += [(a, end), (end, b)]
394
+ continue
395
+ if any((min(e), max(e)) in fixed for e in edges):
396
+ raise RuntimeError("polycrystal mesh: segments of a face cross each other")
397
+ pa, pb = pts[a], pts[b]
398
+ queue = deque(edges)
399
+ budget = 10 * (len(edges) + 2) ** 3 # Sloan: O(n^2) flips, each after O(n) tries
400
+ while queue:
401
+ budget -= 1
402
+ if budget < 0:
403
+ raise RuntimeError("polycrystal mesh: the traces of a face cannot be inserted")
404
+ u, v = queue.popleft()
405
+ k1, k2 = owner[(u, v)], owner[(v, u)]
406
+ w, x = third(k1, u, v), third(k2, u, v)
407
+ if not (_orient(pts[u], pts[x], pts[w]) > 0 and _orient(pts[x], pts[v], pts[w]) > 0):
408
+ queue.append((u, v)) # not convex: later
409
+ continue
410
+ # (u, v, w) and (v, u, x) become (u, x, w) and (x, v, w)
411
+ del owner[(u, v)], owner[(v, u)]
412
+ tris[k1], tris[k2] = [u, x, w], [x, v, w]
413
+ for e in ((u, x), (x, w), (w, u)):
414
+ owner[e] = k1
415
+ for e in ((x, v), (v, w), (w, x)):
416
+ owner[e] = k2
417
+ adj[u].discard(v)
418
+ adj[v].discard(u)
419
+ adj[w].add(x)
420
+ adj[x].add(w)
421
+ if {w, x} & {a, b}:
422
+ continue
423
+ if _orient(pa, pb, pts[w]) * _orient(pa, pb, pts[x]) < 0:
424
+ queue.append((w, x))
425
+ fixed.add((min(a, b), max(a, b)))
426
+ return _constrained_delaunay(points, np.array(tris, dtype=np.int64), sorted(fixed))
427
+
428
+
429
+ def _incircle(pa, pb, pc, pd) -> float:
430
+ """Positive when ``pd`` lies inside the circle through the counter-clockwise
431
+ triangle ``(pa, pb, pc)``."""
432
+ adx, ady = pa[0] - pd[0], pa[1] - pd[1]
433
+ bdx, bdy = pb[0] - pd[0], pb[1] - pd[1]
434
+ cdx, cdy = pc[0] - pd[0], pc[1] - pd[1]
435
+ ad, bd, cd = adx * adx + ady * ady, bdx * bdx + bdy * bdy, cdx * cdx + cdy * cdy
436
+ return adx * (bdy * cd - bd * cdy) - ady * (bdx * cd - bd * cdx) + ad * (bdx * cdy - bdy * cdx)
437
+
438
+
439
+ def _constrained_delaunay(points: np.ndarray, triangles: np.ndarray, fixed) -> np.ndarray:
440
+ """The constrained Delaunay triangulation of a triangulated polygon: Lawson's edge
441
+ flips from any triangulation (counter-clockwise triangles) whose edges include the
442
+ ``fixed`` ones. It is unique (but for cocircular points), so that triangulations of
443
+ the same points differing by flips give the same result; triangles in a canonical
444
+ order."""
445
+ pts = [tuple(p) for p in np.asarray(points, dtype=float)]
446
+ tris = [list(map(int, t)) for t in triangles]
447
+ for t in tris: # counter-clockwise
448
+ (ax, ay), (bx, by), (cx, cy) = pts[t[0]], pts[t[1]], pts[t[2]]
449
+ if (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) < 0:
450
+ t[1], t[2] = t[2], t[1]
451
+ owner = {}
452
+ for k, (a, b, c) in enumerate(tris):
453
+ owner[(a, b)] = owner[(b, c)] = owner[(c, a)] = k
454
+ locked = {(min(a, b), max(a, b)) for a, b in np.asarray(fixed, dtype=np.int64).tolist()}
455
+ stack = [(a, b) for (a, b) in owner if a < b and (a, b) not in locked]
456
+
457
+ def third(t, a, b):
458
+ return next(v for v in t if v != a and v != b)
459
+
460
+ while stack:
461
+ a, b = stack.pop()
462
+ if (a, b) in locked:
463
+ continue
464
+ t1, t2 = owner.get((a, b)), owner.get((b, a))
465
+ if t1 is None or t2 is None:
466
+ continue
467
+ c, d = third(tris[t1], a, b), third(tris[t2], a, b)
468
+ pa, pb, pc, pd = pts[a], pts[b], pts[c], pts[d]
469
+ scale = max((p[0] - pd[0]) ** 2 + (p[1] - pd[1]) ** 2 for p in (pa, pb, pc)) ** 2
470
+ if _incircle(pa, pb, pc, pd) <= 1e-10 * scale:
471
+ continue
472
+ # (a, b, c) and (b, a, d) become (a, d, c) and (d, b, c)
473
+ for e in ((a, b), (b, a), (b, c), (c, a), (a, d), (d, b)):
474
+ owner.pop(e, None)
475
+ tris[t1], tris[t2] = [a, d, c], [d, b, c]
476
+ for e in ((a, d), (d, c), (c, a)):
477
+ owner[e] = t1
478
+ for e in ((d, b), (b, c), (c, d)):
479
+ owner[e] = t2
480
+ stack += [(min(e), max(e)) for e in ((a, d), (d, b), (b, c), (c, a))]
481
+ out = np.array(tris, dtype=np.int64)
482
+ first = np.argmin(out, axis=1) # rotate the smallest vertex first, keep the orientation
483
+ out = np.stack([out[np.arange(len(out)), (first + k) % 3] for k in range(3)], axis=1)
484
+ return out[np.lexsort(out.T[::-1])]
485
+
486
+
487
+ def _subdivide(points: np.ndarray, segments: list, size: float) -> tuple[np.ndarray, list]:
488
+ """Segments split into equal parts no longer than ``size``."""
489
+ new, out = [], []
490
+ n = len(points)
491
+ for a, b in segments:
492
+ pa, pb = points[a], points[b]
493
+ m = int(np.ceil(float(np.hypot(*(pb - pa))) / size - 1e-9))
494
+ if m <= 1:
495
+ out.append((a, b))
496
+ continue
497
+ ids = [a, *range(n + len(new), n + len(new) + m - 1), b]
498
+ new.extend(pa + (pb - pa) * j / m for j in range(1, m))
499
+ out.extend(itertools.pairwise(ids))
500
+ if new:
501
+ points = np.concatenate([points, np.array(new)])
502
+ return points, out
503
+
504
+
505
+ def _same_side(pts2d, s, lo, hi, b, c, tol) -> bool:
506
+ """Whether a segment lies along a side of the square."""
507
+ p, q = pts2d[s[0]], pts2d[s[1]]
508
+ for coord, value in ((0, lo[b]), (0, hi[b]), (1, lo[c]), (1, hi[c])):
509
+ if abs(p[coord] - value) <= tol and abs(q[coord] - value) <= tol:
510
+ return True
511
+ return False
512
+
513
+
514
+ def _insert_face_points(cx: CellComplex, pts: _Points, tol: float) -> list:
515
+ """Loops of the facets with the points of the faces of the box lying on their edges
516
+ (the face meshes subdivide the traces of the grain boundaries)."""
517
+ xyz = pts.array()
518
+ lo, hi = cx.lower, cx.upper
519
+ loops = []
520
+ trees = {}
521
+ for axis in range(3):
522
+ for s in (0, 1):
523
+ ids = np.flatnonzero(np.abs(xyz[:, axis] - (lo, hi)[s][axis]) <= tol)
524
+ trees[(axis, s)] = (ids, cKDTree(xyz[ids]) if ids.size else None)
525
+ for f, loop in enumerate(cx.facets):
526
+ if cx.facet_box[f] > 0:
527
+ loops.append(loop)
528
+ continue
529
+ out = []
530
+ for a, b in zip(loop, np.roll(loop, -1), strict=True):
531
+ out.append(int(a))
532
+ pa, pb = xyz[a], xyz[b]
533
+ inside = {}
534
+ for axis in range(3):
535
+ for s in (0, 1):
536
+ plane = (lo, hi)[s][axis]
537
+ if abs(pa[axis] - plane) > tol or abs(pb[axis] - plane) > tol:
538
+ continue
539
+ ids, tree = trees[(axis, s)]
540
+ if tree is None:
541
+ continue
542
+ ab = pb - pa
543
+ length = float(np.linalg.norm(ab))
544
+ near = tree.query_ball_point(0.5 * (pa + pb), 0.5 * length + tol)
545
+ for k in near:
546
+ w = int(ids[k])
547
+ if w in (a, b):
548
+ continue
549
+ t = float((xyz[w] - pa) @ ab) / length**2
550
+ if 0.0 < t < 1.0 and np.linalg.norm(pa + t * ab - xyz[w]) <= 1e3 * tol:
551
+ inside[w] = t
552
+ out.extend(sorted(inside, key=inside.get))
553
+ loops.append(np.array(out, dtype=np.int64))
554
+ return loops
555
+
556
+
557
+ def initial_mesh(cx: CellComplex, *, size, sizing, periodic, folder, timeout):
558
+ """Tetrahedra of the pieces (cones from their centroids over their triangulated
559
+ facets), with the cell + 1 of each tetrahedron, the triangles of the faces of the box
560
+ (references 1-6, first ``n_box`` of them) and of the grain boundaries."""
561
+ tol = 1e-9 * float((cx.upper - cx.lower).max())
562
+ pts = _Points(cx.vertices)
563
+ face_tris: dict = {}
564
+ if periodic:
565
+ face_tris = _periodic_faces(
566
+ cx, pts, size, sizing, mmg_executable(None, "mmg2d"), folder, timeout
567
+ )
568
+ loops = _insert_face_points(cx, pts, tol)
569
+ else:
570
+ loops = list(cx.facets)
571
+ xyz = pts.array()
572
+ facet_tris = []
573
+ for f, loop in enumerate(loops):
574
+ if f in face_tris:
575
+ facet_tris.append(face_tris[f])
576
+ continue
577
+ # fan from the centre of the facet's own vertices (as checked by the
578
+ # regularization), over its loop with the points added on its edges
579
+ centre = -1
580
+ if len(loop) > 3:
581
+ centre = int(pts.add(xyz[cx.facets[f]].mean(axis=0))[0])
582
+ facet_tris.append(_fan(loop, centre))
583
+ xyz = pts.array()
584
+ tets, refs = [], []
585
+ for p, pf in enumerate(cx.piece_facets):
586
+ members = np.unique(np.concatenate([cx.facets[f] for f in pf]))
587
+ g = int(pts.add(xyz[members].mean(axis=0))[0])
588
+ for f in pf:
589
+ t = facet_tris[f]
590
+ tets.append(np.column_stack([t, np.full(len(t), g)]))
591
+ refs.append(np.full(len(t), cx.piece_cell[p] + 1))
592
+ xyz = pts.array()
593
+ tets = np.concatenate(tets)
594
+ refs = np.concatenate(refs)
595
+ vol = tet_volumes(xyz, tets)
596
+ tets[vol < 0] = tets[vol < 0][:, [0, 2, 1, 3]]
597
+ tri, tri_refs = [], []
598
+ for f in range(cx.n_facets):
599
+ if cx.facet_box[f] > 0:
600
+ tri.append(facet_tris[f])
601
+ tri_refs.append(np.full(len(facet_tris[f]), cx.facet_box[f]))
602
+ n_box = sum(len(t) for t in tri)
603
+ for f in cx.interface_facets():
604
+ tri.append(facet_tris[f])
605
+ tri_refs.append(np.full(len(facet_tris[f]), REF_GRAIN_BOUNDARY))
606
+ return xyz, tets, refs, np.concatenate(tri), np.concatenate(tri_refs), n_box
607
+
608
+
609
+ def _segment_distance(points: np.ndarray, a: np.ndarray, b: np.ndarray) -> np.ndarray:
610
+ """Distance from 2D points to the nearest of the segments ``a[k] b[k]``."""
611
+ ab = b - a
612
+ t = ((points[:, None, :] - a[None]) * ab[None]).sum(-1) / np.maximum((ab * ab).sum(-1), 1e-300)
613
+ proj = a[None] + np.clip(t, 0.0, 1.0)[..., None] * ab[None]
614
+ return np.linalg.norm(points[:, None, :] - proj, axis=-1).min(axis=1)
615
+
616
+
617
+ def _inside(triangles: np.ndarray, m: int) -> np.ndarray:
618
+ """Triangles (counter-clockwise) inside the polygon of the points ``0, ..., m - 1``
619
+ (counter-clockwise), reached from its edges without crossing them: unlike a test of
620
+ their centroids, this leaves out the flat triangles of nearly collinear points that a
621
+ triangulation of the convex hull lays along the edges."""
622
+ owner = {}
623
+ for k, (a, b, c) in enumerate(triangles.tolist()):
624
+ owner[(a, b)] = owner[(b, c)] = owner[(c, a)] = k
625
+ boundary = {(k, (k + 1) % m) for k in range(m)}
626
+ blocked = boundary | {(b, a) for a, b in boundary}
627
+ inside = np.zeros(len(triangles), dtype=bool)
628
+ stack = [owner[e] for e in boundary if e in owner]
629
+ while stack:
630
+ k = stack.pop()
631
+ if inside[k]:
632
+ continue
633
+ inside[k] = True
634
+ a, b, c = triangles[k].tolist()
635
+ for e in ((a, b), (b, c), (c, a)):
636
+ if e not in blocked:
637
+ nb = owner.get((e[1], e[0]))
638
+ if nb is not None and not inside[nb]:
639
+ stack.append(nb)
640
+ return inside
641
+
642
+
643
+ def _mesh_polygon(loop: np.ndarray, size: float) -> tuple[np.ndarray, np.ndarray]:
644
+ """Triangles of a (nearly planar) polygon at the element size: the points of a
645
+ triangular lattice of spacing ``size`` inside it, at least half of it from the
646
+ boundary, and the constrained Delaunay triangulation of its corners with them; the
647
+ points subdividing its sides, collinear but for rounding (which could make flat
648
+ triangles of three of them), are then joined to the vertex facing their side, before
649
+ Lawson's flips. Returns the interior points, lifted onto the fan of the loop from its
650
+ centroid (exact for a planar polygon), and the triangles (indices: the loop points,
651
+ then the interior points), counter-clockwise around the normal of the loop."""
652
+ c = loop.mean(axis=0)
653
+ normal = np.cross(loop - c, np.roll(loop, -1, axis=0) - c).sum(axis=0)
654
+ normal /= np.linalg.norm(normal)
655
+ u = loop[0] - c
656
+ u -= normal * (u @ normal)
657
+ u /= np.linalg.norm(u)
658
+ v = np.cross(normal, u)
659
+ p2 = np.column_stack([(loop - c) @ u, (loop - c) @ v])
660
+ m = len(p2)
661
+ back, ahead = p2 - np.roll(p2, 1, axis=0), np.roll(p2, -1, axis=0) - p2
662
+ turn = back[:, 0] * ahead[:, 1] - back[:, 1] * ahead[:, 0]
663
+ bend = np.linalg.norm(back, axis=1) * np.linalg.norm(ahead, axis=1)
664
+ corners = np.flatnonzero((np.abs(turn) > 1e-6 * bend) | ((back * ahead).sum(axis=1) < 0))
665
+ if len(corners) < 3:
666
+ raise RuntimeError("polycrystal mesh: a facet has less than three corners")
667
+ lo, hi = p2.min(axis=0), p2.max(axis=0)
668
+ dy = 0.5 * np.sqrt(3.0) * size
669
+ rows = []
670
+ for i, y in enumerate(np.arange(lo[1], hi[1] + dy, dy)):
671
+ xs = np.arange(lo[0] + (0.5 * size if i % 2 else 0.0), hi[0] + size, size)
672
+ rows.append(np.column_stack([xs, np.full(len(xs), y)]))
673
+ cand = np.concatenate(rows)
674
+ cand = cand[_point_in_polygon(cand, p2)]
675
+ if len(cand):
676
+ cand = cand[_segment_distance(cand, p2, np.roll(p2, -1, axis=0)) >= 0.5 * size]
677
+ mc = len(corners)
678
+ ring = np.column_stack([np.arange(mc), (np.arange(mc) + 1) % mc])
679
+ tri = _triangulate_pslg(np.vstack([p2[corners], cand]), ring)
680
+ index = np.concatenate([corners, m + np.arange(len(cand))])
681
+ tris = [list(map(int, t)) for t in index[tri[_inside(tri, mc)]]]
682
+ owner = {}
683
+ for k, (a, b, w) in enumerate(tris):
684
+ owner[(a, b)] = owner[(b, w)] = owner[(w, a)] = k
685
+ for i in range(mc):
686
+ a, b = int(corners[i]), int(corners[(i + 1) % mc])
687
+ side = [a, *((a + j) % m for j in range(1, (b - a) % m)), b]
688
+ if len(side) == 2:
689
+ continue
690
+ k = owner.pop((a, b))
691
+ w = next(x for x in tris[k] if x != a and x != b)
692
+ fan = [[p, q, w] for p, q in itertools.pairwise(side)]
693
+ slots = [k, *range(len(tris), len(tris) + len(fan) - 1)]
694
+ tris.extend(fan[1:])
695
+ tris[k] = fan[0]
696
+ for slot, (p, q, x) in zip(slots, fan, strict=True):
697
+ owner[(p, q)] = owner[(q, x)] = owner[(x, p)] = slot
698
+ points = np.vstack([p2, cand])
699
+ edges = np.column_stack([np.arange(m), (np.arange(m) + 1) % m])
700
+ tri = _constrained_delaunay(points, np.array(tris, dtype=np.int64), edges)
701
+ # lift: barycentric coordinates in the fan triangle (centroid, loop[k], loop[k + 1])
702
+ lifted = np.zeros((len(cand), 3))
703
+ if len(cand):
704
+ a2, b2 = p2, np.roll(p2, -1, axis=0)
705
+ a3, b3 = loop, np.roll(loop, -1, axis=0)
706
+ e1, e2 = a2[None], b2[None]
707
+ x = cand[:, None, :]
708
+ den = e1[..., 0] * e2[..., 1] - e1[..., 1] * e2[..., 0]
709
+ la = (x[..., 0] * e2[..., 1] - x[..., 1] * e2[..., 0]) / den
710
+ lb = (e1[..., 0] * x[..., 1] - e1[..., 1] * x[..., 0]) / den
711
+ k = np.argmax(np.minimum(np.minimum(la, lb), 1.0 - la - lb), axis=1)
712
+ idx = np.arange(len(cand))
713
+ la, lb = la[idx, k], lb[idx, k]
714
+ lifted = c + la[:, None] * (a3[k] - c) + lb[:, None] * (b3[k] - c)
715
+ return lifted, tri
716
+
717
+
718
+ def _seen(xyz: np.ndarray, triangles: np.ndarray, apex: np.ndarray, sign: float) -> bool:
719
+ """Whether the cones from ``apex`` over the triangles all have the orientation
720
+ ``sign`` (the triangles are seen from the same side as the fan of their facet)."""
721
+ p = xyz[triangles]
722
+ vol = np.einsum("ij,ij->i", np.cross(p[:, 1] - p[:, 0], p[:, 2] - p[:, 0]), apex - p[:, 0])
723
+ return bool(np.all(sign * vol > 1e-9 * np.abs(vol).sum()))
724
+
725
+
726
+ def whole_initial_mesh(cx: CellComplex, *, size: float):
727
+ """Tetrahedra of whole periodic cells (cones from their centroids over their
728
+ triangulated facets), with the cell + 1 of each tetrahedron, the triangles bounding
729
+ their union (first ``n_outer`` of them) and those of the grain boundaries. The edges are
730
+ subdivided at the element size; each pair of translated facets bounding the union is
731
+ meshed once (:func:`_mesh_polygon`), the translate taking the same triangles. The
732
+ regularization checked that the fans of the facets from their centres are seen from
733
+ the centroids of the pieces; a triangulation of a warped facet that is not (one of its
734
+ triangles seen from the other side) is replaced by that fan."""
735
+ from morphogen.mesh.polyhedra import torus_classes
736
+
737
+ size_box = cx.upper - cx.lower
738
+ tol = 1e-9 * float(size_box.max())
739
+ pts = _Points(cx.vertices)
740
+ vertices = cx.vertices
741
+ apex = np.array(
742
+ [vertices[np.unique(np.concatenate([cx.facets[f] for f in pf]))].mean(axis=0)
743
+ for pf in cx.piece_facets]
744
+ ) # fmt: skip
745
+ subdivided: dict = {}
746
+ for loop in cx.facets:
747
+ for a, b in zip(loop.tolist(), np.roll(loop, -1).tolist(), strict=True):
748
+ key = (min(a, b), max(a, b))
749
+ if key in subdivided:
750
+ continue
751
+ pa, pb = vertices[key[0]], vertices[key[1]]
752
+ m = int(np.ceil(float(np.linalg.norm(pb - pa)) / size - 1e-9))
753
+ inner = [pa + (pb - pa) * j / m for j in range(1, m)]
754
+ subdivided[key] = list(pts.add(np.array(inner))) if inner else []
755
+
756
+ def full_loop(f: int) -> np.ndarray:
757
+ out = []
758
+ loop = cx.facets[f].tolist()
759
+ for a, b in zip(loop, loop[1:] + loop[:1], strict=True):
760
+ out.append(a)
761
+ inner = subdivided[(min(a, b), max(a, b))]
762
+ out.extend(inner if a < b else inner[::-1])
763
+ return np.array(out, dtype=np.int64)
764
+
765
+ outer = np.flatnonzero(cx.facet_pieces[:, 1] < 0)
766
+ labels, _ = torus_classes(vertices, cx.lower, size_box, 0.1 * tol) # exact translates
767
+ pairs: dict = {}
768
+ for f in outer:
769
+ pairs.setdefault(tuple(sorted(labels[cx.facets[f]].tolist())), []).append(int(f))
770
+ facet_tris: dict = {}
771
+ for group in pairs.values():
772
+ if len(group) != 2:
773
+ raise RuntimeError("polycrystal mesh: a facet bounding the cells has no translate")
774
+ f, g = sorted(group)
775
+ loop_f, loop_g = full_loop(f), full_loop(g)
776
+ xyz = pts.array()
777
+ lifted, tri = _mesh_polygon(xyz[loop_f], size)
778
+ # the translation from f to g, from a vertex and its translate
779
+ v0 = cx.facets[f][0]
780
+ w0 = next(w for w in cx.facets[g] if labels[w] == labels[v0])
781
+ offset = vertices[w0] - vertices[v0]
782
+ dist, near = cKDTree(xyz[loop_g]).query(xyz[loop_f] + offset)
783
+ if dist.max() > tol:
784
+ raise RuntimeError("polycrystal mesh: translated facets differ")
785
+ # the cones over the fan of f (from the centre of its vertices) and over the
786
+ # triangles, from the centroids of the pieces of f and g
787
+ centre = vertices[cx.facets[f]].mean(axis=0)
788
+ m = len(loop_f)
789
+ local = np.vstack([xyz[loop_f], lifted, centre]) # loop, interior points, centre
790
+ fan = np.column_stack([np.full(m, len(local) - 1), np.arange(m), (np.arange(m) + 1) % m])
791
+ ok = True
792
+ for facet, shift in ((f, 0.0), (g, offset)):
793
+ a = apex[cx.facet_pieces[facet, 0]] - shift
794
+ p = local[fan]
795
+ vol = np.einsum("ij,ij->i", np.cross(p[:, 1] - p[:, 0], p[:, 2] - p[:, 0]), a - p[:, 0])
796
+ ok = ok and _seen(local, tri, a, np.sign(vol.sum()))
797
+ if not ok: # the fan of the facet and its translate
798
+ c_f, c_g = pts.add(centre)[0], pts.add(centre + offset)[0]
799
+ facet_tris[f] = _fan(loop_f, c_f)
800
+ facet_tris[g] = _fan(loop_g[near], c_g)[:, ::-1]
801
+ continue
802
+ ids_f = np.concatenate([loop_f, pts.add(lifted) if len(lifted) else []]).astype(np.int64)
803
+ ids_g = np.concatenate(
804
+ [loop_g[near], pts.add(lifted + offset) if len(lifted) else []]
805
+ ).astype(np.int64)
806
+ facet_tris[f] = ids_f[tri]
807
+ facet_tris[g] = ids_g[tri][:, ::-1] # the translate is seen from the other side
808
+ xyz = pts.array()
809
+ for f in range(cx.n_facets):
810
+ if f in facet_tris:
811
+ continue
812
+ loop = full_loop(f)
813
+ centre = -1
814
+ if len(loop) > 3:
815
+ centre = int(pts.add(xyz[cx.facets[f]].mean(axis=0))[0])
816
+ facet_tris[f] = _fan(loop, centre)
817
+ xyz = pts.array()
818
+ tets, refs = [], []
819
+ for p, pf in enumerate(cx.piece_facets):
820
+ members = np.unique(np.concatenate([cx.facets[f] for f in pf]))
821
+ g = int(pts.add(xyz[members].mean(axis=0))[0])
822
+ for f in pf:
823
+ t = facet_tris[int(f)]
824
+ tets.append(np.column_stack([t, np.full(len(t), g)]))
825
+ refs.append(np.full(len(t), cx.piece_cell[p] + 1))
826
+ xyz = pts.array()
827
+ tets = np.concatenate(tets)
828
+ refs = np.concatenate(refs)
829
+ vol = tet_volumes(xyz, tets)
830
+ tets[vol < 0] = tets[vol < 0][:, [0, 2, 1, 3]]
831
+ tri = [facet_tris[int(f)] for f in outer]
832
+ tri_refs = [np.full(len(t), 1) for t in tri]
833
+ n_outer = sum(len(t) for t in tri)
834
+ for f in cx.interface_facets():
835
+ tri.append(facet_tris[int(f)])
836
+ tri_refs.append(np.full(len(facet_tris[int(f)]), REF_GRAIN_BOUNDARY))
837
+ return xyz, tets, refs, np.concatenate(tri), np.concatenate(tri_refs), n_outer
838
+
839
+
840
+ def _ridges(cx: CellComplex) -> np.ndarray:
841
+ """The edges (vertex pairs) of the facets that MMG sees — the faces of the box, the
842
+ boundary of whole cells and the facets between cells — where facets of two different
843
+ planes meet: MMG keeps them as ridges, so that the surfaces stay the planar facets of
844
+ the geometry (its detection by angles would miss the edges of small dihedral angles)."""
845
+ seen = (cx.facet_box > 0) | (cx.facet_pieces[:, 1] < 0)
846
+ seen[cx.interface_facets()] = True
847
+ area, _ = cx.facet_vectors()
848
+ normal = area / np.maximum(np.linalg.norm(area, axis=1, keepdims=True), 1e-300)
849
+ edge_facets: dict = {}
850
+ for f in np.flatnonzero(seen):
851
+ loop = cx.facets[f]
852
+ for a, b in zip(loop, np.roll(loop, -1), strict=True):
853
+ edge_facets.setdefault((min(a, b), max(a, b)), []).append(f)
854
+ out = []
855
+ for edge, faces in edge_facets.items():
856
+ n = normal[faces]
857
+ if len(faces) == 1 or np.any(np.abs(n @ n[0]) < 1.0 - 1e-9):
858
+ out.append(edge)
859
+ return np.asarray(out, dtype=np.int64).reshape(-1, 2)
860
+
861
+
862
+ def polycrystal_mesh(
863
+ micro,
864
+ *,
865
+ size: float,
866
+ min_size: float | None = None,
867
+ hausdorff: float | None = None,
868
+ gradation: float = 2.0,
869
+ min_feature: float | None = None,
870
+ phases: str = "all",
871
+ order: int = 1,
872
+ periodic: bool | None = None,
873
+ cells: str = "whole",
874
+ exact: bool = False,
875
+ executable: str | None = None,
876
+ workdir=None,
877
+ timeout: float | None = None,
878
+ ) -> TetMesh:
879
+ """Conforming tetrahedral mesh of a Voronoi or Laguerre tessellation, one subdomain
880
+ per cell: each element knows its cell (``mesh.cell``), its phase and, through its
881
+ cell, its crystal orientation (``mesh.orientations``).
882
+
883
+ Parameters
884
+ ----------
885
+ size
886
+ Largest element size (``-hmax``).
887
+ min_size, hausdorff, gradation
888
+ Smallest element size (default ``size / 10``), Hausdorff distance (default
889
+ ``size / 20``; ``1e-6 size`` when ``exact``) and size gradation of MMG.
890
+ min_feature
891
+ Features of the tessellation smaller than this length (short edges, caps of
892
+ cells on the faces of the box) are removed before meshing (default
893
+ ``size / 4``, 0 when ``exact``; 0 keeps the exact cells, at the price of flat
894
+ elements next to their small features).
895
+ exact
896
+ Keep the facets of the cells exactly: the edges where they bend given to MMG as
897
+ ridges and their ends as corners, and its Hausdorff distance a millionth of the
898
+ size by default (the facets are planar: nothing to approximate, while its
899
+ smoothing moves the nodes of the surfaces within that distance). Not with a
900
+ positive ``min_feature``: the cells are then regularized, their facets bent.
901
+ phases
902
+ ``"all"``, or ``"solid"``: the cells of phase 1 only.
903
+ periodic
904
+ Periodic mesh (default: when the tessellation is periodic).
905
+ cells
906
+ Periodic meshes: ``"whole"`` (default) meshes the whole cells, periodized at the
907
+ design: their union fills the volume of the box and its boundary is made of
908
+ pairs of translated facets with the same triangles, so that every node of the
909
+ boundary has its translates (``mesh.periodic_links()``); ``"box"`` cuts the cells
910
+ by the faces of the box, meshed alike on opposite faces.
911
+ """
912
+ from morphogen.models.tessellation import Tessellation
913
+
914
+ if not isinstance(micro, Tessellation):
915
+ raise TypeError("polycrystal_mesh: a Voronoi or Laguerre tessellation")
916
+ if phases not in ("all", "solid"):
917
+ raise ValueError("phases: 'all' or 'solid'")
918
+ if order not in (1, 2):
919
+ raise ValueError("order: 1 or 2")
920
+ size = float(size)
921
+ if not size > 0:
922
+ raise ValueError("size: must be positive")
923
+ domain: Domain = micro.domain
924
+ periodic = domain.periodic if periodic is None else bool(periodic)
925
+ if periodic and not domain.periodic:
926
+ raise ValueError("matching periodic faces need a periodic tessellation")
927
+ if cells not in ("whole", "box"):
928
+ raise ValueError("cells: 'whole' or 'box'")
929
+ whole = periodic and cells == "whole"
930
+ hmin = float(min_size) if min_size is not None else size / 10.0
931
+ if min_feature is not None:
932
+ feature = float(min_feature)
933
+ else:
934
+ feature = 0.0 if exact else size / 4.0
935
+ # the facets kept: those of the exact cells (planar: regularized cells have bent ones)
936
+ exact = bool(exact) and feature == 0.0
937
+ if hausdorff is not None:
938
+ hausd = float(hausdorff)
939
+ else:
940
+ hausd = 1e-6 * size if exact else size / 20.0
941
+ exe = mmg_executable(executable)
942
+ t0 = time.perf_counter()
943
+ cx = micro.cell_complex(whole=whole)
944
+ if periodic != cx.periodic:
945
+ raise ValueError("the cells of the tessellation and the mesh differ in periodicity")
946
+ cx = regularize(cx, feature) if feature > 0 else cx
947
+ t_cells = time.perf_counter() - t0
948
+ tol = 1e-9 * float(domain.lengths.max())
949
+ sizing = ["-hmax", f"{size:.10g}", "-hmin", f"{hmin:.10g}", "-hausd", f"{hausd:.10g}"]
950
+ sizing += ["-hgrad", f"{float(gradation):.10g}", "-v", "-1"]
951
+ with tempfile.TemporaryDirectory(dir=workdir) as tmp:
952
+ folder = Path(tmp)
953
+ t1 = time.perf_counter()
954
+ if whole:
955
+ xyz, tets, refs, tri, tri_refs, n_box = whole_initial_mesh(cx, size=size)
956
+ else:
957
+ xyz, tets, refs, tri, tri_refs, n_box = initial_mesh(
958
+ cx, size=size, sizing=sizing, periodic=periodic, folder=folder, timeout=timeout
959
+ )
960
+ t_mmg = time.perf_counter() - t1
961
+ used = np.unique(tets)
962
+ renum = np.full(len(xyz), -1, dtype=np.int64)
963
+ renum[used] = np.arange(len(used))
964
+ required_vertices = None
965
+ if whole: # the vertices of the triangles bounding the cells
966
+ required_vertices = np.unique(renum[tri[:n_box]])
967
+ elif periodic:
968
+ on_face = np.zeros(len(used), dtype=bool)
969
+ for d in range(3):
970
+ on_face |= np.abs(xyz[used, d] - domain.lower[d]) <= tol
971
+ on_face |= np.abs(xyz[used, d] - domain.upper[d]) <= tol
972
+ required_vertices = np.flatnonzero(on_face)
973
+ ridges = corners = None
974
+ if exact: # the bends of the facets as ridges, their ends as corners
975
+ ridges = _ridges(cx)
976
+ ridges = ridges[np.all(renum[ridges] >= 0, axis=1)]
977
+ corners = renum[np.unique(ridges)]
978
+ required_vertices = (
979
+ corners if required_vertices is None else np.union1d(required_vertices, corners)
980
+ )
981
+ if not len(ridges):
982
+ ridges = corners = None
983
+ medit.write_mesh(
984
+ folder / "cells.mesh",
985
+ xyz[used],
986
+ renum[tets],
987
+ renum[tri],
988
+ tet_refs=refs,
989
+ tri_refs=tri_refs,
990
+ required_triangles=np.arange(n_box) if periodic else None,
991
+ required_vertices=required_vertices,
992
+ edges=None if ridges is None else renum[ridges],
993
+ ridges=None if ridges is None else np.arange(len(ridges)),
994
+ corners=corners,
995
+ )
996
+ t1 = time.perf_counter()
997
+ data = _run_mmg(exe, folder / "cells.mesh", None, folder / "out.mesh", sizing, timeout)
998
+ t_mmg += time.perf_counter() - t1
999
+ nodes = data["Vertices"]
1000
+ for d in range(3 if not whole else 0): # nodes of the faces exactly on the faces
1001
+ nodes[np.abs(nodes[:, d] - domain.lower[d]) <= tol, d] = domain.lower[d]
1002
+ nodes[np.abs(nodes[:, d] - domain.upper[d]) <= tol, d] = domain.upper[d]
1003
+ elements = data["Tetrahedra"]
1004
+ cell = data["Tetrahedra_refs"] - 1
1005
+ flip = tet_volumes(nodes, elements) < 0
1006
+ elements[flip] = elements[flip][:, [0, 2, 1, 3]]
1007
+ used, inverse = np.unique(elements, return_inverse=True)
1008
+ mesh = TetMesh(
1009
+ nodes=nodes[used],
1010
+ elements=inverse.reshape(elements.shape),
1011
+ phase=micro.cell_phases[cell].astype(np.int64),
1012
+ lower=domain.lower,
1013
+ upper=domain.upper,
1014
+ periodic=periodic,
1015
+ cell=cell,
1016
+ orientations=micro.orientations,
1017
+ whole=whole,
1018
+ metadata={
1019
+ "mesher": "polycrystal (exact cells, mmg3d)",
1020
+ "cells": "whole" if whole else "box",
1021
+ "size": size,
1022
+ "min_feature": feature,
1023
+ "exact_facets": exact,
1024
+ "flattened_caps": int(cx.metadata.get("flattened_caps", 0)),
1025
+ "relabelled_caps": int(cx.metadata.get("relabelled_caps", 0)),
1026
+ "contracted_edges": int(cx.metadata.get("contracted_edges", 0)),
1027
+ "n_cells": int(micro.n_cells),
1028
+ "phases": phases,
1029
+ "matching_faces": periodic,
1030
+ "time_cells_s": round(t_cells, 3),
1031
+ "time_mmg_s": round(t_mmg, 3),
1032
+ },
1033
+ )
1034
+ if phases == "solid":
1035
+ mesh = mesh.subset([1])
1036
+ if order == 2:
1037
+ mesh = mesh.quadratic()
1038
+ log.info(
1039
+ "polycrystal mesh: %d elements, %d nodes (MMG %.1f s)", mesh.n_elements, mesh.n_nodes, t_mmg
1040
+ )
1041
+ return mesh