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.
- morphogen/__init__.py +60 -0
- morphogen/__main__.py +7 -0
- morphogen/_platform.py +55 -0
- morphogen/_public.py +153 -0
- morphogen/_utils.py +80 -0
- morphogen/_version.py +1 -0
- morphogen/analysis/__init__.py +174 -0
- morphogen/analysis/anisotropy.py +135 -0
- morphogen/analysis/basic.py +38 -0
- morphogen/analysis/cells.py +54 -0
- morphogen/analysis/connectivity.py +156 -0
- morphogen/analysis/correlation.py +195 -0
- morphogen/analysis/covariance.py +80 -0
- morphogen/analysis/fractal.py +54 -0
- morphogen/analysis/measures.py +188 -0
- morphogen/analysis/morphology.py +265 -0
- morphogen/analysis/particles.py +160 -0
- morphogen/analysis/percolation.py +2034 -0
- morphogen/analysis/power_laws.py +143 -0
- morphogen/analysis/random_sets.py +351 -0
- morphogen/analysis/stereology.py +289 -0
- morphogen/analysis/surface.py +107 -0
- morphogen/analysis/topology.py +92 -0
- morphogen/automata/__init__.py +74 -0
- morphogen/automata/engine.py +211 -0
- morphogen/automata/growth.py +686 -0
- morphogen/automata/lattice.py +143 -0
- morphogen/automata/reaction.py +255 -0
- morphogen/automata/rules.py +353 -0
- morphogen/automata/tilings.py +1715 -0
- morphogen/cli.py +3526 -0
- morphogen/config.py +2167 -0
- morphogen/contact/__init__.py +113 -0
- morphogen/contact/experiments.py +368 -0
- morphogen/contact/hertz.py +104 -0
- morphogen/contact/kernels.py +827 -0
- morphogen/contact/periodic.py +278 -0
- morphogen/contact/problem.py +578 -0
- morphogen/contact/surfaces.py +310 -0
- morphogen/coupling/__init__.py +43 -0
- morphogen/coupling/ageing.py +143 -0
- morphogen/coupling/diffusion.py +226 -0
- morphogen/coupling/fenicsx.py +484 -0
- morphogen/coupling/oxidation.py +447 -0
- morphogen/coupling/plates.py +247 -0
- morphogen/design/__init__.py +51 -0
- morphogen/design/csp.py +616 -0
- morphogen/design/frames.py +277 -0
- morphogen/design/search.py +287 -0
- morphogen/design/tiles.py +336 -0
- morphogen/distributions.py +312 -0
- morphogen/domain.py +203 -0
- morphogen/dynamics/__init__.py +179 -0
- morphogen/dynamics/model.py +638 -0
- morphogen/dynamics/openradioss.py +643 -0
- morphogen/dynamics/results.py +515 -0
- morphogen/fracture/__init__.py +170 -0
- morphogen/fracture/bulk.py +349 -0
- morphogen/fracture/cohesive.py +1614 -0
- morphogen/fracture/ductile.py +557 -0
- morphogen/fracture/lefm.py +1168 -0
- morphogen/fracture/mixed.py +1178 -0
- morphogen/fracture/periodic.py +733 -0
- morphogen/fracture/phasefield.py +714 -0
- morphogen/fracture/phasefield_finite.py +368 -0
- morphogen/fracture/surface.py +572 -0
- morphogen/fracture/toughness.py +566 -0
- morphogen/gpu.py +108 -0
- morphogen/gui/__init__.py +8 -0
- morphogen/gui/api.py +1927 -0
- morphogen/gui/desktop.py +387 -0
- morphogen/gui/icon.png +0 -0
- morphogen/gui/index.html +1909 -0
- morphogen/gui/server.py +229 -0
- morphogen/gui/tools/__init__.py +629 -0
- morphogen/gui/tools/compare.py +149 -0
- morphogen/gui/tools/contact.py +391 -0
- morphogen/gui/tools/couplings.py +1085 -0
- morphogen/gui/tools/crackfront.py +245 -0
- morphogen/gui/tools/design.py +224 -0
- morphogen/gui/tools/dynamics.py +824 -0
- morphogen/gui/tools/fracture.py +2586 -0
- morphogen/gui/tools/interop.py +1654 -0
- morphogen/gui/tools/learning.py +595 -0
- morphogen/gui/tools/mechanics.py +3881 -0
- morphogen/gui/tools/nonlocal_damage.py +1321 -0
- morphogen/gui/tools/phasefield.py +215 -0
- morphogen/gui/tools/physics.py +597 -0
- morphogen/gui/tools/stability.py +1756 -0
- morphogen/gui/tools/statistics.py +1408 -0
- morphogen/gui/viewer.js +1100 -0
- morphogen/homogenization/__init__.py +210 -0
- morphogen/homogenization/acoustics.py +566 -0
- morphogen/homogenization/amg.py +1005 -0
- morphogen/homogenization/apparent.py +1046 -0
- morphogen/homogenization/behaviours.cu +2285 -0
- morphogen/homogenization/behaviours.py +944 -0
- morphogen/homogenization/beremin.py +263 -0
- morphogen/homogenization/bifurcation.py +1085 -0
- morphogen/homogenization/bloch.py +507 -0
- morphogen/homogenization/bounds.py +226 -0
- morphogen/homogenization/core.py +458 -0
- morphogen/homogenization/coupled.py +1135 -0
- morphogen/homogenization/crystal.py +2967 -0
- morphogen/homogenization/dilatation.py +454 -0
- morphogen/homogenization/elements.py +157 -0
- morphogen/homogenization/fatigue.py +768 -0
- morphogen/homogenization/fe.py +1739 -0
- morphogen/homogenization/fenicsx.py +307 -0
- morphogen/homogenization/fft.py +499 -0
- morphogen/homogenization/fft_nonlinear.py +391 -0
- morphogen/homogenization/finite.py +613 -0
- morphogen/homogenization/flow.py +361 -0
- morphogen/homogenization/frames.py +1125 -0
- morphogen/homogenization/gpu.py +1241 -0
- morphogen/homogenization/harmonic.py +427 -0
- morphogen/homogenization/identification.py +579 -0
- morphogen/homogenization/kernels.py +760 -0
- morphogen/homogenization/laws.py +2061 -0
- morphogen/homogenization/materials.py +1080 -0
- morphogen/homogenization/mfront.py +589 -0
- morphogen/homogenization/networks.py +880 -0
- morphogen/homogenization/nonlinear.py +2612 -0
- morphogen/homogenization/ntfa.py +577 -0
- morphogen/homogenization/paths.py +476 -0
- morphogen/homogenization/photonic.py +467 -0
- morphogen/homogenization/poroelastic.py +212 -0
- morphogen/homogenization/porous.py +1120 -0
- morphogen/homogenization/postprocess.py +290 -0
- morphogen/homogenization/solvers.py +1140 -0
- morphogen/homogenization/tensors.py +240 -0
- morphogen/homogenization/voxel_fe.py +457 -0
- morphogen/homogenization/xfem.py +1016 -0
- morphogen/homogenization/zmat.py +1258 -0
- morphogen/iga/__init__.py +48 -0
- morphogen/iga/analysis.py +508 -0
- morphogen/iga/basis.py +214 -0
- morphogen/iga/geometry.py +501 -0
- morphogen/iga/homogenization.py +219 -0
- morphogen/iga/optimization.py +700 -0
- morphogen/iga/shapes.py +331 -0
- morphogen/image.py +128 -0
- morphogen/io/__init__.py +246 -0
- morphogen/io/amitex.py +741 -0
- morphogen/io/ebsd.py +881 -0
- morphogen/io/export.py +196 -0
- morphogen/io/geometry.py +158 -0
- morphogen/io/medit.py +147 -0
- morphogen/io/meshes.py +844 -0
- morphogen/io/metaimage.py +97 -0
- morphogen/io/mfront.py +1104 -0
- morphogen/io/native.py +57 -0
- morphogen/io/radioss.py +764 -0
- morphogen/io/solvers.py +371 -0
- morphogen/io/tables.py +278 -0
- morphogen/io/tiff.py +66 -0
- morphogen/io/vtk.py +701 -0
- morphogen/io/xdmf.py +200 -0
- morphogen/kernels/__init__.py +5 -0
- morphogen/kernels/annealing.py +192 -0
- morphogen/kernels/cells.py +69 -0
- morphogen/kernels/collective.py +87 -0
- morphogen/kernels/force_biased.py +595 -0
- morphogen/kernels/implicit.py +145 -0
- morphogen/kernels/leaves.py +132 -0
- morphogen/kernels/packing.py +304 -0
- morphogen/kernels/raster.py +279 -0
- morphogen/kernels/rsa.py +371 -0
- morphogen/kernels/union.py +135 -0
- morphogen/kernels/watershed.py +190 -0
- morphogen/laser/__init__.py +234 -0
- morphogen/laser/architectures.py +375 -0
- morphogen/laser/bending.py +216 -0
- morphogen/laser/cells.py +1694 -0
- morphogen/laser/design.py +940 -0
- morphogen/laser/figures.py +227 -0
- morphogen/laser/heat.py +804 -0
- morphogen/laser/materials.py +691 -0
- morphogen/laser/mechanics.py +1670 -0
- morphogen/laser/metallurgy.py +615 -0
- morphogen/laser/patterns.py +828 -0
- morphogen/laser/periodic.py +392 -0
- morphogen/laser/process.py +362 -0
- morphogen/laser/run.py +534 -0
- morphogen/laser/solid.py +216 -0
- morphogen/laser/specimen.py +200 -0
- morphogen/laser/structures.py +708 -0
- morphogen/learning/__init__.py +81 -0
- morphogen/learning/behaviour.py +398 -0
- morphogen/learning/data.py +328 -0
- morphogen/learning/learned.cpp +668 -0
- morphogen/learning/logarithmic.py +202 -0
- morphogen/learning/mfront.py +409 -0
- morphogen/learning/networks.py +767 -0
- morphogen/learning/run.py +212 -0
- morphogen/learning/standard.py +814 -0
- morphogen/learning/training.py +235 -0
- morphogen/mesh/__init__.py +29 -0
- morphogen/mesh/conforming.py +1423 -0
- morphogen/mesh/curved.py +600 -0
- morphogen/mesh/exact.py +1717 -0
- morphogen/mesh/octree.py +350 -0
- morphogen/mesh/polycrystal.py +1041 -0
- morphogen/mesh/polyhedra.py +677 -0
- morphogen/mesh/regularize.py +570 -0
- morphogen/mesh/surface.py +97 -0
- morphogen/mesh/tetra.py +512 -0
- morphogen/mesh/voxel.py +124 -0
- morphogen/micromorphic/__init__.py +31 -0
- morphogen/micromorphic/damage.py +359 -0
- morphogen/micromorphic/ductile.py +534 -0
- morphogen/micromorphic/finite.py +220 -0
- morphogen/micromorphic/microfoam.py +787 -0
- morphogen/micromorphic/space.py +341 -0
- morphogen/models/__init__.py +195 -0
- morphogen/models/affine.py +384 -0
- morphogen/models/automata.py +592 -0
- morphogen/models/base.py +500 -0
- morphogen/models/boolean.py +310 -0
- morphogen/models/bouligand.py +331 -0
- morphogen/models/branching.py +241 -0
- morphogen/models/combination.py +430 -0
- morphogen/models/deadleaves.py +766 -0
- morphogen/models/design.py +289 -0
- morphogen/models/ebsd.py +206 -0
- morphogen/models/fibers.py +1476 -0
- morphogen/models/foam.py +594 -0
- morphogen/models/gaussian.py +314 -0
- morphogen/models/growth.py +459 -0
- morphogen/models/hardcore.py +317 -0
- morphogen/models/hierarchical.py +269 -0
- morphogen/models/honeycomb.py +749 -0
- morphogen/models/implicit.py +177 -0
- morphogen/models/laminate.py +470 -0
- morphogen/models/lattice.py +351 -0
- morphogen/models/lattice_field.py +345 -0
- morphogen/models/levelset_foam.py +563 -0
- morphogen/models/nacre.py +411 -0
- morphogen/models/nested.py +924 -0
- morphogen/models/osteons.py +374 -0
- morphogen/models/pieces.py +167 -0
- morphogen/models/planar.py +126 -0
- morphogen/models/reconstruction.py +203 -0
- morphogen/models/scale_rich.py +1409 -0
- morphogen/models/scale_rich_3d.py +1616 -0
- morphogen/models/tessellation.py +735 -0
- morphogen/models/tiling_field.py +302 -0
- morphogen/models/tpms.py +197 -0
- morphogen/models/transparent.py +406 -0
- morphogen/models/union.py +141 -0
- morphogen/optimization/__init__.py +43 -0
- morphogen/optimization/cell.py +295 -0
- morphogen/optimization/filters.py +115 -0
- morphogen/optimization/mma.py +226 -0
- morphogen/optimization/run.py +219 -0
- morphogen/optimization/topology.py +632 -0
- morphogen/orientations.py +568 -0
- morphogen/parallel.py +599 -0
- morphogen/pipeline.py +978 -0
- morphogen/primitives.py +188 -0
- morphogen/results.py +564 -0
- morphogen/rve/__init__.py +73 -0
- morphogen/rve/report.py +627 -0
- morphogen/rve/scaling.py +363 -0
- morphogen/rve/study.py +1054 -0
- morphogen/rve/windows.py +345 -0
- morphogen/seeding.py +51 -0
- morphogen/settings.py +118 -0
- morphogen/stopping.py +48 -0
- morphogen/symmetry.py +384 -0
- morphogen/templates/activator_inhibitor.yaml +22 -0
- morphogen/templates/aggregation.yaml +23 -0
- morphogen/templates/boolean_cylinders.yaml +20 -0
- morphogen/templates/boolean_spheres.yaml +22 -0
- morphogen/templates/bouligand.yaml +28 -0
- morphogen/templates/cellular_automaton.yaml +25 -0
- morphogen/templates/coated_spheres.yaml +26 -0
- morphogen/templates/contact_fibers.yaml +27 -0
- morphogen/templates/cox_nanocomposite.yaml +22 -0
- morphogen/templates/cross_linked_fibers.yaml +26 -0
- morphogen/templates/curved_arcs.yaml +28 -0
- morphogen/templates/curved_fibers.yaml +24 -0
- morphogen/templates/dead_leaves.yaml +22 -0
- morphogen/templates/delaunay_network.yaml +22 -0
- morphogen/templates/dense_packing.yaml +22 -0
- morphogen/templates/diffusion.yaml +33 -0
- morphogen/templates/ebsd.yaml +34 -0
- morphogen/templates/ebsd_map.ctf +3087 -0
- morphogen/templates/fracture_composite.yaml +42 -0
- morphogen/templates/fracture_rubber.yaml +47 -0
- morphogen/templates/gaussian_excursion.yaml +17 -0
- morphogen/templates/graded_lattice.yaml +24 -0
- morphogen/templates/hardcore_fibers.yaml +22 -0
- morphogen/templates/hardcore_spheres.yaml +22 -0
- morphogen/templates/hierarchical_lattice.yaml +22 -0
- morphogen/templates/homogenization_acoustic_foam.yaml +36 -0
- morphogen/templates/homogenization_beremin.yaml +50 -0
- morphogen/templates/homogenization_cleavage.yaml +51 -0
- morphogen/templates/homogenization_cleavage_band.yaml +55 -0
- morphogen/templates/homogenization_contact.yaml +43 -0
- morphogen/templates/homogenization_crack_closure.yaml +49 -0
- morphogen/templates/homogenization_crystal_plasticity.yaml +50 -0
- morphogen/templates/homogenization_crystal_plasticity_fft.yaml +52 -0
- morphogen/templates/homogenization_crystallization.yaml +30 -0
- morphogen/templates/homogenization_debonding.yaml +43 -0
- morphogen/templates/homogenization_detwinning.yaml +58 -0
- morphogen/templates/homogenization_ductile_damage.yaml +47 -0
- morphogen/templates/homogenization_fatigue.yaml +40 -0
- morphogen/templates/homogenization_grain_fracture.yaml +56 -0
- morphogen/templates/homogenization_gyroid.yaml +30 -0
- morphogen/templates/homogenization_intergranular.yaml +43 -0
- morphogen/templates/homogenization_interphase.yaml +42 -0
- morphogen/templates/homogenization_mixed_loading.yaml +33 -0
- morphogen/templates/homogenization_ntfa.yaml +56 -0
- morphogen/templates/homogenization_piezoelectric.yaml +27 -0
- morphogen/templates/homogenization_polycrystal.yaml +30 -0
- morphogen/templates/homogenization_polycrystal_inclusions.yaml +30 -0
- morphogen/templates/homogenization_poroelastic.yaml +26 -0
- morphogen/templates/homogenization_rubber.yaml +40 -0
- morphogen/templates/homogenization_slip_cleavage.yaml +50 -0
- morphogen/templates/homogenization_spheres.yaml +31 -0
- morphogen/templates/homogenization_transport.yaml +29 -0
- morphogen/templates/homogenization_twinning.yaml +54 -0
- morphogen/templates/homogenization_viscoelastic.yaml +34 -0
- morphogen/templates/homogenization_viscoplastic.yaml +42 -0
- morphogen/templates/homogenization_voronoi.yaml +26 -0
- morphogen/templates/homogenization_xfem.yaml +23 -0
- morphogen/templates/hyperuniform_cells.yaml +24 -0
- morphogen/templates/laguerre.yaml +18 -0
- morphogen/templates/laser_bending.yaml +35 -0
- morphogen/templates/laser_cells.yaml +38 -0
- morphogen/templates/laser_corrugated.yaml +36 -0
- morphogen/templates/level_set_foam.yaml +29 -0
- morphogen/templates/menger_sponge.yaml +17 -0
- morphogen/templates/nacre.yaml +25 -0
- morphogen/templates/nucleation_growth.yaml +25 -0
- morphogen/templates/optimize_auxetic.yaml +29 -0
- morphogen/templates/optimize_auxetic_3d.yaml +27 -0
- morphogen/templates/optimize_bulk.yaml +23 -0
- morphogen/templates/optimize_conductivity.yaml +20 -0
- morphogen/templates/osteons.yaml +28 -0
- morphogen/templates/penetrable_spheres.yaml +21 -0
- morphogen/templates/poisson_fibers.yaml +21 -0
- morphogen/templates/random_laminate.yaml +26 -0
- morphogen/templates/random_lattice.yaml +27 -0
- morphogen/templates/random_walk_fibers.yaml +26 -0
- morphogen/templates/reaction_diffusion.yaml +22 -0
- morphogen/templates/reconstruction.yaml +22 -0
- morphogen/templates/rve_cellular_automaton.yaml +23 -0
- morphogen/templates/rve_crystal_plasticity_fft.yaml +51 -0
- morphogen/templates/rve_multiphysics.yaml +43 -0
- morphogen/templates/rve_poisson_fibers.yaml +22 -0
- morphogen/templates/rve_poisson_fibers_fe.yaml +33 -0
- morphogen/templates/rve_voronoi_windows.yaml +20 -0
- morphogen/templates/scale_rich_network.yaml +29 -0
- morphogen/templates/scale_rich_plates.yaml +30 -0
- morphogen/templates/sequential_dead_leaves.yaml +25 -0
- morphogen/templates/strut_lattice.yaml +21 -0
- morphogen/templates/tile_assembly.yaml +28 -0
- morphogen/templates/tpms.yaml +19 -0
- morphogen/templates/trabecular_bone.yaml +29 -0
- morphogen/templates/transparent_dead_leaves.yaml +23 -0
- morphogen/templates/vascular_tree.yaml +23 -0
- morphogen/templates/voronoi.yaml +20 -0
- morphogen/templates/wood.yaml +34 -0
- morphogen/templates/workflow.yaml +56 -0
- morphogen/texture.py +665 -0
- morphogen/theory.py +162 -0
- morphogen/viz/__init__.py +12 -0
- morphogen/viz/export.py +244 -0
- morphogen/viz/figures.py +707 -0
- morphogen/viz/png.py +148 -0
- morphogen/viz/sections.py +696 -0
- morphogen/viz/surfaces.py +1352 -0
- morphogen/viz/video.py +904 -0
- morphogen/viz/workflow.py +488 -0
- morphogen-1.0.0.dist-info/METADATA +2316 -0
- morphogen-1.0.0.dist-info/RECORD +381 -0
- morphogen-1.0.0.dist-info/WHEEL +4 -0
- morphogen-1.0.0.dist-info/entry_points.txt +5 -0
- morphogen-1.0.0.dist-info/licenses/LICENSE +674 -0
|
@@ -0,0 +1,766 @@
|
|
|
1
|
+
"""Dead leaves models (Matheron 1968; Jeulin 1997).
|
|
2
|
+
|
|
3
|
+
Leaves fall one after the other, each hiding what it covers; after infinitely many,
|
|
4
|
+
every point belongs to the last leaf that covered it. The perfect simulation of Kendall
|
|
5
|
+
& Thönnes (1999) runs the time backwards: leaves are drawn one by one, each going under
|
|
6
|
+
the earlier ones, so that a point belongs to the *first* leaf drawn that covers it, and
|
|
7
|
+
the drawing stops once the domain is covered. Here it stops once the voxel centres of a
|
|
8
|
+
check grid are covered, and a third more leaves are drawn, which leaves a negligible
|
|
9
|
+
part uncovered; voxels left uncovered at finer resolutions take the leaf of the
|
|
10
|
+
nearest centre.
|
|
11
|
+
|
|
12
|
+
The leaves are spheres, or spheroids (``shape: spheroid``: semi-axes ``a``, ``a`` and
|
|
13
|
+
``aspect_ratio * a`` about an axis drawn from ``orientation``), of random sizes. Each
|
|
14
|
+
phase may have its own law of sizes (``phase_radius``: families of leaves, the
|
|
15
|
+
multicomponent dead leaves of Jeulin), ``phase_fractions`` being the fractions of space
|
|
16
|
+
of the phases: the leaves of phase ``i`` fall in the proportion ``p_i ∝ q_i / E[V_i]``.
|
|
17
|
+
A finite ``coverage`` ``c`` (the mean number of leaves falling on a point) stops the
|
|
18
|
+
fall: the points that no leaf covers, a fraction ``exp(-c)``, keep the ``background``
|
|
19
|
+
phase (sequential dead leaves, from the Boolean model for small ``c`` to the dead
|
|
20
|
+
leaves as ``c`` grows).
|
|
21
|
+
|
|
22
|
+
The visible parts of the leaves form a random tessellation with non-convex cells: the
|
|
23
|
+
cell label of a voxel is the index of its leaf (the background, if any, is the last
|
|
24
|
+
label), and the leaves can carry crystal orientations (polycrystals of interpenetrating
|
|
25
|
+
grains).
|
|
26
|
+
|
|
27
|
+
Theory (Jeulin 1997). Let ``K_i(h)`` be the mean geometric covariogram of the leaves of
|
|
28
|
+
family ``i`` (``K_i(0) = E[V_i]``), ``κ_i = K_i / K_i(0)`` and ``c_i = c q_i`` the mean
|
|
29
|
+
number of its leaves over a point. Going back in time, the leaves hitting both ``x`` and
|
|
30
|
+
``x + h`` come at the rate ``a_i = c_i κ_i``, those hitting ``x`` only at ``b_i = c_i (1 -
|
|
31
|
+
κ_i)``, those hitting either at ``λ = Σ c_i (2 - κ_i)``, and those hitting ``x + h`` at
|
|
32
|
+
``μ = c``:
|
|
33
|
+
|
|
34
|
+
* ``P(x, x + h in the same leaf of i) = (a_i / λ) (1 - e^{-λ})``;
|
|
35
|
+
* ``P(x in a leaf of i, x + h in another of j) = (b_i q_j + b_j q_i)(I_1 - I_2)``, with
|
|
36
|
+
``I_1 = (1 - e^{-λ}) / λ`` and ``I_2 = (e^{-λ} - e^{-μ}) / (μ - λ)``;
|
|
37
|
+
* ``P(x in a leaf of i, x + h uncovered) = b_i I_2``, ``P(both uncovered) = e^{-λ}``.
|
|
38
|
+
|
|
39
|
+
With complete coverage (``c → ∞``) they become ``a_i / λ`` and ``(b_i q_j + b_j q_i) /
|
|
40
|
+
λ``: one family of phases of probabilities ``p_i`` gives the covariance ``p_i^2 + p_i (1 -
|
|
41
|
+
p_i) r(h)`` of phase ``i``, ``r(h) = K(h) / (2K(0) - K(h))``. A sphere of radius ``R`` and
|
|
42
|
+
volume ``V`` has ``K(h) = V (1 - 3h/(4R) + h^3/(16R^3))`` up to ``2R``; a spheroid, an
|
|
43
|
+
affine image of the ball, ``K(h w) = V k(h sqrt((1 - t^2)/a^2 + t^2/c^2))``, with ``t =
|
|
44
|
+
w · axis`` and ``k(s) = 1 - 3s/4 + s^3/16`` (``s < 2``), the covariogram of the unit ball
|
|
45
|
+
over its volume.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
from __future__ import annotations
|
|
49
|
+
|
|
50
|
+
import itertools
|
|
51
|
+
import math
|
|
52
|
+
from dataclasses import dataclass
|
|
53
|
+
from typing import ClassVar
|
|
54
|
+
|
|
55
|
+
import numpy as np
|
|
56
|
+
from numba import njit
|
|
57
|
+
from scipy.spatial import cKDTree
|
|
58
|
+
|
|
59
|
+
from morphogen import settings
|
|
60
|
+
from morphogen._utils import check_positive
|
|
61
|
+
from morphogen.distributions import Distribution
|
|
62
|
+
from morphogen.domain import Domain, Grid
|
|
63
|
+
from morphogen.image import VoxelImage
|
|
64
|
+
from morphogen.kernels.leaves import first_cover
|
|
65
|
+
from morphogen.models.affine import ANISOTROPY, Anisotropy, anisotropic
|
|
66
|
+
from morphogen.models.base import Microstructure, Model, param, register, register_kind
|
|
67
|
+
from morphogen.orientations import (
|
|
68
|
+
Aligned,
|
|
69
|
+
Isotropic,
|
|
70
|
+
OrientationDistribution,
|
|
71
|
+
random_orientations,
|
|
72
|
+
)
|
|
73
|
+
from morphogen.seeding import SeedLike, make_rng
|
|
74
|
+
|
|
75
|
+
#: Shapes of the leaves.
|
|
76
|
+
SHAPES = ("sphere", "spheroid")
|
|
77
|
+
_NO_AXES = np.zeros((1, 3))
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@njit(cache=True)
|
|
81
|
+
def _visible_levels(offsets, ptr, leaves, radii, axes, aspect, leaf_phases, background, reach,
|
|
82
|
+
out): # fmt: skip
|
|
83
|
+
"""The level sets of the visible parts of the leaves of each phase (columns of
|
|
84
|
+
``out``) at points (their candidate leaves in order, ``leaves[ptr[p]:ptr[p + 1]]``, and
|
|
85
|
+
the offsets of the points from their centres): for each phase, the minimum over its
|
|
86
|
+
leaves ``i`` of ``max(d_i, -min_{j < i} d_j)``, ``d`` the signed distance to a leaf (the
|
|
87
|
+
ellipsoidal radius minus one times the smallest semi-axis for spheroids: a lower bound
|
|
88
|
+
of the distance outside, 1-Lipschitz), and ``-min_j d_j`` too for the ``background``
|
|
89
|
+
phase (the uncovered space; -1: none); within ``[-reach, reach]``."""
|
|
90
|
+
small = min(1.0, aspect)
|
|
91
|
+
n_phases = out.shape[1]
|
|
92
|
+
best = np.empty(n_phases)
|
|
93
|
+
for p in range(len(ptr) - 1):
|
|
94
|
+
lowest = np.inf
|
|
95
|
+
best[:] = np.inf
|
|
96
|
+
for k in range(ptr[p], ptr[p + 1]):
|
|
97
|
+
i = leaves[k]
|
|
98
|
+
dx, dy, dz = offsets[k, 0], offsets[k, 1], offsets[k, 2]
|
|
99
|
+
d2 = dx * dx + dy * dy + dz * dz
|
|
100
|
+
r = radii[i]
|
|
101
|
+
if aspect == 1.0:
|
|
102
|
+
d = math.sqrt(d2) - r
|
|
103
|
+
else:
|
|
104
|
+
t = dx * axes[i, 0] + dy * axes[i, 1] + dz * axes[i, 2]
|
|
105
|
+
q = (d2 - t * t) / (r * r) + t * t / (aspect * aspect * r * r)
|
|
106
|
+
d = (math.sqrt(q) - 1.0) * r * small
|
|
107
|
+
ph = leaf_phases[i]
|
|
108
|
+
best[ph] = min(best[ph], max(d, -lowest))
|
|
109
|
+
lowest = min(lowest, d)
|
|
110
|
+
if lowest <= -reach: # the leaves below are hidden beyond the reach
|
|
111
|
+
break
|
|
112
|
+
if background >= 0:
|
|
113
|
+
best[background] = min(best[background], -lowest)
|
|
114
|
+
for ph in range(n_phases):
|
|
115
|
+
out[p, ph] = min(max(best[ph], -reach), reach)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _cover(centers, radii, axes, aspect, grid: Grid, periodic: bool, out=None, first: int = 0):
|
|
119
|
+
"""Labels of the first leaves covering the voxel centres of a grid (-1: none)."""
|
|
120
|
+
if out is None:
|
|
121
|
+
out = np.full(grid.shape, -1, dtype=np.int32)
|
|
122
|
+
left = first_cover(
|
|
123
|
+
np.ascontiguousarray(centers, dtype=float),
|
|
124
|
+
np.ascontiguousarray(radii, dtype=float),
|
|
125
|
+
_NO_AXES if axes is None else np.ascontiguousarray(axes, dtype=float),
|
|
126
|
+
float(aspect),
|
|
127
|
+
first,
|
|
128
|
+
np.asarray(grid.domain.lower, dtype=float),
|
|
129
|
+
np.asarray(grid.spacing, dtype=float),
|
|
130
|
+
np.asarray(grid.shape, dtype=np.int64),
|
|
131
|
+
periodic,
|
|
132
|
+
out,
|
|
133
|
+
)
|
|
134
|
+
return out, left
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@register_kind
|
|
138
|
+
class DeadLeaves(Microstructure):
|
|
139
|
+
"""Leaves in the order they cover the space (the first one is on top), and the
|
|
140
|
+
background that they leave uncovered (finite coverage; the last cell)."""
|
|
141
|
+
|
|
142
|
+
kind = "dead_leaves"
|
|
143
|
+
has_labels = True
|
|
144
|
+
|
|
145
|
+
def __init__(
|
|
146
|
+
self,
|
|
147
|
+
domain: Domain,
|
|
148
|
+
centers,
|
|
149
|
+
radii,
|
|
150
|
+
leaf_phases,
|
|
151
|
+
orientations=None,
|
|
152
|
+
*,
|
|
153
|
+
axes=None,
|
|
154
|
+
aspect: float = 1.0,
|
|
155
|
+
background: int | None = None,
|
|
156
|
+
**kwargs,
|
|
157
|
+
) -> None:
|
|
158
|
+
super().__init__(domain, **kwargs)
|
|
159
|
+
self.centers = np.ascontiguousarray(centers, dtype=float).reshape(-1, 3)
|
|
160
|
+
self.radii = np.asarray(radii, dtype=float).reshape(-1)
|
|
161
|
+
self.leaf_phases = np.asarray(leaf_phases, dtype=np.uint8).reshape(-1)
|
|
162
|
+
n = len(self.radii)
|
|
163
|
+
self.aspect = float(aspect)
|
|
164
|
+
self.axes = None if axes is None else np.ascontiguousarray(axes, dtype=float).reshape(n, 3)
|
|
165
|
+
self.background = None if background is None else int(background)
|
|
166
|
+
# the phase of each cell: the leaves, then the background
|
|
167
|
+
self.cell_phases = self.leaf_phases
|
|
168
|
+
if self.background is not None:
|
|
169
|
+
self.cell_phases = np.append(self.leaf_phases, np.uint8(self.background))
|
|
170
|
+
self.orientations = (
|
|
171
|
+
None
|
|
172
|
+
if orientations is None
|
|
173
|
+
else np.asarray(orientations, dtype=float).reshape(len(self.cell_phases), 3)
|
|
174
|
+
)
|
|
175
|
+
self._tree = None
|
|
176
|
+
|
|
177
|
+
@property
|
|
178
|
+
def n_leaves(self) -> int:
|
|
179
|
+
return len(self.radii)
|
|
180
|
+
|
|
181
|
+
def _local(self, points: np.ndarray) -> np.ndarray:
|
|
182
|
+
p = np.asarray(points, dtype=float) - self.domain.lower
|
|
183
|
+
if self.domain.periodic:
|
|
184
|
+
p = np.mod(p, self.domain.lengths)
|
|
185
|
+
p[p >= self.domain.lengths] = 0.0
|
|
186
|
+
return p
|
|
187
|
+
|
|
188
|
+
def _centres_tree(self) -> cKDTree:
|
|
189
|
+
if self._tree is None:
|
|
190
|
+
if self.domain.periodic:
|
|
191
|
+
self._tree = cKDTree(self._local(self.centers), boxsize=self.domain.lengths)
|
|
192
|
+
else:
|
|
193
|
+
self._tree = cKDTree(self.centers - self.domain.lower)
|
|
194
|
+
return self._tree
|
|
195
|
+
|
|
196
|
+
def _nearest(self, points: np.ndarray) -> np.ndarray:
|
|
197
|
+
"""Leaf of the nearest centre (points that no leaf covers, complete coverage)."""
|
|
198
|
+
return self._centres_tree().query(self._local(points), k=1, workers=settings.workers())[1]
|
|
199
|
+
|
|
200
|
+
def _uncovered(self, points: np.ndarray) -> np.ndarray:
|
|
201
|
+
"""The cell of points that no leaf covers: the nearest leaf, or the background."""
|
|
202
|
+
if self.background is not None:
|
|
203
|
+
return np.full(len(points), self.n_leaves, dtype=np.int64)
|
|
204
|
+
return self._nearest(points)
|
|
205
|
+
|
|
206
|
+
def labels(self, shape=None, *, voxel_size=None, grid: Grid | None = None) -> VoxelImage:
|
|
207
|
+
"""Image of the visible leaves (int32 leaf indices; the background: ``n_leaves``)."""
|
|
208
|
+
grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
|
|
209
|
+
out, left = _cover(self.centers, self.radii, self.axes, self.aspect, grid,
|
|
210
|
+
self.domain.periodic) # fmt: skip
|
|
211
|
+
if left:
|
|
212
|
+
missing = out < 0
|
|
213
|
+
out[missing] = self._uncovered(grid.center_points()[missing.ravel()])
|
|
214
|
+
return VoxelImage.from_grid(out, grid, name="cell", metadata=self.image_metadata())
|
|
215
|
+
|
|
216
|
+
def voxelize(self, shape=None, *, voxel_size=None, grid: Grid | None = None, supersampling=1):
|
|
217
|
+
grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
|
|
218
|
+
ss = int(supersampling)
|
|
219
|
+
if ss == 1:
|
|
220
|
+
data = self.cell_phases[self.labels(grid=grid).data]
|
|
221
|
+
return VoxelImage.from_grid(data, grid, name="phase", metadata=self.image_metadata())
|
|
222
|
+
if not 1 <= ss <= 6:
|
|
223
|
+
raise ValueError("supersampling must be an integer between 1 and 6")
|
|
224
|
+
fine = Grid(grid.domain, tuple(n * ss for n in grid.shape))
|
|
225
|
+
ph = (self.cell_phases[self.labels(grid=fine).data] == 1).astype(np.float32)
|
|
226
|
+
nx, ny, nz = grid.shape
|
|
227
|
+
data = ph.reshape(nx, ss, ny, ss, nz, ss).mean(axis=(1, 3, 5), dtype=np.float32)
|
|
228
|
+
return VoxelImage.from_grid(data, grid, name="fraction", metadata=self.image_metadata())
|
|
229
|
+
|
|
230
|
+
def _inside(self, leaves: np.ndarray, d: np.ndarray) -> np.ndarray:
|
|
231
|
+
"""Whether the offsets ``d`` from the centres of ``leaves`` lie in them."""
|
|
232
|
+
r2 = self.radii[leaves] ** 2
|
|
233
|
+
d2 = np.einsum("ij,ij->i", d, d)
|
|
234
|
+
if self.axes is None or self.aspect == 1.0:
|
|
235
|
+
return d2 <= r2
|
|
236
|
+
t = np.einsum("ij,ij->i", d, self.axes[leaves])
|
|
237
|
+
return (d2 - t * t) / r2 + t * t / (self.aspect**2 * r2) <= 1.0
|
|
238
|
+
|
|
239
|
+
def leaf_of(self, points) -> np.ndarray:
|
|
240
|
+
"""Visible cell at each point: its leaf, or the background (``n_leaves``)."""
|
|
241
|
+
pts = np.asarray(points, dtype=float).reshape(-1, 3)
|
|
242
|
+
out = np.full(len(pts), -1, dtype=np.int64)
|
|
243
|
+
if self.n_leaves:
|
|
244
|
+
tree = self._centres_tree()
|
|
245
|
+
p = self._local(pts)
|
|
246
|
+
reach = float(self.radii.max()) * max(1.0, self.aspect)
|
|
247
|
+
for i, cand in enumerate(tree.query_ball_point(p, reach)):
|
|
248
|
+
if not cand:
|
|
249
|
+
continue
|
|
250
|
+
cand = np.asarray(cand)
|
|
251
|
+
d = tree.data[cand] - p[i]
|
|
252
|
+
if self.domain.periodic:
|
|
253
|
+
d -= self.domain.lengths * np.round(d / self.domain.lengths)
|
|
254
|
+
inside = cand[self._inside(cand, d)]
|
|
255
|
+
if inside.size:
|
|
256
|
+
out[i] = inside.min()
|
|
257
|
+
missing = out < 0
|
|
258
|
+
if missing.any():
|
|
259
|
+
out[missing] = self._uncovered(pts[missing]) if self.n_leaves else self.n_leaves
|
|
260
|
+
return out
|
|
261
|
+
|
|
262
|
+
def contains(self, points) -> np.ndarray:
|
|
263
|
+
return self.cell_phases[self.leaf_of(points)] == 1
|
|
264
|
+
|
|
265
|
+
# -- implicit functions ----------------------------------------------------------------
|
|
266
|
+
|
|
267
|
+
def implicit_phases(self) -> list[int]:
|
|
268
|
+
return sorted(int(k) for k in np.unique(self.cell_phases))
|
|
269
|
+
|
|
270
|
+
def _leaf_function(self, i: int, dx, dy, dz):
|
|
271
|
+
"""The implicit function of the leaf ``i`` at offsets from its centre: the
|
|
272
|
+
distance to a sphere; for a spheroid, its radius times the gauge of the point
|
|
273
|
+
minus one (zero on it, the distance to it along its equator)."""
|
|
274
|
+
r = self.radii[i]
|
|
275
|
+
d2 = dx * dx + dy * dy + dz * dz
|
|
276
|
+
if self.axes is None or self.aspect == 1.0:
|
|
277
|
+
return np.sqrt(d2) - r
|
|
278
|
+
a = self.axes[i]
|
|
279
|
+
t = dx * a[0] + dy * a[1] + dz * a[2]
|
|
280
|
+
return r * (np.sqrt(np.maximum(d2 - t * t, 0.0) + t * t / self.aspect**2) / r - 1.0)
|
|
281
|
+
|
|
282
|
+
def _implicit(self, grid: Grid) -> dict[int, np.ndarray]:
|
|
283
|
+
"""The implicit functions of all the phases on a grid (kept for the grid last
|
|
284
|
+
asked): the leaves of a phase where no leaf on top of them covers them, and the
|
|
285
|
+
part of what no leaf covers that the phase takes (the background, or the points
|
|
286
|
+
nearest to the centres of its leaves)."""
|
|
287
|
+
from morphogen.models.implicit import band_of, grid_key, lattice_boxes, ordered_cover
|
|
288
|
+
|
|
289
|
+
key = grid_key(grid)
|
|
290
|
+
cached = getattr(self, "_fields", None)
|
|
291
|
+
if cached is not None and cached[0] == key:
|
|
292
|
+
return cached[1]
|
|
293
|
+
band = band_of(grid)
|
|
294
|
+
phases = self.implicit_phases()
|
|
295
|
+
index = {k: n for n, k in enumerate(phases)}
|
|
296
|
+
lengths = self.domain.lengths if self.domain.periodic else None
|
|
297
|
+
stretch = max(1.0, self.aspect)
|
|
298
|
+
|
|
299
|
+
def objects():
|
|
300
|
+
for i in range(self.n_leaves):
|
|
301
|
+
reach = self.radii[i] * stretch + band
|
|
302
|
+
for slices, offsets in lattice_boxes(self.centers[i], reach, grid, lengths):
|
|
303
|
+
f = self._leaf_function(i, *offsets).astype(np.float32)
|
|
304
|
+
parts = [None] * len(phases)
|
|
305
|
+
parts[index[int(self.leaf_phases[i])]] = f
|
|
306
|
+
yield slices, f, parts
|
|
307
|
+
|
|
308
|
+
parts, top = ordered_cover(grid.shape, band, objects(), len(phases))
|
|
309
|
+
fields = {k: parts[n] for k, n in index.items()}
|
|
310
|
+
uncovered = -top # negative where no leaf covers
|
|
311
|
+
if self.background is not None:
|
|
312
|
+
np.minimum(fields[self.background], uncovered, out=fields[self.background])
|
|
313
|
+
elif self.n_leaves and np.any(uncovered < 0): # the leaf of the nearest centre
|
|
314
|
+
nx, ny, nz = grid.shape
|
|
315
|
+
tree = self._centres_tree()
|
|
316
|
+
scale = 2.0 * float(np.mean(self.radii))
|
|
317
|
+
for k in phases:
|
|
318
|
+
own = cKDTree(tree.data[self.leaf_phases == k], boxsize=tree.boxsize)
|
|
319
|
+
rest = self.leaf_phases != k
|
|
320
|
+
share = np.full(grid.shape, -band, dtype=np.float32)
|
|
321
|
+
if rest.any():
|
|
322
|
+
others = cKDTree(tree.data[rest], boxsize=tree.boxsize)
|
|
323
|
+
q = self._local(grid.center_points())
|
|
324
|
+
d = own.query(q, workers=settings.workers())[0] ** 2
|
|
325
|
+
d -= others.query(q, workers=settings.workers())[0] ** 2
|
|
326
|
+
share = np.clip(d / scale, -band, band).reshape(nx, ny, nz).astype(np.float32)
|
|
327
|
+
np.minimum(fields[k], np.maximum(uncovered, share), out=fields[k])
|
|
328
|
+
self._fields = (key, fields)
|
|
329
|
+
return fields
|
|
330
|
+
|
|
331
|
+
def phase_level_set(
|
|
332
|
+
self, phase: int, shape=None, *, voxel_size=None, grid: Grid | None = None
|
|
333
|
+
) -> VoxelImage:
|
|
334
|
+
"""The implicit function of a phase (see :meth:`Microstructure.phase_level_set`):
|
|
335
|
+
the leaves of the phase outside the leaves on top of them, each by the distance to
|
|
336
|
+
its sphere (spheroids: a function that vanishes on them), clipped to a band of
|
|
337
|
+
four voxels."""
|
|
338
|
+
phase = int(phase)
|
|
339
|
+
if phase not in self.implicit_phases():
|
|
340
|
+
raise ValueError(f"phase {phase}: the phases are {self.implicit_phases()}")
|
|
341
|
+
grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
|
|
342
|
+
data = self._implicit(grid)[phase]
|
|
343
|
+
return VoxelImage.from_grid(data, grid, name="level_set", metadata=self.image_metadata())
|
|
344
|
+
|
|
345
|
+
def level_set(self, shape=None, *, voxel_size=None, grid: Grid | None = None) -> VoxelImage:
|
|
346
|
+
"""The implicit function of phase 1 (:meth:`phase_level_set`)."""
|
|
347
|
+
return self.phase_level_set(1, shape, voxel_size=voxel_size, grid=grid)
|
|
348
|
+
|
|
349
|
+
def level_set_at(self, points, reach: float = np.inf) -> np.ndarray:
|
|
350
|
+
"""Two phases: the level set of the visible parts of the leaves of phase 1 (each
|
|
351
|
+
leaf minus those above it), see :func:`_visible_levels`, within ``[-reach, reach]``
|
|
352
|
+
(default: the largest radius); the points that no leaf covers are of phase 0 (of
|
|
353
|
+
the background phase, with a finite coverage). Its zero set is the boundary of
|
|
354
|
+
phase 1, sharp edges included: the exact meshes follow it. More phases: one level
|
|
355
|
+
set per phase (:meth:`phase_level_sets_at`), of which this is that of phase 1."""
|
|
356
|
+
if 1 not in self.implicit_phases():
|
|
357
|
+
raise NotImplementedError("dead leaves without a phase 1: one level set per "
|
|
358
|
+
"phase (phase_level_sets_at)") # fmt: skip
|
|
359
|
+
return self.phase_level_sets_at(points, reach)[1]
|
|
360
|
+
|
|
361
|
+
def phase_level_sets_at(self, points, reach: float = np.inf) -> dict[int, np.ndarray]:
|
|
362
|
+
"""The functions of all the phases at the points: the visible parts of the leaves
|
|
363
|
+
of each phase (the uncovered points: of the background phase, or of none), see
|
|
364
|
+
:func:`_visible_levels`, within ``[-reach, reach]`` (default: the largest radius)."""
|
|
365
|
+
n_phases = max(int(self.cell_phases.max(initial=0)), 1) + 1
|
|
366
|
+
pts = np.asarray(points, dtype=float).reshape(-1, 3)
|
|
367
|
+
rmax = float(self.radii.max(initial=0.0)) * max(1.0, self.aspect)
|
|
368
|
+
reach = rmax if not np.isfinite(reach) else float(reach)
|
|
369
|
+
out = np.full((len(pts), n_phases), reach)
|
|
370
|
+
background = -1 if self.background is None else int(self.background)
|
|
371
|
+
if not self.n_leaves:
|
|
372
|
+
if background >= 0:
|
|
373
|
+
out[:, background] = -reach
|
|
374
|
+
return {k: out[:, k] for k in self.implicit_phases()}
|
|
375
|
+
tree = self._centres_tree()
|
|
376
|
+
axes = self.axes if self.axes is not None else np.zeros((self.n_leaves, 3))
|
|
377
|
+
aspect = self.aspect if self.axes is not None else 1.0
|
|
378
|
+
phases = self.leaf_phases.astype(np.int64)
|
|
379
|
+
chunk = 4096 # the pairs of points and leaves in memory
|
|
380
|
+
for s in range(0, len(pts), chunk):
|
|
381
|
+
p = self._local(pts[s : s + chunk])
|
|
382
|
+
lists = tree.query_ball_point(p, rmax + reach, workers=settings.workers())
|
|
383
|
+
counts = np.fromiter((len(c) for c in lists), dtype=np.int64, count=len(lists))
|
|
384
|
+
leaves = np.fromiter(itertools.chain.from_iterable(lists), dtype=np.int64,
|
|
385
|
+
count=int(counts.sum())) # fmt: skip
|
|
386
|
+
owner = np.repeat(np.arange(len(p)), counts)
|
|
387
|
+
order = np.lexsort((leaves, owner)) # each point's leaves in order
|
|
388
|
+
leaves, owner = leaves[order], owner[order]
|
|
389
|
+
offsets = p[owner] - tree.data[leaves]
|
|
390
|
+
if self.domain.periodic:
|
|
391
|
+
offsets -= self.domain.lengths * np.round(offsets / self.domain.lengths)
|
|
392
|
+
ptr = np.concatenate([[0], np.cumsum(counts)])
|
|
393
|
+
_visible_levels(np.ascontiguousarray(offsets), ptr, leaves, self.radii, axes, aspect,
|
|
394
|
+
phases, background, reach, out[s : s + chunk]) # fmt: skip
|
|
395
|
+
return {k: np.ascontiguousarray(out[:, k]) for k in self.implicit_phases()}
|
|
396
|
+
|
|
397
|
+
def summary(self) -> dict:
|
|
398
|
+
return {"n_leaves": self.n_leaves}
|
|
399
|
+
|
|
400
|
+
def _geometry(self) -> dict:
|
|
401
|
+
geo = {
|
|
402
|
+
"centers": self.centers.tolist(),
|
|
403
|
+
"radii": self.radii.tolist(),
|
|
404
|
+
"leaf_phases": self.leaf_phases.tolist(),
|
|
405
|
+
}
|
|
406
|
+
if self.orientations is not None:
|
|
407
|
+
geo["orientations"] = self.orientations.tolist()
|
|
408
|
+
if self.axes is not None:
|
|
409
|
+
geo.update(axes=self.axes.tolist(), aspect=self.aspect)
|
|
410
|
+
if self.background is not None:
|
|
411
|
+
geo["background"] = self.background
|
|
412
|
+
return geo
|
|
413
|
+
|
|
414
|
+
@classmethod
|
|
415
|
+
def _from_geometry(cls, domain, geometry, **kwargs):
|
|
416
|
+
return cls(
|
|
417
|
+
domain,
|
|
418
|
+
geometry["centers"],
|
|
419
|
+
geometry["radii"],
|
|
420
|
+
geometry["leaf_phases"],
|
|
421
|
+
geometry.get("orientations"),
|
|
422
|
+
axes=geometry.get("axes"),
|
|
423
|
+
aspect=geometry.get("aspect", 1.0),
|
|
424
|
+
background=geometry.get("background"),
|
|
425
|
+
**kwargs,
|
|
426
|
+
)
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def _ball(s: np.ndarray) -> np.ndarray:
|
|
430
|
+
"""The covariogram of the unit ball over its volume at the distance ``s``."""
|
|
431
|
+
return np.where(s < 2.0, 1.0 - 0.75 * s + s**3 / 16.0, 0.0)
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def _fibonacci(n: int) -> np.ndarray:
|
|
435
|
+
"""``n`` nearly uniform directions of the half sphere (a Fibonacci lattice)."""
|
|
436
|
+
k = np.arange(n) + 0.5
|
|
437
|
+
z = k / n
|
|
438
|
+
phi = math.pi * (1.0 + math.sqrt(5.0)) * k
|
|
439
|
+
s = np.sqrt(1.0 - z * z)
|
|
440
|
+
return np.column_stack([s * np.cos(phi), s * np.sin(phi), z])
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
@register
|
|
444
|
+
@anisotropic
|
|
445
|
+
@dataclass(frozen=True)
|
|
446
|
+
class DeadLeavesModel(Model):
|
|
447
|
+
"""Dead leaves of spheres or spheroids, of one or several families: each point belongs
|
|
448
|
+
to the last leaf covering it (or to a background, with a finite coverage)."""
|
|
449
|
+
|
|
450
|
+
name = "dead_leaves"
|
|
451
|
+
phases: ClassVar[dict[int, str]] = {0: "leaves of phase 0", 1: "leaves of phase 1"}
|
|
452
|
+
count_label = "leaves"
|
|
453
|
+
|
|
454
|
+
@property
|
|
455
|
+
def has_level_set(self) -> bool:
|
|
456
|
+
"""Leaves of the phase 1 among those of the phase 0: one level set."""
|
|
457
|
+
return sorted(self.active_phases()) == [0, 1]
|
|
458
|
+
|
|
459
|
+
radius: Distribution | None = param(
|
|
460
|
+
None,
|
|
461
|
+
doc="Radius of the leaves (spheres; the equatorial semi-axis of spheroids)",
|
|
462
|
+
kind="distribution",
|
|
463
|
+
unit="length",
|
|
464
|
+
)
|
|
465
|
+
phase_fractions: tuple[float, ...] = param(
|
|
466
|
+
(0.5, 0.5),
|
|
467
|
+
doc="Fractions of the space of the leaves of phases 0, 1, ... (the probabilities of "
|
|
468
|
+
"the leaves when they share their sizes)",
|
|
469
|
+
kind="floats",
|
|
470
|
+
)
|
|
471
|
+
phase_radius: tuple[Distribution, ...] | None = param(
|
|
472
|
+
None,
|
|
473
|
+
doc="Radius of the leaves of each phase (families of leaves of their own sizes), "
|
|
474
|
+
"instead of radius",
|
|
475
|
+
kind="distributions",
|
|
476
|
+
unit="length",
|
|
477
|
+
)
|
|
478
|
+
shape: str = param("sphere", doc="Shape of the leaves: sphere or spheroid", kind="str")
|
|
479
|
+
aspect_ratio: float = param(
|
|
480
|
+
1.0, doc="Polar over equatorial semi-axis of the spheroids (> 1 prolate, < 1 oblate)"
|
|
481
|
+
)
|
|
482
|
+
orientation: OrientationDistribution = param(
|
|
483
|
+
Isotropic(),
|
|
484
|
+
doc="Distribution of the axes of the spheroids (isotropic, aligned, planar)",
|
|
485
|
+
kind="orientation",
|
|
486
|
+
)
|
|
487
|
+
coverage: float | None = param(
|
|
488
|
+
None,
|
|
489
|
+
doc="Mean number of leaves falling on a point: a finite fall over the background "
|
|
490
|
+
"(default: complete coverage)",
|
|
491
|
+
)
|
|
492
|
+
background: int = param(
|
|
493
|
+
0, doc="Phase of the points that no leaf covers (finite coverage)", kind="int"
|
|
494
|
+
)
|
|
495
|
+
crystal_orientations: bool = param(
|
|
496
|
+
False, doc="Draw a uniformly random crystal orientation per leaf", kind="bool"
|
|
497
|
+
)
|
|
498
|
+
anisotropy: Anisotropy | None = param(None, doc=ANISOTROPY, kind="anisotropy", kw_only=True)
|
|
499
|
+
|
|
500
|
+
def _validate(self) -> None:
|
|
501
|
+
p = np.asarray(self.phase_fractions, dtype=float)
|
|
502
|
+
if p.ndim != 1 or len(p) < 1 or np.any(p < 0) or abs(p.sum() - 1.0) > 1e-9:
|
|
503
|
+
raise ValueError("phase_fractions: non-negative probabilities summing to 1")
|
|
504
|
+
if len(p) > 255:
|
|
505
|
+
raise ValueError("phase_fractions: at most 255 phases")
|
|
506
|
+
if (self.radius is None) == (self.phase_radius is None):
|
|
507
|
+
raise ValueError("give the radius of the leaves, or that of each phase (phase_radius)")
|
|
508
|
+
if self.phase_radius is not None and len(self.phase_radius) != len(p):
|
|
509
|
+
raise ValueError("phase_radius: one distribution per phase of phase_fractions")
|
|
510
|
+
if self.shape not in SHAPES:
|
|
511
|
+
raise ValueError(f"shape: {' or '.join(SHAPES)}, got {self.shape!r}")
|
|
512
|
+
check_positive(self.aspect_ratio, "aspect_ratio")
|
|
513
|
+
if self.shape == "sphere" and self.aspect_ratio != 1.0:
|
|
514
|
+
raise ValueError("aspect_ratio: the leaves are spheres (give shape: spheroid)")
|
|
515
|
+
if self.coverage is not None:
|
|
516
|
+
check_positive(self.coverage, "coverage")
|
|
517
|
+
if not 0 <= self.background <= 255:
|
|
518
|
+
raise ValueError("background: a phase between 0 and 255")
|
|
519
|
+
|
|
520
|
+
@property
|
|
521
|
+
def aspect(self) -> float:
|
|
522
|
+
"""The polar over the equatorial semi-axis of the leaves (1: spheres)."""
|
|
523
|
+
return self.aspect_ratio if self.shape == "spheroid" else 1.0
|
|
524
|
+
|
|
525
|
+
def _laws(self) -> list[Distribution]:
|
|
526
|
+
n = len(self.phase_fractions)
|
|
527
|
+
return list(self.phase_radius) if self.phase_radius is not None else [self.radius] * n
|
|
528
|
+
|
|
529
|
+
def families(self) -> list[tuple[int, Distribution, float, float]]:
|
|
530
|
+
"""The families of leaves: their phase, the law of their radii, the fraction of
|
|
531
|
+
space ``q`` of their leaves and their proportion ``p`` among the leaves."""
|
|
532
|
+
q = np.asarray(self.phase_fractions, dtype=float)
|
|
533
|
+
laws = self._laws()
|
|
534
|
+
volumes = np.array([self._volume(law) for law in laws])
|
|
535
|
+
w = np.where(q > 0, q / volumes, 0.0)
|
|
536
|
+
p = w / w.sum()
|
|
537
|
+
return [(i, laws[i], float(q[i]), float(p[i])) for i in range(len(q)) if q[i] > 0]
|
|
538
|
+
|
|
539
|
+
def _volume(self, law: Distribution) -> float:
|
|
540
|
+
return 4.0 / 3.0 * math.pi * self.aspect * law.moment(3)
|
|
541
|
+
|
|
542
|
+
def mean_leaf_volume(self) -> float:
|
|
543
|
+
"""The mean volume of a falling leaf, ``1 / Σ q_i / E[V_i]``."""
|
|
544
|
+
return 1.0 / sum(q / self._volume(law) for _, law, q, _ in self.families())
|
|
545
|
+
|
|
546
|
+
def active_phases(self) -> dict[int, str]:
|
|
547
|
+
out = {i: f"leaves of phase {i}" for i, p in enumerate(self.phase_fractions) if p > 0}
|
|
548
|
+
if self.coverage is not None:
|
|
549
|
+
out.setdefault(self.background, f"background (phase {self.background})")
|
|
550
|
+
return out
|
|
551
|
+
|
|
552
|
+
def _draw(self, rng, window: Domain, k: int):
|
|
553
|
+
"""``k`` leaves: centres, radii and phases (families of their own sizes)."""
|
|
554
|
+
families = self.families()
|
|
555
|
+
centers = window.lower + rng.random((k, 3)) * window.lengths
|
|
556
|
+
if self.phase_radius is None:
|
|
557
|
+
return centers, self.radius.sample(rng, k), None
|
|
558
|
+
fam = rng.choice(len(families), size=k, p=np.array([f[3] for f in families]))
|
|
559
|
+
radii = np.empty(k)
|
|
560
|
+
for f, (_, law, _, _) in enumerate(families):
|
|
561
|
+
sel = fam == f
|
|
562
|
+
radii[sel] = law.sample(rng, int(sel.sum()))
|
|
563
|
+
return centers, radii, np.array([f[0] for f in families], dtype=np.uint8)[fam]
|
|
564
|
+
|
|
565
|
+
def generate(self, domain: Domain, seed: SeedLike = None) -> DeadLeaves:
|
|
566
|
+
self._check_domain(domain)
|
|
567
|
+
rng, seed_info = make_rng(seed)
|
|
568
|
+
periodic = domain.periodic
|
|
569
|
+
aspect = self.aspect
|
|
570
|
+
laws = [law for _, law, _, _ in self.families()]
|
|
571
|
+
reach = max(law.upper() for law in laws) * max(1.0, aspect)
|
|
572
|
+
window = domain if periodic else domain.dilated(reach)
|
|
573
|
+
mean_volume = self.mean_leaf_volume()
|
|
574
|
+
spheroid = aspect != 1.0
|
|
575
|
+
centers, radii, phases, axes = [], [], [], []
|
|
576
|
+
if self.coverage is not None: # a Poisson number of leaves over the window
|
|
577
|
+
n = int(rng.poisson(self.coverage * window.volume / mean_volume))
|
|
578
|
+
c, r, ph = self._draw(rng, window, n)
|
|
579
|
+
centers, radii, phases = [c], [r], [ph]
|
|
580
|
+
if spheroid:
|
|
581
|
+
axes.append(self.orientation.sample(rng, n))
|
|
582
|
+
else:
|
|
583
|
+
# leaves until the centres of a check grid (a third of the smallest median
|
|
584
|
+
# semi-axis) are covered, then a third more
|
|
585
|
+
step = min(law.median() for law in laws) * min(1.0, aspect) / 3.0
|
|
586
|
+
shape = tuple(int(np.clip(math.ceil(s / step), 8, 128)) for s in domain.lengths)
|
|
587
|
+
check = Grid(domain, shape)
|
|
588
|
+
cover = np.full(shape, -1, dtype=np.int32)
|
|
589
|
+
batch = max(64, int(0.5 * window.volume / mean_volume))
|
|
590
|
+
n, left = 0, cover.size
|
|
591
|
+
while left:
|
|
592
|
+
c, r, ph = self._draw(rng, window, batch)
|
|
593
|
+
u = self.orientation.sample(rng, batch) if spheroid else None
|
|
594
|
+
cover, left = _cover(c, r, u, aspect, check, periodic, cover, n)
|
|
595
|
+
centers.append(c)
|
|
596
|
+
radii.append(r)
|
|
597
|
+
phases.append(ph)
|
|
598
|
+
axes.append(u)
|
|
599
|
+
n += batch
|
|
600
|
+
if n > 10**8:
|
|
601
|
+
raise RuntimeError("dead_leaves: the leaves do not cover the domain")
|
|
602
|
+
extra = n // 3 + 1
|
|
603
|
+
c, r, ph = self._draw(rng, window, extra)
|
|
604
|
+
centers.append(c)
|
|
605
|
+
radii.append(r)
|
|
606
|
+
phases.append(ph)
|
|
607
|
+
axes.append(self.orientation.sample(rng, extra) if spheroid else None)
|
|
608
|
+
n += extra
|
|
609
|
+
n = sum(len(r) for r in radii)
|
|
610
|
+
if self.phase_radius is None:
|
|
611
|
+
p = np.asarray(self.phase_fractions, dtype=float)
|
|
612
|
+
leaf_phases = rng.choice(len(p), size=n, p=p / p.sum()).astype(np.uint8)
|
|
613
|
+
else:
|
|
614
|
+
leaf_phases = np.concatenate(phases) if n else np.zeros(0, dtype=np.uint8)
|
|
615
|
+
background = self.background if self.coverage is not None else None
|
|
616
|
+
n_cells = n + (background is not None)
|
|
617
|
+
orientations = random_orientations(rng, n_cells) if self.crystal_orientations else None
|
|
618
|
+
return DeadLeaves(
|
|
619
|
+
domain,
|
|
620
|
+
np.concatenate(centers) if n else np.zeros((0, 3)),
|
|
621
|
+
np.concatenate(radii) if n else np.zeros(0),
|
|
622
|
+
leaf_phases,
|
|
623
|
+
orientations,
|
|
624
|
+
axes=np.concatenate(axes) if spheroid and n else None,
|
|
625
|
+
aspect=aspect,
|
|
626
|
+
background=background,
|
|
627
|
+
model=self,
|
|
628
|
+
seed=seed_info,
|
|
629
|
+
)
|
|
630
|
+
|
|
631
|
+
# -- theory --------------------------------------------------------------------------
|
|
632
|
+
|
|
633
|
+
def _cosines(self, direction=None) -> tuple[np.ndarray, np.ndarray]:
|
|
634
|
+
"""Cosines of the angle between the axes of the leaves and the direction of ``h``,
|
|
635
|
+
with their weights: uniform over the directions without ``direction`` (and for
|
|
636
|
+
isotropic axes), that of the aligned axes, or those of 128 drawn axes."""
|
|
637
|
+
if self.aspect == 1.0:
|
|
638
|
+
return np.zeros(1), np.ones(1)
|
|
639
|
+
if direction is None or isinstance(self.orientation, Isotropic):
|
|
640
|
+
x, w = np.polynomial.legendre.leggauss(48)
|
|
641
|
+
return 0.5 * (x + 1.0), 0.5 * w
|
|
642
|
+
u = np.asarray(direction, dtype=float)
|
|
643
|
+
u = u / np.linalg.norm(u)
|
|
644
|
+
if isinstance(self.orientation, Aligned):
|
|
645
|
+
return np.array([abs(float(np.dot(u, self.orientation.direction)))]), np.ones(1)
|
|
646
|
+
axes = self.orientation.sample(np.random.default_rng(0), 128)
|
|
647
|
+
return np.abs(axes @ u), np.full(128, 1.0 / 128)
|
|
648
|
+
|
|
649
|
+
def normalized_covariogram(self, h, law: Distribution | None = None, direction=None):
|
|
650
|
+
"""``K(h) / K(0)``: the mean geometric covariogram of the leaves of a law of radii
|
|
651
|
+
(that of the first family by default) over their mean volume, for the distances
|
|
652
|
+
``h`` along ``direction`` (or averaged over the directions)."""
|
|
653
|
+
law = law if law is not None else self.families()[0][1]
|
|
654
|
+
h = np.asarray(h, dtype=float)
|
|
655
|
+
x, wx = law.quadrature(64)
|
|
656
|
+
t, wt = self._cosines(direction)
|
|
657
|
+
hm = h[..., None] * np.sqrt(1.0 - t * t + (t / self.aspect) ** 2)
|
|
658
|
+
out = np.zeros(h.shape)
|
|
659
|
+
for xi, wi in zip(x, wx, strict=True): # the volume weights the sizes
|
|
660
|
+
out += wi * xi**3 * (_ball(hm / xi) @ wt)
|
|
661
|
+
return out / np.sum(wx * x**3)
|
|
662
|
+
|
|
663
|
+
def _rates(self, h, direction=None) -> tuple[np.ndarray, np.ndarray]:
|
|
664
|
+
"""The fractions of space ``q`` of the families and their normalized covariograms
|
|
665
|
+
``κ`` at the distances ``h`` (last axis: the families)."""
|
|
666
|
+
families = self.families()
|
|
667
|
+
q = np.array([f[2] for f in families])
|
|
668
|
+
kappa = np.stack([self.normalized_covariogram(h, law, direction)
|
|
669
|
+
for _, law, _, _ in families], axis=-1) # fmt: skip
|
|
670
|
+
return q, kappa
|
|
671
|
+
|
|
672
|
+
def bivariate(self, h, direction=None) -> np.ndarray:
|
|
673
|
+
"""The joint probabilities of the families (and of the background, last, with a
|
|
674
|
+
finite coverage) at ``x`` and ``x + h``: shape ``(..., F, F)`` or ``(..., F + 1,
|
|
675
|
+
F + 1)``."""
|
|
676
|
+
q, kappa = self._rates(h, direction)
|
|
677
|
+
f = len(q)
|
|
678
|
+
if self.coverage is None: # the rates are those of a unit coverage
|
|
679
|
+
lam = np.sum(q * (2.0 - kappa), axis=-1)[..., None]
|
|
680
|
+
same, cross = q * kappa / lam, q * (1.0 - kappa) / lam
|
|
681
|
+
out = np.einsum("...i,j->...ij", cross, q)
|
|
682
|
+
out = out + np.swapaxes(out, -1, -2)
|
|
683
|
+
out[..., range(f), range(f)] += same
|
|
684
|
+
return out
|
|
685
|
+
c = self.coverage
|
|
686
|
+
a, b = c * q * kappa, c * q * (1.0 - kappa)
|
|
687
|
+
lam = np.sum(a + 2.0 * b, axis=-1)[..., None]
|
|
688
|
+
gap = lam - c # >= 0: lam = c (h = 0) to 2c (independent points)
|
|
689
|
+
i1 = -np.expm1(-lam) / lam
|
|
690
|
+
safe = np.where(gap > 1e-12 * c, gap, 1.0)
|
|
691
|
+
i2 = np.where(gap > 1e-12 * c, math.exp(-c) * -np.expm1(-gap) / safe, math.exp(-c))
|
|
692
|
+
out = np.zeros((*np.shape(lam)[:-1], f + 1, f + 1))
|
|
693
|
+
cross = np.einsum("...i,j->...ij", b, q) * (i1 - i2)[..., None]
|
|
694
|
+
out[..., :f, :f] = cross + np.swapaxes(cross, -1, -2)
|
|
695
|
+
out[..., range(f), range(f)] += a * -np.expm1(-lam) / lam
|
|
696
|
+
out[..., :f, f] = b * i2
|
|
697
|
+
out[..., f, :f] = b * i2
|
|
698
|
+
out[..., f, f] = np.exp(-lam[..., 0])
|
|
699
|
+
return out
|
|
700
|
+
|
|
701
|
+
def _cells_of(self, phase: int) -> list[int]:
|
|
702
|
+
"""The indices of the families (and of the background) of a phase in
|
|
703
|
+
:meth:`bivariate`."""
|
|
704
|
+
families = self.families()
|
|
705
|
+
idx = [k for k, f in enumerate(families) if f[0] == phase]
|
|
706
|
+
if self.coverage is not None and self.background == phase:
|
|
707
|
+
idx.append(len(families))
|
|
708
|
+
return idx
|
|
709
|
+
|
|
710
|
+
def covariance(self, h, phase: int = 1, direction=None) -> np.ndarray:
|
|
711
|
+
"""``P(x and x + h in the phase)`` (averaged over the directions without
|
|
712
|
+
``direction``)."""
|
|
713
|
+
idx = self._cells_of(phase)
|
|
714
|
+
p = self.bivariate(h, direction)
|
|
715
|
+
return np.sum(p[..., idx, :][..., :, idx], axis=(-2, -1)) if idx else np.zeros(np.shape(h))
|
|
716
|
+
|
|
717
|
+
def same_leaf_probability(self, h, direction=None) -> np.ndarray:
|
|
718
|
+
"""Probability that two points at the distance ``h`` see the same leaf:
|
|
719
|
+
``Σ a_i / λ`` (times ``1 - e^{-λ}`` with a finite coverage)."""
|
|
720
|
+
q, kappa = self._rates(h, direction)
|
|
721
|
+
lam = np.sum(q * (2.0 - kappa), axis=-1)
|
|
722
|
+
same = np.sum(q * kappa, axis=-1) / lam
|
|
723
|
+
if self.coverage is None:
|
|
724
|
+
return same
|
|
725
|
+
return same * -np.expm1(-self.coverage * lam)
|
|
726
|
+
|
|
727
|
+
def phase_fraction(self, phase: int) -> float:
|
|
728
|
+
"""The fraction of space of a phase."""
|
|
729
|
+
q = sum(f[2] for f in self.families() if f[0] == phase)
|
|
730
|
+
if self.coverage is None:
|
|
731
|
+
return float(q)
|
|
732
|
+
bare = math.exp(-self.coverage)
|
|
733
|
+
return float(q * (1.0 - bare) + (bare if self.background == phase else 0.0))
|
|
734
|
+
|
|
735
|
+
def _isotropic(self) -> bool:
|
|
736
|
+
return self.aspect == 1.0 or isinstance(self.orientation, Isotropic)
|
|
737
|
+
|
|
738
|
+
def integral_range(self, phase: int = 1) -> float:
|
|
739
|
+
"""``∫ (C(h) - p^2) dh / (p (1 - p))`` over the space, for the phase of fraction
|
|
740
|
+
``p`` (Gauss-Legendre in the distance, over 24 directions when the leaves are not
|
|
741
|
+
isotropic)."""
|
|
742
|
+
p = self.phase_fraction(phase)
|
|
743
|
+
if not 0.0 < p < 1.0:
|
|
744
|
+
return 0.0
|
|
745
|
+
reach = max(law.upper() for _, law, _, _ in self.families()) * max(1.0, self.aspect)
|
|
746
|
+
x, w = np.polynomial.legendre.leggauss(256)
|
|
747
|
+
h, w = reach * (x + 1.0), reach * w # up to the largest diameter
|
|
748
|
+
directions = [None] if self._isotropic() else list(_fibonacci(24))
|
|
749
|
+
total = 0.0
|
|
750
|
+
for u in directions:
|
|
751
|
+
centred = self.covariance(h, phase, u) - p * p
|
|
752
|
+
total += float(np.sum(centred * 4.0 * math.pi * h**2 * w))
|
|
753
|
+
return total / len(directions) / (p * (1.0 - p))
|
|
754
|
+
|
|
755
|
+
def theory(self, domain: Domain | None = None) -> dict[str, float]:
|
|
756
|
+
out = {"mean_leaf_volume": self.mean_leaf_volume()}
|
|
757
|
+
n = max(len(self.phase_fractions), self.background + 1 if self.coverage else 0)
|
|
758
|
+
for i in range(n):
|
|
759
|
+
out[f"volume_fraction_{i}"] = self.phase_fraction(i)
|
|
760
|
+
if n > 1:
|
|
761
|
+
out["volume_fraction"] = out["volume_fraction_1"]
|
|
762
|
+
if self.coverage is not None:
|
|
763
|
+
out["background_fraction"] = math.exp(-self.coverage)
|
|
764
|
+
phase = 1 if 0.0 < out.get("volume_fraction_1", 0.0) < 1.0 else self.families()[0][0]
|
|
765
|
+
out["integral_range"] = self.integral_range(phase)
|
|
766
|
+
return out
|