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,579 @@
1
+ """Identification of the parameters of a behaviour on reference responses, as ``Zopt``
2
+ does for ``Zsim``: the parameters chosen are those whose material point
3
+ (:func:`~morphogen.homogenization.nonlinear.simulate_point`), under the loading path of
4
+ each reference, gives the stresses of the reference at its times in the least-squares
5
+ sense (a trust-region method on the logarithms of the parameters, which stay positive and
6
+ within ``span`` decades of their starting values). A reference is a response along a
7
+ path: the macroscopic curves of a loading path of a morphology (to give it a macroscopic
8
+ law) or the points of a test. Several references are followed together, each by its
9
+ weight whatever its number of points: a tension and a shear, cycles of several
10
+ amplitudes, which tell the isotropic hardening from the kinematic one.
11
+
12
+ The parameters are named after the keys of the configurations of the material
13
+ (:meth:`~morphogen.homogenization.materials.Material.from_config`): ``young``, ``poisson``
14
+ and, of its von Mises plasticity, ``yield``, ``hardening``, the isotropic terms ``Q``,
15
+ ``b`` (``Q2``, ``b2`` for the second...), the kinematic terms ``C``, ``D`` (``C2``...)
16
+ and Norton's ``K``, ``n``; of its porous plasticity, those of its matrix (``yield``,
17
+ ``hardening``, ``Q``, ``b``..., the kinematic terms ``C1``, ``D1``, ``C2``..., ``K``,
18
+ ``n``), the initial ``porosity``, Gurson's ``q1``,
19
+ ``q2``, ``q3`` and the coalescence ``fc``, ``fF``, Rousselier's ``sigma1``, ``D``, the
20
+ elliptic ``C``, ``F`` (numbers, not tables of the porosity) and the nucleation ``fN``,
21
+ ``eN``, ``sN``, ``A``, ``B``, ``e0``: a porous morphology (a matrix with voids) gives
22
+ its macroscopic law, the classic calibration of Gurson's model on unit cells under
23
+ several triaxialities. Of the behaviours of :mod:`morphogen.homogenization.laws`: the
24
+ terms of a viscoelasticity, ``g1``, ``tau1``, ``g2``... (shear) and ``k1``, ``tauk1``...
25
+ (bulk), which give a viscoelastic composite its Prony series from its relaxation; the
26
+ positive parameters of a hyperelasticity (``mu``, ``c10``, ``c01``, ``c20``, ``c30``,
27
+ ``lock``, ``bulk``; the material given by its law, without ``young`` and ``poisson``); and
28
+ those of a damage (``threshold``, ``strength``, ``ultimate``, ``fracture_energy``,
29
+ ``ratio``, ``viscosity``)."""
30
+
31
+ from __future__ import annotations
32
+
33
+ import copy
34
+ import re
35
+ from collections.abc import Callable
36
+ from dataclasses import dataclass
37
+
38
+ import numpy as np
39
+
40
+ from morphogen.homogenization.behaviours import HILL_COMPONENTS
41
+ from morphogen.homogenization.materials import Material
42
+ from morphogen.homogenization.paths import PathResult
43
+
44
+ #: The parameters of von Mises plasticity that can be identified, beside young and poisson
45
+ PLASTIC = ("yield", "hardening", "Q", "b", "C", "D", "K", "n")
46
+ #: The coefficients of Hill's criterion (``hill11`` ... ``hill31``: those of the components)
47
+ HILL = tuple(f"hill{c}" for c in HILL_COMPONENTS)
48
+ #: Those of porous plasticity (its matrix, its criterion, its nucleation)
49
+ POROUS = ("yield", "hardening", "Q", "b", "K", "n", "porosity", "q1", "q2", "q3", "fc", "fF",
50
+ "sigma1", "D", "C", "F", "fN", "eN", "sN", "A", "B", "e0") # fmt: skip
51
+ #: The coefficients of the criteria of porous plasticity, beside its matrix
52
+ _CRITERION = ("porosity", "q1", "q2", "q3", "fc", "fF", "sigma1", "D", "C", "F")
53
+ #: The behaviours of :mod:`morphogen.homogenization.laws` in the configuration of a material
54
+ ANALYTIC = ("viscoelasticity", "hyperelasticity", "damage")
55
+ #: The parameters of a damage that can be identified
56
+ _DAMAGE = ("threshold", "strength", "ultimate", "fracture_energy", "ratio", "viscosity")
57
+ #: The residuals of a material point that fails (its Newton iterations diverge)
58
+ FAILED = 1e3
59
+
60
+
61
+ def _where(config: dict, name: str) -> tuple[dict, str]:
62
+ """The mapping of the configuration of a material that holds the parameter ``name``,
63
+ and its key there."""
64
+ if name in ("young", "poisson"):
65
+ if name not in config:
66
+ raise ValueError(f"{name}: the material has no isotropic elasticity")
67
+ return config, name
68
+ if isinstance(config.get("porous_plasticity"), dict):
69
+ return _where_porous(config["porous_plasticity"], name)
70
+ if any(isinstance(config.get(key), dict) for key in ANALYTIC):
71
+ return _where_analytic(config, name)
72
+ match = re.fullmatch(r"(Q|b|C|D)(\d*)", name)
73
+ plasticity = config.get("plasticity")
74
+ if not isinstance(plasticity, dict):
75
+ raise ValueError(f"{name}: the material has no von Mises plasticity")
76
+ if name in ("yield", "hardening"):
77
+ return plasticity, name
78
+ if name in ("K", "n"):
79
+ if not isinstance(plasticity.get("norton"), dict):
80
+ raise ValueError(f"{name}: the plasticity has no Norton flow (give K and n)")
81
+ return plasticity["norton"], name
82
+ if name in HILL:
83
+ # von Mises is Hill's criterion of coefficients 1: those not given are 1
84
+ hill = plasticity.get("hill")
85
+ if hill is None or isinstance(hill, (list, tuple)):
86
+ hill = dict(zip(HILL_COMPONENTS, hill or (1.0,) * 6, strict=True))
87
+ plasticity["hill"] = hill
88
+ hill = {str(k): v for k, v in hill.items()}
89
+ plasticity["hill"] = hill
90
+ hill.setdefault(name[4:], 1.0)
91
+ return hill, name[4:]
92
+ if match is None:
93
+ raise ValueError(
94
+ f"parameter {name!r}: one of young, poisson, {', '.join(PLASTIC + HILL)} (Q2, "
95
+ "b2... for the next terms)"
96
+ )
97
+ letter, rank = match.group(1), int(match.group(2) or 1)
98
+ terms = plasticity.get("isotropic" if letter in "Qb" else "kinematic") or []
99
+ if not 1 <= rank <= len(terms):
100
+ kind = "isotropic" if letter in "Qb" else "kinematic"
101
+ raise ValueError(f"{name}: the plasticity has {len(terms)} {kind} terms")
102
+ return terms[rank - 1], letter
103
+
104
+
105
+ def _where_analytic(config: dict, name: str) -> tuple[dict, str]:
106
+ """The mapping of the configuration of a material with a viscoelasticity, a
107
+ hyperelasticity or a damage that holds ``name``."""
108
+ visco, hyper, damage = (config.get(key) for key in ANALYTIC)
109
+ match = re.fullmatch(r"(g|tau|k|tauk)(\d+)", name)
110
+ if match is not None and isinstance(visco, dict):
111
+ letter, rank = match.group(1), int(match.group(2))
112
+ kind, key = ("shear", "g") if letter in ("g", "tau") else ("bulk", "k")
113
+ terms = visco.get(kind) or []
114
+ if not 1 <= rank <= len(terms):
115
+ raise ValueError(f"{name}: the viscoelasticity has {len(terms)} {kind} terms")
116
+ if not isinstance(terms[rank - 1], dict): # pairs: mappings, to be set in place
117
+ visco[kind] = terms = [
118
+ t if isinstance(t, dict) else {key: t[0], "tau": t[1]} for t in terms
119
+ ]
120
+ return terms[rank - 1], key if letter in ("g", "k") else "tau"
121
+ if isinstance(hyper, dict) and name in ("mu", "c10", "c01", "c20", "c30", "lock", "bulk"):
122
+ return hyper, name
123
+ if isinstance(damage, dict) and name in _DAMAGE:
124
+ return damage, name
125
+ raise ValueError(
126
+ f"parameter {name!r}: one of young, poisson, g1, tau1... (shear terms) and k1, "
127
+ "tauk1... (bulk terms) of a viscoelasticity, mu, c10, c01, c20, c30, lock, bulk of a "
128
+ f"hyperelasticity, {', '.join(_DAMAGE)} of a damage"
129
+ )
130
+
131
+
132
+ def _where_porous(porous: dict, name: str) -> tuple[dict, str]:
133
+ """The mapping of the configuration of a porous plasticity that holds ``name``."""
134
+ if name == "yield":
135
+ return porous, "R0" if "R0" in porous else "yield"
136
+ if name == "hardening":
137
+ return porous, "H" if "H" in porous else "hardening"
138
+ if name in ("K", "n"):
139
+ if not isinstance(porous.get("norton"), dict):
140
+ raise ValueError(f"{name}: the porous plasticity has no Norton flow (give K and n)")
141
+ return porous["norton"], name
142
+ if name in _CRITERION:
143
+ if isinstance(porous.get(name), (list, tuple, dict)):
144
+ raise ValueError(f"{name}: a table of the porosity, not identified")
145
+ return porous, name
146
+ if name in ("fN", "eN", "sN", "A", "B", "e0"):
147
+ nucleation = porous.get("nucleation")
148
+ if not isinstance(nucleation, dict) or name not in nucleation:
149
+ raise ValueError(f"{name}: the porous plasticity has no nucleation with {name}")
150
+ return nucleation, name
151
+ # C and D alone: the coefficients of the criteria; C1, D1...: the kinematic terms
152
+ match = re.fullmatch(r"(Q|b)(\d*)|(C|D)(\d+)", name)
153
+ if match is None:
154
+ raise ValueError(
155
+ f"parameter {name!r} of porous plasticity: one of young, poisson, "
156
+ f"{', '.join(POROUS)} (Q2, b2... for the next isotropic terms, C1, D1... for the "
157
+ "kinematic ones)"
158
+ )
159
+ letter = match.group(1) or match.group(3)
160
+ rank = int(match.group(2) or match.group(4) or 1)
161
+ kind = "isotropic" if letter in "Qb" else "kinematic"
162
+ terms = porous.get(kind) or []
163
+ if not 1 <= rank <= len(terms):
164
+ raise ValueError(f"{name}: the matrix has {len(terms)} {kind} terms")
165
+ return terms[rank - 1], letter
166
+
167
+
168
+ def get_parameter(config: dict, name: str) -> float:
169
+ """The value of a parameter in the configuration of a material."""
170
+ mapping, key = _where(config, name)
171
+ return float(mapping.get(key, 0.0))
172
+
173
+
174
+ def set_parameter(config: dict, name: str, value: float) -> None:
175
+ """Set a parameter in the configuration of a material (in place)."""
176
+ mapping, key = _where(config, name)
177
+ mapping[key] = float(value)
178
+
179
+
180
+ def driven(result: PathResult) -> int:
181
+ """The index of the stress component that varies most along a response."""
182
+ return int(np.argmax(np.ptp(np.asarray(result.stress, dtype=float), axis=0)))
183
+
184
+
185
+ @dataclass
186
+ class Reference:
187
+ """A response the identification follows: the ``stresses`` (n x 6 in the order of the
188
+ paths, or the n values of the components compared) at the ``times`` of a loading
189
+ ``path`` (its name or specification), the indices of the ``components`` compared (by
190
+ default the one that varies most) and the ``weight`` of the reference in the gap."""
191
+
192
+ path: object
193
+ times: object
194
+ stresses: object
195
+ components: list[int] | None = None
196
+ weight: float = 1.0
197
+
198
+
199
+ def _prepared(ref: Reference) -> tuple[Reference, np.ndarray]:
200
+ """The reference checked, its components resolved, and the stresses compared."""
201
+ times = np.asarray(ref.times, dtype=float)
202
+ stresses = np.asarray(ref.stresses, dtype=float)
203
+ components = ref.components
204
+ if stresses.ndim == 1:
205
+ if components is None or len(components) != 1:
206
+ raise ValueError("a reference of one component: give its index (components)")
207
+ stresses = stresses[:, None]
208
+ elif components is None:
209
+ components = [int(np.argmax(np.ptp(stresses, axis=0)))]
210
+ components = [int(c) for c in components]
211
+ if not components or any(not 0 <= c < 6 for c in components):
212
+ raise ValueError("components: indices from 0 to 5 (11, 22, 33, 23, 31, 12)")
213
+ if stresses.shape[1] == 6:
214
+ compared = stresses[:, components]
215
+ elif stresses.shape[1] == len(components):
216
+ compared = stresses
217
+ else:
218
+ raise ValueError("the stresses of a reference: its 6 components, or those compared")
219
+ if len(times) != len(compared) or len(times) < 2:
220
+ raise ValueError("the reference: at least two times, one row of stresses at each")
221
+ if not float(ref.weight) > 0:
222
+ raise ValueError("the weight of a reference: positive")
223
+ return Reference(ref.path, times, stresses, components, float(ref.weight)), compared
224
+
225
+
226
+ @dataclass
227
+ class Identification:
228
+ """The parameters identified: their starting and final values, the material, the
229
+ references followed (their components resolved), the responses of the material point
230
+ under their paths with the parameters found and with the starting values (None where
231
+ it fails), the relative root mean square of the gap to each reference (to its largest
232
+ stress) and of the weighted gap to all, before and after, and the number of
233
+ evaluations (a material point under the path of each reference)."""
234
+
235
+ parameters: list[str]
236
+ initial: dict
237
+ values: dict
238
+ material: dict
239
+ references: list[Reference]
240
+ responses: list[PathResult]
241
+ initial_responses: list[PathResult | None]
242
+ gaps: list[float]
243
+ initial_gaps: list[float]
244
+ error: float
245
+ initial_error: float
246
+ evaluations: int
247
+
248
+ @property
249
+ def response(self) -> PathResult:
250
+ """The response under the path of the first reference."""
251
+ return self.responses[0]
252
+
253
+ @property
254
+ def components(self) -> list[int]:
255
+ """The components compared in the first reference."""
256
+ return self.references[0].components
257
+
258
+
259
+ def identify(
260
+ material: dict,
261
+ path,
262
+ times,
263
+ stresses,
264
+ parameters,
265
+ *,
266
+ components=None,
267
+ kinematics: str = "small",
268
+ span: float = 3.0,
269
+ max_evaluations: int = 200,
270
+ callback: Callable[[int, float], None] | None = None,
271
+ ) -> Identification:
272
+ """Identify ``parameters`` of ``material`` (a mapping of the configurations) so that
273
+ its material point under ``path`` gives the ``stresses`` (n x 6 in the order of the
274
+ paths, or n values of one component) of the reference at its ``times``
275
+ (``components``: the indices compared, by default the component that varies most in
276
+ the reference): :func:`identify_references` with one reference."""
277
+ return identify_references(
278
+ material,
279
+ [Reference(path, times, stresses, components)],
280
+ parameters,
281
+ kinematics=kinematics,
282
+ span=span,
283
+ max_evaluations=max_evaluations,
284
+ callback=callback,
285
+ )
286
+
287
+
288
+ def identify_references(
289
+ material: dict,
290
+ references,
291
+ parameters,
292
+ *,
293
+ kinematics: str = "small",
294
+ span: float = 3.0,
295
+ max_evaluations: int = 200,
296
+ callback: Callable[[int, float], None] | None = None,
297
+ ) -> Identification:
298
+ """Identify ``parameters`` of ``material`` (a mapping of the configurations) so that
299
+ its material point under the path of each of the ``references`` (:class:`Reference`)
300
+ gives their stresses at their times: the gaps relative to the largest stress of each
301
+ reference, the mean of their squares over each reference weighted by the references
302
+ (each counts by its weight, whatever its number of points). ``callback(evaluations,
303
+ error)`` after each evaluation (it may raise :class:`~morphogen.stopping.Stopped`)."""
304
+ from scipy.optimize import least_squares
305
+
306
+ from morphogen.homogenization.nonlinear import simulate_point
307
+
308
+ parameters = list(dict.fromkeys(parameters))
309
+ if not parameters:
310
+ raise ValueError("parameters: at least one to identify")
311
+ prepared = [_prepared(r) for r in references]
312
+ if not prepared:
313
+ raise ValueError("references: at least one response to follow")
314
+ refs = [r for r, _ in prepared]
315
+ compared = [c for _, c in prepared]
316
+ scales = [float(np.abs(c).max()) or 1.0 for c in compared]
317
+ sizes = np.array([c.size for c in compared], dtype=float)
318
+ weights = np.array([r.weight for r in refs])
319
+ # the mean of the squares is that of each reference weighted: one reference alone
320
+ # gives the relative gaps of its points
321
+ factors = np.sqrt(weights * sizes.sum() / (sizes * weights.sum()))
322
+ base = copy.deepcopy(material)
323
+ porous = base.get("porous_plasticity")
324
+ if isinstance(porous, dict) and "q1" in parameters and "q3" not in parameters:
325
+ q1, q3 = porous.get("q1"), porous.get("q3")
326
+ if q1 is not None and q3 is not None and abs(q3 - q1**2) <= 1e-12 * q1**2:
327
+ del porous["q3"] # q3 = q1² (Tvergaard's, Z-mat's) follows q1
328
+ start = np.array([get_parameter(base, p) for p in parameters])
329
+ if np.any(start <= 0):
330
+ zero = [p for p, v in zip(parameters, start, strict=True) if v <= 0]
331
+ raise ValueError(f"{', '.join(zero)}: a positive starting value to identify")
332
+ count = [0]
333
+
334
+ def responses(x):
335
+ config = copy.deepcopy(base)
336
+ for name, value in zip(parameters, np.exp(x), strict=True):
337
+ set_parameter(config, name, value)
338
+ out = []
339
+ for ref in refs:
340
+ try:
341
+ point = Material.from_config(config)
342
+ out.append(simulate_point(point, ref.path, kinematics=kinematics))
343
+ except (ValueError, RuntimeError, FloatingPointError, np.linalg.LinAlgError):
344
+ out.append(None)
345
+ return config, out
346
+
347
+ def gaps(results) -> list[np.ndarray]:
348
+ out = []
349
+ for ref, reference, scale, res in zip(refs, compared, scales, results, strict=True):
350
+ if res is None:
351
+ out.append(np.full(reference.size, FAILED))
352
+ continue
353
+ stress = np.asarray(res.stress)
354
+ sim = np.column_stack([np.interp(ref.times, res.times, stress[:, c])
355
+ for c in ref.components]) # fmt: skip
356
+ out.append(((sim - reference) / scale).ravel())
357
+ return out
358
+
359
+ def residuals_of(results) -> np.ndarray:
360
+ r = np.concatenate([g * f for g, f in zip(gaps(results), factors, strict=True)])
361
+ count[0] += 1
362
+ if callback is not None:
363
+ callback(count[0], float(np.sqrt(np.mean(r**2))))
364
+ return r
365
+
366
+ x0 = np.log(start)
367
+ _, initial = responses(x0)
368
+ first = residuals_of(initial)
369
+ fit = least_squares(
370
+ lambda x: residuals_of(responses(x)[1]),
371
+ x0,
372
+ bounds=(x0 - span * np.log(10.0), x0 + span * np.log(10.0)),
373
+ x_scale=1.0,
374
+ max_nfev=int(max_evaluations),
375
+ method="trf",
376
+ )
377
+ config, results = responses(fit.x)
378
+ if any(res is None for res in results):
379
+ raise ValueError("identification: the material point of the parameters found fails")
380
+ final = gaps(results)
381
+ return Identification(
382
+ parameters=parameters,
383
+ initial=dict(zip(parameters, start.tolist(), strict=True)),
384
+ values={p: get_parameter(config, p) for p in parameters},
385
+ material=config,
386
+ references=refs,
387
+ responses=results,
388
+ initial_responses=initial,
389
+ gaps=[float(np.sqrt(np.mean(g**2))) for g in final],
390
+ initial_gaps=[float(np.sqrt(np.mean(g**2))) for g in gaps(initial)],
391
+ error=float(np.sqrt(np.mean(fit.fun**2))),
392
+ initial_error=float(np.sqrt(np.mean(first**2))),
393
+ evaluations=count[0],
394
+ )
395
+
396
+
397
+ #: The loadings of a macroscopic law: a tension along each axis, a shear in each plane
398
+ LOADINGS = ("11", "22", "33", "12", "23", "31")
399
+ #: Those of a higher stress triaxiality (porous morphologies): a tension along an axis whose
400
+ #: lateral strains are held, and a hydrostatic tension
401
+ TRIAXIAL = ("confined11", "confined22", "confined33", "hydrostatic")
402
+ _COLUMN = {"11": 0, "22": 1, "33": 2, "23": 3, "31": 4, "12": 5}
403
+
404
+
405
+ def loading_path(name: str, strain: float, n: int, cycle: bool = False) -> tuple[dict, list[int]]:
406
+ """The path of a loading of a macroscopic law (:data:`LOADINGS`, :data:`TRIAXIAL`) to
407
+ ``strain`` in ``n`` increments (with ``cycle``, then to ``-strain`` in ``2 n``), and the
408
+ components of the stress compared."""
409
+ ramp = [0.0, strain, -strain] if cycle else [0.0, strain]
410
+ held = [0.0] * len(ramp)
411
+ if cycle:
412
+ timing = {"times": [0.0, 1.0, 3.0], "increments": [n, 2 * n]}
413
+ else:
414
+ timing = {"times": [0.0, 1.0], "increments": n}
415
+ if name in LOADINGS:
416
+ return {**timing, "strain": {name: ramp}}, [_COLUMN[name]]
417
+ if name == "hydrostatic":
418
+ return {**timing, "strain": {c: ramp for c in ("11", "22", "33")}}, [0, 1, 2]
419
+ axis = name.removeprefix("confined")
420
+ strains = {c: (ramp if c == axis else held) for c in ("11", "22", "33")}
421
+ return {**timing, "strain": strains}, [0, 1, 2]
422
+
423
+
424
+ @dataclass
425
+ class MacroscopicLaw:
426
+ """The macroscopic law of a morphology (:func:`macroscopic_law`): its responses under
427
+ the loadings, as the references of the identification of the law."""
428
+
429
+ loadings: tuple[str, ...]
430
+ paths: list[dict]
431
+ responses: list[PathResult]
432
+ identification: Identification
433
+
434
+
435
+ def law_start(
436
+ responses,
437
+ loadings,
438
+ law: str = "hill",
439
+ *,
440
+ kinematic: bool = False,
441
+ matrix: dict | None = None,
442
+ porosity: float | None = None,
443
+ ) -> tuple[dict, list[str]]:
444
+ """A starting law for the responses of a morphology under ``loadings`` (one loading
445
+ each, :func:`macroscopic_law`: monotonic, or a cycle that first loads), and the
446
+ parameters to fit: Young's modulus and Poisson's ratio of the first increment of the
447
+ first tension (of the first shear without a tension: its shear modulus, ν = 0.3), the
448
+ yield stress at 70 % of the stress at the peak of the loading (a shear times sqrt 3),
449
+ the linear hardening of the slope of the second half of the loading; with
450
+ ``kinematic``, a backstress ``(C, D)`` that takes half of that hardening and saturates
451
+ over the strain of the loading; fitted, those and, for ``law="hill"``, the
452
+ coefficients of the loadings run but the first (its coefficient stays 1: the
453
+ coefficients and the yield stress have one scale). For ``law="gurson"``, Gurson's
454
+ porous plasticity of the von Mises ``matrix`` (the configuration of a material) and of
455
+ the ``porosity`` (the fraction of the voids), starting from Tvergaard's q1 = 1.5 and q2
456
+ = 1: fitted, the elastic constants (from the first increment of a tension, or those of
457
+ the matrix), q1 and q2."""
458
+ if law not in ("hill", "mises", "gurson"):
459
+ raise ValueError(f"law: 'hill', 'mises' or 'gurson', got {law!r}")
460
+ loadings = [str(c) for c in loadings]
461
+ if law == "gurson":
462
+ return _gurson_start(responses, loadings, matrix, porosity)
463
+ k = next((i for i, c in enumerate(loadings) if c in LOADINGS and c[0] == c[1]), 0)
464
+ if loadings[k] not in LOADINGS:
465
+ raise ValueError(f"{law} law: a tension or a shear among the loadings")
466
+ c, res = loadings[k], responses[k]
467
+ col = _COLUMN[c]
468
+ strain, stress = np.asarray(res.strain), np.asarray(res.stress)
469
+ slope = stress[1, col] / strain[1, col]
470
+ if c[0] == c[1]:
471
+ lateral = [j for j in range(3) if j != col]
472
+ young = float(slope)
473
+ poisson = float(np.clip(-np.mean(strain[1, lateral]) / strain[1, col], 0.0, 0.49))
474
+ factor = 1.0
475
+ else: # a shear alone: the engineering strain, G = slope, E = 2 G (1 + 0.3)
476
+ poisson = 0.3
477
+ young = float(2.6 * slope)
478
+ factor = np.sqrt(3.0)
479
+ peak = int(np.argmax(np.abs(strain[:, col]))) # the end of the first loading
480
+ end = factor * abs(stress[peak, col])
481
+ half = peak // 2
482
+ rise = factor * (abs(stress[peak, col]) - abs(stress[half, col]))
483
+ run = abs(strain[peak, col] - strain[half, col]) / factor # p: the shear over sqrt 3
484
+ hardening = max(rise / run if run > 0 else 0.0, 1e-4 * young)
485
+ plasticity = {"yield": 0.7 * end, "hardening": hardening}
486
+ fitted = ["young", "poisson", "yield", "hardening"]
487
+ if kinematic:
488
+ plasticity["hardening"] = 0.5 * hardening
489
+ span_p = abs(strain[peak, col]) / factor
490
+ plasticity["kinematic"] = [{"C": 0.5 * hardening, "D": 1.0 / max(span_p, 1e-12)}]
491
+ fitted += ["C", "D"]
492
+ if law == "hill":
493
+ plasticity["hill"] = {}
494
+ fitted += [f"hill{d}" for d in loadings if d != c]
495
+ return {"young": young, "poisson": poisson, "plasticity": plasticity}, fitted
496
+
497
+
498
+ def _gurson_start(responses, loadings, matrix, porosity) -> tuple[dict, list[str]]:
499
+ """Gurson's law of a porous morphology: its matrix and porosity, q1 = 1.5, q2 = 1."""
500
+ if matrix is None or porosity is None:
501
+ raise ValueError("gurson law: the matrix (a von Mises material) and the porosity")
502
+ if not 0.0 < float(porosity) < 1.0:
503
+ raise ValueError(f"gurson law: a porosity between 0 and 1, got {porosity}")
504
+ plasticity = matrix.get("plasticity")
505
+ if not isinstance(plasticity, dict) or "young" not in matrix:
506
+ raise ValueError("gurson law: a matrix of isotropic elasticity and von Mises plasticity")
507
+ if plasticity.get("kinematic") or plasticity.get("hill") is not None:
508
+ raise ValueError(
509
+ "gurson law: a matrix without kinematic hardening (the backstresses of the porous "
510
+ "law are not identified on the monotonic loadings of q1 and q2) or Hill's criterion"
511
+ )
512
+ young, poisson = float(matrix["young"]), float(matrix.get("poisson", 0.3))
513
+ k = next((i for i, c in enumerate(loadings) if c in LOADINGS and c[0] == c[1]), None)
514
+ if k is not None: # the porous elasticity of the first increment of a tension
515
+ col = _COLUMN[loadings[k]]
516
+ strain = np.asarray(responses[k].strain)
517
+ stress = np.asarray(responses[k].stress)
518
+ lateral = [j for j in range(3) if j != col]
519
+ young = float(stress[1, col] / strain[1, col])
520
+ poisson = float(np.clip(-np.mean(strain[1, lateral]) / strain[1, col], 0.0, 0.49))
521
+ porous = {"criterion": "gurson", "porosity": float(porosity), "q1": 1.5, "q2": 1.0}
522
+ porous.update({key: copy.deepcopy(v) for key, v in plasticity.items()})
523
+ start = {"young": young, "poisson": poisson, "porous_plasticity": porous}
524
+ return start, ["young", "poisson", "q1", "q2"]
525
+
526
+
527
+ def macroscopic_law(
528
+ respond: Callable[[dict], PathResult],
529
+ start: dict | None = None,
530
+ parameters=None,
531
+ *,
532
+ law: str = "hill",
533
+ loadings=LOADINGS,
534
+ strain: float = 0.01,
535
+ increments: int = 20,
536
+ cycle: bool = False,
537
+ matrix: dict | None = None,
538
+ porosity: float | None = None,
539
+ kinematics: str = "small",
540
+ span: float = 3.0,
541
+ max_evaluations: int = 200,
542
+ callback: Callable[[int, float], None] | None = None,
543
+ ) -> MacroscopicLaw:
544
+ """The law that gives a morphology its macroscopic behaviour: ``respond(path)``, the
545
+ macroscopic response of the morphology along a loading path (a :class:`PathResult`:
546
+ ``lambda path: NonlinearFFTProblem(image, materials).run(path)``), under a monotonic
547
+ loading of each component of ``loadings`` to ``strain`` in ``increments`` steps (a
548
+ tension along an axis, ``"11"``..., or a shear in a plane, ``"12"``...: the other
549
+ stresses free; with ``cycle``, then back to ``-strain`` in twice as many, which shows
550
+ the Bauschinger effect), then the identification of the law on these responses
551
+ together (:func:`identify_references`, each response compared on its loaded
552
+ component): the ``parameters`` of ``start`` (a mapping of the configurations of a
553
+ material), or of the von Mises or Hill ``law`` that :func:`law_start` estimates from
554
+ the responses, with a kinematic hardening when the loadings cycle, or Gurson's law of
555
+ a porous morphology (``matrix``, ``porosity``), whose q1 and q2 need loadings of
556
+ several stress triaxialities (:data:`TRIAXIAL`: a confined or hydrostatic tension,
557
+ compared on its three normal stresses)."""
558
+ loadings = tuple(str(c) for c in loadings)
559
+ unknown = sorted(set(loadings) - set(LOADINGS + TRIAXIAL))
560
+ if unknown or not loadings:
561
+ known = ", ".join(LOADINGS + TRIAXIAL)
562
+ raise ValueError(f"loadings: some of {known}, got {loadings}")
563
+ if not strain > 0 or int(increments) < 1:
564
+ raise ValueError("strain: positive, with at least one increment")
565
+ paths, responses, references = [], [], []
566
+ for c in loadings:
567
+ path, components = loading_path(c, strain, int(increments), cycle)
568
+ response = respond(path)
569
+ paths.append(path)
570
+ responses.append(response)
571
+ references.append(Reference(path, response.times, response.stress, components))
572
+ if start is None or parameters is None:
573
+ estimated, fitted = law_start(responses, loadings, law, kinematic=cycle, matrix=matrix,
574
+ porosity=porosity) # fmt: skip
575
+ start = estimated if start is None else start
576
+ parameters = fitted if parameters is None else parameters
577
+ fit = identify_references(start, references, parameters, kinematics=kinematics, span=span,
578
+ max_evaluations=max_evaluations, callback=callback) # fmt: skip
579
+ return MacroscopicLaw(loadings, paths, responses, fit)