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,2586 @@
1
+ """The tools of the tab Fracture (:mod:`morphogen.fracture`): the stress intensity factors
2
+ of a crack in a plate, a block or a morphology of the workspace (the G-θ method and the
3
+ interaction integrals, in small and finite strains, and the J of inelastic bulks), its
4
+ propagation on meshes rebuilt by MMG at each advance, in a plate or through a morphology
5
+ (kinked after Erdogan & Sih, at a fixed load with Paris' law, or once its driving force
6
+ reaches a toughness: G_c, the J_tip of an inelastic bulk, or the porosity of GTN points at
7
+ the tip; through a morphology, the toughness of each phase and of the interfaces between
8
+ them deflects it along weak interfaces and holds it back at tough phases), cohesive zones
9
+ (a ligament ahead of a notch, the interfaces of the phases or the
10
+ grain boundaries of a morphology) and the growth of a crack through the grains of a
11
+ polycrystal of crystal plasticity.
12
+
13
+ The specimens are boxes ``[lower, upper]`` (a plate of 16 x 32 x 1 by default, the domain
14
+ of a morphology, or a slab of it about the middle of z for the propagation), loaded along y:
15
+ tension on the faces y = 0 and y = H, in-plane shear on
16
+ the four lateral faces, antiplane shear along z, by tractions (the rigid motions held) or by
17
+ grips (the faces y = 0 and H clamped and moved). Straight cracks run from the face x = 0
18
+ (their front along z, through the thickness), at the height ``position``, inclined by
19
+ ``angle`` towards y; a penny crack is centred in the box, its normal along y (turned by the
20
+ same angle). The crack meshes of a morphology carry its phases (each with the material of
21
+ the form, E and ν, or void: the pores, left out of the meshes), conforming to their
22
+ interfaces or as staircases, and the sides of the crack apart."""
23
+
24
+ from __future__ import annotations
25
+
26
+ import math
27
+ from dataclasses import dataclass
28
+ from typing import Any
29
+
30
+ import numpy as np
31
+
32
+ from morphogen.gui.tools import Field, tab, tool
33
+
34
+ tab(
35
+ "fracture",
36
+ "Fracture",
37
+ "Cracks and cohesive zones: the stress intensity factors of a crack (G-θ, interaction "
38
+ "integrals, J of inelastic bulks), its propagation on meshes rebuilt at each advance "
39
+ "(kinking, Paris' law, toughness, ductile growth), cohesive interfaces (force-displacement, "
40
+ "dissipated energies, broken interfaces) and crack growth through a polycrystal.",
41
+ order=50,
42
+ )
43
+
44
+ #: The elements of the meshes, at most (an estimate of 16 V / h³ for MMG)
45
+ MAX_ELEMENTS = 300_000
46
+ #: The default element size keeps the meshes below this many elements
47
+ DEFAULT_ELEMENTS = 50_000
48
+ #: The materials of the phases of a morphology when the form gives none (a contrast of 3)
49
+ DEFAULT_YOUNG, DEFAULT_POISSON, DEFAULT_CONTRAST = 1000.0, 0.3, 3.0
50
+
51
+ LOADINGS = (
52
+ ("tension", "tension along y (mode I)"),
53
+ ("shear", "in-plane shear xy (mode II)"),
54
+ ("mixed", "tension and shear (modes I and II)"),
55
+ ("antiplane", "antiplane shear yz (mode III)"),
56
+ )
57
+ CONTROLS = (
58
+ ("tractions", "tractions on the faces (the rigid motions held)"),
59
+ ("grips", "grips: the faces y = 0 and y = H clamped and moved"),
60
+ )
61
+ BEHAVIOURS = (
62
+ ("elastic", "elastic (neo-Hookean in finite strains)"),
63
+ ("plastic", "von Mises elasto-(visco)plasticity"),
64
+ ("porous", "porous plasticity (Gurson-Tvergaard-Needleman)"),
65
+ ("custom", "a material as JSON (plasticity, porous_plasticity, mfront...)"),
66
+ ("workspace", "a behaviour of the workspace (B: a material point, a Z-set file)"),
67
+ )
68
+ KINEMATICS = (("small", "small strains"), ("finite", "finite strains"))
69
+
70
+
71
+ # -- the fields shared by the tools ------------------------------------------------------------
72
+
73
+
74
+ def _behaviour_fields(when: dict | None = None) -> list[Field]:
75
+ """The fields of the isotropic material of a specimen and of its behaviour (``when``:
76
+ the conditions of them all; the page reads the hidden fields too, so that the fields of
77
+ a behaviour repeat them)."""
78
+ isotropic = {**(when or {}), "behaviour": ["elastic", "plastic", "porous"]}
79
+ inelastic = {**(when or {}), "behaviour": ["plastic", "porous"]}
80
+ porous = {**(when or {}), "behaviour": "porous"}
81
+ custom = {**(when or {}), "behaviour": "custom"}
82
+ kept = {**(when or {}), "behaviour": "workspace"}
83
+ return [
84
+ Field("behaviour", "choice", "elastic", choices=BEHAVIOURS, when=when,
85
+ doc="the behaviour of the points of the bulk (morphogen.fracture.bulk)"),
86
+ Field("kept", "item", label="behaviour of the workspace", items=("behaviour",),
87
+ required=True, when=kept, doc="with its own elasticity"),
88
+ Field("young", "float", DEFAULT_YOUNG, label="Young's modulus E", unit="stress",
89
+ when=isotropic),
90
+ Field("poisson", "float", DEFAULT_POISSON, label="Poisson's ratio ν", when=isotropic),
91
+ Field("yield_stress", "float", label="yield stress R0", unit="stress", when=inelastic,
92
+ doc="blank: E / 1000"),
93
+ Field("hardening", "float", label="linear hardening H", unit="stress", when=inelastic,
94
+ doc="blank: E / 20"),
95
+ Field("viscosity", "float", label="Norton's K", unit="stress", when=inelastic,
96
+ doc="viscoplasticity, the load factor as the time (blank: rate-independent)"),
97
+ Field("exponent", "float", 5.0, label="Norton's n", when=inelastic),
98
+ Field("porosity", "float", 0.01, label="initial porosity f0", when=porous),
99
+ Field("material", "json", label="material (JSON)", when=custom,
100
+ doc='the keys of a Material: young, poisson (or stiffness), plasticity, '
101
+ 'porous_plasticity, crystal_plasticity, mfront; e.g. {"young": 1000, "poisson": '
102
+ '0.3, "plasticity": {"yield": 1, "hardening": 50, "isotropic": [{"Q": 5, "b": '
103
+ '20}]}}'),
104
+ ] # fmt: skip
105
+
106
+
107
+ def _plate_fields(when: dict | None = None, penny: bool = True) -> list[Field]:
108
+ blanks = (" (blank: 16, or 4 for a penny)", " (blank: 32, or 4)", " (blank: 1, or 4)")
109
+ blanks = blanks if penny else ("", "", "")
110
+ return [
111
+ Field("width", "float", None if penny else 16.0, unit="length", when=when,
112
+ doc="along x" + blanks[0]),
113
+ Field("height", "float", None if penny else 32.0, unit="length", when=when,
114
+ doc="along y, the direction of the load" + blanks[1]),
115
+ Field("thickness", "float", None if penny else 1.0, unit="length", when=when,
116
+ doc="along z, the front of a straight crack" + blanks[2]),
117
+ ] # fmt: skip
118
+
119
+
120
+ def _crack_fields(kinds) -> list[Field]:
121
+ choices = {
122
+ "edge": ("edge", "edge: from the face x = 0, its front through the thickness"),
123
+ "through": ("through", "through: a centre crack of 2a in a plate of 2W, by its half "
124
+ "(the plane x = 0 of symmetry; tension)"),
125
+ "penny": ("penny", "penny: a circular crack inside a block"),
126
+ } # fmt: skip
127
+ return [
128
+ Field("crack", "choice", kinds[0], choices=tuple(choices[k] for k in kinds)),
129
+ Field("length", "float", unit="length",
130
+ doc="of a straight crack, or the radius of a penny (blank: 0.28 W for an edge "
131
+ "crack, 0.25 W through, a quarter of the smallest edge for a penny)"),
132
+ Field("position", "float", unit="length", doc="the height y of the crack (blank: the "
133
+ "middle)"),
134
+ Field("angle", "float", 0.0, unit="degree",
135
+ doc="the plane of the crack turned about z, from x towards y"),
136
+ ] # fmt: skip
137
+
138
+
139
+ def _loading_fields(loadings=LOADINGS) -> list[Field]:
140
+ return [
141
+ Field("loading", "choice", "tension", choices=loadings),
142
+ Field("shear_ratio", "float", 0.7, label="shear / tension", when={"loading": "mixed"}),
143
+ Field("control", "choice", "tractions", choices=CONTROLS),
144
+ Field("load", "float", label="load",
145
+ doc="the traction (tractions) or the displacement of each grip (grips) at the "
146
+ "load factor 1 (blank: a nominal strain of 0.1 %: 10⁻³ E, or 5·10⁻⁴ H)"),
147
+ Field("plane_strain", "bool", True, label="plane strain",
148
+ doc="the faces z = 0 and z = T held along z (straight cracks, in-plane loads: the "
149
+ "auxiliary fields of the interaction integrals are those of plane strain); "
150
+ "otherwise the face z = 0 only (a mirror plane)"),
151
+ Field("kinematics", "choice", "small", choices=KINEMATICS,
152
+ doc="finite strains: total Lagrangian, the modes as estimates (turned back by "
153
+ "the rotation of the mean deformation gradient)"),
154
+ Field("element_size", "float", unit="length",
155
+ doc="the largest edge of the tetrahedra meshed by MMG (blank: a / 4.5 for a "
156
+ "straight crack, a / 3 for a penny, a / 9 for the growth through a morphology; "
157
+ "at most about 50 000 elements)"),
158
+ ] # fmt: skip
159
+
160
+
161
+ # -- materials -----------------------------------------------------------------------------------
162
+
163
+
164
+ def _material(p: dict):
165
+ """The isotropic material of a specimen with its behaviour (the fields of
166
+ :func:`_behaviour_fields`)."""
167
+ from morphogen.homogenization.materials import Material
168
+ from morphogen.homogenization.porous import PorousPlasticity
169
+
170
+ kind = p.get("behaviour") or "elastic"
171
+ if kind == "workspace":
172
+ return Material.from_config(p["kept"]["material"])
173
+ if kind == "custom":
174
+ spec = p.get("material")
175
+ if not isinstance(spec, dict) or not spec:
176
+ raise ValueError('material: a JSON object, e.g. {"young": 1000, "poisson": 0.3, '
177
+ '"plasticity": {"yield": 1, "hardening": 50}}') # fmt: skip
178
+ try:
179
+ return Material(**spec)
180
+ except TypeError as exc:
181
+ raise ValueError(f"material: {exc}") from None
182
+ young, poisson = float(p["young"]), float(p["poisson"])
183
+ if kind == "elastic":
184
+ return Material(young=young, poisson=poisson)
185
+ r0 = p["yield_stress"] if p.get("yield_stress") is not None else young / 1000.0
186
+ h = p["hardening"] if p.get("hardening") is not None else young / 20.0
187
+ k, n = p.get("viscosity"), p.get("exponent") or 5.0
188
+ if kind == "plastic":
189
+ plasticity: dict = {"yield": r0, "hardening": h}
190
+ if k:
191
+ plasticity["norton"] = {"K": float(k), "n": float(n)}
192
+ return Material(young=young, poisson=poisson, plasticity=plasticity)
193
+ if kind == "porous":
194
+ gtn = PorousPlasticity("gurson", yield_stress=r0, porosity=float(p["porosity"] or 0.0),
195
+ hardening=h, viscosity=float(k) if k else None,
196
+ exponent=float(n) if k else None) # fmt: skip
197
+ return Material(young=young, poisson=poisson, porous_plasticity=gtn)
198
+ raise ValueError(f"behaviour: one of {', '.join(b[0] for b in BEHAVIOURS)}")
199
+
200
+
201
+ def _phase_materials(item: dict, given, present=()) -> dict:
202
+ """The isotropic materials of the phases of a morphology and of those ``present`` in its
203
+ image (``given``: those of the form, by phase, or ``"void"``: pores, whose elements the
204
+ meshes leave out; the others E = 1000 for the phase 0 and 3000 for the others, ν =
205
+ 0.3)."""
206
+ from morphogen.homogenization.materials import Material
207
+
208
+ phases = {int(k) for k in (item.get("phases") or {"0": "", "1": ""})}
209
+ phases = sorted(phases | {int(k) for k in present})
210
+ out = {}
211
+ for k in phases:
212
+ spec = (given or {}).get(k)
213
+ if spec == "void":
214
+ out[k] = Material(void=True)
215
+ continue
216
+ if spec is None:
217
+ young = DEFAULT_YOUNG * (1.0 if k == 0 else DEFAULT_CONTRAST)
218
+ spec = {"young": young, "poisson": DEFAULT_POISSON}
219
+ out[k] = Material(young=float(spec["young"]), poisson=float(spec["poisson"]))
220
+ present = {int(k) for k in present} or set(out)
221
+ if all(out[k].void for k in present if k in out):
222
+ raise ValueError("every phase of the morphology is void")
223
+ return out
224
+
225
+
226
+ def _check_solid(data, voids, slab: bool = False) -> None:
227
+ """That the phases of a phase image other than ``voids`` make one body (parts below 1 %
228
+ of the largest aside, as :func:`~morphogen.fracture.lefm.without_voids` drops them;
229
+ ``slab``: the image is that of a slab of the morphology)."""
230
+ if not len(voids):
231
+ return
232
+ from scipy import ndimage
233
+
234
+ labels, count = ndimage.label(~np.isin(data, list(voids)))
235
+ if count > 1:
236
+ sizes = np.bincount(labels.ravel())[1:]
237
+ parts = int(np.count_nonzero(sizes >= 0.01 * sizes.max()))
238
+ if parts > 1:
239
+ hint = "; a thicker slab may hold it together" if slab else ""
240
+ raise ValueError(f"void phases {list(voids)}: the body left falls apart into {parts} "
241
+ f"parts (pores are phases enclosed by the others{hint})") # fmt: skip
242
+
243
+
244
+ def _stiffest(materials) -> float:
245
+ """The largest Young's modulus of materials (a crystal: its largest normal stiffness)."""
246
+ from morphogen.fracture.mixed import _stiffest
247
+
248
+ return max(_stiffest(m) for m in materials if not m.void)
249
+
250
+
251
+ def _phase_lookup(micro, spacing: float, lower=None, upper=None):
252
+ """The phase of a morphology at points (``phase_of(points)``), from a voxel image of
253
+ it (or of the box ``[lower, upper]`` in its domain) whose voxels are about ``spacing``
254
+ (at most 256 per edge), the phases of the image and the image (its phases)."""
255
+ from morphogen.domain import Domain, Grid
256
+
257
+ lengths = np.asarray(micro.domain.lengths, dtype=float)
258
+ spacing = max(float(spacing), float(lengths.max()) / 256.0)
259
+ whole = lower is None or (np.allclose(lower, micro.domain.lower)
260
+ and np.allclose(upper, micro.domain.upper)) # fmt: skip
261
+ if whole:
262
+ image = micro.voxelize(voxel_size=spacing)
263
+ else:
264
+ box = Domain(size=tuple(np.asarray(upper, dtype=float) - lower), origin=tuple(lower),
265
+ periodic=False) # fmt: skip
266
+ image = micro.voxelize(grid=Grid.for_domain(box, voxel_size=spacing))
267
+ data = np.asarray(image.data)
268
+ if data.dtype.kind not in "iub":
269
+ raise ValueError("the morphology gives no phase image")
270
+ origin = np.asarray(image.origin, dtype=float)
271
+ steps = np.asarray(image.spacing, dtype=float)
272
+ shape = np.asarray(data.shape)
273
+
274
+ def phase_of(points):
275
+ index = np.floor((np.asarray(points, dtype=float) - origin) / steps).astype(np.int64)
276
+ index = np.clip(index, 0, shape - 1)
277
+ return data[index[:, 0], index[:, 1], index[:, 2]].astype(np.int64)
278
+
279
+ return phase_of, np.unique(data), data
280
+
281
+
282
+ def _load_value(p: dict, lower, upper, young: float) -> float:
283
+ """The load of the form at the load factor 1: the traction or the displacement of each
284
+ grip (blank: a nominal strain of 0.1 %)."""
285
+ if p.get("load") is not None:
286
+ return float(p["load"])
287
+ if p["control"] == "tractions":
288
+ return 1e-3 * young
289
+ return 5e-4 * float(upper[1] - lower[1])
290
+
291
+
292
+ # -- specimens -----------------------------------------------------------------------------------
293
+
294
+
295
+ @dataclass
296
+ class Specimen:
297
+ """A cracked specimen: its box, its crack, the materials of the phases of its crack
298
+ meshes (``mesh_of(crack)``: MMG conforming to the crack; those of a morphology carry
299
+ its phases and the sides of the crack apart, ``mesh.side``, its pores left out), the
300
+ sides of the crack of the elements of a mesh (``sides(mesh)``, None: those of the mesh)
301
+ and its loading."""
302
+
303
+ lower: np.ndarray
304
+ upper: np.ndarray
305
+ crack: Any
306
+ kind: str
307
+ materials: dict
308
+ mesh_of: Any
309
+ sides: Any
310
+ prescribed: Any
311
+ forces: Any
312
+ size: float
313
+ young: float
314
+ names: dict
315
+ morphology: bool = False
316
+ handbook: dict | None = None
317
+ voids: tuple = ()
318
+
319
+ @property
320
+ def interfaces(self) -> str:
321
+ """The kind of the interfaces of the phases of a morphology on its crack meshes."""
322
+ return getattr(self.mesh_of, "kind", "")
323
+
324
+ def solve(self, crack=None, mesh=None, materials=None, **options):
325
+ """The :class:`~morphogen.fracture.mixed.CrackSolution` of a crack of the specimen
326
+ (on its crack mesh, or on ``mesh``; of its materials, or of ``materials``) at the
327
+ load factor 1."""
328
+ from morphogen.fracture.mixed import solve_crack
329
+
330
+ crack = self.crack if crack is None else crack
331
+ mesh = self.mesh_of(crack) if mesh is None else mesh
332
+ sides = None if self.sides is None else self.sides(mesh)
333
+ materials = self.materials if materials is None else materials
334
+ return solve_crack(mesh, crack, materials, self.prescribed, 1.0, forces=self.forces,
335
+ sides=sides, **options) # fmt: skip
336
+
337
+ def labels(self, mesh) -> np.ndarray:
338
+ """The phase of the bulk of each element of a crack mesh (0 for a homogeneous one)."""
339
+ if self.morphology:
340
+ return np.asarray(mesh.phase)
341
+ return np.zeros(mesh.n_elements, dtype=np.int64)
342
+
343
+ def solids(self) -> list:
344
+ """The materials of the phases that are not void."""
345
+ return [m for m in self.materials.values() if not m.void]
346
+
347
+
348
+ def _size(value, crack_size: float, kind: str, volume: float) -> float:
349
+ """The element size of the form, or the default (see :func:`_loading_fields`); checked
350
+ against :data:`MAX_ELEMENTS`."""
351
+ if value is None:
352
+ size = crack_size / (3.0 if kind == "penny" else 4.5)
353
+ size = max(size, (16.0 * volume / DEFAULT_ELEMENTS) ** (1.0 / 3.0))
354
+ else:
355
+ size = float(value)
356
+ if not size > 0:
357
+ raise ValueError("element size: positive")
358
+ count = 16.0 * volume / size**3
359
+ if count > MAX_ELEMENTS:
360
+ raise ValueError(
361
+ f"element size {size:g}: about {count:,.0f} elements, more than {MAX_ELEMENTS:,} "
362
+ "in the interface (a larger element size, or a smaller specimen)"
363
+ )
364
+ return size
365
+
366
+
367
+ def _crack_of(p: dict, lower, upper):
368
+ """The crack of the form in the box: a :class:`~morphogen.fracture.mixed.KinkedCrack`
369
+ (straight, from the face x = lower) or a penny :class:`~morphogen.fracture.lefm.Crack`."""
370
+ from morphogen.fracture.lefm import Crack
371
+ from morphogen.fracture.mixed import KinkedCrack
372
+
373
+ kind = p["crack"]
374
+ lengths = upper - lower
375
+ angle = math.radians(p.get("angle") or 0.0)
376
+ normal = np.array([-math.sin(angle), math.cos(angle), 0.0])
377
+ direction = np.array([math.cos(angle), math.sin(angle), 0.0])
378
+ y = lower[1] + 0.5 * lengths[1] if p.get("position") is None else float(p["position"])
379
+ if not lower[1] < y < upper[1]:
380
+ raise ValueError(f"position: the height of the crack inside the specimen "
381
+ f"({lower[1]:g} to {upper[1]:g})") # fmt: skip
382
+ if kind == "penny":
383
+ a = p["length"] if p.get("length") is not None else 0.25 * float(lengths.min())
384
+ centre = np.array([lower[0] + 0.5 * lengths[0], y, lower[2] + 0.5 * lengths[2]])
385
+ reach = np.min(np.minimum(centre - lower, upper - centre))
386
+ if not 0 < a < reach:
387
+ raise ValueError(f"penny: a radius below {reach:g} (the crack inside the specimen)")
388
+ return Crack("penny", tuple(centre), tuple(normal), float(a))
389
+ default = 0.25 if kind == "through" else 0.28
390
+ a = p["length"] if p.get("length") is not None else default * float(lengths[0])
391
+ if kind == "through" and abs(angle) > 1e-12:
392
+ raise ValueError("through: a centre crack by its symmetric half, normal to y (angle 0)")
393
+ mouth = np.array([lower[0], y, lower[2]])
394
+ tip = mouth + float(a) * direction
395
+ if not (a > 0 and np.all(tip[:2] > lower[:2]) and np.all(tip[:2] < upper[:2])):
396
+ raise ValueError("length: the front of the crack inside the specimen")
397
+ return KinkedCrack((tuple(mouth), tuple(tip)))
398
+
399
+
400
+ def _nearest(mesh, point) -> int:
401
+ return int(np.argmin(np.linalg.norm(mesh.nodes - np.asarray(point, dtype=float), axis=1)))
402
+
403
+
404
+ def _loads(p: dict, kind: str, lower, upper, young: float):
405
+ """The prescribed displacements ``prescribed(mesh)`` and the nodal forces ``forces(mesh)``
406
+ (None for grips) of the loading of the form at the load factor 1 (see the module)."""
407
+ from morphogen.fracture.lefm import face_forces
408
+
409
+ loading, control = p["loading"], p["control"]
410
+ lo, up = np.asarray(lower, dtype=float), np.asarray(upper, dtype=float)
411
+ tol = 1e-9 * float(np.max(up - lo))
412
+ mid = 0.5 * (lo + up)
413
+ straight = kind != "penny"
414
+ if kind == "through" and loading != "tension":
415
+ raise ValueError("through: a centre crack by its symmetric half, in tension")
416
+ plane_strain = bool(p.get("plane_strain")) and straight and loading != "antiplane"
417
+ value = _load_value(p, lo, up, young)
418
+ ratio = float(p.get("shear_ratio") or 0.0) if loading == "mixed" else 0.0
419
+ normal = value if loading in ("tension", "mixed") else 0.0
420
+ shear = value if loading == "shear" else ratio * value
421
+ anti = value if loading == "antiplane" else 0.0
422
+
423
+ def faces(m):
424
+ x = m.nodes
425
+ return {"top": x[:, 1] > up[1] - tol, "bottom": x[:, 1] < lo[1] + tol,
426
+ "left": x[:, 0] < lo[0] + tol, "z0": x[:, 2] < lo[2] + tol,
427
+ "z1": x[:, 2] > up[2] - tol} # fmt: skip
428
+
429
+ if control == "grips":
430
+ top = np.array([shear, normal, anti])
431
+
432
+ def prescribed(m):
433
+ f = faces(m)
434
+ grips = f["top"] | f["bottom"]
435
+ out = [(np.flatnonzero(f["top"]), [0, 1, 2], top),
436
+ (np.flatnonzero(f["bottom"]), [0, 1, 2], -top)] # fmt: skip
437
+ if anti and straight: # pure antiplane shear: the in-plane motion held
438
+ out.append((np.flatnonzero(~grips), [0, 1], 0.0))
439
+ elif plane_strain:
440
+ out.append((np.flatnonzero((f["z0"] | f["z1"]) & ~grips), 2, 0.0))
441
+ if kind == "through": # the plane of symmetry
442
+ out.append((np.flatnonzero(f["left"] & ~grips), 0, 0.0))
443
+ return out
444
+
445
+ return prescribed, None
446
+
447
+ def forces(m):
448
+ def on(axis, side):
449
+ if side > 0:
450
+ return lambda c: c[:, axis] > up[axis] - tol
451
+ return lambda c: c[:, axis] < lo[axis] + tol
452
+
453
+ f = np.zeros(3 * m.n_nodes)
454
+ if normal:
455
+ f += face_forces(m, on(1, 1), [0.0, normal, 0.0])
456
+ f += face_forces(m, on(1, -1), [0.0, -normal, 0.0])
457
+ if shear: # uniform in-plane shear: the four lateral faces
458
+ f += face_forces(m, on(1, 1), [shear, 0.0, 0.0])
459
+ f += face_forces(m, on(1, -1), [-shear, 0.0, 0.0])
460
+ f += face_forces(m, on(0, 1), [0.0, shear, 0.0])
461
+ f += face_forces(m, on(0, -1), [0.0, -shear, 0.0])
462
+ if anti:
463
+ f += face_forces(m, on(1, 1), [0.0, 0.0, anti])
464
+ f += face_forces(m, on(1, -1), [0.0, 0.0, -anti])
465
+ if not straight: # uniform antiplane shear of a block: the faces z too
466
+ f += face_forces(m, on(2, 1), [0.0, anti, 0.0])
467
+ f += face_forces(m, on(2, -1), [0.0, -anti, 0.0])
468
+ return f
469
+
470
+ def prescribed(m):
471
+ f = faces(m)
472
+ if not straight: # a block: three corners hold the rigid motions
473
+ a = _nearest(m, lo)
474
+ b = _nearest(m, (up[0], lo[1], lo[2]))
475
+ c = _nearest(m, (lo[0], up[1], lo[2]))
476
+ return [(a, [0, 1, 2], 0.0), (b, [1, 2], 0.0), (c, 2, 0.0)]
477
+ if anti: # pure antiplane shear (the in-plane motion held), as the strip solution
478
+ corner = _nearest(m, (up[0], lo[1], lo[2]))
479
+ return [(np.arange(m.n_nodes), [0, 1], 0.0), (corner, 2, 0.0)]
480
+ faces_z = f["z0"] | f["z1"] if plane_strain else f["z0"]
481
+ a = _nearest(m, (up[0], mid[1], lo[2]))
482
+ out = [(np.flatnonzero(faces_z), 2, 0.0)]
483
+ if kind == "through": # the plane of symmetry, and one node along y
484
+ return [*out, (np.flatnonzero(f["left"]), 0, 0.0), (a, 1, 0.0)]
485
+ b = _nearest(m, (up[0], up[1], lo[2]))
486
+ return [*out, (a, [0, 1], 0.0), (b, 0, 0.0)]
487
+
488
+ return prescribed, forces
489
+
490
+
491
+ def _handbook(p: dict, kind: str, crack, lower, upper, young: float) -> dict | None:
492
+ """The handbook factor of the specimen when it has one: tension by tractions of an edge
493
+ crack (Tada, Paris & Irwin), of a centre crack (Tada) and of a penny (Sneddon, in an
494
+ infinite body), antiplane shear of an edge crack (the strip); straight cracks normal to
495
+ y, small strains."""
496
+ from morphogen.fracture.lefm import sent_factor
497
+
498
+ if p["control"] != "tractions" or p.get("kinematics") == "finite" or (p.get("angle") or 0):
499
+ return None
500
+ value = _load_value(p, lower, upper, young)
501
+ width = float(upper[0] - lower[0])
502
+ a = float(crack.size)
503
+ if p["loading"] == "tension":
504
+ if kind == "edge":
505
+ factor = value * math.sqrt(math.pi * a) * sent_factor(a / width)
506
+ return {"mode": "K_I", "value": factor, "source": "Tada, Paris & Irwin (SENT)"}
507
+ if kind == "through":
508
+ r = a / width
509
+ shape = (1 - 0.025 * r**2 + 0.06 * r**4) * math.sqrt(1.0 / math.cos(0.5 * math.pi * r))
510
+ return {"mode": "K_I", "value": value * math.sqrt(math.pi * a) * shape,
511
+ "source": "Tada (centre crack in a long strip)"} # fmt: skip
512
+ return {"mode": "K_I", "value": 2.0 * value * math.sqrt(a / math.pi),
513
+ "source": "Sneddon (infinite body)"} # fmt: skip
514
+ if p["loading"] == "antiplane" and kind == "edge":
515
+ strip = math.sqrt(2 * width / (math.pi * a) * math.tan(math.pi * a / (2 * width)))
516
+ return {"mode": "K_III", "value": value * math.sqrt(math.pi * a) * strip,
517
+ "source": "antiplane strip"} # fmt: skip
518
+ return None
519
+
520
+
521
+ INTERFACES = (
522
+ ("conforming", "conforming: the crack meshes follow the interfaces of the phases (MMG "
523
+ "cuts the mesh of the phases by each crack; a level set needed)"),
524
+ ("staircase", "staircase: each element of the crack meshes the phase of its centroid"),
525
+ ) # fmt: skip
526
+
527
+
528
+ class _MorphologyMeshes:
529
+ """The crack meshes of a morphology (``self(crack)``: :func:`~morphogen.fracture.lefm.
530
+ crack_mesh`), its void phases left out, and the ``kind`` of their interfaces: conforming
531
+ to its phases (the mesh of its phases made at the first crack, then cut by each one), or
532
+ staircases (each element the phase ``phase_of`` its centroid); a morphology without a
533
+ level set, or of more than two phases, has staircases."""
534
+
535
+ def __init__(self, micro, lower, upper, size: float, phase_of, present, voids, kind: str):
536
+ self.micro, self.lower, self.upper, self.size = micro, lower, upper, float(size)
537
+ self.phase_of, self.voids, self.phases = phase_of, tuple(voids), None
538
+ self.kind = kind
539
+ if kind == "conforming" and not {int(k) for k in present} <= {0, 1}:
540
+ self._staircase("more than two phases")
541
+
542
+ def _staircase(self, why: str) -> None:
543
+ import warnings
544
+
545
+ warnings.warn(f"{why}: staircase interfaces on the crack meshes", stacklevel=3)
546
+ self.kind = "staircase"
547
+
548
+ def __call__(self, crack):
549
+ from morphogen.fracture.lefm import crack_mesh, phase_mesh
550
+
551
+ if self.kind == "conforming" and self.phases is None:
552
+ try:
553
+ self.phases = phase_mesh(self.micro, self.lower, self.upper, self.size)
554
+ except ValueError as exc: # no level set
555
+ if "level-set" not in str(exc):
556
+ raise
557
+ self._staircase("the morphology has no level set")
558
+ if self.kind == "conforming": # the interfaces followed coarsely (h / 5, h / 3)
559
+ return crack_mesh(self.lower, self.upper, crack, size=self.size,
560
+ morphology=self.phases, voids=self.voids,
561
+ hausdorff=self.size / 5.0, min_size=self.size / 3.0) # fmt: skip
562
+ return crack_mesh(self.lower, self.upper, crack, size=self.size, morphology=self.phase_of,
563
+ voids=self.voids) # fmt: skip
564
+
565
+
566
+ def specimen(p: dict, *, morphology_bulk: bool = True, slab: bool = False) -> Specimen:
567
+ """The cracked specimen of the form of the tools Stress intensity factors and Crack
568
+ propagation: a homogeneous box of the material of :func:`_material`, or the domain of a
569
+ morphology whose phases the crack meshes carry (their materials; its void phases, the
570
+ pores, left out): conforming to their interfaces, or as staircases (each element the
571
+ phase of its centroid). ``slab``: of a morphology, a slab about the middle of z (the
572
+ field ``slab``, blank: the whole depth, at most a sixteenth of the width), in plane
573
+ strain the path of a growth that of its section, meshed by elements of a / 9."""
574
+ from morphogen.fracture.lefm import crack_mesh
575
+
576
+ kind = p["crack"]
577
+ morphology = morphology_bulk and p.get("bulk") == "morphology"
578
+ if morphology:
579
+ item = p.get("source")
580
+ if item is None:
581
+ raise ValueError("morphology: choose a morphology of the workspace")
582
+ micro = item["micro"]
583
+ lower = np.asarray(micro.domain.lower, dtype=float).copy()
584
+ upper = np.asarray(micro.domain.upper, dtype=float).copy()
585
+ if kind == "through":
586
+ raise ValueError("through: a centre crack by the symmetry of a homogeneous plate")
587
+ names = {int(k): v for k, v in (item.get("phases") or {}).items()}
588
+ if slab:
589
+ depth = float(upper[2] - lower[2])
590
+ thickness = p.get("slab") or min(depth, float(upper[0] - lower[0]) / 16.0)
591
+ if not 0 < thickness <= depth * (1 + 1e-12):
592
+ raise ValueError(f"slab: from 0 to the depth of the morphology ({depth:g})")
593
+ middle = 0.5 * (lower[2] + upper[2])
594
+ lower[2], upper[2] = middle - 0.5 * thickness, middle + 0.5 * thickness
595
+ else:
596
+ penny = kind == "penny"
597
+ dims = [p.get("width") or (4.0 if penny else 16.0),
598
+ p.get("height") or (4.0 if penny else 32.0),
599
+ p.get("thickness") or (4.0 if penny else 1.0)] # fmt: skip
600
+ if min(dims) <= 0:
601
+ raise ValueError("width, height, thickness: positive")
602
+ lower, upper = np.zeros(3), np.asarray(dims, dtype=float)
603
+ names = {0: "bulk"}
604
+ crack = _crack_of(p, lower, upper)
605
+ scale = 2.0 if morphology and slab else 1.0 # the growth through a morphology: a / 9
606
+ size = _size(p.get("element_size"), crack.size / scale, kind, float(np.prod(upper - lower)))
607
+ voids = ()
608
+ if morphology:
609
+ phase_of, present, image = _phase_lookup(micro, 0.5 * size, lower, upper)
610
+ materials = _phase_materials(item, p.get("materials"), present)
611
+ if p.get("phase_kept"): # a behaviour of the workspace for one phase
612
+ from morphogen.homogenization.materials import Material
613
+
614
+ phase = p.get("kept_phase")
615
+ if phase not in materials or materials[phase].void:
616
+ solid = [k for k, m in materials.items() if not m.void]
617
+ raise ValueError(f"its phase: one of the solid phases {solid}")
618
+ materials[phase] = Material.from_config(p["phase_kept"]["material"])
619
+ voids = tuple(k for k, m in materials.items() if m.void)
620
+ _check_solid(image, voids, slab and upper[2] - lower[2] < micro.domain.lengths[2])
621
+ front, _ = crack.front(lower, upper, 32)
622
+ if voids and len(front) and np.mean(np.isin(phase_of(front), voids)) > 0.5:
623
+ raise ValueError("the front of the crack lies in a pore (a void phase): another "
624
+ "length or position") # fmt: skip
625
+ mesh_of = _MorphologyMeshes(micro, lower, upper, size, phase_of, present, voids,
626
+ p.get("interfaces") or "staircase") # fmt: skip
627
+ else:
628
+ material = _material(p)
629
+
630
+ def mesh_of(c):
631
+ return crack_mesh(lower, upper, c, size=size)
632
+
633
+ materials = {0: material, 1: material}
634
+ young = _stiffest(materials.values())
635
+ prescribed, forces = _loads(p, kind, lower, upper, young)
636
+ handbook = None if morphology else _handbook(p, kind, crack, lower, upper, young)
637
+ return Specimen(lower, upper, crack, kind, materials, mesh_of, None, prescribed, forces,
638
+ size, young, names, morphology, handbook, voids) # fmt: skip
639
+
640
+
641
+ # -- views -----------------------------------------------------------------------------------------
642
+
643
+
644
+ def section_cut(mesh, axis: int = 2, at=None):
645
+ """The cut of a tetrahedral mesh by the plane ``x[axis] = at`` (by default the middle of
646
+ the mesh): for the four corners of each polygon (a triangle repeats its last one), the
647
+ two nodes of the edge it lies on and its position along it, and the element of each
648
+ polygon."""
649
+ x = mesh.nodes
650
+ tets = mesh.elements[:, :4]
651
+ if at is None:
652
+ at = 0.5 * (x[:, axis].min() + x[:, axis].max())
653
+ d = x[tets, axis] - float(at)
654
+ positive = d > 0
655
+ count = positive.sum(axis=1)
656
+ order = np.argsort(~positive, axis=1, kind="stable") # the positive nodes first
657
+ nodes = np.take_along_axis(tets, order, axis=1)
658
+ dist = np.take_along_axis(d, order, axis=1)
659
+ starts, ends, where, owners = [], [], [], []
660
+ for n, edges in ((1, ((0, 1), (0, 2), (0, 3), (0, 3))), (3, ((3, 0), (3, 1), (3, 2), (3, 2))),
661
+ (2, ((0, 2), (0, 3), (1, 3), (1, 2)))): # fmt: skip
662
+ rows = np.flatnonzero(count == n)
663
+ if not len(rows):
664
+ continue
665
+ i, j = (np.array(k) for k in zip(*edges, strict=True))
666
+ di, dj = dist[rows][:, i], dist[rows][:, j]
667
+ starts.append(nodes[rows][:, i])
668
+ ends.append(nodes[rows][:, j])
669
+ where.append(di / (di - dj))
670
+ owners.append(rows)
671
+ if not owners:
672
+ empty = np.zeros((0, 4), dtype=np.int64)
673
+ return empty, empty, np.zeros((0, 4)), np.zeros(0, dtype=np.int64), axis
674
+ return (np.concatenate(starts), np.concatenate(ends), np.concatenate(where),
675
+ np.concatenate(owners), axis) # fmt: skip
676
+
677
+
678
+ def section(mesh, displacement=None, scale: float = 0.0, axis: int = 2, at=None, cut=None):
679
+ """The section of a tetrahedral mesh by the plane ``x[axis] = at`` (by default the middle
680
+ of the mesh; ``cut``: that of :func:`section_cut`), in the configuration ``x + scale u``:
681
+ its polygons (cells x 4 x 2, in the two other coordinates) and the element of each. The
682
+ lips of an opened crack, whose nodes are duplicated, open with ``u``."""
683
+ a, b, t, owners, axis = section_cut(mesh, axis, at) if cut is None else cut
684
+ x = mesh.nodes
685
+ moved = x if displacement is None else x + scale * np.asarray(displacement).reshape(-1, 3)
686
+ keep = [i for i in range(3) if i != axis]
687
+ points = moved[a] + t[..., None] * (moved[b] - moved[a])
688
+ return points[..., keep], owners
689
+
690
+
691
+ def _canvas(width: float = 6.4, height: float = 4.8, layout: str | None = "constrained"):
692
+ from matplotlib.backends.backend_agg import FigureCanvasAgg
693
+ from matplotlib.figure import Figure
694
+
695
+ fig = Figure(figsize=(width, height), dpi=100, layout=layout)
696
+ FigureCanvasAgg(fig)
697
+ return fig
698
+
699
+
700
+ class _Frames:
701
+ """The frames of a video drawn on one figure of fixed axes, whose cells (a section of a
702
+ mesh coloured by a field), lines and black outlines (the interfaces of phases) are
703
+ updated from frame to frame."""
704
+
705
+ def __init__(self, window, clim, label: str, *, cmap="viridis", lines=None, width=5.6):
706
+ from matplotlib.collections import LineCollection, PolyCollection
707
+
708
+ aspect = (window[1][1] - window[1][0]) / max(window[0][1] - window[0][0], 1e-300)
709
+ height = float(np.clip((width - 1.4) * aspect + 1.0, 3.0, 8.0))
710
+ self.fig = _canvas(width, height, layout=None)
711
+ self.ax = self.fig.add_axes((0.11, 0.09, 0.66, 0.83))
712
+ self.cells = PolyCollection([], cmap=cmap, edgecolors="face", linewidths=0.3)
713
+ self.cells.set_clim(*clim)
714
+ self.ax.add_collection(self.cells)
715
+ self.lines = None
716
+ source = self.cells
717
+ if lines is not None: # (cmap, clim, label) of lines over the cells
718
+ self.lines = LineCollection([], cmap=lines[0], linewidths=1.8)
719
+ self.lines.set_clim(*lines[1])
720
+ self.ax.add_collection(self.lines)
721
+ source, label = self.lines, lines[2]
722
+ self.outlines = LineCollection([], colors="0.08", linewidths=0.9)
723
+ self.ax.add_collection(self.outlines)
724
+ self.fig.colorbar(source, cax=self.fig.add_axes((0.82, 0.15, 0.03, 0.7)), label=label)
725
+ self.ax.set_xlim(*window[0])
726
+ self.ax.set_ylim(*window[1])
727
+ self.ax.set_aspect("equal", adjustable="box")
728
+ self.ax.set_xlabel("x")
729
+ self.ax.set_ylabel("y")
730
+ self.title = self.ax.set_title("", fontsize=9)
731
+
732
+ def frame(self, polygons, values, caption: str, segments=None, colours=None, *,
733
+ outlines=None) -> np.ndarray: # fmt: skip
734
+ self.cells.set_verts(polygons)
735
+ self.cells.set_array(np.asarray(values, dtype=float))
736
+ if self.lines is not None:
737
+ self.lines.set_segments(segments)
738
+ self.lines.set_array(np.asarray(colours, dtype=float))
739
+ self.outlines.set_segments([] if outlines is None else outlines)
740
+ self.title.set_text(caption)
741
+ return _rgb(self.fig)
742
+
743
+
744
+ def _rgb(fig) -> np.ndarray:
745
+ fig.canvas.draw()
746
+ return np.asarray(fig.canvas.buffer_rgba())[..., :3].copy()
747
+
748
+
749
+ def _draw_section(ax, mesh, values, *, displacement=None, scale=0.0, cmap="viridis", clim=None,
750
+ edges=False, window=None, label="", colorbar=True): # fmt: skip
751
+ """The mid-section z of a mesh on axes, its cells coloured by ``values`` (one per
752
+ element), within ``window`` ((x0, x1), (y0, y1)) when given."""
753
+ from matplotlib.collections import PolyCollection
754
+
755
+ polygons, owners = section(mesh, displacement, scale)
756
+ values = np.asarray(values, dtype=float)[owners]
757
+ cells = PolyCollection(polygons, array=values, cmap=cmap, rasterized=True,
758
+ edgecolors="0.25" if edges else "face",
759
+ linewidths=0.15 if edges else 0.3) # fmt: skip
760
+ if clim is not None:
761
+ cells.set_clim(*clim)
762
+ ax.add_collection(cells)
763
+ ax.set_aspect("equal")
764
+ ax.autoscale_view()
765
+ if window is not None:
766
+ ax.set_xlim(*window[0])
767
+ ax.set_ylim(*window[1])
768
+ ax.set_xlabel("x")
769
+ ax.set_ylabel("y")
770
+ if colorbar:
771
+ ax.figure.colorbar(cells, ax=ax, shrink=0.85, label=label)
772
+ return cells
773
+
774
+
775
+ def _labels_cmap(count: int):
776
+ from matplotlib.colors import ListedColormap
777
+
778
+ from morphogen.viz.png import label_colors
779
+
780
+ if count <= 1:
781
+ return ListedColormap([(0.80, 0.84, 0.90)])
782
+ if count <= 10:
783
+ palette = ((0.80, 0.84, 0.90), (0.93, 0.68, 0.38), (0.45, 0.70, 0.55),
784
+ (0.62, 0.55, 0.80), (0.90, 0.50, 0.55), (0.55, 0.75, 0.90),
785
+ (0.85, 0.80, 0.45), (0.65, 0.65, 0.65), (0.95, 0.75, 0.80),
786
+ (0.50, 0.55, 0.40)) # fmt: skip
787
+ return ListedColormap(palette[:count])
788
+ return ListedColormap(label_colors(np.arange(count)) / 255.0)
789
+
790
+
791
+ def _path_xy(crack) -> np.ndarray:
792
+ """The trace of a crack in the plane z: its polyline (a penny: its diameter along the
793
+ trace of its plane)."""
794
+ if hasattr(crack, "points"):
795
+ return np.asarray(crack.points)[:, :2]
796
+ centre, normal = np.asarray(crack.point), np.asarray(crack.normal)
797
+ along = np.array([normal[1], -normal[0], 0.0])
798
+ along /= max(np.linalg.norm(along), 1e-300)
799
+ return np.array([centre - crack.size * along, centre + crack.size * along])[:, :2]
800
+
801
+
802
+ def _tips_xy(crack) -> np.ndarray:
803
+ path = _path_xy(crack)
804
+ return path[-1:] if hasattr(crack, "points") else path
805
+
806
+
807
+ def _window(crack, size: float, lower, upper, reach: float = 6.0):
808
+ """The box around the front of a crack, ``reach`` elements wide on each side."""
809
+ tips = _tips_xy(crack)
810
+ half = reach * size
811
+ lo = np.maximum(tips.min(axis=0) - half, np.asarray(lower)[:2])
812
+ hi = np.minimum(tips.max(axis=0) + half, np.asarray(upper)[:2])
813
+ return (lo[0], hi[0]), (lo[1], hi[1])
814
+
815
+
816
+ def von_mises(solution) -> np.ndarray:
817
+ """The von Mises stress of each element of a solved body (Cauchy stresses)."""
818
+ h, p, _, _, _ = solution.stresses()
819
+ s = p
820
+ if solution.finite:
821
+ f = np.eye(3) + h
822
+ s = np.einsum("eij,ekj->eik", p, f) / np.linalg.det(f)[:, None, None]
823
+ dev = s - np.einsum("eii->e", s)[:, None, None] / 3.0 * np.eye(3)
824
+ return np.sqrt(1.5 * np.einsum("eij,eij->e", dev, dev))
825
+
826
+
827
+ def _state_field(solution):
828
+ """The field shown on a solved body: the cumulated plastic strain of the points of an
829
+ inelastic bulk (the porosity of porous points), else the von Mises stress."""
830
+ bulk = solution.bulk
831
+ if bulk is None:
832
+ return von_mises(solution), "von Mises stress"
833
+ from morphogen.homogenization.behaviours import POROUS, STATE_P
834
+
835
+ if np.any(bulk.kind == POROUS):
836
+ from morphogen.homogenization.porous import porosity
837
+
838
+ return porosity(bulk.old, bulk.behaviours.data[2], bulk.pmat), "porosity"
839
+ return np.asarray(bulk.old[:, STATE_P], dtype=float), "cumulated plastic strain p"
840
+
841
+
842
+ def _magnification(solutions, lower, upper, fraction: float = 0.05) -> float:
843
+ """The magnification drawing the largest displacement as ``fraction`` of the box."""
844
+ peak = max(float(np.abs(s.displacement).max()) for s in solutions)
845
+ return fraction * float(np.max(np.asarray(upper) - np.asarray(lower))) / max(peak, 1e-300)
846
+
847
+
848
+ def _mesh_figure(mesh, crack, size, lower, upper, names: dict, labels=None, title=""):
849
+ """The mid-section of a crack mesh (its phases or grains) and the trace of the crack, with
850
+ the zone around the front."""
851
+ fig = _canvas(10.0, 4.6)
852
+ left, right = fig.subplots(1, 2)
853
+ if labels is None:
854
+ labels = mesh.phase
855
+ values = np.asarray(labels)
856
+ count = int(values.max()) + 1 if values.size else 1
857
+ for ax, window in ((left, None), (right, _window(crack, size, lower, upper))):
858
+ _draw_section(ax, mesh, values, cmap=_labels_cmap(count), clim=(-0.5, count - 0.5),
859
+ edges=True, window=window, colorbar=False) # fmt: skip
860
+ path = _path_xy(crack)
861
+ ax.plot(path[:, 0], path[:, 1], "-", color="crimson", lw=1.8)
862
+ ax.plot(*_tips_xy(crack).T, "o", color="crimson", ms=4)
863
+ left.set_title(title or f"mesh: {mesh.n_elements} tetrahedra (section z)", fontsize=10)
864
+ right.set_title("around the front", fontsize=10)
865
+ if names and len(names) > 1:
866
+ from matplotlib.patches import Patch
867
+
868
+ cmap = _labels_cmap(count)
869
+ handles = [Patch(color=cmap((k + 0.5) / count), label=f"{k}: {name}")
870
+ for k, name in sorted(names.items()) if k < count] # fmt: skip
871
+ right.legend(handles=handles, fontsize=7, loc="upper right", frameon=True)
872
+ return fig
873
+
874
+
875
+ def _field_figure(solution, crack, size, lower, upper, values, label: str, title: str = ""):
876
+ """The field ``values`` of a solved body on its deformed mid-section (magnified), whole
877
+ and around the front."""
878
+ fig = _canvas(10.0, 4.6)
879
+ left, right = fig.subplots(1, 2)
880
+ m = _magnification([solution], lower, upper)
881
+ clim = (float(np.min(values)), float(np.percentile(values, 99.5)))
882
+ if not clim[1] > clim[0]:
883
+ clim = (clim[0], clim[0] + 1e-300 + abs(clim[0]))
884
+ window = _window(crack, size, lower, upper)
885
+ _draw_section(left, solution.mesh, values, displacement=solution.displacement, scale=m,
886
+ clim=clim, colorbar=False) # fmt: skip
887
+ _draw_section(right, solution.mesh, values, displacement=solution.displacement, scale=m,
888
+ clim=clim, window=window, label=label) # fmt: skip
889
+ left.set_title(title or f"{label} (displacements x {m:.3g})", fontsize=10)
890
+ right.set_title("around the front", fontsize=10)
891
+ return fig
892
+
893
+
894
+ def _curves(x, ys: dict, xlabel: str, ylabel: str, title: str = "", *, lines=None,
895
+ styles=None, twin=None): # fmt: skip
896
+ """A figure of curves ``ys`` (label: values) against ``x``; ``lines``: horizontal lines
897
+ (label: value); ``twin``: (label, values) on a second axis."""
898
+ from matplotlib.figure import Figure
899
+
900
+ fig = Figure(figsize=(5.6, 3.9), layout="constrained")
901
+ ax = fig.subplots()
902
+ for k, (label, y) in enumerate(ys.items()):
903
+ style = (styles or {}).get(label, "o-" if len(x) < 30 else "-")
904
+ ax.plot(x, y, style, lw=1.6, ms=4, label=label, color=f"C{k}")
905
+ for label, value in (lines or {}).items():
906
+ ax.axhline(value, color="0.45", lw=0.9, ls="--", label=label)
907
+ ax.set_xlabel(xlabel)
908
+ ax.set_ylabel(ylabel)
909
+ ax.set_title(title, fontsize=10)
910
+ ax.grid(alpha=0.3)
911
+ handles = ax.get_legend_handles_labels()[0]
912
+ if twin is not None:
913
+ other = ax.twinx()
914
+ handles += other.plot(x, twin[1], ":", color="0.3", lw=1.4, label=twin[0])
915
+ other.set_ylabel(twin[0])
916
+ if len(handles) > 1:
917
+ ax.legend(handles=handles, fontsize=8, frameon=False)
918
+ return fig
919
+
920
+
921
+ def _write_vtu(ctx, name: str, solution, fields: dict) -> None:
922
+ """The opened mesh of a solved body, its displacement and element fields (.vtu)."""
923
+ from morphogen.io.meshes import write_vtu_tet
924
+
925
+ write_vtu_tet(ctx.path(f"{name}.vtu"), solution.mesh,
926
+ cell_data={k: np.asarray(v, dtype=float) for k, v in fields.items()},
927
+ point_data={"displacement": np.asarray(solution.displacement)}) # fmt: skip
928
+
929
+
930
+ def _view3d(solution, values, label: str):
931
+ """A 3D view (VTK, when it renders) of the deformed body cut through the middle of z."""
932
+ from morphogen.viz.video import deformed_view, vtk_can_render
933
+
934
+ if not vtk_can_render():
935
+ return None
936
+ return deformed_view(solution.mesh, solution.displacement, np.asarray(values, dtype=float),
937
+ section=(2, 0.5), title=label, cmap="viridis") # fmt: skip
938
+
939
+
940
+ def _growth_frames(solutions, lower, upper, captions, outlines: bool = False) -> list[np.ndarray]:
941
+ """The frames of a growth: the deformed mid-section of each solution (the magnification,
942
+ the colours and the axes of the whole growth), coloured by :func:`_state_field`, with
943
+ ``outlines`` the interfaces of the phases and the walls of the pores of a morphology."""
944
+ fields = [_state_field(s) for s in solutions]
945
+ label = fields[0][1]
946
+ lo = min(float(np.min(f)) for f, _ in fields)
947
+ hi = max(float(np.percentile(f, 99.5)) for f, _ in fields)
948
+ hi = hi if hi > lo else lo + 1e-300 + abs(lo)
949
+ m = _magnification(solutions, lower, upper)
950
+ moved = np.concatenate([s.mesh.nodes + m * s.displacement for s in solutions])
951
+ pad = 0.02 * float(np.max(np.asarray(upper) - np.asarray(lower)))
952
+ window = ((moved[:, 0].min() - pad, moved[:, 0].max() + pad),
953
+ (moved[:, 1].min() - pad, moved[:, 1].max() + pad)) # fmt: skip
954
+ video = _Frames(window, (lo, hi), label)
955
+ frames = []
956
+ for s, (f, _), caption in zip(solutions, fields, captions, strict=True):
957
+ polygons, owners = section(s.mesh, s.displacement, m)
958
+ lines = _outlines(s, m) if outlines else None
959
+ frames.append(video.frame(polygons, f[owners], f"{caption} (displacements x {m:.3g})",
960
+ outlines=lines)) # fmt: skip
961
+ return frames
962
+
963
+
964
+ def _deflections(cracks, advances) -> tuple[list, np.ndarray]:
965
+ """The parts of the path of a growth along interfaces (polylines in the plane z, one per
966
+ advance along an interface) and the points where the crack turned into an interface
967
+ (from the bulk, or by more than 20° from another interface)."""
968
+ lines, turns, before = [], [], None
969
+ for k, advance in enumerate(advances[: len(cracks) - 1]):
970
+ old, new = cracks[k], cracks[k + 1]
971
+ if advance.kind == "interface":
972
+ tail = np.vstack([old.tip, np.asarray(new.points[len(old.points) - 1 :])])[:, :2]
973
+ lines.append(tail)
974
+ if before is None or before.kind != "interface" or abs(advance.angle) > 0.35:
975
+ turns.append(tail[-2] if len(tail) > 2 else tail[0])
976
+ before = advance
977
+ return lines, np.asarray(turns, dtype=float).reshape(-1, 2)
978
+
979
+
980
+ def _growth_figure(solution, cracks, size, lower, upper, title: str, names=None, advances=None):
981
+ """The path of a growing crack over the field of its last configuration (undeformed),
982
+ whole and around the path; with the ``names`` of the phases of a morphology, the path
983
+ over its phases (whole), the outlines of their interfaces and of the pores; with the
984
+ ``advances`` chosen by a toughness, the parts of the path along interfaces and the
985
+ deflections into them marked."""
986
+ from matplotlib.collections import LineCollection
987
+
988
+ values, label = _state_field(solution)
989
+ fig = _canvas(10.0, 4.6)
990
+ left, right = fig.subplots(1, 2)
991
+ path = _path_xy(cracks[-1])
992
+ tips = np.array([_tips_xy(c)[0] for c in cracks])
993
+ half = 4.0 * size
994
+ lo = np.maximum(np.minimum(path.min(axis=0), tips.min(axis=0)) - half, lower[:2])
995
+ hi = np.minimum(np.maximum(path.max(axis=0), tips.max(axis=0)) + half, upper[:2])
996
+ clim = (float(np.min(values)), float(np.percentile(values, 99.5)))
997
+ if not clim[1] > clim[0]:
998
+ clim = (clim[0], clim[0] + 1e-300 + abs(clim[0]))
999
+ outlines = _outlines(solution) if names is not None else None
1000
+ for ax, window in ((left, None), (right, ((lo[0], hi[0]), (lo[1], hi[1])))):
1001
+ if ax is left and names is not None: # the phases of the morphology
1002
+ phases = np.asarray(solution.mesh.phase)
1003
+ count = int(phases.max()) + 1
1004
+ _draw_section(ax, solution.mesh, phases, cmap=_labels_cmap(count),
1005
+ clim=(-0.5, count - 0.5), colorbar=False) # fmt: skip
1006
+ ax.set_xlim(lower[0], upper[0])
1007
+ ax.set_ylim(lower[1], upper[1])
1008
+ if len(names) > 1:
1009
+ from matplotlib.patches import Patch
1010
+
1011
+ cmap = _labels_cmap(count)
1012
+ handles = [Patch(color=cmap((k + 0.5) / count), label=f"{k}: {name}")
1013
+ for k, name in sorted(names.items()) if k < count] # fmt: skip
1014
+ ax.legend(handles=handles, fontsize=7, loc="upper right", frameon=True)
1015
+ else:
1016
+ _draw_section(ax, solution.mesh, values, clim=clim, window=window, label=label,
1017
+ colorbar=ax is right) # fmt: skip
1018
+ if outlines is not None:
1019
+ ax.add_collection(LineCollection(outlines, colors="0.08", linewidths=0.8))
1020
+ ax.plot(path[:, 0], path[:, 1], "-", color="white", lw=3.0)
1021
+ ax.plot(path[:, 0], path[:, 1], "-", color="crimson", lw=1.6)
1022
+ ax.plot(tips[:, 0], tips[:, 1], "o", color="crimson", ms=4, mec="white", mew=0.6)
1023
+ if advances:
1024
+ along, turns = _deflections(cracks, advances)
1025
+ if along:
1026
+ ax.add_collection(LineCollection(along, colors="gold", linewidths=2.2,
1027
+ label="along an interface")) # fmt: skip
1028
+ if len(turns):
1029
+ ax.plot(turns[:, 0], turns[:, 1], "D", color="gold", ms=6, mec="black", mew=0.8,
1030
+ label="deflection") # fmt: skip
1031
+ if ax is right and (along or len(turns)):
1032
+ ax.legend(fontsize=7, loc="lower right", frameon=True)
1033
+ left.set_title(title, fontsize=10)
1034
+ right.set_title(f"the path ({label} of the last crack)", fontsize=10)
1035
+ return fig
1036
+
1037
+
1038
+ def _reach_of(crack) -> float:
1039
+ from morphogen.fracture.mixed import _reach
1040
+
1041
+ return _reach(crack)
1042
+
1043
+
1044
+ def _front_length(crack, lower, upper) -> float:
1045
+ return float(crack.front(lower, upper)[1].sum())
1046
+
1047
+
1048
+ def _auto_stations(crack, size: float, lower, upper) -> int:
1049
+ """As many stations along the front as keep 2.5 elements between them (none below 3)."""
1050
+ length = _front_length(crack, lower, upper)
1051
+ if getattr(crack, "kind", None) == "penny":
1052
+ count = min(16, int(length / (2.5 * size)))
1053
+ return count if count >= 4 else 0
1054
+ count = min(12, int(length / (2.5 * size)) + 1)
1055
+ return count if count >= 3 else 0
1056
+
1057
+
1058
+ def _elastic_twin(material):
1059
+ """The elastic material of an inelastic one (its elastic constants)."""
1060
+ from morphogen.homogenization.materials import Material
1061
+
1062
+ if material.young is not None:
1063
+ return Material(young=material.young, poisson=material.poisson)
1064
+ return Material(stiffness=material.stiffness)
1065
+
1066
+
1067
+ # -- the tools -----------------------------------------------------------------------------------
1068
+
1069
+ _BULK = {"bulk": "homogeneous"}
1070
+
1071
+
1072
+ _MORPHOLOGY = {"bulk": "morphology"}
1073
+
1074
+
1075
+ def _morphology_fields(interfaces: str) -> list[Field]:
1076
+ """The fields of a specimen that is a morphology of the workspace (``interfaces``: the
1077
+ default kind of the interfaces of its crack meshes)."""
1078
+ return [
1079
+ Field("bulk", "choice", "homogeneous", choices=(
1080
+ ("homogeneous", "a homogeneous plate or block"),
1081
+ ("morphology", "a morphology of the workspace: its domain, its phases"))),
1082
+ Field("source", "item", label="morphology", when=_MORPHOLOGY,
1083
+ doc="its domain is the specimen, its phases the bulk"),
1084
+ Field("materials", "materials", of="source", when=_MORPHOLOGY,
1085
+ doc="E and ν of each phase; void phases are pores, left out of the meshes"),
1086
+ Field("phase_kept", "item", label="behaviour of a phase", items=("behaviour",),
1087
+ none="none: the elastic phases above", when=_MORPHOLOGY,
1088
+ doc="a behaviour of the workspace (B: a material point, a Z-set file) given to "
1089
+ "the phase below, with its own elasticity"),
1090
+ Field("kept_phase", "int", 1, label="its phase", when=_MORPHOLOGY),
1091
+ Field("interfaces", "choice", interfaces, choices=INTERFACES, when=_MORPHOLOGY,
1092
+ doc="of the phases on the crack meshes"),
1093
+ ] # fmt: skip
1094
+
1095
+
1096
+ @tool(
1097
+ "crack_factors",
1098
+ "fracture",
1099
+ "Stress intensity factors of a crack",
1100
+ "A crack in a homogeneous plate or block, or in a morphology of the workspace (its phases "
1101
+ "on the crack mesh, conforming to their interfaces or as staircases, its pores left out), "
1102
+ "meshed by MMG conforming to it and opened: "
1103
+ "the factors K_I, K_II and K_III by the interaction integrals and the energy release rate "
1104
+ "G by the G-θ method (Destuynder & Djaoua; the J of Rice on a wider ring), along the "
1105
+ "front at stations or as their means, the angle of kinking (Erdogan & Sih), in small or "
1106
+ "finite strains; an inelastic bulk gives the J of the work density, of the free energy "
1107
+ "and at the tip (configurational forces). The handbook factor of the specimen when it has "
1108
+ "one, and the energy of the body as a check (G = -dΠ/dA).",
1109
+ [
1110
+ *_morphology_fields("staircase"),
1111
+ *_plate_fields(_BULK),
1112
+ *_behaviour_fields(_BULK),
1113
+ *_crack_fields(("edge", "through", "penny")),
1114
+ *_loading_fields(),
1115
+ Field(
1116
+ "stations",
1117
+ "int",
1118
+ doc="points along the front for the profiles of K and G, at least two elements "
1119
+ "apart (blank: as many as fit; 0: the means only)",
1120
+ ),
1121
+ Field(
1122
+ "contact",
1123
+ "bool",
1124
+ False,
1125
+ label="contact of the lips",
1126
+ doc="a penalty: lips closed by compression or shear",
1127
+ ),
1128
+ Field(
1129
+ "friction",
1130
+ "float",
1131
+ 0.0,
1132
+ label="friction of the lips μ",
1133
+ when={"contact": [True]},
1134
+ doc="Coulomb's coefficient: lips in contact stick or slide (0: frictionless); "
1135
+ "linear elements",
1136
+ ),
1137
+ Field(
1138
+ "energy_check",
1139
+ "bool",
1140
+ False,
1141
+ label="energy check",
1142
+ doc="G by the energy of the body for the crack shorter and longer by an element "
1143
+ "(two more solutions; at fixed loads)",
1144
+ ),
1145
+ ],
1146
+ order=1,
1147
+ groups=(
1148
+ ("Specimen", "bulk"),
1149
+ ("Material", "behaviour"),
1150
+ ("Crack", "crack"),
1151
+ ("Loading", "loading"),
1152
+ ("Mesh and integrals", "element_size", True),
1153
+ ),
1154
+ menu="Cracks",
1155
+ )
1156
+ def crack_factors(p: dict, ctx) -> dict:
1157
+ from morphogen.fracture.mixed import energy_release_rate
1158
+
1159
+ ctx.progress(0.02, "specimen")
1160
+ spec = specimen(p)
1161
+ inelastic = any(m.nonlinear for m in spec.materials.values())
1162
+ ctx.progress(0.05, "meshing conforming to the crack (MMG)")
1163
+ mesh = spec.mesh_of(spec.crack)
1164
+ ctx.progress(0.2, f"solving ({mesh.n_elements} tetrahedra)")
1165
+ options = {"kinematics": p["kinematics"], "contact": True if p.get("contact") else None}
1166
+ if p.get("contact") and float(p.get("friction") or 0.0) > 0:
1167
+ options["friction"] = float(p["friction"])
1168
+ solution = spec.solve(mesh=mesh, **options)
1169
+ ctx.progress(0.55, "G-θ and interaction integrals")
1170
+ h = solution.element_size()
1171
+ reach = _reach_of(spec.crack)
1172
+ values: dict = {"elements": mesh.n_elements, "element_size": h, "crack_area": solution.area(),
1173
+ "front_length": _front_length(spec.crack, spec.lower, spec.upper)} # fmt: skip
1174
+ values.update(_morphology_values(spec, solution))
1175
+ modes = solution.modes()
1176
+ young, nu = _isotropic_front(solution)
1177
+ e_prime = young / (1.0 - nu**2)
1178
+ for key in ("K_I", "K_II", "K_III", "G", "G_I", "G_II", "G_III"):
1179
+ values[key] = modes[key]
1180
+ values["kink_angle_deg"] = math.degrees(modes["angle"])
1181
+ r_out = min(8.0 * h, 0.95 * reach)
1182
+ r_in = min(2.0 * h, 0.5 * r_out)
1183
+ energies = ("work", "free", "tip") if inelastic else ("work",)
1184
+ rows = []
1185
+ for k in (2, 3, 4, 6, 8):
1186
+ if k * h > 0.95 * reach:
1187
+ break
1188
+ row = {"r_in": min(h, 0.5 * k * h), "r_out": k * h}
1189
+ for energy in energies:
1190
+ name = "G" if not inelastic else f"J_{energy}"
1191
+ try:
1192
+ row[name] = solution.release_rate(row["r_in"], row["r_out"], energy=energy)
1193
+ except ValueError: # no free energy (MFront)
1194
+ row[name] = math.nan
1195
+ rows.append(row)
1196
+ if inelastic:
1197
+ for energy in energies:
1198
+ try:
1199
+ values[f"J_{energy}"] = solution.release_rate(energy=energy)
1200
+ except ValueError:
1201
+ values[f"J_{energy}"] = math.nan
1202
+ values["J_work_wide_ring"] = solution.release_rate(r_in, r_out, energy="work")
1203
+ else:
1204
+ values["J"] = solution.release_rate(r_in, r_out)
1205
+ values["K_equivalent"] = math.sqrt(max(e_prime * modes["G"], 0.0)) # sqrt(E' G)
1206
+ if spec.handbook is not None:
1207
+ name = spec.handbook["mode"]
1208
+ values[f"{name}_handbook"] = spec.handbook["value"]
1209
+ values[f"{name}_ratio"] = modes[name] / spec.handbook["value"]
1210
+ if p.get("energy_check"):
1211
+ ctx.progress(0.65, "energy check: two more cracks")
1212
+ delta = min(h, 0.5 * reach)
1213
+ values["G_energy"] = energy_release_rate(lambda c: spec.solve(c, **options), spec.crack,
1214
+ delta) # fmt: skip
1215
+ values["G_ratio_energy"] = modes["G"] / values["G_energy"]
1216
+ ctx.progress(0.8, "figures")
1217
+ ctx.table(rows, "domains", "independence of the domain (rings of the G-θ method)")
1218
+ stations = p.get("stations")
1219
+ if stations is None:
1220
+ stations = _auto_stations(spec.crack, h, spec.lower, spec.upper)
1221
+ if stations:
1222
+ try:
1223
+ profile = solution.modes(stations=int(stations))
1224
+ except ValueError as exc:
1225
+ import warnings
1226
+
1227
+ warnings.warn(f"stations: {exc}", stacklevel=2)
1228
+ profile = None
1229
+ if profile is not None:
1230
+ keys = ("K_I", "K_II", "K_III", "G")
1231
+ table = [{"s": float(s), **{k: float(profile[k][i]) for k in keys},
1232
+ "angle_deg": math.degrees(float(profile["angle"][i]))}
1233
+ for i, s in enumerate(profile["s"])] # fmt: skip
1234
+ ctx.table(table, "front", "along the front (s: a length, or an angle on a penny)")
1235
+ ys = {k: profile[k] for k in ("K_I", "K_II", "K_III")}
1236
+ ctx.figure(_curves(profile["s"], ys, "s along the front", "K",
1237
+ "stress intensity factors along the front"), "front") # fmt: skip
1238
+ labels = spec.labels(solution.mesh)
1239
+ names = spec.names if spec.morphology else {}
1240
+ ctx.figure(_rgb(_mesh_figure(solution.mesh, spec.crack, h, spec.lower, spec.upper, names,
1241
+ labels)), "mesh", "mesh conforming to the crack") # fmt: skip
1242
+ field, label = _state_field(solution)
1243
+ ctx.figure(_rgb(_field_figure(solution, spec.crack, h, spec.lower, spec.upper, field, label)),
1244
+ "fields", f"{label} near the front") # fmt: skip
1245
+ lengths = spec.upper - spec.lower
1246
+ if spec.kind == "penny" or lengths[2] > 0.25 * lengths[0]: # a block: a 3D view
1247
+ view = _view3d(solution, field, label)
1248
+ if view is not None:
1249
+ ctx.figure(view, "view3d", f"{label} (3D, cut at the middle of z)")
1250
+ _write_vtu(ctx, "crack", solution, {label.replace(" ", "_"): field, "bulk_phase": labels})
1251
+ text = ""
1252
+ if spec.handbook is not None:
1253
+ name = spec.handbook["mode"]
1254
+ text = (f"{name} = {modes[name]:.5g} against {spec.handbook['value']:.5g} "
1255
+ f"({spec.handbook['source']}): {100 * (values[name + '_ratio'] - 1):+.1f} %. "
1256
+ "Linear tetrahedra without singular elements approach the exact factor from "
1257
+ "below as they shrink at the front; the handbook solution may assume a longer "
1258
+ "strip or an infinite body.") # fmt: skip
1259
+ return {"values": values, "text": text}
1260
+
1261
+
1262
+ def _phase_name(spec, phase: int) -> str:
1263
+ return f"{phase}: {spec.names[phase]}" if phase in spec.names else str(phase)
1264
+
1265
+
1266
+ def _morphology_values(spec, solution) -> dict:
1267
+ """The values of a specimen that is a morphology: the interfaces of its crack meshes,
1268
+ its pores and the phase at the front."""
1269
+ if not spec.morphology:
1270
+ return {}
1271
+ out = {"interfaces": spec.interfaces,
1272
+ "phase_at_front": _phase_name(spec, solution.front_phase())} # fmt: skip
1273
+ if spec.voids:
1274
+ out["pores"] = ", ".join(_phase_name(spec, k) for k in spec.voids)
1275
+ return out
1276
+
1277
+
1278
+ def _isotropic_front(solution) -> tuple[float, float]:
1279
+ """Young's modulus and Poisson's ratio of the material at the front (the Voigt-Reuss-Hill
1280
+ estimate of a crystal), as the interaction integrals take them."""
1281
+ from morphogen.fracture.mixed import _isotropic_moduli
1282
+
1283
+ return _isotropic_moduli(solution.materials[solution.front_phase()])
1284
+
1285
+
1286
+ GROWTHS = (
1287
+ ("fixed", "at a fixed load: an increment per step (Paris' law; elastic bulks)"),
1288
+ ("toughness", "once the driving force at the tip reaches the toughness (G_c, J_tip)"),
1289
+ ("porosity", "once the porosity near the tip reaches a critical value (GTN points)"),
1290
+ )
1291
+ TRANSFERS = (
1292
+ ("nearest", "nearest: the values of the old element (the identity onto the same mesh)"),
1293
+ ("projection", "projection: through the nodes of the old mesh (smoother)"),
1294
+ )
1295
+ _CRITERION = {"growth": ["toughness", "porosity"]}
1296
+
1297
+
1298
+ def _counting_distinct(mesh_of, ctx, steps: int, start: float = 0.05, span: float = 0.8):
1299
+ """``mesh_of`` reporting the progress of a growth, one mesh per new crack; the same
1300
+ crack asked again (an elastic estimate, then the growth) takes the same mesh."""
1301
+ state: dict = {"count": 0, "crack": None, "mesh": None}
1302
+
1303
+ def counted(crack):
1304
+ if state["crack"] is not None and state["crack"] == crack:
1305
+ return state["mesh"]
1306
+ k = min(state["count"], steps)
1307
+ ctx.progress(start + span * k / (steps + 1), f"crack {k} of {steps}: meshing and solving")
1308
+ mesh = mesh_of(crack)
1309
+ state.update(count=state["count"] + 1, crack=crack, mesh=mesh)
1310
+ return mesh
1311
+
1312
+ return counted
1313
+
1314
+
1315
+ def _growth_outputs(ctx, lower, upper, size, cracks, solutions, captions, title: str,
1316
+ names=None, advances=None) -> None: # fmt: skip
1317
+ """The figures, video and file of a growth: the path over the last field (and over the
1318
+ phases of a morphology, with the ``names`` of its phases; the deflections along
1319
+ interfaces of the ``advances`` of a toughness), the frames of every crack (the interfaces
1320
+ of the phases outlined), the opened mesh of the last one."""
1321
+ ctx.figure(_rgb(_growth_figure(solutions[-1], cracks, size, lower, upper, title, names,
1322
+ advances)), "path", "crack path") # fmt: skip
1323
+ ctx.progress(0.92, "video of the growth")
1324
+ frames = _growth_frames(solutions, lower, upper, captions, outlines=names is not None)
1325
+ ctx.video(frames, "growth", "the growth, crack by crack", fps=1.5, mode="loop")
1326
+ field, label = _state_field(solutions[-1])
1327
+ fields = {label.replace(" ", "_"): field}
1328
+ if names is not None:
1329
+ fields["bulk_phase"] = solutions[-1].mesh.phase
1330
+ _write_vtu(ctx, "last_crack", solutions[-1], fields)
1331
+
1332
+
1333
+ @tool(
1334
+ "crack_growth",
1335
+ "fracture",
1336
+ "Crack propagation",
1337
+ "A straight crack in a homogeneous plate, or in a morphology of the workspace (its phases "
1338
+ "on the crack meshes, conforming to their interfaces or as staircases, with the materials "
1339
+ "of its phases; its void phases, the pores, left out), grows on meshes rebuilt by MMG at "
1340
+ "each advance, kinking in the direction of the largest hoop stress (Erdogan & Sih) by the "
1341
+ "factors of the interaction integrals (on the material at the front, the auxiliary fields "
1342
+ "of its moduli): deflected by stiff inclusions, attracted by soft ones and pores, through "
1343
+ "which it runs: at a fixed load, an increment per step (Paris' law counts the "
1344
+ "cycles, Griffith's criterion gives the critical load of each length), or, the load raised "
1345
+ "by steps, once the driving force at the tip reaches the toughness (G of an elastic bulk, "
1346
+ "J_tip of an inelastic one: von Mises elasto-viscoplasticity, GTN; MFront laws have no free "
1347
+ "energy, hence no J_tip) or the porosity of the GTN points near the tip a critical value "
1348
+ "(ductile growth), the state of the points "
1349
+ "carried from mesh to mesh. Through a morphology, a toughness for each phase and for the "
1350
+ "interfaces between them makes each advance the candidate of the largest G(θ) / Γ(θ): the "
1351
+ "kink of the bulk, against the toughness of the phase met, or along an interface within "
1352
+ "an increment ahead (the first-order kinked factors of Cotterell & Rice): deflected along "
1353
+ "weak interfaces (He & Hutchinson), through which it follows a brick-and-mortar, and held "
1354
+ "back by tough phases (the critical load of each advance). The path (over the phases of a "
1355
+ "morphology, its deflections marked), the loads and "
1356
+ "driving forces of each advance, the resistance curve (J_far = J_ψ on a ring around the "
1357
+ "front, Simha et al. 2008, with the configurational forces of the inclusions and pores in "
1358
+ "it) and a video of the growth.",
1359
+ [
1360
+ *_morphology_fields("conforming"),
1361
+ Field(
1362
+ "slab",
1363
+ "float",
1364
+ unit="length",
1365
+ when=_MORPHOLOGY,
1366
+ doc="the thickness of the slab of the morphology about the middle of z, in plane "
1367
+ "strain: the path that of its section (blank: the whole depth, at most a "
1368
+ "sixteenth of the width)",
1369
+ ),
1370
+ *_plate_fields(_BULK, penny=False),
1371
+ *_behaviour_fields(_BULK),
1372
+ *_crack_fields(("edge", "through")),
1373
+ *_loading_fields(LOADINGS[:3]),
1374
+ Field("growth", "choice", "fixed", choices=GROWTHS),
1375
+ Field("steps", "int", doc="advances of the front (blank: 3, or 6 through a morphology)"),
1376
+ Field(
1377
+ "increment",
1378
+ "float",
1379
+ unit="length",
1380
+ doc="advance of the front at each step (blank: 1.5 elements)",
1381
+ ),
1382
+ Field(
1383
+ "kink",
1384
+ "bool",
1385
+ True,
1386
+ when=_CRITERION,
1387
+ doc="in the direction of the largest hoop stress (Erdogan & Sih), else straight",
1388
+ ),
1389
+ Field(
1390
+ "paris_C",
1391
+ "float",
1392
+ label="Paris' C",
1393
+ when={"growth": "fixed"},
1394
+ doc="da/dN = C ΔK^m with ΔK = sqrt(E' G) at the load (blank: no cycles)",
1395
+ ),
1396
+ Field("paris_m", "float", 3.0, label="Paris' m", when={"growth": "fixed"}),
1397
+ Field(
1398
+ "toughness",
1399
+ "float",
1400
+ unit="energy / area",
1401
+ when={"growth": ["fixed", "toughness"]},
1402
+ doc="G_c of an elastic bulk, J_tip of an inelastic one; at a fixed load, the "
1403
+ "critical load of each length is sqrt(G_c / G) (blank: none); by the toughness, "
1404
+ "blank: 1.2 times the elastic G of the first crack at the load factor 1",
1405
+ ),
1406
+ Field("critical_porosity", "float", when={"growth": "porosity"}, doc="blank: 1.05 f0"),
1407
+ Field(
1408
+ "radius",
1409
+ "float",
1410
+ unit="length",
1411
+ when={"growth": "porosity"},
1412
+ doc="the points within this distance of the front (blank: 1.5 element)",
1413
+ ),
1414
+ Field(
1415
+ "load_step",
1416
+ "float",
1417
+ 0.25,
1418
+ when=_CRITERION,
1419
+ doc="of the load factor between the checks of the criterion",
1420
+ ),
1421
+ Field("max_load", "float", 4.0, when=_CRITERION, doc="the loading stops there"),
1422
+ Field(
1423
+ "transfer",
1424
+ "choice",
1425
+ "nearest",
1426
+ choices=TRANSFERS,
1427
+ when=_CRITERION,
1428
+ doc="of the state of the points onto the mesh of the next crack",
1429
+ ),
1430
+ Field(
1431
+ "contact",
1432
+ "bool",
1433
+ False,
1434
+ label="contact of the lips",
1435
+ doc="a penalty 50 E / h",
1436
+ ),
1437
+ Field(
1438
+ "friction",
1439
+ "float",
1440
+ 0.0,
1441
+ label="friction of the lips μ",
1442
+ when={"contact": [True], "growth": ["fixed"]},
1443
+ doc="Coulomb's coefficient: lips in contact stick or slide (0: frictionless)",
1444
+ ),
1445
+ Field(
1446
+ "toughness_phases",
1447
+ "floats",
1448
+ label="toughness of the phases",
1449
+ unit="energy / area",
1450
+ when={**_MORPHOLOGY, "growth": ["fixed", "toughness"]},
1451
+ doc="Γ of each phase of the morphology, in the order of its phases (0, 1, ...; the "
1452
+ "void phases may be left out): the advance into the bulk meets that of the "
1453
+ "toughest phase along it, and an elastic crack grows at sqrt(Γ / G), so that tough "
1454
+ "phases hold it back (blank: the toughness for all the phases)",
1455
+ ),
1456
+ Field(
1457
+ "interface_toughness",
1458
+ "float",
1459
+ label="toughness of the interfaces",
1460
+ unit="energy / area",
1461
+ when={**_MORPHOLOGY, "growth": ["fixed", "toughness"]},
1462
+ doc="Γ of the interfaces between the phases: where an interface lies within an "
1463
+ "increment ahead of the front, the crack goes along it when its G(θ) / Γ is larger "
1464
+ "than that of the bulk (a crack normal to the interface of two alike phases "
1465
+ "deflects below Γ / Γ_bulk = 1/4, He & Hutchinson 1989; blank: no interface "
1466
+ "criterion, the crack crosses the interfaces by the kink of the bulk)",
1467
+ ),
1468
+ ],
1469
+ order=2,
1470
+ groups=(
1471
+ ("Specimen", "bulk"),
1472
+ ("Material", "behaviour"),
1473
+ ("Crack", "crack"),
1474
+ ("Loading", "loading"),
1475
+ ("Growth", "growth"),
1476
+ ),
1477
+ menu="Cracks",
1478
+ )
1479
+ def crack_growth(p: dict, ctx) -> dict:
1480
+ from morphogen.fracture.ductile import propagate_ductile
1481
+ from morphogen.fracture.mixed import propagate_kinked
1482
+
1483
+ ctx.progress(0.01, "specimen")
1484
+ spec = specimen(p, slab=True)
1485
+ solids = spec.solids()
1486
+ growth, steps = p["growth"], p.get("steps")
1487
+ steps = int(steps) if steps is not None else 6 if spec.morphology else 3
1488
+ if steps < 1:
1489
+ raise ValueError("steps: at least one advance")
1490
+ if growth == "fixed" and any(m.nonlinear for m in solids):
1491
+ raise ValueError("a fixed load: an elastic bulk (an inelastic one grows by its toughness "
1492
+ "or its porosity, its state carried along)") # fmt: skip
1493
+ if growth == "porosity" and not any(m.porous for m in solids):
1494
+ if spec.morphology:
1495
+ raise ValueError("porosity: a porous bulk, not the elastic phases of a morphology")
1496
+ raise ValueError("porosity: a porous bulk (behaviour: porous plasticity)")
1497
+ increment = float(p.get("increment") or 1.5 * spec.size)
1498
+ if not increment > 0:
1499
+ raise ValueError("increment: positive")
1500
+ mesh_of = _counting_distinct(spec.mesh_of, ctx, steps)
1501
+ contact = 50.0 * spec.young / spec.size if p.get("contact") else None
1502
+ kinematics = p["kinematics"]
1503
+ values: dict = {"increment": increment, "element_size": spec.size}
1504
+ advances = None # chosen by a toughness of the phases and of their interfaces
1505
+ if growth == "fixed":
1506
+ paris = (float(p["paris_C"]), float(p["paris_m"])) if p.get("paris_C") else None
1507
+ toughness = p.get("toughness")
1508
+ rule = _toughness_of(p, spec, toughness)
1509
+ if rule is not None and rule.uniform: # one value for all the phases: as without
1510
+ toughness, rule = rule.value, None
1511
+ rubbing = {}
1512
+ if contact and float(p.get("friction") or 0.0) > 0:
1513
+ rubbing["friction"] = float(p["friction"])
1514
+ result = propagate_kinked(mesh_of, spec.crack, spec.materials, spec.prescribed, 1.0,
1515
+ increment=increment, steps=steps, kinematics=kinematics,
1516
+ paris=paris, contact=contact, toughness=rule, keep=True,
1517
+ forces=spec.forces, **rubbing) # fmt: skip
1518
+ rows = result.rows()
1519
+ for row in rows:
1520
+ row.pop("z_tip", None)
1521
+ if paris is None:
1522
+ row.pop("N", None)
1523
+ if toughness and rule is None:
1524
+ row["load_critical"] = math.sqrt(toughness / row["G"]) if row["G"] > 0 else math.nan
1525
+ cracks, solutions = result.cracks, result.solutions
1526
+ captions = [f"crack {k}: a = {c.size:.3g}, G = {g:.3g}"
1527
+ for k, (c, g) in enumerate(zip(cracks, result.rates, strict=True))] # fmt: skip
1528
+ _tip_phases(spec, rows, solutions, captions)
1529
+ ctx.table(rows, "advances", "the cracks: lengths, tips, factors, kinks")
1530
+ lengths = np.array([c.size for c in cracks])
1531
+ lines = {"G_c": toughness} if toughness and rule is None else None
1532
+ twin = ("cycles N", result.cycles) if paris is not None else None
1533
+ ctx.figure(_curves(lengths, {"G": result.rates}, "crack length", "G",
1534
+ "energy release rate along the growth", lines=lines, twin=twin),
1535
+ "release_rate", "G along the growth") # fmt: skip
1536
+ values.update(final_length=cracks[-1].size, G_first=float(result.rates[0]),
1537
+ G_last=float(result.rates[-1]),
1538
+ kink_first_deg=math.degrees(float(result.angles[0]))) # fmt: skip
1539
+ if paris is not None:
1540
+ values["cycles"] = float(result.cycles[-1])
1541
+ if rule is not None:
1542
+ advances = result.advances
1543
+ _toughness_outputs(values, spec, rule, cracks, advances)
1544
+ ctx.figure(_curves(lengths, {"critical load": result.loads}, "crack length",
1545
+ "load factor", "the critical load of each crack, sqrt(Γ / G) of "
1546
+ "its advance"), "critical_load", "critical loads") # fmt: skip
1547
+ values["load_critical_first"] = float(result.loads[0])
1548
+ values["load_critical_largest"] = float(np.max(result.loads))
1549
+ else:
1550
+ toughness = porosity = rule = None
1551
+ if growth == "toughness":
1552
+ toughness = p.get("toughness")
1553
+ if toughness is None and not p.get("toughness_phases"): # the elastic G at the tip
1554
+ ctx.progress(0.03, "the elastic G of the first crack")
1555
+ twins = {k: m if m.void else _elastic_twin(m) for k, m in spec.materials.items()}
1556
+ first = spec.solve(spec.crack, mesh_of(spec.crack), twins, kinematics=kinematics)
1557
+ toughness = 1.2 * first.release_rate(energy="tip")
1558
+ rule = _toughness_of(p, spec, toughness)
1559
+ if rule is not None and rule.uniform: # one value for all the phases: as without
1560
+ toughness, rule = rule.value, None
1561
+ if toughness is not None:
1562
+ values["toughness"] = toughness
1563
+ else:
1564
+ porosity = p.get("critical_porosity")
1565
+ if porosity is None:
1566
+ porous = next(m for m in solids if m.porous)
1567
+ porosity = 1.05 * porous.porous_plasticity.porosity
1568
+ values["critical_porosity"] = porosity
1569
+ result = propagate_ductile(mesh_of, spec.crack, spec.materials, spec.prescribed,
1570
+ load_step=float(p["load_step"]), increment=increment,
1571
+ steps=steps, porosity=porosity,
1572
+ toughness=toughness if rule is None else rule,
1573
+ max_load=float(p["max_load"]), kinematics=kinematics,
1574
+ transfer=p["transfer"], radius=p.get("radius"),
1575
+ forces=spec.forces, contact=contact, kink=bool(p["kink"]),
1576
+ keep=True) # fmt: skip
1577
+ cracks, solutions = result.cracks, result.solutions
1578
+ rows = result.rows()
1579
+ for row, c in zip(rows, cracks, strict=True):
1580
+ row["x_tip"], row["y_tip"] = float(c.tip[0]), float(c.tip[1])
1581
+ captions = [f"advance {k}: load {lam:.3g}, J_tip {jt:.3g}" for k, (lam, jt) in
1582
+ enumerate(zip(result.loads, result.tip, strict=True))] # fmt: skip
1583
+ _tip_phases(spec, rows, solutions, captions)
1584
+ ctx.table(rows, "advances", "the advances: loads, driving forces, factors, kinks")
1585
+ ctx.table(result.history, "loading", "every load step: driving forces, porosity at the tip")
1586
+ last = result.history[-1]
1587
+ if rule is not None: # the ratio G(θ) / Γ(θ) of the advance
1588
+ broken = last.get("ratio", 0.0) >= 1.0
1589
+ else:
1590
+ broken = toughness is not None and last["J_tip"] >= toughness
1591
+ met = broken or (porosity is not None and last["porosity_tip"] >= porosity)
1592
+ values.update(advances=len(cracks) - 1, final_length=cracks[-1].size,
1593
+ last_load=float(result.loads[-1]),
1594
+ stopped="after the last step" if met else "at the maximum load") # fmt: skip
1595
+ delta, far = result.resistance()
1596
+ ys = {"J_far (J_ψ, ring)": far, "J_tip": result.tip, "J_work": result.work}
1597
+ if result.advances: # the toughness met by each advance
1598
+ ys["Γ of the advance"] = np.array([a.toughness for a in result.advances])
1599
+ lines = {"toughness": toughness} if toughness is not None and rule is None else None
1600
+ curve = _curves(delta, ys, "crack advance Δa", "driving force", "resistance curve",
1601
+ lines=lines, twin=("load factor", result.loads)) # fmt: skip
1602
+ ctx.figure(curve, "resistance", "R-curve")
1603
+ loads = np.array([h["load"] for h in result.history])
1604
+ if result.advances:
1605
+ key, limit = "ratio", {"G(θ) / Γ(θ) = 1": 1.0}
1606
+ elif porosity is None:
1607
+ key, limit = "J_tip", {"toughness": toughness}
1608
+ else:
1609
+ key, limit = "porosity_tip", {"critical": porosity}
1610
+ trace = np.array([h[key] for h in result.history])
1611
+ ctx.figure(_curves(np.arange(len(loads)), {key: trace}, "load step", key,
1612
+ "the criterion at each load step", lines=limit,
1613
+ twin=("load factor", loads)), "loading", "criterion") # fmt: skip
1614
+ if result.advances:
1615
+ advances = result.advances
1616
+ _toughness_outputs(values, spec, rule, cracks, advances)
1617
+ values["cracks"] = len(cracks)
1618
+ if spec.morphology:
1619
+ values.update(_morphology_values(spec, solutions[-1]))
1620
+ values["phases_at_tips"] = " / ".join(str(row["phase"]) for row in rows)
1621
+ values["largest_kink_deg"] = max(abs(row["angle_deg"]) for row in rows)
1622
+ values["tip_deflection"] = float(cracks[-1].tip[1] - cracks[0].tip[1])
1623
+ names = spec.names if spec.morphology else None
1624
+ _growth_outputs(ctx, spec.lower, spec.upper, spec.size, cracks, solutions, captions,
1625
+ f"{len(cracks)} cracks: the path", names, advances) # fmt: skip
1626
+ return {"values": values}
1627
+
1628
+
1629
+ def _toughness_of(p: dict, spec, toughness):
1630
+ """The toughness of the phases and of their interfaces of the form (the fields
1631
+ ``toughness_phases``, in the order of the phases, and ``interface_toughness``;
1632
+ ``toughness``: that of every phase when the form gives none per phase), or None when it
1633
+ gives neither (one toughness for the whole body, the growth without interfaces). The
1634
+ interfaces are those of the crack meshes (conforming), or of the image of the
1635
+ morphology (staircases)."""
1636
+ from morphogen.fracture.toughness import Toughness
1637
+
1638
+ given, interface = p.get("toughness_phases"), p.get("interface_toughness")
1639
+ if not spec.morphology or (not given and interface is None):
1640
+ return None
1641
+ phases = sorted(spec.materials)
1642
+ solid = [k for k in phases if not spec.materials[k].void]
1643
+ if given:
1644
+ if len(given) == len(phases):
1645
+ table = {k: float(v) for k, v in zip(phases, given, strict=True) if k in solid}
1646
+ elif len(given) == len(solid):
1647
+ table = {k: float(v) for k, v in zip(solid, given, strict=True)}
1648
+ else:
1649
+ raise ValueError(f"toughness of the phases: one value per phase, in the order of "
1650
+ f"the phases {', '.join(map(str, phases))}") # fmt: skip
1651
+ elif toughness is None:
1652
+ raise ValueError("toughness of the interfaces: a toughness of the phases too (the "
1653
+ "toughness, or the toughness of the phases)") # fmt: skip
1654
+ else:
1655
+ table = dict.fromkeys(solid, float(toughness))
1656
+ morphology = spec.mesh_of.phase_of if spec.interfaces == "staircase" else None
1657
+ return Toughness(table, interface, morphology=morphology)
1658
+
1659
+
1660
+ def _toughness_outputs(values: dict, spec, rule, cracks, advances) -> None:
1661
+ """The values of a growth by a toughness of the phases and of their interfaces: that of
1662
+ each phase and of the interfaces, the advances along interfaces and the deflections into
1663
+ them, the length of the path against its extent along the first direction."""
1664
+ values["toughness_phases"] = ", ".join(f"{_phase_name(spec, k)}: {v:.4g}"
1665
+ for k, v in sorted(rule.phases.items())) # fmt: skip
1666
+ if rule.interfaces is not None:
1667
+ values["interface_toughness"] = rule.interfaces
1668
+ taken = advances[: len(cracks) - 1]
1669
+ values["along_interfaces"] = sum(a.kind == "interface" for a in taken)
1670
+ values["deflections"] = len(_deflections(cracks, advances)[1])
1671
+ first = cracks[0]
1672
+ direction = np.asarray(first.points[-1]) - np.asarray(first.points[-2])
1673
+ direction /= np.linalg.norm(direction)
1674
+ reach = float((np.asarray(cracks[-1].tip) - np.asarray(first.tip)) @ direction)
1675
+ values["path_length"] = float(cracks[-1].size - first.size)
1676
+ values["path_extent"] = reach
1677
+
1678
+
1679
+ def _tip_phases(spec, rows, solutions, captions) -> None:
1680
+ """The phase at the front of each crack of a growth through a morphology, in the rows of
1681
+ its table and the captions of its frames."""
1682
+ if not spec.morphology:
1683
+ return
1684
+ for k, (row, solution) in enumerate(zip(rows, solutions, strict=True)):
1685
+ phase = solution.front_phase()
1686
+ row["phase"] = phase
1687
+ captions[k] = f"{captions[k]}, tip in {_phase_name(spec, phase)}"
1688
+
1689
+
1690
+ # -- cohesive zones ------------------------------------------------------------------------------
1691
+
1692
+ COHESIVE_SPECIMENS = (
1693
+ ("ligament", "a notched plate: a cohesive ligament ahead of the notch, pulled by its grips"),
1694
+ ("interfaces", "a morphology of the workspace: the interfaces of its phases or its grain "
1695
+ "boundaries, in tension along y"),
1696
+ ("dcb", "a double cantilever beam (mode I), against the corrected beam theory"),
1697
+ ) # fmt: skip
1698
+ LAWS = (
1699
+ ("bilinear", "bilinear (Camanho & Dávila; Benzeggagh-Kenane mixity)"),
1700
+ ("exponential", "exponential (Ortiz & Pandolfi)"),
1701
+ )
1702
+ _PLATES = {"specimen": ["ligament", "dcb"]}
1703
+
1704
+
1705
+ def _cubic(p: dict, plastic: bool = False):
1706
+ """The cubic crystal of the form (its crystal plasticity, Méric-Cailletaud, with
1707
+ ``plastic``)."""
1708
+ import dataclasses
1709
+
1710
+ from morphogen.homogenization.crystal import CrystalPlasticity
1711
+ from morphogen.homogenization.materials import Material
1712
+
1713
+ crystal = Material.cubic(float(p["c11"]), float(p["c12"]), float(p["c44"]))
1714
+ if not plastic:
1715
+ return crystal
1716
+ slip = CrystalPlasticity.from_config({"families": p.get("families") or ["octahedral"],
1717
+ "tau0": p["tau0"], "Q": p["Q"], "b": p["b"],
1718
+ "K": p["K"], "n": p["n"]}) # fmt: skip
1719
+ return dataclasses.replace(crystal, crystal_plasticity=slip)
1720
+
1721
+
1722
+ def _crystal_fields(when: dict | None = None) -> list[Field]:
1723
+ return [
1724
+ Field("c11", "float", 168e3, label="C11", unit="stress", when=when,
1725
+ doc="cubic crystal (copper, MPa)"),
1726
+ Field("c12", "float", 121e3, label="C12", unit="stress", when=when),
1727
+ Field("c44", "float", 75e3, label="C44", unit="stress", when=when),
1728
+ ] # fmt: skip
1729
+
1730
+
1731
+ def _law(p: dict, young: float, size: float, beam: bool = False):
1732
+ """The traction-separation law of the form; blank values scaled by the stiffest Young's
1733
+ modulus E and the element size h: strengths E / 100, energies giving a cohesive zone of
1734
+ four elements (G = 4 h N² / E), a penalty 100 E / h; for the beam, the strength E / 200
1735
+ and the energy E / 2000 (the case checked against the beam theory: a zone of 20 elements
1736
+ of 1 for E = 1000)."""
1737
+ from morphogen.fracture.cohesive import Bilinear, Exponential
1738
+
1739
+ strength = young / (200.0 if beam else 100.0)
1740
+
1741
+ def energy_of(n):
1742
+ return young / 2000.0 if beam else 4.0 * size * n**2 / young
1743
+
1744
+ if p["law"] == "exponential":
1745
+ sigma = p.get("strength") or strength
1746
+ return Exponential(strength=sigma, energy=p.get("energy") or energy_of(sigma),
1747
+ beta=float(p.get("beta") or 1.0)) # fmt: skip
1748
+ n = p.get("normal_strength") or strength
1749
+ s = p.get("shear_strength") or n
1750
+ g1 = p.get("mode_I") or energy_of(n)
1751
+ g2 = p.get("mode_II") or g1 * (s / n) ** 2
1752
+ k = p.get("stiffness") or 100.0 * young / size
1753
+ return Bilinear(k, n, s, g1, g2, float(p.get("eta") or 2.0)) # fmt: skip
1754
+
1755
+
1756
+ def _law_values(law) -> tuple[float, float, float]:
1757
+ """The mode I strength, fracture energy and separation at failure of a law."""
1758
+ if hasattr(law, "normal_strength"):
1759
+ return law.normal_strength, law.mode_I, 2.0 * law.mode_I / law.normal_strength
1760
+ return law.strength, law.energy, 10.0 * law.critical_opening
1761
+
1762
+
1763
+ def _damage_now(law, mesh, faces, u) -> np.ndarray:
1764
+ """The damage of each interface element (its mean separation) under the displacement
1765
+ ``u`` from an intact history: the damage of a monotonic opening, for the frames."""
1766
+ from morphogen.fracture.cohesive import traction
1767
+
1768
+ x = mesh.nodes[faces.minus]
1769
+ normal = np.cross(x[:, 1] - x[:, 0], x[:, 2] - x[:, 0])
1770
+ normal /= np.maximum(np.linalg.norm(normal, axis=1, keepdims=True), 1e-300)
1771
+ jump = (u[faces.plus] - u[faces.minus]).mean(axis=1)
1772
+ dn = np.einsum("ij,ij->i", jump, normal)
1773
+ ds = np.linalg.norm(jump - dn[:, None] * normal, axis=1)
1774
+ out = np.empty(len(dn))
1775
+ for e in range(len(dn)):
1776
+ _, h = traction(law, (dn[e], ds[e], 0.0), 0.0)
1777
+ out[e] = h
1778
+ if not hasattr(law, "normal_strength"): # exponential: the history is the largest opening
1779
+ out = 1.0 - np.exp(-out / law.critical_opening)
1780
+ return np.clip(out, 0.0, 1.0)
1781
+
1782
+
1783
+ def _interface_segments(mesh, faces, u, scale: float, at: float):
1784
+ """The traces of the interface elements (their faces of side -) on the plane z = ``at``,
1785
+ in the configuration ``x + scale u``: segments (n x 2 x 2) and the element of each."""
1786
+ return _traces(mesh.nodes, faces.minus, mesh.nodes + scale * u, at)
1787
+
1788
+
1789
+ def _traces(nodes, tri, moved, at: float):
1790
+ """The traces of triangles (rows of three nodes) on the plane z = ``at`` of the positions
1791
+ ``nodes``, drawn at the positions ``moved``: segments (n x 2 x 2) and the triangle of
1792
+ each."""
1793
+ tri = np.asarray(tri, dtype=np.int64).reshape(-1, 3)
1794
+ d = nodes[tri, 2] - at
1795
+ positive = d > 0
1796
+ count = positive.sum(axis=1)
1797
+ rows = np.flatnonzero((count == 1) | (count == 2))
1798
+ if not len(rows):
1799
+ return np.zeros((0, 2, 2)), rows
1800
+ lone = np.where(count[rows] == 1, np.argmax(positive[rows], axis=1),
1801
+ np.argmin(positive[rows], axis=1)) # fmt: skip
1802
+ ends = []
1803
+ for shift in (1, 2):
1804
+ other = (lone + shift) % 3
1805
+ a, b = tri[rows, lone], tri[rows, other]
1806
+ da, db = d[rows, lone], d[rows, other]
1807
+ t = (da / (da - db))[:, None]
1808
+ ends.append((moved[a] + t * (moved[b] - moved[a]))[:, :2])
1809
+ return np.stack(ends, axis=1), rows
1810
+
1811
+
1812
+ def _phase_faces(mesh, lips=None) -> np.ndarray:
1813
+ """The faces (rows of three nodes) of the interfaces between the phases of a mesh and of
1814
+ the walls of its pores (its free faces off its box and off the ``lips`` of its crack)."""
1815
+ from morphogen.fracture.lefm import boundary_faces
1816
+ from morphogen.mesh.tetra import TET_FACES
1817
+
1818
+ tets = mesh.elements[:, :4]
1819
+ faces = tets[:, TET_FACES].reshape(-1, 3)
1820
+ owner = np.repeat(np.arange(mesh.n_elements), 4)
1821
+ keys = np.sort(faces, axis=1)
1822
+ order = np.lexsort(keys.T[::-1])
1823
+ same = np.all(keys[order][1:] == keys[order][:-1], axis=1)
1824
+ a, b = order[:-1][same], order[1:][same]
1825
+ between = faces[a][mesh.phase[owner[a]] != mesh.phase[owner[b]]]
1826
+ free = boundary_faces(mesh)
1827
+ x, tol = mesh.nodes[free], mesh.tolerance()
1828
+ wall = np.ones(len(free), dtype=bool)
1829
+ for axis in range(3):
1830
+ for value in (mesh.lower[axis], mesh.upper[axis]):
1831
+ wall &= ~np.all(np.abs(x[:, :, axis] - value) <= tol, axis=1)
1832
+ if lips is not None and lips.n_elements:
1833
+ crack = {tuple(k) for k in np.sort(np.vstack([lips.minus, lips.plus]), axis=1).tolist()}
1834
+ wall &= ~np.array([tuple(k) in crack for k in np.sort(free, axis=1).tolist()], dtype=bool)
1835
+ return np.vstack([between, free[wall]])
1836
+
1837
+
1838
+ def _outlines(solution, scale: float = 0.0, faces=None):
1839
+ """The traces on the mid-plane z of the interfaces of the phases and of the walls of the
1840
+ pores of a solved body (``faces``: those of :func:`_phase_faces`), in the configuration
1841
+ ``x + scale u``: segments (n x 2 x 2)."""
1842
+ mesh = solution.mesh
1843
+ faces = _phase_faces(mesh, solution.faces) if faces is None else faces
1844
+ at = 0.5 * (mesh.nodes[:, 2].min() + mesh.nodes[:, 2].max())
1845
+ moved = mesh.nodes + scale * np.asarray(solution.displacement).reshape(-1, 3)
1846
+ return _traces(mesh.nodes, faces, moved, at)[0]
1847
+
1848
+
1849
+ def _cohesive_figure(mesh, faces, u, damage, scale, title, window=None, *, colorbar=True,
1850
+ size=(6.4, 5.0)): # fmt: skip
1851
+ """The deformed mid-section of a body with cohesive interfaces: the bulk in grey, the
1852
+ traces of the interfaces coloured by their damage."""
1853
+ from matplotlib.collections import LineCollection
1854
+
1855
+ fig = _canvas(*size)
1856
+ ax = fig.subplots()
1857
+ labels = mesh.cell if mesh.cell is not None else mesh.phase
1858
+ _draw_section(ax, mesh, np.zeros(mesh.n_elements) if mesh.cell is None else labels,
1859
+ displacement=u, scale=scale, cmap=_labels_cmap(1), colorbar=False,
1860
+ window=window) # fmt: skip
1861
+ at = 0.5 * (mesh.nodes[:, 2].min() + mesh.nodes[:, 2].max())
1862
+ segments, rows = _interface_segments(mesh, faces, u, scale, at)
1863
+ lines = LineCollection(segments, array=np.asarray(damage)[rows], cmap="inferno_r",
1864
+ linewidths=1.8) # fmt: skip
1865
+ lines.set_clim(0.0, 1.0)
1866
+ ax.add_collection(lines)
1867
+ if colorbar:
1868
+ fig.colorbar(lines, ax=ax, shrink=0.85, label="damage of the interfaces")
1869
+ ax.set_title(title, fontsize=9)
1870
+ return fig
1871
+
1872
+
1873
+ def _report_newton(problem, ctx, load: float, start: float = 0.1, span: float = 0.8) -> None:
1874
+ """Report the load factor of each step of a cohesive problem as its progress (the load
1875
+ factor is an argument of its Newton solver; nothing is reported if it changes)."""
1876
+ newton = problem._newton
1877
+
1878
+ def reported(*args, **kwargs):
1879
+ target = args[5] if len(args) > 5 else kwargs.get("target")
1880
+ if isinstance(target, float):
1881
+ ctx.progress(start + span * min(target / load, 1.0),
1882
+ f"load factor {target:.4g} of {load:.4g}") # fmt: skip
1883
+ return newton(*args, **kwargs)
1884
+
1885
+ problem._newton = reported
1886
+
1887
+
1888
+ def _box_mesh(lower, upper, size: float, plane_y=None):
1889
+ """Six tetrahedra per voxel of the box (about ``size``; ``plane_y`` on the faces of the
1890
+ voxels)."""
1891
+ from morphogen.homogenization.bloch import voxel_tet_mesh
1892
+ from morphogen.image import VoxelImage
1893
+
1894
+ lengths = np.asarray(upper, dtype=float) - np.asarray(lower, dtype=float)
1895
+ shape = np.maximum(1, np.rint(lengths / size)).astype(int)
1896
+ if plane_y is not None: # an even count along y, the plane on a layer of faces
1897
+ below = max(1, round((plane_y - lower[1]) / size))
1898
+ above = max(1, round((upper[1] - plane_y) / size))
1899
+ if not np.isclose((plane_y - lower[1]) / below, (upper[1] - plane_y) / above):
1900
+ raise ValueError("the plane of the ligament: on a layer of voxel faces (its height "
1901
+ "a multiple of the element size)") # fmt: skip
1902
+ shape[1] = below + above
1903
+ image = VoxelImage(np.zeros(tuple(shape), np.uint8), spacing=tuple(lengths / shape),
1904
+ origin=tuple(lower), periodic=False) # fmt: skip
1905
+ return voxel_tet_mesh(image)
1906
+
1907
+
1908
+ def _morphology_mesh(micro, size: float, grains: bool):
1909
+ """A mesh of a morphology conforming to its phases (MMG) or grains (a tessellation, cut
1910
+ by its box), its curved interfaces followed coarsely (a Hausdorff distance of h / 5,
1911
+ elements of h / 3 at least: every interface element is a cohesive one; the regularized
1912
+ cells of tessellations: on the grid, not exact); without a level set, six tetrahedra per
1913
+ voxel of its image (the cells of its labels as grains)."""
1914
+ from morphogen.homogenization.bloch import voxel_tet_mesh
1915
+ from morphogen.mesh.conforming import conforming_mesh
1916
+ from morphogen.mesh.tetra import TetMesh
1917
+
1918
+ tessellation = hasattr(micro, "cell_of") and not getattr(micro, "boundary_thickness", 0)
1919
+ if grains and not tessellation:
1920
+ raise ValueError("grain boundaries: a Voronoi or Laguerre tessellation (without a "
1921
+ "grain-boundary phase)") # fmt: skip
1922
+ coarse = {"size": size, "hausdorff": size / 5.0, "min_size": size / 3.0, "periodic": False,
1923
+ "method": "grid"} # fmt: skip
1924
+ try:
1925
+ if grains:
1926
+ return conforming_mesh(micro, cells="box", **coarse)
1927
+ return conforming_mesh(micro, grains=False, **coarse)
1928
+ except ValueError as exc: # no level set: the voxels
1929
+ if "level-set" not in str(exc):
1930
+ raise
1931
+ image = micro.voxelize(voxel_size=size)
1932
+ mesh = voxel_tet_mesh(image)
1933
+ if grains:
1934
+ cells = np.asarray(micro.labels(grid=image.grid()).data).ravel()
1935
+ mesh = TetMesh(mesh.nodes, mesh.elements, mesh.phase, mesh.lower, mesh.upper,
1936
+ cell=np.tile(cells, 6), orientations=micro.orientations) # fmt: skip
1937
+ return mesh
1938
+
1939
+
1940
+ @tool(
1941
+ "cohesive_zones",
1942
+ "fracture",
1943
+ "Cohesive zones",
1944
+ "Cohesive interface elements (six nodes, zero thickness) inserted along given surfaces "
1945
+ "and loaded by the displacement of grips, in small or finite strains: the ligament ahead "
1946
+ "of the notch of a plate, the interfaces of the phases of a morphology (debonding) or the "
1947
+ "grain boundaries of a tessellation (intergranular cracking), or a double cantilever beam "
1948
+ "against the corrected beam theory. Traction-separation laws: bilinear (Camanho & Dávila, "
1949
+ "Turon et al.) or exponential (Ortiz & Pandolfi), the instabilities passed by the viscous "
1950
+ "regularization of Gao & Bower. The force-displacement curve, the energies (of the loads, "
1951
+ "stored and dissipated by the bulk, dissipated by the interfaces: about G_c per unit of "
1952
+ "cracked area in mode I), the cohesive zone length and the broken interfaces.",
1953
+ [
1954
+ Field("specimen", "choice", "ligament", choices=COHESIVE_SPECIMENS),
1955
+ Field("source", "item", label="morphology", when={"specimen": "interfaces"}),
1956
+ Field(
1957
+ "interfaces",
1958
+ "choice",
1959
+ "phases",
1960
+ when={"specimen": "interfaces"},
1961
+ choices=(
1962
+ ("phases", "between the phases (the debonding of inclusions)"),
1963
+ ("grains", "every grain boundary of a tessellation"),
1964
+ ),
1965
+ ),
1966
+ Field(
1967
+ "materials",
1968
+ "materials",
1969
+ of="source",
1970
+ when={"specimen": "interfaces"},
1971
+ doc="E and ν of each phase; void phases are pores, left out of the mesh",
1972
+ ),
1973
+ Field(
1974
+ "crystal",
1975
+ "bool",
1976
+ False,
1977
+ label="cubic crystal grains",
1978
+ when={"specimen": "interfaces", "interfaces": "grains"},
1979
+ doc="crystal elasticity in each grain, turned by its orientation (random when the "
1980
+ "tessellation has none)",
1981
+ ),
1982
+ *_crystal_fields({"specimen": "interfaces", "interfaces": "grains", "crystal": True}),
1983
+ Field("width", "float", 8.0, unit="length", when={"specimen": "ligament"}),
1984
+ Field(
1985
+ "height",
1986
+ "float",
1987
+ 8.0,
1988
+ unit="length",
1989
+ when={"specimen": "ligament"},
1990
+ doc="the ligament on its mid-plane y = H / 2",
1991
+ ),
1992
+ Field("thickness", "float", 1.0, unit="length", when={"specimen": "ligament"}),
1993
+ Field(
1994
+ "notch",
1995
+ "float",
1996
+ 2.0,
1997
+ unit="length",
1998
+ when={"specimen": "ligament"},
1999
+ doc="the free crack from x = 0, the cohesive ligament beyond",
2000
+ ),
2001
+ Field("beam_length", "float", 60.0, unit="length", when={"specimen": "dcb"}),
2002
+ Field("beam_width", "float", 2.0, unit="length", when={"specimen": "dcb"}),
2003
+ Field(
2004
+ "arm",
2005
+ "float",
2006
+ 4.0,
2007
+ unit="length",
2008
+ when={"specimen": "dcb"},
2009
+ doc="the thickness of each arm",
2010
+ ),
2011
+ Field("precrack", "float", 20.0, unit="length", when={"specimen": "dcb"}),
2012
+ *_behaviour_fields(_PLATES),
2013
+ Field(
2014
+ "element_size",
2015
+ "float",
2016
+ unit="length",
2017
+ doc="blank: 0.5 (ligament), 1 (beam), a tenth of the largest edge (morphology; a "
2018
+ "3D one takes minutes)",
2019
+ ),
2020
+ Field("law", "choice", "bilinear", choices=LAWS),
2021
+ Field(
2022
+ "normal_strength",
2023
+ "float",
2024
+ label="normal strength N",
2025
+ unit="stress",
2026
+ when={"law": "bilinear"},
2027
+ doc="blank: E / 100 (E / 200 for the beam)",
2028
+ ),
2029
+ Field(
2030
+ "shear_strength",
2031
+ "float",
2032
+ label="shear strength S",
2033
+ unit="stress",
2034
+ when={"law": "bilinear"},
2035
+ doc="blank: N",
2036
+ ),
2037
+ Field(
2038
+ "mode_I",
2039
+ "float",
2040
+ label="G_Ic",
2041
+ unit="energy / area",
2042
+ when={"law": "bilinear"},
2043
+ doc="blank: 4 h N² / E, a cohesive zone of four elements (E / 2000 for the beam)",
2044
+ ),
2045
+ Field(
2046
+ "mode_II",
2047
+ "float",
2048
+ label="G_IIc",
2049
+ unit="energy / area",
2050
+ when={"law": "bilinear"},
2051
+ doc="blank: G_Ic (S / N)²",
2052
+ ),
2053
+ Field("eta", "float", 2.0, label="η (Benzeggagh-Kenane)", when={"law": "bilinear"}),
2054
+ Field(
2055
+ "stiffness",
2056
+ "float",
2057
+ label="penalty K",
2058
+ unit="stress / length",
2059
+ when={"law": "bilinear"},
2060
+ doc="blank: 100 E / h",
2061
+ ),
2062
+ Field(
2063
+ "strength",
2064
+ "float",
2065
+ label="strength σc",
2066
+ unit="stress",
2067
+ when={"law": "exponential"},
2068
+ doc="blank: E / 100 (E / 200 for the beam)",
2069
+ ),
2070
+ Field(
2071
+ "energy",
2072
+ "float",
2073
+ label="G_c",
2074
+ unit="energy / area",
2075
+ when={"law": "exponential"},
2076
+ doc="blank: 4 h σc² / E (E / 2000 for the beam)",
2077
+ ),
2078
+ Field("beta", "float", 1.0, label="β (shear / normal)", when={"law": "exponential"}),
2079
+ Field(
2080
+ "displacement",
2081
+ "float",
2082
+ unit="length",
2083
+ doc="of each grip (of the loading line of each arm) at the end (blank: enough to "
2084
+ "break the interfaces in tension)",
2085
+ ),
2086
+ Field("steps", "int", 60, doc="steps of the loading (divided when Newton fails)"),
2087
+ Field(
2088
+ "regularization",
2089
+ "float",
2090
+ label="viscous regularization ζ",
2091
+ doc="of Gao & Bower, in units of the "
2092
+ "displacement (blank: 10⁻³ of the displacement; 0: none)",
2093
+ ),
2094
+ Field("kinematics", "choice", "small", choices=KINEMATICS),
2095
+ ],
2096
+ order=5,
2097
+ groups=(
2098
+ ("Specimen", "specimen"),
2099
+ ("Bulk", "behaviour"),
2100
+ ("Cohesive law", "law"),
2101
+ ("Loading", "displacement"),
2102
+ ),
2103
+ menu="Cohesive zones",
2104
+ )
2105
+ def cohesive_zones(p: dict, ctx) -> dict:
2106
+ from morphogen.fracture.cohesive import (
2107
+ CohesiveProblem,
2108
+ cohesive_zone_length,
2109
+ dcb_beam_theory,
2110
+ dcb_specimen,
2111
+ insert_interfaces,
2112
+ turon_strength,
2113
+ )
2114
+ from morphogen.fracture.lefm import without_voids
2115
+
2116
+ kind = p["specimen"]
2117
+ ctx.progress(0.02, "meshing")
2118
+ names: dict = {}
2119
+ if kind == "interfaces":
2120
+ item = p.get("source")
2121
+ if item is None:
2122
+ raise ValueError("interfaces: choose a morphology of the workspace")
2123
+ micro = item["micro"]
2124
+ lower = np.asarray(micro.domain.lower, dtype=float)
2125
+ upper = np.asarray(micro.domain.upper, dtype=float)
2126
+ size = float(p.get("element_size") or float(np.max(upper - lower)) / 10.0)
2127
+ _size(size, size, "edge", float(np.prod(upper - lower)))
2128
+ grains = p["interfaces"] == "grains"
2129
+ mesh = _morphology_mesh(micro, size, grains)
2130
+ if grains:
2131
+ if p.get("crystal"):
2132
+ orientations = mesh.orientations
2133
+ if orientations is None:
2134
+ from morphogen.orientations import random_orientations
2135
+
2136
+ count = int(mesh.cell.max()) + 1
2137
+ orientations = random_orientations(np.random.default_rng(item.get("seed")),
2138
+ count) # fmt: skip
2139
+ from morphogen.mesh.tetra import TetMesh
2140
+
2141
+ mesh = TetMesh(mesh.nodes, mesh.elements, np.zeros(mesh.n_elements, np.int64),
2142
+ mesh.lower, mesh.upper, metadata=dict(mesh.metadata),
2143
+ cell=mesh.cell, orientations=orientations) # fmt: skip
2144
+ materials = {0: _cubic(p)}
2145
+ else:
2146
+ materials = _phase_materials(item, p.get("materials"), np.unique(mesh.phase))
2147
+ mesh = without_voids(mesh, [k for k, m in materials.items() if m.void])
2148
+ opened, faces = insert_interfaces(mesh, lambda c: np.ones(len(c), dtype=bool),
2149
+ sides=mesh.cell) # fmt: skip
2150
+ else: # the pores (void phases) left out: their walls free
2151
+ materials = _phase_materials(item, p.get("materials"), np.unique(mesh.phase))
2152
+ names = {int(k): v for k, v in (item.get("phases") or {}).items()}
2153
+ mesh = without_voids(mesh, [k for k, m in materials.items() if m.void])
2154
+ opened, faces = insert_interfaces(mesh, "phases")
2155
+ cohesive = faces
2156
+ if not cohesive.n_elements:
2157
+ raise ValueError("no interface in this morphology (one phase, or one grain)")
2158
+ x = opened.nodes
2159
+ tol = 1e-9 * float(np.max(upper - lower))
2160
+ top = np.flatnonzero(x[:, 1] > upper[1] - tol)
2161
+ bottom = np.flatnonzero(x[:, 1] < lower[1] + tol)
2162
+ a = bottom[np.argmin(np.linalg.norm(x[bottom] - lower, axis=1))]
2163
+ b = bottom[np.argmin(np.linalg.norm(x[bottom] - [upper[0], lower[1], lower[2]], axis=1))]
2164
+ prescribed = [(top, 1, 1.0), (bottom, 1, 0.0), (a, [0, 2], 0.0), (b, 2, 0.0)]
2165
+ component, factor, span = 1, 1.0, float(upper[1] - lower[1])
2166
+ elif kind == "ligament":
2167
+ width, height = float(p["width"]), float(p["height"])
2168
+ lower, upper = np.zeros(3), np.array([width, height, float(p["thickness"])])
2169
+ size = float(p.get("element_size") or 0.5)
2170
+ mesh = _box_mesh(lower, upper, size, plane_y=0.5 * height)
2171
+ plane = 0.5 * height
2172
+ opened, faces = insert_interfaces(mesh, lambda c: np.abs(c[:, 1] - plane) < 1e-6 * size)
2173
+ notch = float(p["notch"])
2174
+ if not 0 <= notch < width:
2175
+ raise ValueError("notch: from 0 to the width")
2176
+ cohesive = faces.subset(faces.centroids(opened)[:, 0] > notch)
2177
+ materials = {0: _material(p)}
2178
+ x = opened.nodes
2179
+ tol = 1e-9 * float(np.max(upper))
2180
+ top, bottom = np.flatnonzero(x[:, 1] > height - tol), np.flatnonzero(x[:, 1] < tol)
2181
+ prescribed = [(top, [0, 1, 2], [0.0, 1.0, 0.0]), (bottom, [0, 1, 2], [0.0, -1.0, 0.0])]
2182
+ component, factor, span = 1, 2.0, height
2183
+ else:
2184
+ length, width = float(p["beam_length"]), float(p["beam_width"])
2185
+ arm, precrack = float(p["arm"]), float(p["precrack"])
2186
+ size = float(p.get("element_size") or 1.0)
2187
+ opened, cohesive, sets = dcb_specimen(length, width, arm, precrack, size)
2188
+ lower, upper = np.zeros(3), np.array([length, width, 2 * arm])
2189
+ materials = {0: _material(p)}
2190
+ top, bottom = sets["top"], sets["bottom"]
2191
+ prescribed = [(top, 2, 1.0), (bottom, 2, -1.0), (top, [0, 1], 0.0),
2192
+ (bottom, [0, 1], 0.0)] # fmt: skip
2193
+ component, factor, span = 2, 2.0, 2 * arm
2194
+ young = _stiffest(materials.values())
2195
+ law = _law(p, young, size, beam=kind == "dcb")
2196
+ strength, energy, failure = _law_values(law)
2197
+ load = p.get("displacement")
2198
+ if load is None: # twice the elastic stretch at the strength and the opening at failure
2199
+ if kind == "dcb":
2200
+ load = 3.0 * (float(p["beam_length"]) / 60.0)
2201
+ elif kind == "ligament":
2202
+ load = 2.0 * (strength / young * span + failure) / factor
2203
+ else:
2204
+ load = 2.0 * (strength / young * span + 2.0 * failure) / factor
2205
+ steps = int(p["steps"])
2206
+ viscosity = p.get("regularization")
2207
+ viscosity = 1e-3 * load if viscosity is None else float(viscosity)
2208
+ problem = CohesiveProblem(opened, cohesive, materials, law, kinematics=p["kinematics"])
2209
+ _report_newton(problem, ctx, float(load))
2210
+ ctx.progress(0.1, f"solving: {opened.n_elements} tetrahedra, {cohesive.n_elements} "
2211
+ "interface elements") # fmt: skip
2212
+ result = problem.run(prescribed, float(load), steps=steps, viscosity=viscosity, fields=True)
2213
+ ctx.progress(0.9, "figures")
2214
+ opening = factor * result.loads
2215
+ force = result.reactions[:, 0, component]
2216
+ rows = result.rows()
2217
+ for row, d in zip(rows, opening, strict=True):
2218
+ row["displacement"] = float(d)
2219
+ ctx.table(rows, "steps", "the steps: load factor, reactions, cracked area, works")
2220
+ area = float(cohesive.areas(opened).sum())
2221
+ work = {k: float(v[-1]) for k, v in result.work.items()}
2222
+ if problem.bulk is None: # an elastic bulk stores the work of its forces
2223
+ stored = work.get("bulk", math.nan)
2224
+ else:
2225
+ stored = float(problem.bulk.free_energy() @ problem.bulk.wts)
2226
+ cracked = float(result.cracked[-1])
2227
+ values = {
2228
+ "elements": opened.n_elements,
2229
+ "interface_elements": cohesive.n_elements,
2230
+ "interface_area": area,
2231
+ "peak_force": float(np.max(force)),
2232
+ "displacement_at_peak": float(opening[int(np.argmax(force))]),
2233
+ "cracked_area": cracked,
2234
+ "broken_fraction": cracked / area if area > 0 else 0.0,
2235
+ "work_external": work.get("external", math.nan),
2236
+ "work_interfaces": work.get("interfaces", math.nan),
2237
+ "work_bulk": work.get("bulk", math.nan),
2238
+ "stored_bulk": stored,
2239
+ "dissipated_bulk": work.get("bulk", math.nan) - stored,
2240
+ "cohesive_zone_length": cohesive_zone_length(young, energy, strength),
2241
+ "zone_elements": cohesive_zone_length(young, energy, strength) / size,
2242
+ "strength_for_3_elements": turon_strength(young, energy, size, 3),
2243
+ "G_c": energy,
2244
+ }
2245
+ if cracked > 0: # G_c, the process zones of unbroken interfaces, energy released unstably
2246
+ values["work_interfaces_per_cracked_area"] = work.get("interfaces", math.nan) / cracked
2247
+ ys = {"force": force}
2248
+ title = f"{cohesive.n_elements} interface elements, {opened.n_elements} tetrahedra"
2249
+ if kind == "dcb":
2250
+ beam, _ = dcb_beam_theory(materials[0].young, materials[0].poisson,
2251
+ float(p["beam_width"]), float(p["arm"]), float(p["precrack"]),
2252
+ energy, opening) # fmt: skip
2253
+ ys["corrected beam theory"] = beam
2254
+ values["peak_beam_theory"] = float(np.max(beam))
2255
+ curve = _curves(opening, ys, "displacement" if kind == "interfaces" else "opening", "force",
2256
+ title, styles={"force": "o-", "corrected beam theory": "-"},
2257
+ twin=("cracked area", result.cracked)) # fmt: skip
2258
+ ctx.figure(curve, "force", "force-displacement")
2259
+ energies = {f"work of the {k}": v for k, v in result.work.items()}
2260
+ ctx.figure(_curves(opening, energies, "displacement", "energy", "works: of the loads = "
2261
+ "of the bulk + of the interfaces"), "energies", "energies") # fmt: skip
2262
+ u = result.displacement
2263
+ scale = _magnification([result], lower, upper, 0.04)
2264
+ ctx.figure(_rgb(_cohesive_figure(opened, cohesive, u, result.damage.mean(axis=1), scale,
2265
+ f"broken interfaces (displacements x {scale:.3g})")),
2266
+ "interfaces", "broken interfaces") # fmt: skip
2267
+ ctx.progress(0.95, "video of the opening")
2268
+ chosen = np.unique(np.linspace(0, len(result.fields) - 1, min(24, len(result.fields)))
2269
+ .astype(int)) # fmt: skip
2270
+ ctx.video(_opening_frames(opened, cohesive, law, [result.fields[k] for k in chosen], scale,
2271
+ [f"displacement {opening[k]:.3g}, force {force[k]:.3g}"
2272
+ for k in chosen]),
2273
+ "opening", "the interfaces opening", fps=8, mode="once") # fmt: skip
2274
+ problem.write(ctx.path("cohesive"), result)
2275
+ if names:
2276
+ values["phases"] = ", ".join(f"{k}: {v}" for k, v in sorted(names.items()))
2277
+ return {"values": values}
2278
+
2279
+
2280
+ def _opening_frames(mesh, faces, law, fields, scale: float, captions) -> list[np.ndarray]:
2281
+ """The frames of a cohesive problem: the deformed mid-section of the bulk and the traces
2282
+ of the interfaces coloured by their damage (the largest so far)."""
2283
+ moved = np.concatenate([mesh.nodes + scale * np.asarray(u) for u in fields])
2284
+ pad = 0.02 * float(np.ptp(mesh.nodes, axis=0).max())
2285
+ window = ((moved[:, 0].min() - pad, moved[:, 0].max() + pad),
2286
+ (moved[:, 1].min() - pad, moved[:, 1].max() + pad)) # fmt: skip
2287
+ labels = np.zeros(mesh.n_elements)
2288
+ video = _Frames(window, (-0.5, 0.5), "", cmap=_labels_cmap(1),
2289
+ lines=("inferno_r", (0.0, 1.0), "damage of the interfaces")) # fmt: skip
2290
+ cut = section_cut(mesh)
2291
+ at = 0.5 * (mesh.nodes[:, 2].min() + mesh.nodes[:, 2].max())
2292
+ worst = np.zeros(faces.n_elements)
2293
+ frames = []
2294
+ for u, caption in zip(fields, captions, strict=True):
2295
+ worst = np.maximum(worst, _damage_now(law, mesh, faces, u))
2296
+ polygons, owners = section(mesh, u, scale, cut=cut)
2297
+ segments, rows = _interface_segments(mesh, faces, u, scale, at)
2298
+ frames.append(video.frame(polygons, labels[owners], caption, segments, worst[rows]))
2299
+ return frames
2300
+
2301
+
2302
+ # -- polycrystals ----------------------------------------------------------------------------------
2303
+
2304
+
2305
+ @dataclass
2306
+ class Grains:
2307
+ """The grains of a tessellation for the crack meshes: the cell of points and the crystal
2308
+ orientation of each cell (:func:`~morphogen.fracture.lefm.with_grains`)."""
2309
+
2310
+ tessellation: Any
2311
+ orientations: np.ndarray
2312
+
2313
+ def cell_of(self, points) -> np.ndarray:
2314
+ return self.tessellation.cell_of(points)
2315
+
2316
+
2317
+ def _grains_of(item: dict, seed) -> Grains:
2318
+ micro = item["micro"]
2319
+ if not hasattr(micro, "cell_of") or not hasattr(micro, "germs"):
2320
+ raise ValueError(f"{item['title']}: a polycrystal, a Voronoi or Laguerre tessellation of "
2321
+ "the workspace") # fmt: skip
2322
+ orientations = getattr(micro, "orientations", None)
2323
+ if orientations is None:
2324
+ from morphogen.orientations import random_orientations
2325
+
2326
+ rng = np.random.default_rng(seed if seed is not None else item.get("seed"))
2327
+ orientations = random_orientations(rng, len(micro.germs))
2328
+ return Grains(micro, np.asarray(orientations, dtype=float))
2329
+
2330
+
2331
+ def _grain_map(grains: Grains, lower, upper, at: float, cracks, title: str, count: int = 360):
2332
+ """The grains of the plane z = ``at`` (their cells on a grid), their boundaries, the path
2333
+ of the crack and its successive tips."""
2334
+ from morphogen.viz.png import label_colors
2335
+
2336
+ lengths = np.asarray(upper) - np.asarray(lower)
2337
+ n = np.maximum(2, np.rint(count * lengths[:2] / lengths[:2].max())).astype(int)
2338
+ xs = lower[0] + (np.arange(n[0]) + 0.5) * lengths[0] / n[0]
2339
+ ys = lower[1] + (np.arange(n[1]) + 0.5) * lengths[1] / n[1]
2340
+ gx, gy = np.meshgrid(xs, ys, indexing="ij")
2341
+ points = np.column_stack([gx.ravel(), gy.ravel(), np.full(gx.size, at)])
2342
+ cells = grains.cell_of(points).reshape(n[0], n[1])
2343
+ rgb = label_colors(cells).astype(float) / 255.0
2344
+ edge = np.zeros(cells.shape, dtype=bool)
2345
+ edge[1:, :] |= cells[1:, :] != cells[:-1, :]
2346
+ edge[:, 1:] |= cells[:, 1:] != cells[:, :-1]
2347
+ rgb[edge] = 0.15
2348
+ fig = _canvas(6.4, float(np.clip(6.4 * lengths[1] / lengths[0], 3.5, 8.0)))
2349
+ ax = fig.subplots()
2350
+ ax.imshow(np.transpose(rgb, (1, 0, 2)), origin="lower", interpolation="nearest",
2351
+ extent=(lower[0], upper[0], lower[1], upper[1])) # fmt: skip
2352
+ path = _path_xy(cracks[-1])
2353
+ tips = np.array([_tips_xy(c)[0] for c in cracks])
2354
+ ax.plot(path[:, 0], path[:, 1], "-", color="white", lw=3.2)
2355
+ ax.plot(path[:, 0], path[:, 1], "-", color="crimson", lw=1.8)
2356
+ ax.plot(tips[:, 0], tips[:, 1], "o", color="crimson", ms=4, mec="white", mew=0.6)
2357
+ for tip in tips:
2358
+ ax.annotate(str(int(grains.cell_of(np.array([[tip[0], tip[1], at]]))[0])), tip,
2359
+ textcoords="offset points", xytext=(4, 4), fontsize=7) # fmt: skip
2360
+ ax.set_xlabel("x")
2361
+ ax.set_ylabel("y")
2362
+ ax.set_title(title, fontsize=9)
2363
+ return fig
2364
+
2365
+
2366
+ @tool(
2367
+ "polycrystal_crack",
2368
+ "fracture",
2369
+ "Polycrystal crack growth",
2370
+ "An edge crack grows through the grains of a polycrystal of the workspace (a Voronoi or "
2371
+ "Laguerre tessellation: a slab of it, pulled by grips in plane strain), each grain a cubic "
2372
+ "crystal turned by its orientation, elastic or slipping on its systems (Méric-Cailletaud "
2373
+ "crystal plasticity, in small or finite strains): the body is meshed again by MMG at each "
2374
+ "advance, its elements taking the grain of their centroids (staircase grain boundaries), "
2375
+ "and the state of the points moved grain by grain; the front advances once the driving "
2376
+ "force at the tip (J_tip, the configurational forces of the slips) reaches the toughness, "
2377
+ "kinking after Erdogan & Sih (the Voigt-Reuss-Hill moduli of the crystal). The path over "
2378
+ "the grains, the loads and driving forces of each advance, the resistance curve and a "
2379
+ "video of the growth.",
2380
+ [
2381
+ Field(
2382
+ "source",
2383
+ "item",
2384
+ label="polycrystal",
2385
+ required=True,
2386
+ needs=("grains",),
2387
+ doc="a Voronoi or Laguerre tessellation (its orientations, or random ones)",
2388
+ ),
2389
+ Field(
2390
+ "thickness",
2391
+ "float",
2392
+ unit="length",
2393
+ doc="of the slab about the middle of z (blank: the whole depth, at most a "
2394
+ "sixteenth of the width)",
2395
+ ),
2396
+ *_crystal_fields(),
2397
+ Field(
2398
+ "plasticity",
2399
+ "choice",
2400
+ "crystal",
2401
+ choices=(
2402
+ ("crystal", "crystal plasticity (slip systems)"),
2403
+ ("elastic", "crystal elasticity only"),
2404
+ ),
2405
+ ),
2406
+ Field(
2407
+ "families",
2408
+ "choices",
2409
+ ["octahedral"],
2410
+ when={"plasticity": "crystal"},
2411
+ choices=(
2412
+ ("octahedral", "octahedral {111}<110> (FCC)"),
2413
+ ("cube", "cube {100}<110>"),
2414
+ ("bcc110", "BCC {110}<111>"),
2415
+ ("bcc112", "BCC {112}<111>"),
2416
+ ),
2417
+ ),
2418
+ Field(
2419
+ "tau0",
2420
+ "float",
2421
+ 60.0,
2422
+ label="τ0",
2423
+ unit="stress",
2424
+ when={"plasticity": "crystal"},
2425
+ doc="critical resolved shear stress",
2426
+ ),
2427
+ Field(
2428
+ "Q",
2429
+ "float",
2430
+ 40.0,
2431
+ unit="stress",
2432
+ when={"plasticity": "crystal"},
2433
+ doc="isotropic hardening (Q, b)",
2434
+ ),
2435
+ Field("b", "float", 5.0, when={"plasticity": "crystal"}),
2436
+ Field(
2437
+ "K",
2438
+ "float",
2439
+ 5.0,
2440
+ unit="stress",
2441
+ when={"plasticity": "crystal"},
2442
+ doc="Norton's viscosity (K, n)",
2443
+ ),
2444
+ Field("n", "float", 20.0, when={"plasticity": "crystal"}),
2445
+ Field("length", "float", unit="length", doc="of the crack (blank: 0.3 W)"),
2446
+ Field("position", "float", unit="length", doc="its height y (blank: the middle)"),
2447
+ Field("angle", "float", 0.0, unit="degree"),
2448
+ Field("steps", "int", 3, doc="advances of the front"),
2449
+ Field("increment", "float", unit="length", doc="blank: W / 8"),
2450
+ Field(
2451
+ "toughness",
2452
+ "float",
2453
+ 0.6,
2454
+ unit="energy / area",
2455
+ doc="J_tip at which the front advances (N/mm with MPa and mm)",
2456
+ ),
2457
+ Field(
2458
+ "strain_step",
2459
+ "float",
2460
+ 2.5e-4,
2461
+ doc="of the nominal strain of the grips, between the checks of the criterion",
2462
+ ),
2463
+ Field("max_strain", "float", 7.5e-3, doc="the loading stops there"),
2464
+ Field(
2465
+ "strain_rate",
2466
+ "float",
2467
+ 1.0,
2468
+ unit="1/time",
2469
+ when={"plasticity": "crystal"},
2470
+ doc="of the grips (the time of the viscous slips)",
2471
+ ),
2472
+ Field("kinematics", "choice", "small", choices=KINEMATICS),
2473
+ Field("element_size", "float", unit="length", doc="blank: W / 20"),
2474
+ Field("transfer", "choice", "nearest", choices=TRANSFERS),
2475
+ Field(
2476
+ "seed",
2477
+ "int",
2478
+ doc="of the random orientations of a tessellation without any "
2479
+ "(blank: the seed of the morphology)",
2480
+ ),
2481
+ ],
2482
+ order=4,
2483
+ groups=(
2484
+ ("Polycrystal", "source"),
2485
+ ("Crack", "length"),
2486
+ ("Growth", "steps"),
2487
+ ),
2488
+ menu="Cracks",
2489
+ )
2490
+ def polycrystal_crack(p: dict, ctx) -> dict:
2491
+ from morphogen.fracture.ductile import propagate_ductile
2492
+ from morphogen.fracture.lefm import crack_mesh
2493
+ from morphogen.fracture.mixed import KinkedCrack
2494
+
2495
+ item = p["source"]
2496
+ grains = _grains_of(item, p.get("seed"))
2497
+ domain = item["micro"].domain
2498
+ lower = np.asarray(domain.lower, dtype=float).copy()
2499
+ upper = np.asarray(domain.upper, dtype=float).copy()
2500
+ width, height = float(upper[0] - lower[0]), float(upper[1] - lower[1])
2501
+ depth = float(upper[2] - lower[2])
2502
+ thickness = p.get("thickness") or min(depth, width / 16.0)
2503
+ if not 0 < thickness <= depth * (1 + 1e-12):
2504
+ raise ValueError(f"thickness: from 0 to the depth of the polycrystal ({depth:g})")
2505
+ middle = 0.5 * (lower[2] + upper[2])
2506
+ lower[2], upper[2] = middle - 0.5 * thickness, middle + 0.5 * thickness
2507
+ size = _size(p.get("element_size") or width / 20.0, 1.0, "edge", width * height * thickness)
2508
+ a = float(p.get("length") or 0.3 * width)
2509
+ y = lower[1] + 0.5 * height if p.get("position") is None else float(p["position"])
2510
+ angle = math.radians(p.get("angle") or 0.0)
2511
+ mouth = np.array([lower[0], y, lower[2]])
2512
+ tip = mouth + a * np.array([math.cos(angle), math.sin(angle), 0.0])
2513
+ if not (a > 0 and lower[1] < y < upper[1] and np.all(tip[:2] > lower[:2])
2514
+ and np.all(tip[:2] < upper[:2])): # fmt: skip
2515
+ raise ValueError("length, position, angle: the crack inside the polycrystal")
2516
+ crack = KinkedCrack((tuple(mouth), tuple(tip)))
2517
+ material = _cubic(p, plastic=p["plasticity"] == "crystal")
2518
+ steps = int(p["steps"])
2519
+ if steps < 1:
2520
+ raise ValueError("steps: at least one advance")
2521
+ increment = float(p.get("increment") or width / 8.0)
2522
+ tol = 1e-9 * max(width, height)
2523
+
2524
+ def pulled(m): # the grips move by ±H/2 per unit of the load factor: the nominal strain
2525
+ x = m.nodes
2526
+ top, bottom = x[:, 1] > upper[1] - tol, x[:, 1] < lower[1] + tol
2527
+ faces = (x[:, 2] < lower[2] + tol) | (x[:, 2] > upper[2] - tol)
2528
+ corner = _nearest(m, (upper[0], 0.5 * (lower[1] + upper[1]), lower[2]))
2529
+ u = 0.5 * height
2530
+ return [(np.flatnonzero(top & ~faces), 1, u), (np.flatnonzero(bottom & ~faces), 1, -u),
2531
+ (np.flatnonzero(top & faces), [1, 2], [u, 0.0]),
2532
+ (np.flatnonzero(bottom & faces), [1, 2], [-u, 0.0]),
2533
+ (np.flatnonzero(faces & ~top & ~bottom), 2, 0.0), (corner, 0, 0.0)] # fmt: skip
2534
+
2535
+ def meshed(c):
2536
+ return crack_mesh(lower, upper, c, size=size, grains=grains)
2537
+
2538
+ mesh_of = _counting_distinct(meshed, ctx, steps)
2539
+ options = {}
2540
+ if p["plasticity"] == "crystal":
2541
+ options["duration"] = 1.0 / float(p.get("strain_rate") or 1.0)
2542
+ result = propagate_ductile(mesh_of, crack, material, pulled,
2543
+ load_step=float(p["strain_step"]), increment=increment,
2544
+ steps=steps, toughness=float(p["toughness"]),
2545
+ max_load=float(p["max_strain"]), kinematics=p["kinematics"],
2546
+ transfer=p["transfer"], keep=True, **options) # fmt: skip
2547
+ cracks, solutions = result.cracks, result.solutions
2548
+ at = 0.5 * (lower[2] + upper[2])
2549
+ rows = result.rows()
2550
+ for row, c in zip(rows, cracks, strict=True):
2551
+ row["x_tip"], row["y_tip"] = float(c.tip[0]), float(c.tip[1])
2552
+ row["grain"] = int(grains.cell_of(np.array([[c.tip[0], c.tip[1], at]]))[0])
2553
+ for row in rows:
2554
+ row["strain"] = row.pop("load")
2555
+ ctx.table(rows, "advances", "the advances: strains, driving forces, kinks, grains of the tips")
2556
+ ctx.table(result.history, "loading", "every load step (the load: the nominal strain)")
2557
+ last = result.history[-1]
2558
+ met = last["J_tip"] >= float(p["toughness"])
2559
+ tips = [row["grain"] for row in rows]
2560
+ values = {
2561
+ "grains": len(grains.orientations),
2562
+ "advances": len(cracks) - 1,
2563
+ "final_length": cracks[-1].size,
2564
+ "last_strain": float(result.loads[-1]),
2565
+ "stopped": "after the last step" if met else "at the largest strain",
2566
+ "grains_crossed": len(set(tips)) - 1,
2567
+ "largest_kink_deg": float(np.degrees(np.abs(result.angles)).max()),
2568
+ "elements": solutions[-1].mesh.n_elements,
2569
+ "orientations": "of the tessellation"
2570
+ if getattr(item["micro"], "orientations", None) is not None
2571
+ else "random",
2572
+ }
2573
+ ctx.progress(0.88, "figures")
2574
+ ctx.figure(_rgb(_grain_map(grains, lower, upper, at, cracks,
2575
+ f"the path over the grains (tips in grains {tips})")),
2576
+ "grains", "crack path over the grains") # fmt: skip
2577
+ delta, far = result.resistance()
2578
+ ys = {"J_far (J_ψ, ring)": far, "J_tip": result.tip, "J_work": result.work}
2579
+ ctx.figure(_curves(delta, ys, "crack advance Δa", "driving force", "resistance curve",
2580
+ lines={"toughness": float(p["toughness"])},
2581
+ twin=("nominal strain", result.loads)), "resistance", "R-curve") # fmt: skip
2582
+ captions = [f"advance {k}: strain {lam:.3g}, J_tip {jt:.3g}, grain {g}" for k, (lam, jt, g)
2583
+ in enumerate(zip(result.loads, result.tip, tips, strict=True))] # fmt: skip
2584
+ _growth_outputs(ctx, lower, upper, size, cracks, solutions, captions,
2585
+ f"{len(cracks)} cracks through the grains") # fmt: skip
2586
+ return {"values": values}