morphogen 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (381) hide show
  1. morphogen/__init__.py +60 -0
  2. morphogen/__main__.py +7 -0
  3. morphogen/_platform.py +55 -0
  4. morphogen/_public.py +153 -0
  5. morphogen/_utils.py +80 -0
  6. morphogen/_version.py +1 -0
  7. morphogen/analysis/__init__.py +174 -0
  8. morphogen/analysis/anisotropy.py +135 -0
  9. morphogen/analysis/basic.py +38 -0
  10. morphogen/analysis/cells.py +54 -0
  11. morphogen/analysis/connectivity.py +156 -0
  12. morphogen/analysis/correlation.py +195 -0
  13. morphogen/analysis/covariance.py +80 -0
  14. morphogen/analysis/fractal.py +54 -0
  15. morphogen/analysis/measures.py +188 -0
  16. morphogen/analysis/morphology.py +265 -0
  17. morphogen/analysis/particles.py +160 -0
  18. morphogen/analysis/percolation.py +2034 -0
  19. morphogen/analysis/power_laws.py +143 -0
  20. morphogen/analysis/random_sets.py +351 -0
  21. morphogen/analysis/stereology.py +289 -0
  22. morphogen/analysis/surface.py +107 -0
  23. morphogen/analysis/topology.py +92 -0
  24. morphogen/automata/__init__.py +74 -0
  25. morphogen/automata/engine.py +211 -0
  26. morphogen/automata/growth.py +686 -0
  27. morphogen/automata/lattice.py +143 -0
  28. morphogen/automata/reaction.py +255 -0
  29. morphogen/automata/rules.py +353 -0
  30. morphogen/automata/tilings.py +1715 -0
  31. morphogen/cli.py +3526 -0
  32. morphogen/config.py +2167 -0
  33. morphogen/contact/__init__.py +113 -0
  34. morphogen/contact/experiments.py +368 -0
  35. morphogen/contact/hertz.py +104 -0
  36. morphogen/contact/kernels.py +827 -0
  37. morphogen/contact/periodic.py +278 -0
  38. morphogen/contact/problem.py +578 -0
  39. morphogen/contact/surfaces.py +310 -0
  40. morphogen/coupling/__init__.py +43 -0
  41. morphogen/coupling/ageing.py +143 -0
  42. morphogen/coupling/diffusion.py +226 -0
  43. morphogen/coupling/fenicsx.py +484 -0
  44. morphogen/coupling/oxidation.py +447 -0
  45. morphogen/coupling/plates.py +247 -0
  46. morphogen/design/__init__.py +51 -0
  47. morphogen/design/csp.py +616 -0
  48. morphogen/design/frames.py +277 -0
  49. morphogen/design/search.py +287 -0
  50. morphogen/design/tiles.py +336 -0
  51. morphogen/distributions.py +312 -0
  52. morphogen/domain.py +203 -0
  53. morphogen/dynamics/__init__.py +179 -0
  54. morphogen/dynamics/model.py +638 -0
  55. morphogen/dynamics/openradioss.py +643 -0
  56. morphogen/dynamics/results.py +515 -0
  57. morphogen/fracture/__init__.py +170 -0
  58. morphogen/fracture/bulk.py +349 -0
  59. morphogen/fracture/cohesive.py +1614 -0
  60. morphogen/fracture/ductile.py +557 -0
  61. morphogen/fracture/lefm.py +1168 -0
  62. morphogen/fracture/mixed.py +1178 -0
  63. morphogen/fracture/periodic.py +733 -0
  64. morphogen/fracture/phasefield.py +714 -0
  65. morphogen/fracture/phasefield_finite.py +368 -0
  66. morphogen/fracture/surface.py +572 -0
  67. morphogen/fracture/toughness.py +566 -0
  68. morphogen/gpu.py +108 -0
  69. morphogen/gui/__init__.py +8 -0
  70. morphogen/gui/api.py +1927 -0
  71. morphogen/gui/desktop.py +387 -0
  72. morphogen/gui/icon.png +0 -0
  73. morphogen/gui/index.html +1909 -0
  74. morphogen/gui/server.py +229 -0
  75. morphogen/gui/tools/__init__.py +629 -0
  76. morphogen/gui/tools/compare.py +149 -0
  77. morphogen/gui/tools/contact.py +391 -0
  78. morphogen/gui/tools/couplings.py +1085 -0
  79. morphogen/gui/tools/crackfront.py +245 -0
  80. morphogen/gui/tools/design.py +224 -0
  81. morphogen/gui/tools/dynamics.py +824 -0
  82. morphogen/gui/tools/fracture.py +2586 -0
  83. morphogen/gui/tools/interop.py +1654 -0
  84. morphogen/gui/tools/learning.py +595 -0
  85. morphogen/gui/tools/mechanics.py +3881 -0
  86. morphogen/gui/tools/nonlocal_damage.py +1321 -0
  87. morphogen/gui/tools/phasefield.py +215 -0
  88. morphogen/gui/tools/physics.py +597 -0
  89. morphogen/gui/tools/stability.py +1756 -0
  90. morphogen/gui/tools/statistics.py +1408 -0
  91. morphogen/gui/viewer.js +1100 -0
  92. morphogen/homogenization/__init__.py +210 -0
  93. morphogen/homogenization/acoustics.py +566 -0
  94. morphogen/homogenization/amg.py +1005 -0
  95. morphogen/homogenization/apparent.py +1046 -0
  96. morphogen/homogenization/behaviours.cu +2285 -0
  97. morphogen/homogenization/behaviours.py +944 -0
  98. morphogen/homogenization/beremin.py +263 -0
  99. morphogen/homogenization/bifurcation.py +1085 -0
  100. morphogen/homogenization/bloch.py +507 -0
  101. morphogen/homogenization/bounds.py +226 -0
  102. morphogen/homogenization/core.py +458 -0
  103. morphogen/homogenization/coupled.py +1135 -0
  104. morphogen/homogenization/crystal.py +2967 -0
  105. morphogen/homogenization/dilatation.py +454 -0
  106. morphogen/homogenization/elements.py +157 -0
  107. morphogen/homogenization/fatigue.py +768 -0
  108. morphogen/homogenization/fe.py +1739 -0
  109. morphogen/homogenization/fenicsx.py +307 -0
  110. morphogen/homogenization/fft.py +499 -0
  111. morphogen/homogenization/fft_nonlinear.py +391 -0
  112. morphogen/homogenization/finite.py +613 -0
  113. morphogen/homogenization/flow.py +361 -0
  114. morphogen/homogenization/frames.py +1125 -0
  115. morphogen/homogenization/gpu.py +1241 -0
  116. morphogen/homogenization/harmonic.py +427 -0
  117. morphogen/homogenization/identification.py +579 -0
  118. morphogen/homogenization/kernels.py +760 -0
  119. morphogen/homogenization/laws.py +2061 -0
  120. morphogen/homogenization/materials.py +1080 -0
  121. morphogen/homogenization/mfront.py +589 -0
  122. morphogen/homogenization/networks.py +880 -0
  123. morphogen/homogenization/nonlinear.py +2612 -0
  124. morphogen/homogenization/ntfa.py +577 -0
  125. morphogen/homogenization/paths.py +476 -0
  126. morphogen/homogenization/photonic.py +467 -0
  127. morphogen/homogenization/poroelastic.py +212 -0
  128. morphogen/homogenization/porous.py +1120 -0
  129. morphogen/homogenization/postprocess.py +290 -0
  130. morphogen/homogenization/solvers.py +1140 -0
  131. morphogen/homogenization/tensors.py +240 -0
  132. morphogen/homogenization/voxel_fe.py +457 -0
  133. morphogen/homogenization/xfem.py +1016 -0
  134. morphogen/homogenization/zmat.py +1258 -0
  135. morphogen/iga/__init__.py +48 -0
  136. morphogen/iga/analysis.py +508 -0
  137. morphogen/iga/basis.py +214 -0
  138. morphogen/iga/geometry.py +501 -0
  139. morphogen/iga/homogenization.py +219 -0
  140. morphogen/iga/optimization.py +700 -0
  141. morphogen/iga/shapes.py +331 -0
  142. morphogen/image.py +128 -0
  143. morphogen/io/__init__.py +246 -0
  144. morphogen/io/amitex.py +741 -0
  145. morphogen/io/ebsd.py +881 -0
  146. morphogen/io/export.py +196 -0
  147. morphogen/io/geometry.py +158 -0
  148. morphogen/io/medit.py +147 -0
  149. morphogen/io/meshes.py +844 -0
  150. morphogen/io/metaimage.py +97 -0
  151. morphogen/io/mfront.py +1104 -0
  152. morphogen/io/native.py +57 -0
  153. morphogen/io/radioss.py +764 -0
  154. morphogen/io/solvers.py +371 -0
  155. morphogen/io/tables.py +278 -0
  156. morphogen/io/tiff.py +66 -0
  157. morphogen/io/vtk.py +701 -0
  158. morphogen/io/xdmf.py +200 -0
  159. morphogen/kernels/__init__.py +5 -0
  160. morphogen/kernels/annealing.py +192 -0
  161. morphogen/kernels/cells.py +69 -0
  162. morphogen/kernels/collective.py +87 -0
  163. morphogen/kernels/force_biased.py +595 -0
  164. morphogen/kernels/implicit.py +145 -0
  165. morphogen/kernels/leaves.py +132 -0
  166. morphogen/kernels/packing.py +304 -0
  167. morphogen/kernels/raster.py +279 -0
  168. morphogen/kernels/rsa.py +371 -0
  169. morphogen/kernels/union.py +135 -0
  170. morphogen/kernels/watershed.py +190 -0
  171. morphogen/laser/__init__.py +234 -0
  172. morphogen/laser/architectures.py +375 -0
  173. morphogen/laser/bending.py +216 -0
  174. morphogen/laser/cells.py +1694 -0
  175. morphogen/laser/design.py +940 -0
  176. morphogen/laser/figures.py +227 -0
  177. morphogen/laser/heat.py +804 -0
  178. morphogen/laser/materials.py +691 -0
  179. morphogen/laser/mechanics.py +1670 -0
  180. morphogen/laser/metallurgy.py +615 -0
  181. morphogen/laser/patterns.py +828 -0
  182. morphogen/laser/periodic.py +392 -0
  183. morphogen/laser/process.py +362 -0
  184. morphogen/laser/run.py +534 -0
  185. morphogen/laser/solid.py +216 -0
  186. morphogen/laser/specimen.py +200 -0
  187. morphogen/laser/structures.py +708 -0
  188. morphogen/learning/__init__.py +81 -0
  189. morphogen/learning/behaviour.py +398 -0
  190. morphogen/learning/data.py +328 -0
  191. morphogen/learning/learned.cpp +668 -0
  192. morphogen/learning/logarithmic.py +202 -0
  193. morphogen/learning/mfront.py +409 -0
  194. morphogen/learning/networks.py +767 -0
  195. morphogen/learning/run.py +212 -0
  196. morphogen/learning/standard.py +814 -0
  197. morphogen/learning/training.py +235 -0
  198. morphogen/mesh/__init__.py +29 -0
  199. morphogen/mesh/conforming.py +1423 -0
  200. morphogen/mesh/curved.py +600 -0
  201. morphogen/mesh/exact.py +1717 -0
  202. morphogen/mesh/octree.py +350 -0
  203. morphogen/mesh/polycrystal.py +1041 -0
  204. morphogen/mesh/polyhedra.py +677 -0
  205. morphogen/mesh/regularize.py +570 -0
  206. morphogen/mesh/surface.py +97 -0
  207. morphogen/mesh/tetra.py +512 -0
  208. morphogen/mesh/voxel.py +124 -0
  209. morphogen/micromorphic/__init__.py +31 -0
  210. morphogen/micromorphic/damage.py +359 -0
  211. morphogen/micromorphic/ductile.py +534 -0
  212. morphogen/micromorphic/finite.py +220 -0
  213. morphogen/micromorphic/microfoam.py +787 -0
  214. morphogen/micromorphic/space.py +341 -0
  215. morphogen/models/__init__.py +195 -0
  216. morphogen/models/affine.py +384 -0
  217. morphogen/models/automata.py +592 -0
  218. morphogen/models/base.py +500 -0
  219. morphogen/models/boolean.py +310 -0
  220. morphogen/models/bouligand.py +331 -0
  221. morphogen/models/branching.py +241 -0
  222. morphogen/models/combination.py +430 -0
  223. morphogen/models/deadleaves.py +766 -0
  224. morphogen/models/design.py +289 -0
  225. morphogen/models/ebsd.py +206 -0
  226. morphogen/models/fibers.py +1476 -0
  227. morphogen/models/foam.py +594 -0
  228. morphogen/models/gaussian.py +314 -0
  229. morphogen/models/growth.py +459 -0
  230. morphogen/models/hardcore.py +317 -0
  231. morphogen/models/hierarchical.py +269 -0
  232. morphogen/models/honeycomb.py +749 -0
  233. morphogen/models/implicit.py +177 -0
  234. morphogen/models/laminate.py +470 -0
  235. morphogen/models/lattice.py +351 -0
  236. morphogen/models/lattice_field.py +345 -0
  237. morphogen/models/levelset_foam.py +563 -0
  238. morphogen/models/nacre.py +411 -0
  239. morphogen/models/nested.py +924 -0
  240. morphogen/models/osteons.py +374 -0
  241. morphogen/models/pieces.py +167 -0
  242. morphogen/models/planar.py +126 -0
  243. morphogen/models/reconstruction.py +203 -0
  244. morphogen/models/scale_rich.py +1409 -0
  245. morphogen/models/scale_rich_3d.py +1616 -0
  246. morphogen/models/tessellation.py +735 -0
  247. morphogen/models/tiling_field.py +302 -0
  248. morphogen/models/tpms.py +197 -0
  249. morphogen/models/transparent.py +406 -0
  250. morphogen/models/union.py +141 -0
  251. morphogen/optimization/__init__.py +43 -0
  252. morphogen/optimization/cell.py +295 -0
  253. morphogen/optimization/filters.py +115 -0
  254. morphogen/optimization/mma.py +226 -0
  255. morphogen/optimization/run.py +219 -0
  256. morphogen/optimization/topology.py +632 -0
  257. morphogen/orientations.py +568 -0
  258. morphogen/parallel.py +599 -0
  259. morphogen/pipeline.py +978 -0
  260. morphogen/primitives.py +188 -0
  261. morphogen/results.py +564 -0
  262. morphogen/rve/__init__.py +73 -0
  263. morphogen/rve/report.py +627 -0
  264. morphogen/rve/scaling.py +363 -0
  265. morphogen/rve/study.py +1054 -0
  266. morphogen/rve/windows.py +345 -0
  267. morphogen/seeding.py +51 -0
  268. morphogen/settings.py +118 -0
  269. morphogen/stopping.py +48 -0
  270. morphogen/symmetry.py +384 -0
  271. morphogen/templates/activator_inhibitor.yaml +22 -0
  272. morphogen/templates/aggregation.yaml +23 -0
  273. morphogen/templates/boolean_cylinders.yaml +20 -0
  274. morphogen/templates/boolean_spheres.yaml +22 -0
  275. morphogen/templates/bouligand.yaml +28 -0
  276. morphogen/templates/cellular_automaton.yaml +25 -0
  277. morphogen/templates/coated_spheres.yaml +26 -0
  278. morphogen/templates/contact_fibers.yaml +27 -0
  279. morphogen/templates/cox_nanocomposite.yaml +22 -0
  280. morphogen/templates/cross_linked_fibers.yaml +26 -0
  281. morphogen/templates/curved_arcs.yaml +28 -0
  282. morphogen/templates/curved_fibers.yaml +24 -0
  283. morphogen/templates/dead_leaves.yaml +22 -0
  284. morphogen/templates/delaunay_network.yaml +22 -0
  285. morphogen/templates/dense_packing.yaml +22 -0
  286. morphogen/templates/diffusion.yaml +33 -0
  287. morphogen/templates/ebsd.yaml +34 -0
  288. morphogen/templates/ebsd_map.ctf +3087 -0
  289. morphogen/templates/fracture_composite.yaml +42 -0
  290. morphogen/templates/fracture_rubber.yaml +47 -0
  291. morphogen/templates/gaussian_excursion.yaml +17 -0
  292. morphogen/templates/graded_lattice.yaml +24 -0
  293. morphogen/templates/hardcore_fibers.yaml +22 -0
  294. morphogen/templates/hardcore_spheres.yaml +22 -0
  295. morphogen/templates/hierarchical_lattice.yaml +22 -0
  296. morphogen/templates/homogenization_acoustic_foam.yaml +36 -0
  297. morphogen/templates/homogenization_beremin.yaml +50 -0
  298. morphogen/templates/homogenization_cleavage.yaml +51 -0
  299. morphogen/templates/homogenization_cleavage_band.yaml +55 -0
  300. morphogen/templates/homogenization_contact.yaml +43 -0
  301. morphogen/templates/homogenization_crack_closure.yaml +49 -0
  302. morphogen/templates/homogenization_crystal_plasticity.yaml +50 -0
  303. morphogen/templates/homogenization_crystal_plasticity_fft.yaml +52 -0
  304. morphogen/templates/homogenization_crystallization.yaml +30 -0
  305. morphogen/templates/homogenization_debonding.yaml +43 -0
  306. morphogen/templates/homogenization_detwinning.yaml +58 -0
  307. morphogen/templates/homogenization_ductile_damage.yaml +47 -0
  308. morphogen/templates/homogenization_fatigue.yaml +40 -0
  309. morphogen/templates/homogenization_grain_fracture.yaml +56 -0
  310. morphogen/templates/homogenization_gyroid.yaml +30 -0
  311. morphogen/templates/homogenization_intergranular.yaml +43 -0
  312. morphogen/templates/homogenization_interphase.yaml +42 -0
  313. morphogen/templates/homogenization_mixed_loading.yaml +33 -0
  314. morphogen/templates/homogenization_ntfa.yaml +56 -0
  315. morphogen/templates/homogenization_piezoelectric.yaml +27 -0
  316. morphogen/templates/homogenization_polycrystal.yaml +30 -0
  317. morphogen/templates/homogenization_polycrystal_inclusions.yaml +30 -0
  318. morphogen/templates/homogenization_poroelastic.yaml +26 -0
  319. morphogen/templates/homogenization_rubber.yaml +40 -0
  320. morphogen/templates/homogenization_slip_cleavage.yaml +50 -0
  321. morphogen/templates/homogenization_spheres.yaml +31 -0
  322. morphogen/templates/homogenization_transport.yaml +29 -0
  323. morphogen/templates/homogenization_twinning.yaml +54 -0
  324. morphogen/templates/homogenization_viscoelastic.yaml +34 -0
  325. morphogen/templates/homogenization_viscoplastic.yaml +42 -0
  326. morphogen/templates/homogenization_voronoi.yaml +26 -0
  327. morphogen/templates/homogenization_xfem.yaml +23 -0
  328. morphogen/templates/hyperuniform_cells.yaml +24 -0
  329. morphogen/templates/laguerre.yaml +18 -0
  330. morphogen/templates/laser_bending.yaml +35 -0
  331. morphogen/templates/laser_cells.yaml +38 -0
  332. morphogen/templates/laser_corrugated.yaml +36 -0
  333. morphogen/templates/level_set_foam.yaml +29 -0
  334. morphogen/templates/menger_sponge.yaml +17 -0
  335. morphogen/templates/nacre.yaml +25 -0
  336. morphogen/templates/nucleation_growth.yaml +25 -0
  337. morphogen/templates/optimize_auxetic.yaml +29 -0
  338. morphogen/templates/optimize_auxetic_3d.yaml +27 -0
  339. morphogen/templates/optimize_bulk.yaml +23 -0
  340. morphogen/templates/optimize_conductivity.yaml +20 -0
  341. morphogen/templates/osteons.yaml +28 -0
  342. morphogen/templates/penetrable_spheres.yaml +21 -0
  343. morphogen/templates/poisson_fibers.yaml +21 -0
  344. morphogen/templates/random_laminate.yaml +26 -0
  345. morphogen/templates/random_lattice.yaml +27 -0
  346. morphogen/templates/random_walk_fibers.yaml +26 -0
  347. morphogen/templates/reaction_diffusion.yaml +22 -0
  348. morphogen/templates/reconstruction.yaml +22 -0
  349. morphogen/templates/rve_cellular_automaton.yaml +23 -0
  350. morphogen/templates/rve_crystal_plasticity_fft.yaml +51 -0
  351. morphogen/templates/rve_multiphysics.yaml +43 -0
  352. morphogen/templates/rve_poisson_fibers.yaml +22 -0
  353. morphogen/templates/rve_poisson_fibers_fe.yaml +33 -0
  354. morphogen/templates/rve_voronoi_windows.yaml +20 -0
  355. morphogen/templates/scale_rich_network.yaml +29 -0
  356. morphogen/templates/scale_rich_plates.yaml +30 -0
  357. morphogen/templates/sequential_dead_leaves.yaml +25 -0
  358. morphogen/templates/strut_lattice.yaml +21 -0
  359. morphogen/templates/tile_assembly.yaml +28 -0
  360. morphogen/templates/tpms.yaml +19 -0
  361. morphogen/templates/trabecular_bone.yaml +29 -0
  362. morphogen/templates/transparent_dead_leaves.yaml +23 -0
  363. morphogen/templates/vascular_tree.yaml +23 -0
  364. morphogen/templates/voronoi.yaml +20 -0
  365. morphogen/templates/wood.yaml +34 -0
  366. morphogen/templates/workflow.yaml +56 -0
  367. morphogen/texture.py +665 -0
  368. morphogen/theory.py +162 -0
  369. morphogen/viz/__init__.py +12 -0
  370. morphogen/viz/export.py +244 -0
  371. morphogen/viz/figures.py +707 -0
  372. morphogen/viz/png.py +148 -0
  373. morphogen/viz/sections.py +696 -0
  374. morphogen/viz/surfaces.py +1352 -0
  375. morphogen/viz/video.py +904 -0
  376. morphogen/viz/workflow.py +488 -0
  377. morphogen-1.0.0.dist-info/METADATA +2316 -0
  378. morphogen-1.0.0.dist-info/RECORD +381 -0
  379. morphogen-1.0.0.dist-info/WHEEL +4 -0
  380. morphogen-1.0.0.dist-info/entry_points.txt +5 -0
  381. morphogen-1.0.0.dist-info/licenses/LICENSE +674 -0
@@ -0,0 +1,1408 @@
1
+ """The tools of the tab Statistics: the size of the representative volume element of a
2
+ morphology (Kanit et al. 2003, Dirrenberger et al. 2014), its morphological measures
3
+ against the theory of its model, and its correlation functions and distributions
4
+ (covariance, lineal path, chords, granulometry, pore sizes, Choquet capacities) with
5
+ the closed forms of its model when it has them."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from pathlib import Path
11
+
12
+ import numpy as np
13
+
14
+ from morphogen.gui.tools import Field, Watcher, tab, tool
15
+
16
+ tab(
17
+ "statistics",
18
+ "Statistics",
19
+ "Statistics of a morphology of the workspace: the size of its representative volume "
20
+ "element (RVE) by the ensemble or the window method, its morphological measures "
21
+ "against the theory of its model, its correlation functions and distributions.",
22
+ order=20,
23
+ )
24
+
25
+ #: The phases of an RVE study of moduli when the form gives none: a contrast of 10
26
+ DEFAULT_MATERIALS = {0: {"young": 1.0, "poisson": 0.3}, 1: {"young": 10.0, "poisson": 0.3}}
27
+ PROPERTIES = (
28
+ ("volume_fraction", "volume fraction"),
29
+ ("bulk_modulus", "apparent bulk modulus"),
30
+ ("shear_modulus", "apparent shear modulus"),
31
+ ("stiffness", "apparent stiffness C_ij and compliance S_ij (six loadings)"),
32
+ )
33
+ #: The properties of the form computed by homogenization
34
+ ELASTIC = ["bulk_modulus", "shear_modulus", "stiffness"]
35
+
36
+
37
+ def _model_of(item: dict, what: str = "an RVE study draws realizations") -> dict:
38
+ if not item.get("model"):
39
+ raise ValueError(
40
+ f"{item['title']} is not the realization of a model: {what} of the model of a "
41
+ "morphology generated in Generate"
42
+ )
43
+ return item["model"]
44
+
45
+
46
+ def _edge(item: dict) -> float:
47
+ return float(np.max(item["micro"].domain.lengths))
48
+
49
+
50
+ def _markdown_tables(text: str) -> list[dict]:
51
+ """The pipe tables of a markdown report, with the heading or bold line before each."""
52
+ out, title, lines = [], "", text.splitlines()
53
+ i = 0
54
+ while i < len(lines):
55
+ line = lines[i].strip()
56
+ if line.startswith("#") or (line.startswith("**") and line.endswith("**")):
57
+ title = line.strip("#* ").strip()
58
+ rule = i + 1 < len(lines) and re.match(r"^\|[\s:|-]+\|$", lines[i + 1].strip())
59
+ if line.startswith("|") and rule:
60
+ columns = [c.strip() for c in line.strip("|").split("|")]
61
+ rows = []
62
+ i += 2
63
+ while i < len(lines) and lines[i].strip().startswith("|"):
64
+ rows.append([c.strip() for c in lines[i].strip().strip("|").split("|")])
65
+ i += 1
66
+ out.append({"title": title, "columns": columns, "rows": rows, "count": len(rows)})
67
+ continue
68
+ i += 1
69
+ return out
70
+
71
+
72
+ @tool(
73
+ "rve",
74
+ "statistics",
75
+ "RVE size",
76
+ "The size of the representative volume element of the model of a morphology for a "
77
+ "property: by the ensemble method (independent realizations of several sizes) or by "
78
+ "the window method (sub-volumes of one large realization), the variance D²(V) of the "
79
+ "property fitted as K V^-γ (γ = 1: the integral range A₃ = K / D²_Z), and the volumes "
80
+ "for the relative errors and numbers of realizations chosen (Kanit et al. 2003; "
81
+ "Dirrenberger, Forest & Jeulin 2014). For the stiffness, the mean C̄ of each size, its "
82
+ "compliance S = C̄⁻¹, the standard deviation of each component and the RVE size of "
83
+ "each; by the window method (FFT), the tensor of a window is its mean mutual energy "
84
+ "⟨ε⁽ᵏ⁾ : C : ε⁽ˡ⁾⟩ under the six unit strains of the realization.",
85
+ [
86
+ Field(
87
+ "source",
88
+ "item",
89
+ label="morphology",
90
+ required=True,
91
+ needs=("model",),
92
+ doc="a morphology generated from a model (its model, seed and periodicity)",
93
+ ),
94
+ Field(
95
+ "method",
96
+ "choice",
97
+ "ensemble",
98
+ choices=(
99
+ ("ensemble", "ensemble: independent realizations of each size"),
100
+ ("windows", "windows: sub-volumes of one large realization"),
101
+ ),
102
+ ),
103
+ Field(
104
+ "sizes",
105
+ "floats",
106
+ label="sizes",
107
+ unit="length",
108
+ when={"method": "ensemble"},
109
+ doc="edges of the cubes (blank: 0.5, 1 and 1.5 times the edge of the morphology)",
110
+ ),
111
+ Field(
112
+ "realizations",
113
+ "ints",
114
+ [20, 10, 5],
115
+ when={"method": "ensemble"},
116
+ doc="realizations of each size (one number: the same for all)",
117
+ ),
118
+ Field(
119
+ "size",
120
+ "float",
121
+ label="size of the realization",
122
+ unit="length",
123
+ when={"method": "windows"},
124
+ doc="blank: twice the edge of the morphology",
125
+ ),
126
+ Field(
127
+ "window_sizes",
128
+ "floats",
129
+ when={"method": "windows"},
130
+ unit="length",
131
+ doc="edges of the windows (blank: 1/8, 1/4 and 1/2 of the realization)",
132
+ ),
133
+ Field(
134
+ "shifts",
135
+ "int",
136
+ 1,
137
+ label="shifts per axis",
138
+ when={"method": "windows"},
139
+ doc="1: the windows tiling the realization from its origin; more: also the "
140
+ "tilings shifted by k w / shifts along each axis, wrapping around a periodic "
141
+ "realization (shifts³ tilings; the stiffness from the same solutions)",
142
+ ),
143
+ Field("property", "choice", "volume_fraction", choices=PROPERTIES),
144
+ Field(
145
+ "solver",
146
+ "choice",
147
+ "fft",
148
+ choices=(("fft", "FFT (voxels)"), ("fe", "finite elements (conforming meshes)")),
149
+ when={"property": ELASTIC},
150
+ ),
151
+ Field("materials", "materials", of="source", when={"property": ELASTIC}),
152
+ Field(
153
+ "voxel_size",
154
+ "float",
155
+ unit="length",
156
+ doc="the same for every size (blank: 1/48 of the edge of the morphology)",
157
+ ),
158
+ Field("relative_errors", "floats", [0.01, 0.05]),
159
+ Field("n_realizations", "ints", [1, 10], label="numbers of realizations"),
160
+ ],
161
+ order=5,
162
+ menu="Representative volume",
163
+ )
164
+ def rve_size(p: dict, ctx) -> dict:
165
+ from morphogen import pipeline
166
+ from morphogen.config import load_config
167
+ from morphogen.rve.scaling import _shift_count
168
+
169
+ item = p["source"]
170
+ model = _model_of(item)
171
+ edge = _edge(item)
172
+ periodic = bool(item["micro"].domain.periodic) # that of the realizations
173
+ voxel = p["voxel_size"] or edge / 48
174
+ spec: dict = {
175
+ "relative_errors": p["relative_errors"],
176
+ "n_realizations": p["n_realizations"],
177
+ }
178
+ if p["method"] == "ensemble":
179
+ sizes = p["sizes"] or [0.5 * edge, edge, 1.5 * edge]
180
+ reps = p["realizations"] or [10]
181
+ reps = reps * len(sizes) if len(reps) == 1 else reps
182
+ if len(reps) != len(sizes):
183
+ raise ValueError("realizations: one number, or one per size")
184
+ spec.update(method="ensemble", sizes=sizes, realizations=reps)
185
+ total = int(sum(reps))
186
+ else:
187
+ size = p["size"] or 2 * edge
188
+ windows = p["window_sizes"] or [size / 8, size / 4, size / 2]
189
+ spec.update(method="windows", size=size, window_sizes=windows)
190
+ # the refusals of the API: a positive count, the shifts on a periodic realization
191
+ shifts = _shift_count(p["shifts"], periodic)
192
+ if shifts > 1: # 1, the tiling from the origin: the configuration of before
193
+ spec["shifts"] = shifts
194
+ total = 1
195
+ cfg: dict = {
196
+ "model": model,
197
+ "domain": {"periodic": periodic},
198
+ "seed": item.get("seed") or 1,
199
+ "voxels": {"voxel_size": voxel},
200
+ "rve": spec,
201
+ "outputs": {"directory": str(ctx.folder), "name": "rve", "tables": ["xlsx"]},
202
+ }
203
+ prop = p["property"]
204
+ if prop != "volume_fraction":
205
+ windows = p["method"] == "windows"
206
+ if windows and (prop != "stiffness" or p["solver"] != "fft"):
207
+ raise ValueError(
208
+ "the window method studies the volume fraction (voxels) and the stiffness of "
209
+ "its windows (FFT solver)"
210
+ )
211
+ materials = p["materials"] or DEFAULT_MATERIALS
212
+ bc = "periodic" if periodic or windows else "kubc"
213
+ cfg["homogenization"] = {"materials": materials, "method": p["solver"],
214
+ "boundary_conditions": [bc], "properties": [prop]} # fmt: skip
215
+ if p["solver"] == "fe":
216
+ cfg["mesh"] = {"size": 2 * voxel}
217
+ config = load_config(cfg)
218
+ with Watcher(ctx, ctx.folder / "records", "*.json", total, "realizations"):
219
+ pipeline.run(config)
220
+ if prop == "stiffness":
221
+ _mean_tensors(ctx)
222
+ report = (ctx.folder / "rve_report.md").read_text(encoding="utf-8")
223
+ tables = _markdown_tables(report)
224
+ for png in sorted(ctx.folder.glob("*.png")):
225
+ ctx.figures.append({"title": png.stem.replace("_", " "), "url": ctx.url(png.name)})
226
+ return {"tables": tables, "text": report if not tables else ""}
227
+
228
+
229
+ def _mean_tensors(ctx) -> None:
230
+ """The tables of the mean stiffness ``Cbar`` of the largest volume of the study and
231
+ of its compliance ``S = Cbar^-1`` (each boundary condition); the report gives them at
232
+ every volume, with the standard deviation of each component (by the window method, of
233
+ the largest windows; with shifts, C the mean of the windows of all their tilings)."""
234
+ import json
235
+
236
+ from morphogen.gui.tools import elastic_tables
237
+ from morphogen.rve.report import BC_LABELS
238
+
239
+ report = json.loads((ctx.folder / "rve_report.json").read_text(encoding="utf-8"))
240
+ samples = "windows" if report.get("method") == "windows" else "realizations"
241
+ for t in report.get("tensors", {}).values():
242
+ if t["property"] != "stiffness":
243
+ continue
244
+ last = t["volumes"][-1]
245
+ power = "²" if t.get("dimension", 3) == 2 else "³" # a square (its area), a cube
246
+ tilings = last.get("tilings") or 1 # n the windows of each tiling
247
+ count = f"{last['n']} {samples}" + (f" x {tilings} tilings" if tilings > 1 else "")
248
+ of = (f"at {last['edge']:.4g}{power}, C the mean of {count} "
249
+ f"({BC_LABELS.get(t['bc'], t['bc'])})") # fmt: skip
250
+ elastic_tables(ctx, last["stiffness"], of, names=(f"stiffness_{t['bc']}",
251
+ f"compliance_{t['bc']}"), compliance=last["compliance"]) # fmt: skip
252
+
253
+
254
+ #: The measures offered (those of :data:`morphogen.analysis.measures.MEASURES`)
255
+ def _measure_choices():
256
+ from morphogen.analysis.measures import MEASURES
257
+
258
+ return tuple(MEASURES)
259
+
260
+
261
+ @tool(
262
+ "measures",
263
+ "statistics",
264
+ "Morphological measures",
265
+ "Measures of a morphology on a voxel image of it: phase fractions, specific surface "
266
+ "(Crofton), connectivity, Minkowski functionals and Betti numbers, chords, "
267
+ "thicknesses, tortuosity, fractal dimension, anisotropy (mean intercept lengths), "
268
+ "minima of the covariance; with the closed forms of its model when known.",
269
+ [
270
+ Field("source", "item", label="morphology", required=True),
271
+ Field("resolution", "int", 128, label="voxels per edge", doc="of the image measured"),
272
+ Field(
273
+ "measures",
274
+ "choices",
275
+ ["phase_fractions", "specific_surface", "connectivity"],
276
+ choices=_measure_choices(),
277
+ ),
278
+ ],
279
+ order=1,
280
+ menu="Morphology",
281
+ )
282
+ def measures(p: dict, ctx) -> dict:
283
+ from morphogen.analysis import measure
284
+ from morphogen.gui.api import _voxels
285
+
286
+ micro = p["source"]["micro"]
287
+ _voxels(micro.domain, p["resolution"], 6.0, "image")
288
+ ctx.progress(0.1, "voxel image")
289
+ image = micro.voxelize(shape=p["resolution"])
290
+ labels = micro.labels(grid=image.grid()) if getattr(micro, "has_labels", False) else None
291
+ values = {}
292
+ names = p["measures"] or []
293
+ for k, name in enumerate(names):
294
+ ctx.progress(0.1 + 0.9 * k / max(len(names), 1), name)
295
+ values.update(measure(image, [name], labels=labels))
296
+ out = {"values": values}
297
+ model = micro.model
298
+ if model is not None:
299
+ theory = {k: v for k, v in model.theory(micro.domain).items() if isinstance(v, float)}
300
+ if theory:
301
+ ctx.table([{"quantity": k, "theory": v, "measured": values.get(k)}
302
+ for k, v in theory.items()], "theory", "theory of the model") # fmt: skip
303
+ return out
304
+
305
+
306
+ CURVES = (
307
+ ("covariance", "covariance C(h)"),
308
+ ("lineal_path", "lineal path L(h)"),
309
+ ("chords", "chord length distributions"),
310
+ ("granulometry", "granulometry (openings by balls)"),
311
+ ("pore_sizes", "pore-size function"),
312
+ ("capacity_ball", "Choquet capacity of balls T(B_r)"),
313
+ ("capacity_segment", "Choquet capacity of segments T(l)"),
314
+ )
315
+
316
+
317
+ def _axes_figure(curve, title: str, ylabel: str, theory=None):
318
+ """The curve along the axes, with the closed form of the model: one curve ``(x, y)``,
319
+ or one per axis ``{axis: (x, y)}`` dashed in the colour of that axis."""
320
+ from matplotlib.figure import Figure
321
+
322
+ fig = Figure(figsize=(5.4, 3.8), layout="constrained")
323
+ ax = fig.subplots()
324
+ colours = {}
325
+ for axis in "xyz":
326
+ if axis in curve.lags and len(curve.lags[axis]) > 1:
327
+ (line,) = ax.plot(curve.lags[axis], curve.values[axis], label=axis, lw=1.6)
328
+ colours[axis] = line.get_color()
329
+ if isinstance(theory, dict):
330
+ for axis, xy in theory.items():
331
+ ax.plot(*xy, "--", color=colours.get(axis, "k"), lw=1.2, label=f"theory {axis}")
332
+ elif theory is not None:
333
+ ax.plot(*theory, "k--", lw=1.2, label="theory")
334
+ ax.set_xlabel("h")
335
+ ax.set_ylabel(ylabel)
336
+ ax.set_title(title, fontsize=10)
337
+ ax.grid(alpha=0.3)
338
+ ax.legend(fontsize=8, frameon=False)
339
+ return fig
340
+
341
+
342
+ def _plot(x, ys: dict, title: str, xlabel: str, ylabel: str, *, theory=None, log=False):
343
+ from matplotlib.figure import Figure
344
+
345
+ fig = Figure(figsize=(5.4, 3.8), layout="constrained")
346
+ ax = fig.subplots()
347
+ for label, y in ys.items():
348
+ ax.plot(x if not isinstance(y, tuple) else y[0], y if not isinstance(y, tuple) else y[1],
349
+ lw=1.6, label=label) # fmt: skip
350
+ if theory is not None:
351
+ ax.plot(*theory, "k--", lw=1.2, label="theory")
352
+ if log:
353
+ ax.set_yscale("log")
354
+ ax.set_xlabel(xlabel)
355
+ ax.set_ylabel(ylabel)
356
+ ax.set_title(title, fontsize=10)
357
+ ax.grid(alpha=0.3)
358
+ if len(ys) > 1 or theory is not None:
359
+ ax.legend(fontsize=8, frameon=False)
360
+ return fig
361
+
362
+
363
+ @tool(
364
+ "curves",
365
+ "statistics",
366
+ "Correlation functions and distributions",
367
+ "Functions of a morphology on a voxel image of it, along the three axes: covariance, "
368
+ "lineal path, chord length distributions, granulometry by openings, pore-size "
369
+ "function, Choquet capacities of balls and segments; the closed forms of its model "
370
+ "(Boolean and Poisson models, Gaussian excursions) drawn with them.",
371
+ [
372
+ Field("source", "item", label="morphology", required=True),
373
+ Field("resolution", "int", 96, label="voxels per edge"),
374
+ Field("phase", "int", 1),
375
+ Field("curves", "choices", ["covariance", "lineal_path", "chords"], choices=CURVES),
376
+ ],
377
+ order=2,
378
+ menu="Morphology",
379
+ )
380
+ def curves(p: dict, ctx) -> dict:
381
+ from morphogen.analysis.correlation import lineal_path, pore_size_function
382
+ from morphogen.analysis.covariance import covariance
383
+ from morphogen.analysis.morphology import chord_lengths, granulometry
384
+ from morphogen.analysis.random_sets import choquet_capacity
385
+ from morphogen.gui.api import _voxels
386
+
387
+ micro = p["source"]["micro"]
388
+ _voxels(micro.domain, p["resolution"], 12.0, "image")
389
+ image = micro.voxelize(shape=p["resolution"])
390
+ model, phase = micro.model, p["phase"]
391
+ chosen = p["curves"] or []
392
+ for k, name in enumerate(chosen):
393
+ ctx.progress(k / max(len(chosen), 1), name)
394
+ if name == "covariance":
395
+ c = covariance(image, phase)
396
+ h = c.lags["x"]
397
+ theory = _axis_covariances(model, c) if phase == 1 else None
398
+ ctx.figure(_axes_figure(c, "covariance", "C(h)", theory), "covariance")
399
+ rows = []
400
+ for i, lag in enumerate(h):
401
+ row = {"h": float(lag)}
402
+ row.update({a: float(v[i]) for a, v in c.values.items() if i < len(v)})
403
+ rows.append(row)
404
+ ctx.table(rows, "covariance")
405
+ elif name == "lineal_path":
406
+ lp = lineal_path(image, phase)
407
+ ctx.figure(_axes_figure(lp, "lineal path", "L(h)"), "lineal_path")
408
+ elif name == "chords":
409
+ ys, rows = {}, []
410
+ for axis in range(3):
411
+ if image.shape[axis] < 2:
412
+ continue
413
+ lengths = chord_lengths(image, phase, axis)
414
+ if lengths.size:
415
+ counts, edges = np.histogram(lengths, bins=24, density=True)
416
+ mid = 0.5 * (edges[1:] + edges[:-1])
417
+ ys["xyz"[axis]] = (mid, counts)
418
+ rows.append({"axis": "xyz"[axis], "chords": int(lengths.size),
419
+ "mean": float(lengths.mean())}) # fmt: skip
420
+ if ys:
421
+ ctx.figure(_plot(None, ys, "chord lengths", "length", "density"), "chords")
422
+ ctx.table(rows, "chords", "mean chord lengths")
423
+ elif name == "granulometry":
424
+ g = granulometry(image, phase)
425
+ ctx.figure(_plot(g.radii, {"kept": g.fractions}, "granulometry", "radius",
426
+ "volume fraction kept"), "granulometry") # fmt: skip
427
+ elif name == "pore_sizes":
428
+ ps = pore_size_function(image, 1 - phase if phase in (0, 1) else 0)
429
+ delta = np.asarray(ps.delta, dtype=float)
430
+ if len(delta) == len(ps.density) + 1: # the edges of the bins: their centres
431
+ delta = 0.5 * (delta[1:] + delta[:-1])
432
+ ctx.figure(_plot(delta, {"density": ps.density}, "pore-size function",
433
+ "distance δ", "P(δ)"), "pore_sizes") # fmt: skip
434
+ elif name in ("capacity_ball", "capacity_segment"):
435
+ element = name.split("_")[1]
436
+ cap = choquet_capacity(image, element, phase=phase) # segments along x
437
+ theory = _capacities(model, element, cap.sizes) if phase == 1 else None
438
+ ctx.figure(_plot(cap.sizes, {"measured": cap.values}, f"Choquet capacity ({element})",
439
+ "size", "T(K)", theory=theory), name) # fmt: skip
440
+ return {}
441
+
442
+
443
+ def _axis_covariances(model, curve):
444
+ """The closed-form covariance of a model along each axis of the measured ``curve`` when
445
+ it depends on the direction (anisotropic fibres: ``covariance(h, direction)``), else the
446
+ single one of an isotropic model (or None)."""
447
+ import inspect
448
+
449
+ method = getattr(model, "covariance", None)
450
+ orientation = getattr(model, "orientation", None)
451
+ if method is None or "direction" not in inspect.signature(method).parameters:
452
+ return _closed(model, "covariance", curve.lags["x"])
453
+ if orientation is None or type(orientation).__name__ == "Isotropic":
454
+ return _closed(model, "covariance", curve.lags["x"])
455
+ out = {}
456
+ for k, axis in enumerate("xyz"):
457
+ if axis in curve.lags and len(curve.lags[axis]) > 1:
458
+ x = curve.lags[axis]
459
+ try:
460
+ y = np.asarray(method(x, direction=np.eye(3)[k]), dtype=float)
461
+ except (TypeError, ValueError, NotImplementedError, AttributeError):
462
+ continue
463
+ if y.shape == np.shape(x) and np.all(np.isfinite(y)):
464
+ out[axis] = (x, y)
465
+ return out or None
466
+
467
+
468
+ def _capacities(model, element: str, sizes):
469
+ """The closed-form capacity of a model for the elements measured: segments along x, as
470
+ :func:`morphogen.analysis.random_sets.choquet_capacity` takes them, when the capacity
471
+ depends on the direction (fibres of anisotropic axes); else None."""
472
+ import inspect
473
+
474
+ method = getattr(model, "choquet_capacity", None)
475
+ if method is not None and "direction" in inspect.signature(method).parameters:
476
+ return _closed(model, "choquet_capacity", element, sizes, direction=(1.0, 0.0, 0.0))
477
+ return _closed(model, "choquet_capacity", element, sizes)
478
+
479
+
480
+ def _closed(model, name: str, *args, **kwargs):
481
+ """The closed form ``name`` of a model at the abscissae (its last positional argument),
482
+ when it has one that evaluates to finite values; else None."""
483
+ if model is None or not hasattr(model, name):
484
+ return None
485
+ x = args[-1]
486
+ try:
487
+ y = np.asarray(getattr(model, name)(*args, **kwargs), dtype=float)
488
+ except (TypeError, ValueError, NotImplementedError, AttributeError):
489
+ return None
490
+ return (x, y) if y.shape == np.shape(x) and np.all(np.isfinite(y)) else None
491
+
492
+
493
+ @tool(
494
+ "stereology",
495
+ "statistics",
496
+ "Stereology",
497
+ "The sections of a phase by the planes of a voxel image of a morphology normal to the "
498
+ "three axes (their equivalent radii; touching sections split by a watershed), and the "
499
+ "size distribution of its particles recovered from them by Saltykov's unfolding, for "
500
+ "spheres or aligned ellipsoids of a common shape (Degdeg & Dirrenberger); the shape "
501
+ "consistent with the mean sections of the three directions.",
502
+ [
503
+ Field("source", "item", label="morphology", required=True),
504
+ Field("resolution", "int", 96, label="voxels per edge"),
505
+ Field("phase", "int", 1, doc="the phase of the particles"),
506
+ Field("separate", "bool", True, label="split touching sections (watershed)"),
507
+ Field("shape", "floats", [1.0, 1.0], label="shape factors b/a, c/a", doc="1, 1: spheres"),
508
+ Field("bins", "int", 16, label="classes of radii"),
509
+ Field(
510
+ "classes",
511
+ "int",
512
+ label="3D classes unfolded",
513
+ doc="blank: the number that best refolds the three directions",
514
+ ),
515
+ ],
516
+ order=3,
517
+ menu="Morphology",
518
+ )
519
+ def stereology(p: dict, ctx) -> dict:
520
+ from morphogen.analysis.stereology import consistent_shape, section_sizes, unfold_sections
521
+ from morphogen.gui.api import _voxels
522
+
523
+ micro = p["source"]["micro"]
524
+ _voxels(micro.domain, p["resolution"], 6.0, "image")
525
+ image = micro.voxelize(shape=p["resolution"])
526
+ axes = [a for a in range(3) if image.shape[a] > 1 and min(np.delete(image.shape, a)) > 1]
527
+ sections = []
528
+ for k, axis in enumerate(axes):
529
+ ctx.progress(0.8 * k / max(len(axes), 1), f"sections normal to {'xyz'[axis]}")
530
+ sec = section_sizes(image, p["phase"], axis, separate=p["separate"])
531
+ if len(sec.radii):
532
+ sections.append(sec)
533
+ if not sections:
534
+ raise ValueError(f"no section of phase {p['phase']} in the planes of the image")
535
+ rows = [
536
+ {"axis": "xyz"[s.axis], "sections": len(s.radii), "mean radius": s.mean_radius(),
537
+ "per unit area": float(s.weights.sum() / s.area)}
538
+ for s in sections
539
+ ] # fmt: skip
540
+ ctx.table(rows, "sections", "sections of the three directions")
541
+ shape = tuple((p["shape"] or [1.0, 1.0])[:2])
542
+ if len(shape) != 2:
543
+ raise ValueError("shape factors: two numbers, b/a and c/a")
544
+ ctx.progress(0.85, "unfolding")
545
+ classes = p["classes"] if p["classes"] or len(sections) > 1 else max(2, p["bins"] // 2)
546
+ unfolded = unfold_sections(sections, shape=shape, bins=p["bins"], classes=classes)
547
+ fractions = unfolded.fractions()
548
+ ctx.table(
549
+ [{"short semi-axis": float(r), "per unit volume": float(n), "fraction": float(f)}
550
+ for r, n, f in zip(unfolded.radii, unfolded.density, fractions, strict=True)],
551
+ "unfolded", "size distribution of the particles (Saltykov)",
552
+ ) # fmt: skip
553
+ ctx.figure(
554
+ _plot(unfolded.radii, {"unfolded": unfolded.density}, "particles per unit volume",
555
+ "short semi-axis a", "N_V"),
556
+ "unfolded",
557
+ ) # fmt: skip
558
+ values = {
559
+ f"refolding error {'xyz'[a]}": float(e)
560
+ for a, e in zip(unfolded.axes, unfolded.errors, strict=True)
561
+ }
562
+ values["mean short semi-axis"] = float(np.sum(unfolded.radii * fractions))
563
+ if len(sections) == 3:
564
+ try:
565
+ b, c = consistent_shape(sections)
566
+ values.update({"consistent b/a": b, "consistent c/a": c})
567
+ except (ValueError, np.linalg.LinAlgError, FloatingPointError):
568
+ pass
569
+ return {"values": values}
570
+
571
+
572
+ @tool(
573
+ "fit_table",
574
+ "statistics",
575
+ "RVE fit of a table of results",
576
+ "The RVE scaling law fitted to a table of results of any origin (apparent moduli of "
577
+ "other codes, image measures): one row per realization, a column of volumes and "
578
+ "columns of properties; the variance D²(V) fitted as K V^-γ (γ free or imposed) and "
579
+ "the RVE volumes for the errors and numbers of realizations chosen, as `morphogen fit`.",
580
+ [
581
+ Field("table", "text", label="table (CSV)", required=True,
582
+ doc="a header line, then one line per realization: e.g. volume,E1 then 8,1.23"),
583
+ Field("volume_column", "str", "volume", label="column of the volumes"),
584
+ Field("properties", "str", label="columns of the properties",
585
+ doc="separated by commas (blank: every numeric column but the volume)"),
586
+ Field("gamma", "float", label="γ imposed", doc="blank: fitted"),
587
+ Field("relative_errors", "floats", [0.01, 0.05]),
588
+ Field("n_realizations", "ints", [1, 10], label="numbers of realizations"),
589
+ ],
590
+ order=6,
591
+ menu="Representative volume",
592
+ ) # fmt: skip
593
+ def fit_table(p: dict, ctx) -> dict:
594
+ import csv
595
+ import io as textio
596
+
597
+ from morphogen import pipeline
598
+ from morphogen.config import RVESpec
599
+ from morphogen.rve import report as rve_report
600
+
601
+ text = p["table"].strip()
602
+ dialect = csv.Sniffer().sniff(text.splitlines()[0], delimiters=",;\t ")
603
+ rows = []
604
+ for raw in csv.DictReader(textio.StringIO(text), dialect=dialect):
605
+ row = {}
606
+ for k, v in raw.items():
607
+ if k is None:
608
+ continue
609
+ try:
610
+ row[k.strip()] = float(str(v).replace(",", ".")) if v not in (None, "") else None
611
+ except ValueError:
612
+ row[k.strip()] = v
613
+ rows.append(row)
614
+ volume = p["volume_column"]
615
+ if not rows or volume not in rows[0]:
616
+ raise ValueError(
617
+ f"table: no column {volume!r} (the columns: {', '.join(rows[0]) if rows else 'none'})"
618
+ )
619
+ for row in rows:
620
+ row["volume"] = row[volume]
621
+ if p["properties"]:
622
+ properties = [s.strip() for s in p["properties"].split(",") if s.strip()]
623
+ else:
624
+ properties = [
625
+ k for k, v in rows[0].items() if isinstance(v, float) and k not in ("volume", volume)
626
+ ]
627
+ if not properties:
628
+ raise ValueError("properties: no numeric column besides the volumes")
629
+ spec = RVESpec(relative_errors=p["relative_errors"], n_realizations=p["n_realizations"],
630
+ gamma=p["gamma"], bootstrap=200) # fmt: skip
631
+ ctx.progress(0.3, "fit")
632
+ report = pipeline.build_report(rows, spec, properties)
633
+ rve_report.write(report, ctx.folder)
634
+ for png in sorted(ctx.folder.glob("*.png")):
635
+ ctx.figures.append({"title": png.stem.replace("_", " "), "url": ctx.url(png.name)})
636
+ return {"tables": _markdown_tables((ctx.folder / "rve_report.md").read_text(encoding="utf-8"))}
637
+
638
+
639
+ @tool(
640
+ "reconstruction",
641
+ "statistics",
642
+ "Reconstruction from the statistics",
643
+ "A new morphology whose two-point correlation function (and lineal path) match those "
644
+ "of a morphology of the workspace, by the simulated annealing of Yeong & Torquato "
645
+ "(1998) on a lattice of cells; it joins the workspace, to compare its properties "
646
+ "with those of the original.",
647
+ [
648
+ Field("source", "item", label="morphology", required=True),
649
+ Field("resolution", "int", 48, label="cells per edge"),
650
+ Field("lineal_path", "float", 0.0, label="weight of the lineal path",
651
+ doc="0: the two-point function alone"),
652
+ Field("sweeps", "int", 60, doc="trial swaps per cell"),
653
+ Field("seed", "int", 1),
654
+ ],
655
+ order=7,
656
+ menu="Reconstruction",
657
+ ) # fmt: skip
658
+ def reconstruction(p: dict, ctx) -> dict:
659
+ from morphogen import io
660
+ from morphogen.analysis.covariance import covariance
661
+ from morphogen.domain import Domain
662
+ from morphogen.gui import api
663
+ from morphogen.models.base import model_from_config
664
+ from morphogen.seeding import derive_seed
665
+
666
+ item = p["source"]
667
+ micro = item["micro"]
668
+ lengths = np.asarray(micro.domain.lengths, dtype=float)
669
+ cell = float(lengths.max()) / p["resolution"]
670
+ spec = {"type": "reconstruction", "cell_size": cell, "sweeps": p["sweeps"],
671
+ "lineal_path": p["lineal_path"]} # fmt: skip
672
+ planar = bool(item.get("planar"))
673
+ if planar:
674
+ spec["dimension"] = 2
675
+ if item.get("model") and item["model"].get("type") != "reconstruction":
676
+ spec["reference"] = item["model"]
677
+ else: # the target: the phases of the morphology on the lattice
678
+ target = micro.voxelize(voxel_size=cell)
679
+ path = ctx.path("target.vti")
680
+ io.save_image(target, path)
681
+ spec["image"] = str(path)
682
+ model = model_from_config(spec)
683
+ domain = Domain(size=tuple(float(v) for v in lengths), periodic=True)
684
+ ctx.progress(0.1, "annealing")
685
+ new = model.generate(domain, derive_seed(p["seed"], 0))
686
+ ctx.progress(0.85, "views")
687
+ views = api.morphology_views(new, 384)
688
+ a = micro.voxelize(voxel_size=cell)
689
+ b = new.voxelize(voxel_size=cell)
690
+ ca, cb = covariance(a, 1), covariance(b, 1)
691
+ from matplotlib.figure import Figure
692
+
693
+ fig = Figure(figsize=(5.4, 3.8), layout="constrained")
694
+ ax = fig.subplots()
695
+ ax.plot(ca.lags["x"], np.mean([ca.values[k] for k in "xy"], axis=0), lw=1.8, label="original")
696
+ ax.plot(cb.lags["x"], np.mean([cb.values[k] for k in "xy"], axis=0), "--", lw=1.8,
697
+ label="reconstruction") # fmt: skip
698
+ ax.set_xlabel("h")
699
+ ax.set_ylabel("C(h)")
700
+ ax.set_title("two-point correlation function", fontsize=10)
701
+ ax.grid(alpha=0.3)
702
+ ax.legend(fontsize=8, frameon=False)
703
+ ctx.figure(fig, "covariance")
704
+ for s in views["sections"]:
705
+ ctx.figures.append({"title": f"reconstruction, {s['title']}", "url": s["png"]})
706
+ attrs = getattr(new, "attributes", {}) or {}
707
+ added = ctx.add(
708
+ "morphology",
709
+ f"reconstruction of #{item['number']}",
710
+ micro=new,
711
+ origin="statistics",
712
+ source=item["key"],
713
+ model=model.to_config(),
714
+ domain={"size": [float(v) for v in lengths], "periodic": True},
715
+ seed=p["seed"],
716
+ phases={"0": "phase 0", "1": "phase 1"},
717
+ thumbnail=views["thumbnail"],
718
+ fraction=views["fraction"],
719
+ planar=planar,
720
+ info={"model": "reconstruction", "source": f"#{item['number']}"},
721
+ )
722
+ return {
723
+ "values": {
724
+ "fraction (original)": float((a.data == 1).mean()),
725
+ "fraction (reconstruction)": float((b.data == 1).mean()),
726
+ "initial energy": attrs.get("initial_energy"),
727
+ "final energy": attrs.get("energy"),
728
+ },
729
+ "items": [] if added in ctx.items else [added],
730
+ }
731
+
732
+
733
+ #: The settings of the axes of the orientations of an .ang file, as the form names them
734
+ ANG_AXES = (
735
+ ("1", "1: its first axis down the image (usual)"),
736
+ ("2", "2: its first axis up the image"),
737
+ ("3", "3: its first axis to the right"),
738
+ ("4", "4: its first axis to the left"),
739
+ )
740
+
741
+
742
+ @tool(
743
+ "texture",
744
+ "statistics",
745
+ "Orientation map (EBSD)",
746
+ "The grains and the texture of an orientation map (an .ang or a .ctf file): the grains "
747
+ "found from the disorientations of its points and their numbers phase by phase, the "
748
+ "map in the colours of its orientations, its pole figures, its inverse pole figure and "
749
+ "the disorientations of its boundaries. Its polycrystal — the grains as columns "
750
+ "through one layer of cells, each with its orientation — joins the workspace, for the "
751
+ "tools of the mechanics.",
752
+ [
753
+ Field("file", "str", "ebsd_map.ctf", label="map", required=True,
754
+ doc="an .ang or a .ctf file (ebsd_map.ctf: the map that comes with morphoGen)"),
755
+ Field("threshold", "float", 5.0, unit="degrees",
756
+ doc="two neighbouring points less than this apart are in one grain"),
757
+ Field("min_size", "int", 5, label="smallest grain", unit="points",
758
+ doc="smaller grains are given to their neighbours"),
759
+ Field("setting", "choice", "1", choices=ANG_AXES, label="axes of an .ang file",
760
+ doc="of its orientations, in the image of the map (a .ctf file gives them in "
761
+ "the axes of the image)"),
762
+ Field("poles", "str", "", label="pole figures",
763
+ doc="families of planes, e.g. 100 110 111 (blank: those of the lattice)"),
764
+ Field("direction", "choice", "z", choices=("x", "y", "z"),
765
+ label="direction of the sample",
766
+ doc="of the inverse pole figure and of the colours of the map"),
767
+ Field("halfwidth", "float", 10.0, unit="degrees",
768
+ doc="of the kernel that spreads each pole"),
769
+ Field("add", "bool", True, label="add its polycrystal to the workspace"),
770
+ ],
771
+ order=8,
772
+ menu="Orientation maps",
773
+ ) # fmt: skip
774
+ def texture_map(p: dict, ctx) -> dict:
775
+ from morphogen import texture
776
+ from morphogen.domain import Domain
777
+ from morphogen.gui import api
778
+ from morphogen.io import ebsd as maps
779
+ from morphogen.models.ebsd import EBSD
780
+ from morphogen.viz import figures
781
+
782
+ model = EBSD(file=p["file"], threshold=p["threshold"], min_size=p["min_size"],
783
+ setting=int(p["setting"])) # fmt: skip
784
+ poles = []
785
+ for word in re.split(r"[\s,;]+", (p["poles"] or "").strip()):
786
+ digits = re.findall(r"-?\d", word)
787
+ if word and "".join(digits) != word:
788
+ raise ValueError(f"pole figures: indices such as 111 or 10-10, got {word!r}")
789
+ if word:
790
+ poles.append(tuple(int(v) for v in digits))
791
+ direction = {"x": (1.0, 0.0, 0.0), "y": (0.0, 1.0, 0.0), "z": (0.0, 0.0, 1.0)}[p["direction"]]
792
+ ctx.progress(0.05, "reading the map")
793
+ measured = maps.read_ebsd(model.path(), setting=model.setting)
794
+ ctx.progress(0.2, "grains")
795
+ grains = model.grains()
796
+ summary = grains.summary(poles=poles or None, halfwidth=p["halfwidth"])
797
+ ny, nx = measured.shape
798
+ values = {
799
+ "points": f"{nx} x {ny}",
800
+ f"step ({measured.unit})": f"{measured.step[0]:g} x {measured.step[1]:g}",
801
+ "indexed": float(measured.indexed.mean()),
802
+ "grains": grains.count,
803
+ }
804
+ several = len(summary["phases"]) > 1
805
+ pairs, lengths, angles = grains.boundaries()
806
+ ctx.figure(figures.ipf_map_figure(measured, direction, grains=grains), "map",
807
+ f"the map in the colours of its crystals along {p['direction']}") # fmt: skip
808
+ defaults = {"cubic": ((1, 0, 0), (1, 1, 0), (1, 1, 1)),
809
+ "hexagonal": ((0, 0, 0, 1), (1, 0, -1, 0), (1, 0, -1, 1))} # fmt: skip
810
+ for step, entry in enumerate(summary["phases"]):
811
+ ctx.progress(0.3 + 0.5 * step / len(summary["phases"]), f"texture of {entry['name']}")
812
+ prefix = f"{entry['name']}: " if several else ""
813
+ values[f"{prefix}lattice"] = entry["lattice"]
814
+ values[f"{prefix}grains"] = entry["grains"]
815
+ values[f"{prefix}mean diameter ({measured.unit})"] = entry["mean_diameter"]
816
+ values[f"{prefix}mean diameter by area ({measured.unit})"] = entry["mean_diameter_by_area"]
817
+ values[f"{prefix}spread inside the grains (degrees)"] = entry["mean_spread"]
818
+ if "mean_disorientation" in entry:
819
+ values[f"{prefix}mean disorientation of the boundaries (degrees)"] = entry[
820
+ "mean_disorientation"
821
+ ]
822
+ for name, largest in entry.get("pole_figures", {}).items():
823
+ values[f"{prefix}pole figure {{{name}}}, largest density"] = largest
824
+ k = entry["phase"]
825
+ of = grains.phase == k
826
+ suffix = f"_{k}" if several else ""
827
+ family = {"m-3": "cubic", "6/m": "hexagonal"}.get(entry["lattice"], entry["lattice"])
828
+ if family in defaults:
829
+ ratio = grains.phases[k - 1].c_over_a if family == "hexagonal" else None
830
+ shown = [texture.pole_figure(grains.orientations[of], indices, family,
831
+ weights=grains.areas[of], halfwidth=p["halfwidth"],
832
+ c_over_a=ratio)
833
+ for indices in poles or defaults[family]] # fmt: skip
834
+ ctx.figure(figures.pole_figures_figure(shown), f"pole_figures{suffix}",
835
+ f"{prefix}pole figures") # fmt: skip
836
+ inverse = texture.inverse_pole_figure(grains.orientations[of], direction, family,
837
+ weights=grains.areas[of],
838
+ halfwidth=p["halfwidth"]) # fmt: skip
839
+ points = texture.inverse_poles(grains.orientations[of], direction, family)
840
+ ctx.figure(figures.inverse_pole_figure_figure(inverse, points=points),
841
+ f"inverse_pole_figure{suffix}",
842
+ f"{prefix}the crystals along {p['direction']}") # fmt: skip
843
+ between = of[pairs[:, 0]] if len(pairs) else np.zeros(0, dtype=bool)
844
+ if between.any():
845
+ ctx.figure(figures.disorientation_figure(angles[between], lengths[between],
846
+ lattice=entry["lattice"]),
847
+ f"disorientations{suffix}",
848
+ f"{prefix}disorientations of the boundaries") # fmt: skip
849
+ table = grains.table()
850
+ ctx.table([{name: column[i] for name, column in table.items()} for i in range(grains.count)],
851
+ "grains", "the grains (angles in degrees)") # fmt: skip
852
+ ctx.table([{"grain a": int(a), "grain b": int(b), "length": float(length),
853
+ "disorientation": float(angle)}
854
+ for (a, b), length, angle in zip(pairs.tolist(), lengths, angles, strict=True)],
855
+ "boundaries", "the boundaries between the grains of one phase") # fmt: skip
856
+ items = []
857
+ if p["add"]:
858
+ ctx.progress(0.85, "polycrystal")
859
+ width, height = measured.size
860
+ size = [float(width), float(height), float(min(measured.step))]
861
+ new = model.generate(Domain(size=tuple(size), periodic=False, unit=measured.unit), 0)
862
+ views = api.morphology_views(new, 384)
863
+ added = ctx.add(
864
+ "morphology",
865
+ f"polycrystal of {Path(p['file']).name}",
866
+ micro=new,
867
+ origin="statistics",
868
+ model=model.to_config(),
869
+ domain={"size": size, "periodic": False},
870
+ seed=0,
871
+ phases={str(k): v for k, v in model.active_phases().items()},
872
+ thumbnail=views["thumbnail"],
873
+ fraction=views["fraction"],
874
+ planar=True,
875
+ info={"model": "ebsd", "grains": grains.count},
876
+ )
877
+ items = [] if added in ctx.items else [added]
878
+ return {"values": values, "items": items}
879
+
880
+
881
+ #: The criteria of percolation: along an axis, any of them or all three
882
+ AXES = (
883
+ ("x", "along x"),
884
+ ("y", "along y"),
885
+ ("z", "along z"),
886
+ ("any", "along any axis"),
887
+ ("all", "along the three axes"),
888
+ )
889
+
890
+
891
+ @tool(
892
+ "percolation",
893
+ "statistics",
894
+ "Percolation threshold",
895
+ "The fraction at which a phase of the model of a morphology percolates: the share of "
896
+ "independent realizations whose phase joins the faces normal to an axis (or, on a "
897
+ "periodic morphology, wraps around the box) as a parameter of the model varies (the "
898
+ "volume fraction), its crossing of 1/2 bracketed by bisection down to the tolerance, "
899
+ "the realizations seeded alike at every fraction (common random numbers); optionally, "
900
+ "the rigidity threshold, where the elastic moduli of the phase by the FFT solver vanish, "
901
+ "and the critical exponent of the conductivity or of the elastic moduli of the phase at "
902
+ "the threshold, by the finite-size scaling of its FFT solutions over box sizes.",
903
+ [
904
+ Field(
905
+ "source",
906
+ "item",
907
+ label="morphology",
908
+ required=True,
909
+ needs=("model",),
910
+ doc="a morphology generated from a model (its model, domain and periodicity)",
911
+ ),
912
+ Field("parameter", "str", "volume_fraction", doc="the parameter of the model varied"),
913
+ Field("lower", "float", 0.05, label="lower bound"),
914
+ Field("upper", "float", 0.95, label="upper bound"),
915
+ Field("resolution", "int", 64, label="voxels per edge", doc="of the images"),
916
+ Field("phase", "int", 1),
917
+ Field("axis", "choice", "x", label="percolating", choices=AXES),
918
+ Field(
919
+ "connectivity",
920
+ "choice",
921
+ "6",
922
+ label="neighbours",
923
+ choices=(
924
+ ("6", "6: faces"),
925
+ ("18", "18: faces and edges"),
926
+ ("26", "26: faces, edges and corners"),
927
+ ("4", "4: edges (2-D)"),
928
+ ("8", "8: edges and corners (2-D)"),
929
+ ),
930
+ doc="a planar morphology (one voxel along z) percolates in its plane: 6 is 4 "
931
+ "there, 18 and 26 are 8",
932
+ ),
933
+ Field(
934
+ "boundaries",
935
+ "choice",
936
+ "morphology",
937
+ choices=(
938
+ ("morphology", "those of the morphology"),
939
+ ("periodic", "periodic: wrapping around the box"),
940
+ ("open", "open: joining two faces"),
941
+ ),
942
+ ),
943
+ Field(
944
+ "method",
945
+ "choice",
946
+ "labels",
947
+ label="algorithm",
948
+ choices=(
949
+ ("labels", "labels: the components of the image"),
950
+ ("fire", "forest fire: lit on a face, reaching the other"),
951
+ ),
952
+ doc="the fire crosses the image face to face along the axis, through the "
953
+ "periodic faces across it; the labels wrap around a periodic box",
954
+ ),
955
+ Field("realizations", "int", 9, doc="images at each fraction"),
956
+ Field("tol", "float", 0.005, label="tolerance", doc="width of the final bracket"),
957
+ Field("seed", "int", 1),
958
+ Field(
959
+ "sizes",
960
+ "ints",
961
+ None,
962
+ label="box sizes",
963
+ unit="voxels",
964
+ doc="finite-size scaling: the thresholds of cubes of these sizes (at least 3), at "
965
+ "the voxel size of the resolution, extrapolated to the infinite medium as "
966
+ "p_c + a L^(-1/ν); none: the threshold at the resolution",
967
+ ),
968
+ Field(
969
+ "nu",
970
+ "float",
971
+ None,
972
+ label="ν",
973
+ doc="none: that of random percolation, 0.8765 in 3-D and 4/3 in 2-D",
974
+ ),
975
+ Field("fit_nu", "bool", False, label="fit ν", doc="at least 4 sizes"),
976
+ Field(
977
+ "rigidity",
978
+ "bool",
979
+ False,
980
+ label="rigidity threshold",
981
+ doc="the threshold where the elastic moduli of the phase vanish, not where it "
982
+ "connects (its voxels joined at corners and edges turn about them, so that no "
983
+ "neighbours give it): where half the realizations bear a uniaxial strain along the "
984
+ "axis with a modulus above the cut, the other phases void, by the solver below; "
985
+ "that of the exponent f when its threshold is not given",
986
+ ),
987
+ Field(
988
+ "cut",
989
+ "float",
990
+ None,
991
+ doc="rigidity: the modulus above which a realization bears, over the Young's "
992
+ "modulus of the phase; none: 1e-8 by the FFT solver, 1e-12 by the voxels "
993
+ "factorized, whose energies resolve the moduli down to the round-off",
994
+ ),
995
+ Field(
996
+ "directions",
997
+ "choice",
998
+ "none",
999
+ label="anisotropy",
1000
+ choices=(
1001
+ ("none", "none: the criterion above"),
1002
+ ("axes", "along the axes"),
1003
+ ("lattice", "along the axes and the diagonals"),
1004
+ ("sampled", "along directions sampled"),
1005
+ ),
1006
+ doc="the thresholds across the cores of the box along directions (the cylinders "
1007
+ "of its inscribed ball, by the forest fire, the realizations common to the "
1008
+ "directions), their ratio and their threshold tensor",
1009
+ ),
1010
+ Field(
1011
+ "count",
1012
+ "int",
1013
+ 12,
1014
+ label="directions sampled",
1015
+ when={"directions": "sampled"},
1016
+ doc="over half a circle in 2-D, on a Fibonacci spiral over the half sphere in 3-D",
1017
+ ),
1018
+ Field(
1019
+ "exponent",
1020
+ "choice",
1021
+ "none",
1022
+ label="critical exponent",
1023
+ choices=(
1024
+ ("none", "none"),
1025
+ ("thermal", "t: the conductivity"),
1026
+ ("elastic", "f: the elastic moduli"),
1027
+ ),
1028
+ doc="the exponent of the property of the phase by the solver below: the finite-size "
1029
+ "scaling of its mean over the box sizes at the threshold, L^(-t/ν); the voxels of "
1030
+ "the solver joining through their nodes, take 26 neighbours (8 in 2-D) and the "
1031
+ "periodic boundaries for the threshold of the conductivity",
1032
+ ),
1033
+ Field(
1034
+ "threshold",
1035
+ "float",
1036
+ None,
1037
+ doc="none: extrapolated from the box sizes with the criterion above",
1038
+ ),
1039
+ Field(
1040
+ "threshold_stderr",
1041
+ "float",
1042
+ None,
1043
+ label="its standard error",
1044
+ doc="whose effect on the exponent is computed (the realizations at the threshold "
1045
+ "less and plus it); none: that of the extrapolation, 0 for a threshold given",
1046
+ ),
1047
+ Field(
1048
+ "contrast",
1049
+ "float",
1050
+ 1e-8,
1051
+ doc="the properties of the other phases over those of the phase (0: void)",
1052
+ ),
1053
+ Field(
1054
+ "device",
1055
+ "choice",
1056
+ "auto",
1057
+ choices=(("auto", "auto: the GPU when there is one"), ("cpu", "CPU"), ("gpu", "GPU")),
1058
+ doc="of the FFT solver",
1059
+ ),
1060
+ Field(
1061
+ "solver",
1062
+ "choice",
1063
+ "fft",
1064
+ choices=(
1065
+ ("fft", "FFT: conjugate gradients, on the device"),
1066
+ ("fe", "FE: the voxels assembled and factorized, on the CPU"),
1067
+ ),
1068
+ doc="of the trilinear voxels, for the rigidity and the exponents: the FFT solver, or "
1069
+ "their matrix assembled on the voxels of the materials and solved by conjugate "
1070
+ "gradients preconditioned by its sparse factorization, the same moduli in a few "
1071
+ "iterations where the FFT solver takes thousands, near the rigidity threshold with "
1072
+ "void around (contrast 0)",
1073
+ ),
1074
+ ],
1075
+ order=4,
1076
+ groups=(
1077
+ ("Family", "parameter"),
1078
+ ("Criterion", "phase"),
1079
+ ("Bisection", "realizations"),
1080
+ ("Finite-size scaling", "sizes", True),
1081
+ ("Anisotropy", "directions", True),
1082
+ ("Critical exponent", "exponent", True),
1083
+ ),
1084
+ menu="Morphology",
1085
+ )
1086
+ def percolation(p: dict, ctx) -> dict:
1087
+ from matplotlib.figure import Figure
1088
+
1089
+ from morphogen.analysis.percolation import (
1090
+ family_from_config,
1091
+ percolation_scaling,
1092
+ percolation_threshold,
1093
+ )
1094
+ from morphogen.domain import Domain
1095
+ from morphogen.gui.api import _voxels
1096
+
1097
+ item = p["source"]
1098
+ model = _model_of(item, "the threshold is that")
1099
+ domain, name = item["micro"].domain, p["parameter"] or "volume_fraction"
1100
+ _voxels(domain, p["resolution"], 12.0, "image")
1101
+ config = {
1102
+ "model": model,
1103
+ "domain": {"size": [float(v) for v in domain.lengths], "periodic": bool(domain.periodic)},
1104
+ "voxels": {"shape": p["resolution"]},
1105
+ }
1106
+ lower, upper, tol, n = p["lower"], p["upper"], p["tol"], p["realizations"]
1107
+ sizes = sorted(set(p["sizes"] or ()))
1108
+ if sizes and sizes[-1] > 0: # the largest box (sizes not positive refused by the scaling)
1109
+ _voxels(Domain(size=1.0), sizes[-1], 12.0, "image")
1110
+ ratio = (upper - lower) / tol if None not in (lower, upper) and tol else 0.0
1111
+ total = max(int(n or 1), 1) * (2 + (int(np.ceil(np.log2(ratio))) if ratio > 1 else 0))
1112
+ total *= max(len(sizes), 1)
1113
+ done = [0]
1114
+ criterion = {
1115
+ "phase": p["phase"],
1116
+ "axis": p["axis"],
1117
+ "connectivity": int(p["connectivity"]),
1118
+ "periodic": {"morphology": None, "periodic": True, "open": False}[p["boundaries"]],
1119
+ "method": p["method"],
1120
+ "realizations": n,
1121
+ "tol": tol,
1122
+ "seed": p["seed"],
1123
+ }
1124
+
1125
+ def family(fraction, rng, *size): # the progress, image by image (and the stops there)
1126
+ box = f" ({size[0]} voxels)" if size else ""
1127
+ ctx.progress(min(done[0] / total, 0.99), f"{name} = {fraction:.4g}{box}")
1128
+ done[0] += 1
1129
+ return generate(fraction, rng, *size)
1130
+
1131
+ if p["directions"] != "none":
1132
+ count = {"axes": 3, "lattice": 13}.get(p["directions"], p["count"] or 1)
1133
+ total *= max(int(count), 1)
1134
+ generate = family_from_config(config, name)
1135
+ return _anisotropy_outputs(family, p, name, ctx)
1136
+ if p["exponent"] != "none":
1137
+ if p["threshold"] is not None:
1138
+ total = 0
1139
+ total += max(len(sizes), 1) * max(int(n or 1), 1) * 3
1140
+ generate = family_from_config(config, name, sized=True)
1141
+ return _exponent_outputs(family, sizes, criterion, p, name, ctx)
1142
+ if p["rigidity"]:
1143
+ generate = family_from_config(config, name, sized=True)
1144
+ return _rigidity_outputs(_rigidity_of(family, sizes, criterion, p), p, name, ctx)
1145
+ if sizes:
1146
+ generate = family_from_config(config, name, sized=True)
1147
+ scaling = percolation_scaling(
1148
+ family, sizes, lower, upper, nu=p["nu"], fit_nu=p["fit_nu"], **criterion
1149
+ )
1150
+ results, threshold = scaling.results, scaling.threshold
1151
+ labels, marked = [f"{s} voxels" for s in scaling.sizes], "extrapolated"
1152
+ else:
1153
+ generate = family_from_config(config, name)
1154
+ result = percolation_threshold(family, lower, upper, **criterion)
1155
+ results, threshold, labels, marked = (result,), result.threshold, ["tried"], "threshold"
1156
+ fig = Figure(figsize=(5.4, 3.8), layout="constrained")
1157
+ ax = fig.subplots()
1158
+ for one, label in zip(results, labels, strict=True):
1159
+ ax.plot(one.fractions, one.probabilities, "o-", lw=1.6, ms=4, label=label)
1160
+ ax.axhline(0.5, color="0.6", lw=0.8, ls=":")
1161
+ ax.axvline(threshold, color="k", ls="--", lw=1.2, label=f"{marked} {threshold:.4g}")
1162
+ ax.set_xlabel(name)
1163
+ ax.set_ylabel("percolation probability")
1164
+ ax.set_ylim(-0.03, 1.03)
1165
+ ax.set_title(f"percolation of phase {p['phase']} ({p['axis']})", fontsize=10)
1166
+ ax.grid(alpha=0.3)
1167
+ ax.legend(fontsize=8, frameon=False)
1168
+ ctx.figure(fig, "percolation", "percolation probability")
1169
+ if sizes:
1170
+ return _scaling_outputs(scaling, p, name, ctx)
1171
+ rows = [{name: float(f), "probability": float(q)}
1172
+ for f, q in zip(result.fractions, result.probabilities, strict=True)] # fmt: skip
1173
+ ctx.table(rows, "percolation", "probabilities tried")
1174
+ lo, hi = result.bracket
1175
+ return {"values": {"threshold": result.threshold, "bracket from": lo, "bracket to": hi,
1176
+ "realizations": result.realizations}} # fmt: skip
1177
+
1178
+
1179
+ def _scaling_outputs(scaling, p: dict, name: str, ctx) -> dict:
1180
+ """The figure, the table and the values of a finite-size scaling of the threshold."""
1181
+ from matplotlib.figure import Figure
1182
+
1183
+ x = scaling.sizes.astype(float) ** (-1.0 / scaling.nu)
1184
+ lo, hi = scaling.brackets.T
1185
+ fig = Figure(figsize=(5.4, 3.8), layout="constrained")
1186
+ ax = fig.subplots()
1187
+ ax.errorbar(x, scaling.thresholds, yerr=[scaling.thresholds - lo, hi - scaling.thresholds],
1188
+ fmt="o", ms=4, capsize=2, label="boxes (brackets)") # fmt: skip
1189
+ for size, u, v in zip(scaling.sizes, x, scaling.thresholds, strict=True):
1190
+ ax.annotate(f"{size}", (u, v), textcoords="offset points", xytext=(4, 4), fontsize=7)
1191
+ line = np.linspace(0.0, 1.05 * x.max(), 50)
1192
+ ax.plot(line, scaling.threshold + scaling.amplitude * line, "-", lw=1.4,
1193
+ label=f"fit, ν = {scaling.nu:.4g}") # fmt: skip
1194
+ ax.errorbar([0.0], [scaling.threshold], yerr=[scaling.stderr], fmt="s", color="k", ms=5,
1195
+ capsize=3, label=f"p_c {scaling.threshold:.4g} ± {scaling.stderr:.2g}") # fmt: skip
1196
+ ax.set_xlim(-0.04 * x.max(), 1.08 * x.max())
1197
+ ax.set_xlabel(r"$L^{-1/\nu}$ ($L$: voxels per edge)")
1198
+ ax.set_ylabel(f"{name} at the crossing of 1/2")
1199
+ ax.set_title(f"finite-size scaling of phase {p['phase']} ({p['axis']})", fontsize=10)
1200
+ ax.grid(alpha=0.3)
1201
+ ax.legend(fontsize=8, frameon=False)
1202
+ ctx.figure(fig, "scaling", "finite-size scaling")
1203
+ columns = (scaling.sizes, scaling.thresholds, lo, hi, scaling.residuals)
1204
+ rows = [{"size": int(s), name: float(t), "bracket from": float(a), "bracket to": float(b),
1205
+ "residual": float(r)} for s, t, a, b, r in zip(*columns, strict=True)] # fmt: skip
1206
+ ctx.table(rows, "scaling", "thresholds of the boxes")
1207
+ values = {"threshold": scaling.threshold, "standard error": scaling.stderr,
1208
+ "amplitude": scaling.amplitude, "nu": scaling.nu} # fmt: skip
1209
+ if scaling.nu_stderr is not None:
1210
+ values["nu standard error"] = scaling.nu_stderr
1211
+ values["realizations"] = scaling.results[0].realizations
1212
+ return {"values": values}
1213
+
1214
+
1215
+ def _exponent_outputs(family, sizes, criterion: dict, p: dict, name: str, ctx) -> dict:
1216
+ """The critical exponent of the conductivity or of the elastic moduli of the phase at
1217
+ its threshold (given, or extrapolated from the box sizes with the criterion): the means
1218
+ of the boxes against their size, drawn on logarithmic axes with their fit, tabulated,
1219
+ and the exponent with its errors."""
1220
+ from matplotlib.figure import Figure
1221
+
1222
+ from morphogen.analysis.percolation import (
1223
+ _extrapolated_threshold,
1224
+ percolation_exponent,
1225
+ percolation_scaling,
1226
+ )
1227
+
1228
+ threshold, stderr = p["threshold"], p["threshold_stderr"]
1229
+ if threshold is None: # that of the connectivity for t, of the moduli for f
1230
+ if p["exponent"] == "elastic":
1231
+ scaling = _rigidity_of(family, sizes, criterion, {**p, "fit_nu": False})
1232
+ else:
1233
+ scaling = percolation_scaling(family, sizes, p["lower"], p["upper"], nu=p["nu"],
1234
+ **criterion) # fmt: skip
1235
+ threshold, error = _extrapolated_threshold(scaling, p["lower"], p["upper"])
1236
+ stderr = error if stderr is None else stderr
1237
+ seed = p["seed"]
1238
+ r = percolation_exponent(
1239
+ family,
1240
+ sizes,
1241
+ threshold,
1242
+ threshold_stderr=stderr or 0.0,
1243
+ physics=p["exponent"],
1244
+ phase=p["phase"],
1245
+ axis=p["axis"],
1246
+ contrast=p["contrast"],
1247
+ nu=p["nu"],
1248
+ realizations=p["realizations"],
1249
+ device=p["device"],
1250
+ solver=p["solver"],
1251
+ seed=None if seed is None else seed + 1,
1252
+ )
1253
+ symbol = "t" if r.physics == "thermal" else "f"
1254
+ prop = "conductivity" if r.physics == "thermal" else "uniaxial-strain modulus"
1255
+ fig = Figure(figsize=(5.4, 3.8), layout="constrained")
1256
+ ax = fig.subplots()
1257
+ ax.errorbar(r.sizes, r.means, yerr=r.mean_stderr, fmt="o", ms=4, capsize=2,
1258
+ label=f"means at {threshold:.4g}") # fmt: skip
1259
+ if np.isfinite(r.exponent):
1260
+ line = np.geomspace(r.sizes[0], r.sizes[-1], 50)
1261
+ ax.plot(line, r.amplitude * line ** (-r.ratio), "-", lw=1.4,
1262
+ label=f"{symbol} = {r.exponent:.3f} ± {r.stderr:.2g} (ν = {r.nu:.4g})") # fmt: skip
1263
+ ax.set_xscale("log")
1264
+ ax.set_yscale("log")
1265
+ ax.set_xlabel(r"$L$ (voxels per edge)")
1266
+ ax.set_ylabel(f"{prop} (phase 1)")
1267
+ ax.set_title(f"{prop} of phase {p['phase']} at the threshold ({p['axis']})", fontsize=10)
1268
+ ax.grid(alpha=0.3, which="both")
1269
+ ax.legend(fontsize=8, frameon=False)
1270
+ ctx.figure(fig, "exponent", "finite-size scaling of the property")
1271
+ columns = (r.sizes, r.means, r.mean_stderr, r.residuals)
1272
+ rows = [{"size": int(s), "mean": float(m), "standard error": float(e),
1273
+ "residual": _finite(d)} for s, m, e, d in zip(*columns, strict=True)] # fmt: skip
1274
+ ctx.table(rows, "exponent", "means of the boxes at the threshold")
1275
+ values = {"exponent": r.exponent, "standard error": r.stderr,
1276
+ "error from the threshold": r.threshold_error, "exponent over nu": r.ratio,
1277
+ "nu": r.nu, "threshold": r.threshold, "threshold standard error": stderr or 0.0,
1278
+ "contrast": r.contrast} # fmt: skip
1279
+ values = {k: float(v) for k, v in values.items() if np.isfinite(v)}
1280
+ values["realizations"], values["iterations"] = r.realizations, r.iterations
1281
+ return {"values": values}
1282
+
1283
+
1284
+ def _rigidity_of(family, sizes, criterion: dict, p: dict):
1285
+ """The rigidity threshold of the box sizes, where the elastic moduli of the phase vanish
1286
+ (:func:`~morphogen.analysis.percolation.rigidity_threshold`), with the bisection of the
1287
+ criterion (its neighbours, boundaries and algorithm unused: the solver's)."""
1288
+ from morphogen.analysis.percolation import rigidity_threshold
1289
+
1290
+ return rigidity_threshold(family, sizes, p["lower"], p["upper"], nu=p["nu"],
1291
+ fit_nu=p["fit_nu"], phase=criterion["phase"],
1292
+ axis=criterion["axis"], cut=p["cut"],
1293
+ realizations=criterion["realizations"], tol=criterion["tol"],
1294
+ device=p["device"], solver=p["solver"],
1295
+ seed=criterion["seed"]) # fmt: skip
1296
+
1297
+
1298
+ def _rigidity_outputs(result, p: dict, name: str, ctx) -> dict:
1299
+ """The figures, the tables and the values of a rigidity threshold: the shares of the
1300
+ realizations that bear and their moduli against the fraction, the finite-size scaling."""
1301
+ from matplotlib.figure import Figure
1302
+
1303
+ fig = Figure(figsize=(5.4, 3.8), layout="constrained")
1304
+ ax = fig.subplots()
1305
+ for size, one in zip(result.sizes, result.results, strict=True):
1306
+ ax.plot(one.fractions, one.probabilities, "o-", lw=1.6, ms=4, label=f"{size} voxels")
1307
+ ax.axhline(0.5, color="0.6", lw=0.8, ls=":")
1308
+ ax.axvline(result.threshold, color="k", ls="--", lw=1.2,
1309
+ label=f"extrapolated {result.threshold:.4g}") # fmt: skip
1310
+ ax.set_xlabel(name)
1311
+ ax.set_ylabel("share of the realizations that bear")
1312
+ ax.set_ylim(-0.03, 1.03)
1313
+ ax.set_title(f"rigidity of phase {p['phase']} ({p['axis']})", fontsize=10)
1314
+ ax.grid(alpha=0.3)
1315
+ ax.legend(fontsize=8, frameon=False)
1316
+ ctx.figure(fig, "rigidity", "bearing probability")
1317
+ fig = Figure(figsize=(5.4, 3.8), layout="constrained")
1318
+ ax = fig.subplots()
1319
+ solved = [m[np.isfinite(m)] for m in result.moduli]
1320
+ positive = np.concatenate([m[m > 0] for m in solved]) if solved else np.empty(0)
1321
+ floor = 1e-3 * positive.min() if positive.size else 1e-3 * result.cut
1322
+ for size, one, moduli in zip(result.sizes, result.results, result.moduli, strict=True):
1323
+ fractions = np.broadcast_to(one.fractions[:, None], moduli.shape)
1324
+ keep = np.isfinite(moduli)
1325
+ ax.plot(fractions[keep], np.maximum(moduli[keep], floor), "o", ms=3, alpha=0.6,
1326
+ label=f"{size} voxels") # fmt: skip
1327
+ ax.axhline(result.cut, color="k", ls="--", lw=1.0, label=f"cut {result.cut:.2g}")
1328
+ ax.set_yscale("log")
1329
+ ax.set_xlabel(name)
1330
+ ax.set_ylabel("modulus over that of the phase")
1331
+ ax.set_title("moduli of the realizations solved (the others void)", fontsize=10)
1332
+ ax.grid(alpha=0.3, which="both")
1333
+ ax.legend(fontsize=8, frameon=False)
1334
+ ctx.figure(fig, "moduli", "moduli of the realizations")
1335
+ out = _scaling_outputs(result, p, name, ctx)
1336
+ values = {"cut": result.cut, "largest floppy modulus": result.floppy,
1337
+ "smallest rigid modulus": result.rigid} # fmt: skip
1338
+ out["values"].update({k: float(v) for k, v in values.items() if np.isfinite(v)})
1339
+ out["values"].update(solutions=result.solutions, decided=result.decided,
1340
+ unresolved=result.unresolved, iterations=result.iterations) # fmt: skip
1341
+ return out
1342
+
1343
+
1344
+ def _finite(value):
1345
+ """A number of a table or of the values: None when not finite (beyond the bounds)."""
1346
+ return float(value) if np.isfinite(value) else None
1347
+
1348
+
1349
+ def _anisotropy_outputs(family, p: dict, name: str, ctx) -> dict:
1350
+ """The thresholds of a family across the cores of the box along directions: drawn (a
1351
+ rose in 2-D, bars in 3-D, with the quadratic form of the threshold tensor), tabulated,
1352
+ and their anisotropy (the ratio, the eigenvalues of the tensor)."""
1353
+ from matplotlib.figure import Figure
1354
+
1355
+ from morphogen.analysis.percolation import percolation_anisotropy
1356
+
1357
+ r = percolation_anisotropy(
1358
+ family,
1359
+ p["lower"],
1360
+ p["upper"],
1361
+ directions=p["count"] if p["directions"] == "sampled" else p["directions"],
1362
+ phase=p["phase"],
1363
+ connectivity=int(p["connectivity"]),
1364
+ realizations=p["realizations"],
1365
+ tol=p["tol"],
1366
+ seed=p["seed"],
1367
+ )
1368
+ n, finite = r.directions, np.isfinite(r.thresholds)
1369
+ planar, tensor = bool(np.all(n[:, 2] == 0)), bool(np.all(np.isfinite(r.tensor)))
1370
+ fig = Figure(figsize=(5.4, 4.2), layout="constrained")
1371
+ if planar: # against the angle, a direction and its opposite alike
1372
+ ax = fig.subplots(subplot_kw={"projection": "polar"})
1373
+ angle = np.arctan2(n[:, 1], n[:, 0]) % np.pi
1374
+ for turn, label in ((0.0, "thresholds"), (np.pi, None)):
1375
+ ax.errorbar((angle + turn)[finite], r.thresholds[finite], yerr=r.stderr[finite],
1376
+ fmt="o", ms=4, capsize=2, color="C0", label=label) # fmt: skip
1377
+ if tensor:
1378
+ theta = np.linspace(0.0, 2.0 * np.pi, 361)
1379
+ u = np.column_stack([np.cos(theta), np.sin(theta)])
1380
+ ax.plot(theta, np.einsum("ia,ab,ib->i", u, r.tensor[:2, :2], u), lw=1.2,
1381
+ color="C1", label="threshold tensor") # fmt: skip
1382
+ else:
1383
+ ax = fig.subplots()
1384
+ x = np.arange(len(n))
1385
+ ax.bar(x[finite], r.thresholds[finite], yerr=r.stderr[finite], capsize=2, color="C0",
1386
+ label="thresholds") # fmt: skip
1387
+ if tensor:
1388
+ fitted = np.einsum("ia,ab,ib->i", n, r.tensor, n)
1389
+ ax.plot(x, fitted, "D", ms=4, color="C1", label="threshold tensor")
1390
+ ticks = ["(" + ", ".join(f"{c:.2f}" for c in v) + ")" for v in n]
1391
+ ax.set_xticks(x, ticks, rotation=60, ha="right", fontsize=7)
1392
+ ax.set_ylabel(f"{name} at the crossing of 1/2")
1393
+ ax.grid(alpha=0.3, axis="y")
1394
+ ax.set_title(f"percolation of phase {p['phase']} along {len(n)} directions", fontsize=10)
1395
+ ax.legend(fontsize=8, frameon=False)
1396
+ ctx.figure(fig, "anisotropy", "thresholds along directions")
1397
+ columns = (n, r.thresholds, r.stderr, r.deviations, r.deviation_stderr)
1398
+ rows = [{"x": float(v[0]), "y": float(v[1]), "z": float(v[2]), name: _finite(t),
1399
+ "standard error": _finite(e), "deviation": _finite(d),
1400
+ "paired standard error": _finite(s)}
1401
+ for v, t, e, d, s in zip(*columns, strict=True)] # fmt: skip
1402
+ ctx.table(rows, "anisotropy", "thresholds along directions")
1403
+ values = {"largest over smallest": r.ratio, "ratio standard error": r.ratio_stderr}
1404
+ for k, (v, e) in enumerate(zip(r.eigenvalues, r.eigenvalue_stderr, strict=True)):
1405
+ values[f"eigenvalue {k + 1}"], values[f"eigenvalue {k + 1} standard error"] = v, e
1406
+ values = {k: float(v) for k, v in values.items() if np.isfinite(v)}
1407
+ values["realizations"] = r.realizations
1408
+ return {"values": values}