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,1616 @@
1
+ """Scale-rich networks in three dimensions: plates or beams of power-law thicknesses grown
2
+ one after another until they meet (Both et al. 2026, Fig. 6a and Supplementary S2.5-S2.7).
3
+
4
+ The sequential growth of :mod:`morphogen.models.scale_rich` extends to space by adding
5
+ non-crossing plates or beams, ``lambda_t = lambda_0 t^-alpha`` thick:
6
+
7
+ * **plates**: the plate ``t`` nucleates at a point drawn uniformly in the voids, with a
8
+ normal ``n_t`` (uniform on the sphere, or drawn from a law), and grows in its plane until
9
+ it meets other plates or the box. The voids are convex polyhedra (at first the box),
10
+ bounded by faces of plates and of the box; the plate is the slab ``|n_t . x - c_t| <=
11
+ lambda_t / 2`` clipped by the void of its nucleation point, which it splits into two
12
+ convex voids. Plates and voids partition the box exactly (the relative density is
13
+ exact), the plates never overlap, and every void is a closed cell. The *rim* of a plate
14
+ is the section of its void by its mid-plane: a convex polygon whose edges lie on the
15
+ faces of the plates (or of the box) on which the plate ends, its neighbours. The area
16
+ of a plate is that of its rim.
17
+ * **beams**: the beam ``t`` (a cylinder of diameter ``lambda_t`` with round ends)
18
+ nucleates at a point of the voids where it clears the other beams and the box, along an
19
+ axis ``d_t``, and grows both ways until its axis reaches the surface of another beam
20
+ (a T-junction), or passes within contact of one (the axis ends at its closest approach,
21
+ a lateral junction), or reaches the box. Beams do not split space: their voids form one
22
+ connected, open cell.
23
+
24
+ A plate (beam) fits when its void holds the points ``p +- (lambda_t + epsilon) / 2 n_t``
25
+ (when the ball of radius ``(lambda_t + epsilon) / 2`` about ``p`` clears the beams and the
26
+ box); ``max_attempts`` draws in a row that do not fit jam the network. Each element draws
27
+ its nucleation points and directions from its own generator, so that the network moves
28
+ little when ``lambda_0`` changes (see :func:`morphogen.models.scale_rich.grow`).
29
+
30
+ Laws: the thicknesses as in the plane, ``P(lambda) ~ lambda^-(1 + 1/alpha)``; a plate
31
+ splits a void of volume about ``V_v / t``, so that its area decays as ``t^-2/3`` and the
32
+ areas have the tail ``P(a) ~ a^-5/2``, as the degrees (a plate is met by the later ones in
33
+ proportion to its area): ``(2d - 1) / (d - 1)`` in ``d`` dimensions, 3 in the plane. The
34
+ relative density of plates is exact, and in closed form to a mean field (:func:`first_area`,
35
+ :func:`area_sum`, :meth:`morphogen.models.ScaleRichNetwork.theory`); that of beams, the
36
+ volume of the cylinders on their axes, follows the mean field of their free paths
37
+ (:func:`beam_density_estimate`). Orientation laws, poles, gradients and frames: see
38
+ :class:`morphogen.models.ScaleRichNetwork`.
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import math
44
+ from dataclasses import dataclass
45
+ from functools import lru_cache
46
+
47
+ import numpy as np
48
+ from numba import njit, prange
49
+
50
+ from morphogen.domain import Domain, Grid
51
+ from morphogen.image import VoxelImage
52
+ from morphogen.models.base import Microstructure, register_kind
53
+ from morphogen.orientations import uniform_unit_vectors
54
+
55
+ #: Label of the faces of the voids on the boundary of the box (plates: their index)
56
+ BOX = -1
57
+ #: ``lim (t / V)^(2/3) E[a_t]``: the mean area of the plate ``t`` of a thin network
58
+ #: (``lambda_0 -> 0``) in a box of volume ``V``, measured with uniform normals: 1.2363
59
+ #: (standard error 0.0005) over the plates ``t >= 2000`` of 120 realizations of 20,000 in
60
+ #: a cube. The first plate is ``a_0`` (:func:`first_area`, 0.9412 in a cube), the next
61
+ #: ones approach the limit faster than in the plane (1.08, 1.13 at ``t`` = 2, 3; 1.24 from
62
+ #: ``t`` = 10 on)
63
+ AREA_CONSTANT = 1.236
64
+ #: Uniform draws of a nucleation point: its three coordinates and its rejection by the
65
+ #: density of nucleation
66
+ _DRAWS = 4
67
+ #: Points (``2^k``) of the quasi-Monte Carlo estimate of the relative density of beams, the
68
+ #: volume of their union in the box (a scrambled Sobol set of a fixed seed, the same for
69
+ #: every network): within 1.5e-4 of 2^22 points over 8 networks (5.8e-4 with 2^18)
70
+ UNION_POINTS_LOG2 = 20
71
+
72
+ # -- convex polyhedra: faces (convex polygons counter-clockwise about their outward unit
73
+ # normal), each with the plane n . x = c that bears it and the label of what lies beyond --
74
+
75
+
76
+ @njit(cache=True)
77
+ def _put(out, k, start, x, y, z, tol):
78
+ """Appends a vertex to the face that starts at ``start``, unless it repeats the last."""
79
+ if (k > start and abs(out[k - 1, 0] - x) <= tol and abs(out[k - 1, 1] - y) <= tol
80
+ and abs(out[k - 1, 2] - z) <= tol): # fmt: skip
81
+ return k
82
+ out[k, 0], out[k, 1], out[k, 2] = x, y, z
83
+ return k + 1
84
+
85
+
86
+ @njit(cache=True)
87
+ def _basis(nx, ny, nz):
88
+ """Two unit vectors ``e1, e2`` of the plane normal to ``n`` with ``e1 x e2 = n``."""
89
+ ax, ay, az = abs(nx), abs(ny), abs(nz)
90
+ if ax <= ay and ax <= az:
91
+ hx, hy, hz = 1.0, 0.0, 0.0
92
+ elif ay <= az:
93
+ hx, hy, hz = 0.0, 1.0, 0.0
94
+ else:
95
+ hx, hy, hz = 0.0, 0.0, 1.0
96
+ e1x, e1y, e1z = ny * hz - nz * hy, nz * hx - nx * hz, nx * hy - ny * hx # n x h
97
+ s = math.sqrt(e1x * e1x + e1y * e1y + e1z * e1z)
98
+ e1x, e1y, e1z = e1x / s, e1y / s, e1z / s
99
+ e2x, e2y, e2z = ny * e1z - nz * e1y, nz * e1x - nx * e1z, nx * e1y - ny * e1x # n x e1
100
+ return e1x, e1y, e1z, e2x, e2y, e2z
101
+
102
+
103
+ @njit(cache=True)
104
+ def _cut(verts, fofs, labels, normals, planes, nx, ny, nz, c, tol):
105
+ """The faces of a convex polyhedron clipped to the half-space ``n . x <= c``
106
+ (Sutherland-Hodgman on each face; the faces left with fewer than three vertices go),
107
+ and the section of the polyhedron by the plane ``n . x = c``: its vertices,
108
+ counter-clockwise about ``n``, and the label of the face on which each edge (from a
109
+ vertex to the next) lies."""
110
+ nf = fofs.shape[0] - 1
111
+ out = np.empty((verts.shape[0] + nf, 3))
112
+ ofs = np.zeros(nf + 1, dtype=np.int64)
113
+ lab = np.empty(nf, dtype=np.int64)
114
+ nrm = np.empty((nf, 3))
115
+ pln = np.empty(nf)
116
+ seg = np.empty((nf, 6)) # in each cut face: where its boundary enters the half-space,
117
+ seg_lab = np.empty(nf, dtype=np.int64) # then where it leaves it (the section's way)
118
+ k = g = s = 0
119
+ for f in range(nf):
120
+ a = fofs[f]
121
+ m = fofs[f + 1] - a
122
+ start = k
123
+ got_in = got_out = False
124
+ ix = iy = iz = ox = oy = oz = 0.0
125
+ for j in range(m):
126
+ i0 = a + j
127
+ i1 = a + (j + 1) % m
128
+ d0 = nx * verts[i0, 0] + ny * verts[i0, 1] + nz * verts[i0, 2] - c
129
+ d1 = nx * verts[i1, 0] + ny * verts[i1, 1] + nz * verts[i1, 2] - c
130
+ if d0 <= 0.0:
131
+ k = _put(out, k, start, verts[i0, 0], verts[i0, 1], verts[i0, 2], tol)
132
+ if d1 > 0.0: # leaves the half-space
133
+ t = d0 / (d0 - d1)
134
+ ox = verts[i0, 0] + t * (verts[i1, 0] - verts[i0, 0])
135
+ oy = verts[i0, 1] + t * (verts[i1, 1] - verts[i0, 1])
136
+ oz = verts[i0, 2] + t * (verts[i1, 2] - verts[i0, 2])
137
+ got_out = True
138
+ k = _put(out, k, start, ox, oy, oz, tol)
139
+ elif d1 <= 0.0: # enters it
140
+ t = d0 / (d0 - d1)
141
+ ix = verts[i0, 0] + t * (verts[i1, 0] - verts[i0, 0])
142
+ iy = verts[i0, 1] + t * (verts[i1, 1] - verts[i0, 1])
143
+ iz = verts[i0, 2] + t * (verts[i1, 2] - verts[i0, 2])
144
+ got_in = True
145
+ k = _put(out, k, start, ix, iy, iz, tol)
146
+ if (k - start >= 2 and abs(out[k - 1, 0] - out[start, 0]) <= tol
147
+ and abs(out[k - 1, 1] - out[start, 1]) <= tol
148
+ and abs(out[k - 1, 2] - out[start, 2]) <= tol): # fmt: skip
149
+ k -= 1 # the last vertex repeats the first
150
+ if k - start >= 3:
151
+ ofs[g + 1] = k
152
+ lab[g] = labels[f]
153
+ nrm[g, 0], nrm[g, 1], nrm[g, 2] = normals[f, 0], normals[f, 1], normals[f, 2]
154
+ pln[g] = planes[f]
155
+ g += 1
156
+ else:
157
+ k = start
158
+ if got_in and got_out and (abs(ix - ox) > tol or abs(iy - oy) > tol
159
+ or abs(iz - oz) > tol): # fmt: skip
160
+ seg[s, 0], seg[s, 1], seg[s, 2] = ix, iy, iz
161
+ seg[s, 3], seg[s, 4], seg[s, 5] = ox, oy, oz
162
+ seg_lab[s] = labels[f]
163
+ s += 1
164
+ # the section: the segments of the cut faces, in the order of their angles about n
165
+ cap = np.empty((0, 3))
166
+ cap_lab = np.empty(0, dtype=np.int64)
167
+ if s >= 3:
168
+ e1x, e1y, e1z, e2x, e2y, e2z = _basis(nx, ny, nz)
169
+ gx = gy = gz = 0.0
170
+ for q in range(s):
171
+ gx += seg[q, 0] + seg[q, 3]
172
+ gy += seg[q, 1] + seg[q, 4]
173
+ gz += seg[q, 2] + seg[q, 5]
174
+ gx, gy, gz = gx / (2 * s), gy / (2 * s), gz / (2 * s)
175
+ angle = np.empty(s)
176
+ for q in range(s):
177
+ mx = 0.5 * (seg[q, 0] + seg[q, 3]) - gx
178
+ my = 0.5 * (seg[q, 1] + seg[q, 4]) - gy
179
+ mz = 0.5 * (seg[q, 2] + seg[q, 5]) - gz
180
+ angle[q] = math.atan2(mx * e2x + my * e2y + mz * e2z, mx * e1x + my * e1y + mz * e1z)
181
+ order = np.argsort(angle)
182
+ cap = np.empty((s, 3))
183
+ cap_lab = np.empty(s, dtype=np.int64)
184
+ for q in range(s):
185
+ cap[q, 0], cap[q, 1], cap[q, 2] = seg[order[q], 0], seg[order[q], 1], seg[order[q], 2]
186
+ cap_lab[q] = seg_lab[order[q]]
187
+ return out[:k], ofs[: g + 1], lab[:g], nrm[:g], pln[:g], cap, cap_lab
188
+
189
+
190
+ @njit(cache=True)
191
+ def clip_polyhedron(verts, fofs, labels, normals, planes, nx, ny, nz, c, label, tol):
192
+ """The part of a convex polyhedron where ``n . x <= c``: its faces, the section by the
193
+ plane (when it is a polygon) labelled ``label`` (``n`` a unit vector)."""
194
+ v, o, lab, nrm, pln, cap, _ = _cut(verts, fofs, labels, normals, planes, nx, ny, nz, c, tol)
195
+ if cap.shape[0] < 3:
196
+ return v, o, lab, nrm, pln
197
+ nf = o.shape[0] - 1
198
+ v2 = np.empty((v.shape[0] + cap.shape[0], 3))
199
+ v2[: v.shape[0]] = v
200
+ v2[v.shape[0] :] = cap
201
+ o2 = np.empty(nf + 2, dtype=np.int64)
202
+ o2[: nf + 1] = o
203
+ o2[nf + 1] = v2.shape[0]
204
+ lab2 = np.empty(nf + 1, dtype=np.int64)
205
+ lab2[:nf] = lab
206
+ lab2[nf] = label
207
+ nrm2 = np.empty((nf + 1, 3))
208
+ nrm2[:nf] = nrm
209
+ nrm2[nf, 0], nrm2[nf, 1], nrm2[nf, 2] = nx, ny, nz
210
+ pln2 = np.empty(nf + 1)
211
+ pln2[:nf] = pln
212
+ pln2[nf] = c
213
+ return v2, o2, lab2, nrm2, pln2
214
+
215
+
216
+ @njit(cache=True)
217
+ def section(verts, fofs, labels, normals, planes, nx, ny, nz, c, tol):
218
+ """The section of a convex polyhedron by the plane ``n . x = c``: its vertices,
219
+ counter-clockwise about ``n``, and the label of the face of each edge."""
220
+ out = _cut(verts, fofs, labels, normals, planes, nx, ny, nz, c, tol)
221
+ return out[5], out[6]
222
+
223
+
224
+ @njit(cache=True)
225
+ def polyhedron_volume(verts, fofs, normals, planes) -> float:
226
+ """Volume of a convex polyhedron: ``sum_f (c_f - n_f . x_0) A_f / 3`` (the cones of
227
+ its faces from a vertex ``x_0``)."""
228
+ nf = fofs.shape[0] - 1
229
+ if nf < 4:
230
+ return 0.0
231
+ x0, y0, z0 = verts[0, 0], verts[0, 1], verts[0, 2]
232
+ v = 0.0
233
+ for f in range(nf):
234
+ a, b = fofs[f], fofs[f + 1]
235
+ sx = sy = sz = 0.0
236
+ for j in range(a + 1, b - 1):
237
+ ux = verts[j, 0] - verts[a, 0]
238
+ uy = verts[j, 1] - verts[a, 1]
239
+ uz = verts[j, 2] - verts[a, 2]
240
+ wx = verts[j + 1, 0] - verts[a, 0]
241
+ wy = verts[j + 1, 1] - verts[a, 1]
242
+ wz = verts[j + 1, 2] - verts[a, 2]
243
+ sx += uy * wz - uz * wy
244
+ sy += uz * wx - ux * wz
245
+ sz += ux * wy - uy * wx
246
+ area = 0.5 * abs(sx * normals[f, 0] + sy * normals[f, 1] + sz * normals[f, 2])
247
+ h = planes[f] - (normals[f, 0] * x0 + normals[f, 1] * y0 + normals[f, 2] * z0)
248
+ v += h * area
249
+ return v / 3.0
250
+
251
+
252
+ @njit(cache=True)
253
+ def polygon_area_3d(verts) -> float:
254
+ """Area of a planar polygon of space (vertices in order)."""
255
+ m = verts.shape[0]
256
+ sx = sy = sz = 0.0
257
+ for j in range(1, m - 1):
258
+ ux, uy, uz = verts[j, 0] - verts[0, 0], verts[j, 1] - verts[0, 1], verts[j, 2] - verts[0, 2]
259
+ wx = verts[j + 1, 0] - verts[0, 0]
260
+ wy = verts[j + 1, 1] - verts[0, 1]
261
+ wz = verts[j + 1, 2] - verts[0, 2]
262
+ sx += uy * wz - uz * wy
263
+ sy += uz * wx - ux * wz
264
+ sz += ux * wy - uy * wx
265
+ return 0.5 * math.sqrt(sx * sx + sy * sy + sz * sz)
266
+
267
+
268
+ @njit(cache=True)
269
+ def inside_polyhedron(normals, planes, px, py, pz) -> bool:
270
+ """Whether a convex polyhedron (its face planes) holds the point ``p``."""
271
+ for f in range(planes.shape[0]):
272
+ if normals[f, 0] * px + normals[f, 1] * py + normals[f, 2] * pz > planes[f]:
273
+ return False
274
+ return True
275
+
276
+
277
+ @njit(cache=True)
278
+ def fits_polyhedron(normals, planes, px, py, pz, nx, ny, nz, half) -> bool:
279
+ """Whether a convex polyhedron holds the points ``p +- half n``."""
280
+ for f in range(planes.shape[0]):
281
+ m = normals[f, 0] * nx + normals[f, 1] * ny + normals[f, 2] * nz
282
+ if normals[f, 0] * px + normals[f, 1] * py + normals[f, 2] * pz + half * abs(m) > planes[f]:
283
+ return False
284
+ return True
285
+
286
+
287
+ def box_polyhedron(lower, upper):
288
+ """The box ``[lower, upper]`` as a convex polyhedron (faces labelled :data:`BOX`)."""
289
+ (x0, y0, z0), (x1, y1, z1) = np.asarray(lower, dtype=float), np.asarray(upper, dtype=float)
290
+ faces = [
291
+ ((-1, 0, 0), -x0, [(x0, y0, z0), (x0, y0, z1), (x0, y1, z1), (x0, y1, z0)]),
292
+ ((1, 0, 0), x1, [(x1, y0, z0), (x1, y1, z0), (x1, y1, z1), (x1, y0, z1)]),
293
+ ((0, -1, 0), -y0, [(x0, y0, z0), (x1, y0, z0), (x1, y0, z1), (x0, y0, z1)]),
294
+ ((0, 1, 0), y1, [(x0, y1, z0), (x0, y1, z1), (x1, y1, z1), (x1, y1, z0)]),
295
+ ((0, 0, -1), -z0, [(x0, y0, z0), (x0, y1, z0), (x1, y1, z0), (x1, y0, z0)]),
296
+ ((0, 0, 1), z1, [(x0, y0, z1), (x1, y0, z1), (x1, y1, z1), (x0, y1, z1)]),
297
+ ]
298
+ verts = np.array([v for *_, vs in faces for v in vs], dtype=float)
299
+ fofs = np.arange(0, 25, 4, dtype=np.int64)
300
+ labels = np.full(6, BOX, dtype=np.int64)
301
+ normals = np.array([n for n, *_ in faces], dtype=float)
302
+ planes = np.array([c for _, c, _ in faces], dtype=float)
303
+ return verts, fofs, labels, normals, planes
304
+
305
+
306
+ def frame_boxes(lower, upper, frame: float) -> list[tuple]:
307
+ """The six boxes that make the frame ``[lower, upper]`` minus its inner box (``frame``
308
+ thick), as convex polyhedra."""
309
+ lo, hi = np.asarray(lower, dtype=float), np.asarray(upper, dtype=float)
310
+ f = float(frame)
311
+ a, b = lo + f, hi - f
312
+ spans = [
313
+ ((lo[0], lo[1], lo[2]), (a[0], hi[1], hi[2])),
314
+ ((b[0], lo[1], lo[2]), (hi[0], hi[1], hi[2])),
315
+ ((a[0], lo[1], lo[2]), (b[0], a[1], hi[2])),
316
+ ((a[0], b[1], lo[2]), (b[0], hi[1], hi[2])),
317
+ ((a[0], a[1], lo[2]), (b[0], b[1], a[2])),
318
+ ((a[0], a[1], b[2]), (b[0], b[1], hi[2])),
319
+ ]
320
+ return [box_polyhedron(x, y) for x, y in spans]
321
+
322
+
323
+ def prism(polygon, axes, axis: int, z0: float, z1: float) -> tuple:
324
+ """The convex polygon of the plane of ``axes`` (counter-clockwise vertices) extruded
325
+ along ``axis`` from ``z0`` to ``z1``, as a convex polyhedron (faces labelled
326
+ :data:`BOX`)."""
327
+ poly = np.asarray(polygon, dtype=float)
328
+ m = len(poly)
329
+ b, c = axes
330
+
331
+ def lift(uv, z):
332
+ x = np.empty(3)
333
+ x[b], x[c], x[axis] = uv[0], uv[1], z
334
+ return x
335
+
336
+ faces, normals, planes = [], [], []
337
+ e = np.zeros(3)
338
+ e[axis] = 1.0
339
+ faces.append([lift(q, z0) for q in poly[::-1]])
340
+ normals.append(-e)
341
+ planes.append(-z0)
342
+ faces.append([lift(q, z1) for q in poly])
343
+ normals.append(e)
344
+ planes.append(z1)
345
+ for i in range(m):
346
+ p, q = poly[i], poly[(i + 1) % m]
347
+ du, dv = q - p
348
+ length = float(np.hypot(du, dv))
349
+ if length == 0.0:
350
+ continue
351
+ n = np.zeros(3)
352
+ n[b], n[c] = dv / length, -du / length
353
+ loop = [lift(p, z0), lift(q, z0), lift(q, z1), lift(p, z1)]
354
+ faces.append(loop)
355
+ normals.append(n)
356
+ planes.append(float(n @ loop[0]))
357
+ verts = np.array([v for f in faces for v in f], dtype=float)
358
+ fofs = np.concatenate([[0], np.cumsum([len(f) for f in faces])]).astype(np.int64)
359
+ labels = np.full(len(faces), BOX, dtype=np.int64)
360
+ return verts, fofs, labels, np.array(normals, dtype=float), np.array(planes, dtype=float)
361
+
362
+
363
+ @dataclass
364
+ class Polyhedra:
365
+ """Convex polyhedra in compressed rows: polyhedron ``i`` has the faces ``offsets[i]``
366
+ to ``offsets[i + 1]``; face ``f`` the vertices ``face_offsets[f]`` to
367
+ ``face_offsets[f + 1]`` (counter-clockwise about its outward unit normal
368
+ ``normals[f]``), the plane ``normals[f] . x = planes[f]`` and the label of what lies
369
+ beyond (a plate, or :data:`BOX`)."""
370
+
371
+ offsets: np.ndarray
372
+ face_offsets: np.ndarray
373
+ vertices: np.ndarray
374
+ normals: np.ndarray
375
+ planes: np.ndarray
376
+ labels: np.ndarray
377
+
378
+ def __len__(self) -> int:
379
+ return len(self.offsets) - 1
380
+
381
+ @classmethod
382
+ def from_list(cls, items: list[tuple]) -> Polyhedra:
383
+ """From ``(vertices, face offsets, labels, normals, planes)`` tuples."""
384
+ offsets = np.zeros(len(items) + 1, dtype=np.int64)
385
+ offsets[1:] = np.cumsum([len(p[2]) for p in items])
386
+ shifts = np.concatenate([[0], np.cumsum([len(p[0]) for p in items])[:-1]]) if items else []
387
+ fo = [p[1][:-1] + s for p, s in zip(items, shifts, strict=True)]
388
+ face_offsets = np.concatenate([*fo, [sum(len(p[0]) for p in items)]]).astype(np.int64)
389
+ return cls(
390
+ offsets=offsets,
391
+ face_offsets=face_offsets,
392
+ vertices=np.concatenate([p[0] for p in items]) if items else np.empty((0, 3)),
393
+ normals=np.concatenate([p[3] for p in items]) if items else np.empty((0, 3)),
394
+ planes=np.concatenate([p[4] for p in items]) if items else np.empty(0),
395
+ labels=(np.concatenate([p[2] for p in items]) if items
396
+ else np.empty(0, dtype=np.int64)).astype(np.int64),
397
+ ) # fmt: skip
398
+
399
+ def polyhedron(self, i: int) -> tuple:
400
+ """``(vertices, face offsets, labels, normals, planes)`` of polyhedron ``i``."""
401
+ f0, f1 = self.offsets[i], self.offsets[i + 1]
402
+ v0, v1 = self.face_offsets[f0], self.face_offsets[f1]
403
+ return (self.vertices[v0:v1], self.face_offsets[f0 : f1 + 1] - v0, self.labels[f0:f1],
404
+ self.normals[f0:f1], self.planes[f0:f1]) # fmt: skip
405
+
406
+ def faces(self, i: int) -> list[np.ndarray]:
407
+ """The faces of polyhedron ``i`` (vertices of each, counter-clockwise from
408
+ outside)."""
409
+ verts, fofs, *_ = self.polyhedron(i)
410
+ return [verts[fofs[f] : fofs[f + 1]] for f in range(len(fofs) - 1)]
411
+
412
+ def volumes(self) -> np.ndarray:
413
+ out = np.empty(len(self))
414
+ for i in range(len(self)):
415
+ verts, fofs, _, normals, planes = self.polyhedron(i)
416
+ out[i] = polyhedron_volume(verts, fofs, normals, planes)
417
+ return out
418
+
419
+ def bounds(self) -> np.ndarray:
420
+ """``(n, 6)``: the lower and upper corners of the box of each polyhedron."""
421
+ out = np.full((len(self), 6), np.nan)
422
+ for i in range(len(self)):
423
+ v = self.polyhedron(i)[0]
424
+ if len(v):
425
+ out[i, :3], out[i, 3:] = v.min(axis=0), v.max(axis=0)
426
+ return out
427
+
428
+ def to_dict(self) -> dict:
429
+ return {
430
+ "offsets": self.offsets.tolist(),
431
+ "face_offsets": self.face_offsets.tolist(),
432
+ "vertices": self.vertices.tolist(),
433
+ "normals": self.normals.tolist(),
434
+ "planes": self.planes.tolist(),
435
+ "labels": self.labels.tolist(),
436
+ }
437
+
438
+ @classmethod
439
+ def from_dict(cls, data: dict) -> Polyhedra:
440
+ return cls(
441
+ offsets=np.asarray(data["offsets"], dtype=np.int64),
442
+ face_offsets=np.asarray(data["face_offsets"], dtype=np.int64),
443
+ vertices=np.asarray(data["vertices"], dtype=float).reshape(-1, 3),
444
+ normals=np.asarray(data["normals"], dtype=float).reshape(-1, 3),
445
+ planes=np.asarray(data["planes"], dtype=float).reshape(-1),
446
+ labels=np.asarray(data["labels"], dtype=np.int64).reshape(-1),
447
+ )
448
+
449
+
450
+ class _Cells:
451
+ """The voids of a growing network of plates registered in a grid of buckets of the
452
+ box, to find the void that holds a point (or none: the point lies in a plate)."""
453
+
454
+ def __init__(self, lower, upper, n_buckets: int) -> None:
455
+ self.lo = np.asarray(lower, dtype=float)
456
+ size = np.asarray(upper, dtype=float) - self.lo
457
+ cube = float(np.prod(size)) ** (1.0 / 3.0)
458
+ g = np.clip(np.ceil(max(n_buckets, 1) ** (1.0 / 3.0) * size / cube), 1, 64).astype(int)
459
+ self.g = (int(g[0]), int(g[1]), int(g[2]))
460
+ self.h = size / g
461
+ self.buckets: list[set[int]] = [set() for _ in range(int(np.prod(g)))]
462
+ self.ranges: dict[int, tuple] = {}
463
+ self.cells: list[tuple] = []
464
+
465
+ def _index(self, v: float, axis: int) -> int:
466
+ return min(max(math.floor((v - self.lo[axis]) / self.h[axis]), 0), self.g[axis] - 1)
467
+
468
+ def put(self, cid: int, poly: tuple) -> None:
469
+ """Registers the void ``cid`` (a new one, or in place of the old ``cid``); a
470
+ void with fewer than four faces is empty and holds no point."""
471
+ if cid < len(self.cells):
472
+ self.drop(cid)
473
+ self.cells[cid] = poly
474
+ else:
475
+ self.cells.append(poly)
476
+ if len(poly[2]) < 4:
477
+ return
478
+ lo, hi = poly[0].min(axis=0), poly[0].max(axis=0)
479
+ r = [(self._index(lo[a], a), self._index(hi[a], a)) for a in range(3)]
480
+ self.ranges[cid] = (lo, hi, r)
481
+ g1, g2 = self.g[1], self.g[2]
482
+ for i in range(r[0][0], r[0][1] + 1):
483
+ for j in range(r[1][0], r[1][1] + 1):
484
+ for k in range(r[2][0], r[2][1] + 1):
485
+ self.buckets[(i * g1 + j) * g2 + k].add(cid)
486
+
487
+ def drop(self, cid: int) -> None:
488
+ if cid not in self.ranges:
489
+ return
490
+ *_, r = self.ranges.pop(cid)
491
+ g1, g2 = self.g[1], self.g[2]
492
+ for i in range(r[0][0], r[0][1] + 1):
493
+ for j in range(r[1][0], r[1][1] + 1):
494
+ for k in range(r[2][0], r[2][1] + 1):
495
+ self.buckets[(i * g1 + j) * g2 + k].discard(cid)
496
+
497
+ def locate(self, p) -> int:
498
+ i, j, k = (self._index(p[a], a) for a in range(3))
499
+ for cid in self.buckets[(i * self.g[1] + j) * self.g[2] + k]:
500
+ lo, hi, _ = self.ranges[cid]
501
+ if np.all(lo <= p) and np.all(p <= hi):
502
+ poly = self.cells[cid]
503
+ if inside_polyhedron(poly[3], poly[4], p[0], p[1], p[2]):
504
+ return cid
505
+ return -1
506
+
507
+
508
+ # -- the growth of plates ------------------------------------------------------------------
509
+
510
+
511
+ @dataclass
512
+ class PlateGrowth:
513
+ """The plates and voids of a scale-rich network of plates."""
514
+
515
+ nucleation: np.ndarray # (N, 3) the nucleation points
516
+ normal: np.ndarray # (N, 3) the unit normals of the plates
517
+ thickness: np.ndarray # (N,)
518
+ rim_offsets: np.ndarray # (N + 1,) CSR of the rims: the sections of the voids by the
519
+ rim_vertices: np.ndarray # (R, 3) mid-planes of the plates
520
+ rim_faces: np.ndarray # (R,) the label of the face of each edge (plate or BOX)
521
+ bodies: Polyhedra # the plates
522
+ cells: Polyhedra # the voids
523
+ jammed: bool = False
524
+ attempts: int = 0
525
+
526
+ @property
527
+ def n(self) -> int:
528
+ return len(self.thickness)
529
+
530
+ @property
531
+ def n_cells(self) -> int:
532
+ return len(self.cells)
533
+
534
+ def rims(self) -> list[np.ndarray]:
535
+ """The rim of each plate: the polygon of its mid-plane in its void."""
536
+ o = self.rim_offsets
537
+ return [self.rim_vertices[o[i] : o[i + 1]] for i in range(self.n)]
538
+
539
+ @property
540
+ def areas(self) -> np.ndarray:
541
+ """The areas of the plates (of their rims)."""
542
+ return np.array([polygon_area_3d(r) for r in self.rims()])
543
+
544
+ def body_volumes(self) -> np.ndarray:
545
+ return self.bodies.volumes()
546
+
547
+ def cell_volumes(self) -> np.ndarray:
548
+ return self.cells.volumes()
549
+
550
+ def links(self) -> np.ndarray:
551
+ """The pairs of plates joined: each plate with the plates on which its rim lies
552
+ (the edges of the dual graph, each once)."""
553
+ counts = np.diff(self.rim_offsets)
554
+ i = np.repeat(np.arange(self.n), counts)
555
+ j = self.rim_faces
556
+ keep = j >= 0
557
+ if not np.any(keep):
558
+ return np.empty((0, 2), dtype=np.int64)
559
+ return np.unique(np.column_stack([i[keep], j[keep]]), axis=0)
560
+
561
+ def degrees(self) -> np.ndarray:
562
+ """The number of plates each plate meets (its degree in the dual graph)."""
563
+ e = self.links()
564
+ return np.bincount(e.ravel(), minlength=self.n).astype(np.int64)
565
+
566
+ def boundary_contacts(self) -> np.ndarray:
567
+ """Whether each plate ends on the box."""
568
+ counts = np.diff(self.rim_offsets)
569
+ i = np.repeat(np.arange(self.n), counts)
570
+ out = np.zeros(self.n, dtype=bool)
571
+ out[i[self.rim_faces == BOX]] = True
572
+ return out
573
+
574
+ def orientation_tensor(self) -> np.ndarray:
575
+ """``N = sum V_t n_t n_t / sum V_t``: the normals ``n_t`` of the plates weighted
576
+ by their volumes ``V_t`` (the fabric tensor of the walls)."""
577
+ v = self.body_volumes()
578
+ if not v.sum() > 0:
579
+ return np.full((3, 3), np.nan)
580
+ return np.einsum("t,ti,tj->ij", v, self.normal, self.normal) / v.sum()
581
+
582
+
583
+ def _csr3(items: list[np.ndarray], dtype=float, width: int = 3):
584
+ offsets = np.zeros(len(items) + 1, dtype=np.int64)
585
+ offsets[1:] = np.cumsum([len(a) for a in items])
586
+ shape = (0, width) if width else (0,)
587
+ data = np.concatenate(items).astype(dtype) if items else np.empty(shape, dtype=dtype)
588
+ return offsets, data
589
+
590
+
591
+ def isotropic_directions(t: int, points: np.ndarray, gen: np.random.Generator) -> np.ndarray:
592
+ """Directions uniform on the sphere, one per point."""
593
+ return uniform_unit_vectors(gen, len(points))
594
+
595
+
596
+ def grow_plates(
597
+ lower,
598
+ upper,
599
+ n_plates: int,
600
+ thickness,
601
+ entropy: int,
602
+ *,
603
+ directions=None,
604
+ density=None,
605
+ min_spacing: float = 0.0,
606
+ max_attempts: int = 1000,
607
+ ) -> PlateGrowth:
608
+ """Grow a scale-rich network of plates in the box ``[lower, upper]``.
609
+
610
+ ``thickness(t)`` is the thickness of the plate ``t = 1, 2, ...``; ``directions(t,
611
+ points, generator)`` the unit normals of the plate at candidate nucleation points
612
+ (``(k, 3)`` arrays; default: uniform on the sphere); ``density(x, y, z)`` the relative
613
+ density of nucleation in ``[0, 1]`` (default: uniform), by rejection. As in
614
+ :func:`morphogen.models.scale_rich.grow`, a nucleation point is drawn uniformly in the
615
+ box until it falls in a void, each plate draws from its own generators (points:
616
+ ``SeedSequence(entropy, spawn_key=(t,))``, normals: ``spawn_key=(t, 1)``), and the
617
+ growth jams after ``max_attempts`` points in a row where the plate does not fit."""
618
+ lo = np.asarray(lower, dtype=float).reshape(3)
619
+ hi = np.asarray(upper, dtype=float).reshape(3)
620
+ size = hi - lo
621
+ volume = float(np.prod(size))
622
+ tol = 1e-12 * float(np.max(size))
623
+ draw_normals = isotropic_directions if directions is None else directions
624
+ voids = _Cells(lo, hi, n_buckets=max(1, int(n_plates) // 2))
625
+ voids.put(0, box_polyhedron(lo, hi))
626
+ void_volume = volume
627
+
628
+ nucleation, normal, lam, rims, rim_faces, bodies = [], [], [], [], [], []
629
+ attempts = 0
630
+ jammed = False
631
+ for t in range(1, int(n_plates) + 1):
632
+ width = float(thickness(t))
633
+ half = 0.5 * (width + min_spacing)
634
+ gen = np.random.Generator(np.random.PCG64(np.random.SeedSequence(entropy, spawn_key=(t,))))
635
+ gdir = np.random.Generator(
636
+ np.random.PCG64(np.random.SeedSequence(entropy, spawn_key=(t, 1)))
637
+ )
638
+ failures = k = 0
639
+ block = gen.random((16, _DRAWS))
640
+ pts = lo + block[:, :3] * size
641
+ dirs = draw_normals(t, pts, gdir)
642
+ while True:
643
+ if k == len(block):
644
+ if void_volume <= 1e-12 * volume:
645
+ jammed = True
646
+ break
647
+ block, k = gen.random((256, _DRAWS)), 0
648
+ pts = lo + block[:, :3] * size
649
+ dirs = draw_normals(t, pts, gdir)
650
+ p, u = pts[k], block[k, 3]
651
+ n = dirs[k]
652
+ k += 1
653
+ if density is not None and u >= density(p[0], p[1], p[2]):
654
+ continue
655
+ i = voids.locate(p)
656
+ if i < 0:
657
+ continue # in a plate
658
+ attempts += 1
659
+ _, _, _, fn, fc = voids.cells[i]
660
+ if fits_polyhedron(fn, fc, p[0], p[1], p[2], n[0], n[1], n[2], half):
661
+ break
662
+ failures += 1
663
+ if failures >= max_attempts:
664
+ jammed = True
665
+ break
666
+ if jammed:
667
+ break
668
+ cell = voids.cells[i]
669
+ nx, ny, nz = (float(v) for v in n)
670
+ c = nx * p[0] + ny * p[1] + nz * p[2]
671
+ label = t - 1
672
+ w2 = 0.5 * width
673
+ minus = clip_polyhedron(*cell, nx, ny, nz, c - w2, label, tol)
674
+ plus = clip_polyhedron(*cell, -nx, -ny, -nz, -(c + w2), label, tol)
675
+ body = clip_polyhedron(*cell, nx, ny, nz, c + w2, label, tol)
676
+ body = clip_polyhedron(*body, -nx, -ny, -nz, -(c - w2), label, tol)
677
+ rim, rim_lab = section(*cell, nx, ny, nz, c, tol)
678
+ void_volume += (polyhedron_volume(minus[0], minus[1], minus[3], minus[4])
679
+ + polyhedron_volume(plus[0], plus[1], plus[3], plus[4])
680
+ - polyhedron_volume(cell[0], cell[1], cell[3], cell[4])) # fmt: skip
681
+ voids.put(i, minus)
682
+ voids.put(len(voids.cells), plus)
683
+ nucleation.append(p.copy())
684
+ normal.append((nx, ny, nz))
685
+ lam.append(width)
686
+ rims.append(rim)
687
+ rim_faces.append(rim_lab)
688
+ bodies.append(body)
689
+
690
+ n = len(lam)
691
+ rim_offsets, rim_vertices = _csr3(rims)
692
+ _, rim_labels = _csr3(rim_faces, dtype=np.int64, width=0)
693
+ return PlateGrowth(
694
+ nucleation=np.asarray(nucleation, dtype=float).reshape(n, 3),
695
+ normal=np.asarray(normal, dtype=float).reshape(n, 3),
696
+ thickness=np.asarray(lam, dtype=float),
697
+ rim_offsets=rim_offsets,
698
+ rim_vertices=rim_vertices,
699
+ rim_faces=rim_labels,
700
+ bodies=Polyhedra.from_list(bodies),
701
+ cells=Polyhedra.from_list(voids.cells),
702
+ jammed=jammed,
703
+ attempts=attempts,
704
+ )
705
+
706
+
707
+ # -- the growth of beams -------------------------------------------------------------------
708
+
709
+
710
+ @njit(cache=True)
711
+ def _point_segment(px, py, pz, ax, ay, az, bx, by, bz) -> float:
712
+ """Distance from the point ``p`` to the segment ``[a, b]``."""
713
+ ex, ey, ez = bx - ax, by - ay, bz - az
714
+ ee = ex * ex + ey * ey + ez * ez
715
+ u = 0.0
716
+ if ee > 0.0:
717
+ u = min(max(((px - ax) * ex + (py - ay) * ey + (pz - az) * ez) / ee, 0.0), 1.0)
718
+ qx, qy, qz = ax + u * ex - px, ay + u * ey - py, az + u * ez - pz
719
+ return math.sqrt(qx * qx + qy * qy + qz * qz)
720
+
721
+
722
+ @njit(cache=True)
723
+ def _ray_segment(px, py, pz, dx, dy, dz, smax, ax, ay, az, bx, by, bz):
724
+ """The closest approach of the ray ``p + s d`` (``0 <= s <= smax``, ``|d| = 1``) and
725
+ the segment ``[a, b]``: ``s`` and the distance (Ericson 2005, §5.1.9)."""
726
+ ex, ey, ez = bx - ax, by - ay, bz - az
727
+ rx, ry, rz = px - ax, py - ay, pz - az
728
+ ee = ex * ex + ey * ey + ez * ez
729
+ f = ex * rx + ey * ry + ez * rz
730
+ c = dx * rx + dy * ry + dz * rz
731
+ if ee <= 1e-300:
732
+ s = min(max(-c, 0.0), smax)
733
+ u = 0.0
734
+ else:
735
+ b = dx * ex + dy * ey + dz * ez
736
+ denom = ee - b * b
737
+ s = min(max((b * f - c * ee) / denom, 0.0), smax) if denom > 1e-14 * ee else 0.0
738
+ u = (b * s + f) / ee
739
+ if u < 0.0:
740
+ u = 0.0
741
+ s = min(max(-c, 0.0), smax)
742
+ elif u > 1.0:
743
+ u = 1.0
744
+ s = min(max(b - c, 0.0), smax)
745
+ qx = ax + u * ex - (px + s * dx)
746
+ qy = ay + u * ey - (py + s * dy)
747
+ qz = az + u * ez - (pz + s * dz)
748
+ return s, math.sqrt(qx * qx + qy * qy + qz * qz)
749
+
750
+
751
+ @njit(cache=True)
752
+ def beam_clearance(px, py, pz, ends, radii, n) -> float:
753
+ """``min_j (|p - axis_j| - r_j)`` over the ``n`` first beams: negative in a beam, the
754
+ distance to the nearest one outside (``inf``: none)."""
755
+ best = np.inf
756
+ for j in range(n):
757
+ lo0 = min(ends[j, 0, 0], ends[j, 1, 0]) - radii[j]
758
+ hi0 = max(ends[j, 0, 0], ends[j, 1, 0]) + radii[j]
759
+ lo1 = min(ends[j, 0, 1], ends[j, 1, 1]) - radii[j]
760
+ hi1 = max(ends[j, 0, 1], ends[j, 1, 1]) + radii[j]
761
+ lo2 = min(ends[j, 0, 2], ends[j, 1, 2]) - radii[j]
762
+ hi2 = max(ends[j, 0, 2], ends[j, 1, 2]) + radii[j]
763
+ gx = max(lo0 - px, 0.0, px - hi0)
764
+ gy = max(lo1 - py, 0.0, py - hi1)
765
+ gz = max(lo2 - pz, 0.0, pz - hi2)
766
+ if gx * gx + gy * gy + gz * gz >= best * best and best > 0.0:
767
+ continue # its box is farther than the nearest beam yet
768
+ d = _point_segment(px, py, pz, ends[j, 0, 0], ends[j, 0, 1], ends[j, 0, 2],
769
+ ends[j, 1, 0], ends[j, 1, 1], ends[j, 1, 2]) - radii[j] # fmt: skip
770
+ if d < best:
771
+ best = d
772
+ if best < 0.0:
773
+ return best # in a beam
774
+ return best
775
+
776
+
777
+ @njit(cache=True)
778
+ def beam_stop(px, py, pz, dx, dy, dz, smax, ends, radii, n, radius):
779
+ """How far a beam of ``radius`` grows from ``p`` along ``d`` (``|d| = 1``) among the
780
+ ``n`` first beams, up to ``smax`` (the box): its axis stops where it reaches the
781
+ surface of a beam, or at its closest approach to a beam it passes within contact
782
+ (``r_j + radius``); the distance and the beam (:data:`BOX`: none)."""
783
+ best = smax
784
+ who = BOX
785
+ for j in range(n):
786
+ reach = radii[j] + radius
787
+ # the box of the axis of j widened by the contact against the box of the ray
788
+ qx, qy, qz = px + best * dx, py + best * dy, pz + best * dz
789
+ if (max(ends[j, 0, 0], ends[j, 1, 0]) + reach < min(px, qx)
790
+ or min(ends[j, 0, 0], ends[j, 1, 0]) - reach > max(px, qx)
791
+ or max(ends[j, 0, 1], ends[j, 1, 1]) + reach < min(py, qy)
792
+ or min(ends[j, 0, 1], ends[j, 1, 1]) - reach > max(py, qy)
793
+ or max(ends[j, 0, 2], ends[j, 1, 2]) + reach < min(pz, qz)
794
+ or min(ends[j, 0, 2], ends[j, 1, 2]) - reach > max(pz, qz)): # fmt: skip
795
+ continue
796
+ ax, ay, az = ends[j, 0, 0], ends[j, 0, 1], ends[j, 0, 2]
797
+ bx, by, bz = ends[j, 1, 0], ends[j, 1, 1], ends[j, 1, 2]
798
+ s, dmin = _ray_segment(px, py, pz, dx, dy, dz, best, ax, ay, az, bx, by, bz)
799
+ if dmin > reach:
800
+ continue
801
+ if dmin <= radii[j]: # the axis meets the surface of j first where it crosses it
802
+ lo, hi = 0.0, s
803
+ for _ in range(64):
804
+ mid = 0.5 * (lo + hi)
805
+ if _point_segment(px + mid * dx, py + mid * dy, pz + mid * dz,
806
+ ax, ay, az, bx, by, bz) > radii[j]: # fmt: skip
807
+ lo = mid
808
+ else:
809
+ hi = mid
810
+ s = hi
811
+ if s < best:
812
+ best, who = s, j
813
+ return best, who
814
+
815
+
816
+ @njit(cache=True)
817
+ def beam_contacts(ax, ay, az, dx, dy, dz, length, radius, ends, radii, n, tol):
818
+ """The beams among the ``n`` first ones that the beam of axis ``a + s d`` (``0 <= s <=
819
+ length``) and ``radius`` touches or overlaps (within ``tol``)."""
820
+ out = np.empty(n, dtype=np.int64)
821
+ m = 0
822
+ bx, by, bz = ax + length * dx, ay + length * dy, az + length * dz
823
+ for j in range(n):
824
+ reach = radii[j] + radius + tol
825
+ if (max(ends[j, 0, 0], ends[j, 1, 0]) + reach < min(ax, bx)
826
+ or min(ends[j, 0, 0], ends[j, 1, 0]) - reach > max(ax, bx)
827
+ or max(ends[j, 0, 1], ends[j, 1, 1]) + reach < min(ay, by)
828
+ or min(ends[j, 0, 1], ends[j, 1, 1]) - reach > max(ay, by)
829
+ or max(ends[j, 0, 2], ends[j, 1, 2]) + reach < min(az, bz)
830
+ or min(ends[j, 0, 2], ends[j, 1, 2]) - reach > max(az, bz)): # fmt: skip
831
+ continue
832
+ e = ends[j]
833
+ _, dmin = _ray_segment(ax, ay, az, dx, dy, dz, length, e[0, 0], e[0, 1], e[0, 2],
834
+ e[1, 0], e[1, 1], e[1, 2]) # fmt: skip
835
+ if dmin <= reach:
836
+ out[m] = j
837
+ m += 1
838
+ return out[:m]
839
+
840
+
841
+ def _exit(p, d, lo, hi) -> float:
842
+ """How far the ray ``p + s d`` runs in the box ``[lo, hi]`` holding ``p``."""
843
+ s = math.inf
844
+ for a in range(3):
845
+ if d[a] > 0:
846
+ s = min(s, (hi[a] - p[a]) / d[a])
847
+ elif d[a] < 0:
848
+ s = min(s, (lo[a] - p[a]) / d[a])
849
+ return max(s, 0.0)
850
+
851
+
852
+ @dataclass
853
+ class BeamGrowth:
854
+ """The beams of a scale-rich network of beams."""
855
+
856
+ nucleation: np.ndarray # (N, 3) the nucleation points
857
+ direction: np.ndarray # (N, 3) the unit vectors of the axes
858
+ thickness: np.ndarray # (N,) the diameters
859
+ ends: np.ndarray # (N, 2, 3) the ends of the axes
860
+ neighbours: np.ndarray # (N, 2) the beams that stop the ends (BOX: the boundary)
861
+ contact_offsets: np.ndarray # (N + 1,) CSR of the earlier beams that each beam touches
862
+ contacts: np.ndarray # (M,)
863
+ jammed: bool = False
864
+ attempts: int = 0
865
+
866
+ @property
867
+ def n(self) -> int:
868
+ return len(self.thickness)
869
+
870
+ @property
871
+ def radii(self) -> np.ndarray:
872
+ return 0.5 * self.thickness
873
+
874
+ @property
875
+ def lengths(self) -> np.ndarray:
876
+ """The lengths of the axes of the beams."""
877
+ return np.linalg.norm(self.ends[:, 1] - self.ends[:, 0], axis=1)
878
+
879
+ def volumes(self) -> np.ndarray:
880
+ """The volumes of the cylinders on the axes, ``pi r^2 l`` (their round ends lie in
881
+ the beams they meet or beyond the box)."""
882
+ return np.pi * self.radii**2 * self.lengths
883
+
884
+ def links(self) -> np.ndarray:
885
+ """The pairs of beams joined: each beam with the earlier beams it touches, those
886
+ that stop its ends and those it meets beside them (the edges of the dual graph,
887
+ each once)."""
888
+ i = np.repeat(np.arange(self.n), np.diff(self.contact_offsets))
889
+ return np.column_stack([i, self.contacts]).astype(np.int64).reshape(-1, 2)
890
+
891
+ def degrees(self) -> np.ndarray:
892
+ """The number of beams each beam touches (its degree in the dual graph)."""
893
+ e = self.links()
894
+ return np.bincount(e.ravel(), minlength=self.n).astype(np.int64)
895
+
896
+ def orientation_tensor(self) -> np.ndarray:
897
+ """``M = sum V_t d_t d_t / sum V_t``: the axes ``d_t`` of the beams weighted by
898
+ their volumes ``V_t``."""
899
+ v = self.volumes()
900
+ if not v.sum() > 0:
901
+ return np.full((3, 3), np.nan)
902
+ return np.einsum("t,ti,tj->ij", v, self.direction, self.direction) / v.sum()
903
+
904
+
905
+ def grow_beams(
906
+ lower,
907
+ upper,
908
+ n_beams: int,
909
+ thickness,
910
+ entropy: int,
911
+ *,
912
+ directions=None,
913
+ density=None,
914
+ min_spacing: float = 0.0,
915
+ max_attempts: int = 1000,
916
+ ) -> BeamGrowth:
917
+ """Grow a scale-rich network of beams in the box ``[lower, upper]``: as
918
+ :func:`grow_plates`, ``thickness(t)`` the diameter of the beam ``t`` and
919
+ ``directions`` its axes. A nucleation point inside a beam is drawn again; the beam fits
920
+ where the ball of radius ``(lambda_t + epsilon) / 2`` about the point clears the other
921
+ beams and the faces of the box (:func:`beam_clearance`), and grows both ways
922
+ (:func:`beam_stop`)."""
923
+ lo = np.asarray(lower, dtype=float).reshape(3)
924
+ hi = np.asarray(upper, dtype=float).reshape(3)
925
+ size = hi - lo
926
+ draw_axes = isotropic_directions if directions is None else directions
927
+ cap = int(n_beams)
928
+ ends = np.zeros((cap, 2, 3))
929
+ radii = np.zeros(cap)
930
+ tol = 1e-9 * float(np.max(size))
931
+ nucleation, axes, neighbours, contacts = [], [], [], []
932
+ attempts = 0
933
+ jammed = False
934
+ n = 0
935
+ for t in range(1, cap + 1):
936
+ radius = 0.5 * float(thickness(t))
937
+ clear = radius + 0.5 * min_spacing
938
+ gen = np.random.Generator(np.random.PCG64(np.random.SeedSequence(entropy, spawn_key=(t,))))
939
+ gdir = np.random.Generator(
940
+ np.random.PCG64(np.random.SeedSequence(entropy, spawn_key=(t, 1)))
941
+ )
942
+ failures = k = 0
943
+ block = gen.random((16, _DRAWS))
944
+ pts = lo + block[:, :3] * size
945
+ dirs = draw_axes(t, pts, gdir)
946
+ while True:
947
+ if k == len(block):
948
+ block, k = gen.random((256, _DRAWS)), 0
949
+ pts = lo + block[:, :3] * size
950
+ dirs = draw_axes(t, pts, gdir)
951
+ p, u = pts[k], block[k, 3]
952
+ d = dirs[k]
953
+ k += 1
954
+ if density is not None and u >= density(p[0], p[1], p[2]):
955
+ continue
956
+ gap = beam_clearance(p[0], p[1], p[2], ends, radii, n)
957
+ if gap < 0:
958
+ continue # in a beam
959
+ attempts += 1
960
+ if gap >= clear and np.all(p - lo >= clear) and np.all(hi - p >= clear):
961
+ break
962
+ failures += 1
963
+ if failures >= max_attempts:
964
+ jammed = True
965
+ break
966
+ if jammed:
967
+ break
968
+ d = np.asarray(d, dtype=float)
969
+ s1, j1 = beam_stop(p[0], p[1], p[2], d[0], d[1], d[2], _exit(p, d, lo, hi), ends, radii,
970
+ n, radius) # fmt: skip
971
+ s0, j0 = beam_stop(p[0], p[1], p[2], -d[0], -d[1], -d[2], _exit(p, -d, lo, hi), ends,
972
+ radii, n, radius) # fmt: skip
973
+ ends[n, 0] = p - s0 * d
974
+ ends[n, 1] = p + s1 * d
975
+ start = ends[n, 0]
976
+ contacts.append(beam_contacts(start[0], start[1], start[2], d[0], d[1], d[2], s0 + s1,
977
+ radius, ends, radii, n, tol)) # fmt: skip
978
+ radii[n] = radius
979
+ n += 1
980
+ nucleation.append(p.copy())
981
+ axes.append(d)
982
+ neighbours.append((j0, j1))
983
+ contact_offsets, contact_items = _csr3(contacts, dtype=np.int64, width=0)
984
+ return BeamGrowth(
985
+ nucleation=np.asarray(nucleation, dtype=float).reshape(n, 3),
986
+ direction=np.asarray(axes, dtype=float).reshape(n, 3),
987
+ thickness=2.0 * radii[:n].copy(),
988
+ ends=ends[:n].copy(),
989
+ neighbours=np.asarray(neighbours, dtype=np.int64).reshape(n, 2),
990
+ contact_offsets=contact_offsets,
991
+ contacts=contact_items,
992
+ jammed=jammed,
993
+ attempts=attempts,
994
+ )
995
+
996
+
997
+ # -- theory --------------------------------------------------------------------------------
998
+
999
+
1000
+ def _radial_moments(radius: float, c: float) -> tuple[float, float, float]:
1001
+ """``int_0^R rho^k g(rho) d rho`` for ``k = 1, 2, 3``, with ``g(rho) = int_0^c (c - z) /
1002
+ sqrt(rho^2 + z^2) dz = c asinh(c / rho) - sqrt(rho^2 + c^2) + rho`` (closed forms)."""
1003
+ r = radius
1004
+ s = math.sqrt(r * r + c * c)
1005
+ ash = math.asinh(r / c)
1006
+ inv = math.asinh(c / r) if r > 0 else 0.0
1007
+ q1 = s - c # int rho^k / sqrt(rho^2 + c^2)
1008
+ q2 = 0.5 * (r * s - c * c * ash)
1009
+ q3 = (s**3 - c**3) / 3.0 - c * c * (s - c)
1010
+ a1 = r**2 / 2 * inv + c / 2 * q1 # int rho^k asinh(c / rho), by parts
1011
+ a2 = r**3 / 3 * inv + c / 3 * q2
1012
+ a3 = r**4 / 4 * inv + c / 4 * q3
1013
+ r1 = (s**3 - c**3) / 3.0 # int rho^k sqrt(rho^2 + c^2)
1014
+ r2 = r * (2 * r * r + c * c) * s / 8.0 - c**4 / 8.0 * ash
1015
+ r3 = (s**5 - c**5) / 5.0 - c * c * (s**3 - c**3) / 3.0
1016
+ return c * a1 - r1 + r**3 / 3, c * a2 - r2 + r**4 / 4, c * a3 - r3 + r**5 / 5
1017
+
1018
+
1019
+ @lru_cache(maxsize=64)
1020
+ def _box_integral(a: float, b: float, c: float) -> float:
1021
+ """``int_[0,a]x[0,b]x[0,c] (a - x)(b - y)(c - z) / |r| dr``: the integral over ``z`` and
1022
+ the radius of polar coordinates of the plane in closed form, the angle by Gauss-Legendre
1023
+ on either side of the diagonal (smooth there)."""
1024
+ x, w = np.polynomial.legendre.leggauss(48)
1025
+ diagonal = math.atan2(b, a)
1026
+ total = 0.0
1027
+ for lo, hi, side in ((0.0, diagonal, 0), (diagonal, 0.5 * math.pi, 1)):
1028
+ for xi, wi in zip(lo + (x + 1) * (hi - lo) / 2, w * (hi - lo) / 2, strict=True):
1029
+ sin, cos = math.sin(xi), math.cos(xi)
1030
+ m1, m2, m3 = _radial_moments(a / cos if side == 0 else b / sin, c)
1031
+ total += wi * (a * b * m1 - (a * sin + b * cos) * m2 + sin * cos * m3)
1032
+ return float(total)
1033
+
1034
+
1035
+ def mean_inverse_distance(a: float, b: float, c: float) -> float:
1036
+ """``E[1 / |X - Y|]`` for two points uniform in an ``a x b x c`` box (1.882313 for the
1037
+ unit cube, Bailey, Borwein & Crandall 2007)."""
1038
+ a, b, c = float(a), float(b), float(c)
1039
+ return 8.0 * _box_integral(a, b, c) / (a * b * c) ** 2
1040
+
1041
+
1042
+ def first_area(a: float, b: float, c: float) -> float:
1043
+ """The mean area of the first plate in an ``a x b x c`` box: the section by the plane
1044
+ through a uniform point with a uniform normal, ``int A^2 dE / (4 pi V)`` over the
1045
+ planes ``E``. As ``int_S2 delta(n . r) dn = 2 pi / |r|``, it is ``V E[1/|X - Y|] / 2``
1046
+ (:func:`mean_inverse_distance`): 0.941156 for the unit cube."""
1047
+ a, b, c = float(a), float(b), float(c)
1048
+ return 0.5 * a * b * c * mean_inverse_distance(a, b, c)
1049
+
1050
+
1051
+ def area_sum(decay: float, n_plates: int, a: float, b: float, c: float) -> float:
1052
+ """``sum_t a_t t^-alpha / V^(2/3)`` of a thin network of ``T`` plates in an ``a x b x
1053
+ c`` box: ``a_0 / V^(2/3) + c_3 sum_{t=2..T} t^-(alpha + 2/3)`` (:func:`first_area`,
1054
+ :data:`AREA_CONSTANT`), the relative density per unit of ``lambda_0 / V^(1/3)``."""
1055
+ volume = a * b * c
1056
+ tail = 0.0
1057
+ if n_plates >= 2:
1058
+ t = np.arange(2, int(n_plates) + 1, dtype=float)
1059
+ tail = float(np.sum(t ** (-(decay + 2.0 / 3.0))))
1060
+ return float(first_area(a, b, c) / volume ** (2.0 / 3.0) + AREA_CONSTANT * tail)
1061
+
1062
+
1063
+ @lru_cache(maxsize=16)
1064
+ def _exits(a: float, b: float, c: float, n: int = 4096) -> np.ndarray:
1065
+ """How far rays from uniform points of an ``a x b x c`` box along uniform directions
1066
+ run in it: ``n`` draws of a fixed seed."""
1067
+ rng = np.random.default_rng(2026)
1068
+ size = np.array([a, b, c])
1069
+ p = rng.random((n, 3)) * size
1070
+ d = uniform_unit_vectors(rng, n)
1071
+ with np.errstate(divide="ignore"):
1072
+ s = np.where(d > 0, (size - p) / d, np.where(d < 0, -p / d, np.inf))
1073
+ return s.min(axis=1)
1074
+
1075
+
1076
+ def beam_density_estimate(initial_thickness: float, decay: float, n_beams: int, sides) -> float:
1077
+ """The mean-field relative density of ``T`` beams in a box (isotropic axes and
1078
+ nucleation): a beam of radius ``r_t`` is stopped by a beam ``j`` it passes within ``r_j
1079
+ + r_t`` of, whose capsule of that radius has the mean cross-section ``sigma_j = (pi / 2)
1080
+ (r_j + r_t) l_j + pi (r_j + r_t)^2`` (Cauchy: a quarter of its surface), so that each
1081
+ half of its axis runs ``min(X, D)``: ``X`` exponential of rate ``h_t = sum_j sigma_j /
1082
+ V``, ``D`` the distance to the box. Then ``l_t = 2 E[(1 - exp(-h_t D)) / h_t]`` and
1083
+ ``rho = sum_t pi r_t^2 l_t / V``; jamming is ignored."""
1084
+ a, b, c = (float(v) for v in sides)
1085
+ volume = a * b * c
1086
+ exits = _exits(a, b, c)
1087
+ a1 = a0 = b2 = b1 = rho = 0.0
1088
+ for t in range(1, int(n_beams) + 1):
1089
+ r = 0.5 * float(initial_thickness) * t ** (-float(decay))
1090
+ n = t - 1
1091
+ h = (0.5 * np.pi * (a1 + r * a0) + np.pi * (b2 + 2.0 * r * b1 + n * r * r)) / volume
1092
+ if h * exits.max() < 1e-12:
1093
+ half = float(exits.mean())
1094
+ else:
1095
+ half = float(np.mean(-np.expm1(-h * exits)) / h)
1096
+ length = 2.0 * half
1097
+ rho += np.pi * r * r * length / volume
1098
+ a1 += r * length
1099
+ a0 += length
1100
+ b2 += r * r
1101
+ b1 += r
1102
+ return float(rho)
1103
+
1104
+
1105
+ def beam_thickness_estimate(volume_fraction: float, decay: float, n_beams: int, sides) -> float:
1106
+ """The initial thickness at which the mean field of :func:`beam_density_estimate` gives
1107
+ the relative density (by bisection of its logarithm)."""
1108
+ target = float(volume_fraction)
1109
+ lo, hi = 1e-6 * min(sides), float(max(sides))
1110
+ for _ in range(60):
1111
+ mid = math.sqrt(lo * hi)
1112
+ if beam_density_estimate(mid, decay, n_beams, sides) < target:
1113
+ lo = mid
1114
+ else:
1115
+ hi = mid
1116
+ if hi / lo < 1.0 + 1e-6:
1117
+ break
1118
+ return math.sqrt(lo * hi)
1119
+
1120
+
1121
+ @lru_cache(maxsize=1)
1122
+ def union_points() -> np.ndarray:
1123
+ """The ``2^UNION_POINTS_LOG2`` points of the unit cube (a scrambled Sobol set of a fixed
1124
+ seed) on which the relative density of beams is estimated."""
1125
+ from scipy.stats import qmc
1126
+
1127
+ pts = qmc.Sobol(3, scramble=True, seed=2026).random_base2(UNION_POINTS_LOG2)
1128
+ pts.setflags(write=False)
1129
+ return pts
1130
+
1131
+
1132
+ # -- the field of the plates or beams at points of the box: a grid of buckets --------------
1133
+
1134
+
1135
+ @njit(cache=True)
1136
+ def _register(boxes, reach, lo, h, g):
1137
+ """The elements of each bucket of a ``g[0] x g[1] x g[2]`` grid: those whose box (lower
1138
+ and upper corners), widened by ``reach``, meets it (compressed rows)."""
1139
+ n = boxes.shape[0]
1140
+ nb = g[0] * g[1] * g[2]
1141
+ counts = np.zeros(nb, dtype=np.int64)
1142
+ offsets = np.zeros(nb + 1, dtype=np.int64)
1143
+ items = np.empty(0, dtype=np.int64)
1144
+ fill = np.zeros(nb, dtype=np.int64)
1145
+ for pass_ in range(2):
1146
+ if pass_ == 1:
1147
+ for b in range(nb):
1148
+ offsets[b + 1] = offsets[b] + counts[b]
1149
+ items = np.empty(offsets[-1], dtype=np.int64)
1150
+ fill = offsets[:-1].copy()
1151
+ for p in range(n):
1152
+ r0 = np.empty(3, dtype=np.int64)
1153
+ r1 = np.empty(3, dtype=np.int64)
1154
+ for a in range(3):
1155
+ r0[a] = min(max(math.floor((boxes[p, a] - reach - lo[a]) / h[a]), 0), g[a] - 1)
1156
+ r1[a] = min(max(math.floor((boxes[p, 3 + a] + reach - lo[a]) / h[a]), 0), g[a] - 1)
1157
+ for i in range(r0[0], r1[0] + 1):
1158
+ for j in range(r0[1], r1[1] + 1):
1159
+ for k in range(r0[2], r1[2] + 1):
1160
+ b = (i * g[1] + j) * g[2] + k
1161
+ if pass_ == 0:
1162
+ counts[b] += 1
1163
+ else:
1164
+ items[fill[b]] = p
1165
+ fill[b] += 1
1166
+ return offsets, items
1167
+
1168
+
1169
+ @njit(inline="always")
1170
+ def _bucket(x, y, z, lo, h, g):
1171
+ i = min(max(math.floor((x - lo[0]) / h[0]), 0), g[0] - 1)
1172
+ j = min(max(math.floor((y - lo[1]) / h[1]), 0), g[1] - 1)
1173
+ k = min(max(math.floor((z - lo[2]) / h[2]), 0), g[2] - 1)
1174
+ return (i * g[1] + j) * g[2] + k
1175
+
1176
+
1177
+ @njit(parallel=True, cache=True)
1178
+ def _plates_field(pts, reach, boxes, offsets, normals, planes, b_off, b_items, lo, h, g):
1179
+ """``min(reach, min_p max_f (n_f . x - c_f))`` at points: negative in the plates (convex
1180
+ polyhedra ``p`` of faces ``f``), the distance to the nearest one near them, or less."""
1181
+ out = np.empty(pts.shape[0])
1182
+ for q in prange(pts.shape[0]):
1183
+ x, y, z = pts[q, 0], pts[q, 1], pts[q, 2]
1184
+ b = _bucket(x, y, z, lo, h, g)
1185
+ best = reach
1186
+ for kk in range(b_off[b], b_off[b + 1]):
1187
+ p = b_items[kk]
1188
+ if (x < boxes[p, 0] - reach or x > boxes[p, 3] + reach or y < boxes[p, 1] - reach
1189
+ or y > boxes[p, 4] + reach or z < boxes[p, 2] - reach
1190
+ or z > boxes[p, 5] + reach): # fmt: skip
1191
+ continue
1192
+ phi = -np.inf
1193
+ for f in range(offsets[p], offsets[p + 1]):
1194
+ v = normals[f, 0] * x + normals[f, 1] * y + normals[f, 2] * z - planes[f]
1195
+ if v > phi:
1196
+ phi = v
1197
+ if phi >= best:
1198
+ break
1199
+ if phi < best:
1200
+ best = phi
1201
+ out[q] = best
1202
+ return out
1203
+
1204
+
1205
+ @njit(parallel=True, cache=True)
1206
+ def _beams_field(pts, reach, boxes, ends, radii, b_off, b_items, lo, h, g):
1207
+ """``min(reach, min_j (|x - axis_j| - r_j))`` at points: the signed distance to the
1208
+ beams (round ends) near them, negative inside."""
1209
+ out = np.empty(pts.shape[0])
1210
+ for q in prange(pts.shape[0]):
1211
+ x, y, z = pts[q, 0], pts[q, 1], pts[q, 2]
1212
+ b = _bucket(x, y, z, lo, h, g)
1213
+ best = reach
1214
+ for kk in range(b_off[b], b_off[b + 1]):
1215
+ j = b_items[kk]
1216
+ if (x < boxes[j, 0] - reach or x > boxes[j, 3] + reach or y < boxes[j, 1] - reach
1217
+ or y > boxes[j, 4] + reach or z < boxes[j, 2] - reach
1218
+ or z > boxes[j, 5] + reach): # fmt: skip
1219
+ continue
1220
+ d = _point_segment(x, y, z, ends[j, 0, 0], ends[j, 0, 1], ends[j, 0, 2],
1221
+ ends[j, 1, 0], ends[j, 1, 1], ends[j, 1, 2]) - radii[j] # fmt: skip
1222
+ if d < best:
1223
+ best = d
1224
+ out[q] = best
1225
+ return out
1226
+
1227
+
1228
+ class _Index:
1229
+ """Elements of a network (their boxes) registered in a grid of buckets of the box, to
1230
+ evaluate their field within ``reach`` of them."""
1231
+
1232
+ def __init__(self, boxes: np.ndarray, lower, upper, reach: float) -> None:
1233
+ self.reach = float(reach)
1234
+ self.boxes = np.ascontiguousarray(boxes, dtype=float).reshape(-1, 6)
1235
+ lo, hi = np.asarray(lower, dtype=float), np.asarray(upper, dtype=float)
1236
+ size = hi - lo
1237
+ n = len(self.boxes)
1238
+ cube = float(np.prod(size)) ** (1.0 / 3.0)
1239
+ g = np.clip(np.ceil(max(n, 1) ** (1.0 / 3.0) * size / cube), 1, 128).astype(np.int64)
1240
+ self.g = g
1241
+ self.lo = lo
1242
+ self.h = size / g
1243
+ self.b_off, self.b_items = _register(self.boxes, self.reach, lo, self.h, g)
1244
+
1245
+
1246
+ def _slabs(grid: Grid, ss: int, values_of, reduce_dtype) -> np.ndarray:
1247
+ """``values_of(points)`` on the voxel centres of ``grid`` (``ss`` = 1) or the mean of
1248
+ its ``ss^3`` sub-voxels (sub-grid of ``ss`` times the resolution), slab by slab."""
1249
+ nx, ny, nz = grid.shape
1250
+ out = np.empty(grid.shape, dtype=reduce_dtype)
1251
+ fine = grid if ss == 1 else Grid(grid.domain, (nx * ss, ny * ss, nz * ss))
1252
+ step = max(1, (1 << 21) // max(1, nx * ny * ss**3))
1253
+ for k0 in range(0, nz, step):
1254
+ k1 = min(nz, k0 + step)
1255
+ vals = values_of(fine.center_points(k0 * ss, k1 * ss))
1256
+ if ss == 1:
1257
+ out[:, :, k0:k1] = vals.reshape(nx, ny, k1 - k0)
1258
+ else:
1259
+ v = vals.reshape(nx, ss, ny, ss, k1 - k0, ss).astype(np.float32)
1260
+ out[:, :, k0:k1] = v.mean(axis=(1, 3, 5), dtype=np.float32)
1261
+ return out
1262
+
1263
+
1264
+ # -- the microstructures -------------------------------------------------------------------
1265
+
1266
+
1267
+ class _Network3D(Microstructure):
1268
+ """A scale-rich network of plates or beams in the box, within a ``frame`` of material
1269
+ on which they end (0: none)."""
1270
+
1271
+ def __init__(self, domain: Domain, growth, frame: float = 0.0, **kwargs) -> None:
1272
+ super().__init__(domain, **kwargs)
1273
+ self.growth = growth
1274
+ self.frame = float(frame)
1275
+ self._indices: dict[float, _Index] = {}
1276
+
1277
+ @property
1278
+ def n_ligaments(self) -> int:
1279
+ return self.growth.n
1280
+
1281
+ @property
1282
+ def thicknesses(self) -> np.ndarray:
1283
+ return self.growth.thickness
1284
+
1285
+ def degrees(self) -> np.ndarray:
1286
+ """The degree of each element in the dual graph: the elements it meets."""
1287
+ return self.growth.degrees()
1288
+
1289
+ def links(self) -> np.ndarray:
1290
+ """The pairs of elements that meet."""
1291
+ return self.growth.links()
1292
+
1293
+ def orientation_tensor(self) -> np.ndarray:
1294
+ """The orientation tensor of the elements (3 x 3, trace 1)."""
1295
+ return self.growth.orientation_tensor()
1296
+
1297
+ @property
1298
+ def geometric_anisotropy(self) -> float:
1299
+ """``mu_min / mu_max``, the ratio of the extreme eigenvalues of the orientation
1300
+ tensor: 1 for isotropic directions, 0 when they all lie in a plane (or along an
1301
+ axis)."""
1302
+ mu = np.linalg.eigvalsh(self.orientation_tensor())
1303
+ return float(mu[0] / mu[2]) if mu[2] > 0 else math.nan
1304
+
1305
+ # -- the field -------------------------------------------------------------------
1306
+
1307
+ def _boxes(self) -> np.ndarray:
1308
+ raise NotImplementedError
1309
+
1310
+ def _elements_field(self, pts: np.ndarray, index: _Index) -> np.ndarray:
1311
+ raise NotImplementedError
1312
+
1313
+ def _index(self, reach: float) -> _Index:
1314
+ key = round(float(reach), 12)
1315
+ if key not in self._indices:
1316
+ self._indices.clear()
1317
+ self._indices[key] = _Index(self._boxes(), self.domain.lower, self.domain.upper,
1318
+ reach) # fmt: skip
1319
+ return self._indices[key]
1320
+
1321
+ def field(self, points, reach: float = 0.0) -> np.ndarray:
1322
+ """Negative in the elements (and the frame), positive in the voids: their signed
1323
+ distance near them (plates: a lower bound near their edges), capped at
1324
+ ``reach``."""
1325
+ pts = np.ascontiguousarray(np.asarray(points, dtype=float).reshape(-1, 3))
1326
+ index = self._index(reach)
1327
+ if len(index.boxes):
1328
+ out = self._elements_field(pts, index)
1329
+ else:
1330
+ out = np.full(len(pts), float(reach))
1331
+ if self.frame > 0:
1332
+ inner = np.minimum(pts - self.domain.lower, self.domain.upper - pts).min(axis=1)
1333
+ out = np.minimum(out, inner - self.frame)
1334
+ return out
1335
+
1336
+ def contains(self, points) -> np.ndarray:
1337
+ pts = np.asarray(points, dtype=float).reshape(-1, 3)
1338
+ inside = np.all((pts >= self.domain.lower) & (pts <= self.domain.upper), axis=1)
1339
+ return (self.field(pts) < 0) & inside
1340
+
1341
+ def level_set_at(self, points, reach: float = np.inf) -> np.ndarray:
1342
+ """:meth:`field` within ``reach`` (default: the diagonal of the box): the signed
1343
+ distance to the beams; for plates, the largest of the signed distances to the planes
1344
+ of the faces (the distance outside them near their faces, a lower bound near their
1345
+ edges)."""
1346
+ if not np.isfinite(reach):
1347
+ reach = float(self.domain.diagonal)
1348
+ return self.field(points, float(reach))
1349
+
1350
+ def voxelize(self, shape=None, *, voxel_size=None, grid: Grid | None = None, supersampling=1):
1351
+ grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
1352
+ ss = int(supersampling)
1353
+ if not 1 <= ss <= 6:
1354
+ raise ValueError("supersampling must be an integer between 1 and 6")
1355
+ meta = self.image_metadata()
1356
+ if ss == 1:
1357
+ data = _slabs(grid, 1, lambda p: (self.field(p) < 0).astype(np.uint8), np.uint8)
1358
+ return VoxelImage.from_grid(data, grid, name="phase", metadata=meta)
1359
+ data = _slabs(grid, ss, lambda p: self.field(p) < 0, np.float32)
1360
+ return VoxelImage.from_grid(data, grid, name="fraction", metadata=meta)
1361
+
1362
+ def level_set(self, shape=None, *, voxel_size=None, grid: Grid | None = None) -> VoxelImage:
1363
+ """Negative in the elements, positive in the voids: the distance to them near
1364
+ them (plates: a lower bound near their edges), within the largest half thickness
1365
+ and four voxels of them."""
1366
+ grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
1367
+ thick = float(self.thicknesses.max()) if self.n_ligaments else 0.0
1368
+ reach = 0.5 * thick + 4.0 * float(np.max(grid.spacing))
1369
+ data = _slabs(grid, 1, lambda p: self.field(p, reach).astype(np.float32), np.float32)
1370
+ return VoxelImage.from_grid(data, grid, name="level_set", metadata=self.image_metadata())
1371
+
1372
+ def _frame_volume(self) -> float:
1373
+ inner = np.clip(self.domain.lengths - 2.0 * self.frame, 0.0, None)
1374
+ return float(self.domain.volume - np.prod(inner))
1375
+
1376
+
1377
+ @register_kind
1378
+ class ScaleRichPlates(_Network3D):
1379
+ """A scale-rich network of plates: its plates (phase 1, convex polyhedra that never
1380
+ overlap) and its voids (phase 0, closed convex cells), which partition the box exactly
1381
+ (:func:`grow_plates`); or, with a ``frame``, the box within a frame of that thickness
1382
+ (phase 1 too), on which the plates end."""
1383
+
1384
+ kind = "scale_rich_plates"
1385
+
1386
+ @property
1387
+ def areas(self) -> np.ndarray:
1388
+ """The areas of the plates (of their rims, the sections of their voids by their
1389
+ mid-planes)."""
1390
+ return self.growth.areas
1391
+
1392
+ @property
1393
+ def normals(self) -> np.ndarray:
1394
+ return self.growth.normal
1395
+
1396
+ @property
1397
+ def volume_fraction(self) -> float:
1398
+ """The fraction of the box in the plates and the frame, exact (``1 - sum(void
1399
+ volumes) / V``)."""
1400
+ return float(1.0 - self.growth.cell_volumes().sum() / self.domain.volume)
1401
+
1402
+ def statistics(self, min_tail: int = 50) -> dict:
1403
+ """The power-law tails of the thicknesses, areas and degrees of the plates
1404
+ (:func:`morphogen.analysis.power_laws.power_law_tail`, degrees as integers):
1405
+ ``1 + 1/alpha``, 5/2 and 5/2 for their exponents in theory. No thicknesses with a
1406
+ decay of 0 (one thickness)."""
1407
+ from morphogen.analysis.power_laws import power_law_tail
1408
+
1409
+ tail = min(int(min_tail), max(2, self.n_ligaments // 2))
1410
+ out = {}
1411
+ if np.ptp(self.thicknesses) > 0: # a decay of 0: one thickness, no tail
1412
+ out["thickness"] = power_law_tail(self.thicknesses, min_tail=tail)
1413
+ out["area"] = power_law_tail(self.areas, min_tail=tail)
1414
+ out["degree"] = power_law_tail(self.degrees(), discrete=True, min_tail=tail)
1415
+ return out
1416
+
1417
+ def convex_pieces(self) -> tuple[list[tuple], np.ndarray, np.ndarray]:
1418
+ """The convex pieces that partition the box: the plates (phase 1, cells 1 to N), the
1419
+ voids (phase 0, cell 0) and the boxes of the frame (phase 1, cell N + 1), for the
1420
+ exact meshes of :func:`morphogen.mesh.exact.polyhedral_mesh`."""
1421
+ g = self.growth
1422
+ pieces = [g.bodies.polyhedron(i) for i in range(len(g.bodies))]
1423
+ phase, cells = [1] * len(pieces), list(range(1, len(pieces) + 1))
1424
+ for i in range(len(g.cells)):
1425
+ poly = g.cells.polyhedron(i)
1426
+ if len(poly[2]) >= 4 and polyhedron_volume(poly[0], poly[1], poly[3], poly[4]) > 0:
1427
+ pieces.append(poly)
1428
+ phase.append(0)
1429
+ cells.append(0)
1430
+ if self.frame > 0:
1431
+ boxes = frame_boxes(self.domain.lower, self.domain.upper, self.frame)
1432
+ pieces += boxes
1433
+ phase += [1] * len(boxes)
1434
+ cells += [g.n + 1] * len(boxes)
1435
+ return pieces, np.asarray(phase, dtype=np.int64), np.asarray(cells, dtype=np.int64)
1436
+
1437
+ def _boxes(self) -> np.ndarray:
1438
+ return self.growth.bodies.bounds()
1439
+
1440
+ def _elements_field(self, pts, index) -> np.ndarray:
1441
+ b = self.growth.bodies
1442
+ return _plates_field(pts, index.reach, index.boxes, b.offsets, b.normals, b.planes,
1443
+ index.b_off, index.b_items, index.lo, index.h, index.g) # fmt: skip
1444
+
1445
+ def summary(self) -> dict:
1446
+ """The counts, thicknesses, areas, degrees and anisotropy of the network."""
1447
+ g = self.growth
1448
+ out = {"ligaments": g.n, "jammed": int(g.jammed), "volume_fraction": self.volume_fraction}
1449
+ if g.n:
1450
+ deg = g.degrees()
1451
+ out.update(
1452
+ {
1453
+ "initial_thickness": float(g.thickness[0]),
1454
+ "final_thickness": float(g.thickness[-1]),
1455
+ "mean_area": float(g.areas.mean()),
1456
+ "mean_degree": float(deg.mean()),
1457
+ "max_degree": int(deg.max()),
1458
+ "geometric_anisotropy": self.geometric_anisotropy,
1459
+ }
1460
+ )
1461
+ return out
1462
+
1463
+ def _geometry(self) -> dict:
1464
+ g = self.growth
1465
+ return {
1466
+ "nucleation": g.nucleation.tolist(),
1467
+ "normal": g.normal.tolist(),
1468
+ "thickness": g.thickness.tolist(),
1469
+ "rims": {
1470
+ "offsets": g.rim_offsets.tolist(),
1471
+ "vertices": g.rim_vertices.tolist(),
1472
+ "faces": g.rim_faces.tolist(),
1473
+ },
1474
+ "bodies": g.bodies.to_dict(),
1475
+ "cells": g.cells.to_dict(),
1476
+ "jammed": bool(g.jammed),
1477
+ "attempts": int(g.attempts),
1478
+ "frame": self.frame,
1479
+ }
1480
+
1481
+ @classmethod
1482
+ def _from_geometry(cls, domain, geometry, **kwargs):
1483
+ rims = geometry["rims"]
1484
+ growth = PlateGrowth(
1485
+ nucleation=np.asarray(geometry["nucleation"], dtype=float).reshape(-1, 3),
1486
+ normal=np.asarray(geometry["normal"], dtype=float).reshape(-1, 3),
1487
+ thickness=np.asarray(geometry["thickness"], dtype=float).reshape(-1),
1488
+ rim_offsets=np.asarray(rims["offsets"], dtype=np.int64),
1489
+ rim_vertices=np.asarray(rims["vertices"], dtype=float).reshape(-1, 3),
1490
+ rim_faces=np.asarray(rims["faces"], dtype=np.int64).reshape(-1),
1491
+ bodies=Polyhedra.from_dict(geometry["bodies"]),
1492
+ cells=Polyhedra.from_dict(geometry["cells"]),
1493
+ jammed=bool(geometry.get("jammed", False)),
1494
+ attempts=int(geometry.get("attempts", 0)),
1495
+ )
1496
+ return cls(domain, growth, geometry.get("frame", 0.0), **kwargs)
1497
+
1498
+
1499
+ @register_kind
1500
+ class ScaleRichBeams(_Network3D):
1501
+ """A scale-rich network of beams: cylinders with round ends (phase 1) grown until they
1502
+ meet (:func:`grow_beams`), in one open void (phase 0); or, with a ``frame``, within a
1503
+ frame of that thickness (phase 1 too), on which they end."""
1504
+
1505
+ kind = "scale_rich_beams"
1506
+
1507
+ def __init__(self, domain: Domain, growth, frame: float = 0.0, **kwargs) -> None:
1508
+ super().__init__(domain, growth, frame, **kwargs)
1509
+ self._union: float | None = None
1510
+
1511
+ @property
1512
+ def lengths(self) -> np.ndarray:
1513
+ """The lengths of the axes of the beams."""
1514
+ return self.growth.lengths
1515
+
1516
+ @property
1517
+ def directions(self) -> np.ndarray:
1518
+ return self.growth.direction
1519
+
1520
+ @property
1521
+ def volume_fraction(self) -> float:
1522
+ """The fraction of the box in the beams (their union, round ends and junctions
1523
+ included, cut by the box) and the frame, by quasi-Monte Carlo on
1524
+ :func:`union_points` (within about ``1.5 10^-4``)."""
1525
+ if self._union is None:
1526
+ pts = self.domain.lower + union_points() * self.domain.lengths
1527
+ self._union = float(np.count_nonzero(self.field(pts) < 0) / len(pts))
1528
+ return self._union
1529
+
1530
+ @property
1531
+ def cylinder_fraction(self) -> float:
1532
+ """The fraction of the box in the cylinders on the axes of the beams and the
1533
+ frame, ``(sum pi r^2 l + V_frame) / V`` (the beams of the mean field of
1534
+ :func:`beam_density_estimate`): within a few percent of :attr:`volume_fraction`,
1535
+ the round ends and the overlaps at the junctions counted out, the parts of fat beams
1536
+ beyond the box counted in."""
1537
+ return float((self.growth.volumes().sum() + self._frame_volume()) / self.domain.volume)
1538
+
1539
+ def segments(self):
1540
+ """The beams as :class:`morphogen.primitives.Segments` (round caps)."""
1541
+ from morphogen.primitives import Segments
1542
+
1543
+ g = self.growth
1544
+ return Segments(g.ends[:, 0], g.ends[:, 1], g.radii, round_caps=True)
1545
+
1546
+ def statistics(self, min_tail: int = 50) -> dict:
1547
+ """The power-law tails of the thicknesses, lengths and degrees of the beams (the
1548
+ exponents of the lengths and degrees depend on ``alpha`` and on the box: see
1549
+ docs/theory.md, §93.1). No thicknesses with a decay of 0 (one thickness)."""
1550
+ from morphogen.analysis.power_laws import power_law_tail
1551
+
1552
+ tail = min(int(min_tail), max(2, self.n_ligaments // 2))
1553
+ out = {}
1554
+ if np.ptp(self.thicknesses) > 0: # a decay of 0: one thickness, no tail
1555
+ out["thickness"] = power_law_tail(self.thicknesses, min_tail=tail)
1556
+ out["length"] = power_law_tail(self.lengths, min_tail=tail)
1557
+ out["degree"] = power_law_tail(self.degrees(), discrete=True, min_tail=tail)
1558
+ return out
1559
+
1560
+ def _boxes(self) -> np.ndarray:
1561
+ e = self.growth.ends
1562
+ r = self.growth.radii[:, None]
1563
+ return np.hstack([np.minimum(e[:, 0], e[:, 1]) - r, np.maximum(e[:, 0], e[:, 1]) + r])
1564
+
1565
+ def _elements_field(self, pts, index) -> np.ndarray:
1566
+ g = self.growth
1567
+ return _beams_field(pts, index.reach, index.boxes, np.ascontiguousarray(g.ends),
1568
+ np.ascontiguousarray(g.radii), index.b_off, index.b_items, index.lo,
1569
+ index.h, index.g) # fmt: skip
1570
+
1571
+ def summary(self) -> dict:
1572
+ """The counts, thicknesses, lengths, degrees and anisotropy of the network."""
1573
+ g = self.growth
1574
+ out = {"ligaments": g.n, "jammed": int(g.jammed), "volume_fraction": self.volume_fraction}
1575
+ if g.n:
1576
+ deg = g.degrees()
1577
+ out.update(
1578
+ {
1579
+ "initial_thickness": float(g.thickness[0]),
1580
+ "final_thickness": float(g.thickness[-1]),
1581
+ "mean_length": float(g.lengths.mean()),
1582
+ "mean_degree": float(deg.mean()),
1583
+ "max_degree": int(deg.max()),
1584
+ "geometric_anisotropy": self.geometric_anisotropy,
1585
+ }
1586
+ )
1587
+ return out
1588
+
1589
+ def _geometry(self) -> dict:
1590
+ g = self.growth
1591
+ return {
1592
+ "nucleation": g.nucleation.tolist(),
1593
+ "direction": g.direction.tolist(),
1594
+ "thickness": g.thickness.tolist(),
1595
+ "ends": g.ends.tolist(),
1596
+ "neighbours": g.neighbours.tolist(),
1597
+ "contacts": {"offsets": g.contact_offsets.tolist(), "items": g.contacts.tolist()},
1598
+ "jammed": bool(g.jammed),
1599
+ "attempts": int(g.attempts),
1600
+ "frame": self.frame,
1601
+ }
1602
+
1603
+ @classmethod
1604
+ def _from_geometry(cls, domain, geometry, **kwargs):
1605
+ growth = BeamGrowth(
1606
+ nucleation=np.asarray(geometry["nucleation"], dtype=float).reshape(-1, 3),
1607
+ direction=np.asarray(geometry["direction"], dtype=float).reshape(-1, 3),
1608
+ thickness=np.asarray(geometry["thickness"], dtype=float).reshape(-1),
1609
+ ends=np.asarray(geometry["ends"], dtype=float).reshape(-1, 2, 3),
1610
+ neighbours=np.asarray(geometry["neighbours"], dtype=np.int64).reshape(-1, 2),
1611
+ contact_offsets=np.asarray(geometry["contacts"]["offsets"], dtype=np.int64),
1612
+ contacts=np.asarray(geometry["contacts"]["items"], dtype=np.int64).reshape(-1),
1613
+ jammed=bool(geometry.get("jammed", False)),
1614
+ attempts=int(geometry.get("attempts", 0)),
1615
+ )
1616
+ return cls(domain, growth, geometry.get("frame", 0.0), **kwargs)