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,1321 @@
1
+ """The tools of the tab Nonlocal damage: micromorphic continua, in which a length sets the
2
+ width of the bands where plasticity or damage localize, whatever the elements (Forest
3
+ 2009, the micromorphic approach; :mod:`morphogen.micromorphic`): the microfoam model of
4
+ metallic foams (Dillard, Forest & Ienny 2006), the micromorphic ductile damage of
5
+ elastoplastic solids driven by the plastic strain weighted by the stress triaxiality
6
+ (Rice & Tracey 1969, Johnson & Cook 1985, Lemaitre 1985), and the micromorphic damage of
7
+ quasi-brittle solids (the implicit gradient model of Peerlings et al. 1996).
8
+
9
+ The specimens are made of voxels of six quadratic tetrahedra each
10
+ (:func:`~morphogen.homogenization.bloch.voxel_tet_mesh`): a notched plate, a bar, or a
11
+ morphology of the workspace (its middle section or its volume, without its holes and the
12
+ parts that do not join the grips), in plane strain (one layer of voxels, no displacement
13
+ across it), as a thin plate with free faces (nearly plane stress), or in 3D. Its face ``y =
14
+ 0`` is held, its face ``y = height`` pulled (or pushed); the fields of the elements are
15
+ drawn on their voxels, in the middle section of a volume."""
16
+
17
+ from __future__ import annotations
18
+
19
+ from dataclasses import dataclass
20
+
21
+ import numpy as np
22
+
23
+ from morphogen.gui.tools import Field, tab, tool
24
+
25
+ tab(
26
+ "damage",
27
+ "Nonlocal damage",
28
+ "Micromorphic continua, whose length sets the width of the bands of localization "
29
+ "independently of the elements: the microfoam model of metallic foams, the "
30
+ "micromorphic ductile damage with the stress triaxiality, and the micromorphic damage "
31
+ "of quasi-brittle solids, on a notched plate, a bar or a morphology of the workspace.",
32
+ order=55,
33
+ )
34
+
35
+ #: The label of the voxels without material, and of a weaker zone of a bar
36
+ HOLE, WEAK = 255, 254
37
+ #: Phases taken for holes when the form names none
38
+ HOLE_NAMES = ("void", "pores", "pore", "porosity", "cells", "holes")
39
+ #: The largest problems of the interface (degrees of freedom): the direct solver of the
40
+ #: steps factorizes their tangent at every iteration
41
+ MAX_DOFS = 60_000
42
+ MAX_MICROMORPHIC_DOFS = 25_000
43
+
44
+ SPECIMENS = (
45
+ ("notched_plate", "notched plate: a notch from its left edge at mid-height"),
46
+ ("bar", "bar: notches on both sides at mid-height, or a weaker layer"),
47
+ ("morphology", "a morphology of the workspace (its holes removed)"),
48
+ )
49
+ CONDITIONS = (
50
+ ("plane_strain", "plane strain: one layer of voxels, no displacement across it"),
51
+ ("plane_stress", "thin plate: one layer of voxels with free faces (nearly plane stress)"),
52
+ ("3d", "3D: the plate with its thickness, a bar of square section, the volume"),
53
+ )
54
+ KINEMATICS = (("small", "small strains"), ("finite", "finite strains (total Lagrangian)"))
55
+ GRIPS = (
56
+ ("rollers", "rollers: the gripped faces slide freely"),
57
+ ("clamped", "clamped: the gripped faces do not move sideways"),
58
+ )
59
+ _SHAPED = {"specimen": ["notched_plate", "bar"]}
60
+
61
+
62
+ def _specimen_fields(
63
+ default: str = "notched_plate",
64
+ imperfection: float = 0.1,
65
+ elements: int = 12,
66
+ resolution: int = 24,
67
+ ) -> list[Field]:
68
+ """The fields of the specimen, its grips and its mesh (shared by the tools)."""
69
+ return [
70
+ Field("specimen", "choice", default, choices=SPECIMENS),
71
+ Field("source", "item", label="morphology", required=True, when={"specimen": "morphology"}),
72
+ Field(
73
+ "holes",
74
+ "ints",
75
+ when={"specimen": "morphology"},
76
+ doc="its phases removed (blank: those named void, pores or cells)",
77
+ ),
78
+ Field(
79
+ "resolution",
80
+ "int",
81
+ resolution,
82
+ label="voxels per edge",
83
+ when={"specimen": "morphology"},
84
+ doc="of its voxel image (six tetrahedra per voxel)",
85
+ ),
86
+ Field("condition", "choice", "plane_strain", choices=CONDITIONS),
87
+ Field("width", "float", 1.0, unit="length", when=_SHAPED),
88
+ Field(
89
+ "height",
90
+ "float",
91
+ unit="length",
92
+ when=_SHAPED,
93
+ doc="along the load, y (blank: the width for a plate, twice for a bar)",
94
+ ),
95
+ Field("elements", "int", elements, label="voxels across the width", when=_SHAPED),
96
+ Field(
97
+ "thickness",
98
+ "float",
99
+ unit="length",
100
+ when={"specimen": "notched_plate", "condition": "3d"},
101
+ doc="blank: a quarter of the width",
102
+ ),
103
+ Field(
104
+ "notch_depth",
105
+ "float",
106
+ 0.3 if default == "notched_plate" else 0.0,
107
+ when=_SHAPED,
108
+ doc="fraction of the width (a bar: from each side)",
109
+ ),
110
+ Field(
111
+ "notch_width",
112
+ "float",
113
+ 0.1,
114
+ when=_SHAPED,
115
+ doc="fraction of the width (at least a row of voxels)",
116
+ ),
117
+ Field(
118
+ "imperfection",
119
+ "float",
120
+ imperfection,
121
+ when={"specimen": "bar"},
122
+ doc="the strength of the layer at mid-height of the bar lowered by this fraction "
123
+ "(where the band starts)",
124
+ ),
125
+ Field("grips", "choice", "rollers", choices=GRIPS),
126
+ ]
127
+
128
+
129
+ # -- the specimens ---------------------------------------------------------------------------
130
+
131
+
132
+ @dataclass
133
+ class Specimen:
134
+ """A voxel specimen pulled along y: the labels of its voxels (the phases, ``HOLE``
135
+ without material, ``WEAK`` in the weaker layer of a bar), their edges, its condition
136
+ (``plane_strain``, ``plane_stress`` or ``3d``), the depth of its notch (from ``x = 0``,
137
+ 0 for none) and its title."""
138
+
139
+ labels: np.ndarray
140
+ spacing: tuple
141
+ condition: str
142
+ title: str
143
+ notch: float = 0.0
144
+
145
+ @property
146
+ def shape(self) -> tuple:
147
+ return self.labels.shape
148
+
149
+ @property
150
+ def lengths(self) -> np.ndarray:
151
+ return np.asarray(self.shape, dtype=float) * np.asarray(self.spacing, dtype=float)
152
+
153
+ @property
154
+ def planar(self) -> bool:
155
+ return self.condition != "3d"
156
+
157
+ @property
158
+ def section_area(self) -> float:
159
+ """The gross cross-section normal to the load (width times thickness)."""
160
+ return float(self.lengths[0] * self.lengths[2])
161
+
162
+ def phases(self) -> list[int]:
163
+ return sorted(int(v) for v in np.unique(self.labels) if v != HOLE)
164
+
165
+ def estimate(self, generalized: int) -> int:
166
+ """The degrees of freedom of its full box (an upper bound): three per node of
167
+ the quadratic tetrahedra, ``generalized`` per corner node."""
168
+ n = np.asarray(self.shape)
169
+ return int(3 * np.prod(2 * n + 1) + generalized * np.prod(n + 1))
170
+
171
+ def mesh(self):
172
+ from morphogen.homogenization.bloch import voxel_tet_mesh
173
+ from morphogen.image import VoxelImage
174
+
175
+ image = VoxelImage(self.labels, spacing=self.spacing, periodic=False)
176
+ return voxel_tet_mesh(image, phases=self.phases())
177
+
178
+
179
+ def _rows(centres: np.ndarray, middle: float, width: float, h: float) -> np.ndarray:
180
+ """The voxels whose centres lie within half of ``width`` (at least half a voxel) of
181
+ ``middle``."""
182
+ return np.abs(centres - middle) <= max(width, h) / 2 + 1e-9 * h
183
+
184
+
185
+ def _shaped(p: dict, kind: str) -> Specimen:
186
+ """A notched plate or a bar of the form."""
187
+ width = float(p["width"])
188
+ n = int(p["elements"])
189
+ if not (width > 0 and 1 <= n <= 400):
190
+ raise ValueError("width: positive; voxels across the width: from 1 to 400")
191
+ h = width / n
192
+ height = p["height"] or (width if kind == "notched_plate" else 2.0 * width)
193
+ ny = max(2, round(float(height) / h))
194
+ condition = p["condition"]
195
+ if condition != "3d":
196
+ nz = 1
197
+ elif kind == "bar":
198
+ nz = n
199
+ else:
200
+ nz = max(2, round(float(p["thickness"] or width / 4) / h))
201
+ labels = np.zeros((n, ny, nz), np.uint8)
202
+ xc = (np.arange(n) + 0.5) * h
203
+ yc = (np.arange(ny) + 0.5) * h
204
+ zc = (np.arange(nz) + 0.5) * h
205
+ depth = float(p.get("notch_depth") or 0.0) * width
206
+ rows = _rows(yc, ny * h / 2, float(p.get("notch_width") or 0.0) * width, h)
207
+ if not 0.0 <= depth < (width if kind == "notched_plate" else width / 2):
208
+ raise ValueError("notch depth: a fraction of the width (of its half for a bar)")
209
+ if kind == "notched_plate":
210
+ cut = xc < depth
211
+ labels[np.ix_(cut, rows, np.ones(nz, bool))] = HOLE
212
+ title = f"notched plate {width:g} x {ny * h:g}"
213
+ else:
214
+ cut = (xc < depth) | (xc > width - depth)
215
+ labels[np.ix_(cut, rows, np.ones(nz, bool))] = HOLE
216
+ if condition == "3d": # a groove all around the square section
217
+ side = (zc < depth) | (zc > nz * h - depth)
218
+ labels[np.ix_(np.ones(n, bool), rows, side)] = HOLE
219
+ weak = float(p.get("imperfection") or 0.0)
220
+ if weak:
221
+ if not 0.0 < weak < 1.0:
222
+ raise ValueError("imperfection: a fraction between 0 and 1")
223
+ layer = labels[:, rows, :]
224
+ layer[layer != HOLE] = WEAK
225
+ labels[:, rows, :] = layer
226
+ title = f"bar {width:g} x {ny * h:g}" + (" notched" if depth else "")
227
+ if np.all(labels == HOLE):
228
+ raise ValueError("the notch leaves no material")
229
+ return Specimen(labels, (h, h, h), condition, title, depth if kind == "notched_plate" else 0.0)
230
+
231
+
232
+ def _phase_names(item: dict) -> dict[int, str]:
233
+ names = item.get("phases") or {}
234
+ if not names and item.get("micro") is not None:
235
+ names = item["micro"].phase_names
236
+ return {int(k): str(v) for k, v in names.items()}
237
+
238
+
239
+ def _load_bearing(solid: np.ndarray) -> np.ndarray:
240
+ """The voxels of ``solid`` joined by faces to both gripped faces (``y = 0`` and ``y =
241
+ height``): the others would float, or hang by an edge (singular tangents)."""
242
+ from scipy import ndimage
243
+
244
+ labels, count = ndimage.label(solid)
245
+ if count == 0:
246
+ return np.zeros_like(solid)
247
+ keep = np.intersect1d(np.unique(labels[:, 0, :]), np.unique(labels[:, -1, :]))
248
+ return np.isin(labels, keep[keep > 0])
249
+
250
+
251
+ def _of_morphology(p: dict) -> Specimen:
252
+ """The specimen of a morphology of the workspace: its voxel image (the middle x-y
253
+ section in plane conditions), its holes removed and only the solid joining the grips."""
254
+ from morphogen.gui.api import _voxels
255
+
256
+ item = p["source"]
257
+ micro = item["micro"]
258
+ n = int(p["resolution"])
259
+ if not 4 <= n <= 256:
260
+ raise ValueError("voxels per edge: from 4 to 256")
261
+ _voxels(micro.domain, n, 6.0, "voxel image")
262
+ image = micro.voxelize(shape=n)
263
+ data = np.asarray(image.data)
264
+ if data.dtype.kind not in "iub":
265
+ raise ValueError("the morphology gives no phase image")
266
+ if p["condition"] != "3d":
267
+ data = data[:, :, data.shape[2] // 2][:, :, None]
268
+ names = _phase_names(item)
269
+ holes = p["holes"]
270
+ if not holes:
271
+ holes = [k for k, v in names.items() if v.strip().lower() in HOLE_NAMES]
272
+ solid = ~np.isin(data, list(holes))
273
+ kept = _load_bearing(solid)
274
+ if not kept.any():
275
+ raise ValueError(
276
+ f"the solid of {item['title']} (without the phases {sorted(holes)}) does not join "
277
+ "its faces y = 0 and y = height: no path for the load"
278
+ )
279
+ labels = np.where(kept, data, HOLE).astype(np.uint8)
280
+ section = "section" if p["condition"] != "3d" else "volume"
281
+ return Specimen(labels, tuple(image.spacing), p["condition"], f"{section} of {item['title']}")
282
+
283
+
284
+ def _specimen(p: dict) -> Specimen:
285
+ kind = p["specimen"]
286
+ return _of_morphology(p) if kind == "morphology" else _shaped(p, kind)
287
+
288
+
289
+ def _check_size(specimen: Specimen, generalized: int, limit: int) -> None:
290
+ dofs = specimen.estimate(generalized)
291
+ if dofs > limit:
292
+ raise ValueError(
293
+ f"{specimen.title}: about {dofs} degrees of freedom, more than the {limit} of the "
294
+ "interface (every iteration factorizes the tangent); choose fewer voxels, or a "
295
+ "plane condition"
296
+ )
297
+
298
+
299
+ def _supports(problem, specimen: Specimen, displacement: float, grips: str, extra=()) -> list:
300
+ """The prescribed degrees of freedom: the face ``y = 0`` held along y, the face ``y =
301
+ height`` moved by ``displacement`` (the last entry: its reaction is the force), the
302
+ rigid motions stopped at two corners (rollers) or the faces held sideways (clamped);
303
+ in plane strain no displacement along z; ``extra`` entries after the first ones."""
304
+ x = problem.mesh.nodes
305
+ tol = 1e-9 * float(specimen.lengths.max())
306
+ bottom = np.flatnonzero(np.abs(x[:, 1]) < tol)
307
+ top = np.flatnonzero(np.abs(x[:, 1] - specimen.lengths[1]) < tol)
308
+ if not (len(bottom) and len(top)):
309
+ raise ValueError(f"{specimen.title}: no material on a gripped face")
310
+ plane = specimen.condition == "plane_strain"
311
+ side = [0] if plane else [0, 2]
312
+ entries = [(np.arange(len(x)), 2, 0.0)] if plane else []
313
+ if grips == "clamped":
314
+ entries += [(bottom, [1, *side], 0.0), (top, side, 0.0)]
315
+ else:
316
+ entries.append((bottom, 1, 0.0))
317
+ pin = bottom[np.argmin(np.linalg.norm(x[bottom] - x[bottom].min(axis=0), axis=1))]
318
+ entries.append((pin, side, 0.0))
319
+ if not plane: # no rotation about y
320
+ corner = x[bottom].min(axis=0) + np.array([specimen.lengths[0], 0.0, 0.0])
321
+ far = bottom[np.argmin(np.linalg.norm(x[bottom] - corner, axis=1))]
322
+ if far != pin:
323
+ entries.append((far, 2, 0.0))
324
+ entries += list(extra)
325
+ entries.append((top, 1, float(displacement)))
326
+ return entries
327
+
328
+
329
+ def _run(problem, entries, ctx, *, steps: int, start: float, span: float, label: str, **options):
330
+ """The loading path of a problem (:meth:`~morphogen.micromorphic.space.MixedProblem.run`
331
+ with its fields), its progress reported from ``start`` to ``start + span`` as the load
332
+ of the last entry grows.
333
+
334
+ When the steps stop converging (a crack running unstably snaps back, which the growing
335
+ displacement cannot follow), the converged steps are kept, with a warning: the
336
+ assemblies are watched, and the internal variables passed to one that are those the
337
+ last tangent returned mark the convergence of its step (the solver then takes its
338
+ degrees of freedom, forces and internal variables)."""
339
+ from morphogen.micromorphic.space import PathResult
340
+
341
+ value = entries[-1][2]
342
+ sets = [problem.space.dofs(np.atleast_1d(n), np.atleast_1d(c)) for n, c, _ in entries]
343
+ dof = int(sets[-1][0, 0])
344
+ full = float(value) or 1.0
345
+ inner = problem._assemble
346
+ path: dict = {"loads": [], "reactions": [], "fields": [], "states": [], "last": None}
347
+
348
+ def assemble(values, state, tangent):
349
+ if not path["states"]: # the initial state
350
+ path["loads"].append(0.0)
351
+ path["reactions"].append([np.zeros(s.shape[1]) for s in sets])
352
+ path["fields"].append(np.zeros_like(values))
353
+ path["states"].append(state.copy())
354
+ elif path["last"] is not None and state is path["last"][2]: # a step converged
355
+ u, r, kept = path["last"]
356
+ path["loads"].append(float(u[dof]) / full)
357
+ path["reactions"].append([r[s].sum(axis=0) for s in sets])
358
+ path["fields"].append(u)
359
+ path["states"].append(kept)
360
+ path["last"] = None
361
+ load = min(max(float(values[dof]) / full, 0.0), 1.0)
362
+ ctx.progress(start + span * load, f"{label}: load {100 * load:.0f} %")
363
+ out = inner(values, state, tangent)
364
+ if tangent:
365
+ path["last"] = (np.array(values), out[0], out[2])
366
+ return out
367
+
368
+ problem._assemble = assemble
369
+ try:
370
+ options.setdefault("max_cuts", 10) # steps of a thousandth of the load at least
371
+ return problem.run(entries, steps=int(steps), fields=True, **options)
372
+ except RuntimeError as exc:
373
+ if len(path["loads"]) < 2:
374
+ raise RuntimeError(
375
+ f"{label}: {exc} (more steps or a smaller strain may help)"
376
+ ) from None
377
+ import warnings
378
+
379
+ warnings.warn(
380
+ f"{label}: stopped at {100 * path['loads'][-1]:.0f} % of the load ({exc}: a crack "
381
+ "running unstably, or steps too large); the converged steps are shown",
382
+ stacklevel=2,
383
+ )
384
+ n = len(path["loads"])
385
+ return PathResult(
386
+ np.array(path["loads"]),
387
+ path["reactions"],
388
+ np.zeros(n, int),
389
+ path["fields"][-1],
390
+ path["states"][-1],
391
+ path["fields"],
392
+ path["states"],
393
+ )
394
+ finally:
395
+ del problem._assemble
396
+
397
+
398
+ def _curve(result, specimen: Specimen, displacement: float) -> dict:
399
+ """The displacement of the pulled face and its force (per unit thickness for a plate
400
+ of one layer) at the steps, and the nominal stress (over the gross section)."""
401
+ force = np.array([float(r[-1][0]) for r in result.reactions])
402
+ u = displacement * np.asarray(result.loads)
403
+ per = force / specimen.lengths[2] if specimen.planar else force
404
+ return {"u": u, "force": per, "stress": force / specimen.section_area}
405
+
406
+
407
+ def _voxel_index(mesh, specimen: Specimen) -> np.ndarray:
408
+ """The voxel of each element (by its centroid)."""
409
+ centres = mesh.nodes[mesh.elements[:, :4]].mean(axis=1)
410
+ ijk = np.floor(centres / np.asarray(specimen.spacing)).astype(np.int64)
411
+ ijk = np.clip(ijk, 0, np.asarray(specimen.shape) - 1)
412
+ return np.ravel_multi_index(ijk.T, specimen.shape)
413
+
414
+
415
+ def _on_voxels(index: np.ndarray, values, shape) -> np.ndarray:
416
+ """A field of the elements on their voxels (the mean of the six tetrahedra of equal
417
+ volume), NaN without material."""
418
+ n = int(np.prod(shape))
419
+ count = np.bincount(index, minlength=n)
420
+ total = np.bincount(index, weights=np.asarray(values, dtype=float), minlength=n)
421
+ out = np.full(n, np.nan)
422
+ out[count > 0] = total[count > 0] / count[count > 0]
423
+ return out.reshape(shape)
424
+
425
+
426
+ def _section(volume: np.ndarray) -> np.ndarray:
427
+ """The middle x-y section of a voxel field (x, y)."""
428
+ return volume[:, :, volume.shape[2] // 2]
429
+
430
+
431
+ def _cmap(name: str):
432
+ import matplotlib
433
+
434
+ return matplotlib.colormaps[name].with_extremes(bad="white")
435
+
436
+
437
+ #: The colormaps and ranges of the fields drawn
438
+ FIELD_STYLE = {
439
+ "damage": ("inferno", (0.0, 1.0)),
440
+ "triaxiality": ("RdBu_r", None),
441
+ }
442
+
443
+
444
+ def _maps_figure(maps: dict, specimen: Specimen, title: str = ""):
445
+ """Maps of fields on the voxels of a specimen (its middle section): name -> (x, y)
446
+ array, side by side."""
447
+ from matplotlib.figure import Figure
448
+
449
+ w, h = specimen.lengths[:2]
450
+ cols = len(maps)
451
+ # panels of the shape of the section (3 inches high), each with its colour bar
452
+ panel = 3.0 * float(np.clip(w / h, 0.25, 2.5)) + 1.3
453
+ fig = Figure(figsize=(cols * panel, 3.9), layout="constrained")
454
+ axes = np.atleast_1d(fig.subplots(1, cols))
455
+ for ax, (name, plane) in zip(axes, maps.items(), strict=True):
456
+ key = next((k for k in FIELD_STYLE if name.startswith(k)), "")
457
+ cmap, clim = FIELD_STYLE.get(key, ("viridis", None))
458
+ finite = plane[np.isfinite(plane)]
459
+ if clim is None and key == "triaxiality" and finite.size:
460
+ top = float(np.abs(finite).max()) or 1.0
461
+ clim = (-top, top)
462
+ image = ax.imshow(
463
+ np.asarray(plane, float).T,
464
+ origin="lower",
465
+ extent=(0, w, 0, h),
466
+ cmap=_cmap(cmap),
467
+ interpolation="nearest",
468
+ **({"vmin": clim[0], "vmax": clim[1]} if clim else {}),
469
+ )
470
+ fig.colorbar(image, ax=ax, shrink=0.85, aspect=25)
471
+ ax.set_title(name, fontsize=9, wrap=True)
472
+ ax.set_xlabel("x")
473
+ ax.set_ylabel("y")
474
+ ax.tick_params(labelsize=7)
475
+ if title:
476
+ fig.suptitle(title, fontsize=10)
477
+ return fig
478
+
479
+
480
+ def _curves_figure(curves: dict, xlabel: str, ylabel: str, title: str = ""):
481
+ from matplotlib.figure import Figure
482
+
483
+ fig = Figure(figsize=(5.4, 3.8), layout="constrained")
484
+ ax = fig.subplots()
485
+ for label, (x, y) in curves.items():
486
+ ax.plot(x, y, "o-", ms=2.5, lw=1.5, label=label)
487
+ ax.set_xlabel(xlabel)
488
+ ax.set_ylabel(ylabel)
489
+ ax.set_title(title, fontsize=10)
490
+ ax.grid(alpha=0.3)
491
+ if len(curves) > 1:
492
+ ax.legend(fontsize=8, frameon=False)
493
+ return fig
494
+
495
+
496
+ def _field_video(ctx, volumes, specimen: Specimen, name: str, label: str, captions) -> None:
497
+ """A video of a field on the middle section of a specimen along the steps."""
498
+ from morphogen.viz.video import time_section_frames
499
+
500
+ key = next((k for k in FIELD_STYLE if label.startswith(k)), "")
501
+ cmap, clim = FIELD_STYLE.get(key, ("viridis", None))
502
+ lo, hi = clim if clim else (None, None)
503
+ frames = time_section_frames(
504
+ volumes,
505
+ 2,
506
+ specimen.shape[2] // 2,
507
+ size=420,
508
+ cmap=_cmap(cmap),
509
+ vmin=lo,
510
+ vmax=hi,
511
+ captions=captions,
512
+ label=label,
513
+ )
514
+ ctx.video(frames, name, f"{label} along the loading", fps=8, mode="once")
515
+
516
+
517
+ def _band_width(profile: np.ndarray, h: float) -> float:
518
+ """The full width at half maximum of a profile along y (layers of thickness ``h``),
519
+ interpolated linearly between the centres of the layers at both crossings (a band
520
+ reaching a face ends there)."""
521
+ profile = np.nan_to_num(np.asarray(profile, dtype=float))
522
+ top = float(profile.max()) if profile.size else 0.0
523
+ if not top > 0:
524
+ return float("nan")
525
+ half = 0.5 * top
526
+ above = np.flatnonzero(profile > half)
527
+ i, j = int(above[0]), int(above[-1])
528
+ left = 0.0
529
+ if i > 0:
530
+ left = i - 0.5 + (half - profile[i - 1]) / (profile[i] - profile[i - 1])
531
+ right = float(len(profile))
532
+ if j < len(profile) - 1:
533
+ right = j + 0.5 + (profile[j] - half) / (profile[j] - profile[j + 1])
534
+ return float((right - left) * h)
535
+
536
+
537
+ def _crack(damage: np.ndarray, specimen: Specimen, level: float = 0.9) -> float:
538
+ """The fraction of the ligament of a notched plate that the crack crosses: the reach
539
+ along x of the voxels of its middle section damaged beyond ``level`` that join (by
540
+ their sides) the voxels at the tip of the notch."""
541
+ from scipy import ndimage
542
+
543
+ section = np.nan_to_num(_section(damage)) > level
544
+ h = specimen.spacing[0]
545
+ tip = min(round(specimen.notch / h), section.shape[0] - 1) # the column ahead of it
546
+ rows = np.flatnonzero(_section(specimen.labels)[max(tip - 1, 0)] == HOLE)
547
+ if not len(rows): # a notch shorter than a voxel: the middle row
548
+ rows = np.array([section.shape[1] // 2])
549
+ labels, _ = ndimage.label(section)
550
+ start = np.unique(labels[tip, rows])
551
+ start = start[start > 0]
552
+ if not len(start):
553
+ return 0.0
554
+ reach = np.flatnonzero(np.isin(labels, start).any(axis=1)).max() + 1
555
+ return float((reach - tip) / (section.shape[0] - tip))
556
+
557
+
558
+ def _profile(volume: np.ndarray) -> np.ndarray:
559
+ """The mean of a voxel field over each layer normal to y (0 without material)."""
560
+ finite = np.isfinite(volume)
561
+ total = np.where(finite, volume, 0.0).sum(axis=(0, 2))
562
+ count = finite.sum(axis=(0, 2))
563
+ return np.divide(total, count, out=np.zeros_like(total), where=count > 0)
564
+
565
+
566
+ def _overrides(value, name: str) -> dict[int, dict]:
567
+ """Per-phase changes of the parameters of a material (a mapping phase -> mapping)."""
568
+ if not value:
569
+ return {}
570
+ if not isinstance(value, dict) or not all(isinstance(v, dict) for v in value.values()):
571
+ raise ValueError(f'{name}: a mapping phase -> parameters, e.g. {{"1": {{...}}}}')
572
+ return {int(k): dict(v) for k, v in value.items()}
573
+
574
+
575
+ def _materials(specimen: Specimen, base, overrides: dict, weak: dict) -> dict:
576
+ """The material of each label of a specimen: ``base`` (a dataclass) changed by the
577
+ per-phase ``overrides`` and, in the weaker layer, by ``weak``."""
578
+ import dataclasses
579
+
580
+ out = {}
581
+ for phase in specimen.phases():
582
+ changes = dict(weak) if phase == WEAK else dict(overrides.get(phase, {}))
583
+ try:
584
+ out[phase] = dataclasses.replace(base, **changes) if changes else base
585
+ except TypeError as exc:
586
+ raise ValueError(f"phase {phase}: {exc}") from None
587
+ return out
588
+
589
+
590
+ def _vtu(ctx, problem, values, name: str, cells: dict) -> None:
591
+ """The fields of the elements and the displacement of the nodes, for ParaView."""
592
+ from morphogen.io.meshes import write_vtu_tet
593
+
594
+ u = problem.space.displacement(values)
595
+ write_vtu_tet(
596
+ ctx.path(f"{name}.vtu"),
597
+ problem.mesh,
598
+ {k: np.asarray(v, float) for k, v in cells.items()},
599
+ {"displacement": u},
600
+ )
601
+
602
+
603
+ def _view_3d(ctx, problem, values, field, name: str, title: str, cmap: str, clim=None) -> None:
604
+ """A view of a 3D specimen deformed (true scale) and coloured by a field, when VTK
605
+ renders off screen."""
606
+ from morphogen.viz.video import deformed_view, vtk_can_render
607
+
608
+ if not vtk_can_render():
609
+ return
610
+ rgb = deformed_view(
611
+ problem.mesh,
612
+ problem.space.displacement(values),
613
+ np.asarray(field),
614
+ magnification=1.0,
615
+ cmap=cmap,
616
+ clim=clim,
617
+ title=title,
618
+ )
619
+ ctx.figure(rgb, name, f"{title} (3D view)")
620
+
621
+
622
+ def _captions(curve: dict) -> list[str]:
623
+ return [f"u = {u:.3g}" for u in curve["u"]]
624
+
625
+
626
+ # -- microfoam -------------------------------------------------------------------------------
627
+
628
+
629
+ FOAMS = (
630
+ ("isotropic", "isotropic foam: compressible plasticity, the parameters of the form"),
631
+ ("nickel", "nickel foam of Dillard, Forest & Ienny (2006), MPa and mm"),
632
+ )
633
+
634
+
635
+ @tool(
636
+ "microfoam",
637
+ "damage",
638
+ "Microfoam",
639
+ "The microfoam model of metallic foams (Dillard, Forest & Ienny 2006): anisotropic "
640
+ "compressible plasticity (the elliptic criterion σ_eq² = (3c/2) σ':H:σ' + F (P:σ)²) in "
641
+ "a micromorphic continuum, whose microdeformation χ and characteristic length l_c set "
642
+ "the width of the bands where plasticity localizes (with a softening: a negative "
643
+ "hardening, or the softening branch beyond p_c); in small or finite strains (the "
644
+ "densification of the foam, J). A specimen pulled or crushed: the force-displacement "
645
+ "curve, the bands of the cumulated plastic strain p, the strain and the "
646
+ "microdeformation, and their video; with the classical continuum for comparison "
647
+ "(its bands one element wide).",
648
+ [
649
+ *_specimen_fields("bar", imperfection=0.1, elements=8, resolution=16),
650
+ Field("loading", "choice", "compression", choices=("compression", "tension")),
651
+ Field("strain", "float", 0.04, doc="nominal strain of the specimen at the end"),
652
+ Field("steps", "int", 16),
653
+ Field("kinematics", "choice", "small", choices=KINEMATICS),
654
+ Field("material", "choice", "isotropic", choices=FOAMS),
655
+ Field(
656
+ "length",
657
+ "float",
658
+ 0.02,
659
+ label="length l_c",
660
+ unit="length",
661
+ doc="0: a classical continuum (the nickel foam: 0.1 mm in the article)",
662
+ ),
663
+ Field("young", "float", 100.0, when={"material": "isotropic"}),
664
+ Field("poisson", "float", 0.3, when={"material": "isotropic"}),
665
+ Field("yield_stress", "float", 1.0, when={"material": "isotropic"}),
666
+ Field(
667
+ "hardening",
668
+ "float",
669
+ -10.0,
670
+ when={"material": "isotropic"},
671
+ doc="linear hardening H (negative: a softening that localizes)",
672
+ ),
673
+ Field(
674
+ "F",
675
+ "float",
676
+ 0.3,
677
+ when={"material": "isotropic"},
678
+ doc="weight of the pressure in the criterion (0: von Mises)",
679
+ ),
680
+ Field(
681
+ "micro",
682
+ "floats",
683
+ when={"material": "isotropic"},
684
+ label="higher-order moduli λ, μ",
685
+ doc="blank: 0 and young / 2",
686
+ ),
687
+ Field(
688
+ "relative",
689
+ "floats",
690
+ when={"material": "isotropic"},
691
+ label="relative moduli λ_s, μ_s, μ_c",
692
+ doc="blank: 0, 10 young and 10 young",
693
+ ),
694
+ Field(
695
+ "orientation",
696
+ "choice",
697
+ "TD",
698
+ when={"material": "nickel"},
699
+ choices=(("TD", "TD along the load"), ("RD", "RD along the load")),
700
+ ),
701
+ Field(
702
+ "softening",
703
+ "floats",
704
+ doc="p_c, r, w: Y times r + (1 - r) exp(-((p - p_c)/w)²) beyond p_c (blank: none)",
705
+ ),
706
+ Field(
707
+ "phases",
708
+ "json",
709
+ label="per-phase parameters",
710
+ doc='changes of the material by phase, e.g. {"1": {"yield_stress": 2}}',
711
+ ),
712
+ Field("classical", "bool", False, label="compare with the classical continuum"),
713
+ Field(
714
+ "video",
715
+ "choice",
716
+ "p",
717
+ choices=(
718
+ ("p", "cumulated plastic strain"),
719
+ ("strain", "strain along the load"),
720
+ ("chi", "microdeformation along the load"),
721
+ ("none", "no video"),
722
+ ),
723
+ ),
724
+ ],
725
+ order=1,
726
+ groups=(
727
+ ("Specimen", "specimen"),
728
+ ("Loading", "loading"),
729
+ ("Material", "material"),
730
+ ("Output", "classical", True),
731
+ ),
732
+ )
733
+ def microfoam(p: dict, ctx) -> dict:
734
+ from morphogen.micromorphic import CHI, Microfoam, MicrofoamProblem
735
+
736
+ specimen = _specimen(p)
737
+ length = float(p["length"] or 0.0)
738
+ if length < 0:
739
+ raise ValueError("length: non-negative (0: a classical continuum)")
740
+ softening = tuple(p["softening"]) if p["softening"] else None
741
+ if softening is not None and len(softening) != 3:
742
+ raise ValueError("softening: p_c, r and w")
743
+ if p["material"] == "nickel":
744
+ axes = None if p["orientation"] == "TD" else ((0, 1, 0), (1, 0, 0), (0, 0, 1))
745
+ foam = Microfoam.nickel_foam(length=length or None, axes=axes, softening=softening)
746
+ else:
747
+ young = float(p["young"])
748
+ micro = tuple(p["micro"] or (0.0, young / 2))
749
+ relative = tuple(p["relative"] or (0.0, 10 * young, 10 * young))
750
+ if len(micro) != 2 or len(relative) != 3:
751
+ raise ValueError("higher-order moduli: λ and μ; relative moduli: λ_s, μ_s and μ_c")
752
+ foam = Microfoam(
753
+ young=young,
754
+ poisson=float(p["poisson"]),
755
+ yield_stress=float(p["yield_stress"]),
756
+ hardening=float(p["hardening"]),
757
+ F=float(p["F"]),
758
+ softening=softening,
759
+ length=length or None,
760
+ micro=micro,
761
+ relative=relative,
762
+ )
763
+ weak = {"yield_stress": foam.yield_stress * (1.0 - float(p.get("imperfection") or 0.0))}
764
+ overrides = _overrides(p["phases"], "per-phase parameters")
765
+ sign = -1.0 if p["loading"] == "compression" else 1.0
766
+ strain = abs(float(p["strain"]))
767
+ displacement = sign * strain * specimen.lengths[1]
768
+ cases = [("micromorphic" if length else "classical", foam)]
769
+ if p["classical"] and length:
770
+ import dataclasses
771
+
772
+ cases.append(("classical", dataclasses.replace(foam, length=None)))
773
+ for _, material in cases:
774
+ _check_size(
775
+ specimen,
776
+ 9 if material.length else 0,
777
+ MAX_MICROMORPHIC_DOFS if material.length else MAX_DOFS,
778
+ )
779
+ ctx.progress(0.02, "mesh")
780
+ mesh = specimen.mesh()
781
+ runs = {}
782
+ span = 0.9 / len(cases)
783
+ for k, (name, material) in enumerate(cases):
784
+ problem = MicrofoamProblem(
785
+ mesh, _materials(specimen, material, overrides, weak), kinematics=p["kinematics"]
786
+ )
787
+ extra = []
788
+ if problem.micromorphic and specimen.condition == "plane_strain":
789
+ corners = np.flatnonzero(problem.space.corner)
790
+ odd = [CHI[c] for c in ("chi13", "chi31", "chi23", "chi32", "chi33")]
791
+ extra.append((corners, odd, 0.0)) # no microdeformation out of the plane
792
+ entries = _supports(problem, specimen, displacement, p["grips"], extra)
793
+ hardening = softening is None and all(m.hardening >= 0 for m in problem.materials.values())
794
+ result = _run(
795
+ problem,
796
+ entries,
797
+ ctx,
798
+ steps=p["steps"],
799
+ start=0.02 + k * span,
800
+ span=span,
801
+ label=f"{name} continuum",
802
+ refactor=0.25 if hardening else 0.0,
803
+ predictor=True,
804
+ )
805
+ runs[name] = (problem, result)
806
+ ctx.progress(0.93, "figures")
807
+ first = cases[0][0]
808
+ problem, result = runs[first]
809
+ index = _voxel_index(problem.mesh, specimen)
810
+ curves = {name: _curve(res, specimen, displacement) for name, (_, res) in runs.items()}
811
+ ylabel = "force per unit thickness" if specimen.planar else "force"
812
+ ctx.figure(
813
+ _curves_figure(
814
+ {k: (sign * c["u"], sign * c["force"]) for k, c in curves.items()},
815
+ "displacement of the pulled face" if sign > 0 else "shortening",
816
+ ylabel,
817
+ specimen.title,
818
+ ),
819
+ "force_displacement",
820
+ "force-displacement",
821
+ )
822
+ rows = []
823
+ for name, c in curves.items():
824
+ rows += [
825
+ {
826
+ "continuum": name,
827
+ "displacement": float(u),
828
+ "force": float(f),
829
+ "nominal_stress": float(s),
830
+ }
831
+ for u, f, s in zip(c["u"], c["force"], c["stress"], strict=True)
832
+ ]
833
+ ctx.table(rows, "force_displacement", "force-displacement")
834
+ fields = problem.fields(result.values, result.state)
835
+ finite = p["kinematics"] == "finite"
836
+ maps = {
837
+ "p": fields["p"],
838
+ ("log strain yy" if finite else "strain yy"): fields["strain"][:, 1, 1],
839
+ }
840
+ if problem.micromorphic:
841
+ maps["χyy - 1" if finite else "χyy"] = fields["chi"][:, 1, 1]
842
+ if finite:
843
+ maps["J"] = fields["J"]
844
+ volumes = {k: _on_voxels(index, v, specimen.shape) for k, v in maps.items()}
845
+ ctx.figure(
846
+ _maps_figure(
847
+ {k: _section(v) for k, v in volumes.items()},
848
+ specimen,
849
+ f"{first} continuum at the end: p the cumulated plastic strain, χ the "
850
+ "microdeformation" + (", J the change of volume" if finite else ""),
851
+ ),
852
+ "fields",
853
+ "fields at the end",
854
+ )
855
+ values = {
856
+ "degrees of freedom": problem.space.n_dofs,
857
+ "elements": problem.mesh.n_elements,
858
+ "steps": len(result.loads) - 1,
859
+ "Newton iterations": int(np.sum(result.iterations)),
860
+ }
861
+ p_profile = _profile(volumes["p"])
862
+ for name, c in curves.items():
863
+ stress = sign * c["stress"]
864
+ values[f"peak nominal stress ({name})"] = float(stress.max())
865
+ values[f"final nominal stress ({name})"] = float(stress[-1])
866
+ values["largest p"] = float(np.max(fields["p"]))
867
+ values["band width (p at half maximum, along y)"] = _band_width(p_profile, specimen.spacing[1])
868
+ if finite:
869
+ values["smallest J"] = float(np.min(fields["J"]))
870
+ if "classical" in runs and first != "classical":
871
+ cp, cr = runs["classical"]
872
+ cvol = _on_voxels(
873
+ _voxel_index(cp.mesh, specimen), cp.fields(cr.values, cr.state)["p"], specimen.shape
874
+ )
875
+ values["band width, classical continuum"] = _band_width(_profile(cvol), specimen.spacing[1])
876
+ ctx.figure(
877
+ _maps_figure(
878
+ {
879
+ "p, micromorphic": _section(volumes["p"]),
880
+ "p, classical": _section(cvol),
881
+ },
882
+ specimen,
883
+ "the bands of the two continua",
884
+ ),
885
+ "bands",
886
+ "micromorphic and classical bands",
887
+ )
888
+ if not specimen.planar:
889
+ _view_3d(ctx, problem, result.values, fields["p"], "view_p", "p", "viridis")
890
+ _vtu(
891
+ ctx,
892
+ problem,
893
+ result.values,
894
+ "microfoam",
895
+ {
896
+ "p": fields["p"],
897
+ "strain_yy": fields["strain"][:, 1, 1],
898
+ "chi_yy": fields["chi"][:, 1, 1],
899
+ },
900
+ )
901
+ if p["video"] != "none":
902
+ ctx.progress(0.96, "video")
903
+ frames = []
904
+ for u, state in zip(result.fields, result.states, strict=True):
905
+ f = problem.fields(u, state)
906
+ v = {"p": f["p"], "strain": f["strain"][:, 1, 1], "chi": f["chi"][:, 1, 1]}[p["video"]]
907
+ frames.append(_on_voxels(index, v, specimen.shape))
908
+ label = {"p": "p", "strain": "strain yy", "chi": "chi yy"}[p["video"]]
909
+ _field_video(ctx, frames, specimen, f"video_{p['video']}", label, _captions(curves[first]))
910
+ return {"values": values, "title": f"Microfoam: {specimen.title}"}
911
+
912
+
913
+ # -- ductile damage --------------------------------------------------------------------------
914
+
915
+
916
+ TRIAXIALITY_LAWS = (
917
+ ("none", "none: the plastic strain alone"),
918
+ ("rice_tracey", "Rice & Tracey (1969): exp(β (η - 1/3))"),
919
+ ("johnson_cook", "Johnson & Cook (1985): ε_f = D1 + D2 exp(D3 η)"),
920
+ ("lemaitre", "Lemaitre (1985): R_ν = 2/3 (1 + ν) + 3 (1 - 2ν) η²"),
921
+ )
922
+
923
+
924
+ @tool(
925
+ "ductile",
926
+ "damage",
927
+ "Ductile damage with triaxiality",
928
+ "Micromorphic ductile damage (Forest 2009; the implicit gradient ductile models of "
929
+ "Engelen, Geers & Baaijens 2003): von Mises elastoplasticity of the effective stress, "
930
+ "a damage d = d_max (1 - exp(-(κ - κ0)/κ_c)) driven by a micromorphic cumulated "
931
+ "plastic strain χ - ℓ² Δχ = e, whose length ℓ sets the width of the band of damage; "
932
+ "e the plastic strain weighted by the stress triaxiality η (ė = w(η) ṗ, w(1/3) = 1: "
933
+ "Rice & Tracey's growth of voids, Johnson & Cook's strain to failure, Lemaitre's "
934
+ "energy). A specimen pulled: the force-displacement curve, the fields of the damage, "
935
+ "of the triaxiality and of the plastic strain, a video of the damage growing; with the "
936
+ "plastic strain alone for comparison. In plane strain the triaxial stress ahead of a "
937
+ "notch concentrates the damage there and the crack runs across the ligament.",
938
+ [
939
+ *_specimen_fields("notched_plate", imperfection=0.1),
940
+ Field("strain", "float", 0.016, doc="nominal strain of the specimen at the end"),
941
+ Field("steps", "int", 24),
942
+ Field("kinematics", "choice", "small", choices=KINEMATICS),
943
+ Field("young", "float", 200.0),
944
+ Field("poisson", "float", 0.3),
945
+ Field("yield_stress", "float", 0.4),
946
+ Field("hardening", "float", 10.0, doc="linear hardening H"),
947
+ Field("voce", "floats", doc="Q1, b1 (and Q2, b2) of the Voce hardening (blank: none)"),
948
+ Field("onset", "float", 0.002, label="onset κ0", doc="of the damage"),
949
+ Field("critical", "float", 0.02, label="scale κ_c", doc="of the damage law"),
950
+ Field("max_damage", "float", 0.99),
951
+ Field(
952
+ "length",
953
+ "float",
954
+ label="length ℓ",
955
+ unit="length",
956
+ doc="blank: twice the voxels (at least two voxels)",
957
+ ),
958
+ Field("triaxiality", "choice", "rice_tracey", choices=TRIAXIALITY_LAWS),
959
+ Field(
960
+ "triaxiality_parameters",
961
+ "floats",
962
+ when={"triaxiality": ["rice_tracey", "johnson_cook"]},
963
+ doc="Rice & Tracey: β (blank: 1.5); Johnson & Cook: D1, D2, D3 (blank: 0.05, "
964
+ "3.44, -2.12, their 4340 steel)",
965
+ ),
966
+ Field(
967
+ "compare",
968
+ "bool",
969
+ False,
970
+ label="compare with the plastic strain alone",
971
+ when={"triaxiality": ["rice_tracey", "johnson_cook", "lemaitre"]},
972
+ ),
973
+ Field(
974
+ "phases",
975
+ "json",
976
+ label="per-phase parameters",
977
+ doc='changes of the material by phase, e.g. {"1": {"yield_stress": 0.8}}',
978
+ ),
979
+ Field(
980
+ "video",
981
+ "choice",
982
+ "damage",
983
+ choices=(
984
+ ("damage", "damage"),
985
+ ("triaxiality", "triaxiality"),
986
+ ("p", "cumulated plastic strain"),
987
+ ("none", "no video"),
988
+ ),
989
+ ),
990
+ ],
991
+ order=2,
992
+ groups=(
993
+ ("Specimen", "specimen"),
994
+ ("Loading", "strain"),
995
+ ("Material", "young"),
996
+ ("Output", "video", True),
997
+ ),
998
+ )
999
+ def ductile(p: dict, ctx) -> dict:
1000
+ from morphogen.micromorphic import DuctileProblem, MicromorphicDuctile
1001
+
1002
+ specimen = _specimen(p)
1003
+ h = float(min(specimen.spacing[:2]))
1004
+ length = float(p["length"] or 2.0 * h)
1005
+ law = p["triaxiality"]
1006
+ parameters = tuple(p["triaxiality_parameters"] or ())
1007
+ if law == "johnson_cook" and not parameters:
1008
+ parameters = (0.05, 3.44, -2.12)
1009
+ voce = tuple(p["voce"] or ())
1010
+ if len(voce) % 2 or len(voce) > 4:
1011
+ raise ValueError("voce: Q1, b1 (and Q2, b2)")
1012
+ common = dict(
1013
+ young=float(p["young"]),
1014
+ poisson=float(p["poisson"]),
1015
+ yield_stress=float(p["yield_stress"]),
1016
+ hardening=float(p["hardening"]),
1017
+ voce=tuple(zip(voce[::2], voce[1::2], strict=True)),
1018
+ length=length,
1019
+ onset=float(p["onset"]),
1020
+ critical=float(p["critical"]),
1021
+ max_damage=float(p["max_damage"]),
1022
+ )
1023
+ cases = [
1024
+ (law, MicromorphicDuctile(**common, triaxiality=law, triaxiality_parameters=parameters))
1025
+ ]
1026
+ if law != "none" and p["compare"]:
1027
+ cases.append(("none", MicromorphicDuctile(**common)))
1028
+ _check_size(specimen, 1, MAX_DOFS)
1029
+ weak = {"yield_stress": common["yield_stress"] * (1.0 - float(p.get("imperfection") or 0.0))}
1030
+ overrides = _overrides(p["phases"], "per-phase parameters")
1031
+ displacement = abs(float(p["strain"])) * specimen.lengths[1]
1032
+ ctx.progress(0.02, "mesh")
1033
+ mesh = specimen.mesh()
1034
+ runs = {}
1035
+ span = 0.9 / len(cases)
1036
+ for k, (name, material) in enumerate(cases):
1037
+ problem = DuctileProblem(
1038
+ mesh, _materials(specimen, material, overrides, weak), kinematics=p["kinematics"]
1039
+ )
1040
+ entries = _supports(problem, specimen, displacement, p["grips"])
1041
+ result = _run(
1042
+ problem,
1043
+ entries,
1044
+ ctx,
1045
+ steps=p["steps"],
1046
+ start=0.02 + k * span,
1047
+ span=span,
1048
+ label=f"triaxiality {name}",
1049
+ ordering="MMD_AT_PLUS_A",
1050
+ )
1051
+ runs[name] = (problem, result)
1052
+ ctx.progress(0.93, "figures")
1053
+ problem, result = runs[law]
1054
+ index = _voxel_index(problem.mesh, specimen)
1055
+ curves = {name: _curve(res, specimen, displacement) for name, (_, res) in runs.items()}
1056
+ label = {name: f"triaxiality: {name}" for name in runs}
1057
+ ylabel = "force per unit thickness" if specimen.planar else "force"
1058
+ ctx.figure(
1059
+ _curves_figure(
1060
+ {label[k]: (c["u"], c["force"]) for k, c in curves.items()},
1061
+ "displacement of the pulled face",
1062
+ ylabel,
1063
+ specimen.title,
1064
+ ),
1065
+ "force_displacement",
1066
+ "force-displacement",
1067
+ )
1068
+ rows = []
1069
+ for name, c in curves.items():
1070
+ rows += [
1071
+ {
1072
+ "triaxiality": name,
1073
+ "displacement": float(u),
1074
+ "force": float(f),
1075
+ "nominal_stress": float(s),
1076
+ }
1077
+ for u, f, s in zip(c["u"], c["force"], c["stress"], strict=True)
1078
+ ]
1079
+ ctx.table(rows, "force_displacement", "force-displacement")
1080
+ values = {
1081
+ "degrees of freedom": problem.space.n_dofs,
1082
+ "elements": problem.mesh.n_elements,
1083
+ "length ℓ": length,
1084
+ "steps": len(result.loads) - 1,
1085
+ "Newton iterations": int(np.sum(result.iterations)),
1086
+ }
1087
+ centres = problem.mesh.nodes[problem.mesh.elements[:, :4]].mean(axis=1)
1088
+ damages = {}
1089
+ for name, (prob, res) in runs.items():
1090
+ c = curves[name]
1091
+ damage = prob.damage(res.state)
1092
+ damages[name] = _on_voxels(index, damage, specimen.shape)
1093
+ values[f"peak force ({name})"] = float(c["force"].max())
1094
+ values[f"final force / peak ({name})"] = float(c["force"][-1] / c["force"].max())
1095
+ values[f"largest damage ({name})"] = float(damage.max())
1096
+ if specimen.notch:
1097
+ values[f"crack from the notch (d > 0.9), fraction of the ligament ({name})"] = _crack(
1098
+ damages[name], specimen
1099
+ )
1100
+ triax = problem.triaxiality(result.state)
1101
+ plastic = problem.plastic_strain(result.state)
1102
+ values["largest triaxiality"] = float(triax.max())
1103
+ if specimen.notch: # ahead of the notch: within ℓ of its tip
1104
+ tip = np.hypot(centres[:, 0] - specimen.notch, centres[:, 1] - specimen.lengths[1] / 2)
1105
+ ahead = (tip < max(length, 1.5 * h)) & (centres[:, 0] > specimen.notch)
1106
+ if ahead.any():
1107
+ values["triaxiality ahead of the notch"] = float(triax[ahead].mean())
1108
+ for name, (prob, res) in runs.items():
1109
+ values[f"damage ahead of the notch / mean ({name})"] = float(
1110
+ prob.damage(res.state)[ahead].mean() / max(prob.damage(res.state).mean(), 1e-30)
1111
+ )
1112
+ else:
1113
+ kappa = _on_voxels(index, result.state[:, :, 7].mean(axis=1), specimen.shape)
1114
+ values["band width (κ at half maximum, along y)"] = _band_width(_profile(kappa), h)
1115
+ maps = {
1116
+ f"damage ({law})": _section(damages[law]),
1117
+ "triaxiality": _section(_on_voxels(index, triax, specimen.shape)),
1118
+ "p": _section(_on_voxels(index, plastic, specimen.shape)),
1119
+ }
1120
+ if "none" in damages and law != "none":
1121
+ maps["damage (p alone)"] = _section(damages["none"])
1122
+ title = "end of the loading: damage, triaxiality η, cumulated plastic strain p"
1123
+ ctx.figure(_maps_figure(maps, specimen, title), "fields", "fields at the end")
1124
+ if not specimen.planar:
1125
+ _view_3d(
1126
+ ctx,
1127
+ problem,
1128
+ result.values,
1129
+ problem.damage(result.state),
1130
+ "view_damage",
1131
+ "damage",
1132
+ "inferno",
1133
+ (0.0, 1.0),
1134
+ )
1135
+ _vtu(
1136
+ ctx,
1137
+ problem,
1138
+ result.values,
1139
+ "ductile",
1140
+ {
1141
+ "damage": problem.damage(result.state),
1142
+ "triaxiality": triax,
1143
+ "p": plastic,
1144
+ "e": problem.driving(result.state),
1145
+ },
1146
+ )
1147
+ if p["video"] != "none":
1148
+ ctx.progress(0.96, "video")
1149
+ pick = {
1150
+ "damage": problem.damage,
1151
+ "triaxiality": problem.triaxiality,
1152
+ "p": problem.plastic_strain,
1153
+ }[p["video"]]
1154
+ frames = [_on_voxels(index, pick(s), specimen.shape) for s in result.states]
1155
+ _field_video(
1156
+ ctx, frames, specimen, f"video_{p['video']}", p["video"], _captions(curves[law])
1157
+ )
1158
+ return {"values": values, "title": f"Ductile damage: {specimen.title}"}
1159
+
1160
+
1161
+ # -- micromorphic damage (quasi-brittle) -----------------------------------------------------
1162
+
1163
+
1164
+ @tool(
1165
+ "brittle",
1166
+ "damage",
1167
+ "Micromorphic damage",
1168
+ "The micromorphic damage of quasi-brittle solids (Forest 2009; the implicit gradient "
1169
+ "model of Peerlings, de Borst, Brekelmans & de Vree 1996): a micromorphic equivalent "
1170
+ "strain χ - ℓ² Δχ = ε_eq (the modified von Mises strain, k times weaker in tension than "
1171
+ "in compression), the damage d = 1 - (κ0/κ)(1 - α + α exp(-β (κ - κ0))) of its largest "
1172
+ "value κ, and σ = (1 - d) C : ε: a crack is a band of damage whose width the length ℓ "
1173
+ "sets. A specimen pulled: the force-displacement curve, the fields of the damage and "
1174
+ "of κ, a video of the damage growing.",
1175
+ [
1176
+ *_specimen_fields("bar", imperfection=0.2),
1177
+ Field("strain", "float", 0.006, doc="nominal strain of the specimen at the end"),
1178
+ Field("steps", "int", 30),
1179
+ Field("kinematics", "choice", "small", choices=KINEMATICS),
1180
+ Field("young", "float", 1000.0),
1181
+ Field("poisson", "float", 0.2),
1182
+ Field("threshold", "float", 1e-3, label="threshold κ0"),
1183
+ Field("alpha", "float", 0.99, label="α", doc="the residual stress of the law: 1 - α"),
1184
+ Field("beta", "float", 100.0, label="β", doc="its rate of softening"),
1185
+ Field("ratio", "float", 10.0, label="ratio k", doc="compressive / tensile strength"),
1186
+ Field("max_damage", "float", 0.9999),
1187
+ Field("length", "float", label="length ℓ", unit="length", doc="blank: twice the voxels"),
1188
+ Field(
1189
+ "variational",
1190
+ "bool",
1191
+ False,
1192
+ doc="the stress derived from the free energy (a penalty that does not degrade)",
1193
+ ),
1194
+ Field(
1195
+ "phases",
1196
+ "json",
1197
+ label="per-phase parameters",
1198
+ doc='changes of the material by phase, e.g. {"1": {"threshold": 0.002}}',
1199
+ ),
1200
+ Field(
1201
+ "video",
1202
+ "choice",
1203
+ "damage",
1204
+ choices=(("damage", "damage"), ("kappa", "κ (largest χ)"), ("none", "no video")),
1205
+ ),
1206
+ ],
1207
+ order=3,
1208
+ groups=(
1209
+ ("Specimen", "specimen"),
1210
+ ("Loading", "strain"),
1211
+ ("Material", "young"),
1212
+ ("Output", "video", True),
1213
+ ),
1214
+ )
1215
+ def brittle(p: dict, ctx) -> dict:
1216
+ from morphogen.micromorphic import DamageProblem, MicromorphicDamage
1217
+
1218
+ specimen = _specimen(p)
1219
+ h = float(min(specimen.spacing[:2]))
1220
+ length = float(p["length"] or 2.0 * h)
1221
+ material = MicromorphicDamage(
1222
+ young=float(p["young"]),
1223
+ poisson=float(p["poisson"]),
1224
+ threshold=float(p["threshold"]),
1225
+ length=length,
1226
+ alpha=float(p["alpha"]),
1227
+ beta=float(p["beta"]),
1228
+ ratio=float(p["ratio"]),
1229
+ max_damage=float(p["max_damage"]),
1230
+ variational=bool(p["variational"]),
1231
+ )
1232
+ _check_size(specimen, 1, MAX_DOFS)
1233
+ weak = {"threshold": material.threshold * (1.0 - float(p.get("imperfection") or 0.0))}
1234
+ overrides = _overrides(p["phases"], "per-phase parameters")
1235
+ displacement = abs(float(p["strain"])) * specimen.lengths[1]
1236
+ ctx.progress(0.02, "mesh")
1237
+ problem = DamageProblem(
1238
+ specimen.mesh(), _materials(specimen, material, overrides, weak), kinematics=p["kinematics"]
1239
+ )
1240
+ entries = _supports(problem, specimen, displacement, p["grips"])
1241
+ result = _run(
1242
+ problem,
1243
+ entries,
1244
+ ctx,
1245
+ steps=p["steps"],
1246
+ start=0.02,
1247
+ span=0.9,
1248
+ label="micromorphic damage",
1249
+ ordering="MMD_AT_PLUS_A",
1250
+ predictor=True,
1251
+ )
1252
+ ctx.progress(0.93, "figures")
1253
+ index = _voxel_index(problem.mesh, specimen)
1254
+ curve = _curve(result, specimen, displacement)
1255
+ ylabel = "force per unit thickness" if specimen.planar else "force"
1256
+ ctx.figure(
1257
+ _curves_figure(
1258
+ {"micromorphic damage": (curve["u"], curve["force"])},
1259
+ "displacement of the pulled face",
1260
+ ylabel,
1261
+ specimen.title,
1262
+ ),
1263
+ "force_displacement",
1264
+ "force-displacement",
1265
+ )
1266
+ ctx.table(
1267
+ [
1268
+ {"displacement": float(u), "force": float(f), "nominal_stress": float(s)}
1269
+ for u, f, s in zip(curve["u"], curve["force"], curve["stress"], strict=True)
1270
+ ],
1271
+ "force_displacement",
1272
+ "force-displacement",
1273
+ )
1274
+ damage = problem.damage(result.state)
1275
+ kappa = result.state[:, :, 0].mean(axis=1)
1276
+ kappa_vox = _on_voxels(index, kappa, specimen.shape)
1277
+ damage_vox = _on_voxels(index, damage, specimen.shape)
1278
+ values = {
1279
+ "degrees of freedom": problem.space.n_dofs,
1280
+ "elements": problem.mesh.n_elements,
1281
+ "length ℓ": length,
1282
+ "steps": len(result.loads) - 1,
1283
+ "Newton iterations": int(np.sum(result.iterations)),
1284
+ "peak force": float(curve["force"].max()),
1285
+ "final force / peak": float(curve["force"][-1] / curve["force"].max()),
1286
+ "largest damage": float(damage.max()),
1287
+ "band width (κ at half maximum, along y)": _band_width(_profile(kappa_vox), h),
1288
+ }
1289
+ if specimen.notch:
1290
+ values["crack from the notch (d > 0.9), fraction of the ligament"] = _crack(
1291
+ damage_vox, specimen
1292
+ )
1293
+ ctx.figure(
1294
+ _maps_figure(
1295
+ {"damage": _section(damage_vox), "κ (largest χ)": _section(kappa_vox)},
1296
+ specimen,
1297
+ "end of the loading",
1298
+ ),
1299
+ "fields",
1300
+ "fields at the end",
1301
+ )
1302
+ if not specimen.planar:
1303
+ _view_3d(
1304
+ ctx, problem, result.values, damage, "view_damage", "damage", "inferno", (0.0, 1.0)
1305
+ )
1306
+ _vtu(ctx, problem, result.values, "damage", {"damage": damage, "kappa": kappa})
1307
+ if p["video"] != "none":
1308
+ ctx.progress(0.96, "video")
1309
+ column = 1 if p["video"] == "damage" else 0
1310
+ frames = [
1311
+ _on_voxels(index, s[:, :, column].mean(axis=1), specimen.shape) for s in result.states
1312
+ ]
1313
+ _field_video(
1314
+ ctx,
1315
+ frames,
1316
+ specimen,
1317
+ f"video_{p['video']}",
1318
+ "damage" if column else "kappa",
1319
+ _captions(curve),
1320
+ )
1321
+ return {"values": values, "title": f"Micromorphic damage: {specimen.title}"}