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,177 @@
1
+ """Implicit functions of the phases of the microstructures: helpers.
2
+
3
+ Every realization describes each of its phases by an implicit function
4
+ (:meth:`~morphogen.models.base.Microstructure.phase_level_set`): negative inside the
5
+ phase, positive outside and zero on its boundary, so that its interfaces are those of the
6
+ model itself, at any resolution, and not those of a voxel image: conforming meshes
7
+ (:func:`morphogen.mesh.conforming.conforming_mesh`), surfaces and sections are cut from
8
+ them. The functions are exact where it matters, on the interfaces and around them: signed
9
+ distances to unions of spheres and segments, distances to the faces of cells, minima and
10
+ maxima of the functions of the components of a combination (the union, intersection and
11
+ difference of sets); away from the interfaces they are clipped to a band or only keep
12
+ their sign.
13
+
14
+ One interface gives these functions on grids and at any point:
15
+
16
+ * :meth:`~morphogen.models.base.Microstructure.implicit_phases`: the phases;
17
+ * :meth:`~morphogen.models.base.Microstructure.phase_level_set`: the function of a phase
18
+ at the centres of the voxels of a grid, clipped to a band of four voxels;
19
+ * :meth:`~morphogen.models.base.Microstructure.phase_level_sets_at`: the functions of all
20
+ the phases at any points, ``{k: phi_k}``, exact within a ``reach`` of the interfaces
21
+ (the same values at the centres of the voxels): those that the exact meshes cut and
22
+ that the curved elements follow; NotImplementedError for the structures whose
23
+ functions are those of grids only (:func:`point_functions`);
24
+ * ``level_set`` and ``level_set_at``: the function of phase 1, on a grid and at points;
25
+ ``implicit_at(phase, points, band)``: one phase of ``phase_level_sets_at``, clipped
26
+ (None without point-wise functions);
27
+ * ``lipschitz``: a bound of the slopes of the point-wise functions;
28
+ * :meth:`~morphogen.models.base.Microstructure.implicit_pieces`: the smooth pieces of the
29
+ phases of the structures whose functions have folds (:mod:`morphogen.models.pieces`).
30
+
31
+ The helpers of this module evaluate on the points of a regular grid (the centres of the
32
+ voxels of a :class:`~morphogen.domain.Grid`, which may extend beyond the box of a periodic
33
+ microstructure: the nodes of a background mesh) the functions of objects that cover one
34
+ another in an order: the leaves of a dead-leaves model, the osteons of a cross-section.
35
+ """
36
+
37
+ from __future__ import annotations
38
+
39
+ import math
40
+
41
+ import numpy as np
42
+
43
+ from morphogen.domain import Grid
44
+
45
+
46
+ def implicit_phases_of(micro) -> list[int]:
47
+ """The phases of a structure (:meth:`~morphogen.models.base.Microstructure.
48
+ implicit_phases`; 0 and 1 for an object that has a level set only)."""
49
+ phases = getattr(micro, "implicit_phases", None)
50
+ return list(phases()) if callable(phases) else [0, 1]
51
+
52
+
53
+ def functions_at(micro, points, reach: float) -> dict[int, np.ndarray]:
54
+ """The functions of all the phases of a structure at points
55
+ (:meth:`~morphogen.models.base.Microstructure.phase_level_sets_at`; ``{1: phi, 0:
56
+ -phi}`` for an object with a ``level_set_at`` only, such as a level set written as a
57
+ function of the points)."""
58
+ sets_at = getattr(micro, "phase_level_sets_at", None)
59
+ if callable(sets_at):
60
+ return sets_at(points, reach)
61
+ phi = np.asarray(micro.level_set_at(points, reach), dtype=float)
62
+ return {0: -phi, 1: phi}
63
+
64
+
65
+ def point_functions(micro) -> bool:
66
+ """Whether a structure gives the functions of its phases at any point
67
+ (:func:`functions_at`), not only at the points of grids."""
68
+ if not callable(getattr(micro, "phase_level_sets_at", None)) and not callable(
69
+ getattr(micro, "level_set_at", None)
70
+ ):
71
+ return False
72
+ try:
73
+ functions_at(micro, np.reshape(np.asarray(micro.domain.lower, dtype=float), (1, 3)), 1.0)
74
+ except NotImplementedError:
75
+ return False
76
+ return True
77
+
78
+
79
+ #: Voxels of the band around the interfaces to which the functions are clipped
80
+ BAND = 4.0
81
+
82
+
83
+ def band_of(grid: Grid) -> float:
84
+ """The band of a grid: :data:`BAND` times its largest spacing, along the axes that it
85
+ samples with more than one voxel (a slab one voxel thick, the plane of a section, has
86
+ the band of the volume it is cut from)."""
87
+ spacing = np.asarray(grid.spacing, dtype=float)
88
+ sampled = np.array(grid.shape) > 1
89
+ return BAND * float(spacing[sampled].max() if sampled.any() else spacing.max())
90
+
91
+
92
+ def grid_key(grid: Grid) -> tuple:
93
+ """A key of the points of a grid (for the caches of the functions of all the phases,
94
+ computed together)."""
95
+ return (
96
+ tuple(int(n) for n in grid.shape),
97
+ tuple(float(v) for v in grid.origin),
98
+ tuple(float(v) for v in grid.spacing),
99
+ )
100
+
101
+
102
+ def implicit_functions(
103
+ micro, shape=None, *, voxel_size=None, grid=None
104
+ ) -> list[tuple[str, object]]:
105
+ """The implicit functions that describe a microstructure, on the voxel centres of a
106
+ grid (as :meth:`~morphogen.models.base.Microstructure.level_set`), with the suffix of
107
+ their files: its level set alone (suffix ``""``) for two phases; for several, the
108
+ function of each phase (``"_phase<k>"``), in the order of the phases."""
109
+ where = {"shape": shape, "voxel_size": voxel_size, "grid": grid}
110
+ phases = micro.implicit_phases()
111
+ if phases == [0, 1]:
112
+ return [("", micro.level_set(**where))]
113
+ return [(f"_phase{k}", micro.phase_level_set(k, **where)) for k in phases]
114
+
115
+
116
+ def lattice_boxes(centre, reach: float, grid: Grid, lengths=None, axes=(0, 1, 2)):
117
+ """The points of a grid within ``reach`` of ``centre`` along each of ``axes`` (a box
118
+ around it), for the centre and, with the ``lengths`` of a periodic box, for each of
119
+ its periodic images that comes that close to the grid: yields the slices of the points
120
+ along the axes and their coordinates from the image of the centre (one array per axis,
121
+ to broadcast)."""
122
+ ranges = []
123
+ for a, c in zip(axes, centre, strict=True):
124
+ h = float(grid.spacing[a])
125
+ x0 = float(grid.origin[a]) + 0.5 * h
126
+ n = int(grid.shape[a])
127
+ images = [0.0]
128
+ if lengths is not None:
129
+ period = float(lengths[a])
130
+ first = math.floor((x0 - reach - c) / period)
131
+ last = math.ceil((x0 + (n - 1) * h + reach - c) / period)
132
+ images = [m * period for m in range(first, last + 1)]
133
+ along = []
134
+ for shift in images:
135
+ lo = max(0, math.ceil((c + shift - reach - x0) / h - 1e-9))
136
+ hi = min(n - 1, math.floor((c + shift + reach - x0) / h + 1e-9))
137
+ if hi >= lo:
138
+ along.append((slice(lo, hi + 1), x0 + np.arange(lo, hi + 1) * h - (c + shift)))
139
+ if not along:
140
+ return
141
+ ranges.append(along)
142
+ if len(ranges) == 2:
143
+ for sa, da in ranges[0]:
144
+ for sb, db in ranges[1]:
145
+ yield (sa, sb), (da[:, None], db[None, :])
146
+ return
147
+ for sa, da in ranges[0]:
148
+ for sb, db in ranges[1]:
149
+ for sc, dc in ranges[2]:
150
+ yield (sa, sb, sc), (da[:, None, None], db[None, :, None], dc[None, None, :])
151
+
152
+
153
+ def ordered_cover(shape, band: float, objects, n_parts: int):
154
+ """The implicit functions of the visible parts of objects that cover one another, the
155
+ first on top. ``objects`` yields, in that order and for each object and each box of
156
+ points near it (:func:`lattice_boxes`), ``(slices, cover, parts)``: the implicit
157
+ function ``cover`` of the object at these points (negative inside it) and, for each
158
+ of the parts of the objects (its phases, or the rings of an osteon), its function
159
+ there, or None where the object has no such part. The visible part of an object is
160
+ what lies in it and in none of those on top: the maximum of its function and of
161
+ minus the smallest function of those on top. Returns the functions of the ``n_parts``
162
+ parts (the minimum over the objects) and the smallest function of all the objects
163
+ (positive where nothing covers), clipped to ``band``."""
164
+ parts = np.full((n_parts, *shape), band, dtype=np.float32)
165
+ top = np.full(shape, band, dtype=np.float32) # the smallest function of those on top
166
+ for slices, cover, functions in objects:
167
+ above = -top[slices]
168
+ for k, f in enumerate(functions):
169
+ if f is None:
170
+ continue
171
+ view = parts[(k, *slices)]
172
+ np.minimum(view, np.maximum(f, above), out=view)
173
+ view = top[slices]
174
+ np.minimum(view, cover, out=view)
175
+ np.clip(parts, -band, band, out=parts)
176
+ np.clip(top, -band, band, out=top)
177
+ return parts, top
@@ -0,0 +1,470 @@
1
+ """Random laminates: layers of two phases of random thicknesses, stacked along an axis,
2
+ with holes through the layers of phase 1 (breakup of thin layers).
3
+
4
+ Nanolayered films made by multilayer coextrusion are such stacks; their thinnest
5
+ layers break up into holes and fragments, which adds an in-plane scale to the scale of
6
+ the layers (Bironeau et al. 2016). The model is an alternating renewal process along the
7
+ axis: layers of phase 1 and of phase 0, of independent thicknesses ``t`` and ``s``
8
+ drawn from their distributions; each layer of phase 1 is pierced by cylindrical holes
9
+ across its thickness, a two-dimensional Boolean model of discs covering the fraction
10
+ ``q`` of its area, independent from one layer to the next.
11
+
12
+ Non-periodic boxes see a stationary stack: the layer covering the lower face is of
13
+ phase 1 with probability ``E[t] / (E[t] + E[s])``, its length is drawn from the
14
+ length-biased distribution, and the face falls uniformly in it. Along a periodic axis,
15
+ whole periods are drawn and their thicknesses scaled by a common factor (close to one
16
+ for many layers) so that they fill the box; a random shift makes the stack stationary.
17
+
18
+ With ``p = E[t] / (E[t] + E[s])`` and holes of radius ``r``:
19
+
20
+ * volume fraction: ``p (1 - q)``;
21
+ * specific surface: ``(1 - q) (2 + E[t] lambda 2 pi E[r]) / (E[t] + E[s])``, with
22
+ ``lambda = -ln(1 - q) / (pi E[r^2])`` holes per unit area of each layer;
23
+ * without holes, the volume fraction of a box of edge ``L`` along the axis has the
24
+ variance ``p (1 - p) A / L`` for large ``L`` (renewal-reward theorem), with the
25
+ one-dimensional integral range ``A = (E[s]^2 Var[t] + E[t]^2 Var[s]) /
26
+ ((E[t] + E[s]) E[t] E[s])``: ``2 E[t] E[s] / (E[t] + E[s])`` for exponential
27
+ thicknesses, 0 for constant ones. In the plane of the layers the covariance does not
28
+ decay: the variance decreases as ``1 / L`` only, not as the inverse of the volume.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import math
34
+ from dataclasses import dataclass
35
+ from typing import ClassVar
36
+
37
+ import numpy as np
38
+ from scipy.spatial import cKDTree
39
+
40
+ from morphogen import settings
41
+ from morphogen.distributions import Distribution
42
+ from morphogen.domain import Domain, Grid
43
+ from morphogen.image import VoxelImage
44
+ from morphogen.models.base import Microstructure, Model, param, register, register_kind
45
+ from morphogen.seeding import SeedLike, make_rng
46
+
47
+
48
+ def _size_biased(dist: Distribution, rng, m: int = 4096) -> float:
49
+ """A value of the length-biased distribution ``x f(x) / E[x]`` (by sampling-
50
+ importance-resampling, exact for constants)."""
51
+ if dist.is_constant:
52
+ return float(dist.mean())
53
+ x = dist.sample(rng, m)
54
+ return float(x[rng.choice(m, p=x / x.sum())])
55
+
56
+
57
+ class _Discs:
58
+ """Union of discs in the plane of a layer (periodic or not)."""
59
+
60
+ def __init__(self, centers: np.ndarray, radii: np.ndarray, lengths, periodic: bool):
61
+ self.centers = np.asarray(centers, dtype=float).reshape(-1, 2)
62
+ self.radii = np.asarray(radii, dtype=float).reshape(-1)
63
+ self.lengths = np.asarray(lengths, dtype=float)
64
+ self.periodic = periodic
65
+ self.rmax = float(self.radii.max(initial=0.0))
66
+ self._lifted = self._plane = None
67
+
68
+ def _wrap(self, p):
69
+ if not self.periodic:
70
+ return p
71
+ p = np.mod(p, self.lengths)
72
+ p[p >= self.lengths] = 0.0 # rounding of np.mod
73
+ return p
74
+
75
+ def inside(self, points: np.ndarray) -> np.ndarray:
76
+ """Whether the points (plane coordinates from the lower corner) are in a disc."""
77
+ if not len(self.radii):
78
+ return np.zeros(len(points), dtype=bool)
79
+ if self._lifted is None: # lifting: |p - c|^2 + rmax^2 - r^2 <= rmax^2
80
+ extra = np.sqrt(np.maximum(self.rmax**2 - self.radii**2, 0.0))[:, None]
81
+ box = [*self.lengths, 4.0 * self.rmax + 1.0] if self.periodic else None
82
+ self._lifted = cKDTree(np.hstack([self._wrap(self.centers), extra]), boxsize=box)
83
+ q = np.hstack([self._wrap(points), np.zeros((len(points), 1))])
84
+ dist, _ = self._lifted.query(q, k=1, workers=settings.workers())
85
+ return dist <= self.rmax * (1.0 + 1e-12)
86
+
87
+ def signed(self, points: np.ndarray) -> np.ndarray:
88
+ """``min_j |p - c_j| - r_j``: the signed distance to the union outside it,
89
+ negative inside (with the sign of the union everywhere)."""
90
+ out = np.full(len(points), np.inf)
91
+ n = len(self.radii)
92
+ if not n:
93
+ return out
94
+ if self._plane is None:
95
+ box = list(self.lengths) if self.periodic else None
96
+ self._plane = cKDTree(self._wrap(self.centers), boxsize=box)
97
+ todo, k = np.arange(len(points)), min(n, 8)
98
+ while todo.size:
99
+ dist, idx = self._plane.query(self._wrap(points[todo]), k=k)
100
+ dist, idx = dist.reshape(len(todo), k), idx.reshape(len(todo), k)
101
+ out[todo] = np.min(dist - self.radii[idx], axis=1)
102
+ # farther discs reach at most rmax inside their centre distance
103
+ again = (dist[:, -1] - self.rmax < out[todo]) & (k < n)
104
+ todo, k = todo[again], min(n, 2 * k)
105
+ return out
106
+
107
+
108
+ @register_kind
109
+ class Laminate(Microstructure):
110
+ """Layers of phase 1 (intervals along ``axis``) in phase 0, with holes."""
111
+
112
+ kind = "laminate"
113
+
114
+ def __init__(
115
+ self,
116
+ domain: Domain,
117
+ axis: int,
118
+ starts,
119
+ ends,
120
+ layer_ids=None,
121
+ hole_layers=None,
122
+ hole_centers=None,
123
+ hole_radii=None,
124
+ **kwargs,
125
+ ) -> None:
126
+ super().__init__(domain, **kwargs)
127
+ self.axis = int(axis)
128
+ self.starts = np.asarray(starts, dtype=float).reshape(-1)
129
+ self.ends = np.asarray(ends, dtype=float).reshape(-1)
130
+ order = np.argsort(self.starts)
131
+ self.starts, self.ends = self.starts[order], self.ends[order]
132
+ ids = np.arange(len(order)) if layer_ids is None else np.asarray(layer_ids)[order]
133
+ self.layer_ids = np.asarray(ids, dtype=np.int64)
134
+ self.hole_layers = np.asarray(
135
+ [] if hole_layers is None else hole_layers, dtype=np.int64
136
+ ).reshape(-1)
137
+ self.hole_centers = np.asarray(
138
+ [] if hole_centers is None else hole_centers, dtype=float
139
+ ).reshape(-1, 2)
140
+ self.hole_radii = np.asarray([] if hole_radii is None else hole_radii, dtype=float)
141
+ self._discs: dict[int, _Discs] = {}
142
+
143
+ @property
144
+ def plane_axes(self) -> tuple[int, int]:
145
+ return tuple(a for a in range(3) if a != self.axis) # type: ignore[return-value]
146
+
147
+ @property
148
+ def n_layers(self) -> int:
149
+ """Number of layers of phase 1 (a layer cut by a periodic face counts once)."""
150
+ return int(np.unique(self.layer_ids).size)
151
+
152
+ def discs(self, layer: int) -> _Discs:
153
+ """Holes of a layer, in plane coordinates from the lower corner of the box."""
154
+ if layer not in self._discs:
155
+ sel = self.hole_layers == layer
156
+ b, c = self.plane_axes
157
+ lo = self.domain.lower[[b, c]]
158
+ self._discs[layer] = _Discs(
159
+ self.hole_centers[sel] - lo,
160
+ self.hole_radii[sel],
161
+ self.domain.lengths[[b, c]],
162
+ self.domain.periodic,
163
+ )
164
+ return self._discs[layer]
165
+
166
+ # -- point classification ---------------------------------------------------------------
167
+
168
+ def _layer_at(self, z: np.ndarray) -> np.ndarray:
169
+ """Index of the interval of phase 1 containing each coordinate (-1: none)."""
170
+ k = np.searchsorted(self.starts, z, side="right") - 1
171
+ inside = (k >= 0) & (z < self.ends[np.maximum(k, 0)])
172
+ return np.where(inside, k, -1)
173
+
174
+ def _in_phase(self, z: np.ndarray, plane: np.ndarray) -> np.ndarray:
175
+ k = self._layer_at(z)
176
+ out = k >= 0
177
+ for i in np.unique(k[out]):
178
+ sel = k == i
179
+ out[sel] = ~self.discs(int(self.layer_ids[i])).inside(plane[sel])
180
+ return out
181
+
182
+ def _split(self, points: np.ndarray):
183
+ pts = np.asarray(points, dtype=float).reshape(-1, 3)
184
+ b, c = self.plane_axes
185
+ z = pts[:, self.axis]
186
+ if self.domain.periodic:
187
+ lo, length = self.domain.lower[self.axis], self.domain.lengths[self.axis]
188
+ z = lo + np.mod(z - lo, length)
189
+ return z, pts[:, [b, c]] - self.domain.lower[[b, c]]
190
+
191
+ def contains(self, points) -> np.ndarray:
192
+ return self._in_phase(*self._split(points))
193
+
194
+ # -- discretization -------------------------------------------------------------------
195
+
196
+ def _phases_on(self, grid: Grid) -> np.ndarray:
197
+ b, c = self.plane_axes
198
+ centres = [grid.domain.lower[a] + (np.arange(n) + 0.5) * h for a, n, h in
199
+ zip(range(3), grid.shape, grid.spacing, strict=True)] # fmt: skip
200
+ u, v = np.meshgrid(centres[b], centres[c], indexing="ij")
201
+ plane = np.column_stack([u.ravel(), v.ravel()]) - self.domain.lower[[b, c]]
202
+ k = self._layer_at(centres[self.axis])
203
+ out = np.zeros((grid.shape[self.axis], grid.shape[b], grid.shape[c]), dtype=np.uint8)
204
+ masks: dict[int, np.ndarray] = {}
205
+ for i, layer in enumerate(k):
206
+ if layer < 0:
207
+ continue
208
+ lid = int(self.layer_ids[layer])
209
+ if lid not in masks:
210
+ masks[lid] = (~self.discs(lid).inside(plane)).reshape(u.shape).astype(np.uint8)
211
+ out[i] = masks[lid]
212
+ return np.moveaxis(out, 0, self.axis)
213
+
214
+ def voxelize(self, shape=None, *, voxel_size=None, grid: Grid | None = None, supersampling=1):
215
+ grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
216
+ ss = int(supersampling)
217
+ if ss == 1:
218
+ data = self._phases_on(grid)
219
+ return VoxelImage.from_grid(data, grid, name="phase", metadata=self.image_metadata())
220
+ if not 1 <= ss <= 6:
221
+ raise ValueError("supersampling must be an integer between 1 and 6")
222
+ fine = Grid(grid.domain, tuple(n * ss for n in grid.shape))
223
+ ph = self._phases_on(fine).astype(np.float32)
224
+ nx, ny, nz = grid.shape
225
+ data = ph.reshape(nx, ss, ny, ss, nz, ss).mean(axis=(1, 3, 5), dtype=np.float32)
226
+ return VoxelImage.from_grid(data, grid, name="fraction", metadata=self.image_metadata())
227
+
228
+ def level_set(self, shape=None, *, voxel_size=None, grid: Grid | None = None) -> VoxelImage:
229
+ """Minimum over the layers of phase 1 of ``max(slab, -holes)``: the signed distance
230
+ to the slab along the axis, and minus the signed distance to the holes in the
231
+ plane (negative in phase 1); only the layers around each point count."""
232
+ grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
233
+ b, c = self.plane_axes
234
+ centres = [grid.domain.lower[a] + (np.arange(n) + 0.5) * h for a, n, h in
235
+ zip(range(3), grid.shape, grid.spacing, strict=True)] # fmt: skip
236
+ u, v = np.meshgrid(centres[b], centres[c], indexing="ij")
237
+ plane = np.column_stack([u.ravel(), v.ravel()]) - self.domain.lower[[b, c]]
238
+ starts, ends, ids = self._extended_layers()
239
+ out = np.full((grid.shape[self.axis], *u.shape), np.inf, dtype=np.float32)
240
+ holes: dict[int, np.ndarray] = {}
241
+ for i, z in enumerate(centres[self.axis]):
242
+ k = int(np.searchsorted(starts, z, side="right")) - 1
243
+ for j in (k, k + 1): # the layer below (or containing) and the one above
244
+ if not 0 <= j < len(starts):
245
+ continue
246
+ slab = max(starts[j] - z, z - ends[j])
247
+ lid = int(ids[j])
248
+ if lid not in holes:
249
+ holes[lid] = -self.discs(lid).signed(plane).reshape(u.shape)
250
+ out[i] = np.minimum(out[i], np.maximum(slab, holes[lid]))
251
+ out = np.minimum(out, np.float32(np.max(grid.domain.lengths))) # no layer: far
252
+ data = np.moveaxis(out, 0, self.axis)
253
+ return VoxelImage.from_grid(data, grid, name="level_set", metadata=self.image_metadata())
254
+
255
+ def _extended_layers(self):
256
+ """The layers of phase 1 (starts, ends, ids), with those of the neighbouring periods
257
+ of a periodic domain, joined at its faces."""
258
+ starts, ends, ids = self.starts, self.ends, self.layer_ids
259
+ if self.domain.periodic:
260
+ length = self.domain.lengths[self.axis]
261
+ starts = np.concatenate([starts - length, starts, starts + length])
262
+ ends = np.concatenate([ends - length, ends, ends + length])
263
+ ids = np.tile(ids, 3)
264
+ cut = np.flatnonzero(
265
+ (np.abs(ends[:-1] - starts[1:]) <= 1e-12 * length) & (ids[:-1] == ids[1:])
266
+ )
267
+ ends[cut] = ends[cut + 1]
268
+ keep = np.ones(len(starts), dtype=bool)
269
+ keep[cut + 1] = False
270
+ starts, ends, ids = starts[keep], ends[keep], ids[keep]
271
+ return starts, ends, ids
272
+
273
+ def level_set_at(self, points, reach: float = np.inf) -> np.ndarray:
274
+ """As :meth:`level_set`, at the points: the minimum over the layers around each
275
+ point of ``max(slab, -holes)``."""
276
+ z, plane = self._split(points)
277
+ starts, ends, ids = self._extended_layers()
278
+ out = np.full(len(z), np.inf)
279
+ k = np.searchsorted(starts, z, side="right") - 1
280
+ for j in (k, k + 1): # the layer below (or containing) and the one above
281
+ ok = np.flatnonzero((j >= 0) & (j < len(starts)))
282
+ for lid in np.unique(ids[j[ok]]):
283
+ sel = ok[ids[j[ok]] == lid]
284
+ slab = np.maximum(starts[j[sel]] - z[sel], z[sel] - ends[j[sel]])
285
+ holes = -self.discs(int(lid)).signed(plane[sel])
286
+ out[sel] = np.minimum(out[sel], np.maximum(slab, holes))
287
+ return np.minimum(out, float(np.max(self.domain.lengths))) # no layer: far
288
+
289
+ # -- description ------------------------------------------------------------------------
290
+
291
+ def summary(self) -> dict:
292
+ return {"n_layers": self.n_layers, "n_holes": len(self.hole_radii)}
293
+
294
+ def _geometry(self) -> dict:
295
+ return {
296
+ "axis": self.axis,
297
+ "starts": self.starts.tolist(),
298
+ "ends": self.ends.tolist(),
299
+ "layer_ids": self.layer_ids.tolist(),
300
+ "hole_layers": self.hole_layers.tolist(),
301
+ "hole_centers": self.hole_centers.tolist(),
302
+ "hole_radii": self.hole_radii.tolist(),
303
+ }
304
+
305
+ @classmethod
306
+ def _from_geometry(cls, domain, geometry, **kwargs):
307
+ return cls(
308
+ domain,
309
+ geometry["axis"],
310
+ geometry["starts"],
311
+ geometry["ends"],
312
+ geometry.get("layer_ids"),
313
+ geometry.get("hole_layers"),
314
+ geometry.get("hole_centers"),
315
+ geometry.get("hole_radii"),
316
+ **kwargs,
317
+ )
318
+
319
+
320
+ @register
321
+ @dataclass(frozen=True)
322
+ class RandomLaminate(Model):
323
+ """Layers of random thicknesses stacked along an axis, with holes through the layers
324
+ of phase 1 (nanolayered films, Bironeau et al. 2016)."""
325
+
326
+ name = "random_laminate"
327
+ phases: ClassVar[dict[int, str]] = {0: "layers of phase 0", 1: "layers of phase 1"}
328
+ count_label = "layers"
329
+
330
+ thickness: Distribution = param(
331
+ doc="Thickness of the layers of phase 1", kind="distribution", unit="length"
332
+ )
333
+ spacing: Distribution = param(
334
+ doc="Thickness of the layers of phase 0 between them", kind="distribution", unit="length"
335
+ )
336
+ axis: int = param(2, doc="Stacking direction (0: x, 1: y, 2: z)", kind="int")
337
+ hole_fraction: float = param(
338
+ 0.0,
339
+ doc="Fraction of the area of each layer of phase 1 taken by holes through it",
340
+ kind="fraction",
341
+ )
342
+ hole_radius: Distribution | None = param(
343
+ None,
344
+ doc="Radius of the holes (discs across the layers)",
345
+ kind="distribution",
346
+ unit="length",
347
+ )
348
+
349
+ def _validate(self) -> None:
350
+ if self.axis not in (0, 1, 2):
351
+ raise ValueError("axis: 0, 1 or 2")
352
+ if not 0.0 <= self.hole_fraction < 1.0:
353
+ raise ValueError(f"hole_fraction: must lie in [0, 1), got {self.hole_fraction!r}")
354
+ if self.hole_fraction > 0 and self.hole_radius is None:
355
+ raise ValueError("hole_radius: needed for holes (hole_fraction > 0)")
356
+
357
+ @property
358
+ def period(self) -> float:
359
+ """Mean thickness of a pair of layers."""
360
+ return self.thickness.mean() + self.spacing.mean()
361
+
362
+ def _hole_intensity(self) -> float:
363
+ if not self.hole_fraction > 0:
364
+ return 0.0
365
+ return -math.log1p(-self.hole_fraction) / (math.pi * self.hole_radius.moment(2))
366
+
367
+ def _stack(self, rng, lower: float, length: float, periodic: bool):
368
+ """Intervals of phase 1 along the axis, with their layer ids."""
369
+ t, s = self.thickness, self.spacing
370
+ if periodic:
371
+ pairs = []
372
+ total = 0.0
373
+ while total < length:
374
+ pairs.append((float(t.sample(rng, 1)[0]), float(s.sample(rng, 1)[0])))
375
+ total += sum(pairs[-1])
376
+ # the number of whole periods whose total is the closest to the box
377
+ sums = np.cumsum([a + b for a, b in pairs])
378
+ n = len(sums)
379
+ if n > 1 and abs(sums[-2] - length) < abs(sums[-1] - length):
380
+ n -= 1
381
+ scale = length / sums[n - 1]
382
+ shift = rng.random() * length
383
+ starts, ends, ids = [], [], []
384
+ z = shift
385
+ for i, (a, b) in enumerate(pairs[:n]):
386
+ z0, z1 = z, z + a * scale
387
+ for lo, hi in ((z0, z1), (z0 - length, z1 - length)): # wrapped at the top
388
+ lo, hi = max(lo, 0.0), min(hi, length)
389
+ if hi > lo:
390
+ starts.append(lower + lo)
391
+ ends.append(lower + hi)
392
+ ids.append(i)
393
+ z = (z1 + b * scale) % length
394
+ return np.array(starts), np.array(ends), np.array(ids, dtype=np.int64), scale
395
+ # stationary start: the layer covering the lower face, cut by it
396
+ mt, ms = t.mean(), s.mean()
397
+ phase = int(rng.random() < mt / (mt + ms))
398
+ first = _size_biased(t if phase else s, rng) * (1.0 - rng.random())
399
+ starts, ends = [], []
400
+ z = 0.0
401
+ width = first
402
+ while z < length:
403
+ if phase:
404
+ starts.append(lower + z)
405
+ ends.append(lower + min(z + width, length))
406
+ z += width
407
+ phase = 1 - phase
408
+ width = float((t if phase else s).sample(rng, 1)[0])
409
+ return np.array(starts), np.array(ends), np.arange(len(starts)), 1.0
410
+
411
+ def generate(self, domain: Domain, seed: SeedLike = None) -> Laminate:
412
+ self._check_domain(domain)
413
+ rng, seed_info = make_rng(seed)
414
+ a = self.axis
415
+ starts, ends, ids, scale = self._stack(
416
+ rng, float(domain.lower[a]), float(domain.lengths[a]), domain.periodic
417
+ )
418
+ b, c = (d for d in range(3) if d != a)
419
+ lam = self._hole_intensity()
420
+ layers, centres, radii = [], [], []
421
+ if lam > 0:
422
+ rmax = self.hole_radius.upper()
423
+ margin = 0.0 if domain.periodic else rmax
424
+ lo = domain.lower[[b, c]] - margin
425
+ size = domain.lengths[[b, c]] + 2.0 * margin
426
+ for layer in np.unique(ids):
427
+ n = rng.poisson(lam * size[0] * size[1])
428
+ layers.append(np.full(n, layer))
429
+ centres.append(lo + rng.random((n, 2)) * size)
430
+ radii.append(self.hole_radius.sample(rng, n))
431
+ metadata = {"thickness_scale": scale} if domain.periodic else None
432
+ return Laminate(
433
+ domain,
434
+ a,
435
+ starts,
436
+ ends,
437
+ ids,
438
+ np.concatenate(layers) if layers else None,
439
+ np.concatenate(centres) if centres else None,
440
+ np.concatenate(radii) if radii else None,
441
+ model=self,
442
+ seed=seed_info,
443
+ metadata=metadata,
444
+ )
445
+
446
+ def expected_count(self, domain: Domain) -> float:
447
+ """Mean number of layers of phase 1 across the domain."""
448
+ return float(domain.lengths[self.axis]) / self.period
449
+
450
+ def theory(self, domain: Domain | None = None) -> dict[str, float]:
451
+ mt, ms = self.thickness.mean(), self.spacing.mean()
452
+ p = mt / (mt + ms)
453
+ q = self.hole_fraction
454
+ walls = (
455
+ mt
456
+ * self._hole_intensity()
457
+ * 2.0
458
+ * math.pi
459
+ * (self.hole_radius.mean() if q > 0 else 0.0)
460
+ )
461
+ out = {
462
+ "volume_fraction": p * (1.0 - q),
463
+ "specific_surface": (1.0 - q) * (2.0 + walls) / (mt + ms),
464
+ "layer_period": mt + ms,
465
+ "integral_range": math.inf,
466
+ }
467
+ if q == 0:
468
+ vt, vs = self.thickness.std() ** 2, self.spacing.std() ** 2
469
+ out["integral_range_1d"] = (ms**2 * vt + mt**2 * vs) / ((mt + ms) * mt * ms)
470
+ return out