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,3881 @@
1
+ """The tools of the tab Mechanics: the nonlinear homogenization of a morphology along a
2
+ macroscopic loading path, by finite elements on the conforming mesh of its level set or by
3
+ FFT on its voxels, in small or finite strains (the periodic element of Z-set: the
4
+ macroscopic components prescribed as stresses are unknowns); its reduced model by the
5
+ nonuniform transformation field analysis (NTFA; Michel & Suquet 2003, 2004) against the
6
+ full field; a material point of a behaviour along a loading path, to calibrate its law;
7
+ the identification of a behaviour on runs of the workspace or the points of a test; the
8
+ linear tensors of a morphology (stiffness, thermal expansion, conductivity), with its
9
+ crystals; and the stiffness of a fibre network, an open foam or a random lattice as the
10
+ frame of beams of its framework (:mod:`morphogen.homogenization.networks`).
11
+
12
+ The behaviour of one phase of the form is elastic, von Mises elasto-(visco)plasticity
13
+ (Lemaitre & Chaboche: isotropic and kinematic hardening, Norton's viscosity), the crystal
14
+ plasticity of Méric & Cailletaud on the slip systems of its grains (turned by their
15
+ orientations), porous plasticity (Gurson-Tvergaard-Needleman, Rousselier, the elliptic
16
+ criterion of Abouaf), a material file of Z-set, or an MFront behaviour when MGIS is
17
+ installed; the other phases are elastic or voids, with the elastic constants of the form,
18
+ and the materials of the configurations may replace those of any phase. Stresses are in
19
+ the unit of the elastic moduli (the defaults take the modulus of the first phase, 1, as
20
+ unit); times in that of the viscosities."""
21
+
22
+ from __future__ import annotations
23
+
24
+ import importlib.util
25
+ import json
26
+ import time
27
+ import zipfile
28
+ from dataclasses import replace
29
+ from pathlib import Path
30
+
31
+ import numpy as np
32
+
33
+ from morphogen.gui.tools import Field, elastic_tables, tab, tool
34
+ from morphogen.homogenization.behaviours import HILL_COMPONENTS
35
+
36
+ tab(
37
+ "mechanics",
38
+ "Mechanics",
39
+ "The mechanics of a morphology of the workspace: its macroscopic response along a "
40
+ "loading path (strain, stress or mixed components over time; finite elements or FFT, "
41
+ "small or finite strains) with the fields of its steps, the reduced model of the "
42
+ "nonuniform transformation field analysis (NTFA) against the full field, a material "
43
+ "point to calibrate a behaviour, the identification of a behaviour on runs of the "
44
+ "workspace or the points of a test, the macroscopic law of a morphology in one go (its "
45
+ "tensions and shears, a von Mises or Hill law identified on them), the linear tensors "
46
+ "of the morphology, and the stiffness of a fibre network or an open foam as a frame of "
47
+ "beams.",
48
+ order=40,
49
+ )
50
+
51
+ #: The Voigt components of the loading paths (11, 22, 33, 23, 31, 12; engineering shears)
52
+ COMPONENTS = ("11", "22", "33", "23", "31", "12")
53
+ #: The stem of the files of the realization, as in the runs of configurations
54
+ STEM = "sample_0000"
55
+
56
+
57
+ #: The choice of a behaviour of the workspace (a material point, an import of Z-set)
58
+ KEPT = ("workspace", "a behaviour of the workspace (B: a material point, a Z-set file)")
59
+
60
+
61
+ def _behaviours() -> tuple:
62
+ """The behaviours offered for a phase (MFront when MGIS is installed), and those of the
63
+ workspace."""
64
+ out = [
65
+ ("elastic", "elastic"),
66
+ ("mises", "von Mises elasto-(visco)plasticity (Lemaitre-Chaboche)"),
67
+ ("crystal", "crystal plasticity of the grains (Méric-Cailletaud)"),
68
+ ("porous", "porous plasticity (Gurson-Tvergaard-Needleman, Rousselier, Abouaf)"),
69
+ ("zmat", "a material file of Z-set (gen_evp, porous_plastic)"),
70
+ ("viscoelastic", "linear viscoelasticity (generalized Maxwell: Prony series)"),
71
+ ("hyperelastic", "hyperelasticity (neo-Hookean to Ogden, foams, fibres; finite strains)"),
72
+ ("damage", "isotropic damage of quasi-brittle solids"),
73
+ ("mazars", "Mazars' damage of concrete (tension and compression)"),
74
+ ]
75
+ if importlib.util.find_spec("mgis") is not None:
76
+ out.append(("mfront", "an MFront behaviour (integrated by MGIS)"))
77
+ return (*out, KEPT)
78
+
79
+
80
+ def _kept_field() -> Field:
81
+ """The behaviour of the workspace chosen (an item: its material under ``"material"``)."""
82
+ return Field(
83
+ "kept",
84
+ "item",
85
+ label="behaviour of the workspace",
86
+ items=("behaviour",),
87
+ required=True,
88
+ when={"behaviour": "workspace"},
89
+ doc="with its own elasticity (the elastic constants of the form unused)",
90
+ )
91
+
92
+
93
+ FAMILIES = (
94
+ ("octahedral", "octahedral {111}<110> (FCC)"),
95
+ ("cube", "cube {100}<110>"),
96
+ ("bcc110", "{110}<111> (BCC)"),
97
+ ("bcc112", "{112}<111> (BCC)"),
98
+ ("basal", "basal (0001)<11-20> (hexagonal)"),
99
+ ("prismatic", "prismatic {10-10}<11-20> (hexagonal)"),
100
+ ("pyramidal_a", "pyramidal {10-11}<11-20> (hexagonal)"),
101
+ ("pyramidal_ca", "pyramidal {10-11}<11-23> (hexagonal, c + a)"),
102
+ ("pyramidal2_ca", "pyramidal {11-22}<11-23> (hexagonal, c + a)"),
103
+ )
104
+ TWIN_FAMILIES = (
105
+ ("twin111", "{111}<11-2> (FCC)"),
106
+ ("twin112", "{112}<11-1> (BCC)"),
107
+ ("twin1012", "{10-12}<10-1-1> (hexagonal)"),
108
+ ("twin1011", "{10-11}<10-1-2> (hexagonal)"),
109
+ ("twin1122", "{11-22}<11-2-3> (hexagonal)"),
110
+ ("twin1121", "{11-21}<-1-126> (hexagonal)"),
111
+ )
112
+ CLEAVAGE_PLANES = (
113
+ ("none", "none"),
114
+ ("cube", "{100} (cubic)"),
115
+ ("dodecahedral", "{110} (cubic)"),
116
+ ("octahedral", "{111} (cubic)"),
117
+ ("basal", "basal (0001) (hexagonal)"),
118
+ ("prismatic", "prismatic {10-10} (hexagonal)"),
119
+ )
120
+ CRITERIA = (
121
+ ("gurson", "Gurson-Tvergaard-Needleman"),
122
+ ("rousselier", "Rousselier"),
123
+ ("elliptic", "elliptic (Abouaf, Green, Shima-Oyane: powders, foams)"),
124
+ )
125
+ NUCLEATION = (
126
+ ("none", "none"),
127
+ ("gaussian", "Gaussian (Chu-Needleman): fN, εN, sN"),
128
+ ("constant", "constant: A"),
129
+ ("exponential", "exponential: B, ε0"),
130
+ )
131
+ #: A material file of Z-set in the unit of the defaults (E = 1)
132
+ ZMAT_EXAMPLE = """***behavior gen_evp
133
+ **elasticity isotropic
134
+ young 1.
135
+ poisson 0.3
136
+ **potential gen_evp ep
137
+ *criterion mises
138
+ *flow plasticity
139
+ *isotropic nonlinear
140
+ R0 0.002
141
+ Q 0.001
142
+ b 100.
143
+ ***return"""
144
+
145
+ #: The hyperelastic energies of the forms and the parameters they take, in their order
146
+ HYPERELASTIC = (
147
+ ("neo_hookean", "neo-Hookean: mu (blank: the shear modulus of the elastic constants)"),
148
+ ("mooney_rivlin", "Mooney-Rivlin: c10, c01 (then c20, c11, c02, c30, c21, c12, c03)"),
149
+ ("yeoh", "Yeoh: c10, c20, c30"),
150
+ ("arruda_boyce", "Arruda-Boyce (series): mu, locking stretch"),
151
+ ("eight_chain", "eight chains (inverse Langevin): mu, locking stretch"),
152
+ ("gent", "Gent: mu, Jm"),
153
+ ("van_der_waals", "van der Waals: mu, locking stretch, a, beta"),
154
+ ("fung", "Fung: mu, b"),
155
+ ("ogden", "Ogden: pairs mu, alpha"),
156
+ ("holzapfel", "Holzapfel-Gasser-Ogden: mu, k1, k2, kappa (and the fibres)"),
157
+ ("blatz_ko", "Blatz-Ko (compressible): mu, f"),
158
+ ("hyperfoam", "hyperfoam (compressible): pairs mu, alpha"),
159
+ )
160
+ #: (the least number of them: the others have defaults)
161
+ HYPERELASTIC_PARAMETERS = {
162
+ "neo_hookean": (("mu",), 1),
163
+ "mooney_rivlin": (("c10", "c01", "c20", "c11", "c02", "c30", "c21", "c12", "c03"), 2),
164
+ "yeoh": (("c10", "c20", "c30"), 1),
165
+ "arruda_boyce": (("mu", "lock"), 2),
166
+ "eight_chain": (("mu", "lock"), 2),
167
+ "gent": (("mu", "lock"), 2),
168
+ "van_der_waals": (("mu", "lock", "a", "beta"), 2),
169
+ "fung": (("mu", "b"), 2),
170
+ "holzapfel": (("mu", "k1", "k2", "kappa"), 3),
171
+ "blatz_ko": (("mu", "f"), 1),
172
+ }
173
+ VISCOELASTIC = {"behaviour": "viscoelastic"}
174
+ HYPER = {"behaviour": "hyperelastic"}
175
+ DAMAGE = {"behaviour": "damage"}
176
+ MAZARS = {"behaviour": "mazars"}
177
+ LEMAITRE = {"behaviour": "mises", "coupled_damage": ["lemaitre"]}
178
+ KACHANOV = {"behaviour": "mises", "coupled_damage": ["kachanov"]}
179
+ COUPLED = {"behaviour": "mises", "coupled_damage": ["lemaitre", "kachanov"]}
180
+ PLASTIC = {"behaviour": ["mises", "porous"]}
181
+ MISES = {"behaviour": "mises"}
182
+ CRYSTAL = {"behaviour": "crystal"}
183
+ CLEAVES = {"behaviour": "crystal", "cleavage": [c[0] for c in CLEAVAGE_PLANES[1:]]}
184
+ POROUS = {"behaviour": "porous"}
185
+
186
+
187
+ def _device_field(**kwargs) -> Field:
188
+ """Where the FFT solver of the paths runs."""
189
+ return Field(
190
+ "device",
191
+ "choice",
192
+ "cpu",
193
+ choices=(
194
+ ("cpu", "the CPU"),
195
+ ("gpu", "an NVIDIA GPU (CuPy): the points and the conjugate gradients there"),
196
+ ("auto", "the GPU when there is one"),
197
+ ),
198
+ doc="the GPU gains on images of 32 voxels per edge and more",
199
+ **kwargs,
200
+ )
201
+
202
+
203
+ def _plastic_fields(plastic=None, mises=None) -> tuple[Field, ...]:
204
+ """The fields of von Mises elasto-(visco)plasticity (also those of the matrix of porous
205
+ materials, its kinematic hardening included), shown when the fields of ``plastic``
206
+ (``mises``: Hill's criterion) have their values."""
207
+ return (
208
+ Field(
209
+ "yield_stress",
210
+ "float",
211
+ 0.002,
212
+ label="yield stress R0",
213
+ unit="stress",
214
+ when=plastic,
215
+ doc="that of the matrix of porous materials",
216
+ ),
217
+ Field("hardening", "float", 0.0, label="linear hardening H", unit="stress", when=plastic),
218
+ Field(
219
+ "isotropic",
220
+ "floats",
221
+ [0.001, 100.0],
222
+ label="isotropic hardening Q, b",
223
+ when=plastic,
224
+ doc="R(p) = R0 + H p + Σ Q (1 - exp(-b p)): pairs Q, b, at most three (Q = 0: none)",
225
+ ),
226
+ Field(
227
+ "kinematic",
228
+ "floats",
229
+ label="kinematic hardening C, D",
230
+ when=plastic,
231
+ doc="Armstrong-Frederick backstresses dX = 2/3 C dεp - D X dp: pairs C, D, at "
232
+ "most four (D = 0: linear, Prager; blank: none); porous materials: the criteria "
233
+ "gurson and elliptic of σ - X, X with its hydrostatic part",
234
+ ),
235
+ Field(
236
+ "norton",
237
+ "floats",
238
+ label="Norton viscosity K, n",
239
+ when=plastic,
240
+ doc="viscoplastic flow dp/dt = <f / K>^n (blank: rate-independent plasticity)",
241
+ ),
242
+ Field(
243
+ "hill",
244
+ "floats",
245
+ label="Hill's criterion h11, h22, h33, h12, h23, h31",
246
+ when=mises,
247
+ doc="anisotropic plasticity: f = sqrt(3/2 s : M : s) - R, M = diag(h) on the "
248
+ "components of the deviator s (Z-set's hill1 ... hill6; yield stress in tension "
249
+ "along 1: R0 sqrt(6 / (4 h11 + h22 + h33)), in shear 12: R0 / sqrt(3 h12)); blank: "
250
+ "von Mises (all 1)",
251
+ ),
252
+ )
253
+
254
+
255
+ def _behaviour_fields(doc: str = "") -> tuple[Field, ...]:
256
+ """The fields of the behaviour of a phase or of a material point (``doc``: that of the
257
+ choice of the behaviour)."""
258
+ choices = _behaviours()
259
+ gurson = {"behaviour": "porous", "criterion": "gurson"}
260
+ nucleating = {"behaviour": "porous", "nucleation": ["gaussian", "constant", "exponential"]}
261
+ fields = [
262
+ Field("behaviour", "choice", "mises", choices=choices, doc=doc),
263
+ _kept_field(),
264
+ *_plastic_fields(PLASTIC, MISES),
265
+ Field(
266
+ "coupled_damage",
267
+ "choice",
268
+ "none",
269
+ label="damage of the plastic phase",
270
+ choices=(
271
+ ("none", "none"),
272
+ ("lemaitre", "Lemaitre: ductile damage, by the plastic strain"),
273
+ ("kachanov", "Kachanov-Rabotnov: creep damage, by the time under stress"),
274
+ ),
275
+ when=MISES,
276
+ doc="the plasticity is that of the effective stress σ / (1 - D), the stress (1 - "
277
+ "D) of it; the variable p of the results is then the damage D",
278
+ ),
279
+ Field(
280
+ "lemaitre",
281
+ "floats",
282
+ [2.0, 1.0],
283
+ label="Lemaitre's S, s",
284
+ when=LEMAITRE,
285
+ doc="dD = (Y / S)^s dp, Y = σ_eq² R_ν / (2 E) the energy release rate of the "
286
+ "effective stress with the triaxiality function R_ν (S: a stress)",
287
+ ),
288
+ Field(
289
+ "damage_threshold",
290
+ "float",
291
+ 0.0,
292
+ label="plastic strain at which the damage starts",
293
+ when=LEMAITRE,
294
+ ),
295
+ Field(
296
+ "closure",
297
+ "float",
298
+ 1.0,
299
+ label="closure of the microcracks h",
300
+ when=LEMAITRE,
301
+ doc="the share of the compressions in Y (1: as the tensions; 0.2 for metals)",
302
+ ),
303
+ Field(
304
+ "kachanov",
305
+ "floats",
306
+ [500.0, 4.0],
307
+ label="Kachanov's A, r (and k)",
308
+ when=KACHANOV,
309
+ doc="dD/dt = (χ / A)^r (1 - D)^-k (A: a stress; k: r if not given): under a "
310
+ "constant stress the time to rupture is 1 / ((k + 1) (χ / A)^r); a viscoplastic "
311
+ "phase (Norton)",
312
+ ),
313
+ Field(
314
+ "hayhurst",
315
+ "floats",
316
+ label="Hayhurst's weights α, β",
317
+ when=KACHANOV,
318
+ doc="χ = α σ_I + 3 β σ_m + (1 - α - β) σ_eq (blank: von Mises' stress)",
319
+ ),
320
+ Field(
321
+ "critical_damage",
322
+ "float",
323
+ label="damage of a broken point",
324
+ when=COUPLED,
325
+ doc="a point whose damage reaches it keeps a millionth of its stress (blank: "
326
+ "the damage grows up to 1)",
327
+ ),
328
+ Field(
329
+ "coupled_viscosity",
330
+ "float",
331
+ 0.0,
332
+ label="time of the delayed damage",
333
+ when=COUPLED,
334
+ doc="a viscous regularization (0: none): the damage of the stress follows that "
335
+ "of the law with this delay, which keeps the softening of a morphology well "
336
+ "posed along its loading path",
337
+ ),
338
+ Field(
339
+ "families",
340
+ "choices",
341
+ ["octahedral"],
342
+ label="slip families",
343
+ choices=FAMILIES,
344
+ when=CRYSTAL,
345
+ ),
346
+ Field(
347
+ "cubic",
348
+ "floats",
349
+ label="cubic elasticity C11, C12, C44",
350
+ unit="stress",
351
+ when=CRYSTAL,
352
+ doc="in the axes of the crystal (blank: the isotropic elasticity of the phase)",
353
+ ),
354
+ Field(
355
+ "tau0",
356
+ "float",
357
+ 0.0008,
358
+ label="critical resolved shear stress τ0",
359
+ unit="stress",
360
+ when=CRYSTAL,
361
+ ),
362
+ Field(
363
+ "slip_isotropic",
364
+ "floats",
365
+ [0.0001, 10.0],
366
+ label="slip hardening Q, b",
367
+ when=CRYSTAL,
368
+ doc="r = τ0 + Q Σ_r h_sr (1 - exp(-b v_r)) of the cumulated slips v (Q = 0: none)",
369
+ ),
370
+ Field(
371
+ "slip_kinematic",
372
+ "floats",
373
+ label="slip kinematic hardening C, D",
374
+ when=CRYSTAL,
375
+ doc="x = C α, dα = dγ - D α |dγ| (blank: none)",
376
+ ),
377
+ Field(
378
+ "slip_viscosity",
379
+ "floats",
380
+ [0.0002, 10.0],
381
+ label="slip viscosity K, n",
382
+ when=CRYSTAL,
383
+ doc="dγ/dt = <(|τ - x| - r) / K>^n",
384
+ ),
385
+ Field(
386
+ "interaction",
387
+ "floats",
388
+ label="interaction matrix",
389
+ when=CRYSTAL,
390
+ doc="h_self, h_latent; or the six coefficients of the octahedral systems (self, "
391
+ "coplanar, Hirth, collinear, glissile, Lomer); blank: uniform (Taylor)",
392
+ ),
393
+ Field(
394
+ "hexagonal",
395
+ "floats",
396
+ label="hexagonal elasticity C11, C12, C13, C33, C44",
397
+ unit="stress",
398
+ when=CRYSTAL,
399
+ doc="in the axes of the crystal, c along the third (blank: the cubic or the "
400
+ "isotropic elasticity)",
401
+ ),
402
+ Field(
403
+ "c_over_a",
404
+ "float",
405
+ label="ratio c / a",
406
+ when=CRYSTAL,
407
+ doc="of a hexagonal lattice: for its slip families, its twins and its cleavage "
408
+ "planes (magnesium 1.624, titanium 1.587, zinc 1.856)",
409
+ ),
410
+ Field(
411
+ "twins",
412
+ "choices",
413
+ [],
414
+ label="twin families",
415
+ choices=TWIN_FAMILIES,
416
+ when=CRYSTAL,
417
+ doc="systems that shear in one sense, and back, until the crystal has twinned "
418
+ "(the hardening and the viscosity of the slip)",
419
+ ),
420
+ Field(
421
+ "twin_tau0",
422
+ "float",
423
+ label="critical resolved shear stress of the twins",
424
+ unit="stress",
425
+ when=CRYSTAL,
426
+ doc="blank: that of the slip",
427
+ ),
428
+ Field(
429
+ "twin_saturation",
430
+ "float",
431
+ 1.0,
432
+ label="twinned fraction at saturation",
433
+ when=CRYSTAL,
434
+ doc="the fraction of the crystal that may twin",
435
+ ),
436
+ Field(
437
+ "twin_reorientation",
438
+ "float",
439
+ label="twinned fraction that turns the lattice",
440
+ when=CRYSTAL,
441
+ doc="at this fraction the lattice of a point becomes that of its predominant "
442
+ "twin, which slips and twins as the twin does, and twins back (blank: the "
443
+ "lattice does not turn)",
444
+ ),
445
+ Field(
446
+ "twin_reorientation_growth",
447
+ "float",
448
+ label="growth of that fraction, grain by grain",
449
+ when=CRYSTAL,
450
+ doc="given (0 or more), the lattices are turned grain by grain: the most "
451
+ "twinned points first, while the turned volume of the grain is below its "
452
+ "twinned volume, past the fraction above plus this times their ratio (blank: "
453
+ "point by point, at the fraction above)",
454
+ ),
455
+ Field(
456
+ "twin_detwinning",
457
+ "bool",
458
+ True,
459
+ label="the twins shear back",
460
+ when=CRYSTAL,
461
+ doc="when the stress is reversed, down to no twin (detwinning)",
462
+ ),
463
+ Field(
464
+ "twin_detwinning_share",
465
+ "float",
466
+ 1.0,
467
+ label="share of their resistance on the way back",
468
+ when=CRYSTAL,
469
+ doc="the twins shear back at this share of the resistance of the twinning (no "
470
+ "twin to nucleate: below 1)",
471
+ ),
472
+ Field(
473
+ "cleavage",
474
+ "choice",
475
+ "none",
476
+ label="cleavage planes",
477
+ choices=CLEAVAGE_PLANES,
478
+ when=CRYSTAL,
479
+ doc="planes that open at a normal stress and soften (the crack band)",
480
+ ),
481
+ Field(
482
+ "cleavage_strength",
483
+ "float",
484
+ label="cleavage strength",
485
+ unit="stress",
486
+ when=CLEAVES,
487
+ doc="the normal stress that opens a plane",
488
+ ),
489
+ Field(
490
+ "cleavage_energy",
491
+ "float",
492
+ label="fracture energy of the planes",
493
+ when=CLEAVES,
494
+ doc="per unit area, dissipated in a band of the size below",
495
+ ),
496
+ Field(
497
+ "cleavage_length",
498
+ "float",
499
+ label="size of the elements of the band",
500
+ unit="length",
501
+ when=CLEAVES,
502
+ doc="that of the voxels or of the elements: below stiffness x energy / strength²",
503
+ ),
504
+ Field(
505
+ "cleavage_band",
506
+ "float",
507
+ label="width of the damage band of the planes",
508
+ unit="length",
509
+ when=CLEAVES,
510
+ doc="the planes regularized by their microdamage: they break across a band of "
511
+ "this width (some elements), where their fracture energy is dissipated, "
512
+ "whatever the size of the elements (blank: across one element, of the size "
513
+ "above)",
514
+ ),
515
+ Field(
516
+ "cleavage_viscosity",
517
+ "floats",
518
+ label="viscosity of the planes K, n",
519
+ when=CLEAVES,
520
+ doc="of their opening (blank: that of the slip); a crack that crosses the cell "
521
+ "at once passes with it",
522
+ ),
523
+ Field(
524
+ "cleavage_closure",
525
+ "bool",
526
+ True,
527
+ label="the planes close under pressure",
528
+ when=CLEAVES,
529
+ doc="their opening goes back, and the closed plane carries the pressure; "
530
+ "otherwise it stays open",
531
+ ),
532
+ Field(
533
+ "cleavage_closure_share",
534
+ "float",
535
+ 1.0,
536
+ label="share of their strength at which they close",
537
+ when=CLEAVES,
538
+ doc="a plane that is not broken through closes under this share of the "
539
+ "strength that it has left (1: all of it; near 0: freely)",
540
+ ),
541
+ Field(
542
+ "cleavage_friction",
543
+ "float",
544
+ 0.0,
545
+ label="friction of the planes",
546
+ when=CLEAVES,
547
+ doc="Coulomb's coefficient of the lips of a plane under pressure (0: they "
548
+ "slide freely)",
549
+ ),
550
+ Field(
551
+ "cleavage_coupling",
552
+ "float",
553
+ 0.0,
554
+ label="coupling of the planes with the slip",
555
+ when=CLEAVES,
556
+ doc="the strength of the planes falls as exp(-coupling x cumulated slip): the "
557
+ "slip nucleates the cleavage, and the damage of the planes eases the slip (0: "
558
+ "a constant strength)",
559
+ ),
560
+ Field("criterion", "choice", "gurson", choices=CRITERIA, when=POROUS),
561
+ Field("porosity", "float", 0.01, label="initial porosity f0", when=POROUS),
562
+ Field(
563
+ "gurson",
564
+ "floats",
565
+ [1.5, 1.0],
566
+ label="q1, q2 (q3)",
567
+ when=gurson,
568
+ doc="(Σeq / σ*)² + 2 q1 f* cosh(3 q2 Σm / 2σ*) - 1 - q3 f*² = 0 (q3: q1² by default)",
569
+ ),
570
+ Field(
571
+ "coalescence",
572
+ "floats",
573
+ label="coalescence fc, fF",
574
+ when=gurson,
575
+ doc="Tvergaard-Needleman: f* grows faster beyond fc, to 1/q1 at fF (blank: f* = f)",
576
+ ),
577
+ Field(
578
+ "rousselier",
579
+ "floats",
580
+ [0.0013, 2.0],
581
+ label="σ1, D (q2)",
582
+ when={"behaviour": "porous", "criterion": "rousselier"},
583
+ doc="σ* = Σeq / (1 - f) + D σ1 f exp(q2 Σm / ((1 - f) σ1)) (q2: 1 by default)",
584
+ ),
585
+ Field(
586
+ "elliptic",
587
+ "floats",
588
+ [1.2, 0.05],
589
+ label="C, F",
590
+ when={"behaviour": "porous", "criterion": "elliptic"},
591
+ doc="σ*² = C Σeq² + F I1² (C = 1, F = 0: von Mises; the configurations take "
592
+ "tables of the porosity)",
593
+ ),
594
+ Field("nucleation", "choice", "none", choices=NUCLEATION, when=POROUS),
595
+ Field(
596
+ "nucleation_coefficients",
597
+ "floats",
598
+ when=nucleating,
599
+ doc="gaussian: fN, εN, sN; constant: A; exponential: B, ε0; then optionally "
600
+ "the cumulated plastic strain below which none nucleates",
601
+ ),
602
+ Field(
603
+ "zmat",
604
+ "text",
605
+ ZMAT_EXAMPLE,
606
+ label="Z-set material file",
607
+ when={"behaviour": "zmat"},
608
+ doc="its text, or the path of the file: gen_evp (one von Mises potential, "
609
+ "else through MFront) or porous_plastic; its elasticity replaces that of the "
610
+ "phase",
611
+ ),
612
+ Field(
613
+ "prony_shear",
614
+ "floats",
615
+ [0.5, 1.0],
616
+ label="Prony series of the shear modulus g, τ",
617
+ when=VISCOELASTIC,
618
+ doc="G(t) = G0 (1 - Σ g (1 - exp(-t / τ))): pairs g, τ, the elastic constants "
619
+ "above the instantaneous ones (the sum of the g below 1)",
620
+ ),
621
+ Field(
622
+ "prony_bulk",
623
+ "floats",
624
+ label="Prony series of the bulk modulus k, τ",
625
+ when=VISCOELASTIC,
626
+ doc="pairs k, τ (blank: an elastic bulk response)",
627
+ ),
628
+ Field(
629
+ "hyper_model",
630
+ "choice",
631
+ "neo_hookean",
632
+ label="strain energy",
633
+ choices=HYPERELASTIC,
634
+ when=HYPER,
635
+ ),
636
+ Field(
637
+ "hyper_parameters",
638
+ "floats",
639
+ label="parameters of the energy",
640
+ unit="stress",
641
+ when=HYPER,
642
+ doc="in the order of the model (neo-Hookean, blank: the elastic constants "
643
+ "above); given, the elasticity is that of the energy (finite strains: the "
644
+ "kinematics of the loading)",
645
+ ),
646
+ Field(
647
+ "hyper_bulk",
648
+ "float",
649
+ label="bulk modulus of the energy",
650
+ unit="stress",
651
+ when=HYPER,
652
+ doc="U(J) = K/2 (J - 1)² (blank: that of the elastic constants above); the "
653
+ "compressible energies take their Poisson's ratio from it",
654
+ ),
655
+ Field(
656
+ "hyper_fibres",
657
+ "floats",
658
+ label="directions of the fibres",
659
+ when={"behaviour": "hyperelastic", "hyper_model": "holzapfel"},
660
+ doc="x, y, z of each family of fibres (Holzapfel-Gasser-Ogden), in the axes of "
661
+ "the morphology: they carry tension only",
662
+ ),
663
+ Field(
664
+ "hyper_mullins",
665
+ "floats",
666
+ label="Mullins softening r, m, β",
667
+ when=HYPER,
668
+ doc="Ogden and Roxburgh: on the way back from a stretch the isochoric stress is "
669
+ "that of the virgin solid times 1 - erf((Wm - W) / (m + β Wm)) / r, Wm the "
670
+ "largest energy reached (blank: none)",
671
+ ),
672
+ Field(
673
+ "strength",
674
+ "float",
675
+ 0.002,
676
+ label="tensile strength",
677
+ unit="stress",
678
+ when=DAMAGE,
679
+ doc="the damage starts at the equivalent strain strength / E",
680
+ ),
681
+ Field(
682
+ "ultimate",
683
+ "float",
684
+ 0.02,
685
+ label="ultimate strain of the softening",
686
+ when=DAMAGE,
687
+ doc="no stress beyond it (linear softening), or the strain of the exponential "
688
+ "decay; blank with a fracture energy",
689
+ ),
690
+ Field(
691
+ "fracture_energy",
692
+ "float",
693
+ label="fracture energy",
694
+ when=DAMAGE,
695
+ doc="per unit area, dissipated by a band of the size below (the crack band of "
696
+ "Bažant and Oh): the softening then does not depend on the elements",
697
+ ),
698
+ Field(
699
+ "damage_length",
700
+ "float",
701
+ label="size of the elements of the band",
702
+ unit="length",
703
+ when=DAMAGE,
704
+ doc="that of the voxels or of the elements (with the fracture energy)",
705
+ ),
706
+ Field(
707
+ "softening",
708
+ "choice",
709
+ "exponential",
710
+ choices=("exponential", "linear"),
711
+ when=DAMAGE,
712
+ ),
713
+ Field(
714
+ "equivalent",
715
+ "choice",
716
+ "mazars",
717
+ label="equivalent strain",
718
+ choices=(
719
+ ("mazars", "Mazars: the positive principal strains"),
720
+ ("energy", "the energy norm (as much in compression)"),
721
+ ("mises", "modified von Mises (de Vree et al.)"),
722
+ ),
723
+ when=DAMAGE,
724
+ ),
725
+ Field(
726
+ "damage_viscosity",
727
+ "float",
728
+ 0.0,
729
+ label="time of the delayed damage",
730
+ when=DAMAGE,
731
+ doc="a viscous regularization (0: none): it keeps the softening of a "
732
+ "morphology well posed along its loading path",
733
+ ),
734
+ Field(
735
+ "damage_split",
736
+ "choice",
737
+ "none",
738
+ label="stiffness of closed cracks",
739
+ choices=(
740
+ ("none", "none: as soft in compression"),
741
+ ("volumetric", "the bulk response in compression (Amor et al.)"),
742
+ ("spectral", "the negative principal strains (Miehe et al.): unilateral"),
743
+ ),
744
+ when=DAMAGE,
745
+ ),
746
+ Field(
747
+ "mazars_threshold",
748
+ "float",
749
+ 1e-4,
750
+ label="strain at which the damage starts",
751
+ when=MAZARS,
752
+ ),
753
+ Field(
754
+ "mazars_tension",
755
+ "floats",
756
+ [1.0, 15000.0],
757
+ label="tension A_t, B_t",
758
+ when=MAZARS,
759
+ doc="d_t = 1 - κ0 (1 - A_t) / κ - A_t exp(-B_t (κ - κ0)), κ the largest norm of "
760
+ "the positive principal strains",
761
+ ),
762
+ Field(
763
+ "mazars_compression",
764
+ "floats",
765
+ [1.2, 1500.0],
766
+ label="compression A_c, B_c",
767
+ when=MAZARS,
768
+ doc="the damage is α_t^β d_t + α_c^β d_c, by the shares of the positive strains "
769
+ "that the tensions and the compressions make",
770
+ ),
771
+ Field(
772
+ "mazars_beta",
773
+ "float",
774
+ 1.0,
775
+ label="exponent β of the shares",
776
+ when=MAZARS,
777
+ doc="1; 1.06 lessens the damage in shear",
778
+ ),
779
+ ]
780
+ if any(c[0] == "mfront" for c in choices):
781
+ mf = {"behaviour": "mfront"}
782
+ fields += [
783
+ Field(
784
+ "mfront",
785
+ "str",
786
+ label="MFront source or library",
787
+ when=mf,
788
+ doc="a .mfront file (compiled by mfront --obuild) or a library of the "
789
+ "generic interface",
790
+ ),
791
+ Field(
792
+ "mfront_behaviour",
793
+ "str",
794
+ label="behaviour of the library",
795
+ when=mf,
796
+ doc="blank: the stem of the source",
797
+ ),
798
+ Field("mfront_parameters", "text", label="parameters (JSON)", when=mf),
799
+ Field("mfront_properties", "text", label="material properties (JSON)", when=mf),
800
+ ]
801
+ return tuple(fields)
802
+
803
+
804
+ LOADINGS = (
805
+ ("tension", "monotonic: a strain component to the amplitude, the other stresses free"),
806
+ ("cycle", "cycle: the strain to + and - the amplitude, then back to zero"),
807
+ ("relaxation", "relaxation: the strain reached, then held"),
808
+ ("creep", "creep: a stress component reached, then held"),
809
+ ("custom", "custom: strain, stress or mixed components over time"),
810
+ )
811
+ PRESETS = ["tension", "cycle", "relaxation", "creep"]
812
+
813
+
814
+ def _path_fields(
815
+ default: str = "tension", prefix: str = "", amplitude: float = 0.01
816
+ ) -> tuple[Field, ...]:
817
+ """The fields of a loading path (their names after ``prefix``): a preset of one
818
+ component, or the components over time in the compact text of
819
+ :meth:`~morphogen.homogenization.paths.LoadingPath.parse`."""
820
+ loading = f"{prefix}loading"
821
+ presets = {loading: PRESETS}
822
+ return (
823
+ Field(loading, "choice", default, label="loading", choices=LOADINGS),
824
+ Field(
825
+ f"{prefix}component",
826
+ "choice",
827
+ "11",
828
+ label="component",
829
+ choices=COMPONENTS,
830
+ when=presets,
831
+ ),
832
+ Field(
833
+ f"{prefix}amplitude",
834
+ "float",
835
+ amplitude,
836
+ label="strain amplitude",
837
+ when={loading: ["tension", "cycle", "relaxation"]},
838
+ doc="engineering shear strains (twice the tensor component)",
839
+ ),
840
+ Field(
841
+ f"{prefix}stress",
842
+ "float",
843
+ 0.0025,
844
+ label="stress",
845
+ unit="stress",
846
+ when={loading: "creep"},
847
+ ),
848
+ Field(
849
+ f"{prefix}duration",
850
+ "float",
851
+ 1.0,
852
+ label="loading time",
853
+ unit="time",
854
+ when=presets,
855
+ doc="of the ramp (of each quarter of the cycle)",
856
+ ),
857
+ Field(
858
+ f"{prefix}hold",
859
+ "float",
860
+ 10.0,
861
+ label="hold time",
862
+ unit="time",
863
+ when={loading: ["relaxation", "creep"]},
864
+ ),
865
+ Field(
866
+ f"{prefix}increments",
867
+ "int",
868
+ 10,
869
+ label="increments",
870
+ when=presets,
871
+ doc="of each ramp (a step that does not converge is divided)",
872
+ ),
873
+ Field(
874
+ f"{prefix}path",
875
+ "text",
876
+ "t=0,1,2 n=10 E11=0,0.01,0.01 S12=0,0,0.002",
877
+ label="components over time",
878
+ when={loading: "custom"},
879
+ doc="the times t, increments n of each segment, strain components E11 ... E12 "
880
+ "(engineering shears) and stress components S11 ... S12 at the times (one "
881
+ "value: reached at the end of the first segment and held), the change of "
882
+ "temperature dT; the others free (zero stress). Or a JSON mapping {times, "
883
+ "increments, strain, stress, temperature}",
884
+ ),
885
+ )
886
+
887
+
888
+ def _path(p: dict, prefix: str = "") -> tuple[str, dict]:
889
+ """The name and the specification (:meth:`LoadingPath.from_spec`, checked) of the
890
+ loading path of the form."""
891
+ from morphogen.homogenization.paths import LoadingPath
892
+
893
+ kind = p[f"{prefix}loading"]
894
+ if kind == "custom":
895
+ text = (p[f"{prefix}path"] or "").strip()
896
+ if not text:
897
+ raise ValueError("components over time: e.g. t=0,1 n=10 E11=0,0.01")
898
+ spec = _json(text, "components over time") if text.startswith("{") else None
899
+ path = LoadingPath.from_spec(spec) if spec is not None else LoadingPath.parse(text)
900
+ return "path", path.to_dict() if spec is None else spec
901
+ c = p[f"{prefix}component"]
902
+ d, n = p[f"{prefix}duration"], p[f"{prefix}increments"]
903
+ if not d > 0 or n < 1:
904
+ raise ValueError("loading time: positive, and at least one increment")
905
+ a, hold = p[f"{prefix}amplitude"], p[f"{prefix}hold"]
906
+ if kind in ("relaxation", "creep") and not hold > 0:
907
+ raise ValueError("hold time: positive")
908
+ if kind == "tension":
909
+ spec = {"times": [0.0, d], "increments": n, "strain": {c: [0.0, a]}}
910
+ elif kind == "cycle":
911
+ times = [0.0, d, 3 * d, 4 * d]
912
+ spec = {"times": times, "increments": [n, 2 * n, n], "strain": {c: [0.0, a, -a, 0.0]}}
913
+ elif kind == "relaxation":
914
+ spec = {"times": [0.0, d, d + hold], "increments": [n, n], "strain": {c: [0.0, a, a]}}
915
+ else:
916
+ s = p[f"{prefix}stress"]
917
+ spec = {"times": [0.0, d, d + hold], "increments": [n, n], "stress": {c: [0.0, s, s]}}
918
+ LoadingPath.from_spec(spec) # checked
919
+ return kind, spec
920
+
921
+
922
+ def _json(text, name: str):
923
+ """A JSON value of a text field (None when blank)."""
924
+ if text is None or (isinstance(text, str) and not text.strip()):
925
+ return None
926
+ if not isinstance(text, str):
927
+ return text
928
+ try:
929
+ return json.loads(text)
930
+ except json.JSONDecodeError as exc:
931
+ raise ValueError(f"{name}: not valid JSON ({exc.msg} at character {exc.pos})") from None
932
+
933
+
934
+ # -- behaviours ------------------------------------------------------------------------------
935
+
936
+
937
+ def _pairs(values, name: str, first: str, second: str, most: int) -> list[dict]:
938
+ """The pairs of a field of numbers ``a1, b1, a2, b2...`` (``{first: a, second: b}``)."""
939
+ values = list(values or [])
940
+ if len(values) % 2 or len(values) > 2 * most:
941
+ raise ValueError(f"{name}: pairs {first}, {second} (at most {most})")
942
+ return [{first: values[k], second: values[k + 1]} for k in range(0, len(values), 2)]
943
+
944
+
945
+ def _two(values, name: str, first: str, second: str, optional: str = "") -> list[float]:
946
+ """The two numbers of a field (and an optional third one)."""
947
+ values = list(values or [])
948
+ if len(values) not in ((2, 3) if optional else (2,)):
949
+ extra = f" (and {optional})" if optional else ""
950
+ raise ValueError(f"{name}: two numbers {first}, {second}{extra}")
951
+ return values
952
+
953
+
954
+ def _norton(p: dict) -> dict:
955
+ if not p.get("norton"):
956
+ return {}
957
+ k, n = _two(p["norton"], "Norton viscosity", "K", "n")
958
+ return {"norton": {"K": k, "n": n}}
959
+
960
+
961
+ def _plasticity(p: dict) -> dict:
962
+ """The von Mises plasticity of the form (:meth:`Plasticity.from_config`)."""
963
+ out = {"yield": p["yield_stress"], "hardening": p["hardening"] or 0.0}
964
+ iso = [t for t in _pairs(p.get("isotropic"), "isotropic hardening", "Q", "b", 3) if t["Q"]]
965
+ if iso:
966
+ out["isotropic"] = iso
967
+ kin = _pairs(p.get("kinematic"), "kinematic hardening", "C", "D", 4)
968
+ if kin:
969
+ out["kinematic"] = kin
970
+ if p.get("hill"):
971
+ hill = list(p["hill"])
972
+ if len(hill) != 6:
973
+ raise ValueError("Hill's criterion: six coefficients h11, h22, h33, h12, h23, h31")
974
+ out["hill"] = dict(zip(HILL_COMPONENTS, hill, strict=True))
975
+ return {**out, **_norton(p)}
976
+
977
+
978
+ def _crystal(p: dict) -> dict:
979
+ """The crystal plasticity of the form (:meth:`CrystalPlasticity.from_config`)."""
980
+ q, b = _two(p.get("slip_isotropic") or [0.0, 0.0], "slip hardening", "Q", "b")
981
+ c, d = _two(p.get("slip_kinematic") or [0.0, 0.0], "slip kinematic hardening", "C", "D")
982
+ if not p.get("slip_viscosity"):
983
+ raise ValueError("slip viscosity: K, n (crystal plasticity is viscoplastic)")
984
+ k, n = _two(p["slip_viscosity"], "slip viscosity", "K", "n")
985
+ out = {
986
+ "families": p.get("families") or ["octahedral"],
987
+ "tau0": p["tau0"],
988
+ "Q": q,
989
+ "b": b if q else 0.0,
990
+ "C": c,
991
+ "D": d,
992
+ "K": k,
993
+ "n": n,
994
+ }
995
+ if p.get("interaction"):
996
+ out["interaction"] = list(p["interaction"])
997
+ if p.get("c_over_a"):
998
+ out["c_over_a"] = p["c_over_a"]
999
+ twins = list(p.get("twins") or [])
1000
+ if twins:
1001
+ own = {"tau0": p["twin_tau0"]} if p.get("twin_tau0") else {}
1002
+ out["twins"] = {name: dict(own) for name in twins}
1003
+ if p.get("twin_saturation") not in (None, 1.0):
1004
+ out["twin_saturation"] = p["twin_saturation"]
1005
+ growth = p.get("twin_reorientation_growth")
1006
+ if p.get("twin_reorientation"):
1007
+ turn = p["twin_reorientation"]
1008
+ out["twin_reorientation"] = (
1009
+ turn if growth is None else {"threshold": turn, "growth": growth}
1010
+ )
1011
+ elif growth is not None:
1012
+ raise ValueError(
1013
+ "growth of the fraction that turns the lattice: give that fraction (the "
1014
+ "threshold of the grains before any of their lattices is turned)"
1015
+ )
1016
+ if p.get("twin_detwinning") is False:
1017
+ out["twin_detwinning"] = False
1018
+ elif p.get("twin_detwinning_share") not in (None, 1.0):
1019
+ out["twin_detwinning"] = p["twin_detwinning_share"]
1020
+ planes = p.get("cleavage") or "none"
1021
+ if planes != "none":
1022
+ if not p.get("cleavage_strength"):
1023
+ raise ValueError("cleavage strength: the normal stress that opens the planes")
1024
+ band = p.get("cleavage_band")
1025
+ if not (p.get("cleavage_energy") and (band or p.get("cleavage_length"))):
1026
+ raise ValueError(
1027
+ "cleavage: the fracture energy of the planes and the size of the elements "
1028
+ "that dissipate it (those of the voxels or of the mesh), or the width of "
1029
+ "the damage band of the planes"
1030
+ )
1031
+ spec = {"planes": planes, "strength": p["cleavage_strength"]}
1032
+ spec["energy"] = p["cleavage_energy"]
1033
+ if band: # regularized by their microdamage: the energy is that of their band
1034
+ spec["regularization"] = {"width": band}
1035
+ else:
1036
+ spec["length"] = p["cleavage_length"]
1037
+ if p.get("cleavage_viscosity"):
1038
+ spec["K"], spec["n"] = _two(
1039
+ p["cleavage_viscosity"], "viscosity of the planes", "K", "n"
1040
+ )
1041
+ if p.get("cleavage_closure") is False:
1042
+ spec["closure"] = False
1043
+ elif p.get("cleavage_closure_share") not in (None, 1.0):
1044
+ spec["closure"] = p["cleavage_closure_share"]
1045
+ if p.get("cleavage_friction"):
1046
+ spec["friction"] = p["cleavage_friction"]
1047
+ if p.get("cleavage_coupling"):
1048
+ spec["coupling"] = p["cleavage_coupling"]
1049
+ out["cleavage"] = spec
1050
+ return out
1051
+
1052
+
1053
+ def _porous(p: dict) -> dict:
1054
+ """The porous plasticity of the form (:meth:`PorousPlasticity.from_config`)."""
1055
+ plastic = _plasticity({**p, "hill": None})
1056
+ out = {"criterion": p["criterion"], "porosity": p["porosity"], **plastic}
1057
+ if p["criterion"] == "gurson":
1058
+ q = _two(p.get("gurson") or [1.5, 1.0], "q1, q2", "q1", "q2", "q3")
1059
+ out.update(zip(("q1", "q2", "q3"), q, strict=False))
1060
+ if p.get("coalescence"):
1061
+ out["fc"], out["fF"] = _two(p["coalescence"], "coalescence", "fc", "fF")
1062
+ elif p["criterion"] == "rousselier":
1063
+ values = _two(p.get("rousselier"), "Rousselier", "σ1", "D", "q2")
1064
+ out.update(zip(("sigma1", "D", "q2"), values, strict=False))
1065
+ else:
1066
+ out["C"], out["F"] = _two(p.get("elliptic"), "elliptic criterion", "C", "F")
1067
+ kind = p.get("nucleation") or "none"
1068
+ if kind != "none":
1069
+ names = {"gaussian": ("fN", "eN", "sN"), "constant": ("A",), "exponential": ("B", "e0")}
1070
+ values = list(p.get("nucleation_coefficients") or [])
1071
+ need = names[kind]
1072
+ if len(values) not in (len(need), len(need) + 1):
1073
+ raise ValueError(f"nucleation coefficients: {', '.join(need)} (and the threshold)")
1074
+ out["nucleation"] = {"type": kind, **dict(zip(need, values, strict=False))}
1075
+ if len(values) > len(need):
1076
+ out["nucleation"]["yield"] = values[-1]
1077
+ return out
1078
+
1079
+
1080
+ def _zmat(p: dict, folder: Path) -> str:
1081
+ """The material file of Z-set of the form (its text written in ``folder``), by path."""
1082
+ text = (p.get("zmat") or "").strip()
1083
+ if not text:
1084
+ raise ValueError("Z-set material file: its text (***behavior ... ***return) or its path")
1085
+ if "\n" not in text and Path(text).is_file():
1086
+ return str(Path(text).resolve())
1087
+ from morphogen.homogenization.zmat import describe
1088
+
1089
+ how = describe(text)
1090
+ if how["translation"] == "mfront" and importlib.util.find_spec("mgis") is None:
1091
+ raise ValueError(
1092
+ f"Z-set material file: morphoGen's kernels do not integrate it ({how['reason']}); "
1093
+ "it needs MFront and MGIS (conda install -c conda-forge mgis mfront cxx-compiler)"
1094
+ )
1095
+ path = folder / "material.zmat"
1096
+ path.write_text(text + "\n", encoding="utf-8")
1097
+ return str(path)
1098
+
1099
+
1100
+ def _mfront(p: dict) -> dict:
1101
+ source = (p.get("mfront") or "").strip()
1102
+ if not source:
1103
+ raise ValueError("MFront source or library: its path")
1104
+ out = {"source" if source.endswith(".mfront") else "library": source}
1105
+ if p.get("mfront_behaviour"):
1106
+ out["behaviour"] = p["mfront_behaviour"].strip()
1107
+ for key, name in (
1108
+ ("mfront_parameters", "parameters"),
1109
+ ("mfront_properties", "material_properties"),
1110
+ ):
1111
+ value = _json(p.get(key), name)
1112
+ if value:
1113
+ out[name] = value
1114
+ return out
1115
+
1116
+
1117
+ def _behaviour(p: dict, elastic: dict, folder: Path) -> dict:
1118
+ """The material (a mapping of the configurations) of the behaviour of the form, with the
1119
+ elastic constants ``elastic`` (young, poisson), or that of the workspace chosen (with its
1120
+ own)."""
1121
+ kind = p["behaviour"]
1122
+ if kind == "workspace":
1123
+ return p["kept"]["material"]
1124
+ base = {"young": float(elastic["young"]), "poisson": float(elastic["poisson"])}
1125
+ if kind == "elastic":
1126
+ return base
1127
+ if kind == "mises":
1128
+ out = {**base, "plasticity": _plasticity(p)}
1129
+ coupled = p.get("coupled_damage") or "none"
1130
+ if coupled != "none":
1131
+ out["damage"] = _coupled_damage(p, coupled)
1132
+ return out
1133
+ if kind == "porous":
1134
+ return {**base, "porous_plasticity": _porous(p)}
1135
+ if kind == "crystal":
1136
+ cubic, hexagonal = p.get("cubic"), p.get("hexagonal")
1137
+ if cubic and hexagonal:
1138
+ raise ValueError("elasticity of the crystal: cubic or hexagonal, not both")
1139
+ if cubic:
1140
+ if len(cubic) != 3:
1141
+ raise ValueError("cubic elasticity: C11, C12, C44")
1142
+ base = {"cubic": [float(c) for c in cubic]}
1143
+ if hexagonal:
1144
+ if len(hexagonal) != 5:
1145
+ raise ValueError("hexagonal elasticity: C11, C12, C13, C33, C44")
1146
+ base = {"hexagonal": [float(c) for c in hexagonal]}
1147
+ return {**base, "crystal_plasticity": _crystal(p)}
1148
+ if kind == "zmat":
1149
+ return {"zmat": {"file": _zmat(p, folder)}}
1150
+ if kind == "viscoelastic":
1151
+ series = {
1152
+ "shear": _value_pairs(p.get("prony_shear"), "Prony series of the shear modulus"),
1153
+ "bulk": _value_pairs(p.get("prony_bulk"), "Prony series of the bulk modulus"),
1154
+ }
1155
+ series = {k: v for k, v in series.items() if v}
1156
+ if not series:
1157
+ raise ValueError("Prony series: at least one pair (shear or bulk)")
1158
+ return {**base, "viscoelasticity": series}
1159
+ if kind == "hyperelastic":
1160
+ return _hyperelastic(p, base)
1161
+ if kind == "damage":
1162
+ law = {
1163
+ "strength": p["strength"],
1164
+ "softening": p["softening"],
1165
+ "equivalent": p["equivalent"],
1166
+ "viscosity": p.get("damage_viscosity") or 0.0,
1167
+ "split": p.get("damage_split") or "none",
1168
+ }
1169
+ if p.get("fracture_energy"):
1170
+ if not p.get("damage_length"):
1171
+ raise ValueError(
1172
+ "size of the elements of the band: that of the voxels or elements over "
1173
+ "which the fracture energy is dissipated"
1174
+ )
1175
+ law.update(fracture_energy=p["fracture_energy"], length=p["damage_length"])
1176
+ elif p.get("ultimate"):
1177
+ law["ultimate"] = p["ultimate"]
1178
+ else:
1179
+ raise ValueError("damage: the ultimate strain of the softening, or a fracture energy")
1180
+ return {**base, "damage": law}
1181
+ if kind == "mazars":
1182
+ return {
1183
+ **base,
1184
+ "damage": {
1185
+ "law": "mazars",
1186
+ "threshold": p["mazars_threshold"],
1187
+ "tension": list(_two(p["mazars_tension"], "tension", "A_t", "B_t")),
1188
+ "compression": list(_two(p["mazars_compression"], "compression", "A_c", "B_c")),
1189
+ "beta": p.get("mazars_beta") or 1.0,
1190
+ },
1191
+ }
1192
+ if kind == "mfront":
1193
+ return {**base, "mfront": _mfront(p)}
1194
+ raise ValueError(f"behaviour: one of {', '.join(c[0] for c in _behaviours())}")
1195
+
1196
+
1197
+ def _coupled_damage(p: dict, law: str) -> dict:
1198
+ """The damage coupled to the plasticity of the form
1199
+ (:class:`~morphogen.homogenization.laws.DuctileDamage`)."""
1200
+ out: dict = {"law": law}
1201
+ if law == "lemaitre":
1202
+ values = list(p.get("lemaitre") or [])
1203
+ if len(values) not in (1, 2):
1204
+ raise ValueError("Lemaitre's S, s: the strength S (and the exponent s)")
1205
+ out["S"] = values[0]
1206
+ if len(values) == 2:
1207
+ out["s"] = values[1]
1208
+ if p.get("damage_threshold"):
1209
+ out["threshold"] = p["damage_threshold"]
1210
+ if p.get("closure") is not None:
1211
+ out["closure"] = p["closure"]
1212
+ else:
1213
+ values = list(p.get("kachanov") or [])
1214
+ if len(values) not in (2, 3):
1215
+ raise ValueError("Kachanov's A, r (and k): the resistance A and the exponents")
1216
+ out.update(A=values[0], r=values[1])
1217
+ if len(values) == 3:
1218
+ out["k"] = values[2]
1219
+ weights = list(p.get("hayhurst") or [])
1220
+ if weights:
1221
+ if len(weights) != 2:
1222
+ raise ValueError("Hayhurst's weights: α and β")
1223
+ out.update(alpha=weights[0], beta=weights[1])
1224
+ if p.get("critical_damage"):
1225
+ out["critical"] = p["critical_damage"]
1226
+ if p.get("coupled_viscosity"):
1227
+ out["viscosity"] = p["coupled_viscosity"]
1228
+ return out
1229
+
1230
+
1231
+ def _value_pairs(values, name: str) -> list[list[float]]:
1232
+ """The pairs of a list of floats of a form, as lists of two values."""
1233
+ values = [float(v) for v in values or []]
1234
+ if len(values) % 2:
1235
+ raise ValueError(f"{name}: pairs of values")
1236
+ return [[values[i], values[i + 1]] for i in range(0, len(values), 2)]
1237
+
1238
+
1239
+ def _hyperelastic(p: dict, base: dict) -> dict:
1240
+ """The material of a hyperelastic energy of the form: with the elastic constants
1241
+ ``base`` when it has no parameter of its own (neo-Hookean), else with the elasticity
1242
+ of its parameters and the bulk modulus of the form (by default that of ``base``)."""
1243
+ model = p["hyper_model"]
1244
+ values = [float(v) for v in p.get("hyper_parameters") or []]
1245
+ extra = {}
1246
+ mullins = [float(v) for v in p.get("hyper_mullins") or []]
1247
+ if mullins:
1248
+ if len(mullins) != 3:
1249
+ raise ValueError("Mullins softening: r, m, β")
1250
+ extra["mullins"] = mullins
1251
+ if not values:
1252
+ if model != "neo_hookean":
1253
+ raise ValueError(f"parameters of the energy: those of {model.replace('_', ' ')}")
1254
+ return {**base, "hyperelasticity": {"model": model, **extra}}
1255
+ if model in ("ogden", "hyperfoam"):
1256
+ terms = _value_pairs(values, f"parameters of the energy ({model})")
1257
+ law = {"model": model, "terms": terms}
1258
+ else:
1259
+ names, least = HYPERELASTIC_PARAMETERS[model]
1260
+ if not least <= len(values) <= len(names):
1261
+ raise ValueError(f"parameters of the energy: {', '.join(names)}")
1262
+ law = {"model": model, **dict(zip(names, values, strict=False))}
1263
+ if model == "holzapfel":
1264
+ fibres = [float(v) for v in p.get("hyper_fibres") or []]
1265
+ if not fibres or len(fibres) % 3:
1266
+ raise ValueError("directions of the fibres: x, y, z of each family")
1267
+ law["fibres"] = [fibres[k : k + 3] for k in range(0, len(fibres), 3)]
1268
+ bulk = p.get("hyper_bulk")
1269
+ if not bulk: # that of the elastic constants of the form
1270
+ bulk = base["young"] / (3.0 * (1.0 - 2.0 * base["poisson"]))
1271
+ return {"hyperelasticity": {**law, **extra, "bulk": float(bulk)}}
1272
+
1273
+
1274
+ def _elastic(item: dict, value) -> dict:
1275
+ """The elastic constants of the phases of a morphology from the form (phase -> "void" or
1276
+ {young, poisson}); without them, those the page proposes (1 for the first phase, 10 for
1277
+ the others, voids for the phases named so)."""
1278
+ if value:
1279
+ return {int(k): v for k, v in value.items()}
1280
+ phases = item.get("phases") or {"0": "phase 0", "1": "phase 1"}
1281
+ return {
1282
+ int(k): "void" if name == "void" else {"young": 1.0 if i == 0 else 10.0, "poisson": 0.3}
1283
+ for i, (k, name) in enumerate(phases.items())
1284
+ }
1285
+
1286
+
1287
+ def _materials(p: dict, item: dict, folder: Path) -> tuple[dict, int]:
1288
+ """The materials of the phases (mappings of the configurations) and the phase of the
1289
+ behaviour of the form: the first that is not a void, unless the form names it; the
1290
+ materials of the configurations of the form replace those of the phases they name."""
1291
+ elastic = _elastic(item, p.get("materials"))
1292
+ phase = p.get("phase")
1293
+ if phase is None:
1294
+ phase = next((k for k, m in elastic.items() if m != "void"), None)
1295
+ if phase is None:
1296
+ raise ValueError("materials: every phase is a void")
1297
+ elif phase not in elastic:
1298
+ raise ValueError(f"phase {phase}: not a phase of the morphology ({sorted(elastic)})")
1299
+ if elastic[phase] == "void":
1300
+ raise ValueError(f"phase {phase} is a void: choose a solid phase for the behaviour")
1301
+ out = dict(elastic)
1302
+ out[phase] = _behaviour(p, elastic[phase], folder)
1303
+ out.update(_extra(p))
1304
+ return out, int(phase)
1305
+
1306
+
1307
+ def _extra(p: dict) -> dict:
1308
+ """The materials of the configurations of the form (phase -> material)."""
1309
+ extra = _json(p.get("behaviours"), "materials of the configurations")
1310
+ if extra is None:
1311
+ return {}
1312
+ if not isinstance(extra, dict):
1313
+ raise ValueError("materials of the configurations: a mapping phase -> material")
1314
+ out = {}
1315
+ for key, spec in extra.items():
1316
+ try:
1317
+ out[int(key)] = spec
1318
+ except ValueError:
1319
+ raise ValueError(f"materials of the configurations: phase {key!r}") from None
1320
+ return out
1321
+
1322
+
1323
+ BEHAVIOURS_FIELD = Field(
1324
+ "behaviours",
1325
+ "text",
1326
+ label="materials of the configurations (JSON)",
1327
+ doc='phase -> material of homogenization.materials, replacing those above: e.g. {"1": '
1328
+ '{"cubic": [1.7, 1.2, 0.75], "crystal_plasticity": {"tau0": 0.001, "K": 0.0002, '
1329
+ '"n": 10}}} (all their options: tables, nucleation, several nonlinear phases)',
1330
+ )
1331
+
1332
+
1333
+ # -- figures ---------------------------------------------------------------------------------
1334
+
1335
+
1336
+ def _driven(res) -> tuple[np.ndarray, np.ndarray, str, str, int]:
1337
+ """The strain component that varies most along a response and the stresses (true
1338
+ measures in finite strains), their names and the index of the component."""
1339
+ true = res.finite and res.log_strain is not None and res.cauchy is not None
1340
+ strain = np.asarray(res.log_strain if true else res.strain, dtype=float)
1341
+ stress = np.asarray(res.cauchy if true else res.stress, dtype=float)
1342
+ i = int(np.argmax(np.ptp(strain, axis=0)))
1343
+ e_name, s_name = ("LE", "TS") if true else ("E", "S")
1344
+ return strain, stress, e_name, s_name, i
1345
+
1346
+
1347
+ def _phase_figure(res, names: dict, title: str = ""):
1348
+ """The mean stress of each phase against the macroscopic strain (the component that
1349
+ varies most), and its mean cumulated plastic strain against time."""
1350
+ from matplotlib.figure import Figure
1351
+
1352
+ strain, stress, e_name, s_name, i = _driven(res)
1353
+ j = int(np.argmax(np.ptp(stress, axis=0)))
1354
+ key = "cauchy" if s_name == "TS" else "stress"
1355
+ fig = Figure(figsize=(9.0, 3.6), layout="constrained")
1356
+ ax, ax2 = fig.subplots(1, 2)
1357
+ ax.plot(strain[:, i], stress[:, j], "k-", lw=2.0, label="macroscopic")
1358
+ for phase, series in sorted(res.phases.items()):
1359
+ label = f"{phase}: {names.get(str(phase), phase)}"
1360
+ ax.plot(
1361
+ strain[:, i],
1362
+ np.asarray(series.get(key, series["stress"]))[:, j],
1363
+ lw=1.4,
1364
+ marker=".",
1365
+ ms=3,
1366
+ label=label,
1367
+ )
1368
+ ax2.plot(res.times, series["plastic"], lw=1.4, marker=".", ms=3, label=label)
1369
+ ax.set_xlabel(e_name + COMPONENTS[i])
1370
+ ax.set_ylabel(f"mean {s_name}{COMPONENTS[j]} of the phases")
1371
+ ax2.set_xlabel("time")
1372
+ ax2.set_ylabel("mean cumulated plastic strain p")
1373
+ for a in (ax, ax2):
1374
+ a.grid(alpha=0.3)
1375
+ a.legend(fontsize=8, frameon=False)
1376
+ if title:
1377
+ fig.suptitle(title, fontsize=10)
1378
+ return fig
1379
+
1380
+
1381
+ def _comparison_figure(curves: list[tuple[str, object, object]], title: str = ""):
1382
+ """The responses of the NTFA (dashed) against the full field (solid) along paths:
1383
+ ``(name, full field, NTFA)``."""
1384
+ from matplotlib.figure import Figure
1385
+
1386
+ fig = Figure(figsize=(5.0 * len(curves), 3.8), layout="constrained")
1387
+ axes = np.atleast_1d(fig.subplots(1, len(curves)))
1388
+ for ax, (name, ref, red) in zip(axes, curves, strict=True):
1389
+ strain, stress, e_name, s_name, i = _driven(ref if ref is not None else red)
1390
+ j = int(np.argmax(np.ptp(stress, axis=0)))
1391
+ if ref is not None:
1392
+ ax.plot(strain[:, i], stress[:, j], "k-", lw=1.8, label="full field")
1393
+ ax.plot(
1394
+ red.strain[:, i],
1395
+ red.stress[:, j],
1396
+ "--",
1397
+ color="#d6604d",
1398
+ lw=1.8,
1399
+ marker=".",
1400
+ ms=4,
1401
+ label="NTFA",
1402
+ )
1403
+ ax.set_xlabel(e_name + COMPONENTS[i])
1404
+ ax.set_ylabel(s_name + COMPONENTS[j])
1405
+ ax.set_title(name, fontsize=10)
1406
+ ax.locator_params(axis="x", nbins=5)
1407
+ ax.grid(alpha=0.3)
1408
+ ax.legend(fontsize=8, frameon=False)
1409
+ if title:
1410
+ fig.suptitle(title, fontsize=10)
1411
+ return fig
1412
+
1413
+
1414
+ def _point_figure(res, reference=None, title: str = ""):
1415
+ """The curves of a material point (:func:`morphogen.viz.figures.path_figure`) with a
1416
+ reference curve (strain, stress) on the stress-strain axes."""
1417
+ from morphogen.viz.figures import path_figure
1418
+
1419
+ fig = path_figure(res, title=title)
1420
+ if reference is not None:
1421
+ ax = fig.axes[0]
1422
+ ax.plot(reference[:, 0], reference[:, 1], "ko", ms=3.5, mfc="none", label="reference")
1423
+ ax.legend(fontsize=8)
1424
+ return fig
1425
+
1426
+
1427
+ def _at_times(ref, times) -> np.ndarray:
1428
+ """The stresses of a response at the ``times`` of another one (the planned ends of the
1429
+ steps: a solver that divided steps has more)."""
1430
+ rows = [int(np.argmin(np.abs(np.asarray(ref.times) - t))) for t in times]
1431
+ return np.asarray(ref.stress)[rows]
1432
+
1433
+
1434
+ def _relative_error(ref, red, k: int) -> tuple[float, float]:
1435
+ """The largest and the final gaps of the component ``k`` of the stresses of a response
1436
+ (``red``) to a reference at its times, relative to the largest of the reference."""
1437
+ stress = _at_times(ref, red.times)[:, k]
1438
+ scale = float(np.abs(stress).max()) or 1.0
1439
+ gap = np.abs(np.asarray(red.stress)[:, k] - stress)
1440
+ return float(gap.max() / scale), float(gap[-1] / scale)
1441
+
1442
+
1443
+ # -- outputs -------------------------------------------------------------------------------
1444
+
1445
+
1446
+ def _steps_written(res, folder: Path, name: str, bc: str, which: str) -> list[str]:
1447
+ """The fields of a response (:attr:`PathResult.fields`) as files: those of the steps
1448
+ (``which``: ``"steps"``, the ends of the segments ``"segments"``, ``"end"``) as
1449
+ ``<path>_step<k>.vtu`` (``.vti`` on voxels), and the end as
1450
+ ``sample_0000_<path>_<bc>.vtu``, the fields of the simulations of the interface (von
1451
+ Mises stress, components of the stress, strain and plastic strain, cumulated plastic
1452
+ strain, porosity, displacement)."""
1453
+ from morphogen.pipeline import write_path_fields
1454
+ from morphogen.viz.workflow import path_fields
1455
+
1456
+ times = sorted(res.fields)
1457
+ if not times:
1458
+ return []
1459
+ ends = np.asarray(res.path.times[1:], dtype=float)
1460
+
1461
+ def named(t):
1462
+ arrays = res.fields[t]
1463
+ out = path_fields(arrays)
1464
+ for extra in ("porosity", "orientation"):
1465
+ if extra in arrays:
1466
+ out[extra] = np.asarray(arrays[extra])
1467
+ return out
1468
+
1469
+ written = []
1470
+ for k, t in enumerate(times, start=1):
1471
+ if which == "steps" or (which == "segments" and np.isclose(t, ends).any()):
1472
+ target = folder / f"{name}_step{k:03d}.vtu"
1473
+ written.append(write_path_fields(target, res.support, named(t)).name)
1474
+ last = write_path_fields(folder / f"{STEM}_{name}_{bc}.vtu", res.support, named(times[-1]))
1475
+ return [*written, last.name]
1476
+
1477
+
1478
+ def _register(ctx, pattern: str, kind: str) -> None:
1479
+ """The figures or videos written in the folder of the result (``pattern``) for the page."""
1480
+ for path in sorted(ctx.folder.glob(pattern)):
1481
+ title = path.stem.removeprefix(STEM + "_").replace("_", " ")
1482
+ entry = {"title": title, "url": ctx.url(path.name)}
1483
+ if kind == "videos":
1484
+ entry["format"] = path.suffix[1:]
1485
+ getattr(ctx, kind).append(entry)
1486
+
1487
+
1488
+ # -- the loading path of a morphology --------------------------------------------------------
1489
+
1490
+ FIELDS_SHOWN = (
1491
+ ("von_mises", "von Mises stress"),
1492
+ ("p", "cumulated plastic strain p"),
1493
+ ("displacement", "displacement (norm)"),
1494
+ *((f"stress_{c}", f"stress {c}") for c in COMPONENTS),
1495
+ *((f"strain_{c}", f"strain {c}") for c in COMPONENTS),
1496
+ *((f"plastic_strain_{c}", f"plastic strain {c}") for c in COMPONENTS),
1497
+ )
1498
+ CMAPS = ("viridis", "plasma", "inferno", "magma", "cividis", "turbo", "coolwarm", "RdBu_r", "jet")
1499
+ #: The fields of the interfaces that debond, for the video of a path
1500
+ INTERFACE_FIELDS = (
1501
+ ("interface_damage", "damage of the interfaces (those that debond)"),
1502
+ ("interface_opening", "opening of the interfaces (those that debond)"),
1503
+ )
1504
+ #: The fields of the crystals that twin or cleave
1505
+ CRYSTAL_FIELDS = (
1506
+ ("twin_fraction", "twinned fraction (crystals that twin)"),
1507
+ ("twin_reoriented", "turned lattices (the share of the points that their twins turned)"),
1508
+ ("twin_misorientation", "disorientation of the twins (lattices that their twins turn)"),
1509
+ ("cleavage_damage", "damage of the cleavage planes (crystals that cleave)"),
1510
+ ("cleavage_opening", "opening of the cleavage planes (crystals that cleave)"),
1511
+ ("cleavage_microdamage", "microdamage of the cleavage planes (planes with a damage band)"),
1512
+ )
1513
+ FATIGUE = (
1514
+ ("none", "none"),
1515
+ ("crossland", "Crossland: amplitude of sqrt(J2), largest hydrostatic stress"),
1516
+ ("sines", "Sines: amplitude of sqrt(J2), mean hydrostatic stress"),
1517
+ ("dang_van", "Dang Van: shear and hydrostatic stress at each time of the cycle"),
1518
+ ("findley", "Findley: critical plane (shear amplitude and largest normal stress)"),
1519
+ ("matake", "Matake: plane of the largest shear amplitude"),
1520
+ )
1521
+ JUDGED = {"fatigue": ["crossland", "sines", "dang_van", "findley", "matake"]}
1522
+ DEBOND = {"method": "fe", "interfaces": True}
1523
+
1524
+
1525
+ def _interfaces(p: dict, edge: float) -> dict | None:
1526
+ """The interfaces that debond along the path of the form (``homogenization.nonlinear.
1527
+ interfaces``), or None: a bilinear law of their strength and fracture energy (blank:
1528
+ that of an opening at failure of 2 % of the edge of the domain), Coulomb friction of
1529
+ the lips that close, a viscous regularization."""
1530
+ if not p.get("interfaces"):
1531
+ return None
1532
+ strength = p["interface_strength"]
1533
+ if not strength or not strength > 0:
1534
+ raise ValueError("strength of the interfaces: a positive stress")
1535
+ energy = p["interface_energy"]
1536
+ if energy is None:
1537
+ energy = 0.01 * strength * edge
1538
+ if not energy > 0:
1539
+ raise ValueError("fracture energy of the interfaces: positive")
1540
+ out = {"normal_strength": strength, "mode_I": energy}
1541
+ for key, name in (("friction", "interface_friction"), ("viscosity", "interface_viscosity")):
1542
+ value = p.get(name) or 0.0
1543
+ if value < 0:
1544
+ raise ValueError(f"{key} of the interfaces: 0 or more")
1545
+ if value:
1546
+ out[key] = value
1547
+ if p["interface_faces"] != "phases":
1548
+ out["faces"] = p["interface_faces"]
1549
+ return out
1550
+
1551
+
1552
+ def _fatigue(p: dict) -> dict | None:
1553
+ """The fatigue of the points along the path of the form (``homogenization.fatigue``),
1554
+ or None: a criterion and its two fatigue limits, the times of the cycle."""
1555
+ kind = p.get("fatigue") or "none"
1556
+ if kind == "none":
1557
+ return None
1558
+ names = {"bending": "fatigue_bending", "torsion": "fatigue_torsion",
1559
+ "repeated": "fatigue_repeated"} # fmt: skip
1560
+ limits = ("torsion", "repeated") if kind == "sines" else ("bending", "torsion")
1561
+ out: dict = {"criterion": kind}
1562
+ for key in limits:
1563
+ value = p.get(names[key])
1564
+ if not value or not value > 0:
1565
+ raise ValueError(f"fatigue limit ({key}): a positive stress")
1566
+ out[key] = value
1567
+ if p.get("fatigue_cycle"):
1568
+ out["cycle"] = [float(v) for v in p["fatigue_cycle"]]
1569
+ return out
1570
+
1571
+
1572
+ BEREMIN = {"beremin": True}
1573
+ #: The stress that drives the cleavage of a point, in the criterion of Beremin
1574
+ DRIVING = (
1575
+ ("principal", "the largest principal stress"),
1576
+ *((c[0], f"the normal stress of the planes {c[1]}") for c in CLEAVAGE_PLANES[1:]),
1577
+ )
1578
+
1579
+
1580
+ def _beremin(p: dict) -> dict | None:
1581
+ """The criterion of cleavage of Beremin along the path of the form
1582
+ (``homogenization.beremin``), or None."""
1583
+ if not p.get("beremin"):
1584
+ return None
1585
+ out = {}
1586
+ for key, label in (("modulus", "modulus of Weibull"), ("scale", "scale of the stresses"),
1587
+ ("volume", "reference volume")): # fmt: skip
1588
+ value = p.get(f"beremin_{key}")
1589
+ if not value or not value > 0:
1590
+ raise ValueError(f"cleavage (Beremin): {label}, a positive number")
1591
+ out[key] = value
1592
+ if (p.get("beremin_stress") or "principal") != "principal":
1593
+ out["planes"] = p["beremin_stress"]
1594
+ if p.get("c_over_a"):
1595
+ out["c_over_a"] = p["c_over_a"]
1596
+ if p.get("beremin_plastic") is not None:
1597
+ out["plastic"] = p["beremin_plastic"]
1598
+ return out
1599
+
1600
+
1601
+ def _beremin_figure(res, found, title: str = ""):
1602
+ """The probability of cleavage along a path (the criterion of Beremin) and its Weibull
1603
+ stress, against the strain that the path drives."""
1604
+ from matplotlib.figure import Figure
1605
+
1606
+ strain, _, e_name, _, i = _driven(res)
1607
+ x = strain[-found.times.size :, i]
1608
+ fig = Figure(figsize=(5.4, 3.6), layout="constrained")
1609
+ ax = fig.add_subplot()
1610
+ ax.plot(x, found.probability, "-o", ms=3, color="#b2182b")
1611
+ ax.set_xlabel(f"{e_name}{COMPONENTS[i]}")
1612
+ ax.set_ylabel("probability of cleavage", color="#b2182b")
1613
+ ax.set_ylim(-0.02, 1.02)
1614
+ other = ax.twinx()
1615
+ other.plot(x, found.weibull, "--", color="#2166ac")
1616
+ other.set_ylabel("Weibull stress", color="#2166ac")
1617
+ if title:
1618
+ ax.set_title(title, fontsize=9)
1619
+ return fig
1620
+
1621
+
1622
+ def _fatigue_figure(cycle, title: str = ""):
1623
+ """The share of the volume of the points judged above each utilization of a cycle
1624
+ (:class:`~morphogen.homogenization.fatigue.FatigueResult`): the points beyond their
1625
+ fatigue limit are right of 1."""
1626
+ from matplotlib.figure import Figure
1627
+
1628
+ judged = np.isfinite(cycle.utilization)
1629
+ values = cycle.utilization[judged]
1630
+ weights = np.ones(values.shape) if cycle.weights is None else cycle.weights[judged]
1631
+ order = np.argsort(values)
1632
+ above = 1.0 - np.cumsum(weights[order]) / weights.sum()
1633
+ fig = Figure(figsize=(5.2, 3.6), layout="constrained")
1634
+ ax = fig.add_subplot()
1635
+ ax.step(values[order], np.clip(above, 0.0, 1.0), where="post", color="#2166ac")
1636
+ ax.axvline(1.0, color="#b2182b", lw=1.0, ls="--", label="fatigue limit")
1637
+ ax.set_xlabel("utilization (equivalent stress / limit)")
1638
+ ax.set_ylabel("share of the volume above")
1639
+ ax.set_xlim(0.0, max(1.05, 1.05 * float(values.max())))
1640
+ ax.set_ylim(0.0, 1.0)
1641
+ ax.legend(frameon=False)
1642
+ if title:
1643
+ ax.set_title(title, fontsize=9)
1644
+ return fig
1645
+
1646
+
1647
+ @tool(
1648
+ "path",
1649
+ "mechanics",
1650
+ "Loading path of a morphology",
1651
+ "The macroscopic response of a morphology along a loading path (nonlinear "
1652
+ "homogenization): finite elements on the conforming mesh of its level set (periodic or "
1653
+ "kinematic conditions) or FFT on its voxels (periodic), in small or finite strains; the "
1654
+ "macroscopic components prescribed as stresses are unknowns (the periodic element of "
1655
+ "Z-set). On the mesh, the interfaces of the phases (or of the grains) may debond: "
1656
+ "cohesive zones that open, break and rub. A fatigue criterion judges the points along "
1657
+ "the cycle of the path (utilization, factor of safety), and the criterion of Beremin "
1658
+ "gives the probability of cleavage along it. The curves (macroscopic and "
1659
+ "mean of each phase), the values at the end, the fields of the steps and a video of a "
1660
+ "field along the path; the result joins the workspace as a simulation, with the "
1661
+ "configuration that runs it again.",
1662
+ [
1663
+ Field("source", "item", label="morphology", required=True),
1664
+ Field(
1665
+ "materials",
1666
+ "materials",
1667
+ of="source",
1668
+ doc="elastic constants of the phases (the unit of the stresses), or voids",
1669
+ ),
1670
+ Field(
1671
+ "phase",
1672
+ "int",
1673
+ label="phase of the behaviour",
1674
+ doc="blank: the first phase that is not a void (the matrix, the solid, the grains)",
1675
+ ),
1676
+ *_behaviour_fields("of that phase; the other phases are elastic, or voids"),
1677
+ BEHAVIOURS_FIELD,
1678
+ *_path_fields("tension"),
1679
+ Field(
1680
+ "method",
1681
+ "choice",
1682
+ "fft",
1683
+ choices=(
1684
+ ("fft", "FFT on its voxels (periodic; B-bar or full integration)"),
1685
+ ("fe", "finite elements on the conforming mesh of its level set"),
1686
+ ),
1687
+ ),
1688
+ Field("voxels", "int", 16, label="voxels per edge", when={"method": "fft"}),
1689
+ Field(
1690
+ "integration",
1691
+ "choice",
1692
+ "bbar",
1693
+ when={"method": "fft"},
1694
+ choices=(
1695
+ ("bbar", "B-bar (F-bar in finite strains): no locking under plastic flow"),
1696
+ ("full", "full: 8 Gauss points per voxel (locks under isochoric flow)"),
1697
+ ),
1698
+ ),
1699
+ _device_field(when={"method": "fft"}),
1700
+ Field(
1701
+ "element_size",
1702
+ "float",
1703
+ unit="length",
1704
+ when={"method": "fe"},
1705
+ doc="largest edge of the elements (blank: 1/4 of the edge of the domain)",
1706
+ ),
1707
+ Field(
1708
+ "order",
1709
+ "choice",
1710
+ "2",
1711
+ label="elements",
1712
+ when={"method": "fe"},
1713
+ choices=(
1714
+ ("2", "10-node tetrahedra (accurate plastic flow)"),
1715
+ ("1", "4-node tetrahedra (fast; they lock under isochoric plastic flow)"),
1716
+ ),
1717
+ ),
1718
+ Field(
1719
+ "fe_integration",
1720
+ "choice",
1721
+ "full",
1722
+ label="integration",
1723
+ when={"method": "fe"},
1724
+ choices=(
1725
+ ("full", "full: every point of the elements"),
1726
+ (
1727
+ "bbar",
1728
+ "B-bar (F-bar in finite strains): the volume change of each 10-node "
1729
+ "element as its mean, for nearly incompressible phases (elastomers)",
1730
+ ),
1731
+ ),
1732
+ ),
1733
+ Field(
1734
+ "bc",
1735
+ "choice",
1736
+ "periodic",
1737
+ label="boundary conditions",
1738
+ when={"method": "fe"},
1739
+ choices=(("periodic", "periodic"), ("kubc", "kinematic (u = E x on the boundary)")),
1740
+ ),
1741
+ Field(
1742
+ "kinematics",
1743
+ "choice",
1744
+ "small",
1745
+ choices=(
1746
+ ("small", "small strains"),
1747
+ ("finite", "finite strains (total Lagrangian; nominal and true measures)"),
1748
+ ),
1749
+ ),
1750
+ Field(
1751
+ "tolerance",
1752
+ "float",
1753
+ 1e-6,
1754
+ label="Newton tolerance",
1755
+ doc="relative residual of the equilibrium and of the macroscopic stress",
1756
+ ),
1757
+ Field(
1758
+ "interfaces",
1759
+ "bool",
1760
+ False,
1761
+ label="the interfaces debond",
1762
+ when={"method": "fe"},
1763
+ doc="cohesive zones between the phases of the mesh (finite elements, every "
1764
+ "phase meshed): they open, soften and break, close again and rub along the path",
1765
+ ),
1766
+ Field(
1767
+ "interface_faces",
1768
+ "choice",
1769
+ "phases",
1770
+ label="interfaces",
1771
+ when=DEBOND,
1772
+ choices=(
1773
+ ("phases", "between the phases"),
1774
+ ("grains", "between the grains of a tessellation (and the phases)"),
1775
+ ),
1776
+ ),
1777
+ Field(
1778
+ "interface_strength",
1779
+ "float",
1780
+ 0.002,
1781
+ label="strength of the interfaces",
1782
+ unit="stress",
1783
+ when=DEBOND,
1784
+ doc="the normal traction at which they start to soften (the same in shear)",
1785
+ ),
1786
+ Field(
1787
+ "interface_energy",
1788
+ "float",
1789
+ label="fracture energy of the interfaces",
1790
+ when=DEBOND,
1791
+ doc="per unit area (stress x length); blank: that of an opening at failure of "
1792
+ "2 % of the edge of the domain",
1793
+ ),
1794
+ Field(
1795
+ "interface_friction",
1796
+ "float",
1797
+ 0.0,
1798
+ label="friction of the interfaces",
1799
+ when=DEBOND,
1800
+ doc="Coulomb coefficient of the lips that close again",
1801
+ ),
1802
+ Field(
1803
+ "interface_viscosity",
1804
+ "float",
1805
+ 0.0,
1806
+ label="viscosity of the interfaces",
1807
+ unit="time",
1808
+ when=DEBOND,
1809
+ doc="a viscous regularization (0: none): the interfaces that break at once (a "
1810
+ "snap-back of the response) pass with a time of a few percent of the path",
1811
+ ),
1812
+ Field(
1813
+ "fatigue",
1814
+ "choice",
1815
+ "none",
1816
+ label="fatigue criterion",
1817
+ choices=FATIGUE,
1818
+ doc="high-cycle fatigue of the points of the solid phases along the cycle of "
1819
+ "the path: the equivalent stress of the criterion over its limit (the "
1820
+ "utilization), the factor of safety and the share of the volume beyond",
1821
+ ),
1822
+ Field(
1823
+ "fatigue_bending",
1824
+ "float",
1825
+ label="fatigue limit in bending",
1826
+ unit="stress",
1827
+ when={"fatigue": ["crossland", "dang_van", "findley", "matake"]},
1828
+ doc="fully reversed bending or tension-compression (R = -1)",
1829
+ ),
1830
+ Field(
1831
+ "fatigue_torsion",
1832
+ "float",
1833
+ label="fatigue limit in torsion",
1834
+ unit="stress",
1835
+ when=JUDGED,
1836
+ doc="fully reversed torsion (R = -1)",
1837
+ ),
1838
+ Field(
1839
+ "fatigue_repeated",
1840
+ "float",
1841
+ label="fatigue limit in repeated bending",
1842
+ unit="stress",
1843
+ when={"fatigue": "sines"},
1844
+ doc="the amplitude at the limit of a bending from zero (R = 0)",
1845
+ ),
1846
+ Field(
1847
+ "fatigue_cycle",
1848
+ "floats",
1849
+ label="times of the cycle",
1850
+ when=JUDGED,
1851
+ doc="start, end (blank: the whole path); e.g. the last cycle of a path that "
1852
+ "repeats, once the response is stabilized",
1853
+ ),
1854
+ Field(
1855
+ "beremin",
1856
+ "bool",
1857
+ False,
1858
+ label="probability of cleavage (Beremin)",
1859
+ doc="the local approach: the Weibull stress of the points that have yielded and "
1860
+ "the probability that the weakest link has failed, at each step of the path",
1861
+ ),
1862
+ Field(
1863
+ "beremin_modulus",
1864
+ "float",
1865
+ 22.0,
1866
+ label="modulus of Weibull m",
1867
+ when=BEREMIN,
1868
+ ),
1869
+ Field(
1870
+ "beremin_scale",
1871
+ "float",
1872
+ label="scale of the cleavage stresses σu",
1873
+ unit="stress",
1874
+ when=BEREMIN,
1875
+ doc="of the reference volume: 63 % of them fail at it",
1876
+ ),
1877
+ Field(
1878
+ "beremin_volume",
1879
+ "float",
1880
+ label="reference volume V0",
1881
+ when=BEREMIN,
1882
+ doc="in the unit of the domain cubed; divided by the number of such cells that "
1883
+ "a part holds under the same loading",
1884
+ ),
1885
+ Field(
1886
+ "beremin_stress",
1887
+ "choice",
1888
+ "principal",
1889
+ label="stress that drives the cleavage",
1890
+ choices=DRIVING,
1891
+ when=BEREMIN,
1892
+ doc="the planes of the crystals of the grains, with their orientations",
1893
+ ),
1894
+ Field(
1895
+ "beremin_plastic",
1896
+ "float",
1897
+ label="plastic strain of the plastic zone",
1898
+ when=BEREMIN,
1899
+ doc="the points count once their cumulated plastic strain has passed it "
1900
+ "(blank: every point counts)",
1901
+ ),
1902
+ Field(
1903
+ "fields",
1904
+ "choice",
1905
+ "steps",
1906
+ label="fields written",
1907
+ choices=(
1908
+ ("steps", "at every step"),
1909
+ ("segments", "at the end of each segment"),
1910
+ ("end", "at the end"),
1911
+ ),
1912
+ ),
1913
+ Field(
1914
+ "field",
1915
+ "choice",
1916
+ "von_mises",
1917
+ label="field of the video",
1918
+ choices=(*FIELDS_SHOWN, *INTERFACE_FIELDS, *CRYSTAL_FIELDS),
1919
+ ),
1920
+ Field(
1921
+ "video",
1922
+ "bool",
1923
+ True,
1924
+ label="video of the field along the path",
1925
+ doc="3D views of the deformed mesh (VTK), sections of the voxels",
1926
+ ),
1927
+ Field("cmap", "choice", "viridis", label="colormap", choices=CMAPS),
1928
+ Field(
1929
+ "clim",
1930
+ "floats",
1931
+ label="colour range",
1932
+ doc="low, high (blank: the 0.5 and 99.5 percentiles of the field along the path, "
1933
+ "so that a few singular points do not take the whole range)",
1934
+ ),
1935
+ ],
1936
+ order=1,
1937
+ groups=(
1938
+ ("Morphology and materials", "source"),
1939
+ ("Behaviour", "behaviour"),
1940
+ ("Loading", "loading"),
1941
+ ("Solver", "method"),
1942
+ ("Interfaces", "interfaces", True),
1943
+ ("Fatigue", "fatigue", True),
1944
+ ("Cleavage", "beremin", True),
1945
+ ("Output", "fields", True),
1946
+ ),
1947
+ menu="Loading paths",
1948
+ )
1949
+ def loading_path(p: dict, ctx) -> dict:
1950
+ from morphogen import pipeline
1951
+ from morphogen.config import load_config
1952
+ from morphogen.gui.api import _video_format
1953
+ from morphogen.homogenization import NonlinearFEProblem, NonlinearFFTProblem
1954
+ from morphogen.io.tables import write_table
1955
+ from morphogen.viz.figures import path_figure
1956
+
1957
+ source = p["source"]
1958
+ micro = source["micro"]
1959
+ materials, phase = _materials(p, source, ctx.folder)
1960
+ name, spec = _path(p)
1961
+ fe = p["method"] == "fe"
1962
+ bc = p["bc"] if fe else "periodic"
1963
+ edge = float(np.max(micro.domain.lengths))
1964
+ key = f"{name}.{bc}"
1965
+ fmt = _video_format()
1966
+ views: dict = {"figures": [{"of": key, "kind": "curves"}], "cmap": p["cmap"]}
1967
+ if p["video"]:
1968
+ video = {"of": key, "color": p["field"], "formats": [fmt]}
1969
+ video.update({"frames": 60, "fps": 20} if fe else {"fps": 6})
1970
+ views["videos"] = [video]
1971
+ nonlinear = {"tolerance": p["tolerance"], "kinematics": p["kinematics"]}
1972
+ nonlinear["integration"] = p["fe_integration"] if fe else p["integration"]
1973
+ debonding = _interfaces(p, edge) if fe else None
1974
+ if debonding:
1975
+ nonlinear["interfaces"] = debonding
1976
+ elif p["video"] and p["field"] in dict(INTERFACE_FIELDS):
1977
+ raise ValueError(
1978
+ f"field of the video: {p['field']} is a field of the interfaces that debond "
1979
+ "(finite elements, 'the interfaces debond')"
1980
+ )
1981
+ judged = _fatigue(p)
1982
+ if p["video"] and p["field"] in dict(CRYSTAL_FIELDS):
1983
+ crystal = materials[phase].get("crystal_plasticity") or {}
1984
+ needed = "twins" if p["field"].startswith("twin") else "cleavage"
1985
+ if needed not in crystal:
1986
+ raise ValueError(
1987
+ f"field of the video: {p['field']} is a field of the crystals with {needed} "
1988
+ "(behaviour: crystal plasticity)"
1989
+ )
1990
+ banded = "regularization" in (crystal.get("cleavage") or {})
1991
+ if p["field"] == "cleavage_microdamage" and not banded:
1992
+ raise ValueError(
1993
+ "field of the video: cleavage_microdamage is that of planes with a damage "
1994
+ "band (give the width of the damage band of the planes)"
1995
+ )
1996
+ turns = ("twin_reoriented", "twin_misorientation")
1997
+ if p["field"] in turns and "twin_reorientation" not in crystal:
1998
+ raise ValueError(
1999
+ f"field of the video: {p['field']} is that of lattices that their "
2000
+ "twins turn (give the twinned fraction that turns the lattice)"
2001
+ )
2002
+ model = source.get("model") or {"type": "tpms", "volume_fraction": 0.5} # a stand-in
2003
+ data: dict = {
2004
+ "model": model,
2005
+ "domain": source.get("domain")
2006
+ or {"size": [float(v) for v in micro.domain.lengths], "periodic": True},
2007
+ "seed": int(source.get("seed") or 1),
2008
+ "homogenization": {
2009
+ "materials": {k: _relative(v, ctx.folder) for k, v in materials.items()},
2010
+ "method": p["method"],
2011
+ "boundary_conditions": [bc],
2012
+ "properties": [],
2013
+ "paths": {name: spec},
2014
+ "nonlinear": nonlinear,
2015
+ "fields": True,
2016
+ },
2017
+ "outputs": {"directory": str(ctx.folder), "name": "sample", "tables": ["xlsx"]},
2018
+ "visualization": views,
2019
+ }
2020
+ if judged:
2021
+ data["homogenization"]["fatigue"] = judged
2022
+ weakest = _beremin(p)
2023
+ if weakest:
2024
+ data["homogenization"]["beremin"] = weakest
2025
+ if fe:
2026
+ size = p["element_size"] or edge / 4
2027
+ if not edge / 200 <= size <= edge:
2028
+ raise ValueError(f"element size: between {edge / 200:g} and {edge:g}")
2029
+ data["mesh"] = {"size": size, "order": int(p["order"])}
2030
+ data["outputs"]["conforming_mesh"] = ["vtu"]
2031
+ else:
2032
+ n = p["voxels"]
2033
+ if not 4 <= n <= 128:
2034
+ raise ValueError("voxels per edge: from 4 to 128 for the loading paths")
2035
+ data["voxels"] = {"shape": n}
2036
+ data["homogenization"]["device"] = p["device"]
2037
+ cfg = load_config(data, base_dir=ctx.folder) # the errors of the form, before solving
2038
+ homog = cfg.homogenization
2039
+ path = homog.paths[name]
2040
+ options = homog.options()["nonlinear"]
2041
+ ctx.progress(0.02, "conforming mesh" if fe else "voxels")
2042
+ mesh = image = None
2043
+ info: dict = {}
2044
+ if fe:
2045
+ mesh, info = pipeline._conforming_mesh(micro, cfg)
2046
+ from morphogen import io
2047
+
2048
+ io.save_mesh(mesh, ctx.folder / f"{STEM}_tet.vtu")
2049
+ interfaces = options.pop("interfaces", None)
2050
+ if interfaces:
2051
+ from morphogen.fracture.periodic import CohesiveCell
2052
+ from morphogen.homogenization.apparent import _interface_options
2053
+
2054
+ law, cell = _interface_options(interfaces, mesh, homog.solver)
2055
+ problem = CohesiveCell(
2056
+ mesh, homog.materials, law, bc, tol=homog.tolerance, **cell, **options
2057
+ )
2058
+ else:
2059
+ problem = NonlinearFEProblem(
2060
+ mesh, homog.materials, bc, solver=homog.solver, tol=homog.tolerance, **options
2061
+ )
2062
+ else:
2063
+ from morphogen.homogenization.materials import any_oriented
2064
+
2065
+ _check_voxels(micro, cfg.voxels.shape, len(path.schedule()), "loading path on voxels")
2066
+ image = micro.voxelize(**cfg.voxels.kwargs())
2067
+ grains = {}
2068
+ if any_oriented(homog.materials) and getattr(micro, "orientations", None) is not None:
2069
+ labels = micro.labels(grid=image.grid())
2070
+ grains = {"grains": labels, "orientations": micro.orientations}
2071
+ info = {"voxels": int(np.prod(image.shape))}
2072
+ problem = NonlinearFFTProblem(image, homog.materials, "periodic", tol=homog.tolerance,
2073
+ device=homog.device, **grains, **options) # fmt: skip
2074
+ t0, t_end = float(path.times[0]), float(path.times[-1])
2075
+ started = time.perf_counter()
2076
+
2077
+ def monitor(state):
2078
+ fraction = (state.time - t0) / (t_end - t0)
2079
+ ctx.progress(0.1 + 0.75 * fraction, f"t = {state.time:.4g} of {t_end:.4g}")
2080
+
2081
+ ctx.progress(0.1, "first step")
2082
+ res = problem.run(path, name=name, fields="steps", monitor=monitor)
2083
+ solve_s = time.perf_counter() - started
2084
+ cycle = None
2085
+ if homog.fatigue:
2086
+ from morphogen.homogenization.fatigue import path_fatigue
2087
+
2088
+ ctx.progress(0.85, "fatigue of the cycle")
2089
+ cycle = path_fatigue(res, homog.fatigue["criteria"], cycle=homog.fatigue["cycle"])
2090
+ res.scalars.update({f"fatigue_{n}": v for n, v in cycle.components().items()})
2091
+ res.fields[max(res.fields)].update(cycle.fields()) # with the fields of the end
2092
+ found = None
2093
+ if homog.beremin:
2094
+ from morphogen.homogenization.beremin import path_beremin
2095
+ from morphogen.pipeline import _point_orientations
2096
+
2097
+ ctx.progress(0.85, "probability of cleavage")
2098
+ labelled = (grains["grains"], grains["orientations"]) if not fe and grains else None
2099
+ euler = _point_orientations(mesh, labelled)
2100
+ found = path_beremin(res, homog.beremin["criterion"], orientations=euler)
2101
+ res.series.update(found.series(res.times) or {})
2102
+ res.fields[max(res.fields)].update(found.fields())
2103
+ ctx.progress(0.86, "fields and figures")
2104
+ _steps_written(res, ctx.folder, name, bc, p["fields"])
2105
+ rows = res.rows()
2106
+ write_table(ctx.folder / f"{STEM}_{name}_{bc}.xlsx", rows)
2107
+ values = res.components()
2108
+ values.update(
2109
+ steps=res.n_steps,
2110
+ iterations=int(np.sum(res.iterations)),
2111
+ cuts=int(res.info.get("cuts", 0)),
2112
+ solve_s=round(solve_s, 2),
2113
+ **info,
2114
+ )
2115
+ record = {"realization": 0, "seed": source.get("seed") or "", **micro.summary()}
2116
+ record.update({f"{key}.{k}": v for k, v in res.components().items()}, **info)
2117
+ pipeline._write_results(ctx.folder, [record], [res.row()], 0, 1, cfg.outputs.tables)
2118
+ title = f"{name} of {source['title']}"
2119
+ ctx.figure(path_figure(res, title=title), f"{STEM}_{name}_{bc}_curves", "curves")
2120
+ if res.phases:
2121
+ names = source.get("phases") or {}
2122
+ ctx.figure(_phase_figure(res, names, title), "phases", "mean of each phase")
2123
+ if cycle is not None and np.isfinite(cycle.utilization).any():
2124
+ ctx.figure(_fatigue_figure(cycle, title), "fatigue", "fatigue of the cycle")
2125
+ if found is not None:
2126
+ ctx.figure(_beremin_figure(res, found, title), "beremin", "probability of cleavage")
2127
+ if p["video"]:
2128
+ from dataclasses import replace
2129
+
2130
+ from morphogen.viz.workflow import visualize
2131
+
2132
+ ctx.progress(0.9, "video")
2133
+ clim = _colour_range(res, p["field"], p.get("clim"))
2134
+ view = replace(cfg.visualization.videos[0], clim=clim)
2135
+ spec_video = replace(cfg.visualization, figures=[], videos=[view])
2136
+ if clim is not None:
2137
+ data["visualization"]["videos"][0]["clim"] = list(clim)
2138
+ try:
2139
+ if fe: # VTK aborts the process when it cannot render: ask it first
2140
+ from morphogen.viz.video import NO_RENDERING, vtk_can_render
2141
+
2142
+ if not vtk_can_render():
2143
+ raise RuntimeError(NO_RENDERING)
2144
+ visualize(spec_video, STEM, ctx.folder, image=image, mesh=mesh, results={key: res})
2145
+ except (RuntimeError, ImportError, ValueError) as exc:
2146
+ import warnings
2147
+
2148
+ warnings.warn(f"no video of the field: {exc}", stacklevel=1)
2149
+ _register(ctx, f"{STEM}_{name}_{bc}_*.{fmt}", "videos")
2150
+ ctx.table(rows, f"{STEM}_{name}_{bc}", f"curves of the path {name} ({bc})")
2151
+ _configuration(data, source, ctx.folder)
2152
+ elastic = {str(k): v for k, v in _elastic(source, p.get("materials")).items()}
2153
+ method = "conforming mesh (FE)" if fe else "voxels (FFT)"
2154
+ _, stress, _, s_name, i = _driven(res)
2155
+ item = ctx.session.add(
2156
+ ctx.key,
2157
+ "simulation",
2158
+ f"{name} of #{source['number']}, {'FE' if fe else 'FFT'}",
2159
+ origin="mechanics",
2160
+ source=source["key"],
2161
+ property=None,
2162
+ method=p["method"],
2163
+ values=values,
2164
+ materials=elastic,
2165
+ behaviours={str(k): v for k, v in materials.items()},
2166
+ path={"name": name, **path.to_dict()},
2167
+ kinematics=p["kinematics"],
2168
+ phases=source.get("phases"),
2169
+ thumbnail=source.get("thumbnail"),
2170
+ info={
2171
+ "path": name,
2172
+ "method": method,
2173
+ "behaviour": f"{p['behaviour']} (phase {phase})",
2174
+ f"{s_name}{COMPONENTS[i]} at the end": float(stress[-1, i]),
2175
+ "p at the end": float(res.plastic[-1]),
2176
+ **({"interfaces": "debonding"} if debonding else {}),
2177
+ **(
2178
+ {"fatigue": f"{judged['criterion']}, utilization {cycle.largest:.3g}"}
2179
+ if cycle is not None
2180
+ else {}
2181
+ ),
2182
+ **(
2183
+ {"cleavage (Beremin)": f"probability {float(found.probability[-1]):.3g}"}
2184
+ if found is not None
2185
+ else {}
2186
+ ),
2187
+ },
2188
+ files={"folder": ctx.url("")},
2189
+ )
2190
+ ctx.items.append(ctx.session.public(item))
2191
+ return {"values": values}
2192
+
2193
+
2194
+ def _check_voxels(micro, n: int, steps: int, what: str) -> None:
2195
+ """Refuse a nonlinear simulation on ``n`` voxels along the longest edge that would need
2196
+ more than half of the free memory: per voxel, eight integration points (their strains,
2197
+ stresses, tangents and two sets of internal variables: about 8 kB) and the fields of
2198
+ the ``steps`` kept (about 200 B each)."""
2199
+ from morphogen.gui.api import _voxels
2200
+
2201
+ _voxels(micro.domain, n, 8.0e3 + 200.0 * steps, what)
2202
+
2203
+
2204
+ def _colour_range(res, field: str, given=None) -> tuple[float, float] | None:
2205
+ """The colour range of a field along a path: the one given (low, high), else its 0.5
2206
+ and 99.5 percentiles over the steps (zero below for fields that do not change sign);
2207
+ None when the field is uniform."""
2208
+ if given:
2209
+ if len(given) != 2 or not given[0] < given[1]:
2210
+ raise ValueError("colour range: low, high (low < high)")
2211
+ return float(given[0]), float(given[1])
2212
+ from morphogen.viz.workflow import field_values, path_fields
2213
+
2214
+ values = np.concatenate(
2215
+ [np.ravel(field_values(path_fields(res.fields[t]), field)) for t in sorted(res.fields)]
2216
+ )
2217
+ values = values[np.isfinite(values)]
2218
+ if not values.size:
2219
+ return None
2220
+ lo, hi = (float(v) for v in np.percentile(values, [0.5, 99.5]))
2221
+ lo = 0.0 if values.min() >= 0.0 else lo
2222
+ return (lo, hi) if hi > lo else None
2223
+
2224
+
2225
+ def _relative(spec, folder: Path):
2226
+ """A material of the configuration with the files of the folder by their names (the
2227
+ configuration is written beside them)."""
2228
+ if isinstance(spec, dict) and isinstance(spec.get("zmat"), dict):
2229
+ file = Path(str(spec["zmat"].get("file", "")))
2230
+ if file.parent == Path(folder):
2231
+ return {**spec, "zmat": {**spec["zmat"], "file": file.name}}
2232
+ return spec
2233
+
2234
+
2235
+ def _configuration(data: dict, source: dict, folder: Path) -> None:
2236
+ """The configuration that runs the simulation again (``morphogen run``), when the
2237
+ morphology is the realization of a model."""
2238
+ import yaml
2239
+
2240
+ if source.get("model") is None:
2241
+ return
2242
+ data = json.loads(json.dumps(data))
2243
+ data["outputs"] = {**data["outputs"], "directory": "simulation"}
2244
+ (folder / "configuration.yaml").write_text(
2245
+ yaml.safe_dump(data, sort_keys=False), encoding="utf-8"
2246
+ )
2247
+
2248
+
2249
+ # -- the reduced model of the NTFA ---------------------------------------------------------
2250
+
2251
+ TRAINING = (
2252
+ *((f"tension_{c}", f"tension {c}") for c in COMPONENTS[:3]),
2253
+ *((f"shear_{c}", f"shear {c}") for c in COMPONENTS[3:]),
2254
+ )
2255
+
2256
+
2257
+ @tool(
2258
+ "ntfa",
2259
+ "mechanics",
2260
+ "NTFA reduced model",
2261
+ "The reduced model of the nonuniform transformation field analysis (NTFA; Michel & "
2262
+ "Suquet 2003, 2004) of a morphology on its periodic voxels: the plastic strain of each "
2263
+ "von Mises phase sought on a few modes, the proper orthogonal decomposition of the "
2264
+ "plastic strain fields of full-field simulations along training paths; the reduced "
2265
+ "model then follows any path in milliseconds. Its responses against the full field "
2266
+ "along the training paths and along another path, with their gaps.",
2267
+ [
2268
+ Field("source", "item", label="morphology", required=True),
2269
+ Field(
2270
+ "materials",
2271
+ "materials",
2272
+ of="source",
2273
+ doc="elastic constants of the phases (the unit of the stresses), or voids",
2274
+ ),
2275
+ Field(
2276
+ "phase", "int", label="plastic phase", doc="blank: the first phase that is not a void"
2277
+ ),
2278
+ Field(
2279
+ "behaviour",
2280
+ "choice",
2281
+ "mises",
2282
+ choices=(("mises", "von Mises elasto-(visco)plasticity (Lemaitre-Chaboche)"), KEPT),
2283
+ doc="the NTFA reduces isotropic von Mises phases",
2284
+ ),
2285
+ _kept_field(),
2286
+ *_plastic_fields(MISES, MISES),
2287
+ BEHAVIOURS_FIELD,
2288
+ Field("voxels", "int", 16, label="voxels per edge", doc="of the periodic image"),
2289
+ _device_field(),
2290
+ Field("modes", "int", 6, label="modes per plastic phase"),
2291
+ Field(
2292
+ "training",
2293
+ "choices",
2294
+ ["tension_11", "shear_12"],
2295
+ choices=TRAINING,
2296
+ label="training paths",
2297
+ doc="a strain component to the amplitude, the other "
2298
+ "stresses free; their directions must span those of the paths followed",
2299
+ ),
2300
+ Field(
2301
+ "training_amplitude",
2302
+ "float",
2303
+ 0.004,
2304
+ label="equivalent strain of the training",
2305
+ doc="the strain of the tensions, the engineering strain of the shears √3 times "
2306
+ "it (the same von Mises equivalent strain); the original NTFA stiffens as the "
2307
+ "plastic flow spreads: at a few times the yield strain, a few percent of the "
2308
+ "full field",
2309
+ ),
2310
+ Field("training_increments", "int", 8, label="increments of the training paths"),
2311
+ *_path_fields("cycle", prefix="test_", amplitude=0.003),
2312
+ Field(
2313
+ "compare",
2314
+ "bool",
2315
+ True,
2316
+ label="the full field along the path too",
2317
+ doc="the gap of the reduced model (one more full-field simulation)",
2318
+ ),
2319
+ Field("tolerance", "float", 1e-6, label="Newton tolerance of the full field"),
2320
+ ],
2321
+ order=3,
2322
+ groups=(
2323
+ ("Morphology and materials", "source"),
2324
+ ("Behaviour", "behaviour"),
2325
+ ("Training", "voxels"),
2326
+ ("Test path", "test_loading"),
2327
+ ),
2328
+ menu="Loading paths",
2329
+ )
2330
+ def ntfa(p: dict, ctx) -> dict:
2331
+ from morphogen.homogenization import NonlinearFFTProblem, train_ntfa
2332
+ from morphogen.homogenization.materials import materials_from_config
2333
+ from morphogen.homogenization.paths import LoadingPath
2334
+
2335
+ source = p["source"]
2336
+ micro = source["micro"]
2337
+ if not micro.domain.periodic:
2338
+ raise ValueError("NTFA: a periodic morphology (the model is trained on periodic voxels)")
2339
+ configs, phase = _materials(p, source, ctx.folder)
2340
+ if p["behaviour"] == "workspace" and set(configs[phase]) - {"young", "poisson", "plasticity"}:
2341
+ raise ValueError(f"the NTFA reduces isotropic von Mises phases: {p['kept']['title']} "
2342
+ "is not one") # fmt: skip
2343
+ materials = materials_from_config(configs)
2344
+ n = p["voxels"]
2345
+ if not 4 <= n <= 64:
2346
+ raise ValueError("voxels per edge: from 4 to 64 for the NTFA")
2347
+ if not p["training"]:
2348
+ raise ValueError("training paths: at least one")
2349
+ a, steps = p["training_amplitude"], p["training_increments"]
2350
+ if not a or steps < 1:
2351
+ raise ValueError("training paths: a nonzero amplitude and at least one increment")
2352
+ training = {}
2353
+ for name in p["training"]:
2354
+ kind, _, component = name.partition("_")
2355
+ strain = a if kind == "tension" else np.sqrt(3.0) * a # the same equivalent strain
2356
+ spec = {"times": [0.0, 1.0], "increments": steps, "strain": {component: [0.0, strain]}}
2357
+ training[name] = LoadingPath.from_spec(spec)
2358
+ test_name, spec = _path(p, "test_")
2359
+ test = LoadingPath.from_spec(spec)
2360
+ if any(test.temperature):
2361
+ raise ValueError("NTFA: no change of temperature along the path")
2362
+ total = sum(len(t.schedule()) for t in training.values())
2363
+ _check_voxels(micro, n, total, "NTFA on voxels") # the snapshots of the training
2364
+ total += len(test.schedule()) if p["compare"] else 0
2365
+ image = micro.voxelize(shape=n)
2366
+ done = [0]
2367
+
2368
+ def monitor(state):
2369
+ done[0] += 1
2370
+ ctx.progress(0.05 + 0.9 * done[0] / total, f"full field: step {done[0]} of {total}")
2371
+
2372
+ def full(path, name, keep):
2373
+ problem = NonlinearFFTProblem(image, materials, "periodic", tol=1e-8,
2374
+ newton_tol=p["tolerance"], integration="full",
2375
+ device=p["device"]) # fmt: skip
2376
+ times = [float(t) for t in path.schedule()] if keep else False
2377
+ return problem.run(path, name=name, fields=times, monitor=monitor)
2378
+
2379
+ ctx.progress(0.02, "training: full-field paths")
2380
+ started = time.perf_counter()
2381
+ references, snapshots = {}, []
2382
+ for name, path in training.items():
2383
+ res = full(path, name, keep=True)
2384
+ snapshots += [
2385
+ np.asarray(res.fields[t]["plastic_strain"]).reshape(-1, 6) for t in sorted(res.fields)
2386
+ ]
2387
+ res.fields = {}
2388
+ references[name] = res
2389
+ model = train_ntfa(
2390
+ image,
2391
+ materials,
2392
+ list(training.values()),
2393
+ modes=p["modes"],
2394
+ newton_tol=p["tolerance"],
2395
+ snapshots=snapshots,
2396
+ )
2397
+ training_s = time.perf_counter() - started
2398
+ model.save(ctx.folder / "ntfa_model.npz") # NTFAModel.load, homogenization.ntfa.save
2399
+ with zipfile.ZipFile(ctx.folder / "ntfa_model.zip", "w", zipfile.ZIP_DEFLATED) as archive:
2400
+ archive.write(ctx.folder / "ntfa_model.npz", "ntfa_model.npz") # for the page
2401
+ values: dict = {"modes": model.n_modes, "training_s": round(training_s, 2)}
2402
+ values.update({f"energy_{r}": e for r, e in sorted(model.energy.items())})
2403
+ curves, tables = [], []
2404
+ for name, path in training.items():
2405
+ red = model.run(path, name=name)
2406
+ ref = references[name]
2407
+ _, _, _, _, k = _driven(ref)
2408
+ values[f"gap_{name}"], _ = _relative_error(ref, red, k)
2409
+ curves.append((f"training: {name}", ref, red))
2410
+ tables.append((name, ref, red))
2411
+ started = time.perf_counter()
2412
+ red = model.run(test, name=test_name)
2413
+ values["ntfa_ms"] = round(1e3 * (time.perf_counter() - started), 2)
2414
+ ref = None
2415
+ if p["compare"]:
2416
+ ctx.progress(0.6, "full field along the path")
2417
+ started = time.perf_counter()
2418
+ ref = full(test, test_name, keep=False)
2419
+ values["full_field_s"] = round(time.perf_counter() - started, 2)
2420
+ values["speed_up"] = values["full_field_s"] / max(values["ntfa_ms"] * 1e-3, 1e-9)
2421
+ _, _, _, _, k = _driven(ref)
2422
+ values[f"gap_{test_name}"], values[f"gap_{test_name}_end"] = _relative_error(ref, red, k)
2423
+ curves.append((test_name, ref, red))
2424
+ tables.append((test_name, ref, red))
2425
+ ctx.figure(
2426
+ _comparison_figure(curves, f"NTFA of {source['title']}: {model.n_modes} modes"),
2427
+ "ntfa",
2428
+ "NTFA (dashed) and full field",
2429
+ )
2430
+ for name, ref, red in tables:
2431
+ ctx.table(_comparison_rows(ref, red), f"ntfa_{name}", f"path {name}: NTFA and full field")
2432
+ values.update({f"S{c}_ntfa": v for c, v in zip(COMPONENTS, red.stress[-1], strict=True)})
2433
+ return {"values": values}
2434
+
2435
+
2436
+ def _comparison_rows(ref, red) -> list[dict]:
2437
+ """The curves of the NTFA and of the full field (when given) along a path: the strain
2438
+ component that varies most and the stress components that vary."""
2439
+ _, stress, _, _, i = _driven(ref if ref is not None else red)
2440
+ spans = np.ptp(stress, axis=0)
2441
+ shown = [j for j in range(6) if spans[j] > 0.01 * spans.max()] or [i]
2442
+ full = _at_times(ref, red.times) if ref is not None else None
2443
+ rows = []
2444
+ for k, t in enumerate(red.times):
2445
+ row = {"time": float(t), f"E{COMPONENTS[i]}": float(red.strain[k, i])}
2446
+ for j in shown:
2447
+ if full is not None:
2448
+ row[f"S{COMPONENTS[j]} full"] = float(full[k, j])
2449
+ row[f"S{COMPONENTS[j]} NTFA"] = float(red.stress[k, j])
2450
+ row["p NTFA"] = float(red.plastic[k])
2451
+ rows.append(row)
2452
+ return rows
2453
+
2454
+
2455
+ # -- a material point ------------------------------------------------------------------------
2456
+
2457
+
2458
+ @tool(
2459
+ "point",
2460
+ "mechanics",
2461
+ "Material point",
2462
+ "One behaviour under a loading path at a material point (homogeneous strain and stress, "
2463
+ "no microstructure; the components prescribed as stresses solved for by Newton's "
2464
+ "method, as Zsim does): its curves, with the points of a test to calibrate its law. "
2465
+ "The behaviour joins the workspace (B), for the loading paths of morphologies, cracks "
2466
+ "and the inputs of other solvers.",
2467
+ [
2468
+ Field("young", "float", 1.0, label="Young's modulus E", unit="stress"),
2469
+ Field("poisson", "float", 0.3, label="Poisson's ratio ν"),
2470
+ Field(
2471
+ "expansion",
2472
+ "float",
2473
+ label="thermal expansion α",
2474
+ doc="per unit change of temperature (the dT of custom paths; blank: none)",
2475
+ ),
2476
+ *_behaviour_fields("with the elasticity above (a Z-set file: its own)"),
2477
+ Field(
2478
+ "orientation",
2479
+ "floats",
2480
+ [0.0, 0.0, 0.0],
2481
+ label="orientation of the crystal",
2482
+ unit="degrees",
2483
+ when={"behaviour": ["crystal", "workspace"]},
2484
+ doc="Bunge angles φ1, Φ, φ2 (of crystal plasticity, or of a learned law: its "
2485
+ "material turned)",
2486
+ ),
2487
+ Field(
2488
+ "material",
2489
+ "text",
2490
+ label="material of the configurations (JSON)",
2491
+ doc='replaces the behaviour of the form: e.g. {"young": 1, "poisson": 0.3, '
2492
+ '"plasticity": {"yield": 0.002, "kinematic": [{"C": 0.5, "D": 300}]}}',
2493
+ ),
2494
+ *_path_fields("cycle"),
2495
+ Field(
2496
+ "kinematics",
2497
+ "choice",
2498
+ "small",
2499
+ choices=(
2500
+ ("small", "small strains"),
2501
+ ("finite", "finite strains (nominal and true measures)"),
2502
+ ),
2503
+ ),
2504
+ Field(
2505
+ "reference",
2506
+ "text",
2507
+ label="points of a test",
2508
+ doc="strain, stress along the component of the path (true measures in finite "
2509
+ "strains), one pair per line (comma, space or tab; or semicolons with decimal "
2510
+ "commas): drawn with the curves, and their gap",
2511
+ ),
2512
+ ],
2513
+ order=4,
2514
+ groups=(
2515
+ ("Elasticity", "young"),
2516
+ ("Behaviour", "behaviour"),
2517
+ ("Loading", "loading"),
2518
+ ("Test", "reference", True),
2519
+ ),
2520
+ menu="Behaviours of materials",
2521
+ )
2522
+ def material_point(p: dict, ctx) -> dict:
2523
+ from morphogen.gui.api import behaviour_config, behaviour_summary
2524
+ from morphogen.homogenization import simulate_point
2525
+ from morphogen.homogenization.materials import Material
2526
+
2527
+ spec = _json(p.get("material"), "material of the configurations")
2528
+ kept = spec is None and p["behaviour"] == "workspace"
2529
+ if spec is None:
2530
+ spec = _behaviour(p, {"young": p["young"], "poisson": p["poisson"]}, ctx.folder)
2531
+ if p.get("expansion") and "zmat" not in spec and not kept:
2532
+ spec["expansion"] = p["expansion"]
2533
+ material = Material.from_config(spec)
2534
+ name, path_spec = _path(p)
2535
+ turned = material.crystal_plasticity is not None or material.learned is not None
2536
+ orientation = p.get("orientation") if turned else None
2537
+ if orientation is not None and len(orientation) != 3:
2538
+ raise ValueError("orientation of the crystal: three Bunge angles φ1, Φ, φ2")
2539
+ ctx.progress(0.1, "integration")
2540
+ res = simulate_point(
2541
+ material, path_spec, name=name, orientation=orientation, kinematics=p["kinematics"]
2542
+ )
2543
+ values = res.components()
2544
+ values.update(
2545
+ steps=res.n_steps, iterations=int(np.sum(res.iterations)), cuts=int(res.info.get("cuts", 0))
2546
+ )
2547
+ reference = _reference(p.get("reference"))
2548
+ strain, stress, _, _, i = _driven(res)
2549
+ if reference is not None:
2550
+ e = strain[:, i]
2551
+ if np.all(np.diff(e) >= 0) or np.all(np.diff(e) <= 0):
2552
+ order = np.argsort(e)
2553
+ inside = (reference[:, 0] >= e.min()) & (reference[:, 0] <= e.max())
2554
+ if inside.any():
2555
+ model = np.interp(reference[inside, 0], e[order], stress[order, i])
2556
+ gap = model - reference[inside, 1]
2557
+ scale = float(np.abs(reference[:, 1]).max()) or 1.0
2558
+ values["reference_rms_gap"] = float(np.sqrt(np.mean(gap**2)))
2559
+ values["reference_relative_gap"] = values["reference_rms_gap"] / scale
2560
+ else:
2561
+ import warnings
2562
+
2563
+ warnings.warn("points of a test: their gap along monotonic paths only", stacklevel=1)
2564
+ kind = "material of the configurations" if p.get("material") else p["behaviour"]
2565
+ if kept:
2566
+ kind = p["kept"]["title"]
2567
+ ctx.figure(_point_figure(res, reference, f"material point: {kind}, {name}"), "point", "curves")
2568
+ ctx.table(res.rows(), f"point_{name}", f"curves of the path {name}")
2569
+ config = behaviour_config(material.to_config(), ctx.folder)
2570
+ (ctx.folder / "material.json").write_text(json.dumps(config, indent=1), encoding="utf-8")
2571
+ if kept:
2572
+ return {"values": values}
2573
+ # a behaviour of its own: it joins the workspace (the run with it), sent on from there
2574
+ label, info = behaviour_summary(config)
2575
+ item = ctx.session.add(ctx.key, "behaviour", f"{label} (material point, {name})",
2576
+ material=config, info=info) # fmt: skip
2577
+ return {"values": values, "items": [ctx.session.public(item)]}
2578
+
2579
+
2580
+ def _reference(text) -> np.ndarray | None:
2581
+ """The points (strain, stress) of a test pasted in the form, or None."""
2582
+ if not text or not str(text).strip():
2583
+ return None
2584
+ rows = []
2585
+ for line in str(text).splitlines():
2586
+ if ";" in line:
2587
+ parts = [x.strip().replace(",", ".") for x in line.split(";")]
2588
+ else:
2589
+ parts = line.replace(",", " ").replace("\t", " ").split()
2590
+ try:
2591
+ numbers = [float(x) for x in parts if x]
2592
+ except ValueError:
2593
+ continue # a header
2594
+ if len(numbers) >= 2:
2595
+ rows.append(numbers[:2])
2596
+ if len(rows) < 2:
2597
+ raise ValueError("points of a test: at least two pairs strain, stress")
2598
+ return np.array(rows, dtype=float)
2599
+
2600
+
2601
+ # -- the identification of a behaviour on references ----------------------------------------
2602
+
2603
+ #: The parameters a form identifies (:mod:`morphogen.homogenization.identification`)
2604
+ IDENTIFIED = (
2605
+ ("yield", "R0, the yield stress (of the matrix)"),
2606
+ ("hardening", "H, the linear hardening"),
2607
+ ("Q", "Q, the isotropic hardening"),
2608
+ ("b", "b, its rate"),
2609
+ ("C", "C, the kinematic hardening (elliptic: C)"),
2610
+ ("D", "D, its recall (Rousselier: D)"),
2611
+ ("K", "K, Norton's viscosity"),
2612
+ ("n", "n, Norton's exponent"),
2613
+ ("young", "E, Young's modulus"),
2614
+ ("poisson", "ν, Poisson's ratio"),
2615
+ *((f"hill{c}", f"h{c}, Hill's coefficient of {c}") for c in HILL_COMPONENTS),
2616
+ ("porosity", "f0, the initial porosity"),
2617
+ ("q1", "q1 of Gurson"),
2618
+ ("q2", "q2 of Gurson or Rousselier"),
2619
+ ("fc", "fc, the onset of coalescence"),
2620
+ ("fF", "fF, the porosity at failure"),
2621
+ ("sigma1", "σ1 of Rousselier"),
2622
+ ("F", "F, elliptic"),
2623
+ )
2624
+ #: The behaviours an identification starts from
2625
+ STARTS = (
2626
+ ("mises", "von Mises elasto-(visco)plasticity (Lemaitre-Chaboche)"),
2627
+ ("porous", "porous plasticity (Gurson-Tvergaard-Needleman, Rousselier, elliptic)"),
2628
+ KEPT,
2629
+ )
2630
+ #: The fields of the behaviours of Mechanics that an identification starts from
2631
+ STARTING = ("kept", "yield_stress", "hardening", "isotropic", "kinematic", "norton", "hill",
2632
+ "criterion", "porosity", "gurson", "coalescence", "rousselier", "elliptic",
2633
+ "nucleation", "nucleation_coefficients") # fmt: skip
2634
+ #: The workspace items whose curves an identification follows (runs of paths and points)
2635
+ RUNS = ("simulation", "behaviour", "result")
2636
+
2637
+
2638
+ def _path_of_run(run: dict, session) -> tuple[str, dict, str]:
2639
+ """The loading path (its name and specification) and the kinematics of a run of a
2640
+ loading path or a material point, read again from the parameters of its form (of an
2641
+ identification: those of its first reference)."""
2642
+ from morphogen.gui.tools import TOOLS, Tool
2643
+
2644
+ params = run.get("params") or {}
2645
+ if run.get("tool") == "identify" and params.get("reference", "runs") == "runs":
2646
+ runs = Field("runs", "items", items=RUNS, required=True).parse(params.get("runs"), session)
2647
+ return _path_of_run(runs[0], session)
2648
+ tool = TOOLS[run["tool"]]
2649
+ # the prefix of the fields of its path (that of the validation path of a learned law)
2650
+ prefix = next((f.name[: -len("loading")] for f in tool.fields if f.name.endswith("loading")),
2651
+ "") # fmt: skip
2652
+ names = {f.name for f in _path_fields(prefix=prefix)} | {"kinematics", "reference"}
2653
+ fields = tuple(f for f in tool.fields if f.name in names)
2654
+ p = Tool("path of a run", "", "", "", fields, None).parse(params, session)
2655
+ name, spec = _path(p, prefix)
2656
+ return name, spec, p.get("kinematics") or "small"
2657
+
2658
+
2659
+ def _varying(stresses) -> list[int]:
2660
+ """The stress components a reference compares: those that vary by more than a tenth of
2661
+ the one that varies most (the lateral stresses of a uniaxial strain, which tell the
2662
+ triaxiality; not the residues of the free components)."""
2663
+ ptp = np.ptp(np.asarray(stresses, dtype=float), axis=0)
2664
+ return [int(c) for c in np.flatnonzero(ptp > 0.1 * ptp.max())] or [int(np.argmax(ptp))]
2665
+
2666
+
2667
+ #: The colours of the stress components in the figures of an identification
2668
+ SHADES = ("#d6604d", "#4393c3", "#5aae61", "#9970ab", "#e08214", "#878787")
2669
+
2670
+
2671
+ def _test_reference(p: dict, start: dict):
2672
+ """The reference of the points of a test along the monotonic strain of the path of the
2673
+ form, placed in time by that strain (the material point of the starting values)."""
2674
+ from morphogen.homogenization import Material, simulate_point
2675
+ from morphogen.homogenization.identification import Reference
2676
+
2677
+ name, spec = _path(p)
2678
+ points = _reference(p["points"])
2679
+ first = simulate_point(Material.from_config(start), spec, kinematics=p["kinematics"])
2680
+ i = int(np.argmax(np.ptp(np.asarray(first.strain), axis=0)))
2681
+ e = np.asarray(first.strain)[:, i]
2682
+ if not (np.all(np.diff(e) >= 0) or np.all(np.diff(e) <= 0)) or np.ptp(e) == 0:
2683
+ raise ValueError("points of a test: along a monotonic strain (tension, relaxation)")
2684
+ order = np.argsort(e, kind="stable")
2685
+ inside = (points[:, 0] >= e.min()) & (points[:, 0] <= e.max())
2686
+ if inside.sum() < 2:
2687
+ raise ValueError("points of a test: at least two within the strains of the path")
2688
+ times = np.interp(points[inside, 0], e[order], np.asarray(first.times)[order])
2689
+ stresses = np.zeros((int(inside.sum()), 6))
2690
+ stresses[:, i] = points[inside, 1]
2691
+ return name, Reference(spec, times, stresses)
2692
+
2693
+
2694
+ @tool(
2695
+ "identify",
2696
+ "mechanics",
2697
+ "Identification of a behaviour",
2698
+ "The parameters of a von Mises, Hill or porous behaviour (yield stress, hardenings, "
2699
+ "viscosity, elastic constants, Hill's coefficients; the initial porosity, Gurson's q1, "
2700
+ "q2, the coalescence, "
2701
+ "Rousselier's and the elliptic coefficients) identified on references, as Zopt does for "
2702
+ "Zsim: the curves of runs of the workspace, each under its own path (the macroscopic "
2703
+ "responses of a morphology, to give it a macroscopic law: a porous morphology under "
2704
+ "several triaxialities, its Gurson model; material points), followed together (a "
2705
+ "tension and a cycle in shear tell the isotropic hardening from the kinematic one), or "
2706
+ "the points of a test along the path of the form; the gap of the stresses of a "
2707
+ "material point over time in the least-squares sense, each reference by its weight "
2708
+ "whatever its number of points, the parameters positive. It starts from the values of "
2709
+ "the form or of a behaviour of the workspace; the behaviour identified joins the "
2710
+ "workspace (B).",
2711
+ [
2712
+ Field(
2713
+ "reference",
2714
+ "choice",
2715
+ "runs",
2716
+ choices=(
2717
+ ("runs", "runs of the workspace: their curves, each under its path"),
2718
+ ("points", "the points of a test, along the path below"),
2719
+ ),
2720
+ ),
2721
+ Field(
2722
+ "runs",
2723
+ "items",
2724
+ items=RUNS,
2725
+ needs=("curves",),
2726
+ required=True,
2727
+ when={"reference": "runs"},
2728
+ doc="loading paths of a morphology (S), material points or identifications (B, "
2729
+ "R), all in small or all in finite strains",
2730
+ ),
2731
+ Field(
2732
+ "weights",
2733
+ "floats",
2734
+ label="weights of the runs",
2735
+ when={"reference": "runs"},
2736
+ doc="one per run checked, in the order of the list (by default 1 each)",
2737
+ ),
2738
+ Field(
2739
+ "points",
2740
+ "text",
2741
+ required=True,
2742
+ label="points of a test",
2743
+ when={"reference": "points"},
2744
+ doc="strain, stress along the component of the path (monotonic), one pair per "
2745
+ "line (comma, space or tab; or semicolons with decimal commas)",
2746
+ ),
2747
+ Field("behaviour", "choice", "mises", choices=STARTS),
2748
+ Field("young", "float", 1.0, label="Young's modulus E", unit="stress", when=PLASTIC),
2749
+ Field("poisson", "float", 0.3, label="Poisson's ratio ν", when=PLASTIC),
2750
+ *(f for f in _behaviour_fields() if f.name in STARTING),
2751
+ Field(
2752
+ "fit",
2753
+ "choices",
2754
+ ["yield", "Q", "b"],
2755
+ label="identified",
2756
+ choices=IDENTIFIED,
2757
+ doc="from the values above (positive), the others held",
2758
+ ),
2759
+ Field(
2760
+ "evaluations",
2761
+ "int",
2762
+ 200,
2763
+ label="evaluations at most",
2764
+ doc="each a material point under the path of each reference",
2765
+ ),
2766
+ *(
2767
+ replace(f, when={**(f.when or {}), "reference": "points"})
2768
+ for f in _path_fields("tension")
2769
+ ),
2770
+ Field(
2771
+ "kinematics",
2772
+ "choice",
2773
+ "small",
2774
+ choices=(("small", "small strains"), ("finite", "finite strains")),
2775
+ when={"reference": "points"},
2776
+ ),
2777
+ ],
2778
+ order=5,
2779
+ groups=(
2780
+ ("References", "reference"),
2781
+ ("Starting behaviour", "behaviour"),
2782
+ ("Identified", "fit"),
2783
+ ("Path of the test", "loading", True),
2784
+ ),
2785
+ menu="Behaviours of materials",
2786
+ )
2787
+ def identify_behaviour(p: dict, ctx) -> dict:
2788
+ from matplotlib.figure import Figure
2789
+ from matplotlib.lines import Line2D
2790
+
2791
+ from morphogen.gui.api import behaviour_summary, curves_of
2792
+ from morphogen.homogenization.identification import Reference, identify_references
2793
+ from morphogen.pipeline import read_rows
2794
+
2795
+ # the values of the form, or those of a behaviour of the workspace (with its elasticity)
2796
+ start = _behaviour(p, {"young": p["young"], "poisson": p["poisson"]}, ctx.folder)
2797
+ if not p["fit"]:
2798
+ raise ValueError("identified: at least one parameter")
2799
+ references, labels = [], []
2800
+ if p["reference"] == "runs":
2801
+ runs = p["runs"]
2802
+ weights = p["weights"] or [1.0] * len(runs)
2803
+ if len(weights) != len(runs) or not all(w > 0 for w in weights):
2804
+ raise ValueError(f"weights of the runs: {len(runs)} positive values, one per run")
2805
+ kinematics = set()
2806
+ for run, weight in zip(runs, weights, strict=True):
2807
+ name, spec, kind = _path_of_run(run, ctx.session)
2808
+ rows = read_rows(curves_of(run, ctx.session.root))
2809
+ times = np.array([float(r["time"]) for r in rows])
2810
+ stresses = np.array([[float(r[f"S{c}"]) for c in COMPONENTS] for r in rows])
2811
+ references.append(Reference(spec, times, stresses, _varying(stresses), weight))
2812
+ labels.append((f"#{run['number']}", "custom" if name == "path" else name))
2813
+ kinematics.add(kind)
2814
+ if len(kinematics) > 1:
2815
+ raise ValueError("runs: all in small strains or all in finite strains")
2816
+ (kinematics,) = kinematics
2817
+ numbers = ", ".join(label for label, _ in labels)
2818
+ source = runs[0]["title"] if len(runs) == 1 else f"the runs {numbers}"
2819
+ else:
2820
+ kinematics = p["kinematics"]
2821
+ name, reference = _test_reference(p, start)
2822
+ references.append(reference)
2823
+ labels.append(("the test", "custom" if name == "path" else name))
2824
+ source = "the points of a test"
2825
+ total = max(int(p["evaluations"]), 1)
2826
+
2827
+ def report(count, error):
2828
+ fraction = min(0.02 + 0.93 * count / total, 0.95)
2829
+ ctx.progress(fraction, f"evaluation {count}: gap {error:.3g}")
2830
+
2831
+ fit = identify_references(start, references, p["fit"], kinematics=kinematics,
2832
+ max_evaluations=total, callback=report) # fmt: skip
2833
+ columns = min(len(references), 3)
2834
+ lines = -(-len(references) // columns)
2835
+ fig = Figure(figsize=(1.0 + 4.4 * columns, 3.8 * lines), layout="constrained")
2836
+ axes = fig.subplots(lines, columns, squeeze=False).ravel()
2837
+ for ax, (label, name), ref, initial, res in zip(
2838
+ axes, labels, fit.references, fit.initial_responses, fit.responses, strict=False
2839
+ ):
2840
+ handles = []
2841
+ for k, c in enumerate(ref.components): # each component its colour
2842
+ shade = SHADES[k % len(SHADES)]
2843
+ ax.plot(ref.times, ref.stresses[:, c], "o", color=shade, ms=3.5, mfc="none")
2844
+ if initial is not None:
2845
+ ax.plot(initial.times, np.asarray(initial.stress)[:, c], "--", color=shade,
2846
+ lw=1.0, alpha=0.6) # fmt: skip
2847
+ handles += ax.plot(res.times, np.asarray(res.stress)[:, c], "-", color=shade,
2848
+ lw=1.8, label=f"S{COMPONENTS[c]}") # fmt: skip
2849
+ shown = source if len(references) == 1 else label
2850
+ handles += [
2851
+ Line2D([], [], color="k", marker="o", mfc="none", ls="", ms=3.5, label=shown),
2852
+ Line2D([], [], color="k", ls="--", lw=1.0, alpha=0.6, label="starting values"),
2853
+ Line2D([], [], color="k", ls="-", lw=1.8, label="identified"),
2854
+ ]
2855
+ ax.set_xlabel("time")
2856
+ ax.set_ylabel(f"S{COMPONENTS[ref.components[0]]}" if len(ref.components) == 1 else "stress")
2857
+ ax.set_title(f"{label}, path {name}", fontsize=9)
2858
+ ax.grid(alpha=0.3)
2859
+ ax.legend(handles=handles, fontsize=8, frameon=False)
2860
+ for ax in axes[len(references) :]:
2861
+ ax.set_visible(False)
2862
+ ctx.figure(fig, "identification", "the responses identified, under the paths followed")
2863
+ ctx.table([{"parameter": k, "start": fit.initial[k], "identified": v}
2864
+ for k, v in fit.values.items()], "parameters", "the parameters") # fmt: skip
2865
+ _elasticity_tables(ctx, fit.material, "of the behaviour identified")
2866
+ followed = zip(labels, fit.references, fit.initial_gaps, fit.gaps, strict=True)
2867
+ ctx.table(
2868
+ [
2869
+ {
2870
+ "reference": label,
2871
+ "path": name,
2872
+ "components": ", ".join(f"S{COMPONENTS[c]}" for c in r.components),
2873
+ "points": len(r.times),
2874
+ "weight": r.weight,
2875
+ "starting gap": g0,
2876
+ "gap": g,
2877
+ }
2878
+ for (label, name), r, g0, g in followed
2879
+ ],
2880
+ "references",
2881
+ "the references followed",
2882
+ )
2883
+ for i, ((label, name), res) in enumerate(zip(labels, fit.responses, strict=True), start=1):
2884
+ ctx.table(res.rows(), f"identified_{i:02d}_{name}", f"curves of the path {name} ({label})")
2885
+ (ctx.folder / "material.json").write_text(json.dumps(fit.material, indent=1), "utf-8")
2886
+ label, info = behaviour_summary(fit.material)
2887
+ item = ctx.session.add(ctx.key, "behaviour", f"{label} (identified on {source})",
2888
+ material=fit.material, info=info) # fmt: skip
2889
+ values = {"gap": fit.error, "starting gap": fit.initial_error,
2890
+ "evaluations": fit.evaluations, **fit.values} # fmt: skip
2891
+ if len(references) > 1:
2892
+ values.update({f"gap {label}": g for (label, _), g in zip(labels, fit.gaps, strict=True)})
2893
+ return {"values": values, "items": [ctx.session.public(item)]}
2894
+
2895
+
2896
+ # -- the macroscopic law of a morphology ---------------------------------------------------
2897
+
2898
+ #: The laws a morphology may be given
2899
+ LAWS = (
2900
+ ("hill", "Hill's criterion: its coefficients of the loadings run (that of the first stays 1)"),
2901
+ ("mises", "von Mises"),
2902
+ ("gurson", "Gurson's porous plasticity: q1, q2 of the matrix of the phase, its voids"),
2903
+ )
2904
+ #: The loadings of a macroscopic law
2905
+ LOADING_CHOICES = (
2906
+ ("11", "tension along 1"),
2907
+ ("22", "tension along 2"),
2908
+ ("33", "tension along 3"),
2909
+ ("12", "shear in the plane 12"),
2910
+ ("23", "shear in the plane 23"),
2911
+ ("31", "shear in the plane 31"),
2912
+ ("confined11", "tension along 1, its lateral strains held (a high stress triaxiality)"),
2913
+ ("confined22", "tension along 2, its lateral strains held"),
2914
+ ("confined33", "tension along 3, its lateral strains held"),
2915
+ ("hydrostatic", "hydrostatic tension"),
2916
+ )
2917
+
2918
+
2919
+ @tool(
2920
+ "macroscopic_law",
2921
+ "mechanics",
2922
+ "Macroscopic law of a morphology",
2923
+ "The elasto-plastic law that gives a morphology its macroscopic behaviour, in one go: "
2924
+ "its responses (nonlinear FFT on its voxels) under a tension along each axis and a "
2925
+ "shear in each plane checked, the other stresses free (monotonic, or cycles that show "
2926
+ "the Bauschinger effect), then a von Mises or Hill law (Z-set's form) identified on "
2927
+ "them together, from a law estimated on the responses: Young's modulus, Poisson's "
2928
+ "ratio, the yield stress, the linear hardening, with cycles a kinematic hardening and, "
2929
+ "for Hill, the coefficients of the loadings run (an anisotropic morphology: aligned "
2930
+ "fibres, laminates, lattices); or Gurson's law of a porous morphology, the matrix that "
2931
+ "of the phase and the porosity its voids, q1 and q2 identified on loadings of several "
2932
+ "stress triaxialities (a tension, a confined or hydrostatic one), as on unit cells "
2933
+ "(Tvergaard 1981). The law joins the workspace (B) and is written as a Z-mat file for "
2934
+ "Z-set.",
2935
+ [
2936
+ Field("source", "item", label="morphology", required=True),
2937
+ Field(
2938
+ "materials",
2939
+ "materials",
2940
+ of="source",
2941
+ doc="elastic constants of the phases (the unit of the stresses), or voids",
2942
+ ),
2943
+ Field(
2944
+ "phase",
2945
+ "int",
2946
+ label="phase of the behaviour",
2947
+ doc="blank: the first phase that is not a void (the matrix, the solid, the grains)",
2948
+ ),
2949
+ *_behaviour_fields("of that phase; the other phases are elastic, or voids"),
2950
+ BEHAVIOURS_FIELD,
2951
+ Field(
2952
+ "loadings",
2953
+ "choices",
2954
+ ["11", "22", "33", "12", "23", "31"],
2955
+ choices=LOADING_CHOICES,
2956
+ doc="each a loading of its component (monotonic, or a cycle below), the other "
2957
+ "stresses free",
2958
+ ),
2959
+ Field("strain", "float", 0.01, label="strain of each loading", doc="the component loaded"),
2960
+ Field("increments", "int", 20, label="increments of each loading"),
2961
+ Field(
2962
+ "cycle",
2963
+ "bool",
2964
+ False,
2965
+ label="cycles",
2966
+ doc="each loading then back to -strain (twice the increments): its Bauschinger "
2967
+ "effect, and a kinematic hardening (C, D) in the law",
2968
+ ),
2969
+ Field("law", "choice", "hill", choices=LAWS),
2970
+ Field(
2971
+ "evaluations",
2972
+ "int",
2973
+ 200,
2974
+ label="evaluations at most",
2975
+ doc="each a material point under the paths of the loadings",
2976
+ ),
2977
+ Field(
2978
+ "method",
2979
+ "choice",
2980
+ "fft",
2981
+ choices=(
2982
+ ("fft", "FFT on its voxels (periodic)"),
2983
+ ("fe", "finite elements on the conforming mesh of its level set"),
2984
+ ),
2985
+ ),
2986
+ Field("voxels", "int", 16, label="voxels per edge", when={"method": "fft"}),
2987
+ Field(
2988
+ "integration",
2989
+ "choice",
2990
+ "bbar",
2991
+ when={"method": "fft"},
2992
+ choices=(
2993
+ ("bbar", "B-bar (F-bar in finite strains): no locking under plastic flow"),
2994
+ ("full", "full: 8 Gauss points per voxel"),
2995
+ ),
2996
+ ),
2997
+ _device_field(when={"method": "fft"}),
2998
+ Field(
2999
+ "element_size",
3000
+ "float",
3001
+ unit="length",
3002
+ when={"method": "fe"},
3003
+ doc="largest edge of the elements (blank: 1/4 of the edge of the domain)",
3004
+ ),
3005
+ Field(
3006
+ "order",
3007
+ "choice",
3008
+ "2",
3009
+ label="elements",
3010
+ when={"method": "fe"},
3011
+ choices=(
3012
+ ("2", "10-node tetrahedra (accurate plastic flow)"),
3013
+ ("1", "4-node tetrahedra (fast; they lock under isochoric plastic flow)"),
3014
+ ),
3015
+ ),
3016
+ Field(
3017
+ "fe_integration",
3018
+ "choice",
3019
+ "full",
3020
+ label="integration",
3021
+ when={"method": "fe"},
3022
+ choices=(
3023
+ ("full", "full: every point of the elements"),
3024
+ (
3025
+ "bbar",
3026
+ "B-bar (F-bar in finite strains): the volume change of each 10-node "
3027
+ "element as its mean, for nearly incompressible phases (elastomers)",
3028
+ ),
3029
+ ),
3030
+ ),
3031
+ Field(
3032
+ "kinematics",
3033
+ "choice",
3034
+ "small",
3035
+ choices=(
3036
+ ("small", "small strains"),
3037
+ ("finite", "finite strains (the law in the space of the logarithmic strain)"),
3038
+ ),
3039
+ ),
3040
+ ],
3041
+ order=2,
3042
+ groups=(
3043
+ ("Morphology and materials", "source"),
3044
+ ("Behaviour of the phase", "behaviour"),
3045
+ ("Loadings", "loadings"),
3046
+ ("Law", "law"),
3047
+ ("Solver", "method", True),
3048
+ ),
3049
+ menu="Loading paths",
3050
+ )
3051
+ def macroscopic_law(p: dict, ctx) -> dict:
3052
+ from matplotlib.figure import Figure
3053
+
3054
+ from morphogen import pipeline
3055
+ from morphogen.config import load_config
3056
+ from morphogen.gui.api import behaviour_summary
3057
+ from morphogen.homogenization import NonlinearFEProblem, NonlinearFFTProblem
3058
+ from morphogen.homogenization.identification import loading_path
3059
+ from morphogen.homogenization.identification import macroscopic_law as law_of
3060
+ from morphogen.homogenization.materials import any_oriented
3061
+ from morphogen.homogenization.zmat import write_zmat
3062
+
3063
+ source = p["source"]
3064
+ micro = source["micro"]
3065
+ materials, phase = _materials(p, source, ctx.folder)
3066
+ loadings = [c for c, _ in LOADING_CHOICES if c in (p["loadings"] or [])]
3067
+ voids = [k for k, m in materials.items() if m == "void"]
3068
+ if p["law"] == "gurson" and not voids:
3069
+ raise ValueError("Gurson's law: a porous morphology (one of its phases a void)")
3070
+ if not loadings:
3071
+ raise ValueError("loadings: at least one")
3072
+ fe = p["method"] == "fe"
3073
+ if not fe and not 4 <= p["voxels"] <= 64:
3074
+ raise ValueError("voxels per edge: from 4 to 64 for a macroscopic law")
3075
+ if not p["strain"] > 0 or p["increments"] < 2:
3076
+ raise ValueError("strain: positive, in two increments at least")
3077
+ data = {
3078
+ "model": source.get("model") or {"type": "tpms", "volume_fraction": 0.5}, # a stand-in
3079
+ "domain": source.get("domain")
3080
+ or {"size": [float(v) for v in micro.domain.lengths], "periodic": True},
3081
+ "seed": int(source.get("seed") or 1),
3082
+ "homogenization": {
3083
+ "materials": {k: _relative(v, ctx.folder) for k, v in materials.items()},
3084
+ "method": p["method"],
3085
+ "boundary_conditions": ["periodic"],
3086
+ "properties": [],
3087
+ "paths": { # those of the loadings (checked here; run by the identification)
3088
+ f"loading{c}": loading_path(c, p["strain"], p["increments"], bool(p["cycle"]))[0]
3089
+ for c in loadings
3090
+ },
3091
+ "nonlinear": {"kinematics": p["kinematics"]},
3092
+ },
3093
+ "outputs": {"directory": str(ctx.folder), "name": "sample"},
3094
+ }
3095
+ edge = float(np.max(micro.domain.lengths))
3096
+ if fe:
3097
+ size = p["element_size"] or edge / 4
3098
+ if not edge / 200 <= size <= edge:
3099
+ raise ValueError(f"element size: between {edge / 200:g} and {edge:g}")
3100
+ data["mesh"] = {"size": size, "order": int(p["order"])}
3101
+ data["homogenization"]["nonlinear"]["integration"] = p["fe_integration"]
3102
+ else:
3103
+ data["voxels"] = {"shape": p["voxels"]}
3104
+ data["homogenization"]["nonlinear"]["integration"] = p["integration"]
3105
+ cfg = load_config(data, base_dir=ctx.folder) # the errors of the form, before solving
3106
+ homog = cfg.homogenization
3107
+ options = homog.options()["nonlinear"]
3108
+ if fe:
3109
+ ctx.progress(0.01, "conforming mesh")
3110
+ mesh, _ = pipeline._conforming_mesh(micro, cfg)
3111
+
3112
+ def problem():
3113
+ return NonlinearFEProblem(mesh, homog.materials, "periodic", solver=homog.solver,
3114
+ tol=homog.tolerance, **options) # fmt: skip
3115
+ else:
3116
+ steps = p["increments"] * (3 if p["cycle"] else 1) + 1
3117
+ _check_voxels(micro, cfg.voxels.shape, steps, "macroscopic law on voxels")
3118
+ image = micro.voxelize(**cfg.voxels.kwargs())
3119
+ grains = {}
3120
+ if any_oriented(homog.materials) and getattr(micro, "orientations", None) is not None:
3121
+ labels = micro.labels(grid=image.grid())
3122
+ grains = {"grains": labels, "orientations": micro.orientations}
3123
+
3124
+ def problem():
3125
+ return NonlinearFFTProblem(image, homog.materials, "periodic", tol=homog.tolerance,
3126
+ device=p["device"], **grains, **options) # fmt: skip
3127
+
3128
+ done = [0]
3129
+
3130
+ def respond(path):
3131
+ c = next(iter(path["strain"]))
3132
+ ctx.progress(0.02 + 0.6 * done[0] / len(loadings), f"loading {c} of the morphology")
3133
+ done[0] += 1
3134
+ return problem().run(path)
3135
+
3136
+ total = max(int(p["evaluations"]), 1)
3137
+
3138
+ def report(count, error):
3139
+ ctx.progress(min(0.65 + 0.3 * count / total, 0.95), f"evaluation {count}: gap {error:.3g}")
3140
+
3141
+ porous = {}
3142
+ if p["law"] == "gurson": # the matrix of the phase, the voids of the morphology
3143
+ sample = image if not fe else micro.voxelize(shape=32)
3144
+ porosity = float(np.isin(np.asarray(sample.data), voids).mean())
3145
+ porous = {"matrix": materials[phase], "porosity": porosity}
3146
+ law = law_of(respond, law=p["law"], loadings=loadings, strain=p["strain"],
3147
+ increments=p["increments"], cycle=bool(p["cycle"]),
3148
+ kinematics=p["kinematics"], max_evaluations=total, callback=report,
3149
+ **porous) # fmt: skip
3150
+ fit = law.identification
3151
+ columns = min(len(loadings), 3)
3152
+ lines = -(-len(loadings) // columns)
3153
+ fig = Figure(figsize=(1.0 + 4.4 * columns, 3.8 * lines), layout="constrained")
3154
+ axes = fig.subplots(lines, columns, squeeze=False).ravel()
3155
+ for ax, c, ref, initial, res in zip(axes, loadings, law.responses, fit.initial_responses,
3156
+ fit.responses, strict=False): # fmt: skip
3157
+ # the component loaded (the axis of a confined tension, 11 of a hydrostatic one)
3158
+ k = COMPONENTS.index(c if c in COMPONENTS else (c[-2:] if c[-1].isdigit() else "11"))
3159
+ strain = np.asarray(ref.strain)[:, k]
3160
+ ax.plot(strain, np.asarray(ref.stress)[:, k], "o", ms=3.5, mfc="none", color=SHADES[0],
3161
+ label="the morphology") # fmt: skip
3162
+ if initial is not None:
3163
+ ax.plot(np.asarray(initial.strain)[:, k], np.asarray(initial.stress)[:, k], "--",
3164
+ lw=1.0, alpha=0.6, color="k", label="estimated law") # fmt: skip
3165
+ ax.plot(np.asarray(res.strain)[:, k], np.asarray(res.stress)[:, k], "-", lw=1.8,
3166
+ color=SHADES[1], label="law identified") # fmt: skip
3167
+ ax.set_xlabel(f"E{COMPONENTS[k]}")
3168
+ ax.set_ylabel(f"S{COMPONENTS[k]}")
3169
+ if c in COMPONENTS:
3170
+ title = ("tension " if c[0] == c[1] else "shear ") + c
3171
+ else:
3172
+ title = "hydrostatic tension" if c == "hydrostatic" else f"confined tension {c[-2:]}"
3173
+ ax.set_title(title, fontsize=9)
3174
+ ax.grid(alpha=0.3)
3175
+ ax.legend(fontsize=8, frameon=False)
3176
+ for ax in axes[len(loadings) :]:
3177
+ ax.set_visible(False)
3178
+ ctx.figure(fig, "macroscopic_law", "the responses of the morphology and of its law")
3179
+ ctx.table([{"parameter": k, "estimated": fit.initial[k], "identified": v}
3180
+ for k, v in fit.values.items()], "parameters", "the parameters") # fmt: skip
3181
+ ctx.table([{"loading": c, "starting gap": g0, "gap": g} for c, g0, g in
3182
+ zip(loadings, fit.initial_gaps, fit.gaps, strict=True)], "loadings",
3183
+ "the loadings followed") # fmt: skip
3184
+ _elasticity_tables(ctx, fit.material, "of the law identified")
3185
+ for c, res in zip(loadings, law.responses, strict=True):
3186
+ ctx.table(res.rows(), f"morphology_{c}", f"curves of the morphology under the loading {c}")
3187
+ title = f"the macroscopic law of #{source['number']} {source['title']}"
3188
+ write_zmat(fit.material, ctx.folder / "macroscopic_law.mat", title=title, digits=6)
3189
+ (ctx.folder / "material.json").write_text(json.dumps(fit.material, indent=1), "utf-8")
3190
+ label, info = behaviour_summary(fit.material)
3191
+ item = ctx.session.add(ctx.key, "behaviour",
3192
+ f"{label} (macroscopic law of #{source['number']})",
3193
+ material=fit.material, info=info) # fmt: skip
3194
+ values = {"gap": fit.error, "starting gap": fit.initial_error,
3195
+ "evaluations": fit.evaluations, **fit.values} # fmt: skip
3196
+ values.update({f"gap {c}": g for c, g in zip(loadings, fit.gaps, strict=True)})
3197
+ return {"values": values, "items": [ctx.session.public(item)]}
3198
+
3199
+
3200
+ # -- the linear tensors of a morphology ----------------------------------------------------
3201
+
3202
+ TENSORS = (
3203
+ ("stiffness", "stiffness tensor (engineering constants, anisotropy)"),
3204
+ ("thermal_expansion", "thermal expansion tensor"),
3205
+ ("conductivity_tensor", "conductivity tensor"),
3206
+ )
3207
+ CRYSTALS = (
3208
+ ("none", "isotropic phases"),
3209
+ ("cubic", "a cubic crystal: C11, C12, C44"),
3210
+ ("hexagonal", "a hexagonal crystal: C11, C12, C13, C33, C44 (axis c along 3)"),
3211
+ )
3212
+
3213
+
3214
+ @tool(
3215
+ "tensors",
3216
+ "mechanics",
3217
+ "Linear tensors",
3218
+ "The apparent stiffness tensor of a morphology (its engineering constants, anisotropy "
3219
+ "indices and isotropic projection), its thermal expansion and its conductivity tensor, "
3220
+ "by FFT on its voxels, by finite elements on its conforming mesh (periodic, kinematic "
3221
+ "or static conditions) or by extended finite elements (XFEM) on a regular grid that its "
3222
+ "level set cuts (periodic; no mesh to build, and the interfaces where the model puts "
3223
+ "them); crystals turned by the orientations of the grains of polycrystals; against the "
3224
+ "bounds of the phase fractions (Voigt, Reuss, Hashin-Shtrikman, Levin) and with the "
3225
+ "directional Young's modulus.",
3226
+ [
3227
+ Field("source", "item", label="morphology", required=True),
3228
+ Field(
3229
+ "materials",
3230
+ "materials",
3231
+ of="source",
3232
+ doc="isotropic elastic constants of the phases, or voids",
3233
+ ),
3234
+ Field("tensors", "choices", ["stiffness"], choices=TENSORS),
3235
+ Field(
3236
+ "expansions",
3237
+ "floats",
3238
+ label="thermal expansions of the phases",
3239
+ doc="one per phase, in the order of the materials (the thermal expansion)",
3240
+ ),
3241
+ Field(
3242
+ "conductivities",
3243
+ "floats",
3244
+ label="conductivities of the phases",
3245
+ doc="one per phase, in the order of the materials (the conductivity tensor)",
3246
+ ),
3247
+ Field("crystal", "choice", "none", label="crystals", choices=CRYSTALS),
3248
+ Field(
3249
+ "crystal_phase",
3250
+ "int",
3251
+ label="phase of the crystals",
3252
+ when={"crystal": ["cubic", "hexagonal"]},
3253
+ doc="blank: the first phase that is not a void; its grains turned by their "
3254
+ "orientations (tessellations with crystal orientations)",
3255
+ ),
3256
+ Field(
3257
+ "constants",
3258
+ "floats",
3259
+ [1.684, 1.214, 0.754],
3260
+ label="elastic constants of the crystal",
3261
+ unit="stress",
3262
+ when={"crystal": ["cubic", "hexagonal"]},
3263
+ doc="in its axes (the default: copper, in units of 100 GPa)",
3264
+ ),
3265
+ BEHAVIOURS_FIELD,
3266
+ Field(
3267
+ "method",
3268
+ "choice",
3269
+ "fft",
3270
+ choices=(
3271
+ ("fft", "FFT on its voxels (periodic)"),
3272
+ ("fe", "finite elements on the conforming mesh of its level set"),
3273
+ (
3274
+ "xfem",
3275
+ "extended finite elements (XFEM) on a grid cut by its level set (periodic, "
3276
+ "two phases)",
3277
+ ),
3278
+ ),
3279
+ ),
3280
+ Field("voxels", "int", 32, label="voxels per edge", when={"method": "fft"}),
3281
+ Field(
3282
+ "cells",
3283
+ "int",
3284
+ 16,
3285
+ label="cells per edge",
3286
+ when={"method": "xfem"},
3287
+ doc="of the grid of the extended finite elements, along the longest edge (4 to 48)",
3288
+ ),
3289
+ Field(
3290
+ "element_size",
3291
+ "float",
3292
+ unit="length",
3293
+ when={"method": "fe"},
3294
+ doc="largest edge of the elements (blank: 1/8 of the edge of the domain)",
3295
+ ),
3296
+ Field(
3297
+ "order",
3298
+ "choice",
3299
+ "2",
3300
+ label="elements",
3301
+ when={"method": "fe"},
3302
+ choices=(
3303
+ ("2", "10-node tetrahedra (curved along the interfaces; accurate)"),
3304
+ ("1", "4-node tetrahedra (fast; stiff)"),
3305
+ ),
3306
+ ),
3307
+ Field(
3308
+ "bc",
3309
+ "choice",
3310
+ "periodic",
3311
+ label="boundary conditions",
3312
+ when={"method": "fe"},
3313
+ choices=(
3314
+ ("periodic", "periodic"),
3315
+ ("kubc", "kinematic (KUBC)"),
3316
+ ("subc", "static (SUBC)"),
3317
+ ),
3318
+ ),
3319
+ ],
3320
+ order=6,
3321
+ menu="Linear elasticity",
3322
+ )
3323
+ def linear_tensors(p: dict, ctx) -> dict:
3324
+ from morphogen.analysis.basic import phase_fractions
3325
+ from morphogen.config import MeshSpec
3326
+ from morphogen.homogenization import bounds, homogenize
3327
+ from morphogen.homogenization.materials import any_oriented, materials_from_config
3328
+
3329
+ source = p["source"]
3330
+ micro = source["micro"]
3331
+ wanted = list(p["tensors"] or [])
3332
+ if not wanted:
3333
+ raise ValueError("tensors: at least one")
3334
+ elastic = _elastic(source, p.get("materials"))
3335
+ configs: dict = {}
3336
+ for name, given in (
3337
+ ("expansions", p.get("expansions")),
3338
+ ("conductivities", p.get("conductivities")),
3339
+ ):
3340
+ if given and len(given) != len(elastic):
3341
+ raise ValueError(f"{name} of the phases: one per phase ({len(elastic)})")
3342
+ if "thermal_expansion" in wanted and not p.get("expansions"):
3343
+ raise ValueError("thermal expansions of the phases: one per phase (the thermal expansion)")
3344
+ if "conductivity_tensor" in wanted and not p.get("conductivities"):
3345
+ raise ValueError("conductivities of the phases: one per phase (the conductivity tensor)")
3346
+ crystal = p["crystal"]
3347
+ phase = p.get("crystal_phase") if crystal != "none" else None
3348
+ if crystal != "none" and phase is None:
3349
+ phase = next((k for k, m in elastic.items() if m != "void"), None)
3350
+ if phase is not None and elastic.get(phase, "void") == "void":
3351
+ raise ValueError(f"phase of the crystals: phase {phase} is a void or no phase")
3352
+ for index, (k, m) in enumerate(elastic.items()):
3353
+ if m == "void":
3354
+ configs[k] = "void"
3355
+ continue
3356
+ spec = dict(m)
3357
+ if k == phase:
3358
+ constants = [float(c) for c in p.get("constants") or []]
3359
+ if len(constants) != (3 if crystal == "cubic" else 5):
3360
+ raise ValueError(
3361
+ "elastic constants of the crystal: C11, C12, C44 (cubic) or C11, C12, C13, "
3362
+ "C33, C44 (hexagonal)"
3363
+ )
3364
+ spec = {crystal: constants}
3365
+ if p.get("expansions"):
3366
+ spec["expansion"] = p["expansions"][index]
3367
+ if p.get("conductivities"):
3368
+ spec["conductivity"] = p["conductivities"][index]
3369
+ configs[k] = spec
3370
+ configs.update(_extra(p))
3371
+ materials = materials_from_config(configs)
3372
+ stage = {"fe": "conforming mesh", "xfem": "grid cut by the level set"}
3373
+ ctx.progress(0.05, stage.get(p["method"], "voxels"))
3374
+ extra_args: dict = {}
3375
+ if p["method"] == "xfem":
3376
+ from morphogen.homogenization import LevelSetSample
3377
+
3378
+ n = p["cells"]
3379
+ if not 4 <= n <= 48:
3380
+ raise ValueError("cells per edge: from 4 to 48 for the extended finite elements")
3381
+ if micro.implicit_phases() != [0, 1]:
3382
+ raise ValueError(
3383
+ "extended finite elements: a morphology of two phases, cut by its level set; "
3384
+ "those of several phases by finite elements on their conforming mesh, or by FFT"
3385
+ )
3386
+ if not micro.domain.periodic:
3387
+ raise ValueError("extended finite elements: a periodic morphology")
3388
+ if any_oriented(materials):
3389
+ raise ValueError("extended finite elements: isotropic phases (crystals: FFT or FE)")
3390
+ sample = LevelSetSample.of(micro, n)
3391
+ bc = "periodic"
3392
+ fractions = sample.phase_fractions()
3393
+ info = {"cells": int(np.prod(sample.shape))}
3394
+ elif p["method"] == "fe":
3395
+ from morphogen.mesh.conforming import conforming_mesh
3396
+
3397
+ edge = float(np.max(micro.domain.lengths))
3398
+ size = p["element_size"] or edge / 8
3399
+ if not edge / 200 <= size <= edge:
3400
+ raise ValueError(f"element size: between {edge / 200:g} and {edge:g}")
3401
+ voids = {int(k) for k, m in materials.items() if m.void} # the solid phase is meshed
3402
+ sample = conforming_mesh(micro, **MeshSpec(size=size, order=int(p["order"])).kwargs(voids))
3403
+ bc = p["bc"]
3404
+ fractions = sample.phase_fractions()
3405
+ absent = [k for k in materials if k not in fractions]
3406
+ if len(absent) == 1: # the pores, left out of the mesh
3407
+ fractions[absent[0]] = max(0.0, 1.0 - sum(fractions.values()))
3408
+ info = {"elements": sample.n_elements, "nodes": sample.n_nodes}
3409
+ else:
3410
+ n = p["voxels"]
3411
+ if not 4 <= n <= 256:
3412
+ raise ValueError("voxels per edge: from 4 to 256")
3413
+ sample = micro.voxelize(shape=n)
3414
+ bc = "periodic"
3415
+ fractions = phase_fractions(sample)
3416
+ if any_oriented(materials) and getattr(micro, "orientations", None) is not None:
3417
+ extra_args = {
3418
+ "grains": micro.labels(grid=sample.grid()),
3419
+ "orientations": micro.orientations,
3420
+ }
3421
+ info = {"voxels": int(np.prod(sample.shape))}
3422
+ ctx.progress(0.2, "solving")
3423
+ results = homogenize(sample, materials, bcs=[bc], properties=wanted, **extra_args)
3424
+ values: dict = dict(info)
3425
+ for name in wanted:
3426
+ res = results[f"{name}.{bc}"]
3427
+ tensor = np.asarray(res["tensor"])
3428
+ if name == "stiffness": # with its compliance S = C⁻¹, in the same notation
3429
+ elastic_tables(ctx, tensor, f"({bc})")
3430
+ else:
3431
+ labels = ("1", "2", "3")
3432
+ rows = [
3433
+ {"": a, **{b: float(tensor[i, j]) for j, b in enumerate(labels)}}
3434
+ for i, a in enumerate(labels)
3435
+ ]
3436
+ ctx.table(rows, name, f"{name.replace('_', ' ')} ({bc})")
3437
+ values.update({f"{name}.{k}": v for k, v in res.items() if isinstance(v, float)})
3438
+ if name == "stiffness":
3439
+ ctx.figure(_young_figure(tensor), "young_modulus", "directional Young's modulus")
3440
+ limits = bounds({k: v for k, v in fractions.items() if k in materials}, materials)
3441
+ rows = [{"property": prop, **values_} for prop, values_ in limits.items()]
3442
+ if rows:
3443
+ ctx.table(rows, "bounds", "bounds of the phase fractions")
3444
+ values.update({f"fraction_{k}": float(v) for k, v in sorted(fractions.items())})
3445
+ return {"values": values}
3446
+
3447
+
3448
+ def _elasticity_tables(ctx, material: dict, of: str) -> None:
3449
+ """The tables of the elasticity of a behaviour (its configuration): its stiffness and
3450
+ compliance (``elasticity_stiffness.csv``, ``elasticity_compliance.csv``), none for a
3451
+ behaviour without elastic constants of its own (a law of Z-set or MFront)."""
3452
+ from morphogen.homogenization.materials import Material
3453
+
3454
+ try:
3455
+ m = Material.from_config(material)
3456
+ except (ValueError, TypeError, KeyError, OSError):
3457
+ return
3458
+ if m.elastic and not m.void:
3459
+ names = ("elasticity_stiffness", "elasticity_compliance")
3460
+ elastic_tables(ctx, m.matrix("elastic"), of, names=names)
3461
+
3462
+
3463
+ def _young_figure(stiffness):
3464
+ """The directional Young's modulus ``1 / (n n : S : n n)`` of a stiffness in the planes
3465
+ of the axes (polar curves); of a plane stiffness (3 x 3, Voigt 11, 22, 12), in its
3466
+ plane."""
3467
+ from matplotlib.figure import Figure
3468
+
3469
+ compliance = np.linalg.inv(np.asarray(stiffness, dtype=float))
3470
+ plane = compliance.shape == (3, 3)
3471
+ angle = np.linspace(0.0, 2.0 * np.pi, 361)
3472
+ fig = Figure(figsize=(5.0, 4.4), layout="constrained")
3473
+ ax = fig.add_subplot(projection="polar")
3474
+ planes = (((0, 1), "x-y plane"), ((1, 2), "y-z plane"), ((2, 0), "z-x plane"))
3475
+ for (a, b), name in planes[:1] if plane else planes:
3476
+ n = np.zeros((angle.size, 3))
3477
+ n[:, a], n[:, b] = np.cos(angle), np.sin(angle)
3478
+ if plane:
3479
+ v = np.stack([n[:, 0] ** 2, n[:, 1] ** 2, n[:, 0] * n[:, 1]], axis=1)
3480
+ else:
3481
+ v = np.stack(
3482
+ [
3483
+ n[:, 0] ** 2,
3484
+ n[:, 1] ** 2,
3485
+ n[:, 2] ** 2,
3486
+ n[:, 1] * n[:, 2],
3487
+ n[:, 2] * n[:, 0],
3488
+ n[:, 0] * n[:, 1],
3489
+ ],
3490
+ axis=1,
3491
+ )
3492
+ ax.plot(angle, 1.0 / np.einsum("ni,ij,nj->n", v, compliance, v), lw=1.6, label=name)
3493
+ ax.set_title("directional Young's modulus", fontsize=10)
3494
+ ax.legend(fontsize=8, frameon=False, loc="upper center", bbox_to_anchor=(0.5, -0.06), ncol=3)
3495
+ return fig
3496
+
3497
+
3498
+ # -- the frames of beams of networks -----------------------------------------------------
3499
+
3500
+ #: The beams of the frames of networks
3501
+ BEAMS = (
3502
+ ("euler_bernoulli", "Euler–Bernoulli (rigid in transverse shear)"),
3503
+ ("timoshenko", "Timoshenko (transverse shear stiffness κGA)"),
3504
+ )
3505
+ #: The modes of the beams whose stiffness varies from beam to beam (Ban et al. 2016)
3506
+ SOFTENING = (
3507
+ ("axial", "axial stiffness EA"),
3508
+ ("bending", "bending stiffness EI"),
3509
+ ("modulus", "Young's modulus (EA, EI, GJ and κGA)"),
3510
+ ("area", "area of a general section (EA and κGA)"),
3511
+ )
3512
+ #: The laws of the stiffness of the beams of the replicas (mean 1, coefficient of variation
3513
+ #: CV; :func:`morphogen.homogenization.networks.fibre_scales`)
3514
+ DISTRIBUTIONS = (
3515
+ ("normal", "normal (draws below 10⁻³ raised to it)"),
3516
+ ("lognormal", "lognormal"),
3517
+ ("bimodal", "bimodal: 1 ± CV, equally likely"),
3518
+ )
3519
+ #: The colours of the beams of the drawing of the frame under a uniaxial stress: the value
3520
+ #: of each beam (``force``: its axial force; the others: its share of the energy of the
3521
+ #: network), the scale of :func:`morphogen.viz.figures.frame_figure` and the label
3522
+ DRAWN = {
3523
+ "force": ("symmetric", "axial force N under a stress of 1 along {axis} (tension > 0)"),
3524
+ "stretching": ("log", "share of the energy in the stretching of the beam"),
3525
+ "bending": ("log", "share of the energy in the bending of the beam (torsion, shear)"),
3526
+ "beams": ("linear", ""),
3527
+ }
3528
+ DRAWINGS = (
3529
+ ("force", "axial force (the force chains)"),
3530
+ ("stretching", "stretching energy of each beam"),
3531
+ ("bending", "bending energy of each beam (with its torsion and shear)"),
3532
+ ("beams", "the beams alone"),
3533
+ )
3534
+ #: The Voigt components of plane stiffnesses (11, 22, 12; engineering shear)
3535
+ PLANE_COMPONENTS = ("11", "22", "12")
3536
+
3537
+
3538
+ @tool(
3539
+ "frame",
3540
+ "mechanics",
3541
+ "Stiffness of the frame of beams",
3542
+ "The effective stiffness of a fibre network, an open foam or a random lattice of the "
3543
+ "workspace as the periodic frame of beams of circular sections along its fibres or "
3544
+ "struts. The realizations of delaunay_network, open_foam and random_lattice keep their "
3545
+ "framework; Euler–Bernoulli or Timoshenko beams (Cowper's shear coefficient by default), "
3546
+ "rigid over a few radii at the joints on request. Its Voigt stiffness and engineering "
3547
+ "constants, the split of the energy of a uniaxial stress along each axis into the "
3548
+ "stretching, bending, torsion and shear of the beams, its ratio to the affine estimate "
3549
+ "and the non-affinity of the deformation, a drawing of the beams coloured by their axial "
3550
+ "forces or energies under a uniaxial stress (the force chains, the beams that bend), and "
3551
+ "the softening of networks of non-identical beams (the coefficients s and v of Ban, "
3552
+ "Barocas, Shephard & Picu 2016, and replicas of the stiffness of the beams against them).",
3553
+ [
3554
+ Field(
3555
+ "source",
3556
+ "item",
3557
+ label="network",
3558
+ required=True,
3559
+ needs=("framework",),
3560
+ doc="a realization of delaunay_network, open_foam or random_lattice (Generate), "
3561
+ "whose framework becomes the frame",
3562
+ ),
3563
+ Field("beams", "choice", "euler_bernoulli", choices=BEAMS),
3564
+ Field(
3565
+ "shear_coefficient",
3566
+ "float",
3567
+ label="shear coefficient κ",
3568
+ when={"beams": "timoshenko"},
3569
+ doc="of the transverse shear stiffness κGA (blank: Cowper's, 6(1 + ν)/(7 + 6ν) "
3570
+ "for circular sections)",
3571
+ ),
3572
+ Field(
3573
+ "rigid_joints",
3574
+ "float",
3575
+ label="rigid joints",
3576
+ unit="radii",
3577
+ doc="the beams rigid over that many of their radii from each node, the struts "
3578
+ "merged in the joints of a continuum (blank: none; a third brings Timoshenko beams "
3579
+ "within a few per cent of the FFT solver on open foams)",
3580
+ ),
3581
+ Field("young", "float", 1.0, label="Young's modulus of the fibres", unit="stress"),
3582
+ Field("poisson", "float", 0.3, label="Poisson's ratio of the fibres"),
3583
+ Field(
3584
+ "draw",
3585
+ "choice",
3586
+ "force",
3587
+ label="colour of the beams",
3588
+ choices=DRAWINGS,
3589
+ doc="the beams in the cell (a 3D view; in its plane for a planar network) under "
3590
+ "a uniaxial stress: their axial force (red in tension, blue in compression), or "
3591
+ "the share of the energy of the network in their stretching or bending (a log "
3592
+ "scale); the strongest drawn widest",
3593
+ ),
3594
+ Field(
3595
+ "draw_axis",
3596
+ "choice",
3597
+ "x",
3598
+ label="axis of the stress drawn",
3599
+ choices=(("x", "x"), ("y", "y"), ("z", "z")),
3600
+ doc="of the uniaxial stress of the drawing (x or y in a plane)",
3601
+ ),
3602
+ Field(
3603
+ "softening",
3604
+ "choices",
3605
+ [],
3606
+ label="modes of the softening",
3607
+ choices=SOFTENING,
3608
+ doc="Ban et al.: the stiffness of a mode varying from beam to beam with a "
3609
+ "coefficient of variation CV, (E₀ − ⟨E⟩)/E₀ = s CV² and σ_E²/E₀² = v CV², exact "
3610
+ "to second order (one solve per beam and mode)",
3611
+ ),
3612
+ Field(
3613
+ "axis",
3614
+ "choice",
3615
+ "x",
3616
+ label="axis of the softening",
3617
+ choices=(("x", "x"), ("y", "y"), ("z", "z")),
3618
+ doc="of the uniaxial stress whose Young's modulus softens (x or y in a plane)",
3619
+ ),
3620
+ Field(
3621
+ "replicas",
3622
+ "int",
3623
+ 0,
3624
+ label="replicas per CV",
3625
+ doc="replicas of the stiffness of the beams of each mode on the same geometry, "
3626
+ "against the exact coefficients (0: the coefficients alone; one solve each; 40 "
3627
+ "per CV give the softening within a few per cent at CV = 0.1, the first-order "
3628
+ "part of each replica removed as a control variate)",
3629
+ ),
3630
+ Field(
3631
+ "cvs",
3632
+ "floats",
3633
+ [0.1, 0.2, 0.3],
3634
+ label="coefficients of variation",
3635
+ doc="CV of the stiffness of the beams of the replicas, σ/⟨k⟩",
3636
+ ),
3637
+ Field(
3638
+ "distribution",
3639
+ "choice",
3640
+ "normal",
3641
+ label="distribution of the stiffness",
3642
+ choices=DISTRIBUTIONS,
3643
+ ),
3644
+ Field("seed", "int", 1, label="seed of the replicas"),
3645
+ ],
3646
+ order=7,
3647
+ groups=(
3648
+ ("Beams", "beams"),
3649
+ ("Drawing of the frame", "draw"),
3650
+ ("Softening of non-identical beams", "softening", True),
3651
+ ),
3652
+ menu="Linear elasticity",
3653
+ )
3654
+ def network_frame_stiffness(p: dict, ctx) -> dict:
3655
+ from morphogen._utils import to_jsonable
3656
+ from morphogen.homogenization.frames import cowper_coefficient
3657
+ from morphogen.homogenization.networks import (
3658
+ frame_stiffness,
3659
+ network_frame,
3660
+ softening,
3661
+ softening_coefficients,
3662
+ )
3663
+ from morphogen.homogenization.postprocess import notation
3664
+
3665
+ timoshenko = p["beams"] == "timoshenko"
3666
+ kappa = None
3667
+ if timoshenko:
3668
+ kappa = "cowper" if p.get("shear_coefficient") is None else p["shear_coefficient"]
3669
+ young, poisson = float(p["young"]), float(p["poisson"])
3670
+ modes = list(dict.fromkeys(p.get("softening") or []))
3671
+ replicas = int(p.get("replicas") or 0)
3672
+ cvs = [float(c) for c in (p.get("cvs") or [])]
3673
+ if replicas:
3674
+ if not modes:
3675
+ raise ValueError("replicas: of the modes of the softening (choose one at least)")
3676
+ if replicas < 2:
3677
+ raise ValueError("replicas per CV: at least 2 (0: the coefficients alone)")
3678
+ if not cvs or min(cvs) < 0 or (p["distribution"] == "bimodal" and max(cvs) >= 1):
3679
+ raise ValueError("coefficients of variation: non-negative, one at least (below 1 "
3680
+ "for the bimodal law)") # fmt: skip
3681
+ ctx.progress(0.05, "the frame of the framework")
3682
+ frame = network_frame(p["source"]["micro"], young=young, poisson=poisson,
3683
+ shear_coefficient=kappa, rigid_joints=p.get("rigid_joints")) # fmt: skip
3684
+ dim = len(frame.lattice)
3685
+ axis = "xyz".index(p["axis"])
3686
+ if modes and axis >= dim:
3687
+ raise ValueError("axis of the softening: x or y for a plane network")
3688
+ drawn = p.get("draw") or "force"
3689
+ draw_axis = "xyz".index(p.get("draw_axis") or "x")
3690
+ if draw_axis >= dim:
3691
+ raise ValueError("axis of the stress drawn: x or y for a plane network")
3692
+ ctx.progress(0.1, f"the periodic problem of {len(frame.beams)} beams")
3693
+ result = frame_stiffness(frame)
3694
+ rows = result.by_axis()
3695
+ summary = result.summary(young)
3696
+ plane = dim == 2
3697
+ radius = float(np.sqrt(frame.area[0] / np.pi))
3698
+ density = "fibre volume per unit area" if plane else "fibre volume fraction"
3699
+ values: dict = {
3700
+ "E / E_s": summary["frame_young"],
3701
+ "Poisson's ratio": summary["frame_poisson"],
3702
+ "E / E affine": summary["frame_affinity"],
3703
+ "stretching energy": summary["frame_stretching"],
3704
+ "non-affinity": summary["frame_nonaffinity"],
3705
+ density: result.density,
3706
+ "E / (E_s φ)": summary.get("frame_young_per_density"),
3707
+ **result.engineering(),
3708
+ "beams": len(frame.beams),
3709
+ "nodes": len(frame.nodes),
3710
+ "fibre radius": radius,
3711
+ "mean beam length": result.mean_length,
3712
+ }
3713
+ if timoshenko:
3714
+ cowper = kappa == "cowper"
3715
+ values["shear coefficient κ"] = float(cowper_coefficient(poisson) if cowper else kappa)
3716
+ tensor = result.stiffness
3717
+ units = ("units of the modulus of the fibres", "their inverse")
3718
+ if plane:
3719
+ units = ("per unit area: units of the modulus of the fibres times a length",
3720
+ "their inverse") # fmt: skip
3721
+ compliance = elastic_tables(ctx, tensor, "of the frame", units=units)
3722
+ parts = [k for k in ("stretching", "bending", "torsion", "shear") if k in rows[0]]
3723
+ ctx.table(
3724
+ [
3725
+ {
3726
+ "uniaxial stress along": row["axis"],
3727
+ "E": row["young"],
3728
+ "E / E_s": row["young"] / young,
3729
+ "ν (the next axis)": row["poisson"],
3730
+ "E / E affine": row["affinity"],
3731
+ **{f"{k} energy": row[k] for k in parts},
3732
+ "non-affinity": row["nonaffinity"],
3733
+ }
3734
+ for row in rows
3735
+ ],
3736
+ "axes",
3737
+ "uniaxial stresses: the energy split, the affine ratio and the non-affinity",
3738
+ )
3739
+ ctx.figure(_young_figure(tensor), "young_modulus", "directional Young's modulus")
3740
+ stretching = summary["frame_stretching"]
3741
+ kind = "stretching" if stretching >= 0.5 else "bending"
3742
+ joints = ""
3743
+ if p.get("rigid_joints") is not None:
3744
+ joints = f", rigid over {p['rigid_joints']:g} radii at the joints"
3745
+ text = [
3746
+ f"A {'plane ' if plane else ''}frame of {len(frame.beams)} "
3747
+ f"{'Timoshenko' if timoshenko else 'Euler–Bernoulli'} beams of radius {radius:.4g} "
3748
+ f"between {len(frame.nodes)} nodes{joints}: E / E_s = {summary['frame_young']:.4g} on "
3749
+ f"average over the axes, {100 * stretching:.0f} % of the energy of a uniaxial stress in "
3750
+ f"the stretching of the beams ({kind}-dominated), {summary['frame_affinity']:.3g} of "
3751
+ f"the affine estimate, non-affinity {summary['frame_nonaffinity']:.3g}.",
3752
+ ]
3753
+ if plane:
3754
+ text.append("In the plane, the stiffness is per unit area and φ the fibre volume per "
3755
+ "unit area.") # fmt: skip
3756
+ out = {"stiffness": tensor, "compliance": compliance, "notation": notation(tensor),
3757
+ "engineering": result.engineering(), "axes": rows, "summary": summary,
3758
+ "affine": result.affine} # fmt: skip
3759
+ ctx.progress(0.2, "the forces and energies of the beams, the drawing")
3760
+ drawing = _draw_frame(frame, drawn, draw_axis, ctx)
3761
+ values["beams storing half the energy"] = drawing["half"]
3762
+ text.append(drawing["text"])
3763
+ out["drawing"] = {k: v for k, v in drawing.items() if k != "text"}
3764
+ if modes:
3765
+ softened, studies = [], []
3766
+ for k, mode in enumerate(modes):
3767
+ start, span = 0.3 + 0.65 * k / len(modes), 0.65 / len(modes)
3768
+ ctx.progress(start, f"softening: the {mode} of each beam")
3769
+ if replicas:
3770
+
3771
+ def follow(done, total, start=start, span=span, mode=mode):
3772
+ ctx.progress(start + span * (0.1 + 0.9 * done / total),
3773
+ f"replicas of the {mode}: {done} / {total}") # fmt: skip
3774
+
3775
+ study = softening(frame, mode, cvs, replicas=replicas, law=p["distribution"],
3776
+ axis=axis, seed=p["seed"], callback=follow) # fmt: skip
3777
+ studies.append(study)
3778
+ c = study.coefficients
3779
+ else:
3780
+ c = softening_coefficients(frame, mode, axis)
3781
+ softened.append({"mode": mode, "s": c["mean"], "v": c["variance"], "E₀": c["young"]})
3782
+ ctx.table(
3783
+ softened,
3784
+ "softening",
3785
+ f"softening of non-identical beams along {p['axis']}: (E₀ − ⟨E⟩)/E₀ = s CV², "
3786
+ "σ_E²/E₀² = v CV²",
3787
+ )
3788
+ out["softening"] = {"axis": p["axis"], "modes": softened}
3789
+ found = ", ".join(f"s = {r['s']:.3g}, v = {r['v']:.3g} ({r['mode']})" for r in softened)
3790
+ text.append(f"Ban et al.'s softening along {p['axis']}: {found}.")
3791
+ if studies:
3792
+ text.append(_replicas_shown(studies, p, ctx))
3793
+ out["replicas"] = {"distribution": p["distribution"], "replicas": replicas,
3794
+ "seed": p["seed"], "cv": cvs,
3795
+ "rows": [r for s in studies for r in s.rows()]} # fmt: skip
3796
+ ctx.path("frame_stiffness.json").write_text(
3797
+ json.dumps(to_jsonable(out), indent=2) + "\n", encoding="utf-8"
3798
+ )
3799
+ return {"values": values, "text": " ".join(text)}
3800
+
3801
+
3802
+ #: The columns of the table of the replicas: their names in the page, from the keys of
3803
+ #: :meth:`morphogen.homogenization.networks.Softening.rows`
3804
+ REPLICA_COLUMNS = {
3805
+ "mode": "mode",
3806
+ "cv": "CV",
3807
+ "replicas": "replicas",
3808
+ "mean": "⟨E⟩/E₀",
3809
+ "mean_error": "± (σ/√n)",
3810
+ "corrected": "⟨E⟩/E₀ corrected",
3811
+ "corrected_error": "± (corrected)",
3812
+ "theory": "1 − s CV²",
3813
+ "std": "σ_E/E₀",
3814
+ "scatter": "σ_E²/E₀²",
3815
+ "scatter_error": "± (σ_E²/E₀²)",
3816
+ "theory_scatter": "v CV²",
3817
+ }
3818
+
3819
+
3820
+ def _replicas_shown(studies, p: dict, ctx) -> str:
3821
+ """The table and figure of the replicas of Ban et al. (one study per mode) and their
3822
+ sentence."""
3823
+ from morphogen.viz.figures import softening_figure
3824
+
3825
+ rows = [{REPLICA_COLUMNS[k]: r[k] for k in REPLICA_COLUMNS} for s in studies for r in s.rows()]
3826
+ law, n = p["distribution"], studies[0].replicas
3827
+ ctx.table(rows, "replicas", f"replicas of non-identical beams along {p['axis']} ({law} law, "
3828
+ f"{n} per CV, seed {p['seed']}) against the second order") # fmt: skip
3829
+ ctx.figure(
3830
+ softening_figure(studies, title=f"replicas along {p['axis']}: {law} law, {n} per CV"),
3831
+ "replicas",
3832
+ "replicas: the mean and scatter of E against the second order",
3833
+ )
3834
+ parts = []
3835
+ for study in studies:
3836
+ found = ", ".join(f"{1 - c:.4g} ± {e:.1g}" for c, e in zip(study.corrected, study.error,
3837
+ strict=True)) # fmt: skip
3838
+ theory = ", ".join(f"{t:.4g}" for t in study.predicted())
3839
+ parts.append(f"the {study.mode} softens by {found} (s CV² = {theory})")
3840
+ cv = ", ".join(f"{c:g}" for c in studies[0].cv)
3841
+ return (f"Replicas ({law} law, {n} per CV, corrected by the control variate) at CV = {cv}: "
3842
+ f"{'; '.join(parts)}.") # fmt: skip
3843
+
3844
+
3845
+ def _draw_frame(frame, drawn: str, axis: int, ctx) -> dict:
3846
+ """The drawing of the beams of a frame under a uniaxial stress along ``axis``, coloured
3847
+ by :data:`DRAWN` (the figure ``frame``), the share of the beams that store half its
3848
+ energy, the largest tension and compression and its sentence."""
3849
+ from morphogen.homogenization.networks import beam_forces
3850
+ from morphogen.viz.figures import frame_figure
3851
+
3852
+ loads = beam_forces(frame, axis)
3853
+ parts = [k for k in ("stretching", "bending", "torsion", "shear") if k in loads]
3854
+ energy = sum(loads[k] for k in parts)
3855
+ total = float(energy.sum())
3856
+ stored = np.cumsum(np.sort(energy)[::-1]) / total
3857
+ half = float((np.searchsorted(stored, 0.5) + 1) / len(energy))
3858
+ name = "xyz"[axis]
3859
+ scale, label = DRAWN[drawn]
3860
+ if drawn == "force":
3861
+ shown = loads["force"]
3862
+ elif drawn == "stretching":
3863
+ shown = loads["stretching"] / total
3864
+ elif drawn == "bending":
3865
+ shown = sum(loads[k] for k in parts if k != "stretching") / total
3866
+ else:
3867
+ shown = None
3868
+ view = "in its plane" if len(frame.lattice) == 2 else "in the cell"
3869
+ title = f"{len(frame.beams)} beams {view}"
3870
+ caption = "the frame: its beams"
3871
+ if shown is not None:
3872
+ title += f", uniaxial stress along {name}"
3873
+ caption = f"the frame: {dict(DRAWINGS)[drawn]} under a stress along {name}"
3874
+ ctx.figure(frame_figure(frame, shown, scale=scale, label=label.format(axis=name), title=title),
3875
+ "frame", caption) # fmt: skip
3876
+ force = loads["force"]
3877
+ text = (f"Under a uniaxial stress along {name}, {100 * half:.3g} % of the beams store half "
3878
+ f"the energy; axial forces from {force.min():.3g} to {force.max():.3g} for a stress "
3879
+ "of 1.") # fmt: skip
3880
+ return {"axis": name, "colour": drawn, "half": half, "tension": float(force.max()),
3881
+ "compression": float(force.min()), "text": text} # fmt: skip