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,749 @@
1
+ """Honeycombs and wood: prismatic cells with walls.
2
+
3
+ Prismatic cellular solids, the honeycombs of bees and the cells of wood, of cork or of
4
+ plant stems, are stiff and strong along their axis for their weight, and compliant
5
+ across it (Gibson and Ashby 1997). The model extrudes along an axis a tessellation of
6
+ the plane of germs whose cells are bounded by walls of thickness ``t``: the points of a
7
+ cell closer than ``t / 2`` to its sides (a wall between two cells is the sum of their
8
+ halves). The germs are
9
+
10
+ * ``hexagonal`` or ``square``: lattices whose cells are hexagons ``d`` wide between
11
+ opposite walls, or squares of side ``d``, displaced at random by up to ``disorder``
12
+ cell (a periodic box holds whole cells: the lattice stretches to fit it);
13
+ * ``voronoi``: points of a random sequential addition at least ``regularity`` jamming
14
+ distance apart (Poisson points for 0), one per area ``sqrt(3) d^2 / 2`` of a hexagon;
15
+ * ``wood``: the radial files of softwoods, rectangular cells rather than the cells of
16
+ germs. Along the tangential axis (the second of the plane), files ``d`` wide whose
17
+ radial walls are straight; along the radial axis (the first), cells whose size and
18
+ wall thickness vary through the growth rings of width ``ring_width``: from large
19
+ thin-walled earlywood cells (``d`` across) to small thick-walled latewood cells
20
+ (``latewood_size`` and ``latewood_wall`` times those of earlywood, in the last
21
+ ``latewood_fraction`` of the ring, after a transition of half that width); each file
22
+ is shifted by a random fraction of its cells, so that the tangential walls are
23
+ staggered. Loaded radially, the straight radial walls carry the load; tangentially,
24
+ the radial walls bend between the staggered tangential ones: with uniform cells the
25
+ radial modulus is several times the tangential one. Dense latewood bands, continuous
26
+ along the tangential axis, stiffen it.
27
+
28
+ Rays (``ray_fraction`` of the volume) are ribbons of parenchyma cells that run
29
+ radially across the rings between two files: ``ray_width`` cells across (1: the
30
+ uniseriate rays of softwoods, more for the multiseriate rays of hardwoods) and
31
+ ``ray_height`` high along the grain, at random places, never closer than one ray cell
32
+ along the grain to another ray between the same files or between neighbouring ones.
33
+ Their cells are boxes ``ray_cell_length`` long radially, ``ray_cell_width`` wide and
34
+ ``ray_cell_height`` high, with walls ``ray_wall`` thick. The tracheids pass beside
35
+ the rays: over the height of a ray, its walls replace the radial wall between the two
36
+ files, narrowed by half its width each. Rays make the structure three-dimensional.
37
+
38
+ Walls of uniform thickness ``t`` around hexagons or squares of width ``d`` take the
39
+ fraction ``1 - (1 - t / d)^2`` of the volume, exactly; around the cells of Poisson germs,
40
+ ``t L_A = 2 t sqrt(lambda)`` to first order in ``t`` (``L_A``: length of the sides per
41
+ unit area, ``lambda``: germs per unit area).
42
+ """
43
+
44
+ from __future__ import annotations
45
+
46
+ import math
47
+ import warnings
48
+ from dataclasses import dataclass
49
+ from typing import ClassVar
50
+
51
+ import numpy as np
52
+
53
+ from morphogen._utils import check_positive
54
+ from morphogen.domain import Domain, Grid
55
+ from morphogen.image import VoxelImage
56
+ from morphogen.models.base import Microstructure, Model, param, register, register_kind
57
+ from morphogen.models.planar import (
58
+ PlanarCells,
59
+ axis_centres,
60
+ hardcore_germs,
61
+ jamming_distance,
62
+ pixel_centres,
63
+ plane_axes,
64
+ )
65
+ from morphogen.seeding import SeedLike, make_rng
66
+
67
+ ARRANGEMENTS = ("hexagonal", "square", "voronoi", "wood")
68
+
69
+
70
+ class RadialFiles:
71
+ """Rectangular cells in files along the first axis of the plane: file ``j`` spans
72
+ ``[origin + j width, origin + (j + 1) width)`` across, its cells the intervals between
73
+ its consecutive ``bounds[j]`` along it (on a periodic box, one period: the last bound
74
+ is the first plus the length of the box)."""
75
+
76
+ def __init__(self, origin, width, bounds, lengths, periodic: bool, lower) -> None:
77
+ self.origin = float(origin)
78
+ self.width = float(width)
79
+ self.bounds = [np.asarray(b, dtype=float).reshape(-1) for b in bounds]
80
+ self.lengths = np.asarray(lengths, dtype=float).reshape(2)
81
+ self.lower = np.asarray(lower, dtype=float).reshape(2)
82
+ self.periodic = bool(periodic)
83
+ self.first = np.cumsum([0] + [len(b) - 1 for b in self.bounds]) # cell ids
84
+
85
+ @property
86
+ def n_files(self) -> int:
87
+ return len(self.bounds)
88
+
89
+ def _wrap(self, points) -> np.ndarray:
90
+ p = np.asarray(points, dtype=float).reshape(-1, 2)
91
+ if self.periodic:
92
+ p = self.lower + np.mod(p - self.lower, self.lengths)
93
+ return p
94
+
95
+ def parts(self, points):
96
+ """Cell and file ``j`` of each point, and its distances to the sides of the cell:
97
+ along the file, and across it to its radial walls below and above (on the
98
+ boundaries ``j`` and ``j + 1`` of the files)."""
99
+ p = self._wrap(points)
100
+ n = len(self.bounds)
101
+ y = p[:, 1] - self.origin
102
+ j = np.floor(y / self.width).astype(np.int64)
103
+ below = np.clip(y - j * self.width, 0.0, self.width)
104
+ j = np.mod(j, n) if self.periodic else np.clip(j, 0, n - 1)
105
+ labels = np.zeros(len(p), dtype=np.int64)
106
+ along = np.zeros(len(p))
107
+ for f in np.unique(j):
108
+ sel = j == f
109
+ b = self.bounds[f]
110
+ u = p[sel, 0]
111
+ if self.periodic: # into the period of the file
112
+ u = b[0] + np.mod(u - b[0], b[-1] - b[0])
113
+ k = np.clip(np.searchsorted(b, u, side="right") - 1, 0, len(b) - 2)
114
+ along[sel] = np.minimum(u - b[k], b[k + 1] - u)
115
+ labels[sel] = self.first[f] + k
116
+ return labels, j, along, below, self.width - below
117
+
118
+ def above(self, j: np.ndarray) -> np.ndarray:
119
+ """Boundary above the files ``j`` (the first one again on a periodic box)."""
120
+ return np.mod(j + 1, len(self.bounds)) if self.periodic else j + 1
121
+
122
+ def locate(self, points, reach: float = math.inf) -> tuple[np.ndarray, np.ndarray]:
123
+ """Cell of each point and its distance to the sides of the cell (exact)."""
124
+ labels, _, along, below, above = self.parts(points)
125
+ return labels, np.minimum(along, np.minimum(below, above))
126
+
127
+
128
+ class WoodRays:
129
+ """Rays between radial files: ray ``r`` lies on the boundary ``boundary[r]`` of the
130
+ files (the radial wall between the files ``boundary[r] - 1`` and ``boundary[r]``),
131
+ ``width`` wide across it, from ``z[r]`` to ``z[r] + height`` along the grain (the prism
132
+ axis, of ``period`` on a periodic box). Its cells are boxes ``cell_length`` long
133
+ radially (their boundaries at ``u[r]`` plus multiples of it), ``width / cells`` wide
134
+ and ``cell_height`` high, with walls ``thickness`` thick."""
135
+
136
+ def __init__(self, boundary, z, u, cells, width, height, cell_length, cell_height,
137
+ thickness, period=None) -> None: # fmt: skip
138
+ self.boundary = np.asarray(boundary, dtype=np.int64).reshape(-1)
139
+ self.z = np.asarray(z, dtype=float).reshape(-1)
140
+ self.u = np.asarray(u, dtype=float).reshape(-1)
141
+ self.cells = int(cells)
142
+ self.width = float(width)
143
+ self.height = float(height)
144
+ self.cell_length = float(cell_length)
145
+ self.cell_height = float(cell_height)
146
+ self.thickness = float(thickness)
147
+ self.period = None if period is None else float(period)
148
+
149
+ def __len__(self) -> int:
150
+ return len(self.z)
151
+
152
+ def locate(self, boundary: np.ndarray, z: np.ndarray):
153
+ """For points given by a boundary of the files and their coordinate along the
154
+ grain: the ray on the boundary at their height (-1: none), their height in it, and
155
+ their distance along the grain to the rays of the boundary (0 within the height of
156
+ one, inf: none)."""
157
+ ray = np.full(len(z), -1, dtype=np.int64)
158
+ rel = np.zeros(len(z))
159
+ gap = np.full(len(z), np.inf)
160
+ for r in range(len(self)):
161
+ on = boundary == self.boundary[r]
162
+ if self.period is None:
163
+ dz = z - self.z[r]
164
+ out = np.where(dz < 0.0, -dz, np.maximum(dz - self.height, 0.0))
165
+ else:
166
+ dz = np.mod(z - self.z[r], self.period)
167
+ out = np.where(
168
+ dz < self.height, 0.0, np.minimum(dz - self.height, self.period - dz)
169
+ )
170
+ inside = on & (dz >= 0.0) & (dz < self.height)
171
+ ray[inside] = r
172
+ rel[inside] = dz[inside]
173
+ gap[on] = np.minimum(gap[on], out[on])
174
+ return ray, rel, gap
175
+
176
+ def cell_distance(self, ray: np.ndarray, u: np.ndarray, rel: np.ndarray, across):
177
+ """Distance of points in rays to the walls of their cells: radially, along the
178
+ grain and across (``across``: the position of the points across their ray, from 0
179
+ to its width)."""
180
+ w = self.width / self.cells
181
+ dy = np.mod(across, w)
182
+ du = np.mod(u - self.u[ray], self.cell_length)
183
+ dz = np.mod(rel, self.cell_height)
184
+ return np.minimum.reduce(
185
+ [np.minimum(dy, w - dy), np.minimum(du, self.cell_length - du),
186
+ np.minimum(dz, self.cell_height - dz)]
187
+ ) # fmt: skip
188
+
189
+ def to_dict(self) -> dict:
190
+ return {
191
+ "boundary": self.boundary.tolist(),
192
+ "z": self.z.tolist(),
193
+ "u": self.u.tolist(),
194
+ "cells": self.cells,
195
+ "width": self.width,
196
+ "height": self.height,
197
+ "cell_length": self.cell_length,
198
+ "cell_height": self.cell_height,
199
+ "thickness": self.thickness,
200
+ }
201
+
202
+
203
+ @register_kind
204
+ class PrismaticCells(Microstructure):
205
+ """Prisms along ``axis`` over cells of the plane: the walls (phase 1) are the points
206
+ closer to the sides of their cell than half its wall thickness ``walls[i]``, the
207
+ lumens of the cells phase 0. The cells are those of germs (Voronoi), or rectangles
208
+ in radial ``files`` (wood; the germs are then their centres), between which rays may
209
+ run (``files["rays"]``, :class:`WoodRays`): the structure is then three-dimensional."""
210
+
211
+ kind = "prismatic_cells"
212
+
213
+ def __init__(self, domain, axis, germs, walls, files=None, **kwargs):
214
+ super().__init__(domain, **kwargs)
215
+ self.axis = int(axis)
216
+ self.germs = np.asarray(germs, dtype=float).reshape(-1, 2)
217
+ self.walls = np.broadcast_to(np.asarray(walls, dtype=float), len(self.germs)).copy()
218
+ self.files = files
219
+ b, c = plane_axes(self.axis)
220
+ d = self.domain
221
+ lengths, lower = d.lengths[[b, c]], d.lower[[b, c]]
222
+ if files is None:
223
+ self.cells = PlanarCells(self.germs, lengths, d.periodic, lower)
224
+ else:
225
+ self.cells = RadialFiles(
226
+ files["origin"], files["width"], files["bounds"], lengths, d.periodic, lower
227
+ )
228
+ if self.cells.first[-1] != len(self.germs):
229
+ raise ValueError("prismatic cells: one germ per cell of the files")
230
+ self.rays = None
231
+ if files is not None and files.get("rays"):
232
+ period = float(d.lengths[self.axis]) if d.periodic else None
233
+ self.rays = WoodRays(**files["rays"], period=period)
234
+
235
+ @property
236
+ def n_cells(self) -> int:
237
+ return len(self.germs)
238
+
239
+ @property
240
+ def n_rays(self) -> int:
241
+ return 0 if self.rays is None else len(self.rays)
242
+
243
+ @property
244
+ def ray_fraction(self) -> float:
245
+ """Fraction of the box in rays (their cells and walls), exact: rays run across the
246
+ box radially, so that it is their share of the tangential plane (across the files
247
+ and along the grain)."""
248
+ if self.rays is None:
249
+ return 0.0
250
+ r, f, d, ax = self.rays, self.cells, self.domain, self.axis
251
+ c = plane_axes(ax)[1]
252
+ if d.periodic:
253
+ return len(r) * r.width * r.height / float(d.lengths[c] * d.lengths[ax])
254
+
255
+ def overlap(lo, hi, a, b):
256
+ return np.clip(np.minimum(hi, b) - np.maximum(lo, a), 0.0, None)
257
+
258
+ centre = f.origin + r.boundary * f.width
259
+ across = overlap(centre - 0.5 * r.width, centre + 0.5 * r.width, d.lower[c], d.upper[c])
260
+ along = overlap(r.z, r.z + r.height, d.lower[ax], d.upper[ax])
261
+ return float(np.sum(across * along) / (d.lengths[c] * d.lengths[ax]))
262
+
263
+ def _beside_rays(self, along, below, above, half, u, lower, upper) -> np.ndarray:
264
+ """Signed field at points of the files: ``along`` their distance to the sides of
265
+ their cells along the file, ``below`` and ``above`` to its radial walls, ``half``
266
+ the half walls of their cells, ``u`` their radial coordinate, and ``lower`` and
267
+ ``upper`` the rays on these walls at their height (:meth:`WoodRays.locate`). Over
268
+ its height, a ray replaces the radial wall and narrows the files beside it; in a
269
+ ray, the field is the distance to the walls of its cells."""
270
+ r = self.rays
271
+ hw = 0.5 * r.width
272
+ (ray_lo, rel_lo, gap_lo), (ray_hi, rel_hi, gap_hi) = lower, upper
273
+ out = np.minimum.reduce(
274
+ [along, np.where(ray_lo >= 0, np.inf, below), np.where(ray_hi >= 0, np.inf, above),
275
+ np.hypot(np.maximum(below - hw, 0.0), gap_lo),
276
+ np.hypot(np.maximum(above - hw, 0.0), gap_hi)]
277
+ ) - half # fmt: skip
278
+ for ray, rel, side, across in (
279
+ (ray_lo, rel_lo, below, hw + below),
280
+ (ray_hi, rel_hi, above, hw - above),
281
+ ):
282
+ inside = (ray >= 0) & (side < hw)
283
+ if inside.any():
284
+ dist = r.cell_distance(ray[inside], u[inside], rel[inside], across[inside])
285
+ out[inside] = dist - 0.5 * r.thickness
286
+ return out
287
+
288
+ def _signed(self, plane: np.ndarray, reach: float, z=None) -> np.ndarray:
289
+ """Distance to the sides of the cell minus half its wall (negative in walls), at
290
+ points of the plane, or of space (``z``: along the axis) when rays run between the
291
+ files."""
292
+ if self.rays is None or z is None:
293
+ label, d = self.cells.locate(plane, reach)
294
+ return d - 0.5 * self.walls[label]
295
+ plane = np.asarray(plane, dtype=float).reshape(-1, 2)
296
+ label, j, along, below, above = self.cells.parts(plane)
297
+ z = np.asarray(z, dtype=float).reshape(-1)
298
+ lower, upper = self.rays.locate(j, z), self.rays.locate(self.cells.above(j), z)
299
+ half = 0.5 * self.walls[label]
300
+ return self._beside_rays(along, below, above, half, plane[:, 0], lower, upper)
301
+
302
+ def _field(self, grid: Grid, reach: float) -> np.ndarray:
303
+ """Signed field on the voxels: of the plane (extruded by the callers) without
304
+ rays, of space with them (slice by slice along the axis)."""
305
+ plane, shape = pixel_centres(grid, plane_axes(self.axis))
306
+ if self.rays is None:
307
+ label, d = self.cells.locate(plane, reach)
308
+ return (d - 0.5 * self.walls[label]).astype(np.float32).reshape(shape)
309
+ label, j, along, below, above = self.cells.parts(plane)
310
+ half, up = 0.5 * self.walls[label], self.cells.above(j)
311
+ boundaries = np.arange(self.cells.n_files + 1)
312
+ z = axis_centres(grid, self.axis)
313
+ out = np.empty((len(z), len(plane)), dtype=np.float32)
314
+ for i, zi in enumerate(z):
315
+ ray, rel, gap = self.rays.locate(boundaries, np.full(len(boundaries), zi))
316
+ lower, upper = (ray[j], rel[j], gap[j]), (ray[up], rel[up], gap[up])
317
+ out[i] = self._beside_rays(along, below, above, half, plane[:, 0], lower, upper)
318
+ return np.moveaxis(out.reshape(len(z), *shape), 0, self.axis)
319
+
320
+ def _extruded(self, image2d: np.ndarray, grid: Grid) -> np.ndarray:
321
+ out = np.broadcast_to(image2d[:, :, None], (*image2d.shape, grid.shape[self.axis]))
322
+ return np.ascontiguousarray(np.moveaxis(out, 2, self.axis))
323
+
324
+ def _space_field(self, grid: Grid, reach: float) -> np.ndarray:
325
+ field = self._field(grid, reach)
326
+ return field if field.ndim == 3 else self._extruded(field, grid)
327
+
328
+ @property
329
+ def _reach(self) -> float:
330
+ thickest = float(self.walls.max())
331
+ return 0.5 * max(thickest, 0.0 if self.rays is None else self.rays.thickness)
332
+
333
+ def contains(self, points) -> np.ndarray:
334
+ pts = np.asarray(points, dtype=float).reshape(-1, 3)
335
+ b, c = plane_axes(self.axis)
336
+ out = self._signed(pts[:, [b, c]], self._reach, pts[:, self.axis]) < 0
337
+ if not self.domain.periodic:
338
+ out &= np.all((pts >= self.domain.lower) & (pts <= self.domain.upper), axis=1)
339
+ return out
340
+
341
+ def level_set_at(self, points, reach: float = np.inf) -> np.ndarray:
342
+ """The distance to the sides of the cells minus half their walls at the points
343
+ (exact within ``reach`` of the walls, at least ``reach`` beyond)."""
344
+ pts = np.asarray(points, dtype=float).reshape(-1, 3)
345
+ b, c = plane_axes(self.axis)
346
+ reach = float(min(reach, float(np.max(self.domain.lengths))))
347
+ return self._signed(pts[:, [b, c]], max(reach, self._reach), pts[:, self.axis])
348
+
349
+ def voxelize(self, shape=None, *, voxel_size=None, grid: Grid | None = None, supersampling=1):
350
+ grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
351
+ ss = int(supersampling)
352
+ if ss == 1:
353
+ walls = (self._field(grid, self._reach) < 0).astype(np.uint8)
354
+ data = walls if walls.ndim == 3 else self._extruded(walls, grid)
355
+ return VoxelImage.from_grid(data, grid, name="phase", metadata=self.image_metadata())
356
+ if not 1 <= ss <= 6:
357
+ raise ValueError("supersampling must be an integer between 1 and 6")
358
+ fine = Grid(grid.domain, tuple(n * ss for n in grid.shape))
359
+ walls = (self._field(fine, self._reach) < 0).astype(np.float32)
360
+ if walls.ndim == 3:
361
+ nx, ny, nz = grid.shape
362
+ data = walls.reshape(nx, ss, ny, ss, nz, ss).mean(axis=(1, 3, 5), dtype=np.float32)
363
+ else:
364
+ b, c = plane_axes(self.axis)
365
+ nb, nc = grid.shape[b], grid.shape[c]
366
+ coarse = walls.reshape(nb, ss, nc, ss).mean(axis=(1, 3), dtype=np.float32)
367
+ data = self._extruded(coarse, grid)
368
+ return VoxelImage.from_grid(data, grid, name="fraction", metadata=self.image_metadata())
369
+
370
+ def level_set(self, shape=None, *, voxel_size=None, grid: Grid | None = None) -> VoxelImage:
371
+ """Distance to the sides of the cells minus half their walls: negative in the
372
+ walls, the signed distance to them near their faces."""
373
+ grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
374
+ reach = self._reach + 4.0 * float(np.max(grid.spacing))
375
+ far = np.float32(np.max(grid.domain.lengths))
376
+ data = np.minimum(self._space_field(grid, reach), far).astype(np.float32)
377
+ return VoxelImage.from_grid(data, grid, name="level_set", metadata=self.image_metadata())
378
+
379
+ def summary(self) -> dict:
380
+ out = {"n_cells": self.n_cells, "mean_wall": float(self.walls.mean())}
381
+ if self.rays is not None:
382
+ out["n_rays"] = self.n_rays
383
+ out["ray_fraction"] = self.ray_fraction
384
+ return out
385
+
386
+ def _geometry(self) -> dict:
387
+ geo = {"axis": self.axis, "germs": self.germs.tolist(), "walls": self.walls.tolist()}
388
+ if self.files is not None:
389
+ geo["files"] = {
390
+ "origin": float(self.files["origin"]),
391
+ "width": float(self.files["width"]),
392
+ "bounds": [np.asarray(b).tolist() for b in self.files["bounds"]],
393
+ }
394
+ if self.rays is not None:
395
+ geo["files"]["rays"] = self.rays.to_dict()
396
+ return geo
397
+
398
+ @classmethod
399
+ def _from_geometry(cls, domain, geometry, **kwargs):
400
+ return cls(
401
+ domain,
402
+ geometry["axis"],
403
+ geometry["germs"],
404
+ geometry["walls"],
405
+ geometry.get("files"),
406
+ **kwargs,
407
+ )
408
+
409
+
410
+ @register
411
+ @dataclass(frozen=True)
412
+ class Honeycomb(Model):
413
+ """Prismatic cells along ``axis`` with walls of ``wall_thickness``: hexagonal or
414
+ square honeycombs, random cells, or the radial files, growth rings and rays of wood."""
415
+
416
+ name = "honeycomb"
417
+ phases: ClassVar[dict[int, str]] = {0: "cells", 1: "walls"}
418
+ count_label = "cells"
419
+
420
+ cell_size: float = param(
421
+ 1.0, doc="Width of the cells: between opposite walls of the hexagons, the side of "
422
+ "the squares, the width of the files of wood", unit="length",
423
+ ) # fmt: skip
424
+ wall_thickness: float = param(
425
+ 0.1, doc="Thickness of the walls (of the earlywood for wood)", unit="length"
426
+ )
427
+ arrangement: str = param(
428
+ "hexagonal", doc="hexagonal, square, voronoi (random) or wood (radial files)", kind="str"
429
+ )
430
+ regularity: float = param(
431
+ 0.7, doc="voronoi: least distance of the germs, in jamming distances (0: Poisson)",
432
+ kind="fraction",
433
+ ) # fmt: skip
434
+ disorder: float = param(
435
+ 0.0, doc="Random displacement of the germs of lattices and files, in cells", kind="fraction"
436
+ )
437
+ ring_width: float | None = param(
438
+ None, doc="wood: width of the growth rings (default: no rings)", unit="length"
439
+ )
440
+ latewood_fraction: float = param(
441
+ 0.3, doc="wood: fraction of the rings in latewood", kind="fraction"
442
+ )
443
+ latewood_size: float = param(
444
+ 0.4, doc="wood: radial size of the latewood cells, relative to earlywood"
445
+ )
446
+ latewood_wall: float = param(
447
+ 2.0, doc="wood: wall thickness of the latewood cells, relative to earlywood"
448
+ )
449
+ ray_fraction: float = param(
450
+ 0.0, doc="wood: fraction of the volume in rays, radial ribbons of cells (0: none)",
451
+ kind="fraction",
452
+ ) # fmt: skip
453
+ ray_width: int = param(
454
+ 1, doc="wood: cells across a ray (1: uniseriate rays of softwoods)", kind="int"
455
+ )
456
+ ray_height: float | None = param(
457
+ None, doc="wood: height of the rays along the grain (default: 3 cell sizes)",
458
+ unit="length",
459
+ ) # fmt: skip
460
+ ray_cell_length: float | None = param(
461
+ None, doc="wood: radial length of the ray cells (default: 4 cell sizes)", unit="length"
462
+ )
463
+ ray_cell_width: float | None = param(
464
+ None, doc="wood: tangential width of the ray cells (default: half a cell size)",
465
+ unit="length",
466
+ ) # fmt: skip
467
+ ray_cell_height: float | None = param(
468
+ None, doc="wood: height of the ray cells along the grain (default: 0.6 cell size)",
469
+ unit="length",
470
+ ) # fmt: skip
471
+ ray_wall: float | None = param(
472
+ None, doc="wood: thickness of the walls of the ray cells (default: wall_thickness)",
473
+ unit="length",
474
+ ) # fmt: skip
475
+ axis: int = param(2, doc="Axis of the prisms, the grain of wood (0: x, 1: y, 2: z)", kind="int")
476
+
477
+ def _validate(self) -> None:
478
+ d = check_positive(self.cell_size, "cell_size")
479
+ t = check_positive(self.wall_thickness, "wall_thickness")
480
+ if self.arrangement not in ARRANGEMENTS:
481
+ raise ValueError(f"arrangement: one of {list(ARRANGEMENTS)}")
482
+ if self.axis not in (0, 1, 2):
483
+ raise ValueError("axis: 0, 1 or 2")
484
+ if not 0.0 <= self.regularity <= 0.95:
485
+ raise ValueError("regularity: from 0 (Poisson germs) to 0.95 (near jamming)")
486
+ if not 0.0 <= self.disorder <= 0.5:
487
+ raise ValueError("disorder: from 0 to 0.5 cell")
488
+ check_positive(self.latewood_size, "latewood_size")
489
+ check_positive(self.latewood_wall, "latewood_wall")
490
+ if not 0.0 < self.latewood_fraction < 0.6:
491
+ raise ValueError("latewood_fraction: in (0, 0.6), the transition taking half more")
492
+ if self.ring_width is not None:
493
+ check_positive(self.ring_width, "ring_width")
494
+ if self.ring_width < 3.0 * d:
495
+ raise ValueError("ring_width: at least three cells")
496
+ wood = self.arrangement == "wood" and self.ring_width is not None
497
+ thinnest = d * (min(1.0, self.latewood_size) if wood else 1.0)
498
+ thickest = t * (max(1.0, self.latewood_wall) if wood else 1.0)
499
+ if thickest >= thinnest:
500
+ raise ValueError("wall_thickness: walls thinner than the cells (a lumen remains)")
501
+ if not 0.0 <= self.ray_fraction < 0.5:
502
+ raise ValueError("ray_fraction: from 0 (no rays) to 0.5")
503
+ if self.ray_fraction > 0 and self.arrangement != "wood":
504
+ raise ValueError("ray_fraction: rays cross the files of wood (arrangement: wood)")
505
+ if self.ray_width < 1:
506
+ raise ValueError("ray_width: at least one cell")
507
+ names = ("ray_height", "ray_cell_length", "ray_cell_width", "ray_cell_height", "ray_wall")
508
+ for name in names:
509
+ if getattr(self, name) is not None:
510
+ check_positive(getattr(self, name), name)
511
+ if self.ray_fraction > 0:
512
+ ray = self.ray_cells
513
+ if min(ray["cell_length"], ray["cell_width"], ray["cell_height"]) <= ray["thickness"]:
514
+ raise ValueError("ray cells: longer, wider and higher than their walls are thick")
515
+ if ray["height"] < ray["cell_height"] * (1 - 1e-9):
516
+ raise ValueError("ray_height: at least one ray cell")
517
+ if 0.5 * ray["width"] >= d - thickest:
518
+ raise ValueError(
519
+ "rays: narrower than twice the files less their walls (a lumen remains "
520
+ "beside them)"
521
+ )
522
+
523
+ # -- germs ---------------------------------------------------------------------------
524
+
525
+ def _lattice(self, rng, lower, lengths, periodic: bool):
526
+ """Germs of the hexagonal or square lattice over the box (or a window around it)."""
527
+ d = self.cell_size
528
+ if self.arrangement == "hexagonal":
529
+ cell = np.array([d, d * math.sqrt(3.0)]) # rectangular period with two germs
530
+ basis = np.array([[0.0, 0.0], [0.5, 0.5]])
531
+ else:
532
+ cell = np.array([d, d])
533
+ basis = np.array([[0.0, 0.0]])
534
+ if periodic:
535
+ counts = np.maximum(1, np.rint(lengths / cell)).astype(int)
536
+ if counts[0] < 2 or (self.arrangement == "square" and counts[1] < 2):
537
+ raise ValueError("honeycomb: a periodic box at least two cells wide")
538
+ cell = lengths / counts # whole cells: the lattice stretches to fit the box
539
+ lo, hi = np.zeros(2, dtype=int), counts
540
+ else:
541
+ lo = np.floor((lower - cell) / cell).astype(int)
542
+ hi = np.ceil((lower + lengths + cell) / cell).astype(int)
543
+ i, j = np.meshgrid(np.arange(lo[0], hi[0]), np.arange(lo[1], hi[1]), indexing="ij")
544
+ corners = np.column_stack([i.ravel(), j.ravel()])
545
+ germs = ((corners[:, None, :] + basis[None] + 0.25) * cell).reshape(-1, 2)
546
+ germs += lower if periodic else 0.0
547
+ if self.disorder > 0:
548
+ germs += (rng.random(germs.shape) - 0.5) * 2.0 * self.disorder * d
549
+ return germs, np.full(len(germs), self.wall_thickness)
550
+
551
+ def _random(self, rng, lower, lengths, periodic: bool):
552
+ """Germs of random cells, at least ``regularity`` jamming distance apart."""
553
+ d = self.cell_size
554
+ margin = 0.0 if periodic else 3.0 * d
555
+ window = lengths + 2.0 * margin
556
+ area = float(np.prod(window))
557
+ mean = area / (0.5 * math.sqrt(3.0) * d * d)
558
+ n = max(2, round(mean)) if periodic else max(2, int(rng.poisson(mean)))
559
+ distance = self.regularity * jamming_distance(n, area)
560
+ germs = lower - margin + hardcore_germs(n, window, distance, rng)
561
+ return germs, np.full(n, self.wall_thickness)
562
+
563
+ @property
564
+ def ray_cells(self) -> dict[str, float]:
565
+ """Sizes of the ray cells (``cell_length``, ``cell_width``, ``cell_height``) and of
566
+ the rays (``width``, ``height``), and the ``thickness`` of their walls."""
567
+ d = self.cell_size
568
+
569
+ def given(value, default: float) -> float:
570
+ return default if value is None else float(value)
571
+
572
+ out = {
573
+ "cell_length": given(self.ray_cell_length, 4.0 * d),
574
+ "cell_width": given(self.ray_cell_width, 0.5 * d),
575
+ "cell_height": given(self.ray_cell_height, 0.6 * d),
576
+ "height": given(self.ray_height, 3.0 * d),
577
+ "thickness": given(self.ray_wall, self.wall_thickness),
578
+ }
579
+ out["width"] = self.ray_width * out["cell_width"]
580
+ return out
581
+
582
+ def _rays(self, rng, files: dict, thickest: float, domain: Domain) -> dict:
583
+ """Rays between the ``files`` of a box: their boundaries, lower ends along the
584
+ grain and the radial offsets of their cells. They are placed one after the other at
585
+ random, never closer than one ray cell along the grain to another ray on the same
586
+ boundary or on a neighbouring one (a file is never narrowed from both sides)."""
587
+ ray = self.ray_cells
588
+ ax, periodic = self.axis, domain.periodic
589
+ radial = float(domain.lengths[plane_axes(ax)[0]])
590
+ lower, length = float(domain.lower[ax]), float(domain.lengths[ax])
591
+ n_files, file_width = len(files["bounds"]), float(files["width"])
592
+ width, tall, cell_length = ray["width"], ray["height"], ray["cell_length"]
593
+ if periodic: # whole ray cells radially
594
+ cell_length = radial / max(1, round(radial / cell_length))
595
+ cell_height = tall / max(1, round(tall / ray["cell_height"])) # whole cells per ray
596
+ gap = cell_height
597
+ if 0.5 * width >= file_width - thickest:
598
+ raise ValueError("rays: narrower than twice the files less their walls")
599
+ if periodic:
600
+ if tall + gap > length:
601
+ raise ValueError("rays: a periodic box longer than a ray and one of its cells")
602
+ window, boundaries, first = length, n_files, 0
603
+ n = round(self.ray_fraction * n_files * file_width * length / (width * tall))
604
+ share = n * width * tall / (n_files * file_width * length)
605
+ if abs(share - self.ray_fraction) > 0.1 * self.ray_fraction:
606
+ warnings.warn(
607
+ f"honeycomb: the periodic box holds {n} whole rays, {share:.3g} of the "
608
+ f"volume instead of {self.ray_fraction:.3g}; for the asked fraction, make "
609
+ "it longer along the grain or wider",
610
+ RuntimeWarning,
611
+ stacklevel=3,
612
+ )
613
+ else: # on the inner boundaries of the files, starting below the box
614
+ window, boundaries, first = length + tall, n_files - 1, 1
615
+ mean = self.ray_fraction * boundaries * file_width * window / (width * tall)
616
+ n = int(rng.poisson(mean))
617
+ where, starts = np.zeros(n, dtype=np.int64), np.zeros(n)
618
+ count = attempts = 0
619
+ while count < n:
620
+ attempts += 1
621
+ if attempts > 1000 * (n + 10):
622
+ raise ValueError(
623
+ "ray_fraction: the rays do not fit (fewer, lower or narrower rays)"
624
+ )
625
+ j = first + int(rng.integers(boundaries))
626
+ z = float(rng.random() * window)
627
+ k, dz = where[:count], np.abs(z - starts[:count])
628
+ if periodic:
629
+ apart = np.minimum((j - k) % n_files, (k - j) % n_files)
630
+ dz = np.minimum(dz, length - dz)
631
+ else:
632
+ apart = np.abs(j - k)
633
+ if np.any((apart <= 1) & (dz < tall + gap)):
634
+ continue
635
+ where[count], starts[count] = j, z
636
+ count += 1
637
+ z0 = lower if periodic else lower - tall
638
+ return {
639
+ "boundary": where.tolist(),
640
+ "z": (z0 + starts).tolist(),
641
+ "u": (rng.random(n) * cell_length).tolist(),
642
+ "cells": self.ray_width,
643
+ "width": width,
644
+ "height": tall,
645
+ "cell_length": cell_length,
646
+ "cell_height": cell_height,
647
+ "thickness": ray["thickness"],
648
+ }
649
+
650
+ def ring_profile(self, x: np.ndarray) -> np.ndarray:
651
+ """Latewood share at the positions ``x`` (in rings, from the start of a ring): 0 in
652
+ earlywood, 1 in latewood, linear through the transition."""
653
+ f = self.latewood_fraction
654
+ x = np.mod(x, 1.0)
655
+ return np.clip((x - (1.0 - 1.5 * f)) / (0.5 * f), 0.0, 1.0)
656
+
657
+ def _ring_cells(self, ring: float) -> np.ndarray:
658
+ """Boundaries of the cells of a ring (in rings, from 0 to 1): steps of the local
659
+ cell size, scaled to end on the ring boundary."""
660
+ d = self.cell_size
661
+ x, bounds = 0.0, [0.0]
662
+ while x < 1.0:
663
+ late = float(self.ring_profile(np.array([x]))[0])
664
+ x += d * (1.0 + (self.latewood_size - 1.0) * late) / ring
665
+ bounds.append(x)
666
+ bounds = np.array(bounds)
667
+ if len(bounds) > 2 and bounds[-1] - 1.0 > 0.5 * (bounds[-1] - bounds[-2]):
668
+ bounds = bounds[:-1] # the closest whole number of cells
669
+ return bounds / bounds[-1]
670
+
671
+ def _wood(self, rng, lower, lengths, periodic: bool):
672
+ """Radial files (along the first axis of the plane): the bounds of their cells,
673
+ the centres of the cells and their walls."""
674
+ d = self.cell_size
675
+ margin = 0.0 if periodic else 3.0 * d
676
+ lo, size = lower - margin, lengths + 2.0 * margin
677
+ if periodic:
678
+ n_files = max(2, round(size[1] / d))
679
+ width = size[1] / n_files
680
+ else:
681
+ n_files, width = math.ceil(size[1] / d), d
682
+ ring = d if self.ring_width is None else self.ring_width # no rings: one cell each
683
+ if periodic:
684
+ n_rings = max(1, round(size[0] / ring))
685
+ ring, start = size[0] / n_rings, 0.0
686
+ else:
687
+ n_rings, start = math.ceil(size[0] / ring) + 1, -rng.random()
688
+ cells = np.array([0.0, 1.0]) if self.ring_width is None else self._ring_cells(ring)
689
+ edges = (start + np.arange(n_rings)[:, None] + cells[None, :-1]).ravel()
690
+ steps = np.diff(np.append(edges, edges[0] + n_rings)) # cell sizes, in rings
691
+ bounds, germs, walls = [], [], []
692
+ for j in range(n_files):
693
+ b = edges + rng.random() * steps # each file shifted by part of its cells
694
+ if self.disorder > 0:
695
+ least = np.minimum(steps, np.roll(steps, 1))
696
+ b = b + (rng.random(len(b)) - 0.5) * self.disorder * least
697
+ b = np.append(b, b[0] + n_rings)
698
+ centres = 0.5 * (b[:-1] + b[1:])
699
+ late = self.ring_profile(centres - start) if self.ring_width else 0.0 * centres
700
+ bounds.append(lo[0] + b * ring)
701
+ u = np.mod(centres, n_rings) if periodic else centres # the centres in the box
702
+ v = np.full(len(u), lo[1] + (j + 0.5) * width)
703
+ germs.append(np.column_stack([lo[0] + u * ring, v]))
704
+ walls.append(self.wall_thickness * (1.0 + (self.latewood_wall - 1.0) * late))
705
+ files = {"origin": float(lo[1]), "width": float(width), "bounds": bounds}
706
+ return np.concatenate(germs), np.concatenate(walls), files
707
+
708
+ def generate(self, domain: Domain, seed: SeedLike = None) -> PrismaticCells:
709
+ rng, seed_info = make_rng(seed)
710
+ b, c = plane_axes(self.axis)
711
+ lower, lengths = domain.lower[[b, c]], domain.lengths[[b, c]]
712
+ if domain.periodic and np.any(lengths < 1.5 * self.cell_size):
713
+ raise ValueError("honeycomb: a periodic box at least two cells wide")
714
+ files = None
715
+ if self.arrangement in ("hexagonal", "square"):
716
+ germs, walls = self._lattice(rng, lower, lengths, domain.periodic)
717
+ elif self.arrangement == "voronoi":
718
+ germs, walls = self._random(rng, lower, lengths, domain.periodic)
719
+ else:
720
+ germs, walls, files = self._wood(rng, lower, lengths, domain.periodic)
721
+ if self.ray_fraction > 0:
722
+ files["rays"] = self._rays(rng, files, float(walls.max()), domain)
723
+ return PrismaticCells(domain, self.axis, germs, walls, files, model=self, seed=seed_info)
724
+
725
+ # -- theory ------------------------------------------------------------------------------
726
+
727
+ @property
728
+ def cell_area(self) -> float:
729
+ d = self.cell_size
730
+ return 0.5 * math.sqrt(3.0) * d * d if self.arrangement != "square" else d * d
731
+
732
+ def expected_count(self, domain: Domain) -> float:
733
+ """Mean number of cells across the domain."""
734
+ b, c = plane_axes(self.axis)
735
+ return float(domain.lengths[b] * domain.lengths[c] / self.cell_area)
736
+
737
+ def theory(self, domain: Domain | None = None) -> dict[str, float]:
738
+ d, t = self.cell_size, self.wall_thickness
739
+ out = {"cells_per_area": 1.0 / self.cell_area}
740
+ if self.arrangement in ("hexagonal", "square") and self.disorder == 0:
741
+ out["volume_fraction"] = 1.0 - (1.0 - t / d) ** 2
742
+ out["specific_surface"] = 4.0 * (d - t) / d**2 # lumen perimeter per area
743
+ elif self.arrangement == "voronoi" and self.regularity == 0:
744
+ out["volume_fraction_first_order"] = 2.0 * t / math.sqrt(self.cell_area)
745
+ if self.ray_fraction > 0:
746
+ ray = self.ray_cells
747
+ out["ray_fraction"] = self.ray_fraction
748
+ out["ray_height_cells"] = float(max(1, round(ray["height"] / ray["cell_height"])))
749
+ return out