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,1258 @@
1
+ """Material files of Z-mat (the material library of Z-set: ARMINES, ONERA, Transvalor) read
2
+ into morphoGen's materials, and what of that library morphoGen covers (:data:`COVERAGE`).
3
+
4
+ A material file of Z-mat assembles a behaviour from bricks (Besson, Cailletaud, Chaboche &
5
+ Forest, *Non-linear mechanics of materials*, 2010)::
6
+
7
+ ***behavior gen_evp
8
+ **elasticity isotropic
9
+ young 200000.
10
+ poisson 0.3
11
+ **thermal_strain isotropic
12
+ alpha 1.2e-5
13
+ **potential gen_evp ev
14
+ *criterion mises
15
+ *flow norton
16
+ n 7.
17
+ K 400.
18
+ *kinematic nonlinear
19
+ C 15000.
20
+ D 300.
21
+ *isotropic constant
22
+ R0 130.
23
+ ***return
24
+
25
+ :func:`write_zmat` writes the elastic, von Mises and porous materials of morphoGen as such
26
+ files (a behaviour identified on the response of a morphology, for Z-set).
27
+
28
+ :func:`read_zmat` reads the behaviours ``gen_evp`` and ``reduced_plastic`` (an elasticity,
29
+ a thermal strain, potentials with their criterion, flow, isotropic and kinematic
30
+ hardening), ``porous_plastic`` (porous potentials: a porous criterion, a flow, an isotropic
31
+ hardening, a nucleation; coefficients that depend on the porosity as tables, ``fs = f``;
32
+ the initial porosity from ``*initialize_variable``) and ``linear_elastic``; comments start
33
+ with ``%``. :func:`zmat_material` turns one into a
34
+ :class:`~morphogen.homogenization.materials.Material`:
35
+
36
+ * integrated by morphoGen's own kernels (finite elements, FFT, GPU), as
37
+ :class:`~morphogen.homogenization.behaviours.Plasticity`, when it is one potential with
38
+ the von Mises criterion, a Norton flow or time-independent plasticity, an isotropic
39
+ hardening ``constant``, ``linear``, ``nonlinear``, ``linear_nonlinear`` or
40
+ ``nonlinear_sum`` (three saturating terms at most, without softening) and kinematic
41
+ hardening ``linear`` (Prager) or ``nonlinear`` (Armstrong-Frederick, four at most), on
42
+ an isotropic elasticity (elastic behaviours: any elasticity);
43
+ * ``porous_plastic`` by morphoGen's kernels (on the CPU), as
44
+ :class:`~morphogen.homogenization.porous.PorousPlasticity`: one porous potential with
45
+ the criterion ``gurson`` (``q1``, ``q2``, ``q3 = q1²`` as in Z-mat, the effective
46
+ porosity ``fs``: the porosity, or a table of it, Tvergaard and Needleman's coalescence),
47
+ ``rousselier``, ``modified_rousselier`` or ``elliptic`` (``C``, ``F``: numbers or tables
48
+ of the porosity; Abouaf's compaction), a Norton or rate-independent flow, the isotropic
49
+ hardenings of gen_evp and the nucleation ``constant``, ``gaussian`` or ``exponential``
50
+ (with its threshold ``yield``), the kinematic hardening of gen_evp (``*kinematic linear``
51
+ and ``nonlinear``, four at most) with the criteria ``gurson`` and ``elliptic``, on an
52
+ isotropic elasticity; the modifiers of finite
53
+ strains (``lagrange_rotate_no_J``...) give way to morphoGen's logarithmic strains, chosen
54
+ by the solver;
55
+ * otherwise, as an MFront behaviour (:func:`zmat_mfront_source`, the brick
56
+ ``StandardElastoViscoPlasticity``: Hill's criterion, the flows ``hyperbolic``,
57
+ ``double_norton``, ``norton_exp``, ``strain_hardening`` (as user-defined
58
+ viscoplastic flows), ``power_law`` and tabulated isotropic hardening, softening,
59
+ ``nonlinear_evrad`` (Burlet-Cailletaud), several potentials), written in a cache folder
60
+ and compiled by MFront, integrated by MGIS (:mod:`morphogen.homogenization.mfront`).
61
+
62
+ Conventions: the tensors of Z-set have the components (11, 22, 33, 12, 23, 31), so that the
63
+ coefficients ``hill1`` ... ``hill6`` of its Hill criterion, ``sqrt(3/2 s : M : s)`` with
64
+ ``M`` diagonal on the deviator ``s`` (von Mises when they are all 1), become those of TFEL,
65
+ whose Hill stress is ``F (s11 - s22)^2 + G (s22 - s33)^2 + H (s33 - s11)^2 + 2 L s12^2 + 2 M
66
+ s13^2 + 2 N s23^2`` (not the order of Hill's paper): ``L = 3/2 hill4``, ``M = 3/2 hill6``,
67
+ ``N = 3/2 hill5``, and ``F``, ``G``, ``H`` giving the same normal terms (checked by the yield
68
+ stresses in tension and in each shear); the reference temperature of the thermal strain is
69
+ morphoGen's natural
70
+ state (the loading paths give changes of temperature). Coefficients depending on the
71
+ temperature or other variables, interactions between potentials, damage and the other
72
+ models are not translated: :data:`COVERAGE` lists them with what morphoGen offers instead.
73
+ """
74
+
75
+ from __future__ import annotations
76
+
77
+ import hashlib
78
+ import re
79
+ from dataclasses import dataclass, field
80
+ from pathlib import Path
81
+
82
+ import numpy as np
83
+
84
+ from morphogen._version import __version__
85
+
86
+ #: Behaviours of Z-mat read by :func:`read_zmat`
87
+ BEHAVIOURS = ("gen_evp", "reduced_plastic", "linear_elastic", "porous_plastic")
88
+ #: Options of porous_plastic that change nothing in morphoGen (outputs and numerics)
89
+ _POROUS_HARMLESS = {"no_c_trick", "save_d", "save_l", "bifurcation_d", "bifurcation_l",
90
+ "perturbation", "additional_var_aux"} # fmt: skip
91
+ #: Options of porous_plastic that morphoGen does not translate
92
+ _POROUS_OPTIONS = {"hf", "hp", "broken_behavior", "adiabatic_heating", "coefficient"}
93
+
94
+
95
+ @dataclass
96
+ class ZmatPotential:
97
+ """A potential of a ``gen_evp`` behaviour, or a porous potential of a
98
+ ``porous_plastic`` one: its name and bricks ``(type, coefficients)``: criterion (or
99
+ porous criterion), flow, isotropic and kinematic hardening (lists), and for porous
100
+ potentials the nucleation ``(type, coefficients, crack_like)`` and the shear anisotropy."""
101
+
102
+ name: str
103
+ criterion: tuple = ("mises", {})
104
+ flow: tuple = ("plasticity", {})
105
+ isotropic: list = field(default_factory=list)
106
+ kinematic: list = field(default_factory=list)
107
+ porous: bool = False
108
+ nucleation: tuple | None = None
109
+ shear_anisotropy: tuple | None = None
110
+
111
+
112
+ @dataclass
113
+ class ZmatBehaviour:
114
+ """A behaviour of a material file of Z-mat: its type, elasticity and thermal strain
115
+ ``(type, coefficients)`` and potentials; its modifier (``lagrange_rotate``...), the
116
+ values of ``*initialize_variable`` and the other options (``**name`` -> lines)."""
117
+
118
+ kind: str
119
+ elasticity: tuple
120
+ thermal_strain: tuple | None = None
121
+ potentials: list = field(default_factory=list)
122
+ modifier: str = ""
123
+ initial: dict = field(default_factory=dict)
124
+ options: dict = field(default_factory=dict)
125
+
126
+
127
+ def _number(token: str, where: str) -> float:
128
+ try:
129
+ return float(token.replace("D", "e").replace("d", "e"))
130
+ except ValueError:
131
+ raise ValueError(
132
+ f"zmat: {where}: {token!r} is not a number (coefficients depending on the "
133
+ "temperature, tables and functions are not translated)"
134
+ ) from None
135
+
136
+
137
+ def _coefficients(lines: list[list[str]], where: str) -> dict:
138
+ """``name value`` pairs (several per line allowed)."""
139
+ out: dict = {}
140
+ for tokens in lines:
141
+ if len(tokens) % 2:
142
+ raise ValueError(f"zmat: {where}: coefficients come as 'name value' pairs: {tokens}")
143
+ for name, value in zip(tokens[0::2], tokens[1::2], strict=True):
144
+ out[name] = _number(value, f"{where}.{name}")
145
+ return out
146
+
147
+
148
+ def _is_number(token: str) -> bool:
149
+ try:
150
+ float(token.replace("D", "e").replace("d", "e"))
151
+ except ValueError:
152
+ return False
153
+ return True
154
+
155
+
156
+ def _porous_coefficients(lines: list[list[str]], where: str) -> dict:
157
+ """The coefficients of a brick of a porous potential: ``name value`` pairs, ``name =
158
+ expression`` (kept as ``("=", expression)``) and tables, ``name variable`` followed by
159
+ rows ``value variable_value`` (kept as ``("table", variable, ((x, value)...))``)."""
160
+ out: dict = {}
161
+ k = 0
162
+ while k < len(lines):
163
+ tokens = lines[k]
164
+ text = " ".join(tokens)
165
+ if "=" in text:
166
+ name, _, expression = text.partition("=")
167
+ out[name.strip()] = ("=", expression.strip().rstrip(";").strip())
168
+ k += 1
169
+ continue
170
+ if len(tokens) == 2 and not _is_number(tokens[1]):
171
+ name, variable = tokens
172
+ rows = []
173
+ k += 1
174
+ while k < len(lines) and len(lines[k]) == 2 and all(map(_is_number, lines[k])):
175
+ value, at = (_number(t, f"{where}.{name}") for t in lines[k])
176
+ rows.append((at, value))
177
+ k += 1
178
+ if not rows:
179
+ raise ValueError(f"zmat: {where}: the table of {name} has no rows")
180
+ out[name] = ("table", variable, tuple(sorted(rows)))
181
+ continue
182
+ out.update(_coefficients([tokens], where))
183
+ k += 1
184
+ return out
185
+
186
+
187
+ def read_zmat(source) -> list[ZmatBehaviour]:
188
+ """The behaviours of a material file of Z-mat (a path or its text): see the module."""
189
+ text = (
190
+ Path(source).read_text(encoding="utf-8", errors="replace")
191
+ if (
192
+ isinstance(source, Path)
193
+ or (isinstance(source, str) and "\n" not in source and Path(source).is_file())
194
+ )
195
+ else str(source)
196
+ )
197
+ rows = []
198
+ for raw in text.splitlines():
199
+ line = raw.split("%", 1)[0].strip()
200
+ if line:
201
+ rows.append(line.split())
202
+ out: list[ZmatBehaviour] = []
203
+ behaviour = None
204
+ section = None # (level, keyword, type, name, lines)
205
+ current_potential = None
206
+ initial: dict = {}
207
+ initializing = False
208
+
209
+ def close_section():
210
+ nonlocal section
211
+ if section is None:
212
+ return
213
+ level, key, kind, _, lines = section
214
+ where = f"{'*' * level}{key} {kind}".strip()
215
+ if level == 2 and key == "elasticity":
216
+ behaviour.elasticity = (kind or "isotropic", _coefficients(lines, where))
217
+ elif level == 2 and key == "thermal_strain":
218
+ behaviour.thermal_strain = (kind or "isotropic", _coefficients(lines, where))
219
+ elif level == 2 and key == "option":
220
+ behaviour.options[kind] = lines
221
+ elif level == 1 and current_potential is not None and current_potential.porous:
222
+ coefficients = _porous_coefficients(lines, where)
223
+ if key == "porous_criterion":
224
+ current_potential.criterion = (kind, coefficients)
225
+ elif key == "flow":
226
+ current_potential.flow = (kind or "plasticity", coefficients)
227
+ elif key in ("isotropic_hardening", "isotropic"):
228
+ current_potential.isotropic.append((kind or "constant", coefficients))
229
+ elif key == "kinematic":
230
+ current_potential.kinematic.append((kind, coefficients))
231
+ elif key == "strain_nucleation":
232
+ crack_like = kind.startswith("crack_like")
233
+ current_potential.nucleation = (kind.removeprefix("crack_like").strip(),
234
+ coefficients, crack_like) # fmt: skip
235
+ elif key == "shear_anisotropy":
236
+ current_potential.shear_anisotropy = (kind, coefficients)
237
+ elif level == 1:
238
+ coefficients = _coefficients(lines, where)
239
+ if key == "criterion":
240
+ current_potential.criterion = (kind or "mises", coefficients)
241
+ elif key == "flow":
242
+ current_potential.flow = (kind or "plasticity", coefficients)
243
+ elif key == "isotropic":
244
+ current_potential.isotropic.append((kind or "constant", coefficients))
245
+ elif key == "kinematic":
246
+ current_potential.kinematic.append((kind or "nonlinear", coefficients))
247
+ elif lines:
248
+ raise ValueError(f"zmat: unexpected coefficients after {where}: {lines[0]}")
249
+ section = None
250
+
251
+ for tokens in rows:
252
+ head = tokens[0]
253
+ if head.lower() in ("*initialize_variable", "***initialize_variable"):
254
+ initializing = True
255
+ tokens = tokens[1:]
256
+ if not tokens:
257
+ continue
258
+ head = tokens[0]
259
+ if initializing:
260
+ if head.startswith("*"):
261
+ initializing = False
262
+ else:
263
+ initial.update(_coefficients([tokens], "*initialize_variable"))
264
+ continue
265
+ if head.startswith("***"):
266
+ close_section()
267
+ key = head[3:].lower()
268
+ if key == "behavior" or key == "behaviour":
269
+ kind = "_".join(tokens[1:2]).lower()
270
+ if kind not in BEHAVIOURS:
271
+ raise ValueError(f"zmat: behaviour {kind!r}: one of {list(BEHAVIOURS)}")
272
+ behaviour = ZmatBehaviour(kind, ("isotropic", {}))
273
+ behaviour.modifier = tokens[2].lower() if len(tokens) > 2 else ""
274
+ current_potential = None
275
+ elif key == "return":
276
+ if behaviour is not None:
277
+ out.append(behaviour)
278
+ behaviour = None
279
+ continue # ***material and the other commands of the file
280
+ if behaviour is None:
281
+ continue
282
+ if head.startswith("**") and not head.startswith("***"):
283
+ close_section()
284
+ key = head[2:].lower()
285
+ kind = tokens[1].lower() if len(tokens) > 1 else ""
286
+ if key == "potential":
287
+ if kind not in ("gen_evp", "gen_evp2", ""):
288
+ raise ValueError(f"zmat: potential {kind!r}: only gen_evp potentials")
289
+ name = tokens[2] if len(tokens) > 2 else f"p{len(behaviour.potentials) + 1}"
290
+ current_potential = ZmatPotential(name)
291
+ behaviour.potentials.append(current_potential)
292
+ section = (2, key, kind, name, [])
293
+ elif key == "porous_potential" and behaviour.kind == "porous_plastic":
294
+ name = tokens[1] if len(tokens) > 1 else f"p{len(behaviour.potentials) + 1}"
295
+ current_potential = ZmatPotential(name, criterion=("", {}), porous=True)
296
+ behaviour.potentials.append(current_potential)
297
+ section = (2, key, "", name, [])
298
+ elif behaviour.kind == "porous_plastic" and key.lower() in (
299
+ _POROUS_HARMLESS | _POROUS_OPTIONS
300
+ ):
301
+ current_potential = None
302
+ section = (2, "option", key.lower(), "", [tokens[1:]] if len(tokens) > 1 else [])
303
+ elif key in ("elasticity", "thermal_strain"):
304
+ section = (2, key, kind, "", [])
305
+ elif key in ("global_output", "verbose"):
306
+ section = (2, key, kind, "", [])
307
+ else:
308
+ raise ValueError(
309
+ f"zmat: **{key} is not translated (elasticity, thermal_strain and "
310
+ "potentials only: interactions, damage, localization... are not)"
311
+ )
312
+ continue
313
+ if head.startswith("*"):
314
+ close_section()
315
+ key = head[1:].lower()
316
+ if key in ("integration", "initialize_variable"):
317
+ section = None # options of the integration of Z-set: skipped
318
+ continue
319
+ porous = current_potential is not None and current_potential.porous
320
+ bricks = (
321
+ ("porous_criterion", "flow", "isotropic_hardening", "isotropic", "kinematic",
322
+ "strain_nucleation", "shear_anisotropy")
323
+ if porous
324
+ else ("criterion", "flow", "isotropic", "kinematic")
325
+ ) # fmt: skip
326
+ if current_potential is None or key not in bricks:
327
+ raise ValueError(f"zmat: *{key} outside a potential or not translated")
328
+ kind = tokens[1].lower() if len(tokens) > 1 else ""
329
+ extra = tokens[2:]
330
+ lines = []
331
+ if porous:
332
+ if key == "strain_nucleation" and kind == "crack_like" and extra:
333
+ kind, extra = f"crack_like {extra[0].lower()}", extra[1:]
334
+ # coefficients on the line of the brick (``*flow norton K .01 n 5.``)
335
+ if len(extra) >= 2 and len(extra) % 2 == 0 and all(map(_is_number, extra[1::2])):
336
+ lines.append(extra)
337
+ section = (1, key, kind, "", lines)
338
+ continue
339
+ if section is not None:
340
+ section[4].append(tokens)
341
+ close_section()
342
+ if behaviour is not None:
343
+ out.append(behaviour)
344
+ if not out:
345
+ raise ValueError("zmat: no ***behavior in the file")
346
+ for b in out:
347
+ b.initial = dict(initial)
348
+ return out
349
+
350
+
351
+ # -- translation -------------------------------------------------------------------------
352
+
353
+
354
+ def _get(coefficients: dict, where: str, *names, default=None):
355
+ """The first of ``names`` among the coefficients (aliases), or the default."""
356
+ for name in names:
357
+ if name in coefficients:
358
+ return coefficients[name]
359
+ if default is None:
360
+ raise ValueError(f"zmat: {where}: missing coefficient {names[0]}")
361
+ return default
362
+
363
+
364
+ def _check_known(coefficients: dict, where: str, known: set) -> None:
365
+ unknown = sorted(set(coefficients) - known)
366
+ if unknown:
367
+ raise ValueError(f"zmat: {where}: unknown coefficients {unknown}; known: {sorted(known)}")
368
+
369
+
370
+ def _elastic_material_kwargs(behaviour: ZmatBehaviour) -> dict:
371
+ """The elastic part of a material: ``young``/``poisson``, or a stiffness."""
372
+ kind, c = behaviour.elasticity
373
+ where = f"**elasticity {kind}"
374
+ if kind == "isotropic":
375
+ _check_known(c, where, {"young", "poisson", "E", "nu"})
376
+ return {"young": _get(c, where, "young", "E"), "poisson": _get(c, where, "poisson", "nu")}
377
+ if kind == "cubic":
378
+ _check_known(c, where, {"y1111", "y1122", "y1212", "c11", "c12", "c44"})
379
+ values = (
380
+ _get(c, where, "y1111", "c11"),
381
+ _get(c, where, "y1122", "c12"),
382
+ _get(c, where, "y1212", "c44"),
383
+ )
384
+ return {"cubic": values}
385
+ if kind in ("orthotropic", "transverse", "anisotropic"):
386
+ return {"stiffness": _stiffness(kind, c, where)}
387
+ raise ValueError(f"zmat: {where}: isotropic, cubic, orthotropic, transverse or anisotropic")
388
+
389
+
390
+ def _stiffness(kind: str, c: dict, where: str) -> np.ndarray:
391
+ """The 6 x 6 stiffness (Voigt order 11, 22, 33, 23, 31, 12) of an anisotropic
392
+ elasticity of Z-mat (``y<ijkl>`` coefficients, or the engineering constants of a
393
+ transversely isotropic material, its axis 1)."""
394
+ if kind == "transverse":
395
+ _check_known(c, where, {"El", "Et", "Glt", "nult", "nutt"})
396
+ el, et, glt = c["El"], c["Et"], c["Glt"]
397
+ nult, nutt = c["nult"], c["nutt"]
398
+ s = np.zeros((6, 6))
399
+ s[0, 0], s[1, 1], s[2, 2] = 1 / el, 1 / et, 1 / et
400
+ s[0, 1] = s[1, 0] = s[0, 2] = s[2, 0] = -nult / el
401
+ s[1, 2] = s[2, 1] = -nutt / et
402
+ s[3, 3] = 2 * (1 + nutt) / et # the plane 23 is isotropic
403
+ s[4, 4] = s[5, 5] = 1 / glt
404
+ return np.linalg.inv(s)
405
+ index = {"11": 0, "22": 1, "33": 2, "23": 3, "32": 3, "31": 4, "13": 4, "12": 5, "21": 5}
406
+ out = np.zeros((6, 6))
407
+ for name, value in c.items():
408
+ m = re.fullmatch(r"y(\d\d)(\d\d)", name)
409
+ if m is None or m.group(1) not in index or m.group(2) not in index:
410
+ raise ValueError(
411
+ f"zmat: {where}: coefficient {name!r}: give the components y1111, y1122... "
412
+ "(the numbering c44, c55, c66 depends on the order of the components)"
413
+ )
414
+ i, j = index[m.group(1)], index[m.group(2)]
415
+ out[i, j] = out[j, i] = value
416
+ if kind == "orthotropic" and np.count_nonzero(out[:3, 3:]) + np.count_nonzero(
417
+ out[3:, 3:] - np.diag(np.diag(out[3:, 3:]))
418
+ ):
419
+ raise ValueError(f"zmat: {where}: an orthotropic stiffness couples no shear")
420
+ return out
421
+
422
+
423
+ def _native(behaviour: ZmatBehaviour):
424
+ """The :class:`Plasticity` of a behaviour that morphoGen's kernels integrate, or
425
+ ``None`` (with the reason) when it needs MFront."""
426
+ from morphogen.homogenization.behaviours import MAX_ISOTROPIC, MAX_KINEMATIC, Plasticity
427
+
428
+ if len(behaviour.potentials) != 1:
429
+ return None, "several potentials"
430
+ if behaviour.elasticity[0] != "isotropic":
431
+ return None, "anisotropic elasticity"
432
+ p = behaviour.potentials[0]
433
+ if p.criterion[0] not in ("mises", "hill"):
434
+ return None, f"criterion {p.criterion[0]}"
435
+ hill = None
436
+ if p.criterion[0] == "hill":
437
+ c = p.criterion[1]
438
+ if any(isinstance(v, tuple) for v in c.values()):
439
+ return None, "coefficients of Hill's criterion depending on variables"
440
+ # Z-set's hill1 ... hill6: the components 11, 22, 33, 12, 23, 31, morphoGen's order
441
+ hill = tuple(_get(c, "*criterion hill", f"hill{i}", default=1.0) for i in range(1, 7))
442
+ flow = _flow(p)
443
+ if isinstance(flow, str):
444
+ return None, flow
445
+ k, n = flow
446
+ hardening = _isotropic_hardening(p, MAX_ISOTROPIC)
447
+ if isinstance(hardening, str):
448
+ return None, hardening
449
+ r0, h, terms = hardening
450
+ kinematic = []
451
+ for kind, c in p.kinematic:
452
+ where = f"*kinematic {kind}"
453
+ if kind == "linear":
454
+ kinematic.append((_get(c, where, "C"), 0.0))
455
+ elif kind == "nonlinear":
456
+ kinematic.append((_get(c, where, "C"), _get(c, where, "D")))
457
+ else:
458
+ return None, f"kinematic hardening {kind}"
459
+ if len(kinematic) > MAX_KINEMATIC:
460
+ return None, "more than four kinematic terms"
461
+ return (
462
+ Plasticity(r0, h, tuple(terms), tuple(kinematic), viscosity=k, exponent=n, hill=hill),
463
+ "",
464
+ )
465
+
466
+
467
+ def _flow(p: ZmatPotential):
468
+ """``(K, n)`` of a Norton flow, ``(None, None)`` for plasticity, or the reason why the
469
+ flow is not native."""
470
+ flow, fc = p.flow
471
+ if flow == "plasticity":
472
+ return None, None
473
+ if flow == "norton":
474
+ if any(isinstance(v, tuple) for v in fc.values()):
475
+ return "coefficients of the flow depending on variables"
476
+ k, n = _get(fc, "*flow norton", "K"), _get(fc, "*flow norton", "n")
477
+ return (k, n) if n >= 1.0 else "a Norton exponent below 1"
478
+ return f"flow {flow}"
479
+
480
+
481
+ def _isotropic_hardening(p: ZmatPotential, most: int):
482
+ """``(R0, H, ((Q, b)...))`` of the isotropic hardening of a potential, or the reason
483
+ why it is not native."""
484
+ r0, h, terms = 0.0, 0.0, []
485
+ if len(p.isotropic) > 1:
486
+ return "several isotropic hardenings"
487
+ for kind, c in p.isotropic:
488
+ where = f"*isotropic {kind}"
489
+ if any(isinstance(v, tuple) for v in c.values()):
490
+ return "coefficients of the hardening depending on variables"
491
+ if kind == "constant":
492
+ r0 = _get(c, where, "R0")
493
+ elif kind in ("linear", "iso_linear"):
494
+ r0, h = _get(c, where, "R0"), _get(c, where, "H")
495
+ elif kind == "nonlinear":
496
+ r0 = _get(c, where, "R0")
497
+ terms = [(_get(c, where, "Q"), _get(c, where, "b"))]
498
+ elif kind == "linear_nonlinear":
499
+ r0, h = _get(c, where, "R0"), _get(c, where, "H")
500
+ terms = [(_get(c, where, "Q"), _get(c, where, "b"))]
501
+ elif kind in ("nonlinear_sum", "nonlinear_double"):
502
+ r0 = _get(c, where, "R0")
503
+ k_terms = sorted(int(m.group(1)) for name in c if (m := re.fullmatch(r"Q(\d+)", name)))
504
+ terms = [(c[f"Q{i}"], _get(c, where, f"b{i}")) for i in k_terms]
505
+ else:
506
+ return f"isotropic hardening {kind}"
507
+ if len(terms) > most or any(q < 0 for q, _ in terms) or h < 0:
508
+ return "softening or more than three saturating terms"
509
+ return r0, h, tuple(terms)
510
+
511
+
512
+ def _porosity_table(value, where: str, name: str):
513
+ """A coefficient of a porous criterion: a number, or a table of the porosity (``f``,
514
+ ``ft``, ``fg``) as pairs ``(f, value)``."""
515
+ from morphogen.homogenization.porous import MAX_TABLE
516
+
517
+ if not isinstance(value, tuple):
518
+ return float(value)
519
+ if value[0] == "table" and value[1].lower() in ("f", "ft", "fg"):
520
+ if len(value[2]) > MAX_TABLE:
521
+ raise ValueError(f"zmat: {where}: {name}: a table of {MAX_TABLE} points at most")
522
+ return [list(pair) for pair in value[2]]
523
+ raise ValueError(
524
+ f"zmat: {where}: {name} depends on {value[1]!r}: numbers, or tables of the porosity "
525
+ f"({_see_coverage()})"
526
+ )
527
+
528
+
529
+ def _native_porous(behaviour: ZmatBehaviour, porosity: float | None = None):
530
+ """The :class:`~morphogen.homogenization.porous.PorousPlasticity` of a
531
+ ``porous_plastic`` behaviour (see the module) and the notes of its translation."""
532
+ from morphogen.homogenization.porous import MAX_ISOTROPIC, PorousPlasticity
533
+
534
+ notes = []
535
+ if behaviour.elasticity[0] != "isotropic":
536
+ raise ValueError("zmat: porous_plastic: an isotropic elasticity (morphoGen's kernels)")
537
+ if len(behaviour.potentials) != 1:
538
+ raise ValueError(f"zmat: porous_plastic: one porous potential ({_see_coverage()})")
539
+ for option in behaviour.options:
540
+ if option in _POROUS_OPTIONS:
541
+ raise ValueError(
542
+ f"zmat: porous_plastic: **{option} is not translated ({_see_coverage()})"
543
+ )
544
+ if behaviour.modifier:
545
+ notes.append(
546
+ f"modifier {behaviour.modifier}: morphoGen's solvers choose small or finite strains "
547
+ "(logarithmic strains)"
548
+ )
549
+ p = behaviour.potentials[0]
550
+ kinematic = _porous_kinematic(p)
551
+ if p.shear_anisotropy is not None and p.shear_anisotropy[0] not in ("mises", ""):
552
+ raise ValueError(
553
+ f"zmat: porous_plastic: *shear_anisotropy {p.shear_anisotropy[0]}: mises only "
554
+ f"({_see_coverage()})"
555
+ )
556
+ flow = _flow(p)
557
+ if isinstance(flow, str):
558
+ raise ValueError(f"zmat: porous_plastic: {flow} ({_see_coverage()})")
559
+ hardening = _isotropic_hardening(p, MAX_ISOTROPIC)
560
+ if isinstance(hardening, str):
561
+ raise ValueError(f"zmat: porous_plastic: {hardening} ({_see_coverage()})")
562
+ r0, h, terms = hardening
563
+ kind, c = p.criterion
564
+ where = f"*porous_criterion {kind}"
565
+ kwargs: dict = {}
566
+ if kind == "gurson":
567
+ _check_known(c, where, {"q1", "q2", "fs"})
568
+ kwargs = {"q1": _get(c, where, "q1", default=1.5), "q2": _get(c, where, "q2", default=1.0)}
569
+ fs = c.get("fs")
570
+ if isinstance(fs, tuple) and fs[0] == "=":
571
+ if fs[1].lower() not in ("f", "ft", "fg"):
572
+ raise ValueError(f"zmat: {where}: fs = {fs[1]}: the porosity, or a table of it")
573
+ elif fs is not None:
574
+ table = _porosity_table(fs, where, "fs")
575
+ kwargs["effective"] = [[0.0, table]] if isinstance(table, float) else table
576
+ criterion = "gurson"
577
+ elif kind in ("rousselier", "modified_rousselier"):
578
+ known = {"sigma1", "D", "q2"} if kind == "modified_rousselier" else {"sigma1", "D"}
579
+ _check_known(c, where, known)
580
+ kwargs = {"sigma1": _get(c, where, "sigma1"), "D": _get(c, where, "D")}
581
+ if kind == "modified_rousselier":
582
+ kwargs["q2"] = _get(c, where, "q2")
583
+ criterion = "rousselier"
584
+ elif kind == "elliptic":
585
+ _check_known(c, where, {"C", "F"})
586
+ kwargs = {name: _porosity_table(c[name], where, name) for name in ("C", "F") if name in c}
587
+ criterion = "elliptic"
588
+ else:
589
+ raise ValueError(f"zmat: porous criterion {kind!r} is not translated ({_see_coverage()})")
590
+ nucleation = None
591
+ if p.nucleation is not None:
592
+ nkind, nc, crack_like = p.nucleation
593
+ nwhere = f"*strain_nucleation {nkind}"
594
+ if crack_like or "porosity_yield" in nc:
595
+ raise ValueError(f"zmat: {nwhere}: crack_like and porosity_yield are not translated")
596
+ if any(isinstance(v, tuple) for v in nc.values()):
597
+ raise ValueError(f"zmat: {nwhere}: numbers only")
598
+ names = {"constant": {"A": "A"}, "gaussian": {"fn": "fN", "en": "eN", "sn": "sN"},
599
+ "exponential": {"B": "B", "e0": "e0"}} # fmt: skip
600
+ if nkind not in names:
601
+ raise ValueError(f"zmat: {nwhere}: constant, gaussian or exponential")
602
+ _check_known(nc, nwhere, set(names[nkind]) | {"yield"})
603
+ nucleation = {"type": nkind, "yield": nc.get("yield", 0.0)}
604
+ nucleation.update({ours: _get(nc, nwhere, zmat) for zmat, ours in names[nkind].items()})
605
+ if porosity is None:
606
+ found = [behaviour.initial[k] for k in ("f", "ft", "fg", "f0") if k in behaviour.initial]
607
+ porosity = found[0] if found else 0.0
608
+ if not found:
609
+ notes.append("initial porosity 0 (*initialize_variable f, or the option porosity)")
610
+ pp = PorousPlasticity(
611
+ criterion,
612
+ r0,
613
+ porosity=porosity,
614
+ hardening=h,
615
+ isotropic=terms,
616
+ viscosity=flow[0],
617
+ exponent=flow[1],
618
+ nucleation=nucleation,
619
+ kinematic=kinematic,
620
+ **kwargs,
621
+ )
622
+ return pp, notes
623
+
624
+
625
+ def _porous_kinematic(p: ZmatPotential) -> tuple:
626
+ """The kinematic terms ``(C, D)`` of a porous potential, with the bricks of gen_evp:
627
+ ``*kinematic linear`` (``C``: Prager) and ``nonlinear`` (``C``, ``D``: Armstrong-Frederick;
628
+ the type by default), numbers, four at most."""
629
+ from morphogen.homogenization.porous import MAX_KINEMATIC
630
+
631
+ out = []
632
+ for kind, c in p.kinematic:
633
+ kind = kind or "nonlinear"
634
+ where = f"*kinematic {kind}"
635
+ if kind not in ("linear", "nonlinear"):
636
+ raise ValueError(
637
+ f"zmat: porous_plastic: kinematic hardening {kind!r} is not translated "
638
+ f"({_see_coverage()})"
639
+ )
640
+ if any(isinstance(v, tuple) for v in c.values()):
641
+ raise ValueError(f"zmat: porous_plastic: {where}: numbers only")
642
+ _check_known(c, where, {"C"} if kind == "linear" else {"C", "D"})
643
+ out.append((_get(c, where, "C"), _get(c, where, "D") if kind == "nonlinear" else 0.0))
644
+ if len(out) > MAX_KINEMATIC:
645
+ raise ValueError(f"zmat: porous_plastic: {MAX_KINEMATIC} kinematic terms at most")
646
+ return tuple(out)
647
+
648
+
649
+ def _real(value: float) -> str:
650
+ return repr(float(value))
651
+
652
+
653
+ def _hill(c: dict) -> dict:
654
+ """TFEL's Hill coefficients (``F (s11 - s22)^2 + G (s22 - s33)^2 + H (s33 - s11)^2 + 2 L
655
+ s12^2 + 2 M s13^2 + 2 N s23^2``) of Z-mat's ``hill1`` ... ``hill6`` (on the deviator,
656
+ components 11, 22, 33, 12, 23, 31)."""
657
+ h = [_get(c, "*criterion hill", f"hill{i}", default=1.0) for i in range(1, 7)]
658
+ # a (s22 - s33)^2 + b (s33 - s11)^2 + c (s11 - s22)^2 = 3/2 (h1 s11^2 + h2 s22^2 + h3
659
+ # s33^2) for the deviators (s33 = -s11 - s22): three equations
660
+ m = np.array([[1.0, 4.0, 1.0], [4.0, 1.0, 1.0], [4.0, 4.0, -2.0]])
661
+ rhs = np.array([1.5 * (h[0] + h[2]), 1.5 * (h[1] + h[2]), 3.0 * h[2]])
662
+ a, b, c = np.linalg.solve(m, rhs)
663
+ return {"F": c, "G": a, "H": b, "L": 1.5 * h[3], "M": 1.5 * h[5], "N": 1.5 * h[4]}
664
+
665
+
666
+ def _brick_terms(items: dict) -> str:
667
+ return ", ".join(f"{k} : {_real(v) if not isinstance(v, str) else v}" for k, v in items.items())
668
+
669
+
670
+ def _flow_lines(potential: ZmatPotential, index: int) -> tuple[list[str], str]:
671
+ """The ``inelastic_flow`` entry of a potential and the name of its equivalent strain."""
672
+ kind, c = potential.criterion
673
+ if kind == "mises":
674
+ criterion = '"Mises"'
675
+ elif kind == "hill":
676
+ criterion = f'"Hill" {{{_brick_terms(_hill(c))}}}'
677
+ else:
678
+ raise ValueError(f"zmat: criterion {kind!r}: mises or hill ({_see_coverage()})")
679
+ flow, fc = potential.flow
680
+ where = f"*flow {flow}"
681
+ extra: dict = {}
682
+ if flow == "plasticity":
683
+ name, strain = '"Plastic"', "EquivalentPlasticStrain"
684
+ elif flow == "norton":
685
+ name, strain = '"Norton"', "EquivalentViscoplasticStrain"
686
+ extra = {"K": _get(fc, where, "K"), "n": _get(fc, where, "n")}
687
+ else:
688
+ # the coefficients of the user-defined flows of the brick are renamed (MFront
689
+ # reserves n, among others) and must all appear in the expression
690
+ expressions = {
691
+ "hyperbolic": (
692
+ "zA * sinh((f / zK) ** zN) ** zM",
693
+ {"zA": ("eps0", 1.0), "zK": ("K", None), "zN": ("n", 1.0), "zM": ("m", 1.0)},
694
+ ),
695
+ "double_norton": (
696
+ "(f / zK) ** zN + (f / zK2) ** zN2",
697
+ {"zK": ("K", None), "zN": ("n1", None), "zK2": ("K2", None), "zN2": ("n2", None)},
698
+ ),
699
+ "norton_exp": (
700
+ "(f / zK) ** zN * exp(zA * (f / zK) ** (zN + 1))",
701
+ {"zK": ("K", None), "zN": ("n", None), "zA": ("alpha", None)},
702
+ ),
703
+ "strain_hardening": (
704
+ "(f / zK) ** zN * (p + zV) ** zM",
705
+ {"zK": ("K", None), "zN": ("n", None), "zM": ("m", None), "zV": ("v0", None)},
706
+ ),
707
+ }
708
+ if flow not in expressions:
709
+ raise ValueError(f"zmat: flow {flow!r} is not translated ({_see_coverage()})")
710
+ expression, names = expressions[flow]
711
+ _check_known(fc, where, {zmat for zmat, _ in names.values()} | {"cutoff"})
712
+ for key, (zmat, default) in names.items():
713
+ extra[key] = _get(fc, where, zmat, default=default)
714
+ extra["vp"] = f'"{expression}"'
715
+ name, strain = '"UserDefinedViscoplasticity"', "EquivalentViscoplasticStrain"
716
+ lines = [f" inelastic_flow : {name} {{", f" criterion : {criterion},"]
717
+ for kind, c in potential.isotropic or [("constant", {"R0": 0.0})]:
718
+ lines += [f" isotropic_hardening : {term}," for term in _isotropic_terms(kind, c)]
719
+ for kind, c in potential.kinematic:
720
+ lines.append(f" kinematic_hardening : {_kinematic_term(kind, c)},")
721
+ for key, value in extra.items():
722
+ lines.append(f" {key} : {value if isinstance(value, str) else _real(value)},")
723
+ lines[-1] = lines[-1].rstrip(",")
724
+ lines.append(" },")
725
+ return lines, strain
726
+
727
+
728
+ def _isotropic_terms(kind: str, c: dict) -> list[str]:
729
+ where = f"*isotropic {kind}"
730
+ r0 = _get(c, where, "R0", default=0.0)
731
+ linear = f'"Linear" {{R0 : {_real(r0)}, H : {_real(c.get("H", 0.0))}}}'
732
+ voce = '"Voce" {{R0 : 0, Rinf : {}, b : {}}}'
733
+ if kind == "constant":
734
+ return [f'"Linear" {{R0 : {_real(r0)}, H : 0}}']
735
+ if kind in ("linear", "iso_linear"):
736
+ return [linear]
737
+ if kind in ("nonlinear", "linear_nonlinear"):
738
+ return [linear, voce.format(_real(_get(c, where, "Q")), _real(_get(c, where, "b")))]
739
+ if kind in ("nonlinear_sum", "nonlinear_double"):
740
+ ids = sorted(int(m.group(1)) for name in c if (m := re.fullmatch(r"Q(\d+)", name)))
741
+ return [linear] + [
742
+ voce.format(_real(c[f"Q{i}"]), _real(_get(c, where, f"b{i}"))) for i in ids
743
+ ]
744
+ if kind == "power_law":
745
+ k, e0, n = (_get(c, where, x) for x in ("K", "e0", "n"))
746
+ return [
747
+ f'"UserDefined" {{R : "zR + zK * (p + zE) ** zN", zR : {_real(r0)}, '
748
+ f"zK : {_real(k)}, zE : {_real(max(e0, 0.0))}, zN : {_real(n)}}}"
749
+ ]
750
+ raise ValueError(f"zmat: isotropic hardening {kind!r} is not translated ({_see_coverage()})")
751
+
752
+
753
+ def _kinematic_term(kind: str, c: dict) -> str:
754
+ where = f"*kinematic {kind}"
755
+ if kind == "linear":
756
+ return f'"Prager" {{C : {_real(_get(c, where, "C"))}}}'
757
+ if kind == "nonlinear":
758
+ return (
759
+ f'"Armstrong-Frederick" {{C : {_real(_get(c, where, "C"))}, '
760
+ f"D : {_real(_get(c, where, 'D'))}}}"
761
+ )
762
+ if kind == "nonlinear_evrad":
763
+ return (
764
+ f'"Burlet-Cailletaud" {{C : {_real(_get(c, where, "C"))}, '
765
+ f"D : {_real(_get(c, where, 'D'))}, eta : {_real(_get(c, where, 'eta'))}}}"
766
+ )
767
+ raise ValueError(f"zmat: kinematic hardening {kind!r} is not translated ({_see_coverage()})")
768
+
769
+
770
+ def _see_coverage() -> str:
771
+ return "see morphogen.homogenization.zmat.COVERAGE"
772
+
773
+
774
+ def zmat_mfront_source(behaviour: ZmatBehaviour, name: str = "ZmatBehaviour") -> str:
775
+ """The MFront source of a ``gen_evp`` behaviour (the brick
776
+ ``StandardElastoViscoPlasticity``, one inelastic flow per potential; see the
777
+ module)."""
778
+ if behaviour.elasticity[0] != "isotropic":
779
+ raise ValueError("zmat: the plastic behaviours of MFront's brick need isotropic elasticity")
780
+ el = _elastic_material_kwargs(behaviour)
781
+ hooke = {"young_modulus": el["young"], "poisson_ratio": el["poisson"]}
782
+ if behaviour.thermal_strain is not None:
783
+ kind, c = behaviour.thermal_strain
784
+ if kind != "isotropic":
785
+ raise ValueError("zmat: **thermal_strain isotropic only")
786
+ hooke["thermal_expansion"] = _get(c, "**thermal_strain", "alpha")
787
+ hooke["thermal_expansion_reference_temperature"] = 293.15 # the natural state
788
+ lines = [
789
+ "@DSL Implicit;",
790
+ f"@Behaviour {name};",
791
+ "@Author morphoGen;",
792
+ "@Description {",
793
+ f' "morphoGen {__version__}: a gen_evp behaviour of Z-mat, '
794
+ f'{len(behaviour.potentials)} potential(s), with the brick StandardElastoViscoPlasticity."',
795
+ "}",
796
+ "@Algorithm NewtonRaphson;",
797
+ "@Epsilon 1.e-14;",
798
+ "@Theta 1;",
799
+ ]
800
+ if any(p.criterion[0] == "hill" for p in behaviour.potentials):
801
+ # Hill's criterion is written in the axes of the material (those of the sample,
802
+ # or of the grain of a crystal): an orthotropic behaviour for MFront
803
+ lines.append("@OrthotropicBehaviour;")
804
+ lines += [
805
+ "@Brick StandardElastoViscoPlasticity{",
806
+ f' stress_potential : "Hooke" {{{_brick_terms(hooke)}}},',
807
+ ]
808
+ for k, potential in enumerate(behaviour.potentials):
809
+ flow, _ = _flow_lines(potential, k)
810
+ lines += flow
811
+ lines[-1] = lines[-1].rstrip(",")
812
+ lines.append("};")
813
+ return "\n".join(lines) + "\n"
814
+
815
+
816
+ def _equivalent_strain(behaviour: ZmatBehaviour) -> str:
817
+ first = behaviour.potentials[0]
818
+ base = (
819
+ "EquivalentPlasticStrain"
820
+ if first.flow[0] == "plasticity"
821
+ else ("EquivalentViscoplasticStrain")
822
+ )
823
+ return base + ("0" if len(behaviour.potentials) > 1 else "")
824
+
825
+
826
+ def zmat_material(
827
+ source,
828
+ *,
829
+ name: str | None = None,
830
+ directory=None,
831
+ behaviour: int = 0,
832
+ native: bool = True,
833
+ porosity: float | None = None,
834
+ ):
835
+ """The :class:`~morphogen.homogenization.materials.Material` of the behaviour
836
+ ``behaviour`` of a material file of Z-mat (path or text): morphoGen's kernels when they
837
+ integrate it (unless ``native`` is false: MFront for all plastic behaviours, e.g. for
838
+ the exports to other codes), otherwise an MFront behaviour whose source is written in
839
+ ``directory`` (by default ``~/.cache/morphogen/zmat``) under the name ``name`` (by
840
+ default the stem of the file); see the module. ``porosity``: the initial porosity of a
841
+ ``porous_plastic`` behaviour (by default that of its ``*initialize_variable``)."""
842
+ from morphogen.homogenization.materials import Material
843
+ from morphogen.homogenization.mfront import MFrontBehaviour
844
+
845
+ behaviours = read_zmat(source)
846
+ if not 0 <= behaviour < len(behaviours):
847
+ raise ValueError(f"zmat: behaviour {behaviour}: the file has {len(behaviours)}")
848
+ b = behaviours[behaviour]
849
+ kwargs = _elastic_material_kwargs(b)
850
+ expansion = None
851
+ if b.thermal_strain is not None:
852
+ kind, c = b.thermal_strain
853
+ if kind != "isotropic":
854
+ raise ValueError("zmat: **thermal_strain isotropic only")
855
+ expansion = _get(c, "**thermal_strain", "alpha")
856
+ base = Material.from_config(kwargs)
857
+ if expansion is not None:
858
+ import dataclasses
859
+
860
+ base = dataclasses.replace(base, expansion=expansion)
861
+ if not b.potentials:
862
+ return base
863
+ import dataclasses
864
+
865
+ if b.kind == "porous_plastic":
866
+ if not native:
867
+ raise ValueError("zmat: porous_plastic is translated for morphoGen's kernels only")
868
+ porous, _ = _native_porous(b, porosity)
869
+ return dataclasses.replace(base, porous_plasticity=porous)
870
+ plasticity, _ = _native(b)
871
+ if plasticity is not None and native:
872
+ return dataclasses.replace(base, plasticity=plasticity)
873
+ stem = mfront_name(name or (Path(source).stem if _is_file(source) else "ZmatBehaviour"))
874
+ text = zmat_mfront_source(b, stem)
875
+ key = hashlib.sha256(text.encode("utf-8")).hexdigest()[:16]
876
+ folder = Path(directory) if directory else Path.home() / ".cache" / "morphogen" / "zmat"
877
+ folder = folder / key
878
+ folder.mkdir(parents=True, exist_ok=True)
879
+ path = folder / f"{stem}.mfront"
880
+ path.write_text(text, encoding="utf-8")
881
+ behaviour_spec = MFrontBehaviour(
882
+ source=str(path), behaviour=stem, plastic_strain=_equivalent_strain(b)
883
+ )
884
+ return dataclasses.replace(base, mfront=behaviour_spec)
885
+
886
+
887
+ def mfront_name(stem: str) -> str:
888
+ """A name of MFront behaviour from the stem of a file: ``Zmat`` and its letters and
889
+ digits (the prefix avoids the names of TFEL's classes, such as ``Hill``)."""
890
+ out = re.sub(r"[^A-Za-z0-9]", "", str(stem))
891
+ out = out.removeprefix("Zmat")
892
+ return "Zmat" + (out[:1].upper() + out[1:] if out else "Behaviour")
893
+
894
+
895
+ def _is_file(source) -> bool:
896
+ return isinstance(source, Path) or (
897
+ isinstance(source, str) and "\n" not in source and Path(source).is_file()
898
+ )
899
+
900
+
901
+ def describe(source, behaviour: int = 0) -> dict:
902
+ """How a behaviour of a Z-mat file is translated: ``"native"`` (morphoGen's kernels,
903
+ with the configuration of the material) or ``"mfront"`` (and why)."""
904
+ b = read_zmat(source)[behaviour]
905
+ if not b.potentials:
906
+ return {"translation": "native", "kind": "elastic", "material": _elastic_material_kwargs(b)}
907
+ if b.kind == "porous_plastic":
908
+ porous, notes = _native_porous(b)
909
+ material = {**_elastic_material_kwargs(b), "porous_plasticity": porous.to_config()}
910
+ return {"translation": "native", "kind": "porous", "material": material, "notes": notes}
911
+ plasticity, reason = _native(b)
912
+ if plasticity is not None:
913
+ material = {**_elastic_material_kwargs(b), "plasticity": plasticity.to_config()}
914
+ return {"translation": "native", "kind": "plastic", "material": material}
915
+ return {"translation": "mfront", "reason": reason, "source": zmat_mfront_source(b)}
916
+
917
+
918
+ # -- writing -------------------------------------------------------------------------------
919
+
920
+
921
+ def _elasticity_lines(m, real) -> list[str]:
922
+ """The ``**elasticity`` of a material: isotropic, cubic, or its stiffness component by
923
+ component (named, so that the order of the shear components does not matter)."""
924
+ if m.young is not None:
925
+ return [" **elasticity isotropic", f" young {real(m.young)}",
926
+ f" poisson {real(m.poisson)}"] # fmt: skip
927
+ if m.stiffness is None:
928
+ raise ValueError("zmat: a material with elastic constants")
929
+ c = np.asarray(m.stiffness, dtype=float)
930
+ if m.symmetry == "cubic":
931
+ return [" **elasticity cubic", f" y1111 {real(c[0, 0])}",
932
+ f" y1122 {real(c[0, 1])}", f" y1212 {real(c[3, 3])}"] # fmt: skip
933
+ names = ("11", "22", "33", "23", "31", "12") # morphoGen's Voigt order
934
+ out = [" **elasticity anisotropic"]
935
+ for i in range(6):
936
+ out += [f" y{names[i]}{names[j]} {real(c[i, j])}" for j in range(i, 6) if c[i, j]]
937
+ return out
938
+
939
+
940
+ def _written_flow(p, real) -> list[str]:
941
+ """The flow of a von Mises or porous plasticity: Norton's, or plasticity."""
942
+ if p.viscous:
943
+ return [" *flow norton", f" n {real(p.exponent)}", f" K {real(p.viscosity)}"]
944
+ return [" *flow plasticity"]
945
+
946
+
947
+ def _written_hardening(p, real, brick: str) -> list[str]:
948
+ """The isotropic hardening of a von Mises or porous plasticity: one brick (``brick``:
949
+ ``*isotropic`` or ``*isotropic_hardening``)."""
950
+ r0, h, terms = p.yield_stress, p.hardening, p.isotropic
951
+ if len(terms) > 1 and h:
952
+ raise ValueError(
953
+ "zmat: a linear hardening with several saturating terms has no isotropic brick "
954
+ "of Z-mat (linear_nonlinear: one term; nonlinear_sum: no linear hardening)"
955
+ )
956
+ if not terms:
957
+ kind = "linear" if h else "constant"
958
+ elif len(terms) == 1:
959
+ kind = "linear_nonlinear" if h else "nonlinear"
960
+ else:
961
+ kind = "nonlinear_sum"
962
+ out = [f" {brick} {kind}", f" R0 {real(r0)}"]
963
+ if h:
964
+ out.append(f" H {real(h)}")
965
+ if len(terms) == 1:
966
+ ((q, b),) = terms
967
+ out += [f" Q {real(q)}", f" b {real(b)}"]
968
+ else:
969
+ for k, (q, b) in enumerate(terms, start=1):
970
+ out += [f" Q{k} {real(q)}", f" b{k} {real(b)}"]
971
+ return out
972
+
973
+
974
+ def _potential_lines(p, real) -> list[str]:
975
+ """The potential of a :class:`~morphogen.homogenization.behaviours.Plasticity`: its
976
+ criterion (von Mises, or Hill's with its coefficients ``hill1`` ... ``hill6`` of the
977
+ components 11, 22, 33, 12, 23, 31), its flow, its kinematic terms (one brick each,
978
+ named ``X1``... when several) and its isotropic hardening (one brick); ``real`` writes
979
+ the numbers."""
980
+ if p.hill is None:
981
+ criterion = [" *criterion mises"]
982
+ else:
983
+ criterion = [" *criterion hill"]
984
+ criterion += [f" hill{i} {real(h)}" for i, h in enumerate(p.hill, start=1)]
985
+ out = [" **potential gen_evp ev", *criterion, *_written_flow(p, real)]
986
+ return out + _kinematic_lines(p.kinematic, real) + _written_hardening(p, real, "*isotropic")
987
+
988
+
989
+ def _kinematic_lines(kinematic, real) -> list[str]:
990
+ """The kinematic terms ``(C, D)`` of a von Mises or porous potential: one brick each,
991
+ ``linear`` when ``D = 0``, ``nonlinear`` otherwise, named ``X1``... when several."""
992
+ out = []
993
+ for k, (c, d) in enumerate(kinematic, start=1):
994
+ name = f" X{k}" if len(kinematic) > 1 else ""
995
+ if d == 0:
996
+ out += [f" *kinematic linear{name}", f" C {real(c)}"]
997
+ else:
998
+ out += [f" *kinematic nonlinear{name}", f" C {real(c)}", f" D {real(d)}"]
999
+ return out
1000
+
1001
+
1002
+ def _table_lines(name: str, table, real) -> list[str]:
1003
+ """A coefficient of a porous criterion: a number, or a table of the porosity (rows
1004
+ ``value f``)."""
1005
+ if len(table) == 1 and table[0][0] == 0.0:
1006
+ return [f" {name} {real(table[0][1])}"]
1007
+ return [f" {name} f", *[f" {real(v)} {real(f)}" for f, v in table]]
1008
+
1009
+
1010
+ def _porous_lines(pp, real) -> list[str]:
1011
+ """The porous potential of a :class:`~morphogen.homogenization.porous.PorousPlasticity`:
1012
+ its criterion, flow, kinematic terms (those of gen_evp), isotropic hardening and
1013
+ nucleation."""
1014
+ out = [" **porous_potential"]
1015
+ if pp.criterion == "gurson":
1016
+ if abs(pp.q3 - pp.q1**2) > 1e-12 * pp.q1**2:
1017
+ raise ValueError("zmat: Gurson's q3 is q1² in Z-mat (no coefficient q3)")
1018
+ out += [" *porous_criterion gurson", f" q1 {real(pp.q1)}", f" q2 {real(pp.q2)}"]
1019
+ if pp.effective: # the effective porosity: Tvergaard and Needleman's coalescence
1020
+ out += _table_lines("fs", pp.effective, real)
1021
+ elif pp.criterion == "rousselier":
1022
+ kind = "rousselier" if pp.q2 == 1.0 else "modified_rousselier"
1023
+ out += [f" *porous_criterion {kind}", f" sigma1 {real(pp.sigma1)}",
1024
+ f" D {real(pp.D)}"] # fmt: skip
1025
+ if kind == "modified_rousselier":
1026
+ out.append(f" q2 {real(pp.q2)}")
1027
+ else:
1028
+ out += [" *porous_criterion elliptic", *_table_lines("C", pp.C, real),
1029
+ *_table_lines("F", pp.F, real)] # fmt: skip
1030
+ out += _written_flow(pp, real) + _kinematic_lines(pp.kinematic, real)
1031
+ out += _written_hardening(pp, real, "*isotropic_hardening")
1032
+ if pp.nucleation is not None:
1033
+ nucleation = dict(pp.nucleation)
1034
+ kind, threshold = nucleation.pop("type"), nucleation.pop("yield", 0.0)
1035
+ names = {"fN": "fn", "eN": "en", "sN": "sn"} # Z-mat's names of the Gaussian
1036
+ out.append(f" *strain_nucleation {kind}")
1037
+ out += [f" {names.get(k, k)} {real(v)}" for k, v in nucleation.items()]
1038
+ if threshold:
1039
+ out.append(f" yield {real(threshold)}")
1040
+ return out
1041
+
1042
+
1043
+ def write_zmat(material, path=None, *, title: str = "", digits: int | None = None) -> str:
1044
+ """The material file of Z-mat of a material (a
1045
+ :class:`~morphogen.homogenization.materials.Material` or the mapping of its
1046
+ configuration), which :func:`read_zmat` and :func:`zmat_material` read back as the
1047
+ same material: a ``linear_elastic`` behaviour (isotropic, cubic or anisotropic
1048
+ elasticity); a ``gen_evp`` behaviour of one von Mises potential (a Norton flow or
1049
+ time-independent plasticity, one isotropic hardening ``constant``, ``linear``,
1050
+ ``nonlinear``, ``linear_nonlinear`` or ``nonlinear_sum``, the kinematic terms
1051
+ ``linear`` or ``nonlinear``) on an isotropic elasticity, with an isotropic thermal
1052
+ strain; or a ``porous_plastic`` behaviour of one porous potential (Gurson's criterion
1053
+ with the table of its effective porosity, Rousselier's or the elliptic one with the
1054
+ tables of its coefficients, the flow, kinematic terms and isotropic hardening of the
1055
+ matrix, the nucleation), its initial porosity in ``*initialize_variable`` (as in the examples of
1056
+ Z-mat's manual). The numbers are written in full (they read back exactly), or with
1057
+ ``digits`` significant digits. Written in ``path`` when it is given; ``title``: a
1058
+ comment at the top. Crystal plasticity and MFront behaviours are not written (MFront
1059
+ sources describe them)."""
1060
+ from morphogen.homogenization.materials import Material
1061
+
1062
+ m = material if isinstance(material, Material) else Material.from_config(material)
1063
+ if m.void:
1064
+ raise ValueError("zmat: a void has no behaviour")
1065
+ for name, what in (
1066
+ ("crystal_plasticity", "crystal plasticity"),
1067
+ ("mfront", "an MFront behaviour"),
1068
+ ):
1069
+ if getattr(m, name) is not None:
1070
+ raise ValueError(f"zmat: {what} is not written as a material file (MFront is)")
1071
+ porous = m.porous_plasticity
1072
+ if (m.plasticity is not None or porous is not None) and m.young is None:
1073
+ raise ValueError("zmat: plasticity on an isotropic elasticity only")
1074
+ if m.analytic:
1075
+ raise ValueError(
1076
+ "zmat: the viscoelasticity, hyperelasticity and damage of "
1077
+ "morphogen.homogenization.laws are not written as a material file"
1078
+ )
1079
+ if digits is not None and int(digits) < 1:
1080
+ raise ValueError("zmat: digits, at least 1 (None: the numbers in full)")
1081
+ real = _real if digits is None else (lambda value: format(float(value), f".{int(digits)}g"))
1082
+ lines = [f"% {line}" for line in str(title).splitlines() if line.strip()]
1083
+ lines.append(f"% written by morphoGen {__version__}")
1084
+ if porous is not None:
1085
+ if m.expansion is not None:
1086
+ raise ValueError("zmat: porous_plastic without a thermal strain")
1087
+ lines += ["***material", " *initialize_variable", f" f {real(porous.porosity)}",
1088
+ "***behavior porous_plastic"] # fmt: skip
1089
+ else:
1090
+ kind = "gen_evp" if m.plasticity is not None else "linear_elastic"
1091
+ lines.append(f"***behavior {kind}")
1092
+ lines += _elasticity_lines(m, real)
1093
+ if m.expansion is not None:
1094
+ if not isinstance(m.expansion, float):
1095
+ raise ValueError("zmat: an isotropic thermal expansion only (**thermal_strain)")
1096
+ lines += [" **thermal_strain isotropic", f" alpha {real(m.expansion)}"]
1097
+ if m.plasticity is not None:
1098
+ lines += _potential_lines(m.plasticity, real)
1099
+ if porous is not None:
1100
+ lines += _porous_lines(porous, real)
1101
+ lines.append("***return")
1102
+ text = "\n".join(lines) + "\n"
1103
+ if path is not None:
1104
+ Path(path).write_text(text, encoding="utf-8")
1105
+ return text
1106
+
1107
+
1108
+ #: What of Z-mat's library morphoGen covers: (category, Z-mat brick or model, status,
1109
+ #: what morphoGen offers). Status: "native" (morphoGen's kernels), "mfront" (translated
1110
+ #: by :func:`zmat_material` into an MFront behaviour), "elsewhere" (morphoGen has it under
1111
+ #: another form), "user" (an MFront law of the user), "no".
1112
+ COVERAGE = [
1113
+ ("model", "linear_elastic", "native", "isotropic, cubic, orthotropic, transverse, anisotropic"),
1114
+ ("model", "gen_evp", "native", "one potential of von Mises or Hill; the others through MFront"),
1115
+ ("model", "reduced_plastic", "native", "as gen_evp"),
1116
+ (
1117
+ "model",
1118
+ "finite_strain crystal (Méric-Cailletaud)",
1119
+ "elsewhere",
1120
+ "crystal_plasticity, small and finite strains (CrystalPlasticity)",
1121
+ ),
1122
+ (
1123
+ "model",
1124
+ "porous_plastic (one porous potential)",
1125
+ "native",
1126
+ "PorousPlasticity: small and finite strains, the CPU and the GPU",
1127
+ ),
1128
+ (
1129
+ "porous_criterion",
1130
+ "gurson, rousselier, modified_rousselier, elliptic",
1131
+ "native",
1132
+ "GTN (q3 = q1², fs = f or a table: coalescence), Rousselier, Abouaf's elliptic (C, F "
1133
+ "tables of f)",
1134
+ ),
1135
+ (
1136
+ "porous_criterion",
1137
+ "cam_clay, fkm, zhang_niemi, elliptic_aniso, elliptic_fiber",
1138
+ "no",
1139
+ "",
1140
+ ),
1141
+ (
1142
+ "kinematic (porous_plastic)",
1143
+ "linear, nonlinear",
1144
+ "native",
1145
+ "gurson and elliptic: the potential of σ - X (Besson & Guillemer-Neel 2003), four at "
1146
+ "most; not rousselier",
1147
+ ),
1148
+ (
1149
+ "strain_nucleation",
1150
+ "constant, gaussian, exponential (yield)",
1151
+ "native",
1152
+ "Chu-Needleman; not crack_like, porosity_yield",
1153
+ ),
1154
+ (
1155
+ "porous_plastic",
1156
+ "several porous potentials, Hf, Hp, *shear_anisotropy hill, broken_behavior, "
1157
+ "adiabatic_heating",
1158
+ "no",
1159
+ "",
1160
+ ),
1161
+ ("model", "damage elasticity, aniso_damage", "user", "an MFront law"),
1162
+ (
1163
+ "model",
1164
+ "hyper_elastic (Mooney, Ogden, Arruda-Boyce, neo-Hookean)",
1165
+ "user",
1166
+ "an MFront law; morphoGen's finite strains: Hencky's elasticity",
1167
+ ),
1168
+ ("model", "linear_viscoelastic, viscoelastic_spectral", "user", "an MFront law"),
1169
+ (
1170
+ "model",
1171
+ "needleman, crisfield, chaboche, generalized debonding",
1172
+ "elsewhere",
1173
+ "cohesive zone elements (morphogen.fracture.cohesive)",
1174
+ ),
1175
+ ("model", "diffusion, coefficient_diffusion", "elsewhere", "coupling.diffusion (transient)"),
1176
+ (
1177
+ "elasticity",
1178
+ "isotropic, cubic, orthotropic, transverse, anisotropic",
1179
+ "native",
1180
+ "crystals turned by the orientations of their grains",
1181
+ ),
1182
+ ("elasticity", "coefficients depending on the temperature", "no", ""),
1183
+ ("thermal_strain", "isotropic", "native", "expansion (crystals: anisotropic)"),
1184
+ ("criterion", "mises", "native", ""),
1185
+ (
1186
+ "criterion",
1187
+ "hill",
1188
+ "native",
1189
+ "hill1 ... hill6 (components 11, 22, 33, 12, 23, 31); Hill (F, G, H, L, M, N) "
1190
+ "for MFront with the models that need it",
1191
+ ),
1192
+ ("criterion", "tresca", "user", "MFront's Hosford criterion with a large exponent"),
1193
+ (
1194
+ "criterion",
1195
+ "linear_drucker_prager, cast_iron, karafillis_boyce, nouailhas, 2M1C",
1196
+ "user",
1197
+ "an MFront law",
1198
+ ),
1199
+ ("flow", "plasticity", "native", "rate-independent"),
1200
+ ("flow", "norton", "native", "dp/dt = <f/K>^n (n >= 1; MFront otherwise)"),
1201
+ (
1202
+ "flow",
1203
+ "hyperbolic, double_norton, norton_exp, strain_hardening",
1204
+ "mfront",
1205
+ "user-defined viscoplastic flows of the brick",
1206
+ ),
1207
+ (
1208
+ "flow",
1209
+ "sellars_tegart, gsell, modified_visco, function, flow_sum",
1210
+ "user",
1211
+ "UserDefinedViscoplasticity of MFront's brick",
1212
+ ),
1213
+ (
1214
+ "isotropic",
1215
+ "constant, linear, nonlinear, linear_nonlinear, nonlinear_sum",
1216
+ "native",
1217
+ "three saturating terms at most, without softening (MFront otherwise)",
1218
+ ),
1219
+ ("isotropic", "power_law", "mfront", "UserDefined isotropic hardening"),
1220
+ (
1221
+ "isotropic",
1222
+ "by_point, iso_table, linear_pp, nonlinear recovery",
1223
+ "user",
1224
+ "MFront's Data hardening (tables)",
1225
+ ),
1226
+ ("kinematic", "linear, nonlinear", "native", "Prager, Armstrong-Frederick (four at most)"),
1227
+ ("kinematic", "nonlinear_evrad", "mfront", "Burlet-Cailletaud"),
1228
+ ("kinematic", "ziegler, aniso_nonlinear, nonlinear with recovery", "user", "an MFront law"),
1229
+ ("potential", "several gen_evp potentials", "mfront", "one inelastic flow per potential"),
1230
+ ("potential", "interactions between potentials", "no", ""),
1231
+ (
1232
+ "modifier",
1233
+ "lagrange_rotate, lagrange_polar (finite strains)",
1234
+ "elsewhere",
1235
+ "finite strains: logarithmic strains (Hencky) of the loading paths",
1236
+ ),
1237
+ ("modifier", "plane_stress", "no", "morphoGen's volume elements are 3D"),
1238
+ (
1239
+ "simulation",
1240
+ "****simulate (material point)",
1241
+ "elsewhere",
1242
+ "loading paths of a single material point (PathResult) and of volume elements",
1243
+ ),
1244
+ (
1245
+ "optimization",
1246
+ "****optimize (identification)",
1247
+ "elsewhere",
1248
+ "homogenization.identification: von Mises parameters on references (material "
1249
+ "points), the behaviour found written back by write_zmat",
1250
+ ),
1251
+ ]
1252
+
1253
+
1254
+ def coverage_markdown() -> str:
1255
+ """:data:`COVERAGE` as a Markdown table."""
1256
+ rows = ["| category | Z-mat | morphoGen | how |", "|---|---|---|---|"]
1257
+ rows += [f"| {a} | {b} | {c} | {d} |" for a, b, c, d in COVERAGE]
1258
+ return "\n".join(rows) + "\n"