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,924 @@
1
+ """Nested models: structures placed in, or around, the phases of others.
2
+
3
+ * ``cox_spheres``: spheres clustered in the phase 1 of another model (aggregates of
4
+ particles in nanocomposites, at any number of scales): a Cox (doubly stochastic)
5
+ Boolean model, or hard-core spheres placed among its germs.
6
+ * ``coating``: a layer of constant thickness around the phase 1 of a model (an
7
+ interphase), or a shell inside it (hollow members: spheres, fibres, struts).
8
+ * ``fractal_sponge``: the attractor of an iterated function system on a cubic grid (the
9
+ Menger sponge, Cantor dust, the Vicsek fractal, or any set of sub-cubes), iterated a
10
+ finite number of times.
11
+
12
+ Hierarchical lattices of hollow tubes are in :mod:`morphogen.models.hierarchical`, and
13
+ the ``nested`` operation of :mod:`morphogen.models.combination` fills the phase 1 of a
14
+ structure with another.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import math
20
+ from dataclasses import dataclass
21
+ from typing import ClassVar
22
+
23
+ import numpy as np
24
+ from scipy import ndimage
25
+
26
+ from morphogen import theory
27
+ from morphogen._utils import check_fraction, check_positive
28
+ from morphogen.distributions import Constant, Distribution
29
+ from morphogen.domain import Domain, Grid
30
+ from morphogen.image import VoxelImage
31
+ from morphogen.kernels.rsa import rsa_insert
32
+ from morphogen.models.affine import ANISOTROPY, Anisotropy, anisotropic
33
+ from morphogen.models.base import Microstructure, Model, param, register, register_kind
34
+ from morphogen.models.implicit import band_of
35
+ from morphogen.models.union import PrimitiveUnion
36
+ from morphogen.primitives import Segments, Spheres
37
+ from morphogen.seeding import SeedLike, make_rng, seed_from_description
38
+
39
+
40
+ def _child_seeds(rng, seed_info, n: int) -> list:
41
+ """Seeds of the parts of a nested realization, derived from its own seed."""
42
+ if seed_info is not None:
43
+ return list(seed_from_description(seed_info).spawn(n))
44
+ return list(rng.spawn(n))
45
+
46
+
47
+ def _supersampled(fine: np.ndarray, grid: Grid, ss: int) -> np.ndarray:
48
+ nx, ny, nz = grid.shape
49
+ return fine.reshape(nx, ss, ny, ss, nz, ss).mean(axis=(1, 3, 5), dtype=np.float32)
50
+
51
+
52
+ # -- clustered spheres ----------------------------------------------------------------------
53
+
54
+
55
+ @register_kind
56
+ class ClusteredSpheres(PrimitiveUnion):
57
+ """Spheres (phase 1) clustered in aggregates, a realization of another model; the
58
+ aggregates outside the spheres may form a phase of their own."""
59
+
60
+ kind = "clustered_spheres"
61
+
62
+ def __init__(self, domain, spheres, aggregates: Microstructure, aggregate_phase=None, **kw):
63
+ super().__init__(domain, spheres=spheres, **kw)
64
+ self.aggregates = aggregates
65
+ self.aggregate_phase = None if aggregate_phase is None else int(aggregate_phase)
66
+
67
+ @property
68
+ def phase_names(self) -> dict[int, str]:
69
+ return self.model.active_phases() if self.model is not None else super().phase_names
70
+
71
+ def voxelize(self, shape=None, *, voxel_size=None, grid: Grid | None = None, supersampling=1):
72
+ image = super().voxelize(
73
+ shape, voxel_size=voxel_size, grid=grid, supersampling=supersampling
74
+ )
75
+ if self.aggregate_phase is None or supersampling != 1:
76
+ return image
77
+ inside = self.aggregates.voxelize(grid=image.grid()).data == 1
78
+ data = image.data.copy()
79
+ data[(data == 0) & inside] = self.aggregate_phase
80
+ return image.with_data(data)
81
+
82
+ def implicit_phases(self) -> list[int]:
83
+ phases = {0, 1}
84
+ if self.aggregate_phase is not None:
85
+ phases.add(self.aggregate_phase)
86
+ return sorted(phases)
87
+
88
+ def phase_level_set(
89
+ self, phase: int, shape=None, *, voxel_size=None, grid: Grid | None = None
90
+ ) -> VoxelImage:
91
+ """The implicit function of a phase (see :meth:`Microstructure.phase_level_set`):
92
+ the spheres by their signed distance; the aggregates, when a phase of their own,
93
+ by the level set of their structure outside the spheres."""
94
+ phase = int(phase)
95
+ if phase not in self.implicit_phases():
96
+ raise ValueError(f"phase {phase}: the phases are {self.implicit_phases()}")
97
+ if self.aggregate_phase in (None, 0):
98
+ return Microstructure.phase_level_set(self, phase, shape, voxel_size=voxel_size,
99
+ grid=grid) # fmt: skip
100
+ grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
101
+ spheres = np.asarray(self.level_set(grid=grid).data, dtype=np.float32)
102
+ zone = np.asarray(self.aggregates.level_set(grid=grid).data, dtype=np.float32)
103
+ if self.aggregate_phase == 1: # one phase with the spheres
104
+ data = np.minimum(spheres, zone)
105
+ data = data if phase == 1 else -data
106
+ elif phase == 1:
107
+ data = spheres
108
+ elif phase == self.aggregate_phase:
109
+ data = np.maximum(zone, -spheres)
110
+ else:
111
+ data = -np.minimum(spheres, zone)
112
+ return VoxelImage.from_grid(data, grid, name="level_set", metadata=self.image_metadata())
113
+
114
+ def phase_level_sets_at(self, points, reach: float = np.inf) -> dict[int, np.ndarray]:
115
+ """The functions of :meth:`phase_level_set` at the points: the signed distance to
116
+ the spheres, and the point-wise level set of the aggregates when they form a phase
117
+ of their own."""
118
+ if self.aggregate_phase in (None, 0):
119
+ phi = PrimitiveUnion.level_set_at(self, points, reach)
120
+ return {0: -phi, 1: phi}
121
+ spheres = PrimitiveUnion.level_set_at(self, points, reach)
122
+ zone = np.asarray(self.aggregates.level_set_at(points, reach), dtype=float)
123
+ if self.aggregate_phase == 1: # one phase with the spheres
124
+ phi = np.minimum(spheres, zone)
125
+ return {0: -phi, 1: phi}
126
+ return {
127
+ 0: -np.minimum(spheres, zone),
128
+ 1: spheres,
129
+ self.aggregate_phase: np.maximum(zone, -spheres),
130
+ }
131
+
132
+ def level_set_at(self, points, reach: float = np.inf) -> np.ndarray:
133
+ """The function of phase 1 (:meth:`phase_level_sets_at`)."""
134
+ return self.phase_level_sets_at(points, reach)[1]
135
+
136
+ def implicit_pieces(self, depth: float = 0.0) -> tuple[list, int] | None:
137
+ """The pieces of the spheres (:meth:`PrimitiveUnion.implicit_pieces`), when the
138
+ aggregates are not a phase of their own nor of the spheres; None otherwise."""
139
+ if self.aggregate_phase not in (None, 0):
140
+ return None
141
+ return super().implicit_pieces(depth)
142
+
143
+ def summary(self) -> dict:
144
+ out = super().summary()
145
+ out.update({f"aggregates_{k}": v for k, v in self.aggregates.summary().items()})
146
+ return out
147
+
148
+ def _geometry(self) -> dict:
149
+ geo = super()._geometry()
150
+ geo["aggregates"] = self.aggregates.to_dict()
151
+ if self.aggregate_phase is not None:
152
+ geo["aggregate_phase"] = self.aggregate_phase
153
+ return geo
154
+
155
+ @classmethod
156
+ def _from_geometry(cls, domain, geometry, **kwargs):
157
+ spheres = Spheres.from_dict(geometry["spheres"]) if "spheres" in geometry else None
158
+ aggregates = Microstructure.from_dict(geometry["aggregates"])
159
+ return cls(domain, spheres, aggregates, geometry.get("aggregate_phase"), **kwargs)
160
+
161
+
162
+ @register
163
+ @anisotropic
164
+ @dataclass(frozen=True)
165
+ class CoxSpheres(Model):
166
+ """Spheres clustered in the phase 1 of another model: a Cox Boolean model.
167
+
168
+ The centres of the spheres are Poisson points of intensity ``theta_1`` in the
169
+ aggregates (the phase 1 of ``aggregates``, any model, Cox spheres included) and
170
+ ``theta_0`` outside, the spheres being whole (Jeulin & Moreaud 2007; Jean, Jeulin,
171
+ Forest et al. 2011 for carbon black in rubber). With ``hardcore``, non-overlapping
172
+ spheres are placed among such germs by random sequential addition instead. The
173
+ fractions are local: that of the spheres within the aggregates and outside them.
174
+ """
175
+
176
+ name = "cox_spheres"
177
+ phases: ClassVar[dict[int, str]] = {0: "matrix", 1: "spheres"}
178
+ count_label = "spheres"
179
+
180
+ aggregates: Model = param(
181
+ doc="Model whose phase 1 holds the spheres (aggregates)", kind="model"
182
+ )
183
+ radius: Distribution = param(
184
+ Constant(1.0), doc="Sphere radius (number or distribution)", kind="distribution",
185
+ unit="length",
186
+ ) # fmt: skip
187
+ local_fraction: float | None = param(
188
+ None, doc="Volume fraction of the spheres in the aggregates", kind="fraction"
189
+ )
190
+ intensity: float | None = param(
191
+ None, doc="Number of sphere centres per unit volume of the aggregates", unit="1/length^3"
192
+ )
193
+ outside_fraction: float = param(
194
+ 0.0, doc="Volume fraction of the spheres outside the aggregates", kind="fraction"
195
+ )
196
+ hardcore: bool = param(
197
+ False, doc="Non-overlapping spheres (random sequential addition)", kind="bool"
198
+ )
199
+ min_gap: float = param(0.0, doc="Hard-core spheres: minimal gap between them", unit="length")
200
+ aggregate_phase: int | None = param(
201
+ None, doc="Phase of the aggregates outside the spheres (default: the matrix)", kind="int"
202
+ )
203
+ anisotropy: Anisotropy | None = param(None, doc=ANISOTROPY, kind="anisotropy", kw_only=True)
204
+
205
+ def _validate(self) -> None:
206
+ if (self.local_fraction is None) == (self.intensity is None):
207
+ raise ValueError("give exactly one of 'local_fraction' and 'intensity'")
208
+ if self.local_fraction is not None:
209
+ check_fraction(self.local_fraction, "local_fraction")
210
+ else:
211
+ check_positive(self.intensity, "intensity")
212
+ if self.hardcore:
213
+ raise ValueError("hard-core spheres: give their local_fraction")
214
+ if not 0.0 <= self.outside_fraction < 1.0:
215
+ raise ValueError("outside_fraction: in [0, 1)")
216
+ check_positive(self.min_gap, "min_gap", allow_zero=True)
217
+ if self.aggregate_phase is not None and not 2 <= self.aggregate_phase <= 255:
218
+ raise ValueError("aggregate_phase: a phase index from 2 to 255")
219
+
220
+ @property
221
+ def has_level_set(self) -> bool:
222
+ return self.aggregate_phase is None
223
+
224
+ @property
225
+ def supports_periodic(self) -> bool:
226
+ return self.aggregates.supports_periodic
227
+
228
+ def active_phases(self) -> dict[int, str]:
229
+ out = dict(self.phases)
230
+ if self.aggregate_phase is not None:
231
+ out[self.aggregate_phase] = f"aggregates ({self.aggregates.name})"
232
+ return out
233
+
234
+ @property
235
+ def mean_volume(self) -> float:
236
+ return 4.0 / 3.0 * math.pi * self.radius.moment(3)
237
+
238
+ @property
239
+ def intensities(self) -> tuple[float, float]:
240
+ """Intensities of the germs in and out of the aggregates (Boolean spheres)."""
241
+ inside = (
242
+ self.intensity
243
+ if self.intensity is not None
244
+ else theory.boolean_intensity(self.local_fraction, self.mean_volume)
245
+ )
246
+ outside = theory.boolean_intensity(self.outside_fraction, self.mean_volume)
247
+ return inside, outside
248
+
249
+ def generate(self, domain: Domain, seed: SeedLike = None) -> ClusteredSpheres:
250
+ self._check_domain(domain)
251
+ rng, seed_info = make_rng(seed)
252
+ seeds = _child_seeds(rng, seed_info, 2)
253
+ rmax = self.radius.upper()
254
+ reach = (2.0 * rmax + self.min_gap) if self.hardcore else rmax
255
+ if domain.periodic:
256
+ if 2.0 * reach >= min(domain.size):
257
+ raise ValueError("cox_spheres: spheres too large for the periodic box")
258
+ window = domain
259
+ else:
260
+ window = domain.dilated(reach)
261
+ aggregates = self.aggregates.generate(window, seeds[0])
262
+ local = np.random.default_rng(seeds[1])
263
+ if self.hardcore:
264
+ centers, radii = self._hardcore(window, aggregates, local)
265
+ else:
266
+ inside, outside = self.intensities
267
+ top = max(inside, outside)
268
+ n = local.poisson(top * window.volume)
269
+ centers = window.lower + local.random((n, 3)) * window.lengths
270
+ rate = np.where(aggregates.contains(centers), inside, outside)
271
+ centers = centers[local.random(n) * top < rate]
272
+ radii = self.radius.sample(local, len(centers))
273
+ spheres = Spheres(centers, radii)
274
+ if not domain.periodic:
275
+ spheres = spheres.subset(domain.distance_to_box(spheres.centers) <= spheres.radii)
276
+ return ClusteredSpheres(
277
+ domain, spheres, aggregates, self.aggregate_phase, model=self, seed=seed_info
278
+ )
279
+
280
+ def _hardcore(self, window: Domain, aggregates: Microstructure, rng):
281
+ """Random sequential addition among the germs of the Cox process (a periodic box,
282
+ cropped later for non-periodic domains)."""
283
+ probe = window.lower + rng.random((20000, 3)) * window.lengths
284
+ p_in = float(aggregates.contains(probe).mean())
285
+ target = window.volume * (p_in * self.local_fraction + (1 - p_in) * self.outside_fraction)
286
+ radii = np.empty(0)
287
+ while np.sum(4.0 / 3.0 * math.pi * radii**3) < target:
288
+ more = self.radius.sample(rng, int(0.2 * target / self.mean_volume) + 16)
289
+ radii = np.concatenate([radii, more])
290
+ if radii.size == 0:
291
+ return np.zeros((0, 3)), radii
292
+ cum = np.cumsum(4.0 / 3.0 * math.pi * radii**3)
293
+ radii = np.sort(radii[: int(np.searchsorted(cum, target)) + 1])[::-1].copy()
294
+ top = max(self.local_fraction, self.outside_fraction)
295
+ box = window.lengths
296
+ reach = 2.0 * radii.max() + self.min_gap if radii.size else 1.0
297
+ cell_n = np.maximum(1, np.floor(box / reach)).astype(np.int64)
298
+ cell_h = box / cell_n
299
+ head = np.full(int(np.prod(cell_n)), -1, dtype=np.int64)
300
+ nxt = np.full(len(radii), -1, dtype=np.int64)
301
+ pos = np.zeros((len(radii), 3))
302
+ placed, attempts, budget = 0, 0, 20_000 * max(len(radii), 1)
303
+ while placed < len(radii) and attempts < budget:
304
+ cand = rng.random((8192, 3)) * box
305
+ rate = np.where(
306
+ aggregates.contains(window.lower + cand), self.local_fraction, self.outside_fraction
307
+ )
308
+ cand = np.ascontiguousarray(cand[rng.random(len(cand)) * top < rate])
309
+ placed, _ = rsa_insert(
310
+ radii, float(self.min_gap), box, cell_h, cell_n, head, nxt, pos, placed, cand
311
+ )
312
+ attempts += 8192
313
+ if placed < len(radii):
314
+ raise RuntimeError(
315
+ f"cox_spheres: {placed} of {len(radii)} hard-core spheres placed; lower the "
316
+ "local fraction (random sequential addition jams near 0.38 for equal spheres)"
317
+ )
318
+ return window.lower + pos, radii
319
+
320
+ def expected_count(self, domain: Domain) -> float | None:
321
+ """Mean number of sphere centres in the domain (Boolean spheres)."""
322
+ try:
323
+ p = self.aggregates.theory(domain)["volume_fraction"]
324
+ except (KeyError, ValueError, NotImplementedError):
325
+ return None
326
+ if self.hardcore:
327
+ return (
328
+ domain.volume
329
+ * (p * self.local_fraction + (1 - p) * self.outside_fraction)
330
+ / (self.mean_volume)
331
+ )
332
+ inside, outside = self.intensities
333
+ return (inside * p + outside * (1.0 - p)) * domain.volume
334
+
335
+ def theory(self, domain: Domain | None = None) -> dict[str, float]:
336
+ """Fractions when the spheres are small compared with the aggregates (a sphere
337
+ rarely straddles their boundary): ``1 - p exp(-theta_1 V) - (1 - p) exp(-theta_0
338
+ V)`` for Boolean spheres, ``p f_1 + (1 - p) f_0`` for hard-core ones, ``p`` being
339
+ the fraction of the aggregates."""
340
+ try:
341
+ p = self.aggregates.theory(domain).get("volume_fraction")
342
+ except (ValueError, NotImplementedError):
343
+ p = None
344
+ inside, outside = self.intensities
345
+ out = {"intensity_inside": inside, "intensity_outside": outside}
346
+ if p is None:
347
+ return out
348
+ out["aggregate_fraction"] = p
349
+ if self.hardcore:
350
+ out["volume_fraction"] = p * self.local_fraction + (1 - p) * self.outside_fraction
351
+ return out
352
+ v = self.mean_volume
353
+ q_in, q_out = math.exp(-inside * v), math.exp(-outside * v)
354
+ out["volume_fraction"] = 1.0 - p * q_in - (1.0 - p) * q_out
355
+ area = 4.0 * math.pi * self.radius.moment(2)
356
+ out["specific_surface"] = area * (inside * p * q_in + outside * (1.0 - p) * q_out)
357
+ return out
358
+
359
+
360
+ # -- coatings and shells ---------------------------------------------------------------------
361
+
362
+
363
+ def _signed_distance(inner: Microstructure, grid: Grid, band: float) -> tuple:
364
+ """Phases of a structure on a grid and the signed distance to its phase 1 (negative
365
+ inside): exact for unions of spheres and segments, from the Euclidean distance
366
+ transform of the voxels otherwise."""
367
+ phases = inner.voxelize(grid=grid).data
368
+ if isinstance(inner, PrimitiveUnion):
369
+ return phases, inner.level_set(grid=grid, band=band).data.astype(np.float64)
370
+ solid = phases == 1
371
+ h = grid.spacing
372
+ wrap = "wrap" if inner.domain.periodic else "nearest"
373
+ outside = _edt(~solid, h, wrap, band)
374
+ inside = _edt(solid, h, wrap, band)
375
+ half = 0.5 * float(np.min(h)) # from voxel centres to the interface between them
376
+ return phases, np.where(solid, -(inside - half), outside - half)
377
+
378
+
379
+ def _edt(mask: np.ndarray, spacing, mode: str, band: float = math.inf) -> np.ndarray:
380
+ """Distance from the voxels of ``mask`` to the nearest voxel outside it, exact up to
381
+ ``band`` and at least ``band`` beyond (periodic: on a copy wrapped over the band)."""
382
+ if not mask.any():
383
+ return np.zeros(mask.shape)
384
+ if mask.all():
385
+ return np.full(mask.shape, np.inf)
386
+ if mode == "wrap":
387
+ h = np.broadcast_to(np.asarray(spacing, dtype=float), (mask.ndim,))
388
+ pad = [min(n, math.ceil(band / s) + 1) for n, s in zip(mask.shape, h, strict=True)]
389
+ tiled = np.pad(mask, [(p, p) for p in pad], mode="wrap")
390
+ d = ndimage.distance_transform_edt(tiled, sampling=spacing)
391
+ return d[tuple(slice(p, p + n) for p, n in zip(pad, mask.shape, strict=True))]
392
+ return ndimage.distance_transform_edt(mask, sampling=spacing)
393
+
394
+
395
+ @register_kind
396
+ class CoatedStructure(Microstructure):
397
+ """A structure with a layer around its phase 1 (outside) or a shell inside it."""
398
+
399
+ kind = "coated"
400
+
401
+ def __init__(self, domain, inner, thickness, side, phase, core_phase, bores=None, **kw):
402
+ super().__init__(domain, **kw)
403
+ self.inner = inner
404
+ self.thickness = float(thickness)
405
+ self.side = side
406
+ self.phase = int(phase)
407
+ self.core_phase = int(core_phase)
408
+ self.bores = bores # hollow unions of spheres and segments: the same, thinner
409
+
410
+ @property
411
+ def phase_names(self) -> dict[int, str]:
412
+ return self.model.active_phases() if self.model is not None else super().phase_names
413
+
414
+ def _phases_on(self, grid: Grid) -> np.ndarray:
415
+ if self.bores is not None: # union of the members minus the union of their bores
416
+ outer = self.inner.voxelize(grid=grid).data == 1
417
+ bore = self.bores.voxelize(grid=grid).data == 1
418
+ out = np.zeros(grid.shape, dtype=np.uint8)
419
+ out[outer] = 1
420
+ out[outer & bore] = self.core_phase
421
+ return out
422
+ band = self.thickness + 2.0 * float(np.max(grid.spacing))
423
+ phases, dist = _signed_distance(self.inner, grid, band)
424
+ out = phases.astype(np.uint8, copy=True)
425
+ if self.side == "outside":
426
+ out[(phases == 0) & (dist <= self.thickness)] = self.phase
427
+ else:
428
+ out[(phases == 1) & (dist < -self.thickness)] = self.core_phase
429
+ return out
430
+
431
+ def voxelize(self, shape=None, *, voxel_size=None, grid: Grid | None = None, supersampling=1):
432
+ grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
433
+ ss = int(supersampling)
434
+ if ss == 1:
435
+ data = self._phases_on(grid)
436
+ return VoxelImage.from_grid(data, grid, name="phase", metadata=self.image_metadata())
437
+ fine = Grid(grid.domain, tuple(n * ss for n in grid.shape))
438
+ data = _supersampled((self._phases_on(fine) == 1).astype(np.float32), grid, ss)
439
+ return VoxelImage.from_grid(data, grid, name="fraction", metadata=self.image_metadata())
440
+
441
+ def level_set(self, shape=None, *, voxel_size=None, grid: Grid | None = None) -> VoxelImage:
442
+ """Hollow members (a void core): the union minus the bores (exact sets), or the
443
+ shell ``-t <= d <= 0`` of the signed distance; a coating leaves phase 1 as is."""
444
+ grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
445
+ if self.side == "outside":
446
+ return self.inner.level_set(grid=grid)
447
+ if self.core_phase != 0:
448
+ raise NotImplementedError("a shell with a filled core has three phases")
449
+ if self.bores is not None:
450
+ outer = self.inner.level_set(grid=grid).data.astype(np.float32)
451
+ bore = self.bores.level_set(grid=grid).data.astype(np.float32)
452
+ data = np.maximum(outer, -bore)
453
+ else:
454
+ band = self.thickness + 4.0 * float(np.max(grid.spacing))
455
+ _, dist = _signed_distance(self.inner, grid, band)
456
+ data = np.maximum(dist, -dist - self.thickness).astype(np.float32)
457
+ return VoxelImage.from_grid(data, grid, name="level_set", metadata=self.image_metadata())
458
+
459
+ def implicit_phases(self) -> list[int]:
460
+ if self.side == "outside":
461
+ return sorted({0, 1, self.phase})
462
+ return sorted({0, 1, self.core_phase})
463
+
464
+ def phase_level_set(
465
+ self, phase: int, shape=None, *, voxel_size=None, grid: Grid | None = None
466
+ ) -> VoxelImage:
467
+ """The implicit function of a phase (see :meth:`Microstructure.phase_level_set`),
468
+ from the signed distance ``d`` to the phase 1 of the structure: a coating of
469
+ thickness ``t`` is ``0 < d < t``, a shell ``-t < d < 0`` and its core ``d < -t``
470
+ (hollow unions of spheres and segments: the union minus the bores, and the
471
+ bores). The distance is exact for unions of spheres and segments; for the other
472
+ structures it is that of their voxels on the grid (as in their images)."""
473
+ phase = int(phase)
474
+ if phase not in self.implicit_phases():
475
+ raise ValueError(f"phase {phase}: the phases are {self.implicit_phases()}")
476
+ grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
477
+ clip = band_of(grid)
478
+ t = self.thickness
479
+ if self.bores is not None:
480
+ outer = np.asarray(self.inner.level_set(grid=grid).data, dtype=np.float64)
481
+ bore = np.asarray(self.bores.level_set(grid=grid).data, dtype=np.float64)
482
+ regions = {1: np.maximum(outer, -bore), self.core_phase: np.maximum(outer, bore)}
483
+ outside = -outer
484
+ else:
485
+ _, d = _signed_distance(self.inner, grid, t + clip)
486
+ if self.side == "outside":
487
+ regions = {1: d, self.phase: np.maximum(-d, d - t)}
488
+ outside = t - d
489
+ else:
490
+ regions = {1: np.maximum(d, -d - t), self.core_phase: d + t}
491
+ outside = -d
492
+ # the phases that share an index are one (a core of the phase of the matrix...)
493
+ fields: dict[int, np.ndarray] = {0: outside}
494
+ for k in (1, *(q for q in regions if q != 1)):
495
+ fields[k] = np.minimum(fields[k], regions[k]) if k in fields else regions[k]
496
+ data = np.clip(fields[phase], -clip, clip).astype(np.float32)
497
+ return VoxelImage.from_grid(data, grid, name="level_set", metadata=self.image_metadata())
498
+
499
+ def _exact_distance(self) -> bool:
500
+ """Whether the distance to the phase 1 of the structure is known at any point: a
501
+ union of spheres and segments of two phases (the distance of the other structures
502
+ is that of their voxels, :func:`_signed_distance`)."""
503
+ return isinstance(self.inner, PrimitiveUnion) and self.inner.implicit_phases() == [0, 1]
504
+
505
+ def phase_level_sets_at(self, points, reach: float = np.inf) -> dict[int, np.ndarray]:
506
+ """The functions of :meth:`phase_level_set` at the points, for the coatings and
507
+ shells of a union of spheres and segments (whose signed distance is exact
508
+ there): the same functions of that distance, or of those of the union and of its
509
+ bores. The coatings of the other structures, whose distance is that of their
510
+ voxels, have none."""
511
+ if not self._exact_distance():
512
+ raise NotImplementedError(
513
+ "the coatings and shells of a structure that is not a union of spheres and "
514
+ "segments: the distance to its phase 1 is that of its voxels"
515
+ )
516
+ pts = np.asarray(points, dtype=float).reshape(-1, 3)
517
+ t = self.thickness
518
+ if not np.isfinite(reach):
519
+ reach = 0.1 * float(self.domain.lengths.min()) + t
520
+ reach = float(reach)
521
+ if self.bores is not None:
522
+ outer = self.inner.signed_distance(pts, reach)
523
+ bore = self.bores.signed_distance(pts, reach)
524
+ regions = {1: np.maximum(outer, -bore), self.core_phase: np.maximum(outer, bore)}
525
+ outside = -outer
526
+ else:
527
+ d = self.inner.signed_distance(pts, reach + t)
528
+ if self.side == "outside":
529
+ regions = {1: d, self.phase: np.maximum(-d, d - t)}
530
+ outside = t - d
531
+ else:
532
+ regions = {1: np.maximum(d, -d - t), self.core_phase: d + t}
533
+ outside = -d
534
+ # the phases that share an index are one (a core of the phase of the matrix...)
535
+ fields: dict[int, np.ndarray] = {0: outside}
536
+ for k in (1, *(q for q in regions if q != 1)):
537
+ fields[k] = np.minimum(fields[k], regions[k]) if k in fields else regions[k]
538
+ return {k: np.clip(fields[k], -reach, reach) for k in self.implicit_phases()}
539
+
540
+ def implicit_pieces(self, depth: float = 0.0) -> tuple[list, int] | None:
541
+ """The pieces of a coated union of spheres and segments, or of its hollow
542
+ members (see :mod:`morphogen.models.pieces`): the primitives, then the same with
543
+ their radii increased by the thickness of the coating; the bores of hollow
544
+ members, then the primitives. None for the other structures."""
545
+ from morphogen.models.pieces import Piece, union_pieces
546
+
547
+ inner = self.inner
548
+ if not isinstance(inner, PrimitiveUnion) or inner.implicit_phases() != [0, 1]:
549
+ return None
550
+ if self.side == "outside":
551
+ pieces = [Piece(1, part) for part in union_pieces(inner, 0.0, depth)]
552
+ pieces += [
553
+ Piece(self.phase, part) for part in union_pieces(inner, self.thickness, depth)
554
+ ]
555
+ return pieces, 0
556
+ if self.bores is None:
557
+ return None
558
+ pieces = [Piece(self.core_phase, part) for part in union_pieces(self.bores, 0.0, depth)]
559
+ pieces += [Piece(1, part) for part in union_pieces(inner, 0.0, depth)]
560
+ return pieces, 0
561
+
562
+ @property
563
+ def lipschitz(self) -> float:
564
+ parts = [self.inner] + ([self.bores] if self.bores is not None else [])
565
+ return max(float(getattr(p, "lipschitz", 1.0)) for p in parts)
566
+
567
+ def level_set_at(self, points, reach: float = np.inf) -> np.ndarray:
568
+ """As :meth:`level_set`, at the points: the level set of the structure (coating),
569
+ or the function of phase 1 of :meth:`phase_level_sets_at` (the members of a union
570
+ less their bores, the shell of its signed distance)."""
571
+ if self.side == "outside":
572
+ return self.inner.level_set_at(points, reach)
573
+ return self.phase_level_sets_at(points, reach)[1]
574
+
575
+ def contains(self, points) -> np.ndarray:
576
+ """Phase 1: that of the structure (coating), or its shell (hollow members of
577
+ unions of spheres and segments)."""
578
+ if self.side == "outside":
579
+ return self.inner.contains(points)
580
+ if self.bores is None:
581
+ raise NotImplementedError("point queries of shells need unions of spheres or segments")
582
+ inside = self.inner.contains(points)
583
+ return inside & ~self.bores.contains(points) if self.core_phase != 1 else inside
584
+
585
+ def summary(self) -> dict:
586
+ return {f"inner_{k}": v for k, v in self.inner.summary().items()}
587
+
588
+ def _geometry(self) -> dict:
589
+ geo = {
590
+ "inner": self.inner.to_dict(),
591
+ "thickness": self.thickness,
592
+ "side": self.side,
593
+ "phase": self.phase,
594
+ "core_phase": self.core_phase,
595
+ }
596
+ if self.bores is not None:
597
+ geo["bores"] = self.bores.to_dict()
598
+ return geo
599
+
600
+ @classmethod
601
+ def _from_geometry(cls, domain, geometry, **kwargs):
602
+ bores = geometry.get("bores")
603
+ return cls(
604
+ domain,
605
+ Microstructure.from_dict(geometry["inner"]),
606
+ geometry["thickness"],
607
+ geometry["side"],
608
+ geometry["phase"],
609
+ geometry["core_phase"],
610
+ None if bores is None else Microstructure.from_dict(bores),
611
+ **kwargs,
612
+ )
613
+
614
+
615
+ def bores_of(union: PrimitiveUnion, thickness: float) -> PrimitiveUnion:
616
+ """The same spheres and segments, thinner by ``thickness`` (those thinner than it
617
+ are left out: they stay full)."""
618
+ sph, seg = union.spheres, union.segments
619
+ keep_s = sph.radii > thickness
620
+ keep_g = seg.radii > thickness
621
+ spheres = Spheres(sph.centers[keep_s], sph.radii[keep_s] - thickness)
622
+ segments = Segments(
623
+ seg.start[keep_g], seg.end[keep_g], seg.radii[keep_g] - thickness,
624
+ round_caps=seg.round_caps,
625
+ ) # fmt: skip
626
+ return PrimitiveUnion(union.domain, spheres=spheres, segments=segments)
627
+
628
+
629
+ @register
630
+ @dataclass(frozen=True)
631
+ class Coating(Model):
632
+ """A layer of constant thickness on the phase 1 of a model.
633
+
634
+ ``outside``: a coating (an interphase) of phase ``phase`` around it, within the
635
+ distance ``thickness``. ``inside``: a shell of that thickness, the core becoming the
636
+ phase ``core_phase`` (0: hollow members). Unions of spheres and segments (Boolean
637
+ and hard-core spheres, fibres, strut lattices...) are coated exactly, and their
638
+ members are hollowed one by one (each minus a thinner copy: bores join where members
639
+ meet); other structures through the distance transform of their voxels.
640
+ """
641
+
642
+ name = "coating"
643
+ phases: ClassVar[dict[int, str]] = {0: "matrix", 1: "phase 1 of the model", 2: "coating"}
644
+
645
+ model: Model = param(doc="Model whose phase 1 is coated or hollowed", kind="model")
646
+ thickness: float = param(doc="Thickness of the layer", unit="length")
647
+ side: str = param(
648
+ "outside", doc="outside (a coating around phase 1) or inside (a shell)", kind="str"
649
+ )
650
+ phase: int = param(2, doc="Phase of the coating (outside)", kind="int")
651
+ core_phase: int = param(
652
+ 0, doc="Phase of the core within the shell (inside; 0: hollow)", kind="int"
653
+ )
654
+
655
+ def _validate(self) -> None:
656
+ check_positive(self.thickness, "thickness")
657
+ if self.side not in ("outside", "inside"):
658
+ raise ValueError("side: 'outside' (a coating) or 'inside' (a shell)")
659
+ if not 2 <= self.phase <= 255:
660
+ raise ValueError("phase: a phase index from 2 to 255")
661
+ if self.core_phase == 1 or not 0 <= self.core_phase <= 255:
662
+ raise ValueError("core_phase: 0 (hollow) or a phase index from 2 to 255")
663
+
664
+ @property
665
+ def has_level_set(self) -> bool: # two phases: hollow members
666
+ return self.side == "inside" and self.core_phase == 0 and self.model.has_level_set
667
+
668
+ @property
669
+ def supports_periodic(self) -> bool:
670
+ return self.model.supports_periodic
671
+
672
+ def active_phases(self) -> dict[int, str]:
673
+ if self.side == "outside":
674
+ return {0: "matrix", 1: f"phase 1 ({self.model.name})", self.phase: "coating"}
675
+ out = {0: "matrix", 1: "shell"}
676
+ if self.core_phase != 0:
677
+ out[self.core_phase] = "core"
678
+ return out
679
+
680
+ def generate(self, domain: Domain, seed: SeedLike = None) -> CoatedStructure:
681
+ self._check_domain(domain)
682
+ rng, seed_info = make_rng(seed)
683
+ inner = self.model.generate(domain, _child_seeds(rng, seed_info, 1)[0])
684
+ bores = None
685
+ if self.side == "inside" and isinstance(inner, PrimitiveUnion):
686
+ bores = bores_of(inner, self.thickness)
687
+ return CoatedStructure(
688
+ domain,
689
+ inner,
690
+ self.thickness,
691
+ self.side,
692
+ self.phase,
693
+ self.core_phase,
694
+ bores,
695
+ model=self,
696
+ seed=seed_info,
697
+ )
698
+
699
+ def theory(self, domain: Domain | None = None) -> dict[str, float]:
700
+ """Boolean spheres: their coating is the dilation of a Boolean model, the Boolean
701
+ model of the spheres of radii ``R + t``."""
702
+ from morphogen.models.boolean import BooleanSpheres
703
+
704
+ m = self.model
705
+ if not isinstance(m, BooleanSpheres) or self.side != "outside":
706
+ return {}
707
+ theta, t = m.theta, self.thickness
708
+ nodes, weights = m.radius.quadrature(64)
709
+ dilated = float(np.sum(weights * 4.0 / 3.0 * math.pi * (nodes + t) ** 3))
710
+ p = 1.0 - math.exp(-theta * m.mean_grain_volume)
711
+ return {
712
+ "volume_fraction": p,
713
+ "coating_fraction": 1.0 - math.exp(-theta * dilated) - p,
714
+ }
715
+
716
+
717
+ # -- fractal sponges ---------------------------------------------------------------------------
718
+
719
+ #: Sub-cubes kept by the classical patterns of a 3 x 3 x 3 subdivision.
720
+ _CENTRE_AND_FACES = {(1, 1, 1), (0, 1, 1), (2, 1, 1), (1, 0, 1), (1, 2, 1), (1, 1, 0), (1, 1, 2)}
721
+ PATTERNS = {
722
+ "menger": sorted(set(np.ndindex(3, 3, 3)) - _CENTRE_AND_FACES),
723
+ "vicsek": sorted(_CENTRE_AND_FACES),
724
+ "cantor_dust": sorted(c for c in np.ndindex(3, 3, 3) if 1 not in c),
725
+ }
726
+
727
+
728
+ @register_kind
729
+ class FractalStructure(Microstructure):
730
+ """Periodic tiling of the cube kept by an iterated function system."""
731
+
732
+ kind = "fractal_sponge"
733
+
734
+ def __init__(self, domain, cell_size, subdivisions, kept, level, **kw):
735
+ super().__init__(domain, **kw)
736
+ self.cell_size = float(cell_size)
737
+ self.subdivisions = int(subdivisions)
738
+ self.kept = [tuple(int(v) for v in c) for c in kept]
739
+ self.level = int(level)
740
+ k = self.subdivisions
741
+ self._mask = np.zeros(k**3, dtype=bool)
742
+ for i, j, m in self.kept:
743
+ self._mask[(i * k + j) * k + m] = True
744
+
745
+ def contains(self, points) -> np.ndarray:
746
+ pts = np.asarray(points, dtype=float).reshape(-1, 3)
747
+ k = self.subdivisions
748
+ u = np.mod((pts - self.domain.lower) / self.cell_size, 1.0)
749
+ inside = np.ones(len(pts), dtype=bool)
750
+ for _ in range(self.level):
751
+ d = np.minimum((u * k).astype(np.int64), k - 1)
752
+ inside &= self._mask[(d[:, 0] * k + d[:, 1]) * k + d[:, 2]]
753
+ u = u * k - d
754
+ return inside
755
+
756
+ def voxelize(self, shape=None, *, voxel_size=None, grid: Grid | None = None, supersampling=1):
757
+ grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
758
+ ss = int(supersampling)
759
+ fine = grid if ss == 1 else Grid(grid.domain, tuple(n * ss for n in grid.shape))
760
+ data = np.empty(fine.shape, dtype=bool)
761
+ for k0 in range(0, fine.shape[2], 16):
762
+ k1 = min(fine.shape[2], k0 + 16)
763
+ data[:, :, k0:k1] = self.contains(fine.center_points(k0, k1)).reshape(
764
+ fine.shape[0], fine.shape[1], k1 - k0
765
+ )
766
+ if ss == 1:
767
+ return VoxelImage.from_grid(
768
+ data.astype(np.uint8), grid, name="phase", metadata=self.image_metadata()
769
+ )
770
+ frac = _supersampled(data.astype(np.float32), grid, ss)
771
+ return VoxelImage.from_grid(frac, grid, name="fraction", metadata=self.image_metadata())
772
+
773
+ def level_set(self, shape=None, *, voxel_size=None, grid: Grid | None = None) -> VoxelImage:
774
+ """The signed distance to the solid in the maximum norm (negative inside),
775
+ clipped to a band of four voxels and to the edge of the smallest cubes: the
776
+ solid is a union of such cubes, and the distance from a point to the nearest
777
+ cube of the other state among the 26 around its own is the largest of its
778
+ distances to the faces that separate them."""
779
+ grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
780
+ k = self.subdivisions
781
+ h = self.cell_size / k**self.level
782
+ band = min(h, band_of(grid))
783
+ nx, ny, nz = grid.shape
784
+ out = np.empty(grid.shape, dtype=np.float32)
785
+ offsets = [o for o in np.ndindex(3, 3, 3) if o != (1, 1, 1)]
786
+ step = max(1, (1 << 18) // (nx * ny))
787
+ for k0 in range(0, nz, step):
788
+ k1 = min(nz, k0 + step)
789
+ pts = grid.center_points(k0, k1)
790
+ u = (pts - self.domain.lower) / h
791
+ cell = np.floor(u)
792
+ frac = u - cell
793
+ centre = (cell + 0.5) * h + self.domain.lower
794
+ own = self.contains(centre)
795
+ dist = np.full(len(pts), band)
796
+ for o in offsets:
797
+ shift = np.array(o, dtype=float) - 1.0
798
+ other = self.contains(centre + shift * h) != own
799
+ if not other.any():
800
+ continue
801
+ # to the faces towards that cube, along the axes where it is shifted
802
+ gaps = np.where(shift > 0, 1.0 - frac, frac) * h
803
+ d = np.where(shift != 0, gaps, 0.0).max(axis=1)
804
+ dist = np.where(other, np.minimum(dist, d), dist)
805
+ out[:, :, k0:k1] = np.where(own, -dist, dist).reshape(nx, ny, k1 - k0)
806
+ return VoxelImage.from_grid(out, grid, name="level_set", metadata=self.image_metadata())
807
+
808
+ def convex_pieces(self):
809
+ """The structure as boxes of one phase each (the cubes of the finest level, merged
810
+ greedily), clipped to the box: the pieces, their phases and their cells (the
811
+ phases), for :func:`morphogen.mesh.exact.polyhedral_mesh`."""
812
+ from morphogen.mesh.exact import grid_boxes
813
+
814
+ step = self.cell_size / self.subdivisions**self.level
815
+ lo, hi = self.domain.lower, self.domain.upper
816
+ edges = []
817
+ for d in range(3):
818
+ n = int(np.ceil((hi[d] - lo[d]) / step - 1e-9))
819
+ e = lo[d] + step * np.arange(n + 1)
820
+ e[-1] = hi[d]
821
+ edges.append(e)
822
+ centres = [0.5 * (e[1:] + e[:-1]) for e in edges]
823
+ grid = np.stack(np.meshgrid(*centres, indexing="ij"), axis=-1)
824
+ labels = self.contains(grid.reshape(-1, 3)).reshape(grid.shape[:3]).astype(np.int64)
825
+ pieces, phase = grid_boxes(labels, edges)
826
+ return pieces, phase, phase.copy()
827
+
828
+ def summary(self) -> dict:
829
+ return {"kept_cubes": len(self.kept) ** self.level, "level": self.level}
830
+
831
+ def _geometry(self) -> dict:
832
+ return {
833
+ "cell_size": self.cell_size,
834
+ "subdivisions": self.subdivisions,
835
+ "kept": [list(c) for c in self.kept],
836
+ "level": self.level,
837
+ }
838
+
839
+ @classmethod
840
+ def _from_geometry(cls, domain, geometry, **kwargs):
841
+ return cls(
842
+ domain,
843
+ geometry["cell_size"],
844
+ geometry["subdivisions"],
845
+ geometry["kept"],
846
+ geometry["level"],
847
+ **kwargs,
848
+ )
849
+
850
+
851
+ @register
852
+ @dataclass(frozen=True)
853
+ class FractalSponge(Model):
854
+ """Iterated function system on a cubic grid: the Menger sponge and its kin.
855
+
856
+ The cube of edge ``cell_size`` is divided into ``subdivisions^3`` sub-cubes, of which
857
+ the pattern keeps some (``menger``: all but the centre and the face centres, 20 of
858
+ 27; ``vicsek``: the centre and the face centres; ``cantor_dust``: the 8 corners; or
859
+ ``kept``: indices (i, j, k)); each kept sub-cube is divided alike, ``level`` times.
860
+ The attractor has the similarity dimension ``log N / log k`` (N cubes kept of k^3);
861
+ the domain is tiled by the cube.
862
+ """
863
+
864
+ name = "fractal_sponge"
865
+ phases: ClassVar[dict[int, str]] = {0: "void", 1: "solid"}
866
+ count_label = "unit cells"
867
+
868
+ pattern: str = param("menger", doc="menger, vicsek or cantor_dust (or 'kept')", kind="str")
869
+ kept: tuple | None = param(
870
+ None, doc="Sub-cubes kept, as [i, j, k] indices (overrides the pattern)", kind="json"
871
+ )
872
+ subdivisions: int = param(3, doc="Sub-cubes per edge at each level", kind="int")
873
+ level: int = param(3, doc="Number of iterations", kind="int")
874
+ cell_size: float = param(1.0, doc="Edge of the cube of the sponge", unit="length")
875
+
876
+ def _validate(self) -> None:
877
+ check_positive(self.cell_size, "cell_size")
878
+ if not 2 <= self.subdivisions <= 9:
879
+ raise ValueError("subdivisions: from 2 to 9")
880
+ if not 1 <= self.level <= 8:
881
+ raise ValueError("level: from 1 to 8")
882
+ if self.kept is None:
883
+ if self.pattern not in PATTERNS:
884
+ raise ValueError(f"pattern: one of {sorted(PATTERNS)}, or give 'kept'")
885
+ if self.subdivisions != 3:
886
+ raise ValueError("the named patterns divide the cube in 3 x 3 x 3")
887
+ else:
888
+ cubes = {tuple(int(v) for v in c) for c in self.kept}
889
+ k = self.subdivisions
890
+ if not cubes or any(len(c) != 3 or not all(0 <= v < k for v in c) for c in cubes):
891
+ raise ValueError(f"kept: sub-cube indices [i, j, k] from 0 to {k - 1}")
892
+
893
+ @property
894
+ def cubes(self) -> list[tuple]:
895
+ if self.kept is not None:
896
+ return sorted({tuple(int(v) for v in c) for c in self.kept})
897
+ return list(PATTERNS[self.pattern])
898
+
899
+ def generate(self, domain: Domain, seed: SeedLike = None) -> FractalStructure:
900
+ _, seed_info = make_rng(seed)
901
+ if domain.periodic:
902
+ ratio = domain.lengths / self.cell_size
903
+ if np.any(np.abs(ratio - np.rint(ratio)) > 1e-6 * np.maximum(ratio, 1.0)):
904
+ raise ValueError("fractal_sponge: a periodic domain holds whole cubes")
905
+ return FractalStructure(
906
+ domain,
907
+ self.cell_size,
908
+ self.subdivisions,
909
+ self.cubes,
910
+ self.level,
911
+ model=self,
912
+ seed=seed_info,
913
+ )
914
+
915
+ def expected_count(self, domain: Domain) -> float:
916
+ return domain.volume / self.cell_size**3
917
+
918
+ def theory(self, domain: Domain | None = None) -> dict[str, float]:
919
+ n, k = len(self.cubes), self.subdivisions
920
+ return {
921
+ "volume_fraction": (n / k**3) ** self.level,
922
+ "fractal_dimension": math.log(n) / math.log(k),
923
+ "smallest_cube": self.cell_size / k**self.level,
924
+ }