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/pipeline.py ADDED
@@ -0,0 +1,978 @@
1
+ """Execution of configurations: batches of realizations and RVE studies.
2
+
3
+ Outputs of a run (in ``outputs.directory``):
4
+
5
+ * ``<name>_<index>.<ext>`` files of each realization (geometry, images, voxel meshes...;
6
+ conforming tetrahedral meshes are ``<name>_<index>_tet.<ext>``, and local fields
7
+ ``<name>_<index>_<property>_<bc>.vtu`` or ``.vti``);
8
+ * ``results.csv`` (``results_task<i>of<n>.csv`` for split runs): one row per realization
9
+ with its seed, measurements and apparent properties (columns ``<property>.<bc>``; of a
10
+ stiffness, the upper triangles of the stiffness ``stiffness.<bc>.C11`` ... ``C66`` and
11
+ of its compliance ``stiffness.<bc>.S11`` ... ``S66``, in the notation that ``run.json``
12
+ states, beside its engineering constants), the solid fraction, and the relative,
13
+ normalized (per unit of solid fraction) and specific values of the moduli and
14
+ conductivities (:mod:`morphogen.homogenization.postprocess`);
15
+ * ``homogenization.csv`` (``homogenization_task<i>of<n>.csv``): one row per realization,
16
+ apparent property (or named loading or path) and boundary condition, with the
17
+ macroscopic response, the energy estimate, the isotropy criterion and the solver data;
18
+ * ``<name>_<index>_<path>_<bc>.csv``: the macroscopic curves of each loading path (time,
19
+ strain, stress, temperature, mean cumulated plastic strain, and the mean stress and
20
+ plastic strain of each phase), and with ``fields`` the element fields at the end of
21
+ each of its segments (``..._<k>.vtu``);
22
+ * with ``outputs.tables``, these tables also as ``.txt`` (tab-separated) or ``.xlsx``;
23
+ * with a ``visualization`` section, the figures and videos of the first realizations
24
+ (``<name>_<index>_<view>.<format>``, see :mod:`morphogen.viz.workflow`): sections and
25
+ orthoslices of the image, views of the mesh, fields on the deformed mesh, curves;
26
+ * ``run.json``: configuration, theoretical values, versions and timing (and the notation
27
+ of the stiffness and compliance, ``stiffness_notation``, when they are computed);
28
+ * with ``outputs.database``, the run is added to that database of the configurations
29
+ tested (:mod:`morphogen.results`);
30
+ * for RVE studies, ``rve_report.json`` / ``.md`` / ``.tex`` and figures (when matplotlib
31
+ is installed): statistics, scaling-law fits and RVE sizes (see :mod:`morphogen.rve`);
32
+ with the stiffness, per boundary condition and size the mean stiffness ``Cbar``, its
33
+ compliance ``S = Cbar^-1`` and the standard deviation of each component, with the RVE
34
+ size of each component (``rve_stiffness.csv``, ``rve_stiffness_<bc>.png``; the
35
+ conductivity tensor likewise, ``rve_conductivity_tensor.csv``);
36
+ * for window studies, ``results.csv`` has one row per window size (``window_edge``,
37
+ ``volume``, the number ``n`` of windows): the statistics of the volume fraction
38
+ (``mean``, ``variance``, ``relative_error``) and, of each tensor of the windows
39
+ (:mod:`morphogen.rve.windows`: the homogenization computing ``stiffness`` or
40
+ ``conductivity_tensor`` by FFT), the components of their mean ``<tensor>.periodic.C11``
41
+ ..., of its inverse ``S11`` ... and their standard deviations ``C11_std`` ...; ``run.json``
42
+ holds the apparent tensors of the whole realization (``apparent``). With ``rve.shifts``
43
+ (> 1), the tilings shifted around the periodic realization (:mod:`morphogen.rve.scaling`)
44
+ add the column ``tilings`` after ``n``, then the windows of one tiling: the means over all
45
+ the windows, the variances pooled within the tilings, from the same solutions.
46
+ """
47
+
48
+ from __future__ import annotations
49
+
50
+ import csv
51
+ import json
52
+ import logging
53
+ import platform
54
+ import sys
55
+ import time
56
+ from pathlib import Path
57
+
58
+ import numpy as np
59
+
60
+ from morphogen import io, parallel, rve, settings
61
+ from morphogen._utils import to_jsonable
62
+ from morphogen._version import __version__
63
+ from morphogen.analysis.basic import phase_fractions
64
+ from morphogen.analysis.measures import measure
65
+ from morphogen.config import (
66
+ HomogenizationSpec,
67
+ RunConfig,
68
+ RVESpec,
69
+ path_quantities,
70
+ property_entries,
71
+ )
72
+ from morphogen.domain import Domain
73
+ from morphogen.homogenization import Apparent, PathResult, Response, bounds, homogenize
74
+ from morphogen.homogenization.apparent import COUPLED, FLOW, HARMONIC
75
+ from morphogen.homogenization.beremin import path_beremin
76
+ from morphogen.homogenization.coupled import coupled_entries
77
+ from morphogen.homogenization.fatigue import path_fatigue
78
+ from morphogen.homogenization.materials import any_oriented
79
+ from morphogen.homogenization.postprocess import NOTATION, matrix_entries, normalized_values
80
+ from morphogen.homogenization.xfem import LevelSetSample
81
+ from morphogen.io.tables import write_table
82
+ from morphogen.mesh.conforming import conforming_mesh
83
+ from morphogen.mesh.surface import surface_mesh
84
+ from morphogen.mesh.tetra import TetMesh
85
+ from morphogen.mesh.voxel import voxel_mesh
86
+ from morphogen.models.base import Microstructure, Model
87
+ from morphogen.models.implicit import implicit_functions
88
+ from morphogen.rve import report as rve_report
89
+ from morphogen.seeding import derive_seed
90
+ from morphogen.stopping import checkpoint
91
+ from morphogen.viz.workflow import element_arrays
92
+
93
+ log = logging.getLogger("morphogen")
94
+
95
+
96
+ def versions() -> dict:
97
+ """The versions of morphoGen, Python, NumPy, SciPy, Numba (and pymmg) and the platform, recorded
98
+ with the results."""
99
+ import numba
100
+ import scipy
101
+
102
+ out = {
103
+ "morphogen": __version__,
104
+ "python": sys.version.split()[0],
105
+ "numpy": np.__version__,
106
+ "scipy": scipy.__version__,
107
+ "numba": numba.__version__,
108
+ "platform": platform.platform(),
109
+ }
110
+ try:
111
+ from importlib.metadata import version
112
+
113
+ out["pymmg"] = version("pymmg")
114
+ except Exception:
115
+ pass
116
+ return out
117
+
118
+
119
+ def write_rows(path: Path, rows: list[dict]) -> Path:
120
+ """Rows (mappings) written as a CSV file, the union of their keys as columns in their order of
121
+ appearance."""
122
+ keys: list[str] = []
123
+ for row in rows:
124
+ keys.extend(k for k in row if k not in keys)
125
+ with open(path, "w", encoding="utf-8", newline="") as f:
126
+ writer = csv.DictWriter(f, fieldnames=keys, lineterminator="\n")
127
+ writer.writeheader()
128
+ for row in rows:
129
+ writer.writerow({k: row.get(k, "") for k in keys})
130
+ return path
131
+
132
+
133
+ def read_rows(path) -> list[dict]:
134
+ """The rows of a CSV file as mappings, its numbers as floats."""
135
+
136
+ def parse(v):
137
+ try:
138
+ return float(v)
139
+ except ValueError:
140
+ return v
141
+
142
+ with open(Path(path), encoding="utf-8", newline="") as f:
143
+ return [{k: parse(v) for k, v in row.items()} for row in csv.DictReader(f)]
144
+
145
+
146
+ def _task_name(stem: str, task_id: int, n_tasks: int) -> str:
147
+ return f"{stem}.csv" if n_tasks == 1 else f"{stem}_task{task_id}of{n_tasks}.csv"
148
+
149
+
150
+ def _results_name(task_id: int, n_tasks: int) -> str:
151
+ return _task_name("results", task_id, n_tasks)
152
+
153
+
154
+ _COMPONENTS = ("11", "22", "33", "23", "31", "12")
155
+
156
+
157
+ def _field_arrays(result: Apparent) -> dict[str, np.ndarray]:
158
+ """Derived local fields of a solution (element values, last axis: components)."""
159
+ return element_arrays(result.solution.fields, result.solution.physics)
160
+
161
+
162
+ def _point_orientations(sample, grains) -> np.ndarray | None:
163
+ """The Bunge angles of the crystal of each point of the fields of a sample (the
164
+ voxels of an image with its ``grains``: labels and orientations; the elements of a
165
+ mesh of grains), or None without crystals."""
166
+ if grains is not None:
167
+ labels = np.asarray(getattr(grains[0], "data", grains[0]))
168
+ return np.asarray(grains[1], dtype=float)[labels]
169
+ cell = getattr(sample, "cell", None)
170
+ orientations = getattr(sample, "orientations", None)
171
+ if cell is not None and orientations is not None:
172
+ return np.asarray(orientations, dtype=float)[np.asarray(cell)]
173
+ return None
174
+
175
+
176
+ def write_path_fields(target: Path, support, arrays: dict) -> Path:
177
+ """Fields of a loading path at one time (:attr:`PathResult.fields`) on their support:
178
+ ``.vtu`` of a mesh, the displacement of the nodes as point data, the other fields as
179
+ cell data; ``.vti`` of an image, one array per component (``stress_11`` ...,
180
+ ``displacement_1`` ..., the displacement at the centres of the voxels). The suffix of
181
+ ``target`` is replaced by that of the format; returns the path of the file written."""
182
+ values = {n: np.asarray(v, dtype=np.float32) for n, v in arrays.items()}
183
+ if isinstance(support, TetMesh):
184
+ cell = {n: v for n, v in values.items() if n != "displacement"}
185
+ nodal = {n: v for n, v in values.items() if n == "displacement"}
186
+ return io.write_vtu_tet(Path(target).with_suffix(".vtu"), support, cell, nodal)
187
+ images = []
188
+ for name, v in values.items():
189
+ if v.ndim == 3:
190
+ images.append(support.with_data(v, name=name))
191
+ continue
192
+ labels = _COMPONENTS if v.shape[-1] == 6 else [str(c + 1) for c in range(v.shape[-1])]
193
+ for c, label in enumerate(labels):
194
+ component = np.ascontiguousarray(v[..., c])
195
+ images.append(support.with_data(component, name=f"{name}_{label}"))
196
+ return io.write_vti(Path(target).with_suffix(".vti"), images)
197
+
198
+
199
+ def read_path_texture(path) -> tuple[np.ndarray, np.ndarray]:
200
+ """The lattices of the crystals in a file of the fields of a loading path
201
+ (:func:`write_path_fields`: a ``.vti`` of the voxels of an image, a ``.vtu`` of the
202
+ elements of a mesh): their orientations (Bunge angles in degrees, m x 3) and their
203
+ volumes (m; those of the elements, or one per voxel). The fields have these
204
+ orientations for crystals in finite strains, or whose twins turn their lattices."""
205
+ path = Path(path)
206
+ if path.suffix.lower() == ".vti":
207
+ from morphogen.io.vtk import vti_names
208
+
209
+ names = [f"orientation_{c}" for c in "123"]
210
+ missing = [n for n in names if n not in vti_names(path)]
211
+ if missing:
212
+ raise ValueError(f"{path}: no orientation of the lattices among its fields")
213
+ arrays = {image.name: image.data for image in io.read_vti(path, names=names)}
214
+ euler = np.stack([np.asarray(arrays[n], dtype=float).ravel() for n in names], axis=1)
215
+ weights = np.ones(len(euler))
216
+ elif path.suffix.lower() == ".vtu":
217
+ from morphogen.mesh.tetra import element_volumes
218
+
219
+ grid = io.read_vtu(path)
220
+ if "orientation" not in grid["cell_data"]:
221
+ raise ValueError(f"{path}: no orientation of the lattices among its fields")
222
+ euler = np.asarray(grid["cell_data"]["orientation"], dtype=float).reshape(-1, 3)
223
+ weights = np.abs(element_volumes(grid["points"], grid["cells"][:, :4]))
224
+ else:
225
+ raise ValueError(f"{path}: the fields of a path are a .vti or a .vtu file")
226
+ crystals = ~np.isnan(euler).any(axis=1)
227
+ if not crystals.any():
228
+ raise ValueError(f"{path}: no crystal has an orientation")
229
+ return euler[crystals], weights[crystals]
230
+
231
+
232
+ def _write_fields(result: Apparent, path_stem: Path) -> Path:
233
+ """Local fields of a solution: ``.vtu`` on its mesh, ``.vti`` on its image."""
234
+ support = result.solution.support
235
+ arrays = _field_arrays(result)
236
+ if isinstance(support, TetMesh):
237
+ fields = result.solution.fields
238
+ nodal = {}
239
+ if "displacement" in fields:
240
+ nodal["displacement"] = fields["displacement"]
241
+ if "temperature" in fields:
242
+ nodal["temperature"] = fields["temperature"]
243
+ cell = {k: np.asarray(v, dtype=np.float32) for k, v in arrays.items()}
244
+ return io.write_vtu_tet(path_stem.with_suffix(".vtu"), support, cell, nodal)
245
+ images = [support.with_data(np.asarray(v, dtype=np.float32), name=k) for k, v in arrays.items()]
246
+ return io.write_vti(path_stem.with_suffix(".vti"), images)
247
+
248
+
249
+ def _mesh_fractions(mesh: TetMesh, materials) -> dict[int, float]:
250
+ """Volume fractions of the phases of a mesh; a phase left out of the mesh (the pores
251
+ of porous media) takes the rest of the box."""
252
+ fractions = mesh.phase_fractions()
253
+ absent = [p for p in materials if p not in fractions]
254
+ if len(absent) == 1:
255
+ fractions[absent[0]] = max(0.0, 1.0 - sum(fractions.values()))
256
+ return dict(sorted(fractions.items()))
257
+
258
+
259
+ def _homogenize(
260
+ sample,
261
+ spec: HomogenizationSpec,
262
+ stem: str,
263
+ outdir: Path,
264
+ grains=None,
265
+ quantities=(),
266
+ *,
267
+ keep=False,
268
+ tables=(),
269
+ entries=(),
270
+ ):
271
+ """Apparent properties of one sample (mesh or image; ``grains``: labels and
272
+ orientations of the grains of an image): wide values, long rows and the results.
273
+ ``quantities`` (:class:`~morphogen.homogenization.paths.PathQuantity`) of the loading
274
+ paths add long rows (``property``, ``bc``, ``value``) for the statistics of RVE
275
+ studies, as do the ``entries`` ``(property, entry)`` of the strong couplings and of the
276
+ harmonic properties (rows ``<property>.<entry>``). ``keep``: the fields kept for the
277
+ figures and videos (true, or ``"steps"`` for the loading paths); ``tables``: formats of
278
+ the curves of the paths besides .csv."""
279
+ extra = {} if grains is None else {"grains": grains[0], "orientations": grains[1]}
280
+ # the fatigue of a cycle and the criterion of Beremin read the stresses of each step
281
+ judged = spec.fatigue or spec.beremin
282
+ fields = "steps" if keep == "steps" or judged else bool(spec.fields or keep)
283
+ results = homogenize(sample, spec.materials, **spec.options(), fields=fields, **extra)
284
+ values: dict = {}
285
+ rows: list[dict] = []
286
+ for key, res in results.items():
287
+ if isinstance(res, PathResult):
288
+ if spec.fatigue and res.name == spec.fatigue["path"] and res.fields:
289
+ cycle = path_fatigue(res, spec.fatigue["criteria"], cycle=spec.fatigue["cycle"])
290
+ res.scalars.update({f"fatigue_{n}": v for n, v in cycle.components().items()})
291
+ # with the fields of the end of the path, for its figures
292
+ res.fields[max(res.fields)].update(cycle.fields())
293
+ target = outdir / f"{stem}_{key.replace('.', '_')}_fatigue.vtu"
294
+ written = write_path_fields(target, res.support, cycle.fields())
295
+ log.info(
296
+ "fatigue of %s: largest utilization %.4g, factor of safety %.4g, %.3g %% "
297
+ "of the points beyond their limit; fields: %s",
298
+ key, cycle.largest, cycle.safety, 100 * cycle.fraction(), written.name,
299
+ ) # fmt: skip
300
+ if spec.beremin and res.name == spec.beremin["path"] and res.fields:
301
+ found = path_beremin(res, spec.beremin["criterion"],
302
+ orientations=_point_orientations(sample, grains)) # fmt: skip
303
+ res.series.update(found.series(res.times) or {})
304
+ res.fields[max(res.fields)].update(found.fields())
305
+ target = outdir / f"{stem}_{key.replace('.', '_')}_beremin.vtu"
306
+ written = write_path_fields(target, res.support, found.fields())
307
+ log.info(
308
+ "cleavage of %s (Beremin): largest Weibull stress %.5g, probability of "
309
+ "failure %.4g; field: %s",
310
+ key, found.largest, float(found.probability[-1]), written.name,
311
+ ) # fmt: skip
312
+ values.update({f"{key}.{n}": v for n, v in res.components().items()})
313
+ rows.append(res.row())
314
+ for q in quantities:
315
+ if q.path == res.name and q.bc in (None, res.bc):
316
+ rows.append({"property": q.name, "bc": res.bc, "value": q.of(res)})
317
+ write_rows(outdir / f"{stem}_{key.replace('.', '_')}.csv", res.rows())
318
+ for fmt in tables:
319
+ write_table(outdir / f"{stem}_{key.replace('.', '_')}.{fmt}", res.rows())
320
+ ends = res.path.times[1:] # the fields of the files: at the ends of the segments
321
+ kept = [(t, a) for t, a in sorted(res.fields.items()) if np.isclose(t, ends).any()]
322
+ for k, (t, arrays) in enumerate(kept if spec.fields else []):
323
+ target = outdir / f"{stem}_{key.replace('.', '_')}_{k + 1}.vtu"
324
+ written = write_path_fields(target, res.support, arrays)
325
+ log.info("fields of %s at time %g: %s", key, t, written.name)
326
+ continue
327
+ if isinstance(res, (Apparent, Response)):
328
+ if isinstance(res, Apparent):
329
+ values[key] = res.value
330
+ else:
331
+ values.update({f"{key}.{n}": v for n, v in res.components().items()})
332
+ rows.append(res.row())
333
+ if spec.fields and res.solution.fields is not None:
334
+ _write_fields(res, outdir / f"{stem}_{key.replace('.', '_')}")
335
+ else:
336
+ named = {}
337
+ prop, _, bc = key.partition(".")
338
+ if prop in COUPLED: # the tensors of a coupled law, by name
339
+ named = coupled_entries(res)
340
+ elif prop in HARMONIC or prop in FLOW: # their scalar entries, by name
341
+ named = {}
342
+ elif prop not in ("thermal_expansion", "swelling"): # theirs are named A.., B..
343
+ named = matrix_entries(res["tensor"], "C")
344
+ if "compliance" in res: # of the stiffness: S = C^-1, in the same notation
345
+ named.update(matrix_entries(res["compliance"], "S"))
346
+ named.update({n: v for n, v in res.items() if isinstance(v, float)})
347
+ values.update({f"{key}.{k}": v for k, v in named.items()})
348
+ for name, entry in entries: # the scalar results of the statistics of RVE studies
349
+ if name == prop and entry in named:
350
+ rows.append({"property": f"{prop}.{entry}", "bc": bc, "value": named[entry]})
351
+ if isinstance(sample, TetMesh):
352
+ fractions = _mesh_fractions(sample, spec.materials)
353
+ elif isinstance(sample, LevelSetSample):
354
+ fractions = sample.phase_fractions()
355
+ else:
356
+ fractions = phase_fractions(sample)
357
+ for phase, fraction in fractions.items():
358
+ values.setdefault(f"fraction_{phase}", fraction)
359
+ present = {p: f for p, f in fractions.items() if p in spec.materials}
360
+ values.update(normalized_values(values, present, spec.materials))
361
+ return values, rows, results
362
+
363
+
364
+ def _conforming_mesh(micro: Microstructure, cfg: RunConfig) -> tuple[TetMesh, dict]:
365
+ homog = cfg.homogenization
366
+ porous = homog.void_phases if homog is not None else set()
367
+ mesh = conforming_mesh(micro, **cfg.mesh.kwargs(porous))
368
+ q = mesh.quality()
369
+ info = {
370
+ "mesh_nodes": mesh.n_nodes,
371
+ "mesh_elements": mesh.n_elements,
372
+ "mesh_order": mesh.order,
373
+ "mesh_quality_min": float(q.min()) if q.size else float("nan"),
374
+ "mesh_time_s": sum( # the background, octree, cells or complex, and MMG
375
+ float(v) for k, v in mesh.metadata.items() if k.startswith("time_") and k.endswith("_s")
376
+ ),
377
+ }
378
+ return mesh, info
379
+
380
+
381
+ def _process(
382
+ micro: Microstructure,
383
+ cfg: RunConfig,
384
+ stem: str,
385
+ outdir: Path,
386
+ measures,
387
+ index: int = 0,
388
+ *,
389
+ homogenize: bool = True,
390
+ ) -> tuple[dict, list[dict]]:
391
+ """Write the files of one realization (the ``index``-th of the run: the first ones
392
+ have figures and videos); return its measurements and the rows of its apparent
393
+ properties (none without ``homogenize``: a window study solves its realization
394
+ itself)."""
395
+ out = cfg.outputs
396
+ for fmt in out.geometry:
397
+ io.save_microstructure(micro, outdir / f"{stem}.{fmt}")
398
+ homog = cfg.homogenization
399
+ fe = homog is not None and homog.method == "fe"
400
+ xfem = homog is not None and homog.method == "xfem"
401
+ viz = cfg.visualization
402
+ viz = viz if viz is not None and index < viz.realizations else None
403
+ values: dict = {}
404
+ mesh = None
405
+ shown = viz is not None and viz.shows("mesh")
406
+ if cfg.mesh is not None and (
407
+ fe or out.conforming_mesh or "volume_fraction" in measures or shown
408
+ ):
409
+ mesh, info = _conforming_mesh(micro, cfg)
410
+ checkpoint() # a stop after the mesh (morphogen.stopping)
411
+ values.update(info)
412
+ for fmt in out.conforming_mesh:
413
+ # Abaqus inputs with the materials of the phases (MFront laws for the nonlinear,
414
+ # and for all in finite strains)
415
+ extra = {}
416
+ if fmt == "inp" and homog is not None:
417
+ extra = {"materials": homog.materials, "kinematics": _kinematics(homog)}
418
+ io.save_mesh(mesh, outdir / f"{stem}_tet.{fmt}", **extra)
419
+ if out.periodic_pairs and mesh.periodic:
420
+ io.write_periodic_pairs(outdir / f"{stem}_tet_periodic.csv", mesh)
421
+ if out.periodic_equations and mesh.periodic:
422
+ io.write_periodic_equations(outdir / f"{stem}_tet_equations.inp", mesh)
423
+ if out.neper:
424
+ io.write_neper(outdir / stem, micro)
425
+ morph = [m for m in measures if m in _measure_names()]
426
+ use_image = cfg.voxels is not None and (
427
+ out.needs_voxels
428
+ or bool(morph)
429
+ or (homog is not None and not fe and not xfem and homogenize)
430
+ or cfg.diffusion is not None
431
+ or (viz is not None and viz.shows("image", "labels"))
432
+ )
433
+ image = labels = None
434
+ if use_image:
435
+ shown = viz is not None and viz.shows("labels")
436
+ image = _voxel_outputs(micro, cfg, stem, outdir, measures, labels=shown)
437
+ labels = image[1]
438
+ image = image[0]
439
+ if morph:
440
+ values.update(measure(image, morph, labels=labels))
441
+ elif "volume_fraction" in measures and mesh is not None:
442
+ values["volume_fraction"] = _mesh_fractions(
443
+ mesh, homog.materials if homog is not None else {0: None, 1: None}
444
+ ).get(1, 0.0)
445
+ if cfg.diffusion is not None:
446
+ values.update(_diffuse(image, cfg.diffusion, stem, outdir))
447
+ fe_rows: list[dict] = []
448
+ results = None
449
+ if homog is not None and homogenize:
450
+ sample = mesh if fe else image
451
+ if xfem: # the level set on the grid of the voxels section, cut by the interfaces
452
+ grid = cfg.voxels
453
+ sample = LevelSetSample.of(micro, grid.shape, spacing=grid.voxel_size)
454
+ grains = None
455
+ if not fe and not xfem and _oriented(micro, homog):
456
+ # crystals turned by the orientations of the grains of the image
457
+ if labels is None:
458
+ labels = micro.labels(grid=image.grid())
459
+ grains = (labels, micro.orientations)
460
+ quantities = path_quantities(cfg.rve.properties, homog) if cfg.rve is not None else []
461
+ entries = property_entries(cfg.rve.properties, homog) if cfg.rve is not None else []
462
+ keep = viz.fields() if viz is not None else False
463
+ fe_values, fe_rows, results = _homogenize(
464
+ sample,
465
+ homog,
466
+ stem,
467
+ outdir,
468
+ grains,
469
+ quantities,
470
+ keep=keep,
471
+ tables=out.tables,
472
+ entries=entries,
473
+ )
474
+ values.update(fe_values)
475
+ if viz is not None:
476
+ from morphogen.viz.workflow import visualize
477
+
478
+ visualize(viz, stem, outdir, image=image, labels=labels, mesh=mesh, results=results)
479
+ return values, fe_rows
480
+
481
+
482
+ def _oriented(micro: Microstructure, homog: HomogenizationSpec) -> bool:
483
+ """Whether the materials include crystals and the microstructure orients its grains."""
484
+ return any_oriented(homog.materials) and getattr(micro, "orientations", None) is not None
485
+
486
+
487
+ def _kinematics(homog: HomogenizationSpec) -> str:
488
+ """The kinematics of the loading paths of a run (and of its exports)."""
489
+ return homog.nonlinear.get("kinematics", "small")
490
+
491
+
492
+ def _diffuse(image, spec, stem: str, outdir: Path) -> dict:
493
+ """Transient diffusion in the image: the uptake curve (``<stem>_diffusion.csv``: the
494
+ mean concentration, its ratio to saturation and the mean of each phase), the fields
495
+ at the times (``<stem>_diffusion_<k>.vti``); returns the relative uptakes."""
496
+ from morphogen.coupling.diffusion import transient_diffusion
497
+
498
+ res = transient_diffusion(
499
+ image,
500
+ spec.diffusivity,
501
+ spec.times,
502
+ solubility=spec.solubility,
503
+ exposed=spec.exposed,
504
+ boundary=spec.boundary(),
505
+ initial=spec.initial,
506
+ consumption=spec.consumption,
507
+ steps=spec.steps,
508
+ )
509
+ labels = np.asarray(image.data)
510
+ rows = []
511
+ for k, t in enumerate(res.times):
512
+ row = {
513
+ "time": float(t),
514
+ "uptake": float(res.uptake[k]),
515
+ "relative_uptake": float(res.relative_uptake[k]),
516
+ }
517
+ for p in np.unique(labels):
518
+ row[f"c_{int(p)}"] = float(res.fields[k][labels == p].mean())
519
+ rows.append(row)
520
+ if spec.fields:
521
+ target = outdir / f"{stem}_diffusion_{k + 1}.vti"
522
+ io.write_vti(
523
+ target, image.with_data(res.fields[k].astype(np.float32), name="concentration")
524
+ )
525
+ write_rows(outdir / f"{stem}_diffusion.csv", rows)
526
+ return {
527
+ f"diffusion.relative_uptake_{k + 1}": float(v) for k, v in enumerate(res.relative_uptake)
528
+ }
529
+
530
+
531
+ def _voxel_outputs(
532
+ micro: Microstructure, cfg: RunConfig, stem: str, outdir: Path, measures, labels=False
533
+ ):
534
+ """Voxel image of a realization and the files derived from it; returns the image
535
+ and the cell labels (tessellations, grain structures) when needed (``labels``: for
536
+ the figures and videos). With ``voxels.section``, the image, the labels and the
537
+ level sets are those of one layer of voxels of the volume (the surfaces stay those
538
+ of the volume)."""
539
+ out = cfg.outputs
540
+ vox = cfg.voxels
541
+ volume = micro.voxelize(**vox.kwargs())
542
+ grid = volume.grid() # of the volume: the fields of a section are its layers
543
+ image = vox.layer(volume)
544
+ wanted = labels or out.labels or out.mesh or out.damask or "cells" in measures
545
+ labels = None
546
+ if micro.has_labels and wanted:
547
+ labels = vox.layer(micro.labels(grid=grid))
548
+ if out.damask:
549
+ homog = cfg.homogenization
550
+ io.write_damask(
551
+ outdir / f"{stem}_damask",
552
+ labels,
553
+ micro.orientations,
554
+ micro.cell_phases,
555
+ materials=homog.materials if homog is not None else None,
556
+ )
557
+ if out.amitex is not None:
558
+ homog = cfg.homogenization
559
+ grains = {}
560
+ if _oriented(micro, homog):
561
+ if labels is None:
562
+ labels = vox.layer(micro.labels(grid=grid))
563
+ grains = {"grains": labels.data, "orientations": micro.orientations}
564
+ # the nonlinear materials go to AMITEX as MFront laws, along the paths only (all of
565
+ # them in finite strains, whose runs are the paths)
566
+ finite = _kinematics(homog) == "finite"
567
+ nonlinear = not out.amitex.get("elastic_only") and any(
568
+ m.nonlinear for m in homog.materials.values()
569
+ )
570
+ stiffness = not (nonlinear or finite) and (
571
+ "stiffness" in homog.properties or not (homog.loadings or homog.paths)
572
+ )
573
+ io.write_amitex(outdir / f"{stem}_amitex", image, homog.materials,
574
+ loadings={} if finite else homog.loadings, paths=homog.paths,
575
+ stiffness=stiffness, name=stem, kinematics=_kinematics(homog), **grains,
576
+ **out.amitex) # fmt: skip
577
+ exported = (
578
+ vox.layer(micro.voxelize(grid=grid, supersampling=vox.supersampling))
579
+ if (out.image and vox.supersampling > 1)
580
+ else image
581
+ )
582
+ for fmt in out.image:
583
+ io.save_image(exported, outdir / f"{stem}.{fmt}")
584
+ for fmt in out.labels:
585
+ if labels is None:
586
+ raise ValueError(
587
+ "outputs.labels: only tessellations and grain structures have cell labels"
588
+ )
589
+ io.save_image(labels, outdir / f"{stem}_labels.{fmt}")
590
+ several = micro.implicit_phases() != [0, 1] # one implicit function per phase
591
+ if out.level_set:
592
+ for suffix, field in implicit_functions(micro, grid=grid):
593
+ for fmt in out.level_set:
594
+ io.save_image(vox.layer(field), outdir / f"{stem}_levelset{suffix}.{fmt}")
595
+ if out.mesh:
596
+ mesh = voxel_mesh(image, phases=out.mesh_phases, labels=labels)
597
+ homog = cfg.homogenization
598
+ extra = {}
599
+ if homog is not None: # Abaqus inputs with the materials (and grains) of the run
600
+ extra.update(materials=homog.materials, kinematics=_kinematics(homog))
601
+ if labels is not None and _oriented(micro, homog):
602
+ extra["orientations"] = micro.orientations
603
+ for fmt in out.mesh:
604
+ io.save_mesh(mesh, outdir / f"{stem}.{fmt}", **(extra if fmt == "inp" else {}))
605
+ if out.periodic_pairs:
606
+ io.write_periodic_pairs(outdir / f"{stem}_periodic.csv", mesh)
607
+ if out.periodic_equations and image.periodic and out.mesh_phases is None:
608
+ io.write_periodic_equations(outdir / f"{stem}_equations.inp", mesh)
609
+ for fmt in out.surface:
610
+ if several: # the surface of each phase but the last (that of the others together)
611
+ for k in micro.implicit_phases()[:-1]:
612
+ field = micro.phase_level_set(k, grid=grid)
613
+ io.save_mesh(surface_mesh(field), outdir / f"{stem}_phase{k}.{fmt}")
614
+ continue
615
+ try:
616
+ field = micro.level_set(grid=grid)
617
+ except NotImplementedError:
618
+ field = micro.voxelize(grid=grid, supersampling=max(2, vox.supersampling))
619
+ io.save_mesh(surface_mesh(field), outdir / f"{stem}.{fmt}")
620
+ return image, labels
621
+
622
+
623
+ def _measure_names():
624
+ from morphogen.analysis.measures import MEASURES
625
+
626
+ return MEASURES
627
+
628
+
629
+ def _manifest(cfg: RunConfig, outdir: Path, extra: dict) -> Path:
630
+ try:
631
+ theory = cfg.model.theory(cfg.domain)
632
+ except (ValueError, NotImplementedError):
633
+ theory = {}
634
+ data = {
635
+ "versions": versions(),
636
+ "config": cfg.source,
637
+ "seed": cfg.seed,
638
+ "model": cfg.model.to_config(),
639
+ "theory": theory,
640
+ **extra,
641
+ }
642
+ homog = cfg.homogenization
643
+ if homog is not None and "stiffness" in homog.properties: # of its columns C.., S..
644
+ data["stiffness_notation"] = NOTATION
645
+ if cfg.outputs.database is not None:
646
+ data["database"] = str(Path(cfg.outputs.database).resolve())
647
+ path = outdir / "run.json"
648
+ if "task" in extra and extra["task"]["n"] > 1:
649
+ path = outdir / f"run_task{extra['task']['id']}of{extra['task']['n']}.json"
650
+ path.write_text(json.dumps(to_jsonable(data), indent=2) + "\n", encoding="utf-8")
651
+ return path
652
+
653
+
654
+ def _check_task(task_id: int, n_tasks: int) -> None:
655
+ if n_tasks < 1 or not 0 <= task_id < n_tasks:
656
+ raise ValueError(f"task id {task_id} must lie in [0, {n_tasks})")
657
+
658
+
659
+ def run(
660
+ cfg: RunConfig,
661
+ *,
662
+ task_id: int = 0,
663
+ n_tasks: int = 1,
664
+ jobs: int = 1,
665
+ resume: bool = False,
666
+ ) -> Path:
667
+ """Execute a configuration; returns the output directory.
668
+
669
+ ``n_tasks`` > 1 runs the share ``task_id`` of the realizations (a task of a job
670
+ array; :func:`morphogen.parallel.merge` gathers the tasks); ``jobs`` processes run
671
+ them on this machine; ``resume`` skips the realizations already done (see
672
+ :mod:`morphogen.parallel`). Scripts calling it with ``jobs`` > 1 must guard their main
673
+ code with ``if __name__ == "__main__":`` (processes are started with ``spawn``).
674
+ """
675
+ _check_task(task_id, n_tasks)
676
+ if jobs < 1:
677
+ raise ValueError("jobs: a positive number of processes")
678
+ if cfg.visualization is not None:
679
+ from morphogen.viz.workflow import check
680
+
681
+ check(cfg.visualization) # before any realization
682
+ if cfg.threads is not None:
683
+ settings.set_num_threads(cfg.threads)
684
+ if cfg.seed is None:
685
+ if n_tasks > 1:
686
+ raise ValueError(
687
+ "a run split in tasks needs a seed shared by the tasks: set 'seed' in the "
688
+ "configuration or give --seed"
689
+ )
690
+ cfg.seed = int(np.random.SeedSequence().entropy)
691
+ log.info("seed of the run: %d", cfg.seed)
692
+ outdir = cfg.outputs.directory
693
+ outdir.mkdir(parents=True, exist_ok=True)
694
+ if cfg.rve is not None and cfg.rve.method == "windows":
695
+ run_windows(cfg, outdir)
696
+ else:
697
+ run_items(cfg, outdir, task_id, n_tasks, jobs=jobs, resume=resume)
698
+ if cfg.outputs.database is not None and n_tasks == 1:
699
+ from morphogen.results import record_run
700
+
701
+ record_run(outdir, cfg.outputs.database)
702
+ return outdir
703
+
704
+
705
+ def _write_results(outdir, rows, fe_rows, task_id, n_tasks, tables=()) -> None:
706
+ write_rows(outdir / _results_name(task_id, n_tasks), rows)
707
+ if fe_rows:
708
+ write_rows(outdir / _task_name("homogenization", task_id, n_tasks), fe_rows)
709
+ for fmt in tables: # the same tables as .txt or .xlsx
710
+ for stem, table in (("results", rows), ("homogenization", fe_rows)):
711
+ if table:
712
+ name = Path(_task_name(stem, task_id, n_tasks)).with_suffix(f".{fmt}")
713
+ write_table(outdir / name, table)
714
+
715
+
716
+ def run_items(
717
+ cfg: RunConfig, outdir: Path, task_id: int, n_tasks: int, *, jobs: int = 1, resume=False
718
+ ) -> None:
719
+ """Realizations of a batch or of an ensemble RVE study (the share of one task)."""
720
+ t0 = time.time()
721
+ todo = parallel.task_items(parallel.items(cfg), task_id, n_tasks)
722
+ records = parallel.execute(cfg, todo, outdir, jobs=jobs, resume=resume)
723
+ rows, fe_rows = parallel.rows_of(records)
724
+ _write_results(outdir, rows, fe_rows, task_id, n_tasks, cfg.outputs.tables)
725
+ task = {"id": task_id, "n": n_tasks, "jobs": jobs}
726
+ _manifest(cfg, outdir, {"task": task, "elapsed_s": time.time() - t0})
727
+ if cfg.rve is not None and n_tasks == 1:
728
+ write_report(rows, outdir, cfg.rve, cfg, fe_rows=fe_rows)
729
+
730
+
731
+ def run_batch(cfg: RunConfig, outdir: Path, task_id: int, n_tasks: int) -> None:
732
+ """The items of a batch configuration that fall to a task (``task_id`` among ``n_tasks``)
733
+ generated and processed, their outputs and records in ``outdir``."""
734
+ run_items(cfg, outdir, task_id, n_tasks)
735
+
736
+
737
+ def run_ensemble(cfg: RunConfig, outdir: Path, task_id: int, n_tasks: int) -> None:
738
+ """The realizations of an RVE study by the ensemble method that fall to a task (``task_id``
739
+ among ``n_tasks``) generated and processed, their outputs and records in ``outdir``."""
740
+ run_items(cfg, outdir, task_id, n_tasks)
741
+
742
+
743
+ def run_windows(cfg: RunConfig, outdir: Path) -> None:
744
+ """An RVE study by the window method: one realization of the size of the study, measured in
745
+ windows of the sizes given, its statistics, results and report in ``outdir``: of the
746
+ volume fraction, and of the tensors of the windows when the homogenization computes
747
+ them (:func:`morphogen.rve.window_tensors`: the realization solved once per unit load
748
+ by the FFT solver, each window its mean mutual energies); with ``rve.shifts``, over the
749
+ tilings shifted around the periodic realization, from the same solutions."""
750
+ spec = cfg.rve
751
+ t0 = time.time()
752
+ size = spec.size
753
+ domain = Domain(
754
+ size=(size, size, size),
755
+ origin=cfg.domain.origin,
756
+ periodic=cfg.domain.periodic,
757
+ unit=cfg.domain.unit,
758
+ )
759
+ micro = cfg.model.generate(domain, derive_seed(cfg.seed, 0))
760
+ _process(micro, cfg, f"{cfg.outputs.name}_L{size:g}", outdir, [], homogenize=False)
761
+ image = micro.voxelize(**cfg.voxels.kwargs())
762
+ h = float(np.mean(image.spacing))
763
+ edges = sorted({max(1, round(w / h)) for w in spec.window_sizes})
764
+ options = study_options(spec)
765
+ options.bootstrap = 0
766
+ stats = rve.window_statistics(image, edges, phase=1, shifts=spec.shifts)
767
+ rows = [{"window_edge": e * h, **row} for e, row in zip(edges, stats.rows(), strict=True)]
768
+ analyses = []
769
+ if "volume_fraction" in spec.properties:
770
+ theory = _theory(cfg, domain)
771
+ analyses.append(rve.analyze_statistics(stats, "volume_fraction", options, theory=theory))
772
+ else: # the windows alone (and their tilings)
773
+ keep = ("window_edge", "volume", "n", "tilings")
774
+ rows = [{k: row[k] for k in keep if k in row} for row in rows]
775
+ tensors, apparent = [], {}
776
+ for name in [p for p in spec.properties if rve.is_tensor(p)]:
777
+ prop = name.partition(".")[0]
778
+ windows = _window_tensors(micro, image, cfg.homogenization, edges, prop, spec.shifts)
779
+ t = windows.statistics(options)
780
+ tensors.append(t)
781
+ apparent[t.key] = windows.apparent
782
+ for row, entries in zip(rows, t.volume_rows(), strict=True):
783
+ row.update({f"{t.key}.{k}": v for k, v in entries.items() if k[0] in "CS"})
784
+ write_rows(outdir / "results.csv", rows)
785
+ extra = {"task": {"id": 0, "n": 1}, "elapsed_s": time.time() - t0}
786
+ if apparent: # of the whole realization, from its mean stresses (fluxes)
787
+ extra["apparent"] = apparent
788
+ _manifest(cfg, outdir, extra)
789
+ report = rve.StudyReport(analyses, {}, options, method="windows", tensors=tensors)
790
+ rve_report.write(report, outdir)
791
+
792
+
793
+ def _window_tensors(micro, image, homog: HomogenizationSpec, edges, prop: str, shifts=1):
794
+ """The tensors ``prop`` of the windows of a realization (its voxel ``image``; crystals
795
+ turned by the orientations of its grains), by the FFT solver of the homogenization, over
796
+ ``shifts`` tilings per axis."""
797
+ grains = {}
798
+ if _oriented(micro, homog):
799
+ grains = {"grains": micro.labels(grid=image.grid()), "orientations": micro.orientations}
800
+ loads = 3 if prop != "stiffness" or image.shape[2] == 1 else 6
801
+ log.info("window tensors %s: %d unit loads on %s voxels", prop, loads, image.shape)
802
+ return rve.window_tensors(image, homog.materials, edges, property=prop,
803
+ tol=homog.tolerance, maxiter=homog.max_iterations,
804
+ device=homog.device, shifts=shifts, **grains) # fmt: skip
805
+
806
+
807
+ def _theory(cfg: RunConfig, domain: Domain) -> dict:
808
+ try:
809
+ return cfg.model.theory(domain)
810
+ except (ValueError, NotImplementedError):
811
+ return {}
812
+
813
+
814
+ def study_options(spec: RVESpec) -> rve.StudyOptions:
815
+ """The options of an RVE study (:class:`morphogen.rve.StudyOptions`) from the section ``rve`` of
816
+ a configuration."""
817
+ return rve.StudyOptions(
818
+ gamma=spec.gamma,
819
+ min_volume=spec.min_volume,
820
+ max_volume=spec.max_volume,
821
+ relative_errors=tuple(spec.relative_errors),
822
+ n_realizations=tuple(spec.n_realizations),
823
+ bootstrap=spec.bootstrap,
824
+ weights=spec.weights,
825
+ )
826
+
827
+
828
+ def _counter(model: Model | None):
829
+ """Mean number of objects of the model in a cube of the given volume."""
830
+ if model is None:
831
+ return None
832
+ try:
833
+ if model.expected_count(Domain.cube(1.0)) is None:
834
+ return None
835
+ except (ValueError, NotImplementedError):
836
+ return None
837
+
838
+ def count(volume: float) -> float:
839
+ return float(model.expected_count(Domain.cube(volume ** (1.0 / 3.0))))
840
+
841
+ return count
842
+
843
+
844
+ def _bounds(rows: list[dict], homog: HomogenizationSpec | None) -> dict:
845
+ """Bounds from the mean phase fractions of the largest volume."""
846
+ if homog is None or not rows:
847
+ return {}
848
+ volumes = np.array([float(r.get("volume", np.nan)) for r in rows])
849
+ largest = [r for r, v in zip(rows, volumes, strict=True) if v == np.nanmax(volumes)]
850
+ fractions = {}
851
+ for key in dict.fromkeys(k for r in largest for k in r if k.startswith("fraction_")):
852
+ # a phase absent from a realization: a zero fraction there
853
+ values = [r.get(key) for r in largest]
854
+ values = [0.0 if v is None or v == "" else float(v) for v in values]
855
+ fractions[int(key.split("_")[1])] = float(np.nanmean(values))
856
+ try:
857
+ return bounds(fractions, homog.materials) if fractions else {}
858
+ except (ValueError, KeyError):
859
+ return {}
860
+
861
+
862
+ def build_report(
863
+ rows: list[dict],
864
+ spec: RVESpec,
865
+ properties=None,
866
+ theory=None,
867
+ *,
868
+ fe_rows: list[dict] | None = None,
869
+ count=None,
870
+ bound_values: dict | None = None,
871
+ group_by: str | None = None,
872
+ ) -> rve.StudyReport:
873
+ """RVE report of results tables (wide ``rows``; long ``fe_rows`` from homogenization),
874
+ with the mean stiffness and compliance per volume of each boundary condition whose
875
+ stiffness the rows hold (:func:`morphogen.rve.tensors_from_rows`; the conductivity
876
+ tensor likewise): all of them when ``properties`` is None, else those it names
877
+ (``stiffness``, ``stiffness.<bc>``, ``conductivity_tensor``...)."""
878
+ if not rows and not fe_rows:
879
+ raise ValueError("no results to analyse")
880
+ wanted = list(properties) if properties is not None else None
881
+ options = study_options(spec)
882
+ asked = None if wanted is None else [p for p in wanted if rve.is_tensor(p)]
883
+ tensors = []
884
+ if rows and asked != []:
885
+ tensors = rve.tensors_from_rows(rows, properties=asked, options=options)
886
+ if asked and not tensors:
887
+ what = " or ".join(sorted({p.partition(".")[0] for p in asked}))
888
+ raise ValueError(
889
+ f"no {what} in the results for {asked}: the columns <tensor>.<bc>.C11 ... "
890
+ "(C66 of a stiffness, C33 of a conductivity) of a homogenization computing it"
891
+ )
892
+ if wanted is not None:
893
+ wanted = [p for p in wanted if not rve.is_tensor(p)]
894
+ series: list[rve.Series] = []
895
+ fe_names = set()
896
+ if fe_rows:
897
+ fe_series = rve.series_from_rows(fe_rows)
898
+ fe_names = {s.key for s in fe_series}
899
+ series += [
900
+ s for s in fe_series if wanted is None or s.key in wanted or s.property in wanted
901
+ ]
902
+ if rows:
903
+ morph = None
904
+ if wanted is not None:
905
+ morph = [
906
+ p
907
+ for p in wanted
908
+ if p not in fe_names and not any(n.startswith(p + ".") for n in fe_names)
909
+ ]
910
+ if morph is None or morph:
911
+ try:
912
+ wide = rve.series_from_rows(rows, properties=morph, group_by=group_by)
913
+ except ValueError:
914
+ if morph:
915
+ raise
916
+ wide = []
917
+ series += [s for s in wide if s.key not in fe_names]
918
+ if not series and not tensors:
919
+ raise ValueError(f"no series to analyse for the properties {wanted}")
920
+ return rve.analyze_study(
921
+ series, options, count=count, bounds=bound_values, theory=theory, tensors=tensors
922
+ )
923
+
924
+
925
+ def write_report(
926
+ rows, outdir: Path, spec, cfg: RunConfig | None = None, properties=None, *, fe_rows=None
927
+ ) -> rve.StudyReport:
928
+ """Write rve_report.json/.md/.tex (and plots) of a study."""
929
+ theory = _theory(cfg, cfg.domain) if cfg is not None else None
930
+ if properties is None and cfg is not None and cfg.rve is not None:
931
+ properties = cfg.rve.properties
932
+ report = build_report(
933
+ rows,
934
+ spec,
935
+ properties,
936
+ theory,
937
+ fe_rows=fe_rows,
938
+ count=_counter(cfg.model) if cfg is not None else None,
939
+ bound_values=_bounds(rows, cfg.homogenization if cfg is not None else None),
940
+ )
941
+ rve_report.write(report, outdir)
942
+ return report
943
+
944
+
945
+ def report_markdown(report: rve.StudyReport) -> str:
946
+ """The Markdown report of an RVE study (:func:`morphogen.rve.report.markdown`)."""
947
+ return rve_report.markdown(report)
948
+
949
+
950
+ def collect_results(paths, stem: str = "results") -> list[dict]:
951
+ """Rows of one or several results files (a directory: its ``<stem>.csv``, or all its
952
+ ``<stem>*.csv`` files of split runs that were not merged)."""
953
+ files: list[Path] = []
954
+ for p in [paths] if isinstance(paths, (str, Path)) else paths:
955
+ p = Path(p)
956
+ if p.is_dir():
957
+ merged = p / f"{stem}.csv"
958
+ files.extend([merged] if merged.exists() else sorted(p.glob(f"{stem}*.csv")))
959
+ else:
960
+ files.append(p)
961
+ if not files:
962
+ raise ValueError(f"no {stem} files found in {paths}")
963
+ rows = []
964
+ for f in files:
965
+ rows.extend(read_rows(f))
966
+ return rows
967
+
968
+
969
+ def collect_homogenization(paths) -> list[dict]:
970
+ """Rows of the homogenization files of result directories (empty if none)."""
971
+ dirs = [Path(p) for p in ([paths] if isinstance(paths, (str, Path)) else paths)]
972
+ dirs = [d for d in dirs if d.is_dir()]
973
+ if not any(next(d.glob("homogenization*.csv"), None) for d in dirs):
974
+ return []
975
+ try:
976
+ return collect_results(dirs, stem="homogenization")
977
+ except ValueError:
978
+ return []