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,1476 @@
1
+ """Fibre models: Poisson fibres, a Boolean model on isotropic Poisson lines (Jeulin
2
+ 1991); hard-core (non-overlapping) fibres by random sequential addition; curved fibres,
3
+ worm-like chains, arcs or helices, overlapping or not; bending fibres, random walks packed
4
+ without overlap to high fractions by forces (Altendorf & Jeulin 2011), drawn into
5
+ contact (Keilmann, Redenbach & Willot 2026); entangled cross-linked fibres, straight
6
+ fibres bonded at a fraction of their contacts (Chatti et al. 2018, 2020)."""
7
+
8
+ from __future__ import annotations
9
+
10
+ import math
11
+ from dataclasses import dataclass
12
+ from typing import ClassVar
13
+
14
+ import numpy as np
15
+
16
+ from morphogen import theory
17
+ from morphogen._utils import check_fraction, check_positive, exactly_one
18
+ from morphogen.distributions import Constant, Distribution
19
+ from morphogen.domain import Domain
20
+ from morphogen.kernels.rsa import (
21
+ random_sequential_addition_fibres,
22
+ random_sequential_addition_polylines,
23
+ )
24
+ from morphogen.models.base import Model, param, register
25
+ from morphogen.models.boolean import _germ_window
26
+ from morphogen.models.combination import Combined
27
+ from morphogen.models.union import PrimitiveUnion
28
+ from morphogen.orientations import (
29
+ Aligned,
30
+ Isotropic,
31
+ OrientationDistribution,
32
+ Planar,
33
+ angle_weights,
34
+ half_sphere,
35
+ orthonormal_basis,
36
+ )
37
+ from morphogen.primitives import Segments, Spheres
38
+ from morphogen.seeding import SeedLike, make_rng
39
+
40
+
41
+ def _clip_lines(points, directions, lower, upper):
42
+ """Parameters [t0, t1] of the lines ``p + t d`` inside the box (slab method)."""
43
+ with np.errstate(divide="ignore", invalid="ignore"):
44
+ inv = 1.0 / directions
45
+ ta = (lower - points) * inv
46
+ tb = (upper - points) * inv
47
+ t_near = np.where(np.isnan(ta), -np.inf, np.minimum(ta, tb))
48
+ t_far = np.where(np.isnan(tb), np.inf, np.maximum(ta, tb))
49
+ # lines parallel to a slab and outside it never enter the box
50
+ parallel = directions == 0.0
51
+ outside = parallel & ((points < lower) | (points > upper))
52
+ t0 = np.max(np.where(parallel, -np.inf, t_near), axis=1)
53
+ t1 = np.min(np.where(parallel, np.inf, t_far), axis=1)
54
+ t1 = np.where(np.any(outside, axis=1), -np.inf, t1)
55
+ return t0, t1
56
+
57
+
58
+ @register
59
+ @dataclass(frozen=True)
60
+ class PoissonFibers(Model):
61
+ """Infinite cylinders of radius R around Poisson lines, isotropic or of directions
62
+ drawn from ``orientation``.
63
+
64
+ The model is parameterized by the volume fraction ``p`` of fibres or by the mean
65
+ fibre length per unit volume ``L_V`` (``p = 1 - exp(-L_V pi R^2)`` for any law of
66
+ directions). In the notation of Jeulin and of Dirrenberger et al. (2014) the intensity
67
+ of the lines is ``theta = L_V / pi`` and ``p = 1 - exp(-theta pi^2 R^2)``.
68
+
69
+ Infinite lines cannot be made periodic: domains must be non-periodic. The sample is
70
+ the exact restriction of the infinite random medium to the box. The covariance
71
+ (:meth:`covariance`) is in closed form along any direction, for any law.
72
+ """
73
+
74
+ name = "poisson_fibers"
75
+ phases: ClassVar[dict[int, str]] = {0: "pores", 1: "fibres"}
76
+ supports_periodic = False
77
+ count_label = "fibres"
78
+
79
+ radius: float = param(1.0, doc="Fibre radius", unit="length")
80
+ volume_fraction: float | None = param(None, doc="Volume fraction of fibres", kind="fraction")
81
+ length_density: float | None = param(
82
+ None, doc="Mean fibre length per unit volume L_V", unit="1/length^2"
83
+ )
84
+ orientation: OrientationDistribution = param(
85
+ Isotropic(),
86
+ doc="Distribution of the directions of the lines (isotropic, aligned, planar, beta, "
87
+ "girdle, von_mises_fisher, mixture)",
88
+ kind="orientation",
89
+ )
90
+
91
+ def _validate(self) -> None:
92
+ check_positive(self.radius, "radius")
93
+ exactly_one("volume_fraction", self.volume_fraction, "length_density", self.length_density)
94
+ if self.volume_fraction is not None:
95
+ check_fraction(self.volume_fraction, "volume_fraction")
96
+ else:
97
+ check_positive(self.length_density, "length_density")
98
+
99
+ @property
100
+ def lv(self) -> float:
101
+ """Mean fibre length per unit volume."""
102
+ if self.length_density is not None:
103
+ return self.length_density
104
+ return -math.log1p(-self.volume_fraction) / (math.pi * self.radius**2)
105
+
106
+ def generate(self, domain: Domain, seed: SeedLike = None) -> PrimitiveUnion:
107
+ self._check_domain(domain)
108
+ rng, seed_info = make_rng(seed)
109
+ r = self.radius
110
+ # lines hitting the ball containing the box dilated by r: the number is Poisson
111
+ # with mean L_V * pi * rho^2 (mean projected area of the ball)
112
+ rho = 0.5 * domain.diagonal + r
113
+ n = rng.poisson(self.lv * math.pi * rho * rho)
114
+ directions = self.orientation.sample(rng, n).reshape(n, 3) # isotropic: uniform
115
+ e1, e2 = orthonormal_basis(directions)
116
+ u = rng.random(n)
117
+ phi = rng.uniform(0.0, 2.0 * math.pi, n)
118
+ radial = rho * np.sqrt(u)
119
+ points = (
120
+ domain.center
121
+ + (radial * np.cos(phi))[:, None] * e1
122
+ + (radial * np.sin(phi))[:, None] * e2
123
+ )
124
+ lower, upper = domain.lower - r, domain.upper + r
125
+ t0, t1 = _clip_lines(points, directions, lower, upper)
126
+ keep = t0 <= t1
127
+ a = points[keep] + t0[keep, None] * directions[keep]
128
+ b = points[keep] + t1[keep, None] * directions[keep]
129
+ segments = Segments(a, b, np.full(len(a), r), round_caps=True)
130
+ return PrimitiveUnion(domain, segments=segments, model=self, seed=seed_info)
131
+
132
+ # -- theory --------------------------------------------------------------------------
133
+
134
+ def theory(self, domain: Domain | None = None) -> dict[str, float]:
135
+ lv, r = self.lv, self.radius
136
+ q = math.exp(-lv * math.pi * r * r)
137
+ return {
138
+ "length_density": lv,
139
+ "theta_jeulin": lv / math.pi,
140
+ "volume_fraction": 1.0 - q,
141
+ "specific_surface": 2.0 * math.pi * r * lv * q,
142
+ "integral_range": math.inf,
143
+ "variance_exponent": 2.0 / 3.0,
144
+ }
145
+
146
+ def choquet_capacity(self, element: str, size, direction=None) -> np.ndarray:
147
+ """``T(K) = P(K hits A)``: the lines of direction ``u`` hitting a convex body are
148
+ those crossing its projection on the plane normal to ``u`` (on average ``L_V S / 4``
149
+ isotropic lines, Cauchy), and those hitting the fibres hit ``A' (+) K'``: for balls
150
+ of radius ``size`` a ball of radius R + r (any law), for segments of length
151
+ ``size`` along ``direction`` a spherocylinder of projection ``pi R^2 + 2 R l |sin
152
+ g|`` (``g`` its angle to the line, ``E|sin g| = pi/4`` for isotropic lines; without a
153
+ direction, the mean of the capacities over the directions); pairs of points at
154
+ distance ``size``: ``2 p - C(h)``."""
155
+ size = np.asarray(size, dtype=float)
156
+ lv, r = self.lv, self.radius
157
+ if element == "ball":
158
+ return -np.expm1(-lv * math.pi * (r + size) ** 2)
159
+ if element == "segment":
160
+ if isinstance(self.orientation, Isotropic):
161
+ return -np.expm1(-lv * (math.pi * r * r + 0.5 * math.pi * r * size))
162
+ if direction is None:
163
+ rule = zip(*half_sphere(6), strict=True)
164
+ return sum(w * self.choquet_capacity(element, size, u) for u, w in rule)
165
+ b, w = angle_weights(self.orientation, direction)
166
+ sine = float(np.sum(w * np.sin(b)))
167
+ return -np.expm1(-lv * (math.pi * r * r + 2.0 * r * size * sine))
168
+ if element == "pair":
169
+ p = -math.expm1(-lv * math.pi * r * r)
170
+ return 2.0 * p - self.covariance(size, direction)
171
+ raise ValueError('element: "ball", "segment" or "pair"')
172
+
173
+ def expected_fibers(self, domain: Domain) -> float:
174
+ """Mean number of fibre axes hitting the box, ``L_V`` times the mean area of its
175
+ projection along the lines, ``sum_k A_k E|u_k|`` (``A_k`` the area of the faces
176
+ normal to the axis ``k``): ``L_V S / 4`` for isotropic lines (Dirrenberger 2014,
177
+ eq. 9)."""
178
+ if isinstance(self.orientation, Isotropic):
179
+ return self.lv * domain.surface_area / 4.0
180
+ u, w = self.orientation.quadrature()
181
+ lx, ly, lz = domain.size
182
+ mean = w @ np.abs(u.reshape(-1, 3)) # E|u_k|
183
+ return self.lv * float(ly * lz * mean[0] + lx * lz * mean[1] + lx * ly * mean[2])
184
+
185
+ def expected_count(self, domain: Domain) -> float:
186
+ return self.expected_fibers(domain)
187
+
188
+ def covariance(self, h, direction=None) -> np.ndarray:
189
+ """C(h) = P(x in A, x + h in A), for ``h`` along ``direction`` (any for isotropic
190
+ lines; averaged over the directions of ``h`` without one).
191
+
192
+ The lines of direction ``u`` hitting {x, x + h} dilated by the fibre radius are
193
+ those crossing the union of two disks of radius R, ``|h| sin(b)`` apart, in the
194
+ plane normal to ``u`` (``b`` the angle between ``h`` and ``u``): ``P(x, x + h not in
195
+ A) = q^2 exp(L_V E_u[lens(|h| sin b)])``, the mean over the law of the directions
196
+ (cos b uniform for isotropic lines; :func:`morphogen.theory.oriented_covariance`).
197
+ """
198
+ lv, r = self.lv, self.radius
199
+ q = math.exp(-lv * math.pi * r * r)
200
+
201
+ def lens(dist, b):
202
+ return theory.disk_intersection_area(dist * np.sin(b), r)
203
+
204
+ return theory.oriented_covariance(q, lv, lens, h, self.orientation, direction)
205
+
206
+
207
+ def _check_lumen(lumen: float) -> None:
208
+ if not 0.0 <= lumen < 1.0:
209
+ raise ValueError("lumen: the inner radius over the radius, in [0, 1)")
210
+
211
+
212
+ def _fibres(domain: Domain, segments: Segments, lumen: float, model, seed_info):
213
+ """The union of the fibres, or, for hollow ones, of their walls: the union of the
214
+ fibres minus that of their lumens (exact without overlaps; a lumen crossing another
215
+ fibre opens its wall there)."""
216
+ outer = PrimitiveUnion(domain, segments=_crop(segments, domain), model=model, seed=seed_info)
217
+ if lumen <= 0.0:
218
+ return outer
219
+ inner = Segments(segments.start, segments.end, segments.radii * lumen, segments.round_caps)
220
+ lumens = PrimitiveUnion(domain, segments=_crop(inner, domain), model=model, seed=seed_info)
221
+ return Combined(domain, "difference", [outer, lumens], model=model, seed=seed_info)
222
+
223
+
224
+ def _crop(segments: Segments, domain: Domain) -> Segments:
225
+ """The segments that reach a non-periodic domain."""
226
+ if domain.periodic:
227
+ return segments
228
+ lo, hi = segments.bounds()
229
+ return segments.subset(np.all((hi >= domain.lower) & (lo <= domain.upper), axis=1))
230
+
231
+
232
+ @register
233
+ @dataclass(frozen=True)
234
+ class HardcoreFibers(Model):
235
+ """Non-overlapping straight fibres (spherocylinders) placed by random sequential
236
+ addition (RSA).
237
+
238
+ Fibres are added one at a time, with uniformly random centres and axes drawn from
239
+ ``orientation``; a trial is rejected when the fibre would come closer than ``min_gap``
240
+ to one already placed. The process jams at a volume fraction that falls as the fibres
241
+ lengthen (isotropic fibres) and rises when they are aligned.
242
+
243
+ Generation always takes place in a periodic box; for non-periodic domains the box is
244
+ enlarged by a fibre length and cropped, which avoids wall effects.
245
+ """
246
+
247
+ name = "hardcore_fibers"
248
+ phases: ClassVar[dict[int, str]] = {0: "matrix", 1: "fibres"}
249
+ count_label = "fibres"
250
+
251
+ radius: Distribution = param(
252
+ Constant(0.5), doc="Fibre radius", kind="distribution", unit="length"
253
+ )
254
+ length: Distribution = param(
255
+ Constant(5.0),
256
+ doc="Length of the cylindrical part of the fibres (round caps)",
257
+ kind="distribution",
258
+ unit="length",
259
+ )
260
+ orientation: OrientationDistribution = param(
261
+ Isotropic(),
262
+ doc="Distribution of the fibre axes (isotropic, aligned, planar)",
263
+ kind="orientation",
264
+ )
265
+ volume_fraction: float | None = param(None, doc="Target volume fraction", kind="fraction")
266
+ number: int | None = param(None, doc="Number of fibres in the generation box", kind="int")
267
+ min_gap: float = param(0.0, doc="Minimal distance between fibre surfaces", unit="length")
268
+ max_attempts: int | None = param(
269
+ None, doc="Maximal number of trials (default: 10000 per fibre)", kind="int"
270
+ )
271
+ lumen: float = param(
272
+ 0.0,
273
+ doc="Hollow fibres: inner radius of their lumens over their radius (0: solid fibres; "
274
+ "the lumens belong to phase 0)",
275
+ kind="fraction",
276
+ )
277
+
278
+ def _validate(self) -> None:
279
+ exactly_one("volume_fraction", self.volume_fraction, "number", self.number)
280
+ if self.volume_fraction is not None:
281
+ check_fraction(self.volume_fraction, "volume_fraction")
282
+ elif self.number < 0:
283
+ raise ValueError("number: must be non-negative")
284
+ check_positive(self.min_gap, "min_gap", allow_zero=True)
285
+ if self.max_attempts is not None and self.max_attempts < 1:
286
+ raise ValueError("max_attempts: must be positive")
287
+ _check_lumen(self.lumen)
288
+
289
+ @property
290
+ def mean_volume(self) -> float:
291
+ return math.pi * self.radius.moment(2) * self.length.moment(1) + (
292
+ 4.0 / 3.0 * math.pi * self.radius.moment(3)
293
+ )
294
+
295
+ @property
296
+ def mean_surface(self) -> float:
297
+ return 2.0 * math.pi * self.radius.moment(1) * self.length.moment(1) + (
298
+ 4.0 * math.pi * self.radius.moment(2)
299
+ )
300
+
301
+ def _draw(self, rng, box_volume: float) -> tuple[np.ndarray, np.ndarray]:
302
+ """Radii and lengths of the fibres to place: the given number, or as many as make
303
+ the total volume closest to the target."""
304
+ if self.number is not None:
305
+ return self.radius.sample(rng, self.number), self.length.sample(rng, self.number)
306
+ target = self.volume_fraction * box_volume
307
+ radii, lengths = np.empty(0), np.empty(0)
308
+ while True:
309
+ m = int(1.1 * target / self.mean_volume) + 16
310
+ radii = np.concatenate([radii, self.radius.sample(rng, m)])
311
+ lengths = np.concatenate([lengths, self.length.sample(rng, m)])
312
+ cum = np.cumsum(math.pi * radii**2 * lengths + 4.0 / 3.0 * math.pi * radii**3)
313
+ if cum[-1] >= target:
314
+ break
315
+ k = int(np.searchsorted(cum, target))
316
+ n = k + 1 if k == 0 or cum[k] - target <= target - cum[k - 1] else k
317
+ return radii[:n], lengths[:n]
318
+
319
+ def generate(self, domain: Domain, seed: SeedLike = None) -> PrimitiveUnion:
320
+ rng, seed_info = make_rng(seed)
321
+ reach = self.length.upper() + 2.0 * self.radius.upper() + self.min_gap
322
+ if domain.periodic:
323
+ if reach >= min(domain.size) / 2.0:
324
+ raise ValueError(
325
+ f"hardcore_fibers: fibres (reach {reach:g}) must be shorter than half the "
326
+ f"periodic box (edge {min(domain.size):g})"
327
+ )
328
+ box = domain
329
+ else:
330
+ box = domain.dilated(reach)
331
+ radii, lengths = self._draw(rng, box.volume)
332
+ max_attempts = self.max_attempts or 10_000 * max(len(radii), 1)
333
+ local, axes = random_sequential_addition_fibres(
334
+ radii, lengths, box.lengths, self.min_gap, rng, self.orientation, max_attempts
335
+ )
336
+ centres = box.lower + local
337
+ half = 0.5 * lengths[:, None] * axes
338
+ segments = Segments(centres - half, centres + half, radii, round_caps=True)
339
+ return _fibres(domain, segments, self.lumen, self, seed_info)
340
+
341
+ def expected_count(self, domain: Domain) -> float | None:
342
+ """Mean number of fibre centres in the domain (given a volume fraction)."""
343
+ if self.volume_fraction is None:
344
+ return None
345
+ return self.volume_fraction * domain.volume / self.mean_volume
346
+
347
+ def theory(self, domain: Domain | None = None) -> dict[str, float]:
348
+ if self.volume_fraction is not None:
349
+ p = self.volume_fraction
350
+ elif domain is not None and domain.periodic:
351
+ p = self.number * self.mean_volume / domain.volume
352
+ else:
353
+ return {}
354
+ # no overlaps: the fraction and the surface are those of the fibres
355
+ out = {
356
+ "volume_fraction": p,
357
+ "specific_surface": p * self.mean_surface / self.mean_volume,
358
+ "intensity": p / self.mean_volume,
359
+ }
360
+ if self.lumen > 0.0: # the walls of the hollow fibres (volume_fraction: with lumens)
361
+ lam = self.lumen
362
+ r2, r3, ell = self.radius.moment(2), self.radius.moment(3), self.length.moment(1)
363
+ wall = math.pi * (1.0 - lam**2) * r2 * ell + 4.0 / 3.0 * math.pi * (1.0 - lam**3) * r3
364
+ out["solid_fraction"] = p * wall / self.mean_volume
365
+ return out
366
+
367
+
368
+ def _inverse_langevin(c: float) -> float:
369
+ """The concentration ``kappa`` of the von Mises-Fisher distribution on the sphere
370
+ whose mean cosine, ``coth(kappa) - 1/kappa``, is ``c`` (0 < c < 1)."""
371
+ k = c * (3.0 - c * c) / (1.0 - c * c) # Cohen's approximation, then Newton
372
+ for _ in range(50):
373
+ if k > 30.0:
374
+ f, df = 1.0 - 1.0 / k - c, 1.0 / (k * k)
375
+ else:
376
+ f = 1.0 / math.tanh(k) - 1.0 / k - c
377
+ df = 1.0 / (k * k) - 1.0 / math.sinh(k) ** 2
378
+ step = f / df
379
+ k = max(k - step, 0.5 * k)
380
+ if abs(step) <= 1e-14 * k:
381
+ break
382
+ return k
383
+
384
+
385
+ SHAPES = ("worm_like", "arc", "helix")
386
+
387
+
388
+ @register
389
+ @dataclass(frozen=True)
390
+ class CurvedFibers(Model):
391
+ """Curved fibres: chains of ``segments`` straight spherocylinders along curved axes,
392
+ a Boolean model or non-overlapping fibres.
393
+
394
+ ``shape`` sets the axes. ``worm_like``: the direction performs a persistent random
395
+ walk, each segment of length ``ds = length / segments`` turning from the previous one
396
+ by an angle whose cosine follows the von Mises-Fisher distribution of mean
397
+ ``exp(-ds / persistence)``, about a uniformly random perpendicular axis, so that the
398
+ tangents decorrelate as ``exp(-s / persistence)`` along the contour (the discrete
399
+ worm-like chain); the first direction follows ``orientation``. ``arc``: circular arcs
400
+ of radius ``curvature_radius`` (a distribution) bent in a uniformly random plane, the
401
+ tangent at the middle of the contour following ``orientation`` (the curved fibres of
402
+ PuMA). ``helix``: crimped fibres, helices of radius ``helix_radius`` and pitch
403
+ ``helix_pitch`` about straight axes following ``orientation``, of random phase. The
404
+ segments have round caps, so that the joints are smooth.
405
+
406
+ ``overlap: true``: a Boolean model, the centres of the fibres (the middles of their
407
+ contours) a Poisson point process. ``overlap: false``: fibres placed one at a time
408
+ by random sequential addition, a trial rejected when it comes closer than
409
+ ``min_gap`` to a fibre already placed (generated in a periodic box, enlarged and
410
+ cropped for non-periodic domains).
411
+ """
412
+
413
+ name = "curved_fibers"
414
+ phases: ClassVar[dict[int, str]] = {0: "matrix", 1: "fibres"}
415
+ count_label = "fibres"
416
+
417
+ radius: float = param(0.5, doc="Fibre radius", unit="length")
418
+ length: float = param(20.0, doc="Contour length of the fibres", unit="length")
419
+ persistence: float = param(
420
+ 10.0,
421
+ doc="Persistence length of worm-like chains: the tangents decorrelate as "
422
+ "exp(-s / persistence)",
423
+ unit="length",
424
+ )
425
+ segments: int = param(10, doc="Straight segments per fibre", kind="int")
426
+ orientation: OrientationDistribution = param(
427
+ Isotropic(),
428
+ doc="Distribution of the first direction (worm-like chains), the middle tangent "
429
+ "(arcs) or the axis (helices) of the fibres",
430
+ kind="orientation",
431
+ )
432
+ volume_fraction: float | None = param(None, doc="Volume fraction of fibres", kind="fraction")
433
+ intensity: float | None = param(None, doc="Fibre centres per unit volume", unit="1/length^3")
434
+ shape: str = param("worm_like", doc="Axes of the fibres: worm_like, arc or helix", kind="str")
435
+ curvature_radius: Distribution = param(
436
+ Constant(20.0),
437
+ doc="Radius of curvature of the arcs",
438
+ kind="distribution",
439
+ unit="length",
440
+ )
441
+ helix_radius: float = param(1.0, doc="Radius of the helices (crimp amplitude)", unit="length")
442
+ helix_pitch: float = param(
443
+ 10.0, doc="Pitch of the helices: their advance along the axis per turn", unit="length"
444
+ )
445
+ overlap: bool = param(
446
+ True,
447
+ doc="Boolean model; false: non-overlapping fibres by random sequential addition",
448
+ kind="bool",
449
+ )
450
+ min_gap: float = param(
451
+ 0.0, doc="Minimal distance between the surfaces of non-overlapping fibres", unit="length"
452
+ )
453
+ max_attempts: int | None = param(
454
+ None,
455
+ doc="Maximal number of trials of non-overlapping fibres (default 10000 each)",
456
+ kind="int",
457
+ )
458
+ lumen: float = param(
459
+ 0.0,
460
+ doc="Hollow fibres: inner radius of their lumens over their radius (0: solid fibres; "
461
+ "the lumens belong to phase 0)",
462
+ kind="fraction",
463
+ )
464
+
465
+ def _validate(self) -> None:
466
+ check_positive(self.radius, "radius")
467
+ check_positive(self.length, "length")
468
+ check_positive(self.persistence, "persistence")
469
+ if self.segments < 1:
470
+ raise ValueError("segments: at least one per fibre")
471
+ exactly_one("volume_fraction", self.volume_fraction, "intensity", self.intensity)
472
+ if self.volume_fraction is not None:
473
+ check_fraction(self.volume_fraction, "volume_fraction")
474
+ else:
475
+ check_positive(self.intensity, "intensity")
476
+ if self.shape not in SHAPES:
477
+ raise ValueError(f"shape: one of {', '.join(SHAPES)}")
478
+ check_positive(self.helix_radius, "helix_radius", allow_zero=True)
479
+ check_positive(self.helix_pitch, "helix_pitch")
480
+ check_positive(self.min_gap, "min_gap", allow_zero=True)
481
+ if self.max_attempts is not None and self.max_attempts < 1:
482
+ raise ValueError("max_attempts: must be positive")
483
+ _check_lumen(self.lumen)
484
+
485
+ @property
486
+ def mean_grain_volume(self) -> float:
487
+ """Volume of a straight fibre: the union of the segments of a curved one is a
488
+ little smaller (their caps overlap more at the bends)."""
489
+ return math.pi * self.radius**2 * self.length + 4.0 / 3.0 * math.pi * self.radius**3
490
+
491
+ @property
492
+ def theta(self) -> float:
493
+ if self.intensity is not None:
494
+ return self.intensity
495
+ if not self.overlap:
496
+ return self.volume_fraction / self.mean_grain_volume
497
+ return theory.boolean_intensity(self.volume_fraction, self.mean_grain_volume)
498
+
499
+ @property
500
+ def correlation(self) -> float:
501
+ """Mean cosine of the angle between consecutive segments (worm-like chains)."""
502
+ return math.exp(-self.length / self.segments / self.persistence)
503
+
504
+ def tangents(self, rng, n: int) -> np.ndarray:
505
+ """Directions (n x segments x 3) of the segments of ``n`` worm-like chains."""
506
+ m = self.segments
507
+ out = np.empty((n, m, 3))
508
+ if n == 0:
509
+ return out
510
+ out[:, 0] = self.orientation.sample(rng, n)
511
+ c = self.correlation
512
+ kappa = _inverse_langevin(c) if c > 1e-12 else 0.0
513
+ for k in range(1, m):
514
+ t = out[:, k - 1]
515
+ u = rng.random(n)
516
+ if kappa < 1e-8:
517
+ w = 2.0 * u - 1.0
518
+ else:
519
+ w = 1.0 + np.log(u + (1.0 - u) * math.exp(-2.0 * kappa)) / kappa
520
+ phi = rng.uniform(0.0, 2.0 * math.pi, n)
521
+ e1, e2 = orthonormal_basis(t)
522
+ sin = np.sqrt(np.clip(1.0 - w * w, 0.0, None))
523
+ turn = np.cos(phi)[:, None] * e1 + np.sin(phi)[:, None] * e2
524
+ nxt = w[:, None] * t + sin[:, None] * turn
525
+ out[:, k] = nxt / np.linalg.norm(nxt, axis=1)[:, None]
526
+ return out
527
+
528
+ def axes(self, rng, n: int) -> np.ndarray:
529
+ """Points (n x (segments + 1) x 3) of the axes of ``n`` fibres, relative to the
530
+ middles of their contours."""
531
+ m = self.segments
532
+ if self.shape == "worm_like":
533
+ points = np.zeros((n, m + 1, 3))
534
+ points[:, 1:] = np.cumsum(self.tangents(rng, n) * (self.length / m), axis=1)
535
+ else:
536
+ s = (np.arange(m + 1) / m - 0.5) * self.length # arc length from the middle
537
+ t = self.orientation.sample(rng, n).reshape(n, 3)
538
+ e1, e2 = orthonormal_basis(t)
539
+ phi = rng.uniform(0.0, 2.0 * math.pi, n)[:, None]
540
+ u = np.cos(phi) * e1 + np.sin(phi) * e2
541
+ if self.shape == "arc":
542
+ rho = self.curvature_radius.sample(rng, n)
543
+ if np.any(rho <= 0.0):
544
+ raise ValueError("curvature_radius: positive radii")
545
+ a = s[None, :] / rho[:, None]
546
+ points = rho[:, None, None] * (
547
+ np.sin(a)[..., None] * t[:, None, :]
548
+ + (1.0 - np.cos(a))[..., None] * u[:, None, :]
549
+ )
550
+ else:
551
+ w = np.cross(t, u)
552
+ c = self.helix_pitch / (2.0 * math.pi)
553
+ a = s / math.hypot(self.helix_radius, c) # turning angle from the middle
554
+ points = (
555
+ self.helix_radius
556
+ * (
557
+ np.cos(a)[None, :, None] * u[:, None, :]
558
+ + np.sin(a)[None, :, None] * w[:, None, :]
559
+ )
560
+ + c * a[None, :, None] * t[:, None, :]
561
+ )
562
+ if m % 2 == 0:
563
+ middle = points[:, m // 2]
564
+ else:
565
+ middle = 0.5 * (points[:, m // 2] + points[:, m // 2 + 1])
566
+ return points - middle[:, None, :]
567
+
568
+ def _packed(self, domain: Domain, rng) -> np.ndarray:
569
+ """Axes of non-overlapping fibres placed by random sequential addition."""
570
+ reach = self.length + 2.0 * self.radius + self.min_gap
571
+ if domain.periodic:
572
+ if reach >= min(domain.size) / 2.0:
573
+ raise ValueError(
574
+ f"curved_fibers: fibres (reach {reach:g}) must be shorter than half the "
575
+ f"periodic box (edge {min(domain.size):g})"
576
+ )
577
+ box = domain
578
+ else:
579
+ box = domain.dilated(reach)
580
+ n = round(self.theta * box.volume)
581
+ offsets = self.axes(rng, n)
582
+ max_attempts = self.max_attempts or 10_000 * max(n, 1)
583
+ centres = random_sequential_addition_polylines(
584
+ offsets, self.radius, box.lengths, self.min_gap, rng, max_attempts
585
+ )
586
+ return box.lower + centres[:, None, :] + offsets
587
+
588
+ def generate(self, domain: Domain, seed: SeedLike = None) -> PrimitiveUnion:
589
+ rng, seed_info = make_rng(seed)
590
+ if self.overlap:
591
+ window = _germ_window(domain, 0.5 * self.length + self.radius, self.name)
592
+ n = rng.poisson(self.theta * window.volume)
593
+ centres = window.lower + rng.random((n, 3)) * window.lengths
594
+ points = self.axes(rng, n) + centres[:, None, :]
595
+ else:
596
+ points = self._packed(domain, rng)
597
+ m = self.segments
598
+ radii = np.full(len(points) * m, self.radius)
599
+ segments = Segments(points[:, :-1].reshape(-1, 3), points[:, 1:].reshape(-1, 3), radii)
600
+ return _fibres(domain, segments, self.lumen, self, seed_info)
601
+
602
+ def expected_count(self, domain: Domain) -> float:
603
+ """Mean number of fibre centres in the domain."""
604
+ return self.theta * domain.volume
605
+
606
+ def mean_square_end_to_end(self) -> float:
607
+ """Mean square distance between the ends of the axis of a fibre: for worm-like
608
+ chains ds^2 (m + 2 sum_d (m - d) c^d); the chords of the arcs (exact for their
609
+ polylines); the axial advance and the radial chord of the helices."""
610
+ m, length = self.segments, self.length
611
+ ds = length / m
612
+ if self.shape == "worm_like":
613
+ c = self.correlation
614
+ d = np.arange(1, m)
615
+ return ds * ds * (m + 2.0 * float(np.sum((m - d) * c**d)))
616
+ if self.shape == "arc":
617
+ nodes, weights = self.curvature_radius.quadrature(96)
618
+ chord = 2.0 * nodes * np.sin(0.5 * length / nodes)
619
+ return float(np.sum(weights * chord**2))
620
+ c = self.helix_pitch / (2.0 * math.pi)
621
+ a = length / math.hypot(self.helix_radius, c)
622
+ return (c * a) ** 2 + (2.0 * self.helix_radius * math.sin(0.5 * a)) ** 2
623
+
624
+ def theory(self, domain: Domain | None = None) -> dict[str, float]:
625
+ theta = self.theta
626
+ if self.overlap:
627
+ # exact for straight fibres; a little above that of curved ones (overlaps)
628
+ fraction = 1.0 - math.exp(-theta * self.mean_grain_volume)
629
+ else:
630
+ fraction = theta * self.mean_grain_volume # a little above (joints)
631
+ out = {
632
+ "intensity": theta,
633
+ "volume_fraction": fraction,
634
+ "length_density": theta * self.length,
635
+ "mean_square_end_to_end": self.mean_square_end_to_end(),
636
+ }
637
+ if self.lumen > 0.0 and not self.overlap: # the walls of the hollow fibres
638
+ lam, r = self.lumen, self.radius
639
+ wall = math.pi * (1.0 - lam**2) * r * r * self.length
640
+ wall += 4.0 / 3.0 * math.pi * (1.0 - lam**3) * r**3
641
+ out["solid_fraction"] = theta * wall
642
+ return out
643
+
644
+
645
+ def von_mises_fisher(rng, mean, kappa) -> np.ndarray:
646
+ """Unit vectors drawn from von Mises-Fisher laws on the sphere, of densities
647
+ ``kappa exp(kappa m.x) / (4 pi sinh kappa)``, one per row of ``mean`` (unit vectors
648
+ ``m``) and entry of ``kappa`` (>= 0; 0 is uniform): the cosine ``w = m.x`` by inversion,
649
+ ``w = 1 + ln(u + (1 - u) e^(-2 kappa)) / kappa``, the azimuth about ``m`` uniform."""
650
+ mean = np.asarray(mean, dtype=float).reshape(-1, 3)
651
+ n = len(mean)
652
+ kappa = np.broadcast_to(np.asarray(kappa, dtype=float), (n,))
653
+ u = 1.0 - rng.random(n) # in (0, 1]
654
+ flat = kappa < 1e-8
655
+ k = np.where(flat, 1.0, kappa)
656
+ w = np.where(flat, 2.0 * u - 1.0, 1.0 + np.log(u + (1.0 - u) * np.exp(-2.0 * k)) / k)
657
+ phi = rng.uniform(0.0, 2.0 * math.pi, n)
658
+ e1, e2 = orthonormal_basis(mean)
659
+ sin = np.sqrt(np.clip(1.0 - w * w, 0.0, None))
660
+ x = w[:, None] * mean + sin[:, None] * (np.cos(phi)[:, None] * e1 + np.sin(phi)[:, None] * e2)
661
+ return x / np.linalg.norm(x, axis=1, keepdims=True)
662
+
663
+
664
+ def multivariate_von_mises_fisher_walk(rng, main, kappa1: float, kappa2: float, steps: int):
665
+ """Directions (n x steps x 3) of the random walks of Altendorf & Jeulin (2011): step
666
+ ``k`` follows the multivariate von Mises-Fisher law of density proportional to
667
+ ``exp(kappa1 mu.t + kappa2 t_(k-1).t)``, ``mu`` the main direction (a row of ``main``)
668
+ and ``t_0 = mu``, i.e. the von Mises-Fisher law about ``kappa1 mu + kappa2 t_(k-1)`` of
669
+ concentration its length."""
670
+ main = np.asarray(main, dtype=float).reshape(-1, 3)
671
+ out = np.empty((len(main), steps, 3))
672
+ prev = main
673
+ for k in range(steps):
674
+ v = kappa1 * main + kappa2 * prev
675
+ kappa = np.linalg.norm(v, axis=1)
676
+ mean = np.where(kappa[:, None] > 0.0, v / np.maximum(kappa, 1e-300)[:, None], main)
677
+ prev = out[:, k] = von_mises_fisher(rng, mean, kappa)
678
+ return out
679
+
680
+
681
+ def _turn(vectors, a, b):
682
+ """``vectors`` (n x 3) turned by the rotation taking the unit vector ``a`` to ``b``
683
+ about their common normal (Rodrigues' formula)."""
684
+ axis = np.cross(a, b)
685
+ sin, cos = float(np.linalg.norm(axis)), float(np.dot(a, b))
686
+ if sin < 1e-12:
687
+ if cos > 0.0:
688
+ return vectors
689
+ axis, sin, cos = orthonormal_basis(a)[0][0], 0.0, -1.0 # half a turn
690
+ else:
691
+ axis = axis / sin
692
+ return (
693
+ vectors * cos + np.cross(axis, vectors) * sin + np.outer(vectors @ axis, axis) * (1.0 - cos)
694
+ )
695
+
696
+
697
+ def _chain_volumes(x, first, radii) -> np.ndarray:
698
+ """Volumes of chains of spherocylinders that overlap only at their joints: ``pi r^2 L
699
+ + 4/3 pi r^3`` less ``2/3 r^3 (2 tan(d/2) - d)`` at a joint turning by ``d`` (the
700
+ cylinders overlap inside the bend, the ball of the joint fills its outside)."""
701
+ out = np.empty(len(radii))
702
+ for f, r in enumerate(radii):
703
+ t = np.diff(x[first[f] : first[f + 1]], axis=0)
704
+ lengths = np.linalg.norm(t, axis=1)
705
+ out[f] = math.pi * r * r * lengths.sum() + 4.0 / 3.0 * math.pi * r**3
706
+ if len(t) > 1:
707
+ u = t / np.maximum(lengths, 1e-300)[:, None]
708
+ d = np.arccos(np.clip(np.einsum("ij,ij->i", u[:-1], u[1:]), -1.0, 1.0))
709
+ out[f] -= 2.0 / 3.0 * r**3 * float(np.sum(2.0 * np.tan(0.5 * d) - d))
710
+ return out
711
+
712
+
713
+ END_STEPS = ("repulsion", "shrink")
714
+
715
+
716
+ @register
717
+ @dataclass(frozen=True)
718
+ class RandomWalkFibers(Model):
719
+ """Bending fibres packed without overlap by forces (Altendorf & Jeulin 2011).
720
+
721
+ As in the papers (Phys. Rev. E 83, 041804; ISMM 2011): random walks, then a
722
+ force-biased packing, to high volume fractions (0.51 for isotropic fibres of aspect
723
+ ratio 11, 0.64 nearly aligned). A fibre of radius ``r`` (from ``radius``) and contour
724
+ length ``L`` (from ``length``) is a chain of ``m = round(L / (step r))`` steps of
725
+ length ``L / m``. Its main direction ``mu`` follows ``orientation`` (in the papers
726
+ Schladitz's beta law, ``{type: beta, beta: 0.1}`` about z); each step follows the
727
+ multivariate von Mises-Fisher law of density proportional to ``exp(kappa1 mu.t +
728
+ kappa2 t'.t)``, ``t'`` the previous step (``mu`` for the first): ``kappa1``, the
729
+ reliability to the main direction, holds the fibre to it, ``kappa2``, the reliability
730
+ to the previous step, sets the smoothness of its bending. The chain is turned about
731
+ its first node, uniform in the box, so that its end-to-end vector follows ``mu``; as
732
+ many fibres as bring their total volume ``pi r^2 L + 4/3 pi r^3`` closest to
733
+ ``volume_fraction`` (or ``number`` of them). As in Altendorf, Jeulin & Willot (Int. J.
734
+ Solids Struct. 51, 3807, 2014): ``placement_trials > 1`` places the fibres one after
735
+ another at the best of that many uniform positions, the one of least overlap with the
736
+ fibres placed before it (the sum of the depths of the overlapping pairs of segments;
737
+ :func:`morphogen.kernels.force_biased.place`), which shortens the packing (2.5 to 9
738
+ times fewer steps for 30 trials, the more the looser the packing); the orthotropic
739
+ laws of their glass fibres are mixtures of beta laws (``{type: mixture, laws: [...],
740
+ weights: [...]}``).
741
+
742
+ ``packing: true``: the chains are packed by the forces of the paper
743
+ (:mod:`morphogen.kernels.force_biased`), repulsions of the overlapping segments plus
744
+ ``recovery`` times the springs on their lengths and the open angular springs on the
745
+ joints, until the total force falls below ``0.04 r`` per fibre and the largest overlap
746
+ below ``0.1 r_min`` (else, after ``max_steps`` steps, the fraction is out of reach);
747
+ the overlaps left are removed by steps of repulsions alone (``end_step: repulsion``,
748
+ the radii kept but for a residue) or by reducing the radius of each fibre by half its
749
+ largest overlap (``shrink``, the paper's end step). ``packing: false``: the
750
+ overlapping walks, a Boolean model whose ``volume_fraction`` is that of the union.
751
+
752
+ ``interaction_distance > 0``: the contact packing of Keilmann, Redenbach & Willot
753
+ (Comput. Mater. Sci. 264, 114458, 2026), which raises the number of contacts. After
754
+ the packing, the pairs of segments of different fibres whose surfaces are closer than
755
+ ``contact_distance + interaction_distance`` are candidates, shortlisted so that a
756
+ segment keeps only its closest candidate of each other fibre; the packing runs again
757
+ with the contact forces, each shortlisted pair drawn together by ``contact_weight``
758
+ times half its excess over ``contact_distance`` (smoothed by the friction ramp over
759
+ ``contact_distance``), until the total force changes by less than 0.001 % over a step
760
+ (1000 steps at most); the pairs that leave a force above ``contact_threshold`` times
761
+ the mean radius on one of their nodes (conflicting forces) are released and the
762
+ packing run once more, before the end step. The summary counts the contacts after
763
+ the packing (and before the contact packing, ``*_before``): the pairs of fibres closer
764
+ than ``contact_distance`` (plus 1 % of the smallest radius), their mean number per
765
+ fibre, and the clots, connected components of the segments in contact (consecutive
766
+ ones of a fibre joined) that hold more than two fibres; the theory gives Toll's
767
+ estimate for straight fibres of the same lengths, the contacts per fibre of their
768
+ Boolean model.
769
+
770
+ Choices (the papers leave them open or differ): chains of spherocylinders instead of
771
+ balls ``r/2`` apart (smooth fibres, any ``step``, no overlap meaning axes at least
772
+ ``r_a + r_b + min_gap`` apart), the push of a segment shared by its nodes with the
773
+ barycentric weights of its closest point; one radius per fibre; segments of a fibre
774
+ at most ``ceil(2.5 / step)`` steps apart exempt (the paper's five balls); the moves
775
+ capped to a quarter of the shortest segment or radius, a segment stretched beyond
776
+ twice its rest length shortened to it after a step; a joint folded beyond its
777
+ chord moved towards the middle of the chord; the paper's tolerance ``0.002 s`` per
778
+ fibre (window ``s = 20 r``) made ``0.04 r``. The realized fraction (``volume_fraction``
779
+ of the summary) departs from the target by the change of the contour lengths, which
780
+ the springs leave free within 5 %. Generated in a periodic box, which fibres may
781
+ outgrow (they bend around their images); non-periodic domains are cut from a periodic
782
+ box enlarged by half the reach of a fibre on every side.
783
+ """
784
+
785
+ name = "random_walk_fibers"
786
+ phases: ClassVar[dict[int, str]] = {0: "matrix", 1: "fibres"}
787
+ count_label = "fibres"
788
+
789
+ radius: Distribution = param(
790
+ Constant(0.5), doc="Fibre radius (one per fibre)", kind="distribution", unit="length"
791
+ )
792
+ length: Distribution = param(
793
+ Constant(10.0),
794
+ doc="Contour length of the fibre axes (round caps)",
795
+ kind="distribution",
796
+ unit="length",
797
+ )
798
+ orientation: OrientationDistribution = param(
799
+ Isotropic(),
800
+ doc="Distribution of the main directions of the fibres (isotropic, aligned, planar, "
801
+ "{type: beta, beta: 0.1, axis: [0, 0, 1]}, Schladitz's beta law, or a mixture of "
802
+ "laws, {type: mixture, laws: [...], weights: [...]})",
803
+ kind="orientation",
804
+ )
805
+ kappa1: float = param(
806
+ 10.0, doc="Reliability of the steps to the main direction of their fibre (>= 0)"
807
+ )
808
+ kappa2: float = param(
809
+ 100.0, doc="Reliability of the steps to the previous one: smoothness of the bending"
810
+ )
811
+ step: float = param(
812
+ 0.5, doc="Length of the steps of the walks (segments) over the fibre radius (paper: 0.5)"
813
+ )
814
+ volume_fraction: float | None = param(None, doc="Target volume fraction", kind="fraction")
815
+ number: int | None = param(None, doc="Number of fibres in the generation box", kind="int")
816
+ packing: bool = param(
817
+ True, doc="Force-biased packing without overlaps; false: the overlapping walks", kind="bool"
818
+ )
819
+ recovery: float = param(
820
+ 0.2,
821
+ doc="Weight of the recovery forces (segment lengths, joint angles) against the "
822
+ "repulsions (epsilon of the paper)",
823
+ kind="fraction",
824
+ )
825
+ max_steps: int = param(10_000, doc="Maximal number of packing steps", kind="int")
826
+ end_step: str = param(
827
+ "repulsion",
828
+ doc="Removal of the last overlaps: repulsion (repulsions alone, radii kept) or "
829
+ "shrink (each radius reduced by half the largest overlap of its fibre)",
830
+ kind="str",
831
+ )
832
+ min_gap: float = param(0.0, doc="Minimal distance between fibre surfaces", unit="length")
833
+ lumen: float = param(
834
+ 0.0,
835
+ doc="Hollow fibres: inner radius of their lumens over their radius (0: solid fibres; "
836
+ "the lumens belong to phase 0)",
837
+ kind="fraction",
838
+ )
839
+ interaction_distance: float = param(
840
+ 0.0,
841
+ doc="Contact packing (Keilmann et al. 2026): fibres closer than this (between "
842
+ "surfaces) after the packing are drawn into contact (0: none)",
843
+ unit="length",
844
+ )
845
+ contact_distance: float = param(
846
+ 0.0, doc="Distance between surfaces below which fibres are in contact", unit="length"
847
+ )
848
+ contact_weight: float = param(
849
+ 0.5, doc="Weight of the contact forces (paper: 0.5)", kind="fraction"
850
+ )
851
+ contact_threshold: float = param(
852
+ 0.05,
853
+ doc="Contact pairs left with a force above this times the mean radius on a node are "
854
+ "released (paper: 0.1 voxel for a radius of 2 voxels)",
855
+ )
856
+ placement_trials: int = param(
857
+ 1,
858
+ doc="Initial placement (Altendorf, Jeulin & Willot 2014): each fibre at the best of "
859
+ "this many uniform positions, the one of least overlap with the fibres placed "
860
+ "before it (1: uniform positions; more with packing only)",
861
+ kind="int",
862
+ )
863
+
864
+ def _validate(self) -> None:
865
+ exactly_one("volume_fraction", self.volume_fraction, "number", self.number)
866
+ if not 1 <= self.placement_trials <= 10_000:
867
+ raise ValueError("placement_trials: from 1 (uniform positions) to 10000")
868
+ if self.volume_fraction is not None:
869
+ check_fraction(self.volume_fraction, "volume_fraction")
870
+ elif self.number < 0:
871
+ raise ValueError("number: must be non-negative")
872
+ check_positive(self.interaction_distance, "interaction_distance", allow_zero=True)
873
+ check_positive(self.contact_distance, "contact_distance", allow_zero=True)
874
+ check_fraction(self.contact_weight, "contact_weight", open_interval=False)
875
+ check_positive(self.contact_threshold, "contact_threshold")
876
+ if self.interaction_distance > 0.0 and not self.packing:
877
+ raise ValueError("interaction_distance: the contact packing needs packing: true")
878
+ if self.placement_trials > 1 and not self.packing: # it would thin their overlaps
879
+ raise ValueError(
880
+ "placement_trials: the placement of least overlap needs packing: true "
881
+ "(unpacked fibres overlap as a Boolean model, its volume fraction that of "
882
+ "uniform positions)"
883
+ )
884
+ check_positive(self.kappa1, "kappa1", allow_zero=True)
885
+ check_positive(self.kappa2, "kappa2", allow_zero=True)
886
+ check_positive(self.step, "step")
887
+ check_fraction(self.recovery, "recovery", open_interval=False)
888
+ if self.max_steps < 0:
889
+ raise ValueError("max_steps: must be non-negative")
890
+ if self.end_step not in END_STEPS:
891
+ raise ValueError(f"end_step: one of {', '.join(END_STEPS)}")
892
+ check_positive(self.min_gap, "min_gap", allow_zero=True)
893
+ _check_lumen(self.lumen)
894
+
895
+ mean_volume = HardcoreFibers.mean_volume
896
+ mean_surface = HardcoreFibers.mean_surface
897
+
898
+ def _draw(self, rng, box_volume: float) -> tuple[np.ndarray, np.ndarray]:
899
+ """Radii and lengths: the given number of fibres, or as many as bring their total
900
+ volume closest to the target, ``p V`` (packed) or ``-ln(1 - p) V`` (overlapping)."""
901
+ if self.number is not None:
902
+ return self.radius.sample(rng, self.number), self.length.sample(rng, self.number)
903
+ p = self.volume_fraction
904
+ target = (p if self.packing else -math.log1p(-p)) * box_volume
905
+ radii, lengths = np.empty(0), np.empty(0)
906
+ while True:
907
+ m = int(1.1 * target / self.mean_volume) + 16
908
+ radii = np.concatenate([radii, self.radius.sample(rng, m)])
909
+ lengths = np.concatenate([lengths, self.length.sample(rng, m)])
910
+ cum = np.cumsum(math.pi * radii**2 * lengths + 4.0 / 3.0 * math.pi * radii**3)
911
+ if cum[-1] >= target:
912
+ break
913
+ k = int(np.searchsorted(cum, target))
914
+ n = k + 1 if k == 0 or cum[k] - target <= target - cum[k - 1] else k
915
+ return radii[:n], lengths[:n]
916
+
917
+ def walks(self, rng, radii, lengths) -> tuple[np.ndarray, np.ndarray]:
918
+ """The nodes of the walks of fibres of the given radii and contour lengths (from
919
+ their first nodes), all chains one after another, and the index of the first node
920
+ of each chain (then the number of nodes)."""
921
+ radii, lengths = np.asarray(radii, dtype=float), np.asarray(lengths, dtype=float)
922
+ if np.any(radii <= 0.0) or np.any(lengths <= 0.0):
923
+ raise ValueError("random_walk_fibers: positive radii and lengths")
924
+ n = len(radii)
925
+ m = np.maximum(1, np.rint(lengths / (self.step * radii))).astype(np.int64)
926
+ first = np.zeros(n + 1, dtype=np.int64)
927
+ first[1:] = np.cumsum(m + 1)
928
+ nodes = np.zeros((int(first[-1]), 3))
929
+ if n == 0:
930
+ return nodes, first
931
+ main = self.orientation.sample(rng, n).reshape(n, 3)
932
+ steps = multivariate_von_mises_fisher_walk(rng, main, self.kappa1, self.kappa2, m.max())
933
+ for f in range(n):
934
+ t = steps[f, : m[f]] * (lengths[f] / m[f])
935
+ chord = t.sum(axis=0)
936
+ norm = float(np.linalg.norm(chord))
937
+ if norm > 0.0: # the end-to-end vector along the main direction
938
+ t = _turn(t, chord / norm, main[f])
939
+ nodes[first[f] + 1 : first[f + 1]] = np.cumsum(t, axis=0)
940
+ return nodes, first
941
+
942
+ def _pack(self, x, first, radii, box: Domain) -> tuple[np.ndarray, dict]:
943
+ """Force-biased packing of the chains ``x`` (in ``[0, box)``, moved in place): the
944
+ radii (less half the largest overlap left of each fibre) and the statistics."""
945
+ from morphogen.kernels.force_biased import overlaps, pack
946
+
947
+ n = len(radii)
948
+ m = np.diff(first) - 1
949
+ seg_fibre = np.repeat(np.arange(n), m)
950
+ seg_index = np.arange(len(seg_fibre)) - np.repeat(first[:-1] - np.arange(n), m)
951
+ seg_node = seg_index + first[seg_fibre]
952
+ rest = np.linalg.norm(x[seg_node + 1] - x[seg_node], axis=1)
953
+ e1, e2 = x[:-2] - x[1:-1], x[2:] - x[1:-1]
954
+ cos = np.einsum("ij,ij->i", e1, e2)
955
+ cos /= np.maximum(np.linalg.norm(e1, axis=1) * np.linalg.norm(e2, axis=1), 1e-300)
956
+ rest_angle = np.full(len(x), math.pi) # those of the ends of the chains: unused
957
+ rest_angle[1:-1] = np.arccos(np.clip(cos, -1.0, 1.0))
958
+ related = np.full(n, math.ceil(2.5 / self.step - 1e-9), dtype=np.int64)
959
+ lengths = np.asarray(box.lengths, dtype=float)
960
+ gap, r_min = float(self.min_gap), float(radii.min())
961
+ if 2.0 * (2.0 * radii.max() + gap + 1.5 * rest.max()) >= lengths.min():
962
+ raise ValueError(
963
+ f"random_walk_fibers: the box (edge {lengths.min():g}) must exceed twice the "
964
+ "reach of two segments, 2 (2 r + min_gap + 1.5 step r)"
965
+ )
966
+ args = (first, seg_node, seg_fibre, seg_index, radii, related, rest, rest_angle,
967
+ lengths, gap, float(self.recovery), 0.25 * min(r_min, rest.min())) # fmt: skip
968
+ tol = 0.04 * float(radii.mean()) * n
969
+ steps, force, largest = pack(x, *args, tol, 0.1 * r_min, int(self.max_steps), False)
970
+ if largest > 0.1 * r_min:
971
+ raise RuntimeError(
972
+ f"random_walk_fibers: overlaps of {largest:.3g} left after {steps} packing "
973
+ f"steps, above 0.1 r_min = {0.1 * r_min:.3g}; lower the volume fraction or "
974
+ "raise max_steps"
975
+ )
976
+ stats = {}
977
+ if self.interaction_distance > 0.0:
978
+ stats = {f"{k}_before": v for k, v in self._contacts(x, args, radii).items()}
979
+ largest, more = self._contact_packing(x, args, radii)
980
+ stats.update(more)
981
+ end = 0
982
+ if self.end_step == "repulsion" and largest > 0.0:
983
+ end, _, largest = pack(x, *args, 0.0, 1e-9 * r_min, max(self.max_steps, 1000), True)
984
+ worst = np.zeros(n)
985
+ overlaps(x, seg_node, seg_fibre, seg_index, radii, related, lengths, gap,
986
+ np.zeros((0, 3)), worst) # fmt: skip
987
+ shrunk = radii - 0.5 * worst # then r_i + r_j + gap <= the distance of any two
988
+ stats.update(self._contacts(x, args, shrunk)) # those of the fibres returned
989
+ return shrunk, {
990
+ "packing_steps": int(steps),
991
+ "packing_force": float(force),
992
+ "end_steps": int(end),
993
+ "radius_reduction": float(np.max(0.5 * worst / radii)),
994
+ "volume_fraction": float(np.sum(_chain_volumes(x, first, shrunk)) / box.volume),
995
+ **stats,
996
+ }
997
+
998
+ def _contact_packing(self, x, args, radii) -> tuple[float, dict]:
999
+ """The contact packing of Keilmann et al. (2026) of the packed chains ``x`` (moved
1000
+ in place): the largest overlap left and the statistics."""
1001
+ from morphogen.kernels.force_biased import near_pairs, pack_contacts
1002
+
1003
+ seg_node, seg_fibre, lengths, gap = args[1], args[2], args[8], args[9]
1004
+ eps = float(self.contact_distance)
1005
+ reach = gap + eps + float(self.interaction_distance)
1006
+ s, t, d = near_pairs(x, seg_node, seg_fibre, radii, lengths, reach)
1007
+ keep = _shortlist(s, t, d, seg_fibre, len(radii))
1008
+ s, t = s[keep], t[keep]
1009
+ lim = radii[seg_fibre[s]] + radii[seg_fibre[t]] + gap + eps
1010
+ active = np.ones(len(s), dtype=np.bool_)
1011
+ force = np.zeros(len(x))
1012
+ run = (s, t, active, lim, eps, float(self.contact_weight), 1e-5, 1000, force)
1013
+ steps, _, largest = pack_contacts(x, *args, *run)
1014
+ a, b = seg_node[s], seg_node[t]
1015
+ loads = np.max(np.stack([force[a], force[a + 1], force[b], force[b + 1]]), axis=0)
1016
+ stuck = loads > self.contact_threshold * float(radii.mean())
1017
+ if np.any(stuck): # conflicting forces: those pairs released, the packing run again
1018
+ active[stuck] = False
1019
+ more, _, largest = pack_contacts(x, *args, *run)
1020
+ steps += more
1021
+ return largest, {
1022
+ "contact_pairs": len(s),
1023
+ "released_pairs": int(np.sum(stuck)),
1024
+ "contact_steps": int(steps),
1025
+ }
1026
+
1027
+ def _contacts(self, x, args, radii) -> dict:
1028
+ """Contacts of the chains: the pairs of fibres of which two segments are closer
1029
+ than ``r_a + r_b + min_gap + contact_distance`` (plus 1 % of the smallest radius),
1030
+ their number and mean number per fibre, and the clots of Keilmann et al. (2026,
1031
+ sec. 3.1), the connected components of the segments in contact, consecutive ones
1032
+ of a fibre joined, that hold more than two fibres."""
1033
+ from scipy.sparse import coo_matrix
1034
+ from scipy.sparse.csgraph import connected_components
1035
+
1036
+ from morphogen.kernels.force_biased import near_pairs
1037
+
1038
+ seg_node, seg_fibre, lengths, gap = args[1], args[2], args[8], args[9]
1039
+ n_seg = len(seg_node)
1040
+ tol = gap + float(self.contact_distance) + 0.01 * float(radii.min())
1041
+ s, t, _ = near_pairs(x, seg_node, seg_fibre, radii, lengths, tol)
1042
+ touching = np.zeros(n_seg, dtype=bool)
1043
+ touching[s] = touching[t] = True
1044
+ k = np.flatnonzero((seg_fibre[1:] == seg_fibre[:-1]) & touching[1:] & touching[:-1])
1045
+ rows, cols = np.concatenate([s, k]), np.concatenate([t, k + 1])
1046
+ graph = coo_matrix((np.ones(len(rows)), (rows, cols)), shape=(n_seg, n_seg))
1047
+ label = connected_components(graph, directed=False)[1]
1048
+ ids = np.flatnonzero(touching)
1049
+ members = np.unique(np.stack([label[ids], seg_fibre[ids]], axis=1), axis=0)
1050
+ sizes = np.unique(members[:, 0], return_counts=True)[1]
1051
+ fs, ft = seg_fibre[s], seg_fibre[t]
1052
+ pairs = len(np.unique(np.minimum(fs, ft) * len(radii) + np.maximum(fs, ft)))
1053
+ return {
1054
+ "contacts": int(pairs),
1055
+ "contacts_per_fibre": 2.0 * pairs / len(radii),
1056
+ "clots": int(np.sum(sizes > 2)),
1057
+ }
1058
+
1059
+ def generate(self, domain: Domain, seed: SeedLike = None) -> PrimitiveUnion:
1060
+ rng, seed_info = make_rng(seed)
1061
+ reach = self.length.upper() + 2.0 * self.radius.upper() + self.min_gap
1062
+ box = domain if domain.periodic else domain.dilated(0.5 * reach)
1063
+ radii, lengths = self._draw(rng, box.volume)
1064
+ nodes, first = self.walks(rng, radii, lengths)
1065
+ n = len(radii)
1066
+ summary = {"fibres": n}
1067
+ if self.placement_trials == 1 or n == 0:
1068
+ x = nodes + np.repeat(rng.random((n, 3)) * box.lengths, np.diff(first), axis=0)
1069
+ else: # the best of the trials, the one of least overlap with those placed before
1070
+ from morphogen.kernels.force_biased import place
1071
+
1072
+ x = nodes.copy()
1073
+ shifts = rng.random((n, self.placement_trials, 3)) * box.lengths
1074
+ lengths_box = np.asarray(box.lengths, dtype=float)
1075
+ depth = place(x, first, radii, lengths_box, float(self.min_gap), shifts)
1076
+ summary["placement_overlap"] = float(depth / max(float(radii.mean()), 1e-300))
1077
+ if self.packing and n:
1078
+ radii, stats = self._pack(x, first, radii, box)
1079
+ summary.update(stats)
1080
+ seg_fibre = np.repeat(np.arange(n), np.diff(first) - 1)
1081
+ seg_node = np.arange(len(seg_fibre)) + seg_fibre # no segment from the last node
1082
+ start, end = x[seg_node], x[seg_node + 1]
1083
+ period = np.asarray(box.lengths, dtype=float) # the midpoints moved into the box
1084
+ shift = box.lower - period * np.floor(0.5 * (start + end) / period)
1085
+ segments = Segments(start + shift, end + shift, radii[seg_fibre])
1086
+ micro = _fibres(domain, segments, self.lumen, self, seed_info)
1087
+ micro.metadata["summary"] = summary
1088
+ return micro
1089
+
1090
+ def expected_count(self, domain: Domain) -> float | None:
1091
+ """Mean number of fibres in the domain (given a volume fraction)."""
1092
+ if self.volume_fraction is None:
1093
+ return None
1094
+ p = self.volume_fraction if self.packing else -math.log1p(-self.volume_fraction)
1095
+ return p * domain.volume / self.mean_volume
1096
+
1097
+ def theory(self, domain: Domain | None = None) -> dict[str, float]:
1098
+ if self.volume_fraction is not None:
1099
+ p = self.volume_fraction
1100
+ total = p if self.packing else -math.log1p(-p) # fibre volume per unit volume
1101
+ elif domain is not None and domain.periodic:
1102
+ total = self.number * self.mean_volume / domain.volume
1103
+ p = total if self.packing else -math.expm1(-total)
1104
+ else:
1105
+ return {}
1106
+ intensity = total / self.mean_volume
1107
+ out = {"intensity": intensity, "length_density": intensity * self.length.moment(1)}
1108
+ # packed: without overlaps, the segments within the 5-10 % of their springs
1109
+ out["volume_fraction"] = p
1110
+ if self.packing:
1111
+ out["specific_surface"] = p * self.mean_surface / self.mean_volume
1112
+ reach = 2.0 * self.radius.moment(1) + self.min_gap + self.contact_distance
1113
+ ell = self.length.moment(1)
1114
+ out["toll_contacts_per_fibre"] = intensity * excluded_volume(
1115
+ reach, ell, ell * ell, mean_sine(self.orientation)
1116
+ )
1117
+ return out
1118
+
1119
+
1120
+ def _shortlist(s, t, d, seg_fibre, n_fibres: int) -> np.ndarray:
1121
+ """The contact candidates kept (Keilmann et al. 2026, eq. 18): a pair of segments
1122
+ ``(s, t)`` at distance ``d`` is kept when no other candidate pair of the same two fibres
1123
+ sharing one of its segments is closer, so that a segment keeps at most one pair per
1124
+ other fibre."""
1125
+ m = len(s)
1126
+ if m == 0:
1127
+ return np.zeros(0, dtype=bool)
1128
+ ends = np.concatenate([s, t]).astype(np.int64)
1129
+ other = np.concatenate([seg_fibre[t], seg_fibre[s]]).astype(np.int64)
1130
+ inverse = np.unique(ends * n_fibres + other, return_inverse=True)[1]
1131
+ both = np.concatenate([d, d])
1132
+ best = np.full(int(inverse.max()) + 1, np.inf)
1133
+ np.minimum.at(best, inverse, both)
1134
+ closest = both <= best[inverse]
1135
+ return closest[:m] & closest[m:]
1136
+
1137
+
1138
+ def mean_sine(orientation: OrientationDistribution, pairs: int = 200_000) -> float:
1139
+ """``E|sin g|``, ``g`` the angle between two independent axes of the law: pi/4
1140
+ isotropic, 2/pi planar, 0 aligned, otherwise by Monte Carlo over ``pairs`` pairs drawn
1141
+ from a fixed seed (deterministic, to about 0.2 %)."""
1142
+ if isinstance(orientation, Isotropic):
1143
+ return math.pi / 4.0
1144
+ if isinstance(orientation, Planar):
1145
+ return 2.0 / math.pi
1146
+ if isinstance(orientation, Aligned):
1147
+ return 0.0
1148
+ rng = np.random.default_rng(2026)
1149
+ u = orientation.sample(rng, pairs).reshape(-1, 3)
1150
+ v = orientation.sample(rng, pairs).reshape(-1, 3)
1151
+ return float(np.mean(np.linalg.norm(np.cross(u, v), axis=1)))
1152
+
1153
+
1154
+ def excluded_volume(reach: float, length: float, length2: float, sine: float) -> float:
1155
+ """Mean volume of the centres of a straight fibre whose axis comes closer than
1156
+ ``reach`` to that of another one (axes of mean length ``length`` and mean product of
1157
+ two lengths ``length2``, ``E|sin g| = sine`` between them): the parallelogram swept by
1158
+ one axis along the other dilated by a ball (Steiner), ``4/3 pi D^3 + 2 pi D^2 l +
1159
+ 2 D l1 l2 E|sin g|`` (Onsager's excluded volume for ``D = 2r``)."""
1160
+ return (
1161
+ 4.0 / 3.0 * math.pi * reach**3
1162
+ + 2.0 * math.pi * reach**2 * length
1163
+ + 2.0 * reach * length2 * sine
1164
+ )
1165
+
1166
+
1167
+ def _closest_parameters(r, a, b) -> tuple[np.ndarray, np.ndarray]:
1168
+ """Parameters ``(s, t)`` in [0, 1] of the closest points of the segments ``p + s a`` and
1169
+ ``q + t b``, ``r = p - q``, rows of pairs (Ericson 2005, sec. 5.1.9, as in
1170
+ :mod:`morphogen.kernels.force_biased`; parallel segments: the middle of the span of
1171
+ ``a`` facing ``b``)."""
1172
+ A = np.einsum("ij,ij->i", a, a)
1173
+ E = np.einsum("ij,ij->i", b, b)
1174
+ B = np.einsum("ij,ij->i", a, b)
1175
+ C = np.einsum("ij,ij->i", a, r)
1176
+ F = np.einsum("ij,ij->i", b, r)
1177
+ den = A * E - B * B
1178
+ lo, hi = np.clip(-C / A, 0.0, 1.0), np.clip((B - C) / A, 0.0, 1.0)
1179
+ with np.errstate(divide="ignore", invalid="ignore"):
1180
+ s = np.where(den > 1e-9 * A * E, np.clip((B * F - C * E) / den, 0.0, 1.0), 0.5 * (lo + hi))
1181
+ t = (B * s + F) / E
1182
+ s = np.where(t < 0.0, lo, np.where(t > 1.0, hi, s))
1183
+ return s, np.clip(t, 0.0, 1.0)
1184
+
1185
+
1186
+ class _Bonded(Combined):
1187
+ """The fibres and their cross-links of another phase, with the summary of the model."""
1188
+
1189
+ def summary(self) -> dict:
1190
+ return {**super().summary(), **self.metadata.get("summary", {})}
1191
+
1192
+
1193
+ @register
1194
+ @dataclass(frozen=True)
1195
+ class CrossLinkedFibers(Model):
1196
+ """Entangled cross-linked fibres: straight fibres bonded by cross-links at a fraction
1197
+ of their contacts (Mezeix et al. 2009, 2016; Chatti et al. 2018, 2020).
1198
+
1199
+ As in Chatti et al. (Comput. Mater. Sci. 151, 14, 2018; Int. J. Solids Struct. 184,
1200
+ 221, 2020), the volume elements of carbon fibres sprayed with epoxy: straight fibres of
1201
+ radius ``radius``, in contact where their axes come closer than a diameter (plus
1202
+ ``contact_gap``: a contact is a crossing), each contact bonded by a cross-link with
1203
+ the probability ``bonded_fraction`` (theirs: 1/3 to 1). ``length: null``: infinite
1204
+ fibres on Poisson lines whose directions follow ``orientation`` (the fibres of
1205
+ Chatti et al., 12 mm long, cross their 1 mm volume element; non-periodic samples, the
1206
+ exact restriction of the infinite medium); a ``length``: a Boolean model of
1207
+ spherocylinders of that cylindrical length (Mikado networks; periodic or not).
1208
+ ``orientation``: isotropic, or for their moulded material ``{type: girdle, sigma:
1209
+ 0.4}``, their Gaussian law of the angle to the axis of compression (eq. 3). A
1210
+ cross-link is a ball of radius ``link_radius`` centred between the closest points of
1211
+ the axes, of phase ``link_phase`` outside the fibres (2; 1: merged with them). All the
1212
+ contacts bonded, the networks cross-linked at every crossing of Ban et al. (2016),
1213
+ Shahsavari & Picu (2015) or Bosco et al. (2017).
1214
+
1215
+ The contacts along a fibre axis form, for Poisson lines, a Poisson process of
1216
+ intensity ``2 D L_V E|sin g|`` (``D = 2r + contact_gap``, ``g`` the angle between two
1217
+ fibres, ``E|sin g| = pi/4`` isotropic): the contacts are on average ``1 / (pi r L_V)``
1218
+ apart along an isotropic fibre, about ``d / 2f`` at small fractions ``f`` (Mezeix et al.
1219
+ 2016, eq. 16, after Toll), the cross-links ``1 / bonded_fraction`` times farther; a
1220
+ finite fibre has on average ``theta (4/3 pi D^3 + 2 pi D^2 l + 2 D l^2 E|sin g|)``
1221
+ contacts (its excluded volume). The summary counts the contacts and cross-links
1222
+ centred in the domain and their spacings along the axes inside it.
1223
+ """
1224
+
1225
+ name = "cross_linked_fibers"
1226
+ phases: ClassVar[dict[int, str]] = {0: "pores", 1: "fibres", 2: "cross-links"}
1227
+ count_label = "fibres"
1228
+
1229
+ radius: float = param(0.5, doc="Fibre radius", unit="length")
1230
+ length: float | None = param(
1231
+ None,
1232
+ doc="Length of the cylindrical part of the fibres (round caps); none: infinite "
1233
+ "fibres on Poisson lines (non-periodic domains)",
1234
+ unit="length",
1235
+ )
1236
+ orientation: OrientationDistribution = param(
1237
+ Isotropic(),
1238
+ doc="Distribution of the fibre axes (isotropic, planar, or {type: girdle, sigma: "
1239
+ "0.4, axis: [0, 0, 1]}, the moulded fibres of Chatti et al.)",
1240
+ kind="orientation",
1241
+ )
1242
+ volume_fraction: float | None = param(
1243
+ None, doc="Volume fraction of the fibres", kind="fraction"
1244
+ )
1245
+ length_density: float | None = param(
1246
+ None, doc="Mean length of fibre axes per unit volume L_V", unit="1/length^2"
1247
+ )
1248
+ contact_gap: float = param(
1249
+ 0.0,
1250
+ doc="Fibres are in contact where their surfaces are closer than this (0: where they cross)",
1251
+ unit="length",
1252
+ )
1253
+ bonded_fraction: float = param(
1254
+ 1.0, doc="Fraction of the contacts bonded by a cross-link", kind="fraction"
1255
+ )
1256
+ link_radius: float = param(
1257
+ 0.75, doc="Radius of the cross-links, balls centred at the contacts", unit="length"
1258
+ )
1259
+ link_phase: int = param(
1260
+ 2, doc="Phase of the cross-links (1: merged with the fibres)", kind="int"
1261
+ )
1262
+
1263
+ def _validate(self) -> None:
1264
+ check_positive(self.radius, "radius")
1265
+ if self.length is not None:
1266
+ check_positive(self.length, "length")
1267
+ exactly_one("volume_fraction", self.volume_fraction, "length_density", self.length_density)
1268
+ if self.volume_fraction is not None:
1269
+ check_fraction(self.volume_fraction, "volume_fraction")
1270
+ else:
1271
+ check_positive(self.length_density, "length_density")
1272
+ check_positive(self.contact_gap, "contact_gap", allow_zero=True)
1273
+ check_fraction(self.bonded_fraction, "bonded_fraction", open_interval=False)
1274
+ check_positive(self.link_radius, "link_radius")
1275
+ if not 1 <= self.link_phase <= 255:
1276
+ raise ValueError("link_phase: 1 (with the fibres) or a phase index from 2 to 255")
1277
+
1278
+ @property
1279
+ def supports_periodic(self) -> bool: # infinite lines cannot be made periodic
1280
+ return self.length is not None
1281
+
1282
+ def active_phases(self) -> dict[int, str]:
1283
+ if self.link_phase == 1:
1284
+ return {0: "pores", 1: "fibres and cross-links"}
1285
+ return {0: "pores", 1: "fibres", self.link_phase: "cross-links"}
1286
+
1287
+ @property
1288
+ def grain_volume(self) -> float:
1289
+ """Volume of a fibre: an infinite cylinder per unit length, or a spherocylinder."""
1290
+ r = self.radius
1291
+ if self.length is None:
1292
+ return math.pi * r * r
1293
+ return math.pi * r * r * self.length + 4.0 / 3.0 * math.pi * r**3
1294
+
1295
+ @property
1296
+ def lv(self) -> float:
1297
+ """Mean length of fibre axes (cylindrical parts) per unit volume."""
1298
+ if self.length_density is not None:
1299
+ return self.length_density
1300
+ density = -math.log1p(-self.volume_fraction) / self.grain_volume
1301
+ return density if self.length is None else density * self.length
1302
+
1303
+ @property
1304
+ def contact_reach(self) -> float:
1305
+ """Distance between axes below which two fibres are in contact."""
1306
+ return 2.0 * self.radius + self.contact_gap
1307
+
1308
+ def _lines(self, domain: Domain, rng, reach: float) -> tuple[np.ndarray, np.ndarray]:
1309
+ """Ends of the Poisson lines within ``reach`` of the box, clipped to the box
1310
+ dilated by ``reach``: as many as hit the ball containing it (Poisson, of mean
1311
+ ``L_V pi rho^2`` for any law of directions), through points uniform in the disc of
1312
+ that ball normal to their directions."""
1313
+ rho = 0.5 * domain.diagonal + reach
1314
+ n = rng.poisson(self.lv * math.pi * rho * rho)
1315
+ directions = self.orientation.sample(rng, n).reshape(n, 3)
1316
+ e1, e2 = orthonormal_basis(directions)
1317
+ radial = rho * np.sqrt(rng.random(n))
1318
+ phi = rng.uniform(0.0, 2.0 * math.pi, n)
1319
+ points = (
1320
+ domain.center
1321
+ + (radial * np.cos(phi))[:, None] * e1
1322
+ + (radial * np.sin(phi))[:, None] * e2
1323
+ )
1324
+ t0, t1 = _clip_lines(points, directions, domain.lower - reach, domain.upper + reach)
1325
+ keep = t0 <= t1
1326
+ a = points[keep] + t0[keep, None] * directions[keep]
1327
+ return a, points[keep] + t1[keep, None] * directions[keep]
1328
+
1329
+ def contacts(self, start, end, domain: Domain) -> tuple[np.ndarray, np.ndarray]:
1330
+ """The contacts of the fibres of axes ``start -> end``: the pairs ``(i, j)`` of
1331
+ fibres whose axes come closer than :attr:`contact_reach` (nearest periodic images
1332
+ in a periodic domain) and the middles of their closest points (wrapped into a
1333
+ periodic domain)."""
1334
+ start = np.asarray(start, float).reshape(-1, 3)
1335
+ vec = np.asarray(end, float).reshape(-1, 3) - start
1336
+ n = len(start)
1337
+ if self.length is None: # lines: every pair, 256 rows at a time
1338
+ blocks = []
1339
+ for k in range(0, max(n - 1, 0), 256):
1340
+ rows = np.arange(k, min(k + 256, n - 1))
1341
+ count = n - 1 - rows
1342
+ i = np.repeat(rows, count)
1343
+ j = i + 1 + np.arange(len(i)) - np.repeat(np.cumsum(count) - count, count)
1344
+ blocks.append(self._close(start, vec, i, j, domain))
1345
+ else:
1346
+ from scipy import spatial
1347
+
1348
+ mid = start + 0.5 * vec
1349
+ if domain.periodic:
1350
+ box = domain.lengths
1351
+ tree = spatial.cKDTree(np.mod(mid - domain.lower, box), boxsize=box)
1352
+ else:
1353
+ tree = spatial.cKDTree(mid)
1354
+ pairs = tree.query_pairs(self.length + self.contact_reach, output_type="ndarray")
1355
+ blocks = [self._close(start, vec, pairs[:, 0], pairs[:, 1], domain)]
1356
+ if not blocks:
1357
+ return np.zeros((0, 2), dtype=np.int64), np.zeros((0, 3))
1358
+ return np.concatenate([b[0] for b in blocks]), np.concatenate([b[1] for b in blocks])
1359
+
1360
+ def _close(self, start, vec, i, j, domain: Domain) -> tuple[np.ndarray, np.ndarray]:
1361
+ """The pairs ``(i, j)`` of axes in contact and the middles of their closest points."""
1362
+ reach = self.contact_reach
1363
+ shift = np.zeros((len(i), 3))
1364
+ if domain.periodic: # the nearest image of the middle of j
1365
+ box = domain.lengths
1366
+ gap = (start[j] + 0.5 * vec[j]) - (start[i] + 0.5 * vec[i])
1367
+ shift = -box * np.round(gap / box)
1368
+ s, t = _closest_parameters(start[i] - (start[j] + shift), vec[i], vec[j])
1369
+ p = start[i] + s[:, None] * vec[i]
1370
+ q = start[j] + shift + t[:, None] * vec[j]
1371
+ close = np.einsum("ij,ij->i", p - q, p - q) < reach * reach
1372
+ middles = 0.5 * (p[close] + q[close])
1373
+ if domain.periodic:
1374
+ middles = domain.lower + np.mod(middles - domain.lower, domain.lengths)
1375
+ return np.stack([i[close], j[close]], axis=1), middles
1376
+
1377
+ def generate(self, domain: Domain, seed: SeedLike = None) -> PrimitiveUnion:
1378
+ self._check_domain(domain)
1379
+ rng, seed_info = make_rng(seed)
1380
+ r, ell, link = self.radius, self.length, self.link_radius
1381
+ reach = 0.5 * self.contact_reach + link # a cross-link reaches this far from an axis
1382
+ if ell is None:
1383
+ start, end = self._lines(domain, rng, reach)
1384
+ else:
1385
+ if domain.periodic and ell + self.contact_reach >= 0.5 * min(domain.size):
1386
+ raise ValueError(
1387
+ f"{self.name}: fibres (length {ell:g} plus a diameter and the gap) must "
1388
+ f"be shorter than half the periodic box (edge {min(domain.size):g})"
1389
+ )
1390
+ window = _germ_window(domain, 0.5 * ell + reach, self.name)
1391
+ n = rng.poisson(self.lv / ell * window.volume)
1392
+ centres = window.lower + rng.random((n, 3)) * window.lengths
1393
+ half = 0.5 * ell * self.orientation.sample(rng, n).reshape(n, 3)
1394
+ start, end = centres - half, centres + half
1395
+ pairs, middles = self.contacts(start, end, domain)
1396
+ bonded = rng.random(len(pairs)) < self.bonded_fraction
1397
+ lo, hi = domain.lower, domain.upper
1398
+ near = np.all((middles >= lo - link) & (middles <= hi + link), axis=1)
1399
+ inside = np.all((middles >= lo) & (middles < hi), axis=1)
1400
+ segments = _crop(Segments(start, end, np.full(len(start), r), round_caps=True), domain)
1401
+ inner = segments.lengths if domain.periodic else _inner_lengths(segments, domain)
1402
+ summary = {
1403
+ "fibres": int(np.sum(inner > 0.0)), # axes crossing the domain
1404
+ "contacts": int(np.sum(inside)),
1405
+ "cross_links": int(np.sum(inside & bonded)),
1406
+ }
1407
+ axes = float(np.sum(inner))
1408
+ for key, count in (
1409
+ ("contact", summary["contacts"]),
1410
+ ("cross_link", summary["cross_links"]),
1411
+ ):
1412
+ summary[f"{key}_spacing"] = axes / (2.0 * count) if count else math.inf
1413
+ balls = middles[near & bonded]
1414
+ links = Spheres(balls, np.full(len(balls), link))
1415
+ if self.link_phase == 1:
1416
+ micro = PrimitiveUnion(
1417
+ domain, spheres=links, segments=segments, model=self, seed=seed_info
1418
+ )
1419
+ else:
1420
+ fibres = PrimitiveUnion(domain, segments=segments, model=self, seed=seed_info)
1421
+ bonds = PrimitiveUnion(domain, spheres=links, model=self, seed=seed_info)
1422
+ resin = Combined(domain, "difference", [bonds, fibres], model=self, seed=seed_info)
1423
+ parts = [fibres, resin]
1424
+ micro = _Bonded(
1425
+ domain, "inclusions", parts, [self.link_phase], model=self, seed=seed_info
1426
+ )
1427
+ micro.metadata["summary"] = summary
1428
+ return micro
1429
+
1430
+ def expected_count(self, domain: Domain) -> float:
1431
+ """Mean number of fibre axes crossing the domain: ``theta V`` in a periodic box;
1432
+ else, ``A`` the mean area of the projection of the box along the fibres (``S / 4``
1433
+ if isotropic), ``L_V A`` for lines and ``theta (V + l A)`` for segments."""
1434
+ if domain.periodic:
1435
+ return self.lv / self.length * domain.volume
1436
+ if isinstance(self.orientation, Isotropic):
1437
+ m = np.full(3, 0.5) # E|u_k|
1438
+ else:
1439
+ u = self.orientation.sample(np.random.default_rng(2026), 200_000)
1440
+ m = np.abs(u.reshape(-1, 3)).mean(axis=0)
1441
+ lx, ly, lz = domain.size
1442
+ area = float(ly * lz * m[0] + lx * lz * m[1] + lx * ly * m[2])
1443
+ if self.length is None:
1444
+ return self.lv * area
1445
+ return self.lv / self.length * (domain.volume + self.length * area)
1446
+
1447
+ def theory(self, domain: Domain | None = None) -> dict[str, float]:
1448
+ lv, r, reach = self.lv, self.radius, self.contact_reach
1449
+ sine = mean_sine(self.orientation)
1450
+ b = self.bonded_fraction
1451
+ out = {"length_density": lv, "mean_sine": sine}
1452
+ if self.length is None:
1453
+ per_length = 2.0 * reach * lv * sine # contacts per unit length of axis
1454
+ out["volume_fraction"] = -math.expm1(-lv * math.pi * r * r)
1455
+ out["contacts_per_length"] = per_length
1456
+ out["contact_intensity"] = 0.5 * lv * per_length
1457
+ else:
1458
+ theta, ell = lv / self.length, self.length
1459
+ per_fibre = theta * excluded_volume(reach, ell, ell * ell, sine)
1460
+ per_length = 2.0 * reach * lv * sine # without the ends of the fibres
1461
+ out["intensity"] = theta
1462
+ out["volume_fraction"] = -math.expm1(-theta * self.grain_volume)
1463
+ out["contacts_per_fibre"] = per_fibre
1464
+ out["contact_intensity"] = 0.5 * theta * per_fibre
1465
+ out["cross_link_intensity"] = b * out["contact_intensity"]
1466
+ out["contact_spacing"] = 1.0 / per_length if per_length > 0.0 else math.inf
1467
+ out["cross_link_spacing"] = 1.0 / (b * per_length) if b * per_length > 0 else math.inf
1468
+ return out
1469
+
1470
+
1471
+ def _inner_lengths(segments: Segments, domain: Domain) -> np.ndarray:
1472
+ """Lengths of the parts of the segments inside a box."""
1473
+ vec = segments.end - segments.start
1474
+ t0, t1 = _clip_lines(segments.start, vec, domain.lower, domain.upper)
1475
+ t0, t1 = np.clip(t0, 0.0, 1.0), np.clip(t1, 0.0, 1.0)
1476
+ return np.maximum(t1 - t0, 0.0) * np.linalg.norm(vec, axis=1)