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,1168 @@
1
+ """Linear elastic fracture mechanics of 3D cracks: cracks described by two level sets, their
2
+ energy release rate, and their propagation, either on meshes conforming to the crack,
3
+ remeshed at each step as in Z-cracks, or by the extended finite element method (XFEM) on
4
+ a fixed mesh.
5
+
6
+ A crack (:class:`Crack`) is the zero of ``φ``, the signed distance to its plane, where
7
+ ``ψ``, the signed distance to its front within the plane, is negative: a straight front
8
+ (a through or edge crack of length ``size`` from ``point`` along ``direction``) or a circular
9
+ one (a penny of radius ``size``). It grows by moving its front (:meth:`Crack.grown`).
10
+
11
+ *Conforming meshes* (Z-cracks): the body is meshed by MMG conforming to the plane of the
12
+ crack (:func:`crack_mesh`, or any mesh whose faces lie on it, such as six tetrahedra per
13
+ voxel), and the faces behind the front are opened by duplicating their nodes
14
+ (:func:`morphogen.fracture.cohesive.insert_interfaces`): free crack faces.
15
+
16
+ *Morphologies*: the crack meshes of a morphology carry its phases, those of the materials
17
+ (``mesh.phase``), and the sides of the crack apart (``mesh.side``), through the opened
18
+ meshes, the solvers and the transfers of their state: each element in the phase of its
19
+ centroid (:func:`with_phases`: staircase interfaces, as the grains of polycrystals), or the
20
+ interfaces of the phases conforming as well: the background mesh cut by MMG along the
21
+ level set of the morphology without remeshing (:func:`phase_mesh`, once), then along the
22
+ plane of each crack and remeshed in MMG's multi-material mode, each phase split into its two
23
+ sides (:func:`cut_mesh`). The elements of void phases (pores) are removed
24
+ (:func:`without_voids`); the walls of the pores and the interfaces of the phases keep their
25
+ nodes when the front is snapped.
26
+
27
+ *XFEM* (:class:`XFEM`; Moës, Dolbow & Belytschko 1999; Sukumar, Moës, Moran & Belytschko
28
+ 2000): the displacement of linear tetrahedra is enriched, with shifted functions, by the
29
+ jump ``H(φ) - H(φ_i)`` at the nodes of the elements that the crack cuts through, and by
30
+ the branch functions ``√r (sin θ/2, cos θ/2, sin θ/2 sin θ, cos θ/2 sin θ)`` (``r =
31
+ sqrt(φ² + ψ²)``, ``θ = atan2(φ, ψ)``) at the nodes within ``tip_radius`` of the front; the
32
+ enriched elements are integrated on sub-tetrahedra of their two sides, refined near the
33
+ front.
34
+
35
+ *Energy release rate* (:func:`release_rate`): under prescribed forces, the potential
36
+ energy is ``-W/2`` with ``W = fᵀ u``, so that ``G = (W(a + δ) - W(a - δ)) / (2 (A(a + δ) -
37
+ A(a - δ)))``, the areas those of the crack inside the body (the opened faces, or the
38
+ crack surface in the cut elements): the mean of ``G`` along the front, for its uniform
39
+ advance; in mode I, ``K = sqrt(E' G)``.
40
+
41
+ *Quadratic elements* (``order=2`` of :func:`conforming_work`): the opened mesh is made of
42
+ 10-node tetrahedra, and the mid-edge nodes of the edges that leave the front are moved to
43
+ a quarter of their length from it (:func:`quarter_points`; Barsoum 1976, Henshell & Shaw
44
+ 1975): along such an edge the displacement of the isoparametric element is then a
45
+ polynomial of the square root of the distance to the front, the leading term of the
46
+ fields of a crack, which 4-node elements, of constant strain, only approach by their
47
+ refinement. The XFEM, whose enrichment carries that term, keeps its 4-node elements.
48
+
49
+ *Propagation* (:func:`propagate`): the front advances by steps, its rate given by Paris'
50
+ law ``da/dN = C ΔK^m`` (the cycles of each step) or by Griffith (the load factor at which
51
+ ``G`` reaches ``G_c``, ``G`` growing as its square); the mesh is rebuilt at each step
52
+ (conforming) or kept (XFEM).
53
+ """
54
+
55
+ from __future__ import annotations
56
+
57
+ import math
58
+ from collections.abc import Callable
59
+ from dataclasses import dataclass, replace
60
+
61
+ import numpy as np
62
+ import scipy.sparse as sp
63
+ import scipy.sparse.linalg as spla
64
+
65
+ from morphogen.mesh.tetra import TET_EDGES, TET_FACES, TetMesh
66
+ from morphogen.mesh.tetra import tet_volumes as _tet_volumes
67
+
68
+ _Q4 = np.array(
69
+ [
70
+ [0.5854101966249685, 0.1381966011250105, 0.1381966011250105, 0.1381966011250105],
71
+ [0.1381966011250105, 0.5854101966249685, 0.1381966011250105, 0.1381966011250105],
72
+ [0.1381966011250105, 0.1381966011250105, 0.5854101966249685, 0.1381966011250105],
73
+ [0.1381966011250105, 0.1381966011250105, 0.1381966011250105, 0.5854101966249685],
74
+ ]
75
+ )
76
+
77
+
78
+ @dataclass(frozen=True)
79
+ class Crack:
80
+ """A planar crack (see the module): ``kind`` ``"straight"`` (from ``point`` along
81
+ ``direction`` over ``size``) or ``"penny"`` (centre ``point``, radius ``size``), its
82
+ plane through ``point`` normal to ``normal``."""
83
+
84
+ kind: str
85
+ point: tuple
86
+ normal: tuple
87
+ size: float
88
+ direction: tuple | None = None
89
+
90
+ def __post_init__(self) -> None:
91
+ if self.kind not in ("straight", "penny"):
92
+ raise ValueError("Crack: kind 'straight' or 'penny'")
93
+ n = np.asarray(self.normal, dtype=float)
94
+ object.__setattr__(self, "normal", tuple(n / np.linalg.norm(n)))
95
+ object.__setattr__(self, "point", tuple(float(v) for v in self.point))
96
+ if self.kind == "straight":
97
+ if self.direction is None:
98
+ raise ValueError("Crack: the direction of a straight crack")
99
+ d = np.asarray(self.direction, dtype=float)
100
+ d = d - (d @ n) * n / (n @ n)
101
+ object.__setattr__(self, "direction", tuple(d / np.linalg.norm(d)))
102
+ if not self.size > 0:
103
+ raise ValueError("Crack: a positive size")
104
+
105
+ def phi(self, x) -> np.ndarray:
106
+ """Signed distance to the plane of the crack."""
107
+ return (np.asarray(x, dtype=float) - self.point) @ np.asarray(self.normal)
108
+
109
+ def psi(self, x) -> np.ndarray:
110
+ """Signed distance to the front within the plane (negative on the crack)."""
111
+ y = np.asarray(x, dtype=float) - self.point
112
+ if self.kind == "straight":
113
+ return y @ np.asarray(self.direction) - self.size
114
+ n = np.asarray(self.normal)
115
+ inplane = y - np.outer(y @ n, n) if y.ndim == 2 else y - (y @ n) * n
116
+ return np.linalg.norm(inplane, axis=-1) - self.size
117
+
118
+ def grown(self, da: float) -> Crack:
119
+ """The crack whose front has moved by ``da``."""
120
+ return replace(self, size=self.size + float(da))
121
+
122
+ def frame(self, x):
123
+ """At points ``x`` (rows): the distance ``r`` to the front, the axes of the nearest
124
+ point of the front, ``n`` (normal to the crack), ``d`` (in its plane, the direction
125
+ of propagation) and ``t = d × n`` (along the front), and the coordinate ``s`` along
126
+ the front (a length, or the angle of a penny from the axis ``n × x``, ``n × y`` for
127
+ a normal along ``x``)."""
128
+ x = np.atleast_2d(np.asarray(x, dtype=float))
129
+ n = np.broadcast_to(np.asarray(self.normal), x.shape).copy()
130
+ r = np.hypot(self.phi(x), self.psi(x))
131
+ if self.kind == "straight":
132
+ d = np.broadcast_to(np.asarray(self.direction), x.shape).copy()
133
+ t = np.cross(d, n)
134
+ return r, n, d, t, (x - self.point) @ t[0]
135
+ y = x - self.point
136
+ inplane = y - np.outer(y @ n[0], n[0])
137
+ d = inplane / np.maximum(np.linalg.norm(inplane, axis=1, keepdims=True), 1e-300)
138
+ e1 = np.cross(n[0], [1.0, 0.0, 0.0] if abs(n[0, 0]) < 0.9 else [0.0, 1.0, 0.0])
139
+ e1 /= np.linalg.norm(e1)
140
+ e2 = np.cross(n[0], e1)
141
+ return r, n, d, np.cross(d, n), np.arctan2(inplane @ e2, inplane @ e1)
142
+
143
+ def front(self, lower, upper, count: int = 400):
144
+ """Points of the front inside the box ``[lower, upper]`` and the length (or angle)
145
+ of front that each represents."""
146
+ if self.kind == "penny":
147
+ n = np.asarray(self.normal)
148
+ e1 = np.cross(n, [1.0, 0.0, 0.0] if abs(n[0]) < 0.9 else [0.0, 1.0, 0.0])
149
+ e1 /= np.linalg.norm(e1)
150
+ e2 = np.cross(n, e1)
151
+ a = np.linspace(0.0, 2 * np.pi, count, endpoint=False)
152
+ pts = np.asarray(self.point) + self.size * (
153
+ np.outer(np.cos(a), e1) + np.outer(np.sin(a), e2)
154
+ )
155
+ step = np.full(count, 2 * np.pi * self.size / count)
156
+ else:
157
+ d, n = np.asarray(self.direction), np.asarray(self.normal)
158
+ return line_in_box(np.asarray(self.point) + self.size * d, np.cross(d, n), lower, upper,
159
+ count) # fmt: skip
160
+ inside = np.all(
161
+ (pts >= np.asarray(lower) - 1e-9) & (pts <= np.asarray(upper) + 1e-9), axis=1
162
+ )
163
+ return pts[inside], step[inside]
164
+
165
+
166
+ def line_in_box(point, direction, lower, upper, count: int = 400):
167
+ """Points (midpoints of ``count`` equal parts) of the segment of the line through ``point``
168
+ along ``direction`` inside the box ``[lower, upper]``, and the length of each part."""
169
+ p0, t = np.asarray(point, dtype=float), np.asarray(direction, dtype=float)
170
+ lo, hi = np.asarray(lower, dtype=float), np.asarray(upper, dtype=float)
171
+ s_min, s_max = -np.inf, np.inf
172
+ for i in range(3):
173
+ if abs(t[i]) < 1e-12:
174
+ if not lo[i] - 1e-9 <= p0[i] <= hi[i] + 1e-9:
175
+ return np.zeros((0, 3)), np.zeros(0)
176
+ continue
177
+ a, b = sorted(((lo[i] - p0[i]) / t[i], (hi[i] - p0[i]) / t[i]))
178
+ s_min, s_max = max(s_min, a), min(s_max, b)
179
+ if not s_max > s_min:
180
+ return np.zeros((0, 3)), np.zeros(0)
181
+ step = (s_max - s_min) / count
182
+ s = s_min + (np.arange(count) + 0.5) * step
183
+ return p0 + np.outer(s, t), np.full(count, step)
184
+
185
+
186
+ # -- conforming meshes -----------------------------------------------------------------------
187
+
188
+
189
+ class _Plane:
190
+ """A body whose level set is that of the plane of a crack (for MMG)."""
191
+
192
+ def __init__(self, domain, crack: Crack):
193
+ self.domain, self.crack = domain, crack
194
+
195
+ def level_set(self, shape=None, *, voxel_size=None, grid=None):
196
+ from morphogen.image import VoxelImage
197
+
198
+ values = self.crack.phi(grid.center_points()).reshape(grid.shape)
199
+ return VoxelImage(values, spacing=tuple(grid.spacing), origin=tuple(grid.origin))
200
+
201
+
202
+ def crack_mesh(lower, upper, crack: Crack, size: float, grains=None, *, morphology=None,
203
+ voids=(), conforming: bool = False, front_size: float | None = None,
204
+ front_radius: float | None = None, **options) -> TetMesh: # fmt: skip
205
+ """A tetrahedral mesh of the box ``[lower, upper]`` conforming to the plane of the
206
+ crack (MMG; ``options`` those of :func:`morphogen.mesh.conforming.conforming_mesh`):
207
+ the remeshing step of the conforming approach. Its two phases are the sides of the
208
+ crack. ``grains``: a tessellation (a polycrystal) whose cells the elements take
209
+ (:func:`with_grains`).
210
+
211
+ ``morphology``: a microstructure whose phases the elements take (``mesh.phase``, the
212
+ phases of the materials), the sides of the crack kept apart (``mesh.side``): each
213
+ element in the phase of its centroid (:func:`with_phases`: staircase interfaces), or,
214
+ with ``conforming``, a mesh conforming to the interfaces of its phases too, the
215
+ background mesh cut by its level set (:func:`phase_mesh`) cut by the plane of the crack
216
+ and remeshed by MMG (:func:`cut_mesh`; ``options`` among ``background``, ``min_size``,
217
+ ``hausdorff``, ``gradation``, ``executable``, ``workdir``, ``timeout``); ``morphology``
218
+ may be that mesh of its phases, made once for all the cracks of a growth. ``voids``:
219
+ phases whose elements are removed (pores; :func:`without_voids`).
220
+
221
+ ``front_size``: the size of the elements within ``front_radius`` of the front (by
222
+ default four times that size), where the mesh is refined by a second pass of MMG with
223
+ a map of sizes (:func:`refine_front`): the singular fields of a curved front resolved
224
+ without a fine mesh of the whole body."""
225
+ from morphogen.domain import Domain
226
+ from morphogen.mesh.conforming import conforming_mesh
227
+
228
+ lower, upper = np.asarray(lower, dtype=float), np.asarray(upper, dtype=float)
229
+ if morphology is None and len(voids):
230
+ raise ValueError("crack_mesh: voids are phases of a morphology")
231
+ if morphology is not None and (conforming or isinstance(morphology, TetMesh)):
232
+ unknown = set(options) - set(_CUT_OPTIONS) - {"background"}
233
+ if unknown:
234
+ raise TypeError(f"crack_mesh of the phases: unexpected options {sorted(unknown)}")
235
+ common = {k: v for k, v in options.items() if k in ("executable", "workdir", "timeout")}
236
+ phases = morphology
237
+ if not isinstance(phases, TetMesh):
238
+ phases = phase_mesh(morphology, lower, upper, size,
239
+ background=options.get("background"), **common) # fmt: skip
240
+ elif not (np.allclose(phases.lower, lower) and np.allclose(phases.upper, upper)):
241
+ raise ValueError("crack_mesh: the mesh of the phases is not that of the box")
242
+ cut = {k: v for k, v in options.items() if k in _CUT_OPTIONS}
243
+ mesh = without_voids(cut_mesh(phases, crack, size, **cut), voids)
244
+ if front_size is not None:
245
+ mesh = refine_front(mesh, crack, front_size, front_radius, **common)
246
+ mesh = snap_front(mesh, crack)
247
+ else:
248
+ domain = Domain(size=tuple(upper - lower), origin=tuple(lower), periodic=False)
249
+ mesh = conforming_mesh(
250
+ _Plane(domain, crack), size=size, phases="all", periodic=False, **options
251
+ )
252
+ if front_size is not None:
253
+ common = {k: v for k, v in options.items() if k in ("executable", "workdir", "timeout")}
254
+ mesh = refine_front(mesh, crack, front_size, front_radius, **common)
255
+ mesh = snap_front(mesh, crack)
256
+ if morphology is not None:
257
+ mesh = without_voids(with_phases(mesh, morphology, 0.25 * float(size)), voids)
258
+ if grains is not None:
259
+ mesh = with_grains(mesh, grains)
260
+ # its two phases are the sides of the crack, or those of its materials and its sides
261
+ mesh.metadata["crack_sides"] = "phase" if mesh.side is None else "side"
262
+ return mesh
263
+
264
+
265
+ #: The options of :func:`cut_mesh` among those of :func:`crack_mesh`
266
+ _CUT_OPTIONS = ("min_size", "hausdorff", "gradation", "executable", "workdir", "timeout")
267
+
268
+
269
+ def phase_mesh(morphology, lower, upper, size: float, *, background: float | None = None,
270
+ executable=None, workdir=None, timeout=None) -> TetMesh: # fmt: skip
271
+ """The background mesh of the box ``[lower, upper]`` (six tetrahedra per cube of a
272
+ grid of spacing ``background``, by default ``size / 2``) cut by MMG along the zero level
273
+ set of a morphology (two phases: negative in phase 1), without remeshing: a mesh
274
+ conforming to the interfaces of its phases, its elements of any quality, to be cut by
275
+ each crack and remeshed once (:func:`cut_mesh`; :func:`crack_mesh` with
276
+ ``conforming``). The level set is sampled and moved away from zero near the nodes of
277
+ the grid as for :func:`morphogen.mesh.conforming.conforming_mesh`; the plane of a
278
+ crack is then cut on the same grid as by the crack meshes of a homogeneous body."""
279
+ import tempfile
280
+ from pathlib import Path
281
+
282
+ from morphogen.domain import Domain
283
+ from morphogen.io import medit
284
+ from morphogen.mesh.conforming import (
285
+ REF_INSIDE,
286
+ SNAP,
287
+ _Part,
288
+ _run_mmg,
289
+ _snap_level_set,
290
+ background_mesh,
291
+ mmg_executable,
292
+ node_level_set,
293
+ )
294
+
295
+ lower, upper = np.asarray(lower, dtype=float), np.asarray(upper, dtype=float)
296
+ box = Domain(size=tuple(upper - lower), origin=tuple(lower), periodic=False)
297
+ body = _Part(morphology, box)
298
+ spacing = float(background) if background is not None else 0.5 * float(size)
299
+ values, shape = node_level_set(body, spacing)
300
+ values = _snap_level_set(values, SNAP)
301
+ nodes, tets, tri, tri_refs = background_mesh(shape, lower, upper)
302
+ exe = mmg_executable(executable)
303
+ with tempfile.TemporaryDirectory(dir=workdir) as tmp:
304
+ folder = Path(tmp)
305
+ medit.write_mesh(folder / "bg.mesh", nodes, tets, tri, tri_refs=tri_refs)
306
+ medit.write_sol(folder / "bg.sol", values.ravel())
307
+ data = _run_mmg(exe, folder / "bg.mesh", folder / "bg.sol", folder / "cut.mesh",
308
+ ["-ls", "0", "-nosurf", "-noinsert", "-noswap", "-nomove", "-v", "-1"],
309
+ timeout) # fmt: skip
310
+ xyz, elements = data["Vertices"], data["Tetrahedra"]
311
+ tol = 1e-9 * float(np.max(upper - lower))
312
+ for d in range(3): # the nodes of the faces exactly on them
313
+ xyz[:, d] = np.where(np.abs(xyz[:, d] - lower[d]) <= tol, lower[d], xyz[:, d])
314
+ xyz[:, d] = np.where(np.abs(xyz[:, d] - upper[d]) <= tol, upper[d], xyz[:, d])
315
+ flip = _tet_volumes(xyz, elements) < 0
316
+ elements[flip] = elements[flip][:, [0, 2, 1, 3]]
317
+ used, inverse = np.unique(elements, return_inverse=True)
318
+ phase = np.where(data["Tetrahedra_refs"] == REF_INSIDE, 1, 0)
319
+ spacings = [float(v) for v in (upper - lower) / np.array(shape)]
320
+ metadata = {"mesher": "mmg3d -ls, cut without remeshing", "size": float(size),
321
+ "background_spacing": spacings} # fmt: skip
322
+ return TetMesh(xyz[used], inverse.reshape(elements.shape), phase, lower, upper,
323
+ metadata=metadata) # fmt: skip
324
+
325
+
326
+ def cut_mesh(mesh: TetMesh, crack, size: float, *, min_size=None, hausdorff=None,
327
+ gradation: float = 2.0, executable=None, workdir=None,
328
+ timeout=None) -> TetMesh: # fmt: skip
329
+ """The mesh of the phases of a morphology (linear tetrahedra) cut by the plane of a
330
+ crack, ``φ = 0``, and remeshed by MMG in its multi-material mode, each phase split into
331
+ its two sides (the sizes those of :func:`morphogen.mesh.conforming.conforming_mesh`):
332
+ a mesh conforming to the interfaces of the phases and to the crack, its phases in
333
+ ``mesh.phase`` and the sides of the crack in ``mesh.side`` (1 where ``φ < 0``, as the
334
+ phases of :func:`crack_mesh`), the faces of the box kept plane. The values of ``φ``
335
+ at the nodes closer to zero than a fraction of their variation along the edges are
336
+ moved away from it, as on the grids of the conforming meshes (no sliver)."""
337
+ import tempfile
338
+ from pathlib import Path
339
+
340
+ from morphogen.io import medit
341
+ from morphogen.mesh.conforming import SNAP, _run_mmg, mmg_executable
342
+
343
+ if mesh.order != 1:
344
+ raise ValueError("cut_mesh: linear tetrahedra")
345
+ x, tets = mesh.nodes, mesh.elements
346
+ phi = crack.phi(x)
347
+ edges = tets[:, TET_EDGES].reshape(-1, 2)
348
+ jump = np.abs(phi[edges[:, 0]] - phi[edges[:, 1]])
349
+ variation = np.zeros(len(x))
350
+ np.maximum.at(variation, edges[:, 0], jump)
351
+ np.maximum.at(variation, edges[:, 1], jump)
352
+ threshold = SNAP * variation
353
+ near = np.abs(phi) < threshold
354
+ phi = np.where(near, np.where(phi < 0, -threshold, threshold), phi)
355
+ faces = boundary_faces(mesh)
356
+ lower, upper = mesh.lower, mesh.upper
357
+ tol = mesh.tolerance()
358
+ refs = np.full(len(faces), 7, dtype=np.int64) # the walls of pores, if any
359
+ for axis in range(3):
360
+ for side, value in ((0, lower[axis]), (1, upper[axis])):
361
+ on = np.all(np.abs(x[faces][:, :, axis] - value) <= tol, axis=1)
362
+ refs[on] = 1 + 2 * axis + side
363
+ phases = np.unique(mesh.phase)
364
+ # each phase p (reference 1 + p) split into 101 + 2p where φ < 0 and 100 + 2p elsewhere
365
+ split = "".join(f"{1 + p} {101 + 2 * p} {100 + 2 * p}\n" for p in phases.tolist())
366
+ sizing = ["-hmax", f"{size:.10g}",
367
+ "-hmin", f"{(min_size if min_size is not None else size / 10):.10g}",
368
+ "-hausd", f"{(hausdorff if hausdorff is not None else size / 20):.10g}",
369
+ "-hgrad", f"{float(gradation):.10g}", "-v", "-1"] # fmt: skip
370
+ exe = mmg_executable(executable)
371
+ with tempfile.TemporaryDirectory(dir=workdir) as tmp:
372
+ folder = Path(tmp)
373
+ medit.write_mesh(folder / "cut.mesh", x, tets, faces, tet_refs=1 + mesh.phase,
374
+ tri_refs=refs) # fmt: skip
375
+ medit.write_sol(folder / "cut.sol", phi)
376
+ (folder / "cut.mmg3d").write_text(f"LSReferences\n{len(phases)}\n{split}")
377
+ data = _run_mmg(exe, folder / "cut.mesh", folder / "cut.sol", folder / "out.mesh",
378
+ ["-ls", "0", *sizing], timeout) # fmt: skip
379
+ xyz = data["Vertices"]
380
+ for d in range(3): # the nodes of the faces exactly on them
381
+ xyz[:, d] = np.where(np.abs(xyz[:, d] - lower[d]) <= tol, lower[d], xyz[:, d])
382
+ xyz[:, d] = np.where(np.abs(xyz[:, d] - upper[d]) <= tol, upper[d], xyz[:, d])
383
+ elements, labels = data["Tetrahedra"], data["Tetrahedra_refs"] - 100
384
+ if np.any(labels < 0):
385
+ raise RuntimeError("cut_mesh: MMG left elements of no phase")
386
+ flip = _tet_volumes(xyz, elements) < 0
387
+ elements[flip] = elements[flip][:, [0, 2, 1, 3]]
388
+ used, inverse = np.unique(elements, return_inverse=True)
389
+ metadata = {**mesh.metadata, "mesher": "mmg3d -ls, multi-material", "size": float(size)}
390
+ return TetMesh(xyz[used], inverse.reshape(elements.shape), labels // 2, lower, upper,
391
+ metadata=metadata, side=labels % 2) # fmt: skip
392
+
393
+
394
+ def phases_at(morphology, points, spacing: float | None = None) -> np.ndarray:
395
+ """The phase of a morphology at points (rows): its point queries (two phases), or the
396
+ voxel of an image of it whose voxels are about ``spacing`` (at most 256 per edge; by
397
+ default 1/128 of its longest edge); ``morphology`` may also be a function giving the
398
+ phases of points."""
399
+ points = np.atleast_2d(np.asarray(points, dtype=float))
400
+ if callable(morphology) and not hasattr(morphology, "domain"):
401
+ return np.asarray(morphology(points), dtype=np.int64)
402
+ names = getattr(morphology, "phase_names", None) or {0: "0", 1: "1"}
403
+ if set(names) <= {0, 1}:
404
+ try:
405
+ return np.asarray(morphology.contains(points), dtype=bool).astype(np.int64)
406
+ except NotImplementedError:
407
+ pass
408
+ lengths = np.asarray(morphology.domain.lengths, dtype=float)
409
+ spacing = float(lengths.max()) / 128.0 if spacing is None else float(spacing)
410
+ image = morphology.voxelize(voxel_size=max(spacing, float(lengths.max()) / 256.0))
411
+ data = np.asarray(image.data)
412
+ if data.dtype.kind not in "iub":
413
+ raise ValueError("phases_at: the morphology gives no phase image")
414
+ steps = np.asarray(image.spacing, dtype=float)
415
+ index = np.floor((points - np.asarray(image.origin, dtype=float)) / steps).astype(np.int64)
416
+ index = np.clip(index, 0, np.asarray(data.shape) - 1)
417
+ return data[index[:, 0], index[:, 1], index[:, 2]].astype(np.int64)
418
+
419
+
420
+ def with_phases(mesh: TetMesh, morphology, spacing: float | None = None) -> TetMesh:
421
+ """A crack mesh (its phases the sides of the crack) with the phases of a morphology:
422
+ each element in the phase of the morphology at its centroid (``mesh.phase``, by
423
+ :func:`phases_at`), the sides of the crack kept in ``mesh.side``. The interfaces of
424
+ the phases are then staircases of element faces, as the grain boundaries of
425
+ :func:`with_grains`."""
426
+ centroids = mesh.nodes[mesh.elements[:, :4]].mean(axis=1)
427
+ side = mesh.phase if mesh.side is None else mesh.side
428
+ return TetMesh(mesh.nodes, mesh.elements, phases_at(morphology, centroids, spacing),
429
+ mesh.lower, mesh.upper, periodic=mesh.periodic, metadata=dict(mesh.metadata),
430
+ cell=mesh.cell, orientations=mesh.orientations, side=side) # fmt: skip
431
+
432
+
433
+ def without_voids(mesh: TetMesh, voids=(), islands: float = 0.01) -> TetMesh:
434
+ """A mesh without the elements of the phases ``voids`` (pores), and without the parts
435
+ of it they leave apart whose volume is below ``islands`` times that of the largest
436
+ (more than one large part: an error, a body that falls apart)."""
437
+ voids = [int(p) for p in voids]
438
+ if not voids or not np.isin(mesh.phase, voids).any():
439
+ return mesh
440
+ out = mesh.select(~np.isin(mesh.phase, voids))
441
+ if not out.n_elements:
442
+ raise ValueError("void phases: no element left")
443
+ labels, count = out.components()
444
+ if count > 1:
445
+ volumes = np.bincount(labels, np.abs(out.volumes()), minlength=count)
446
+ large = np.flatnonzero(volumes >= islands * volumes.max())
447
+ if len(large) > 1:
448
+ raise ValueError(f"void phases {voids}: the body left falls apart into "
449
+ f"{len(large)} parts") # fmt: skip
450
+ out = out.select(labels == large[0])
451
+ return out
452
+
453
+
454
+ def with_grains(mesh: TetMesh, grains) -> TetMesh:
455
+ """The mesh with the grains of a tessellation (``grains``: its ``cell_of(points)`` and
456
+ its ``orientations``): each element in the cell of its centroid (``mesh.cell``), the
457
+ crystal orientations of the cells (``mesh.orientations``). The grain boundaries are
458
+ then staircases of element faces, whose steps shrink with the elements; the crack
459
+ meshes of a polycrystal stay conforming to the crack alone (MMG cuts one level set)."""
460
+ centroids = mesh.nodes[mesh.elements[:, :4]].mean(axis=1)
461
+ cell = np.asarray(grains.cell_of(centroids), dtype=np.int64)
462
+ return TetMesh(mesh.nodes, mesh.elements, mesh.phase, mesh.lower, mesh.upper,
463
+ periodic=mesh.periodic, metadata=dict(mesh.metadata), cell=cell,
464
+ orientations=getattr(grains, "orientations", None),
465
+ side=mesh.side) # fmt: skip
466
+
467
+
468
+ def interface_nodes(mesh: TetMesh) -> np.ndarray:
469
+ """The nodes (a mask) of the interfaces between the phases of a mesh and of its free
470
+ faces off the faces of its box (the walls of its pores)."""
471
+ tets = mesh.elements[:, :4]
472
+ held = np.zeros(mesh.n_nodes, dtype=bool)
473
+ phases = np.unique(mesh.phase)
474
+ if len(phases) > 1:
475
+ count = np.zeros(mesh.n_nodes, dtype=np.int64)
476
+ for p in phases:
477
+ touched = np.zeros(mesh.n_nodes, dtype=bool)
478
+ touched[tets[mesh.phase == p].ravel()] = True
479
+ count += touched
480
+ held |= count > 1
481
+ free = boundary_faces(mesh)
482
+ x, tol = mesh.nodes[free], mesh.tolerance()
483
+ on_box = np.zeros(len(free), dtype=bool)
484
+ for axis in range(3):
485
+ for value in (mesh.lower[axis], mesh.upper[axis]):
486
+ on_box |= np.all(np.abs(x[:, :, axis] - value) <= tol, axis=1)
487
+ held[free[~on_box].ravel()] = True
488
+ return held
489
+
490
+
491
+ def refine_front(mesh: TetMesh, crack, size: float, radius: float | None = None, *,
492
+ gradation: float = 1.5, executable=None, workdir=None,
493
+ timeout=None) -> TetMesh: # fmt: skip
494
+ """A crack mesh (linear tetrahedra; its phases, or its phases and its sides) remeshed
495
+ by MMG with elements of ``size`` within ``radius`` of the front of the crack (by
496
+ default four times that size), growing beyond it by the ratio ``gradation`` between
497
+ neighbours up to the sizes of the mesh: the surfaces between its labels (the surface
498
+ of the crack, the interfaces of the phases, the walls of the pores) and the faces of
499
+ the box are kept."""
500
+ import tempfile
501
+ from pathlib import Path
502
+
503
+ from morphogen.io import medit
504
+ from morphogen.mesh.conforming import _run_mmg, mmg_executable
505
+
506
+ if mesh.order != 1:
507
+ raise ValueError("refine_front: linear tetrahedra")
508
+ size = float(size)
509
+ radius = 4.0 * size if radius is None else float(radius)
510
+ if not (size > 0 and radius > 0):
511
+ raise ValueError("refine_front: a positive size and radius")
512
+ x, tets = mesh.nodes, mesh.elements
513
+ edges = tets[:, TET_EDGES].reshape(-1, 2)
514
+ lengths = np.linalg.norm(x[edges[:, 0]] - x[edges[:, 1]], axis=1)
515
+ counts = np.maximum(np.bincount(edges.ravel(), minlength=len(x)), 1)
516
+ local = np.bincount(edges.ravel(), np.repeat(lengths, 2), minlength=len(x)) / counts
517
+ r = crack.frame(x)[0]
518
+ # the size of the front within the radius, then that of the mesh (MMG grades between)
519
+ wanted = np.where(r <= radius, np.minimum(size, local), local)
520
+ faces = boundary_faces(mesh)
521
+ lower, upper = mesh.lower, mesh.upper
522
+ tol = mesh.tolerance()
523
+ refs = np.full(len(faces), 7, dtype=np.int64) # the walls of pores, if any
524
+ for axis in range(3):
525
+ for side, value in ((0, lower[axis]), (1, upper[axis])):
526
+ on = np.all(np.abs(x[faces][:, :, axis] - value) <= tol, axis=1)
527
+ refs[on] = 1 + 2 * axis + side
528
+ labels = mesh.phase if mesh.side is None else 2 * mesh.phase + mesh.side
529
+ exe = mmg_executable(executable)
530
+ with tempfile.TemporaryDirectory(dir=workdir) as tmp:
531
+ folder = Path(tmp)
532
+ medit.write_mesh(folder / "front.mesh", x, tets, faces, tet_refs=1 + labels,
533
+ tri_refs=refs) # fmt: skip
534
+ medit.write_sol(folder / "front.sol", wanted)
535
+ args = ["-hgrad", f"{float(gradation):.10g}", "-hausd", f"{0.05 * size:.10g}", "-v", "-1"]
536
+ data = _run_mmg(exe, folder / "front.mesh", folder / "front.sol", folder / "out.mesh",
537
+ args, timeout) # fmt: skip
538
+ xyz = data["Vertices"]
539
+ for d in range(3): # the nodes of the faces exactly on them
540
+ xyz[:, d] = np.where(np.abs(xyz[:, d] - lower[d]) <= tol, lower[d], xyz[:, d])
541
+ xyz[:, d] = np.where(np.abs(xyz[:, d] - upper[d]) <= tol, upper[d], xyz[:, d])
542
+ elements, found = data["Tetrahedra"], data["Tetrahedra_refs"] - 1
543
+ flip = _tet_volumes(xyz, elements) < 0
544
+ elements[flip] = elements[flip][:, [0, 2, 1, 3]]
545
+ used, inverse = np.unique(elements, return_inverse=True)
546
+ metadata = {**mesh.metadata, "front_size": size, "front_radius": radius}
547
+ if mesh.side is None:
548
+ phase, side = found, None
549
+ else:
550
+ phase, side = found // 2, found % 2
551
+ return TetMesh(xyz[used], inverse.reshape(elements.shape), phase, lower, upper,
552
+ periodic=mesh.periodic, metadata=metadata, side=side) # fmt: skip
553
+
554
+
555
+ def snap_front(mesh: TetMesh, crack, fraction: float = 0.5, quality: float = 0.2) -> TetMesh:
556
+ """The mesh with the nodes of the crack surface (between its two phases, the sides of
557
+ the crack, or its two sides ``mesh.side``) within ``fraction`` of the length of their
558
+ edges from the front moved onto it, in the surface: the opened faces then end on the
559
+ front, instead of a zigzag that lengthens or shortens the crack locally by a fraction
560
+ of an element (the remeshing of Z-cracks, whose meshes have the front along their
561
+ edges). A node stays if the move would leave an element around it below ``quality``
562
+ times its volume, a triangle of the surface below that fraction of its area, or a node
563
+ of a face of the box off it; and, with its sides apart from its phases, the nodes of
564
+ the interfaces of the phases and of the walls of the pores (:func:`interface_nodes`)."""
565
+ labels = mesh.phase if mesh.side is None else mesh.side
566
+ phases = np.unique(labels)
567
+ if len(phases) != 2:
568
+ return mesh
569
+ x = mesh.nodes.copy()
570
+ tets = mesh.elements[:, :4]
571
+ sides = [np.zeros(len(x), dtype=bool) for _ in phases]
572
+ for side, p in zip(sides, phases, strict=True):
573
+ side[tets[labels == p].ravel()] = True
574
+ surface = sides[0] & sides[1]
575
+ if mesh.side is not None:
576
+ surface &= ~interface_nodes(mesh)
577
+ edges = tets[:, [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]].reshape(-1, 2)
578
+ lengths = np.linalg.norm(x[edges[:, 0]] - x[edges[:, 1]], axis=1)
579
+ counts = np.maximum(np.bincount(edges.ravel(), minlength=len(x)), 1)
580
+ size = np.bincount(edges.ravel(), np.repeat(lengths, 2), minlength=len(x)) / counts
581
+ psi = crack.psi(x)
582
+ candidates = np.flatnonzero(surface & (np.abs(psi) < fraction * size) & (psi != 0))
583
+ if not len(candidates):
584
+ return mesh
585
+ directions = crack.frame(x[candidates])[2]
586
+ per_node = np.bincount(tets.ravel(), minlength=len(x))
587
+ start = np.concatenate([[0], np.cumsum(per_node)])
588
+ owners = np.argsort(tets.ravel(), kind="stable") // 4
589
+ span = float(np.max(mesh.upper - mesh.lower))
590
+ faces_of = np.asarray(TET_FACES)
591
+ moved = 0
592
+ for k in np.argsort(np.abs(psi[candidates])):
593
+ v = candidates[k]
594
+ old = x[v].copy()
595
+ new = old - psi[v] * directions[k]
596
+ boxed = (np.abs(old - mesh.lower) < 1e-9 * span) | (np.abs(old - mesh.upper) < 1e-9 * span)
597
+ if np.any(boxed & (np.abs(new - old) > 1e-12 * span)):
598
+ continue
599
+ star = tets[owners[start[v] : start[v + 1]]]
600
+ faces = star[:, faces_of].reshape(-1, 3)
601
+ faces = faces[np.any(faces == v, axis=1) & np.all(surface[faces], axis=1)]
602
+
603
+ def shape(points, star=star, faces=faces):
604
+ p = points[faces]
605
+ return _tet_volumes(points, star), np.cross(p[:, 1] - p[:, 0], p[:, 2] - p[:, 0])
606
+
607
+ volumes, normals = shape(x)
608
+ x[v] = new
609
+ moved_volumes, moved_normals = shape(x)
610
+ kept = np.einsum("ij,ij->i", moved_normals, normals) > quality * np.einsum(
611
+ "ij,ij->i", normals, normals
612
+ )
613
+ if np.all(moved_volumes / volumes > quality) and np.all(kept):
614
+ moved += 1
615
+ else:
616
+ x[v] = old
617
+ out = TetMesh(x, mesh.elements, mesh.phase, mesh.lower, mesh.upper, periodic=mesh.periodic,
618
+ metadata=dict(mesh.metadata), cell=mesh.cell,
619
+ orientations=mesh.orientations, side=mesh.side) # fmt: skip
620
+ out.metadata["front_nodes_moved"] = moved
621
+ return out
622
+
623
+
624
+ def open_crack(mesh: TetMesh, crack: Crack, sides=None):
625
+ """The mesh with the crack opened and the area of the crack (see :func:`crack_faces`)."""
626
+ opened, faces = crack_faces(mesh, crack, sides)
627
+ return opened, float(faces.areas(opened).sum())
628
+
629
+
630
+ def crack_faces(mesh: TetMesh, crack, sides=None):
631
+ """The mesh with the faces of the crack opened, those between its two sides behind its
632
+ front, and the pairs of faces of its lips (interface elements). ``sides``: a label per
633
+ element (by default the sides ``mesh.side`` of a crack mesh of a morphology, or the two
634
+ phases of a mesh from :func:`crack_mesh`, whose interface MMG may have moved slightly,
635
+ otherwise the sign of ``φ`` at the centroids of the elements)."""
636
+ from morphogen.fracture.cohesive import insert_interfaces
637
+
638
+ if sides is None:
639
+ if mesh.side is not None:
640
+ sides = mesh.side
641
+ elif mesh.metadata.get("crack_sides") == "phase":
642
+ sides = mesh.phase
643
+ else:
644
+ sides = crack.phi(mesh.nodes[mesh.elements].mean(axis=1)) > 0
645
+ return insert_interfaces(mesh, lambda c: crack.psi(c) < 0.0, sides=sides)
646
+
647
+
648
+ def boundary_faces(mesh: TetMesh) -> np.ndarray:
649
+ """The faces of a tetrahedral mesh that belong to one element (rows of three nodes)."""
650
+ faces = mesh.elements[:, np.asarray(TET_FACES)].reshape(-1, 3)
651
+ keys = np.sort(faces, axis=1)
652
+ _, first, counts = np.unique(keys, axis=0, return_index=True, return_counts=True)
653
+ return faces[first[counts == 1]]
654
+
655
+
656
+ def face_forces(mesh: TetMesh, where: Callable, traction) -> np.ndarray:
657
+ """Nodal forces (3 n) of a uniform ``traction`` on the boundary faces whose centroids
658
+ (those of their corners) satisfy ``where``: a third of the force of each face to each
659
+ of its nodes for 4-node elements; for 10-node ones the consistent forces of the six
660
+ nodes of the face, ``∫ N_a dA`` (a third to each mid-edge node of a plane face with
661
+ straight edges, nothing to its corners)."""
662
+ traction = np.asarray(traction, dtype=float)
663
+ f = np.zeros((mesh.n_nodes, 3))
664
+ if mesh.order == 1:
665
+ faces = boundary_faces(mesh)
666
+ x = mesh.nodes[faces]
667
+ keep = np.asarray(where(x.mean(axis=1)), dtype=bool)
668
+ areas = 0.5 * np.linalg.norm(
669
+ np.cross(x[keep, 1] - x[keep, 0], x[keep, 2] - x[keep, 0]), axis=1
670
+ )
671
+ for k in range(3):
672
+ np.add.at(f, faces[keep, k], np.outer(areas / 3.0, traction))
673
+ return f.ravel()
674
+ from morphogen.fracture.cohesive import _GAUSS6, _shape6
675
+
676
+ faces = _boundary_faces6(mesh)
677
+ x = mesh.nodes[faces]
678
+ keep = np.asarray(where(x[:, :3].mean(axis=1)), dtype=bool)
679
+ faces, x = faces[keep], x[keep]
680
+ shape, dxi, deta = np.empty(6), np.empty(6), np.empty(6)
681
+ for xi, eta, weight in _GAUSS6:
682
+ _shape6(xi, eta, shape, dxi, deta)
683
+ a = np.einsum("i,eic->ec", dxi, x)
684
+ b = np.einsum("i,eic->ec", deta, x)
685
+ area = 0.5 * weight * np.linalg.norm(np.cross(a, b), axis=1)
686
+ for k in range(6):
687
+ np.add.at(f, faces[:, k], np.outer(area * shape[k], traction))
688
+ return f.ravel()
689
+
690
+
691
+ def _boundary_faces6(mesh: TetMesh) -> np.ndarray:
692
+ """The faces of a mesh of 10-node tetrahedra that belong to one element: their
693
+ corners, then the mid-edge nodes of their edges 0-1, 1-2 and 2-0."""
694
+ corners = mesh.elements[:, np.asarray(TET_FACES)].reshape(-1, 3)
695
+ keys = np.sort(corners, axis=1)
696
+ _, first, counts = np.unique(keys, axis=0, return_index=True, return_counts=True)
697
+ first = first[counts == 1]
698
+ element, face = first // 4, first % 4
699
+ # the mid-edge node of each pair of corners of an element
700
+ local = {(int(i), int(j)): 4 + k for k, (i, j) in enumerate(np.asarray(TET_EDGES))}
701
+ local.update({(j, i): k for (i, j), k in list(local.items())})
702
+ mids = np.empty((len(first), 3), dtype=np.int64)
703
+ for f in range(4):
704
+ at = face == f
705
+ c = np.asarray(TET_FACES)[f]
706
+ for k, (i, j) in enumerate(((0, 1), (1, 2), (2, 0))):
707
+ mids[at, k] = mesh.elements[element[at], local[(int(c[i]), int(c[j]))]]
708
+ return np.concatenate([corners[first], mids], axis=1)
709
+
710
+
711
+ def quarter_points(mesh: TetMesh, front) -> TetMesh:
712
+ """The mesh of 10-node tetrahedra whose mid-edge nodes on the edges that leave the
713
+ nodes ``front`` (those of a crack front: one end on it, the other not) are moved to a
714
+ quarter of the edge from the front (Barsoum 1976): the displacements of these
715
+ elements vary as the square root of the distance to the front along these edges, and
716
+ their strains as its inverse, as the fields of a crack. The edges along the front and
717
+ the others keep their mid-edge nodes."""
718
+ if mesh.order != 2:
719
+ raise ValueError("quarter_points: 10-node tetrahedra (mesh.quadratic())")
720
+ on = np.zeros(mesh.n_nodes, dtype=bool)
721
+ on[np.asarray(front, dtype=np.int64)] = True
722
+ ends = mesh.elements[:, np.asarray(TET_EDGES)] # (elements, 6, 2)
723
+ mids = mesh.elements[:, 4:]
724
+ a, b = ends[..., 0], ends[..., 1]
725
+ nodes = mesh.nodes.copy()
726
+ for tip, other in ((a, b), (b, a)):
727
+ leave = on[tip] & ~on[other]
728
+ nodes[mids[leave]] = 0.75 * mesh.nodes[tip[leave]] + 0.25 * mesh.nodes[other[leave]]
729
+ return mesh._derived(nodes, mesh.elements)
730
+
731
+
732
+ def _isotropic(young: float, poisson: float) -> np.ndarray:
733
+ lam = young * poisson / ((1 + poisson) * (1 - 2 * poisson))
734
+ mu = young / (2 * (1 + poisson))
735
+ d = np.zeros((6, 6))
736
+ d[:3, :3] = lam
737
+ d[np.arange(3), np.arange(3)] += 2 * mu
738
+ d[np.arange(3, 6), np.arange(3, 6)] = mu
739
+ return d
740
+
741
+
742
+ def _solve(k: sp.spmatrix, f: np.ndarray, fixed: np.ndarray) -> np.ndarray:
743
+ n = k.shape[0]
744
+ free = np.setdiff1d(np.arange(n), fixed)
745
+ u = np.zeros(n)
746
+ u[free] = spla.spsolve(k[free][:, free].tocsc(), f[free])
747
+ return u
748
+
749
+
750
+ def conforming_work(
751
+ mesh: TetMesh,
752
+ material,
753
+ crack: Crack,
754
+ forces,
755
+ supports,
756
+ *,
757
+ order: int = 1,
758
+ quarter_point: bool = True,
759
+ ) -> tuple[float, float]:
760
+ """``W = fᵀ u`` of the body with the crack opened on its (conforming) mesh, and the
761
+ area of the crack: ``forces(mesh)`` the nodal forces and ``supports(mesh)`` the fixed
762
+ dofs (functions of the opened mesh). ``order`` 2: on the 10-node tetrahedra of the
763
+ mesh, those of the front with their mid-edge nodes at the quarter of their edges
764
+ (``quarter_point``; see :func:`quarter_points`)."""
765
+ from morphogen.homogenization.fe import assemble
766
+
767
+ if order not in (1, 2):
768
+ raise ValueError("conforming_work: order 1 or 2")
769
+ if order == 1:
770
+ opened, area = open_crack(mesh.linear(), crack)
771
+ else:
772
+ opened, faces = crack_faces(mesh.quadratic(), crack)
773
+ area = float(faces.areas(opened).sum())
774
+ if quarter_point: # the nodes that the two lips share: the front
775
+ front = np.intersect1d(faces.minus[:, :3], faces.plus[:, :3])
776
+ opened = quarter_points(opened, front)
777
+ d = _isotropic(material.young, material.poisson)
778
+ k = assemble(opened, 3, np.zeros(opened.n_elements, dtype=np.int64), d[None]).tocsr()
779
+ f = forces(opened)
780
+ u = _solve(k, f, np.asarray(supports(opened), dtype=np.int64))
781
+ return float(f @ u), area
782
+
783
+
784
+ # -- XFEM ----------------------------------------------------------------------------------
785
+
786
+
787
+ def _split(x: np.ndarray, phi: np.ndarray):
788
+ """Sub-tetrahedra of a tetrahedron cut by the plane ``φ = 0`` (linear ``φ``): rows of
789
+ four vertices, and the side (+1, -1) of each."""
790
+ pos = phi > 0
791
+ if pos.all() or (~pos).all():
792
+ return [x], [1.0 if pos.all() else -1.0]
793
+
794
+ def cut(i, j):
795
+ return x[i] + phi[i] / (phi[i] - phi[j]) * (x[j] - x[i])
796
+
797
+ def prism(a, b, c, pa, pb, pc): # triangles (a, b, c) and (pa, pb, pc) facing each other
798
+ return [np.array([a, b, c, pa]), np.array([b, c, pa, pb]), np.array([c, pa, pb, pc])]
799
+
800
+ ip = np.flatnonzero(pos)
801
+ im = np.flatnonzero(~pos)
802
+ if len(ip) in (1, 3):
803
+ lone, others = (ip[0], im) if len(ip) == 1 else (im[0], ip)
804
+ side_lone = 1.0 if len(ip) == 1 else -1.0
805
+ p = [cut(lone, o) for o in others]
806
+ tets = [np.array([x[lone], p[0], p[1], p[2]])]
807
+ sides = [side_lone]
808
+ rest = prism(x[others[0]], x[others[1]], x[others[2]], p[0], p[1], p[2])
809
+ return tets + rest, sides + [-side_lone] * 3
810
+ a, b = ip
811
+ c, d = im
812
+ pac, pad, pbc, pbd = cut(a, c), cut(a, d), cut(b, c), cut(b, d)
813
+ plus = prism(x[a], pac, pad, x[b], pbc, pbd)
814
+ minus = prism(x[c], pac, pbc, x[d], pad, pbd)
815
+ return plus + minus, [1.0] * 3 + [-1.0] * 3
816
+
817
+
818
+ def _refine(tet: np.ndarray) -> list:
819
+ """Eight sub-tetrahedra by the midpoints of the edges."""
820
+ a, b, c, d = tet
821
+ ab, ac, ad, bc, bd, cd = (
822
+ (a + b) / 2,
823
+ (a + c) / 2,
824
+ (a + d) / 2,
825
+ (b + c) / 2,
826
+ (b + d) / 2,
827
+ (c + d) / 2,
828
+ )
829
+ return [
830
+ np.array(t)
831
+ for t in (
832
+ [a, ab, ac, ad],
833
+ [ab, b, bc, bd],
834
+ [ac, bc, c, cd],
835
+ [ad, bd, cd, d],
836
+ [ab, ac, ad, bd],
837
+ [ab, ac, bc, bd],
838
+ [ac, ad, bd, cd],
839
+ [ac, bc, bd, cd],
840
+ )
841
+ ]
842
+
843
+
844
+ def _branch(phi, psi, gphi, gpsi):
845
+ """The four branch functions and their gradients (rows) at points of level sets
846
+ ``phi``, ``psi`` (gradients ``gphi``, ``gpsi``)."""
847
+ r = np.sqrt(phi**2 + psi**2)
848
+ r = np.maximum(r, 1e-14)
849
+ th = np.arctan2(phi, psi)
850
+ sr = np.sqrt(r)
851
+ s2, c2, s, c = np.sin(th / 2), np.cos(th / 2), np.sin(th), np.cos(th)
852
+ f = np.stack([sr * s2, sr * c2, sr * s2 * s, sr * c2 * s], axis=-1)
853
+ dfr = np.stack([s2 / (2 * sr), c2 / (2 * sr), s2 * s / (2 * sr), c2 * s / (2 * sr)], axis=-1)
854
+ dft = np.stack(
855
+ [sr * c2 / 2, -sr * s2 / 2, sr * (c2 / 2 * s + s2 * c), sr * (-s2 / 2 * s + c2 * c)],
856
+ axis=-1,
857
+ )
858
+ dr = (phi[:, None] * gphi + psi[:, None] * gpsi) / r[:, None]
859
+ dt = (psi[:, None] * gphi - phi[:, None] * gpsi) / r[:, None] ** 2
860
+ grad = dfr[:, :, None] * dr[:, None, :] + dft[:, :, None] * dt[:, None, :]
861
+ return f, grad
862
+
863
+
864
+ def _b_rows(c: int, g: np.ndarray) -> np.ndarray:
865
+ """Voigt strains (11, 22, 33, 23, 31, 12; engineering shears) of the displacement
866
+ component ``c`` with the gradients ``g`` (points x 3): points x 6."""
867
+ out = np.zeros((len(g), 6))
868
+ out[:, c] = g[:, c]
869
+ pairs = {3: (1, 2), 4: (2, 0), 5: (0, 1)}
870
+ for row, (i, j) in pairs.items():
871
+ if c == i:
872
+ out[:, row] += g[:, j]
873
+ if c == j:
874
+ out[:, row] += g[:, i]
875
+ return out
876
+
877
+
878
+ class XFEM:
879
+ """A cracked body by the extended finite element method (see the module): a linear
880
+ tetrahedral ``mesh`` of an isotropic ``material``, the ``crack``, the radius
881
+ ``tip_radius`` within which the nodes get the branch functions (by default twice the
882
+ mean edge) and the number of refinements of the sub-tetrahedra of the elements near the
883
+ front (``refine``)."""
884
+
885
+ def __init__(self, mesh: TetMesh, material, crack: Crack, *, tip_radius=None, refine: int = 0):
886
+ from morphogen.fracture.cohesive import _tet_gradients
887
+
888
+ if mesh.order != 1:
889
+ raise ValueError("XFEM: linear tetrahedra")
890
+ self.mesh, self.crack = mesh, crack
891
+ self.d = _isotropic(material.young, material.poisson)
892
+ x, elems = mesh.nodes, mesh.elements
893
+ self.grads, self.volumes = _tet_gradients(x, elems)
894
+ h = float(np.mean(np.linalg.norm(x[elems[:, 1]] - x[elems[:, 0]], axis=1)))
895
+ self.tip_radius = 2.0 * h if tip_radius is None else float(tip_radius)
896
+ self.refine = int(refine)
897
+ phi = crack.phi(x)
898
+ phi = np.where(np.abs(phi) < 1e-9 * h, 1e-9 * h, phi) # no node on the plane
899
+ psi = crack.psi(x)
900
+ self.phi, self.psi = phi, psi
901
+ pe, se = phi[elems], psi[elems]
902
+ cut = (pe.min(axis=1) < 0) & (pe.max(axis=1) > 0)
903
+ near = np.sqrt(phi**2 + psi**2) < self.tip_radius
904
+ tip_elements = cut & (se.min(axis=1) <= 0) & (se.max(axis=1) >= 0)
905
+ tip = np.zeros(mesh.n_nodes, dtype=bool)
906
+ tip[np.unique(elems[tip_elements])] = True
907
+ tip |= near
908
+ split = cut & (se.max(axis=1) < 0)
909
+ jump = np.zeros(mesh.n_nodes, dtype=bool)
910
+ jump[np.unique(elems[split])] = True
911
+ jump &= ~tip
912
+ self.jump, self.tip = jump, tip
913
+ offset = np.full(mesh.n_nodes, -1, dtype=np.int64)
914
+ count = 3 * mesh.n_nodes
915
+ for i in range(mesh.n_nodes):
916
+ if jump[i]:
917
+ offset[i], count = count, count + 3
918
+ elif tip[i]:
919
+ offset[i], count = count, count + 12
920
+ self.offset, self.n_dofs = offset, count
921
+ self.enriched = np.flatnonzero((jump | tip)[elems].any(axis=1))
922
+ self.cut = cut
923
+
924
+ def _points(self, e: int):
925
+ """Quadrature points (rows), weights and sides of an enriched element."""
926
+ x = self.mesh.nodes[self.mesh.elements[e]]
927
+ phi = self.phi[self.mesh.elements[e]]
928
+ subs, sides = _split(x, phi)
929
+ near_front = self.tip[self.mesh.elements[e]].any()
930
+ if near_front:
931
+ for _ in range(self.refine):
932
+ refined, refined_sides = [], []
933
+ for t, s in zip(subs, sides, strict=True):
934
+ pieces = _refine(t)
935
+ refined += pieces
936
+ refined_sides += [s] * len(pieces)
937
+ subs, sides = refined, refined_sides
938
+ pts, wts, sgn = [], [], []
939
+ for t, s in zip(subs, sides, strict=True):
940
+ vol = abs(np.linalg.det(np.stack([t[1] - t[0], t[2] - t[0], t[3] - t[0]]))) / 6.0
941
+ if vol <= 0:
942
+ continue
943
+ pts.append(_Q4 @ t)
944
+ wts.append(np.full(4, vol / 4.0))
945
+ sgn.append(np.full(4, s))
946
+ return np.concatenate(pts), np.concatenate(wts), np.concatenate(sgn)
947
+
948
+ def stiffness(self) -> sp.csr_matrix:
949
+ """The stiffness of all the dofs: the standard ones (``3 n``) then the enriched."""
950
+ from morphogen.homogenization.fe import assemble
951
+
952
+ mesh = self.mesh
953
+ k_std = assemble(mesh, 3, np.zeros(mesh.n_elements, dtype=np.int64), self.d[None])
954
+ rows, cols, vals = [], [], []
955
+ for e in self.enriched:
956
+ nodes = mesh.elements[e]
957
+ g = self.grads[e]
958
+ pts, wts, sgn = self._points(e)
959
+ x0 = mesh.nodes[nodes[0]]
960
+ # barycentric coordinates of the points: N = 1 - sum, from the gradients
961
+ nval = np.empty((len(pts), 4))
962
+ nval[:, 1:] = (pts - x0) @ g[1:].T
963
+ nval[:, 0] = 1.0 - nval[:, 1:].sum(axis=1)
964
+ phi_q, psi_q = nval @ self.phi[nodes], nval @ self.psi[nodes]
965
+ gphi, gpsi = self.phi[nodes] @ g, self.psi[nodes] @ g
966
+ columns, dofs = [], []
967
+ for a, i in enumerate(nodes):
968
+ for c in range(3):
969
+ columns.append(_b_rows(c, np.tile(g[a], (len(pts), 1))))
970
+ dofs.append(3 * i + c)
971
+ if self.jump[i]:
972
+ hi = 1.0 if self.phi[i] > 0 else -1.0
973
+ for c in range(3):
974
+ columns.append(_b_rows(c, (sgn - hi)[:, None] * g[a][None]))
975
+ dofs.append(self.offset[i] + c)
976
+ elif self.tip[i]:
977
+ f, gf = _branch(phi_q, psi_q, gphi[None], gpsi[None])
978
+ fi, _ = _branch(
979
+ self.phi[i : i + 1], self.psi[i : i + 1], gphi[None], gpsi[None]
980
+ )
981
+ for kf in range(4):
982
+ grad = (f[:, kf] - fi[0, kf])[:, None] * g[a][None] + nval[
983
+ :, a : a + 1
984
+ ] * gf[:, kf]
985
+ for c in range(3):
986
+ columns.append(_b_rows(c, grad))
987
+ dofs.append(self.offset[i] + 3 * kf + c)
988
+ b = np.stack(columns, axis=2) # points x 6 x columns
989
+ ke = np.einsum("q,qia,ij,qjb->ab", wts, b, self.d, b)
990
+ dofs = np.asarray(dofs)
991
+ enriched = dofs >= 3 * mesh.n_nodes
992
+ keep = enriched[:, None] | enriched[None, :] # the standard block is in k_std
993
+ r, cc = np.meshgrid(dofs, dofs, indexing="ij")
994
+ rows.append(r[keep])
995
+ cols.append(cc[keep])
996
+ vals.append(ke[keep])
997
+ n = self.n_dofs
998
+ k = (
999
+ sp.csr_matrix(
1000
+ (np.concatenate(vals), (np.concatenate(rows), np.concatenate(cols))), shape=(n, n)
1001
+ )
1002
+ if rows
1003
+ else sp.csr_matrix((n, n))
1004
+ )
1005
+ k_std = sp.csr_matrix((k_std.data, k_std.indices, k_std.indptr), shape=k_std.shape)
1006
+ k_std.resize((n, n))
1007
+ return (k + k_std).tocsr()
1008
+
1009
+ def crack_area(self) -> float:
1010
+ """The area of the crack inside the body: the parts behind the front of its sections
1011
+ by the cut elements (polygons clipped by ``ψ = 0``)."""
1012
+ total = 0.0
1013
+ x = self.mesh.nodes
1014
+ for e in np.flatnonzero(self.cut):
1015
+ nodes = self.mesh.elements[e]
1016
+ p, s = self.phi[nodes], self.psi[nodes]
1017
+ points, values = [], []
1018
+ for i in range(4):
1019
+ for j in range(i + 1, 4):
1020
+ if (p[i] > 0) != (p[j] > 0):
1021
+ t = p[i] / (p[i] - p[j])
1022
+ points.append(x[nodes[i]] + t * (x[nodes[j]] - x[nodes[i]]))
1023
+ values.append(s[i] + t * (s[j] - s[i]))
1024
+ pts = np.array(points)
1025
+ centre = pts.mean(axis=0)
1026
+ normal = np.asarray(self.crack.normal)
1027
+ ref = pts[0] - centre
1028
+ ang = np.arctan2(np.cross(ref, pts - centre) @ normal, (pts - centre) @ ref)
1029
+ order = np.argsort(ang)
1030
+ poly, vals = pts[order], np.asarray(values)[order]
1031
+ clipped = [] # Sutherland-Hodgman on psi < 0
1032
+ for k in range(len(poly)):
1033
+ a, b = poly[k], poly[(k + 1) % len(poly)]
1034
+ va, vb = vals[k], vals[(k + 1) % len(poly)]
1035
+ if va < 0:
1036
+ clipped.append(a)
1037
+ if (va < 0) != (vb < 0):
1038
+ clipped.append(a + va / (va - vb) * (b - a))
1039
+ if len(clipped) >= 3:
1040
+ c = np.array(clipped)
1041
+ for k in range(1, len(c) - 1):
1042
+ total += 0.5 * np.linalg.norm(np.cross(c[k] - c[0], c[k + 1] - c[0]))
1043
+ return total
1044
+
1045
+ def work(self, forces: np.ndarray, supports) -> float:
1046
+ """``W = fᵀ u`` under the nodal forces (``3 n``) with the fixed standard dofs (the
1047
+ enriched dofs of the same components of their nodes fixed too)."""
1048
+ n3 = 3 * self.mesh.n_nodes
1049
+ fixed = np.asarray(supports, dtype=np.int64)
1050
+ extra = []
1051
+ for dof in fixed:
1052
+ i, c = int(dof) // 3, int(dof) % 3
1053
+ if self.offset[i] >= 0:
1054
+ functions = 1 if self.jump[i] else 4
1055
+ extra.extend(self.offset[i] + 3 * k + c for k in range(functions))
1056
+ f = np.zeros(self.n_dofs)
1057
+ f[:n3] = forces
1058
+ u = _solve(self.stiffness(), f, np.concatenate([fixed, np.asarray(extra, dtype=np.int64)]))
1059
+ self.solution = u
1060
+ return float(f @ u)
1061
+
1062
+
1063
+ # -- energy release rate and propagation ------------------------------------------------------
1064
+
1065
+
1066
+ def release_rate(
1067
+ work_area: Callable[[Crack], tuple[float, float]], crack: Crack, delta: float
1068
+ ) -> float:
1069
+ """The mean energy release rate along the front, ``(W(a + δ) - W(a - δ)) / (2 (A(a + δ) -
1070
+ A(a - δ)))``, from a function giving ``W = fᵀ u`` and the area of the crack."""
1071
+ w_plus, a_plus = work_area(crack.grown(delta))
1072
+ w_minus, a_minus = work_area(crack.grown(-delta))
1073
+ if not a_plus > a_minus:
1074
+ raise ValueError("release_rate: the crack area must grow (a larger delta for the mesh)")
1075
+ return 0.5 * (w_plus - w_minus) / (a_plus - a_minus)
1076
+
1077
+
1078
+ def xfem_work(mesh: TetMesh, material, forces, supports, **options) -> Callable:
1079
+ """``crack -> (W, area)`` by XFEM on a fixed mesh (``forces``, ``supports``: functions of
1080
+ the mesh)."""
1081
+ f = forces(mesh)
1082
+ fixed = supports(mesh)
1083
+
1084
+ def run(crack: Crack):
1085
+ model = XFEM(mesh, material, crack, **options)
1086
+ return model.work(f, fixed), model.crack_area()
1087
+
1088
+ return run
1089
+
1090
+
1091
+ def conforming_work_of(
1092
+ mesh_of: Callable[[Crack], TetMesh], material, forces, supports, **options
1093
+ ) -> Callable:
1094
+ """``crack -> (W, area)`` on conforming meshes, ``mesh_of(crack)`` meshing (or remeshing,
1095
+ :func:`crack_mesh`) the body for each crack; ``options``: those of
1096
+ :func:`conforming_work` (``order=2`` for 10-node elements, with quarter points)."""
1097
+
1098
+ def run(crack: Crack):
1099
+ return conforming_work(mesh_of(crack), material, crack, forces, supports, **options)
1100
+
1101
+ return run
1102
+
1103
+
1104
+ @dataclass
1105
+ class Propagation:
1106
+ """The steps of a propagation: crack sizes, energy release rates, stress intensity
1107
+ factors (mode I), cycles (Paris) or critical load factors (Griffith)."""
1108
+
1109
+ sizes: np.ndarray
1110
+ rates: np.ndarray
1111
+ factors: np.ndarray
1112
+ cycles: np.ndarray
1113
+ loads: np.ndarray
1114
+
1115
+ def rows(self) -> list[dict]:
1116
+ return [
1117
+ {"a": float(a), "G": float(g), "K": float(k), "N": float(n), "load": float(lam)}
1118
+ for a, g, k, n, lam in zip(
1119
+ self.sizes, self.rates, self.factors, self.cycles, self.loads, strict=True
1120
+ )
1121
+ ]
1122
+
1123
+
1124
+ def propagate(
1125
+ work_area: Callable[[Crack], tuple[float, float]],
1126
+ crack: Crack,
1127
+ *,
1128
+ young: float,
1129
+ poisson: float,
1130
+ increment: float,
1131
+ steps: int,
1132
+ delta: float | None = None,
1133
+ paris: tuple[float, float] | None = None,
1134
+ toughness: float | None = None,
1135
+ plane_strain: bool = True,
1136
+ ) -> Propagation:
1137
+ """Grow a crack by ``steps`` uniform advances of its front by ``increment`` (see the
1138
+ module): ``G`` at each size by :func:`release_rate` (``delta``: half the advance of its
1139
+ differences, by default ``increment / 2``), ``K = sqrt(E' G)`` (``E' = E / (1 - ν²)`` in
1140
+ plane strain), the cycles of Paris' law ``da/dN = C K^m`` (``paris = (C, m)``, the
1141
+ loading of the forces as the range) and the load factor ``sqrt(G_c / G)`` at which
1142
+ Griffith's criterion is met (``toughness`` G_c)."""
1143
+ e_prime = young / (1 - poisson**2) if plane_strain else young
1144
+ delta = increment / 2 if delta is None else delta
1145
+ sizes, rates, factors, cycles, loads = [], [], [], [], []
1146
+ n = 0.0
1147
+ for _ in range(int(steps) + 1):
1148
+ g = release_rate(work_area, crack, delta)
1149
+ k = math.sqrt(max(e_prime * g, 0.0))
1150
+ sizes.append(crack.size)
1151
+ rates.append(g)
1152
+ factors.append(k)
1153
+ loads.append(math.sqrt(toughness / g) if toughness else math.nan)
1154
+ cycles.append(n)
1155
+ if paris is not None:
1156
+ c, m = paris
1157
+ n += increment / (c * k**m)
1158
+ crack = crack.grown(increment)
1159
+ return Propagation(
1160
+ np.array(sizes), np.array(rates), np.array(factors), np.array(cycles), np.array(loads)
1161
+ )
1162
+
1163
+
1164
+ def sent_factor(ratio: float) -> float:
1165
+ """The geometry factor of the single edge notched plate in uniform tension, ``K = σ
1166
+ sqrt(π a) F(a/W)`` (Tada, Paris & Irwin; 0.5 % for a/W < 0.6)."""
1167
+ r = float(ratio)
1168
+ return 1.12 - 0.231 * r + 10.55 * r**2 - 21.72 * r**3 + 30.39 * r**4