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/config.py ADDED
@@ -0,0 +1,2167 @@
1
+ """Configuration files (YAML, JSON or TOML) describing generation runs and RVE studies.
2
+
3
+ A configuration has the sections ``model``, ``domain``, ``voxels`` (voxel images),
4
+ ``mesh`` (conforming tetrahedral meshes), ``outputs``, ``analysis``, ``homogenization``
5
+ (apparent properties: finite elements on the meshes, or FFT on the voxel images),
6
+ ``visualization`` (figures and videos of the images, meshes and fields of the first
7
+ realizations) and, for RVE studies, ``rve`` (see docs/architecture.md and the templates).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import itertools
13
+ import json
14
+ import tomllib
15
+ from dataclasses import dataclass, field
16
+ from pathlib import Path
17
+
18
+ import numpy as np
19
+ import yaml
20
+
21
+ from morphogen.analysis.measures import MEASURES
22
+ from morphogen.domain import Domain
23
+ from morphogen.gpu import DEVICES
24
+ from morphogen.homogenization.apparent import (
25
+ CONTACT_OPTIONS,
26
+ INTERFACE_OPTIONS,
27
+ PHYSICS,
28
+ PROPERTIES,
29
+ )
30
+ from morphogen.homogenization.core import VOIGT_NAMES, Loading, boundary_condition
31
+ from morphogen.homogenization.materials import Material, materials_from_config
32
+ from morphogen.homogenization.paths import LoadingPath, PathQuantity
33
+ from morphogen.homogenization.solvers import SOLVERS
34
+ from morphogen.io import GEOMETRY_FORMATS, IMAGE_FORMATS
35
+ from morphogen.models.base import Model, get_model, model_from_config
36
+ from morphogen.rve.study import TENSOR_PROPERTIES
37
+
38
+ SURFACE_FORMATS = ("stl",)
39
+ MESH_FORMATS = ("inp", "msh", "vtu", "xdmf", "med", "mesh")
40
+ HOMOGENIZATION_METHODS = ("auto", "fe", "fft", "xfem")
41
+ #: Formats of the tables of a run besides .csv (outputs.tables), of the figures and the
42
+ #: videos of the visualization section (the 3D views of VTK are bitmaps)
43
+ TABLE_FORMATS = ("csv", "txt", "xlsx")
44
+ FIGURE_FORMATS = ("png", "tif", "jpg", "svg", "pdf", "eps", "tex")
45
+ BITMAP_FORMATS = ("png", "tif", "jpg")
46
+ VIDEO_FORMATS = ("mp4", "gif", "frames")
47
+
48
+
49
+ class ConfigError(ValueError):
50
+ """Invalid configuration (the message names the faulty entry)."""
51
+
52
+
53
+ def _check_keys(section: str, data: dict, allowed: set, required: set = frozenset()) -> None:
54
+ if not isinstance(data, dict):
55
+ raise ConfigError(f"{section}: expected a mapping, got {data!r}")
56
+ unknown = sorted(set(data) - allowed)
57
+ if unknown:
58
+ raise ConfigError(f"{section}: unknown keys {unknown}; allowed: {sorted(allowed)}")
59
+ missing = sorted(required - set(data))
60
+ if missing:
61
+ raise ConfigError(f"{section}: missing keys {missing}")
62
+
63
+
64
+ def _list_of(section: str, value, allowed) -> list[str]:
65
+ if value is None:
66
+ return []
67
+ items = [value] if isinstance(value, str) else list(value)
68
+ for item in items:
69
+ if item not in allowed:
70
+ raise ConfigError(f"{section}: unknown value {item!r}; allowed: {list(allowed)}")
71
+ return [str(v) for v in items]
72
+
73
+
74
+ def _positive_int(section: str, value) -> int:
75
+ if isinstance(value, bool) or not isinstance(value, int) or value < 1:
76
+ raise ConfigError(f"{section}: expected a positive integer, got {value!r}")
77
+ return value
78
+
79
+
80
+ @dataclass
81
+ class VoxelSpec:
82
+ shape: int | tuple[int, int, int] | None = None
83
+ voxel_size: float | None = None
84
+ supersampling: int = 1
85
+ #: the axis (0, 1, 2) normal to which the image of a run is one layer of voxels
86
+ #: through the middle of the realization (``section: x``, ``y`` or ``z``): a planar
87
+ #: study of a three-dimensional model
88
+ section: int | None = None
89
+
90
+ def kwargs(self) -> dict:
91
+ return {"shape": self.shape, "voxel_size": self.voxel_size}
92
+
93
+ def image(self, micro, supersampling: int = 1):
94
+ """The voxel image of a realization: its volume, or the layer of its section."""
95
+ extra = {"supersampling": supersampling} if supersampling > 1 else {}
96
+ return self.layer(micro.voxelize(**self.kwargs(), **extra))
97
+
98
+ def layer(self, image):
99
+ """The layer of the section of an image of the volume (the image itself without
100
+ a section)."""
101
+ return image if self.section is None else image.layer(self.section)
102
+
103
+
104
+ @dataclass
105
+ class MeshSpec:
106
+ """Conforming tetrahedral meshes of the realizations (see
107
+ :func:`morphogen.mesh.conforming.conforming_mesh`). ``order``: None in a
108
+ configuration that does not give it, then 2 (10-node tetrahedra) when the mesh is
109
+ analysed by finite elements and 1 (4-node) when it is only written
110
+ (:func:`load_config`)."""
111
+
112
+ size: float
113
+ min_size: float | None = None
114
+ hausdorff: float | None = None
115
+ gradation: float = 2.0
116
+ background: float | None = None
117
+ order: int | None = None
118
+ curved: bool | None = None
119
+ sharp_edges: bool | None = None
120
+ phases: str = "auto"
121
+ grains: bool | None = None
122
+ min_feature: float | None = None
123
+ cells: str = "whole"
124
+ method: str = "auto"
125
+
126
+ def kwargs(self, porous=False) -> dict:
127
+ """Arguments of ``conforming_mesh``; ``phases='auto'`` meshes only the solid phase
128
+ of porous media (``porous``: the void phases, or True for a void phase 0): phase 1
129
+ when phase 0 is the void, phase 0 when the pores are phase 1."""
130
+ phases = self.phases
131
+ if phases == "auto":
132
+ voids = {0} if porous is True else set(porous or ())
133
+ if not voids:
134
+ phases = "all"
135
+ else:
136
+ phases = "matrix" if voids == {1} else "solid"
137
+ out = {
138
+ "size": self.size,
139
+ "min_size": self.min_size,
140
+ "hausdorff": self.hausdorff,
141
+ "gradation": self.gradation,
142
+ "background": self.background,
143
+ "order": 1 if self.order is None else self.order,
144
+ "phases": phases,
145
+ "cells": self.cells,
146
+ "method": self.method,
147
+ }
148
+ if self.curved is not None:
149
+ out["curved"] = self.curved
150
+ if self.sharp_edges is not None:
151
+ out["sharp_edges"] = self.sharp_edges
152
+ if self.grains is not None:
153
+ out["grains"] = self.grains
154
+ if self.min_feature is not None:
155
+ out["min_feature"] = self.min_feature
156
+ return out
157
+
158
+
159
+ @dataclass
160
+ class OutputSpec:
161
+ directory: Path = Path("morphogen_output")
162
+ name: str = "sample"
163
+ geometry: list[str] = field(default_factory=list)
164
+ image: list[str] = field(default_factory=list)
165
+ labels: list[str] = field(default_factory=list)
166
+ level_set: list[str] = field(default_factory=list)
167
+ mesh: list[str] = field(default_factory=list)
168
+ mesh_phases: list[int] | None = None
169
+ conforming_mesh: list[str] = field(default_factory=list)
170
+ periodic_pairs: bool = False
171
+ periodic_equations: bool = False
172
+ surface: list[str] = field(default_factory=list)
173
+ damask: bool = False
174
+ neper: bool = False
175
+ database: Path | None = None
176
+ #: AMITEX_FFTP runs of the image (the options of morphogen.io.write_amitex), or None
177
+ amitex: dict | None = None
178
+ #: the tables of the run (results, homogenization, curves of the loading paths) in
179
+ #: these formats too, besides .csv
180
+ tables: list[str] = field(default_factory=list)
181
+
182
+ @property
183
+ def needs_voxels(self) -> bool:
184
+ return bool(
185
+ self.image
186
+ or self.labels
187
+ or self.mesh
188
+ or self.surface
189
+ or self.level_set
190
+ or self.damask
191
+ or self.amitex is not None
192
+ )
193
+
194
+
195
+ #: Options of outputs.amitex (those of morphogen.io.write_amitex)
196
+ AMITEX_OPTIONS = ("fields", "tolerance", "elastic_only", "processes", "library")
197
+
198
+
199
+ def _amitex(value) -> dict | None:
200
+ """``outputs.amitex``: true (the default options), false, or a mapping of options."""
201
+ if value is None or value is False:
202
+ return None
203
+ if value is True:
204
+ return {}
205
+ if not isinstance(value, dict):
206
+ raise ConfigError(f"outputs.amitex: true, or a mapping of options {list(AMITEX_OPTIONS)}")
207
+ _check_keys("outputs.amitex", value, set(AMITEX_OPTIONS))
208
+ out = {}
209
+ for key in ("fields", "elastic_only"):
210
+ if key in value:
211
+ out[key] = bool(value[key])
212
+ if value.get("tolerance") is not None:
213
+ tol = float(value["tolerance"])
214
+ if not 0.0 < tol < 1e-3:
215
+ raise ConfigError("outputs.amitex.tolerance: a positive number below 1e-3 (AMITEX)")
216
+ out["tolerance"] = tol
217
+ if "processes" in value:
218
+ n = int(value["processes"])
219
+ if n < 1:
220
+ raise ConfigError("outputs.amitex.processes: a positive number of MPI processes")
221
+ out["processes"] = n
222
+ if "library" in value:
223
+ out["library"] = str(value["library"])
224
+ return out
225
+
226
+
227
+ #: Options of the nonlinear solver in configurations, and their names in the code
228
+ NONLINEAR_OPTIONS = {
229
+ "tolerance": "newton_tol",
230
+ "max_iterations": "max_newton",
231
+ "max_cuts": "max_cuts",
232
+ "kinematics": "kinematics",
233
+ "integration": "integration",
234
+ "tangent": "tangent",
235
+ "contact": "contact",
236
+ "interfaces": "interfaces",
237
+ "microdamage": "microdamage",
238
+ }
239
+
240
+
241
+ @dataclass
242
+ class HomogenizationSpec:
243
+ """Apparent properties computed on every realization: finite elements on its
244
+ conforming mesh (``method: fe``) or FFT on its voxel image (``method: fft``); and
245
+ loading paths followed in time with the nonlinear behaviours of the materials, by
246
+ either method."""
247
+
248
+ materials: dict[int, Material]
249
+ method: str = "auto"
250
+ boundary_conditions: list[str] = field(default_factory=lambda: ["periodic"])
251
+ properties: list[str] = field(default_factory=lambda: ["bulk_modulus", "shear_modulus"])
252
+ solver: str = "auto"
253
+ tolerance: float = 1e-8
254
+ max_iterations: int | None = None
255
+ fields: bool = False
256
+ loadings: dict = field(default_factory=dict)
257
+ paths: dict = field(default_factory=dict)
258
+ nonlinear: dict = field(default_factory=dict)
259
+ device: str = "cpu"
260
+ ntfa: dict = field(default_factory=dict)
261
+ #: the mean absolute temperature of the thermoelectric coupling (K)
262
+ mean_temperature: float = 300.0
263
+ #: the angular frequencies of the harmonic properties, the wavelengths of the
264
+ #: refractive index
265
+ frequencies: list[float] | None = None
266
+ wavelengths: list[float] | None = None
267
+ #: the brittle fracture of the loading paths by the phase-field method (the
268
+ #: parameters of morphogen.fracture.phasefield.PhaseField, and of its solver)
269
+ fracture: dict | None = None
270
+ #: the bulk modulus of the fluid of the pores, for the undrained response of the
271
+ #: property 'poroelastic'
272
+ fluid_bulk_modulus: float | None = None
273
+ #: 'full', or 'bbar': the volume change of each element as its mean (10-node
274
+ #: tetrahedra: the elastic problems and the loading paths; voxels: the loading paths)
275
+ integration: str | None = None
276
+ #: the fatigue of the points along a cycle of a loading path: its ``path``, the
277
+ #: times of its ``cycle`` (None: the whole path) and the ``criteria`` of the phases
278
+ #: (mappings for morphogen.homogenization.fatigue.criterion_from_config)
279
+ fatigue: dict | None = None
280
+ #: the criterion of cleavage of Beremin along a loading path: its ``path`` and its
281
+ #: ``criterion`` (a mapping for morphogen.homogenization.beremin.Beremin)
282
+ beremin: dict | None = None
283
+
284
+ @property
285
+ def porous(self) -> bool:
286
+ return any(m.void for m in self.materials.values())
287
+
288
+ @property
289
+ def void_phases(self) -> set[int]:
290
+ """The phases whose material is a void."""
291
+ return {int(p) for p, m in self.materials.items() if m.void}
292
+
293
+ def series(self) -> list[str]:
294
+ """Names ``<property>.<bc>`` of the scalar apparent properties computed."""
295
+ return [
296
+ f"{p}.{bc}"
297
+ for p in self.properties
298
+ if p in PROPERTIES
299
+ for bc in self.boundary_conditions
300
+ ]
301
+
302
+ def tensors(self) -> list[str]:
303
+ """Names ``stiffness.<bc>`` of the stiffnesses computed (not under mixed
304
+ conditions), whose mean and compliance per volume RVE studies give, then those
305
+ ``conductivity_tensor.<bc>`` of the conductivities (their mean and resistivity) and
306
+ of the tensors of the other transport phenomena (``permittivity_tensor.<bc>``...)."""
307
+ return [
308
+ f"{p}.{bc}"
309
+ for p in TENSOR_PROPERTIES
310
+ if p in self.properties
311
+ for bc in self.boundary_conditions
312
+ if bc != "mixed"
313
+ ]
314
+
315
+ def options(self) -> dict:
316
+ return {
317
+ "bcs": self.boundary_conditions,
318
+ "properties": self.properties,
319
+ "solver": self.solver,
320
+ "tol": self.tolerance,
321
+ "maxiter": self.max_iterations,
322
+ "loadings": self.loadings,
323
+ "paths": self.paths,
324
+ "nonlinear": {NONLINEAR_OPTIONS[k]: v for k, v in self.nonlinear.items()},
325
+ "device": self.device,
326
+ "ntfa": self.ntfa or None,
327
+ "mean_temperature": self.mean_temperature,
328
+ "frequencies": self.frequencies,
329
+ "wavelengths": self.wavelengths,
330
+ "fracture": self.fracture,
331
+ "fluid_bulk_modulus": self.fluid_bulk_modulus,
332
+ "integration": self.integration,
333
+ }
334
+
335
+
336
+ @dataclass
337
+ class RVESpec:
338
+ method: str = "ensemble"
339
+ sizes: list[float] = field(default_factory=list)
340
+ realizations: list[int] = field(default_factory=list)
341
+ size: float | None = None
342
+ window_sizes: list[float] = field(default_factory=list)
343
+ properties: list[str] = field(default_factory=lambda: ["volume_fraction"])
344
+ relative_errors: list[float] = field(default_factory=lambda: [0.01, 0.05])
345
+ n_realizations: list[int] = field(default_factory=lambda: [1, 10])
346
+ gamma: float | None = None
347
+ min_volume: float | None = None
348
+ max_volume: float | None = None
349
+ bootstrap: int = 1000
350
+ weights: str = "none"
351
+ #: the window method: the tilings per axis, shifted around the periodic realization
352
+ shifts: int = 1
353
+
354
+
355
+ @dataclass
356
+ class DiffusionSpec:
357
+ """Transient diffusion in the voxel image of each realization
358
+ (:func:`morphogen.coupling.diffusion.transient_diffusion`): ``diffusivity``,
359
+ ``solubility`` and ``consumption`` of each phase, the ``exposed`` faces held at the
360
+ ``activity`` (a number, or a piecewise linear history ``(times, values)``), the
361
+ ``initial`` activity, the output ``times``, the implicit Euler ``steps`` of each
362
+ interval; ``fields``: the concentration fields at the times."""
363
+
364
+ diffusivity: dict[int, float]
365
+ solubility: dict[int, float]
366
+ consumption: dict[int, float]
367
+ exposed: tuple[str, ...] = ("x-", "x+")
368
+ activity: float | tuple = 1.0
369
+ initial: float = 0.0
370
+ times: tuple[float, ...] = ()
371
+ steps: int = 40
372
+ fields: bool = False
373
+
374
+ def boundary(self):
375
+ if isinstance(self.activity, tuple):
376
+ t, v = self.activity
377
+ return lambda time: float(np.interp(time, t, v))
378
+ return float(self.activity)
379
+
380
+
381
+ @dataclass
382
+ class ViewSpec:
383
+ """A figure or a video of each realization (the ``visualization`` section): ``of``
384
+ what (``image``, ``labels``, ``mesh``, or a result ``<name>.<bc>`` of the
385
+ homogenization, ``group`` "result" or "path"), its ``kind``, the field colouring it
386
+ (``color``) and the options of the views (see :mod:`morphogen.viz.workflow`)."""
387
+
388
+ of: str
389
+ group: str
390
+ kind: str
391
+ formats: list[str]
392
+ color: str | None = None
393
+ axis: int = 2
394
+ phase: int = 1
395
+ magnification: float | None = None
396
+ wave: str = "ramp"
397
+ section: tuple[int, float] | None = None
398
+ part: str = "total"
399
+ frames: int | None = None
400
+ mode: str = "once"
401
+ repeat: int = 1
402
+ fps: float | None = None
403
+ cmap: str | None = None
404
+ clim: tuple[float, float] | None = None
405
+ name: str | None = None
406
+ #: rendered by VTK (3D views)
407
+ vtk: bool = False
408
+
409
+ @property
410
+ def label(self) -> str:
411
+ """The name of its files, after the stem of the realization."""
412
+ if self.name:
413
+ return self.name
414
+ if self.group in ("image", "labels"):
415
+ return f"{self.of}_{self.kind}"
416
+ if self.group == "mesh":
417
+ return "mesh_sweep" if self.kind == "sweep" else "mesh"
418
+ base = self.of.replace(".", "_")
419
+ return f"{base}_curves" if self.kind == "curves" else f"{base}_{self.color}"
420
+
421
+
422
+ @dataclass
423
+ class VisualizationSpec:
424
+ """Figures and videos of the first ``realizations`` of a run, in the colormap
425
+ ``cmap``, videos at ``fps`` frames per second, 3D views of ``size`` pixels seen from
426
+ the ``elevation`` and ``azimuth`` of their camera (degrees), figures at ``dpi`` (see
427
+ :mod:`morphogen.viz.workflow`)."""
428
+
429
+ figures: list[ViewSpec] = field(default_factory=list)
430
+ videos: list[ViewSpec] = field(default_factory=list)
431
+ realizations: int = 1
432
+ cmap: str = "viridis"
433
+ fps: float = 24.0
434
+ size: tuple[int, int] = (640, 480)
435
+ dpi: int = 200
436
+ elevation: float = 25.0
437
+ azimuth: float = 30.0
438
+
439
+ @property
440
+ def views(self) -> list[ViewSpec]:
441
+ return [*self.figures, *self.videos]
442
+
443
+ def shows(self, *groups: str) -> bool:
444
+ return any(v.group in groups for v in self.views)
445
+
446
+ def fields(self) -> bool | str:
447
+ """What the homogenization keeps for the views: the fields of the loading paths
448
+ at each of their steps (``"steps"``), the fields (``True``), or nothing."""
449
+ if any(v.group == "path" for v in self.videos):
450
+ return "steps"
451
+ return any(v.group in ("result", "path") and v.kind == "field" for v in self.views)
452
+
453
+
454
+ @dataclass
455
+ class RunConfig:
456
+ model: Model
457
+ domain: Domain
458
+ seed: int | None = None
459
+ realizations: int = 1
460
+ voxels: VoxelSpec | None = None
461
+ mesh: MeshSpec | None = None
462
+ outputs: OutputSpec = field(default_factory=OutputSpec)
463
+ analysis: list[str] = field(default_factory=list)
464
+ rve: RVESpec | None = None
465
+ homogenization: HomogenizationSpec | None = None
466
+ diffusion: DiffusionSpec | None = None
467
+ visualization: VisualizationSpec | None = None
468
+ threads: int | None = None
469
+ source: dict = field(default_factory=dict)
470
+
471
+
472
+ def read_config_file(path) -> dict:
473
+ """The mapping of a configuration file (.yaml, .yml, .json or .toml); :class:`ConfigError` if it
474
+ cannot be read."""
475
+ path = Path(path)
476
+ ext = path.suffix.lower()
477
+ text = path.read_text(encoding="utf-8")
478
+ try:
479
+ if ext in (".yaml", ".yml"):
480
+ data = yaml.safe_load(text)
481
+ elif ext == ".json":
482
+ data = json.loads(text)
483
+ elif ext == ".toml":
484
+ data = tomllib.loads(text)
485
+ else:
486
+ raise ConfigError(f"{path}: configuration files must be .yaml, .yml, .json or .toml")
487
+ except (yaml.YAMLError, json.JSONDecodeError, tomllib.TOMLDecodeError) as exc:
488
+ raise ConfigError(f"{path}: cannot parse the file ({exc})") from None
489
+ if not isinstance(data, dict):
490
+ raise ConfigError(f"{path}: the configuration must be a mapping")
491
+ return data
492
+
493
+
494
+ def _voxels(data) -> VoxelSpec:
495
+ _check_keys("voxels", data, {"shape", "voxel_size", "supersampling", "section"})
496
+ if ("shape" in data) == ("voxel_size" in data):
497
+ raise ConfigError("voxels: give exactly one of 'shape' and 'voxel_size'")
498
+ shape = data.get("shape")
499
+ if shape is not None and not isinstance(shape, int):
500
+ shape = tuple(shape)
501
+ ss = data.get("supersampling", 1)
502
+ if isinstance(ss, bool) or not isinstance(ss, int) or not 1 <= ss <= 6:
503
+ raise ConfigError("voxels.supersampling: an integer between 1 and 6")
504
+ section = data.get("section")
505
+ if section is not None:
506
+ if section not in ("x", "y", "z"):
507
+ raise ConfigError(
508
+ "voxels.section: 'x', 'y' or 'z', the normal of the layer of voxels through "
509
+ "the middle of the realization that the run studies (a planar section)"
510
+ )
511
+ section = "xyz".index(section)
512
+ return VoxelSpec(shape=shape, voxel_size=data.get("voxel_size"), supersampling=ss,
513
+ section=section) # fmt: skip
514
+
515
+
516
+ def _positive_float(section: str, value, *, optional: bool = False) -> float | None:
517
+ if value is None and optional:
518
+ return None
519
+ if isinstance(value, bool):
520
+ raise ConfigError(f"{section}: expected a positive number, got {value!r}")
521
+ try:
522
+ x = float(value)
523
+ except (TypeError, ValueError):
524
+ raise ConfigError(f"{section}: expected a positive number, got {value!r}") from None
525
+ if not x > 0 or x == float("inf"):
526
+ raise ConfigError(f"{section}: expected a positive number, got {value!r}")
527
+ return x
528
+
529
+
530
+ def _mesh(data) -> MeshSpec:
531
+ allowed = {
532
+ "size",
533
+ "min_size",
534
+ "hausdorff",
535
+ "gradation",
536
+ "background",
537
+ "order",
538
+ "curved",
539
+ "sharp_edges",
540
+ "phases",
541
+ "grains",
542
+ "min_feature",
543
+ "cells",
544
+ "method",
545
+ }
546
+ _check_keys("mesh", data, allowed, {"size"})
547
+ sharp_edges = data.get("sharp_edges")
548
+ if sharp_edges is not None and not isinstance(sharp_edges, bool):
549
+ raise ConfigError(
550
+ "mesh.sharp_edges: true (the mesh follows the sharp edges of the phases: the "
551
+ "default of the structures that give their smooth pieces) or false (rounded)"
552
+ )
553
+ grains = data.get("grains")
554
+ if grains is not None and not isinstance(grains, bool):
555
+ raise ConfigError("mesh.grains: true (one subdomain per grain of a tessellation) or false")
556
+ min_feature = data.get("min_feature")
557
+ if min_feature is not None:
558
+ try:
559
+ min_feature = float(min_feature)
560
+ except (TypeError, ValueError):
561
+ min_feature = -1.0
562
+ if not 0.0 <= min_feature < float("inf"):
563
+ raise ConfigError("mesh.min_feature: a non-negative length (0 keeps the exact cells)")
564
+ order = data.get("order")
565
+ if order is not None and (order not in (1, 2) or isinstance(order, bool)):
566
+ raise ConfigError(
567
+ "mesh.order: 1 (4-node tetrahedra) or 2 (10-node tetrahedra; the default of "
568
+ "the meshes analysed by finite elements)"
569
+ )
570
+ curved = data.get("curved")
571
+ if curved is not None and not isinstance(curved, bool):
572
+ raise ConfigError(
573
+ "mesh.curved: true (10-node elements whose edges follow the interfaces, the "
574
+ "default) or false (straight edges)"
575
+ )
576
+ if curved and order == 1:
577
+ raise ConfigError("mesh.curved: the edges of 10-node elements (mesh.order: 2)")
578
+ phases = data.get("phases", "auto")
579
+ if phases not in ("auto", "all", "solid"):
580
+ raise ConfigError("mesh.phases: 'auto', 'all' or 'solid'")
581
+ cells = data.get("cells", "whole")
582
+ if cells not in ("whole", "box"):
583
+ raise ConfigError(
584
+ "mesh.cells: 'whole' (whole periodic grains) or 'box' (grains cut by the box)"
585
+ )
586
+ method = data.get("method", "auto")
587
+ if method not in ("auto", "exact", "grid"):
588
+ raise ConfigError(
589
+ "mesh.method: 'auto' (the exact geometry when the model has one, the grid "
590
+ "otherwise), 'exact' (the exact geometry, without a grid) or 'grid' (the level "
591
+ "set on a background grid)"
592
+ )
593
+ gradation = _positive_float("mesh.gradation", data.get("gradation", 2.0))
594
+ if gradation < 1.0:
595
+ raise ConfigError("mesh.gradation: a number >= 1 (size ratio of neighbouring elements)")
596
+ return MeshSpec(
597
+ size=_positive_float("mesh.size", data["size"]),
598
+ min_size=_positive_float("mesh.min_size", data.get("min_size"), optional=True),
599
+ hausdorff=_positive_float("mesh.hausdorff", data.get("hausdorff"), optional=True),
600
+ gradation=gradation,
601
+ background=_positive_float("mesh.background", data.get("background"), optional=True),
602
+ order=None if order is None else int(order),
603
+ curved=curved,
604
+ sharp_edges=sharp_edges,
605
+ phases=phases,
606
+ grains=grains,
607
+ min_feature=min_feature,
608
+ cells=cells,
609
+ method=method,
610
+ )
611
+
612
+
613
+ def _outputs(data, base: Path) -> OutputSpec:
614
+ allowed = {
615
+ "directory",
616
+ "name",
617
+ "geometry",
618
+ "image",
619
+ "labels",
620
+ "level_set",
621
+ "mesh",
622
+ "conforming_mesh",
623
+ "surface",
624
+ "periodic_pairs",
625
+ "periodic_equations",
626
+ "damask",
627
+ "neper",
628
+ "database",
629
+ "amitex",
630
+ "tables",
631
+ }
632
+ _check_keys("outputs", data, allowed)
633
+ mesh = data.get("mesh")
634
+ phases = None
635
+ if isinstance(mesh, dict):
636
+ _check_keys("outputs.mesh", mesh, {"formats", "phases"})
637
+ phases = mesh.get("phases")
638
+ mesh = mesh.get("formats", [])
639
+ directory = Path(data.get("directory", "morphogen_output"))
640
+ if not directory.is_absolute():
641
+ directory = base / directory
642
+ database = data.get("database")
643
+ if database is not None:
644
+ database = Path(database)
645
+ database = database if database.is_absolute() else base / database
646
+ return OutputSpec(
647
+ amitex=_amitex(data.get("amitex")),
648
+ directory=directory,
649
+ name=str(data.get("name", "sample")),
650
+ geometry=_list_of("outputs.geometry", data.get("geometry"), GEOMETRY_FORMATS),
651
+ image=_list_of("outputs.image", data.get("image"), IMAGE_FORMATS),
652
+ labels=_list_of("outputs.labels", data.get("labels"), IMAGE_FORMATS),
653
+ level_set=_list_of("outputs.level_set", data.get("level_set"), IMAGE_FORMATS),
654
+ mesh=_list_of("outputs.mesh", mesh, MESH_FORMATS),
655
+ mesh_phases=None if phases is None else [int(p) for p in phases],
656
+ conforming_mesh=_list_of(
657
+ "outputs.conforming_mesh", data.get("conforming_mesh"), MESH_FORMATS
658
+ ),
659
+ periodic_pairs=bool(data.get("periodic_pairs", False)),
660
+ periodic_equations=bool(data.get("periodic_equations", False)),
661
+ damask=bool(data.get("damask", False)),
662
+ neper=bool(data.get("neper", False)),
663
+ surface=_list_of("outputs.surface", data.get("surface"), SURFACE_FORMATS),
664
+ database=database,
665
+ tables=[
666
+ t for t in _list_of("outputs.tables", data.get("tables"), TABLE_FORMATS) if t != "csv"
667
+ ],
668
+ )
669
+
670
+
671
+ def _mfront_paths(materials, base: Path):
672
+ """The materials with the sources and libraries of their MFront behaviours, their Z-mat
673
+ files and the files of their learned laws, relative to the directory of the
674
+ configuration file."""
675
+ if not isinstance(materials, dict):
676
+ return materials
677
+ out = {}
678
+ for key, spec in materials.items():
679
+ zm = spec.get("zmat") if isinstance(spec, dict) else None
680
+ if zm is not None: # Z-mat files relative to the configuration
681
+ zm = {"file": zm} if isinstance(zm, str) else dict(zm)
682
+ if "file" in zm and not Path(str(zm["file"])).is_absolute():
683
+ zm["file"] = str(base / str(zm["file"]))
684
+ spec = {**spec, "zmat": zm}
685
+ mf = spec.get("mfront") if isinstance(spec, dict) else None
686
+ if isinstance(mf, str):
687
+ mf = {"source" if mf.endswith(".mfront") else "library": mf}
688
+ if isinstance(mf, dict):
689
+ mf = dict(mf)
690
+ for name in ("source", "library"):
691
+ if name in mf and not Path(str(mf[name])).is_absolute():
692
+ mf[name] = str(base / str(mf[name]))
693
+ spec = {**spec, "mfront": mf}
694
+ ln = spec.get("learned") if isinstance(spec, dict) else None
695
+ model = ln.get("model") if isinstance(ln, dict) else ln
696
+ if isinstance(model, str) and not Path(model).is_absolute(): # a learned law's file
697
+ model = str(base / model)
698
+ spec = {**spec, "learned": {**ln, "model": model} if isinstance(ln, dict) else model}
699
+ out[key] = spec
700
+ return out
701
+
702
+
703
+ def _diffusion(data) -> DiffusionSpec:
704
+ """The ``diffusion`` section of a configuration."""
705
+ from morphogen.coupling.diffusion import FACES
706
+
707
+ if not isinstance(data, dict):
708
+ raise ConfigError("diffusion: a mapping (phases, exposed, activity, times...)")
709
+ _check_keys(
710
+ "diffusion",
711
+ data,
712
+ {"phases", "exposed", "activity", "initial", "times", "steps", "fields"},
713
+ {"phases", "times"},
714
+ )
715
+ phases = data["phases"]
716
+ if not isinstance(phases, dict) or not phases:
717
+ raise ConfigError(
718
+ "diffusion.phases: a mapping phase -> {diffusivity, solubility, consumption}"
719
+ )
720
+ diff, sol, cons = {}, {}, {}
721
+ for key, props in phases.items():
722
+ name = f"diffusion.phases.{key}"
723
+ if not isinstance(props, dict):
724
+ raise ConfigError(f"{name}: a mapping (diffusivity, solubility, consumption)")
725
+ _check_keys(name, props, {"diffusivity", "solubility", "consumption"}, {"diffusivity"})
726
+ p = int(key)
727
+ diff[p] = float(props["diffusivity"])
728
+ sol[p] = float(props.get("solubility", 1.0))
729
+ cons[p] = float(props.get("consumption", 0.0))
730
+ if diff[p] < 0 or cons[p] < 0:
731
+ raise ConfigError(f"{name}: non-negative diffusivity and consumption")
732
+ if sol[p] <= 0:
733
+ raise ConfigError(f"{name}.solubility: positive (an impermeable phase: diffusivity 0)")
734
+ exposed = tuple(str(f) for f in (data.get("exposed") or ("x-", "x+")))
735
+ wrong = [f for f in exposed if f not in FACES]
736
+ if wrong:
737
+ raise ConfigError(f"diffusion.exposed: faces among {', '.join(FACES)}, got {wrong}")
738
+ activity = data.get("activity", 1.0)
739
+ if isinstance(activity, dict):
740
+ _check_keys("diffusion.activity", activity, {"times", "values"}, {"times", "values"})
741
+ t = tuple(float(v) for v in activity["times"])
742
+ v = tuple(float(x) for x in activity["values"])
743
+ if len(t) != len(v) or len(t) < 2 or any(b <= a for a, b in itertools.pairwise(t)):
744
+ raise ConfigError("diffusion.activity: increasing times and one value per time")
745
+ activity = (t, v)
746
+ else:
747
+ activity = float(activity)
748
+ times = tuple(
749
+ float(t) for t in (data["times"] if isinstance(data["times"], list) else [data["times"]])
750
+ )
751
+ if not times or times[0] <= 0 or any(b <= a for a, b in itertools.pairwise(times)):
752
+ raise ConfigError("diffusion.times: positive, increasing output times")
753
+ steps = _positive_int("diffusion.steps", data.get("steps", 40))
754
+ return DiffusionSpec(
755
+ diff,
756
+ sol,
757
+ cons,
758
+ exposed,
759
+ activity,
760
+ float(data.get("initial", 0.0)),
761
+ times,
762
+ steps,
763
+ bool(data.get("fields", False)),
764
+ )
765
+
766
+
767
+ def _integration(name: str, section) -> str:
768
+ """The integration of a section: 'full' or 'bbar' ('reduced': the same)."""
769
+ from morphogen.homogenization.fe import integration_of
770
+
771
+ try:
772
+ return integration_of(section["integration"])
773
+ except ValueError:
774
+ raise ConfigError(
775
+ f"{name}: 'full' (every point of the elements) or 'bbar' (also 'reduced': the "
776
+ "volume change of each element as its mean, B-bar and F-bar; for nearly "
777
+ "incompressible phases and plastic flow)"
778
+ ) from None
779
+
780
+
781
+ def _homogenization(data, base: Path | None = None) -> HomogenizationSpec:
782
+ allowed = {
783
+ "materials",
784
+ "method",
785
+ "boundary_conditions",
786
+ "properties",
787
+ "solver",
788
+ "tolerance",
789
+ "max_iterations",
790
+ "fields",
791
+ "loadings",
792
+ "paths",
793
+ "nonlinear",
794
+ "device",
795
+ "ntfa",
796
+ "mean_temperature",
797
+ "frequencies",
798
+ "wavelengths",
799
+ "fracture",
800
+ "fluid_bulk_modulus",
801
+ "integration",
802
+ "fatigue",
803
+ "beremin",
804
+ }
805
+ _check_keys("homogenization", data, allowed, {"materials"})
806
+ method = data.get("method", "auto")
807
+ if method not in HOMOGENIZATION_METHODS:
808
+ raise ConfigError(
809
+ "homogenization.method: 'fe' (finite elements on conforming meshes), 'fft' "
810
+ "(voxel images, periodic), 'xfem' (extended finite elements on the grid of the "
811
+ "voxels section, cut by the level set; periodic) or 'auto'"
812
+ )
813
+ try:
814
+ raw = data["materials"] if base is None else _mfront_paths(data["materials"], base)
815
+ materials = materials_from_config(raw)
816
+ except ValueError as exc:
817
+ raise ConfigError(f"homogenization.{exc}") from None
818
+ bcs_raw = data.get("boundary_conditions", ["periodic"])
819
+ bcs_raw = [bcs_raw] if isinstance(bcs_raw, str) else list(bcs_raw)
820
+ bcs = []
821
+ for b in bcs_raw:
822
+ try:
823
+ name = boundary_condition(b)
824
+ except ValueError as exc:
825
+ raise ConfigError(f"homogenization.boundary_conditions: {exc}") from None
826
+ if name not in bcs:
827
+ bcs.append(name)
828
+ if not bcs:
829
+ raise ConfigError("homogenization.boundary_conditions: give at least one")
830
+ paths = _paths(data.get("paths"))
831
+ props = _list_of(
832
+ "homogenization.properties",
833
+ data.get("properties", [] if paths else ["bulk_modulus", "shear_modulus"]),
834
+ tuple(PHYSICS),
835
+ )
836
+ if not props and not paths:
837
+ raise ConfigError("homogenization.properties: give at least one (or loading paths)")
838
+ solver = data.get("solver", "auto")
839
+ if solver not in SOLVERS:
840
+ raise ConfigError(f"homogenization.solver: one of {list(SOLVERS)}")
841
+ tol = float(data.get("tolerance", 1e-8))
842
+ if not 0.0 < tol < 1.0:
843
+ raise ConfigError("homogenization.tolerance: a number in (0, 1)")
844
+ maxiter = data.get("max_iterations")
845
+ if maxiter is not None:
846
+ maxiter = _positive_int("homogenization.max_iterations", maxiter)
847
+ if "subc" in bcs and any(m.void for m in materials.values()):
848
+ raise ConfigError(
849
+ "homogenization: static uniform (subc) conditions cannot be applied to porous "
850
+ "media (Dirrenberger et al. 2014); use 'mixed'"
851
+ )
852
+ loadings_raw = data.get("loadings") or {}
853
+ if not isinstance(loadings_raw, dict):
854
+ raise ConfigError("homogenization.loadings: a mapping name -> loading")
855
+ loadings = {}
856
+ for name, spec in loadings_raw.items():
857
+ name = str(name)
858
+ if name in PHYSICS or "." in name:
859
+ raise ConfigError(f"homogenization.loadings: {name!r} is not a valid name")
860
+ try:
861
+ loadings[name] = Loading.from_spec(spec)
862
+ except ValueError as exc:
863
+ raise ConfigError(f"homogenization.loadings.{name}: {exc}") from None
864
+ twice = sorted(set(loadings) & set(paths))
865
+ if twice:
866
+ raise ConfigError(f"homogenization: {twice} name both a loading and a path")
867
+ nonlinear = data.get("nonlinear") or {}
868
+ if not isinstance(nonlinear, dict):
869
+ raise ConfigError("homogenization.nonlinear: a mapping of options")
870
+ _check_keys("homogenization.nonlinear", nonlinear, set(NONLINEAR_OPTIONS), set())
871
+ nl = {}
872
+ if "tolerance" in nonlinear:
873
+ nl["tolerance"] = float(nonlinear["tolerance"])
874
+ if not 0.0 < nl["tolerance"] < 1.0:
875
+ raise ConfigError("homogenization.nonlinear.tolerance: a number in (0, 1)")
876
+ for key in ("max_iterations", "max_cuts"):
877
+ if key in nonlinear:
878
+ nl[key] = _positive_int(f"homogenization.nonlinear.{key}", nonlinear[key])
879
+ if "kinematics" in nonlinear:
880
+ nl["kinematics"] = str(nonlinear["kinematics"])
881
+ if nl["kinematics"] not in ("small", "finite"):
882
+ raise ConfigError("homogenization.nonlinear.kinematics: 'small' or 'finite' strains")
883
+ if "integration" in nonlinear:
884
+ nl["integration"] = _integration("homogenization.nonlinear.integration", nonlinear)
885
+ if "tangent" in nonlinear:
886
+ nl["tangent"] = str(nonlinear["tangent"])
887
+ if nl["tangent"] not in ("auto", "symmetric", "full"):
888
+ raise ConfigError(
889
+ "homogenization.nonlinear.tangent: 'auto', 'symmetric' (symmetrized, "
890
+ "conjugate gradients) or 'full' (GMRES)"
891
+ )
892
+ if nonlinear.get("microdamage") is not None:
893
+ nl["microdamage"] = _microdamage(
894
+ "homogenization.nonlinear.microdamage", nonlinear["microdamage"]
895
+ )
896
+ if nonlinear.get("contact") not in (None, False):
897
+ nl["contact"] = _contact("homogenization.nonlinear.contact", nonlinear["contact"])
898
+ if not paths:
899
+ raise ConfigError(
900
+ "homogenization.nonlinear.contact: the walls of the pores touch along the "
901
+ "loading paths (homogenization.paths)"
902
+ )
903
+ # walls that close move far: finite strains, unless the configuration says otherwise
904
+ nl.setdefault("kinematics", "finite")
905
+ if nonlinear.get("interfaces") not in (None, False):
906
+ name = "homogenization.nonlinear.interfaces"
907
+ nl["interfaces"] = _interfaces(name, nonlinear["interfaces"])
908
+ if not paths:
909
+ raise ConfigError(
910
+ f"{name}: the interfaces debond along the loading paths (homogenization.paths)"
911
+ )
912
+ if "contact" in nl:
913
+ raise ConfigError(
914
+ f"{name}: the interfaces of the phases, or the contact of the walls of the "
915
+ "pores (homogenization.nonlinear.contact), not both"
916
+ )
917
+ if paths and not ({"periodic", "kubc"} & set(bcs)):
918
+ raise ConfigError(
919
+ "homogenization.paths: loading paths are solved under periodic or kubc conditions"
920
+ )
921
+ device = str(data.get("device", "cpu"))
922
+ if device not in DEVICES:
923
+ raise ConfigError(f"homogenization.device: one of {list(DEVICES)} (the FFT solver)")
924
+ ntfa = _ntfa(data.get("ntfa"), paths, base)
925
+ mean_temperature = float(data.get("mean_temperature", 300.0))
926
+ if not mean_temperature > 0.0:
927
+ raise ConfigError("homogenization.mean_temperature: an absolute temperature (K)")
928
+ spectra = {}
929
+ for key, needed in (("frequencies", ("dynamic_stiffness", "complex_conductivity")),
930
+ ("wavelengths", ("refractive_index",))): # fmt: skip
931
+ values = data.get(key)
932
+ if values is not None:
933
+ values = [values] if np.ndim(values) == 0 else list(values)
934
+ try:
935
+ values = [float(v) for v in values]
936
+ except (TypeError, ValueError):
937
+ values = [-1.0]
938
+ if not values or min(values) <= 0.0:
939
+ raise ConfigError(f"homogenization.{key}: positive values")
940
+ elif any(p in props for p in needed):
941
+ asked = [p for p in needed if p in props]
942
+ raise ConfigError(f"homogenization.{key}: those of the properties {asked}")
943
+ spectra[key] = values
944
+ fracture = data.get("fracture")
945
+ if fracture is not None:
946
+ from morphogen.fracture.phasefield import PhaseField
947
+
948
+ if not isinstance(fracture, dict):
949
+ raise ConfigError("homogenization.fracture: a mapping (toughness, length, ...)")
950
+ solver_keys = {"staggered_tol", "max_staggered", "tol"}
951
+ try:
952
+ PhaseField.from_config({k: v for k, v in fracture.items() if k not in solver_keys})
953
+ except (ValueError, TypeError) as exc:
954
+ raise ConfigError(f"homogenization.fracture: {exc}") from None
955
+ if not paths:
956
+ raise ConfigError(
957
+ "homogenization.fracture: the loading paths along which the samples break "
958
+ "(homogenization.paths)"
959
+ )
960
+ fracture = dict(fracture)
961
+ fluid = data.get("fluid_bulk_modulus")
962
+ if fluid is not None:
963
+ try:
964
+ fluid = float(fluid)
965
+ except (TypeError, ValueError):
966
+ fluid = -1.0
967
+ if not fluid > 0.0:
968
+ raise ConfigError("homogenization.fluid_bulk_modulus: a positive bulk modulus")
969
+ if "poroelastic" not in props:
970
+ raise ConfigError(
971
+ "homogenization.fluid_bulk_modulus: that of the property 'poroelastic'"
972
+ )
973
+ if "poroelastic" in props:
974
+ if not any(m.void for m in materials.values()):
975
+ raise ConfigError(
976
+ "homogenization.properties: 'poroelastic' needs pores (a material 'void')"
977
+ )
978
+ if not {"periodic", "kubc"} & set(bcs):
979
+ raise ConfigError(
980
+ "homogenization.properties: 'poroelastic' is computed under periodic or kubc "
981
+ "conditions"
982
+ )
983
+ flows = [p for p in props if PHYSICS[p] == "flow"]
984
+ if flows and not any(m.void for m in materials.values()):
985
+ raise ConfigError(
986
+ f"homogenization.properties: {flows} need pores (a material 'void'): the fluid "
987
+ "flows through them"
988
+ )
989
+ if "swelling" in props and not any(m.swelling is not None for m in materials.values()):
990
+ raise ConfigError(
991
+ "homogenization.properties: 'swelling' needs the swelling of a material "
992
+ "(materials: {phase: {swelling: ...}})"
993
+ )
994
+ return HomogenizationSpec(
995
+ materials=materials,
996
+ method=method,
997
+ boundary_conditions=bcs,
998
+ properties=props,
999
+ solver=solver,
1000
+ tolerance=tol,
1001
+ max_iterations=maxiter,
1002
+ fields=bool(data.get("fields", False)),
1003
+ loadings=loadings,
1004
+ paths=paths,
1005
+ nonlinear=nl,
1006
+ device=device,
1007
+ ntfa=ntfa,
1008
+ mean_temperature=mean_temperature,
1009
+ fracture=fracture,
1010
+ fluid_bulk_modulus=fluid,
1011
+ integration=_integration("homogenization.integration", data)
1012
+ if data.get("integration") is not None
1013
+ else None,
1014
+ fatigue=_fatigue(data.get("fatigue"), paths, materials),
1015
+ beremin=_beremin(data.get("beremin"), paths),
1016
+ **spectra,
1017
+ )
1018
+
1019
+
1020
+ #: The scalar results of the fatigue of a cycle (quantities of its loading path)
1021
+ FATIGUE_QUANTITIES = ("fatigue_utilization", "fatigue_safety", "fatigue_beyond")
1022
+
1023
+
1024
+ def _beremin(value, paths: dict) -> dict | None:
1025
+ """The criterion of cleavage of Beremin along a loading path (``homogenization.
1026
+ beremin``): its ``modulus``, ``scale`` and reference ``volume``, the cleavage
1027
+ ``planes`` of the crystals and the ``plastic`` strain of the plastic zone; the
1028
+ ``path`` (the only one, when left out)."""
1029
+ from morphogen.homogenization.beremin import Beremin
1030
+
1031
+ if value is None:
1032
+ return None
1033
+ name = "homogenization.beremin"
1034
+ if not isinstance(value, dict):
1035
+ raise ConfigError(f"{name}: a mapping (modulus, scale, volume, planes, plastic, path)")
1036
+ if not paths:
1037
+ raise ConfigError(f"{name}: the fields of a loading path (homogenization.paths)")
1038
+ value = dict(value)
1039
+ path = value.pop("path", None)
1040
+ if path is None and len(paths) != 1:
1041
+ raise ConfigError(f"{name}.path: one of the loading paths {list(paths)}")
1042
+ path = next(iter(paths)) if path is None else str(path)
1043
+ if path not in paths:
1044
+ raise ConfigError(f"{name}.path: one of the loading paths {list(paths)}, got {path!r}")
1045
+ try:
1046
+ Beremin.from_config(value)
1047
+ except (TypeError, ValueError) as exc:
1048
+ raise ConfigError(f"{name}: {str(exc).removeprefix('beremin: ')}") from None
1049
+ return {"path": path, "criterion": value}
1050
+
1051
+
1052
+ def _fatigue(value, paths: dict, materials: dict) -> dict | None:
1053
+ """The fatigue of the points along a cycle of a loading path (``homogenization.
1054
+ fatigue``): one criterion and its limits for the solid phases (or those of
1055
+ ``phases``), or the ``criteria`` of the phases; the ``path`` (the only one, when
1056
+ left out) and the times of its ``cycle`` (the whole path)."""
1057
+ from morphogen.homogenization.fatigue import criterion_from_config
1058
+
1059
+ if value is None:
1060
+ return None
1061
+ name = "homogenization.fatigue"
1062
+ if not isinstance(value, dict):
1063
+ raise ConfigError(f"{name}: a mapping (criterion, bending, torsion, path, cycle...)")
1064
+ if not paths:
1065
+ raise ConfigError(f"{name}: the cycle of a loading path (homogenization.paths)")
1066
+ value = dict(value)
1067
+ path = value.pop("path", None)
1068
+ if path is None and len(paths) != 1:
1069
+ raise ConfigError(f"{name}.path: one of the loading paths {list(paths)}")
1070
+ path = next(iter(paths)) if path is None else str(path)
1071
+ if path not in paths:
1072
+ raise ConfigError(f"{name}.path: one of the loading paths {list(paths)}, got {path!r}")
1073
+ cycle = value.pop("cycle", None)
1074
+ steps = np.concatenate([[paths[path].times[0]], paths[path].schedule()])
1075
+ if cycle is not None:
1076
+ try:
1077
+ start, end = (float(v) for v in cycle)
1078
+ except (TypeError, ValueError):
1079
+ raise ConfigError(f"{name}.cycle: the times of its start and of its end") from None
1080
+ if not steps[0] <= start < end <= steps[-1]:
1081
+ raise ConfigError(
1082
+ f"{name}.cycle: two times of the path {path!r}, from {steps[0]:g} to "
1083
+ f"{steps[-1]:g}, the first before the second"
1084
+ )
1085
+ cycle = (start, end)
1086
+ steps = steps[(steps >= start - 1e-9) & (steps <= end + 1e-9)]
1087
+ if steps.size < 3:
1088
+ raise ConfigError(
1089
+ f"{name}: a cycle of two steps of the path {path!r} at least (its fields are "
1090
+ "kept at the ends of its steps)"
1091
+ )
1092
+ solid = sorted(p for p, m in materials.items() if not m.void)
1093
+ criteria = value.pop("criteria", None)
1094
+ phases = value.pop("phases", None)
1095
+ try:
1096
+ if criteria is not None:
1097
+ if value or phases is not None or not isinstance(criteria, dict) or not criteria:
1098
+ raise ValueError
1099
+ specs = {int(p): dict(c) for p, c in criteria.items()}
1100
+ else:
1101
+ chosen = solid if phases is None else np.atleast_1d(phases).tolist()
1102
+ specs = {int(p): dict(value) for p in chosen}
1103
+ except (TypeError, ValueError):
1104
+ raise ConfigError(
1105
+ f"{name}: one criterion and its limits (for the solid phases, or 'phases'), or "
1106
+ "'criteria', a mapping of the phases to theirs"
1107
+ ) from None
1108
+ absent = sorted(set(specs) - set(solid))
1109
+ if absent:
1110
+ raise ConfigError(f"{name}: {absent} are not solid phases of the materials {solid}")
1111
+ for phase, spec in specs.items():
1112
+ try:
1113
+ criterion_from_config(spec)
1114
+ except ValueError as exc:
1115
+ raise ConfigError(f"{name} (phase {phase}): {exc}") from None
1116
+ return {"path": path, "cycle": cycle, "criteria": specs}
1117
+
1118
+
1119
+ def _ntfa(raw, paths, base: Path | None) -> dict:
1120
+ """Options of the reduced model (NTFA) that follows the loading paths."""
1121
+ if raw is None:
1122
+ return {}
1123
+ if not isinstance(raw, dict):
1124
+ raise ConfigError("homogenization.ntfa: a mapping (training, modes, save, full_field)")
1125
+ _check_keys(
1126
+ "homogenization.ntfa", raw, {"training", "modes", "save", "full_field"}, {"training"}
1127
+ )
1128
+ if not paths:
1129
+ raise ConfigError("homogenization.ntfa: give the paths to follow (homogenization.paths)")
1130
+ try:
1131
+ training = _paths(raw["training"])
1132
+ except ConfigError as exc:
1133
+ raise ConfigError(
1134
+ str(exc).replace("homogenization.paths", "homogenization.ntfa.training")
1135
+ ) from None
1136
+ if not training:
1137
+ raise ConfigError("homogenization.ntfa.training: at least one path")
1138
+ modes = raw.get("modes", 6)
1139
+ if isinstance(modes, dict):
1140
+ modes = {
1141
+ int(k): _positive_int(f"homogenization.ntfa.modes.{k}", v) for k, v in modes.items()
1142
+ }
1143
+ else:
1144
+ modes = _positive_int("homogenization.ntfa.modes", modes)
1145
+ out = {"training": training, "modes": modes, "full_field": bool(raw.get("full_field", False))}
1146
+ if raw.get("save"):
1147
+ save = Path(str(raw["save"]))
1148
+ out["save"] = str(save if base is None or save.is_absolute() else base / save)
1149
+ return out
1150
+
1151
+
1152
+ def _paths(raw) -> dict[str, LoadingPath]:
1153
+ """Loading paths of a configuration (name -> path)."""
1154
+ raw = raw or {}
1155
+ if not isinstance(raw, dict):
1156
+ raise ConfigError("homogenization.paths: a mapping name -> path")
1157
+ out = {}
1158
+ for name, spec in raw.items():
1159
+ name = str(name)
1160
+ if name in PHYSICS or "." in name:
1161
+ raise ConfigError(f"homogenization.paths: {name!r} is not a valid name")
1162
+ try:
1163
+ out[name] = LoadingPath.from_spec(spec)
1164
+ except ValueError as exc:
1165
+ raise ConfigError(f"homogenization.paths.{name}: {exc}") from None
1166
+ return out
1167
+
1168
+
1169
+ def _rve_properties(value, homog: HomogenizationSpec | None) -> list[str]:
1170
+ """RVE properties: measures, apparent properties (all their BCs) or '<prop>.<bc>', the
1171
+ stiffness ('stiffness' or 'stiffness.<bc>': its mean and compliance per volume) and the
1172
+ conductivity tensor ('conductivity_tensor', '.<bc>') like the tensors of the other
1173
+ transport phenomena, quantities of the curves of the loading paths
1174
+ ('<path>.<quantity>[@<time>][.<bc>]': a column, or 'strength' and 'work') and scalar
1175
+ results of the strong couplings and of the harmonic properties
1176
+ ('<property>.<entry>[.<bc>]': 'piezoelectric.e33', 'dynamic_stiffness.shear_loss_1')."""
1177
+ series = homog.series() if homog is not None else []
1178
+ tensors = homog.tensors() if homog is not None else []
1179
+ if value is None:
1180
+ return ["volume_fraction", *series, *tensors]
1181
+ items = [value] if isinstance(value, str) else list(value)
1182
+ out = []
1183
+ for item in items:
1184
+ item = str(item)
1185
+ if item in MEASURES or item in series or item in tensors:
1186
+ names = [item]
1187
+ elif homog is not None and item in homog.properties and item in PROPERTIES:
1188
+ names = [f"{item}.{bc}" for bc in homog.boundary_conditions]
1189
+ elif item in TENSOR_PROPERTIES and any(t.startswith(f"{item}.") for t in tensors):
1190
+ names = [t for t in tensors if t.startswith(f"{item}.")]
1191
+ elif homog is not None and "." in item and item.partition(".")[0] in homog.paths:
1192
+ names = [_path_quantity(item, homog)]
1193
+ elif homog is not None and item.partition(".")[0] in _entry_properties(homog):
1194
+ names = [_property_entry(item, homog)]
1195
+ else:
1196
+ heads = [p for p in TENSOR_PROPERTIES if any(t.startswith(f"{p}.") for t in tensors)]
1197
+ allowed = list(MEASURES) + series + heads + tensors
1198
+ if homog is not None and homog.paths:
1199
+ allowed.append("<path>.<quantity>[@<time>][.<bc>] (e.g. tension.S11@5)")
1200
+ for prop in _entry_properties(homog) if homog is not None else ():
1201
+ allowed.append(
1202
+ f"{prop}.<entry>[.<bc>] (e.g. {prop}.{_entry_names(prop, homog)[0]})"
1203
+ )
1204
+ raise ConfigError(f"rve.properties: unknown value {item!r}; allowed: {allowed}")
1205
+ out.extend(n for n in names if n not in out)
1206
+ return out
1207
+
1208
+
1209
+ def path_quantities(names, homog: HomogenizationSpec | None) -> list[PathQuantity]:
1210
+ """The quantities of the loading paths of ``homog`` among the RVE properties ``names``."""
1211
+ if homog is None or not homog.paths:
1212
+ return []
1213
+ return [PathQuantity.parse(n) for n in names if "." in n and n.partition(".")[0] in homog.paths]
1214
+
1215
+
1216
+ def _entry_properties(homog: HomogenizationSpec) -> list[str]:
1217
+ """The properties computed whose results are named scalars: the strong couplings and
1218
+ the harmonic properties."""
1219
+ named = ("thermal_expansion", "swelling", "poroelastic")
1220
+ families = ("coupled", "harmonic", "flow")
1221
+ return [p for p in homog.properties if PHYSICS.get(p) in families or p in named]
1222
+
1223
+
1224
+ def _entry_names(prop: str, homog: HomogenizationSpec) -> tuple[str, ...]:
1225
+ """The scalar results of a coupled or harmonic property of ``homog``, of its
1226
+ poroelastic law and of its tensors of thermal expansion and of swelling."""
1227
+ if prop == "poroelastic":
1228
+ from morphogen.homogenization.poroelastic import POROELASTIC_ENTRIES, UNDRAINED_ENTRIES
1229
+
1230
+ fluid = homog.fluid_bulk_modulus is not None
1231
+ return (*POROELASTIC_ENTRIES, *(UNDRAINED_ENTRIES if fluid else ()))
1232
+ if prop in ("thermal_expansion", "swelling"):
1233
+ letter = "A" if prop == "thermal_expansion" else "B"
1234
+ return (*(f"{letter}{name}" for name in VOIGT_NAMES), "mean")
1235
+ if prop == "hydraulic_permeability":
1236
+ from morphogen.homogenization.flow import ENTRIES
1237
+
1238
+ return ENTRIES
1239
+ if prop == "acoustic":
1240
+ from morphogen.homogenization.acoustics import PARAMETERS
1241
+
1242
+ return PARAMETERS
1243
+ if PHYSICS[prop] == "coupled":
1244
+ from morphogen.homogenization.coupled import entry_names
1245
+
1246
+ return entry_names(prop)
1247
+ from morphogen.homogenization.harmonic import entry_names
1248
+
1249
+ values = homog.wavelengths if prop == "refractive_index" else homog.frequencies
1250
+ return entry_names(prop, np.size(values))
1251
+
1252
+
1253
+ def _property_entry(item: str, homog: HomogenizationSpec) -> str:
1254
+ """Canonical name ``<property>.<entry>[.<bc>]`` of a scalar result of a strong coupling
1255
+ or of a harmonic property, checked against the results of the property."""
1256
+ prop, _, rest = item.partition(".")
1257
+ entry, _, bc = rest.partition(".")
1258
+ names = _entry_names(prop, homog)
1259
+ if entry not in names:
1260
+ shown = ", ".join(names[:12]) + (" ..." if len(names) > 12 else "")
1261
+ raise ConfigError(
1262
+ f"rve.properties: {item!r}: unknown result {entry!r} of {prop}; use one of {shown}"
1263
+ )
1264
+ if PHYSICS[prop] == "elastic": # under the conditions of the elastic problems
1265
+ solved = [b for b in homog.boundary_conditions if b != "mixed"]
1266
+ if prop == "poroelastic":
1267
+ solved = [b for b in solved if b != "subc"]
1268
+ if bc:
1269
+ try:
1270
+ bc = boundary_condition(bc)
1271
+ except ValueError as exc:
1272
+ raise ConfigError(f"rve.properties: {item!r}: {exc}") from None
1273
+ if bc not in solved:
1274
+ raise ConfigError(
1275
+ f"rve.properties: {item!r}: {prop} is computed under {solved} conditions"
1276
+ )
1277
+ return f"{prop}.{entry}" + (f".{bc}" if bc else "")
1278
+ if bc and bc != "periodic":
1279
+ raise ConfigError(f"rve.properties: {item!r}: {prop} is solved under periodic conditions")
1280
+ return f"{prop}.{entry}" + (".periodic" if bc else "")
1281
+
1282
+
1283
+ def property_entries(names, homog: HomogenizationSpec | None) -> list[tuple[str, str]]:
1284
+ """The scalar results ``(property, entry)`` of the strong couplings and of the harmonic
1285
+ properties of ``homog`` among the RVE properties ``names``."""
1286
+ if homog is None:
1287
+ return []
1288
+ props = _entry_properties(homog)
1289
+ out = []
1290
+ for name in names:
1291
+ prop, _, rest = str(name).partition(".")
1292
+ if prop in props and rest:
1293
+ out.append((prop, rest.partition(".")[0]))
1294
+ return out
1295
+
1296
+
1297
+ def _microdamage(name: str, value) -> dict:
1298
+ """The options of the alternate scheme of the microdamage of regularized cleavage
1299
+ planes (``homogenization.nonlinear.microdamage``): its ``tolerance``, the most
1300
+ ``passes`` of a step, its ``acceleration``."""
1301
+ if not isinstance(value, dict):
1302
+ raise ConfigError(f"{name}: a mapping (tolerance, passes, acceleration)")
1303
+ _check_keys(name, value, {"tolerance", "passes", "acceleration"}, set())
1304
+ out = {}
1305
+ if "tolerance" in value:
1306
+ tolerance = value["tolerance"]
1307
+ if isinstance(tolerance, bool) or not isinstance(tolerance, (int, float)):
1308
+ raise ConfigError(f"{name}.tolerance: a number in (0, 1)")
1309
+ if not 0.0 < tolerance < 1.0:
1310
+ raise ConfigError(f"{name}.tolerance: a number in (0, 1)")
1311
+ out["tolerance"] = float(tolerance)
1312
+ if "passes" in value:
1313
+ out["passes"] = _positive_int(f"{name}.passes", value["passes"])
1314
+ if "acceleration" in value:
1315
+ if not isinstance(value["acceleration"], bool):
1316
+ raise ConfigError(f"{name}.acceleration: true or false")
1317
+ out["acceleration"] = value["acceleration"]
1318
+ return out
1319
+
1320
+
1321
+ def _contact(name: str, value) -> dict:
1322
+ """The options of the contact of the walls of the pores along the loading paths
1323
+ (``true``, or a mapping of them): those of morphogen.contact.periodic.ContactCell."""
1324
+ if value is True:
1325
+ return {}
1326
+ if not isinstance(value, dict):
1327
+ raise ConfigError(f"{name}: true, or a mapping of its options {list(CONTACT_OPTIONS)}")
1328
+ _check_keys(name, value, set(CONTACT_OPTIONS), set())
1329
+ out = {}
1330
+ for key in ("friction", "stiffness", "tangential", "depth", "tolerance"):
1331
+ if key not in value:
1332
+ continue
1333
+ number = value[key]
1334
+ if isinstance(number, bool) or not isinstance(number, (int, float)):
1335
+ raise ConfigError(f"{name}.{key}: a number, got {number!r}")
1336
+ out[key] = float(number)
1337
+ if key == "friction" and not (np.isfinite(out[key]) and out[key] >= 0):
1338
+ raise ConfigError(f"{name}.friction: Coulomb's coefficient, 0 or more")
1339
+ if key != "friction" and not (np.isfinite(out[key]) and out[key] > 0):
1340
+ raise ConfigError(f"{name}.{key}: a positive number")
1341
+ if "augmentations" in value:
1342
+ count = value["augmentations"]
1343
+ if isinstance(count, bool) or not isinstance(count, int) or count < 0:
1344
+ raise ConfigError(f"{name}.augmentations: a number of updates of the multipliers")
1345
+ out["augmentations"] = count
1346
+ if "points" in value:
1347
+ if value["points"] not in ("gauss", "nodes"):
1348
+ raise ConfigError(
1349
+ f"{name}.points: 'gauss' (inside the faces) or 'nodes' (their nodes: corners "
1350
+ f"and edges that touch), got {value['points']!r}"
1351
+ )
1352
+ out["points"] = value["points"]
1353
+ return out
1354
+
1355
+
1356
+ #: The options of the cell of the interfaces, beside their law
1357
+ _CELL_OPTIONS = ("faces", "viscosity", "slip")
1358
+
1359
+
1360
+ def _interface_numbers(name: str, value: dict, keys) -> dict:
1361
+ """The numbers ``keys`` of the options of the interfaces: positive, or of 0 or more
1362
+ for the friction and the viscosity."""
1363
+ out = {}
1364
+ for key in keys:
1365
+ if key not in value or value[key] is None:
1366
+ continue
1367
+ number = value[key]
1368
+ if isinstance(number, bool) or not isinstance(number, (int, float)):
1369
+ raise ConfigError(f"{name}.{key}: a number, got {number!r}")
1370
+ out[key] = float(number)
1371
+ if key in ("friction", "viscosity"):
1372
+ if not (np.isfinite(out[key]) and out[key] >= 0):
1373
+ raise ConfigError(f"{name}.{key}: a number of 0 or more")
1374
+ elif not (np.isfinite(out[key]) and out[key] > 0):
1375
+ raise ConfigError(f"{name}.{key}: a positive number")
1376
+ return out
1377
+
1378
+
1379
+ def _interface_law(name: str, value, extra=()) -> dict:
1380
+ """A law of interfaces: its kind and its parameters (morphogen.fracture.periodic.
1381
+ interface_law); ``extra``: the other keys allowed beside them."""
1382
+ from morphogen.fracture.periodic import LAW_OPTIONS
1383
+
1384
+ if not isinstance(value, dict):
1385
+ raise ConfigError(f"{name}: a mapping of the law of the interfaces and its parameters")
1386
+ law = str(value.get("law", "bilinear"))
1387
+ if law not in LAW_OPTIONS:
1388
+ raise ConfigError(f"{name}.law: one of {list(LAW_OPTIONS)}, got {law!r}")
1389
+ allowed = set(LAW_OPTIONS[law]) | {"law", *extra}
1390
+ foreign = sorted(set(value) - allowed)
1391
+ if foreign:
1392
+ raise ConfigError(
1393
+ f"{name}: {foreign} are not parameters of the law {law!r}; use {sorted(allowed)}"
1394
+ )
1395
+ required = {"bilinear": ("normal_strength", "mode_I"), "exponential": ("strength", "energy")}
1396
+ missing = [key for key in required.get(law, ()) if key not in value]
1397
+ if missing:
1398
+ raise ConfigError(f"{name}: the law {law!r} needs {missing}")
1399
+ return {"law": law, **_interface_numbers(name, value, LAW_OPTIONS[law])}
1400
+
1401
+
1402
+ def _interfaces(name: str, value) -> dict:
1403
+ """The law of the interfaces of the phases along the loading paths — or their
1404
+ ``laws``, by pair of phases (``"0-1"``) — and the options of their cell (a mapping):
1405
+ those of morphogen.fracture.periodic (interface_law and CohesiveCell)."""
1406
+ if not isinstance(value, dict):
1407
+ raise ConfigError(f"{name}: a mapping of the law of the interfaces and its options")
1408
+ _check_keys(name, value, set(INTERFACE_OPTIONS), set())
1409
+ if "laws" in value:
1410
+ foreign = sorted(set(value) - {"laws", *_CELL_OPTIONS})
1411
+ laws = value["laws"]
1412
+ if foreign or not isinstance(laws, dict) or not laws:
1413
+ raise ConfigError(
1414
+ f"{name}: 'laws', a mapping of pairs of phases (0-1) to their laws, beside "
1415
+ f"{list(_CELL_OPTIONS)} only"
1416
+ )
1417
+ out: dict = {"laws": {}}
1418
+ for key, law in laws.items():
1419
+ try:
1420
+ p, q = sorted(int(part) for part in str(key).split("-"))
1421
+ except ValueError:
1422
+ raise ConfigError(f"{name}.laws: pairs of two phases (0-1), got {key!r}") from None
1423
+ out["laws"][f"{p}-{q}"] = _interface_law(f"{name}.laws.{key}", law)
1424
+ else:
1425
+ out = _interface_law(name, value, _CELL_OPTIONS)
1426
+ out.update(_interface_numbers(name, value, ("viscosity", "slip")))
1427
+ faces = value.get("faces", "phases")
1428
+ if isinstance(faces, str):
1429
+ if faces not in ("phases", "grains"):
1430
+ raise ConfigError(f"{name}.faces: 'phases', 'grains' or pairs of phases")
1431
+ else:
1432
+ try:
1433
+ faces = [[int(p) for p in pair] for pair in faces]
1434
+ except (TypeError, ValueError):
1435
+ faces = []
1436
+ if not faces or any(len(pair) != 2 or pair[0] == pair[1] for pair in faces):
1437
+ raise ConfigError(
1438
+ f"{name}.faces: 'phases', 'grains' or pairs of two different phases ([[0, 1]])"
1439
+ )
1440
+ out["faces"] = faces
1441
+ return out
1442
+
1443
+
1444
+ def _path_quantity(item: str, homog: HomogenizationSpec) -> str:
1445
+ """Canonical name of a quantity of a loading path, checked against the path (its
1446
+ times), the boundary conditions and the components of the curves."""
1447
+ try:
1448
+ q = PathQuantity.parse(item)
1449
+ except ValueError as exc:
1450
+ raise ConfigError(f"rve.properties: {exc}") from None
1451
+ finite = homog.nonlinear.get("kinematics") == "finite"
1452
+ families = ["E", "S", "LE", "TS"] if finite else ["E", "S"]
1453
+ allowed = [f + n for f in families for n in VOIGT_NAMES] + ["p"]
1454
+ phases = [p for p, m in homog.materials.items() if not m.void]
1455
+ allowed += [
1456
+ f"{f}{n}_{p}"
1457
+ for p in phases
1458
+ for f in (["S", "TS"] if finite else ["S"])
1459
+ for n in VOIGT_NAMES
1460
+ ]
1461
+ allowed += [f"p_{p}" for p in phases]
1462
+ # the largest stress of the loading and the work done; the columns of a fracture
1463
+ allowed += ["strength", "work"]
1464
+ if homog.fracture:
1465
+ allowed += ["damage", "crack_surface", "elastic_energy", "fracture_energy"]
1466
+ contact = homog.nonlinear.get("contact") is not None
1467
+ if contact:
1468
+ from morphogen.contact.periodic import SERIES
1469
+
1470
+ allowed += list(SERIES)
1471
+ interfaces = homog.nonlinear.get("interfaces") is not None
1472
+ if interfaces:
1473
+ from morphogen.fracture.periodic import SERIES as DEBONDING
1474
+
1475
+ allowed += list(DEBONDING)
1476
+ # the twinned fraction, the opening and the damage of the cleavage planes of crystals
1477
+ crystals = [m.crystal_plasticity for m in homog.materials.values() if m.crystal_plastic]
1478
+ twinned = list(dict.fromkeys(name for cp in crystals for name in cp.field_names))
1479
+ allowed += twinned
1480
+ fatigue = homog.fatigue is not None and homog.fatigue["path"] == q.path
1481
+ if fatigue:
1482
+ allowed += list(FATIGUE_QUANTITIES)
1483
+ beremin = homog.beremin is not None and homog.beremin["path"] == q.path
1484
+ if beremin:
1485
+ from morphogen.homogenization.beremin import SERIES as BEREMIN
1486
+
1487
+ allowed += list(BEREMIN)
1488
+ if q.quantity not in allowed:
1489
+ raise ConfigError(
1490
+ f"rve.properties: {item!r}: unknown quantity {q.quantity!r} of the curves; use "
1491
+ f"E11 ... S12{', LE11 ... TS12' if finite else ''}, p, a phase (S11_<phase>, "
1492
+ "p_<phase>), strength or work"
1493
+ + (", damage, crack_surface, elastic_energy, fracture_energy" if homog.fracture else "")
1494
+ + (
1495
+ ", contact_area, contact_pressure, contact_penetration, contact_dissipation"
1496
+ if contact
1497
+ else ""
1498
+ )
1499
+ + (
1500
+ ", debonded_area, interface_damage, interface_opening, interface_dissipation"
1501
+ if interfaces
1502
+ else ""
1503
+ )
1504
+ + (", fatigue_utilization, fatigue_safety, fatigue_beyond" if fatigue else "")
1505
+ + (f", {', '.join(twinned)}" if twinned else "")
1506
+ + (", beremin_weibull, beremin_probability" if beremin else "")
1507
+ )
1508
+ if q.time is not None:
1509
+ ends = homog.paths[q.path].schedule()
1510
+ if not np.any(np.isclose(ends, q.time, rtol=1e-9, atol=1e-12)):
1511
+ raise ConfigError(
1512
+ f"rve.properties: {item!r}: no step of the path {q.path!r} ends at the time "
1513
+ f"{q.time:g} (the steps end at {[float(f'{t:.6g}') for t in ends]})"
1514
+ )
1515
+ solved = [b for b in homog.boundary_conditions if b in ("periodic", "kubc")]
1516
+ if q.bc is not None and q.bc not in solved:
1517
+ raise ConfigError(
1518
+ f"rve.properties: {item!r}: the paths are solved under {solved} conditions"
1519
+ )
1520
+ return q.key
1521
+
1522
+
1523
+ def _rve(data, homog: HomogenizationSpec | None = None) -> RVESpec:
1524
+ allowed = {
1525
+ "method",
1526
+ "sizes",
1527
+ "realizations",
1528
+ "size",
1529
+ "window_sizes",
1530
+ "properties",
1531
+ "relative_errors",
1532
+ "n_realizations",
1533
+ "gamma",
1534
+ "min_volume",
1535
+ "max_volume",
1536
+ "bootstrap",
1537
+ "weights",
1538
+ "shifts",
1539
+ }
1540
+ _check_keys("rve", data, allowed)
1541
+ method = data.get("method", "ensemble")
1542
+ if method not in ("ensemble", "windows"):
1543
+ raise ConfigError("rve.method: 'ensemble' or 'windows'")
1544
+ spec = RVESpec(method=method)
1545
+ if "shifts" in data:
1546
+ if method != "windows":
1547
+ raise ConfigError("rve.shifts: the shifted tilings of the window method")
1548
+ spec.shifts = _positive_int("rve.shifts", data["shifts"])
1549
+ spec.properties = _rve_properties(data.get("properties"), homog)
1550
+ spec.relative_errors = [float(e) for e in data.get("relative_errors", [0.01, 0.05])]
1551
+ spec.n_realizations = [int(n) for n in data.get("n_realizations", [1, 10])]
1552
+ if any(e <= 0 for e in spec.relative_errors) or any(n < 1 for n in spec.n_realizations):
1553
+ raise ConfigError("rve: relative_errors must be positive and n_realizations >= 1")
1554
+ spec.gamma = None if data.get("gamma") is None else float(data["gamma"])
1555
+ spec.min_volume = data.get("min_volume")
1556
+ spec.max_volume = data.get("max_volume")
1557
+ boot = data.get("bootstrap", 1000)
1558
+ if isinstance(boot, bool) or not isinstance(boot, int) or boot < 0:
1559
+ raise ConfigError("rve.bootstrap: a non-negative integer (number of replicates)")
1560
+ spec.bootstrap = boot
1561
+ spec.weights = str(data.get("weights", "none"))
1562
+ if spec.weights not in ("none", "n"):
1563
+ raise ConfigError("rve.weights: 'none' or 'n'")
1564
+ if method == "ensemble":
1565
+ if "sizes" not in data or "realizations" not in data:
1566
+ raise ConfigError("rve: the ensemble method needs 'sizes' and 'realizations'")
1567
+ spec.sizes = [float(s) for s in data["sizes"]]
1568
+ reals = data["realizations"]
1569
+ reals = [reals] * len(spec.sizes) if isinstance(reals, int) else list(reals)
1570
+ if len(reals) != len(spec.sizes):
1571
+ raise ConfigError("rve.realizations: one number, or one per size")
1572
+ spec.realizations = [_positive_int("rve.realizations", r) for r in reals]
1573
+ else:
1574
+ if "size" not in data or "window_sizes" not in data:
1575
+ raise ConfigError("rve: the window method needs 'size' and 'window_sizes'")
1576
+ spec.size = float(data["size"])
1577
+ spec.window_sizes = [float(w) for w in data["window_sizes"]]
1578
+ if homog is not None:
1579
+ _window_homogenization(homog)
1580
+ tensors = homog.tensors() if homog is not None else []
1581
+ bad = [p for p in spec.properties if p != "volume_fraction" and p not in tensors]
1582
+ if bad:
1583
+ raise ConfigError(
1584
+ "rve: the window method measures volume_fraction and the tensors of its "
1585
+ f"windows (stiffness, conductivity_tensor), not {bad}"
1586
+ )
1587
+ return spec
1588
+
1589
+
1590
+ def _window_homogenization(homog: HomogenizationSpec) -> None:
1591
+ """The homogenization of a window study: the tensors of its windows (the stiffness, the
1592
+ conductivity tensor), the realization solved once per unit load by the FFT solver."""
1593
+ other = [p for p in homog.properties if p not in TENSOR_PROPERTIES]
1594
+ if other or not homog.properties:
1595
+ raise ConfigError(
1596
+ "rve: the window method computes the tensors of its windows "
1597
+ f"(homogenization.properties: stiffness, conductivity_tensor), not {other}"
1598
+ )
1599
+ if homog.loadings or homog.paths or homog.ntfa:
1600
+ raise ConfigError(
1601
+ "rve: the window method solves the unit loads of its tensors, not loadings or "
1602
+ "paths (homogenization.loadings, paths, ntfa)"
1603
+ )
1604
+ if homog.fields:
1605
+ raise ConfigError("rve: the window method writes no fields (homogenization.fields)")
1606
+
1607
+
1608
+ def _colormap(section: str, value) -> str:
1609
+ """A matplotlib colormap name (checked when matplotlib is installed)."""
1610
+ name = str(value)
1611
+ try:
1612
+ import matplotlib
1613
+ except ImportError: # pragma: no cover - checked when the figures are drawn
1614
+ return name
1615
+ if name not in matplotlib.colormaps:
1616
+ raise ConfigError(f"{section}: {name!r} is not a matplotlib colormap (viridis, ...)")
1617
+ return name
1618
+
1619
+
1620
+ def _field_kind(physics: str) -> str:
1621
+ """The kind of fields of the solutions of a physics: "elastic", or "thermal" for
1622
+ every transport phenomenon of a scalar potential."""
1623
+ return "elastic" if physics == "elastic" else "thermal"
1624
+
1625
+
1626
+ def _result_group(section: str, of: str, homog: HomogenizationSpec | None) -> tuple[str, str]:
1627
+ """The group ("result" or "path") and the kind of fields ("elastic", "thermal",
1628
+ "path") of a view of the result ``of`` = ``<name>.<bc>`` of the homogenization (the
1629
+ fields of every transport phenomenon are those of the kind "thermal": a potential,
1630
+ its gradient and its flux)."""
1631
+ key, dot, bc = of.rpartition(".")
1632
+ if not dot or not key:
1633
+ raise ConfigError(
1634
+ f"{section}.of: 'image', 'labels', 'mesh' or a result '<name>.<bc>' of the "
1635
+ f"homogenization, got {of!r}"
1636
+ )
1637
+ if homog is None:
1638
+ raise ConfigError(f"{section}.of: {of!r} is a result of the homogenization section")
1639
+ if bc not in homog.boundary_conditions:
1640
+ raise ConfigError(
1641
+ f"{section}.of: {bc!r} is not one of the boundary conditions "
1642
+ f"{homog.boundary_conditions}"
1643
+ )
1644
+ if key in homog.paths:
1645
+ if bc not in ("periodic", "kubc"):
1646
+ raise ConfigError(f"{section}.of: loading paths are followed under periodic or kubc")
1647
+ if homog.ntfa and not homog.ntfa.get("full_field"):
1648
+ raise ConfigError(f"{section}.of: the paths are followed by the NTFA model only")
1649
+ return "path", "path"
1650
+ if key in homog.loadings:
1651
+ return "result", _field_kind(homog.loadings[key].physics)
1652
+ if key in PROPERTIES and key in homog.properties:
1653
+ return "result", _field_kind(PHYSICS[key])
1654
+ names = [p for p in homog.properties if p in PROPERTIES] + [*homog.loadings, *homog.paths]
1655
+ raise ConfigError(
1656
+ f"{section}.of: {key!r} is none of the properties with fields, loadings and paths "
1657
+ f"of the homogenization: {names}"
1658
+ )
1659
+
1660
+
1661
+ def _number(section: str, value, low: float, high: float) -> float:
1662
+ try:
1663
+ x = float(value)
1664
+ except (TypeError, ValueError):
1665
+ x = float("nan")
1666
+ if isinstance(value, bool) or not low < x <= high:
1667
+ raise ConfigError(f"{section}: a number in ({low:g}, {high:g}], got {value!r}")
1668
+ return x
1669
+
1670
+
1671
+ def _view(section: str, data, homog: HomogenizationSpec | None, *, video: bool) -> ViewSpec:
1672
+ """One figure or video of the ``visualization`` section."""
1673
+ from morphogen.viz.video import MODES
1674
+ from morphogen.viz.workflow import DEFAULT_FIELD, FIELDS, KINDS, NODAL
1675
+
1676
+ if isinstance(data, str):
1677
+ data = {"of": data}
1678
+ if not isinstance(data, dict) or "of" not in data:
1679
+ raise ConfigError(
1680
+ f"{section}: a mapping with 'of' (image, labels, mesh, or a result '<name>.<bc>' "
1681
+ "of the homogenization)"
1682
+ )
1683
+ of = str(data["of"])
1684
+ if of in ("image", "labels", "mesh"):
1685
+ group, physics = of, None
1686
+ else:
1687
+ group, physics = _result_group(section, of, homog)
1688
+ options = {
1689
+ "image": {"axis", "phase", "cmap"},
1690
+ "labels": {"axis"},
1691
+ "mesh": {"color", "axis"},
1692
+ "result": {"color", "axis", "magnification", "section", "part", "cmap", "clim"},
1693
+ "path": {"color", "axis", "magnification", "section", "part", "cmap", "clim"},
1694
+ }[group]
1695
+ allowed = {"of", "kind", "formats", "name"} | options
1696
+ if video:
1697
+ allowed |= {"frames", "mode", "repeat", "fps"} | ({"wave"} if group == "result" else set())
1698
+ _check_keys(section, data, allowed)
1699
+ kinds = KINDS[group][1 if video else 0]
1700
+ kind = str(data.get("kind", kinds[0]))
1701
+ if kind not in kinds:
1702
+ what = "videos" if video else "figures"
1703
+ raise ConfigError(f"{section}.kind: one of {list(kinds)} for the {what} of {of}")
1704
+ formats = _list_of(
1705
+ f"{section}.formats",
1706
+ data.get("formats", "mp4" if video else "png"),
1707
+ VIDEO_FORMATS if video else FIGURE_FORMATS,
1708
+ )
1709
+ if not formats:
1710
+ raise ConfigError(f"{section}.formats: give at least one")
1711
+ fe = homog is not None and homog.method in ("fe", "xfem") # fields on a mesh
1712
+ vtk = (
1713
+ group == "mesh"
1714
+ or kind == "surface"
1715
+ or (group in ("result", "path") and kind == "field" and fe)
1716
+ )
1717
+ if vtk and not video:
1718
+ vector = [f for f in formats if f not in BITMAP_FORMATS]
1719
+ if vector:
1720
+ raise ConfigError(
1721
+ f"{section}.formats: the 3D views are bitmaps {list(BITMAP_FORMATS)}, not {vector}"
1722
+ )
1723
+ color = data.get("color")
1724
+ if group == "mesh":
1725
+ color = str(color or "phase")
1726
+ if color not in ("phase", "none"):
1727
+ raise ConfigError(f"{section}.color: 'phase' or 'none' (uniform)")
1728
+ elif physics is not None:
1729
+ color = str(color or DEFAULT_FIELD[physics])
1730
+ if color not in FIELDS[physics]:
1731
+ raise ConfigError(f"{section}.color: one of {list(FIELDS[physics])}")
1732
+ if not fe and color in NODAL and group == "result":
1733
+ raise ConfigError(f"{section}.color: {color!r} is on the nodes of finite elements")
1734
+ axis = data.get("axis", 2)
1735
+ if isinstance(axis, bool) or axis not in (0, 1, 2):
1736
+ raise ConfigError(f"{section}.axis: 0, 1 or 2")
1737
+ phase = data.get("phase", 1)
1738
+ if isinstance(phase, bool) or not isinstance(phase, int) or phase < 0:
1739
+ raise ConfigError(f"{section}.phase: a phase number")
1740
+ magnification = data.get("magnification")
1741
+ if magnification is not None:
1742
+ magnification = _number(f"{section}.magnification", magnification, 0.0, 1e12)
1743
+ cut = data.get("section")
1744
+ if cut is not None:
1745
+ if not fe:
1746
+ raise ConfigError(
1747
+ f"{section}.section: planes cut finite element meshes; the sections of the "
1748
+ "voxel images are normal to 'axis'"
1749
+ )
1750
+ if isinstance(cut, dict):
1751
+ _check_keys(f"{section}.section", cut, {"axis", "fraction"}, {"axis"})
1752
+ cut = (cut["axis"], cut.get("fraction", 0.5))
1753
+ if not isinstance(cut, (list, tuple)) or len(cut) != 2 or cut[0] not in (0, 1, 2):
1754
+ raise ConfigError(f"{section}.section: {{axis: 0, 1 or 2, fraction: 0 to 1}}")
1755
+ fraction = float(cut[1])
1756
+ if not 0.0 <= fraction <= 1.0:
1757
+ raise ConfigError(f"{section}.section.fraction: between 0 and 1")
1758
+ cut = (int(cut[0]), fraction)
1759
+ part = str(data.get("part", "total"))
1760
+ if part not in ("total", "fluctuation"):
1761
+ raise ConfigError(f"{section}.part: 'total' or 'fluctuation' (without E x)")
1762
+ if part == "fluctuation" and physics == "thermal":
1763
+ raise ConfigError(f"{section}.part: the fluctuations of mechanical displacements")
1764
+ wave = str(data.get("wave", "ramp"))
1765
+ if wave not in ("ramp", "sine"):
1766
+ raise ConfigError(f"{section}.wave: 'ramp' (a load growing) or 'sine' (oscillating)")
1767
+ frames = data.get("frames")
1768
+ if frames is not None:
1769
+ frames = _positive_int(f"{section}.frames", frames)
1770
+ mode = str(data.get("mode", "once"))
1771
+ if mode not in MODES:
1772
+ raise ConfigError(f"{section}.mode: one of {list(MODES)}")
1773
+ fps = data.get("fps")
1774
+ if fps is not None:
1775
+ fps = _number(f"{section}.fps", fps, 0.0, 240.0)
1776
+ cmap = data.get("cmap")
1777
+ if cmap is not None:
1778
+ cmap = _colormap(f"{section}.cmap", cmap)
1779
+ clim = data.get("clim")
1780
+ if clim is not None:
1781
+ if not isinstance(clim, (list, tuple)) or len(clim) != 2:
1782
+ raise ConfigError(f"{section}.clim: [low, high]")
1783
+ clim = (float(clim[0]), float(clim[1]))
1784
+ if not clim[0] < clim[1]:
1785
+ raise ConfigError(f"{section}.clim: low < high")
1786
+ name = data.get("name")
1787
+ if name is not None:
1788
+ name = str(name)
1789
+ if not name or any(c in name for c in '/\\:*?"<>| '):
1790
+ raise ConfigError(f"{section}.name: a file name without spaces or separators")
1791
+ return ViewSpec(
1792
+ of=of,
1793
+ group=group,
1794
+ kind=kind,
1795
+ formats=formats,
1796
+ color=color,
1797
+ axis=int(axis),
1798
+ phase=int(phase),
1799
+ magnification=magnification,
1800
+ wave=wave,
1801
+ section=cut,
1802
+ part=part,
1803
+ frames=frames,
1804
+ mode=mode,
1805
+ repeat=_positive_int(f"{section}.repeat", data.get("repeat", 1)),
1806
+ fps=fps,
1807
+ cmap=cmap,
1808
+ clim=clim,
1809
+ name=name,
1810
+ vtk=vtk,
1811
+ )
1812
+
1813
+
1814
+ def _visualization(data, homog: HomogenizationSpec | None) -> VisualizationSpec:
1815
+ """The ``visualization`` section: figures and videos of the first realizations."""
1816
+ if not isinstance(data, dict):
1817
+ raise ConfigError("visualization: a mapping (figures, videos, realizations, cmap...)")
1818
+ _check_keys(
1819
+ "visualization",
1820
+ data,
1821
+ {"figures", "videos", "realizations", "cmap", "fps", "size", "dpi", "elevation", "azimuth"},
1822
+ )
1823
+ camera = {}
1824
+ for key in ("elevation", "azimuth"):
1825
+ if key in data:
1826
+ camera[key] = _number(f"visualization.{key}", data[key], -360.0, 360.0)
1827
+
1828
+ def views(key: str, video: bool) -> list[ViewSpec]:
1829
+ items = data.get(key) or []
1830
+ items = [items] if isinstance(items, (str, dict)) else items
1831
+ if not isinstance(items, list):
1832
+ raise ConfigError(f"visualization.{key}: a list of views")
1833
+ return [
1834
+ _view(f"visualization.{key}[{k}]", v, homog, video=video) for k, v in enumerate(items)
1835
+ ]
1836
+
1837
+ figures, videos = views("figures", False), views("videos", True)
1838
+ if not figures and not videos:
1839
+ raise ConfigError("visualization: give figures or videos")
1840
+ files = [(v.label, f) for v in figures + videos for f in v.formats]
1841
+ twice = sorted({label for label, f in files if files.count((label, f)) > 1})
1842
+ if twice:
1843
+ raise ConfigError(f"visualization: views write the same files {twice}; name them ('name')")
1844
+ size = data.get("size", [640, 480])
1845
+ size = [size, size] if isinstance(size, int) and not isinstance(size, bool) else size
1846
+ if (
1847
+ not isinstance(size, (list, tuple))
1848
+ or len(size) != 2
1849
+ or not all(isinstance(n, int) and not isinstance(n, bool) and 16 <= n <= 8192 for n in size)
1850
+ ):
1851
+ raise ConfigError("visualization.size: [width, height] in pixels (16 to 8192)")
1852
+ return VisualizationSpec(
1853
+ figures=figures,
1854
+ videos=videos,
1855
+ realizations=_positive_int("visualization.realizations", data.get("realizations", 1)),
1856
+ cmap=_colormap("visualization.cmap", data.get("cmap", "viridis")),
1857
+ fps=_number("visualization.fps", data.get("fps", 24), 0.0, 240.0),
1858
+ size=(int(size[0]), int(size[1])),
1859
+ dpi=_positive_int("visualization.dpi", data.get("dpi", 200)),
1860
+ **camera,
1861
+ )
1862
+
1863
+
1864
+ def _check_method(homog: HomogenizationSpec, mesh: MeshSpec | None) -> None:
1865
+ """Resolve ``method: auto`` (finite elements when a mesh is described) and check
1866
+ that the boundary conditions suit the method."""
1867
+ if homog.method == "auto":
1868
+ homog.method = "fe" if mesh is not None else "fft"
1869
+ if homog.method == "fe" and mesh is None:
1870
+ raise ConfigError(
1871
+ "homogenization.method 'fe': describe the conforming meshes in a 'mesh' section "
1872
+ "(at least the element size)"
1873
+ )
1874
+ if homog.method == "fe" and homog.device == "gpu":
1875
+ raise ConfigError(
1876
+ "homogenization.device 'gpu': the GPU runs the FFT solver (method: fft); finite "
1877
+ "elements run on the CPU"
1878
+ )
1879
+ coupled = [p for p in homog.properties if PHYSICS[p] in ("coupled", "harmonic")]
1880
+ if homog.method != "fft" and coupled:
1881
+ raise ConfigError(
1882
+ f"homogenization.properties: the coupled and harmonic problems {coupled} are "
1883
+ "solved on voxel images (method: fft, periodic conditions)"
1884
+ )
1885
+ flows = [p for p in homog.properties if PHYSICS[p] == "flow"]
1886
+ if homog.method != "fft" and flows:
1887
+ raise ConfigError(
1888
+ f"homogenization.properties: the flows through the pores {flows} are solved on "
1889
+ "voxel images (method: fft, periodic conditions)"
1890
+ )
1891
+ if homog.fracture is not None and homog.method != "fft":
1892
+ raise ConfigError(
1893
+ "homogenization.fracture: the phase-field method runs on voxel images (method: "
1894
+ "fft, periodic conditions)"
1895
+ )
1896
+ if homog.nonlinear.get("contact") is not None:
1897
+ name = "homogenization.nonlinear.contact"
1898
+ if homog.method != "fe":
1899
+ raise ConfigError(
1900
+ f"{name}: the walls of the pores are the free faces of a conforming mesh "
1901
+ "(method: fe, with a 'mesh' section)"
1902
+ )
1903
+ if not homog.porous:
1904
+ raise ConfigError(
1905
+ f"{name}: the walls of the pores of a porous medium (a void material)"
1906
+ )
1907
+ if mesh.phases == "all":
1908
+ raise ConfigError(f"{name}: the mesh of the solid alone (mesh.phases: auto or solid)")
1909
+ if homog.solver not in ("auto", "direct"):
1910
+ raise ConfigError(f"{name}: the tangent of the contacts is factorized (solver: direct)")
1911
+ if homog.fatigue is not None and homog.method == "xfem":
1912
+ raise ConfigError(
1913
+ "homogenization.fatigue: the fields of the phases of a mesh or of an image "
1914
+ "(method: fe or fft)"
1915
+ )
1916
+ if homog.beremin is not None and homog.method == "xfem":
1917
+ raise ConfigError(
1918
+ "homogenization.beremin: the fields of the phases of a mesh or of an image "
1919
+ "(method: fe or fft)"
1920
+ )
1921
+ if homog.nonlinear.get("interfaces") is not None:
1922
+ name = "homogenization.nonlinear.interfaces"
1923
+ if homog.method != "fe":
1924
+ raise ConfigError(
1925
+ f"{name}: the interfaces of the phases are the faces of a conforming mesh "
1926
+ "(method: fe, with a 'mesh' section)"
1927
+ )
1928
+ if homog.solver not in ("auto", "direct"):
1929
+ raise ConfigError(
1930
+ f"{name}: the tangent of the interfaces is factorized (solver: direct)"
1931
+ )
1932
+ if homog.method in ("fft", "xfem"):
1933
+ other = [b for b in homog.boundary_conditions if b != "periodic"]
1934
+ if other:
1935
+ solver = "FFT solver" if homog.method == "fft" else "XFEM solver of level sets"
1936
+ raise ConfigError(
1937
+ f"homogenization: {other} conditions need finite elements on conforming "
1938
+ f"meshes (method: fe, with a 'mesh' section); the {solver} is periodic"
1939
+ )
1940
+ if homog.method == "xfem":
1941
+ if homog.device == "gpu":
1942
+ raise ConfigError("homogenization.device 'gpu': the GPU runs the FFT solver")
1943
+ if "integration" in homog.nonlinear or homog.integration is not None:
1944
+ raise ConfigError(
1945
+ "homogenization.integration: an option of the finite elements of a mesh "
1946
+ "(method: fe) and of the voxels of the loading paths (method: fft)"
1947
+ )
1948
+ if homog.ntfa:
1949
+ raise ConfigError("homogenization.ntfa: a reduced model of voxel images (method: fft)")
1950
+
1951
+
1952
+ def _model_paths(model, base: Path):
1953
+ """The model of a configuration with its files (the ``path_parameters`` of its
1954
+ class: parameters, or keys of parameters that are mappings, ``texture.file``) taken
1955
+ from the folder of the configuration; the models that it holds likewise."""
1956
+ if isinstance(model, (list, tuple)):
1957
+ return [_model_paths(item, base) for item in model]
1958
+ if not isinstance(model, dict):
1959
+ return model
1960
+ out = {key: _model_paths(value, base) for key, value in model.items()}
1961
+ try:
1962
+ names = get_model(str(model.get("type"))).path_parameters
1963
+ except ValueError:
1964
+ return out
1965
+ for name in names:
1966
+ *holders, key = name.split(".")
1967
+ target = out
1968
+ for holder in holders:
1969
+ target = target.get(holder) if isinstance(target, dict) else None
1970
+ value = target.get(key) if isinstance(target, dict) else None
1971
+ if isinstance(value, str) and value and not Path(value).expanduser().is_absolute():
1972
+ target[key] = str(base / value)
1973
+ return out
1974
+
1975
+
1976
+ def load_config(source, *, base_dir=None) -> RunConfig:
1977
+ """Validate a configuration given as a file path or a mapping."""
1978
+ if isinstance(source, (str, Path)):
1979
+ path = Path(source)
1980
+ data = read_config_file(path)
1981
+ base = path.parent if base_dir is None else Path(base_dir)
1982
+ else:
1983
+ data = dict(source)
1984
+ base = Path.cwd() if base_dir is None else Path(base_dir)
1985
+ allowed = {
1986
+ "model",
1987
+ "domain",
1988
+ "seed",
1989
+ "realizations",
1990
+ "voxels",
1991
+ "outputs",
1992
+ "analysis",
1993
+ "rve",
1994
+ "homogenization",
1995
+ "diffusion",
1996
+ "mesh",
1997
+ "visualization",
1998
+ "threads",
1999
+ "version",
2000
+ }
2001
+ if "optimization" in data and "model" not in data:
2002
+ raise ConfigError("this is a topology optimization: run it with 'morphogen optimize'")
2003
+ _check_keys("configuration", data, allowed, {"model"})
2004
+ try:
2005
+ model = model_from_config(_model_paths(data["model"], base))
2006
+ except ValueError as exc:
2007
+ raise ConfigError(str(exc)) from None
2008
+ homog = None
2009
+ if data.get("homogenization") is not None:
2010
+ homog = _homogenization(data["homogenization"], base)
2011
+ rve = _rve(data["rve"], homog) if data.get("rve") is not None else None
2012
+ for count in ("n_cells", "number"):
2013
+ if rve is not None and getattr(model, count, None) is not None:
2014
+ raise ConfigError(
2015
+ f"model.{count}: RVE studies compare samples of different sizes and need "
2016
+ "a density (intensity or volume_fraction); a fixed count would change "
2017
+ "the microstructure with the sample size"
2018
+ )
2019
+ dom = dict(data.get("domain") or {})
2020
+ _check_keys("domain", dom, {"size", "origin", "periodic", "unit"})
2021
+ if rve is not None:
2022
+ if "size" in dom:
2023
+ raise ConfigError("domain.size: not used by RVE studies (see rve.sizes / rve.size)")
2024
+ dom["size"] = rve.sizes[0] if rve.method == "ensemble" else rve.size
2025
+ elif "size" not in dom:
2026
+ raise ConfigError("domain: 'size' is required")
2027
+ try:
2028
+ domain = Domain.from_dict(dom)
2029
+ except ValueError as exc:
2030
+ raise ConfigError(str(exc)) from None
2031
+ if rve is not None and rve.shifts > 1 and not domain.periodic:
2032
+ raise ConfigError(
2033
+ "rve.shifts: the shifted tilings wrap around the realization, a periodic one "
2034
+ "(domain.periodic: true)"
2035
+ )
2036
+ seed = data.get("seed")
2037
+ if seed is not None and (isinstance(seed, bool) or not isinstance(seed, int) or seed < 0):
2038
+ raise ConfigError(f"seed: expected a non-negative integer, got {seed!r}")
2039
+ voxels = _voxels(data["voxels"]) if data.get("voxels") is not None else None
2040
+ diffusion = _diffusion(data["diffusion"]) if data.get("diffusion") is not None else None
2041
+ if diffusion is not None:
2042
+ if voxels is None:
2043
+ raise ConfigError("diffusion: give the voxel grid (voxels section)")
2044
+ missing = sorted(set(model.active_phases()) - set(diffusion.diffusivity))
2045
+ if missing:
2046
+ raise ConfigError(f"diffusion.phases: no properties for phase(s) {missing}")
2047
+ mesh = _mesh(data["mesh"]) if data.get("mesh") is not None else None
2048
+ outputs = _outputs(data.get("outputs") or {}, base)
2049
+ analysis = _list_of("analysis", data.get("analysis"), MEASURES)
2050
+ if homog is not None:
2051
+ _check_method(homog, mesh)
2052
+ if mesh is not None and mesh.order is None:
2053
+ # quadratic elements for the finite element analyses: linear tetrahedra are stiff,
2054
+ # and lock under isochoric plastic flow; a mesh that is only written stays linear
2055
+ analysed = homog is not None and homog.method == "fe"
2056
+ mesh.order = 2 if analysed else 1
2057
+ if mesh.curved and mesh.order == 1:
2058
+ raise ConfigError("mesh.curved: the edges of 10-node elements (mesh.order: 2)")
2059
+ if homog is not None:
2060
+ if homog.method == "xfem":
2061
+ if not model.has_level_set:
2062
+ raise ConfigError(
2063
+ f"homogenization.method 'xfem': the model {model.name} has no level set "
2064
+ "(tessellations: method fe, grain by grain, or fft)"
2065
+ )
2066
+ if not domain.periodic:
2067
+ raise ConfigError(
2068
+ "homogenization.method 'xfem': a periodic domain (domain.periodic: true)"
2069
+ )
2070
+ if rve is not None and rve.method == "windows" and homog.method != "fft":
2071
+ raise ConfigError(
2072
+ "rve: the window method solves its realization by the FFT solver "
2073
+ "(homogenization.method: fft, periodic conditions)"
2074
+ )
2075
+ phases = model.active_phases()
2076
+ missing = sorted(set(phases) - set(homog.materials))
2077
+ if missing:
2078
+ raise ConfigError(
2079
+ f"homogenization.materials: no material for phase(s) {missing} of model "
2080
+ f"{model.name} ({', '.join(f'{p}: {phases[p]}' for p in missing)})"
2081
+ )
2082
+ viz = None
2083
+ if data.get("visualization") is not None:
2084
+ viz = _visualization(data["visualization"], homog)
2085
+ if viz.shows("mesh") and mesh is None:
2086
+ raise ConfigError("visualization: the views of the mesh need the 'mesh' section")
2087
+ if viz.shows("image", "labels") and voxels is None:
2088
+ raise ConfigError("visualization: the views of the image need the 'voxels' section")
2089
+ if rve is not None and rve.method == "windows":
2090
+ raise ConfigError("visualization: the realizations of batches and ensemble studies")
2091
+ if outputs.conforming_mesh and mesh is None:
2092
+ raise ConfigError("outputs.conforming_mesh: give the 'mesh' section (element size...)")
2093
+ if (outputs.damask or outputs.neper) and not model.meshed_by_grains:
2094
+ raise ConfigError("outputs.damask, outputs.neper: Voronoi and Laguerre tessellations only")
2095
+ if outputs.damask and not getattr(model, "crystal_orientations", False):
2096
+ raise ConfigError("outputs.damask: the grains need orientations (crystal_orientations)")
2097
+ if outputs.amitex is not None:
2098
+ if homog is None:
2099
+ raise ConfigError("outputs.amitex: give the materials (homogenization section)")
2100
+ if homog.nonlinear.get("kinematics", "small") == "finite" and not homog.paths:
2101
+ raise ConfigError(
2102
+ "outputs.amitex in finite strains: the runs of AMITEX are the loading paths "
2103
+ "(homogenization.paths)"
2104
+ )
2105
+ if outputs.periodic_equations and not domain.periodic:
2106
+ raise ConfigError("outputs.periodic_equations: a periodic domain")
2107
+ if outputs.periodic_equations and not (outputs.conforming_mesh or outputs.mesh):
2108
+ raise ConfigError(
2109
+ "outputs.periodic_equations: the equations refer to the nodes of a mesh written "
2110
+ "by outputs.conforming_mesh or outputs.mesh"
2111
+ )
2112
+ if mesh is not None and mesh.grains and not model.meshed_by_grains:
2113
+ what = (
2114
+ "are mapped by an anisotropy (voxelize them)"
2115
+ if hasattr(model, "boundary_thickness")
2116
+ and not getattr(getattr(model, "anisotropy", None), "is_identity", True)
2117
+ else "have a grain-boundary phase"
2118
+ if hasattr(model, "boundary_thickness")
2119
+ else ("are not tessellations")
2120
+ )
2121
+ raise ConfigError(f"mesh.grains: the realizations of model {model.name} {what}")
2122
+ measures = set(analysis)
2123
+ if rve is not None:
2124
+ measures |= {p for p in rve.properties if p in MEASURES}
2125
+ # without voxels, the volume fraction is measured on the conforming mesh
2126
+ from_mesh = {"volume_fraction"} if mesh is not None else set()
2127
+ needs_voxels = (
2128
+ outputs.needs_voxels
2129
+ or bool(measures - from_mesh)
2130
+ or (homog is not None and homog.method in ("fft", "xfem"))
2131
+ or (rve is not None and rve.method == "windows")
2132
+ )
2133
+ if voxels is not None and voxels.section is not None:
2134
+ if homog is not None and homog.method == "xfem":
2135
+ raise ConfigError(
2136
+ "voxels.section: the extended finite elements cut the grid of the volume "
2137
+ "(method: fft for a planar section)"
2138
+ )
2139
+ if rve is not None and rve.method == "windows":
2140
+ raise ConfigError("voxels.section: the window method takes its windows in the volume")
2141
+ if needs_voxels and voxels is None:
2142
+ raise ConfigError(
2143
+ "voxels: required to write images or voxel meshes, for morphological "
2144
+ "measurements and window studies, by the FFT solver and (the grid) by the "
2145
+ "extended finite elements"
2146
+ )
2147
+ if rve is not None and voxels is not None and voxels.voxel_size is None:
2148
+ raise ConfigError("voxels: RVE studies need 'voxel_size' (same resolution at all sizes)")
2149
+ threads = data.get("threads")
2150
+ if threads is not None:
2151
+ threads = _positive_int("threads", threads)
2152
+ return RunConfig(
2153
+ model=model,
2154
+ domain=domain,
2155
+ seed=seed,
2156
+ realizations=_positive_int("realizations", data.get("realizations", 1)),
2157
+ voxels=voxels,
2158
+ mesh=mesh,
2159
+ outputs=outputs,
2160
+ analysis=analysis,
2161
+ rve=rve,
2162
+ homogenization=homog,
2163
+ diffusion=diffusion,
2164
+ visualization=viz,
2165
+ threads=threads,
2166
+ source=data,
2167
+ )