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/amitex.py ADDED
@@ -0,0 +1,741 @@
1
+ """Runs of AMITEX_FFTP, the FFT solver of voxel microstructures of the CEA
2
+ (https://amitexfftp.github.io/AMITEX), on morphoGen images, and their results.
3
+
4
+ :func:`write_amitex` writes the files of the runs of a voxel image of phases:
5
+
6
+ * the material and zone numbers of the voxels (``<name>_materials.vtk``,
7
+ ``<name>_zones.vtk``: legacy VTK with exactly ten header lines, then big-endian 32-bit
8
+ integers, x varying fastest; numbers from 1). Each phase present is a material, in
9
+ increasing order; the crystals of a phase turned by the orientations of their grains
10
+ have one zone per grain, the other phases one zone;
11
+ * the material file (``<name>_material.xml``): the native law ``elasiso`` for isotropic
12
+ phases (the Lamé coefficients; zero for voids) and ``elasaniso`` for crystals (the
13
+ nine orthotropic constants C11, C12, C13, C22, C23, C33, C66, C55, C44 in the axes of
14
+ the crystal, then the first two axes of the crystal, the first two rows of its
15
+ orientation matrix, in the axes of the sample for each zone, in binary files of
16
+ big-endian doubles); the reference medium of the solver is the mean of the extreme
17
+ moduli, as in morphoGen's FFT solver. The nonlinear materials (von Mises and crystal
18
+ plasticity) are MFront laws (:mod:`morphogen.io.mfront`, in ``mfront/``), compiled by
19
+ the script with the ``umat`` interface (``mfront/src/libUmatBehaviour.so``, the law
20
+ ``umat<behaviour>``), with the coefficients that this interface imposes: YOUN, NU,
21
+ RHO, ALPH (von Mises), or the nine orthotropic constants YG1, YG2, YG3, NU12, NU23,
22
+ NU13, G12, G23, G13, the axes V1, V2 of the crystal in each zone (as those of
23
+ ``elasaniso``), RHO, ALP1, ALP2, ALP3 (crystals); their internal variables start at
24
+ zero;
25
+ * a loading file per run (``<name>_<run>.xml``): the six unit strains of the stiffness
26
+ tensor (one partial loading each; linear materials only), named macroscopic
27
+ loadings, or loading paths (one partial loading per segment);
28
+ * the algorithm file (``<name>_algorithm.xml``), ``<name>_run.sh``, which compiles the
29
+ MFront laws and runs them all with MPI, and ``<name>_amitex.json``, the description of
30
+ the export that :func:`read_amitex_run` reads back with the results.
31
+
32
+ In finite strains (``kinematics="finite"``: ``Small_Perturbations`` false, loading paths
33
+ of the nine components of the displacement gradient and of the nominal stress), every
34
+ phase but the voids is an MFront law, Hencky's elasticity for the elastic ones (AMITEX's
35
+ native laws in finite strains are not morphoGen's): the laws of Hencky's strain measure
36
+ (elasticity, von Mises) are the functions ``umat<behaviour>_malls`` of the interface,
37
+ which compute the logarithmic strain from the deformation gradients that AMITEX gives
38
+ them, those of the deformation gradient (crystals: morphoGen's kernel) ``umat<behaviour>``.
39
+
40
+ AMITEX orders the components of symmetric tensors (xx, yy, zz, xy, xz, yz), with
41
+ engineering shear strains, and those of gradients (xx, yy, zz, xy, xz, yz, yx, zx, zy);
42
+ morphoGen's are (11, 22, 33, 23, 31, 12) and row by row.
43
+
44
+ :func:`read_amitex` reads the averages of a run over the unit cell (``.std``),
45
+ :func:`read_amitex_materials` and :func:`read_amitex_zones` those of its materials
46
+ (``.mstd``) and of the zones of a material (``.zstd``), and :func:`read_amitex_run` the
47
+ runs of an export, with the apparent stiffness of its unit strains;
48
+ :func:`morphogen.io.read_vtk` reads the fields of the runs (``.vtk``).
49
+ """
50
+
51
+ from __future__ import annotations
52
+
53
+ import dataclasses
54
+ import json
55
+ import re
56
+ import shutil
57
+ import xml.etree.ElementTree as ET
58
+ from dataclasses import dataclass, field
59
+ from pathlib import Path
60
+
61
+ import numpy as np
62
+
63
+ from morphogen._version import __version__
64
+ from morphogen.image import VoxelImage
65
+ from morphogen.io.mfront import (
66
+ identifier,
67
+ mfront_state_size,
68
+ mfront_strain_measure,
69
+ mfront_symmetry,
70
+ orthotropic_constants,
71
+ umat_function,
72
+ user_behaviour,
73
+ write_mfront,
74
+ write_parameters,
75
+ )
76
+
77
+ #: AMITEX's names of the components of symmetric tensors, in morphoGen's Voigt order
78
+ #: (11, 22, 33, 23, 31, 12); in finite strains, of the macroscopic components (11, 22,
79
+ #: 33, 23, 13, 12) of gradients and nominal stresses
80
+ COMPONENTS = ("xx", "yy", "zz", "yz", "xz", "xy")
81
+ #: AMITEX's names of the nine components of gradients
82
+ GRADIENT = ("xx", "yy", "zz", "xy", "xz", "yz", "yx", "zx", "zy")
83
+ #: morphoGen's component k of a symmetric tensor is AMITEX's _FROM6[k]
84
+ _FROM6 = np.array([0, 1, 2, 5, 4, 3])
85
+ #: component (11, 12, 13, 21, 22, 23, 31, 32, 33) of a gradient: AMITEX's _FROM9[k]
86
+ _FROM9 = np.array([0, 3, 4, 6, 1, 5, 7, 8, 2])
87
+ #: the macroscopic components (11, 22, 33, 23, 13, 12) of tensors stored row by row
88
+ _MACRO = np.array([0, 4, 8, 5, 2, 1])
89
+ #: Laws of the material file
90
+ LAWS = ("elasiso", "elasaniso")
91
+ #: The library of the MFront laws of the nonlinear materials, compiled by the script of an
92
+ #: export with the umat interface (relative to its directory)
93
+ UMAT_LIBRARY = "mfront/src/libUmatBehaviour.so"
94
+ #: The material properties that the umat interface imposes (glossary names): of isotropic
95
+ #: behaviours, of orthotropic ones before the axes V1, V2 of their material, and after them
96
+ _UMAT_ISOTROPIC = ("YoungModulus", "PoissonRatio", "MassDensity", "ThermalExpansion")
97
+ _UMAT_ORTHOTROPIC = ("YoungModulus1", "YoungModulus2", "YoungModulus3", "PoissonRatio12",
98
+ "PoissonRatio23", "PoissonRatio13", "ShearModulus12", "ShearModulus23",
99
+ "ShearModulus13") # fmt: skip
100
+ _UMAT_TAIL = ("MassDensity", "ThermalExpansion1", "ThermalExpansion2", "ThermalExpansion3")
101
+
102
+
103
+ def _umat_coefficients(m, user, kinematics: str) -> tuple[bool, list[float], list[float]]:
104
+ """Whether the MFront law of a material is orthotropic, and its coefficients for the
105
+ umat interface: those that the interface imposes (the elastic constants of the
106
+ material, its density, no thermal expansion; the values of the material properties of
107
+ the behaviour that have their glossary names), the axes of the zones of orthotropic
108
+ behaviours, then the other material properties of the behaviour (``user``: a
109
+ :class:`~morphogen.io.mfront.UserBehaviour`; None: a law written by morphoGen) in
110
+ order. Returns the coefficients before the axes and those after them."""
111
+ from morphogen.homogenization.materials import isotropic_matrix
112
+
113
+ values = dict(m.mfront.material_properties) if user is not None else {}
114
+ if user is not None:
115
+ orthotropic = user.orthotropic
116
+ else:
117
+ orthotropic = mfront_symmetry(m, kinematics) == "orthotropic"
118
+ if orthotropic:
119
+ stiffness = m.stiffness if m.stiffness is not None else isotropic_matrix(*m.lame)
120
+ default = dict(zip(_UMAT_ORTHOTROPIC, orthotropic_constants(stiffness), strict=True))
121
+ default.update(dict.fromkeys(_UMAT_TAIL, 0.0), MassDensity=m.density or 0.0)
122
+ head = [values.get(k, default[k]) for k in _UMAT_ORTHOTROPIC]
123
+ rest = [values.get(k, default[k]) for k in _UMAT_TAIL]
124
+ imposed = _UMAT_ORTHOTROPIC + _UMAT_TAIL
125
+ else:
126
+ e, nu = (m.young, m.poisson) if m.young is not None else (0.0, 0.0)
127
+ default = {"YoungModulus": e, "PoissonRatio": nu, "MassDensity": m.density or 0.0,
128
+ "ThermalExpansion": 0.0} # fmt: skip
129
+ head = [values.get(k, default[k]) for k in _UMAT_ISOTROPIC]
130
+ rest = []
131
+ imposed = _UMAT_ISOTROPIC
132
+ own = user.properties if user is not None else ()
133
+ return orthotropic, head, rest + [values[k] for k in own if k not in imposed]
134
+
135
+
136
+ # -- inputs ----------------------------------------------------------------------------------
137
+
138
+
139
+ def write_amitex_field(path, values, spacing, origin=(0.0, 0.0, 0.0), name: str = "MaterialId"):
140
+ """An integer field of the voxels as AMITEX_FFTP reads it: legacy VTK with exactly ten
141
+ header lines (``DIMENSIONS``: the numbers of voxels plus one, cell data), then
142
+ big-endian 32-bit integers, x varying fastest."""
143
+ data = np.asarray(values)
144
+ if data.ndim != 3 or data.dtype.kind not in "iub":
145
+ raise ValueError("AMITEX fields: an integer field of the voxels (3D)")
146
+ if data.size and (data.min() < 0 or data.max() >= 2**31):
147
+ raise ValueError("AMITEX fields: values between 0 and 2^31 - 1")
148
+ nx, ny, nz = data.shape
149
+ s = [float(v) for v in spacing]
150
+ o = [float(v) for v in origin]
151
+ head = (
152
+ "# vtk DataFile Version 4.5\n"
153
+ "Materiau\n"
154
+ "BINARY\n"
155
+ "DATASET STRUCTURED_POINTS\n"
156
+ f"DIMENSIONS {nx + 1} {ny + 1} {nz + 1}\n"
157
+ f"ORIGIN {o[0]:.10e} {o[1]:.10e} {o[2]:.10e}\n"
158
+ f"SPACING {s[0]:.10e} {s[1]:.10e} {s[2]:.10e}\n"
159
+ f"CELL_DATA {nx * ny * nz}\n"
160
+ f"SCALARS {name} int\n"
161
+ "LOOKUP_TABLE default\n"
162
+ )
163
+ raw = np.ascontiguousarray(data.transpose(2, 1, 0), dtype=">i4").tobytes()
164
+ path = Path(path)
165
+ path.write_bytes(head.encode("ascii") + raw)
166
+ return path
167
+
168
+
169
+ def _write_bin(path: Path, values) -> Path:
170
+ """Values per zone in AMITEX's binary format: their number, ``double``, then
171
+ big-endian doubles."""
172
+ v = np.ascontiguousarray(np.asarray(values, dtype=float).ravel(), dtype=">f8")
173
+ path.write_bytes(f"{v.size}\ndouble\n".encode("ascii") + v.tobytes())
174
+ return path
175
+
176
+
177
+ def _number(value: float) -> str:
178
+ return repr(float(value))
179
+
180
+
181
+ def _xml(path: Path, root: ET.Element) -> Path:
182
+ ET.indent(root, space=" ")
183
+ text = ET.tostring(root, encoding="unicode")
184
+ path.write_text('<?xml version="1.0" encoding="UTF-8"?>\n' + text + "\n", encoding="utf-8")
185
+ return path
186
+
187
+
188
+ def _orthotropic(stiffness, phase: int) -> list[float]:
189
+ """The nine constants of ``elasaniso`` of a stiffness in the axes of the crystal
190
+ (morphoGen's Voigt order): C11, C12, C13, C22, C23, C33, C66, C55, C44."""
191
+ d = np.asarray(stiffness, dtype=float)
192
+ coupling = np.concatenate([d[:3, 3:].ravel(), d[3:, :3].ravel(),
193
+ d[3:, 3:][~np.eye(3, dtype=bool)]]) # fmt: skip
194
+ if np.abs(coupling).max() > 1e-12 * np.abs(d).max():
195
+ raise ValueError(
196
+ f"phase {phase}: AMITEX's elasaniso is orthotropic in the axes of the crystal; "
197
+ "this stiffness couples normal and shear components"
198
+ )
199
+ return [d[0, 0], d[0, 1], d[0, 2], d[1, 1], d[1, 2], d[2, 2], d[5, 5], d[4, 4], d[3, 3]]
200
+
201
+
202
+ def _components(element: ET.Element, values, controls, finite: bool) -> None:
203
+ """The driving of the components at the end of a partial loading: morphoGen's six
204
+ components (strains where ``controls``), and in finite strains the lower triangle of
205
+ the gradient, zero."""
206
+ for name, value, strain in zip(COMPONENTS, values, controls, strict=True):
207
+ ET.SubElement(element, name, Driving="Strain" if strain else "Stress",
208
+ Evolution="Linear", Value=_number(value)) # fmt: skip
209
+ if finite:
210
+ for name in GRADIENT[6:]:
211
+ ET.SubElement(element, name, Driving="Strain", Evolution="Linear", Value="0")
212
+
213
+
214
+ def write_amitex_loading(path, segments, *, kinematics: str = "small", fields: bool = False):
215
+ """A loading file of AMITEX_FFTP: ``segments`` lists the partial loadings, each a
216
+ tuple (final time, number of increments, the six components at its end, which are
217
+ strains (``controls``)). Components are morphoGen's: Voigt order with engineering
218
+ shear strains in small strains, the macroscopic components (11, 22, 33, 23, 13, 12)
219
+ of the gradient and of the nominal stress in finite strains, the gradient upper
220
+ triangular (as morphoGen's). ``fields``: the stress and strain fields at every
221
+ increment."""
222
+ if kinematics not in ("small", "finite"):
223
+ raise ValueError("kinematics: 'small' or 'finite'")
224
+ root = ET.Element("Loading_Output")
225
+ root.append(ET.Comment(f" morphoGen {__version__} "))
226
+ output = ET.SubElement(root, "Output")
227
+ flag = "1" if fields else "0"
228
+ ET.SubElement(output, "vtk_StressStrain", Strain=flag, Stress=flag)
229
+ for tag, (t_end, n_incr, values, controls) in enumerate(segments, start=1):
230
+ loading = ET.SubElement(root, "Loading", Tag=str(tag))
231
+ ET.SubElement(loading, "Time_Discretization", Discretization="Linear",
232
+ Nincr=str(int(n_incr)), Tfinal=_number(t_end)) # fmt: skip
233
+ _components(loading, values, controls, kinematics == "finite")
234
+ return _xml(Path(path), root)
235
+
236
+
237
+ def _segments(item) -> list[tuple]:
238
+ """Partial loadings of a :class:`Loading` (one, from time 0 to 1) or of a
239
+ :class:`LoadingPath` (one per segment)."""
240
+ from morphogen.homogenization.core import Loading
241
+ from morphogen.homogenization.paths import LoadingPath
242
+
243
+ if isinstance(item, LoadingPath):
244
+ if any(item.temperature):
245
+ raise ValueError("AMITEX: the loadings written carry no change of temperature")
246
+ return [(item.times[k + 1], item.increments[k], item.values[k + 1], item.controls)
247
+ for k in range(len(item.times) - 1)] # fmt: skip
248
+ if isinstance(item, Loading):
249
+ if item.temperature:
250
+ raise ValueError("AMITEX: the loadings written carry no change of temperature")
251
+ if item.physics != "elastic":
252
+ raise ValueError("AMITEX: elastic loadings only")
253
+ if item.kind == "mixed":
254
+ controls = item.controls
255
+ else:
256
+ controls = (item.kind == "strain",) * 6
257
+ return [(1.0, 1, item.value, controls)]
258
+ raise TypeError(f"AMITEX: a Loading or a LoadingPath, got {type(item).__name__}")
259
+
260
+
261
+ def _stiffness_segments() -> list[tuple]:
262
+ """The six unit strains (engineering shears), one partial loading each: in linear
263
+ elasticity, the state at the end of loading k is the column k of the stiffness."""
264
+ unit = np.eye(6)
265
+ return [(float(k + 1), 1, unit[k], (True,) * 6) for k in range(6)]
266
+
267
+
268
+ @dataclass
269
+ class AmitexExport:
270
+ """The files of the AMITEX runs of an image (:func:`write_amitex`): the directory,
271
+ the name of the files, and the run of each loading (its loading file and the root of
272
+ its results, relative to the directory)."""
273
+
274
+ directory: Path
275
+ name: str
276
+ files: list[Path]
277
+ runs: dict[str, dict]
278
+
279
+
280
+ def write_amitex(
281
+ directory,
282
+ image: VoxelImage,
283
+ materials: dict,
284
+ *,
285
+ grains=None,
286
+ orientations=None,
287
+ loadings: dict | None = None,
288
+ paths: dict | None = None,
289
+ stiffness: bool | None = None,
290
+ name: str = "amitex",
291
+ fields: bool = False,
292
+ tolerance: float | None = None,
293
+ library: str = "",
294
+ processes: int = 4,
295
+ elastic_only: bool = False,
296
+ kinematics: str = "small",
297
+ ) -> AmitexExport:
298
+ """The inputs of AMITEX_FFTP runs of a periodic voxel image of phases (see the
299
+ module): ``materials`` (phase -> :class:`~morphogen.homogenization.Material`),
300
+ crystals turned by the orientations of their grains (``grains``: label of each
301
+ voxel, ``orientations``: Bunge angles of each label). The runs: the six unit strains
302
+ of the apparent stiffness (``stiffness``; by default when no loading is given), the
303
+ named ``loadings`` (:class:`~morphogen.homogenization.Loading`) and ``paths``
304
+ (:class:`~morphogen.homogenization.LoadingPath`). ``fields``: stress and strain
305
+ fields at every increment; ``tolerance``: the convergence criterion of AMITEX
306
+ (``Default``: 1e-4); ``library``: the path of ``libUmatAmitex.so`` (empty: the
307
+ native laws found through ``AMITEX_PATH``); ``processes``: MPI processes of the
308
+ script. The nonlinear materials (von Mises and crystal plasticity) are MFront laws,
309
+ which need loadings or paths (not the unit strains of the stiffness); ``elastic_only``
310
+ exports their elasticity instead. ``kinematics``: small or finite strains (paths
311
+ only; every phase but the voids an MFront law)."""
312
+ from morphogen.homogenization.core import Loading
313
+ from morphogen.homogenization.fft import reference_moduli
314
+ from morphogen.homogenization.materials import material_table
315
+ from morphogen.homogenization.paths import LoadingPath
316
+
317
+ if kinematics not in ("small", "finite"):
318
+ raise ValueError("kinematics: 'small' or 'finite'")
319
+ finite = kinematics == "finite"
320
+ directory = Path(directory)
321
+ directory.mkdir(parents=True, exist_ok=True)
322
+ if not re.fullmatch(r"[A-Za-z0-9_.-]+", name):
323
+ raise ValueError(f"name: letters, digits, '_', '-' and '.', got {name!r}")
324
+ phase = np.asarray(image.data)
325
+ if phase.ndim != 3 or phase.dtype.kind not in "iub":
326
+ raise ValueError("AMITEX: a 3D image of integer phases")
327
+ loadings = {str(k): Loading.from_spec(v) for k, v in (loadings or {}).items()}
328
+ paths = {str(k): LoadingPath.from_spec(v) for k, v in (paths or {}).items()}
329
+ if finite and (stiffness or loadings or not paths):
330
+ raise ValueError(
331
+ "AMITEX in finite strains: loading paths only (the unit strains of the stiffness "
332
+ "and the loadings are linear problems)"
333
+ )
334
+ laws = [] # the phases of MFront laws: the nonlinear ones, all in finite strains
335
+ for p in np.unique(phase):
336
+ m = materials.get(int(p))
337
+ if m is not None and not m.void and (finite or (m.nonlinear and not elastic_only)):
338
+ laws.append(int(p))
339
+ if laws and not finite:
340
+ if stiffness or (stiffness is None and not loadings and not paths):
341
+ raise ValueError(
342
+ f"phases {laws}: the unit strains of the apparent stiffness need linear "
343
+ "materials; give loading paths for the nonlinear materials (or elastic_only)"
344
+ )
345
+ table = material_table(phase, materials, "elastic", grains=grains, orientations=orientations)
346
+ files: list[Path] = []
347
+ # materials and zones of the voxels
348
+ mat_ids = (table.stat + 1).reshape(phase.shape)
349
+ zone_ids = np.ones(phase.size, dtype=np.int64)
350
+ root = ET.Element("Materials")
351
+ root.append(ET.Comment(f" morphoGen {__version__}: {len(table.phases)} materials "))
352
+ used = np.unique(table.mat[table.mat >= 0])
353
+ void = any(materials[p].void for p in table.phases)
354
+ pool = table.matrices[used]
355
+ if void:
356
+ pool = np.concatenate([pool, np.zeros((1, 6, 6))])
357
+ lam0, mu0 = reference_moduli(pool, table.isotropic) if pool.size else (0.0, 0.0)
358
+ ET.SubElement(root, "Reference_Material", Lambda0=_number(lam0), Mu0=_number(mu0))
359
+ description = []
360
+ sources: list[str] = []
361
+ parameters: dict[str, tuple] = {}
362
+ for s, p in enumerate(table.phases):
363
+ m = materials[p]
364
+ sel = np.flatnonzero(table.stat == s)
365
+ num = s + 1
366
+ entry = {"material": num, "phase": int(p), "zones": 1}
367
+ law = None
368
+ if p in laws:
369
+ # the MFront law of the material, compiled by the script (umat interface)
370
+ if elastic_only and m.nonlinear: # Hencky's elasticity (finite strains)
371
+ m = dataclasses.replace(m, plasticity=None, crystal_plasticity=None, mfront=None,
372
+ porous_plasticity=None, learned=None) # fmt: skip
373
+ user = user_behaviour(m, kinematics) if m.mfront is not None else None
374
+ if user is None and m.expands:
375
+ raise ValueError(
376
+ f"phase {p}: the thermal expansion of a phase written as an MFront law is "
377
+ "not exported to AMITEX_FFTP (its inputs carry no change of temperature)"
378
+ )
379
+ if user is None:
380
+ behaviour = f"{identifier(name)}Phase{p}"
381
+ source = write_mfront(m, directory / "mfront" / f"{behaviour}.mfront",
382
+ name=behaviour, kinematics=kinematics) # fmt: skip
383
+ n_state = max(mfront_state_size(m, kinematics), 1) # one at least, for Cast3M
384
+ measure = mfront_strain_measure(m, kinematics)
385
+ else: # the user's law: its source, its parameters in the directory of the runs
386
+ behaviour = user.name
387
+ source = directory / "mfront" / user.source.name
388
+ if source.name not in sources:
389
+ source.parent.mkdir(parents=True, exist_ok=True)
390
+ shutil.copyfile(user.source, source)
391
+ n_state = max(user.internal_variables, 1) # one at least, for Cast3M
392
+ measure = user.strain_measure
393
+ if parameters.setdefault(behaviour, m.mfront.parameters) != m.mfront.parameters:
394
+ raise ValueError(f"phase {p}: the parameters of {behaviour} are global")
395
+ written = write_parameters(directory, behaviour, m.mfront.parameters)
396
+ if written is not None and written not in files:
397
+ files.append(written)
398
+ if source.name not in sources:
399
+ sources.append(source.name)
400
+ files.append(source)
401
+ law = umat_function(behaviour, measure)
402
+ orthotropic, head, rest = _umat_coefficients(m, user, kinematics)
403
+ entry.update(mfront=f"mfront/{source.name}", library=UMAT_LIBRARY,
404
+ internal_variables=n_state) # fmt: skip
405
+ if m.void or (law is None and m.stiffness is None) or (law and not orthotropic):
406
+ kind = "void" if m.void else "isotropic"
407
+ root.append(ET.Comment(f" phase {p}: {kind}{', MFront law' if law else ''} "))
408
+ if law:
409
+ # the coefficients of the umat interface: YOUN, NU, RHO, ALPH, then the
410
+ # other material properties of the behaviour
411
+ el = ET.SubElement(root, "Material", numM=str(num), Lib=UMAT_LIBRARY, Law=law)
412
+ coefficients = head + rest
413
+ else:
414
+ el = ET.SubElement(root, "Material", numM=str(num), Lib=library, Law="elasiso")
415
+ coefficients = (0.0, 0.0) if m.void else m.lame
416
+ for k, value in enumerate(coefficients, start=1):
417
+ ET.SubElement(el, "Coeff", Index=str(k), Type="Constant", Value=_number(value))
418
+ if law:
419
+ for k in range(1, n_state + 1):
420
+ ET.SubElement(el, "IntVar", Index=str(k), Type="Constant", Value="0.")
421
+ entry["law"] = law or "elasiso"
422
+ else:
423
+ ids = table.mat[sel]
424
+ first = int(ids.min())
425
+ zone_ids[sel] = ids - first + 1
426
+ rotations = table.rotations[first : int(ids.max()) + 1]
427
+ n_zones = len(rotations)
428
+ what = "crystal, MFront law" if law else "crystal"
429
+ root.append(ET.Comment(f" phase {p}: {what}, {n_zones} zones (grains) "))
430
+ if law:
431
+ # the coefficients of the umat interface: YG1, YG2, YG3, NU12, NU23, NU13,
432
+ # G12, G23, G13, the axes V1 and V2 of each zone, RHO, ALP1, ALP2, ALP3,
433
+ # then the other material properties of the behaviour
434
+ el = ET.SubElement(root, "Material", numM=str(num), Lib=UMAT_LIBRARY, Law=law)
435
+ constants = head
436
+ else:
437
+ el = ET.SubElement(root, "Material", numM=str(num), Lib=library, Law="elasaniso")
438
+ constants = _orthotropic(m.stiffness, p)
439
+ for k, value in enumerate(constants, start=1):
440
+ ET.SubElement(el, "Coeff", Index=str(k), Type="Constant", Value=_number(value))
441
+ for k, (row, axis) in enumerate([(r, a) for r in (0, 1) for a in range(3)]):
442
+ target = directory / f"{name}_M{num}_N{row + 1}{'XYZ'[axis]}.bin"
443
+ files.append(_write_bin(target, rotations[:, row, axis]))
444
+ ET.SubElement(el, "Coeff", Index=str(10 + k), Type="Constant_Zone",
445
+ File=target.name, Format="binary") # fmt: skip
446
+ if law:
447
+ for k, value in enumerate(rest, start=16):
448
+ ET.SubElement(el, "Coeff", Index=str(k), Type="Constant",
449
+ Value=_number(value)) # fmt: skip
450
+ for k in range(1, (n_state if law else 6) + 1):
451
+ ET.SubElement(el, "IntVar", Index=str(k), Type="Constant", Value="0.")
452
+ entry.update(law=law or "elasaniso", zones=n_zones)
453
+ if grains is not None and orientations is not None and m.oriented("elastic"):
454
+ labels = np.asarray(grains).ravel()[sel]
455
+ order = np.argsort(ids, kind="stable")
456
+ _, start = np.unique(ids[order], return_index=True)
457
+ entry["grains"] = [int(g) for g in labels[order][start]]
458
+ description.append(entry)
459
+ files.append(write_amitex_field(directory / f"{name}_materials.vtk", mat_ids, image.spacing,
460
+ image.origin, "MaterialId")) # fmt: skip
461
+ files.append(write_amitex_field(directory / f"{name}_zones.vtk",
462
+ zone_ids.reshape(phase.shape), image.spacing, image.origin,
463
+ "ZoneId")) # fmt: skip
464
+ files.append(_xml(directory / f"{name}_material.xml", root))
465
+ # algorithm
466
+ algo = ET.Element("Algorithm_Parameters")
467
+ a = ET.SubElement(algo, "Algorithm", Type="Basic_Scheme")
468
+ crit = "Default" if tolerance is None else _number(tolerance)
469
+ ET.SubElement(a, "Convergence_Criterion", Value=crit)
470
+ ET.SubElement(a, "Convergence_Acceleration", Value="true")
471
+ mech = ET.SubElement(algo, "Mechanics")
472
+ ET.SubElement(mech, "Filter", Type="Default")
473
+ ET.SubElement(mech, "Small_Perturbations", Value="false" if finite else "true")
474
+ files.append(_xml(directory / f"{name}_algorithm.xml", algo))
475
+ # loadings
476
+ runs: dict[str, dict] = {}
477
+ if stiffness or (stiffness is None and not loadings and not paths):
478
+ runs["stiffness"] = {"kind": "stiffness", "segments": _stiffness_segments()}
479
+ for key, item in loadings.items():
480
+ runs[str(key)] = {"kind": "loading", "segments": _segments(item)}
481
+ for key, item in paths.items():
482
+ runs[str(key)] = {"kind": "path", "segments": _segments(item)}
483
+ lines = [
484
+ "#!/bin/sh",
485
+ f"# morphoGen {__version__}: the AMITEX_FFTP runs of {name} (set AMITEX_PATH for "
486
+ "the native laws of the material file)",
487
+ 'cd "$(dirname "$0")" || exit 1',
488
+ "mkdir -p results",
489
+ ]
490
+ if sources:
491
+ lines += [
492
+ "# the MFront laws of the materials (TFEL's mfront on the PATH)",
493
+ f"(cd mfront && mfront --obuild --interface=umat {' '.join(sources)}) || exit 1",
494
+ ]
495
+ manifest_runs = {}
496
+ for key, run in runs.items():
497
+ if not re.fullmatch(r"[A-Za-z0-9_.-]+", key):
498
+ raise ValueError(f"loading names: letters, digits, '_', '-' and '.', got {key!r}")
499
+ loading = directory / f"{name}_{key}.xml"
500
+ files.append(write_amitex_loading(loading, run["segments"], kinematics=kinematics,
501
+ fields=fields)) # fmt: skip
502
+ result = f"results/{name}_{key}"
503
+ lines.append(
504
+ f"mpirun -np ${{NP:-{int(processes)}}} amitex_fftp -nm {name}_materials.vtk "
505
+ f"-nz {name}_zones.vtk -m {name}_material.xml -c {loading.name} "
506
+ f"-a {name}_algorithm.xml -s {result}"
507
+ )
508
+ manifest_runs[key] = {
509
+ "kind": run["kind"],
510
+ "loading": loading.name,
511
+ "results": result,
512
+ "times": [float(seg[0]) for seg in run["segments"]],
513
+ }
514
+ script = directory / f"{name}_run.sh"
515
+ script.write_text("\n".join(lines) + "\n", encoding="utf-8")
516
+ files.append(script)
517
+ manifest = {
518
+ "morphogen": __version__,
519
+ "name": name,
520
+ "shape": [int(n) for n in phase.shape],
521
+ "spacing": [float(v) for v in image.spacing],
522
+ "origin": [float(v) for v in image.origin],
523
+ "volume": float(np.prod(np.asarray(phase.shape) * np.asarray(image.spacing))),
524
+ "kinematics": kinematics,
525
+ "materials": description,
526
+ "reference": {"lambda0": float(lam0), "mu0": float(mu0)},
527
+ "runs": manifest_runs,
528
+ }
529
+ target = directory / f"{name}_amitex.json"
530
+ target.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
531
+ files.append(target)
532
+ return AmitexExport(directory=directory, name=name, files=files, runs=manifest_runs)
533
+
534
+
535
+ # -- results ---------------------------------------------------------------------------------
536
+
537
+ #: A number written by Fortran without the letter of its exponent (0.49801817-310)
538
+ _FORTRAN = re.compile(r"^([+-]?(?:\d+\.\d*|\.\d+|\d+))([+-]\d+)$")
539
+
540
+
541
+ def _value(token: str) -> float:
542
+ try:
543
+ return float(token)
544
+ except ValueError:
545
+ match = _FORTRAN.match(token)
546
+ if match is None:
547
+ raise ValueError(f"not a number: {token!r}") from None
548
+ return float(f"{match.group(1)}e{match.group(2)}")
549
+
550
+
551
+ def _table(path) -> tuple[list[str], np.ndarray]:
552
+ """The comment lines and the rows of numbers of an output file of AMITEX."""
553
+ comments, rows = [], []
554
+ for line in Path(path).read_text(encoding="utf-8", errors="replace").splitlines():
555
+ text = line.strip()
556
+ if not text:
557
+ continue
558
+ if text.startswith("#"):
559
+ comments.append(text)
560
+ continue
561
+ rows.append([_value(t) for t in text.split()])
562
+ if not rows:
563
+ raise ValueError(f"{path}: no values")
564
+ width = len(rows[0])
565
+ if any(len(r) != width for r in rows):
566
+ raise ValueError(f"{path}: rows of different lengths")
567
+ return comments, np.array(rows)
568
+
569
+
570
+ @dataclass
571
+ class AmitexResult:
572
+ """Averages over the unit cell, a material or a zone at the output increments of an
573
+ AMITEX_FFTP run, in morphoGen's orders. In small strains, ``stress`` and ``strain``
574
+ (Voigt 11, 22, 33, 23, 31, 12; engineering shear strains); in finite strains, the
575
+ macroscopic components (11, 22, 33, 23, 13, 12) of the first Piola-Kirchhoff stress
576
+ and of the displacement gradient, their nine components (row by row) in ``pk1`` and
577
+ ``gradient``, the Cauchy stress and the Green-Lagrange strain (Voigt).
578
+ ``stress_std``, ``strain_std``: the standard deviations over the voxels;
579
+ ``iterations``: those of each increment (unit cell); ``extra``: the other columns
580
+ (the internal variables of the zones)."""
581
+
582
+ kinematics: str
583
+ times: np.ndarray
584
+ stress: np.ndarray
585
+ strain: np.ndarray
586
+ stress_std: np.ndarray
587
+ strain_std: np.ndarray
588
+ iterations: np.ndarray | None = None
589
+ cauchy: np.ndarray | None = None
590
+ green_lagrange: np.ndarray | None = None
591
+ pk1: np.ndarray | None = None
592
+ gradient: np.ndarray | None = None
593
+ extra: np.ndarray | None = None
594
+
595
+
596
+ def _kinematics(comments, width: int, kinematics: str | None) -> str:
597
+ if kinematics is not None:
598
+ if kinematics not in ("small", "finite"):
599
+ raise ValueError("kinematics: 'small' or 'finite'")
600
+ return kinematics
601
+ if any("xx,yy,zz,xy,xz,yz,yx,zx,zy" in c.replace(" ", "") for c in comments) or width >= 61:
602
+ return "finite"
603
+ return "small"
604
+
605
+
606
+ def _result(rows: np.ndarray, kinematics: str, *, unit_cell: bool) -> AmitexResult:
607
+ """The quantities of rows of an output file: in small strains time, stress (6),
608
+ strain (6) and their standard deviations; in finite strains time, Cauchy stress (6),
609
+ first Piola-Kirchhoff stress (9), Green-Lagrange strain (6), displacement gradient
610
+ (9) and their standard deviations; then, for the unit cell, the iterations."""
611
+ width = rows.shape[1]
612
+ times = rows[:, 0]
613
+ if kinematics == "small":
614
+ if width < 25:
615
+ raise ValueError(f"AMITEX averages in small strains: 25 columns, got {width}")
616
+ rest = rows[:, 25:]
617
+ out = AmitexResult(
618
+ kinematics, times, rows[:, 1:7][:, _FROM6], rows[:, 7:13][:, _FROM6],
619
+ rows[:, 13:19][:, _FROM6], rows[:, 19:25][:, _FROM6],
620
+ ) # fmt: skip
621
+ else:
622
+ if width < 61:
623
+ raise ValueError(f"AMITEX averages in finite strains: 61 columns, got {width}")
624
+ pk1, grad = rows[:, 7:16][:, _FROM9], rows[:, 22:31][:, _FROM9]
625
+ rest = rows[:, 61:]
626
+ out = AmitexResult(
627
+ kinematics, times, pk1[:, _MACRO], grad[:, _MACRO],
628
+ rows[:, 37:46][:, _FROM9][:, _MACRO], rows[:, 52:61][:, _FROM9][:, _MACRO],
629
+ cauchy=rows[:, 1:7][:, _FROM6], green_lagrange=rows[:, 16:22][:, _FROM6],
630
+ pk1=pk1, gradient=grad,
631
+ ) # fmt: skip
632
+ if unit_cell and rest.shape[1]:
633
+ out.iterations = rest[:, 0].astype(int)
634
+ rest = rest[:, 1:]
635
+ if rest.shape[1]:
636
+ out.extra = rest
637
+ return out
638
+
639
+
640
+ def _results_path(prefix, suffix: str) -> Path:
641
+ path = Path(prefix)
642
+ return path if path.suffix == suffix else path.parent / f"{path.name}{suffix}"
643
+
644
+
645
+ def read_amitex(prefix, *, kinematics: str | None = None) -> AmitexResult:
646
+ """The averages over the unit cell of an AMITEX_FFTP run (``<prefix>.std``, the root
647
+ of its results); small or finite strains are recognized from the header or the
648
+ number of columns, unless given."""
649
+ path = _results_path(prefix, ".std")
650
+ comments, rows = _table(path)
651
+ return _result(rows, _kinematics(comments, rows.shape[1], kinematics), unit_cell=True)
652
+
653
+
654
+ def _grouped(path, kinematics: str | None) -> dict[int, AmitexResult]:
655
+ """The averages of the materials or zones of a file whose increments have one row
656
+ each, at the same time, numbered from 1."""
657
+ comments, rows = _table(path)
658
+ times = rows[:, 0]
659
+ breaks = np.flatnonzero(np.diff(times) != 0) + 1
660
+ sizes = np.diff(np.concatenate([[0], breaks, [len(times)]]))
661
+ if np.any(sizes != sizes[0]):
662
+ raise ValueError(f"{path}: increments with different numbers of rows")
663
+ n = int(sizes[0])
664
+ kin = _kinematics(comments, rows.shape[1], kinematics)
665
+ return {k + 1: _result(rows[k::n], kin, unit_cell=False) for k in range(n)}
666
+
667
+
668
+ def read_amitex_materials(prefix, *, kinematics: str | None = None) -> dict[int, AmitexResult]:
669
+ """The averages over each material (``<prefix>.mstd``), by material number."""
670
+ return _grouped(_results_path(prefix, ".mstd"), kinematics)
671
+
672
+
673
+ def read_amitex_zones(prefix, material: int, *, kinematics: str | None = None):
674
+ """The averages over each zone of a material (``<prefix>_<material>.zstd``), by zone
675
+ number; their internal variables in ``extra``."""
676
+ path = Path(prefix)
677
+ path = path.parent / f"{path.name}_{int(material)}.zstd"
678
+ return _grouped(path, kinematics)
679
+
680
+
681
+ @dataclass
682
+ class AmitexRun:
683
+ """The runs of an export (:func:`write_amitex`) and their results: the description of
684
+ the export, the averages of each run (``results``; runs without results are left
685
+ out), the apparent stiffness of the unit strains and its properties."""
686
+
687
+ manifest: dict
688
+ results: dict[str, AmitexResult] = field(default_factory=dict)
689
+ stiffness: np.ndarray | None = None
690
+ properties: dict[str, float] = field(default_factory=dict)
691
+
692
+
693
+ def amitex_stiffness(result: AmitexResult, times=(1.0, 2.0, 3.0, 4.0, 5.0, 6.0)) -> np.ndarray:
694
+ """The apparent stiffness (Voigt, engineering shears) of a run of the six unit strains:
695
+ its column k is the stress at the end of the partial loading k (``times``)."""
696
+ columns = []
697
+ for t in times:
698
+ hit = np.flatnonzero(np.isclose(result.times, t, rtol=1e-9, atol=1e-12))
699
+ if hit.size == 0:
700
+ raise ValueError(f"no output at the end of the unit strain at t = {t:g}")
701
+ columns.append(result.stress[hit[-1]])
702
+ return np.column_stack(columns)
703
+
704
+
705
+ def read_amitex_run(directory, name: str | None = None) -> AmitexRun:
706
+ """The results of the runs of an export (``<name>_amitex.json`` in ``directory``;
707
+ the only one there by default): the averages of each run whose results exist, and
708
+ for the unit strains the apparent stiffness, the bulk modulus (``C_ij`` summed over
709
+ the normal components, over 9), the shear modulus (``C66``, plane 12), the moduli of
710
+ its isotropic projection and its engineering constants."""
711
+ from morphogen.homogenization.apparent import isotropic_projection
712
+ from morphogen.homogenization.postprocess import engineering_constants
713
+
714
+ directory = Path(directory)
715
+ if name is None:
716
+ found = sorted(directory.glob("*_amitex.json"))
717
+ if len(found) != 1:
718
+ raise ValueError(f"{directory}: give the name of the export ({len(found)} found)")
719
+ target = found[0]
720
+ else:
721
+ target = directory / f"{name}_amitex.json"
722
+ manifest = json.loads(target.read_text(encoding="utf-8"))
723
+ out = AmitexRun(manifest=manifest)
724
+ for key, run in manifest["runs"].items():
725
+ prefix = directory / run["results"]
726
+ if not _results_path(prefix, ".std").exists():
727
+ continue
728
+ result = read_amitex(prefix, kinematics=manifest.get("kinematics", "small"))
729
+ out.results[key] = result
730
+ if run["kind"] == "stiffness":
731
+ c = amitex_stiffness(result, run["times"])
732
+ out.stiffness = c
733
+ bulk, shear = isotropic_projection(c)
734
+ out.properties.update(
735
+ bulk_modulus=float(c[:3, :3].sum() / 9.0),
736
+ shear_modulus=float(c[5, 5]),
737
+ isotropic_bulk=float(bulk),
738
+ isotropic_shear=float(shear),
739
+ **engineering_constants(c),
740
+ )
741
+ return out