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,2034 @@
1
+ """Percolation: the forest-fire algorithm, the thresholds of families of microstructures and
2
+ their finite-size scaling, the anisotropy of percolation: along directions of one image
3
+ and of a family, in 2-D and 3-D, the rigidity threshold, where the elastic moduli by the
4
+ FFT solvers vanish, and the critical exponents of the conductivity and of the elastic
5
+ moduli at the threshold.
6
+
7
+ A planar image (one voxel along z, the 2-D images of morphoGen) percolates in its plane,
8
+ along x or y, through 4 (``connectivity`` 4, or 6: through edges) or 8 (8, 18 or 26: and
9
+ corners) neighbours."""
10
+
11
+ from __future__ import annotations
12
+
13
+ from collections.abc import Callable
14
+ from dataclasses import dataclass, field, fields, replace
15
+
16
+ import numpy as np
17
+ from numba import njit
18
+ from scipy.optimize import minimize_scalar
19
+
20
+ from morphogen.analysis.basic import as_array
21
+ from morphogen.analysis.connectivity import _structure, connected_components, wrapping
22
+ from morphogen.analysis.surface import DIRECTIONS_13
23
+ from morphogen.domain import Grid
24
+ from morphogen.image import VoxelImage
25
+ from morphogen.seeding import SeedLike
26
+
27
+ _CRITERIA = ("x", "y", "z", "any", "all")
28
+ _METHODS = ("labels", "fire")
29
+ _CONNECTIVITIES = (4, 6, 8, 18, 26)
30
+ #: The directions of the square lattice: its axes and the diagonals of its squares
31
+ _LATTICE_2D = ((1, 0, 0), (0, 1, 0), (1, 1, 0), (1, -1, 0))
32
+ #: The exponents of the correlation length of random percolation in 2-D (exact) and 3-D
33
+ NU_2D, NU_3D = 4.0 / 3.0, 0.8765
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class Fire:
38
+ """Forest fire lit on a face of an image (:func:`burn`).
39
+
40
+ ``percolates`` tells whether the fire reaches the opposite face, at the step ``time``
41
+ (the chemical distance between the faces; ``None`` when it does not); ``front[t]`` is
42
+ the number of voxels that catch fire at step ``t``, from the face (``front[0]``) to the
43
+ step at which the opposite face is reached, or to the extinction of the fire when the
44
+ whole clusters were burnt (``full``); ``times``, then, the step at which each voxel
45
+ caught fire (-1: unburnt, outside the phase or in a cluster not lit), else ``None``.
46
+ """
47
+
48
+ percolates: bool
49
+ time: int | None
50
+ front: np.ndarray
51
+ times: np.ndarray | None = field(default=None, repr=False)
52
+
53
+
54
+ @njit(cache=True)
55
+ def _burn(times, nx, ny, nz, offsets, axis, wx, wy, wz, full, queue):
56
+ """Breadth-first burning of a C-ordered ``(nx, ny, nz)`` image, raveled in ``times`` (-1
57
+ in the phase, -2 outside), from its face at 0 along ``axis``, through the neighbours
58
+ ``offsets`` (in the plane when ``nz == 1``), wrapping along the directions ``wx``,
59
+ ``wy``, ``wz``: ``times`` receives
60
+ the step at which each voxel catches fire and ``queue`` the voxels in the order they do,
61
+ step by step; the burning stops at the end of the step at which the face at the far end
62
+ is reached, unless ``full``. Returns the number of voxels burnt and that step (-1: not
63
+ reached)."""
64
+ nyz = ny * nz
65
+ last = nx - 1 if axis == 0 else (ny - 1 if axis == 1 else nz - 1)
66
+ shifts = offsets[:, 0] * nyz + offsets[:, 1] * nz + offsets[:, 2] # flat, inside the box
67
+ tail = 0
68
+ for i in range(1 if axis == 0 else nx):
69
+ for j in range(1 if axis == 1 else ny):
70
+ for k in range(1 if axis == 2 else nz):
71
+ q = i * nyz + j * nz + k
72
+ if times[q] == -1:
73
+ times[q] = 0
74
+ queue[tail] = q
75
+ tail += 1
76
+ reached = 0 if tail > 0 and last == 0 else -1
77
+ head, step = 0, 0
78
+ while head < tail and (full or reached < 0):
79
+ end = tail # the front of this step: queue[head:end]
80
+ while head < end:
81
+ q = queue[head]
82
+ head += 1
83
+ i = q // nyz
84
+ j = (q - i * nyz) // nz
85
+ k = q - i * nyz - j * nz
86
+ if 0 < i < nx - 1 and 0 < j < ny - 1 and (nz == 1 or 0 < k < nz - 1): # no face
87
+ c = i if axis == 0 else (j if axis == 1 else k)
88
+ for m in range(shifts.shape[0]):
89
+ p = q + shifts[m]
90
+ if times[p] == -1:
91
+ times[p] = step + 1
92
+ queue[tail] = p
93
+ tail += 1
94
+ if reached < 0 and c + offsets[m, axis] == last:
95
+ reached = step + 1
96
+ continue
97
+ for m in range(offsets.shape[0]):
98
+ ii, jj, kk = i + offsets[m, 0], j + offsets[m, 1], k + offsets[m, 2]
99
+ if ii < 0 or ii >= nx:
100
+ if not wx:
101
+ continue
102
+ ii = ii + nx if ii < 0 else ii - nx
103
+ if jj < 0 or jj >= ny:
104
+ if not wy:
105
+ continue
106
+ jj = jj + ny if jj < 0 else jj - ny
107
+ if kk < 0 or kk >= nz:
108
+ if not wz:
109
+ continue
110
+ kk = kk + nz if kk < 0 else kk - nz
111
+ p = ii * nyz + jj * nz + kk
112
+ if times[p] == -1:
113
+ times[p] = step + 1
114
+ queue[tail] = p
115
+ tail += 1
116
+ if reached < 0 and (ii if axis == 0 else (jj if axis == 1 else kk)) == last:
117
+ reached = step + 1
118
+ step += 1
119
+ return tail, reached
120
+
121
+
122
+ def _check_connectivity(connectivity) -> None:
123
+ if connectivity not in _CONNECTIVITIES:
124
+ raise ValueError("connectivity: 6, 18 or 26 (4 or 8 for a planar image)")
125
+
126
+
127
+ def _in_space(connectivity: int, planar: bool) -> int:
128
+ """The neighbours of the 3-D lattice that ``connectivity`` stands for: on a planar image
129
+ those of 6 (4) and 18 (8) in its plane; 4 and 8 refused on 3-D images."""
130
+ _check_connectivity(connectivity)
131
+ if connectivity in (4, 8):
132
+ if not planar:
133
+ raise ValueError(
134
+ f"connectivity {connectivity}: a planar image (one voxel along z); 6, 18 or 26 "
135
+ "in 3-D"
136
+ )
137
+ return 6 if connectivity == 4 else 18
138
+ return connectivity
139
+
140
+
141
+ def _offsets(connectivity: int, planar: bool = False) -> np.ndarray:
142
+ """The offsets of the ``connectivity`` neighbours of a voxel (those in the plane of a
143
+ planar image: 4 for 4 and 6, 8 for 8, 18 and 26)."""
144
+ offsets = np.argwhere(_structure(_in_space(connectivity, planar))) - 1
145
+ keep = np.any(offsets != 0, axis=1) & ((offsets[:, 2] == 0) | (not planar))
146
+ return np.ascontiguousarray(offsets[keep], dtype=np.int64)
147
+
148
+
149
+ def _mask(image, phase) -> np.ndarray:
150
+ mask = np.ascontiguousarray(as_array(image) == phase)
151
+ if mask.ndim != 3:
152
+ raise ValueError(
153
+ f"image: expected a 3-D image ((nx, ny, 1) for a 2-D one), got the shape {mask.shape}"
154
+ )
155
+ return mask
156
+
157
+
158
+ def _axes(mask: np.ndarray) -> str:
159
+ """The axes along which an image percolates: x and y in the plane of a planar image."""
160
+ return "xy" if mask.shape[2] == 1 else "xyz"
161
+
162
+
163
+ def _spacing(image) -> np.ndarray:
164
+ return np.asarray(image.spacing if isinstance(image, VoxelImage) else (1.0, 1.0, 1.0), float)
165
+
166
+
167
+ def _fire(mask: np.ndarray, axis: int, offsets: np.ndarray, periodic, full) -> Fire:
168
+ """The forest fire of the C-ordered boolean ``mask`` along the axis number ``axis``."""
169
+ dtype = np.int32 if mask.size < 2**31 else np.int64
170
+ times = np.subtract(mask.ravel(), 2, dtype=dtype) # -1 in the phase, -2 outside
171
+ queue = np.empty(int(np.count_nonzero(mask)), dtype=dtype)
172
+ wrap = [bool(periodic) and a != axis for a in range(3)]
173
+ burnt, reached = _burn(times, *mask.shape, offsets, axis, *wrap, bool(full), queue)
174
+ return Fire(
175
+ percolates=bool(reached >= 0),
176
+ time=int(reached) if reached >= 0 else None,
177
+ front=np.bincount(times[queue[:burnt]]), # the steps of the voxels, in burning order
178
+ times=np.maximum(times, -1).reshape(mask.shape) if full else None,
179
+ )
180
+
181
+
182
+ def burn(
183
+ image,
184
+ phase: int = 1,
185
+ axis: str = "x",
186
+ *,
187
+ connectivity: int = 6,
188
+ periodic: bool | None = None,
189
+ full: bool = False,
190
+ ) -> Fire:
191
+ """The forest fire of the phase ``phase`` of a 3-D image along ``axis`` (the burning
192
+ algorithm of Herrmann, Hong & Stanley 1984): the phase voxels of the face at 0 normal
193
+ to the axis catch fire at time 0, and at each step the fire spreads to the unburnt
194
+ phase voxels among the ``connectivity`` neighbours (6: faces; 18: and edges; 26: and
195
+ corners) of those burning, the transverse directions wrapping around a periodic image
196
+ (``periodic``, by default that of the image), never the axis. The phase percolates
197
+ along the axis when the fire reaches the opposite face, at the step ``time``: the
198
+ chemical distance between the faces, the number of steps of the shortest path through
199
+ the phase (``n - 1`` for a straight channel ``n`` voxels long). The breadth-first
200
+ burning, compiled, queues each voxel once and stops at the end of that step, unless
201
+ ``full`` asks for the whole clusters lit on the face and their burning times; it costs
202
+ the voxels burnt, where :func:`~morphogen.analysis.connectivity.connected_components`
203
+ labels the whole image, and decides as its flags ``percolating`` on open boundaries.
204
+ A planar image (one voxel along z) burns in its plane, along x or y, through 4
205
+ (``connectivity`` 4 or 6) or 8 (8, 18 or 26) neighbours; :func:`burn_along` burns along
206
+ any direction.
207
+ """
208
+ mask = _mask(image, phase)
209
+ if axis not in _axes(mask):
210
+ raise ValueError(f"axis: x, y or z (x or y for a planar image), got {axis!r}")
211
+ offsets = _offsets(connectivity, mask.shape[2] == 1)
212
+ if periodic is None:
213
+ periodic = image.periodic if isinstance(image, VoxelImage) else False
214
+ return _fire(mask, "xyz".index(axis), offsets, periodic, full)
215
+
216
+
217
+ @dataclass(frozen=True)
218
+ class PercolationThreshold:
219
+ """Estimate of a percolation threshold.
220
+
221
+ ``threshold`` is the middle of ``bracket``, the last interval of fractions at whose ends
222
+ the percolation probability lies on either side of 1/2; ``fractions`` are the fractions
223
+ tried, in increasing order, and ``probabilities`` the fractions of the ``realizations``
224
+ images that percolate at each.
225
+ """
226
+
227
+ threshold: float
228
+ bracket: tuple[float, float]
229
+ fractions: np.ndarray
230
+ probabilities: np.ndarray
231
+ realizations: int
232
+
233
+
234
+ def _percolates(image, phase, axis, connectivity, periodic, method="labels") -> bool:
235
+ if periodic is None:
236
+ periodic = image.periodic if isinstance(image, VoxelImage) else False
237
+ mask = _mask(image, phase)
238
+ axes, planar = _axes(mask), mask.shape[2] == 1
239
+ if axis not in (*axes, "any", "all"):
240
+ raise ValueError(f"axis: x, y, any or all for a planar image, got {axis!r}")
241
+ names = axes if axis in ("any", "all") else axis
242
+ if method == "fire": # face to face along each axis asked, the others wrapping if periodic
243
+ offsets = _offsets(connectivity, planar)
244
+ burns = (_fire(mask, "xyz".index(a), offsets, periodic, False).percolates for a in names)
245
+ return all(burns) if axis == "all" else any(burns)
246
+ connectivity = _in_space(connectivity, planar) # one voxel thick: the same neighbours
247
+ if periodic:
248
+ flags = wrapping(mask, 1, connectivity=connectivity)
249
+ else:
250
+ flags = connected_components(mask, 1, connectivity=connectivity).percolating
251
+ burns = [flags[a] for a in names] # not z in a plane, joined and wrapped trivially
252
+ return all(burns) if axis == "all" else any(burns)
253
+
254
+
255
+ def _bisection(lower, upper, tol, realizations, seed) -> list[np.random.SeedSequence]:
256
+ """The bounds, the tolerance and the number of realizations of a bisection checked, and
257
+ the seeds of the realizations: ``SeedSequence(entropy, spawn_key=(..., i))``."""
258
+ if not 0.0 <= lower < upper <= 1.0:
259
+ raise ValueError(f"bounds: expected 0 <= lower < upper <= 1, got {lower!r}, {upper!r}")
260
+ if not tol > 0.0:
261
+ raise ValueError(f"tol: expected a positive tolerance, got {tol!r}")
262
+ if isinstance(realizations, bool) or int(realizations) != realizations or realizations < 1:
263
+ raise ValueError(f"realizations: expected a positive integer, got {realizations!r}")
264
+ if isinstance(seed, np.random.Generator):
265
+ seed = int(seed.integers(2**63))
266
+ base = seed if isinstance(seed, np.random.SeedSequence) else np.random.SeedSequence(seed)
267
+ return [
268
+ np.random.SeedSequence(base.entropy, spawn_key=(*base.spawn_key, i))
269
+ for i in range(int(realizations))
270
+ ]
271
+
272
+
273
+ def percolation_threshold(
274
+ generate: Callable[[float, np.random.Generator], object],
275
+ lower: float = 0.0,
276
+ upper: float = 1.0,
277
+ *,
278
+ phase: int = 1,
279
+ axis: str = "x",
280
+ connectivity: int = 6,
281
+ periodic: bool | None = None,
282
+ method: str = "labels",
283
+ realizations: int = 9,
284
+ tol: float = 0.005,
285
+ seed: SeedLike = None,
286
+ ) -> PercolationThreshold:
287
+ """Percolation threshold of a family of microstructures: the fraction at which the
288
+ probability that the phase ``phase`` of ``generate(fraction, rng)`` percolates crosses 1/2.
289
+
290
+ ``generate`` returns a 3-D image (a :class:`~morphogen.image.VoxelImage`, or a boolean
291
+ or label array; one voxel along z for a 2-D one, percolating along x or y). The
292
+ probability is the fraction of ``realizations`` images that percolate; realization ``i``
293
+ gets a generator built from the same seed at every fraction (common random numbers),
294
+ independent of the other realizations and reproducible from
295
+ ``seed`` (an integer, a seed sequence, a generator, or ``None`` for fresh entropy), so
296
+ that a family growing with the fraction for a given stream, such as
297
+ ``rng.random(shape) < fraction``, percolates from a threshold of its own in each
298
+ realization and the estimate is the median of these thresholds (with an even number of
299
+ realizations a probability of exactly 1/2 counts as percolating). The probabilities at
300
+ ``lower`` and ``upper`` must lie on either side of 1/2, in either order (a phase that
301
+ stops percolating as the fraction grows); the bracket is halved until it is narrower
302
+ than ``tol`` and the threshold is its middle. The estimate carries the finite-size shift
303
+ of the criterion and the spread of the realizations' thresholds, both of order
304
+ ``L**(-1/nu)`` (``nu`` about 0.88 in 3-D, 4/3 in 2-D) for images ``L`` voxels across,
305
+ the spread divided by the square root of ``realizations``.
306
+
307
+ The phase percolates along ``axis`` (``"x"``, ``"y"``, ``"z"``, ``"any"`` or ``"all"``
308
+ of them; x and y in 2-D) through its ``connectivity`` neighbours (6: faces; 18: and
309
+ edges; 26: and corners; 4 or 8 in 2-D) when a component joins the two faces normal to
310
+ the axis inside the box, as in
311
+ :func:`~morphogen.analysis.connectivity.connected_components`, or, on periodic images
312
+ (``periodic``, by default that of each image), when a component wraps around the box
313
+ along the axis: a cycle of neighbours through the faces winds around it, so that the
314
+ tiled component is an infinite cluster. For instance, for the spheres of a Boolean
315
+ model, whose continuum threshold is 0.2895 (0.27 on these images, 64 voxels across a
316
+ periodic box 16 radii across, where spheres closer than about a voxel touch)::
317
+
318
+ from morphogen.domain import Domain
319
+ from morphogen.models import BooleanSpheres
320
+
321
+ domain = Domain(size=16.0, periodic=True)
322
+
323
+ def spheres(fraction, rng):
324
+ model = BooleanSpheres(radius=1.0, volume_fraction=fraction)
325
+ return model.generate(domain, seed=rng).voxelize(64)
326
+
327
+ result = percolation_threshold(spheres, 0.15, 0.45, seed=0)
328
+
329
+ With ``method="fire"`` the phase percolates along the axis when the forest fire of
330
+ :func:`burn`, lit on the face at 0, reaches the opposite face (along each axis for
331
+ ``"any"`` and ``"all"``): face to face, through the transverse faces of a periodic image
332
+ but not those normal to the axis, a cluster crossing the slab that the image tiles
333
+ transversally. The labels (``method="labels"``, the default) decide alike on open
334
+ boundaries; on periodic images their wrapping implies it (the lift of a cycle winding
335
+ around the box along the axis crosses it from face to face) but not conversely (a
336
+ staircase joins the faces without wrapping), so that the fire percolates in at least as
337
+ many images and its estimate lies at or below theirs. The fire stops at the opposite
338
+ face and burns only the clusters lit on the first, where the labels label the whole
339
+ image.
340
+ """
341
+ if axis not in _CRITERIA:
342
+ raise ValueError(f"axis: one of {', '.join(_CRITERIA)}, got {axis!r}")
343
+ _check_connectivity(connectivity)
344
+ if method not in _METHODS:
345
+ raise ValueError(f"method: one of {', '.join(_METHODS)}, got {method!r}")
346
+ seeds = _bisection(lower, upper, tol, realizations, seed)
347
+
348
+ def probability(fraction: float) -> float:
349
+ hits = sum(
350
+ _percolates(
351
+ generate(fraction, np.random.default_rng(s)),
352
+ phase,
353
+ axis,
354
+ connectivity,
355
+ periodic,
356
+ method,
357
+ )
358
+ for s in seeds
359
+ )
360
+ return hits / len(seeds)
361
+
362
+ return _bisect(probability, lower, upper, tol, len(seeds))
363
+
364
+
365
+ def _bisect(probability, lower, upper, tol, realizations, what="percolation", rising=None):
366
+ """The bisection of :func:`percolation_threshold`: the bracket in which ``probability``
367
+ of the fraction crosses 1/2 between ``lower`` and ``upper`` (rising or falling; 1/2
368
+ counted above), halved down to ``tol`` or to the resolution of the fractions. With the
369
+ direction known (``rising``), the bounds are tried last, and only those that the
370
+ bracket reaches (the same bracket, for a monotone probability)."""
371
+ tried: dict[float, float] = {}
372
+
373
+ def above(fraction: float) -> bool:
374
+ tried[fraction] = probability(fraction)
375
+ return tried[fraction] >= 0.5
376
+
377
+ lo, hi = float(lower), float(upper)
378
+ if rising is None:
379
+ rising = above(hi)
380
+ if above(lo) == rising:
381
+ raise ValueError(
382
+ f"the {what} probability does not cross 1/2 between {lo:g} and {hi:g} "
383
+ f"({tried[lo]:g} and {tried[hi]:g})"
384
+ )
385
+ while hi - lo > tol:
386
+ mid = 0.5 * (lo + hi)
387
+ if not lo < mid < hi: # the floating-point resolution of the fractions
388
+ break
389
+ if above(mid) == rising:
390
+ hi = mid
391
+ else:
392
+ lo = mid
393
+ for end, side in ((lo, not rising), (hi, rising)):
394
+ if end not in tried and above(end) != side:
395
+ raise ValueError(
396
+ f"the {what} probability does not cross 1/2 between {lower:g} and "
397
+ f"{upper:g} ({tried[end]:g} at {end:g})"
398
+ )
399
+ fractions = np.array(sorted(tried))
400
+ return PercolationThreshold(
401
+ threshold=0.5 * (lo + hi),
402
+ bracket=(lo, hi),
403
+ fractions=fractions,
404
+ probabilities=np.array([tried[f] for f in fractions]),
405
+ realizations=realizations,
406
+ )
407
+
408
+
409
+ @dataclass(frozen=True)
410
+ class PercolationScaling:
411
+ """Finite-size scaling of a percolation threshold (:func:`percolation_scaling`).
412
+
413
+ ``thresholds[k]`` is the threshold of the boxes ``sizes[k]`` voxels across, the middle
414
+ of ``brackets[k]`` (``results[k]``: its :class:`PercolationThreshold`); ``threshold``
415
+ is that of the infinite medium, extrapolated by the fit ``thresholds = threshold +
416
+ amplitude * sizes**(-1/nu)``, with the standard error ``stderr``; ``nu`` is the exponent
417
+ given or, with its standard error ``nu_stderr`` (else ``None``), fitted; ``residuals``
418
+ are the thresholds minus the fit.
419
+ """
420
+
421
+ sizes: np.ndarray
422
+ thresholds: np.ndarray
423
+ brackets: np.ndarray
424
+ threshold: float
425
+ stderr: float
426
+ amplitude: float
427
+ nu: float
428
+ nu_stderr: float | None
429
+ residuals: np.ndarray
430
+ results: tuple[PercolationThreshold, ...] = field(default=(), repr=False)
431
+
432
+
433
+ def _scaling_fit(sizes, thresholds, widths, nu, fit_nu):
434
+ """Least squares of ``thresholds = p_c + a * sizes**(-theta)`` weighted by
435
+ ``sizes**(2/nu)``, ``theta`` being ``1/nu`` or (``fit_nu``) fitted too: ``p_c``, ``a``,
436
+ ``theta``, the residuals and the standard errors of the three, from the residuals and
437
+ from the widths of the brackets (a threshold uniform in its own: variance width**2/12),
438
+ linearized about the fit."""
439
+ logs = np.log(sizes)
440
+ root = sizes ** (1.0 / nu) # the square roots of the weights
441
+
442
+ def linear(theta):
443
+ design = np.column_stack([np.ones_like(logs), np.exp(-theta * logs)])
444
+ return np.linalg.lstsq(root[:, None] * design, root * thresholds, rcond=None)[0], design
445
+
446
+ def cost(theta):
447
+ beta, design = linear(theta)
448
+ return float(np.sum((root * (thresholds - design @ beta)) ** 2))
449
+
450
+ theta = 1.0 / nu
451
+ if fit_nu: # p_c and a eliminated: 1/nu scanned over [0.2, 5], refined about the best
452
+ grid = np.geomspace(0.2, 5.0, 97)
453
+ k = int(np.argmin([cost(t) for t in grid]))
454
+ bounds = (grid[max(k - 1, 0)], grid[min(k + 1, len(grid) - 1)])
455
+ best = minimize_scalar(cost, bounds=bounds, method="bounded", options={"xatol": 1e-12})
456
+ theta = float(best.x)
457
+ (pc, a), design = linear(theta)
458
+ residuals = thresholds - design @ (pc, a)
459
+ jacobian = np.column_stack([design, -a * design[:, 1] * logs]) if fit_nu else design
460
+ weighted = root[:, None] * jacobian
461
+ inverse = np.linalg.pinv(weighted.T @ weighted)
462
+ gain = inverse @ (weighted.T * root) # the derivatives of the parameters by the thresholds
463
+ scatter = np.sum((root * residuals) ** 2) / (len(sizes) - jacobian.shape[1])
464
+ errors = np.sqrt(scatter * np.diag(inverse) + gain**2 @ (widths**2 / 12.0))
465
+ return float(pc), float(a), theta, residuals, errors
466
+
467
+
468
+ def _check_sizes(sizes, need: int, fitted: str) -> np.ndarray:
469
+ """The distinct box sizes of ``sizes`` (positive integers, at least ``need``), sorted."""
470
+ values = np.atleast_1d(np.asarray(sizes))
471
+ if (
472
+ values.ndim != 1
473
+ or values.dtype.kind not in "iuf"
474
+ or not np.all(np.isfinite(values))
475
+ or np.any(values != np.round(values))
476
+ or np.any(values < 1)
477
+ ):
478
+ raise ValueError(f"sizes: expected positive integers, got {sizes!r}")
479
+ values = np.unique(values.astype(np.int64))
480
+ if len(values) < need:
481
+ raise ValueError(
482
+ f"sizes: at least {need} distinct sizes to fit {fitted} with an error, got "
483
+ f"{len(values)}"
484
+ )
485
+ return values
486
+
487
+
488
+ def _base_seed(seed: SeedLike) -> np.random.SeedSequence:
489
+ """The seed sequence of ``seed`` (an integer, a seed sequence, a generator or None)."""
490
+ if isinstance(seed, np.random.Generator):
491
+ seed = int(seed.integers(2**63))
492
+ return seed if isinstance(seed, np.random.SeedSequence) else np.random.SeedSequence(seed)
493
+
494
+
495
+ def percolation_scaling(
496
+ generate: Callable[[float, np.random.Generator, int], object],
497
+ sizes,
498
+ lower: float = 0.0,
499
+ upper: float = 1.0,
500
+ *,
501
+ nu: float | None = None,
502
+ fit_nu: bool = False,
503
+ phase: int = 1,
504
+ axis: str = "x",
505
+ connectivity: int = 6,
506
+ periodic: bool | None = None,
507
+ method: str = "labels",
508
+ realizations: int = 9,
509
+ tol: float = 0.005,
510
+ seed: SeedLike = None,
511
+ ) -> PercolationScaling:
512
+ """Finite-size scaling of the percolation threshold of a family of microstructures: the
513
+ thresholds p½(L) of :func:`percolation_threshold` in boxes of each of the ``sizes`` L,
514
+ ``generate(fraction, rng, size)`` returning an image ``size`` voxels per edge,
515
+ extrapolated to the infinite medium.
516
+
517
+ Near the threshold p_c of the infinite medium, the correlation length diverging as
518
+ ``|p - p_c|**(-nu)``, the probability that the phase of a box L voxels across
519
+ percolates depends on the fraction p through ``(p - p_c) * L**(1/nu)`` only (Stauffer &
520
+ Aharony 1994, ch. 4): it crosses 1/2 at ``p½(L) = p_c + a * L**(-1/nu)``, the amplitude
521
+ ``a`` set by the criterion, the shape of the box and its boundaries (positive for the
522
+ faces normal to one axis of an open cube, joined at p_c with a probability below 1/2),
523
+ and the thresholds of the realizations spread over a width of the same order. With
524
+ common random numbers a family growing with the fraction percolates from a threshold of
525
+ its own in each realization, and p½(L) is the median of these thresholds (the lower
526
+ median for an even number of realizations): it scatters from seed to seed by about
527
+ ``sqrt(pi/2) = 1.25`` times their spread over ``sqrt(realizations)``, so that the shift
528
+ and the scatter both shrink as ``L**(-1/nu)``, the scatter also as
529
+ ``1/sqrt(realizations)``. ``p_c`` and ``a`` (and ``nu``, from the value given, with
530
+ ``fit_nu``) are fitted by least squares weighted by ``L**(2/nu)``, the inverse variance
531
+ of p½; the variance of ``p_c`` adds that of the fit, from its residuals, and that of the
532
+ bisection, each p½ uniform in its bracket (variance ``width**2 / 12``). The
533
+ extrapolation removes the shift but amplifies the scatter (the intercept of a line
534
+ through points scattered as their abscissae ``L**(-1/nu)``): it improves on the largest
535
+ box where the shift there exceeds the scatter. For the sites of the cubic lattice (by
536
+ the fire, through faces, from 16 to 48 voxels across, ``tol=0.002``), the faces normal
537
+ to the three axes of an open cube are joined at p_c + 0.008 on 48 voxels, and 9, 25
538
+ and 99 realizations extrapolate to p_c within 0.0034, 0.0022 and 0.0015 (the scatter
539
+ over seeds, matched by ``stderr``); those normal to one axis are joined at
540
+ p_c + 0.0036, extrapolated within 0.0020 by 49 realizations. Four such sizes leave
541
+ ``nu`` undetermined (1.0 +/- 1 with ``fit_nu``) and ``p_c`` then within 0.01 to 0.03
542
+ only.
543
+
544
+ ``nu`` is by default the exponent of random percolation, ``0.8765`` in 3-D (0.8765(16),
545
+ Ballesteros et al. 1999, with p_c = 0.3116081(7) for the sites of the cubic lattice;
546
+ 0.88 in Stauffer & Aharony 1994) and ``4/3`` in 2-D (exact: den Nijs 1979, Nienhuis
547
+ 1982) for planar images (one voxel along z), universal: that of the lattices and of the
548
+ continuum percolation of overlapping objects of a finite range. In 2-D a square is
549
+ crossed at p_c with the probability 1/2 (by duality; Ziff 1992), and its 1/2-crossing
550
+ lies off p_c by much less than its scatter, the fit finding ``a`` near 0: for the sites
551
+ of the square lattice (by the fire, 32 to 256 across, 49 realizations, six seeds),
552
+ squares extrapolate within 0.002 of p_c = 0.59274621(13) through 4 neighbours (Newman &
553
+ Ziff 2000) and 0.003 of 0.407254 through 8 (1 - p_c: the matching lattice; Sykes &
554
+ Essam 1964), and rectangles twice as long as wide, joined the long way (``a`` about
555
+ 0.36, the largest 0.006 above p_c), within 0.002. The ``sizes`` are at least 3 distinct positive
556
+ integers (4 with ``fit_nu``), each bisected between ``lower`` and ``upper`` with the
557
+ criterion (``phase``, ``axis``, ``connectivity``, ``periodic``, ``method``), the
558
+ ``realizations`` and the ``tol`` of :func:`percolation_threshold`, from a seed of its
559
+ own derived from ``seed`` and the size (independent estimates, each reproducible
560
+ whatever the other sizes). For instance, the site percolation of the cubic lattice::
561
+
562
+ def site(fraction, rng, size):
563
+ return rng.random((size, size, size)) < fraction
564
+
565
+ result = percolation_scaling(site, [16, 24, 32, 48], 0.2, 0.45, method="fire")
566
+
567
+ and for the model of a configuration, the family of :func:`family_from_config` with
568
+ ``sized=True``.
569
+ """
570
+ need, fitted = (4, "p_c, a and nu") if fit_nu else (3, "p_c and a")
571
+ values = _check_sizes(sizes, need, fitted)
572
+ if nu is not None and not nu > 0.0:
573
+ raise ValueError(f"nu: expected a positive exponent, got {nu!r}")
574
+ base = _base_seed(seed)
575
+ planar = [] # whether each image is planar, for the default exponent
576
+
577
+ def sized(fraction, rng, size):
578
+ image = generate(fraction, rng, size)
579
+ planar.append(np.ndim(as_array(image)) == 3 and np.shape(as_array(image))[2] == 1)
580
+ return image
581
+
582
+ results = tuple(
583
+ percolation_threshold(
584
+ lambda fraction, rng, size=size: sized(fraction, rng, size),
585
+ lower,
586
+ upper,
587
+ phase=phase,
588
+ axis=axis,
589
+ connectivity=connectivity,
590
+ periodic=periodic,
591
+ method=method,
592
+ realizations=realizations,
593
+ tol=tol,
594
+ seed=np.random.SeedSequence(base.entropy, spawn_key=(*base.spawn_key, size)),
595
+ )
596
+ for size in values.tolist()
597
+ )
598
+ if nu is None:
599
+ nu = NU_2D if all(planar) else NU_3D
600
+ thresholds = np.array([r.threshold for r in results])
601
+ brackets = np.array([r.bracket for r in results])
602
+ pc, a, theta, residuals, errors = _scaling_fit(
603
+ values.astype(float), thresholds, brackets[:, 1] - brackets[:, 0], float(nu), fit_nu
604
+ )
605
+ return PercolationScaling(
606
+ sizes=values,
607
+ thresholds=thresholds,
608
+ brackets=brackets,
609
+ threshold=pc,
610
+ stderr=float(errors[0]),
611
+ amplitude=a,
612
+ nu=1.0 / theta if fit_nu else float(nu),
613
+ nu_stderr=float(errors[2]) / theta**2 if fit_nu else None,
614
+ residuals=residuals,
615
+ results=results,
616
+ )
617
+
618
+
619
+ def family_from_config(
620
+ config, parameter: str = "volume_fraction", *, base_dir=None, sized: bool = False
621
+ ) -> Callable[..., VoxelImage]:
622
+ """The family of microstructures of a run configuration, for :func:`percolation_threshold`.
623
+
624
+ ``config`` is a file, a mapping or a :class:`~morphogen.config.RunConfig` (validated by
625
+ :func:`~morphogen.config.load_config`, with ``base_dir``) whose ``model``, ``domain`` and
626
+ ``voxels`` sections are used: ``generate(fraction, rng)`` draws from ``rng`` a
627
+ realization of the model whose parameter ``parameter`` is ``fraction``, in the domain,
628
+ and voxelizes it on the grid of the configuration, as :func:`morphogen.pipeline.run`
629
+ does. A model without the parameter, and a configuration without a domain size or a
630
+ voxel grid, are refused (:class:`~morphogen.config.ConfigError`). For instance::
631
+
632
+ config = {
633
+ "model": {"type": "boolean_spheres", "radius": 1.0, "volume_fraction": 0.3},
634
+ "domain": {"size": 16.0, "periodic": True},
635
+ "voxels": {"shape": 64},
636
+ }
637
+ result = percolation_threshold(family_from_config(config), 0.15, 0.45, seed=0)
638
+
639
+ With ``sized``, ``generate(fraction, rng, size)``, for :func:`percolation_scaling`,
640
+ voxelizes the realization in a box ``size`` voxels per edge at the voxel size of the
641
+ configuration, the domain scaled to it (its origin and periodicity kept): the box grows
642
+ in units of the microstructure, as finite-size scaling wants, where a finer grid of the
643
+ same domain would converge to the threshold of that domain. The parameters of the model
644
+ must then be intensive (sizes, fractions, densities), a number of objects being diluted
645
+ in the growing box. A grid of one voxel along z (a 2-D configuration) keeps it: the box
646
+ grows in the plane, ``size`` voxels along x and y.
647
+ """
648
+ from morphogen.config import ConfigError, RunConfig, load_config
649
+
650
+ cfg = config if isinstance(config, RunConfig) else load_config(config, base_dir=base_dir)
651
+ model, domain, voxels = cfg.model, cfg.domain, cfg.voxels
652
+ names = [f.name for f in fields(model)]
653
+ if parameter not in names:
654
+ raise ConfigError(
655
+ f"model {model.name}: no parameter {parameter!r} to vary (its parameters: "
656
+ f"{', '.join(names)})"
657
+ )
658
+ if domain is None:
659
+ raise ConfigError("percolation: give the size of the domain (domain.size)")
660
+ if voxels is None:
661
+ raise ConfigError("percolation: give the voxel grid (voxels section)")
662
+ grid = voxels.kwargs()
663
+
664
+ def varied(fraction: float):
665
+ try:
666
+ return replace(model, **{parameter: float(fraction)})
667
+ except (TypeError, ValueError) as exc:
668
+ raise ValueError(f"model {model.name}: {parameter} = {fraction:g}: {exc}") from None
669
+
670
+ def generate(fraction: float, rng: np.random.Generator) -> VoxelImage:
671
+ return varied(fraction).generate(domain, seed=rng).voxelize(**grid)
672
+
673
+ if not sized:
674
+ return generate
675
+ configured = Grid.for_domain(domain, **grid)
676
+ spacing, flat = configured.spacing, configured.shape[2] == 1
677
+
678
+ def generate_sized(fraction: float, rng: np.random.Generator, size: int) -> VoxelImage:
679
+ if isinstance(size, bool) or int(size) != size or size < 1:
680
+ raise ValueError(f"size: expected a positive integer, got {size!r}")
681
+ shape = (int(size), int(size), 1 if flat else int(size))
682
+ box = replace(domain, size=tuple(float(h) * n for h, n in zip(spacing, shape, strict=True)))
683
+ return varied(fraction).generate(box, seed=rng).voxelize(shape=shape)
684
+
685
+ return generate_sized
686
+
687
+
688
+ # -- along directions: the cores of an image, and the anisotropy of the thresholds -----------
689
+
690
+
691
+ @njit(cache=True)
692
+ def _spread(times, nx, ny, nz, offsets, sources, target, full, queue):
693
+ """Breadth-first burning of a C-ordered ``(nx, ny, nz)`` image raveled in ``times`` (-1
694
+ where it may burn, -2 elsewhere), lit on those of the flat indices ``sources``, through
695
+ the neighbours ``offsets`` (in the plane when ``nz == 1``) inside the box: ``times``
696
+ receives the step at which each voxel catches fire and ``queue`` the voxels in the order
697
+ they do; the burning stops at the end of the step at which a voxel of ``target``
698
+ (nonzero, flat) catches fire, unless ``full``. Returns the number of voxels burnt and
699
+ that step (-1: not reached)."""
700
+ nyz = ny * nz
701
+ shifts = offsets[:, 0] * nyz + offsets[:, 1] * nz + offsets[:, 2]
702
+ tail, reached = 0, -1
703
+ for q in sources:
704
+ if times[q] == -1:
705
+ times[q] = 0
706
+ queue[tail] = q
707
+ tail += 1
708
+ if target[q]:
709
+ reached = 0
710
+ head, step = 0, 0
711
+ while head < tail and (full or reached < 0):
712
+ end = tail
713
+ while head < end:
714
+ q = queue[head]
715
+ head += 1
716
+ i = q // nyz
717
+ j = (q - i * nyz) // nz
718
+ k = q - i * nyz - j * nz
719
+ inner = 0 < i < nx - 1 and 0 < j < ny - 1 and (nz == 1 or 0 < k < nz - 1)
720
+ for m in range(offsets.shape[0]):
721
+ if not inner:
722
+ ii, jj, kk = i + offsets[m, 0], j + offsets[m, 1], k + offsets[m, 2]
723
+ if ii < 0 or ii >= nx or jj < 0 or jj >= ny or kk < 0 or kk >= nz:
724
+ continue
725
+ p = q + shifts[m]
726
+ if times[p] == -1:
727
+ times[p] = step + 1
728
+ queue[tail] = p
729
+ tail += 1
730
+ if reached < 0 and target[p]:
731
+ reached = step + 1
732
+ step += 1
733
+ return tail, reached
734
+
735
+
736
+ @dataclass(frozen=True)
737
+ class _Core:
738
+ """The core of a box along a direction: its voxels (flat mask), those of its lower cap
739
+ (flat indices) and of its upper one (flat mask), the chemical distance across it full."""
740
+
741
+ inside: np.ndarray
742
+ lower: np.ndarray
743
+ upper: np.ndarray
744
+ straight: int
745
+
746
+
747
+ def _core(shape, spacing, direction, offsets) -> _Core:
748
+ """The core of a box of ``shape`` voxels of ``spacing`` along the unit ``direction``."""
749
+ h = np.asarray(spacing, dtype=float)
750
+ extents = np.asarray(shape, dtype=float) * h
751
+ planar = shape[2] == 1
752
+ half = float((extents[:2] if planar else extents).min()) / (2.0 * np.sqrt(2.0)) # R
753
+ x, y, z = (
754
+ (np.arange(n) + 0.5) * d - 0.5 * e for n, d, e in zip(shape, h, extents, strict=True)
755
+ ) # the centres of the voxels, from the centre of the box
756
+ x, y, z = x[:, None, None], y[None, :, None], z[None, None, :]
757
+ t = direction[0] * x + direction[1] * y + direction[2] * z # along the axis of the core
758
+ slack = 1e-9 * half # ties (systematic along diagonals) decided alike despite rounding
759
+ inside = (np.abs(t) <= half + slack) & (x**2 + y**2 + z**2 - t**2 <= (half + slack) ** 2)
760
+ step = float(np.abs(offsets @ (np.asarray(direction) * h)).max()) # longest, along it
761
+ lower = inside & (t < step - half - slack) # a step from crossing the cap, not onto it
762
+ upper = inside & (t > half - step + slack)
763
+ if not lower.any():
764
+ raise ValueError(f"image: {tuple(shape)} voxels too few for a core along {direction}")
765
+ times = np.where(inside.ravel(), -1, -2).astype(np.int32)
766
+ queue = np.empty(int(np.count_nonzero(inside)), dtype=np.int32)
767
+ sources = np.flatnonzero(lower)
768
+ _, reached = _spread(times, *shape, offsets, sources, upper.ravel(), False, queue)
769
+ if reached < 0:
770
+ raise ValueError(f"image: {tuple(shape)} voxels too few for a core along {direction}")
771
+ return _Core(inside.ravel(), sources, upper.ravel(), int(reached))
772
+
773
+
774
+ def _fire_core(mask: np.ndarray, core: _Core, offsets: np.ndarray, full: bool) -> Fire:
775
+ """The forest fire of the C-ordered boolean ``mask`` across ``core``."""
776
+ dtype = np.int32 if mask.size < 2**31 else np.int64
777
+ times = np.where(core.inside & mask.ravel(), -1, -2).astype(dtype)
778
+ queue = np.empty(int(np.count_nonzero(times == -1)), dtype=dtype)
779
+ burnt, reached = _spread(times, *mask.shape, offsets, core.lower, core.upper, full, queue)
780
+ return Fire(
781
+ percolates=bool(reached >= 0),
782
+ time=int(reached) if reached >= 0 else None,
783
+ front=np.bincount(times[queue[:burnt]]),
784
+ times=np.maximum(times, -1).reshape(mask.shape) if full else None,
785
+ )
786
+
787
+
788
+ def _directions(directions, planar: bool, spacing) -> np.ndarray:
789
+ """The unit vectors (rows) of ``directions`` (see :func:`directional_percolation`)."""
790
+ if isinstance(directions, str) or directions is None:
791
+ if directions == "axes":
792
+ d = np.eye(3)[: 2 if planar else 3]
793
+ elif directions == "lattice":
794
+ d = np.array(_LATTICE_2D if planar else DIRECTIONS_13, dtype=float) * spacing
795
+ else:
796
+ raise ValueError(f"directions: axes, lattice, a number or vectors, got {directions!r}")
797
+ elif np.ndim(directions) == 0:
798
+ count = directions
799
+ if isinstance(count, bool) or int(count) != count or count < 1:
800
+ raise ValueError(f"directions: expected a positive number, got {count!r}")
801
+ k = np.arange(int(count))
802
+ if planar: # equal angles over half a turn, from x
803
+ angle = np.pi * k / int(count)
804
+ d = np.column_stack([np.cos(angle), np.sin(angle), np.zeros(len(k))])
805
+ else: # a Fibonacci spiral over the half sphere z > 0
806
+ z, phi = 1.0 - (k + 0.5) / int(count), np.pi * (3.0 - np.sqrt(5.0)) * k
807
+ r = np.sqrt(1.0 - z**2)
808
+ d = np.column_stack([r * np.cos(phi), r * np.sin(phi), z])
809
+ else:
810
+ d = np.atleast_2d(np.asarray(directions, dtype=float))
811
+ if d.ndim != 2 or d.shape[1] not in (2, 3) or not np.all(np.isfinite(d)):
812
+ raise ValueError(f"directions: vectors of 2 or 3 components, got {directions!r}")
813
+ if d.shape[1] == 2:
814
+ d = np.column_stack([d, np.zeros(len(d))])
815
+ norms = np.linalg.norm(d, axis=1)
816
+ if not np.all(norms > 0):
817
+ raise ValueError("directions: a vector of zero length")
818
+ d = d / norms[:, None]
819
+ if planar and np.any(np.abs(d[:, 2]) > 1e-12):
820
+ raise ValueError("directions: in the plane of a planar image (no z component)")
821
+ return d
822
+
823
+
824
+ def burn_along(
825
+ image, direction, phase: int = 1, *, connectivity: int = 6, full: bool = False
826
+ ) -> Fire:
827
+ """The forest fire of the phase ``phase`` of an image along ``direction`` (a vector, in
828
+ physical units for anisotropic voxels; in the plane of a planar image), across the core
829
+ of the image along it: the cylinder (a square in 2-D) of the voxels whose centres lie
830
+ within ``R`` of the axis through the centre of the box along the direction and within
831
+ ``R`` of the centre along it, ``2 R`` long and across, ``R = D / (2 sqrt 2)`` for the
832
+ diameter ``D`` of the ball (disc) inscribed in the box, its smallest edge. The phase
833
+ voxels of the core within a step of a neighbour of crossing its lower cap catch fire at
834
+ time 0 (one layer along an axis, as the face of :func:`burn`; the cap is the plane
835
+ normal to the direction at ``-R``), the fire spreads through the ``connectivity``
836
+ neighbours inside the core, and the phase percolates along the direction when it reaches
837
+ those of the upper cap, at the step ``time``, the chemical distance across the core
838
+ (``Fire`` as :func:`burn`; ``times`` -1 outside the core too).
839
+
840
+ Any direction crosses a congruent cylinder of the inscribed ball, so that a medium
841
+ isotropic in law crosses alike along all (up to the voxels of the core) and the
842
+ differences between directions are those of the medium, not of the box: the two planes
843
+ of the box normal to a diagonal touch it only at corners. The core lies inside the box
844
+ (the periodicity of the image unused) and spans ``1/sqrt 2`` of its smallest edge (half
845
+ of a square, 0.28 of a cube); it has the aspect of a cube (a square), whose faces
846
+ :func:`burn` joins, and a square of the plane is crossed at p_c with the probability 1/2
847
+ (by duality). Its chemical distance when full, that of an image of the phase alone,
848
+ makes ``time`` a tortuosity (:func:`directional_percolation`).
849
+ """
850
+ if isinstance(direction, str) or np.ndim(direction) != 1:
851
+ raise ValueError(f"direction: a vector of 2 or 3 components, got {direction!r}")
852
+ mask = _mask(image, phase)
853
+ planar = mask.shape[2] == 1
854
+ offsets = _offsets(connectivity, planar)
855
+ spacing = _spacing(image)
856
+ core = _core(mask.shape, spacing, _directions(direction, planar, spacing)[0], offsets)
857
+ return _fire_core(mask, core, offsets, bool(full))
858
+
859
+
860
+ @dataclass(frozen=True)
861
+ class DirectionalPercolation:
862
+ """Percolation of a phase of one image along directions (:func:`directional_percolation`).
863
+
864
+ ``directions`` are unit vectors (rows; no z component in 2-D), ``percolates`` whether
865
+ the fire crosses the core of the image along each, ``distances`` its chemical distance
866
+ across (-1: it does not) and ``straight`` that across the full core, ``tortuosity`` the
867
+ geometric tortuosity across (inf: no crossing).
868
+ """
869
+
870
+ directions: np.ndarray
871
+ percolates: np.ndarray
872
+ distances: np.ndarray
873
+ straight: np.ndarray
874
+ tortuosity: np.ndarray
875
+
876
+
877
+ def _path_lengths(inside: np.ndarray, spacing, lower: np.ndarray, upper: np.ndarray):
878
+ """The Euclidean lengths of the shortest paths through the voxels ``inside`` (boolean;
879
+ 26 neighbours, 8 in the plane of a planar image) from those among ``lower`` (flat
880
+ indices) to each of those of ``upper`` (a flat mask) that they reach."""
881
+ from scipy.sparse import coo_matrix
882
+ from scipy.sparse.csgraph import dijkstra
883
+
884
+ planar = inside.shape[2] == 1
885
+ index = np.full(inside.shape, -1, dtype=np.int64)
886
+ index[inside] = np.arange(int(np.count_nonzero(inside)))
887
+ pad = [(1, 1), (1, 1), (0, 0) if planar else (1, 1)]
888
+ padded, low = np.pad(index, pad, constant_values=-1), np.array([p[0] for p in pad])
889
+ rows, cols, weights = [], [], []
890
+ for d in np.argwhere(np.ones((3, 3, 1 if planar else 3), dtype=bool)) - low:
891
+ if tuple(d) <= (0, 0, 0): # each pair of neighbours once
892
+ continue
893
+ start = low + d
894
+ other = padded[tuple(slice(s, s + n) for s, n in zip(start, inside.shape, strict=True))]
895
+ keep = (index >= 0) & (other >= 0)
896
+ rows.append(index[keep])
897
+ cols.append(other[keep])
898
+ weights.append(np.full(int(keep.sum()), float(np.linalg.norm(d * spacing))))
899
+ count = int(np.count_nonzero(inside))
900
+ graph = coo_matrix(
901
+ (np.concatenate(weights), (np.concatenate(rows), np.concatenate(cols))), (count, count)
902
+ ).tocsr()
903
+ flat = index.ravel()
904
+ sources, targets = flat[lower], flat[upper]
905
+ sources, targets = sources[sources >= 0], targets[targets >= 0]
906
+ if not len(sources) or not len(targets):
907
+ return np.empty(0)
908
+ lengths = dijkstra(graph, directed=False, indices=sources, min_only=True)[targets]
909
+ return lengths[np.isfinite(lengths)]
910
+
911
+
912
+ def directional_percolation(
913
+ image, directions="lattice", phase: int = 1, *, connectivity: int = 6
914
+ ) -> DirectionalPercolation:
915
+ """Percolation of the phase ``phase`` of one image along each of ``directions``: the fire
916
+ of :func:`burn_along` across the core of the image along each, a direction and its
917
+ opposite alike. ``directions`` are ``"lattice"`` (the axes and the diagonals of the
918
+ grid: 4 directions in 2-D, 13 in 3-D, in physical units for anisotropic voxels, as for
919
+ the mean intercept length of :func:`~morphogen.analysis.anisotropy.fabric_tensor`),
920
+ ``"axes"``, a number of directions sampled (in 2-D at equal angles over half a turn from
921
+ x; in 3-D on a Fibonacci spiral over the half sphere z > 0, quasi-uniform), or vectors
922
+ (rows of 2 or 3 components).
923
+
924
+ The chemical distance across the core, the number of steps of the shortest path through
925
+ the ``connectivity`` neighbours, follows the metric of the lattice, which is not
926
+ isotropic: through 4 neighbours a diagonal of the square lattice is crossed by many
927
+ staircases of the same length, which the phase seldom blocks all, where an axis has
928
+ one straight path (on sites of the square lattice at p = 0.65, 1.03 and 1.33 times the
929
+ distance across the full core). The geometric tortuosity compares the directions: as
930
+ :func:`~morphogen.analysis.morphology.geometric_tortuosity` across the faces normal to
931
+ an axis, the mean Euclidean length of the shortest paths through the phase (26
932
+ neighbours, 8 in 2-D, steps between voxel centres) from the lower cap to the voxels of
933
+ the upper one they reach, here over that across the full core (1 for a straight
934
+ channel along the direction, the bias of the metric of the steps divided out), and only
935
+ where the phase percolates along the direction.
936
+ """
937
+ mask = _mask(image, phase)
938
+ planar = mask.shape[2] == 1
939
+ offsets = _offsets(connectivity, planar)
940
+ spacing = _spacing(image)
941
+ dirs = _directions(directions, planar, spacing)
942
+ cores = [_core(mask.shape, spacing, n, offsets) for n in dirs]
943
+ fires = [_fire_core(mask, core, offsets, False) for core in cores]
944
+ distances = np.array([-1 if f.time is None else f.time for f in fires], dtype=np.int64)
945
+ tortuosity = np.full(len(dirs), np.inf)
946
+ shape = mask.shape
947
+ for k, core in enumerate(cores):
948
+ if distances[k] >= 0:
949
+ phase_in = (core.inside & mask.ravel()).reshape(shape)
950
+ lengths = _path_lengths(phase_in, spacing, core.lower, core.upper)
951
+ full = _path_lengths(core.inside.reshape(shape), spacing, core.lower, core.upper)
952
+ tortuosity[k] = lengths.mean() / full.mean()
953
+ return DirectionalPercolation(
954
+ directions=dirs,
955
+ percolates=distances >= 0,
956
+ distances=distances,
957
+ straight=np.array([core.straight for core in cores], dtype=np.int64),
958
+ tortuosity=tortuosity,
959
+ )
960
+
961
+
962
+ @dataclass(frozen=True)
963
+ class PercolationAnisotropy:
964
+ """Percolation thresholds of a family along directions (:func:`percolation_anisotropy`).
965
+
966
+ ``samples[i, k]`` is the threshold of realization ``i`` along ``directions[k]`` (unit
967
+ vectors, rows; no z component in 2-D), the middle of a bracket narrower than the
968
+ tolerance (``inf`` or ``-inf``: beyond the bounds); ``thresholds`` their medians, with
969
+ the standard errors ``stderr``; ``deviations`` the medians of the differences of the
970
+ realizations' thresholds from their means over the directions, with the standard errors
971
+ ``deviation_stderr``; ``ratio`` the median of the ratios of their thresholds along the
972
+ directions of the largest and the smallest deviation, with ``ratio_stderr`` (``inf``
973
+ when a threshold lies beyond the bounds); ``tensor`` the threshold tensor (3 x 3,
974
+ nothing along z in 2-D), its ``eigenvalues`` (increasing; 2 in 2-D) with
975
+ ``eigenvalue_stderr`` and its ``principal`` directions (rows), ``residuals`` the paired
976
+ thresholds (the median of the realizations' means plus the deviations) less its
977
+ quadratic form. The standard errors leave out the samples beyond the bounds (NaN for
978
+ fewer than two left); the tensor is NaN where a threshold lies beyond them.
979
+ """
980
+
981
+ directions: np.ndarray
982
+ thresholds: np.ndarray
983
+ stderr: np.ndarray
984
+ deviations: np.ndarray
985
+ deviation_stderr: np.ndarray
986
+ ratio: float
987
+ ratio_stderr: float
988
+ tensor: np.ndarray
989
+ eigenvalues: np.ndarray
990
+ eigenvalue_stderr: np.ndarray
991
+ principal: np.ndarray
992
+ residuals: np.ndarray
993
+ samples: np.ndarray = field(repr=False)
994
+ realizations: int
995
+
996
+
997
+ def _median_stderr(values) -> np.ndarray:
998
+ """The standard error of the median of the finite values of each column of ``values``
999
+ (rows: realizations), ``sqrt(pi/2)`` times their standard deviation over the square root
1000
+ of their number (a normal law); NaN for fewer than two."""
1001
+ values = np.asarray(values, dtype=float)
1002
+ out = np.full(values.shape[1], np.nan)
1003
+ for k in range(values.shape[1]):
1004
+ finite = values[np.isfinite(values[:, k]), k]
1005
+ if len(finite) > 1:
1006
+ out[k] = np.std(finite, ddof=1) * np.sqrt(np.pi / 2 / len(finite))
1007
+ return out
1008
+
1009
+
1010
+ def _medians(values) -> np.ndarray:
1011
+ """The medians of the columns of ``values`` over their rows that are not NaN (NaN for
1012
+ none): infinite values beyond the bounds count, on their side."""
1013
+ values = np.asarray(values, dtype=float)
1014
+ out = np.full(values.shape[1], np.nan)
1015
+ for k in range(values.shape[1]):
1016
+ kept = values[~np.isnan(values[:, k]), k]
1017
+ if len(kept):
1018
+ out[k] = np.median(kept)
1019
+ return out
1020
+
1021
+
1022
+ def _quadratic(directions: np.ndarray, planar: bool) -> np.ndarray:
1023
+ """The rows of the least squares of ``n . T . n``: the components xx, yy, xy (2-D) or
1024
+ xx, yy, zz, yz, zx, xy (3-D) of ``T``."""
1025
+ x, y, z = directions.T
1026
+ if planar:
1027
+ return np.column_stack([x * x, y * y, 2 * x * y])
1028
+ return np.column_stack([x * x, y * y, z * z, 2 * y * z, 2 * z * x, 2 * x * y])
1029
+
1030
+
1031
+ def _tensors(components: np.ndarray, planar: bool) -> np.ndarray:
1032
+ """The symmetric 3 x 3 tensors of the components of :func:`_quadratic` (last axis)."""
1033
+ pairs = ((0, 0), (1, 1), (0, 1)) if planar else ((0, 0), (1, 1), (2, 2), (1, 2), (2, 0), (0, 1))
1034
+ out = np.zeros((*components.shape[:-1], 3, 3))
1035
+ for m, (a, b) in enumerate(pairs):
1036
+ out[..., a, b] = out[..., b, a] = components[..., m]
1037
+ return out
1038
+
1039
+
1040
+ def percolation_anisotropy(
1041
+ generate: Callable[[float, np.random.Generator], object],
1042
+ lower: float = 0.0,
1043
+ upper: float = 1.0,
1044
+ *,
1045
+ directions="lattice",
1046
+ phase: int = 1,
1047
+ connectivity: int = 6,
1048
+ realizations: int = 9,
1049
+ tol: float = 0.005,
1050
+ seed: SeedLike = None,
1051
+ ) -> PercolationAnisotropy:
1052
+ """Percolation thresholds of a family of microstructures along directions, and their
1053
+ anisotropy: the fractions at which the phase ``phase`` of ``generate(fraction, rng)``
1054
+ (as for :func:`percolation_threshold`) percolates along each of ``directions`` (as for
1055
+ :func:`directional_percolation`: across the core of the image along each).
1056
+
1057
+ Each realization, seeded as by :func:`percolation_threshold` and alike at every
1058
+ fraction, is bisected along every direction to a threshold of its own, the middle of a
1059
+ bracket narrower than ``tol`` (for a family growing with the fraction, the fraction from
1060
+ which it crosses; ``inf`` or ``-inf`` beyond ``lower`` and ``upper``: a direction along
1061
+ which it does not cross between them, or always does); the directions bracketed alike
1062
+ share the images, each image burnt along all those whose bracket it halves. The
1063
+ thresholds are the medians of the realizations' (the estimate of
1064
+ :func:`percolation_threshold`: the lower median for an even number, of a family growing
1065
+ with the fraction), with the standard errors ``sqrt(pi/2) s / sqrt(N)`` from the
1066
+ standard deviation ``s`` of the ``N`` realizations' (a normal law). The realizations are
1067
+ common to the directions, which are compared within each: the deviations are the
1068
+ medians of the differences of a realization's thresholds from their mean over the
1069
+ directions, the ratio that of its thresholds along the directions of the extreme
1070
+ deviations, with the standard errors of these paired differences, free of the scatter
1071
+ that the directions share and the thresholds carry (a difference of the medians along
1072
+ two directions would keep it: the same realization tends to be their median). An
1073
+ isotropic family has deviations within a few standard errors, and a ratio above 1 by
1074
+ about as much. The threshold tensor ``T`` is the symmetric tensor whose quadratic form
1075
+ ``p(n) = n . T . n`` fits the paired thresholds (the median of the realizations' means
1076
+ plus the deviations) by least squares (diagonal and exact on the axes alone); its
1077
+ eigenvalues bound the fitted thresholds, reached along its principal directions, their
1078
+ standard errors (the shared scatter included) from the tensors fitted to each
1079
+ realization, projected on these directions; the residuals tell how far a quadratic
1080
+ form describes the thresholds.
1081
+
1082
+ In the infinite medium, a statistically homogeneous medium of a finite range of
1083
+ correlation percolates from one threshold along every direction: its infinite cluster,
1084
+ when there is one, is unbounded along all. A box ``L`` across crosses at fractions that
1085
+ depend on the direction through the shape of the clusters: elongated ones (aligned
1086
+ fibres, stretched correlations) cross it sooner along their elongation, along which the
1087
+ box is shorter in units of their correlation length, and the thresholds differ by an
1088
+ amount of the order of their shift from p_c, ``L**(-1/nu)``
1089
+ (:func:`percolation_scaling`), however large the realizations. This is the anisotropy of
1090
+ percolation of a volume of that size, a specimen or an RVE; it vanishes with the size
1091
+ unless the medium is disconnected along some directions (layers separated by sheets of
1092
+ the other phase: thresholds ``inf`` across them). For instance, for fibres aligned
1093
+ along x::
1094
+
1095
+ from morphogen.config import model_from_config
1096
+ from morphogen.domain import Domain
1097
+
1098
+ domain = Domain(size=12.0)
1099
+ config = {"type": "boolean_cylinders", "radius": 0.5, "length": 6.0,
1100
+ "orientation": {"type": "aligned", "direction": [1, 0, 0]}}
1101
+
1102
+ def fibres(fraction, rng):
1103
+ model = model_from_config({**config, "volume_fraction": fraction})
1104
+ return model.generate(domain, seed=rng).voxelize(48)
1105
+
1106
+ result = percolation_anisotropy(fibres, 0.005, 0.6, realizations=25, tol=0.002, seed=0)
1107
+
1108
+ cross along x from a volume fraction of 0.099, across from 0.40 to 0.42 (a ratio of 5.0
1109
+ +/- 0.8), the smallest eigenvalue of the tensor, 0.087, along x; the sections of the
1110
+ fibres by a plane (strips, ``Domain(size=(12, 12, 0.0625), periodic=False)`` on 192 x 192
1111
+ x 1 voxels) from 0.25 along x and 0.90 across.
1112
+ """
1113
+ _check_connectivity(connectivity)
1114
+ seeds = _bisection(lower, upper, tol, realizations, seed)
1115
+ geometry: dict = {}
1116
+
1117
+ def crossings(fraction: float, s, ks=None) -> np.ndarray:
1118
+ image = generate(fraction, np.random.default_rng(s))
1119
+ mask = _mask(image, phase)
1120
+ key = (mask.shape, tuple(_spacing(image).tolist()))
1121
+ if not geometry:
1122
+ planar = mask.shape[2] == 1
1123
+ offsets = _offsets(connectivity, planar)
1124
+ dirs = _directions(directions, planar, np.asarray(key[1]))
1125
+ cores = [_core(mask.shape, key[1], n, offsets) for n in dirs]
1126
+ geometry.update(key=key, planar=planar, offsets=offsets, dirs=dirs, cores=cores)
1127
+ elif key != geometry["key"]:
1128
+ raise ValueError(f"generate: images of one grid, got {key} and {geometry['key']}")
1129
+ cores, offsets = geometry["cores"], geometry["offsets"]
1130
+ ks = range(len(cores)) if ks is None else ks
1131
+ return np.array([_fire_core(mask, cores[k], offsets, False).percolates for k in ks])
1132
+
1133
+ at_lower = np.array([crossings(float(lower), s) for s in seeds])
1134
+ at_upper = np.array([crossings(float(upper), s) for s in seeds])
1135
+ switching = at_lower != at_upper
1136
+ if not switching.any():
1137
+ raise ValueError(
1138
+ f"the percolation does not change between {lower:g} and {upper:g} along any "
1139
+ f"direction ({int(at_lower.sum())} and {int(at_upper.sum())} crossings of "
1140
+ f"{at_lower.size})"
1141
+ )
1142
+ rising = bool(at_upper.sum() >= at_lower.sum())
1143
+ samples = np.where(at_lower == rising, -np.inf, np.inf) # beyond the bounds
1144
+ for i, s in enumerate(seeds):
1145
+ stack = [(float(lower), float(upper), np.flatnonzero(switching[i]))]
1146
+ while stack:
1147
+ a, b, ks = stack.pop()
1148
+ mid = 0.5 * (a + b)
1149
+ if b - a <= tol or not a < mid < b:
1150
+ samples[i, ks] = mid
1151
+ continue
1152
+ moved = crossings(mid, s, ks) != at_lower[i, ks] # switched within [a, mid]
1153
+ for u, v, part in ((a, mid, ks[moved]), (mid, b, ks[~moved])):
1154
+ if len(part):
1155
+ stack.append((u, v, part))
1156
+ return _anisotropy(geometry["dirs"], samples, rising, geometry["planar"])
1157
+
1158
+
1159
+ def _anisotropy(dirs, samples, rising: bool, planar: bool) -> PercolationAnisotropy:
1160
+ """The statistics of the thresholds ``samples`` (realizations x directions)."""
1161
+ count = len(samples)
1162
+ thresholds = np.sort(samples, axis=0)[(count - 1) // 2 if rising else count // 2]
1163
+ finite = np.isfinite(thresholds)
1164
+ with np.errstate(invalid="ignore", divide="ignore"): # samples beyond the bounds: NaN
1165
+ means = np.full((count, 1), np.nan) # of each realization over the finite thresholds
1166
+ if finite.any():
1167
+ means = samples[:, finite].mean(axis=1)[:, None]
1168
+ paired = samples - means # within each realization: their common scatter cancels
1169
+ deviations = _medians(paired)
1170
+ ratio, logs = np.inf, np.full((count, 1), np.nan)
1171
+ if finite.all(): # between the directions of the extreme deviations, paired too
1172
+ big, small = int(np.argmax(deviations)), int(np.argmin(deviations))
1173
+ logs = np.log(samples[:, [big]]) - np.log(samples[:, [small]])
1174
+ ratio = float(np.exp(_medians(logs)[0]))
1175
+ rows, d = _quadratic(dirs, planar), 2 if planar else 3
1176
+ inverse = np.linalg.pinv(rows)
1177
+ nan = np.full(d, np.nan)
1178
+ tensor, values, errors, axes = np.full((3, 3), np.nan), nan, nan, np.full((d, 3), np.nan)
1179
+ residuals = np.full(len(dirs), np.nan)
1180
+ if finite.all():
1181
+ paired_thresholds = _medians(means)[0] + deviations
1182
+ components = inverse @ paired_thresholds
1183
+ tensor = _tensors(components, planar)
1184
+ values, vectors = np.linalg.eigh(tensor[:d, :d])
1185
+ largest = vectors[np.argmax(np.abs(vectors), axis=0), np.arange(d)]
1186
+ vectors *= np.where(largest < 0, -1.0, 1.0) # the largest component positive
1187
+ axes = np.zeros((d, 3))
1188
+ axes[:, :d] = vectors.T
1189
+ with np.errstate(invalid="ignore"): # realizations beyond the bounds: NaN errors
1190
+ each = _tensors(samples @ inverse.T, planar)[:, :d, :d] # one per realization
1191
+ errors = _median_stderr(np.einsum("ja,iab,jb->ij", vectors.T, each, vectors.T))
1192
+ residuals = paired_thresholds - rows @ components
1193
+ return PercolationAnisotropy(
1194
+ directions=dirs,
1195
+ thresholds=thresholds,
1196
+ stderr=_median_stderr(samples),
1197
+ deviations=deviations,
1198
+ deviation_stderr=_median_stderr(paired),
1199
+ ratio=ratio,
1200
+ ratio_stderr=float(ratio * _median_stderr(logs)[0]),
1201
+ tensor=tensor,
1202
+ eigenvalues=values,
1203
+ eigenvalue_stderr=errors,
1204
+ principal=axes,
1205
+ residuals=residuals,
1206
+ samples=samples,
1207
+ realizations=count,
1208
+ )
1209
+
1210
+
1211
+ # -- the critical exponents of the effective properties at the threshold ---------------------
1212
+
1213
+ #: The physics of :func:`percolation_exponent`: the conductivity (t) and the elasticity (f)
1214
+ _PHYSICS = ("thermal", "elastic")
1215
+ #: Poisson's ratio of the phases in elasticity
1216
+ _POISSON = 0.3
1217
+ #: The solvers of the trilinear voxels: the FFT solver, or their matrix assembled on the
1218
+ #: voxels of the materials and factorized (:mod:`morphogen.homogenization.voxel_fe`)
1219
+ _SOLVERS = ("fft", "fe")
1220
+ #: The default cut of :func:`rigidity_threshold` for each solver: above the stress averages
1221
+ #: of the floppy images of the FFT solver, its iterations stopping short of the round-off,
1222
+ #: and above the energies of those of the voxels factorized, which resolve the moduli
1223
+ #: of the realizations that bear down to the round-off
1224
+ CUTS = {"fft": 1e-8, "fe": 1e-12}
1225
+ #: The default tolerance of the conjugate gradients of each solver for the moduli: 1e-8 for
1226
+ #: the FFT solver, 1e-10 for the voxels factorized, whose solutions at 1e-8 leave the soft
1227
+ #: modes of floppy images unresolved, with energies of 1e-13 to 2e-8 and stress averages that
1228
+ #: agree with them (sites of the cubic lattice near their rigidity threshold: 23 of 32
1229
+ #: realizations of 32³ to 80³ voxels bear from fractions lower by 0.0003 to 0.003)
1230
+ SOLVER_TOLS = {"fft": 1e-8, "fe": 1e-10}
1231
+
1232
+
1233
+ def _check_solver(solver) -> str:
1234
+ if solver not in _SOLVERS:
1235
+ raise ValueError(f"solver: one of {', '.join(_SOLVERS)}, got {solver!r}")
1236
+ return solver
1237
+
1238
+
1239
+ @dataclass(frozen=True)
1240
+ class PercolationExponent:
1241
+ """Critical exponent of an effective property at a percolation threshold
1242
+ (:func:`percolation_exponent`).
1243
+
1244
+ ``exponent`` is that of the property (``physics``: ``"thermal"``, the conductivity along
1245
+ the axis, t; ``"elastic"``, the modulus of a uniaxial strain along it, f), ``nu`` times
1246
+ ``ratio``, the slope of ``-ln <P>`` against ``ln L`` fitted to the ``means`` (standard
1247
+ errors ``mean_stderr``) of the realizations of the ``sizes`` at the ``threshold``:
1248
+ ``means = amplitude * sizes**(-ratio)``, ``residuals`` the logarithms of the means less
1249
+ the fit; ``stderr`` is its statistical standard error and ``threshold_error`` half its
1250
+ change between the threshold less and plus ``threshold_stderr`` (0 without).
1251
+ ``fractions`` are those computed (increasing: the threshold, the two shifted by its
1252
+ standard error, those of the ``sweep``), ``values[k, j]`` the mean property of the boxes
1253
+ ``sizes[k]`` at ``fractions[j]`` with the standard errors ``value_stderr``, and
1254
+ ``samples[k, i, j]`` that of realization ``i``; ``sweep_exponents[k]`` is the exponent
1255
+ fitted to the means of size ``k`` against ``fraction - threshold`` over the ``sweep``,
1256
+ with ``sweep_stderr`` and ``sweep_threshold_error`` (empty without a sweep).
1257
+ ``iterations`` and ``residual`` are the largest number of iterations and relative
1258
+ residual of the ``solver``.
1259
+ """
1260
+
1261
+ physics: str
1262
+ threshold: float
1263
+ exponent: float
1264
+ stderr: float
1265
+ threshold_error: float
1266
+ ratio: float
1267
+ amplitude: float
1268
+ nu: float
1269
+ sizes: np.ndarray
1270
+ means: np.ndarray
1271
+ mean_stderr: np.ndarray
1272
+ residuals: np.ndarray
1273
+ fractions: np.ndarray
1274
+ values: np.ndarray
1275
+ value_stderr: np.ndarray
1276
+ sweep: np.ndarray
1277
+ sweep_exponents: np.ndarray
1278
+ sweep_stderr: np.ndarray
1279
+ sweep_threshold_error: np.ndarray
1280
+ contrast: float
1281
+ realizations: int
1282
+ iterations: int
1283
+ residual: float
1284
+ samples: np.ndarray = field(repr=False)
1285
+ solver: str = "fft"
1286
+
1287
+
1288
+ def _extrapolated_threshold(scaling: PercolationScaling, lower: float, upper: float):
1289
+ """The threshold of a finite-size scaling and its standard error, for
1290
+ :func:`percolation_exponent`: refused when the threshold less or plus its error leaves
1291
+ the bounds of the bisection (boxes too small or realizations too few for an
1292
+ exponent)."""
1293
+ threshold, stderr = scaling.threshold, scaling.stderr
1294
+ if not (min(lower, upper) < threshold - stderr and threshold + stderr < max(lower, upper)):
1295
+ raise ValueError(
1296
+ f"the threshold extrapolated, {threshold:.4g} +/- {stderr:.2g}, leaves the bounds "
1297
+ f"{lower:g} and {upper:g}: too uncertain for an exponent (larger boxes or more "
1298
+ "realizations, or give the threshold)"
1299
+ )
1300
+ return threshold, stderr
1301
+
1302
+
1303
+ def _power_fit(x, means, errors):
1304
+ """Least squares of ``ln means = c + b ln x`` weighted by ``(means / errors)**2``, the
1305
+ inverse variances of the logarithms: ``b``, ``exp(c)``, the residuals and the standard
1306
+ error of ``b``, from the errors scaled by the scatter of the residuals where it exceeds
1307
+ them (the root of their reduced chi-square, which corrections to the power law raise),
1308
+ or from that scatter alone, unweighted, when the realizations of a mean are all alike
1309
+ (a relative error below 10⁻⁶: a deterministic family, or boxes where none carries and
1310
+ the property is that of the other phase); NaN unless the means are positive."""
1311
+ x, means, errors = (np.asarray(v, dtype=float) for v in (x, means, errors))
1312
+ n = len(x)
1313
+ if n < 2 or not (np.all(means > 0) and np.all(x > 0)):
1314
+ return np.nan, np.nan, np.full(n, np.nan), np.nan
1315
+ weighted = bool(np.all(errors > 1e-6 * means))
1316
+ w = means / errors if weighted else np.ones(n)
1317
+ design = np.column_stack([np.ones(n), np.log(x)])
1318
+ (c, b), *_ = np.linalg.lstsq(design * w[:, None], np.log(means) * w, rcond=None)
1319
+ residuals = np.log(means) - design @ (c, b)
1320
+ inverse = np.linalg.pinv((design * w[:, None]).T @ (design * w[:, None]))
1321
+ scatter = float(np.sum((residuals * w) ** 2)) / (n - 2) if n > 2 else 0.0
1322
+ variance = inverse[1, 1] * (max(1.0, scatter) if weighted else scatter)
1323
+ return float(b), float(np.exp(c)), residuals, float(np.sqrt(variance))
1324
+
1325
+
1326
+ #: The round-off of the element matrices perturbed to check an energy (:func:`_bears`): their
1327
+ #: entries times ``1 + ROUNDING * r``, ``r`` symmetric and standard normal
1328
+ _ROUNDING = 2.2e-16
1329
+
1330
+
1331
+ def _effective(mask, spacing, axis, physics, contrast, tol, maxiter, device, solver="fft",
1332
+ rounding=None): # fmt: skip
1333
+ """The effective property of a periodic image whose voxels ``mask`` conduct
1334
+ (conductivity 1; Young's modulus 1) and the others ``contrast`` times as much (void at
1335
+ 0), by the FFT solver on ``device`` or (``solver="fe"``) by the matrix of the trilinear
1336
+ voxels assembled and factorized, on the CPU, on the voxels that bear along the axis
1337
+ alone when the others are void (:func:`~morphogen.homogenization.voxel_fe.load_bearing`,
1338
+ exact): the conductivity along the axis number ``axis``, or the modulus of a uniaxial
1339
+ strain along it from the energy of the solution, the mean of ``sigma : epsilon``
1340
+ (stationary, its error of second order, and an upper bound); with the iterations, the
1341
+ relative residual and the stress average ``sigma_aa`` (the conductivity again), which
1342
+ equals the energy at the exact solution. ``rounding`` seeds a perturbation of the
1343
+ element matrices at their round-off (:data:`_ROUNDING`)."""
1344
+ from morphogen.homogenization import VOID, Loading, Material, make_problem
1345
+ from morphogen.homogenization.apparent import apparent_conductivity
1346
+
1347
+ if solver == "fe" and contrast == 0.0:
1348
+ from morphogen.homogenization.voxel_fe import load_bearing
1349
+
1350
+ mask = load_bearing(mask, axis)
1351
+ if not mask.any(): # nothing winds around the box along the axis
1352
+ return 0.0, 0, 0.0, 0.0
1353
+ image = VoxelImage(mask.astype(np.uint8), spacing=tuple(spacing), periodic=True)
1354
+ solid = Material(young=1.0, poisson=_POISSON, conductivity=1.0)
1355
+ other = VOID
1356
+ if contrast > 0.0:
1357
+ other = Material(young=contrast, poisson=_POISSON, conductivity=contrast)
1358
+ if solver == "fe":
1359
+ from morphogen.homogenization.voxel_fe import VoxelFEElasticProblem, VoxelFEThermalProblem
1360
+
1361
+ cls = VoxelFEElasticProblem if physics == "elastic" else VoxelFEThermalProblem
1362
+ problem = cls(image, {0: other, 1: solid}, tol=tol, maxiter=maxiter)
1363
+ else:
1364
+ problem = make_problem(image, {0: other, 1: solid}, physics, tol=tol, maxiter=maxiter,
1365
+ device=device) # fmt: skip
1366
+ if rounding is not None:
1367
+ k = problem.element_matrices
1368
+ r = np.random.default_rng(rounding).standard_normal(k.shape)
1369
+ problem.element_matrices = k * (1.0 + 0.5 * _ROUNDING * (r + np.swapaxes(r, 1, 2)))
1370
+ if physics == "thermal":
1371
+ result = apparent_conductivity(problem, axis)
1372
+ info = result.solution.info
1373
+ return float(result.value), info.iterations, info.residual, float(result.value)
1374
+ strain = np.zeros(6)
1375
+ strain[axis] = 1.0
1376
+ solution = problem.solve(Loading.strain(strain))
1377
+ info = solution.info
1378
+ return (float(solution.energy), info.iterations, info.residual,
1379
+ float(solution.stress[axis, axis])) # fmt: skip
1380
+
1381
+
1382
+ def _bound(maxiter, physics: str, shape) -> int | None:
1383
+ """The bound of the iterations of the conjugate gradients: ``maxiter``, else that of the
1384
+ solver (20 L + 1000, L the largest dimension) for the conductivity and 50 L + 1000 for
1385
+ the moduli, whose solutions near the rigidity threshold take up to 45 L."""
1386
+ if maxiter:
1387
+ return int(maxiter)
1388
+ return 50 * int(max(shape)) + 1000 if physics == "elastic" else None
1389
+
1390
+
1391
+ def _samples(generate, size, indices, grid, base, phase, axis, physics, contrast, tol, maxiter,
1392
+ device, solver="fft"): # fmt: skip
1393
+ """The property of the realizations ``indices`` of the boxes ``size`` voxels across at
1394
+ the fractions ``grid`` (:func:`percolation_exponent`; realization ``i`` drawn from the
1395
+ seed ``(base, size, i)``, the same at every fraction), with the largest number of
1396
+ iterations and relative residual of the solver and whether each image is planar."""
1397
+ samples = np.empty((len(indices), len(grid)))
1398
+ iterations, residual, planar = 0, 0.0, []
1399
+ for row, i in enumerate(indices):
1400
+ s = np.random.SeedSequence(base.entropy, spawn_key=(*base.spawn_key, size, i))
1401
+ for j, fraction in enumerate(np.asarray(grid).tolist()):
1402
+ image = generate(fraction, np.random.default_rng(s), size)
1403
+ mask = _mask(image, phase)
1404
+ if axis not in _axes(mask):
1405
+ raise ValueError(f"axis: x or y for a planar image, got {axis!r}")
1406
+ planar.append(mask.shape[2] == 1)
1407
+ value, it, res, _ = _effective(mask, _spacing(image), "xyz".index(axis), physics,
1408
+ contrast, tol, _bound(maxiter, physics, mask.shape),
1409
+ device, solver) # fmt: skip
1410
+ samples[row, j] = value
1411
+ iterations, residual = max(iterations, int(it)), max(residual, float(res))
1412
+ return samples, iterations, residual, planar
1413
+
1414
+
1415
+ def percolation_exponent(
1416
+ generate: Callable[[float, np.random.Generator, int], object],
1417
+ sizes,
1418
+ threshold: float,
1419
+ *,
1420
+ threshold_stderr: float = 0.0,
1421
+ fractions=(),
1422
+ physics: str = "thermal",
1423
+ phase: int = 1,
1424
+ axis: str = "x",
1425
+ contrast: float = 1e-8,
1426
+ nu: float | None = None,
1427
+ realizations: int = 16,
1428
+ tol: float | None = None,
1429
+ maxiter: int | None = None,
1430
+ device: str = "auto",
1431
+ solver: str = "fft",
1432
+ seed: SeedLike = None,
1433
+ ) -> PercolationExponent:
1434
+ """Critical exponent of the conductivity (t) or of the elastic moduli (f) of the
1435
+ percolating phase of a family of microstructures, by the finite-size scaling of the
1436
+ property at its percolation threshold, and optionally by a sweep above it.
1437
+
1438
+ Near the threshold p_c of the infinite medium the conductivity of the phase ``phase``
1439
+ vanishes as ``(p - p_c)**t``, its elastic moduli as ``(p - p_c)**f``, and the
1440
+ correlation length diverges as ``|p - p_c|**(-nu)``; at p_c, in boxes L across, the
1441
+ mean property scales as ``L**(-t/nu)`` (``L**(-f/nu)``; Derrida & Vannimenus 1982,
1442
+ Stauffer & Aharony 1994). ``generate(fraction, rng, size)`` returns an image ``size``
1443
+ voxels per edge (one voxel along z for a planar one), as for :func:`percolation_scaling`
1444
+ (:func:`family_from_config` with ``sized=True`` for the model of a configuration); for
1445
+ each of the ``sizes`` (at least 3), the ``realizations`` are drawn at the ``threshold``,
1446
+ each from a seed of its own derived from ``seed``, the size and its number, and their
1447
+ phase conducts (conductivity 1) or bears (Young's modulus 1, Poisson's ratio 0.3) while
1448
+ the other phases have ``contrast`` times its properties (void at 0). The periodic FFT
1449
+ solver (:mod:`morphogen.homogenization.fft`; ``device``: ``"cpu"``, ``"gpu"`` or
1450
+ ``"auto"``, the GPU when there is one; ``tol`` and ``maxiter`` of its conjugate
1451
+ gradients, ``tol`` by default 1e-8, and 1e-10 for the voxels factorized
1452
+ (:data:`SOLVER_TOLS`), ``maxiter`` by default that of the solver, 20 L + 1000 for L the largest
1453
+ dimension, for the conductivity and 50 L + 1000 for the moduli, whose solutions near
1454
+ the rigidity threshold take up to 45 L), or (``solver="fe"``) the same trilinear voxels
1455
+ assembled and solved by conjugate gradients preconditioned by the sparse factorization
1456
+ of their matrix, on the CPU (:mod:`morphogen.homogenization.voxel_fe`: the same
1457
+ solutions in a few iterations near the rigidity threshold, void around; with a contrast
1458
+ every voxel is assembled; void around, on the voxels that bear alone), gives the
1459
+ conductivity along ``axis`` (``physics="thermal"``) or the modulus of a uniaxial strain
1460
+ along it, ``C_xxxx`` along x (``"elastic"``; all the moduli share f, and Young's modulus
1461
+ would take six solutions), from the energy of the solution, the mean of σ : ε
1462
+ (stationary: its error is of second order, where the stress average strays with the
1463
+ round-off of the element matrices on floppy images, see :func:`rigidity_threshold`).
1464
+ The logarithms of the means are fitted
1465
+ against ``ln L`` by least squares weighted by their inverse variances (the standard
1466
+ errors of the means over their values), the slope times ``nu`` being the exponent:
1467
+ ``nu`` is by default that of random percolation, 0.8765 in 3-D and 4/3 in 2-D
1468
+ (:func:`percolation_scaling`). Its standard error comes from those of the means, scaled
1469
+ by the scatter of the residuals when it exceeds them (corrections to scaling); with a
1470
+ ``threshold_stderr``, the realizations are also computed at the threshold less and plus
1471
+ it (the same images: common random numbers) and ``threshold_error`` is half the change
1472
+ of the exponent between them, the error that the threshold's own leaves.
1473
+
1474
+ The finite-size scaling at p_c is the method of the literature (Derrida & Vannimenus
1475
+ 1982; Gingold & Lobb 1990: t = 2.003 +/- 0.047 in 3-D; Grassberger 1999: t/nu = 0.9745
1476
+ +/- 0.0015 in 2-D): every box contributes at its threshold, where the property is
1477
+ critical, and the corrections are those of L alone. A sweep in ``p - p_c`` needs boxes
1478
+ much larger than the correlation length at every fraction of its window, which ends
1479
+ where the critical region does: on images of a few hundred voxels across the window is
1480
+ narrow and its exponent drifts with it (Kirkpatrick's 1.6 +/- 0.1 in 3-D, 1973, came
1481
+ from such sweeps). ``fractions`` (at least 3,
1482
+ above the threshold plus its standard error) add one on every size: ``sweep_exponents``
1483
+ are the slopes of ``ln <P>`` against ``ln(p - p_c)`` of each size, with their standard
1484
+ errors and the change that the threshold's error makes (refitted at p_c +/- its
1485
+ standard error), for comparison.
1486
+
1487
+ The threshold must be that of the solver. Its trilinear voxels join two voxels through
1488
+ the nodes they share, a face, an edge or a corner: the conductivity percolates through
1489
+ 26 neighbours (8 in 2-D), so that its threshold is that of :func:`percolation_scaling`
1490
+ with ``connectivity=26`` (wrapping around the periodic box, as the solver, or by the
1491
+ fire, faster on large planar images: the criteria extrapolate to the same p_c), below
1492
+ that of the faces (for sites of the cubic lattice 0.0976 against 0.3116; for Boolean
1493
+ spheres of 3 voxels of radius, 0.186 against 0.245). In elasticity a shared corner is a
1494
+ ball joint and an edge a hinge, about which the voxels turn freely: the moduli vanish
1495
+ where the joined voxels become rigid, between the thresholds of 26 and 6 neighbours (8
1496
+ and 4 in 2-D), at the threshold that :func:`rigidity_threshold` finds from the moduli
1497
+ themselves. The values of the realizations that do not percolate, of the order of
1498
+ the contrast, are known to the tolerance of the solver only. The contrast shifts the property
1499
+ by about ``contrast * (L / l)**((t + s)/nu)`` of itself at p_c (Efros & Shklovskii
1500
+ 1976, Straley 1976; ``l`` the size of the grains, s the exponent of a superconducting
1501
+ phase, about 0.73 in 3-D and 1.30 in 2-D), and the sweep within ``contrast**(1/(t +
1502
+ s))`` of p_c: at the default 10⁻⁸, below 10⁻³ of the property and 0.002 in fraction for
1503
+ boxes up to 40 grains across in 3-D and 300 in 2-D. The threshold weighs most: periodic
1504
+ Boolean discs of 4 pixels of radius (64 to 512 pixels, 48 realizations; p_c = 0.5997
1505
+ +/- 0.0054 through 8 neighbours) give t = 1.13 +/- 0.16 +/- 0.21 (the second error that
1506
+ of the threshold, dt/dp_c about -40), spheres of 3 voxels of radius (24 to 96 voxels,
1507
+ 32 realizations; 0.1861 +/- 0.0040 through 26) t = 2.37 +/- 0.36 +/- 0.32 (dt/dp_c
1508
+ about -80), against 1.30 and 2.0. At their rigidity thresholds (by
1509
+ :func:`rigidity_threshold`, void around, ``solver="fe"``, the energies at the tolerance
1510
+ 1e-10, those that bear under 1e-9 confirmed at 1e-11), the sites of the square lattice
1511
+ (0.4617 +/- 0.0004; 16 to 256 pixels, 200 to 400 realizations) give f/nu = 2.26 +/-
1512
+ 0.07 +/- 0.05 (f = 3.01 with nu = 4/3), the slope rising with the box (1.55 between 16²
1513
+ and 24² pixels, 2.93 +/- 0.68 between 192² and 256²; 2.46 +/- 0.06 +/- 0.07 from 32²,
1514
+ 2.63 +/- 0.07 +/- 0.08 with a correction to scaling L**-1), and those of the cubic
1515
+ lattice (0.1304 +/- 0.0002; 8 to 80 voxels, 400 to 20 realizations) f/nu = 4.48 +/-
1516
+ 0.09 +/- 0.09 (f = 3.93 with nu = 0.8765; 4.73 +/- 0.17 +/- 0.16 from 16³, 4.73 to 4.85
1517
+ with a correction), 1.4 to 2.0 combined errors above the bond-bending f/nu of about 4.3
1518
+ and far from the 2.1 of central forces on the bcc lattice (Arbabi & Sahimi 1993), and
1519
+ 3 to 8 below the 2-D bond-bending 2.97 (f = 3.96), still rising there. At the
1520
+ thresholds of the first measurements (0.4627; 0.12904 by the energies at 1e-8, where
1521
+ floppy images bore) the same moduli give 2.15 and 5.04, the latter steepening to 6.15
1522
+ from 24³ as that threshold lay low (f = 2.88 +/- 0.12 +/- 0.23 and 4.58 +/- 0.19 +/-
1523
+ 0.07 then, with 64 and 128 realizations). Boolean discs of 4 pixels of radius (0.608
1524
+ +/- 0.006, 32² to 256² pixels) give f = 3.20 +/- 0.19 +/- 0.24 and spheres of 3 voxels
1525
+ (0.202 +/- 0.004, 24³ to 48³ voxels) 4.65 +/- 0.59 +/- 0.05 (at 1e-8), those of the
1526
+ sites within the errors: the voxels do not resolve the necks narrower than a voxel. By
1527
+ their thresholds, distinct from those of the connectivity, and the exponents of the
1528
+ widths of the realizations' thresholds (nu = 1.14 +/- 0.02 in 2-D, 0.76 +/- 0.03 in
1529
+ 3-D), the voxels' rigidity is a percolation of its own, as for central forces, whose
1530
+ f/nu is in 3-D that of bond bending. At the threshold the
1531
+ contrast 10⁻⁸ raises the mean moduli by 4·10⁻⁵ of those of void (10⁻⁶: 0.4 %, 10⁻⁴:
1532
+ 30 % on 24² pixels, by the FFT solver), the realizations
1533
+ that do not bear taking it times 14 to 58. For instance, the conductivity
1534
+ of Boolean spheres (the inverted Swiss cheese), 3 voxels per radius::
1535
+
1536
+ from morphogen.domain import Domain
1537
+ from morphogen.models import BooleanSpheres
1538
+
1539
+ def spheres(fraction, rng, size):
1540
+ model = BooleanSpheres(radius=1.0, volume_fraction=fraction)
1541
+ domain = Domain(size=size / 3.0, periodic=True)
1542
+ return model.generate(domain, seed=rng).voxelize(size)
1543
+
1544
+ sizes = [24, 32, 48, 64]
1545
+ pc = percolation_scaling(spheres, sizes, 0.1, 0.4, connectivity=26, periodic=True,
1546
+ realizations=49, tol=0.002, seed=0)
1547
+ result = percolation_exponent(spheres, sizes, pc.threshold,
1548
+ threshold_stderr=pc.stderr, seed=1)
1549
+ """
1550
+ if physics not in _PHYSICS:
1551
+ raise ValueError(f"physics: one of {', '.join(_PHYSICS)}, got {physics!r}")
1552
+ if axis not in ("x", "y", "z"):
1553
+ raise ValueError(f"axis: x, y or z (x or y for a planar image), got {axis!r}")
1554
+ _check_solver(solver)
1555
+ tol = SOLVER_TOLS[solver] if tol is None else tol
1556
+ values = _check_sizes(sizes, 3, "the exponent")
1557
+ threshold, sigma = float(threshold), float(threshold_stderr)
1558
+ if not np.isfinite(threshold):
1559
+ raise ValueError(f"threshold: expected a finite fraction, got {threshold!r}")
1560
+ if not (np.isfinite(sigma) and sigma >= 0.0):
1561
+ raise ValueError(f"threshold_stderr: expected a nonnegative error, got {sigma!r}")
1562
+ sweep = np.unique(np.asarray(fractions, dtype=float).ravel())
1563
+ if sweep.size and (
1564
+ sweep.size < 3 or not np.all(np.isfinite(sweep)) or not np.all(sweep > threshold + sigma)
1565
+ ):
1566
+ raise ValueError(
1567
+ f"fractions: at least 3 above the threshold plus its standard error "
1568
+ f"({threshold + sigma:g}), got {fractions!r}"
1569
+ )
1570
+ if not (np.isfinite(contrast) and 0.0 <= contrast < 1.0):
1571
+ raise ValueError(f"contrast: expected 0 <= contrast < 1, got {contrast!r}")
1572
+ if isinstance(realizations, bool) or int(realizations) != realizations or realizations < 2:
1573
+ raise ValueError(f"realizations: expected an integer of at least 2, got {realizations!r}")
1574
+ if nu is not None and not nu > 0.0:
1575
+ raise ValueError(f"nu: expected a positive exponent, got {nu!r}")
1576
+ if not tol > 0.0:
1577
+ raise ValueError(f"tol: expected a positive tolerance, got {tol!r}")
1578
+ base, count = _base_seed(seed), int(realizations)
1579
+ shifted = (threshold - sigma, threshold + sigma) if sigma > 0.0 else ()
1580
+ grid = np.unique([threshold, *shifted, *sweep.tolist()])
1581
+ samples = np.empty((len(values), count, len(grid)))
1582
+ iterations, residual, planar = 0, 0.0, []
1583
+ for k, size in enumerate(values.tolist()):
1584
+ samples[k], it, res, flat = _samples(generate, size, range(count), grid, base, phase,
1585
+ axis, physics, float(contrast), tol, maxiter,
1586
+ device, solver) # fmt: skip
1587
+ iterations, residual = max(iterations, it), max(residual, res)
1588
+ planar.extend(flat)
1589
+ if nu is None:
1590
+ nu = NU_2D if all(planar) else NU_3D
1591
+ nu = float(nu)
1592
+ means = samples.mean(axis=1)
1593
+ errors = samples.std(axis=1, ddof=1) / np.sqrt(count)
1594
+
1595
+ def column(fraction):
1596
+ j = int(np.searchsorted(grid, fraction))
1597
+ return means[:, j], errors[:, j]
1598
+
1599
+ slope, amplitude, residuals, slope_stderr = _power_fit(values, *column(threshold))
1600
+ threshold_error = 0.0
1601
+ if shifted:
1602
+ lo, hi = (_power_fit(values, *column(f))[0] for f in shifted)
1603
+ threshold_error = 0.5 * nu * abs(hi - lo)
1604
+ sweeps = np.empty((len(values) if sweep.size else 0, 3))
1605
+ for k, row in enumerate(sweeps):
1606
+ y, e = means[k, np.searchsorted(grid, sweep)], errors[k, np.searchsorted(grid, sweep)]
1607
+ row[0], _, _, row[1] = _power_fit(sweep - threshold, y, e)
1608
+ row[2] = 0.0
1609
+ if shifted:
1610
+ lo, hi = (_power_fit(sweep - f, y, e)[0] for f in shifted)
1611
+ row[2] = 0.5 * abs(hi - lo)
1612
+ at = column(threshold)
1613
+ return PercolationExponent(
1614
+ physics=physics,
1615
+ threshold=threshold,
1616
+ exponent=-nu * slope,
1617
+ stderr=nu * slope_stderr,
1618
+ threshold_error=threshold_error,
1619
+ ratio=-slope,
1620
+ amplitude=amplitude,
1621
+ nu=nu,
1622
+ sizes=values,
1623
+ means=at[0],
1624
+ mean_stderr=at[1],
1625
+ residuals=residuals,
1626
+ fractions=grid,
1627
+ values=means,
1628
+ value_stderr=errors,
1629
+ sweep=sweep,
1630
+ sweep_exponents=sweeps[:, 0],
1631
+ sweep_stderr=sweeps[:, 1],
1632
+ sweep_threshold_error=sweeps[:, 2],
1633
+ contrast=float(contrast),
1634
+ realizations=count,
1635
+ iterations=iterations,
1636
+ residual=residual,
1637
+ samples=samples,
1638
+ solver=solver,
1639
+ )
1640
+
1641
+
1642
+ # -- the rigidity threshold: where the elastic moduli of the phase vanish ---------------------
1643
+
1644
+ #: The neighbours through which the voxels of the FFT solvers join, at the nodes they share
1645
+ #: (26: a face, an edge or a corner; 8 in 2-D), and through which they are welded, rigidly
1646
+ #: (6: a face; 4 in 2-D: an edge), for 3-D and for planar images
1647
+ _JOINED, _WELDED = {False: 26, True: 8}, {False: 6, True: 4}
1648
+
1649
+
1650
+ @dataclass(frozen=True)
1651
+ class RigidityThreshold(PercolationScaling):
1652
+ """Finite-size scaling of the rigidity threshold of a phase, the fraction from which its
1653
+ elastic moduli do not vanish (:func:`rigidity_threshold`).
1654
+
1655
+ The fields of :class:`PercolationScaling`, the probabilities of ``results[k]`` being the
1656
+ shares of the realizations of the boxes ``sizes[k]`` that bear at its fractions;
1657
+ ``bearing[k][j, i]`` tells whether realization ``i`` bears at the fraction ``j`` and
1658
+ ``moduli[k][j, i]`` is its modulus over the Young's modulus of the phase, from the energy
1659
+ of its solution (NaN where the image was decided without the solver); ``cut`` is the
1660
+ modulus above which a realization bears, ``contrast`` the properties of the other
1661
+ phases over those of the phase (void at 0), ``floppy`` the largest modulus solved at or
1662
+ under the cut and ``rigid`` the smallest of those that bear (NaN without such
1663
+ solutions; the cut may move between them without changing a decision); ``solutions``
1664
+ is the number of solutions of the ``solver`` (``"fft"`` or ``"fe"``) and ``decided``
1665
+ that of the images decided without one, ``unresolved`` that of the solutions above the
1666
+ cut whose stress average strays from their energy by more than half of it (decided by
1667
+ the round-off of their energies for ``"fe"``, by their stress averages for ``"fft"``),
1668
+ ``confirmed`` that of the energies that bore under 1000 times the cut, decided again by
1669
+ a solution at the floor of the residual (``"fe"``), ``iterations`` and ``residual`` the
1670
+ largest number of iterations and relative residual of the solver.
1671
+ """
1672
+
1673
+ contrast: float = 0.0
1674
+ cut: float = 1e-8
1675
+ floppy: float = float("nan")
1676
+ rigid: float = float("nan")
1677
+ solutions: int = 0
1678
+ decided: int = 0
1679
+ iterations: int = 0
1680
+ residual: float = 0.0
1681
+ bearing: tuple[np.ndarray, ...] = field(default=(), repr=False)
1682
+ moduli: tuple[np.ndarray, ...] = field(default=(), repr=False)
1683
+ solver: str = "fft"
1684
+ unresolved: int = 0
1685
+ confirmed: int = 0
1686
+
1687
+
1688
+ #: A solution resolves its modulus when its stress average lies within this fraction of its
1689
+ #: energy (:func:`_bears`)
1690
+ _RESOLVED = 0.5
1691
+ #: An energy is resolved when those of the element matrices perturbed at their round-off lie
1692
+ #: within this fraction of it (:func:`_bears`)
1693
+ _STABLE = 0.01
1694
+ #: An energy that bears under this many times the cut is confirmed by a solution of the
1695
+ #: voxels factorized at the tolerance :data:`_FLOOR` (:func:`_bears`): at 1e-10 the floppy
1696
+ #: images whose soft modes the iterations leave unresolved keep energies of 1e-12 to 3e-11
1697
+ #: whose stress averages agree with them, and even their perturbations
1698
+ _CONFIRM = 1e3
1699
+ #: The tolerance of the confirmations, near the floor of the residual (3e-12 to 1.2e-11)
1700
+ _FLOOR = 1e-11
1701
+
1702
+
1703
+ def _decision(args, value, average, cut, solver, tally) -> bool:
1704
+ """Whether a solution of :func:`_effective` (``args``) of energy ``value`` and stress
1705
+ average ``average`` bears (:func:`_bears`); ``tally`` counts."""
1706
+ if not value > cut:
1707
+ tally["floppy"] = max(tally["floppy"], value)
1708
+ return False
1709
+ if abs(average - value) <= _RESOLVED * value:
1710
+ return True
1711
+ tally["unresolved"] += 1
1712
+ if solver == "fe":
1713
+ energies = [value, *(_effective(*args, rounding=k)[0] for k in (1, 2))]
1714
+ return max(energies) - min(energies) <= _STABLE * max(energies)
1715
+ return bool(average > cut)
1716
+
1717
+
1718
+ def _bears(mask, spacing, axis, known, contrast, cut, tol, maxiter, device, tally,
1719
+ solver="fft"): # fmt: skip
1720
+ """Whether the phase ``mask`` bears a uniaxial strain along ``axis`` with a modulus
1721
+ above ``cut`` (:func:`rigidity_threshold`), and that modulus (NaN when decided without
1722
+ the solver): not when none of its components wraps around the box along the axis
1723
+ through the nodes of its voxels (they translate freely), when one of its components
1724
+ joined by faces does (a rigid cluster), else as an image of ``known`` (the packed
1725
+ masks of the other images of the realization and their decisions) that bears and that
1726
+ it contains, or that does not and that contains it (the moduli grow with the stiffness
1727
+ of the voxels), else by the ``solver``: the modulus is the energy of the solution, an
1728
+ upper bound, so that it does not bear at or under the cut; above it, it bears when the
1729
+ stress average, linear in the error of the solution, agrees with the energy within
1730
+ :data:`_RESOLVED` of it, and otherwise (a floppy image whose mechanisms take large
1731
+ displacements, which the round-off of the element matrices strains) when two more
1732
+ solutions, the element matrices perturbed at their round-off, leave the energy within
1733
+ :data:`_STABLE` of itself (``"fe"``), or when the stress average exceeds the cut
1734
+ (``"fft"``, whose iterations stop short of the round-off). An energy of the voxels
1735
+ factorized that bears under :data:`_CONFIRM` times the cut is decided again, so, by a
1736
+ solution at the tolerance :data:`_FLOOR` (when ``tol`` is looser), whose energy is the
1737
+ modulus: the soft modes of a floppy image that the iterations have not resolved keep
1738
+ energies near the cut whose stress averages and perturbations agree with them;
1739
+ ``tally`` counts."""
1740
+ flat = mask.shape[2] == 1
1741
+ decided = None
1742
+ if not _percolates(mask, 1, axis, _JOINED[flat], True):
1743
+ decided = False
1744
+ elif _percolates(mask, 1, axis, _WELDED[flat], True):
1745
+ decided = True
1746
+ packed = np.packbits(mask)
1747
+ for other, bears in known if decided is None else ():
1748
+ if (not np.any(other & ~packed)) if bears else (not np.any(packed & ~other)):
1749
+ decided = bears
1750
+ break
1751
+ if decided is not None:
1752
+ tally["decided"] += 1
1753
+ return decided, np.nan
1754
+ args = (mask, spacing, "xyz".index(axis), "elastic", contrast, tol,
1755
+ _bound(maxiter, "elastic", mask.shape), device, solver) # fmt: skip
1756
+ value, it, res, average = _effective(*args)
1757
+ tally["solutions"] += 1
1758
+ tally["iterations"] = max(tally["iterations"], int(it))
1759
+ tally["residual"] = max(tally["residual"], float(res))
1760
+ bears = _decision(args, value, average, cut, solver, tally)
1761
+ if bears and solver == "fe" and value < _CONFIRM * cut and tol > _FLOOR:
1762
+ tally["confirmed"] += 1
1763
+ args = (*args[:5], _FLOOR, *args[6:])
1764
+ value, it, res, average = _effective(*args)
1765
+ tally["iterations"] = max(tally["iterations"], int(it))
1766
+ bears = _decision(args, value, average, cut, solver, tally)
1767
+ if bears:
1768
+ tally["rigid"] = min(tally["rigid"], value)
1769
+ known.append((packed, bears))
1770
+ return bears, value
1771
+
1772
+
1773
+ def _tally() -> dict:
1774
+ """The counts of :func:`_bears`."""
1775
+ return {"solutions": 0, "decided": 0, "iterations": 0, "residual": 0.0, "floppy": -np.inf,
1776
+ "rigid": np.inf, "unresolved": 0, "confirmed": 0, "planar": []} # fmt: skip
1777
+
1778
+
1779
+ def _rigidity_size(generate, size, lower, upper, tol, realizations, base, phase, axis,
1780
+ contrast, cut, solver_tol, maxiter, device, tally, solver="fft"): # fmt: skip
1781
+ """The bisection of :func:`rigidity_threshold` on the boxes ``size`` voxels across, the
1782
+ realizations seeded from ``(base, size)``: its :class:`PercolationThreshold`, whether
1783
+ each realization bears at its fractions (rows) and their moduli; ``tally`` counts."""
1784
+ sub = np.random.SeedSequence(base.entropy, spawn_key=(*base.spawn_key, size))
1785
+ seeds = _bisection(lower, upper, tol, realizations, sub)
1786
+ known = [[] for _ in seeds] # the images solved of each realization, packed
1787
+ computed: dict[float, tuple[np.ndarray, np.ndarray]] = {}
1788
+
1789
+ def probability(fraction):
1790
+ bearing, moduli = np.zeros(len(seeds), dtype=bool), np.full(len(seeds), np.nan)
1791
+ for i, s in enumerate(seeds):
1792
+ image = generate(fraction, np.random.default_rng(s), size)
1793
+ mask = _mask(image, phase)
1794
+ if axis not in _axes(mask):
1795
+ raise ValueError(f"axis: x or y for a planar image, got {axis!r}")
1796
+ tally["planar"].append(mask.shape[2] == 1)
1797
+ bearing[i], moduli[i] = _bears(mask, _spacing(image), axis, known[i], contrast, cut,
1798
+ solver_tol, maxiter, device, tally,
1799
+ solver) # fmt: skip
1800
+ computed[fraction] = bearing, moduli
1801
+ return float(bearing.mean())
1802
+
1803
+ # the phase grows with the fraction or shrinks, and so does the share that bears: the
1804
+ # bounds are tried last, the images far above the threshold costing most to factorize
1805
+ shares = [_mask(generate(f, np.random.default_rng(seeds[0]), size), phase).mean()
1806
+ for f in (lower, upper)] # fmt: skip
1807
+ result = _bisect(probability, lower, upper, tol, len(seeds), "bearing",
1808
+ rising=bool(shares[1] >= shares[0])) # fmt: skip
1809
+ rows = [computed[f] for f in result.fractions.tolist()]
1810
+ return result, np.array([b for b, _ in rows]), np.array([m for _, m in rows])
1811
+
1812
+
1813
+ def _rigidity_fit(sizes, results, bearing, moduli, nu, fit_nu, contrast, cut, tally,
1814
+ solver="fft"): # fmt: skip
1815
+ """The :class:`RigidityThreshold` of the bisections ``results`` of the ``sizes``."""
1816
+ if nu is None:
1817
+ nu = NU_2D if all(tally["planar"]) else NU_3D
1818
+ thresholds = np.array([r.threshold for r in results])
1819
+ brackets = np.array([r.bracket for r in results])
1820
+ widths = brackets[:, 1] - brackets[:, 0]
1821
+ pc, a, theta, residuals, errors = _scaling_fit(
1822
+ np.asarray(sizes, dtype=float), thresholds, widths, float(nu), fit_nu
1823
+ )
1824
+ floppy, rigid = tally["floppy"], tally["rigid"]
1825
+ return RigidityThreshold(
1826
+ sizes=np.asarray(sizes),
1827
+ thresholds=thresholds,
1828
+ brackets=brackets,
1829
+ threshold=pc,
1830
+ stderr=float(errors[0]),
1831
+ amplitude=a,
1832
+ nu=1.0 / theta if fit_nu else float(nu),
1833
+ nu_stderr=float(errors[2]) / theta**2 if fit_nu else None,
1834
+ residuals=residuals,
1835
+ results=tuple(results),
1836
+ contrast=float(contrast),
1837
+ cut=float(cut),
1838
+ floppy=float(floppy) if np.isfinite(floppy) else np.nan,
1839
+ rigid=float(rigid) if np.isfinite(rigid) else np.nan,
1840
+ solutions=tally["solutions"],
1841
+ decided=tally["decided"],
1842
+ iterations=tally["iterations"],
1843
+ residual=tally["residual"],
1844
+ bearing=tuple(bearing),
1845
+ moduli=tuple(moduli),
1846
+ solver=solver,
1847
+ unresolved=tally["unresolved"],
1848
+ confirmed=tally["confirmed"],
1849
+ )
1850
+
1851
+
1852
+ def rigidity_threshold(
1853
+ generate: Callable[[float, np.random.Generator, int], object],
1854
+ sizes,
1855
+ lower: float = 0.0,
1856
+ upper: float = 1.0,
1857
+ *,
1858
+ nu: float | None = None,
1859
+ fit_nu: bool = False,
1860
+ phase: int = 1,
1861
+ axis: str = "x",
1862
+ cut: float | None = None,
1863
+ contrast: float = 0.0,
1864
+ realizations: int = 9,
1865
+ tol: float = 0.005,
1866
+ solver_tol: float | None = None,
1867
+ maxiter: int | None = None,
1868
+ device: str = "auto",
1869
+ solver: str = "fft",
1870
+ seed: SeedLike = None,
1871
+ ) -> RigidityThreshold:
1872
+ """Rigidity threshold of a phase of a family of microstructures: the fraction from which
1873
+ its elastic moduli by the FFT solver do not vanish, the other phases void, by the
1874
+ finite-size scaling of the fractions at which half the realizations of boxes of each of
1875
+ the ``sizes`` bear.
1876
+
1877
+ The trilinear voxels of the FFT solvers (:mod:`morphogen.homogenization.fft`) join
1878
+ through the nodes they share, but a corner is a ball joint and an edge a hinge (in 2-D a
1879
+ corner is a hinge), about which they turn freely; only a face (an edge in 2-D) welds
1880
+ them. The clusters welded by their faces are rigid bodies pinned together at the
1881
+ corners and edges between them, and the moduli of the phase are not zero when these
1882
+ bodies and joints make a rigid network wrapping around the periodic box: from a
1883
+ fraction between the thresholds of percolation through 26 and 6 neighbours (8 and 4 in
1884
+ 2-D), which no connectivity gives (the rigidity percolation of central-force networks,
1885
+ of bodies and joints, whereas the bond-bending forces of lattice models make every
1886
+ connected cluster rigid). A realization bears when its modulus of a uniaxial strain
1887
+ along ``axis`` (C_xxxx along x; Young's modulus 1 and Poisson's ratio 0.3), the other
1888
+ phases at ``contrast`` times the properties of the phase (void at the default 0),
1889
+ exceeds ``cut``; the fraction p½(L) at which half the realizations of the boxes L
1890
+ voxels across bear is bisected as in :func:`percolation_threshold` (``realizations``,
1891
+ ``tol``; common random numbers: for a family growing with the fraction, the median of
1892
+ the fractions from which the realizations bear), each size from a seed of its own
1893
+ derived from ``seed`` (the realizations of :func:`percolation_scaling` with the same
1894
+ seed, which bear from fractions between those where they join through 26 and 6
1895
+ neighbours), and the p½(L) are extrapolated as ``p½(L) = p_c + a * L**(-1/nu)`` by the
1896
+ fit of :func:`percolation_scaling` (``nu``, ``fit_nu``; by default the exponent of
1897
+ random percolation, 4/3 in 2-D, 0.8765 in 3-D; that of the rigidity percolation of
1898
+ central-force networks is 1.21 +/- 0.06 in 2-D, Jacobs & Thorpe 1996).
1899
+
1900
+ The criterion is that of the moduli themselves, from the energy of each solution, the
1901
+ mean of σ : ε, which equals the stress average σ_xx at the exact solution but is
1902
+ stationary: an upper bound whose error is of second order in that of the solution, that
1903
+ of the stress average being of first order. A realization does not bear when its energy
1904
+ is at or under ``cut``; above it, it bears when its stress average agrees with its
1905
+ energy within half of it (the modulus resolved), and otherwise (``unresolved``) by two
1906
+ more solutions with the element matrices perturbed at their round-off (2.2e-16 of their
1907
+ entries), bearing when the three energies agree within 1 % (``solver="fe"``), or by its
1908
+ stress average (``"fft"``, whose iterations stop short of the round-off). The floppy
1909
+ images of large boxes need it: their mechanisms take displacements of 1e3 to 7e5 for a
1910
+ unit strain, which the round-off of the element matrices, the same in every voxel,
1911
+ strains, so that their stress averages stray to -1e-10 to -6e-7 at any tolerance and
1912
+ their energies, 1e-20 to 2e-7, scatter by 17 to 50 % when the element matrices are
1913
+ perturbed, while those of the images that bear move by 1.4e-3 at most and agree with
1914
+ their stress averages within 30 %. The criterion wants solutions that have resolved the
1915
+ soft modes of the floppy images: the voxels factorized iterate to ``solver_tol``, by
1916
+ default 1e-10, and an energy that bears under 1000 times the cut is decided again by a
1917
+ solution at 1e-11, near the floor of the residual (``confirmed``). At 1e-8 one to three
1918
+ iterations leave floppy images at energies of 1e-13 to 2e-8 whose stress averages
1919
+ agree with them: 23 of 32 realizations of 32³ to 80³ voxels of the sites of the cubic
1920
+ lattice bore from fractions lower by 0.0003 to 0.003 than at 1e-10, where such energies
1921
+ fall to 1e-21 to 1e-14; at 1e-10 a few keep 1e-12 to 3e-11, their stress averages and
1922
+ perturbations agreeing (the iterates, not the mechanisms, carry them), and fall under the
1923
+ cut at 1e-11 or take stress averages of the opposite sign, while a modulus of 2.0e-12 on
1924
+ 64³ voxels stays to three digits. Void around, the moduli of the realizations that bear
1925
+ then spread down to 1.2e-12 without a gap (77 of the 5,308 solutions that bear on 8³ to
1926
+ 80³ voxels of the sites near their thresholds lie between 1e-12 and 1e-10). The cut is
1927
+ the round-off of the moduli of the solver, by default (:data:`CUTS`) 1e-8 for the FFT
1928
+ solver and 1e-12 for the voxels factorized, whose energies resolve the moduli down to
1929
+ it; p½(L) lies where the moduli of half the realizations exceed it, and a cut too high
1930
+ biases it up as the moduli come down with the box. With a contrast δ the realizations
1931
+ that do not bear take δ times an enhancement that rises
1932
+ steeply as they approach their own rigidity (up to 650 on 32² pixels and 4,400 on 64²
1933
+ for the sites of the square lattice), while those that have just become rigid bear as
1934
+ little as 2e-6 (32²): a cut that is a multiple of δ must exceed the one and stay below
1935
+ the other, which δ = 1e-8 (the default of :func:`percolation_exponent`) does not allow;
1936
+ ``cut`` must exceed ``contrast``. The median of the realizations' fractions is robust
1937
+ where the moduli spread over decades and needs no exponent, where the crossing of the
1938
+ curves L^(f/nu) <C(p)> presupposes f, the exponent sought, from means that scatter by
1939
+ tens of percent.
1940
+
1941
+ The images are decided without the solver when they can be: the phase does not bear
1942
+ when none of its components wraps around the box along the axis through 26 neighbours
1943
+ (8 in 2-D: they translate freely), it bears when a component joined by faces (6; 4 in
1944
+ 2-D) wraps (a rigid body), and, the moduli growing with the stiffness of the voxels, an
1945
+ image that contains an image of the same realization that bears bears and one contained
1946
+ in an image that does not does not (the images of a family growing with the fraction).
1947
+ The others are solved by conjugate gradients of tolerance ``solver_tol`` (by default
1948
+ :data:`SOLVER_TOLS`: 1e-8 for the FFT solver, 1e-10 for the voxels factorized) and at most
1949
+ ``maxiter`` iterations (by default 50 L + 1000, L the largest dimension: near the
1950
+ threshold the solutions of the FFT solver take up to 45 L, more than its 20 L + 1000),
1951
+ by the FFT solver on ``device`` (``solver="fft"``; ``"cpu"``, ``"gpu"`` or ``"auto"``)
1952
+ or (``solver="fe"``) by the same trilinear voxels assembled on those of the phase and
1953
+ preconditioned by the sparse factorization of their matrix, on the CPU
1954
+ (:mod:`morphogen.homogenization.voxel_fe`): the same moduli, to the tolerance, in one to
1955
+ three iterations, where the Fourier preconditioner of a homogeneous medium spreads the
1956
+ displacements of the voxels over the void around them and the clusters pinned at their
1957
+ corners turn about them with a vanishing energy, on the voxels that bear alone
1958
+ (:func:`~morphogen.homogenization.voxel_fe.load_bearing`: the same moduli, 15 to 25 %
1959
+ fewer voxels). For a family whose phase grows with the fraction (shrinks), the bounds
1960
+ are tried last and only when the bracket reaches them: the images far above the
1961
+ threshold cost most to factorize (on 48³ voxels of sites 122 s at 0.2096 against 1.5 s
1962
+ at 0.1307). The result counts the ``solutions``, the images ``decided`` and the energies
1963
+ ``unresolved``, gives the largest modulus solved under the cut (``floppy``) and the
1964
+ smallest of those that bear (``rigid``), and the shares, decisions and moduli of the
1965
+ fractions tried.
1966
+
1967
+ For the sites of the square lattice (400 realizations of 16² to 128² pixels and 300 of
1968
+ 192² and 256², each bisected to its own threshold, its images nested, ``solver="fe"``,
1969
+ the cut 1e-12 and the tolerance 1e-10), p½(L) = 0.4397, 0.4564, 0.4547, 0.4559,
1970
+ 0.4595, 0.4611, 0.4614, 0.4617 and 0.4612, flat from 96² on, extrapolate to p_c =
1971
+ 0.4617 +/- 0.0004 with the exponent of the fit free (1.5 +/- 0.2: ``nu`` 4/3 does not
1972
+ fit them, a chi-square of 34 for 7 degrees of freedom), and the widths of the
1973
+ realizations' thresholds fall as L**(-1/nu) with nu = 1.14 +/- 0.02 (central-force
1974
+ rigidity percolation in 2-D: 1.21 +/- 0.06, Jacobs & Thorpe 1996), the share that bears
1975
+ at p_c staying at about one half from 96² on; a quarter of the way from the threshold
1976
+ through 8 neighbours, 0.4073, to that through 4, 0.5927. The first measurement, 96
1977
+ realizations bisected to 0.0035 by the stress averages at the cut 1e-8, gave 0.4627 +/-
1978
+ 0.0016 (32 realizations by the FFT solver: 0.4647 +/- 0.0056, the decisions the same).
1979
+ For the sites of the cubic lattice (1,725 realizations of 8³ to 80³ voxels, each
1980
+ bisected to its own threshold, at the tolerance 1e-10 with the confirmations), p½(L) =
1981
+ 0.1356, 0.1338, 0.1332, 0.1316, 0.1321, 0.1314, 0.1313, 0.1309 and 0.1308 extrapolate to
1982
+ p_c = 0.1304 +/- 0.0002 (``nu`` 0.8765; 0.1300 +/- 0.0003 from 32³, the means 0.1303
1983
+ +/- 0.0001; the shares of 48³ to 80³ voxels cross at 0.1302, a third of the
1984
+ realizations bearing at p_c whatever the box; the widths give nu = 0.76 +/- 0.03),
1985
+ between the thresholds through 26 and 18 neighbours, 0.0975 and 0.1383, far below that
1986
+ through the faces, 0.3116: the corners alone hold the voxels. At the tolerance 1e-8,
1987
+ where floppy images bear, the first measurement (192 realizations of 8³ to 48³ voxels)
1988
+ gave 0.12904 +/- 0.00029, and 0.1307 +/- 0.0009 by the stress averages of 96
1989
+ realizations of 8³ to 32³. Boolean discs of 4
1990
+ pixels of radius and spheres of 3 voxels (64 realizations, 32² to 256² pixels and 24³ to
1991
+ 48³ voxels) bear from 0.608 +/- 0.006 and 0.202 +/- 0.004, between their thresholds
1992
+ through 8 and 4 neighbours (0.596 and 0.624) and through 26 and 6 (0.182 and 0.236),
1993
+ their p½(L) near those through the corners: their grains meet at several nodes, which
1994
+ brace them, where the sites meet at one. With :func:`percolation_exponent`::
1995
+
1996
+ def squares(fraction, rng, size):
1997
+ return rng.random((size, size, 1)) < fraction
1998
+
1999
+ sizes = [16, 24, 32, 48, 64, 96, 128, 192, 256]
2000
+ rigid = rigidity_threshold(squares, sizes, 0.38, 0.58, realizations=96, tol=0.0035,
2001
+ solver="fe", seed=2026)
2002
+ result = percolation_exponent(squares, sizes, rigid.threshold,
2003
+ threshold_stderr=rigid.stderr, physics="elastic",
2004
+ contrast=0.0, realizations=64, solver="fe", seed=2027)
2005
+
2006
+ (the measurements above bisected each realization to its own threshold instead, the
2007
+ images nested, by these decisions).
2008
+ """
2009
+ if axis not in ("x", "y", "z"):
2010
+ raise ValueError(f"axis: x, y or z (x or y for a planar image), got {axis!r}")
2011
+ _check_solver(solver)
2012
+ cut = CUTS[solver] if cut is None else cut
2013
+ solver_tol = SOLVER_TOLS[solver] if solver_tol is None else solver_tol
2014
+ need, fitted = (4, "p_c, a and nu") if fit_nu else (3, "p_c and a")
2015
+ values = _check_sizes(sizes, need, fitted)
2016
+ if nu is not None and not nu > 0.0:
2017
+ raise ValueError(f"nu: expected a positive exponent, got {nu!r}")
2018
+ if not (np.isfinite(contrast) and 0.0 <= contrast < 1.0):
2019
+ raise ValueError(f"contrast: expected 0 <= contrast < 1, got {contrast!r}")
2020
+ if not (np.isfinite(cut) and contrast < cut < 1.0):
2021
+ raise ValueError(f"cut: expected a modulus between the contrast ({contrast:g}) and 1, "
2022
+ f"got {cut!r}") # fmt: skip
2023
+ if not solver_tol > 0.0:
2024
+ raise ValueError(f"solver_tol: expected a positive tolerance, got {solver_tol!r}")
2025
+ if maxiter is not None and (isinstance(maxiter, bool) or int(maxiter) != maxiter
2026
+ or maxiter < 1): # fmt: skip
2027
+ raise ValueError(f"maxiter: expected a positive integer, got {maxiter!r}")
2028
+ base, tally = _base_seed(seed), _tally()
2029
+ runs = [_rigidity_size(generate, size, lower, upper, tol, realizations, base, phase, axis,
2030
+ float(contrast), float(cut), solver_tol, maxiter, device, tally,
2031
+ solver) for size in values.tolist()] # fmt: skip
2032
+ results, bearing, moduli = zip(*runs, strict=True)
2033
+ return _rigidity_fit(values, results, bearing, moduli, nu, fit_nu, contrast, cut, tally,
2034
+ solver) # fmt: skip