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,714 @@
1
+ """Brittle fracture of voxel images by the phase-field method: cracks that start, branch
2
+ and merge in a periodic microstructure without being meshed or tracked.
3
+
4
+ A field ``d`` (0: sound, 1: broken) regularizes the cracks over the length ``l``
5
+ (Francfort & Marigo 1998; Bourdin, Francfort & Marigo 2000): the energy of the cell is
6
+
7
+ E(u, d) = int g(d) psi(eps(u)) dV + int G_c gamma(d, grad d) dV, g(d) = (1 - d)^2 + k,
8
+
9
+ with the crack density ``gamma = d^2 / (2 l) + l |grad d|^2 / 2`` (the model ``AT2``: the
10
+ damage grows from the first load) or ``gamma = 3/8 (d / l + l |grad d|^2)`` (``AT1``:
11
+ elastic up to the stress ``sqrt(3 G_c E / (8 l))`` in uniaxial tension), whose integral
12
+ tends to the area of the cracks as ``l`` vanishes: the work to break the cell is the
13
+ toughness ``G_c`` times that area, whatever the voxels, provided they resolve ``l``
14
+ (linear elements over-estimate it by the factor ``1 + h / (2 l)``, ``h`` their size: at
15
+ least two voxels per length).
16
+
17
+ The problem is solved by alternate minimization (Bourdin et al. 2000): at each step of a
18
+ loading path, until the damage no longer moves,
19
+
20
+ 1. the displacement at fixed damage: the periodic elastic problem of the voxels of the
21
+ FFT solver (:mod:`morphogen.homogenization.fft`), each voxel with its stiffness times
22
+ ``g`` of its damage (conjugate gradients preconditioned in Fourier space, the
23
+ reference medium scaled by the degradation of the nodes; the macroscopic components
24
+ prescribed as stresses are condensed);
25
+ 2. the damage at fixed displacement: ``(G_c / l + 2 psi+) d - G_c l lap(d) = 2 psi+``
26
+ (``AT2``) with ``psi+`` the tensile energy of each voxel, under the bound that the
27
+ damage does not decrease (irreversibility, by a primal-dual active set: the obstacle
28
+ problem of ``AT1``, whose damage is zero below its elastic limit and whose cracks have
29
+ the finite width ``4 l``); trilinear elements with a lumped reaction, conjugate
30
+ gradients. With ``irreversibility="history"`` the bound is replaced by the largest
31
+ ``psi+`` reached at each voxel (the history field of Miehe, Hofacker & Welschinger
32
+ 2010): simpler, but it widens the cracks and over-estimates their energy.
33
+
34
+ The stress is degraded as a whole (``sigma = g(d) C : eps``: the hybrid formulation of
35
+ Ambati, Gerasimov & De Lorenzis 2015, linear at fixed damage) while the energy that
36
+ drives the damage is its tensile part only: all of it (``split="none"``), the spectral
37
+ split of Miehe et al. (``"spectral"``: ``lambda <tr eps>+^2 / 2 + mu sum <eps_i>+^2``, by
38
+ default) or the volumetric one of Amor et al. (``"volumetric"``: ``K <tr eps>+^2 / 2 + mu
39
+ dev eps : dev eps``), so that compression does not break. Each phase has its toughness;
40
+ the phases without one do not break (their stiffness is not degraded), the voids carry
41
+ neither stress nor cracks. Initial cracks are voxels given as broken: the damage of their
42
+ nodes is held at 1.
43
+
44
+ The results are those of a loading path (the macroscopic stress and strain in time),
45
+ with the mean damage, the regularized area of the cracks and the energies; the strength
46
+ of the cell (its largest stress) and its work of fracture are quantities for the
47
+ statistics of representative volumes (:meth:`PhaseFieldResult.strength`,
48
+ :meth:`PhaseFieldResult.work`).
49
+
50
+ In finite strains (rubbers, foams, soft tissues): :mod:`morphogen.fracture.
51
+ phasefield_finite`, the same damage problem with the energy of the deformation gradient
52
+ and the nonlinear FFT solver for the displacement.
53
+ """
54
+
55
+ from __future__ import annotations
56
+
57
+ import logging
58
+ import math
59
+ import time
60
+ from dataclasses import dataclass
61
+
62
+ import numpy as np
63
+ from numba import njit, prange
64
+
65
+ from morphogen.homogenization import kernels
66
+ from morphogen.homogenization.fft import FFTElasticProblem, FourierPreconditioner
67
+ from morphogen.homogenization.materials import Material
68
+ from morphogen.homogenization.paths import LoadingPath, PathResult
69
+ from morphogen.homogenization.solvers import conjugate_gradient
70
+ from morphogen.image import VoxelImage
71
+ from morphogen.stopping import checkpoint
72
+
73
+ log = logging.getLogger("morphogen")
74
+
75
+ #: Models of the crack density: (c_w, the local term) of ``gamma = (w(d) / l + l |grad
76
+ #: d|^2) / c_w``
77
+ MODELS = ("AT2", "AT1")
78
+ #: Splits of the energy that drives the damage
79
+ SPLITS = ("spectral", "volumetric", "none")
80
+ #: Engineering shears of the tensor components of the strains
81
+ _ENGINEERING = np.array([1.0, 1.0, 1.0, 2.0, 2.0, 2.0])
82
+
83
+
84
+ @dataclass(frozen=True)
85
+ class PhaseField:
86
+ """The fracture of the phases of a sample: ``toughness``, the critical energy release
87
+ rate ``G_c`` of all the phases (one value) or of each (a mapping phase -> ``G_c``; the
88
+ phases left out do not break), the regularization ``length`` ``l`` (at least two
89
+ voxels), the ``model`` (:data:`MODELS`), the ``split`` of the driving energy
90
+ (:data:`SPLITS`), the ``residual`` stiffness ``k`` of a broken voxel and the
91
+ ``irreversibility``: ``"bound"`` (the damage of each node never decreases) or
92
+ ``"history"`` (the largest driving energy reached; see the module)."""
93
+
94
+ toughness: float | dict
95
+ length: float
96
+ model: str = "AT2"
97
+ split: str = "spectral"
98
+ residual: float = 1e-6
99
+ irreversibility: str = "bound"
100
+
101
+ def __post_init__(self) -> None:
102
+ if isinstance(self.toughness, dict):
103
+ values = {int(p): float(g) for p, g in self.toughness.items()}
104
+ if not values or any(not (math.isfinite(g) and g > 0) for g in values.values()):
105
+ raise ValueError("toughness: positive values (phase -> G_c)")
106
+ object.__setattr__(self, "toughness", tuple(sorted(values.items())))
107
+ elif not (math.isfinite(self.toughness) and self.toughness > 0):
108
+ raise ValueError("toughness: a positive critical energy release rate")
109
+ else:
110
+ object.__setattr__(self, "toughness", float(self.toughness))
111
+ if not (math.isfinite(self.length) and self.length > 0):
112
+ raise ValueError("length: a positive regularization length")
113
+ if self.model not in MODELS:
114
+ raise ValueError(f"model: one of {MODELS}, got {self.model!r}")
115
+ if self.split not in SPLITS:
116
+ raise ValueError(f"split: one of {SPLITS}, got {self.split!r}")
117
+ if not 0.0 < self.residual < 1e-2:
118
+ raise ValueError("residual: a small positive fraction of the stiffness")
119
+ if self.irreversibility not in ("bound", "history"):
120
+ raise ValueError("irreversibility: 'bound' (the damage never decreases) or 'history'")
121
+
122
+ @classmethod
123
+ def from_config(cls, spec) -> PhaseField:
124
+ """A mapping of the parameters of :class:`PhaseField`."""
125
+ if isinstance(spec, PhaseField):
126
+ return spec
127
+ if not isinstance(spec, dict):
128
+ raise ValueError("phase field: a mapping (toughness, length, model, split)")
129
+ unknown = sorted(set(spec) - set(cls.__dataclass_fields__))
130
+ if unknown:
131
+ raise ValueError(f"phase field: unknown keys {unknown}")
132
+ return cls(**spec)
133
+
134
+ def of(self, phase: int) -> float | None:
135
+ """The toughness of a phase (None: it does not break)."""
136
+ if isinstance(self.toughness, tuple):
137
+ return dict(self.toughness).get(int(phase))
138
+ return self.toughness
139
+
140
+ def critical_stress(self, modulus: float) -> float:
141
+ """The largest stress of a homogeneous bar of modulus ``modulus`` (that of its
142
+ loading: Young's modulus in uniaxial stress) and of this toughness (one value):
143
+ ``9/16 sqrt(E G_c / (3 l))`` (``AT2``), ``sqrt(3 E G_c / (8 l))`` (``AT1``)."""
144
+ gc = self.toughness if not isinstance(self.toughness, tuple) else None
145
+ if gc is None:
146
+ raise ValueError("critical_stress: one toughness for all the phases")
147
+ if self.model == "AT2":
148
+ return 9.0 / 16.0 * math.sqrt(modulus * gc / (3.0 * self.length))
149
+ return math.sqrt(3.0 * modulus * gc / (8.0 * self.length))
150
+
151
+
152
+ # -- kernels -----------------------------------------------------------------------------------
153
+
154
+
155
+ @njit(parallel=True, cache=True)
156
+ def _apply_scaled(nx, ny, nz, nd, group, scale, mats, w, out):
157
+ """``out = K w`` on the periodic grid, the element matrix of the voxel ``e`` being
158
+ ``scale[e] * mats[group[e]]`` (-1: none)."""
159
+ corners = kernels.CORNERS
160
+ size = 8 * nd
161
+ for n in prange(nx * ny * nz):
162
+ k = n % nz
163
+ j = (n // nz) % ny
164
+ i = n // (ny * nz)
165
+ acc = np.zeros(nd)
166
+ we = np.empty(size)
167
+ for a in range(2):
168
+ ei = i - a if i - a >= 0 else nx - 1
169
+ for b in range(2):
170
+ ej = j - b if j - b >= 0 else ny - 1
171
+ for c in range(2):
172
+ ek = k - c if k - c >= 0 else nz - 1
173
+ e = (ei * ny + ej) * nz + ek
174
+ g = group[e]
175
+ if g < 0:
176
+ continue
177
+ ln = kernels.CORNER_INDEX[a, b, c]
178
+ for q in range(8):
179
+ qi = ei + corners[q, 0]
180
+ qj = ej + corners[q, 1]
181
+ qk = ek + corners[q, 2]
182
+ if qi == nx:
183
+ qi = 0
184
+ if qj == ny:
185
+ qj = 0
186
+ if qk == nz:
187
+ qk = 0
188
+ m = (qi * ny + qj) * nz + qk
189
+ for c2 in range(nd):
190
+ we[q * nd + c2] = w[m * nd + c2]
191
+ mat = mats[g]
192
+ factor = scale[e]
193
+ for r in range(nd):
194
+ row = ln * nd + r
195
+ s = 0.0
196
+ for col in range(size):
197
+ s += mat[row, col] * we[col]
198
+ acc[r] += factor * s
199
+ for r in range(nd):
200
+ out[n * nd + r] = acc[r]
201
+
202
+
203
+ @njit(parallel=True, cache=True)
204
+ def _load_scaled(nx, ny, nz, nd, group, scale, loads):
205
+ """``-sum_e scale[e] loads[group[e]]``: the nodal forces of element loads."""
206
+ out = np.zeros(nx * ny * nz * nd)
207
+ for n in prange(nx * ny * nz):
208
+ k = n % nz
209
+ j = (n // nz) % ny
210
+ i = n // (ny * nz)
211
+ for a in range(2):
212
+ ei = i - a if i - a >= 0 else nx - 1
213
+ for b in range(2):
214
+ ej = j - b if j - b >= 0 else ny - 1
215
+ for c in range(2):
216
+ ek = k - c if k - c >= 0 else nz - 1
217
+ e = (ei * ny + ej) * nz + ek
218
+ g = group[e]
219
+ if g < 0:
220
+ continue
221
+ ln = kernels.CORNER_INDEX[a, b, c]
222
+ for r in range(nd):
223
+ out[n * nd + r] -= scale[e] * loads[g, ln * nd + r]
224
+ return out
225
+
226
+
227
+ def _to_nodes(values: np.ndarray) -> np.ndarray:
228
+ """The sum over the eight voxels around each node of a periodic grid of the values of
229
+ the voxels (the node ``(i, j, k)`` is the lower corner of the voxel ``(i, j, k)``)."""
230
+ out = np.zeros_like(values)
231
+ for a in (0, 1):
232
+ for b in (0, 1):
233
+ for c in (0, 1):
234
+ out += np.roll(values, (a, b, c), axis=(0, 1, 2))
235
+ return out
236
+
237
+
238
+ def _to_voxels(values: np.ndarray) -> np.ndarray:
239
+ """The mean over the eight corners of each voxel of nodal values."""
240
+ out = np.zeros_like(values)
241
+ for a in (0, 1):
242
+ for b in (0, 1):
243
+ for c in (0, 1):
244
+ out += np.roll(values, (-a, -b, -c), axis=(0, 1, 2))
245
+ return out / 8.0
246
+
247
+
248
+ # -- results -----------------------------------------------------------------------------------
249
+
250
+
251
+ @dataclass
252
+ class PhaseFieldResult(PathResult):
253
+ """The response of a cell that breaks along a loading path: a
254
+ :class:`~morphogen.homogenization.paths.PathResult` (the macroscopic ``strain`` and
255
+ ``stress`` at the ``times``; its variable ``plastic`` is the mean damage of the phases
256
+ that break, as that of each phase in ``phases``) with the ``damage`` (the same), the
257
+ regularized area of the cracks per unit volume (``crack_surface``), the elastic and
258
+ fracture energies per unit volume, and the alternate minimizations of each step
259
+ (``iterations``). With ``fields``: the damage, strain and stress of the voxels at chosen
260
+ times. :meth:`~morphogen.homogenization.paths.PathResult.strength` is the strength of
261
+ the cell and :meth:`~morphogen.homogenization.paths.PathResult.work` the work done on
262
+ it: with the stored energy released, more than the fracture energy when the cell
263
+ breaks at once (the cracks of a brittle cell run faster than its loading)."""
264
+
265
+ damage: np.ndarray | None = None
266
+ crack_surface: np.ndarray | None = None
267
+ elastic_energy: np.ndarray | None = None
268
+ fracture_energy: np.ndarray | None = None
269
+
270
+ def _row(self, k: int) -> dict:
271
+ row = super()._row(k)
272
+ row.update(
273
+ damage=float(self.damage[k]),
274
+ crack_surface=float(self.crack_surface[k]),
275
+ elastic_energy=float(self.elastic_energy[k]),
276
+ fracture_energy=float(self.fracture_energy[k]),
277
+ )
278
+ return row
279
+
280
+
281
+ # -- the problem -------------------------------------------------------------------------------
282
+
283
+
284
+ class PhaseFieldProblem:
285
+ """The brittle fracture of a periodic voxel image (see the module): ``materials`` of
286
+ its phases (elastic; the crystals turned by the orientations of their ``grains``),
287
+ ``fracture`` (:class:`PhaseField`, or a mapping of its parameters), ``initial``: the
288
+ voxels broken from the start (a boolean array of the shape of the image). ``tol``:
289
+ the relative residual of the conjugate gradients; ``staggered_tol``: the largest change
290
+ of the damage that ends the alternate minimization of a step, of at most
291
+ ``max_staggered`` iterations."""
292
+
293
+ def __init__(self, image: VoxelImage, materials: dict[int, Material], fracture, *,
294
+ initial=None, grains=None, orientations=None, tol: float = 1e-7,
295
+ staggered_tol: float = 1e-3, max_staggered: int = 200): # fmt: skip
296
+ self.fracture = PhaseField.from_config(fracture)
297
+ self.elastic = FFTElasticProblem(image, materials, tol=tol, grains=grains,
298
+ orientations=orientations) # fmt: skip
299
+ p = self.elastic
300
+ self.image, self.shape = image, image.shape
301
+ self.tol = float(tol)
302
+ self.staggered_tol, self.max_staggered = float(staggered_tol), int(max_staggered)
303
+ frac = self.fracture
304
+ h = float(max(image.spacing[d] for d in range(3) if image.shape[d] > 1))
305
+ if frac.length < 1.5 * h:
306
+ log.warning(
307
+ "phase field: the length %.3g is less than two voxels (%.3g): the cracks "
308
+ "are not resolved and the work of fracture over-estimated", frac.length, h
309
+ ) # fmt: skip
310
+ phase = np.asarray(image.data).reshape(self.shape)
311
+ # toughness of each voxel (0: it does not break) and its Lame coefficients
312
+ gc = np.zeros(self.shape)
313
+ lam = np.zeros(self.shape)
314
+ mu = np.zeros(self.shape)
315
+ for ph in np.unique(phase):
316
+ m = materials[int(ph)]
317
+ if m.void:
318
+ continue
319
+ value = frac.of(int(ph))
320
+ if value is not None:
321
+ gc[phase == ph] = value
322
+ if frac.split != "none":
323
+ if not m.isotropic or m.stiffness is not None:
324
+ raise ValueError(
325
+ f"phase {int(ph)}: the {frac.split} split needs isotropic phases "
326
+ "(split='none' for crystals)"
327
+ )
328
+ lam[phase == ph], mu[phase == ph] = m.lame
329
+ self.gc, self.lam, self.mu = gc, lam, mu
330
+ self.solid = (p.mat >= 0).reshape(self.shape)
331
+ self.breakable = gc > 0
332
+ if not self.breakable.any():
333
+ raise ValueError("phase field: no phase with a toughness")
334
+ self.volume = float(image.volume)
335
+ self.voxel = float(np.prod(image.spacing))
336
+ # the damage equation: diffusion a, reaction r = r0 + 2 H, source 2 H - s0
337
+ length = frac.length
338
+ if frac.model == "AT2":
339
+ self.diffusion, self.reaction0, self.source0 = gc * length, gc / length, 0.0 * gc
340
+ self.floor = 0.0 * gc
341
+ else:
342
+ self.diffusion = 0.75 * gc * length
343
+ self.reaction0 = 0.0 * gc
344
+ self.source0 = 0.375 * gc / length
345
+ self.floor = 0.0 * gc
346
+ self.k_d = np.ascontiguousarray(p.element.k_thermal[None])
347
+ self.group_d = np.where(self.breakable.ravel(), 0, -1).astype(np.int64)
348
+ self.history = self.floor.copy()
349
+ #: the nodes held at d = 1: those of the voxels broken from the start
350
+ self.fixed = np.zeros(self.shape, dtype=bool)
351
+ if initial is not None:
352
+ broken = np.asarray(initial, dtype=bool)
353
+ if broken.shape != self.shape:
354
+ raise ValueError("initial: a boolean array of the shape of the image")
355
+ self.fixed = _to_nodes((broken & self.breakable).astype(float)) > 0
356
+ self.d = np.zeros(self.shape)
357
+ self._preconditioner = None
358
+ self._warm: dict = {}
359
+ if initial is not None:
360
+ self.d = self._damage(self.history)
361
+
362
+ # -- the displacement at fixed damage ------------------------------------------------
363
+
364
+ def degradation(self, d: np.ndarray | None = None) -> np.ndarray:
365
+ """``g`` of each voxel for the nodal damage ``d`` (the current one by default): 1
366
+ in the phases that do not break."""
367
+ d = self.d if d is None else d
368
+ mean = np.clip(_to_voxels(d), 0.0, 1.0)
369
+ g = (1.0 - mean) ** 2 + self.fracture.residual
370
+ return np.where(self.breakable, g, 1.0)
371
+
372
+ def _mechanics(self, g: np.ndarray, strain: np.ndarray, dt: float, key):
373
+ """The periodic fluctuation of the macroscopic strain ``strain`` and the change of
374
+ temperature ``dt`` in the cell degraded by ``g`` (warm start: ``key``)."""
375
+ p = self.elastic
376
+ nx, ny, nz = self.shape
377
+ scale = np.ascontiguousarray(g.ravel())
378
+ loads = p.element_matrices @ p.element.affine_displacement(strain)
379
+ if dt:
380
+ loads = loads - dt * p._thermal_loads()
381
+ rhs = _load_scaled(nx, ny, nz, 3, p.mat, scale, np.ascontiguousarray(loads))
382
+ norm = float(np.linalg.norm(rhs))
383
+ reference = float(np.sqrt(np.sum(p.counts * np.sum(loads * loads, axis=1))))
384
+ if norm <= 1e-12 * reference:
385
+ return np.zeros_like(rhs), 0
386
+ if self._preconditioner is None:
387
+ self._preconditioner = FourierPreconditioner.from_element(
388
+ self.shape, p._reference_element(), 3
389
+ )
390
+ mats = p.element_matrices
391
+
392
+ def apply(v):
393
+ out = np.empty_like(v)
394
+ _apply_scaled(nx, ny, nz, 3, p.mat, scale, mats, v, out)
395
+ return out
396
+
397
+ # the reference medium scaled by the degradation of the nodes: the stiffness of a
398
+ # damaged cell is that of the sound one times g, which the Fourier inverse of the
399
+ # sound reference ignores (thousands of iterations across broken voxels)
400
+ nodal = _to_nodes(g) / 8.0
401
+ weight = np.repeat(1.0 / np.sqrt(nodal.ravel()), 3)
402
+ reference = self._preconditioner
403
+
404
+ def precondition(r):
405
+ return weight * reference(weight * r)
406
+
407
+ start = self._warm.get(key)
408
+ maxiter = 40 * int(max(self.shape)) + 2000
409
+ if start is None:
410
+ w, its, res = conjugate_gradient(apply, precondition, rhs, self.tol, maxiter)
411
+ else: # from the solution of the last iteration
412
+ r = rhs - apply(start)
413
+ ratio = float(np.linalg.norm(r)) / norm
414
+ if ratio <= self.tol:
415
+ w, its, res = start, 0, ratio
416
+ else:
417
+ dw, its, res = conjugate_gradient(apply, precondition, r, self.tol / ratio,
418
+ maxiter) # fmt: skip
419
+ w, res = start + dw, res * ratio
420
+ if res > 10.0 * self.tol:
421
+ log.warning("phase field: the elastic solve stopped at the residual %.2e", res)
422
+ self._warm[key] = w
423
+ return w, its
424
+
425
+ def _voxel_fields(self, w, strain, dt):
426
+ """Voxel means of the strain (tensor components), of the sound stress ``C : eps``
427
+ and twice the sound energy density (zero in the voids)."""
428
+ p = self.elastic
429
+ nx, ny, nz = self.shape
430
+ el = p.element
431
+ eps, sig, energy = kernels.elastic_fields(
432
+ nx, ny, nz, True, p.mat, p.table.matrices, p.table.eigen, float(dt), w,
433
+ el.affine_displacement(strain), el.b_mean, el.b_gauss,
434
+ ) # fmt: skip
435
+ return np.nan_to_num(eps), np.nan_to_num(sig), np.nan_to_num(energy)
436
+
437
+ def _driving(self, eps, energy, dt) -> np.ndarray:
438
+ """The tensile energy density ``psi+`` of the voxels."""
439
+ split = self.fracture.split
440
+ if split == "none":
441
+ return 0.5 * energy.reshape(self.shape)
442
+ e = eps
443
+ if dt:
444
+ p = self.elastic
445
+ thermal = p.table.eigen[np.maximum(p.mat, 0)] * np.array([1, 1, 1, 0.5, 0.5, 0.5])
446
+ e = eps - dt * np.where((p.mat >= 0)[:, None], thermal, 0.0)
447
+ tr = e[:, :3].sum(axis=1)
448
+ lam, mu = self.lam.ravel(), self.mu.ravel()
449
+ if split == "volumetric":
450
+ dev2 = np.sum((e[:, :3] - tr[:, None] / 3.0) ** 2, axis=1) + 2.0 * np.sum(
451
+ e[:, 3:] ** 2, axis=1
452
+ )
453
+ bulk = lam + 2.0 * mu / 3.0
454
+ psi = 0.5 * bulk * np.maximum(tr, 0.0) ** 2 + mu * dev2
455
+ else:
456
+ t = np.empty((len(e), 3, 3))
457
+ for k, (a, b) in enumerate(((0, 0), (1, 1), (2, 2), (1, 2), (2, 0), (0, 1))):
458
+ t[:, a, b] = t[:, b, a] = e[:, k]
459
+ principal = np.linalg.eigvalsh(t)
460
+ psi = 0.5 * lam * np.maximum(tr, 0.0) ** 2 + mu * np.sum(
461
+ np.maximum(principal, 0.0) ** 2, axis=1
462
+ )
463
+ return psi.reshape(self.shape)
464
+
465
+ # -- the damage at fixed displacement ------------------------------------------------
466
+
467
+ def _damage(self, history: np.ndarray, lower: np.ndarray | None = None) -> np.ndarray:
468
+ """The nodal damage of a history field: the minimum of the energy at fixed
469
+ displacement, ``(r0 + 2 H) d - div(a grad d) = 2 H - s0`` (the reaction and the
470
+ source lumped at the nodes), under the bound ``d >= lower`` (the damage of the last
471
+ step: irreversibility; zero by default) by a primal-dual active set: the nodes at
472
+ their bound are held there while the multiplier of the bound pushes them down."""
473
+ nx, ny, nz = self.shape
474
+ on = self.breakable
475
+ reaction = _to_nodes(np.where(on, self.reaction0 + 2.0 * history, 0.0)) * self.voxel / 8.0
476
+ source = _to_nodes(np.where(on, 2.0 * history - self.source0, 0.0)) * self.voxel / 8.0
477
+ source = source.ravel()
478
+ scale = np.ascontiguousarray(self.diffusion.ravel())
479
+ diag = (_to_nodes(self.diffusion) * float(self.k_d[0, 0, 0]) + reaction).ravel()
480
+ alive = diag > 0
481
+ fixed = self.fixed.ravel()
482
+ bound = np.zeros(diag.size) if lower is None else lower.ravel()
483
+ held = np.where(fixed, 1.0, bound)
484
+ mass = reaction.ravel()
485
+
486
+ def operator(v):
487
+ out = np.empty_like(v)
488
+ _apply_scaled(nx, ny, nz, 1, self.group_d, scale, self.k_d, v, out)
489
+ return out + mass * v
490
+
491
+ d = np.where(fixed, 1.0, np.maximum(self.d.ravel(), bound))
492
+ active = fixed.copy()
493
+ for _ in range(50):
494
+ free = alive & ~active
495
+ # the unknowns scaled by the diagonal: the residuals are then errors of the
496
+ # damage, whatever the driving energies (those of a crack tip are far above)
497
+ s = np.where(free, 1.0 / np.sqrt(np.where(free, diag, 1.0)), 0.0)
498
+ d = np.where(active, held, np.where(free, d, 0.0))
499
+ r = s * (source - operator(d))
500
+ norm = math.sqrt(float(free.sum()))
501
+ residual = float(np.linalg.norm(r))
502
+ if residual > self.tol * norm:
503
+ y, _, _ = conjugate_gradient(lambda v, s=s: s * operator(s * v), lambda v: v, r,
504
+ self.tol * norm / residual, 5000) # fmt: skip
505
+ d = d + s * y
506
+ multiplier = np.where(active & ~fixed, operator(d) - source, 0.0)
507
+ wanted = fixed | (alive & (multiplier + diag * (bound - d) > 1e-12 * diag))
508
+ if np.array_equal(wanted, active):
509
+ break
510
+ active = wanted
511
+ return np.clip(np.maximum(d, bound), 0.0, 1.0).reshape(self.shape)
512
+
513
+ def crack_surface(self, d: np.ndarray | None = None, weight: np.ndarray | None = None) -> float:
514
+ """The regularized area of the cracks, ``int gamma(d, grad d) dV`` over the phases
515
+ that break; with ``weight`` (the toughness of the voxels), the fracture energy."""
516
+ d = self.d if d is None else d
517
+ nx, ny, nz = self.shape
518
+ frac = self.fracture
519
+ on = self.breakable.astype(float) if weight is None else weight
520
+ length = frac.length
521
+ nodal = _to_nodes(on) * self.voxel / 8.0
522
+ grad = np.empty(d.size)
523
+ _apply_scaled(nx, ny, nz, 1, self.group_d, np.ascontiguousarray(on.ravel()), self.k_d,
524
+ np.ascontiguousarray(d.ravel()), grad) # fmt: skip
525
+ gradient = float(d.ravel() @ grad)
526
+ if frac.model == "AT2":
527
+ return float(np.sum(nodal * d * d) / (2.0 * length) + 0.5 * length * gradient)
528
+ return float(0.375 * (np.sum(nodal * d) / length + length * gradient))
529
+
530
+ # -- loading paths -------------------------------------------------------------------
531
+
532
+ def _state(self, g, values, controls, dt):
533
+ """The macroscopic strain and stress, the fluctuation and the voxel fields of the
534
+ cell degraded by ``g`` under the components ``values`` (strains where ``controls``,
535
+ stresses elsewhere)."""
536
+ unknown = np.flatnonzero(~controls)
537
+ strain = np.where(controls, values, 0.0)
538
+ w, its = self._mechanics(g, strain, dt, "base")
539
+ fields = self._voxel_fields(w, strain, dt)
540
+ gv = g.ravel() * self.voxel / self.volume
541
+
542
+ def mean_stress(sig):
543
+ return gv @ sig
544
+
545
+ stress = mean_stress(fields[1])
546
+ if unknown.size:
547
+ # the cell is linear at fixed damage: the unit strains of the free components
548
+ columns, units = np.zeros((6, unknown.size)), []
549
+ for k, j in enumerate(unknown):
550
+ unit = np.zeros(6)
551
+ unit[j] = 1.0
552
+ wj, n = self._mechanics(g, unit, 0.0, int(j))
553
+ its += n
554
+ units.append(wj)
555
+ columns[:, k] = mean_stress(self._voxel_fields(wj, unit, 0.0)[1])
556
+ free = np.linalg.solve(columns[unknown], values[unknown] - stress[unknown])
557
+ strain[unknown] = free
558
+ w = w + sum(c * wj for c, wj in zip(free, units, strict=True))
559
+ fields = self._voxel_fields(w, strain, dt)
560
+ stress = mean_stress(fields[1])
561
+ return strain, stress, w, fields, its
562
+
563
+ def run(self, path, *, name: str = "path", fields=False, monitor=None) -> PhaseFieldResult:
564
+ """Follow a loading path (:class:`~morphogen.homogenization.paths.LoadingPath`, or
565
+ a mapping for it; its components prescribed as strains or as stresses, with a
566
+ change of temperature): :class:`PhaseFieldResult`. ``fields``: true for the damage,
567
+ strain and stress of the voxels at the end of each segment of the path, ``"steps"``
568
+ at the end of each step, or a list of times of its steps. ``monitor(time, records
569
+ so far)`` after each step; a true value ends the path there."""
570
+ path = LoadingPath.from_spec(path)
571
+ t0 = time.perf_counter()
572
+ controls = path.strain_controlled
573
+ ends = path.schedule()
574
+ if fields is True:
575
+ wanted = np.asarray(path.times[1:], dtype=float)
576
+ elif isinstance(fields, str):
577
+ if fields != "steps":
578
+ raise ValueError("fields: true, 'steps' or a list of times of the path")
579
+ wanted = np.asarray(ends, dtype=float)
580
+ else:
581
+ wanted = np.asarray(fields if fields else [], dtype=float)
582
+ names = ("t", "e", "s", "T", "d", "gamma", "elastic", "fracture", "its", "phases")
583
+ rec = {k: [] for k in names}
584
+ rec["t"].append(float(path.times[0]))
585
+ rec["e"].append(np.zeros(6))
586
+ rec["s"].append(np.zeros(6))
587
+ rec["T"].append(0.0)
588
+ rec["d"].append(self._mean_damage())
589
+ rec["gamma"].append(self.crack_surface() / self.volume)
590
+ rec["elastic"].append(0.0)
591
+ rec["fracture"].append(self.crack_surface(weight=self.gc) / self.volume)
592
+ rec["phases"].append(self._phase_means(None, None))
593
+ kept, solves = {}, 0
594
+ for t in ends:
595
+ checkpoint()
596
+ values, dt = path.at(float(t))
597
+ history, d = self.history, self.d
598
+ committed = self.d
599
+ for it in range(1, self.max_staggered + 1): # noqa: B007
600
+ g = self.degradation(d)
601
+ strain, stress, _, (eps, sig, energy), n = self._state(g, values, controls, dt)
602
+ solves += n
603
+ history = self._driving(eps, energy, dt)
604
+ if self.fracture.irreversibility == "history":
605
+ history = np.maximum(self.history, history)
606
+ new = self._damage(history, committed)
607
+ change = float(np.abs(new - d).max())
608
+ d = new
609
+ self.d = new # the next damage solve starts from it
610
+ if change < self.staggered_tol:
611
+ break
612
+ else:
613
+ log.warning(
614
+ "phase field: the alternate minimization of the step to t = %g stopped at "
615
+ "a change of the damage of %.2e", t, change
616
+ ) # fmt: skip
617
+ self.history, self.d = history, d
618
+ g = self.degradation(d)
619
+ rec["t"].append(float(t))
620
+ rec["e"].append(strain)
621
+ rec["s"].append(stress)
622
+ rec["T"].append(float(dt))
623
+ rec["phases"].append(self._phase_means(eps, g.ravel()[:, None] * sig))
624
+ rec["d"].append(self._mean_damage())
625
+ rec["gamma"].append(self.crack_surface() / self.volume)
626
+ rec["elastic"].append(0.5 * float(g.ravel() @ energy) * self.voxel / self.volume)
627
+ rec["fracture"].append(self.crack_surface(weight=self.gc) / self.volume)
628
+ rec["its"].append(it)
629
+ if wanted.size and np.any(np.isclose(t, wanted, rtol=1e-12, atol=0.0)):
630
+ kept[float(t)] = {
631
+ "damage": _to_voxels(d),
632
+ "p": _to_voxels(d),
633
+ "strain": eps.reshape(*self.shape, 6),
634
+ "stress": (g.ravel()[:, None] * sig).reshape(*self.shape, 6),
635
+ }
636
+ if monitor is not None and monitor(float(t), rec):
637
+ break
638
+ phases = {}
639
+ for ph in rec["phases"][0]:
640
+ phases[ph] = {key: np.array([step[ph][key] for step in rec["phases"]])
641
+ for key in ("stress", "strain", "plastic")} # fmt: skip
642
+ return PhaseFieldResult(
643
+ name=name,
644
+ bc="periodic",
645
+ path=path,
646
+ times=np.array(rec["t"]),
647
+ strain=np.array(rec["e"]),
648
+ stress=np.array(rec["s"]),
649
+ temperature=np.array(rec["T"]),
650
+ plastic=np.array(rec["d"]),
651
+ phases=phases,
652
+ iterations=np.array(rec["its"], dtype=int),
653
+ info={
654
+ "linear_iterations": int(solves),
655
+ "time_s": round(time.perf_counter() - t0, 3),
656
+ },
657
+ fields=kept,
658
+ support=self.image if kept else None,
659
+ damage=np.array(rec["d"]),
660
+ crack_surface=np.array(rec["gamma"]),
661
+ elastic_energy=np.array(rec["elastic"]),
662
+ fracture_energy=np.array(rec["fracture"]),
663
+ )
664
+
665
+ def _mean_damage(self) -> float:
666
+ """The mean damage of the voxels that may break."""
667
+ d = np.clip(_to_voxels(self.d), 0.0, 1.0)
668
+ return float(d[self.breakable].mean())
669
+
670
+ def _phase_means(self, eps, sig) -> dict:
671
+ """The mean stress, strain (engineering shears) and damage of each phase that
672
+ carries a material."""
673
+ p = self.elastic
674
+ damage = np.clip(_to_voxels(self.d), 0.0, 1.0).ravel()
675
+ out = {}
676
+ for g, phase in enumerate(p.table.phases):
677
+ sel = (p.stat == g) & (p.mat >= 0)
678
+ if not sel.any():
679
+ continue
680
+ zero = np.zeros(6)
681
+ out[int(phase)] = {
682
+ "stress": zero if sig is None else sig[sel].mean(axis=0),
683
+ "strain": zero if eps is None else eps[sel].mean(axis=0) * _ENGINEERING,
684
+ "plastic": float(damage[sel].mean()),
685
+ }
686
+ return out
687
+
688
+
689
+ def phase_field_fracture(
690
+ image: VoxelImage,
691
+ materials: dict[int, Material],
692
+ fracture,
693
+ path,
694
+ *,
695
+ name: str = "path",
696
+ fields=False,
697
+ kinematics: str = "small",
698
+ **options,
699
+ ) -> PhaseFieldResult:
700
+ """The response of a periodic voxel image that breaks along a loading path: a
701
+ :class:`PhaseFieldProblem` (its ``options``: ``initial``, ``grains``, ``orientations``,
702
+ ``tol``, ``staggered_tol``, ``max_staggered``) run along ``path``; with
703
+ ``kinematics="finite"``, in finite strains (:class:`~morphogen.fracture.
704
+ phasefield_finite.FinitePhaseFieldProblem`: hyperelastic or elastic phases, nominal
705
+ strains and stresses, its options)."""
706
+ if kinematics not in ("small", "finite"):
707
+ raise ValueError(f"kinematics: 'small' or 'finite', got {kinematics!r}")
708
+ if kinematics == "finite":
709
+ from morphogen.fracture.phasefield_finite import FinitePhaseFieldProblem
710
+
711
+ problem = FinitePhaseFieldProblem(image, materials, fracture, **options)
712
+ else:
713
+ problem = PhaseFieldProblem(image, materials, fracture, **options)
714
+ return problem.run(path, name=name, fields=fields)