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,686 @@
1
+ """Lattice growth processes: nucleation and growth, grain growth and aggregation.
2
+
3
+ Nucleation and growth
4
+ Nuclei appear at random cells, all at once (site saturation) or at a constant rate
5
+ in the untransformed volume (continuous nucleation), and grow at a constant velocity
6
+ until they impinge on each other (Johnson-Mehl-Avrami-Kolmogorov kinetics). The
7
+ automaton is event-driven: each cell is transformed by the first grain reaching it,
8
+ and grains are propagated from cell to neighbouring cell (26 neighbours) with the
9
+ position of their nucleus, so that arrival times are exact distances in the growth
10
+ metric (spheres, or cubes and octahedra oriented by the crystal orientation of each
11
+ grain), without the anisotropy of lattice distances. Grains are star-shaped with
12
+ respect to their nucleus, which makes the propagation exact up to the resolution of
13
+ the lattice. Nuclei falling in transformed cells are discarded (phantom nuclei).
14
+ Grain growth
15
+ Monte Carlo Potts model (Anderson, Srolovitz and Grest 1984): a cell takes the label
16
+ of a random neighbour if this does not increase the number of unlike neighbours (or
17
+ with the Boltzmann probability at temperature T > 0). Grain boundaries move with
18
+ their mean curvature: the mean grain size grows as the square root of time
19
+ (parabolic growth). Cells are swept by independent sublattices in parallel, with
20
+ counter-based random numbers (results do not depend on the number of threads).
21
+ Aggregation
22
+ Particles join a growing aggregate: clusters grown from seeds, or deposits on a
23
+ substrate (the face z = 0; y = 0 in 2D). Diffusion-limited aggregation (random
24
+ walkers, Witten and Sander 1981) gives fractal clusters of dimension about 2.5 in 3D
25
+ and 1.71 in 2D; Eden growth (random perimeter cells) compact clusters with rough
26
+ surfaces; ballistic aggregation (straight trajectories) dense porous aggregates.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import heapq
32
+ import math
33
+
34
+ import numpy as np
35
+ from numba import njit, prange
36
+
37
+ #: Growth metrics of nucleation and growth.
38
+ GROWTH_SHAPES = ("sphere", "cube", "octahedron")
39
+ #: Aggregation processes and geometries.
40
+ AGGREGATION_PROCESSES = ("dla", "eden", "ballistic")
41
+ AGGREGATION_GEOMETRIES = ("cluster", "deposit")
42
+
43
+
44
+ def shape_volume_coefficient(shape: str, dims: int = 3) -> float:
45
+ """Volume (area in 2D) of the growth shape of radius 1: ``V(r) = c r^d``."""
46
+ if dims == 3:
47
+ return {"sphere": 4.0 * math.pi / 3.0, "cube": 8.0, "octahedron": 4.0 / 3.0}[shape]
48
+ return {"sphere": math.pi, "cube": 4.0, "octahedron": 2.0}[shape]
49
+
50
+
51
+ # -- nucleation and growth -----------------------------------------------------------------
52
+
53
+
54
+ @njit(cache=True)
55
+ def _metric(d0, d1, d2, rot, l, use_rot, norm):
56
+ if use_rot:
57
+ e0 = rot[l, 0, 0] * d0 + rot[l, 0, 1] * d1 + rot[l, 0, 2] * d2
58
+ e1 = rot[l, 1, 0] * d0 + rot[l, 1, 1] * d1 + rot[l, 1, 2] * d2
59
+ e2 = rot[l, 2, 0] * d0 + rot[l, 2, 1] * d1 + rot[l, 2, 2] * d2
60
+ else:
61
+ e0, e1, e2 = d0, d1, d2
62
+ if norm == 0:
63
+ return math.sqrt(e0 * e0 + e1 * e1 + e2 * e2)
64
+ if norm == 1:
65
+ return max(abs(e0), abs(e1), abs(e2))
66
+ return abs(e0) + abs(e1) + abs(e2)
67
+
68
+
69
+ @njit(cache=True)
70
+ def _grow(nx, ny, nz, h, cells, times, rot, use_rot, norm, rate, periodic, dims, labels, arrival):
71
+ n_offs = 26 if dims == 3 else 8
72
+ offs = np.empty((n_offs, 3), dtype=np.int64)
73
+ m = 0
74
+ for a in range(-1, 2):
75
+ for b in range(-1, 2):
76
+ for c in range(-1, 2):
77
+ if (a == 0 and b == 0 and c == 0) or (dims == 2 and c != 0):
78
+ continue
79
+ offs[m, 0] = a
80
+ offs[m, 1] = b
81
+ offs[m, 2] = c
82
+ m += 1
83
+ lx, ly, lz = nx * h[0], ny * h[1], nz * h[2]
84
+ n_cells = nx * ny * nz
85
+ best = np.full(n_cells, np.inf)
86
+ done = np.zeros(n_cells, dtype=np.uint8)
87
+ real = np.zeros(len(times), dtype=np.uint8)
88
+ heap = [(0.0, np.int64(0), np.int64(0))]
89
+ heap.pop()
90
+ for i in range(len(times)):
91
+ c = (cells[i, 0] * ny + cells[i, 1]) * nz + cells[i, 2]
92
+ heapq.heappush(heap, (times[i], c, np.int64(-i - 1)))
93
+ while len(heap) > 0:
94
+ t, c, o = heapq.heappop(heap)
95
+ if done[c]:
96
+ continue # reached earlier (a nucleus there is a phantom)
97
+ g = o
98
+ if o < 0:
99
+ g = -o - 1
100
+ real[g] = 1
101
+ done[c] = 1
102
+ labels[c] = g
103
+ arrival[c] = t
104
+ i = c // (ny * nz)
105
+ j = (c // nz) % ny
106
+ k = c % nz
107
+ for m in range(n_offs):
108
+ ii = i + offs[m, 0]
109
+ jj = j + offs[m, 1]
110
+ kk = k + offs[m, 2]
111
+ if periodic:
112
+ ii %= nx
113
+ jj %= ny
114
+ kk %= nz
115
+ elif ii < 0 or ii >= nx or jj < 0 or jj >= ny or kk < 0 or kk >= nz:
116
+ continue
117
+ cn = (ii * ny + jj) * nz + kk
118
+ if done[cn]:
119
+ continue
120
+ d0 = (ii - cells[g, 0]) * h[0]
121
+ d1 = (jj - cells[g, 1]) * h[1]
122
+ d2 = (kk - cells[g, 2]) * h[2]
123
+ if periodic:
124
+ d0 -= lx * np.rint(d0 / lx)
125
+ d1 -= ly * np.rint(d1 / ly)
126
+ d2 -= lz * np.rint(d2 / lz)
127
+ tn = times[g] + _metric(d0, d1, d2, rot, g, use_rot, norm) / rate
128
+ if tn < best[cn]:
129
+ best[cn] = tn
130
+ heapq.heappush(heap, (tn, cn, g))
131
+ return real
132
+
133
+
134
+ def grow_grains(
135
+ shape,
136
+ cell_size,
137
+ nuclei,
138
+ times,
139
+ *,
140
+ growth_rate: float = 1.0,
141
+ growth_shape: str = "sphere",
142
+ rotations=None,
143
+ periodic: bool = True,
144
+ dims: int = 3,
145
+ ):
146
+ """Transformation of a lattice by grains growing from nuclei.
147
+
148
+ Parameters
149
+ ----------
150
+ shape, cell_size
151
+ Lattice ``(nx, ny, nz)`` (``nz = 1`` in 2D) and edge(s) of its cells.
152
+ nuclei, times
153
+ Cell indices ``(n, 3)`` of the nuclei and their nucleation times.
154
+ growth_rate
155
+ Radius gained by a grain per unit time (half-edge of cubes, half-diagonal of
156
+ octahedra).
157
+ growth_shape
158
+ ``sphere`` (isotropic growth), ``cube`` or ``octahedron`` (faceted growth).
159
+ rotations
160
+ Optional rotation matrices ``(n, 3, 3)`` (crystal = g @ sample) orienting the
161
+ faceted shapes.
162
+
163
+ Returns
164
+ -------
165
+ tuple
166
+ ``(labels, arrival, real)``: the index of the nucleus of the grain of each cell
167
+ (int32), the time at which each cell is transformed (inf if never), and whether
168
+ each nucleus formed a grain (False for phantom nuclei, which fell in transformed
169
+ cells).
170
+ """
171
+ if growth_shape not in GROWTH_SHAPES:
172
+ raise ValueError(f"growth_shape: one of {GROWTH_SHAPES}, got {growth_shape!r}")
173
+ nx, ny, nz = (int(n) for n in shape)
174
+ h = np.broadcast_to(np.asarray(cell_size, dtype=float), (3,)).copy()
175
+ cells = np.ascontiguousarray(nuclei, dtype=np.int64).reshape(-1, 3)
176
+ t = np.ascontiguousarray(times, dtype=float).reshape(-1)
177
+ if len(cells) != len(t):
178
+ raise ValueError("nuclei and times: same length")
179
+ if not growth_rate > 0:
180
+ raise ValueError("growth_rate: must be positive")
181
+ use_rot = rotations is not None
182
+ rot = (
183
+ np.ascontiguousarray(rotations, dtype=float).reshape(-1, 3, 3)
184
+ if use_rot
185
+ else np.zeros((1, 3, 3))
186
+ )
187
+ labels = np.full(nx * ny * nz, -1, dtype=np.int32)
188
+ arrival = np.full(nx * ny * nz, np.inf)
189
+ norm = GROWTH_SHAPES.index(growth_shape)
190
+ real = _grow(
191
+ nx,
192
+ ny,
193
+ nz,
194
+ h,
195
+ cells,
196
+ t,
197
+ rot,
198
+ use_rot,
199
+ norm,
200
+ float(growth_rate),
201
+ bool(periodic),
202
+ int(dims),
203
+ labels,
204
+ arrival,
205
+ )
206
+ return labels.reshape(nx, ny, nz), arrival.reshape(nx, ny, nz), real.astype(bool)
207
+
208
+
209
+ # -- grain growth --------------------------------------------------------------------------
210
+
211
+
212
+ @njit(cache=True)
213
+ def _mix(x):
214
+ """splitmix64 finalizer (a bijective hash of 64-bit integers)."""
215
+ x = (x ^ (x >> np.uint64(30))) * np.uint64(0xBF58476D1CE4E5B9)
216
+ x = (x ^ (x >> np.uint64(27))) * np.uint64(0x94D049BB133111EB)
217
+ return x ^ (x >> np.uint64(31))
218
+
219
+
220
+ @njit(cache=True)
221
+ def _uniform(seed, a, b):
222
+ """Uniform number in [0, 1) depending only on (seed, a, b)."""
223
+ x = _mix(np.uint64(seed) + np.uint64(0x9E3779B97F4A7C15) * np.uint64(a + 1))
224
+ x = _mix(x ^ np.uint64(b))
225
+ return (x >> np.uint64(11)) * (1.0 / 9007199254740992.0)
226
+
227
+
228
+ @njit(cache=True)
229
+ def _colour(i, n, c):
230
+ """Colour of index i along an axis of n cells: parity, and 2 for the last cell of
231
+ odd periodic axes, so that neighbours never share a colour."""
232
+ if n % 2 == 1 and i == n - 1:
233
+ return 2 == c
234
+ return i % 2 == c
235
+
236
+
237
+ @njit(parallel=True, cache=True)
238
+ def _potts_sweep(labels, offs, temperature, seed, step, colour):
239
+ nx, ny, nz = labels.shape
240
+ n_offs = offs.shape[0]
241
+ cx = colour // 9
242
+ cy = (colour // 3) % 3
243
+ cz = colour % 3
244
+ for i in prange(nx):
245
+ if not _colour(i, nx, cx):
246
+ continue
247
+ for j in range(ny):
248
+ if not _colour(j, ny, cy):
249
+ continue
250
+ for k in range(nz):
251
+ if not _colour(k, nz, cz):
252
+ continue
253
+ cell = (i * ny + j) * nz + k
254
+ r = _uniform(seed, 2 * step, cell)
255
+ m = int(r * n_offs)
256
+ q = labels[(i + offs[m, 0]) % nx, (j + offs[m, 1]) % ny, (k + offs[m, 2]) % nz]
257
+ s = labels[i, j, k]
258
+ if q == s:
259
+ continue
260
+ de = 0
261
+ for o in range(n_offs):
262
+ v = labels[(i + offs[o, 0]) % nx, (j + offs[o, 1]) % ny, (k + offs[o, 2]) % nz]
263
+ de += (v != q) - (v != s)
264
+ if de <= 0 or (
265
+ temperature > 0
266
+ and _uniform(seed, 2 * step + 1, cell) < math.exp(-de / temperature)
267
+ ):
268
+ labels[i, j, k] = q
269
+
270
+
271
+ def potts_coarsening(
272
+ labels, steps: int, *, temperature: float = 0.5, seed: int = 0, dims: int = 3, callback=None
273
+ ) -> np.ndarray:
274
+ """Normal grain growth of a periodic label image by ``steps`` Monte Carlo sweeps of
275
+ the Potts model (Moore neighbourhood: 26 neighbours in 3D, 8 in 2D).
276
+
277
+ ``temperature`` is in units of the energy of a pair of unlike neighbours; small
278
+ positive values (about 0.5) avoid the pinning of boundaries by the lattice.
279
+ ``callback(step, labels)`` is called after every sweep.
280
+ """
281
+ from morphogen.automata.lattice import offsets
282
+
283
+ lab = np.ascontiguousarray(labels, dtype=np.int32).copy()
284
+ if lab.ndim != 3:
285
+ raise ValueError("labels: a 3D array (nx, ny, 1) in 2D")
286
+ if np.any(lab < 0):
287
+ raise ValueError("grain growth needs a fully labelled lattice (no label -1)")
288
+ if steps < 0 or temperature < 0:
289
+ raise ValueError("steps and temperature: non-negative")
290
+ offs = offsets("moore", 1, dims=dims)
291
+ for step in range(int(steps)):
292
+ for colour in range(27):
293
+ _potts_sweep(lab, offs, float(temperature), int(seed), step * 27 + colour, colour)
294
+ if callback is not None:
295
+ callback(step + 1, lab)
296
+ return lab
297
+
298
+
299
+ # -- aggregation ---------------------------------------------------------------------------
300
+
301
+ _DLA, _EDEN, _BALLISTIC = 0, 1, 2
302
+
303
+
304
+ @njit(cache=True)
305
+ def _unit_vector(rng, dims):
306
+ while True:
307
+ v0 = 2.0 * rng.random() - 1.0
308
+ v1 = 2.0 * rng.random() - 1.0
309
+ v2 = 2.0 * rng.random() - 1.0 if dims == 3 else 0.0
310
+ r2 = v0 * v0 + v1 * v1 + v2 * v2
311
+ if 1e-6 < r2 <= 1.0:
312
+ r = math.sqrt(r2)
313
+ return v0 / r, v1 / r, v2 / r
314
+
315
+
316
+ @njit(cache=True)
317
+ def _wrap(p, n, deposit, g):
318
+ for a in range(3):
319
+ if deposit and a == g:
320
+ continue
321
+ p[a] %= n[a]
322
+
323
+
324
+ @njit(cache=True)
325
+ def _inside(p, n):
326
+ return 0 <= p[0] < n[0] and 0 <= p[1] < n[1] and 0 <= p[2] < n[2]
327
+
328
+
329
+ @njit(cache=True)
330
+ def _centre_distance(p, centre, n, dims):
331
+ s = 0.0
332
+ for a in range(dims):
333
+ d = p[a] - centre[a]
334
+ d -= n[a] * np.rint(d / n[a])
335
+ s += d * d
336
+ return math.sqrt(s)
337
+
338
+
339
+ @njit(cache=True)
340
+ def _occupy(p, occ, owner, order, contact, dirs, n, deposit, g, index, n_trees):
341
+ """Add the cell p to the aggregate; returns the updated number of trees."""
342
+ label = -1
343
+ for d in range(dirs.shape[0]):
344
+ q0 = p[0] + dirs[d, 0]
345
+ q1 = p[1] + dirs[d, 1]
346
+ q2 = p[2] + dirs[d, 2]
347
+ if deposit and ((g == 2 and (q2 < 0 or q2 >= n[2])) or (g == 1 and (q1 < 0 or q1 >= n[1]))):
348
+ continue
349
+ q0 %= n[0]
350
+ q1 %= n[1]
351
+ q2 %= n[2]
352
+ if occ[q0, q1, q2] and label < 0:
353
+ label = owner[q0, q1, q2]
354
+ contact[q0, q1, q2] += 1
355
+ if label < 0:
356
+ label = n_trees
357
+ n_trees += 1
358
+ occ[p[0], p[1], p[2]] = 1
359
+ owner[p[0], p[1], p[2]] = label
360
+ order[p[0], p[1], p[2]] = index
361
+ return n_trees
362
+
363
+
364
+ @njit(cache=True)
365
+ def _aggregate(occ, owner, order, process, deposit, n_target, sticking, dims, single, rng):
366
+ nx, ny, nz = occ.shape
367
+ n = np.array([nx, ny, nz], dtype=np.int64)
368
+ g = 2 if dims == 3 else 1 # growth axis of deposits
369
+ nd = 2 * dims
370
+ dirs = np.zeros((nd, 3), dtype=np.int64)
371
+ for a in range(dims):
372
+ dirs[2 * a, a] = 1
373
+ dirs[2 * a + 1, a] = -1
374
+ contact = np.zeros(occ.shape, dtype=np.int16)
375
+ n_trees = 0
376
+ centre = np.zeros(3)
377
+ for i in range(nx):
378
+ for j in range(ny):
379
+ for k in range(nz):
380
+ if occ[i, j, k]:
381
+ n_trees = max(n_trees, owner[i, j, k] + 1)
382
+ centre[0] = i
383
+ centre[1] = j
384
+ centre[2] = k
385
+ for d in range(nd):
386
+ q = np.array([i + dirs[d, 0], j + dirs[d, 1], k + dirs[d, 2]])
387
+ if deposit and (q[g] < 0 or q[g] >= n[g]):
388
+ continue
389
+ _wrap(q, n, False, g)
390
+ contact[q[0], q[1], q[2]] += 1
391
+ top = -1
392
+ if deposit:
393
+ for i in range(nx):
394
+ for j in range(ny if g == 2 else 1):
395
+ if g == 2:
396
+ contact[i, j, 0] += 1
397
+ else:
398
+ contact[i, 0, 0] += 1
399
+ r_max = 0.0
400
+ lateral = max(n[0], n[1]) if g == 2 else n[0]
401
+ r_cap = 0.5 * min(n[0], n[1], n[2] if dims == 3 else n[1]) - 2.0
402
+ added = 0
403
+ index = 1
404
+ p = np.zeros(3, dtype=np.int64)
405
+ q = np.zeros(3, dtype=np.int64)
406
+ # Eden: perimeter list
407
+ perim = np.empty(0, dtype=np.int64)
408
+ in_perim = np.zeros(0, dtype=np.uint8)
409
+ n_perim = 0
410
+ if process == _EDEN:
411
+ perim = np.empty(nx * ny * nz, dtype=np.int64)
412
+ in_perim = np.zeros(nx * ny * nz, dtype=np.uint8)
413
+ for i in range(nx):
414
+ for j in range(ny):
415
+ for k in range(nz):
416
+ if not occ[i, j, k] and contact[i, j, k] > 0:
417
+ c = (i * ny + j) * nz + k
418
+ perim[n_perim] = c
419
+ in_perim[c] = 1
420
+ n_perim += 1
421
+ while True:
422
+ if deposit and top >= n[g] - 1:
423
+ break
424
+ if n_target >= 0 and added >= n_target:
425
+ break
426
+ if process == _EDEN:
427
+ if n_perim == 0:
428
+ break
429
+ r = rng.integers(0, n_perim)
430
+ c = perim[r]
431
+ n_perim -= 1
432
+ perim[r] = perim[n_perim]
433
+ in_perim[c] = 0
434
+ p[0] = c // (ny * nz)
435
+ p[1] = (c // nz) % ny
436
+ p[2] = c % nz
437
+ n_trees = _occupy(p, occ, owner, order, contact, dirs, n, deposit, g, index, n_trees)
438
+ index += 1
439
+ added += 1
440
+ top = max(top, p[g])
441
+ for d in range(nd):
442
+ for a in range(3):
443
+ q[a] = p[a] + dirs[d, a]
444
+ if deposit and (q[g] < 0 or q[g] >= n[g]):
445
+ continue
446
+ _wrap(q, n, False, g)
447
+ cq = (q[0] * ny + q[1]) * nz + q[2]
448
+ if not occ[q[0], q[1], q[2]] and not in_perim[cq]:
449
+ perim[n_perim] = cq
450
+ in_perim[cq] = 1
451
+ n_perim += 1
452
+ continue
453
+ # launch a particle
454
+ launched = False
455
+ attempts = 0
456
+ sphere = single and not deposit and r_max + 3.0 < r_cap
457
+ u0, u1, u2 = 0.0, 0.0, 0.0
458
+ x0, x1, x2 = 0.0, 0.0, 0.0
459
+ while not launched:
460
+ attempts += 1
461
+ if deposit:
462
+ for a in range(3):
463
+ p[a] = rng.integers(0, n[a]) if a != g and a < dims else 0
464
+ p[g] = top + 2
465
+ if process == _BALLISTIC:
466
+ u0, u1, u2 = 0.0, 0.0, 0.0
467
+ if g == 2:
468
+ u2 = -1.0
469
+ else:
470
+ u1 = -1.0
471
+ elif sphere:
472
+ rl = r_max + 3.0
473
+ v0, v1, v2 = _unit_vector(rng, dims)
474
+ if process == _BALLISTIC:
475
+ # straight line of direction -v and random impact parameter
476
+ w0, w1, w2 = _unit_vector(rng, dims)
477
+ dot = w0 * v0 + w1 * v1 + w2 * v2
478
+ w0 -= dot * v0
479
+ w1 -= dot * v1
480
+ w2 -= dot * v2
481
+ wn = math.sqrt(w0 * w0 + w1 * w1 + w2 * w2)
482
+ if wn < 1e-9:
483
+ continue
484
+ b = rl * (math.sqrt(rng.random()) if dims == 3 else rng.random())
485
+ x0 = centre[0] + (rl + 1.0) * v0 + b * w0 / wn
486
+ x1 = centre[1] + (rl + 1.0) * v1 + b * w1 / wn
487
+ x2 = centre[2] + (rl + 1.0) * v2 + b * w2 / wn
488
+ u0, u1, u2 = -v0, -v1, -v2
489
+ p[0] = math.floor(x0 + 0.5)
490
+ p[1] = math.floor(x1 + 0.5)
491
+ p[2] = math.floor(x2 + 0.5)
492
+ else:
493
+ p[0] = int(np.rint(centre[0] + rl * v0))
494
+ p[1] = int(np.rint(centre[1] + rl * v1))
495
+ p[2] = int(np.rint(centre[2] + rl * v2))
496
+ _wrap(p, n, False, g)
497
+ else:
498
+ p[0] = rng.integers(0, nx)
499
+ p[1] = rng.integers(0, ny)
500
+ p[2] = rng.integers(0, nz)
501
+ if process == _BALLISTIC:
502
+ u0, u1, u2 = _unit_vector(rng, dims)
503
+ if _inside(p, n):
504
+ if occ[p[0], p[1], p[2]]:
505
+ continue
506
+ if contact[p[0], p[1], p[2]] > 0 and attempts < 1000:
507
+ continue
508
+ launched = True
509
+ if process == _BALLISTIC and not sphere:
510
+ x0, x1, x2 = float(p[0]), float(p[1]), float(p[2])
511
+ stuck = False
512
+ steps = 0
513
+ if process == _DLA:
514
+ z_kill = top + 2 + max(4, lateral // 2)
515
+ while not stuck:
516
+ if _inside(p, n) and contact[p[0], p[1], p[2]] > 0:
517
+ if sticking >= 1.0 or rng.random() < sticking:
518
+ stuck = True
519
+ break
520
+ if sphere:
521
+ dist = _centre_distance(p, centre, n, dims)
522
+ if dist > min(2.0 * (r_max + 3.0) + 10.0, r_cap + 1.0):
523
+ break # killed: launch again
524
+ if dist > r_max + 6.0:
525
+ rho = dist - r_max - 3.0
526
+ v0, v1, v2 = _unit_vector(rng, dims)
527
+ p[0] = int(np.rint(p[0] + rho * v0))
528
+ p[1] = int(np.rint(p[1] + rho * v1))
529
+ p[2] = int(np.rint(p[2] + rho * v2))
530
+ _wrap(p, n, False, g)
531
+ continue
532
+ d = rng.integers(0, nd)
533
+ for a in range(3):
534
+ q[a] = p[a] + dirs[d, a]
535
+ if deposit:
536
+ if q[g] < 0:
537
+ continue
538
+ if q[g] > z_kill:
539
+ break # wandered away: launch again
540
+ _wrap(q, n, deposit, g)
541
+ if _inside(q, n) and occ[q[0], q[1], q[2]]:
542
+ continue
543
+ for a in range(3):
544
+ p[a] = q[a]
545
+ else: # ballistic: straight flight (voxel traversal)
546
+ max_steps = 4 * (nx + ny + nz)
547
+ step0 = 1 if u0 > 0 else -1
548
+ step1 = 1 if u1 > 0 else -1
549
+ step2 = 1 if u2 > 0 else -1
550
+ c0, c1, c2 = p[0], p[1], p[2]
551
+ fx0 = x0 - (math.floor(x0 + 0.5) - 0.5) # position inside the cell, in [0, 1)
552
+ fx1 = x1 - (math.floor(x1 + 0.5) - 0.5)
553
+ fx2 = x2 - (math.floor(x2 + 0.5) - 0.5)
554
+ inf = 1e300
555
+ t0 = ((1.0 - fx0) / u0 if u0 > 0 else fx0 / -u0) if u0 != 0 else inf
556
+ t1 = ((1.0 - fx1) / u1 if u1 > 0 else fx1 / -u1) if u1 != 0 else inf
557
+ t2 = ((1.0 - fx2) / u2 if u2 > 0 else fx2 / -u2) if u2 != 0 else inf
558
+ dt0 = 1.0 / abs(u0) if u0 != 0 else inf
559
+ dt1 = 1.0 / abs(u1) if u1 != 0 else inf
560
+ dt2 = 1.0 / abs(u2) if u2 != 0 else inf
561
+ p[0], p[1], p[2] = c0, c1, c2
562
+ while steps < max_steps:
563
+ steps += 1
564
+ if _inside(p, n) and contact[p[0], p[1], p[2]] > 0:
565
+ if sticking >= 1.0 or rng.random() < sticking:
566
+ stuck = True
567
+ break
568
+ for a in range(3):
569
+ q[a] = p[a]
570
+ if t0 <= t1 and t0 <= t2:
571
+ q[0] += step0
572
+ t0 += dt0
573
+ elif t1 <= t2:
574
+ q[1] += step1
575
+ t1 += dt1
576
+ else:
577
+ q[2] += step2
578
+ t2 += dt2
579
+ if deposit and q[g] < 0:
580
+ stuck = _inside(p, n)
581
+ break
582
+ _wrap(q, n, deposit, g)
583
+ if _inside(q, n) and occ[q[0], q[1], q[2]]:
584
+ stuck = _inside(p, n) # blocked: stays where it is
585
+ break
586
+ for a in range(3):
587
+ p[a] = q[a]
588
+ if (
589
+ sphere
590
+ and _centre_distance(p, centre, n, dims) > r_max + 6.0
591
+ and steps > 4 * (r_max + 4.0)
592
+ ):
593
+ break # missed the cluster
594
+ if stuck and _inside(p, n) and not occ[p[0], p[1], p[2]]:
595
+ n_trees = _occupy(p, occ, owner, order, contact, dirs, n, deposit, g, index, n_trees)
596
+ index += 1
597
+ added += 1
598
+ top = max(top, p[g])
599
+ if single:
600
+ r_max = max(r_max, _centre_distance(p, centre, n, dims))
601
+ return added
602
+
603
+
604
+ def aggregate(
605
+ shape,
606
+ rng: np.random.Generator,
607
+ *,
608
+ process: str = "dla",
609
+ geometry: str = "cluster",
610
+ n_seeds: int = 1,
611
+ n_particles: int | None = None,
612
+ sticking: float = 1.0,
613
+ dims: int = 3,
614
+ ):
615
+ """Grow an aggregate on a lattice.
616
+
617
+ Parameters
618
+ ----------
619
+ shape
620
+ Lattice ``(nx, ny, nz)`` (``nz = 1`` in 2D). Clusters live on a periodic
621
+ lattice; deposits on a lattice periodic along the substrate (the face z = 0, or
622
+ y = 0 in 2D).
623
+ process
624
+ ``dla`` (random walkers), ``eden`` (random perimeter cells) or ``ballistic``
625
+ (straight trajectories: random directions for clusters, normal to the substrate
626
+ for deposits).
627
+ geometry
628
+ ``cluster``: growth from ``n_seeds`` random cells (one seed: the centre of the
629
+ lattice, walkers launched from a sphere around the cluster); ``deposit``:
630
+ growth from the substrate.
631
+ n_particles
632
+ Number of particles to add (default for deposits: until the deposit reaches the
633
+ opposite face).
634
+ sticking
635
+ Probability that a particle in contact with the aggregate sticks to it (dla,
636
+ ballistic): lower values give denser aggregates.
637
+
638
+ Returns
639
+ -------
640
+ occupied : numpy.ndarray
641
+ The aggregate (uint8).
642
+ owner : numpy.ndarray
643
+ The index of the seed or substrate tree of each particle (int32, -1 elsewhere).
644
+ order : numpy.ndarray
645
+ The order of arrival of each particle (int32: 0 for seeds, -1 elsewhere).
646
+ """
647
+ if process not in AGGREGATION_PROCESSES:
648
+ raise ValueError(f"process: one of {AGGREGATION_PROCESSES}, got {process!r}")
649
+ if geometry not in AGGREGATION_GEOMETRIES:
650
+ raise ValueError(f"geometry: one of {AGGREGATION_GEOMETRIES}, got {geometry!r}")
651
+ if not 0.0 < sticking <= 1.0:
652
+ raise ValueError("sticking: must lie in (0, 1]")
653
+ shape = tuple(int(n) for n in shape)
654
+ occ = np.zeros(shape, dtype=np.uint8)
655
+ owner = np.full(shape, -1, dtype=np.int32)
656
+ order = np.full(shape, -1, dtype=np.int32)
657
+ deposit = geometry == "deposit"
658
+ single = not deposit and n_seeds == 1
659
+ if not deposit:
660
+ if n_seeds < 1:
661
+ raise ValueError("n_seeds: at least 1")
662
+ if single:
663
+ cells = np.array([[n // 2 for n in shape]])
664
+ else:
665
+ flat = rng.choice(int(np.prod(shape)), size=int(n_seeds), replace=False)
666
+ cells = np.stack(np.unravel_index(flat, shape), axis=1)
667
+ for s, c in enumerate(cells):
668
+ occ[tuple(c)] = 1
669
+ owner[tuple(c)] = s
670
+ order[tuple(c)] = 0
671
+ if n_particles is None and not deposit:
672
+ raise ValueError("clusters need a number of particles")
673
+ target = -1 if n_particles is None else int(n_particles)
674
+ _aggregate(
675
+ occ,
676
+ owner,
677
+ order,
678
+ AGGREGATION_PROCESSES.index(process),
679
+ deposit,
680
+ target,
681
+ float(sticking),
682
+ int(dims),
683
+ single,
684
+ rng,
685
+ )
686
+ return occ, owner, order