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,627 @@
1
+ """Reports of RVE studies: Markdown, LaTeX (booktabs), JSON and figures.
2
+
3
+ The tables follow Dirrenberger et al. (2014): realizations per volume (Table 3), mean
4
+ values with ``[Zbar - 2 D_Z, Zbar + 2 D_Z]`` and bounds (Table 4), statistical isotropy
5
+ (Tables 5-7), relative errors (Table 8), fitted exponents (Table 9) and RVE sizes
6
+ (Table 10), plus the discrepancy between boundary conditions (eq. 69) and the number of
7
+ realizations needed per volume. Volumes are printed as ``L^3``, the areas of the square
8
+ windows of a planar image as ``L^2``, and the edges of the RVE sizes are ``V^(1/3)`` (the
9
+ side ``A^(1/2)`` of a square of area ``A``).
10
+
11
+ When the realizations have their apparent stiffness
12
+ (:class:`~morphogen.rve.study.TensorStatistics`), each boundary condition adds the tables
13
+ of the mean stiffness ``Cbar_ij +/- 2 D`` and of the compliance ``S_ij = Cbar^-1 +/- 2 D``
14
+ per volume (every component of the upper triangle, Voigt order 11 22 33 23 31 12 with
15
+ engineering shears), the RVE sizes of their components, the figure
16
+ ``rve_stiffness_<bc>.png`` (the components against the volume, their relative scatter and
17
+ its fits) and the table ``rve_stiffness.csv`` (one row per condition and volume: ``C11``
18
+ ... ``C66``, ``S11`` ... ``S66`` and their standard deviations ``C11_std`` ...). The
19
+ conductivity tensor likewise, with its inverse the resistivity
20
+ (``rve_conductivity_tensor.csv``, the axes 1 2 3); by the window method
21
+ (:mod:`morphogen.rve.windows`) the tables count the windows of each size, whose tensors
22
+ are their mean mutual energies, as ``n x T`` with ``T`` tilings shifted around the
23
+ periodic realization (``n`` the windows of one, the count of the uncertainties).
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import json
29
+ import math
30
+ import re
31
+ from pathlib import Path
32
+
33
+ import numpy as np
34
+
35
+ from morphogen._utils import to_jsonable
36
+ from morphogen.rve.study import (
37
+ TENSOR_WORDS,
38
+ TRANSPORT_TENSORS,
39
+ StudyOptions,
40
+ StudyReport,
41
+ TensorStatistics,
42
+ )
43
+
44
+ BC_LABELS = {
45
+ "kubc": "KUBC",
46
+ "subc": "SUBC",
47
+ "mixed": "MBC",
48
+ "periodic": "PBC",
49
+ }
50
+
51
+
52
+ def _num(x, digits: int = 4) -> str:
53
+ if x is None or (isinstance(x, float) and not math.isfinite(x)):
54
+ return "-"
55
+ x = float(x)
56
+ if x == 0:
57
+ return "0"
58
+ if abs(x) >= 1e6 or abs(x) < 1e-3:
59
+ return f"{x:.{digits - 1}e}"
60
+ v = float(f"{x:.{digits}g}")
61
+ decimals = max(0, digits - 1 - math.floor(math.log10(abs(v))))
62
+ return f"{v:.{decimals}f}"
63
+
64
+
65
+ def _count(x) -> str:
66
+ """A number of realizations (an integer; '-' when undefined)."""
67
+ if x is None or not math.isfinite(float(x)):
68
+ return "-"
69
+ return str(int(x))
70
+
71
+
72
+ def _edge(volume: float, dimension: int = 3) -> str:
73
+ """A volume as the power of its edge, ``L^3``, or an area as ``L^2`` (``dimension``
74
+ 2: the square windows of a planar image)."""
75
+ edge = volume ** (1.0 / dimension)
76
+ if abs(edge - round(edge)) < 1e-6 * max(1.0, edge):
77
+ return f"{round(edge)}^{dimension}"
78
+ return f"{edge:.4g}^{dimension}"
79
+
80
+
81
+ def _samples(stats, k: int) -> str:
82
+ """The samples of the size ``k`` of statistics: its realizations (windows), ``n x T``
83
+ with ``T`` shifted tilings of ``n`` windows each."""
84
+ n = str(int(stats.n[k]))
85
+ return n if stats.tilings is None else f"{n} x {int(stats.tilings[k])}"
86
+
87
+
88
+ #: The note of the tables that count the windows of shifted tilings
89
+ _TILINGS = (
90
+ "n x T: the n windows of each of T tilings shifted around the periodic realization, the "
91
+ "means over all the windows, the variances pooled within the tilings, the uncertainties "
92
+ "counting the n windows of one tiling (the independent ones)."
93
+ )
94
+
95
+
96
+ def series_label(analysis) -> str:
97
+ """The label of an analysed series: its property, with its boundary conditions if any."""
98
+ s = analysis.series
99
+ return f"{s.property} ({BC_LABELS.get(s.bc, s.bc)})" if s.bc else s.property
100
+
101
+
102
+ def _volumes(report: StudyReport) -> list[float]:
103
+ vols = set()
104
+ for a in report.analyses:
105
+ vols.update(a.stats.volume.tolist())
106
+ return sorted(vols)
107
+
108
+
109
+ def _per_volume(a, volumes, getter) -> list[str]:
110
+ cells = []
111
+ for v in volumes:
112
+ idx = np.flatnonzero(a.stats.volume == v)
113
+ cells.append(getter(int(idx[0])) if idx.size else "")
114
+ return cells
115
+
116
+
117
+ def tables(report: StudyReport) -> list[tuple[str, list[str], list[list[str]], str]]:
118
+ """The report tables as (title, header, rows, note): those of the series, then those
119
+ of the mean stiffness and compliance of each boundary condition (:func:`tensor_tables`)."""
120
+ out = _series_tables(report) if report.analyses else []
121
+ for t in report.tensors:
122
+ out += tensor_tables(t, report.options)
123
+ return out
124
+
125
+
126
+ #: The notation of the tables of the mean stiffnesses, in space and in the plane
127
+ _SHORT_NOTATION = {
128
+ 6: "Voigt 11 22 33 23 31 12, engineering shears",
129
+ 3: "Voigt 11 22 12, engineering shear",
130
+ }
131
+
132
+
133
+ def _short_notation(t: TensorStatistics) -> str:
134
+ """The notation of the tables of a mean tensor: Voigt for a stiffness, the axes for a
135
+ conductivity."""
136
+ if t.property in TRANSPORT_TENSORS:
137
+ return "axes 1 2 3"
138
+ return _SHORT_NOTATION[len(t.mean[0])]
139
+
140
+
141
+ def _words(t: TensorStatistics) -> tuple[str, str, str, str]:
142
+ """The names of a tensor and of its inverse, singular and plural."""
143
+ return TENSOR_WORDS.get(t.property, TENSOR_WORDS["stiffness"])
144
+
145
+
146
+ def _mutual(t: TensorStatistics) -> tuple[str, str]:
147
+ """What the window tensors of ``t`` average, and the unit macroscopic loads."""
148
+ if t.property in TRANSPORT_TENSORS:
149
+ return "grad T_k . K grad T_l, the mutual dissipation", "gradients G_k"
150
+ return "eps_k : C : eps_l, the mutual energy density", "strains E_k"
151
+
152
+
153
+ def tensor_label(t: TensorStatistics) -> str:
154
+ """The label of the mean tensor of a boundary condition: ``stiffness (PBC)``."""
155
+ return f"{t.property} ({BC_LABELS.get(t.bc, t.bc)})" if t.bc else t.property
156
+
157
+
158
+ def tensor_tables(
159
+ t: TensorStatistics, options: StudyOptions | None = None
160
+ ) -> list[tuple[str, list[str], list[list[str]], str]]:
161
+ """The tables of the mean stiffness and compliance of a boundary condition, as
162
+ (title, header, rows, note): each component of ``Cbar`` and of ``S = Cbar^-1`` per
163
+ volume (mean +/- 2 D), then the RVE sizes of the components that have one (of a
164
+ conductivity and its resistivity likewise; per window size by the window method)."""
165
+ options = options or StudyOptions()
166
+ d = len(t.mean[0])
167
+ where = f"{BC_LABELS.get(t.bc, t.bc)}; " if t.bc else ""
168
+ heads = ["component", *[_edge(v, t.dimension) for v in t.volume]]
169
+ pairs = [(i, j) for i in range(d) for j in range(i, d)]
170
+ count = [t.samples, *[_samples(t, k) for k in range(len(t.volume))]]
171
+ one, many, inverse, inverses = _words(t)
172
+ what = (
173
+ f"Cbar: the mean of the apparent {many} of the realizations; D: the standard "
174
+ "deviation of each component."
175
+ )
176
+ if t.method == "windows":
177
+ mutual, loads = _mutual(t)
178
+ what = (
179
+ "Cbar: the mean of the tensors C of the windows of each size, C_kl the mean over "
180
+ f"a window of {mutual} of the solutions of the whole realization under its unit "
181
+ f"macroscopic {loads}; D: the standard deviation of each component over the "
182
+ "windows."
183
+ )
184
+ if t.tilings is not None:
185
+ what += f" {_TILINGS}"
186
+
187
+ def cells(mean, std, i, j):
188
+ out = []
189
+ for k in range(len(t.volume)):
190
+ m, dev = mean[k, i, j], std[k, i, j]
191
+ out.append(f"{_num(m)} +/- {_num(2 * dev, 2)}" if math.isfinite(dev) else _num(m))
192
+ return out
193
+
194
+ out = []
195
+ for letter, mean, std, title, note in (
196
+ (
197
+ "C",
198
+ t.mean,
199
+ t.std,
200
+ f"Mean {one} Cbar_ij +/- 2 D",
201
+ f"{what} Notation: {t.notation}.",
202
+ ),
203
+ (
204
+ "S",
205
+ t.compliance,
206
+ t.compliance_std,
207
+ f"{inverse.capitalize()} S_ij = Cbar^-1 +/- 2 D",
208
+ f"S: the inverse of the mean {one} (S Cbar = I), not the mean of the "
209
+ f"{inverses} of the {t.samples} (mean_compliance in rve_report.json); D: the "
210
+ f"standard deviation of each component of the {inverses} C^-1 of the "
211
+ f"{t.samples}.",
212
+ ),
213
+ ):
214
+ rows = [count] + [[f"{letter}{i + 1}{j + 1}", *cells(mean, std, i, j)] for i, j in pairs]
215
+ out.append((f"{title} ({where}{_short_notation(t)})", heads, rows, note))
216
+ eps, ns = options.relative_errors, options.n_realizations
217
+ rows = []
218
+ for name, a in t.components.items():
219
+ if not a.rve:
220
+ continue
221
+ edges = {(r["eps_rel"], r["n"]): r["edge"] for r in a.rve}
222
+ size = [_num(edges.get((float(e), int(k))), 4) for e in eps for k in ns]
223
+ rows.append([name, _num(a.reference_mean), _num(a.fit.gamma, 3), _num(a.fit.K, 3), *size])
224
+ if rows:
225
+ gamma = (
226
+ f"gamma = {options.gamma:.4g} imposed" if options.gamma is not None else "fitted gamma"
227
+ )
228
+ heads = ["component", "Zbar", "gamma", "K"]
229
+ heads += [f"edge, eps = {100 * e:g} %, n = {k}" for e in eps for k in ns]
230
+ note = (
231
+ f"D^2(V) = K V^-gamma fitted to each component of the {many} of the "
232
+ f"{t.samples} and of their {inverses} C^-1 (Zbar: their mean at the largest "
233
+ "volume); the edge of V_RVE = (4 K / (eps^2 Zbar^2 n))^(1/gamma). The components "
234
+ f"off the diagonal whose mean the {t.samples} of the largest volume do not "
235
+ f"distinguish from zero (Student's t test at {100 * t.level:g} %), as the "
236
+ "couplings that vanish on average, have none."
237
+ )
238
+ out.append((f"RVE sizes per component ({where}{gamma})", heads, rows, note))
239
+ return out
240
+
241
+
242
+ def _series_tables(report: StudyReport) -> list[tuple[str, list[str], list[list[str]], str]]:
243
+ """The tables of the series of a study (see the module)."""
244
+ vols = _volumes(report)
245
+ dimension = report.dimension
246
+ heads = ["series", *[_edge(v, dimension) for v in vols]]
247
+ out = []
248
+ rows = [
249
+ [series_label(a), *_per_volume(a, vols, lambda i, a=a: _samples(a.stats, i))]
250
+ for a in report.analyses
251
+ ]
252
+ title = "Windows per volume" if report.method == "windows" else "Realizations per volume"
253
+ shifted = any(a.stats.tilings is not None for a in report.analyses)
254
+ out.append((title, heads, rows, _TILINGS if shifted else ""))
255
+
256
+ def interval(a, i):
257
+ m, var = a.stats.mean[i], a.stats.variance[i]
258
+ if not math.isfinite(var):
259
+ return _num(m)
260
+ return f"{_num(m)} +/- {_num(2 * math.sqrt(var), 2)}"
261
+
262
+ rows = [
263
+ [series_label(a), *_per_volume(a, vols, lambda i, a=a: interval(a, i))]
264
+ for a in report.analyses
265
+ ]
266
+ out.append(("Mean values Zbar +/- 2 D_Z", heads, rows, ""))
267
+ if report.bounds:
268
+ bheads = ["property", "Voigt", "Reuss", "HS lower", "HS upper"]
269
+ brows = [
270
+ [p, *(_num(b.get(k)) for k in ("voigt", "reuss", "hs_lower", "hs_upper"))]
271
+ for p, b in report.bounds.items()
272
+ ]
273
+ out.append(("Bounds", bheads, brows, "Voigt/Reuss are the Wiener bounds in conduction."))
274
+ if report.discrepancy:
275
+ rows = []
276
+ for prop, drows in report.discrepancy.items():
277
+ by_v = {r["volume"]: r for r in drows}
278
+ rows.append(
279
+ [prop, *[_num(by_v[v]["discrepancy"], 3) if v in by_v else "" for v in vols]]
280
+ )
281
+ out.append(
282
+ (
283
+ "Discrepancy between boundary conditions D(Z) = (Zmax - Zmin) / Zmin",
284
+ ["property", *heads[1:]],
285
+ rows,
286
+ "Dirrenberger et al. (2014), eq. 69.",
287
+ )
288
+ )
289
+ iso = [a for a in report.analyses if a.isotropy is not None]
290
+ if iso:
291
+ rows = [
292
+ [series_label(a), *_per_volume(a, vols, lambda i, a=a: _num(a.isotropy[i], 2))]
293
+ for a in iso
294
+ ]
295
+ out.append(
296
+ (
297
+ "Statistical isotropy of the mean response",
298
+ heads,
299
+ rows,
300
+ "Criteria d_k, d_mu (eqs. 73-74) and (|Q2| + |Q3|) / |Q1| (eq. 72); "
301
+ "isotropy when << 1.",
302
+ )
303
+ )
304
+
305
+ def rel(a, i):
306
+ e = a.stats.relative_error()[i]
307
+ return f"{100 * e:.3g} %" if math.isfinite(e) else "-"
308
+
309
+ rows = [
310
+ [series_label(a), *_per_volume(a, vols, lambda i, a=a: rel(a, i))] for a in report.analyses
311
+ ]
312
+ out.append(
313
+ ("Relative error of the samples eps_rel = 2 D_Z(V) / (Zbar sqrt(n))", heads, rows, "")
314
+ )
315
+ fheads = [
316
+ "series",
317
+ "gamma",
318
+ f"{int(100 * report.options.level)} % interval",
319
+ "K",
320
+ "R^2",
321
+ "sizes",
322
+ ]
323
+ rows = []
324
+ for a in report.analyses:
325
+ f = a.free_fit
326
+ if f is None:
327
+ rows.append([series_label(a), "-", "-", "-", "-", "-"])
328
+ continue
329
+ lo, hi = f.gamma_interval(report.options.level)
330
+ boot = a.bootstrap if report.options.gamma is None else None
331
+ ci = f"[{_num(lo, 3)}, {_num(hi, 3)}]" if math.isfinite(lo) else "-"
332
+ if boot:
333
+ ci += f" (bootstrap [{_num(boot['gamma'][0], 3)}, {_num(boot['gamma'][1], 3)}])"
334
+ rows.append(
335
+ [series_label(a), _num(f.gamma, 3), ci, _num(f.K, 3), _num(f.r2, 3), str(f.n_points)]
336
+ )
337
+ rng = ""
338
+ if report.options.min_volume or report.options.max_volume:
339
+ lo = _edge(report.options.min_volume, dimension) if report.options.min_volume else "-"
340
+ hi = _edge(report.options.max_volume, dimension) if report.options.max_volume else "-"
341
+ rng = f"Fits on volumes in [{lo}, {hi}]."
342
+ out.append(("Scaling of the variance D_Z^2(V) = K V^-gamma (gamma fitted)", fheads, rows, rng))
343
+ gamma_txt = (
344
+ f"gamma = {report.options.gamma:.4g} imposed"
345
+ if report.options.gamma is not None
346
+ else "fitted gamma"
347
+ )
348
+ rheads = ["series", "K", "eps_rel", "n", "V_RVE", "edge"]
349
+ has_count = any("count" in r for a in report.analyses for r in a.rve)
350
+ has_ci = any("edge_ci" in r for a in report.analyses for r in a.rve)
351
+ if has_ci:
352
+ rheads.append(f"edge {int(100 * report.options.level)} % interval")
353
+ if has_count:
354
+ rheads.append("objects")
355
+ rows = []
356
+ for a in report.analyses:
357
+ for r in a.rve:
358
+ row = [
359
+ series_label(a),
360
+ _num(a.fit.K, 3),
361
+ f"{100 * r['eps_rel']:g} %",
362
+ str(r["n"]),
363
+ _num(r["volume"], 3),
364
+ _num(r["edge"], 4),
365
+ ]
366
+ if has_ci:
367
+ ci = r.get("edge_ci")
368
+ row.append(f"[{_num(ci[0], 3)}, {_num(ci[1], 3)}]" if ci else "-")
369
+ if has_count:
370
+ row.append(_num(r.get("count"), 3))
371
+ rows.append(row)
372
+ note = "Zbar is the mean at the largest volume (Dirrenberger et al. 2014, eq. 87)."
373
+ if dimension == 2:
374
+ note += " V_RVE is an area, its edge V_RVE^(1/2) the side of the square window."
375
+ out.append(
376
+ (f"RVE sizes V_RVE = (4 K / (eps^2 Zbar^2 n))^(1/gamma), {gamma_txt}", rheads, rows, note)
377
+ )
378
+ eps = report.options.relative_errors
379
+ nheads = ["series", "volume", *[f"n for eps = {100 * e:g} %" for e in eps]]
380
+ rows = []
381
+ for a in report.analyses:
382
+ for r in a.needed:
383
+ needed = [_count(r[f"eps={e:g}"]) for e in eps]
384
+ rows.append([series_label(a), _edge(r["volume"], dimension), *needed])
385
+ if rows:
386
+ out.append(("Realizations needed per volume", nheads, rows, ""))
387
+ return out
388
+
389
+
390
+ def markdown(report: StudyReport, title: str | None = None) -> str:
391
+ """The Markdown report of an RVE study: the point variance and integral range of each property,
392
+ then the tables of the study."""
393
+ lines = [title or f"# RVE report ({report.method} method)", ""]
394
+ for a in report.analyses:
395
+ if a.point_variance is not None and a.integral_range is not None:
396
+ lines.append(
397
+ f"{series_label(a)}: point variance D^2 = {_num(a.point_variance)}, "
398
+ f"A3* = {_num(a.integral_range)}"
399
+ )
400
+ if lines[-1] != "":
401
+ lines.append("")
402
+ for name, head, rows, note in tables(report):
403
+ lines += [
404
+ f"## {name}",
405
+ "",
406
+ "| " + " | ".join(head) + " |",
407
+ "|" + "|".join(["---"] + ["---:"] * (len(head) - 1)) + "|",
408
+ ]
409
+ lines += ["| " + " | ".join(r) + " |" for r in rows]
410
+ lines.append("")
411
+ if note:
412
+ lines += [note, ""]
413
+ return "\n".join(lines)
414
+
415
+
416
+ #: An exponent of the text of the tables: ^3, ^-1, ^-gamma, ^(1/gamma)
417
+ _EXPONENT = re.compile(r"\^(\([^()]*\)|-?\w+)")
418
+
419
+
420
+ def _tex(s: str) -> str:
421
+ s = (
422
+ s.replace("\\", r"\textbackslash{}")
423
+ .replace("_", r"\_")
424
+ .replace("%", r"\%")
425
+ .replace("+/-", r"$\pm$")
426
+ .replace("&", r"\&")
427
+ )
428
+ return _EXPONENT.sub(lambda m: f"$^{{{m[1]}}}$", s)
429
+
430
+
431
+ def latex(report: StudyReport) -> str:
432
+ """The tables in LaTeX (booktabs package)."""
433
+ parts = ["% RVE report written by morphoGen (needs \\usepackage{booktabs})", ""]
434
+ for name, head, rows, note in tables(report):
435
+ parts += [
436
+ r"\begin{table}[htbp]",
437
+ r"\centering",
438
+ f"\\caption{{{_tex(name)}}}",
439
+ r"\begin{tabular}{l" + "r" * (len(head) - 1) + "}",
440
+ r"\toprule",
441
+ " & ".join(_tex(h) for h in head) + r" \\",
442
+ r"\midrule",
443
+ ]
444
+ parts += [" & ".join(_tex(c) for c in r) + r" \\" for r in rows]
445
+ parts += [r"\bottomrule", r"\end{tabular}"]
446
+ if note:
447
+ parts.append(f"\\par\\smallskip{{\\footnotesize {_tex(note)}}}")
448
+ parts += [r"\end{table}", ""]
449
+ return "\n".join(parts)
450
+
451
+
452
+ def _measure_axis(dimension: int, windows: bool = False) -> str:
453
+ """The axis of the volumes V of the figures: of cubes, or the areas of the squares of a
454
+ planar image (``dimension`` 2); ``windows``, of the windows of the study."""
455
+ return ("window " if windows else "") + ("area V" if dimension == 2 else "volume V")
456
+
457
+
458
+ def plot(report: StudyReport, outdir: Path) -> list[Path]:
459
+ """Figures per property: variance, mean +/- 2 D_Z and RVE size (needs matplotlib),
460
+ against the volumes, or the areas of the squares of a planar image."""
461
+ try:
462
+ import matplotlib
463
+
464
+ matplotlib.use("Agg")
465
+ import matplotlib.pyplot as plt
466
+ except ImportError:
467
+ return []
468
+ outdir = Path(outdir)
469
+ files = []
470
+ by_prop: dict[str, list] = {}
471
+ for a in report.analyses:
472
+ by_prop.setdefault(a.series.property, []).append(a)
473
+ for prop, group in by_prop.items():
474
+ fig, ax = plt.subplots(figsize=(5.5, 4))
475
+ for a in group:
476
+ st = a.stats
477
+ ok = np.isfinite(st.variance) & (st.variance > 0)
478
+ if not ok.any():
479
+ continue
480
+ label = BC_LABELS.get(a.series.bc, a.series.bc) or "data"
481
+ (line,) = ax.loglog(st.volume[ok], st.variance[ok], "o", label=label)
482
+ for fit, style in ((a.free_fit, "--"), (a.fit if report.options.gamma else None, "-")):
483
+ if fit is None:
484
+ continue
485
+ vv = np.geomspace(st.volume[ok].min(), st.volume[ok].max(), 50)
486
+ ax.loglog(
487
+ vv,
488
+ fit.variance(vv),
489
+ style,
490
+ color=line.get_color(),
491
+ label=f"{label}: gamma = {fit.gamma:.3g}",
492
+ )
493
+ ax.set_xlabel(_measure_axis(report.dimension))
494
+ ax.set_ylabel(f"D^2(V) of {prop}")
495
+ if ax.get_legend_handles_labels()[0]:
496
+ ax.legend(fontsize=8)
497
+ fig.tight_layout()
498
+ path = outdir / f"rve_{prop}.png"
499
+ fig.savefig(path, dpi=130)
500
+ plt.close(fig)
501
+ files.append(path)
502
+ fig, ax = plt.subplots(figsize=(5.5, 4))
503
+ for a in group:
504
+ st = a.stats
505
+ err = 2.0 * np.sqrt(np.where(np.isfinite(st.variance), st.variance, 0.0))
506
+ ax.errorbar(
507
+ st.volume,
508
+ st.mean,
509
+ yerr=err,
510
+ fmt="o-",
511
+ capsize=3,
512
+ label=BC_LABELS.get(a.series.bc, a.series.bc) or prop,
513
+ )
514
+ for name, value in report.bounds.get(prop, {}).items():
515
+ if name in ("hs_upper", "voigt") and value > 0:
516
+ ax.axhline(value, ls=":", color="gray")
517
+ ax.annotate(
518
+ name.replace("_", " "),
519
+ (ax.get_xlim()[0], value),
520
+ fontsize=7,
521
+ va="bottom",
522
+ color="gray",
523
+ )
524
+ ax.set_xscale("log")
525
+ ax.set_xlabel(_measure_axis(report.dimension))
526
+ ax.set_ylabel(f"{prop}: mean +/- 2 D")
527
+ if ax.get_legend_handles_labels()[0]:
528
+ ax.legend(fontsize=8)
529
+ fig.tight_layout()
530
+ path = outdir / f"rve_{prop}_mean.png"
531
+ fig.savefig(path, dpi=130)
532
+ plt.close(fig)
533
+ files.append(path)
534
+ fits = [a for a in group if a.fit is not None and a.reference_mean != 0]
535
+ if fits:
536
+ fig, ax = plt.subplots(figsize=(5.5, 4))
537
+ eps = np.geomspace(0.005, 0.2, 40)
538
+ dimension = report.dimension # the edge of a cube, or of a square (its area V)
539
+ for a in fits:
540
+ for k in report.options.n_realizations:
541
+ edge = a.fit.rve_volume(eps, a.reference_mean, k) ** (1.0 / dimension)
542
+ lab = BC_LABELS.get(a.series.bc, a.series.bc) or prop
543
+ ax.loglog(100 * eps, edge, label=f"{lab}, n = {k}")
544
+ ax.set_xlabel("relative error eps_rel (%)")
545
+ ax.set_ylabel(f"RVE edge V_RVE^(1/{dimension})")
546
+ if ax.get_legend_handles_labels()[0]:
547
+ ax.legend(fontsize=8)
548
+ fig.tight_layout()
549
+ path = outdir / f"rve_{prop}_size.png"
550
+ fig.savefig(path, dpi=130)
551
+ plt.close(fig)
552
+ files.append(path)
553
+ for t in report.tensors:
554
+ files.append(_tensor_figure(plt, t, outdir))
555
+ return files
556
+
557
+
558
+ def _tensor_figure(plt, t: TensorStatistics, outdir: Path) -> Path:
559
+ """The convergence of the mean stiffness and compliance of a boundary condition with
560
+ the volume (the area of the squares of a planar image): the components of ``Cbar`` and
561
+ of ``S = Cbar^-1`` (+/- 2 D) that the realizations (windows) distinguish from zero, and
562
+ their relative scatter ``D / |Zbar|`` with the fitted laws (dashed); of a conductivity
563
+ and its resistivity likewise."""
564
+ fig, axes = plt.subplots(2, 2, figsize=(10, 7.5), sharex=True)
565
+ one, _, inverse, _ = _words(t)
566
+ tensors = (("C", t.mean, t.std, f"{one} Cbar"), ("S", t.compliance, t.compliance_std,
567
+ f"{inverse} S = Cbar^-1")) # fmt: skip
568
+ for col, (letter, mean, std, what) in enumerate(tensors):
569
+ top, bottom = axes[0, col], axes[1, col]
570
+ names = [n for n in t.components if n[0] == letter and t.significant(n)]
571
+ for name in names:
572
+ i, j = t.index(name)
573
+ bars = top.errorbar(t.volume, mean[:, i, j], yerr=2.0 * np.nan_to_num(std[:, i, j]),
574
+ fmt="o-", ms=3, capsize=2, label=name) # fmt: skip
575
+ a = t.components[name]
576
+ st, ref = a.stats, abs(a.reference_mean)
577
+ ok = np.isfinite(st.variance) & (st.variance > 0)
578
+ if not ok.any() or ref == 0:
579
+ continue
580
+ color = bars[0].get_color()
581
+ bottom.loglog(st.volume[ok], np.sqrt(st.variance[ok]) / ref, "o", ms=3, color=color)
582
+ if a.fit is not None:
583
+ vv = np.geomspace(st.volume[ok].min(), st.volume[ok].max(), 50)
584
+ bottom.loglog(vv, np.sqrt(a.fit.variance(vv)) / ref, "--", lw=1, color=color)
585
+ top.set_xscale("log")
586
+ top.set_title(f"{what}: mean +/- 2 D", fontsize=9)
587
+ bottom.set_xlabel(_measure_axis(t.dimension, t.method == "windows"))
588
+ bottom.set_ylabel(f"D / |Zbar| of the components of {letter}")
589
+ if names:
590
+ top.legend(fontsize=7, ncol=3)
591
+ fig.suptitle(f"{tensor_label(t)}: {_short_notation(t)}", fontsize=10)
592
+ fig.tight_layout()
593
+ path = outdir / f"rve_{t.key.replace('.', '_')}.png"
594
+ fig.savefig(path, dpi=130)
595
+ plt.close(fig)
596
+ return path
597
+
598
+
599
+ def write(
600
+ report: StudyReport, outdir, *, stem: str = "rve_report", figures: bool = True
601
+ ) -> list[Path]:
602
+ """Write ``<stem>.json``, ``.md`` and ``.tex`` (and the figures) in ``outdir``, and
603
+ ``rve_<tensor>.csv`` (the mean stiffness and compliance per boundary condition and
604
+ volume, :meth:`~morphogen.rve.study.TensorStatistics.volume_rows`) when the study has
605
+ them."""
606
+ from morphogen.io.tables import write_table
607
+
608
+ outdir = Path(outdir)
609
+ outdir.mkdir(parents=True, exist_ok=True)
610
+ files = []
611
+ path = outdir / f"{stem}.json"
612
+ path.write_text(json.dumps(to_jsonable(report.to_dict()), indent=2) + "\n", encoding="utf-8")
613
+ files.append(path)
614
+ by_tensor: dict[str, list[dict]] = {}
615
+ for t in report.tensors:
616
+ by_tensor.setdefault(t.property, []).extend(t.volume_rows())
617
+ for name, rows in by_tensor.items():
618
+ files.append(write_table(outdir / f"rve_{name}.csv", rows))
619
+ path = outdir / f"{stem}.md"
620
+ path.write_text(markdown(report), encoding="utf-8")
621
+ files.append(path)
622
+ path = outdir / f"{stem}.tex"
623
+ path.write_text(latex(report), encoding="utf-8")
624
+ files.append(path)
625
+ if figures:
626
+ files += plot(report, outdir)
627
+ return files