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
morphogen/io/mfront.py ADDED
@@ -0,0 +1,1104 @@
1
+ """MFront sources of morphoGen's behaviours (TFEL, https://thelfer.github.io/tfel).
2
+
3
+ :func:`mfront_source` writes a nonlinear material of morphoGen as an MFront behaviour, for
4
+ the codes that integrate MFront behaviours through its interfaces (AMITEX_FFTP and Cast3M
5
+ with ``umat``, Abaqus with ``abaqus``, Code_Aster, MGIS: see
6
+ :mod:`morphogen.homogenization.mfront`); the values of the material are constants of the
7
+ source:
8
+
9
+ * von Mises elasto-(visco)plasticity (:class:`~morphogen.homogenization.Plasticity`): the
10
+ brick ``StandardElastoViscoPlasticity`` of MFront: Hooke's law, the Norton flow of the
11
+ von Mises criterion (``Plastic``, rate-independent, without viscosity), linear and Voce
12
+ isotropic hardening (``R0 + H p + sum Q (1 - exp(-b p))``), Armstrong-Frederick and
13
+ Prager kinematic hardening (``X = 2/3 C a``, ``da = deps_p - D a dp``); in finite
14
+ strains, in the space of the logarithmic strain (``@StrainMeasure Hencky``), as
15
+ morphoGen's finite strains. Hill's criterion makes it an orthotropic behaviour (the
16
+ criterion ``Hill`` of the brick, with TFEL's ``F`` ... ``N`` from Z-set's coefficients:
17
+ :mod:`morphogen.homogenization.zmat`), in the axes of the sample;
18
+ * porous plasticity (:class:`~morphogen.homogenization.porous.PorousPlasticity`): where
19
+ MFront's brick is exactly morphoGen's porous plasticity (:func:`_porous_brick`), the
20
+ criterion of Gurson-Tvergaard-Needleman: the same brick with its porous criterion
21
+ ``GursonTvergaardNeedleman1982`` (``q_1``, ``q_2``, ``q_3``; the effective porosity
22
+ ``f`` or Tvergaard & Needleman's coalescence, MFront's ``f_c`` and ``f_r``, ``f_r``
23
+ the porosity of morphoGen's slope of ``f*`` when ``q3`` is not ``q1²``) and the
24
+ porosity in its implicit system (``porosity_evolution``, ``standard implicit
25
+ scheme``: morphoGen's backward Euler, ``ε̇p = (1 - f) ṗ ∂σ*/∂σ``, ``ḟ = (1 - f) tr
26
+ ε̇p + A ṗ``), Plastic or Norton flows with the isotropic hardening of von Mises,
27
+ morphoGen's constant nucleation from ``p = 0`` (MFront's power law of exponent 0,
28
+ ``"PowerLaw (strain)"``); its porosity is ``f0`` until the matrix flows (the source
29
+ sets it while ``p = 0``: the natural state of its internal variables is zero, as
30
+ those of morphoGen's other exports). Small and finite strains (Hencky), thermal
31
+ expansion as von Mises. The bounds of the porosity differ: morphoGen keeps ``f*``
32
+ below ``0.995 / q1``, the brick its porosity below 0.985 of its upper bound (1, or
33
+ ``f_r``) and breaks the material (zero stress) beyond 0.984 of it. The others
34
+ (Rousselier's criterion, the elliptic one, the effective porosities of other tables
35
+ and the coalescence with ``q3 > q1²``, Chu & Needleman's Gaussian and the exponential
36
+ nucleation, the thresholds of the nucleation, kinematic hardening: :func:`_porous_brick`
37
+ says why the brick differs) hold morphoGen's own integration of a point
38
+ (``porous_update``, the C port of its kernel, with its row of parameters and its
39
+ internal variables: :func:`_porous_kernel`), in small strains or in the space of the
40
+ logarithmic strain (``@StrainMeasure Hencky``), its consistent tangent the operator;
41
+ * Méric-Cailletaud crystal plasticity
42
+ (:class:`~morphogen.homogenization.CrystalPlasticity`), in small strains: an implicit
43
+ scheme of morphoGen's equations (its Jacobian by finite differences), the elasticity of
44
+ the crystal as orthotropic constants in its axes (``@ComputeStiffnessTensor``: E1, E2,
45
+ E3, nu12, nu23, nu13, G12, G23, G13, MFront's order), morphoGen's slip systems as their
46
+ Schmid tensors in TFEL's components (11, 22, 33, then sqrt(2) times 12, 13, 23: not
47
+ morphoGen's order, 23, 31, 12), the parameters of each system and the interaction
48
+ matrix. The behaviour is orthotropic: the solver gives the axes of each grain (MGIS
49
+ through morphoGen turns the strains to them; the ``umat`` interface takes them from
50
+ the coefficients V1, V2; Abaqus from ``*ORIENTATION``); in finite strains, morphoGen's
51
+ own integration of a point (its kernel in the source);
52
+ * in finite strains, the elastic materials too: Hencky's elasticity (the stress conjugate
53
+ to the logarithmic strain linear in it, ``@StrainMeasure Hencky``), isotropic or in
54
+ the axes of the crystal;
55
+ * the learned laws (a material whose ``learned`` names a trained model:
56
+ :mod:`morphogen.learning.mfront`): the trained parameters as constants and morphoGen's
57
+ C++ port of the model (the perceptron, the potential, the recurrent network and its
58
+ state, the standard model and its internal variables), in small strains or in finite
59
+ strains (``@StrainMeasure Hencky`` for the laws of the logarithmic strain,
60
+ ``GreenLagrange`` for the others), their thermal strain that of morphoGen's learned
61
+ laws, orthotropic in the axes of their material.
62
+
63
+ The interfaces of the other codes compute the logarithmic strain of the Hencky laws from
64
+ the deformation gradients (the function ``umat<behaviour>_malls`` of the ``umat``
65
+ interface: :func:`umat_function`). Abaqus gives the axes of the orthotropic laws in
66
+ finite strains through their first six state variables (``@AbaqusOrthotropyManagementPolicy``
67
+ ``MFront``, which the other interfaces ignore). :func:`mfront_state_size` gives the
68
+ number of internal state variables of a behaviour (those of the ``umat`` and ``abaqus``
69
+ interfaces in three dimensions, without these axes).
70
+
71
+ Thermal expansion is exported in small strains: ``thermal_expansion`` of the Hooke
72
+ potential of the brick (von Mises; Hill's criterion also takes three principal values in
73
+ the axes of the sample), ``@ComputeThermalExpansion`` of the crystals (one coefficient,
74
+ or three principal values in the axes of the crystal), morphoGen's thermal strain ``alpha
75
+ (T + dT - 293.15)`` in the sources of its porous kernel. Its reference temperatures are
76
+ MFront's, 293.15 K, the natural temperature of morphoGen's MFront behaviours (MGIS gets
77
+ ``293.15 + dT``): MFront's ``alpha (T - 293.15)`` is morphoGen's ``alpha dT``. Finite
78
+ strains: MFront's coefficient is a mean one (its Hencky brick stretches by ``1 + alpha
79
+ dT``), morphoGen's that of the logarithmic strain ``alpha dT``: the brick gets the mean
80
+ coefficient ``(exp(alpha theta) - 1) / theta`` (:func:`_mean_expansion`); the crystals,
81
+ Hencky's elasticity, the porous kernels and the learned laws of finite strains,
82
+ morphoGen's own sources, compute its logarithmic thermal strain themselves. The Abaqus
83
+ inputs start their nodes at 293.15 K when a material expands (their steps give absolute
84
+ temperatures); MFront's
85
+ abaqus interface has no stress-free expansion in finite strains, so they refuse the
86
+ brick's expanding laws of finite strains (:func:`mfront_brick`; morphoGen's own sources
87
+ compute their thermal strain and pass). The AMITEX_FFTP exports refuse every expanding
88
+ phase written as an MFront law: their loadings carry no change of temperature.
89
+ """
90
+
91
+ from __future__ import annotations
92
+
93
+ import math
94
+ import re
95
+ from dataclasses import dataclass
96
+ from pathlib import Path
97
+
98
+ import numpy as np
99
+
100
+ from morphogen._version import __version__
101
+
102
+ _SQRT2 = math.sqrt(2.0)
103
+ _NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
104
+ #: The axes of the orthotropic laws of finite strains in their first six state variables,
105
+ #: in Abaqus (the only orthotropy of its interface in finite strains; others ignore it)
106
+ ABAQUS_AXES = "@AbaqusOrthotropyManagementPolicy[abaqus] MFront;"
107
+ #: The function of the umat interface (Cast3M, AMITEX) of each strain measure in finite
108
+ #: strains: its strategies (Miehe, Apel & Lambrecht's logarithmic strain for Hencky,
109
+ #: finite rotations and small strains for Green-Lagrange)
110
+ _UMAT_FINITE = {"Hencky": "_malls", "GreenLagrange": "_frst"}
111
+ _STRAIN_MEASURE = re.compile(r"^\s*@StrainMeasure\s*(?:\[[^\]]*\]\s*)?(\w+)", re.M)
112
+ _ABAQUS_POLICY = re.compile(
113
+ r"^\s*@AbaqusOrthotropyManagementPolicy\s*(?:\[[^\]]*\]\s*)?MFront\b", re.M
114
+ )
115
+
116
+
117
+ def _real(value: float) -> str:
118
+ return repr(float(value))
119
+
120
+
121
+ def identifier(name: str) -> str:
122
+ """An identifier for the names of MFront behaviours, from the name of a file or of an
123
+ export: its letters and digits only (the dispatcher of MFront's laws in Abaqus splits
124
+ the names of the materials, ``ABAQUSBEHAVIOUR_<behaviour>_3D``, at their
125
+ underscores)."""
126
+ out = re.sub(r"[^A-Za-z0-9]", "", name)
127
+ return out if out[:1].isalpha() else f"M{out}"
128
+
129
+
130
+ def _check(material, kinematics: str) -> str:
131
+ """The kind of behaviour of a material to export: ``vonmises``, ``porous`` (the brick),
132
+ ``porous_kernel`` (morphoGen's kernel in the source: :func:`_porous_brick`),
133
+ ``crystal``, ``learned`` (:mod:`morphogen.learning.mfront`), and in finite strains
134
+ ``crystal_finite`` and ``elastic_finite``."""
135
+ if kinematics not in ("small", "finite"):
136
+ raise ValueError("kinematics: 'small' or 'finite'")
137
+ if material.void:
138
+ raise ValueError("mfront: a void has no behaviour")
139
+ if not material.nonlinear and kinematics == "small":
140
+ raise ValueError("mfront: a nonlinear material (plasticity or crystal_plasticity)")
141
+ if material.mfront is not None:
142
+ raise ValueError("mfront: the material is already an MFront behaviour (its source)")
143
+ if material.analytic:
144
+ raise ValueError(
145
+ "mfront: no source for the viscoelasticity, hyperelasticity and damage of "
146
+ "morphogen.homogenization.laws (integrated by morphoGen's solvers only)"
147
+ )
148
+ if material.learned is not None: # its model and expansion: morphogen.learning.mfront
149
+ from morphogen.learning.mfront import learned_model
150
+
151
+ learned_model(material, kinematics)
152
+ return "learned"
153
+ if material.expands:
154
+ _check_expansion(material, kinematics)
155
+ if material.porous:
156
+ return "porous" if _porous_brick(material.porous_plasticity) else "porous_kernel"
157
+ if material.crystal_plastic:
158
+ if material.crystal_plasticity.extended:
159
+ raise ValueError(
160
+ "mfront: no source for the twins and the cleavage planes of a crystal "
161
+ "(integrated by morphoGen's solvers only)"
162
+ )
163
+ return "crystal_finite" if kinematics == "finite" else "crystal"
164
+ if not material.nonlinear:
165
+ if not material.elastic:
166
+ raise ValueError("mfront: the material has no elastic parameters")
167
+ return "elastic_finite"
168
+ return "vonmises"
169
+
170
+
171
+ def _check_expansion(material, kinematics: str) -> None:
172
+ """The thermal expansions that the sources take: in small strains, one coefficient, or
173
+ principal values in the axes of the behaviour (those of a crystal, or of the sample for
174
+ Hill's criterion)."""
175
+ if not isinstance(material.expansion, tuple):
176
+ return
177
+ a = np.asarray(material.expansion, dtype=float)
178
+ if np.abs(a - np.diag(np.diag(a))).max() > 1e-12 * np.abs(a).max():
179
+ raise ValueError("mfront: an expansion tensor with shear components in its axes")
180
+ if material.plastic and material.plasticity.hill is None:
181
+ raise ValueError("mfront: an anisotropic expansion of a von Mises material")
182
+ if material.porous:
183
+ raise ValueError("mfront: an anisotropic expansion of a porous material")
184
+
185
+
186
+ def _mean_expansion(alpha: float) -> str:
187
+ """MFront's mean coefficient of thermal expansion (``dl / l0 = alpha_m (T - T0)``, the
188
+ stretch of its Hencky brick) whose logarithmic strain is morphoGen's ``alpha (T - T0)``
189
+ in finite strains: ``(exp(alpha theta) - 1) / theta``, ``theta = T - 293.15``, by its
190
+ series (five terms: below 1e-11 of it up to ``alpha theta = 0.02``)."""
191
+ u = f"({_real(alpha)}*(T-293.15))"
192
+ return (f'"{_real(alpha)}*(1+{u}*(0.5+{u}*(0.16666666666666666+{u}*'
193
+ f'(0.041666666666666664+{u}*0.008333333333333333))))"') # fmt: skip
194
+
195
+
196
+ def _thermal_strain(material, name: str) -> list[str]:
197
+ """The C lines of morphoGen's thermal strain at the end of the step (logarithmic in
198
+ finite strains), its tensor components ``name[6]`` in the axes of the behaviour:
199
+ ``alpha (T + dT - 293.15)`` (the sources that hold morphoGen's own kernels: crystals and
200
+ Hencky's elasticity of finite strains, the porous kernels)."""
201
+ values = _expansion_values(material) if material.expands else [0.0]
202
+ if len(values) == 1:
203
+ values = values * 3
204
+ theta = "(T + dT - 293.15)"
205
+ rows = ", ".join(f"{_real(v)} * {theta}" for v in values)
206
+ return [f" const double {name}[6] = {{{rows}, 0, 0, 0}};"]
207
+
208
+
209
+ def _hencky_strain(material) -> list[str]:
210
+ """The C lines of the elastic Hencky strain ``e``: the logarithmic strain at the end of
211
+ the step without morphoGen's thermal strain."""
212
+ if not material.expands:
213
+ return [" const auto e = eto + deto;"]
214
+ thermal = "StrainStensor{eth[0], eth[1], eth[2], 0, 0, 0}"
215
+ return [*_thermal_strain(material, "eth"), f" const auto e = eto + deto - {thermal};"]
216
+
217
+
218
+ def _expansion_values(material) -> list[float]:
219
+ """The coefficient of thermal expansion, or its three principal values."""
220
+ if isinstance(material.expansion, tuple):
221
+ return [float(v) for v in np.diag(np.asarray(material.expansion, dtype=float))]
222
+ return [float(material.expansion)]
223
+
224
+
225
+ def orthotropic_constants(stiffness) -> list[float]:
226
+ """The engineering constants of an orthotropic stiffness (6 x 6, morphoGen's Voigt
227
+ order 11, 22, 33, 23, 31, 12 with engineering strains) in MFront's order: E1, E2, E3,
228
+ nu12, nu23, nu13, G12, G23, G13 (``nu_ij = -eps_j / eps_i`` under ``sigma_i``)."""
229
+ d = np.asarray(stiffness, dtype=float)
230
+ coupling = np.concatenate([d[:3, 3:].ravel(), d[3:, :3].ravel(),
231
+ d[3:, 3:][~np.eye(3, dtype=bool)]]) # fmt: skip
232
+ if np.abs(coupling).max() > 1e-12 * np.abs(d).max():
233
+ raise ValueError(
234
+ "mfront: the stiffness of the crystal couples normal and shear components "
235
+ "(MFront's orthotropic elasticity in its axes)"
236
+ )
237
+ s = np.linalg.inv(d)
238
+ e1, e2, e3 = 1 / s[0, 0], 1 / s[1, 1], 1 / s[2, 2]
239
+ return [e1, e2, e3, -s[1, 0] * e1, -s[2, 1] * e2, -s[2, 0] * e1,
240
+ 1 / s[5, 5], 1 / s[3, 3], 1 / s[4, 4]] # fmt: skip
241
+
242
+
243
+ def _stiffness(material) -> np.ndarray:
244
+ from morphogen.homogenization.materials import isotropic_matrix
245
+
246
+ if material.stiffness is not None:
247
+ return np.asarray(material.stiffness, dtype=float)
248
+ return isotropic_matrix(*material.lame)
249
+
250
+
251
+ def _young_poisson(material) -> tuple[float, float]:
252
+ lam, mu = material.lame
253
+ return mu * (3 * lam + 2 * mu) / (lam + mu), lam / (2 * (lam + mu))
254
+
255
+
256
+ def mfront_state_size(material, kinematics: str = "small") -> int:
257
+ """The number of internal state variables of the MFront behaviour of a material (see
258
+ :func:`mfront_source`) in three dimensions: the elastic strain (6), then the back
259
+ strains of the kinematic terms (6 each) and the cumulated plastic strain (von Mises),
260
+ the porosity, the cumulated plastic strain of the matrix, the rupture of the brick and,
261
+ with a nucleation, the nucleated porosity (porous plasticity of the brick), or the
262
+ slips, cumulated slips and kinematic variables of the systems and the cumulated plastic
263
+ strain (crystals); in finite strains, the internal variables of morphoGen's kernel and
264
+ the cumulated plastic strain (crystals), none (elasticity). The porous kernels: the
265
+ elastic strain (6, small strains only), the internal variables of morphoGen's kernel
266
+ (10, and 6 per backstress), the cumulated plastic strain and the porosity. The learned
267
+ laws: the state of the recurrent network, the internal variables of the standard model
268
+ (none for the perceptron and the potential)."""
269
+ from morphogen.homogenization import porous
270
+ from morphogen.homogenization.crystal import state_width
271
+
272
+ kind = _check(material, kinematics)
273
+ if kind == "learned":
274
+ from morphogen.learning.mfront import learned_model
275
+
276
+ return learned_model(material, kinematics).n_state
277
+ n = material.crystal_plasticity.n_systems if material.crystal_plastic else 0
278
+ if kind == "crystal_finite":
279
+ return state_width(n, True) + 1
280
+ if kind == "crystal":
281
+ return 7 + 3 * n
282
+ if kind == "elastic_finite":
283
+ return 0
284
+ if kind == "porous":
285
+ return 9 + (material.porous_plasticity.nucleation is not None)
286
+ if kind == "porous_kernel":
287
+ width = porous.state_width(len(material.porous_plasticity.kinematic))
288
+ return width + 2 + (6 if kinematics == "small" else 0)
289
+ return 7 + 6 * len(material.plasticity.kinematic)
290
+
291
+
292
+ def mfront_brick(material, kinematics: str = "small") -> bool:
293
+ """Whether the source of a material is MFront's brick ``StandardElastoViscoPlasticity``
294
+ (von Mises, Hill's criterion, the porous plasticity that it matches), whose thermal
295
+ expansion is MFront's stress-free one (``thermal_expansion`` of its Hooke potential),
296
+ or one of morphoGen's own sources (crystals, Hencky's elasticity, the porous kernels,
297
+ the learned laws), which compute their thermal strain."""
298
+ return _check(material, kinematics) in ("vonmises", "porous")
299
+
300
+
301
+ def mfront_symmetry(material, kinematics: str = "small") -> str:
302
+ """``isotropic`` (von Mises, isotropic elasticity) or ``orthotropic`` (crystals,
303
+ anisotropic elasticity and Hill's criterion: the solver gives their axes, those of the
304
+ sample for Hill's criterion) behaviour of a material; a learned law is orthotropic in
305
+ the axes of its material (``oriented``), isotropic in those of the sample."""
306
+ kind = _check(material, kinematics)
307
+ if kind == "learned":
308
+ return "orthotropic" if material.learned.oriented else "isotropic"
309
+ crystal = kind in ("crystal", "crystal_finite")
310
+ hill = kind == "vonmises" and material.plasticity.hill is not None
311
+ orthotropic = crystal or hill or material.stiffness is not None
312
+ return "orthotropic" if orthotropic else "isotropic"
313
+
314
+
315
+ def mfront_strain_measure(material, kinematics: str = "small") -> str | None:
316
+ """The strain measure of the source of a material (:func:`mfront_source`): Hencky's
317
+ for elasticity, von Mises and porous plasticity in finite strains, none for the others (small
318
+ strains, and crystals in finite strains, whose kernel takes the deformation
319
+ gradient); a learned law in finite strains, Hencky's (a law of the logarithmic strain)
320
+ or Green-Lagrange's."""
321
+ kind = _check(material, kinematics)
322
+ if kind == "learned":
323
+ from morphogen.learning.mfront import learned_strain_measure
324
+
325
+ return learned_strain_measure(material, kinematics)
326
+ hencky = ("vonmises", "porous", "porous_kernel", "elastic_finite")
327
+ return "Hencky" if kinematics == "finite" and kind in hencky else None
328
+
329
+
330
+ def umat_function(behaviour: str, strain_measure: str | None = None) -> str:
331
+ """The function of a behaviour in the library of the umat interface (Cast3M, AMITEX):
332
+ ``umat<behaviour>`` (in lower case), and for the strain measures of finite strains
333
+ that of the strategy of the interface (``_malls``: Hencky's logarithmic strain,
334
+ ``_frst``: Green-Lagrange's)."""
335
+ if strain_measure is not None and strain_measure not in _UMAT_FINITE:
336
+ raise ValueError(f"umat: the strain measure {strain_measure} (Hencky or GreenLagrange)")
337
+ return f"umat{behaviour.lower()}{_UMAT_FINITE.get(strain_measure, '')}"
338
+
339
+
340
+ def _kernels(ns: int, width: int) -> str:
341
+ """morphoGen's kernels of the points for a host compiler: the C port of the GPU
342
+ (``behaviours.cu``) without its kernels of launches, its functions inline (the block
343
+ is in several translation units) and its constants ``constexpr`` (of the namespace of
344
+ the behaviour: macros would reach TFEL's headers)."""
345
+ from importlib import resources
346
+
347
+ from morphogen.homogenization.behaviours import kernel_constants
348
+
349
+ path = resources.files("morphogen.homogenization") / "behaviours.cu"
350
+ text = path.read_text(encoding="utf-8").split('extern "C" __global__')[0]
351
+ text = text.replace("#define MG_INF __longlong_as_double(0x7ff0000000000000LL)\n", "")
352
+ for qualifier in ("__device__ __forceinline__ ", "__device__ __noinline__ ", "__device__ "):
353
+ text = text.replace(qualifier, "inline ")
354
+ head = [
355
+ f"constexpr {'double' if isinstance(value, float) else 'int'} {name} = {value!r};"
356
+ for name, value in kernel_constants(ns, width).items()
357
+ ]
358
+ return "\n".join([*head, "constexpr double MG_INF = HUGE_VAL;", text])
359
+
360
+
361
+ def _crystal_finite(material, name: str) -> str:
362
+ """Méric-Cailletaud crystal plasticity in finite strains: morphoGen's own integration
363
+ of a point (``cp_finite``, the C port of its kernel), the first Piola-Kirchhoff stress
364
+ and its consistent derivative, wrapped in a behaviour of the ``DefaultFiniteStrain``
365
+ DSL; the internal variables of the kernel (in the axes of the crystal) are an array of
366
+ auxiliary state variables."""
367
+ from morphogen.homogenization.crystal import state_width
368
+
369
+ cp = material.crystal_plasticity
370
+ normals, directions = cp.systems()
371
+ ns = len(normals)
372
+ width = state_width(ns, True)
373
+ systems = np.concatenate([directions, normals], axis=1) # l, n of each system
374
+ families = "; ".join(
375
+ f"{fam} (" + ", ".join(f"{k} = {v:g}" for k, v in
376
+ zip(("tau0", "Q", "b", "C", "D", "K", "n"), values,
377
+ strict=True)) + ")"
378
+ for fam, values in cp.families
379
+ ) # fmt: skip
380
+ space = f"morphogen_{name}"
381
+ lines = [
382
+ "@DSL DefaultFiniteStrain;",
383
+ f"@Behaviour {name};",
384
+ "@Author morphoGen;",
385
+ "@Description {",
386
+ f' "morphoGen {__version__}: Meric-Cailletaud crystal plasticity in finite strains '
387
+ f"(F = Fe Fp, Saint Venant-Kirchhoff elasticity of Fe, the slip systems in the "
388
+ f"intermediate configuration), {ns} slip systems: {families}; integrated by "
389
+ f"morphoGen's kernel (cp_finite), in the axes of the crystal.\"",
390
+ "}",
391
+ "@ModellingHypothesis Tridimensional;",
392
+ "@OrthotropicBehaviour;",
393
+ ABAQUS_AXES,
394
+ f"@AuxiliaryStateVariable real mg[{width}];",
395
+ 'mg.setEntryName("MorphogenState");',
396
+ "@AuxiliaryStateVariable strain p;",
397
+ 'p.setGlossaryName("EquivalentPlasticStrain");',
398
+ "@LocalVariable real K[81];",
399
+ "",
400
+ "@Includes{",
401
+ "// morphoGen's kernels of the points and the constants of the material (MFront",
402
+ "// includes this block in several headers of one translation unit)",
403
+ f"#ifndef {space.upper()}_KERNELS",
404
+ f"#define {space.upper()}_KERNELS",
405
+ "#include <cmath>",
406
+ "#include <math.h>",
407
+ f"namespace {space} {{",
408
+ _kernels(ns, width),
409
+ "// the slip systems (directions l, normals n), the parameters of each system, the",
410
+ "// interaction matrix and the stiffness (Voigt 11 22 33 23 31 12, engineering",
411
+ "// shears), in the axes of the crystal",
412
+ f"constexpr double systems[{6 * ns}] = {_array(systems.ravel())};",
413
+ f"constexpr double params[{7 * ns}] = {_array(cp.params_array().ravel())};",
414
+ f"constexpr double h[{ns * ns}] = {_array(cp.interaction_matrix().ravel())};",
415
+ f"constexpr double stiffness[36] = {_array(_stiffness(material).ravel())};",
416
+ "// the components of TFEL's tensors (11 22 33 12 21 13 31 23 32) row by row",
417
+ "constexpr int ROWS[9] = {0, 4, 8, 1, 3, 2, 6, 5, 7};",
418
+ f"}} // end of namespace {space}",
419
+ "#endif",
420
+ "}",
421
+ "",
422
+ "@Integrator{",
423
+ f" namespace mk = {space};",
424
+ " double hg[9], f[9], old[mk::WIDTH], nw[mk::WIDTH], pk1[9];",
425
+ " for (int k = 0; k != 9; ++k) {",
426
+ " f[mk::ROWS[k]] = F1[k];",
427
+ " hg[mk::ROWS[k]] = F1[k] - (k < 3 ? 1 : 0);",
428
+ " }",
429
+ " for (int r = 0; r != mk::WIDTH; ++r) {",
430
+ " old[r] = mg[r];",
431
+ " }",
432
+ *_thermal_strain(material, "eth"),
433
+ " mk::Work work;",
434
+ " if (mk::cp_finite(mk::systems, mk::params, mk::h, mk::NS, mk::stiffness, hg, eth, dt,",
435
+ " old, nw, pk1, &K[0], 0, 1.0, &work) != 0) {",
436
+ " return false;",
437
+ " }",
438
+ " for (int r = 0; r != mk::WIDTH; ++r) {",
439
+ " mg[r] = nw[r];",
440
+ " }",
441
+ " p = nw[mk::STATE_P];",
442
+ " // the Cauchy stress, P F^T / J, in TFEL's components (sqrt(2) on the shears)",
443
+ " const auto J = det(F1);",
444
+ " double t[3][3];",
445
+ " for (int i = 0; i != 3; ++i) {",
446
+ " for (int j = 0; j != 3; ++j) {",
447
+ " t[i][j] = 0;",
448
+ " for (int a = 0; a != 3; ++a) {",
449
+ " t[i][j] += pk1[3 * i + a] * f[3 * j + a] / J;",
450
+ " }",
451
+ " }",
452
+ " }",
453
+ " const auto r2 = std::sqrt(2.);",
454
+ " sig = StressStensor{t[0][0], t[1][1], t[2][2], r2 * t[0][1], r2 * t[0][2],",
455
+ " r2 * t[1][2]};",
456
+ "}",
457
+ "",
458
+ "@TangentOperator<DPK1_DF>{",
459
+ f" namespace mk = {space};",
460
+ " tfel::math::t2tot2<N, stress> k;",
461
+ " for (int I = 0; I != 9; ++I) {",
462
+ " for (int L = 0; L != 9; ++L) {",
463
+ " k(I, L) = K[9 * mk::ROWS[I] + mk::ROWS[L]];",
464
+ " }",
465
+ " }",
466
+ " Dt = k;",
467
+ "}",
468
+ ]
469
+ return "\n".join(lines) + "\n"
470
+
471
+
472
+ def _elastic_finite(material, name: str) -> str:
473
+ """Hencky's elasticity in finite strains: the stress conjugate to the logarithmic
474
+ strain linear in it (``@StrainMeasure Hencky``), isotropic (the Lamé coefficients) or
475
+ anisotropic in the axes of the crystal (its orthotropic constants, MFront's order)."""
476
+ lines = ["@DSL Default;", f"@Behaviour {name};", "@Author morphoGen;", "@Description {"]
477
+ if material.stiffness is None:
478
+ lam, mu = material.lame
479
+ e, nu = _young_poisson(material)
480
+ lines += [
481
+ f' "morphoGen {__version__}: isotropic Hencky elasticity (the space of the '
482
+ f'logarithmic strain): E = {e:g}, nu = {nu:g}."',
483
+ "}",
484
+ "@StrainMeasure Hencky;",
485
+ "@ProvidesSymmetricTangentOperator;",
486
+ "",
487
+ "@Integrator{",
488
+ f" constexpr auto lambda = {_real(lam)};",
489
+ f" constexpr auto mu = {_real(mu)};",
490
+ *_hencky_strain(material),
491
+ " sig = lambda * trace(e) * StrainStensor::Id() + 2 * mu * e;",
492
+ " if (computeTangentOperator_) {",
493
+ " Dt = lambda * Stensor4::IxI() + 2 * mu * Stensor4::Id();",
494
+ " }",
495
+ "}",
496
+ ]
497
+ else:
498
+ constants = orthotropic_constants(material.stiffness)
499
+ values = ", ".join(f"{k} = {v:g}" for k, v in zip(
500
+ ("E1", "E2", "E3", "nu12", "nu23", "nu13", "G12", "G23", "G13"), constants,
501
+ strict=True)) # fmt: skip
502
+ lines += [
503
+ f' "morphoGen {__version__}: Hencky elasticity of a crystal (the space of the '
504
+ f'logarithmic strain), in its axes: {values}."',
505
+ "}",
506
+ "@ModellingHypothesis Tridimensional;",
507
+ "@OrthotropicBehaviour;",
508
+ ABAQUS_AXES,
509
+ "@StrainMeasure Hencky;",
510
+ "@ProvidesSymmetricTangentOperator;",
511
+ "@ComputeStiffnessTensor<UnAltered>{" + ", ".join(_real(c) for c in constants) + "};",
512
+ "",
513
+ "@Integrator{",
514
+ *_hencky_strain(material),
515
+ " sig = D * e;",
516
+ " if (computeTangentOperator_) {",
517
+ " Dt = D;",
518
+ " }",
519
+ "}",
520
+ ]
521
+ return "\n".join(lines) + "\n"
522
+
523
+
524
+ def _isotropic_hardening(r0: float, h: float, isotropic) -> list[str]:
525
+ """The isotropic hardening ``R0 + H p + sum Q (1 - exp(-b p))`` of the brick: linear,
526
+ and Voce's ``Rinf + (R0 - Rinf) exp(-b p)`` from ``R0 = 0`` to ``Rinf = Q``."""
527
+ hardening = [f' isotropic_hardening : "Linear" {{R0 : {_real(r0)}, H : {_real(h)}}},']
528
+ for q, b in isotropic:
529
+ hardening.append(f' isotropic_hardening : "Voce" {{R0 : 0, Rinf : {_real(q)}, '
530
+ f"b : {_real(b)}}},") # fmt: skip
531
+ return hardening
532
+
533
+
534
+ def _vonmises(material, name: str, kinematics: str) -> str:
535
+ pl = material.plasticity
536
+ e, nu = _young_poisson(material)
537
+ hardening = _isotropic_hardening(pl.yield_stress, pl.hardening, pl.isotropic)
538
+ for c, d in pl.kinematic:
539
+ if d > 0:
540
+ hardening.append(f' kinematic_hardening : "Armstrong-Frederick" {{C : {_real(c)}, '
541
+ f"D : {_real(d)}}},") # fmt: skip
542
+ else:
543
+ hardening.append(f' kinematic_hardening : "Prager" {{C : {_real(c)}}},')
544
+ if pl.viscous:
545
+ flow = "Norton"
546
+ hardening.append(f" K : {_real(pl.viscosity)},")
547
+ hardening.append(f" n : {_real(pl.exponent)},")
548
+ else:
549
+ flow = "Plastic"
550
+ hardening[-1] = hardening[-1].rstrip(",")
551
+ terms = [f"R0 = {pl.yield_stress:g}", f"H = {pl.hardening:g}"]
552
+ terms += [f"Voce (Q, b) = ({q:g}, {b:g})" for q, b in pl.isotropic]
553
+ terms += [f"kinematic (C, D) = ({c:g}, {d:g})" for c, d in pl.kinematic]
554
+ terms += [f"Norton K = {pl.viscosity:g}, n = {pl.exponent:g}"] if pl.viscous else []
555
+ if pl.hill is not None:
556
+ from morphogen.homogenization.behaviours import HILL_COMPONENTS
557
+
558
+ terms += [", ".join(f"h{c} = {h:g}" for c, h in zip(HILL_COMPONENTS, pl.hill,
559
+ strict=True))] # fmt: skip
560
+ space = (" in the space of the logarithmic strain (Hencky)" if kinematics == "finite"
561
+ else " in small strains") # fmt: skip
562
+ criterion = '"Mises"'
563
+ if pl.hill is not None:
564
+ # Z-set's hill1 ... hill6 (components 11, 22, 33, 12, 23, 31) as TFEL's F ... N
565
+ from morphogen.homogenization.zmat import _hill
566
+
567
+ coefficients = _hill({f"hill{i}": h for i, h in enumerate(pl.hill, start=1)})
568
+ criterion = (
569
+ '"Hill" {' + ", ".join(f"{k} : {_real(v)}" for k, v in coefficients.items()) + "}"
570
+ )
571
+ law = "Hill" if pl.hill is not None else "von Mises"
572
+ hooke = f"young_modulus : {_real(e)}, poisson_ratio : {_real(nu)}"
573
+ if material.expands:
574
+ values = _expansion_values(material)
575
+ terms.append("thermal expansion " + ", ".join(f"{v:g}" for v in values))
576
+ # finite strains: the mean coefficient whose stretch is morphoGen's exp(alpha dT)
577
+ text = [_mean_expansion(v) if kinematics == "finite" else _real(v) for v in values]
578
+ if len(values) == 1:
579
+ hooke += f", thermal_expansion : {text[0]}"
580
+ else:
581
+ hooke += "".join(f", thermal_expansion{i} : {v}"
582
+ for i, v in enumerate(text, start=1)) # fmt: skip
583
+ lines = [
584
+ "@DSL Implicit;",
585
+ f"@Behaviour {name};",
586
+ "@Author morphoGen;",
587
+ "@Description {",
588
+ f' "morphoGen {__version__}: {law} elasto-'
589
+ f"{'visco' if pl.viscous else ''}plasticity{space}: E = {e:g}, nu = {nu:g}, "
590
+ f'{", ".join(terms)}."',
591
+ "}",
592
+ "@Algorithm NewtonRaphson;",
593
+ "@Epsilon 1.e-14;",
594
+ "@Theta 1;",
595
+ ]
596
+ if kinematics == "finite":
597
+ lines.append("@StrainMeasure Hencky;")
598
+ if pl.hill is not None:
599
+ # Hill's criterion is written in the axes of the material, those of the sample
600
+ if isinstance(material.expansion, tuple): # MFront asks it of orthotropic expansions
601
+ lines.append("@ModellingHypothesis Tridimensional;")
602
+ lines.append("@OrthotropicBehaviour;")
603
+ lines += [
604
+ "@Brick StandardElastoViscoPlasticity{",
605
+ f' stress_potential : "Hooke" {{{hooke}}},',
606
+ f' inelastic_flow : "{flow}" {{',
607
+ f" criterion : {criterion},",
608
+ *hardening,
609
+ " }",
610
+ "};",
611
+ ]
612
+ return "\n".join(lines) + "\n"
613
+
614
+
615
+ #: The threshold ``en`` of MFront's power law of the nucleation of exponent 0 that is
616
+ #: morphoGen's constant nucleation from ``p = 0`` (MFront's rate ``fn (p / en - 1)^m``
617
+ #: needs ``en > 0``; it integrates it from ``max(p, en)``: ``fn en`` short of ``A dp``)
618
+ _NUCLEATION_EN = 1e-200
619
+
620
+
621
+ def _porous_brick(pp) -> tuple[str, str | None] | None:
622
+ """The porous criterion and the nucleation model (None: none) of MFront's brick that
623
+ are exactly those of a porous plasticity, or None: its source then holds morphoGen's
624
+ kernel (:func:`_porous_kernel`). The brick's ``GursonTvergaardNeedleman1982`` is GTN's
625
+ criterion with its effective porosity ``f`` (MFront's ``f_c`` beyond any porosity) or
626
+ Tvergaard & Needleman's coalescence (MFront's ``f* = f_c + delta (f - f_c)`` beyond
627
+ ``f_c``, ``delta = (f_u - f_c) / (f_r - f_c)``, ``f_u = (q1 - sqrt(q1² - q3)) / q3``
628
+ the ultimate porosity, ``1 / q1`` when ``q3 = q1²``: ``f_r`` the porosity of
629
+ morphoGen's slope, ``fF`` when ``q3 = q1²``); its nucleation, morphoGen's constant
630
+ nucleation ``A`` from ``p = 0`` (MFront's power law of exponent 0, ``"PowerLaw
631
+ (strain)"``, its threshold :data:`_NUCLEATION_EN`, its maximum nucleated porosity 1).
632
+ Not the brick's: Rousselier's criterion (MFront's ``RousselierTanguyBesson2002`` puts
633
+ the matrix stress in place of morphoGen's constant ``σ1``: homogeneous of degree 1 in
634
+ the stress), the elliptic one (none in the brick), the effective porosities of other
635
+ tables, the coalescence with ``q3 > q1²`` (MFront's ``f*`` reaches ``f_u`` at
636
+ ``f_r``, not real then), Chu & Needleman's Gaussian nucleation (MFront integrates the
637
+ Gaussian exactly over a step, ``fN / 2 (erf((p + dp - eN) / (sqrt(2) sN)) - erf((p -
638
+ eN) / (sqrt(2) sN)))``, morphoGen by backward Euler, ``A(p + dp) dp``), the exponential
639
+ one (none), the thresholds of the nucleation (MFront's power law integrates its rate
640
+ from its threshold ``en``, ``fn (p + dp - en)`` in the step that crosses it, morphoGen's
641
+ backward Euler ``A dp``) and kinematic hardening (MFront 5.1's brick: "kinematic
642
+ hardening rules are not supported when coupled with a porosity evolution")."""
643
+ nuc = pp.nucleation
644
+ if pp.criterion != "gurson" or pp.kinematic:
645
+ return None
646
+ if nuc is not None and (nuc["type"] != "constant" or nuc["yield"] > 0):
647
+ return None
648
+ q1, q2, q3 = pp.q1, pp.q2, pp.q3
649
+ table = pp.effective
650
+ if not table:
651
+ fc, fr = 1.0, 2.0 # the porosity never reaches f_c: f* = f
652
+ else:
653
+ on_identity = len(table) == 3 and all(abs(x - y) <= 1e-12 for x, y in table[:2])
654
+ if not (on_identity and table[0][0] == 0.0 and table[2][1] > table[1][1]):
655
+ return None
656
+ (_, _), (fc, _), (ff, fstar) = table
657
+ if abs(q3 - q1 * q1) <= 1e-12 * q1 * q1 and abs(fstar - 1 / q1) <= 1e-12 / q1:
658
+ fr = ff
659
+ elif q3 > q1 * q1:
660
+ return None
661
+ else:
662
+ fu = (q1 - math.sqrt(q1 * q1 - q3)) / q3
663
+ fr = fc + (fu - fc) * (ff - fc) / (fstar - fc)
664
+ values = {"f_c": fc, "f_r": fr, "q_1": q1, "q_2": q2, "q_3": q3}
665
+ criterion = ('"GursonTvergaardNeedleman1982" {'
666
+ + ", ".join(f"{k} : {_real(v)}" for k, v in values.items()) + "}") # fmt: skip
667
+ if nuc is None:
668
+ return criterion, None
669
+ return criterion, (f'"PowerLaw (strain)" {{fn : {_real(nuc["A"])}, '
670
+ f"en : {_real(_NUCLEATION_EN)}, m : 0, fmax : 1}}") # fmt: skip
671
+
672
+
673
+ _CRITERION_NAMES = {"gurson": "Gurson-Tvergaard-Needleman", "rousselier": "Rousselier",
674
+ "elliptic": "elliptic"} # fmt: skip
675
+
676
+
677
+ def _porous_terms(pp) -> list[str]:
678
+ """The parameters of a porous plasticity, for the descriptions of its sources."""
679
+
680
+ def pairs(table):
681
+ return ", ".join(f"({x:g}, {y:g})" for x, y in table)
682
+
683
+ terms = [f"f0 = {pp.porosity:g}"]
684
+ if pp.criterion == "gurson":
685
+ terms += [f"q1 = {pp.q1:g}", f"q2 = {pp.q2:g}", f"q3 = {pp.q3:g}"]
686
+ terms += [f"effective porosity {pairs(pp.effective)}"] if pp.effective else []
687
+ elif pp.criterion == "rousselier":
688
+ terms += [f"sigma1 = {pp.sigma1:g}", f"D = {pp.D:g}", f"q2 = {pp.q2:g}"]
689
+ else:
690
+ terms += [f"C {pairs(pp.C)}", f"F {pairs(pp.F)}"]
691
+ terms += [f"R0 = {pp.yield_stress:g}", f"H = {pp.hardening:g}"]
692
+ terms += [f"Voce (Q, b) = ({q:g}, {b:g})" for q, b in pp.isotropic]
693
+ terms += [f"kinematic (C, D) = ({c:g}, {d:g})" for c, d in pp.kinematic]
694
+ if pp.viscous:
695
+ terms.append(f"Norton K = {pp.viscosity:g}, n = {pp.exponent:g}")
696
+ nuc = pp.nucleation
697
+ if nuc is not None:
698
+ values = ", ".join(f"{k} = {v:g}" for k, v in nuc.items() if k not in ("type", "yield"))
699
+ start = f" from p = {nuc['yield']:g}" if nuc["yield"] > 0 else ""
700
+ terms.append(f"{nuc['type']} nucleation {values}{start}")
701
+ return terms
702
+
703
+
704
+ def _porous(material, name: str, kinematics: str) -> str:
705
+ """The source of a porous plasticity of the brick (:func:`_porous_brick`): the porosity
706
+ in its implicit system (``standard implicit scheme``), its initial value ``f0`` until
707
+ the matrix flows."""
708
+ pp = material.porous_plasticity
709
+ e, nu = _young_poisson(material)
710
+ criterion, nucleation = _porous_brick(pp)
711
+ hardening = _isotropic_hardening(pp.yield_stress, pp.hardening, pp.isotropic)
712
+ terms = _porous_terms(pp)
713
+ if pp.viscous:
714
+ flow = "Norton"
715
+ hardening += [f" K : {_real(pp.viscosity)},", f" n : {_real(pp.exponent)},"]
716
+ else:
717
+ flow = "Plastic"
718
+ hardening[-1] = hardening[-1].rstrip(",")
719
+ hooke = f"young_modulus : {_real(e)}, poisson_ratio : {_real(nu)}"
720
+ if material.expands:
721
+ alpha = _expansion_values(material)[0]
722
+ terms.append(f"thermal expansion {alpha:g}")
723
+ text = _mean_expansion(alpha) if kinematics == "finite" else _real(alpha)
724
+ hooke += f", thermal_expansion : {text}"
725
+ space = (" in the space of the logarithmic strain (Hencky)" if kinematics == "finite"
726
+ else " in small strains") # fmt: skip
727
+ evolution = [' algorithm : "standard implicit scheme"']
728
+ if nucleation is not None:
729
+ evolution[-1] += ","
730
+ evolution.append(f" nucleation_model : {nucleation}")
731
+ lines = [
732
+ "@DSL Implicit;",
733
+ f"@Behaviour {name};",
734
+ "@Author morphoGen;",
735
+ "@Description {",
736
+ f' "morphoGen {__version__}: porous elasto-{"visco" if pp.viscous else ""}plasticity '
737
+ f"(Gurson-Tvergaard-Needleman){space}: E = {e:g}, nu = {nu:g}, "
738
+ f'{", ".join(terms)}."',
739
+ "}",
740
+ "@Algorithm NewtonRaphson;",
741
+ "@Epsilon 1.e-14;",
742
+ "@Theta 1;",
743
+ ]
744
+ if kinematics == "finite":
745
+ lines.append("@StrainMeasure Hencky;")
746
+ lines += [
747
+ "@Brick StandardElastoViscoPlasticity{",
748
+ f' stress_potential : "Hooke" {{{hooke}}},',
749
+ f' inelastic_flow : "{flow}" {{',
750
+ f" criterion : {criterion},",
751
+ *hardening,
752
+ " },",
753
+ " porosity_evolution : {",
754
+ *evolution,
755
+ " }",
756
+ "};",
757
+ "",
758
+ "// the porosity is f0 until the matrix flows (it changes with the plastic strain",
759
+ "// only): the natural state of the internal variables is zero, as in the other",
760
+ "// exports of morphoGen",
761
+ "@InitLocalVariables<AtBeginning>{",
762
+ " if (this->p <= 0) {",
763
+ f" this->f = {_real(pp.porosity)};",
764
+ " }",
765
+ "}",
766
+ ]
767
+ return "\n".join(lines) + "\n"
768
+
769
+
770
+ def _porous_kernel(material, name: str, kinematics: str) -> str:
771
+ """The source of a porous plasticity outside the brick (:func:`_porous_brick`):
772
+ morphoGen's own integration of a point (``porous_update``, the C port of its kernel,
773
+ with its row of parameters), in small strains or in the space of the logarithmic
774
+ strain (``@StrainMeasure Hencky``: the stress conjugate to it), the consistent tangent
775
+ of the kernel the operator, morphoGen's thermal strain ``alpha (T + dT - 293.15)``
776
+ (:func:`_thermal_strain`). Its auxiliary state variables: the elastic strain (small
777
+ strains), the internal variables of the kernel (``MorphogenState``: the plastic strain,
778
+ ``p``, the growth of the porosity, the nucleated porosity, the matrix stress, the
779
+ backstresses), the cumulated plastic strain and the porosity; their natural state,
780
+ zero, is the porosity ``f0``."""
781
+ from morphogen.homogenization.porous import state_width
782
+
783
+ pp = material.porous_plasticity
784
+ width = state_width(len(pp.kinematic))
785
+ row = pp.params(*material.lame)
786
+ e, nu = _young_poisson(material)
787
+ terms = _porous_terms(pp)
788
+ if material.expands:
789
+ terms.append(f"thermal expansion {_expansion_values(material)[0]:g}")
790
+ small = kinematics == "small"
791
+ where = " in small strains" if small else " in the space of the logarithmic strain (Hencky)"
792
+ space = f"morphogen_{name}"
793
+ lines = [
794
+ "@DSL Default;",
795
+ f"@Behaviour {name};",
796
+ "@Author morphoGen;",
797
+ "@Description {",
798
+ f' "morphoGen {__version__}: porous elasto-{"visco" if pp.viscous else ""}plasticity '
799
+ f"({_CRITERION_NAMES[pp.criterion]}){where}: E = {e:g}, nu = {nu:g}, "
800
+ f"{', '.join(terms)}; integrated by morphoGen's kernel (porous_update).\"",
801
+ "}",
802
+ "@ModellingHypothesis Tridimensional;",
803
+ *([] if small else ["@StrainMeasure Hencky;"]),
804
+ "@ProvidesSymmetricTangentOperator;",
805
+ ]
806
+ if small:
807
+ lines += ["@AuxiliaryStateVariable StrainStensor eel;",
808
+ 'eel.setGlossaryName("ElasticStrain");'] # fmt: skip
809
+ lines += [
810
+ f"@AuxiliaryStateVariable real mg[{width}];",
811
+ 'mg.setEntryName("MorphogenState");',
812
+ "@AuxiliaryStateVariable strain p;",
813
+ 'p.setGlossaryName("EquivalentPlasticStrain");',
814
+ "@AuxiliaryStateVariable real f;",
815
+ 'f.setGlossaryName("Porosity");',
816
+ "",
817
+ "@Includes{",
818
+ "// morphoGen's kernels of the points and the parameters of the material (MFront",
819
+ "// includes this block in several headers of one translation unit)",
820
+ f"#ifndef {space.upper()}_KERNELS",
821
+ f"#define {space.upper()}_KERNELS",
822
+ "#include <cmath>",
823
+ "#include <math.h>",
824
+ f"namespace {space} {{",
825
+ _kernels(1, width),
826
+ "// the row of parameters of the porous point (morphogen.homogenization.porous)",
827
+ f"constexpr double params[{row.size}] = {_array(row)};",
828
+ "// morphoGen's components (11 22 33 23 31 12) of TFEL's (11 22 33 12 13 23)",
829
+ "constexpr int VOIGT[6] = {0, 1, 2, 5, 4, 3};",
830
+ f"}} // end of namespace {space}",
831
+ "#endif",
832
+ "}",
833
+ "",
834
+ "@Integrator{",
835
+ f" namespace mk = {space};",
836
+ " // TFEL's components of tensors: sqrt(2) times the shears; morphoGen's strain: the",
837
+ " // engineering shears",
838
+ " const auto r2 = std::sqrt(2.);",
839
+ " const StrainStensor e = eto + deto;",
840
+ " double e6[6], old[mk::WIDTH], nw[mk::WIDTH], s6[6], k6[36];",
841
+ " for (int i = 0; i != 6; ++i) {",
842
+ " e6[mk::VOIGT[i]] = (i < 3 ? 1 : r2) * e[i];",
843
+ " }",
844
+ " for (int r = 0; r != mk::WIDTH; ++r) {",
845
+ " old[r] = mg[r];",
846
+ " }",
847
+ *_thermal_strain(material, "eth"),
848
+ " if (mk::porous_update(mk::params, e6, eth, dt, old, nw, s6, k6) != 0) {",
849
+ " return false;",
850
+ " }",
851
+ " for (int r = 0; r != mk::WIDTH; ++r) {",
852
+ " mg[r] = nw[r];",
853
+ " }",
854
+ " p = nw[mk::STATE_P];",
855
+ " f = mk::params[mk::P_F0] + nw[mk::STATE_FG] + nw[mk::STATE_FN];",
856
+ " for (int i = 0; i != 6; ++i) {",
857
+ " const auto c = i < 3 ? 1 : r2;",
858
+ " sig[i] = c * s6[mk::VOIGT[i]];",
859
+ ]
860
+ if small: # the strain without the thermal and the plastic ones (the kernel's 0 ... 5)
861
+ lines.append(" eel[i] = e[i] - c * (eth[mk::VOIGT[i]] + nw[mk::VOIGT[i]]);")
862
+ lines += [
863
+ " }",
864
+ " if (computeTangentOperator_) {",
865
+ " for (int i = 0; i != 6; ++i) {",
866
+ " for (int j = 0; j != 6; ++j) {",
867
+ " const auto c = (i < 3 ? 1 : r2) * (j < 3 ? 1 : r2);",
868
+ " Dt(i, j) = c * k6[6 * mk::VOIGT[i] + mk::VOIGT[j]];",
869
+ " }",
870
+ " }",
871
+ " }",
872
+ "}",
873
+ ]
874
+ return "\n".join(lines) + "\n"
875
+
876
+
877
+ def _array(values) -> str:
878
+ return "{" + ", ".join(_real(v) for v in values) + "}"
879
+
880
+
881
+ def _crystal(material, name: str) -> str:
882
+ cp = material.crystal_plasticity
883
+ normals, directions = cp.systems()
884
+ ns = len(normals)
885
+ par = cp.params_array() # tau0, Q, b, C, D, K, n of each system
886
+ h = cp.interaction_matrix()
887
+ m = 0.5 * (directions[:, :, None] * normals[:, None, :]
888
+ + normals[:, :, None] * directions[:, None, :]) # fmt: skip
889
+ # TFEL's components of the Schmid tensors: 11, 22, 33, then sqrt(2) times 12, 13, 23
890
+ tfel = np.stack([m[:, 0, 0], m[:, 1, 1], m[:, 2, 2], _SQRT2 * m[:, 0, 1],
891
+ _SQRT2 * m[:, 0, 2], _SQRT2 * m[:, 1, 2]], axis=1) # fmt: skip
892
+ constants = orthotropic_constants(_stiffness(material))
893
+ families = "; ".join(
894
+ f"{fam} (" + ", ".join(f"{k} = {v:g}" for k, v in
895
+ zip(("tau0", "Q", "b", "C", "D", "K", "n"), values,
896
+ strict=True)) + ")"
897
+ for fam, values in cp.families
898
+ ) # fmt: skip
899
+ space = f"morphogen_{name}"
900
+ expansion = [] # one coefficient, or the principal values in the axes of the crystal
901
+ if material.expands:
902
+ values = _expansion_values(material)
903
+ text = _array(values) if len(values) > 1 else _real(values[0])
904
+ expansion = [f"@ComputeThermalExpansion {text};"]
905
+ rows = ",\n".join(" " + _array(row) for row in tfel)
906
+ hrows = ",\n".join(" " + _array(row) for row in h)
907
+ lines = [
908
+ "@DSL Implicit;",
909
+ f"@Behaviour {name};",
910
+ "@Author morphoGen;",
911
+ "@Description {",
912
+ f' "morphoGen {__version__}: Meric-Cailletaud crystal plasticity in small strains, '
913
+ f"{ns} slip systems: {families}; the elasticity and the slip systems in the axes "
914
+ 'of the crystal."',
915
+ "}",
916
+ "@ModellingHypothesis Tridimensional;",
917
+ "@OrthotropicBehaviour;",
918
+ "@Algorithm NewtonRaphson_NumericalJacobian;",
919
+ "@PerturbationValueForNumericalJacobianComputation 1.e-10;",
920
+ "@Epsilon 1.e-13;",
921
+ "@Theta 1;",
922
+ "@Brick StandardElasticity;",
923
+ "@ComputeStiffnessTensor<UnAltered>{" + ", ".join(_real(c) for c in constants) + "};",
924
+ *expansion,
925
+ f"@IntegerConstant Nss = {ns};",
926
+ "",
927
+ "@Includes{",
928
+ "// morphoGen's slip systems, the parameters of each system and the interaction matrix",
929
+ "// (MFront includes this block in several headers of one translation unit)",
930
+ f"#ifndef {space.upper()}_SYSTEMS",
931
+ f"#define {space.upper()}_SYSTEMS",
932
+ f"namespace {space} {{",
933
+ " // Schmid tensors, TFEL's components: 11, 22, 33, then sqrt(2) times 12, 13, 23",
934
+ f" constexpr double m[{ns}][6] = {{",
935
+ rows,
936
+ " };",
937
+ ]
938
+ for k, key in enumerate(("tau0", "Q", "b", "C", "D", "K", "n")):
939
+ lines.append(f" constexpr double {key}[{ns}] = {_array(par[:, k])};")
940
+ lines += [
941
+ f" constexpr double h[{ns}][{ns}] = {{",
942
+ hrows,
943
+ " };",
944
+ f"}} // end of namespace {space}",
945
+ "#endif",
946
+ "}",
947
+ "",
948
+ "@StateVariable strain g[Nss];",
949
+ 'g.setEntryName("Slip");',
950
+ "@AuxiliaryStateVariable strain v[Nss];",
951
+ 'v.setEntryName("CumulatedSlip");',
952
+ "@AuxiliaryStateVariable strain a[Nss];",
953
+ 'a.setEntryName("KinematicVariable");',
954
+ "@AuxiliaryStateVariable strain p;",
955
+ 'p.setGlossaryName("EquivalentPlasticStrain");',
956
+ "",
957
+ "@Integrator{",
958
+ f" namespace cs = {space};",
959
+ " for (unsigned short i = 0; i != Nss; ++i) {",
960
+ " auto tau = real(0);",
961
+ " for (unsigned short k = 0; k != 6; ++k) {",
962
+ " feel[k] += dg[i] * cs::m[i][k];",
963
+ " tau += sig[k] * cs::m[i][k];",
964
+ " }",
965
+ " auto r = real(cs::tau0[i]);",
966
+ " if (cs::Q[i] != 0) {",
967
+ " for (unsigned short j = 0; j != Nss; ++j) {",
968
+ " r += cs::Q[i] * cs::h[i][j] * (1 - exp(-cs::b[i] * (v[j] + abs(dg[j]))));",
969
+ " }",
970
+ " }",
971
+ " const auto x = cs::C[i] * (a[i] + dg[i]) / (1 + cs::D[i] * abs(dg[i]));",
972
+ " const auto f = abs(tau - x) - r;",
973
+ " const auto vp = (f > 0) ? pow(f / cs::K[i], cs::n[i]) : real(0);",
974
+ " fg[i] -= dt * vp * ((tau - x >= 0) ? 1 : -1);",
975
+ " }",
976
+ "}",
977
+ "",
978
+ "@UpdateAuxiliaryStateVariables{",
979
+ f" namespace cs = {space};",
980
+ " auto dep = Stensor(real(0));",
981
+ " for (unsigned short i = 0; i != Nss; ++i) {",
982
+ " a[i] = (a[i] + dg[i]) / (1 + cs::D[i] * abs(dg[i]));",
983
+ " v[i] += abs(dg[i]);",
984
+ " for (unsigned short k = 0; k != 6; ++k) {",
985
+ " dep[k] += dg[i] * cs::m[i][k];",
986
+ " }",
987
+ " }",
988
+ " p += sqrt(2 * (dep | dep) / 3);",
989
+ "}",
990
+ ]
991
+ return "\n".join(lines) + "\n"
992
+
993
+
994
+ @dataclass(frozen=True)
995
+ class UserBehaviour:
996
+ """The MFront behaviour of a material (its ``mfront`` key) as the exports to other
997
+ codes need it: its source, name and symmetry, the names of its material properties
998
+ in the order of their declaration, the number of its internal state variables, its
999
+ strain measure (finite strains: Hencky, GreenLagrange; None: the deformation
1000
+ gradient) and whether Abaqus gives its axes through its first six state variables
1001
+ (``@AbaqusOrthotropyManagementPolicy MFront``)."""
1002
+
1003
+ source: Path
1004
+ name: str
1005
+ orthotropic: bool
1006
+ properties: tuple[str, ...]
1007
+ internal_variables: int
1008
+ strain_measure: str | None = None
1009
+ abaqus_axes: bool = False
1010
+
1011
+
1012
+ def _source_text(path: Path) -> str:
1013
+ """The text of an MFront source without its comments."""
1014
+ text = path.read_text(encoding="utf-8", errors="replace")
1015
+ return re.sub(r"//[^\n]*", "", re.sub(r"/\*.*?\*/", "", text, flags=re.S))
1016
+
1017
+
1018
+ def user_behaviour(material, kinematics: str = "small") -> UserBehaviour:
1019
+ """The behaviour of an MFront material for the exports (:class:`UserBehaviour`), as
1020
+ MGIS describes it (its source compiled with the generic interface, which needs MGIS
1021
+ and MFront): a behaviour of the kinematics of the export (finite strains: written in
1022
+ the deformation gradient, or with Hencky's or Green-Lagrange's strain measure)
1023
+ without external state variables but the temperature, given by its source (the
1024
+ exports compile it for their interface)."""
1025
+ from morphogen.homogenization.mfront import load_behaviour
1026
+
1027
+ if kinematics not in ("small", "finite"):
1028
+ raise ValueError("kinematics: 'small' or 'finite'")
1029
+ spec = material.mfront
1030
+ if spec.source is None:
1031
+ raise ValueError(
1032
+ "an MFront material given by its library: the exports compile its source with "
1033
+ "the interface of their code"
1034
+ )
1035
+ others = [name for name, _ in spec.external_state_variables if name != "Temperature"]
1036
+ if others:
1037
+ raise ValueError(f"mfront: the external state variables {others} are not exported")
1038
+ try:
1039
+ law = load_behaviour(spec, finite=kinematics == "finite")
1040
+ except ValueError as exc:
1041
+ raise ValueError(
1042
+ f"mfront: the exports in {kinematics} strains take {kinematics} strain behaviours "
1043
+ f"({exc})"
1044
+ ) from None
1045
+ text = _source_text(Path(spec.source))
1046
+ found = _STRAIN_MEASURE.search(text)
1047
+ measure = found.group(1) if found and kinematics == "finite" else None
1048
+ if measure is not None and measure not in _UMAT_FINITE:
1049
+ raise ValueError(
1050
+ f"mfront: {spec.behaviour}: the strain measure {measure} in finite strains (the "
1051
+ f"exports take {', '.join(_UMAT_FINITE)}, or the deformation gradient)"
1052
+ )
1053
+ names = tuple(v.name for v in law.behaviour.mps)
1054
+ axes = law.orthotropic and _ABAQUS_POLICY.search(text) is not None
1055
+ return UserBehaviour(Path(spec.source), spec.behaviour, law.orthotropic, names, law.n_isv,
1056
+ measure, axes) # fmt: skip
1057
+
1058
+
1059
+ def write_parameters(directory, behaviour: str, parameters) -> Path | None:
1060
+ """``<behaviour>-parameters.txt``: the values of the parameters of an MFront behaviour,
1061
+ which its compiled code reads from the working directory of the run (none: no
1062
+ file)."""
1063
+ if not parameters:
1064
+ return None
1065
+ path = Path(directory) / f"{behaviour}-parameters.txt"
1066
+ path.write_text("".join(f"{name} {_real(value)}\n" for name, value in parameters), "utf-8")
1067
+ return path
1068
+
1069
+
1070
+ def mfront_source(material, name: str, *, kinematics: str = "small") -> str:
1071
+ """The MFront source of the behaviour ``name`` of a material (see the module): von
1072
+ Mises plasticity, porous plasticity (the brick, or morphoGen's kernel), crystal
1073
+ plasticity and the learned laws (:mod:`morphogen.learning.mfront`) in small or finite
1074
+ strains, and in finite strains Hencky's elasticity of the elastic materials."""
1075
+ if not _NAME.fullmatch(name):
1076
+ raise ValueError(f"mfront: the name of a behaviour is an identifier, got {name!r}")
1077
+ kind = _check(material, kinematics)
1078
+ if kind == "learned":
1079
+ from morphogen.learning.mfront import learned_source
1080
+
1081
+ return learned_source(material, name, kinematics=kinematics)
1082
+ if kind == "crystal_finite":
1083
+ return _crystal_finite(material, name)
1084
+ if kind == "crystal":
1085
+ return _crystal(material, name)
1086
+ if kind == "elastic_finite":
1087
+ return _elastic_finite(material, name)
1088
+ if kind == "porous":
1089
+ return _porous(material, name, kinematics)
1090
+ if kind == "porous_kernel":
1091
+ return _porous_kernel(material, name, kinematics)
1092
+ return _vonmises(material, name, kinematics)
1093
+
1094
+
1095
+ def write_mfront(material, path, *, name: str | None = None, kinematics: str = "small") -> Path:
1096
+ """Write the MFront source of a material (:func:`mfront_source`); the name of the
1097
+ behaviour is the stem of ``path`` by default."""
1098
+ path = Path(path)
1099
+ if path.suffix != ".mfront":
1100
+ raise ValueError(f"mfront: a .mfront file, got {path.name!r}")
1101
+ text = mfront_source(material, name or path.stem, kinematics=kinematics)
1102
+ path.parent.mkdir(parents=True, exist_ok=True)
1103
+ path.write_text(text, encoding="utf-8")
1104
+ return path