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,310 @@
1
+ """Boolean models: unions of random grains implanted on Poisson points."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from dataclasses import dataclass
7
+ from typing import ClassVar
8
+
9
+ import numpy as np
10
+
11
+ from morphogen import theory
12
+ from morphogen._utils import check_fraction, check_positive, exactly_one
13
+ from morphogen.distributions import Constant, Distribution
14
+ from morphogen.domain import Domain
15
+ from morphogen.models.affine import ANISOTROPY, Anisotropy, anisotropic
16
+ from morphogen.models.base import Model, param, register
17
+ from morphogen.models.union import PrimitiveUnion
18
+ from morphogen.orientations import Isotropic, OrientationDistribution, angle_weights
19
+ from morphogen.primitives import Segments, Spheres
20
+ from morphogen.seeding import SeedLike, make_rng
21
+
22
+
23
+ def _germ_window(domain: Domain, extent: float, name: str) -> Domain:
24
+ """Window in which germs must be drawn for an unbiased sample of ``domain``."""
25
+ if domain.periodic:
26
+ if 2.0 * extent >= min(domain.size):
27
+ raise ValueError(
28
+ f"{name}: grains (extent {extent:g}) must be smaller than half the periodic "
29
+ f"box (edge {min(domain.size):g})"
30
+ )
31
+ return domain
32
+ return domain.dilated(extent)
33
+
34
+
35
+ @register
36
+ @anisotropic
37
+ @dataclass(frozen=True)
38
+ class BooleanSpheres(Model):
39
+ """Boolean model of spheres: union of balls centred on a Poisson point process.
40
+
41
+ Give either the volume fraction of the union or the intensity of the germs; the
42
+ other follows from ``p = 1 - exp(-theta * E[4/3 pi R^3])``.
43
+ """
44
+
45
+ name = "boolean_spheres"
46
+ phases: ClassVar[dict[int, str]] = {0: "matrix", 1: "spheres"}
47
+ count_label = "spheres"
48
+
49
+ radius: Distribution = param(
50
+ Constant(1.0),
51
+ doc="Sphere radius (number or distribution)",
52
+ kind="distribution",
53
+ unit="length",
54
+ )
55
+ volume_fraction: float | None = param(
56
+ None, doc="Volume fraction of the union of spheres", kind="fraction"
57
+ )
58
+ intensity: float | None = param(
59
+ None, doc="Number of sphere centres per unit volume", unit="1/length^3"
60
+ )
61
+ anisotropy: Anisotropy | None = param(None, doc=ANISOTROPY, kind="anisotropy", kw_only=True)
62
+
63
+ def _validate(self) -> None:
64
+ exactly_one("volume_fraction", self.volume_fraction, "intensity", self.intensity)
65
+ if self.volume_fraction is not None:
66
+ check_fraction(self.volume_fraction, "volume_fraction")
67
+ else:
68
+ check_positive(self.intensity, "intensity")
69
+
70
+ @property
71
+ def mean_grain_volume(self) -> float:
72
+ return 4.0 / 3.0 * math.pi * self.radius.moment(3)
73
+
74
+ @property
75
+ def theta(self) -> float:
76
+ """Intensity of the Poisson germs."""
77
+ if self.intensity is not None:
78
+ return self.intensity
79
+ return theory.boolean_intensity(self.volume_fraction, self.mean_grain_volume)
80
+
81
+ def generate(self, domain: Domain, seed: SeedLike = None) -> PrimitiveUnion:
82
+ rng, seed_info = make_rng(seed)
83
+ rmax = self.radius.upper()
84
+ window = _germ_window(domain, rmax, self.name)
85
+ n = rng.poisson(self.theta * window.volume)
86
+ centers = window.lower + rng.random((n, 3)) * window.lengths
87
+ radii = self.radius.sample(rng, n)
88
+ spheres = Spheres(centers, radii)
89
+ if not domain.periodic:
90
+ spheres = spheres.subset(domain.distance_to_box(centers) <= radii)
91
+ return PrimitiveUnion(domain, spheres=spheres, model=self, seed=seed_info)
92
+
93
+ # -- theory --------------------------------------------------------------------------
94
+
95
+ def expected_count(self, domain: Domain) -> float:
96
+ """Mean number of germs (grain centres) in the domain."""
97
+ return self.theta * domain.volume
98
+
99
+ def theory(self, domain: Domain | None = None) -> dict[str, float]:
100
+ theta = self.theta
101
+ q = math.exp(-theta * self.mean_grain_volume)
102
+ s = 4.0 * math.pi * self.radius.moment(2) # mean surface of the spheres
103
+ m = 4.0 * math.pi * self.radius.moment(1) # their integral of mean curvature
104
+ return {
105
+ "intensity": theta,
106
+ "volume_fraction": 1.0 - q,
107
+ "specific_surface": theta * q * s,
108
+ # Miles' formulae of isotropic Boolean models of convex grains
109
+ "mean_curvature_density": q * (theta * m - math.pi**2 / 32.0 * (theta * s) ** 2),
110
+ "euler_density": q
111
+ * (theta - theta**2 * m * s / (4.0 * math.pi) + math.pi / 384.0 * (theta * s) ** 3),
112
+ "integral_range": self.integral_range(),
113
+ "variance_exponent": 1.0,
114
+ }
115
+
116
+ def choquet_capacity(self, element: str, size) -> np.ndarray:
117
+ """``T(K) = 1 - exp(-theta E[|A' (+) K'|])``: balls of radius ``size`` (dilated
118
+ spheres of radius R + r), segments of length ``size`` (the sphere swept along the
119
+ segment: (4/3) pi R^3 + pi R^2 l), pairs of points at distance ``size``
120
+ (``2 p - C(h)``)."""
121
+ size = np.asarray(size, dtype=float)
122
+ theta = self.theta
123
+ m1, m2, m3 = (self.radius.moment(k) for k in (1, 2, 3))
124
+ if element == "ball":
125
+ volume = 4.0 / 3.0 * math.pi * (m3 + 3.0 * size * m2 + 3.0 * size**2 * m1 + size**3)
126
+ elif element == "segment":
127
+ volume = 4.0 / 3.0 * math.pi * m3 + math.pi * m2 * size
128
+ elif element == "pair":
129
+ p = 1.0 - math.exp(-theta * self.mean_grain_volume)
130
+ return 2.0 * p - self.covariance(size)
131
+ else:
132
+ raise ValueError('element: "ball", "segment" or "pair"')
133
+ return -np.expm1(-theta * volume)
134
+
135
+ def _mean_covariogram(self, h):
136
+ nodes, weights = self.radius.quadrature(96)
137
+ h = np.asarray(h, dtype=float)
138
+ return np.sum(weights * theory.sphere_covariogram(h[..., None], nodes), axis=-1)
139
+
140
+ def covariance(self, h) -> np.ndarray:
141
+ """C(h) = P(x in A, x + h in A) for the union A of the spheres."""
142
+ theta = self.theta
143
+ q = math.exp(-theta * self.mean_grain_volume)
144
+ big_q = q * q * np.exp(theta * self._mean_covariogram(h))
145
+ return 1.0 - 2.0 * q + big_q
146
+
147
+ def integral_range(self) -> float:
148
+ """A3 = int (C(h) - p^2) dh / (p (1 - p)) of the indicator of the union."""
149
+ theta = self.theta
150
+ q = math.exp(-theta * self.mean_grain_volume)
151
+ p = 1.0 - q
152
+
153
+ def f(h):
154
+ return q * q * math.expm1(theta * float(self._mean_covariogram(h)))
155
+
156
+ return theory.radial_integral(f, 2.0 * self.radius.upper()) / (p * q)
157
+
158
+
159
+ @register
160
+ @dataclass(frozen=True)
161
+ class BooleanCylinders(Model):
162
+ """Boolean model of finite fibres: cylinders (flat caps) or spherocylinders.
163
+
164
+ Fibre centres form a Poisson point process; radius, length (of the cylindrical
165
+ part) and axis orientation are independent random variables. The covariance
166
+ (:meth:`covariance`) is in closed form along any direction, for any law of the axes
167
+ (Peyrega et al. 2009).
168
+ """
169
+
170
+ name = "boolean_cylinders"
171
+ phases: ClassVar[dict[int, str]] = {0: "matrix", 1: "fibres"}
172
+ count_label = "fibres"
173
+
174
+ radius: Distribution = param(
175
+ Constant(1.0), doc="Fibre radius", kind="distribution", unit="length"
176
+ )
177
+ length: Distribution = param(
178
+ Constant(10.0),
179
+ doc="Length of the cylindrical part of the fibres",
180
+ kind="distribution",
181
+ unit="length",
182
+ )
183
+ orientation: OrientationDistribution = param(
184
+ Isotropic(),
185
+ doc="Distribution of the fibre axes (isotropic, aligned, planar, beta, girdle, "
186
+ "von_mises_fisher, mixture)",
187
+ kind="orientation",
188
+ )
189
+ caps: str = param(
190
+ "flat", doc="End caps: 'flat' (cylinders) or 'round' (spherocylinders)", kind="str"
191
+ )
192
+ volume_fraction: float | None = param(None, doc="Volume fraction of fibres", kind="fraction")
193
+ intensity: float | None = param(None, doc="Fibre centres per unit volume", unit="1/length^3")
194
+
195
+ def _validate(self) -> None:
196
+ exactly_one("volume_fraction", self.volume_fraction, "intensity", self.intensity)
197
+ if self.caps not in ("flat", "round"):
198
+ raise ValueError(f"caps: expected 'flat' or 'round', got {self.caps!r}")
199
+ if self.volume_fraction is not None:
200
+ check_fraction(self.volume_fraction, "volume_fraction")
201
+ else:
202
+ check_positive(self.intensity, "intensity")
203
+
204
+ @property
205
+ def mean_grain_volume(self) -> float:
206
+ v = math.pi * self.radius.moment(2) * self.length.moment(1)
207
+ if self.caps == "round":
208
+ v += 4.0 / 3.0 * math.pi * self.radius.moment(3)
209
+ return v
210
+
211
+ @property
212
+ def mean_grain_surface(self) -> float:
213
+ s = 2.0 * math.pi * self.radius.moment(1) * self.length.moment(1)
214
+ if self.caps == "round":
215
+ return s + 4.0 * math.pi * self.radius.moment(2)
216
+ return s + 2.0 * math.pi * self.radius.moment(2)
217
+
218
+ @property
219
+ def theta(self) -> float:
220
+ if self.intensity is not None:
221
+ return self.intensity
222
+ return theory.boolean_intensity(self.volume_fraction, self.mean_grain_volume)
223
+
224
+ def generate(self, domain: Domain, seed: SeedLike = None) -> PrimitiveUnion:
225
+ rng, seed_info = make_rng(seed)
226
+ rmax, lmax = self.radius.upper(), self.length.upper()
227
+ extent = 0.5 * lmax + rmax
228
+ window = _germ_window(domain, extent, self.name)
229
+ n = rng.poisson(self.theta * window.volume)
230
+ centers = window.lower + rng.random((n, 3)) * window.lengths
231
+ axes = self.orientation.sample(rng, n)
232
+ radii = self.radius.sample(rng, n)
233
+ half = 0.5 * self.length.sample(rng, n)[:, None]
234
+ segments = Segments(
235
+ centers - half * axes, centers + half * axes, radii, round_caps=self.caps == "round"
236
+ )
237
+ if not domain.periodic:
238
+ lo, hi = segments.bounds()
239
+ keep = np.all((hi >= domain.lower) & (lo <= domain.upper), axis=1)
240
+ segments = segments.subset(keep)
241
+ return PrimitiveUnion(domain, segments=segments, model=self, seed=seed_info)
242
+
243
+ def expected_count(self, domain: Domain) -> float:
244
+ """Mean number of germs (grain centres) in the domain."""
245
+ return self.theta * domain.volume
246
+
247
+ def theory(self, domain: Domain | None = None) -> dict[str, float]:
248
+ theta = self.theta
249
+ q = math.exp(-theta * self.mean_grain_volume)
250
+ return {
251
+ "intensity": theta,
252
+ "volume_fraction": 1.0 - q,
253
+ "specific_surface": theta * q * self.mean_grain_surface,
254
+ "integral_range": self.integral_range(),
255
+ }
256
+
257
+ def _covariogram(self, h, angle) -> np.ndarray:
258
+ """``E_{r,l}[K]`` at the distances ``h`` and angles ``angle`` to the axis
259
+ (broadcasting): ``(l - h cos b)+ lens(h sin b)`` for cylinders, the expectations over
260
+ the lengths and the radii apart (32 quantiles each when random); the integral of
261
+ the lens of the sections for spherocylinders (6 quantiles of each when random)."""
262
+ along, across = h * np.cos(angle), h * np.sin(angle)
263
+ if self.caps == "flat":
264
+ ls, wl = self.length.quadrature(32)
265
+ rs, wr = self.radius.quadrature(32)
266
+ reach = sum(w * np.maximum(x - along, 0.0) for x, w in zip(ls, wl, strict=True))
267
+ lens = sum(
268
+ w * theory.disk_intersection_area(across, x) for x, w in zip(rs, wr, strict=True)
269
+ )
270
+ return reach * lens
271
+ out = np.zeros(np.broadcast_shapes(np.shape(along), np.shape(across)))
272
+ for r, wr in zip(*self.radius.quadrature(6), strict=True):
273
+ for ell, wl in zip(*self.length.quadrature(6), strict=True):
274
+ out += wr * wl * theory.spherocylinder_covariogram(along, across, r, ell)
275
+ return out
276
+
277
+ def mean_covariogram(self, h, direction=None) -> np.ndarray:
278
+ """``E[K(h)] = E|K ∩ (K + h)|``, the mean geometric covariogram of the fibres over
279
+ their radii, lengths and axes, for ``h`` of the lengths ``h`` along ``direction``
280
+ (averaged over the directions without one): ``K = (l - |h·u|)+ lens(|h × u|)`` for
281
+ cylinders (Peyrega et al. 2009, eq. 15), the integral along the axis of the lens of
282
+ the sections for spherocylinders (:func:`morphogen.theory.spherocylinder_covariogram`);
283
+ ``E[K(0)] = E[V]`` and ``int E[K(h)] dh = E[V^2]``."""
284
+ h = np.abs(np.asarray(h, dtype=float))
285
+ b, w = angle_weights(self.orientation, direction)
286
+ return (self._covariogram(h.reshape(-1, 1), b[None, :]) @ w).reshape(h.shape)
287
+
288
+ def covariance(self, h, direction=None) -> np.ndarray:
289
+ """``C(h) = P(x in A, x + h in A) = 1 - 2q + q^2 exp(theta E[K(h)])`` along
290
+ ``direction`` (any for isotropic axes), or averaged over the directions of ``h``
291
+ without one (:func:`morphogen.theory.oriented_covariance`)."""
292
+ theta = self.theta
293
+ q = math.exp(-theta * self.mean_grain_volume)
294
+ return theory.oriented_covariance(
295
+ q, theta, self._covariogram, h, self.orientation, direction
296
+ )
297
+
298
+ def integral_range(self) -> float:
299
+ """``A3 = int (C(h) - p^2) dh / (p q)`` over the space: ``4 pi int h^2 (C̄(h) - p^2)
300
+ dh / (p q)``, ``C̄`` the covariance averaged over the directions (96 Gauss-Legendre
301
+ distances up to the largest extent of a fibre); the mean volume of the fibres
302
+ weighted by their volumes, ``E[V^2] / E[V]``, as ``p -> 0``."""
303
+ theta = self.theta
304
+ q = math.exp(-theta * self.mean_grain_volume)
305
+ p = 1.0 - q
306
+ reach = self.length.upper() + 2.0 * self.radius.upper()
307
+ x, w = np.polynomial.legendre.leggauss(96)
308
+ h, w = 0.5 * reach * (x + 1.0), 0.5 * reach * w
309
+ centred = self.covariance(h) - p * p
310
+ return float(np.sum(w * 4.0 * math.pi * h * h * centred) / (p * q))
@@ -0,0 +1,331 @@
1
+ """Bouligand structures: twisted plywoods of fibres.
2
+
3
+ The fibrous composites of arthropod cuticles (chitin), of fish scales and of the
4
+ osteons of bone (collagen) stack layers of parallel fibres, each layer turned by a
5
+ small angle from the one below (Bouligand 1972): the fibre direction describes a
6
+ helicoid along the stacking axis. Cracks follow the twisting fibres, which spreads the
7
+ damage and makes the dactyl club of the mantis shrimp so impact tolerant (Weaver et al.
8
+ 2012); helicoidal laminates of carbon fibres borrow the arrangement.
9
+
10
+ Layer ``k`` (thickness ``h``) holds parallel cylinders of radius ``r`` at the spacing
11
+ ``s``, in the direction ``theta_0 + k delta`` (``delta``: the pitch angle) at a random
12
+ offset. The fibres of a layer do not overlap (``2 r <= s``), nor those of consecutive
13
+ layers (``2 r <= h``): the volume fraction of fibres is ``pi r^2 / (s h)``.
14
+
15
+ A periodic box holds a whole number of half-turns of the helicoid, and fibre families
16
+ that are periodic in its plane: the fibres normal to ``(a / L_u, b / L_v)`` (integers
17
+ ``a``, ``b``) at the spacing ``1 / |(a / L_u, b / L_v)|``. The number of layers and the
18
+ pitch are those closest to the asked thickness and pitch, and each layer takes the
19
+ periodic family closest to its direction and spacing (a larger box gets closer); the
20
+ directions and spacings taken are those of the realization.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import math
26
+ import warnings
27
+ from dataclasses import dataclass
28
+ from typing import ClassVar
29
+
30
+ import numpy as np
31
+
32
+ from morphogen._utils import check_positive
33
+ from morphogen.domain import Domain, Grid
34
+ from morphogen.image import VoxelImage
35
+ from morphogen.models.base import Microstructure, Model, param, register, register_kind
36
+ from morphogen.models.planar import axis_centres, pixel_centres, plane_axes
37
+ from morphogen.seeding import SeedLike, make_rng
38
+
39
+
40
+ def periodic_families(lengths, spacing: float, least: float):
41
+ """Fibre families that are periodic in a rectangle of sides ``lengths``: the fibre
42
+ direction (degrees, in ``[0, 180)``) and the spacing of each, at least ``least``."""
43
+ lu, lv = (float(x) for x in lengths)
44
+ a_max = math.ceil(3.0 * lu / spacing) + 1
45
+ b_max = math.ceil(3.0 * lv / spacing) + 1
46
+ a, b = np.meshgrid(np.arange(-a_max, a_max + 1), np.arange(0, b_max + 1), indexing="ij")
47
+ a, b = a.ravel(), b.ravel()
48
+ keep = (b > 0) | (a > 0)
49
+ a, b = a[keep], b[keep]
50
+ nu, nv = a / lu, b / lv
51
+ s = 1.0 / np.hypot(nu, nv)
52
+ ok = s >= least
53
+ normal = np.degrees(np.arctan2(nv[ok], nu[ok]))
54
+ return np.mod(normal - 90.0, 180.0), s[ok]
55
+
56
+
57
+ def _angle_gap(a, b):
58
+ """Difference of fibre directions (degrees, modulo 180)."""
59
+ return np.abs((np.asarray(a) - b + 90.0) % 180.0 - 90.0)
60
+
61
+
62
+ @register_kind
63
+ class BouligandStructure(Microstructure):
64
+ """Layers of parallel fibres along ``axis``: layer ``k`` spans ``[z0 + k h, z0 + (k +
65
+ 1) h)``, its fibres the cylinders of radius ``r`` around the lines of its mid-plane
66
+ in the direction ``angles[k]`` (degrees from the first axis of the plane), at the
67
+ spacing ``spacings[k]``, one of them through ``offsets[k]`` along their normal."""
68
+
69
+ kind = "bouligand"
70
+
71
+ def __init__(self, domain, axis, radius, thickness, origin, angles, spacings, offsets, **kw):
72
+ super().__init__(domain, **kw)
73
+ self.axis = int(axis)
74
+ self.radius = float(radius)
75
+ self.thickness = float(thickness)
76
+ self.origin = float(origin)
77
+ self.angles = np.asarray(angles, dtype=float).reshape(-1)
78
+ self.spacings = np.asarray(spacings, dtype=float).reshape(-1)
79
+ self.offsets = np.asarray(offsets, dtype=float).reshape(-1)
80
+ t = np.radians(self.angles)
81
+ self.normals = np.column_stack([-np.sin(t), np.cos(t)])
82
+
83
+ @property
84
+ def n_layers(self) -> int:
85
+ return len(self.angles)
86
+
87
+ def _layer(self, j: np.ndarray) -> np.ndarray:
88
+ if self.domain.periodic:
89
+ return np.mod(j, self.n_layers)
90
+ return np.where((j >= 0) & (j < self.n_layers), j, -1)
91
+
92
+ def _distance(self, plane: np.ndarray, z: np.ndarray, j: np.ndarray) -> np.ndarray:
93
+ """Distance to the nearest fibre axis of the layers ``j`` (``inf``: none)."""
94
+ k = self._layer(j)
95
+ out = np.full(len(z), np.inf)
96
+ ok = k >= 0
97
+ kk = k[ok]
98
+ u = np.einsum("ij,ij->i", plane[ok], self.normals[kk]) - self.offsets[kk]
99
+ du = u - self.spacings[kk] * np.round(u / self.spacings[kk])
100
+ dz = z[ok] - (self.origin + (j[ok] + 0.5) * self.thickness)
101
+ out[ok] = np.hypot(du, dz)
102
+ return out
103
+
104
+ def level_set_at(self, points, reach: float = np.inf) -> np.ndarray:
105
+ """The signed distance to the fibres (negative inside)."""
106
+ return self.signed_distance(points)
107
+
108
+ def signed_distance(self, points) -> np.ndarray:
109
+ """Distance to the fibres (negative inside): the distance to the nearest axis of
110
+ the layers around each point, minus the radius."""
111
+ pts = np.asarray(points, dtype=float).reshape(-1, 3)
112
+ if self.domain.periodic:
113
+ pts = self.domain.wrap(pts)
114
+ b, c = plane_axes(self.axis)
115
+ z = pts[:, self.axis]
116
+ j = np.floor((z - self.origin) / self.thickness).astype(np.int64)
117
+ plane = pts[:, [b, c]]
118
+ d = np.minimum.reduce([self._distance(plane, z, j + s) for s in (-1, 0, 1)])
119
+ return d - self.radius
120
+
121
+ def contains(self, points) -> np.ndarray:
122
+ return self.signed_distance(points) <= 0.0
123
+
124
+ def _field(self, grid: Grid) -> np.ndarray:
125
+ b, c = plane_axes(self.axis)
126
+ plane, shape = pixel_centres(grid, (b, c))
127
+ z = axis_centres(grid, self.axis)
128
+ out = np.empty((len(z), *shape), dtype=np.float32)
129
+ for i, zi in enumerate(z):
130
+ j0 = math.floor((zi - self.origin) / self.thickness)
131
+ zz = np.full(len(plane), zi)
132
+ d = np.minimum.reduce(
133
+ [self._distance(plane, zz, np.full(len(plane), j0 + s)) for s in (-1, 0, 1)]
134
+ )
135
+ out[i] = (d - self.radius).reshape(shape)
136
+ return np.moveaxis(out, 0, self.axis)
137
+
138
+ def voxelize(self, shape=None, *, voxel_size=None, grid: Grid | None = None, supersampling=1):
139
+ grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
140
+ ss = int(supersampling)
141
+ if ss == 1:
142
+ data = (self._field(grid) <= 0).astype(np.uint8)
143
+ return VoxelImage.from_grid(data, grid, name="phase", metadata=self.image_metadata())
144
+ if not 1 <= ss <= 6:
145
+ raise ValueError("supersampling must be an integer between 1 and 6")
146
+ fine = Grid(grid.domain, tuple(n * ss for n in grid.shape))
147
+ ph = (self._field(fine) <= 0).astype(np.float32)
148
+ nx, ny, nz = grid.shape
149
+ data = ph.reshape(nx, ss, ny, ss, nz, ss).mean(axis=(1, 3, 5), dtype=np.float32)
150
+ return VoxelImage.from_grid(data, grid, name="fraction", metadata=self.image_metadata())
151
+
152
+ def level_set(self, shape=None, *, voxel_size=None, grid: Grid | None = None) -> VoxelImage:
153
+ """Signed distance to the fibres (exact: the union of the cylinders of the
154
+ layers around each point)."""
155
+ grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
156
+ far = np.float32(np.max(grid.domain.lengths))
157
+ data = np.minimum(self._field(grid), far)
158
+ return VoxelImage.from_grid(data, grid, name="level_set", metadata=self.image_metadata())
159
+
160
+ def summary(self) -> dict:
161
+ fraction = np.mean(math.pi * self.radius**2 / (self.spacings * self.thickness))
162
+ return {
163
+ "n_layers": self.n_layers,
164
+ "pitch_angle": float(self.pitch_angle),
165
+ "fiber_fraction": float(fraction),
166
+ }
167
+
168
+ @property
169
+ def pitch_angle(self) -> float:
170
+ """Mean rotation from one layer to the next (degrees)."""
171
+ if self.n_layers < 2:
172
+ return 0.0
173
+ turns = (np.diff(self.angles) + 90.0) % 180.0 - 90.0
174
+ return float(np.mean(turns))
175
+
176
+ def _geometry(self) -> dict:
177
+ return {
178
+ "axis": self.axis,
179
+ "radius": self.radius,
180
+ "thickness": self.thickness,
181
+ "origin": self.origin,
182
+ "angles": self.angles.tolist(),
183
+ "spacings": self.spacings.tolist(),
184
+ "offsets": self.offsets.tolist(),
185
+ }
186
+
187
+ @classmethod
188
+ def _from_geometry(cls, domain, geometry, **kwargs):
189
+ return cls(
190
+ domain,
191
+ geometry["axis"],
192
+ geometry["radius"],
193
+ geometry["thickness"],
194
+ geometry["origin"],
195
+ geometry["angles"],
196
+ geometry["spacings"],
197
+ geometry["offsets"],
198
+ **kwargs,
199
+ )
200
+
201
+
202
+ @register
203
+ @dataclass(frozen=True)
204
+ class Bouligand(Model):
205
+ """Bouligand (twisted plywood) structure: layers of parallel fibres, each turned by
206
+ ``pitch_angle`` from the one below, stacked along ``axis``."""
207
+
208
+ name = "bouligand"
209
+ phases: ClassVar[dict[int, str]] = {0: "matrix", 1: "fibres"}
210
+ count_label = "layers"
211
+
212
+ fiber_radius: float = param(0.05, doc="Radius of the fibres", unit="length")
213
+ fiber_spacing: float | None = param(
214
+ None, doc="Distance between the fibres of a layer (default: 2.5 radii)", unit="length"
215
+ )
216
+ layer_thickness: float | None = param(
217
+ None, doc="Thickness of the layers (default: one fibre diameter)", unit="length"
218
+ )
219
+ pitch_angle: float = param(
220
+ 15.0, doc="Rotation of the fibres from a layer to the next (degrees)"
221
+ )
222
+ start_angle: float | None = param(
223
+ None, doc="Direction of the fibres of the first layer, in degrees from the first "
224
+ "axis of the plane (default: random)",
225
+ ) # fmt: skip
226
+ axis: int = param(2, doc="Stacking direction (0: x, 1: y, 2: z)", kind="int")
227
+
228
+ def _validate(self) -> None:
229
+ r = check_positive(self.fiber_radius, "fiber_radius")
230
+ if self.axis not in (0, 1, 2):
231
+ raise ValueError("axis: 0, 1 or 2")
232
+ if not -90.0 < self.pitch_angle <= 90.0:
233
+ raise ValueError("pitch_angle: in (-90, 90] degrees")
234
+ if self.spacing < 2.0 * r * (1 - 1e-12):
235
+ raise ValueError("fiber_spacing: at least one fibre diameter (no overlap)")
236
+ if self.thickness < 2.0 * r * (1 - 1e-12):
237
+ raise ValueError("layer_thickness: at least one fibre diameter (no overlap)")
238
+
239
+ @property
240
+ def spacing(self) -> float:
241
+ return 2.5 * self.fiber_radius if self.fiber_spacing is None else self.fiber_spacing
242
+
243
+ @property
244
+ def thickness(self) -> float:
245
+ return 2.0 * self.fiber_radius if self.layer_thickness is None else self.layer_thickness
246
+
247
+ def _stack(self, height: float) -> tuple[int, float]:
248
+ """Layers and pitch of a periodic box: whole half-turns, the closest to the
249
+ asked layer thickness and pitch angle."""
250
+ h, delta = self.thickness, self.pitch_angle
251
+ n0 = max(1, round(height / h))
252
+ best = None
253
+ for n in range(1, 2 * n0 + 4):
254
+ if height / n < 2.0 * self.fiber_radius * (1 - 1e-12):
255
+ break
256
+ m = round(n * delta / 180.0)
257
+ pitch = 180.0 * m / n
258
+ if pitch <= -90.0 or pitch > 90.0:
259
+ continue
260
+ turn = (pitch - delta) / max(abs(delta), 1.0) # relative, or in degrees near 0
261
+ cost = (math.log(height / (n * h)) / 0.1) ** 2 + (turn / 0.05) ** 2
262
+ if best is None or cost < best[0]:
263
+ best = (cost, n, pitch)
264
+ if best is None:
265
+ raise ValueError("bouligand: the box is thinner than one layer of fibres")
266
+ return best[1], best[2]
267
+
268
+ def generate(self, domain: Domain, seed: SeedLike = None) -> BouligandStructure:
269
+ rng, seed_info = make_rng(seed)
270
+ ax = self.axis
271
+ b, c = plane_axes(ax)
272
+ height = float(domain.lengths[ax])
273
+ start = rng.uniform(0.0, 180.0) if self.start_angle is None else self.start_angle
274
+ if domain.periodic:
275
+ n, pitch = self._stack(height)
276
+ thickness = height / n
277
+ if abs(thickness / self.thickness - 1) > 0.05 or abs(pitch - self.pitch_angle) > max(
278
+ 0.5, 0.05 * abs(self.pitch_angle)
279
+ ):
280
+ warnings.warn(
281
+ f"bouligand: the periodic box holds {n} layers {thickness:.4g} thick, "
282
+ f"turned by {pitch:.4g} degrees (whole half-turns); for the asked values, "
283
+ "make its height a multiple of 180 / pitch_angle layers",
284
+ RuntimeWarning,
285
+ stacklevel=2,
286
+ )
287
+ origin = float(domain.lower[ax] + rng.random() * thickness)
288
+ wanted = start + pitch * np.arange(n)
289
+ dirs, gaps = periodic_families(
290
+ domain.lengths[[b, c]], self.spacing, 2.0 * self.fiber_radius
291
+ )
292
+ angles, spacings = [], []
293
+ for w in wanted:
294
+ cost = (_angle_gap(dirs, w) / 1.0) ** 2 + (np.log(gaps / self.spacing) / 0.025) ** 2
295
+ i = int(np.argmin(cost))
296
+ angles.append(dirs[i])
297
+ spacings.append(gaps[i])
298
+ angles, spacings = np.array(angles), np.array(spacings)
299
+ else:
300
+ thickness = self.thickness
301
+ origin = float(domain.lower[ax] - rng.random() * thickness)
302
+ n = math.ceil((domain.upper[ax] - origin) / thickness)
303
+ angles = np.mod(start + self.pitch_angle * np.arange(n), 180.0)
304
+ spacings = np.full(n, self.spacing)
305
+ offsets = rng.random(n) * spacings
306
+ return BouligandStructure(
307
+ domain,
308
+ ax,
309
+ self.fiber_radius,
310
+ thickness,
311
+ origin,
312
+ angles,
313
+ spacings,
314
+ offsets,
315
+ model=self,
316
+ seed=seed_info,
317
+ )
318
+
319
+ def expected_count(self, domain: Domain) -> float:
320
+ """Number of layers across the domain."""
321
+ return float(domain.lengths[self.axis] / self.thickness)
322
+
323
+ def theory(self, domain: Domain | None = None) -> dict[str, float]:
324
+ r, s, h = self.fiber_radius, self.spacing, self.thickness
325
+ turn = 180.0 / abs(self.pitch_angle) if self.pitch_angle else math.inf
326
+ return {
327
+ "volume_fraction": math.pi * r * r / (s * h),
328
+ "specific_surface": 2.0 * math.pi * r / (s * h),
329
+ "layers_per_half_turn": turn,
330
+ "half_turn_height": turn * h,
331
+ }