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/cli.py ADDED
@@ -0,0 +1,3526 @@
1
+ """Command-line interface: ``morphogen <command>`` (see ``morphogen --help``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import csv
7
+ import json
8
+ import logging
9
+ import os
10
+ import sys
11
+ from importlib import resources
12
+ from pathlib import Path
13
+
14
+ import numpy as np
15
+ import yaml
16
+
17
+ from morphogen import analysis, gpu, io, pipeline, settings
18
+ from morphogen._platform import full_speed
19
+ from morphogen._utils import to_jsonable
20
+ from morphogen._version import __version__
21
+ from morphogen.config import ConfigError, RVESpec, _mfront_paths, load_config
22
+ from morphogen.models.base import get_model, list_models
23
+ from morphogen.rve import report as rve_report
24
+
25
+ log = logging.getLogger("morphogen")
26
+
27
+
28
+ def _templates() -> dict[str, str]:
29
+ folder = resources.files("morphogen") / "templates"
30
+ return {
31
+ p.name[: -len(".yaml")]: p.read_text(encoding="utf-8")
32
+ for p in folder.iterdir()
33
+ if p.name.endswith(".yaml")
34
+ }
35
+
36
+
37
+ #: Environment variables holding the index of a task of a job array, and their origin.
38
+ ARRAY_INDEX = (
39
+ ("SLURM_ARRAY_TASK_ID", 0),
40
+ ("PBS_ARRAY_INDEX", 0),
41
+ ("PBS_ARRAYID", 0),
42
+ ("SGE_TASK_ID", 1),
43
+ ("OAR_ARRAY_INDEX", 1),
44
+ ("LSB_JOBINDEX", 1),
45
+ )
46
+
47
+
48
+ def _task_id(value: str) -> int:
49
+ """``--task-id``: an index, or ``auto`` (from the job array of the scheduler)."""
50
+ if value != "auto":
51
+ return int(value)
52
+ for name, origin in ARRAY_INDEX:
53
+ if os.environ.get(name, "").strip().isdigit():
54
+ return int(os.environ[name]) - origin
55
+ raise ValueError("--task-id auto: no job array index in the environment")
56
+
57
+
58
+ def cmd_run(args) -> int:
59
+ cfg = load_config(args.config)
60
+ if args.output is not None:
61
+ cfg.outputs.directory = Path(args.output)
62
+ if args.seed is not None:
63
+ cfg.seed = args.seed
64
+ if args.threads is not None:
65
+ cfg.threads = args.threads
66
+ if args.db is not None:
67
+ cfg.outputs.database = Path(args.db)
68
+ if args.mpi:
69
+ from morphogen import parallel
70
+
71
+ outdir = parallel.run_mpi(cfg, jobs=args.jobs, resume=args.resume)
72
+ else:
73
+ outdir = pipeline.run(
74
+ cfg,
75
+ task_id=_task_id(args.task_id),
76
+ n_tasks=args.n_tasks,
77
+ jobs=args.jobs,
78
+ resume=args.resume,
79
+ )
80
+ print(f"results written to {outdir}")
81
+ report = outdir / "rve_report.md"
82
+ if report.exists() and not args.quiet:
83
+ print(report.read_text(encoding="utf-8"))
84
+ return 0
85
+
86
+
87
+ def _amitex_export(args) -> int:
88
+ from morphogen.homogenization import Loading, LoadingPath, materials_from_config
89
+ from morphogen.homogenization.materials import any_oriented
90
+
91
+ materials = materials_from_config(_material_spec(args))
92
+ path = Path(args.target)
93
+ grains = {}
94
+ if path.suffix.lower() == ".json":
95
+ if args.voxels is None:
96
+ raise ValueError("--voxels N: the voxels of the image of the geometry")
97
+ micro = io.load_microstructure(path)
98
+ image = micro.voxelize(args.voxels)
99
+ orientations = getattr(micro, "orientations", None)
100
+ if orientations is not None and any_oriented(materials):
101
+ grains = {"grains": micro.labels(grid=image.grid()).data,
102
+ "orientations": orientations} # fmt: skip
103
+ else:
104
+ image = io.load_image(path, name=args.array)
105
+ loadings = {}
106
+ for k, text in enumerate(args.loading or []):
107
+ name, sep, rest = text.partition(":")
108
+ name, rest = (name.strip(), rest) if sep else (f"loading{k + 1}", text)
109
+ loadings[name] = Loading.parse(rest)
110
+ paths = {}
111
+ if args.paths:
112
+ loaded = yaml.safe_load(Path(args.paths).read_text(encoding="utf-8"))
113
+ loaded = loaded.get("paths", loaded) if isinstance(loaded, dict) else None
114
+ if not isinstance(loaded, dict):
115
+ raise ValueError("--paths: a YAML/JSON file mapping names to loading paths")
116
+ paths.update({str(k): LoadingPath.from_spec(v) for k, v in loaded.items()})
117
+ for k, text in enumerate(args.path or []):
118
+ name, sep, rest = text.partition(":")
119
+ name, rest = (name.strip(), rest) if sep else (f"path{k + 1}", text)
120
+ paths[name] = LoadingPath.parse(rest)
121
+ stiffness = True if args.stiffness else None
122
+ export = io.write_amitex(
123
+ args.output or f"{path.stem}_amitex",
124
+ image,
125
+ materials,
126
+ loadings=loadings,
127
+ paths=paths,
128
+ stiffness=stiffness,
129
+ name=args.name or path.stem,
130
+ fields=args.fields,
131
+ tolerance=args.tol,
132
+ processes=args.processes,
133
+ library=args.library or "",
134
+ elastic_only=args.elastic_only,
135
+ kinematics=args.kinematics,
136
+ **grains,
137
+ )
138
+ if args.json:
139
+ print(json.dumps({"directory": str(export.directory), "name": export.name,
140
+ "runs": export.runs}, indent=2)) # fmt: skip
141
+ else:
142
+ print(f"AMITEX runs of {path.name} ({image.shape} voxels) in {export.directory}: "
143
+ f"{', '.join(export.runs)}; run {export.name}_run.sh there") # fmt: skip
144
+ return 0
145
+
146
+
147
+ def _amitex_read(args) -> int:
148
+ from morphogen.homogenization.postprocess import NOTATION, compliance, matrix_entries
149
+
150
+ run = io.read_amitex_run(args.target, args.name)
151
+ out = {"name": run.manifest["name"], "volume": run.manifest["volume"], "runs": {}}
152
+ for key, res in run.results.items():
153
+ out["runs"][key] = {
154
+ "times": res.times.tolist(),
155
+ "stress": res.stress.tolist(),
156
+ "strain": res.strain.tolist(),
157
+ }
158
+ if run.stiffness is not None:
159
+ out["stiffness"] = run.stiffness.tolist()
160
+ out["compliance"] = compliance(run.stiffness).tolist()
161
+ out["notation"] = NOTATION
162
+ out["properties"] = run.properties
163
+ missing = sorted(set(run.manifest["runs"]) - set(run.results))
164
+ if missing:
165
+ out["missing"] = missing
166
+ if args.output:
167
+ if run.stiffness is None:
168
+ raise ValueError("-o: a table of the apparent stiffness, which needs its run")
169
+ row = {"name": out["name"], "volume": out["volume"], **run.properties}
170
+ row.update(matrix_entries(run.stiffness, "C"))
171
+ row.update(matrix_entries(out["compliance"], "S"))
172
+ target = Path(args.output)
173
+ new = not target.exists()
174
+ with open(target, "a", newline="", encoding="utf-8") as f:
175
+ writer = csv.DictWriter(f, fieldnames=list(row))
176
+ if new:
177
+ writer.writeheader()
178
+ writer.writerow(row)
179
+ if args.json:
180
+ print(json.dumps(out, indent=2))
181
+ return 0
182
+ print(f"{out['name']}: runs with results {sorted(run.results) or 'none'}"
183
+ + (f", without {missing}" if missing else "")) # fmt: skip
184
+ if run.stiffness is not None:
185
+ print("apparent", end=" ")
186
+ _print_elastic(run.stiffness, out["compliance"])
187
+ for key, value in run.properties.items():
188
+ print(f"{key:>16s}: {value:.6g}")
189
+ return 0
190
+
191
+
192
+ def cmd_amitex(args) -> int:
193
+ return _amitex_export(args) if args.action == "export" else _amitex_read(args)
194
+
195
+
196
+ def cmd_db(args) -> int:
197
+ from morphogen.results import ResultsDatabase, write_records
198
+
199
+ with ResultsDatabase(args.db) as db:
200
+ if args.action == "add":
201
+ for directory in args.items:
202
+ n = db.add_run(directory, name=args.name)
203
+ print(f"{directory}: {n} records added to {args.db}")
204
+ return 0
205
+ if args.action == "remove":
206
+ for run in args.items:
207
+ if not db.remove(run):
208
+ raise ValueError(f"no run {run!r} in {args.db}")
209
+ return 0
210
+ records = db.records(args.where or [])
211
+ if args.action == "export":
212
+ if not args.output:
213
+ raise ValueError("export: give the output file (-o results.csv)")
214
+ write_records(records, args.output)
215
+ print(f"{len(records)} records written to {args.output}")
216
+ return 0
217
+ if args.action == "keys":
218
+ keys = db.keys(args.where or [])
219
+ if args.json:
220
+ print(json.dumps(keys, indent=2))
221
+ else:
222
+ for k, v in keys.items():
223
+ kind = "number" if v["numeric"] else "text"
224
+ print(f"{k:60s} {v['count']:7d} {kind}")
225
+ return 0
226
+ runs = db.runs()
227
+ if args.json:
228
+ print(json.dumps({"runs": runs, "records": len(records)}, indent=2))
229
+ return 0
230
+ for r in runs:
231
+ line = f"{r['id']:4d} {r['name']:24s} {r['records']:6d} records {r['added']}"
232
+ print(f"{line} {r['path']}")
233
+ print(f"{len(records)} records" + (" match the conditions" if args.where else ""))
234
+ return 0
235
+
236
+
237
+ def cmd_ashby(args) -> int:
238
+ from morphogen.results import ResultsDatabase, ashby_chart, ashby_points, write_records
239
+
240
+ with ResultsDatabase(args.db) as db:
241
+ records = db.records(args.where or [])
242
+ if not records:
243
+ raise ValueError("no record (add runs with 'morphogen db add', or relax --where)")
244
+ by = None if args.by in ("", "none") else args.by
245
+ path = ashby_chart(
246
+ records,
247
+ args.output,
248
+ args.x,
249
+ args.y,
250
+ by,
251
+ log=not args.linear,
252
+ guides=args.guides,
253
+ groups=args.groups,
254
+ theme=args.theme,
255
+ title=args.title,
256
+ )
257
+ data = ashby_points(records, args.x, args.y, by, log=not args.linear, groups=args.groups)
258
+ if args.table:
259
+ keys = ["run_name", "realization", *([by] if by else []), data["x"], data["y"]]
260
+ write_records(records, args.table, keys)
261
+ shown = sum(len(g["points"]) for g in data["groups"])
262
+ print(f"{path}: {shown} of {len(records)} records, {data['y']} against {data['x']}")
263
+ return 0
264
+
265
+
266
+ def cmd_merge(args) -> int:
267
+ from morphogen import parallel
268
+
269
+ outdir = parallel.merge(args.directory, report=not args.no_report)
270
+ print(f"results merged in {outdir}")
271
+ report = Path(outdir) / "rve_report.md"
272
+ if report.exists() and not args.quiet and not args.no_report:
273
+ print(report.read_text(encoding="utf-8"))
274
+ return 0
275
+
276
+
277
+ def cmd_status(args) -> int:
278
+ from morphogen import parallel
279
+
280
+ info = parallel.status(args.directory)
281
+ if args.json:
282
+ print(json.dumps(info, indent=2))
283
+ return 0
284
+ print(f"{info['directory']}: {info['done']} of {info['expected']} realizations done")
285
+ if info["done"]:
286
+ print(f"mean time per realization: {info['mean_time_s']:.2f} s")
287
+ if info["missing"]:
288
+ shown = ", ".join(info["missing"][:5]) + (" ..." if len(info["missing"]) > 5 else "")
289
+ print(f"missing: {shown}")
290
+ print("merged" if info["merged"] else "not merged yet (morphogen merge <directory>)")
291
+ return 0 if not info["missing"] else 1
292
+
293
+
294
+ def cmd_submit(args) -> int:
295
+ from morphogen import parallel
296
+
297
+ cfg = load_config(args.config)
298
+ outdir = Path(args.output) if args.output else cfg.outputs.directory
299
+ seed = args.seed if args.seed is not None else cfg.seed
300
+ if seed is None: # one seed for all the tasks
301
+ seed = int(np.random.SeedSequence().entropy)
302
+ opts = parallel.JobOptions(
303
+ tasks=args.tasks,
304
+ jobs=args.jobs,
305
+ threads=args.threads,
306
+ time=args.time,
307
+ memory=args.memory,
308
+ queue=args.queue,
309
+ account=args.account,
310
+ name=args.name or f"morphogen-{cfg.outputs.name}",
311
+ setup=list(args.setup or []),
312
+ )
313
+ array, merging = parallel.job_script(args.scheduler, args.config, outdir, opts, seed=seed)
314
+ outdir.mkdir(parents=True, exist_ok=True)
315
+ paths = [outdir / f"{args.scheduler}_array.sh", outdir / f"{args.scheduler}_merge.sh"]
316
+ for path, text in zip(paths, (array, merging), strict=True):
317
+ path.write_text(text, encoding="utf-8", newline="\n")
318
+ path.chmod(0o755)
319
+ print(f"job array script: {paths[0]}\nmerging script: {paths[1]}")
320
+ if args.submit:
321
+ ids = parallel.submit(args.scheduler, *paths)
322
+ print(f"submitted: job array {ids[0]}, merging job {ids[1]}")
323
+ else:
324
+ print(f"submit the array, then '{paths[1].name}' after it (or use --submit)")
325
+ return 0
326
+
327
+
328
+ def cmd_fit(args) -> int:
329
+ rows = pipeline.collect_results(args.results)
330
+ fe_rows = pipeline.collect_homogenization(args.results)
331
+ if args.volume_column != "volume":
332
+ for row in rows + fe_rows:
333
+ if args.volume_column not in row:
334
+ raise ValueError(f"no column {args.volume_column!r} in the results")
335
+ row["volume"] = row[args.volume_column]
336
+ if args.bootstrap < 0:
337
+ raise ValueError("--bootstrap: a non-negative number of replicates")
338
+ spec = RVESpec(
339
+ relative_errors=args.eps,
340
+ n_realizations=args.n,
341
+ gamma=args.gamma,
342
+ min_volume=args.min_volume,
343
+ max_volume=args.max_volume,
344
+ bootstrap=args.bootstrap,
345
+ weights=args.weights,
346
+ )
347
+ report = pipeline.build_report(
348
+ rows, spec, args.property, fe_rows=fe_rows or None, group_by=args.group_by
349
+ )
350
+ if args.output:
351
+ files = rve_report.write(report, Path(args.output))
352
+ print(f"report written to {args.output} ({', '.join(f.name for f in files)})")
353
+ print(rve_report.markdown(report))
354
+ return 0
355
+
356
+
357
+ def _material_spec(args) -> dict:
358
+ """The materials of the phases of ``--materials`` (a file; the sources of MFront
359
+ behaviours relative to it) and ``--material`` (on the command line)."""
360
+ spec = {}
361
+ if args.materials:
362
+ loaded = yaml.safe_load(Path(args.materials).read_text(encoding="utf-8"))
363
+ loaded = loaded.get("materials", loaded) if isinstance(loaded, dict) else {}
364
+ spec.update(_mfront_paths(loaded, Path(args.materials).parent))
365
+ for text in args.material or []:
366
+ phase, value = _parse_material(text)
367
+ spec[phase] = value
368
+ if not spec:
369
+ raise ValueError("give the materials of the phases (--material or --materials)")
370
+ return spec
371
+
372
+
373
+ def cmd_mfront(args) -> int:
374
+ from morphogen.homogenization import materials_from_config
375
+ from morphogen.io.mfront import identifier, write_mfront
376
+
377
+ materials = materials_from_config(_material_spec(args))
378
+ stem = identifier(args.name or (Path(args.materials).stem if args.materials else "material"))
379
+ directory = Path(args.output or ".")
380
+ written = []
381
+ for p, m in sorted(materials.items()):
382
+ # the nonlinear materials; in finite strains, the elastic ones too (Hencky)
383
+ if m.void or m.mfront is not None or not (m.nonlinear or args.kinematics == "finite"):
384
+ continue
385
+ target = directory / f"{stem}Phase{p}.mfront"
386
+ written.append(write_mfront(m, target, kinematics=args.kinematics))
387
+ print(f"phase {p}: {target}")
388
+ if not written:
389
+ raise ValueError("no material to write (plasticity, porous_plasticity, "
390
+ "crystal_plasticity, learned; in finite strains, elasticity)") # fmt: skip
391
+ names = " ".join(p.name for p in written)
392
+ print(f"compile: cd {directory} && mfront --obuild --interface=INTERFACE {names}")
393
+ print(" (INTERFACE: generic for MGIS and morphoGen, umat for AMITEX_FFTP and Cast3M, "
394
+ "abaqus, aster...)") # fmt: skip
395
+ return 0
396
+
397
+
398
+ def _apparent_properties() -> tuple[str, ...]:
399
+ """The apparent properties of ``morphogen homogenize --property``."""
400
+ from morphogen.homogenization.apparent import COUPLED, FLOW, HARMONIC, PROPERTIES, TENSORS
401
+
402
+ scalars = [p for p in PROPERTIES if p not in ("bulk_modulus", "shear_modulus")]
403
+ return ("bulk_modulus", "shear_modulus", "stiffness", "thermal_expansion", *scalars,
404
+ *(t for t in TENSORS if t not in ("stiffness", "thermal_expansion")),
405
+ *COUPLED, *HARMONIC, *FLOW) # fmt: skip
406
+
407
+
408
+ def _parse_material(text: str):
409
+ """``PHASE=void`` or ``PHASE=key:value,key:value`` (young, poisson, bulk, shear,
410
+ conductivity, expansion, density, electrical_conductivity, permittivity, permeability,
411
+ diffusivity; crystals: ``cubic:c11/c12/c44``, ``hexagonal:c11/c12/c13/c33/c44``,
412
+ conductivities ``k1/k2/k3``)."""
413
+ phase, sep, spec = text.partition("=")
414
+ if not sep:
415
+ raise ValueError(f"--material {text!r}: expected PHASE=void or PHASE=young:...,poisson:...")
416
+ spec = spec.strip()
417
+ if spec.lower() == "void":
418
+ return phase.strip(), "void"
419
+ values = {}
420
+ for item in spec.split(","):
421
+ key, sep, value = item.partition(":")
422
+ if not sep:
423
+ raise ValueError(f"--material {text!r}: items are key:value")
424
+ numbers = [float(v) for v in value.split("/")]
425
+ values[key.strip()] = numbers[0] if len(numbers) == 1 else numbers
426
+ return phase.strip(), values
427
+
428
+
429
+ def _homogenization_sample(args, materials):
430
+ """Mesh or image to homogenize: a geometry (.json) is meshed conformingly, a
431
+ tetrahedral mesh (.vtu, .mesh) is used as is (finite elements), an image is solved
432
+ by FFT."""
433
+ from morphogen.homogenization.materials import any_oriented
434
+ from morphogen.mesh.conforming import conforming_mesh
435
+
436
+ path = Path(args.sample)
437
+ ext = path.suffix.lower()
438
+ if ext == ".json":
439
+ micro = io.load_microstructure(path)
440
+ if args.voxels is not None:
441
+ # FFT on the image of the geometry; crystals turned by its grains
442
+ image = micro.voxelize(args.voxels)
443
+ orientations = getattr(micro, "orientations", None)
444
+ if orientations is not None and any_oriented(materials):
445
+ labels = micro.labels(grid=image.grid())
446
+ return image, {"grains": labels, "orientations": orientations}
447
+ return image, {}
448
+ if args.size is None:
449
+ raise ValueError(
450
+ "--size: element size of the conforming mesh of a geometry (or --voxels N "
451
+ "for the FFT solver)"
452
+ )
453
+ phases = args.mesh_phases
454
+ if phases == "auto":
455
+ phases = "solid" if any(m.void for m in materials.values()) else "all"
456
+ periodic = True if args.periodic else None
457
+ extra = {} if args.min_feature is None else {"min_feature": args.min_feature}
458
+ mesh = conforming_mesh(
459
+ micro,
460
+ size=args.size,
461
+ hausdorff=args.hausdorff,
462
+ order=args.order,
463
+ phases=phases,
464
+ periodic=periodic,
465
+ cells=args.cells,
466
+ method=args.mesh_method,
467
+ **extra,
468
+ )
469
+ return mesh, {}
470
+ if ext in (".vtu", ".mesh"):
471
+ return io.read_tet_mesh(path, periodic=True if args.periodic else None), {}
472
+ image = io.load_image(path, name=args.array)
473
+ if args.periodic:
474
+ image.periodic = True
475
+ return image, {}
476
+
477
+
478
+ def _matrix_text(matrix) -> str:
479
+ """A matrix as the commands print it (the round-off below 1e-12 of its largest entry
480
+ as zeros)."""
481
+ m = np.asarray(matrix, dtype=float)
482
+ m = np.where(np.abs(m) < 1e-12 * np.abs(m).max(), 0.0, m)
483
+ return np.array2string(m, formatter={"float_kind": "{:11.5g}".format})
484
+
485
+
486
+ def _print_harmonic(res: dict) -> None:
487
+ """The scalar entries of a harmonic property (a row per frequency or wavelength)."""
488
+ axis = "wavelengths" if "wavelengths" in res else "frequencies"
489
+ values = np.asarray(res[axis])
490
+ names = sorted({k.rsplit("_", 1)[0] for k, v in res.items()
491
+ if isinstance(v, float) and k.rsplit("_", 1)[-1].isdigit()}) # fmt: skip
492
+ print(" " + f"{axis[:-1]:>12s} " + " ".join(f"{n:>16s}" for n in names))
493
+ for i, x in enumerate(values):
494
+ print(" " + f"{x:12.6g} " + " ".join(f"{res[f'{n}_{i + 1}']:16.6g}" for n in names))
495
+
496
+
497
+ def _print_elastic(stiffness, compliance=None, units=("of the moduli", "their inverse")):
498
+ """The stiffness ``C`` and its compliance ``S = C^-1`` as the commands print them, with
499
+ their notation (:func:`morphogen.homogenization.postprocess.notation`) and ``units``
500
+ (those of C, those of S)."""
501
+ from morphogen.homogenization.postprocess import compliance as inverse
502
+ from morphogen.homogenization.postprocess import notation
503
+
504
+ c = np.asarray(stiffness, dtype=float)
505
+ s = inverse(c) if compliance is None else np.asarray(compliance, dtype=float)
506
+ print(f"stiffness C ({notation(c)}), units {units[0]}:")
507
+ print(_matrix_text(c))
508
+ print(f"compliance S = C^-1, units {units[1]}:")
509
+ print(_matrix_text(s))
510
+
511
+
512
+ def _contact_sample(args, materials):
513
+ """The mesh of a test of contact (``morphogen compress``, ``morphogen indent``): a
514
+ geometry (.json) meshed conformingly, or a tetrahedral mesh (.vtu, .mesh); its solid
515
+ alone when phases are voids. The surfaces that touch are the faces of a mesh."""
516
+ from morphogen.mesh.tetra import TetMesh
517
+
518
+ if Path(args.sample).suffix.lower() not in (".json", ".vtu", ".mesh"):
519
+ raise ValueError(
520
+ "a geometry (.json, meshed with --size) or a tetrahedral mesh (.vtu, .mesh): the "
521
+ "surfaces that touch are the faces of a mesh (morphogen mesh makes one of an image)"
522
+ )
523
+ mesh, _ = _homogenization_sample(args, materials)
524
+ if not isinstance(mesh, TetMesh): # pragma: no cover - the suffixes above
525
+ raise ValueError("a tetrahedral mesh")
526
+ voids = {int(k) for k, m in materials.items() if m.void}
527
+ phases = {int(k) for k in np.unique(mesh.phase)}
528
+ if phases & voids:
529
+ mesh = mesh.subset(sorted(phases - voids))
530
+ missing = sorted(phases - voids - {int(k) for k in materials})
531
+ if missing:
532
+ raise ValueError(f"no material for the phases {missing} of the mesh")
533
+ return mesh
534
+
535
+
536
+ def _contact_report(args, mesh, values: dict, rows: list, curve: str, lines: list) -> int:
537
+ """The results of a test of contact: its curve (.csv), its report (``-o``, ``--json``)
538
+ or its lines on the terminal."""
539
+ target = Path(args.curve or curve)
540
+ target.parent.mkdir(parents=True, exist_ok=True)
541
+ pipeline.write_rows(target, rows)
542
+ out = {
543
+ "file": str(args.sample),
544
+ "elements": mesh.n_elements,
545
+ "nodes": mesh.n_nodes,
546
+ "order": mesh.order,
547
+ **values,
548
+ "curve": str(target),
549
+ }
550
+ if args.output:
551
+ Path(args.output).write_text(json.dumps(to_jsonable(out), indent=2) + "\n", "utf-8")
552
+ if args.json:
553
+ print(json.dumps(to_jsonable(out), indent=2))
554
+ return 0
555
+ print(
556
+ f"{args.sample}: {mesh.n_elements} tetrahedra ({mesh.order * 6 - 2}-node), "
557
+ f"{mesh.n_nodes} nodes"
558
+ )
559
+ for line in lines:
560
+ print(line)
561
+ print(f"curve {target}")
562
+ return 0
563
+
564
+
565
+ def cmd_compress(args) -> int:
566
+ from morphogen.contact import compression
567
+ from morphogen.homogenization import materials_from_config
568
+
569
+ materials = materials_from_config(_material_spec(args))
570
+ mesh = _contact_sample(args, materials)
571
+ res = compression(
572
+ mesh,
573
+ materials,
574
+ args.strain,
575
+ axis=args.axis,
576
+ friction=args.friction,
577
+ self_contact=not args.no_self_contact,
578
+ points=args.points,
579
+ steps=args.steps,
580
+ kinematics="small" if args.small else "finite",
581
+ )
582
+ fields = None
583
+ if args.fields:
584
+ fields = str(res.problem.write(args.fields, res.result))
585
+ tangent = res.tangent()
586
+ values = {
587
+ "height": res.height,
588
+ "section": res.section,
589
+ "strain": float(res.strain[-1]),
590
+ "stress": float(res.stress[-1]),
591
+ "force": float(res.force[-1]),
592
+ "modulus": res.modulus,
593
+ "tangent_modulus": float(tangent[-1]),
594
+ "area_fixed": float(res.area[-1, 0]),
595
+ "area_moving": float(res.area[-1, 1]),
596
+ "self_area": float(res.self_area[-1]),
597
+ "friction": float(res.friction[-1]),
598
+ "steps": len(res.strain) - 1,
599
+ "iterations": int(np.sum(res.result.iterations)),
600
+ "fields": fields,
601
+ }
602
+ lines = [
603
+ f"compressed by {-100 * res.strain[-1]:.4g} % between two platens "
604
+ f"(friction {args.friction:g}): nominal stress {res.stress[-1]:.6g}",
605
+ f"apparent modulus {res.modulus:.6g} at the first step, {tangent[-1]:.6g} at the last",
606
+ f"in contact: {res.area[-1, 0]:.6g} and {res.area[-1, 1]:.6g} with the platens, "
607
+ f"{res.self_area[-1]:.6g} of the sample with itself",
608
+ ]
609
+ stem = Path(args.sample).stem
610
+ return _contact_report(args, mesh, values, res.rows(), f"{stem}_compression.csv", lines)
611
+
612
+
613
+ def cmd_indent(args) -> int:
614
+ from morphogen.contact import indentation
615
+ from morphogen.homogenization import materials_from_config
616
+
617
+ materials = materials_from_config(_material_spec(args))
618
+ mesh = _contact_sample(args, materials)
619
+ res = indentation(
620
+ mesh,
621
+ materials,
622
+ args.depth,
623
+ indenter=args.indenter,
624
+ radius=args.radius,
625
+ half_angle=args.half_angle,
626
+ point=args.point,
627
+ axis=args.axis,
628
+ friction=args.friction,
629
+ steps=args.steps,
630
+ unload=args.unload,
631
+ base=args.base,
632
+ kinematics="small" if args.small else "finite",
633
+ )
634
+ fields = None
635
+ if args.fields:
636
+ fields = str(res.problem.write(args.fields, res.result, step=len(res.depth) - 1))
637
+ peak = int(np.argmax(res.depth))
638
+ values = {
639
+ "indenter": res.indenter,
640
+ "depth": float(res.depth[peak]),
641
+ "force": float(res.force[peak]),
642
+ "area": float(res.area[peak]),
643
+ "radius": float(res.radius[peak]),
644
+ "pressure": float(res.pressure[peak]),
645
+ "hardness": float(res.hardness[peak]),
646
+ "modulus": float(res.modulus[peak]),
647
+ "stiffness": res.stiffness,
648
+ "unloading_modulus": res.unloading_modulus,
649
+ "steps": len(res.depth) - 1,
650
+ "iterations": int(np.sum(res.result.iterations)),
651
+ "fields": fields,
652
+ }
653
+ lines = [
654
+ f"{res.indenter} pressed to {res.depth[peak]:.6g}: force {res.force[peak]:.6g}, "
655
+ f"contact of radius {res.radius[peak]:.6g}, mean pressure {res.hardness[peak]:.6g}",
656
+ f"reduced modulus read from the force: {res.modulus[peak]:.6g} (a half-space)",
657
+ ]
658
+ if args.poisson is not None and res.indenter == "sphere":
659
+ values["layer_modulus"] = float(res.layer_modulus(args.poisson)[peak])
660
+ lines.append(
661
+ f"with the base of the sample (a layer of thickness {res.thickness:.6g}): "
662
+ f"{values['layer_modulus']:.6g}"
663
+ )
664
+ if res.unloading_modulus is not None:
665
+ lines.append(f"from the slope of the unloading: {res.unloading_modulus:.6g}")
666
+ stem = Path(args.sample).stem
667
+ return _contact_report(args, mesh, values, res.rows(), f"{stem}_indentation.csv", lines)
668
+
669
+
670
+ def _interface_options(text: str) -> dict:
671
+ """The law of the interfaces of ``--interfaces``: ``KEY:VALUE`` pairs separated by
672
+ commas (``normal_strength:30,mode_I:0.05,friction:0.3``); ``faces`` is ``phases``,
673
+ ``grains`` or pairs of phases (``faces:0-1+0-2``)."""
674
+ out: dict = {}
675
+ for item in text.split(","):
676
+ key, sep, value = item.partition(":")
677
+ key, value = key.strip(), value.strip()
678
+ if not sep or not key or not value:
679
+ raise ValueError(f"--interfaces {text!r}: KEY:VALUE pairs separated by commas")
680
+ if key == "law":
681
+ out[key] = value
682
+ elif key == "faces":
683
+ if value in ("phases", "grains"):
684
+ out[key] = value
685
+ else:
686
+ try:
687
+ pairs = [[int(p) for p in pair.split("-")] for pair in value.split("+")]
688
+ except ValueError:
689
+ pairs = []
690
+ if not pairs or any(len(pair) != 2 for pair in pairs):
691
+ raise ValueError(
692
+ f"--interfaces: faces is phases, grains or pairs of phases (0-1+0-2), "
693
+ f"got {value!r}"
694
+ )
695
+ out[key] = pairs
696
+ else:
697
+ try:
698
+ out[key] = float(value)
699
+ except ValueError:
700
+ raise ValueError(f"--interfaces: {key} is a number, got {value!r}") from None
701
+ return out
702
+
703
+
704
+ def _nonlinear_options(args) -> dict | None:
705
+ """The options of the loading paths of ``morphogen homogenize``: finite strains
706
+ (``--finite``), the contact of the walls of the pores (``--contact [MU]``) and the
707
+ interfaces of the phases that debond (``--interfaces KEY:VALUE,...``)."""
708
+ out = {}
709
+ if args.finite:
710
+ out["kinematics"] = "finite"
711
+ if args.contact is not None:
712
+ if not args.contact >= 0:
713
+ raise ValueError("--contact: a coefficient of friction of 0 or more")
714
+ out["contact"] = {"friction": args.contact}
715
+ if args.interfaces is not None:
716
+ out["interfaces"] = _interface_options(args.interfaces)
717
+ return out or None
718
+
719
+
720
+ def cmd_homogenize(args) -> int:
721
+ from morphogen.homogenization import (
722
+ Apparent,
723
+ Loading,
724
+ LoadingPath,
725
+ PathResult,
726
+ Response,
727
+ bounds,
728
+ homogenize,
729
+ materials_from_config,
730
+ )
731
+ from morphogen.homogenization.apparent import COUPLED, HARMONIC
732
+ from morphogen.homogenization.coupled import NOTATION as COUPLED_NOTATION
733
+ from morphogen.homogenization.postprocess import notation
734
+ from morphogen.mesh.tetra import TetMesh
735
+
736
+ materials = materials_from_config(_material_spec(args))
737
+ sample, grains = _homogenization_sample(args, materials)
738
+ if isinstance(sample, TetMesh) and args.save_mesh:
739
+ io.save_mesh(sample, args.save_mesh)
740
+ loadings = {}
741
+ for k, text in enumerate(args.loading or []):
742
+ name, sep, rest = text.partition(":")
743
+ name, rest = (name.strip(), rest) if sep else (f"loading{k + 1}", text)
744
+ loadings[name] = Loading.parse(rest)
745
+ paths = {}
746
+ if args.paths:
747
+ loaded = yaml.safe_load(Path(args.paths).read_text(encoding="utf-8"))
748
+ loaded = loaded.get("paths", loaded) if isinstance(loaded, dict) else None
749
+ if not isinstance(loaded, dict):
750
+ raise ValueError("--paths: a YAML/JSON file mapping names to loading paths")
751
+ paths.update({str(k): LoadingPath.from_spec(v) for k, v in loaded.items()})
752
+ for k, text in enumerate(args.path or []):
753
+ name, sep, rest = text.partition(":")
754
+ name, rest = (name.strip(), rest) if sep else (f"path{k + 1}", text)
755
+ paths[name] = LoadingPath.parse(rest)
756
+ results = homogenize(
757
+ sample,
758
+ materials,
759
+ bcs=args.bc,
760
+ properties=args.property,
761
+ solver=args.solver,
762
+ tol=args.tol,
763
+ fields=bool(args.fields),
764
+ loadings=loadings,
765
+ paths=paths,
766
+ nonlinear=_nonlinear_options(args),
767
+ integration=args.integration,
768
+ device=args.device,
769
+ frequencies=args.frequencies,
770
+ wavelengths=args.wavelengths,
771
+ fluid_bulk_modulus=args.fluid_bulk_modulus,
772
+ **grains,
773
+ )
774
+ if isinstance(sample, TetMesh):
775
+ fractions = pipeline._mesh_fractions(sample, materials)
776
+ described = (
777
+ f"{sample.n_elements} tetrahedra ({sample.order * 6 - 2}-node), "
778
+ f"{sample.n_nodes} nodes, finite elements"
779
+ )
780
+ size = {"elements": sample.n_elements, "nodes": sample.n_nodes, "order": sample.order}
781
+ else:
782
+ fractions = analysis.phase_fractions(sample)
783
+ described = f"{sample.shape} voxels, FFT solver"
784
+ size = {"shape": list(sample.shape)}
785
+ out = {"file": str(args.sample), **size, "phase_fractions": fractions}
786
+ table = []
787
+ responses = {}
788
+ curves = {}
789
+ for key, res in results.items():
790
+ if isinstance(res, PathResult):
791
+ folder = Path(args.curves)
792
+ folder.mkdir(parents=True, exist_ok=True)
793
+ target = folder / f"{Path(args.sample).stem}_{key.replace('.', '_')}.csv"
794
+ pipeline.write_rows(target, res.rows())
795
+ curves[key] = {**res.components(), "steps": res.n_steps, "curve": str(target)}
796
+ if args.fields and res.fields:
797
+ folder = Path(args.fields)
798
+ folder.mkdir(parents=True, exist_ok=True)
799
+ for k, arrays in enumerate(res.fields[t] for t in sorted(res.fields)):
800
+ stem = f"{Path(args.sample).stem}_{key.replace('.', '_')}_{k + 1}.vtu"
801
+ pipeline.write_path_fields(folder / stem, res.support, arrays)
802
+ continue
803
+ if isinstance(res, (Apparent, Response)):
804
+ if isinstance(res, Apparent):
805
+ table.append(res.row())
806
+ else:
807
+ responses[key] = res.components()
808
+ if args.fields:
809
+ folder = Path(args.fields)
810
+ folder.mkdir(parents=True, exist_ok=True)
811
+ stem = f"{Path(args.sample).stem}_{key.replace('.', '_')}"
812
+ pipeline._write_fields(res, folder / stem)
813
+ elif key.partition(".")[0] in COUPLED: # the tensors of a coupled law
814
+ out[key] = {**res, "notation": COUPLED_NOTATION}
815
+ elif key.partition(".")[0] in HARMONIC:
816
+ out[key] = res
817
+ elif isinstance(res, dict) and "compliance" in res: # a stiffness, its compliance
818
+ out[key] = {**res, "notation": notation(res["tensor"])}
819
+ else:
820
+ out[key] = res
821
+ out["results"] = table
822
+ if responses:
823
+ out["loadings"] = responses
824
+ if curves:
825
+ out["paths"] = curves
826
+ try:
827
+ out["bounds"] = bounds(fractions, materials)
828
+ except (ValueError, KeyError):
829
+ out["bounds"] = {}
830
+ if args.output:
831
+ Path(args.output).write_text(json.dumps(to_jsonable(out), indent=2) + "\n", "utf-8")
832
+ if args.json:
833
+ print(json.dumps(to_jsonable(out), indent=2))
834
+ return 0
835
+ print(
836
+ f"{args.sample}: {described}; phase fractions "
837
+ + ", ".join(f"{p}: {f:.4f}" for p, f in fractions.items())
838
+ )
839
+ width = max([15] + [len(row["property"]) for row in table])
840
+ print(
841
+ f"{'property':>{width}s} {'bc':>9s} {'value':>12s} {'energy':>12s} {'isotropy':>9s} "
842
+ f"{'dofs':>9s} {'iter':>5s} {'time_s':>7s}"
843
+ )
844
+ for row in table:
845
+ print(
846
+ f"{row['property']:>{width}s} {row['bc']:>9s} {row['value']:12.6g} "
847
+ f"{row['energy_value']:12.6g} {row['isotropy']:9.3g} {row['n_dofs']:9d} "
848
+ f"{row['iterations']:5d} {row['solve_s']:7.2f}"
849
+ )
850
+ for key, res in results.items():
851
+ if isinstance(res, Response):
852
+ print(f"{key}: " + " ".join(f"{n} {v:.6g}" for n, v in res.components().items()))
853
+ elif isinstance(res, PathResult):
854
+ final = " ".join(f"{n} {v:.6g}" for n, v in res.components().items())
855
+ print(f"{key}: {res.n_steps} steps, final {final}; curve {curves[key]['curve']}")
856
+ elif key.partition(".")[0] in HARMONIC: # its scalar entries at each frequency
857
+ print(f"{key}:")
858
+ _print_harmonic(res)
859
+ elif key.partition(".")[0] in COUPLED: # its tensors by name, then its constants
860
+ print(f"{key} ({COUPLED_NOTATION}):")
861
+ for name, value in res.items():
862
+ if name != "tensor" and isinstance(value, np.ndarray) and value.ndim == 2:
863
+ print(f" {name}:")
864
+ print(_matrix_text(value))
865
+ constants = {n: v for n, v in res.items() if isinstance(v, float) and n != "residual"}
866
+ print(" constants: " + ", ".join(f"{n} {v:.6g}" for n, v in constants.items()))
867
+ elif key.partition(".")[0] in ("hydraulic_permeability", "acoustic"):
868
+ print(f"{key} (lengths in the unit of the voxels, permeabilities in its square):")
869
+ tensor = res.get("tensor", res.get("permeability_tensor"))
870
+ print(" permeability tensor k (<v> = -k grad p / viscosity):")
871
+ print(_matrix_text(tensor))
872
+ constants = {n: v for n, v in res.items() if isinstance(v, float) and len(n) > 3}
873
+ print(" " + ", ".join(f"{n} {v:.6g}" for n, v in constants.items()))
874
+ elif key.partition(".")[0] == "poroelastic": # drained C and S, Biot, Gassmann
875
+ print(f"{key} (Sigma = C E - b p; porosity change = b : E + p / N):")
876
+ _print_elastic(res["tensor"], res["compliance"])
877
+ print(" tensor of Biot b:")
878
+ print(_matrix_text(res["biot"]))
879
+ if "skempton" in res:
880
+ print(" undrained stiffness:")
881
+ print(_matrix_text(res["undrained_stiffness"]))
882
+ print(" tensor of Skempton B (p = -B : Sigma / 3):")
883
+ print(_matrix_text(res["skempton"]))
884
+ constants = {n: v for n, v in res.items() if isinstance(v, float) and len(n) > 3}
885
+ print(" constants: " + ", ".join(f"{n} {v:.6g}" for n, v in constants.items()))
886
+ elif isinstance(res, dict) and "compliance" in res: # C, S = C^-1, the constants
887
+ print(f"{key}:")
888
+ _print_elastic(res["tensor"], res["compliance"])
889
+ names = [f"E{i}" for i in (1, 2, 3)] + ["G23", "G31", "G12"]
890
+ names += [f"nu{i}{j}" for i in (1, 2, 3) for j in (1, 2, 3) if i != j]
891
+ print("engineering constants: " + ", ".join(f"{n} {res[n]:.6g}" for n in names))
892
+ elif not isinstance(res, Apparent):
893
+ print(f"{key}:")
894
+ print(_matrix_text(res["tensor"]))
895
+ for prop, b in out["bounds"].items():
896
+ print(f"bounds of {prop}: " + ", ".join(f"{k} {v:.6g}" for k, v in b.items()))
897
+ return 0
898
+
899
+
900
+ def cmd_bands(args) -> int:
901
+ """The band structure of the Bloch waves of a periodic cell (an image or a mesh)."""
902
+ from morphogen.homogenization import band_structure, materials_from_config
903
+ from morphogen.homogenization.bloch import POINTS
904
+
905
+ materials = materials_from_config(_material_spec(args))
906
+ path = Path(args.sample)
907
+ if path.suffix.lower() in (".vtu", ".mesh"):
908
+ sample = io.read_tet_mesh(path, periodic=True)
909
+ else:
910
+ sample = io.load_image(path, name=args.array)
911
+ sample.periodic = True
912
+ unknown = [c for c in args.path or () if c not in POINTS]
913
+ if unknown or (args.path and len(args.path) < 2):
914
+ raise ValueError(
915
+ f"--path: at least two corners of the Brillouin zone among {', '.join(POINTS)}"
916
+ )
917
+ bands = band_structure(
918
+ sample,
919
+ materials,
920
+ tuple(args.path) if args.path else None,
921
+ bands=args.bands,
922
+ points=args.points,
923
+ order=args.order,
924
+ phases=args.phases,
925
+ waves=args.waves,
926
+ coarsen=args.coarsen,
927
+ )
928
+ names = [f"omega{k + 1}" for k in range(bands.frequencies.shape[1])]
929
+ rows = [
930
+ {"distance": float(d), "kx": float(k[0]), "ky": float(k[1]), "kz": float(k[2]),
931
+ **{n: float(f) for n, f in zip(names, row, strict=True)}}
932
+ for d, k, row in zip(bands.distance, bands.wavevectors, bands.frequencies, strict=True)
933
+ ] # fmt: skip
934
+ gaps = [{"below": n, "low": low, "high": high} for n, low, high in bands.gaps()]
935
+ if args.output:
936
+ pipeline.write_rows(Path(args.output), rows)
937
+ if args.figure:
938
+ ax = bands.plot(ylabel="angular frequency")
939
+ ax.figure.savefig(args.figure, dpi=150)
940
+ out = {
941
+ "file": str(args.sample),
942
+ "waves": args.waves,
943
+ "path": [name for _, name in bands.labels],
944
+ "wavevectors": len(rows),
945
+ "bands": bands.frequencies.shape[1],
946
+ "gaps": gaps,
947
+ "highest": float(bands.frequencies.max()),
948
+ }
949
+ if args.json:
950
+ print(json.dumps(to_jsonable({**out, "frequencies": bands.frequencies}), indent=2))
951
+ return 0
952
+ corners = " - ".join(out["path"])
953
+ print(f"{args.sample}: {out['bands']} bands of the {args.waves} waves at {len(rows)} wave "
954
+ f"vectors along {corners}") # fmt: skip
955
+ for (_, name), i in zip(bands.labels, _label_rows(bands), strict=True):
956
+ values = " ".join(f"{f:.6g}" for f in bands.frequencies[i])
957
+ print(f" {name:>2s}: {values}")
958
+ if gaps:
959
+ for gap in gaps:
960
+ low, high, n = gap["low"], gap["high"], gap["below"]
961
+ width = 200 * (high - low) / (high + low)
962
+ print(f"band gap between the bands {n} and {n + 1}: {low:.6g} to {high:.6g} "
963
+ f"({width:.1f} % of its middle)") # fmt: skip
964
+ else:
965
+ print("no band gap along this path")
966
+ for target in (args.output, args.figure):
967
+ if target:
968
+ print(f"written: {target}")
969
+ return 0
970
+
971
+
972
+ def _label_rows(bands) -> list[int]:
973
+ """The rows of the wave vectors of the corners of the path of a band structure."""
974
+ return [int(np.argmin(np.abs(bands.distance - position))) for position, _ in bands.labels]
975
+
976
+
977
+ def _indices(text: str) -> tuple[int, ...]:
978
+ """The indices of a family of planes written without spaces: 111, 10-10, 0001."""
979
+ import re
980
+
981
+ found = re.findall(r"-?\d", text.replace(" ", "").replace(",", ""))
982
+ if not found or "".join(found) != text.replace(" ", "").replace(",", ""):
983
+ raise argparse.ArgumentTypeError(
984
+ f"expected Miller indices such as 111 or 10-10, got {text!r}"
985
+ )
986
+ return tuple(int(v) for v in found)
987
+
988
+
989
+ def _sample_direction(text: str) -> tuple[float, float, float]:
990
+ """A direction of the sample: x, y, z or three numbers separated by commas."""
991
+ named = {"x": (1.0, 0.0, 0.0), "y": (0.0, 1.0, 0.0), "z": (0.0, 0.0, 1.0)}
992
+ if text.lower() in named:
993
+ return named[text.lower()]
994
+ try:
995
+ values = tuple(float(v) for v in text.split(","))
996
+ except ValueError:
997
+ values = ()
998
+ if len(values) != 3 or not any(values):
999
+ raise argparse.ArgumentTypeError(f"expected x, y, z or three numbers a,b,c, got {text!r}")
1000
+ return values
1001
+
1002
+
1003
+ def _fields_texture(args) -> int:
1004
+ """``morphogen texture`` on the fields of a loading path: the texture of the lattices
1005
+ of its crystals (a .vti or a .vtu file with their orientations)."""
1006
+ from morphogen import texture
1007
+
1008
+ euler, weights = pipeline.read_path_texture(args.map)
1009
+ family = {"m-3": "cubic", "6/m": "hexagonal"}.get(args.lattice, args.lattice)
1010
+ defaults = {"cubic": ((1, 0, 0), (1, 1, 0), (1, 1, 1)),
1011
+ "hexagonal": ((0, 0, 0, 1), (1, 0, -1, 0), (1, 0, -1, 1))} # fmt: skip
1012
+ shown = [texture.pole_figure(euler, indices, family, weights=weights,
1013
+ halfwidth=args.halfwidth)
1014
+ for indices in args.poles or defaults[family]] # fmt: skip
1015
+ inverse = texture.inverse_pole_figure(euler, args.direction, family, weights=weights,
1016
+ halfwidth=args.halfwidth) # fmt: skip
1017
+ names = ["".join(str(int(v)) for v in f.indices) for f in shown]
1018
+ summary = {
1019
+ "file": str(args.map),
1020
+ "crystals": len(euler),
1021
+ "lattice": family,
1022
+ "pole_figures": {n: f.maximum for n, f in zip(names, shown, strict=True)},
1023
+ "inverse_pole_figure": inverse.maximum,
1024
+ "files": [],
1025
+ }
1026
+ if args.output:
1027
+ from morphogen.viz import figures
1028
+ from morphogen.viz.export import save_figure
1029
+
1030
+ folder = Path(args.output)
1031
+ name = {(1.0, 0.0, 0.0): "x", (0.0, 1.0, 0.0): "y", (0.0, 0.0, 1.0): "z"}.get(
1032
+ tuple(args.direction), "d"
1033
+ )
1034
+ written = [
1035
+ save_figure(figures.pole_figures_figure(shown), folder / f"pole_figures.{args.format}"),
1036
+ save_figure(figures.inverse_pole_figure_figure(inverse),
1037
+ folder / f"inverse_pole_figure_{name}.{args.format}"),
1038
+ ] # fmt: skip
1039
+ summary["files"] = [str(p) for p in written]
1040
+ if args.json:
1041
+ print(json.dumps(to_jsonable(summary), indent=2))
1042
+ return 0
1043
+ print(f"{args.map}: the lattices of {len(euler)} crystals ({family})")
1044
+ maxima = ", ".join(f"{{{n}}} {f.maximum:.1f}" for n, f in zip(names, shown, strict=True))
1045
+ print(f" pole figures, largest density in multiples of random: {maxima}")
1046
+ print(f" inverse pole figure of the direction {tuple(args.direction)}: {inverse.maximum:.1f}")
1047
+ for path in summary["files"]:
1048
+ print(f"written: {path}")
1049
+ return 0
1050
+
1051
+
1052
+ def cmd_texture(args) -> int:
1053
+ """The grains and the texture of an orientation map (an .ang or a .ctf file), or the
1054
+ texture of the lattices of the fields of a loading path (.vti, .vtu)."""
1055
+ from morphogen.io import ebsd as maps
1056
+ from morphogen.viz.png import encode_png, upscale
1057
+
1058
+ if Path(args.map).suffix.lower() in (".vti", ".vtu"):
1059
+ return _fields_texture(args)
1060
+ measured = maps.read_ebsd(args.map, axes=args.axes, setting=args.setting)
1061
+ grains = measured.grains(args.threshold, min_size=args.min_size)
1062
+ ny, nx = measured.shape
1063
+ summary = {
1064
+ "file": str(args.map),
1065
+ "points": [nx, ny],
1066
+ "step": list(measured.step),
1067
+ "size": list(measured.size),
1068
+ "indexed": float(measured.indexed.mean()),
1069
+ "threshold": args.threshold,
1070
+ "min_size": args.min_size,
1071
+ **grains.summary(poles=args.poles, halfwidth=args.halfwidth),
1072
+ }
1073
+ written = []
1074
+ if args.output:
1075
+ folder = Path(args.output)
1076
+ folder.mkdir(parents=True, exist_ok=True)
1077
+ written.append(io.write_table(folder / "grains.csv", grains.table()))
1078
+ pairs, lengths, angles = grains.boundaries()
1079
+ boundaries = {"grain_a": pairs[:, 0], "grain_b": pairs[:, 1], "length": lengths,
1080
+ "disorientation": angles} # fmt: skip
1081
+ written.append(io.write_table(folder / "boundaries.csv", boundaries))
1082
+ name = {(1.0, 0.0, 0.0): "x", (0.0, 1.0, 0.0): "y", (0.0, 0.0, 1.0): "z"}.get(
1083
+ tuple(args.direction), "d"
1084
+ )
1085
+ colours = np.rint(255.0 * measured.colours(args.direction)).astype(np.uint8)
1086
+ target = folder / f"map_ipf_{name}.png"
1087
+ target.write_bytes(encode_png(upscale(colours, max(1, 512 // max(nx, ny)))))
1088
+ written.append(target)
1089
+ written += _texture_figures(folder, measured, grains, args, name)
1090
+ if args.convert:
1091
+ cleaned = measured
1092
+ if args.clean: # the map of the grains: their mean orientations at every point
1093
+ cleaned = maps.EBSDMap.from_grains(grains.labels, grains.orientations, grains.step,
1094
+ phase=grains.phase, phases=grains.phases,
1095
+ unit=grains.unit) # fmt: skip
1096
+ written.append(maps.write_ebsd(args.convert, cleaned, axes=args.axes, setting=args.setting))
1097
+ summary["files"] = [str(p) for p in written]
1098
+ if args.json:
1099
+ print(json.dumps(to_jsonable(summary), indent=2))
1100
+ return 0
1101
+ print(f"{args.map}: {nx} x {ny} points every {measured.step[0]:g} x {measured.step[1]:g} "
1102
+ f"{measured.unit}, {100.0 * summary['indexed']:.1f} % indexed") # fmt: skip
1103
+ print(f"grains (neighbouring points less than {args.threshold:g} degrees apart, "
1104
+ f"{args.min_size} points at least): {grains.count}") # fmt: skip
1105
+ for entry in summary["phases"]:
1106
+ print(f" {entry['name']} ({entry['lattice']}): {entry['grains']} grains, "
1107
+ f"{100.0 * entry['area_fraction']:.1f} % of the area") # fmt: skip
1108
+ print(f" mean diameter {entry['mean_diameter']:.3g} {measured.unit} "
1109
+ f"({entry['mean_diameter_by_area']:.3g} by area), spread inside the grains "
1110
+ f"{entry['mean_spread']:.2f} degrees") # fmt: skip
1111
+ if "mean_disorientation" in entry:
1112
+ random = " (40.7 for crystals at random)" if entry["lattice"] == "cubic" else ""
1113
+ print(f" {entry['boundaries']} boundaries, mean disorientation "
1114
+ f"{entry['mean_disorientation']:.1f} degrees{random}") # fmt: skip
1115
+ if entry.get("pole_figures"):
1116
+ maxima = ", ".join(f"{{{k}}} {v:.1f}" for k, v in entry["pole_figures"].items())
1117
+ print(f" pole figures, largest density in multiples of random: {maxima}")
1118
+ for path in written:
1119
+ print(f"written: {path}")
1120
+ return 0
1121
+
1122
+
1123
+ def _texture_figures(folder: Path, measured, grains, args, name: str) -> list[Path]:
1124
+ """The figures of ``morphogen texture`` (matplotlib): the map with its boundaries,
1125
+ the pole figures and the inverse pole figure of each cubic or hexagonal phase, the
1126
+ disorientations of the boundaries."""
1127
+ from morphogen import texture
1128
+
1129
+ try:
1130
+ from morphogen.viz import figures
1131
+ from morphogen.viz.export import save_figure
1132
+
1133
+ figures._figure()
1134
+ except ImportError:
1135
+ log.warning("no figures without matplotlib: pip install 'morphogen[plot]'")
1136
+ return []
1137
+ written = []
1138
+
1139
+ def save(fig, stem: str) -> None:
1140
+ written.append(save_figure(fig, folder / f"{stem}.{args.format}"))
1141
+
1142
+ save(figures.ipf_map_figure(measured, args.direction, grains=grains), f"map_ipf_{name}_grains")
1143
+ defaults = {"cubic": ((1, 0, 0), (1, 1, 0), (1, 1, 1)),
1144
+ "hexagonal": ((0, 0, 0, 1), (1, 0, -1, 0), (1, 0, -1, 1))} # fmt: skip
1145
+ pairs, lengths, angles = grains.boundaries()
1146
+ for k, phase in enumerate(grains.phases, start=1):
1147
+ of = grains.phase == k
1148
+ if not of.any():
1149
+ continue
1150
+ suffix = f"_phase{k}" if len(grains.phases) > 1 else ""
1151
+ lattice = grains.lattice(k)
1152
+ family = {"m-3": "cubic", "6/m": "hexagonal"}.get(lattice, lattice)
1153
+ if family in defaults:
1154
+ ratio = phase.c_over_a if family == "hexagonal" else None
1155
+ shown = [texture.pole_figure(grains.orientations[of], indices, family,
1156
+ weights=grains.areas[of], halfwidth=args.halfwidth,
1157
+ c_over_a=ratio)
1158
+ for indices in args.poles or defaults[family]] # fmt: skip
1159
+ save(figures.pole_figures_figure(shown, title=phase.name or None),
1160
+ f"pole_figures{suffix}") # fmt: skip
1161
+ inverse = texture.inverse_pole_figure(grains.orientations[of], args.direction, family,
1162
+ weights=grains.areas[of],
1163
+ halfwidth=args.halfwidth) # fmt: skip
1164
+ points = texture.inverse_poles(grains.orientations[of], args.direction, family)
1165
+ save(figures.inverse_pole_figure_figure(inverse, points=points),
1166
+ f"inverse_pole_figure_{name}{suffix}") # fmt: skip
1167
+ between = of[pairs[:, 0]] if len(pairs) else np.zeros(0, dtype=bool)
1168
+ if between.any():
1169
+ save(figures.disorientation_figure(angles[between], lengths[between], lattice=lattice),
1170
+ f"disorientations{suffix}") # fmt: skip
1171
+ return written
1172
+
1173
+
1174
+ def cmd_analyze(args) -> int:
1175
+ image = io.load_image(args.image, name=args.array)
1176
+ labels = None
1177
+ if "cells" in args.measure:
1178
+ labels = image
1179
+ out = analysis.measure(image, [m for m in args.measure], labels=labels)
1180
+ out = {"file": str(args.image), "shape": list(image.shape), **out}
1181
+ if args.json:
1182
+ print(json.dumps(to_jsonable(out), indent=2))
1183
+ else:
1184
+ for key, value in out.items():
1185
+ print(f"{key:>20s}: {value}")
1186
+ return 0
1187
+
1188
+
1189
+ def _sizes(text: str) -> list[int]:
1190
+ """Box sizes, in voxels per edge: integers separated by commas."""
1191
+ try:
1192
+ return [int(v) for v in text.replace(" ", "").split(",") if v]
1193
+ except ValueError:
1194
+ raise argparse.ArgumentTypeError(
1195
+ f"expected integers separated by commas, got {text!r}"
1196
+ ) from None
1197
+
1198
+
1199
+ def _percolation_scaling(args, cfg) -> int:
1200
+ """``morphogen percolation --sizes``: the thresholds of the boxes, extrapolated."""
1201
+ from morphogen.analysis.percolation import family_from_config, percolation_scaling
1202
+
1203
+ result = percolation_scaling(
1204
+ family_from_config(cfg, args.parameter, sized=True),
1205
+ args.sizes,
1206
+ args.lower,
1207
+ args.upper,
1208
+ nu=args.nu,
1209
+ fit_nu=args.fit_nu,
1210
+ phase=args.phase,
1211
+ axis=args.axis,
1212
+ connectivity=args.connectivity,
1213
+ periodic=args.periodic,
1214
+ method=args.method,
1215
+ realizations=args.realizations,
1216
+ tol=args.tol,
1217
+ seed=cfg.seed if args.seed is None else args.seed,
1218
+ )
1219
+ if args.json:
1220
+ out = {
1221
+ "config": str(args.config),
1222
+ "model": cfg.model.name,
1223
+ "parameter": args.parameter,
1224
+ "method": args.method,
1225
+ "threshold": result.threshold,
1226
+ "stderr": result.stderr,
1227
+ "amplitude": result.amplitude,
1228
+ "nu": result.nu,
1229
+ "nu_stderr": result.nu_stderr,
1230
+ "realizations": args.realizations,
1231
+ "sizes": result.sizes,
1232
+ "thresholds": result.thresholds,
1233
+ "brackets": result.brackets,
1234
+ "residuals": result.residuals,
1235
+ }
1236
+ print(json.dumps(to_jsonable(out), indent=2))
1237
+ return 0
1238
+ along = {"any": "any axis", "all": "the three axes"}.get(args.axis, args.axis)
1239
+ nu = f"nu = {result.nu:.4g}"
1240
+ if result.nu_stderr is not None:
1241
+ nu += f" +/- {result.nu_stderr:.2g} fitted"
1242
+ print(
1243
+ f"percolation threshold of phase {args.phase} of {cfg.model.name} along {along}, "
1244
+ f"extrapolated from {len(result.sizes)} box sizes: {args.parameter} = "
1245
+ f"{result.threshold:.4g} +/- {result.stderr:.2g} (a = {result.amplitude:.4g}, {nu}; "
1246
+ f"{args.realizations} realizations{', forest fire' if args.method == 'fire' else ''})"
1247
+ )
1248
+ print(f"{'size':>8s} {args.parameter:>20s} {'bracket':>21s} residual")
1249
+ for size, threshold, (lo, hi), residual in zip(
1250
+ result.sizes, result.thresholds, result.brackets, result.residuals, strict=True
1251
+ ):
1252
+ print(f"{size:8d} {threshold:20.4g} {f'[{lo:.4g}, {hi:.4g}]':>21s} {residual:+.2e}")
1253
+ return 0
1254
+
1255
+
1256
+ def _directions(text: str):
1257
+ """Directions of percolation: axes, lattice (the axes and the diagonals) or a number."""
1258
+ if text in ("axes", "lattice"):
1259
+ return text
1260
+ try:
1261
+ count = int(text)
1262
+ except ValueError:
1263
+ count = 0
1264
+ if count < 1:
1265
+ raise argparse.ArgumentTypeError(f"expected axes, lattice or a number, got {text!r}")
1266
+ return count
1267
+
1268
+
1269
+ def _percolation_anisotropy(args, cfg) -> int:
1270
+ """``morphogen percolation --directions``: the thresholds along directions, their
1271
+ anisotropy and the threshold tensor."""
1272
+ from morphogen.analysis.percolation import family_from_config, percolation_anisotropy
1273
+
1274
+ r = percolation_anisotropy(
1275
+ family_from_config(cfg, args.parameter),
1276
+ args.lower,
1277
+ args.upper,
1278
+ directions=args.directions,
1279
+ phase=args.phase,
1280
+ connectivity=args.connectivity,
1281
+ realizations=args.realizations,
1282
+ tol=args.tol,
1283
+ seed=cfg.seed if args.seed is None else args.seed,
1284
+ )
1285
+ names = ("directions", "thresholds", "stderr", "deviations", "deviation_stderr", "ratio",
1286
+ "ratio_stderr", "tensor", "eigenvalues", "eigenvalue_stderr", "principal",
1287
+ "residuals", "samples") # fmt: skip
1288
+ if args.json:
1289
+ out = {"config": str(args.config), "model": cfg.model.name, "parameter": args.parameter,
1290
+ "realizations": r.realizations, **{k: getattr(r, k) for k in names}} # fmt: skip
1291
+ print(json.dumps(to_jsonable(out), indent=2))
1292
+ return 0
1293
+
1294
+ def vector(v):
1295
+ return "(" + ", ".join(f"{c:+.3f}" for c in v) + ")"
1296
+
1297
+ print(
1298
+ f"percolation thresholds of phase {args.phase} of {cfg.model.name} along "
1299
+ f"{len(r.directions)} directions (across the cores of the inscribed ball, forest fire, "
1300
+ f"{r.realizations} realizations): largest over smallest {r.ratio:.4g} +/- "
1301
+ f"{r.ratio_stderr:.2g}"
1302
+ )
1303
+ if np.all(np.isfinite(r.eigenvalues)):
1304
+ axes = zip(r.eigenvalues, r.eigenvalue_stderr, r.principal, strict=True)
1305
+ terms = (f"{v:.4g} +/- {e:.2g} along {vector(a)}" for v, e, a in axes)
1306
+ print("threshold tensor: " + "; ".join(terms))
1307
+ print(f"{'direction':>24s} {args.parameter:>20s} {'stderr':>8s} {'deviation':>10s} paired")
1308
+ for n, t, e, d, p in zip(r.directions, r.thresholds, r.stderr, r.deviations,
1309
+ r.deviation_stderr, strict=True): # fmt: skip
1310
+ print(f"{vector(n):>24s} {t:20.4g} {e:8.2g} {d:+10.2e} {p:.2g}")
1311
+ return 0
1312
+
1313
+
1314
+ def _fractions(text: str) -> list[float]:
1315
+ """Fractions of a sweep: numbers separated by commas."""
1316
+ try:
1317
+ return [float(v) for v in text.replace(" ", "").split(",") if v]
1318
+ except ValueError:
1319
+ raise argparse.ArgumentTypeError(
1320
+ f"expected numbers separated by commas, got {text!r}"
1321
+ ) from None
1322
+
1323
+
1324
+ #: The solvers of the voxels of ``morphogen percolation --solver``, as the output names them
1325
+ _SOLVED = {"fft": "FFT", "fe": "voxel FE"}
1326
+
1327
+
1328
+ def _rigidity(args, cfg, family):
1329
+ """The rigidity threshold of the --sizes: where the elastic moduli of the phase vanish
1330
+ (``--rigidity``, and the threshold of ``--exponent elastic``)."""
1331
+ from morphogen.analysis.percolation import rigidity_threshold
1332
+
1333
+ return rigidity_threshold(
1334
+ family,
1335
+ args.sizes,
1336
+ args.lower,
1337
+ args.upper,
1338
+ nu=args.nu,
1339
+ fit_nu=args.fit_nu and not args.exponent,
1340
+ phase=args.phase,
1341
+ axis=args.axis,
1342
+ cut=args.cut,
1343
+ realizations=args.realizations,
1344
+ tol=args.tol,
1345
+ device=args.device,
1346
+ solver=args.solver,
1347
+ seed=cfg.seed if args.seed is None else args.seed,
1348
+ )
1349
+
1350
+
1351
+ def _percolation_rigidity(args, cfg) -> int:
1352
+ """``morphogen percolation --rigidity``: the rigidity threshold of the boxes, where the
1353
+ elastic moduli of the phase vanish, extrapolated."""
1354
+ from morphogen.analysis.percolation import family_from_config
1355
+
1356
+ if not args.sizes:
1357
+ raise ValueError("--rigidity: give the box sizes of the finite-size scaling (--sizes)")
1358
+ if args.axis not in ("x", "y", "z"):
1359
+ raise ValueError(f"--rigidity: along one axis (x, y or z), got {args.axis!r}")
1360
+ r = _rigidity(args, cfg, family_from_config(cfg, args.parameter, sized=True))
1361
+ if args.json:
1362
+ names = ("threshold", "stderr", "amplitude", "nu", "nu_stderr", "sizes", "thresholds",
1363
+ "brackets", "residuals", "cut", "contrast", "floppy", "rigid", "solver",
1364
+ "solutions", "decided", "unresolved", "iterations", "residual") # fmt: skip
1365
+ out = {"config": str(args.config), "model": cfg.model.name, "parameter": args.parameter,
1366
+ "criterion": "rigidity", "realizations": args.realizations,
1367
+ **{k: getattr(r, k) for k in names},
1368
+ "probabilities": [one.probabilities for one in r.results],
1369
+ "fractions": [one.fractions for one in r.results]} # fmt: skip
1370
+ print(json.dumps(to_jsonable(out), indent=2))
1371
+ return 0
1372
+ nu = f"nu = {r.nu:.4g}"
1373
+ if r.nu_stderr is not None:
1374
+ nu += f" +/- {r.nu_stderr:.2g} fitted"
1375
+ print(
1376
+ f"rigidity threshold of phase {args.phase} of {cfg.model.name} along {args.axis}, "
1377
+ f"extrapolated from {len(r.sizes)} box sizes: {args.parameter} = {r.threshold:.4g} "
1378
+ f"+/- {r.stderr:.2g} (a = {r.amplitude:.4g}, {nu}; {args.realizations} realizations "
1379
+ f"bearing a uniaxial strain above {r.cut:.2g} of the Young's modulus of the phase, the "
1380
+ "other phases void)"
1381
+ )
1382
+ print(
1383
+ f"{r.solutions} {_SOLVED[r.solver]} solutions ({r.decided} images decided by their "
1384
+ f"connectivity or inclusion, {r.unresolved} energies above the cut unresolved by the "
1385
+ f"stress average), at most {r.iterations} iterations; moduli solved: floppy up to "
1386
+ f"{r.floppy:.2g}, rigid from {r.rigid:.2g}"
1387
+ )
1388
+ print(f"{'size':>8s} {args.parameter:>20s} {'bracket':>21s} residual")
1389
+ for size, threshold, (lo, hi), residual in zip(
1390
+ r.sizes, r.thresholds, r.brackets, r.residuals, strict=True
1391
+ ):
1392
+ print(f"{size:8d} {threshold:20.4g} {f'[{lo:.4g}, {hi:.4g}]':>21s} {residual:+.2e}")
1393
+ return 0
1394
+
1395
+
1396
+ def _percolation_exponent(args, cfg) -> int:
1397
+ """``morphogen percolation --exponent``: the critical exponent of the conductivity or of
1398
+ the elastic moduli, by finite-size scaling at the threshold (extrapolated first by the
1399
+ same sizes unless given: that of the connectivity for the conductivity, that of the
1400
+ moduli, the rigidity, for the elastic moduli)."""
1401
+ from morphogen.analysis.percolation import (
1402
+ _extrapolated_threshold,
1403
+ family_from_config,
1404
+ percolation_exponent,
1405
+ percolation_scaling,
1406
+ )
1407
+
1408
+ if not args.sizes:
1409
+ raise ValueError("--exponent: give the box sizes of the finite-size scaling (--sizes)")
1410
+ if args.axis not in ("x", "y", "z"):
1411
+ raise ValueError(f"--exponent: along one axis (x, y or z), got {args.axis!r}")
1412
+ family = family_from_config(cfg, args.parameter, sized=True)
1413
+ seed = cfg.seed if args.seed is None else args.seed
1414
+ scaling, threshold, stderr = None, args.threshold, args.threshold_stderr
1415
+ criterion = "given" if threshold is not None else "connectivity"
1416
+ if threshold is None and args.exponent == "elastic":
1417
+ criterion, scaling = "rigidity", _rigidity(args, cfg, family)
1418
+ threshold, error = _extrapolated_threshold(scaling, args.lower, args.upper)
1419
+ stderr = error if stderr is None else stderr
1420
+ elif threshold is None:
1421
+ scaling = percolation_scaling(
1422
+ family,
1423
+ args.sizes,
1424
+ args.lower,
1425
+ args.upper,
1426
+ nu=args.nu,
1427
+ phase=args.phase,
1428
+ axis=args.axis,
1429
+ connectivity=args.connectivity,
1430
+ periodic=args.periodic,
1431
+ method=args.method,
1432
+ realizations=args.realizations,
1433
+ tol=args.tol,
1434
+ seed=seed,
1435
+ )
1436
+ threshold, error = _extrapolated_threshold(scaling, args.lower, args.upper)
1437
+ stderr = error if stderr is None else stderr
1438
+ r = percolation_exponent(
1439
+ family,
1440
+ args.sizes,
1441
+ threshold,
1442
+ threshold_stderr=stderr or 0.0,
1443
+ fractions=args.fractions or (),
1444
+ physics=args.exponent,
1445
+ phase=args.phase,
1446
+ axis=args.axis,
1447
+ contrast=args.contrast,
1448
+ nu=args.nu,
1449
+ realizations=args.realizations,
1450
+ device=args.device,
1451
+ solver=args.solver,
1452
+ seed=None if seed is None else seed + 1,
1453
+ )
1454
+ name = "t" if r.physics == "thermal" else "f"
1455
+ total = float(np.hypot(r.stderr, r.threshold_error))
1456
+ if args.json:
1457
+ out = {"config": str(args.config), "model": cfg.model.name, "parameter": args.parameter,
1458
+ "physics": r.physics, "threshold": r.threshold,
1459
+ "threshold_stderr": stderr or 0.0, "exponent": r.exponent, "stderr": r.stderr,
1460
+ "threshold_error": r.threshold_error, "error": total, "ratio": r.ratio,
1461
+ "amplitude": r.amplitude, "nu": r.nu, "contrast": r.contrast,
1462
+ "realizations": r.realizations, "sizes": r.sizes, "means": r.means,
1463
+ "mean_stderr": r.mean_stderr, "residuals": r.residuals,
1464
+ "fractions": r.fractions, "values": r.values, "value_stderr": r.value_stderr,
1465
+ "sweep": r.sweep, "sweep_exponents": r.sweep_exponents,
1466
+ "sweep_stderr": r.sweep_stderr, "sweep_threshold_error": r.sweep_threshold_error,
1467
+ "solver": r.solver, "iterations": r.iterations, "residual": r.residual} # fmt: skip
1468
+ out["threshold_criterion"] = criterion
1469
+ if scaling is not None:
1470
+ out["threshold_sizes"], out["thresholds"] = scaling.sizes, scaling.thresholds
1471
+ print(json.dumps(to_jsonable(out), indent=2))
1472
+ return 0
1473
+ prop = "conductivity" if r.physics == "thermal" else "uniaxial-strain modulus"
1474
+ origin = {"given": "given", "connectivity": "extrapolated",
1475
+ "rigidity": "extrapolated from the moduli"}[criterion] # fmt: skip
1476
+ print(
1477
+ f"critical exponent of the {prop} of phase {args.phase} of {cfg.model.name} along "
1478
+ f"{args.axis}: {name} = {r.exponent:.3f} +/- {total:.2g} ({name}/nu = {r.ratio:.4g}, "
1479
+ f"nu = {r.nu:.4g}; statistical {r.stderr:.2g}, from the threshold {r.threshold_error:.2g})"
1480
+ )
1481
+ print(
1482
+ f"at the threshold {args.parameter} = {r.threshold:.4g} +/- {stderr or 0.0:.2g} "
1483
+ f"({origin}), contrast {r.contrast:.2g}, {r.realizations} realizations per size, at "
1484
+ f"most {r.iterations} iterations of the {_SOLVED[r.solver]} solver"
1485
+ )
1486
+ print(f"{'size':>8s} {'mean':>12s} {'stderr':>10s} residual")
1487
+ for size, mean, error, residual in zip(r.sizes, r.means, r.mean_stderr, r.residuals,
1488
+ strict=True): # fmt: skip
1489
+ print(f"{size:8d} {mean:12.4e} {error:10.2e} {residual:+.2e}")
1490
+ if r.sweep.size:
1491
+ fractions = ", ".join(f"{f:.4g}" for f in r.sweep)
1492
+ print(f"sweep over {args.parameter} = {fractions}:")
1493
+ for size, e, s, d in zip(r.sizes, r.sweep_exponents, r.sweep_stderr,
1494
+ r.sweep_threshold_error, strict=True): # fmt: skip
1495
+ print(f"{size:8d} {name} = {e:.3f} +/- {s:.2g} (from the threshold {d:.2g})")
1496
+ return 0
1497
+
1498
+
1499
+ def cmd_percolation(args) -> int:
1500
+ from morphogen.analysis.percolation import family_from_config, percolation_threshold
1501
+
1502
+ cfg = load_config(args.config)
1503
+ if args.rigidity and args.exponent == "thermal":
1504
+ raise ValueError("--rigidity: the threshold of the elastic moduli, for --exponent elastic")
1505
+ if args.connectivity is None: # the FFT solvers join voxels through their nodes
1506
+ args.connectivity = 26 if args.exponent else 6
1507
+ if args.exponent:
1508
+ if args.periodic is None: # and are periodic
1509
+ args.periodic = True
1510
+ return _percolation_exponent(args, cfg)
1511
+ if args.rigidity:
1512
+ return _percolation_rigidity(args, cfg)
1513
+ if args.directions is not None:
1514
+ return _percolation_anisotropy(args, cfg)
1515
+ if args.sizes:
1516
+ return _percolation_scaling(args, cfg)
1517
+ result = percolation_threshold(
1518
+ family_from_config(cfg, args.parameter),
1519
+ args.lower,
1520
+ args.upper,
1521
+ phase=args.phase,
1522
+ axis=args.axis,
1523
+ connectivity=args.connectivity,
1524
+ periodic=args.periodic,
1525
+ method=args.method,
1526
+ realizations=args.realizations,
1527
+ tol=args.tol,
1528
+ seed=cfg.seed if args.seed is None else args.seed,
1529
+ )
1530
+ lo, hi = result.bracket
1531
+ if args.json:
1532
+ out = {
1533
+ "config": str(args.config),
1534
+ "model": cfg.model.name,
1535
+ "parameter": args.parameter,
1536
+ "method": args.method,
1537
+ "threshold": result.threshold,
1538
+ "bracket": [lo, hi],
1539
+ "realizations": result.realizations,
1540
+ "fractions": result.fractions,
1541
+ "probabilities": result.probabilities,
1542
+ }
1543
+ print(json.dumps(to_jsonable(out), indent=2))
1544
+ return 0
1545
+ along = {"any": "any axis", "all": "the three axes"}.get(args.axis, args.axis)
1546
+ print(
1547
+ f"percolation threshold of phase {args.phase} of {cfg.model.name} along {along}: "
1548
+ f"{args.parameter} = {result.threshold:.4g} in [{lo:.4g}, {hi:.4g}] "
1549
+ f"({result.realizations} realizations{', forest fire' if args.method == 'fire' else ''})"
1550
+ )
1551
+ print(f"{args.parameter:>20s} probability")
1552
+ for fraction, probability in zip(result.fractions, result.probabilities, strict=True):
1553
+ print(f"{fraction:20.4g} {probability:11.3f}")
1554
+ return 0
1555
+
1556
+
1557
+ #: The theories of the beams of ``morphogen frame-stiffness``
1558
+ BEAM_THEORIES = ("euler-bernoulli", "timoshenko")
1559
+
1560
+
1561
+ def _realization(path: Path, seed: int | None, realization: int):
1562
+ """A realization of a file and its configuration: a geometry (.json, as ``morphogen
1563
+ run`` writes them; None) or a configuration, whose model is realized in its domain as
1564
+ the realization ``realization`` of its batch run (``seed``: the configuration's when
1565
+ None)."""
1566
+ from morphogen.models.base import Microstructure
1567
+ from morphogen.seeding import derive_seed
1568
+
1569
+ if path.suffix.lower() == ".json":
1570
+ data = json.loads(path.read_text(encoding="utf-8"))
1571
+ if isinstance(data, dict) and "kind" in data:
1572
+ if seed is not None or realization:
1573
+ raise ValueError("--seed, --realization: the realizations of a configuration")
1574
+ return Microstructure.from_dict(data), None
1575
+ cfg = load_config(path)
1576
+ if realization < 0:
1577
+ raise ValueError("--realization: an index from 0")
1578
+ seed = cfg.seed if seed is None else seed
1579
+ return cfg.model.generate(cfg.domain, derive_seed(seed, realization)), cfg
1580
+
1581
+
1582
+ def cmd_frame_stiffness(args) -> int:
1583
+ """The stiffness of the frame of beams of a realization of a network model (its
1584
+ framework, kept in its metadata): the stiffness, engineering constants, energy split,
1585
+ affine ratio and non-affinity, and Ban et al.'s softening coefficients, against
1586
+ replicas of the stiffness of the beams on request."""
1587
+ from morphogen.homogenization.frames import cowper_coefficient
1588
+ from morphogen.homogenization.networks import (
1589
+ frame_stiffness,
1590
+ network_frame,
1591
+ softening,
1592
+ softening_coefficients,
1593
+ )
1594
+ from morphogen.homogenization.postprocess import notation
1595
+
1596
+ if args.replicas:
1597
+ if not args.softening:
1598
+ raise ValueError("--replicas: of the modes of --softening")
1599
+ if args.replicas < 2:
1600
+ raise ValueError("--replicas: at least 2 (0: the coefficients alone)")
1601
+ if min(args.cv) < 0 or (args.distribution == "bimodal" and max(args.cv) >= 1):
1602
+ raise ValueError("--cv: non-negative (below 1 for the bimodal law)")
1603
+ elif args.table or args.figure:
1604
+ raise ValueError("--table, --figure: of the replicas (--replicas N)")
1605
+ micro, cfg = _realization(Path(args.file), args.seed, args.realization)
1606
+ timoshenko = args.beams == "timoshenko"
1607
+ if args.shear_coefficient is not None and not timoshenko:
1608
+ raise ValueError("--shear-coefficient: of Timoshenko beams (--beams timoshenko)")
1609
+ kappa = None
1610
+ if timoshenko:
1611
+ kappa = "cowper" if args.shear_coefficient is None else args.shear_coefficient
1612
+ frame = network_frame(micro, young=args.young, poisson=args.poisson, shear_coefficient=kappa,
1613
+ rigid_joints=args.rigid_joints) # fmt: skip
1614
+ result = frame_stiffness(frame)
1615
+ dim = result.dimension
1616
+ axis = "xyz".index(args.axis)
1617
+ if axis >= dim:
1618
+ raise ValueError("--axis: x or y for a plane network")
1619
+ out = {
1620
+ "file": str(args.file),
1621
+ "model": micro.model.name if micro.model is not None else micro.kind,
1622
+ "seed": None if cfg is None else (cfg.seed if args.seed is None else args.seed),
1623
+ "realization": None if cfg is None else args.realization,
1624
+ "dimension": dim,
1625
+ "nodes": len(frame.nodes),
1626
+ "beams": len(frame.beams),
1627
+ "radius": float(np.sqrt(frame.area[0] / np.pi)),
1628
+ "theory": args.beams,
1629
+ "shear_coefficient": None,
1630
+ "rigid_joints": args.rigid_joints,
1631
+ "young": args.young,
1632
+ "poisson": args.poisson,
1633
+ "fibre_volume_fraction": result.density,
1634
+ "mean_length": result.mean_length,
1635
+ "stiffness": result.stiffness,
1636
+ "compliance": result.compliance(),
1637
+ "notation": notation(result.stiffness),
1638
+ "affine": result.affine,
1639
+ "engineering": result.engineering(),
1640
+ "axes": result.by_axis(),
1641
+ "summary": result.summary(args.young),
1642
+ }
1643
+ if timoshenko:
1644
+ cowper = kappa == "cowper"
1645
+ out["shear_coefficient"] = float(cowper_coefficient(args.poisson) if cowper else kappa)
1646
+ studies = []
1647
+ if args.softening:
1648
+ out["softening"] = {"axis": args.axis}
1649
+ for mode in dict.fromkeys(args.softening):
1650
+ if args.replicas:
1651
+ options = {"law": args.distribution, "axis": axis, "seed": args.replica_seed}
1652
+ study = softening(frame, mode, args.cv, replicas=args.replicas, **options)
1653
+ studies.append(study)
1654
+ c = study.coefficients
1655
+ else:
1656
+ c = softening_coefficients(frame, mode, axis)
1657
+ out["softening"][mode] = {"young": c["young"], "s": c["mean"], "v": c["variance"]}
1658
+ written = []
1659
+ if studies:
1660
+ rows = [row for study in studies for row in study.rows()]
1661
+ out["replicas"] = {"axis": args.axis, "distribution": args.distribution,
1662
+ "replicas": args.replicas, "seed": args.replica_seed,
1663
+ "cv": list(args.cv), "rows": rows} # fmt: skip
1664
+ if args.table:
1665
+ with open(args.table, "w", encoding="utf-8", newline="") as file:
1666
+ writer = csv.DictWriter(file, list(rows[0]))
1667
+ writer.writeheader()
1668
+ writer.writerows(rows)
1669
+ written.append(f"table of the replicas written to {args.table}")
1670
+ if args.figure:
1671
+ from morphogen.viz.export import save_figure
1672
+ from morphogen.viz.figures import softening_figure
1673
+
1674
+ title = (f"{out['model']}: replicas along {args.axis}, {args.distribution} law, "
1675
+ f"{args.replicas} per CV") # fmt: skip
1676
+ save_figure(softening_figure(studies, title=title), args.figure)
1677
+ written.append(f"figure of the replicas written to {args.figure}")
1678
+ if args.json:
1679
+ print(json.dumps(to_jsonable(out), indent=2))
1680
+ else:
1681
+ _print_frame_stiffness(out)
1682
+ for line in written:
1683
+ print(line)
1684
+ return 0
1685
+
1686
+
1687
+ def _print_frame_stiffness(out: dict) -> None:
1688
+ """The text of ``morphogen frame-stiffness`` (``out``: its JSON output)."""
1689
+ plane = out["dimension"] == 2
1690
+ seed = ""
1691
+ if out["realization"] is not None:
1692
+ seed = f", realization {out['realization']}"
1693
+ seed += "" if out["seed"] is None else f" of seed {out['seed']}"
1694
+ beams = "Timoshenko" if out["theory"] == "timoshenko" else "Euler-Bernoulli"
1695
+ if out["shear_coefficient"] is not None:
1696
+ beams += f" beams (shear coefficient {out['shear_coefficient']:.4g})"
1697
+ else:
1698
+ beams += " beams"
1699
+ joints = ""
1700
+ if out["rigid_joints"] is not None:
1701
+ joints = f", rigid over {out['rigid_joints']:g} radii at the joints"
1702
+ print(
1703
+ f"{out['model']}{seed}: a {'plane ' if plane else ''}frame of {out['beams']} {beams} "
1704
+ f"of radius {out['radius']:.4g} between {out['nodes']} nodes{joints} (fibres "
1705
+ f"E = {out['young']:g}, nu = {out['poisson']:g}); fibre volume "
1706
+ f"{'per unit area' if plane else 'fraction'} {out['fibre_volume_fraction']:.4g}, mean "
1707
+ f"length {out['mean_length']:.4g}"
1708
+ )
1709
+ units = ("of the modulus of the fibres", "its inverse")
1710
+ if plane:
1711
+ units = ("of the modulus of the fibres times a length (per unit area)", "its inverse")
1712
+ _print_elastic(out["stiffness"], out["compliance"], units)
1713
+ constants = ", ".join(f"{k} {v:.5g}" for k, v in out["engineering"].items())
1714
+ print(f"engineering constants: {constants}")
1715
+ rows = out["axes"]
1716
+ parts = [k for k in ("stretching", "bending", "torsion", "shear") if k in rows[0]]
1717
+ print(f"{'uniaxial stress':>15s} {'E':>11s} {'nu':>7s} {'E/E_affine':>10s}"
1718
+ + "".join(f" {k:>10s}" for k in parts) + f" {'non-affinity':>12s}") # fmt: skip
1719
+ for row in rows:
1720
+ print(f"{'along ' + row['axis']:>15s} {row['young']:11.5g} {row['poisson']:7.4f} "
1721
+ f"{row['affinity']:10.4f}" + "".join(f" {row[k]:10.4f}" for k in parts)
1722
+ + f" {row['nonaffinity']:12.4g}") # fmt: skip
1723
+ means = ", ".join(f"{k} {v:.5g}" for k, v in out["summary"].items())
1724
+ print(f"means over the axes, the moduli relative to that of the fibres: {means}")
1725
+ if "softening" in out:
1726
+ print("softening of non-identical beams (Ban et al. 2016) under a uniaxial stress "
1727
+ f"along {out['softening']['axis']}: (E0 - <E>)/E0 = s CV^2, var(E)/E0^2 = v "
1728
+ "CV^2") # fmt: skip
1729
+ print(f"{'mode':>10s} {'s':>9s} {'v':>11s}")
1730
+ for mode, c in out["softening"].items():
1731
+ if mode != "axis":
1732
+ print(f"{mode:>10s} {c['s']:9.4g} {c['v']:11.4g}")
1733
+ if "replicas" in out:
1734
+ r = out["replicas"]
1735
+ print(f"replicas ({r['distribution']} law, {r['replicas']} per CV, seed {r['seed']}): "
1736
+ "the mean of E/E0, plain and corrected by the control variate, against 1 - s "
1737
+ "CV^2; var(E)/E0^2 against v CV^2") # fmt: skip
1738
+ print(f"{'mode':>10s} {'CV':>6s} {'<E>/E0':>9s} {'+-':>8s} {'corrected':>9s} {'+-':>8s} "
1739
+ f"{'1 - s CV^2':>10s} {'var/E0^2':>10s} {'+-':>8s} {'v CV^2':>10s}") # fmt: skip
1740
+ for row in r["rows"]:
1741
+ print(f"{row['mode']:>10s} {row['cv']:6.3g} {row['mean']:9.6f} "
1742
+ f"{row['mean_error']:8.2g} {row['corrected']:9.6f} "
1743
+ f"{row['corrected_error']:8.2g} {row['theory']:10.6f} {row['scatter']:10.4g} "
1744
+ f"{row['scatter_error']:8.2g} {row['theory_scatter']:10.4g}") # fmt: skip
1745
+
1746
+
1747
+ def cmd_fit_rule(args) -> int:
1748
+ """Cellular-automaton rule whose structures match the morphology of an image, on the
1749
+ square grid or on the cells of another tiling (``--tiling``)."""
1750
+ from morphogen.automata.tilings import PLANAR, QUASIPERIODIC
1751
+ from morphogen.design.search import fit_rule
1752
+
1753
+ image = io.load_image(args.image, name=args.array)
1754
+ if image.data.dtype.kind == "f":
1755
+ raise ValueError("fit-rule needs a phase image (not partial volumes)")
1756
+ planar = image.shape[2] == 1
1757
+ if planar and args.tiling not in PLANAR:
1758
+ raise ValueError(f"--tiling {args.tiling}: three-dimensional images only")
1759
+ n = args.lattice or (64 if planar else 24)
1760
+ shape = (n, n, 1) if planar else (n, n, n)
1761
+
1762
+ def progress(generation, genome, cost):
1763
+ log.info("generation %d: cost %.4g", generation, cost)
1764
+
1765
+ fit = fit_rule(
1766
+ image,
1767
+ neighbourhood=args.neighbourhood,
1768
+ dims=2 if planar else 3,
1769
+ lattice=args.tiling,
1770
+ shape=shape,
1771
+ steps=args.steps,
1772
+ initial_fraction=args.initial_fraction,
1773
+ population=args.population,
1774
+ generations=args.generations,
1775
+ rng=np.random.default_rng(args.seed),
1776
+ callback=progress,
1777
+ )
1778
+ names = ["volume_fraction", "interface_density"] + [
1779
+ f"correlation_{h}" for h in range(1, len(fit.target) - 1)
1780
+ ]
1781
+ out = {
1782
+ "rule": fit.rule,
1783
+ "tiling": args.tiling,
1784
+ "initial_fraction": fit.initial_fraction,
1785
+ "cost": fit.cost,
1786
+ "evaluations": fit.evaluations,
1787
+ "target": dict(zip(names, fit.target.tolist(), strict=True)),
1788
+ "fitted": dict(zip(names, fit.descriptors.tolist(), strict=True)),
1789
+ }
1790
+ if args.output:
1791
+ h = float(np.mean(image.spacing[:2] if planar else image.spacing))
1792
+ lengths = [float(v) for v in np.asarray(image.shape) * np.asarray(image.spacing)]
1793
+ config = {
1794
+ "model": {
1795
+ "type": "cellular_automaton",
1796
+ "rule": fit.rule,
1797
+ "neighbourhood": args.neighbourhood,
1798
+ "steps": args.steps,
1799
+ "initial_fraction": round(fit.initial_fraction, 4),
1800
+ "cell_size": h,
1801
+ "dimension": 2 if planar else 3,
1802
+ },
1803
+ "domain": {"size": lengths, "periodic": args.tiling not in QUASIPERIODIC},
1804
+ "seed": 1,
1805
+ "voxels": {"shape": list(image.shape)},
1806
+ "outputs": {"directory": "out/fitted_rule", "name": "automaton", "image": ["vti"]},
1807
+ "analysis": ["volume_fraction", "specific_surface", "connectivity"],
1808
+ }
1809
+ if args.tiling != "square":
1810
+ config["model"]["lattice"] = args.tiling
1811
+ Path(args.output).write_text(
1812
+ f"# Cellular automaton fitted to {Path(args.image).name} (morphogen fit-rule)\n"
1813
+ + yaml.safe_dump(config, sort_keys=False),
1814
+ encoding="utf-8",
1815
+ )
1816
+ out["config"] = str(args.output)
1817
+ if args.json:
1818
+ print(json.dumps(to_jsonable(out), indent=2))
1819
+ else:
1820
+ on = f", {args.tiling} tiling" if args.tiling != "square" else ""
1821
+ print(f"rule: {fit.rule} (initial fraction {fit.initial_fraction:.3f}{on})")
1822
+ print(f"cost: {fit.cost:.4g} after {fit.evaluations} evaluations")
1823
+ print(f"{'descriptor':>18s} {'target':>9s} {'fitted':>9s}")
1824
+ for name in names:
1825
+ print(f"{name:>18s} {out['target'][name]:9.4f} {out['fitted'][name]:9.4f}")
1826
+ if args.output:
1827
+ print(f"configuration written to {args.output}")
1828
+ return 0
1829
+
1830
+
1831
+ def cmd_learn(args) -> int:
1832
+ """A behaviour learned from data (:mod:`morphogen.learning`) of a configuration file:
1833
+ the data, the training, the errors, the file of the model."""
1834
+ from morphogen.learning import learn
1835
+
1836
+ path = Path(args.config)
1837
+ loaded = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
1838
+ cfg = loaded.get("learning", loaded) if isinstance(loaded, dict) else None
1839
+ if not isinstance(cfg, dict):
1840
+ raise ValueError(f"{path}: a mapping of the learning (or a 'learning' mapping)")
1841
+ cfg = dict(cfg)
1842
+ # the files of the command line from the current directory, those of the file from it
1843
+ for key, value in (("output", args.output), ("save_data", args.data)):
1844
+ if value is not None:
1845
+ cfg[key] = str(Path(value).resolve())
1846
+ cfg.setdefault("output", f"{path.stem}.npz")
1847
+ overrides = (("model", "kind", args.model), ("training", "epochs", args.epochs),
1848
+ ("data", "paths", args.paths), ("data", "seed", args.seed),
1849
+ ("model", "seed", args.seed), ("training", "seed", args.seed)) # fmt: skip
1850
+ for section, key, value in overrides:
1851
+ if value is not None:
1852
+ cfg[section] = {**(cfg.get(section) or {}), key: value}
1853
+
1854
+ def progress(epoch, train_loss, validation_loss):
1855
+ if epoch % 10 == 0:
1856
+ log.info("epoch %d: loss %.4g, validation %.4g", epoch, train_loss, validation_loss)
1857
+
1858
+ _, out = learn(cfg, base=path.parent, callback=progress)
1859
+ if args.json:
1860
+ print(json.dumps(to_jsonable(out), indent=2))
1861
+ return 0
1862
+ t, v = out["training"], out["validation"]
1863
+ print(
1864
+ f"{out['model']} model, {out['paths']} paths of {out['points']} points: {t['epochs']} "
1865
+ f"epochs ({t['time_s']:.1f} s), the best {t['best_epoch']}; validation paths: relative "
1866
+ f"error {v['relative']:.4f} (mean {v['mean']:.4f}, max {v['max']:.4f})"
1867
+ )
1868
+ for name, row in out.get("tests", {}).items():
1869
+ failed = f" (failed: {row['failed']})" if "failed" in row else ""
1870
+ print(
1871
+ f"path {name}: stress gap {row['stress']:.4f}, strain gap {row['strain']:.4f}{failed}"
1872
+ )
1873
+ print(f"model: {out['output']}")
1874
+ if "save_data" in out:
1875
+ print(f"data: {out['save_data']}")
1876
+ return 0
1877
+
1878
+
1879
+ def cmd_optimize(args) -> int:
1880
+ """Topology optimization of a periodic cell from a configuration file."""
1881
+ from morphogen.optimization.run import load_optimization_config, run_optimization
1882
+
1883
+ cfg = load_optimization_config(args.config)
1884
+ if args.output is not None:
1885
+ cfg.directory = Path(args.output)
1886
+ if args.seed is not None:
1887
+ cfg.seed = args.seed
1888
+
1889
+ def progress(iteration, density, objective):
1890
+ log.info(
1891
+ "iteration %d: objective %.6g, volume %.4f", iteration, objective, float(density.mean())
1892
+ )
1893
+
1894
+ design, outdir = run_optimization(cfg, callback=progress)
1895
+ props = design.properties()
1896
+ print(f"results written to {outdir}")
1897
+ state = "converged" if design.converged else "not converged"
1898
+ print(
1899
+ f"{design.iterations} iterations ({state}), {design.time_s:.1f} s; volume fraction "
1900
+ f"{design.volume_fraction:.4f} (thresholded design: {design.binary_fraction:.4f})"
1901
+ )
1902
+ refined = design.check.get("properties", {})
1903
+ if refined:
1904
+ print(f"{'':>16s} {'design grid':>12s} {design.check['refinement']} x finer")
1905
+ for key, value in props.items():
1906
+ line = f"{key:>16s}: {value:12.6g}"
1907
+ if key in refined:
1908
+ line += f" {refined[key]:12.6g}"
1909
+ print(line)
1910
+ tensor = design.binary_tensor
1911
+ if np.shape(tensor) == (6, 6) and np.all(np.isfinite(tensor)): # an elastic design
1912
+ print("thresholded design:", end=" ")
1913
+ try:
1914
+ _print_elastic(tensor, units=("of the material", "its inverse"))
1915
+ except np.linalg.LinAlgError:
1916
+ print("a singular stiffness (no compliance)")
1917
+ if design.hinges:
1918
+ print(
1919
+ f"warning: {design.hinges} blocks of voxels touch only along an edge or at a "
1920
+ "corner (hinges): check the constants on the finer grid, or use a larger "
1921
+ "filter radius or a softer projection"
1922
+ )
1923
+ return 0
1924
+
1925
+
1926
+ def cmd_laser(args) -> int:
1927
+ """Laser-architectured sheets: the designs of a configuration file, its optimization,
1928
+ the results."""
1929
+ from morphogen.laser.run import load_laser_config, run_laser
1930
+
1931
+ cfg = load_laser_config(args.config)
1932
+ if args.output is not None:
1933
+ cfg.directory = Path(args.output)
1934
+ if args.seed is not None:
1935
+ cfg.seed = args.seed
1936
+ if args.evaluations is not None and cfg.optimization is not None:
1937
+ cfg.optimization["evaluations"] = args.evaluations
1938
+ if args.no_optimization:
1939
+ cfg.optimization = None
1940
+
1941
+ def progress(row):
1942
+ log.info(
1943
+ "evaluation %d: objective %.6g%s", row["evaluation"], row["objective"],
1944
+ "" if row["feasible"] else " (infeasible)",
1945
+ ) # fmt: skip
1946
+
1947
+ summary, outdir = run_laser(cfg, callback=progress, log=log.info)
1948
+ if args.json:
1949
+ print(json.dumps(to_jsonable(summary), indent=2))
1950
+ return 0
1951
+ print(f"results written to {outdir}")
1952
+ if cfg.case.loading.get("kind", "tension") == "bending":
1953
+ keys = ("bending_load_at_deflection", "bending_load", "bending_stiffness",
1954
+ "bending_energy", "volume_fraction", "path_length") # fmt: skip
1955
+ heads = ("F(d) (N)", "F max (N)", "k (N/mm)", "W (mJ)", "treated", "path (mm)")
1956
+ else:
1957
+ keys = ("yield_strength", "tensile_strength", "uniform_elongation", "energy",
1958
+ "strength_ductility", "volume_fraction", "path_length") # fmt: skip
1959
+ heads = ("Rp (MPa)", "Rm (MPa)", "Ag", "W (MJ/m3)", "Rm Ag", "treated", "path (mm)")
1960
+
1961
+ print(f"{'design':>14s} " + " ".join(f"{h:>10s}" for h in heads))
1962
+ for name, d in summary["designs"].items():
1963
+ m = d["measures"]
1964
+ print(f"{name:>14s} " + " ".join(f"{m[k]:10.4g}" for k in keys))
1965
+ opt = summary.get("optimization")
1966
+ if opt is not None:
1967
+ vals = ", ".join(f"{k} = {v:.4g}" for k, v in opt["values"].items())
1968
+ state = "" if opt["feasible"] else " (no feasible design: the least infeasible)"
1969
+ print(f"optimum ({opt['method']}, {opt['evaluations']} evaluations): {vals}{state}")
1970
+ return 0
1971
+
1972
+
1973
+ def _view_source(path: Path, shape):
1974
+ """Microstructure or image of a file: geometry (.json), configuration (first
1975
+ realization of its model) or voxel image."""
1976
+ from morphogen.models.base import Microstructure
1977
+
1978
+ ext = path.suffix.lower()
1979
+ if ext in (".json", ".yaml", ".yml", ".toml"):
1980
+ data = json.loads(path.read_text(encoding="utf-8")) if ext == ".json" else None
1981
+ if data is not None and "kind" in data:
1982
+ return Microstructure.from_dict(data), None
1983
+ cfg = load_config(path)
1984
+ return cfg.model.generate(cfg.domain, cfg.seed), cfg
1985
+ return io.load_image(path), None
1986
+
1987
+
1988
+ def cmd_view(args) -> int:
1989
+ """Figures of a microstructure, an image or the formation of a structure."""
1990
+ from morphogen.viz import figures
1991
+
1992
+ path = Path(args.file)
1993
+ micro, cfg = _view_source(path, args.shape)
1994
+ stem = path.with_suffix("")
1995
+ if args.animate:
1996
+ if cfg is None or not hasattr(cfg.model, "evolution"):
1997
+ raise ValueError("--animate needs a configuration of an automaton or growth model")
1998
+ frames = cfg.model.evolution(cfg.domain, cfg.seed, args.frames)
1999
+ axis_frames = [np.flipud(np.take(f, f.shape[2] // 2, axis=2).T) for f in frames]
2000
+ kind = "labels" if frames[-1].dtype == np.int32 else "auto"
2001
+ figures.save_gif(axis_frames, args.animate, fps=args.fps, kind=kind)
2002
+ print(f"animation written to {args.animate} ({len(frames)} frames)")
2003
+ return 0
2004
+ if args.surface:
2005
+ fig = figures.surface_figure(micro, shape=args.shape)
2006
+ elif args.tile:
2007
+ fig = figures.tiled_figure(micro, tiles=args.tile, shape=args.shape)
2008
+ elif args.history:
2009
+ history = getattr(micro, "attributes", {}).get("history")
2010
+ if history is None:
2011
+ raise ValueError("this structure has no history (automata record one)")
2012
+ fig = figures.history_figure(history)
2013
+ elif args.kinetics:
2014
+ fig = figures.kinetics_figure(micro)
2015
+ else:
2016
+ title = micro.model.name if getattr(micro, "model", None) is not None else path.name
2017
+ fig = figures.slices_figure(micro, shape=args.shape, labels=args.labels, title=title)
2018
+ out = Path(args.output) if args.output else Path(f"{stem}_view.png")
2019
+ fig.savefig(out)
2020
+ print(f"figure written to {out}")
2021
+ return 0
2022
+
2023
+
2024
+ def _export_source(path: Path, array: str | None):
2025
+ """The object of a file to export and the arrays of a mesh: a microstructure (.json
2026
+ geometry), a table, a tetrahedral mesh (.vtu with its point and cell arrays, .mesh)
2027
+ or a voxel image (the array ``array``, or the first one)."""
2028
+ ext = path.suffix.lower()
2029
+ if ext == ".json":
2030
+ return io.load_microstructure(path), {}
2031
+ if ext in (".csv", ".txt", ".tsv", ".dat", ".xlsx"):
2032
+ return io.read_table(path), {}
2033
+ if ext in (".vtu", ".mesh"):
2034
+ arrays = {}
2035
+ if ext == ".vtu":
2036
+ from morphogen.io.vtk import read_vtu
2037
+
2038
+ data = read_vtu(path)
2039
+ arrays = {**data["point_data"], **data["cell_data"]}
2040
+ return io.read_tet_mesh(path), arrays
2041
+ return io.load_image(path, array), {}
2042
+
2043
+
2044
+ def _export_options(obj, arrays: dict, args, video: bool) -> dict:
2045
+ """The options of :func:`morphogen.export` given on the command line, for the kind of
2046
+ object and of output."""
2047
+ from morphogen.image import VoxelImage
2048
+ from morphogen.mesh.tetra import TetMesh
2049
+ from morphogen.models.base import Microstructure
2050
+
2051
+ def given(**kw) -> dict:
2052
+ return {k: v for k, v in kw.items() if v is not None}
2053
+
2054
+ size = args.size or []
2055
+ pixels = tuple(size) if len(size) == 2 else ((size[0], size[0] * 3 // 4) if size else None)
2056
+ side = max(size) if size else None
2057
+ lo, hi = args.clim or (None, None)
2058
+ clim = tuple(args.clim) if args.clim else None
2059
+
2060
+ def array(name: str):
2061
+ if name not in arrays:
2062
+ raise ValueError(f"no array {name!r} in the mesh (arrays: {', '.join(arrays)})")
2063
+ return arrays[name]
2064
+
2065
+ options = given(fps=args.fps, mode=args.mode, repeat=args.repeat) if video else {}
2066
+ if isinstance(obj, Microstructure):
2067
+ options.update(given(shape=args.shape, voxel_size=args.voxel_size))
2068
+ if isinstance(obj, (VoxelImage, Microstructure)) and video:
2069
+ kind = args.kind or "sections"
2070
+ options["kind"] = kind
2071
+ if kind == "sections":
2072
+ options.update(given(axis=args.axis, size=side, cmap=args.cmap, vmin=lo, vmax=hi))
2073
+ elif kind == "orthoslices":
2074
+ options.update(given(frames=args.frames, size=side, cmap=args.cmap, vmin=lo, vmax=hi))
2075
+ else:
2076
+ options.update(given(phase=args.phase, frames=args.frames, size=pixels))
2077
+ elif isinstance(obj, TetMesh) and (
2078
+ video or Path(args.output).suffix.lower() in (".png", ".tif", ".jpg")
2079
+ ):
2080
+ field = None
2081
+ if args.field:
2082
+ field = "phase" if args.field == "phase" else array(args.field)
2083
+ options.update(given(field=field, size=pixels, cmap=args.cmap, clim=clim))
2084
+ if args.field:
2085
+ options.setdefault("title", args.field)
2086
+ if video:
2087
+ kind = args.kind or ("field" if args.displacement else "turntable")
2088
+ options.update(kind=kind, **given(frames=args.frames))
2089
+ if kind == "sweep":
2090
+ options.update(given(axis=args.axis))
2091
+ elif kind == "field":
2092
+ if not args.displacement:
2093
+ raise ValueError("--kind field: give the displacement (--displacement NAME)")
2094
+ options.update(
2095
+ displacement=array(args.displacement),
2096
+ **given(
2097
+ magnification=args.magnification,
2098
+ wave=args.wave,
2099
+ section=tuple(args.section) if args.section else None,
2100
+ ),
2101
+ )
2102
+ return options
2103
+
2104
+
2105
+ def cmd_export(args) -> int:
2106
+ """Convert a file (image, mesh, geometry, table) to another format, a figure or a
2107
+ video."""
2108
+ from morphogen.io.export import VIDEOS, export
2109
+
2110
+ source = Path(args.input)
2111
+ obj, arrays = _export_source(source, args.array)
2112
+ out = Path(args.output)
2113
+ video = out.suffix.lower() in VIDEOS or args.format == "frames"
2114
+ written = export(obj, out, **_export_options(obj, arrays, args, video))
2115
+ files = written if isinstance(written, list) else [written]
2116
+ print("written to " + ", ".join(str(f) for f in files))
2117
+ return 0
2118
+
2119
+
2120
+ def cmd_zmat(args) -> int:
2121
+ """How morphoGen reads a material file of Z-mat, or what of Z-mat it covers."""
2122
+ from morphogen.homogenization import zmat
2123
+
2124
+ if args.coverage:
2125
+ sys.stdout.write(zmat.coverage_markdown())
2126
+ return 0
2127
+ if not args.file:
2128
+ raise ValueError("zmat: give a material file of Z-mat (or --coverage)")
2129
+ out = zmat.describe(Path(args.file), args.behaviour)
2130
+ if args.output and out["translation"] == "mfront":
2131
+ stem = zmat.mfront_name(Path(args.file).stem)
2132
+ b = zmat.read_zmat(Path(args.file))[args.behaviour]
2133
+ target = Path(args.output) / f"{stem}.mfront"
2134
+ target.parent.mkdir(parents=True, exist_ok=True)
2135
+ target.write_text(zmat.zmat_mfront_source(b, stem), encoding="utf-8")
2136
+ out["written"] = str(target)
2137
+ if args.json:
2138
+ print(json.dumps(to_jsonable(out), indent=2))
2139
+ elif out["translation"] == "native":
2140
+ print("morphoGen's kernels (finite elements, FFT, GPU); the material of a configuration:")
2141
+ for note in out.get("notes", []):
2142
+ print(f" note: {note}")
2143
+ print(yaml.safe_dump(to_jsonable(out["material"]), sort_keys=False).rstrip())
2144
+ else:
2145
+ print(f"an MFront behaviour ({out['reason']}): MFront compiles it, MGIS integrates it;")
2146
+ print(out.get("written") or out["source"])
2147
+ return 0
2148
+
2149
+
2150
+ def cmd_gui(args) -> int:
2151
+ """Graphical interface in the web browser."""
2152
+ from morphogen.gui import serve
2153
+
2154
+ serve(args.port, open_browser=not args.no_browser)
2155
+ return 0
2156
+
2157
+
2158
+ def cmd_desktop(args) -> int:
2159
+ """The graphical interface in a window of its own (the stand-alone application)."""
2160
+ from morphogen.gui.desktop import run
2161
+
2162
+ return run(session_dir=args.session, debug=args.debug, browser=args.browser)
2163
+
2164
+
2165
+ def _radioss_print(out: dict, as_json: bool) -> None:
2166
+ if as_json:
2167
+ print(json.dumps(to_jsonable(out), indent=2))
2168
+ return
2169
+ for key, value in out.items():
2170
+ if isinstance(value, float):
2171
+ value = f"{value:.6g}"
2172
+ print(f"{key:>34s}: {value}")
2173
+
2174
+
2175
+ def _radioss_mesh(args, materials):
2176
+ """The mesh of the source of ``morphogen radioss export``: a geometry (.json) meshed by
2177
+ its voxels or conformingly, or the voxels of an image."""
2178
+ from morphogen.dynamics import explicit_mesh
2179
+
2180
+ path = Path(args.source)
2181
+ if path.suffix.lower() == ".json":
2182
+ micro = io.load_microstructure(path)
2183
+ mesh = explicit_mesh(
2184
+ micro,
2185
+ materials,
2186
+ mesh=args.mesh,
2187
+ resolution=args.voxels or 24,
2188
+ element_size=args.element_size,
2189
+ order=args.order,
2190
+ )
2191
+ names = {int(k): str(v) for k, v in (getattr(micro, "phase_names", None) or {}).items()}
2192
+ return mesh, names, getattr(micro, "kind", None) or path.stem
2193
+ if args.mesh != "voxels":
2194
+ raise ValueError("--mesh conforming: a geometry (.json), not an image")
2195
+ from morphogen.mesh.voxel import voxel_mesh
2196
+
2197
+ image = io.load_image(path, name=args.array)
2198
+ present = {int(q) for q in np.unique(image.data)}
2199
+ missing = sorted(present - set(materials))
2200
+ if missing:
2201
+ raise ValueError(f"phases {missing} of the image: no material (give theirs, or 'void')")
2202
+ solid = sorted(q for q in present if materials[q] is not None)
2203
+ if not solid:
2204
+ raise ValueError("every phase of the image is void")
2205
+ return voxel_mesh(image, solid if len(solid) < len(present) else None), {}, path.stem
2206
+
2207
+
2208
+ def _radioss_loading(args):
2209
+ from morphogen.dynamics import ExplicitLoading
2210
+
2211
+ spec = {
2212
+ "kind": args.loading,
2213
+ "axis": args.axis,
2214
+ "strain": args.strain,
2215
+ "lateral": args.lateral,
2216
+ "contact": not args.no_contact,
2217
+ "friction": args.friction,
2218
+ }
2219
+ if args.rate is not None:
2220
+ spec["strain_rate"] = args.rate
2221
+ if args.velocity is not None:
2222
+ spec["velocity"] = args.velocity
2223
+ if args.duration is not None:
2224
+ spec["duration"] = args.duration
2225
+ if args.shear_axis is not None:
2226
+ spec["shear_axis"] = args.shear_axis
2227
+ return ExplicitLoading.from_config(spec)
2228
+
2229
+
2230
+ def _radioss_summary(directory: Path, args) -> int:
2231
+ from morphogen.dynamics import read_explicit_run, summary, write_frames, write_tables
2232
+
2233
+ result = read_explicit_run(directory)
2234
+ out = summary(result)
2235
+ out["forces from"] = result.source
2236
+ write_tables(result, directory)
2237
+ if args.frames_vtu:
2238
+ out["frames written"] = len(write_frames(result, directory / "frames"))
2239
+ for note in result.warnings:
2240
+ print(f"warning: {note}", file=sys.stderr)
2241
+ _radioss_print(out, args.json)
2242
+ return 0
2243
+
2244
+
2245
+ def cmd_radioss(args) -> int:
2246
+ """OpenRadioss, the explicit solver: its installation, the inputs of a morphology,
2247
+ their runs and their results."""
2248
+ from morphogen import dynamics
2249
+
2250
+ if args.action == "info":
2251
+ try:
2252
+ install = dynamics.find_openradioss(args.path)
2253
+ except FileNotFoundError as exc:
2254
+ if args.json:
2255
+ print(json.dumps({"found": False, "reason": str(exc)}, indent=2))
2256
+ else:
2257
+ print(f"OpenRadioss: not found ({exc})")
2258
+ return 1
2259
+ _radioss_print({"found": True, **install.describe()}, args.json)
2260
+ return 0
2261
+ if args.action == "install":
2262
+
2263
+ def report(fraction, message):
2264
+ print(f"\r{100 * fraction:5.1f} % {message[:70]:<70s}", end="", file=sys.stderr)
2265
+
2266
+ install = dynamics.install_openradioss(args.output, tag=args.tag, progress=report)
2267
+ print(file=sys.stderr)
2268
+ _radioss_print(install.describe(), args.json)
2269
+ return 0
2270
+ if args.action == "export":
2271
+ if not args.materials:
2272
+ raise ValueError("--materials: a YAML/JSON file of the materials of the phases")
2273
+ spec = yaml.safe_load(Path(args.materials).read_text(encoding="utf-8"))
2274
+ spec = spec.get("materials", spec) if isinstance(spec, dict) else spec
2275
+ materials = dynamics.explicit_materials(spec, density=args.density)
2276
+ mesh, names, stem = _radioss_mesh(args, materials)
2277
+ loading = _radioss_loading(args)
2278
+ target = Path(args.output or f"{Path(args.source).stem}_openradioss")
2279
+ inputs = io.write_radioss(
2280
+ target,
2281
+ mesh,
2282
+ {q: m for q, m in materials.items() if m is not None},
2283
+ loading,
2284
+ name=args.name or stem,
2285
+ units=args.units,
2286
+ frames=args.frames,
2287
+ time_step=args.time_step,
2288
+ length_scale=args.length_scale,
2289
+ phase_names=names,
2290
+ title=f"{loading.kind} of {stem}",
2291
+ )
2292
+ m = inputs.manifest
2293
+ out = {
2294
+ "directory": str(inputs.directory),
2295
+ "name": inputs.name,
2296
+ "elements": f"{m['n_elements']} {m['elements']}",
2297
+ "nodes": m["n_nodes"],
2298
+ "end time": m["end_time"],
2299
+ "stable time step (estimate)": m["critical_time_step"],
2300
+ "cycles (estimate)": round(m["cycles"]),
2301
+ }
2302
+ if args.run:
2303
+ dynamics.run_openradioss(
2304
+ target, threads=args.threads, mpi=args.mpi, installation=args.path
2305
+ )
2306
+ return _radioss_summary(Path(target), args)
2307
+ _radioss_print(out, args.json)
2308
+ return 0
2309
+ directory = Path(args.source)
2310
+ if args.action == "run":
2311
+
2312
+ def report(fraction, message):
2313
+ if args.verbose:
2314
+ print(f"\r{100 * fraction:5.1f} % {message[:60]:<60s}", end="", file=sys.stderr)
2315
+
2316
+ run = dynamics.run_openradioss(
2317
+ directory, threads=args.threads, mpi=args.mpi, installation=args.path, progress=report
2318
+ )
2319
+ if args.verbose:
2320
+ print(file=sys.stderr)
2321
+ for note in run.warnings:
2322
+ print(f"warning: {note}", file=sys.stderr)
2323
+ elif args.convert: # read: the outputs converted first when they can be
2324
+ try:
2325
+ install = dynamics.find_openradioss(args.path)
2326
+ except FileNotFoundError as exc:
2327
+ print(f"warning: outputs not converted ({exc})", file=sys.stderr)
2328
+ else:
2329
+ from morphogen.io.radioss import read_manifest
2330
+
2331
+ run = dynamics.RadiossRun(directory, read_manifest(directory)["name"], [], None, {})
2332
+ dynamics.convert_outputs(run, install)
2333
+ return _radioss_summary(directory, args)
2334
+
2335
+
2336
+ def cmd_models(args) -> int:
2337
+ if args.name is None:
2338
+ for name in list_models():
2339
+ doc = (get_model(name).__doc__ or "").strip().splitlines()[0]
2340
+ print(f"{name:20s} {doc}")
2341
+ return 0
2342
+ cls = get_model(args.name)
2343
+ params = cls.parameters()
2344
+ if args.json:
2345
+ print(json.dumps({"name": cls.name, "parameters": params}, indent=2))
2346
+ return 0
2347
+ print(f"{cls.name}: {(cls.__doc__ or '').strip()}")
2348
+ print()
2349
+ print("phases: " + ", ".join(f"{k} = {v}" for k, v in cls.phases.items()))
2350
+ print("parameters:")
2351
+ for p in params:
2352
+ default = "required" if p["required"] else f"default {p['default']!r}"
2353
+ unit = f" [{p['unit']}]" if p["unit"] else ""
2354
+ print(f" {p['name']} ({p['kind']}{unit}, {default}): {p['doc']}")
2355
+ return 0
2356
+
2357
+
2358
+ def cmd_template(args) -> int:
2359
+ templates = _templates()
2360
+ if args.name is None:
2361
+ for name in sorted(templates):
2362
+ print(name)
2363
+ return 0
2364
+ if args.name not in templates:
2365
+ raise ValueError(
2366
+ f"unknown template {args.name!r}; available: {', '.join(sorted(templates))}"
2367
+ )
2368
+ text = templates[args.name]
2369
+ if args.output:
2370
+ Path(args.output).write_text(text, encoding="utf-8")
2371
+ print(f"template written to {args.output}")
2372
+ else:
2373
+ sys.stdout.write(text)
2374
+ return 0
2375
+
2376
+
2377
+ def cmd_info(args) -> int:
2378
+ import numba
2379
+
2380
+ from morphogen.homogenization import mfront
2381
+ from morphogen.mesh.conforming import mmg_executable
2382
+
2383
+ for key, value in pipeline.versions().items():
2384
+ print(f"{key:>10s}: {value}")
2385
+ try:
2386
+ mmg = mmg_executable()
2387
+ except (ImportError, FileNotFoundError) as exc:
2388
+ mmg = f"not found ({exc})"
2389
+ print(f"{'mmg3d':>10s}: {mmg}")
2390
+ from morphogen.dynamics import find_openradioss
2391
+
2392
+ try:
2393
+ radioss = find_openradioss()
2394
+ radioss = f"{radioss.root}" + (f" ({radioss.version})" if radioss.version else "")
2395
+ except FileNotFoundError:
2396
+ radioss = "not found (morphogen radioss install)"
2397
+ print(f"{'openradioss':>10s}: {radioss}")
2398
+ print(f"{'threads':>10s}: {numba.get_num_threads()}")
2399
+ device = gpu.info()
2400
+ if device["gpu"] is None:
2401
+ print(f"{'gpu':>10s}: not available ({device['reason']})")
2402
+ else:
2403
+ print(f"{'gpu':>10s}: {device['gpu']} ({device['memory_gb']} GB, CuPy {device['cupy']})")
2404
+ behaviours = mfront.info()
2405
+ if not behaviours["mgis"]:
2406
+ print(f"{'mfront':>10s}: not available ({behaviours['reason']})")
2407
+ elif behaviours["mfront"] is None:
2408
+ print(f"{'mfront':>10s}: MGIS without the mfront generator (compiled libraries only)")
2409
+ else:
2410
+ print(f"{'mfront':>10s}: TFEL {behaviours['tfel']} and MGIS ({behaviours['mfront']})")
2411
+ print(f"{'models':>10s}: {', '.join(list_models())}")
2412
+ return 0
2413
+
2414
+
2415
+ def build_parser() -> argparse.ArgumentParser:
2416
+ from morphogen.automata.tilings import LATTICES
2417
+ from morphogen.homogenization.networks import LAWS as NETWORK_LAWS
2418
+ from morphogen.homogenization.networks import MODES as NETWORK_MODES
2419
+
2420
+ parser = argparse.ArgumentParser(
2421
+ prog="morphogen",
2422
+ description="Morphological modelling and generation of virtual microstructures.",
2423
+ )
2424
+ parser.add_argument("--version", action="version", version=f"morphogen {__version__}")
2425
+ parser.add_argument("-v", "--verbose", action="store_true", help="print progress")
2426
+ sub = parser.add_subparsers(dest="command", required=True)
2427
+
2428
+ p = sub.add_parser("run", help="generate realizations or run an RVE study from a config file")
2429
+ p.add_argument("config", help="configuration file (.yaml, .json or .toml)")
2430
+ p.add_argument("-o", "--output", help="output directory (overrides outputs.directory)")
2431
+ p.add_argument("--seed", type=int, help="base seed (overrides the configuration)")
2432
+ p.add_argument(
2433
+ "--task-id",
2434
+ default="0",
2435
+ help="index of this task when the run is split (e.g. $SLURM_ARRAY_TASK_ID), or "
2436
+ "'auto': the index of the job array of the scheduler",
2437
+ )
2438
+ p.add_argument("--n-tasks", type=int, default=1, help="number of tasks of a split run")
2439
+ p.add_argument("-j", "--jobs", type=int, default=1, help="processes running the realizations")
2440
+ p.add_argument(
2441
+ "--threads", type=int, help="number of threads (shared by the processes; default all)"
2442
+ )
2443
+ p.add_argument(
2444
+ "--resume", action="store_true", help="skip the realizations already done (records)"
2445
+ )
2446
+ p.add_argument(
2447
+ "--mpi", action="store_true", help="one task per MPI rank (mpirun ...; needs mpi4py)"
2448
+ )
2449
+ p.add_argument("-q", "--quiet", action="store_true", help="do not print the RVE report")
2450
+ p.add_argument("--db", help="add the run to this database of results (outputs.database)")
2451
+ p.set_defaults(func=cmd_run)
2452
+
2453
+ p = sub.add_parser(
2454
+ "amitex", help="runs of AMITEX_FFTP on an image (export), and their results (read)"
2455
+ )
2456
+ p.add_argument("action", choices=("export", "read"), help="write the inputs, or read results")
2457
+ p.add_argument(
2458
+ "target", help="export: an image, or a geometry (.json) with --voxels; read: the "
2459
+ "directory of an export"
2460
+ ) # fmt: skip
2461
+ p.add_argument("--material", nargs="+", help="materials, as for morphogen homogenize")
2462
+ p.add_argument("--materials", help="YAML/JSON file of the materials of the phases")
2463
+ p.add_argument("--voxels", type=int, help="voxels along the longest edge of a geometry")
2464
+ p.add_argument("--array", help="array of the image file")
2465
+ p.add_argument("--loading", nargs="+", help="named macroscopic loadings ('tension: S11=1')")
2466
+ p.add_argument("--path", nargs="+", help="loading paths, as for morphogen homogenize")
2467
+ p.add_argument("--paths", help="YAML/JSON file of loading paths")
2468
+ p.add_argument(
2469
+ "--stiffness",
2470
+ action="store_true",
2471
+ help="also the six unit strains of the stiffness (default without loadings)",
2472
+ )
2473
+ p.add_argument("--fields", action="store_true", help="stress and strain fields of the runs")
2474
+ p.add_argument("--tol", type=float, help="convergence criterion of AMITEX (default 1e-4)")
2475
+ p.add_argument("--processes", type=int, default=4, help="MPI processes of the script")
2476
+ p.add_argument("--library", help="path of libUmatAmitex.so (default: through AMITEX_PATH)")
2477
+ p.add_argument(
2478
+ "--elastic-only",
2479
+ action="store_true",
2480
+ help="export the elasticity of the nonlinear materials (default: their MFront laws)",
2481
+ )
2482
+ p.add_argument("--kinematics", choices=("small", "finite"), default="small",
2483
+ help="finite: paths in finite strains, every phase an MFront law") # fmt: skip
2484
+ p.add_argument("--name", help="name of the files (default: the stem of the sample)")
2485
+ p.add_argument("-o", "--output", help="export: directory; read: CSV table to append to")
2486
+ p.add_argument("--json", action="store_true", help="JSON output")
2487
+ p.set_defaults(func=cmd_amitex)
2488
+
2489
+ p = sub.add_parser(
2490
+ "mfront", help="MFront sources of the materials (von Mises, porous plasticity, "
2491
+ "crystals, learned laws; in finite strains, elasticity too)"
2492
+ ) # fmt: skip
2493
+ p.add_argument("--material", nargs="+", help="materials, as for morphogen homogenize")
2494
+ p.add_argument("--materials", help="YAML/JSON file of the materials of the phases")
2495
+ p.add_argument("--kinematics", choices=("small", "finite"), default="small",
2496
+ help="finite: Hencky elasticity and von Mises plasticity in the "
2497
+ "logarithmic strain space, crystals by morphoGen's kernel") # fmt: skip
2498
+ p.add_argument("--name", help="stem of the behaviours (default: that of --materials)")
2499
+ p.add_argument("-o", "--output", help="directory of the sources (default: here)")
2500
+ p.set_defaults(func=cmd_mfront)
2501
+
2502
+ p = sub.add_parser(
2503
+ "db", help="database of the configurations tested and their results (SQLite)"
2504
+ )
2505
+ p.add_argument(
2506
+ "action",
2507
+ choices=("add", "list", "keys", "export", "remove"),
2508
+ help="add run directories, list the runs, list the keys of the records, export "
2509
+ "the records (CSV), remove runs",
2510
+ )
2511
+ p.add_argument("items", nargs="*", help="run directories (add) or run ids (remove)")
2512
+ p.add_argument("--db", default="morphogen.db", help="database file (default morphogen.db)")
2513
+ p.add_argument("--name", help="name of the runs added (default: outputs.name)")
2514
+ p.add_argument(
2515
+ "--where",
2516
+ nargs="+",
2517
+ help="conditions on the records, e.g. 'model.type == gyroid' 'solid_fraction < 0.3'",
2518
+ )
2519
+ p.add_argument("-o", "--output", help="output file of export (.csv)")
2520
+ p.add_argument("--json", action="store_true", help="JSON output")
2521
+ p.set_defaults(func=cmd_db)
2522
+
2523
+ p = sub.add_parser("ashby", help="Ashby chart of the records of a database")
2524
+ p.add_argument("-o", "--output", default="ashby.png", help="chart file (.png, .svg, .pdf)")
2525
+ p.add_argument("--db", default="morphogen.db", help="database file (default morphogen.db)")
2526
+ p.add_argument("--x", help="key of the x axis (default solid_fraction)")
2527
+ p.add_argument("--y", help="key of the y axis (default: a relative modulus)")
2528
+ p.add_argument("--by", default="model.type", help="key of the families ('none': one)")
2529
+ p.add_argument("--groups", nargs="+", help="families shown first (three in colour)")
2530
+ p.add_argument("--where", nargs="+", help="conditions on the records (see 'db')")
2531
+ p.add_argument("--linear", action="store_true", help="linear axes (default logarithmic)")
2532
+ p.add_argument(
2533
+ "--guides", nargs="*", type=float, help="exponents n of the lines y = x^n (default 1 2)"
2534
+ )
2535
+ p.add_argument("--theme", choices=("light", "dark"), default="light", help="colours")
2536
+ p.add_argument("--title", help="title of the chart")
2537
+ p.add_argument("--table", help="also write the points as a table (.csv)")
2538
+ p.set_defaults(func=cmd_ashby)
2539
+
2540
+ p = sub.add_parser("merge", help="gather the results of the tasks of a split run")
2541
+ p.add_argument("directory", help="output directory of the run")
2542
+ p.add_argument("--no-report", action="store_true", help="do not write the RVE report")
2543
+ p.add_argument("-q", "--quiet", action="store_true", help="do not print the RVE report")
2544
+ p.set_defaults(func=cmd_merge)
2545
+
2546
+ p = sub.add_parser("status", help="realizations done and missing in a run directory")
2547
+ p.add_argument("directory", help="output directory of the run")
2548
+ p.add_argument("--json", action="store_true", help="JSON output")
2549
+ p.set_defaults(func=cmd_status)
2550
+
2551
+ p = sub.add_parser(
2552
+ "submit",
2553
+ help="job array of a configuration on a cluster (SLURM, PBS, Torque, SGE, OAR, LSF)",
2554
+ )
2555
+ p.add_argument("config", help="configuration file (.yaml, .json or .toml)")
2556
+ p.add_argument(
2557
+ "--scheduler",
2558
+ required=True,
2559
+ choices=("slurm", "pbs", "torque", "sge", "oar", "lsf"),
2560
+ help="batch scheduler",
2561
+ )
2562
+ p.add_argument("--tasks", type=int, required=True, help="number of tasks of the array")
2563
+ p.add_argument("-j", "--jobs", type=int, default=1, help="processes per task")
2564
+ p.add_argument("--threads", type=int, default=1, help="threads per process")
2565
+ p.add_argument("--time", default="01:00:00", help="time limit of a task (HH:MM:SS)")
2566
+ p.add_argument("--memory", help="memory of a task (e.g. 8G, scheduler syntax)")
2567
+ p.add_argument("--queue", help="partition or queue")
2568
+ p.add_argument("--account", help="account or project")
2569
+ p.add_argument("--name", help="job name")
2570
+ p.add_argument(
2571
+ "--setup",
2572
+ nargs="+",
2573
+ help="shell lines run before morphoGen (e.g. 'module load python')",
2574
+ )
2575
+ p.add_argument("-o", "--output", help="output directory (overrides outputs.directory)")
2576
+ p.add_argument("--seed", type=int, help="seed of the run (default: the configuration's)")
2577
+ p.add_argument(
2578
+ "--submit", action="store_true", help="submit the jobs (default: write the scripts)"
2579
+ )
2580
+ p.set_defaults(func=cmd_submit)
2581
+
2582
+ p = sub.add_parser("fit", help="RVE scaling-law fit of results tables (morphoGen or external)")
2583
+ p.add_argument("results", nargs="+", help="results CSV files or directories (results*.csv)")
2584
+ p.add_argument("--property", nargs="+", help="columns to analyse (default: all measures)")
2585
+ p.add_argument("--volume-column", default="volume", help="column holding the sample volume")
2586
+ p.add_argument("--eps", nargs="+", type=float, default=[0.01, 0.05], help="relative errors")
2587
+ p.add_argument("--n", nargs="+", type=int, default=[1, 10], help="numbers of realizations")
2588
+ p.add_argument("--gamma", type=float, help="impose the scaling exponent")
2589
+ p.add_argument("--min-volume", type=float, help="smallest volume used in the fit")
2590
+ p.add_argument("--max-volume", type=float, help="largest volume used in the fit")
2591
+ p.add_argument(
2592
+ "--group-by", help="column splitting the rows into series (e.g. a boundary condition)"
2593
+ )
2594
+ p.add_argument(
2595
+ "--bootstrap", type=int, default=1000, help="bootstrap replicates (0: no intervals)"
2596
+ )
2597
+ p.add_argument(
2598
+ "--weights",
2599
+ choices=("none", "n"),
2600
+ default="none",
2601
+ help="weights of the sizes in the fit ('n': (n - 1) / 2)",
2602
+ )
2603
+ p.add_argument("-o", "--output", help="directory for rve_report.json/.md/.tex and figures")
2604
+ p.set_defaults(func=cmd_fit)
2605
+
2606
+ p = sub.add_parser(
2607
+ "homogenize",
2608
+ help="apparent elastic and thermal properties of a sample: finite elements on a "
2609
+ "conforming mesh, or FFT on a voxel image",
2610
+ )
2611
+ p.add_argument(
2612
+ "sample",
2613
+ help="geometry (.json, meshed with --size), tetrahedral mesh (.vtu, .mesh) or phase "
2614
+ "image (.vti, .vtk, .mhd, .npz, .npy, .tif: FFT solver, periodic conditions)",
2615
+ )
2616
+ p.add_argument("--array", help="array name in multi-array image files")
2617
+ p.add_argument("--size", type=float, help="element size of the conforming mesh (.json)")
2618
+ p.add_argument(
2619
+ "--voxels",
2620
+ type=int,
2621
+ help="FFT solver on an image of N voxels per edge of the geometry (.json) instead of "
2622
+ "a conforming mesh",
2623
+ )
2624
+ p.add_argument("--hausdorff", type=float, help="Hausdorff distance of the interface mesh")
2625
+ p.add_argument(
2626
+ "--mesh-method",
2627
+ choices=("auto", "exact", "grid"),
2628
+ default="auto",
2629
+ help="conforming mesh of the exact geometry, without a grid (cells, convex pieces or "
2630
+ "adaptive level set), or of the level set sampled on a background grid; auto "
2631
+ "(default): exact when the model has an exact geometry, the grid otherwise",
2632
+ )
2633
+ p.add_argument(
2634
+ "--min-feature",
2635
+ type=float,
2636
+ help="tessellations: features of the cells smaller than this length are removed "
2637
+ "before meshing (default size / 4; 0 keeps the exact cells)",
2638
+ )
2639
+ p.add_argument(
2640
+ "--cells",
2641
+ choices=("whole", "box"),
2642
+ default="whole",
2643
+ help="periodic tessellations: mesh the whole grains, periodized at the design "
2644
+ "(default), or the grains cut by the faces of the box",
2645
+ )
2646
+ p.add_argument(
2647
+ "--order",
2648
+ type=int,
2649
+ choices=(1, 2),
2650
+ default=2,
2651
+ help="elements of the conforming mesh: 2 (default), 10-node tetrahedra whose edges "
2652
+ "follow the interfaces; 1, 4-node tetrahedra (faster, stiffer)",
2653
+ )
2654
+ p.add_argument(
2655
+ "--mesh-phases",
2656
+ choices=("auto", "all", "solid"),
2657
+ default="auto",
2658
+ help="mesh both phases, or phase 1 only (auto: solid when a phase is a void)",
2659
+ )
2660
+ p.add_argument(
2661
+ "--integration",
2662
+ choices=("full", "bbar", "reduced"),
2663
+ help="of the elements: full (every point), or bbar (also: reduced), the volume "
2664
+ "change of each element as its mean (B-bar, F-bar), for nearly incompressible "
2665
+ "phases and plastic flow; default: full on a mesh, bbar for the loading paths of "
2666
+ "an image",
2667
+ )
2668
+ p.add_argument(
2669
+ "--loading",
2670
+ action="append",
2671
+ metavar="[NAME:] COMPONENTS",
2672
+ help="a macroscopic loading to solve, e.g. 'tension: E11=0.01' (strain E, stress S, "
2673
+ "gradient G, flux Q, change of temperature dT; free components: zero stress or "
2674
+ "flux); repeatable",
2675
+ )
2676
+ p.add_argument(
2677
+ "--path",
2678
+ action="append",
2679
+ metavar="[NAME:] ITEMS",
2680
+ help="a loading path followed in time with the nonlinear behaviours (finite "
2681
+ "elements, periodic or kubc; FFT on images, periodic), e.g. "
2682
+ "'tension: t=0,10 n=20 E11=0,0.02' (times t, "
2683
+ "increments n, strain E and stress S components and change of temperature dT at the "
2684
+ "times; free components: zero stress); repeatable",
2685
+ )
2686
+ p.add_argument("--paths", help="YAML/JSON file mapping names to loading paths")
2687
+ p.add_argument(
2688
+ "--finite",
2689
+ action="store_true",
2690
+ help="follow the loading paths in finite strains (strains E: components of the upper "
2691
+ "triangular gradient F - I, nominal strains and simple shears; stresses S: nominal "
2692
+ "stresses; the curves add the logarithmic strains LE and the Cauchy stresses TS)",
2693
+ )
2694
+ p.add_argument(
2695
+ "--contact",
2696
+ nargs="?",
2697
+ type=float,
2698
+ const=0.0,
2699
+ metavar="MU",
2700
+ help="the walls of the pores that close along the loading paths press on each other "
2701
+ "(and on their images across the faces of a periodic cell), with Coulomb's friction "
2702
+ "MU (default 0): finite elements on the mesh of the solid, in finite strains; the "
2703
+ "curves add the area in contact, the largest pressure, the deepest penetration and "
2704
+ "the energy that friction dissipated",
2705
+ )
2706
+ p.add_argument(
2707
+ "--interfaces",
2708
+ metavar="KEY:VALUE,...",
2709
+ help="the interfaces of the phases of a mesh debond along the loading paths: their "
2710
+ "traction-separation law (normal_strength:N,mode_I:G for the bilinear law, with "
2711
+ "shear_strength, mode_II, eta, stiffness; law:exponential,strength:N,energy:G; "
2712
+ "law:contact for lips without adhesion), Coulomb's friction of the broken "
2713
+ "interfaces (friction:MU), the faces that are interfaces (faces:phases, grains or "
2714
+ "pairs 0-1+0-2), the time of the viscous regularization (viscosity:T) and the "
2715
+ "elastic slip of the friction (slip:D); the "
2716
+ "curves add the debonded area, the mean damage and the largest opening of the "
2717
+ "interfaces and the energy that friction dissipated",
2718
+ )
2719
+ p.add_argument(
2720
+ "--curves", default=".", help="directory for the curves of the loading paths (.csv)"
2721
+ )
2722
+ p.add_argument("--save-mesh", help="write the conforming mesh to this file (.vtu, .inp...)")
2723
+ p.add_argument(
2724
+ "--material",
2725
+ nargs="+",
2726
+ help="PHASE=void or PHASE=young:E,poisson:nu[,conductivity:k] (or bulk:k,shear:mu; "
2727
+ "crystals: cubic:C11/C12/C44, hexagonal:C11/C12/C13/C33/C44; thermal expansion "
2728
+ "expansion:a, density:rho; the other transport coefficients electrical_conductivity:s, "
2729
+ "permittivity:e, permeability:m, diffusivity:d, each one value or k1/k2/k3)",
2730
+ )
2731
+ p.add_argument(
2732
+ "--materials",
2733
+ help="YAML/JSON file mapping phases to materials (with their plasticity or crystal "
2734
+ "plasticity, if any)",
2735
+ )
2736
+ p.add_argument(
2737
+ "--bc",
2738
+ nargs="+",
2739
+ default=["periodic"],
2740
+ help="boundary conditions: kubc, mixed, periodic, subc (aliases utg, mtbc, pbc, uhf)",
2741
+ )
2742
+ p.add_argument(
2743
+ "--property",
2744
+ nargs="+",
2745
+ default=["bulk_modulus", "shear_modulus"],
2746
+ choices=_apparent_properties(),
2747
+ metavar="PROPERTY",
2748
+ help="apparent properties: " + ", ".join(_apparent_properties()),
2749
+ )
2750
+ p.add_argument(
2751
+ "--frequencies",
2752
+ nargs="+",
2753
+ type=float,
2754
+ help="angular frequencies of the harmonic properties (dynamic_stiffness, "
2755
+ "complex_conductivity)",
2756
+ )
2757
+ p.add_argument(
2758
+ "--wavelengths",
2759
+ nargs="+",
2760
+ type=float,
2761
+ help="wavelengths of the effective refractive index (refractive_index)",
2762
+ )
2763
+ p.add_argument(
2764
+ "--fluid-bulk-modulus",
2765
+ type=float,
2766
+ help="bulk modulus of the fluid of the pores: the undrained response of the "
2767
+ "property poroelastic (Gassmann, Skempton)",
2768
+ )
2769
+ p.add_argument(
2770
+ "--solver",
2771
+ choices=("auto", "direct", "amg", "cg", "fenicsx"),
2772
+ default="auto",
2773
+ help="linear solver of the finite element problems (fenicsx: FEniCSx, Linux/WSL)",
2774
+ )
2775
+ p.add_argument("--tol", type=float, default=1e-8, help="relative residual of iterative solvers")
2776
+ p.add_argument("--periodic", action="store_true", help="treat the sample as periodic")
2777
+ p.add_argument("--fields", help="directory for the local fields (.vtu or .vti)")
2778
+ p.add_argument(
2779
+ "--device",
2780
+ choices=("cpu", "gpu", "auto"),
2781
+ default="cpu",
2782
+ help="device of the FFT solver of images: the GPU needs CuPy (morphogen info)",
2783
+ )
2784
+ p.add_argument("-o", "--output", help="write the results to this JSON file")
2785
+ p.add_argument("--json", action="store_true", help="JSON output")
2786
+ p.add_argument("--threads", type=int, help="number of threads")
2787
+ p.set_defaults(func=cmd_homogenize)
2788
+
2789
+ def contact_test(name: str, help_text: str):
2790
+ """The parser of a test of contact, with the arguments of its sample."""
2791
+ p = sub.add_parser(name, help=help_text)
2792
+ p.add_argument(
2793
+ "sample",
2794
+ help="geometry (.json, meshed with --size) or tetrahedral mesh (.vtu, .mesh) of the "
2795
+ "sample; with void phases, its solid alone",
2796
+ )
2797
+ p.add_argument("--size", type=float, help="element size of the conforming mesh (.json)")
2798
+ p.add_argument("--hausdorff", type=float, help="Hausdorff distance of the interface mesh")
2799
+ p.add_argument(
2800
+ "--order", type=int, choices=(1, 2), default=2,
2801
+ help="elements of the conforming mesh: 10-node tetrahedra (2, default) or 4-node "
2802
+ "ones (1)",
2803
+ ) # fmt: skip
2804
+ p.add_argument(
2805
+ "--mesh-phases", choices=("auto", "all", "solid"), default="auto",
2806
+ help="mesh both phases, or phase 1 only (auto: solid when a phase is a void)",
2807
+ ) # fmt: skip
2808
+ p.add_argument("--material", nargs="+", help="materials, as for morphogen homogenize")
2809
+ p.add_argument("--materials", help="YAML/JSON file of the materials of the phases")
2810
+ p.add_argument("--axis", type=int, choices=(0, 1, 2), default=2,
2811
+ help="the axis of the test (default 2: z)") # fmt: skip
2812
+ p.add_argument("--friction", type=float, default=0.0,
2813
+ help="Coulomb's coefficient of friction (default 0)") # fmt: skip
2814
+ p.add_argument("--steps", type=int, default=20, help="steps of the loading (default 20)")
2815
+ p.add_argument("--small", action="store_true",
2816
+ help="small strains (default: finite strains)") # fmt: skip
2817
+ p.add_argument("--curve", help="file of the curve (.csv; default: <sample>_<test>.csv)")
2818
+ p.add_argument("--fields", help="write the deformed sample and the contact pressure "
2819
+ "at the end of the loading to this file (.vtu)") # fmt: skip
2820
+ p.add_argument("-o", "--output", help="write the results to this JSON file")
2821
+ p.add_argument("--json", action="store_true", help="JSON output")
2822
+ p.set_defaults(voxels=None, periodic=False, cells="box", min_feature=None, array=None)
2823
+ return p
2824
+
2825
+ p = contact_test(
2826
+ "compress",
2827
+ "compression of a sample between two rigid platens, its walls free to close on "
2828
+ "themselves (contact and friction): nominal stress against nominal strain",
2829
+ )
2830
+ p.add_argument("--strain", type=float, required=True,
2831
+ help="nominal strain at the end, negative: the approach of the platens over "
2832
+ "the height of the sample (-0.2: compressed by 20 %%)") # fmt: skip
2833
+ p.add_argument("--no-self-contact", action="store_true",
2834
+ help="the surface of the sample does not press on itself (its walls go "
2835
+ "through each other)") # fmt: skip
2836
+ p.add_argument("--points", choices=("gauss", "nodes"), default="gauss",
2837
+ help="the contact points of the faces of the sample: inside them (gauss, the "
2838
+ "default), or at their nodes (nodes: a sample whose corners and edges meet "
2839
+ "the platens, or its own walls, first)") # fmt: skip
2840
+ p.set_defaults(func=cmd_compress)
2841
+
2842
+ p = contact_test(
2843
+ "indent",
2844
+ "indentation of the upper face of a sample by a rigid sphere or cone: force against "
2845
+ "depth, area of the contact, and the modulus that the force reads",
2846
+ )
2847
+ p.add_argument("--depth", type=float, required=True, help="depth of the indentation")
2848
+ p.add_argument("--indenter", choices=("sphere", "cone"), default="sphere")
2849
+ p.add_argument("--radius", type=float, help="radius of the sphere")
2850
+ p.add_argument("--half-angle", type=float, default=70.3,
2851
+ help="half-angle of the cone, degrees from its axis (default 70.3: the cone "
2852
+ "of the area of the pyramids of Berkovich and Vickers)") # fmt: skip
2853
+ p.add_argument("--point", type=float, nargs=2, metavar=("U", "V"),
2854
+ help="where on the face (its two coordinates; default: its middle)") # fmt: skip
2855
+ p.add_argument("--unload", action="store_true",
2856
+ help="then withdraw the indenter in as many steps (the slope of the "
2857
+ "unloading: Oliver and Pharr)") # fmt: skip
2858
+ p.add_argument("--base", choices=("fixed", "smooth"), default="fixed",
2859
+ help="the lower face of the sample: glued (default) or sliding") # fmt: skip
2860
+ p.add_argument("--poisson", type=float,
2861
+ help="Poisson's ratio of the sample, to read the modulus of a sphere with "
2862
+ "the rigid base under the sample (a layer of finite thickness)") # fmt: skip
2863
+ p.set_defaults(func=cmd_indent, steps=10)
2864
+
2865
+ p = sub.add_parser(
2866
+ "bands",
2867
+ help="band structure of the Bloch waves of a periodic cell: elastic waves, the "
2868
+ "scalar waves of sonic and planar photonic crystals, or light in a "
2869
+ "three-dimensional photonic crystal, and their band gaps",
2870
+ )
2871
+ p.add_argument(
2872
+ "sample",
2873
+ help="phase image of the cell (.vti, .vtk, .mhd, .npz, .npy, .tif: cut into "
2874
+ "tetrahedra; its voxels carry the plane waves of the electromagnetic waves) or "
2875
+ "tetrahedral mesh (.vtu, .mesh) with matching opposite faces",
2876
+ )
2877
+ p.add_argument("--array", help="array name in multi-array image files")
2878
+ p.add_argument(
2879
+ "--material",
2880
+ nargs="+",
2881
+ help="materials, as for morphogen homogenize (with density:rho for the elastic, "
2882
+ "acoustic and shear waves; permittivity:e and permeability:m for tm, te and "
2883
+ "electromagnetic)",
2884
+ )
2885
+ p.add_argument("--materials", help="YAML/JSON file of the materials of the phases")
2886
+ p.add_argument(
2887
+ "--waves",
2888
+ choices=("elastic", "acoustic", "shear", "tm", "te", "electromagnetic"),
2889
+ default="elastic",
2890
+ help="elastic waves of the solid; scalar waves: acoustic (the pressure of fluids), "
2891
+ "shear (antiplane), tm and te (light in the plane of a cell invariant along z); "
2892
+ "electromagnetic: light in a three-dimensional cell (plane waves on the voxels "
2893
+ "of an image)",
2894
+ )
2895
+ p.add_argument(
2896
+ "--path",
2897
+ nargs="+",
2898
+ metavar="CORNER",
2899
+ help="corners of the Brillouin zone: G, X, Y, Z, M, R (default: G X M G R; G X M G "
2900
+ "in the plane of an image one voxel thick)",
2901
+ )
2902
+ p.add_argument(
2903
+ "--coarsen",
2904
+ type=int,
2905
+ default=1,
2906
+ metavar="N",
2907
+ help="electromagnetic waves: plane waves on a grid N times coarser than the voxels, "
2908
+ "whose cells cut by the interfaces take an averaged permittivity tensor (voxelize "
2909
+ "2 to 4 times finer than the plane waves)",
2910
+ )
2911
+ p.add_argument("--bands", type=int, default=8, help="number of bands (the lowest)")
2912
+ p.add_argument("--points", type=int, default=8, help="wave vectors per segment of the path")
2913
+ p.add_argument("--order", type=int, choices=(1, 2), default=2, help="1: 4-node, 2: 10-node")
2914
+ p.add_argument("--phases", type=int, nargs="+", help="phases of an image kept in the cell")
2915
+ p.add_argument("-o", "--output", help="CSV file of the bands (a row per wave vector)")
2916
+ p.add_argument("--figure", help="figure of the bands with their gaps (.png, .svg, .pdf)")
2917
+ p.add_argument("--json", action="store_true", help="JSON output")
2918
+ p.set_defaults(func=cmd_bands)
2919
+
2920
+ p = sub.add_parser("analyze", help="morphological measurements on a voxel image")
2921
+ p.add_argument("image", help="image file (.vti, .vtk, .mhd, .npz, .npy, .tif)")
2922
+ p.add_argument("--array", help="array name in multi-array files")
2923
+ p.add_argument(
2924
+ "--measure",
2925
+ nargs="+",
2926
+ default=["volume_fraction", "specific_surface"],
2927
+ choices=sorted(analysis.MEASURES),
2928
+ help="measures to compute",
2929
+ )
2930
+ p.add_argument("--json", action="store_true", help="JSON output")
2931
+ p.set_defaults(func=cmd_analyze)
2932
+
2933
+ p = sub.add_parser(
2934
+ "texture",
2935
+ help="grains and texture of an orientation map (EBSD): pole figures, inverse pole "
2936
+ "figure, disorientations of the boundaries; texture of the lattices of the fields "
2937
+ "of a loading path",
2938
+ )
2939
+ p.add_argument(
2940
+ "map",
2941
+ help="orientation map: an .ang (EDAX/TSL) or a .ctf (Oxford/HKL) file; or the "
2942
+ "fields of a loading path with the orientations of the lattices (.vti, .vtu)",
2943
+ )
2944
+ p.add_argument(
2945
+ "--lattice",
2946
+ default="cubic",
2947
+ choices=("cubic", "hexagonal"),
2948
+ help="lattice of the crystals of the fields of a path (a map gives its own)",
2949
+ )
2950
+ p.add_argument(
2951
+ "--threshold",
2952
+ type=float,
2953
+ default=5.0,
2954
+ help="disorientation (degrees) below which two neighbouring points are in one grain",
2955
+ )
2956
+ p.add_argument(
2957
+ "--min-size",
2958
+ type=int,
2959
+ default=5,
2960
+ help="points: smaller grains are given to their neighbours",
2961
+ )
2962
+ p.add_argument(
2963
+ "--axes",
2964
+ choices=("map", "file"),
2965
+ default="map",
2966
+ help="map: the orientations brought into the axes of the image of the map (x to "
2967
+ "the right, y upwards, z towards the viewer); file: as the file gives them",
2968
+ )
2969
+ p.add_argument(
2970
+ "--setting",
2971
+ type=int,
2972
+ choices=(1, 2, 3, 4),
2973
+ default=1,
2974
+ help="axes of the orientations of an .ang file: their first axis down the image "
2975
+ "(1, the usual setting), up (2), to the right (3) or to the left (4)",
2976
+ )
2977
+ p.add_argument(
2978
+ "--poles",
2979
+ nargs="+",
2980
+ type=_indices,
2981
+ metavar="HKL",
2982
+ help="families of planes of the pole figures: 100 110 111 (cubic), 0001 10-10 "
2983
+ "10-11 (hexagonal) by default",
2984
+ )
2985
+ p.add_argument(
2986
+ "--direction",
2987
+ type=_sample_direction,
2988
+ default=(0.0, 0.0, 1.0),
2989
+ help="direction of the sample of the inverse pole figure and of the colours of "
2990
+ "the map: x, y, z (default) or a,b,c",
2991
+ )
2992
+ p.add_argument(
2993
+ "--halfwidth",
2994
+ type=float,
2995
+ default=10.0,
2996
+ help="half-width (degrees) of the kernel that spreads each pole",
2997
+ )
2998
+ p.add_argument(
2999
+ "-o",
3000
+ "--output",
3001
+ help="folder for the tables (grains.csv, boundaries.csv), the map in the colours "
3002
+ "of its orientations and, with matplotlib, the figures",
3003
+ )
3004
+ p.add_argument(
3005
+ "--format",
3006
+ default="png",
3007
+ choices=("png", "svg", "pdf"),
3008
+ help="format of the figures",
3009
+ )
3010
+ p.add_argument(
3011
+ "--convert",
3012
+ metavar="FILE",
3013
+ help="also write the map as this .ang or .ctf file (the other format, other axes)",
3014
+ )
3015
+ p.add_argument(
3016
+ "--clean",
3017
+ action="store_true",
3018
+ help="with --convert: write the map of the grains (each point with the mean "
3019
+ "orientation of its grain, the points that were not indexed filled)",
3020
+ )
3021
+ p.add_argument("--json", action="store_true", help="JSON output")
3022
+ p.set_defaults(func=cmd_texture)
3023
+
3024
+ p = sub.add_parser(
3025
+ "percolation",
3026
+ help="percolation threshold of the model of a configuration against a parameter",
3027
+ )
3028
+ p.add_argument("config", help="configuration file: its model, domain and voxels sections")
3029
+ p.add_argument(
3030
+ "--parameter",
3031
+ default="volume_fraction",
3032
+ help="parameter of the model varied (default volume_fraction)",
3033
+ )
3034
+ p.add_argument("--lower", type=float, default=0.05, help="lower bound (default 0.05)")
3035
+ p.add_argument("--upper", type=float, default=0.95, help="upper bound (default 0.95)")
3036
+ p.add_argument("--phase", type=int, default=1, help="phase that percolates (default 1)")
3037
+ p.add_argument(
3038
+ "--axis",
3039
+ choices=("x", "y", "z", "any", "all"),
3040
+ default="x",
3041
+ help="joined along this axis, any of them or all three (default x)",
3042
+ )
3043
+ p.add_argument(
3044
+ "--connectivity",
3045
+ type=int,
3046
+ choices=(4, 6, 8, 18, 26),
3047
+ help="neighbours: 6 through faces, 18 and edges, 26 and corners; 4 or 8 in 2-D (one "
3048
+ "voxel along z; default 6, which is 4 there; 26 with --exponent thermal, the voxels "
3049
+ "of the FFT solvers joining through their nodes)",
3050
+ )
3051
+ p.add_argument(
3052
+ "--periodic",
3053
+ action=argparse.BooleanOptionalAction,
3054
+ help="wrapping around the box, or (--no-periodic) joining two faces (default: as "
3055
+ "the domain; periodic with --exponent, as the FFT solvers)",
3056
+ )
3057
+ p.add_argument(
3058
+ "--directions",
3059
+ type=_directions,
3060
+ help="anisotropy: the thresholds across the cores of the box along these directions "
3061
+ "(axes; lattice: the axes and the diagonals, 4 in 2-D and 13 in 3-D; or a number "
3062
+ "sampled over the half circle or sphere), their ratio and threshold tensor",
3063
+ )
3064
+ p.add_argument(
3065
+ "--method",
3066
+ choices=("labels", "fire"),
3067
+ default="labels",
3068
+ help="components labelled, or a forest fire lit on a face reaching the other "
3069
+ "(open along the axis, periodic or not across it; default labels)",
3070
+ )
3071
+ p.add_argument("--realizations", type=int, default=9, help="images at each fraction")
3072
+ p.add_argument("--tol", type=float, default=0.005, help="width of the final bracket")
3073
+ p.add_argument("--seed", type=int, help="seed (default: the configuration's)")
3074
+ p.add_argument(
3075
+ "--sizes",
3076
+ type=_sizes,
3077
+ help="finite-size scaling: the thresholds of cubes of these sizes (voxels per edge, "
3078
+ "separated by commas, at least 3) at the voxel size of the configuration, "
3079
+ "extrapolated to the infinite medium as p_c + a L^(-1/nu)",
3080
+ )
3081
+ p.add_argument(
3082
+ "--nu",
3083
+ type=float,
3084
+ help="exponent of the correlation length (default that of random percolation: "
3085
+ "0.8765 in 3-D, 4/3 in 2-D)",
3086
+ )
3087
+ p.add_argument("--fit-nu", action="store_true", help="fit nu too (at least 4 sizes)")
3088
+ p.add_argument(
3089
+ "--rigidity",
3090
+ action="store_true",
3091
+ help="the threshold of the elastic moduli over the --sizes, where the phase becomes "
3092
+ "rigid (its voxels joined at corners and edges turn about them, so that no "
3093
+ "connectivity gives it): where half the realizations bear a uniaxial strain along the "
3094
+ "axis with a modulus above --cut, the other phases void, by the --solver of the voxels "
3095
+ "(on --device); that of --exponent elastic",
3096
+ )
3097
+ p.add_argument(
3098
+ "--cut",
3099
+ type=float,
3100
+ default=None,
3101
+ help="rigidity: the modulus above which a realization bears, over the Young's modulus "
3102
+ "of the phase (default 1e-8 with --solver fft, 1e-12 with fe, whose energies resolve "
3103
+ "the moduli down to the round-off)",
3104
+ )
3105
+ p.add_argument(
3106
+ "--exponent",
3107
+ choices=("thermal", "elastic"),
3108
+ help="critical exponent of the conductivity (t) or of the elastic moduli (f) of the "
3109
+ "phase, by the --solver of the voxels: the finite-size scaling of their means at the "
3110
+ "threshold over the --sizes, L^(-t/nu)",
3111
+ )
3112
+ p.add_argument(
3113
+ "--threshold",
3114
+ type=float,
3115
+ help="threshold of the exponent (default: extrapolated first over the --sizes, for t "
3116
+ "with the criterion, through 26 neighbours and wrapping around the box by default, "
3117
+ "for f by the moduli as with --rigidity)",
3118
+ )
3119
+ p.add_argument(
3120
+ "--threshold-stderr",
3121
+ type=float,
3122
+ help="standard error of the threshold, whose effect on the exponent is computed "
3123
+ "(default: that of the extrapolation; 0 with --threshold)",
3124
+ )
3125
+ p.add_argument(
3126
+ "--fractions",
3127
+ type=_fractions,
3128
+ help="exponent: a sweep too, over these fractions above the threshold (at least 3, "
3129
+ "separated by commas)",
3130
+ )
3131
+ p.add_argument(
3132
+ "--contrast",
3133
+ type=float,
3134
+ default=1e-8,
3135
+ help="exponent: the properties of the other phases over those of the phase (default "
3136
+ "1e-8; 0: void)",
3137
+ )
3138
+ p.add_argument(
3139
+ "--device",
3140
+ choices=("cpu", "gpu", "auto"),
3141
+ default="auto",
3142
+ help="exponent and rigidity: the device of the FFT solver (default auto: the GPU when "
3143
+ "there is one)",
3144
+ )
3145
+ p.add_argument(
3146
+ "--solver",
3147
+ choices=("fft", "fe"),
3148
+ default="fft",
3149
+ help="exponent and rigidity: the solver of the trilinear voxels, fft (default, on "
3150
+ "--device) or fe, their matrix assembled on the voxels of the materials and solved by "
3151
+ "conjugate gradients preconditioned by its sparse factorization, on the CPU: the same "
3152
+ "moduli in a few iterations where the FFT solver takes thousands, near the rigidity "
3153
+ "threshold with void around (--contrast 0)",
3154
+ )
3155
+ p.add_argument("--json", action="store_true", help="JSON output")
3156
+ p.set_defaults(func=cmd_percolation)
3157
+
3158
+ p = sub.add_parser(
3159
+ "frame-stiffness",
3160
+ help="stiffness of the frame of beams of a fibre network, open foam or random lattice "
3161
+ "(a realization of delaunay_network, open_foam or random_lattice)",
3162
+ )
3163
+ p.add_argument(
3164
+ "file",
3165
+ help="configuration of a network model (a realization of it), or the geometry (.json) "
3166
+ "of a realization",
3167
+ )
3168
+ p.add_argument("--seed", type=int, help="seed (default: the configuration's)")
3169
+ p.add_argument(
3170
+ "--realization",
3171
+ type=int,
3172
+ default=0,
3173
+ help="the realization of the configuration, seeded as in its batch run (default 0)",
3174
+ )
3175
+ p.add_argument(
3176
+ "--beams",
3177
+ choices=BEAM_THEORIES,
3178
+ default="euler-bernoulli",
3179
+ help="Euler-Bernoulli beams (default), or Timoshenko beams (shear stiffness kappa G A)",
3180
+ )
3181
+ p.add_argument(
3182
+ "--shear-coefficient",
3183
+ type=float,
3184
+ help="kappa of Timoshenko beams (default Cowper's, 6(1 + nu)/(7 + 6 nu) for circles)",
3185
+ )
3186
+ p.add_argument(
3187
+ "--rigid-joints",
3188
+ type=float,
3189
+ metavar="C",
3190
+ help="beams rigid over C of their radii from each node (default none; a third "
3191
+ "matches the continuum for Timoshenko beams)",
3192
+ )
3193
+ p.add_argument("--young", type=float, default=1.0, help="Young's modulus of the fibres")
3194
+ p.add_argument("--poisson", type=float, default=0.3, help="Poisson's ratio of the fibres")
3195
+ p.add_argument(
3196
+ "--softening",
3197
+ nargs="+",
3198
+ choices=NETWORK_MODES,
3199
+ help="Ban et al.'s coefficients s and v of the softening of non-identical beams, the "
3200
+ "stiffness of a mode varying from beam to beam: axial (EA), bending (EI), modulus (E) "
3201
+ "or area (EA and kappa G A)",
3202
+ )
3203
+ p.add_argument(
3204
+ "--axis",
3205
+ choices=("x", "y", "z"),
3206
+ default="x",
3207
+ help="axis of the uniaxial stress of the softening coefficients (default x)",
3208
+ )
3209
+ p.add_argument(
3210
+ "--replicas",
3211
+ type=int,
3212
+ default=0,
3213
+ metavar="N",
3214
+ help="N replicas per CV of the stiffness of the beams of each mode of --softening, on "
3215
+ "the same geometry, against s and v (default 0: the coefficients alone; one solve each)",
3216
+ )
3217
+ p.add_argument(
3218
+ "--cv",
3219
+ type=float,
3220
+ nargs="+",
3221
+ default=[0.1, 0.2, 0.3],
3222
+ help="coefficients of variation of the replicas (default 0.1 0.2 0.3)",
3223
+ )
3224
+ p.add_argument(
3225
+ "--distribution",
3226
+ choices=NETWORK_LAWS,
3227
+ default="normal",
3228
+ help="law of the stiffness of the replicas: normal (draws below 1e-3 raised to it, the "
3229
+ "default), lognormal or bimodal (1 - CV or 1 + CV)",
3230
+ )
3231
+ p.add_argument("--replica-seed", type=int, default=1, help="seed of the replicas (default 1)")
3232
+ p.add_argument("--table", help="write the table of the replicas (.csv)")
3233
+ p.add_argument("--figure", help="figure of the replicas (.png, .svg, .pdf)")
3234
+ p.add_argument("--json", action="store_true", help="JSON output")
3235
+ p.set_defaults(func=cmd_frame_stiffness)
3236
+
3237
+ p = sub.add_parser(
3238
+ "fit-rule",
3239
+ help="find a cellular-automaton rule whose structures match the morphology of an "
3240
+ "image (volume fraction, interface density, correlation function)",
3241
+ )
3242
+ p.add_argument("image", help="phase image (phase 1: state 1); one voxel per cell")
3243
+ p.add_argument("--array", help="array name in multi-array image files")
3244
+ p.add_argument(
3245
+ "--neighbourhood",
3246
+ default="moore",
3247
+ choices=("von_neumann", "moore", "edges", "euclidean"),
3248
+ help="neighbourhood of the automaton",
3249
+ )
3250
+ p.add_argument("--steps", type=int, default=15, help="updates from the initial noise")
3251
+ p.add_argument(
3252
+ "--initial-fraction", type=float, help="density of the initial noise (default: searched)"
3253
+ )
3254
+ p.add_argument("--lattice", type=int, help="cells per edge of the trial lattices")
3255
+ p.add_argument(
3256
+ "--tiling",
3257
+ default="square",
3258
+ choices=LATTICES,
3259
+ help="cells of the automaton: square (the grid), triangular, hexagonal, penrose, "
3260
+ "ammann_beenker (prisms in 3-D), bcc, fcc or icosahedral (3-D); quasi-periodic "
3261
+ "tilings run on free patches and their configurations on non-periodic domains",
3262
+ )
3263
+ p.add_argument("--population", type=int, default=24, help="rules per generation")
3264
+ p.add_argument("--generations", type=int, default=15, help="generations of the search")
3265
+ p.add_argument("--seed", type=int, default=0, help="seed of the search")
3266
+ p.add_argument("-o", "--output", help="write a configuration of the fitted automaton")
3267
+ p.add_argument("--json", action="store_true", help="JSON output")
3268
+ p.set_defaults(func=cmd_fit_rule)
3269
+
3270
+ p = sub.add_parser(
3271
+ "optimize",
3272
+ help="topology optimization of a periodic cell (inverse homogenization, FFT solver)",
3273
+ )
3274
+ p.add_argument("config", help="configuration file with an 'optimization' section")
3275
+ p.add_argument("-o", "--output", help="output directory (overrides outputs.directory)")
3276
+ p.add_argument("--seed", type=int, help="seed (random initial designs)")
3277
+ p.add_argument("--threads", type=int, help="number of threads")
3278
+ p.set_defaults(func=cmd_optimize)
3279
+
3280
+ p = sub.add_parser(
3281
+ "laser",
3282
+ help="architectured sheets by localized laser treatment: treatment, tensile test and "
3283
+ "optimization of the laser path",
3284
+ )
3285
+ p.add_argument("config", help="configuration file with a 'laser_sheet' section")
3286
+ p.add_argument("-o", "--output", help="output directory (overrides outputs.directory)")
3287
+ p.add_argument("--seed", type=int, help="seed of the optimization")
3288
+ p.add_argument("--evaluations", type=int, help="evaluations of the optimization")
3289
+ p.add_argument("--no-optimization", action="store_true", help="evaluate the designs only")
3290
+ p.add_argument("--json", action="store_true", help="print the summary as JSON")
3291
+ p.set_defaults(func=cmd_laser)
3292
+
3293
+ p = sub.add_parser(
3294
+ "learn",
3295
+ help="learn a behaviour from data: random paths, a network trained, evaluated, saved",
3296
+ )
3297
+ p.add_argument("config", help="configuration file (a 'learning' section, or its keys)")
3298
+ p.add_argument("-o", "--output", help="file of the model (.npz; overrides output)")
3299
+ p.add_argument("--data", help="also save the data (.npz; overrides save_data)")
3300
+ p.add_argument("--model", choices=["feedforward", "potential", "recurrent", "standard"],
3301
+ help="kind of model (overrides model.kind)") # fmt: skip
3302
+ p.add_argument("--epochs", type=int, help="epochs of the training")
3303
+ p.add_argument("--paths", type=int, help="random paths of the data")
3304
+ p.add_argument("--seed", type=int, help="seed of the paths, of the model and of the training")
3305
+ p.add_argument("--json", action="store_true", help="print the summary as JSON")
3306
+ p.set_defaults(func=cmd_learn)
3307
+
3308
+ p = sub.add_parser(
3309
+ "view",
3310
+ help="figures of a microstructure (sections, tiling, 3D surface, history) or "
3311
+ "animation of its formation",
3312
+ )
3313
+ p.add_argument(
3314
+ "file",
3315
+ help="geometry (.json), configuration (its first realization) or voxel image",
3316
+ )
3317
+ p.add_argument("--shape", type=int, help="voxels per edge to voxelize a geometry")
3318
+ p.add_argument("--labels", action="store_true", help="show the cell (grain) labels")
3319
+ p.add_argument(
3320
+ "--tile",
3321
+ type=int,
3322
+ help="tile the middle sections of a periodic cell (those normal to x, y and z; the "
3323
+ "section of a planar one)",
3324
+ )
3325
+ p.add_argument("--surface", action="store_true", help="3D view of the phase-1 boundary")
3326
+ p.add_argument("--history", action="store_true", help="history of an automaton")
3327
+ p.add_argument("--kinetics", action="store_true", help="transformation kinetics (JMAK)")
3328
+ p.add_argument("--animate", help="write an animated GIF of the formation (configuration)")
3329
+ p.add_argument("--frames", type=int, default=24, help="frames of the animation")
3330
+ p.add_argument("--fps", type=int, default=8, help="frames per second of the animation")
3331
+ p.add_argument("-o", "--output", help="figure file (default: <file>_view.png)")
3332
+ p.set_defaults(func=cmd_view)
3333
+
3334
+ p = sub.add_parser(
3335
+ "export",
3336
+ help="convert an image, a mesh, a geometry or a table to another format, a figure or "
3337
+ "a video (mp4, gif)",
3338
+ description="The output format follows the suffix: data (.vti, .vtu, .msh, .inp, .xdmf, "
3339
+ ".stl...), tables (.csv, .txt, .xlsx), figures (.png, .tif, .svg, .pdf, .tex: TikZ), "
3340
+ "videos (.mp4, .gif; or --format frames and a folder).",
3341
+ )
3342
+ p.add_argument(
3343
+ "input",
3344
+ help="image, mesh (.vtu with its arrays, .mesh), geometry (.json) "
3345
+ "or table (.csv, .txt, .xlsx)",
3346
+ )
3347
+ p.add_argument("output", help="output file (its suffix chooses the format) or folder")
3348
+ p.add_argument("--format", choices=("frames",), help="PNG frames in the output folder")
3349
+ p.add_argument("--array", help="array of a multi-array image")
3350
+ p.add_argument(
3351
+ "--kind",
3352
+ choices=("sections", "orthoslices", "turntable", "sweep", "field"),
3353
+ help="video: sections, orthoslices or turntable (images); turntable, sweep or field "
3354
+ "(meshes)",
3355
+ )
3356
+ p.add_argument("--axis", type=int, choices=(0, 1, 2), help="axis of sections and sweeps")
3357
+ p.add_argument("--phase", type=int, help="phase of the surface of an image (turntable)")
3358
+ p.add_argument("--field", help="array colouring a mesh ('phase': the phases)")
3359
+ p.add_argument("--displacement", help="point array displacing a mesh (kind field)")
3360
+ p.add_argument("--magnification", type=float, help="of the displacement (default: auto)")
3361
+ p.add_argument("--wave", choices=("ramp", "sine"), help="load growing or oscillating")
3362
+ p.add_argument(
3363
+ "--section",
3364
+ nargs=2,
3365
+ type=float,
3366
+ metavar=("AXIS", "FRACTION"),
3367
+ help="cut the mesh by a plane normal to AXIS at FRACTION of the box",
3368
+ )
3369
+ p.add_argument("--frames", type=int, help="number of frames")
3370
+ p.add_argument("--fps", type=float, help="frames per second")
3371
+ p.add_argument("--mode", choices=("once", "loop", "bounce"), help="once, loop, back and forth")
3372
+ p.add_argument("--repeat", type=int, help="loops of the video")
3373
+ p.add_argument("--cmap", help="matplotlib colormap (viridis, inferno, coolwarm...)")
3374
+ p.add_argument("--clim", nargs=2, type=float, metavar=("LOW", "HIGH"), help="colour range")
3375
+ p.add_argument(
3376
+ "--size", nargs="+", type=int, help="pixels: W [H] of 3D views, side of sections"
3377
+ )
3378
+ p.add_argument("--shape", type=int, help="voxels per edge to voxelize a geometry")
3379
+ p.add_argument("--voxel-size", type=float, help="voxel size to voxelize a geometry")
3380
+ p.set_defaults(func=cmd_export)
3381
+
3382
+ p = sub.add_parser(
3383
+ "zmat",
3384
+ help="read a material file of Z-mat (Z-set): its translation to morphoGen, or the "
3385
+ "coverage of Z-mat's library",
3386
+ )
3387
+ p.add_argument("file", nargs="?", help="material file of Z-mat (***behavior gen_evp ...)")
3388
+ p.add_argument("--behaviour", type=int, default=0, help="index of the behaviour in the file")
3389
+ p.add_argument("-o", "--output", help="folder for the MFront source (when one is needed)")
3390
+ p.add_argument("--coverage", action="store_true", help="the coverage of Z-mat (Markdown)")
3391
+ p.add_argument("--json", action="store_true", help="JSON output")
3392
+ p.set_defaults(func=cmd_zmat)
3393
+
3394
+ p = sub.add_parser("gui", help="graphical interface in the web browser (local server)")
3395
+ p.add_argument("--port", type=int, default=8765, help="port of the local server")
3396
+ p.add_argument("--no-browser", action="store_true", help="do not open the browser")
3397
+ p.set_defaults(func=cmd_gui)
3398
+
3399
+ p = sub.add_parser(
3400
+ "desktop",
3401
+ help="the graphical interface as a stand-alone application, in a window of its own "
3402
+ "(pip install 'morphogen[desktop]')",
3403
+ )
3404
+ p.add_argument(
3405
+ "--session", help="folder of the files of the session (default: a temporary one)"
3406
+ )
3407
+ p.add_argument("--debug", action="store_true", help="the developer tools of the page")
3408
+ p.add_argument(
3409
+ "--browser",
3410
+ action="store_true",
3411
+ help="in the web browser rather than a window (as morphogen gui)",
3412
+ )
3413
+ p.set_defaults(func=cmd_desktop)
3414
+
3415
+ p = sub.add_parser(
3416
+ "radioss",
3417
+ help="explicit dynamics with OpenRadioss: its installation, the inputs of a morphology "
3418
+ "(crushing, tension, shear, impact), their runs and their results",
3419
+ )
3420
+ p.add_argument(
3421
+ "action",
3422
+ choices=("info", "install", "export", "run", "read"),
3423
+ help="info: the installation found; install: a release from GitHub; export: the "
3424
+ "inputs of a geometry (.json) or an image; run: run inputs written by export; read: "
3425
+ "the results of a run (made here or elsewhere)",
3426
+ )
3427
+ p.add_argument("source", nargs="?", help="export: geometry or image; run, read: folder")
3428
+ p.add_argument("-o", "--output", help="export: folder of the inputs; install: folder")
3429
+ p.add_argument("--path", help="folder of OpenRadioss (default: found)")
3430
+ p.add_argument("--tag", help="install: the tag of a release (default: the latest)")
3431
+ p.add_argument(
3432
+ "--materials",
3433
+ help="export: YAML/JSON file of the materials of the phases "
3434
+ "(young, poisson, density, plasticity, johnson_cook, failure_strain; 'void')",
3435
+ )
3436
+ p.add_argument("--density", type=float, help="export: density of the materials that give none")
3437
+ p.add_argument(
3438
+ "--units",
3439
+ default="Mg mm s",
3440
+ help="export: units of mass, length and time of "
3441
+ "every value (default 'Mg mm s': MPa, Mg/mm³, mm/s)",
3442
+ )
3443
+ p.add_argument(
3444
+ "--length-scale",
3445
+ type=float,
3446
+ default=1.0,
3447
+ help="export: the length unit of the units per unit of the geometry",
3448
+ )
3449
+ p.add_argument("--mesh", choices=("voxels", "conforming"), default="voxels")
3450
+ p.add_argument("--voxels", type=int, help="export: voxels per edge of a geometry (24)")
3451
+ p.add_argument(
3452
+ "--element-size", type=float, help="export: conforming meshes, the largest element"
3453
+ )
3454
+ p.add_argument("--order", type=int, choices=(1, 2), default=1, help="conforming: tetrahedra")
3455
+ p.add_argument("--array", help="export: the array of an image (default: its first)")
3456
+ p.add_argument(
3457
+ "--loading", choices=("compression", "tension", "shear", "impact"), default="compression"
3458
+ )
3459
+ p.add_argument("--axis", default="z", help="normal to the loaded faces (x, y, z)")
3460
+ p.add_argument("--shear-axis", help="shear: the direction of the drive")
3461
+ p.add_argument("--strain", type=float, default=0.2, help="final nominal strain (0.2)")
3462
+ p.add_argument("--rate", type=float, help="nominal strain rate, in 1/time (default 100)")
3463
+ p.add_argument("--velocity", type=float, help="impact: speed, in length/time")
3464
+ p.add_argument("--duration", type=float, help="duration (default: from the strain)")
3465
+ p.add_argument(
3466
+ "--lateral",
3467
+ choices=("fixed", "free"),
3468
+ default="fixed",
3469
+ help="the loaded faces held across the axis, or free to slide",
3470
+ )
3471
+ p.add_argument("--friction", type=float, default=0.0, help="of the contacts")
3472
+ p.add_argument("--no-contact", action="store_true", help="no self contact")
3473
+ p.add_argument("--frames", type=int, default=50, help="export: animations over the run")
3474
+ p.add_argument("--time-step", type=float, help="export: minimum time step (mass scaling)")
3475
+ p.add_argument("--name", help="export: name of the run")
3476
+ p.add_argument("--run", action="store_true", help="export: run the inputs at once")
3477
+ p.add_argument("--threads", type=int, help="run: OpenMP threads (default: all the cores)")
3478
+ p.add_argument("--mpi", type=int, help="run: MPI processes")
3479
+ p.add_argument(
3480
+ "--no-convert",
3481
+ dest="convert",
3482
+ action="store_false",
3483
+ help="read: do not convert the outputs with OpenRadioss's tools",
3484
+ )
3485
+ p.add_argument(
3486
+ "--frames-vtu",
3487
+ action="store_true",
3488
+ help="run, read: the animations as .vtu files in <folder>/frames",
3489
+ )
3490
+ p.add_argument("--json", action="store_true", help="JSON output")
3491
+ p.set_defaults(func=cmd_radioss)
3492
+
3493
+ p = sub.add_parser("models", help="list the models or describe one")
3494
+ p.add_argument("name", nargs="?")
3495
+ p.add_argument("--json", action="store_true")
3496
+ p.set_defaults(func=cmd_models)
3497
+
3498
+ p = sub.add_parser("template", help="print an example configuration")
3499
+ p.add_argument("name", nargs="?", help="template name (omit to list them)")
3500
+ p.add_argument("-o", "--output", help="write to this file")
3501
+ p.set_defaults(func=cmd_template)
3502
+
3503
+ p = sub.add_parser("info", help="versions and settings")
3504
+ p.set_defaults(func=cmd_info)
3505
+ return parser
3506
+
3507
+
3508
+ def main(argv=None) -> int:
3509
+ parser = build_parser()
3510
+ args = parser.parse_args(argv)
3511
+ logging.basicConfig(
3512
+ level=logging.INFO if args.verbose else logging.WARNING, format="%(message)s"
3513
+ )
3514
+ if getattr(args, "threads", None):
3515
+ settings.set_num_threads(args.threads)
3516
+ full_speed() # Windows: the long runs kept off the efficiency cores (EcoQoS)
3517
+ np.seterr(all="ignore")
3518
+ try:
3519
+ return int(args.func(args) or 0)
3520
+ except (ConfigError, ValueError, FileNotFoundError, RuntimeError, ImportError, KeyError) as exc:
3521
+ print(f"error: {exc}", file=sys.stderr)
3522
+ return 2
3523
+
3524
+
3525
+ if __name__ == "__main__": # pragma: no cover
3526
+ sys.exit(main())