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,924 @@
|
|
|
1
|
+
"""Nested models: structures placed in, or around, the phases of others.
|
|
2
|
+
|
|
3
|
+
* ``cox_spheres``: spheres clustered in the phase 1 of another model (aggregates of
|
|
4
|
+
particles in nanocomposites, at any number of scales): a Cox (doubly stochastic)
|
|
5
|
+
Boolean model, or hard-core spheres placed among its germs.
|
|
6
|
+
* ``coating``: a layer of constant thickness around the phase 1 of a model (an
|
|
7
|
+
interphase), or a shell inside it (hollow members: spheres, fibres, struts).
|
|
8
|
+
* ``fractal_sponge``: the attractor of an iterated function system on a cubic grid (the
|
|
9
|
+
Menger sponge, Cantor dust, the Vicsek fractal, or any set of sub-cubes), iterated a
|
|
10
|
+
finite number of times.
|
|
11
|
+
|
|
12
|
+
Hierarchical lattices of hollow tubes are in :mod:`morphogen.models.hierarchical`, and
|
|
13
|
+
the ``nested`` operation of :mod:`morphogen.models.combination` fills the phase 1 of a
|
|
14
|
+
structure with another.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import math
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
from typing import ClassVar
|
|
22
|
+
|
|
23
|
+
import numpy as np
|
|
24
|
+
from scipy import ndimage
|
|
25
|
+
|
|
26
|
+
from morphogen import theory
|
|
27
|
+
from morphogen._utils import check_fraction, check_positive
|
|
28
|
+
from morphogen.distributions import Constant, Distribution
|
|
29
|
+
from morphogen.domain import Domain, Grid
|
|
30
|
+
from morphogen.image import VoxelImage
|
|
31
|
+
from morphogen.kernels.rsa import rsa_insert
|
|
32
|
+
from morphogen.models.affine import ANISOTROPY, Anisotropy, anisotropic
|
|
33
|
+
from morphogen.models.base import Microstructure, Model, param, register, register_kind
|
|
34
|
+
from morphogen.models.implicit import band_of
|
|
35
|
+
from morphogen.models.union import PrimitiveUnion
|
|
36
|
+
from morphogen.primitives import Segments, Spheres
|
|
37
|
+
from morphogen.seeding import SeedLike, make_rng, seed_from_description
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _child_seeds(rng, seed_info, n: int) -> list:
|
|
41
|
+
"""Seeds of the parts of a nested realization, derived from its own seed."""
|
|
42
|
+
if seed_info is not None:
|
|
43
|
+
return list(seed_from_description(seed_info).spawn(n))
|
|
44
|
+
return list(rng.spawn(n))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _supersampled(fine: np.ndarray, grid: Grid, ss: int) -> np.ndarray:
|
|
48
|
+
nx, ny, nz = grid.shape
|
|
49
|
+
return fine.reshape(nx, ss, ny, ss, nz, ss).mean(axis=(1, 3, 5), dtype=np.float32)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
# -- clustered spheres ----------------------------------------------------------------------
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@register_kind
|
|
56
|
+
class ClusteredSpheres(PrimitiveUnion):
|
|
57
|
+
"""Spheres (phase 1) clustered in aggregates, a realization of another model; the
|
|
58
|
+
aggregates outside the spheres may form a phase of their own."""
|
|
59
|
+
|
|
60
|
+
kind = "clustered_spheres"
|
|
61
|
+
|
|
62
|
+
def __init__(self, domain, spheres, aggregates: Microstructure, aggregate_phase=None, **kw):
|
|
63
|
+
super().__init__(domain, spheres=spheres, **kw)
|
|
64
|
+
self.aggregates = aggregates
|
|
65
|
+
self.aggregate_phase = None if aggregate_phase is None else int(aggregate_phase)
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def phase_names(self) -> dict[int, str]:
|
|
69
|
+
return self.model.active_phases() if self.model is not None else super().phase_names
|
|
70
|
+
|
|
71
|
+
def voxelize(self, shape=None, *, voxel_size=None, grid: Grid | None = None, supersampling=1):
|
|
72
|
+
image = super().voxelize(
|
|
73
|
+
shape, voxel_size=voxel_size, grid=grid, supersampling=supersampling
|
|
74
|
+
)
|
|
75
|
+
if self.aggregate_phase is None or supersampling != 1:
|
|
76
|
+
return image
|
|
77
|
+
inside = self.aggregates.voxelize(grid=image.grid()).data == 1
|
|
78
|
+
data = image.data.copy()
|
|
79
|
+
data[(data == 0) & inside] = self.aggregate_phase
|
|
80
|
+
return image.with_data(data)
|
|
81
|
+
|
|
82
|
+
def implicit_phases(self) -> list[int]:
|
|
83
|
+
phases = {0, 1}
|
|
84
|
+
if self.aggregate_phase is not None:
|
|
85
|
+
phases.add(self.aggregate_phase)
|
|
86
|
+
return sorted(phases)
|
|
87
|
+
|
|
88
|
+
def phase_level_set(
|
|
89
|
+
self, phase: int, shape=None, *, voxel_size=None, grid: Grid | None = None
|
|
90
|
+
) -> VoxelImage:
|
|
91
|
+
"""The implicit function of a phase (see :meth:`Microstructure.phase_level_set`):
|
|
92
|
+
the spheres by their signed distance; the aggregates, when a phase of their own,
|
|
93
|
+
by the level set of their structure outside the spheres."""
|
|
94
|
+
phase = int(phase)
|
|
95
|
+
if phase not in self.implicit_phases():
|
|
96
|
+
raise ValueError(f"phase {phase}: the phases are {self.implicit_phases()}")
|
|
97
|
+
if self.aggregate_phase in (None, 0):
|
|
98
|
+
return Microstructure.phase_level_set(self, phase, shape, voxel_size=voxel_size,
|
|
99
|
+
grid=grid) # fmt: skip
|
|
100
|
+
grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
|
|
101
|
+
spheres = np.asarray(self.level_set(grid=grid).data, dtype=np.float32)
|
|
102
|
+
zone = np.asarray(self.aggregates.level_set(grid=grid).data, dtype=np.float32)
|
|
103
|
+
if self.aggregate_phase == 1: # one phase with the spheres
|
|
104
|
+
data = np.minimum(spheres, zone)
|
|
105
|
+
data = data if phase == 1 else -data
|
|
106
|
+
elif phase == 1:
|
|
107
|
+
data = spheres
|
|
108
|
+
elif phase == self.aggregate_phase:
|
|
109
|
+
data = np.maximum(zone, -spheres)
|
|
110
|
+
else:
|
|
111
|
+
data = -np.minimum(spheres, zone)
|
|
112
|
+
return VoxelImage.from_grid(data, grid, name="level_set", metadata=self.image_metadata())
|
|
113
|
+
|
|
114
|
+
def phase_level_sets_at(self, points, reach: float = np.inf) -> dict[int, np.ndarray]:
|
|
115
|
+
"""The functions of :meth:`phase_level_set` at the points: the signed distance to
|
|
116
|
+
the spheres, and the point-wise level set of the aggregates when they form a phase
|
|
117
|
+
of their own."""
|
|
118
|
+
if self.aggregate_phase in (None, 0):
|
|
119
|
+
phi = PrimitiveUnion.level_set_at(self, points, reach)
|
|
120
|
+
return {0: -phi, 1: phi}
|
|
121
|
+
spheres = PrimitiveUnion.level_set_at(self, points, reach)
|
|
122
|
+
zone = np.asarray(self.aggregates.level_set_at(points, reach), dtype=float)
|
|
123
|
+
if self.aggregate_phase == 1: # one phase with the spheres
|
|
124
|
+
phi = np.minimum(spheres, zone)
|
|
125
|
+
return {0: -phi, 1: phi}
|
|
126
|
+
return {
|
|
127
|
+
0: -np.minimum(spheres, zone),
|
|
128
|
+
1: spheres,
|
|
129
|
+
self.aggregate_phase: np.maximum(zone, -spheres),
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
def level_set_at(self, points, reach: float = np.inf) -> np.ndarray:
|
|
133
|
+
"""The function of phase 1 (:meth:`phase_level_sets_at`)."""
|
|
134
|
+
return self.phase_level_sets_at(points, reach)[1]
|
|
135
|
+
|
|
136
|
+
def implicit_pieces(self, depth: float = 0.0) -> tuple[list, int] | None:
|
|
137
|
+
"""The pieces of the spheres (:meth:`PrimitiveUnion.implicit_pieces`), when the
|
|
138
|
+
aggregates are not a phase of their own nor of the spheres; None otherwise."""
|
|
139
|
+
if self.aggregate_phase not in (None, 0):
|
|
140
|
+
return None
|
|
141
|
+
return super().implicit_pieces(depth)
|
|
142
|
+
|
|
143
|
+
def summary(self) -> dict:
|
|
144
|
+
out = super().summary()
|
|
145
|
+
out.update({f"aggregates_{k}": v for k, v in self.aggregates.summary().items()})
|
|
146
|
+
return out
|
|
147
|
+
|
|
148
|
+
def _geometry(self) -> dict:
|
|
149
|
+
geo = super()._geometry()
|
|
150
|
+
geo["aggregates"] = self.aggregates.to_dict()
|
|
151
|
+
if self.aggregate_phase is not None:
|
|
152
|
+
geo["aggregate_phase"] = self.aggregate_phase
|
|
153
|
+
return geo
|
|
154
|
+
|
|
155
|
+
@classmethod
|
|
156
|
+
def _from_geometry(cls, domain, geometry, **kwargs):
|
|
157
|
+
spheres = Spheres.from_dict(geometry["spheres"]) if "spheres" in geometry else None
|
|
158
|
+
aggregates = Microstructure.from_dict(geometry["aggregates"])
|
|
159
|
+
return cls(domain, spheres, aggregates, geometry.get("aggregate_phase"), **kwargs)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
@register
|
|
163
|
+
@anisotropic
|
|
164
|
+
@dataclass(frozen=True)
|
|
165
|
+
class CoxSpheres(Model):
|
|
166
|
+
"""Spheres clustered in the phase 1 of another model: a Cox Boolean model.
|
|
167
|
+
|
|
168
|
+
The centres of the spheres are Poisson points of intensity ``theta_1`` in the
|
|
169
|
+
aggregates (the phase 1 of ``aggregates``, any model, Cox spheres included) and
|
|
170
|
+
``theta_0`` outside, the spheres being whole (Jeulin & Moreaud 2007; Jean, Jeulin,
|
|
171
|
+
Forest et al. 2011 for carbon black in rubber). With ``hardcore``, non-overlapping
|
|
172
|
+
spheres are placed among such germs by random sequential addition instead. The
|
|
173
|
+
fractions are local: that of the spheres within the aggregates and outside them.
|
|
174
|
+
"""
|
|
175
|
+
|
|
176
|
+
name = "cox_spheres"
|
|
177
|
+
phases: ClassVar[dict[int, str]] = {0: "matrix", 1: "spheres"}
|
|
178
|
+
count_label = "spheres"
|
|
179
|
+
|
|
180
|
+
aggregates: Model = param(
|
|
181
|
+
doc="Model whose phase 1 holds the spheres (aggregates)", kind="model"
|
|
182
|
+
)
|
|
183
|
+
radius: Distribution = param(
|
|
184
|
+
Constant(1.0), doc="Sphere radius (number or distribution)", kind="distribution",
|
|
185
|
+
unit="length",
|
|
186
|
+
) # fmt: skip
|
|
187
|
+
local_fraction: float | None = param(
|
|
188
|
+
None, doc="Volume fraction of the spheres in the aggregates", kind="fraction"
|
|
189
|
+
)
|
|
190
|
+
intensity: float | None = param(
|
|
191
|
+
None, doc="Number of sphere centres per unit volume of the aggregates", unit="1/length^3"
|
|
192
|
+
)
|
|
193
|
+
outside_fraction: float = param(
|
|
194
|
+
0.0, doc="Volume fraction of the spheres outside the aggregates", kind="fraction"
|
|
195
|
+
)
|
|
196
|
+
hardcore: bool = param(
|
|
197
|
+
False, doc="Non-overlapping spheres (random sequential addition)", kind="bool"
|
|
198
|
+
)
|
|
199
|
+
min_gap: float = param(0.0, doc="Hard-core spheres: minimal gap between them", unit="length")
|
|
200
|
+
aggregate_phase: int | None = param(
|
|
201
|
+
None, doc="Phase of the aggregates outside the spheres (default: the matrix)", kind="int"
|
|
202
|
+
)
|
|
203
|
+
anisotropy: Anisotropy | None = param(None, doc=ANISOTROPY, kind="anisotropy", kw_only=True)
|
|
204
|
+
|
|
205
|
+
def _validate(self) -> None:
|
|
206
|
+
if (self.local_fraction is None) == (self.intensity is None):
|
|
207
|
+
raise ValueError("give exactly one of 'local_fraction' and 'intensity'")
|
|
208
|
+
if self.local_fraction is not None:
|
|
209
|
+
check_fraction(self.local_fraction, "local_fraction")
|
|
210
|
+
else:
|
|
211
|
+
check_positive(self.intensity, "intensity")
|
|
212
|
+
if self.hardcore:
|
|
213
|
+
raise ValueError("hard-core spheres: give their local_fraction")
|
|
214
|
+
if not 0.0 <= self.outside_fraction < 1.0:
|
|
215
|
+
raise ValueError("outside_fraction: in [0, 1)")
|
|
216
|
+
check_positive(self.min_gap, "min_gap", allow_zero=True)
|
|
217
|
+
if self.aggregate_phase is not None and not 2 <= self.aggregate_phase <= 255:
|
|
218
|
+
raise ValueError("aggregate_phase: a phase index from 2 to 255")
|
|
219
|
+
|
|
220
|
+
@property
|
|
221
|
+
def has_level_set(self) -> bool:
|
|
222
|
+
return self.aggregate_phase is None
|
|
223
|
+
|
|
224
|
+
@property
|
|
225
|
+
def supports_periodic(self) -> bool:
|
|
226
|
+
return self.aggregates.supports_periodic
|
|
227
|
+
|
|
228
|
+
def active_phases(self) -> dict[int, str]:
|
|
229
|
+
out = dict(self.phases)
|
|
230
|
+
if self.aggregate_phase is not None:
|
|
231
|
+
out[self.aggregate_phase] = f"aggregates ({self.aggregates.name})"
|
|
232
|
+
return out
|
|
233
|
+
|
|
234
|
+
@property
|
|
235
|
+
def mean_volume(self) -> float:
|
|
236
|
+
return 4.0 / 3.0 * math.pi * self.radius.moment(3)
|
|
237
|
+
|
|
238
|
+
@property
|
|
239
|
+
def intensities(self) -> tuple[float, float]:
|
|
240
|
+
"""Intensities of the germs in and out of the aggregates (Boolean spheres)."""
|
|
241
|
+
inside = (
|
|
242
|
+
self.intensity
|
|
243
|
+
if self.intensity is not None
|
|
244
|
+
else theory.boolean_intensity(self.local_fraction, self.mean_volume)
|
|
245
|
+
)
|
|
246
|
+
outside = theory.boolean_intensity(self.outside_fraction, self.mean_volume)
|
|
247
|
+
return inside, outside
|
|
248
|
+
|
|
249
|
+
def generate(self, domain: Domain, seed: SeedLike = None) -> ClusteredSpheres:
|
|
250
|
+
self._check_domain(domain)
|
|
251
|
+
rng, seed_info = make_rng(seed)
|
|
252
|
+
seeds = _child_seeds(rng, seed_info, 2)
|
|
253
|
+
rmax = self.radius.upper()
|
|
254
|
+
reach = (2.0 * rmax + self.min_gap) if self.hardcore else rmax
|
|
255
|
+
if domain.periodic:
|
|
256
|
+
if 2.0 * reach >= min(domain.size):
|
|
257
|
+
raise ValueError("cox_spheres: spheres too large for the periodic box")
|
|
258
|
+
window = domain
|
|
259
|
+
else:
|
|
260
|
+
window = domain.dilated(reach)
|
|
261
|
+
aggregates = self.aggregates.generate(window, seeds[0])
|
|
262
|
+
local = np.random.default_rng(seeds[1])
|
|
263
|
+
if self.hardcore:
|
|
264
|
+
centers, radii = self._hardcore(window, aggregates, local)
|
|
265
|
+
else:
|
|
266
|
+
inside, outside = self.intensities
|
|
267
|
+
top = max(inside, outside)
|
|
268
|
+
n = local.poisson(top * window.volume)
|
|
269
|
+
centers = window.lower + local.random((n, 3)) * window.lengths
|
|
270
|
+
rate = np.where(aggregates.contains(centers), inside, outside)
|
|
271
|
+
centers = centers[local.random(n) * top < rate]
|
|
272
|
+
radii = self.radius.sample(local, len(centers))
|
|
273
|
+
spheres = Spheres(centers, radii)
|
|
274
|
+
if not domain.periodic:
|
|
275
|
+
spheres = spheres.subset(domain.distance_to_box(spheres.centers) <= spheres.radii)
|
|
276
|
+
return ClusteredSpheres(
|
|
277
|
+
domain, spheres, aggregates, self.aggregate_phase, model=self, seed=seed_info
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
def _hardcore(self, window: Domain, aggregates: Microstructure, rng):
|
|
281
|
+
"""Random sequential addition among the germs of the Cox process (a periodic box,
|
|
282
|
+
cropped later for non-periodic domains)."""
|
|
283
|
+
probe = window.lower + rng.random((20000, 3)) * window.lengths
|
|
284
|
+
p_in = float(aggregates.contains(probe).mean())
|
|
285
|
+
target = window.volume * (p_in * self.local_fraction + (1 - p_in) * self.outside_fraction)
|
|
286
|
+
radii = np.empty(0)
|
|
287
|
+
while np.sum(4.0 / 3.0 * math.pi * radii**3) < target:
|
|
288
|
+
more = self.radius.sample(rng, int(0.2 * target / self.mean_volume) + 16)
|
|
289
|
+
radii = np.concatenate([radii, more])
|
|
290
|
+
if radii.size == 0:
|
|
291
|
+
return np.zeros((0, 3)), radii
|
|
292
|
+
cum = np.cumsum(4.0 / 3.0 * math.pi * radii**3)
|
|
293
|
+
radii = np.sort(radii[: int(np.searchsorted(cum, target)) + 1])[::-1].copy()
|
|
294
|
+
top = max(self.local_fraction, self.outside_fraction)
|
|
295
|
+
box = window.lengths
|
|
296
|
+
reach = 2.0 * radii.max() + self.min_gap if radii.size else 1.0
|
|
297
|
+
cell_n = np.maximum(1, np.floor(box / reach)).astype(np.int64)
|
|
298
|
+
cell_h = box / cell_n
|
|
299
|
+
head = np.full(int(np.prod(cell_n)), -1, dtype=np.int64)
|
|
300
|
+
nxt = np.full(len(radii), -1, dtype=np.int64)
|
|
301
|
+
pos = np.zeros((len(radii), 3))
|
|
302
|
+
placed, attempts, budget = 0, 0, 20_000 * max(len(radii), 1)
|
|
303
|
+
while placed < len(radii) and attempts < budget:
|
|
304
|
+
cand = rng.random((8192, 3)) * box
|
|
305
|
+
rate = np.where(
|
|
306
|
+
aggregates.contains(window.lower + cand), self.local_fraction, self.outside_fraction
|
|
307
|
+
)
|
|
308
|
+
cand = np.ascontiguousarray(cand[rng.random(len(cand)) * top < rate])
|
|
309
|
+
placed, _ = rsa_insert(
|
|
310
|
+
radii, float(self.min_gap), box, cell_h, cell_n, head, nxt, pos, placed, cand
|
|
311
|
+
)
|
|
312
|
+
attempts += 8192
|
|
313
|
+
if placed < len(radii):
|
|
314
|
+
raise RuntimeError(
|
|
315
|
+
f"cox_spheres: {placed} of {len(radii)} hard-core spheres placed; lower the "
|
|
316
|
+
"local fraction (random sequential addition jams near 0.38 for equal spheres)"
|
|
317
|
+
)
|
|
318
|
+
return window.lower + pos, radii
|
|
319
|
+
|
|
320
|
+
def expected_count(self, domain: Domain) -> float | None:
|
|
321
|
+
"""Mean number of sphere centres in the domain (Boolean spheres)."""
|
|
322
|
+
try:
|
|
323
|
+
p = self.aggregates.theory(domain)["volume_fraction"]
|
|
324
|
+
except (KeyError, ValueError, NotImplementedError):
|
|
325
|
+
return None
|
|
326
|
+
if self.hardcore:
|
|
327
|
+
return (
|
|
328
|
+
domain.volume
|
|
329
|
+
* (p * self.local_fraction + (1 - p) * self.outside_fraction)
|
|
330
|
+
/ (self.mean_volume)
|
|
331
|
+
)
|
|
332
|
+
inside, outside = self.intensities
|
|
333
|
+
return (inside * p + outside * (1.0 - p)) * domain.volume
|
|
334
|
+
|
|
335
|
+
def theory(self, domain: Domain | None = None) -> dict[str, float]:
|
|
336
|
+
"""Fractions when the spheres are small compared with the aggregates (a sphere
|
|
337
|
+
rarely straddles their boundary): ``1 - p exp(-theta_1 V) - (1 - p) exp(-theta_0
|
|
338
|
+
V)`` for Boolean spheres, ``p f_1 + (1 - p) f_0`` for hard-core ones, ``p`` being
|
|
339
|
+
the fraction of the aggregates."""
|
|
340
|
+
try:
|
|
341
|
+
p = self.aggregates.theory(domain).get("volume_fraction")
|
|
342
|
+
except (ValueError, NotImplementedError):
|
|
343
|
+
p = None
|
|
344
|
+
inside, outside = self.intensities
|
|
345
|
+
out = {"intensity_inside": inside, "intensity_outside": outside}
|
|
346
|
+
if p is None:
|
|
347
|
+
return out
|
|
348
|
+
out["aggregate_fraction"] = p
|
|
349
|
+
if self.hardcore:
|
|
350
|
+
out["volume_fraction"] = p * self.local_fraction + (1 - p) * self.outside_fraction
|
|
351
|
+
return out
|
|
352
|
+
v = self.mean_volume
|
|
353
|
+
q_in, q_out = math.exp(-inside * v), math.exp(-outside * v)
|
|
354
|
+
out["volume_fraction"] = 1.0 - p * q_in - (1.0 - p) * q_out
|
|
355
|
+
area = 4.0 * math.pi * self.radius.moment(2)
|
|
356
|
+
out["specific_surface"] = area * (inside * p * q_in + outside * (1.0 - p) * q_out)
|
|
357
|
+
return out
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
# -- coatings and shells ---------------------------------------------------------------------
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _signed_distance(inner: Microstructure, grid: Grid, band: float) -> tuple:
|
|
364
|
+
"""Phases of a structure on a grid and the signed distance to its phase 1 (negative
|
|
365
|
+
inside): exact for unions of spheres and segments, from the Euclidean distance
|
|
366
|
+
transform of the voxels otherwise."""
|
|
367
|
+
phases = inner.voxelize(grid=grid).data
|
|
368
|
+
if isinstance(inner, PrimitiveUnion):
|
|
369
|
+
return phases, inner.level_set(grid=grid, band=band).data.astype(np.float64)
|
|
370
|
+
solid = phases == 1
|
|
371
|
+
h = grid.spacing
|
|
372
|
+
wrap = "wrap" if inner.domain.periodic else "nearest"
|
|
373
|
+
outside = _edt(~solid, h, wrap, band)
|
|
374
|
+
inside = _edt(solid, h, wrap, band)
|
|
375
|
+
half = 0.5 * float(np.min(h)) # from voxel centres to the interface between them
|
|
376
|
+
return phases, np.where(solid, -(inside - half), outside - half)
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def _edt(mask: np.ndarray, spacing, mode: str, band: float = math.inf) -> np.ndarray:
|
|
380
|
+
"""Distance from the voxels of ``mask`` to the nearest voxel outside it, exact up to
|
|
381
|
+
``band`` and at least ``band`` beyond (periodic: on a copy wrapped over the band)."""
|
|
382
|
+
if not mask.any():
|
|
383
|
+
return np.zeros(mask.shape)
|
|
384
|
+
if mask.all():
|
|
385
|
+
return np.full(mask.shape, np.inf)
|
|
386
|
+
if mode == "wrap":
|
|
387
|
+
h = np.broadcast_to(np.asarray(spacing, dtype=float), (mask.ndim,))
|
|
388
|
+
pad = [min(n, math.ceil(band / s) + 1) for n, s in zip(mask.shape, h, strict=True)]
|
|
389
|
+
tiled = np.pad(mask, [(p, p) for p in pad], mode="wrap")
|
|
390
|
+
d = ndimage.distance_transform_edt(tiled, sampling=spacing)
|
|
391
|
+
return d[tuple(slice(p, p + n) for p, n in zip(pad, mask.shape, strict=True))]
|
|
392
|
+
return ndimage.distance_transform_edt(mask, sampling=spacing)
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
@register_kind
|
|
396
|
+
class CoatedStructure(Microstructure):
|
|
397
|
+
"""A structure with a layer around its phase 1 (outside) or a shell inside it."""
|
|
398
|
+
|
|
399
|
+
kind = "coated"
|
|
400
|
+
|
|
401
|
+
def __init__(self, domain, inner, thickness, side, phase, core_phase, bores=None, **kw):
|
|
402
|
+
super().__init__(domain, **kw)
|
|
403
|
+
self.inner = inner
|
|
404
|
+
self.thickness = float(thickness)
|
|
405
|
+
self.side = side
|
|
406
|
+
self.phase = int(phase)
|
|
407
|
+
self.core_phase = int(core_phase)
|
|
408
|
+
self.bores = bores # hollow unions of spheres and segments: the same, thinner
|
|
409
|
+
|
|
410
|
+
@property
|
|
411
|
+
def phase_names(self) -> dict[int, str]:
|
|
412
|
+
return self.model.active_phases() if self.model is not None else super().phase_names
|
|
413
|
+
|
|
414
|
+
def _phases_on(self, grid: Grid) -> np.ndarray:
|
|
415
|
+
if self.bores is not None: # union of the members minus the union of their bores
|
|
416
|
+
outer = self.inner.voxelize(grid=grid).data == 1
|
|
417
|
+
bore = self.bores.voxelize(grid=grid).data == 1
|
|
418
|
+
out = np.zeros(grid.shape, dtype=np.uint8)
|
|
419
|
+
out[outer] = 1
|
|
420
|
+
out[outer & bore] = self.core_phase
|
|
421
|
+
return out
|
|
422
|
+
band = self.thickness + 2.0 * float(np.max(grid.spacing))
|
|
423
|
+
phases, dist = _signed_distance(self.inner, grid, band)
|
|
424
|
+
out = phases.astype(np.uint8, copy=True)
|
|
425
|
+
if self.side == "outside":
|
|
426
|
+
out[(phases == 0) & (dist <= self.thickness)] = self.phase
|
|
427
|
+
else:
|
|
428
|
+
out[(phases == 1) & (dist < -self.thickness)] = self.core_phase
|
|
429
|
+
return out
|
|
430
|
+
|
|
431
|
+
def voxelize(self, shape=None, *, voxel_size=None, grid: Grid | None = None, supersampling=1):
|
|
432
|
+
grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
|
|
433
|
+
ss = int(supersampling)
|
|
434
|
+
if ss == 1:
|
|
435
|
+
data = self._phases_on(grid)
|
|
436
|
+
return VoxelImage.from_grid(data, grid, name="phase", metadata=self.image_metadata())
|
|
437
|
+
fine = Grid(grid.domain, tuple(n * ss for n in grid.shape))
|
|
438
|
+
data = _supersampled((self._phases_on(fine) == 1).astype(np.float32), grid, ss)
|
|
439
|
+
return VoxelImage.from_grid(data, grid, name="fraction", metadata=self.image_metadata())
|
|
440
|
+
|
|
441
|
+
def level_set(self, shape=None, *, voxel_size=None, grid: Grid | None = None) -> VoxelImage:
|
|
442
|
+
"""Hollow members (a void core): the union minus the bores (exact sets), or the
|
|
443
|
+
shell ``-t <= d <= 0`` of the signed distance; a coating leaves phase 1 as is."""
|
|
444
|
+
grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
|
|
445
|
+
if self.side == "outside":
|
|
446
|
+
return self.inner.level_set(grid=grid)
|
|
447
|
+
if self.core_phase != 0:
|
|
448
|
+
raise NotImplementedError("a shell with a filled core has three phases")
|
|
449
|
+
if self.bores is not None:
|
|
450
|
+
outer = self.inner.level_set(grid=grid).data.astype(np.float32)
|
|
451
|
+
bore = self.bores.level_set(grid=grid).data.astype(np.float32)
|
|
452
|
+
data = np.maximum(outer, -bore)
|
|
453
|
+
else:
|
|
454
|
+
band = self.thickness + 4.0 * float(np.max(grid.spacing))
|
|
455
|
+
_, dist = _signed_distance(self.inner, grid, band)
|
|
456
|
+
data = np.maximum(dist, -dist - self.thickness).astype(np.float32)
|
|
457
|
+
return VoxelImage.from_grid(data, grid, name="level_set", metadata=self.image_metadata())
|
|
458
|
+
|
|
459
|
+
def implicit_phases(self) -> list[int]:
|
|
460
|
+
if self.side == "outside":
|
|
461
|
+
return sorted({0, 1, self.phase})
|
|
462
|
+
return sorted({0, 1, self.core_phase})
|
|
463
|
+
|
|
464
|
+
def phase_level_set(
|
|
465
|
+
self, phase: int, shape=None, *, voxel_size=None, grid: Grid | None = None
|
|
466
|
+
) -> VoxelImage:
|
|
467
|
+
"""The implicit function of a phase (see :meth:`Microstructure.phase_level_set`),
|
|
468
|
+
from the signed distance ``d`` to the phase 1 of the structure: a coating of
|
|
469
|
+
thickness ``t`` is ``0 < d < t``, a shell ``-t < d < 0`` and its core ``d < -t``
|
|
470
|
+
(hollow unions of spheres and segments: the union minus the bores, and the
|
|
471
|
+
bores). The distance is exact for unions of spheres and segments; for the other
|
|
472
|
+
structures it is that of their voxels on the grid (as in their images)."""
|
|
473
|
+
phase = int(phase)
|
|
474
|
+
if phase not in self.implicit_phases():
|
|
475
|
+
raise ValueError(f"phase {phase}: the phases are {self.implicit_phases()}")
|
|
476
|
+
grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
|
|
477
|
+
clip = band_of(grid)
|
|
478
|
+
t = self.thickness
|
|
479
|
+
if self.bores is not None:
|
|
480
|
+
outer = np.asarray(self.inner.level_set(grid=grid).data, dtype=np.float64)
|
|
481
|
+
bore = np.asarray(self.bores.level_set(grid=grid).data, dtype=np.float64)
|
|
482
|
+
regions = {1: np.maximum(outer, -bore), self.core_phase: np.maximum(outer, bore)}
|
|
483
|
+
outside = -outer
|
|
484
|
+
else:
|
|
485
|
+
_, d = _signed_distance(self.inner, grid, t + clip)
|
|
486
|
+
if self.side == "outside":
|
|
487
|
+
regions = {1: d, self.phase: np.maximum(-d, d - t)}
|
|
488
|
+
outside = t - d
|
|
489
|
+
else:
|
|
490
|
+
regions = {1: np.maximum(d, -d - t), self.core_phase: d + t}
|
|
491
|
+
outside = -d
|
|
492
|
+
# the phases that share an index are one (a core of the phase of the matrix...)
|
|
493
|
+
fields: dict[int, np.ndarray] = {0: outside}
|
|
494
|
+
for k in (1, *(q for q in regions if q != 1)):
|
|
495
|
+
fields[k] = np.minimum(fields[k], regions[k]) if k in fields else regions[k]
|
|
496
|
+
data = np.clip(fields[phase], -clip, clip).astype(np.float32)
|
|
497
|
+
return VoxelImage.from_grid(data, grid, name="level_set", metadata=self.image_metadata())
|
|
498
|
+
|
|
499
|
+
def _exact_distance(self) -> bool:
|
|
500
|
+
"""Whether the distance to the phase 1 of the structure is known at any point: a
|
|
501
|
+
union of spheres and segments of two phases (the distance of the other structures
|
|
502
|
+
is that of their voxels, :func:`_signed_distance`)."""
|
|
503
|
+
return isinstance(self.inner, PrimitiveUnion) and self.inner.implicit_phases() == [0, 1]
|
|
504
|
+
|
|
505
|
+
def phase_level_sets_at(self, points, reach: float = np.inf) -> dict[int, np.ndarray]:
|
|
506
|
+
"""The functions of :meth:`phase_level_set` at the points, for the coatings and
|
|
507
|
+
shells of a union of spheres and segments (whose signed distance is exact
|
|
508
|
+
there): the same functions of that distance, or of those of the union and of its
|
|
509
|
+
bores. The coatings of the other structures, whose distance is that of their
|
|
510
|
+
voxels, have none."""
|
|
511
|
+
if not self._exact_distance():
|
|
512
|
+
raise NotImplementedError(
|
|
513
|
+
"the coatings and shells of a structure that is not a union of spheres and "
|
|
514
|
+
"segments: the distance to its phase 1 is that of its voxels"
|
|
515
|
+
)
|
|
516
|
+
pts = np.asarray(points, dtype=float).reshape(-1, 3)
|
|
517
|
+
t = self.thickness
|
|
518
|
+
if not np.isfinite(reach):
|
|
519
|
+
reach = 0.1 * float(self.domain.lengths.min()) + t
|
|
520
|
+
reach = float(reach)
|
|
521
|
+
if self.bores is not None:
|
|
522
|
+
outer = self.inner.signed_distance(pts, reach)
|
|
523
|
+
bore = self.bores.signed_distance(pts, reach)
|
|
524
|
+
regions = {1: np.maximum(outer, -bore), self.core_phase: np.maximum(outer, bore)}
|
|
525
|
+
outside = -outer
|
|
526
|
+
else:
|
|
527
|
+
d = self.inner.signed_distance(pts, reach + t)
|
|
528
|
+
if self.side == "outside":
|
|
529
|
+
regions = {1: d, self.phase: np.maximum(-d, d - t)}
|
|
530
|
+
outside = t - d
|
|
531
|
+
else:
|
|
532
|
+
regions = {1: np.maximum(d, -d - t), self.core_phase: d + t}
|
|
533
|
+
outside = -d
|
|
534
|
+
# the phases that share an index are one (a core of the phase of the matrix...)
|
|
535
|
+
fields: dict[int, np.ndarray] = {0: outside}
|
|
536
|
+
for k in (1, *(q for q in regions if q != 1)):
|
|
537
|
+
fields[k] = np.minimum(fields[k], regions[k]) if k in fields else regions[k]
|
|
538
|
+
return {k: np.clip(fields[k], -reach, reach) for k in self.implicit_phases()}
|
|
539
|
+
|
|
540
|
+
def implicit_pieces(self, depth: float = 0.0) -> tuple[list, int] | None:
|
|
541
|
+
"""The pieces of a coated union of spheres and segments, or of its hollow
|
|
542
|
+
members (see :mod:`morphogen.models.pieces`): the primitives, then the same with
|
|
543
|
+
their radii increased by the thickness of the coating; the bores of hollow
|
|
544
|
+
members, then the primitives. None for the other structures."""
|
|
545
|
+
from morphogen.models.pieces import Piece, union_pieces
|
|
546
|
+
|
|
547
|
+
inner = self.inner
|
|
548
|
+
if not isinstance(inner, PrimitiveUnion) or inner.implicit_phases() != [0, 1]:
|
|
549
|
+
return None
|
|
550
|
+
if self.side == "outside":
|
|
551
|
+
pieces = [Piece(1, part) for part in union_pieces(inner, 0.0, depth)]
|
|
552
|
+
pieces += [
|
|
553
|
+
Piece(self.phase, part) for part in union_pieces(inner, self.thickness, depth)
|
|
554
|
+
]
|
|
555
|
+
return pieces, 0
|
|
556
|
+
if self.bores is None:
|
|
557
|
+
return None
|
|
558
|
+
pieces = [Piece(self.core_phase, part) for part in union_pieces(self.bores, 0.0, depth)]
|
|
559
|
+
pieces += [Piece(1, part) for part in union_pieces(inner, 0.0, depth)]
|
|
560
|
+
return pieces, 0
|
|
561
|
+
|
|
562
|
+
@property
|
|
563
|
+
def lipschitz(self) -> float:
|
|
564
|
+
parts = [self.inner] + ([self.bores] if self.bores is not None else [])
|
|
565
|
+
return max(float(getattr(p, "lipschitz", 1.0)) for p in parts)
|
|
566
|
+
|
|
567
|
+
def level_set_at(self, points, reach: float = np.inf) -> np.ndarray:
|
|
568
|
+
"""As :meth:`level_set`, at the points: the level set of the structure (coating),
|
|
569
|
+
or the function of phase 1 of :meth:`phase_level_sets_at` (the members of a union
|
|
570
|
+
less their bores, the shell of its signed distance)."""
|
|
571
|
+
if self.side == "outside":
|
|
572
|
+
return self.inner.level_set_at(points, reach)
|
|
573
|
+
return self.phase_level_sets_at(points, reach)[1]
|
|
574
|
+
|
|
575
|
+
def contains(self, points) -> np.ndarray:
|
|
576
|
+
"""Phase 1: that of the structure (coating), or its shell (hollow members of
|
|
577
|
+
unions of spheres and segments)."""
|
|
578
|
+
if self.side == "outside":
|
|
579
|
+
return self.inner.contains(points)
|
|
580
|
+
if self.bores is None:
|
|
581
|
+
raise NotImplementedError("point queries of shells need unions of spheres or segments")
|
|
582
|
+
inside = self.inner.contains(points)
|
|
583
|
+
return inside & ~self.bores.contains(points) if self.core_phase != 1 else inside
|
|
584
|
+
|
|
585
|
+
def summary(self) -> dict:
|
|
586
|
+
return {f"inner_{k}": v for k, v in self.inner.summary().items()}
|
|
587
|
+
|
|
588
|
+
def _geometry(self) -> dict:
|
|
589
|
+
geo = {
|
|
590
|
+
"inner": self.inner.to_dict(),
|
|
591
|
+
"thickness": self.thickness,
|
|
592
|
+
"side": self.side,
|
|
593
|
+
"phase": self.phase,
|
|
594
|
+
"core_phase": self.core_phase,
|
|
595
|
+
}
|
|
596
|
+
if self.bores is not None:
|
|
597
|
+
geo["bores"] = self.bores.to_dict()
|
|
598
|
+
return geo
|
|
599
|
+
|
|
600
|
+
@classmethod
|
|
601
|
+
def _from_geometry(cls, domain, geometry, **kwargs):
|
|
602
|
+
bores = geometry.get("bores")
|
|
603
|
+
return cls(
|
|
604
|
+
domain,
|
|
605
|
+
Microstructure.from_dict(geometry["inner"]),
|
|
606
|
+
geometry["thickness"],
|
|
607
|
+
geometry["side"],
|
|
608
|
+
geometry["phase"],
|
|
609
|
+
geometry["core_phase"],
|
|
610
|
+
None if bores is None else Microstructure.from_dict(bores),
|
|
611
|
+
**kwargs,
|
|
612
|
+
)
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def bores_of(union: PrimitiveUnion, thickness: float) -> PrimitiveUnion:
|
|
616
|
+
"""The same spheres and segments, thinner by ``thickness`` (those thinner than it
|
|
617
|
+
are left out: they stay full)."""
|
|
618
|
+
sph, seg = union.spheres, union.segments
|
|
619
|
+
keep_s = sph.radii > thickness
|
|
620
|
+
keep_g = seg.radii > thickness
|
|
621
|
+
spheres = Spheres(sph.centers[keep_s], sph.radii[keep_s] - thickness)
|
|
622
|
+
segments = Segments(
|
|
623
|
+
seg.start[keep_g], seg.end[keep_g], seg.radii[keep_g] - thickness,
|
|
624
|
+
round_caps=seg.round_caps,
|
|
625
|
+
) # fmt: skip
|
|
626
|
+
return PrimitiveUnion(union.domain, spheres=spheres, segments=segments)
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
@register
|
|
630
|
+
@dataclass(frozen=True)
|
|
631
|
+
class Coating(Model):
|
|
632
|
+
"""A layer of constant thickness on the phase 1 of a model.
|
|
633
|
+
|
|
634
|
+
``outside``: a coating (an interphase) of phase ``phase`` around it, within the
|
|
635
|
+
distance ``thickness``. ``inside``: a shell of that thickness, the core becoming the
|
|
636
|
+
phase ``core_phase`` (0: hollow members). Unions of spheres and segments (Boolean
|
|
637
|
+
and hard-core spheres, fibres, strut lattices...) are coated exactly, and their
|
|
638
|
+
members are hollowed one by one (each minus a thinner copy: bores join where members
|
|
639
|
+
meet); other structures through the distance transform of their voxels.
|
|
640
|
+
"""
|
|
641
|
+
|
|
642
|
+
name = "coating"
|
|
643
|
+
phases: ClassVar[dict[int, str]] = {0: "matrix", 1: "phase 1 of the model", 2: "coating"}
|
|
644
|
+
|
|
645
|
+
model: Model = param(doc="Model whose phase 1 is coated or hollowed", kind="model")
|
|
646
|
+
thickness: float = param(doc="Thickness of the layer", unit="length")
|
|
647
|
+
side: str = param(
|
|
648
|
+
"outside", doc="outside (a coating around phase 1) or inside (a shell)", kind="str"
|
|
649
|
+
)
|
|
650
|
+
phase: int = param(2, doc="Phase of the coating (outside)", kind="int")
|
|
651
|
+
core_phase: int = param(
|
|
652
|
+
0, doc="Phase of the core within the shell (inside; 0: hollow)", kind="int"
|
|
653
|
+
)
|
|
654
|
+
|
|
655
|
+
def _validate(self) -> None:
|
|
656
|
+
check_positive(self.thickness, "thickness")
|
|
657
|
+
if self.side not in ("outside", "inside"):
|
|
658
|
+
raise ValueError("side: 'outside' (a coating) or 'inside' (a shell)")
|
|
659
|
+
if not 2 <= self.phase <= 255:
|
|
660
|
+
raise ValueError("phase: a phase index from 2 to 255")
|
|
661
|
+
if self.core_phase == 1 or not 0 <= self.core_phase <= 255:
|
|
662
|
+
raise ValueError("core_phase: 0 (hollow) or a phase index from 2 to 255")
|
|
663
|
+
|
|
664
|
+
@property
|
|
665
|
+
def has_level_set(self) -> bool: # two phases: hollow members
|
|
666
|
+
return self.side == "inside" and self.core_phase == 0 and self.model.has_level_set
|
|
667
|
+
|
|
668
|
+
@property
|
|
669
|
+
def supports_periodic(self) -> bool:
|
|
670
|
+
return self.model.supports_periodic
|
|
671
|
+
|
|
672
|
+
def active_phases(self) -> dict[int, str]:
|
|
673
|
+
if self.side == "outside":
|
|
674
|
+
return {0: "matrix", 1: f"phase 1 ({self.model.name})", self.phase: "coating"}
|
|
675
|
+
out = {0: "matrix", 1: "shell"}
|
|
676
|
+
if self.core_phase != 0:
|
|
677
|
+
out[self.core_phase] = "core"
|
|
678
|
+
return out
|
|
679
|
+
|
|
680
|
+
def generate(self, domain: Domain, seed: SeedLike = None) -> CoatedStructure:
|
|
681
|
+
self._check_domain(domain)
|
|
682
|
+
rng, seed_info = make_rng(seed)
|
|
683
|
+
inner = self.model.generate(domain, _child_seeds(rng, seed_info, 1)[0])
|
|
684
|
+
bores = None
|
|
685
|
+
if self.side == "inside" and isinstance(inner, PrimitiveUnion):
|
|
686
|
+
bores = bores_of(inner, self.thickness)
|
|
687
|
+
return CoatedStructure(
|
|
688
|
+
domain,
|
|
689
|
+
inner,
|
|
690
|
+
self.thickness,
|
|
691
|
+
self.side,
|
|
692
|
+
self.phase,
|
|
693
|
+
self.core_phase,
|
|
694
|
+
bores,
|
|
695
|
+
model=self,
|
|
696
|
+
seed=seed_info,
|
|
697
|
+
)
|
|
698
|
+
|
|
699
|
+
def theory(self, domain: Domain | None = None) -> dict[str, float]:
|
|
700
|
+
"""Boolean spheres: their coating is the dilation of a Boolean model, the Boolean
|
|
701
|
+
model of the spheres of radii ``R + t``."""
|
|
702
|
+
from morphogen.models.boolean import BooleanSpheres
|
|
703
|
+
|
|
704
|
+
m = self.model
|
|
705
|
+
if not isinstance(m, BooleanSpheres) or self.side != "outside":
|
|
706
|
+
return {}
|
|
707
|
+
theta, t = m.theta, self.thickness
|
|
708
|
+
nodes, weights = m.radius.quadrature(64)
|
|
709
|
+
dilated = float(np.sum(weights * 4.0 / 3.0 * math.pi * (nodes + t) ** 3))
|
|
710
|
+
p = 1.0 - math.exp(-theta * m.mean_grain_volume)
|
|
711
|
+
return {
|
|
712
|
+
"volume_fraction": p,
|
|
713
|
+
"coating_fraction": 1.0 - math.exp(-theta * dilated) - p,
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
|
|
717
|
+
# -- fractal sponges ---------------------------------------------------------------------------
|
|
718
|
+
|
|
719
|
+
#: Sub-cubes kept by the classical patterns of a 3 x 3 x 3 subdivision.
|
|
720
|
+
_CENTRE_AND_FACES = {(1, 1, 1), (0, 1, 1), (2, 1, 1), (1, 0, 1), (1, 2, 1), (1, 1, 0), (1, 1, 2)}
|
|
721
|
+
PATTERNS = {
|
|
722
|
+
"menger": sorted(set(np.ndindex(3, 3, 3)) - _CENTRE_AND_FACES),
|
|
723
|
+
"vicsek": sorted(_CENTRE_AND_FACES),
|
|
724
|
+
"cantor_dust": sorted(c for c in np.ndindex(3, 3, 3) if 1 not in c),
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
|
|
728
|
+
@register_kind
|
|
729
|
+
class FractalStructure(Microstructure):
|
|
730
|
+
"""Periodic tiling of the cube kept by an iterated function system."""
|
|
731
|
+
|
|
732
|
+
kind = "fractal_sponge"
|
|
733
|
+
|
|
734
|
+
def __init__(self, domain, cell_size, subdivisions, kept, level, **kw):
|
|
735
|
+
super().__init__(domain, **kw)
|
|
736
|
+
self.cell_size = float(cell_size)
|
|
737
|
+
self.subdivisions = int(subdivisions)
|
|
738
|
+
self.kept = [tuple(int(v) for v in c) for c in kept]
|
|
739
|
+
self.level = int(level)
|
|
740
|
+
k = self.subdivisions
|
|
741
|
+
self._mask = np.zeros(k**3, dtype=bool)
|
|
742
|
+
for i, j, m in self.kept:
|
|
743
|
+
self._mask[(i * k + j) * k + m] = True
|
|
744
|
+
|
|
745
|
+
def contains(self, points) -> np.ndarray:
|
|
746
|
+
pts = np.asarray(points, dtype=float).reshape(-1, 3)
|
|
747
|
+
k = self.subdivisions
|
|
748
|
+
u = np.mod((pts - self.domain.lower) / self.cell_size, 1.0)
|
|
749
|
+
inside = np.ones(len(pts), dtype=bool)
|
|
750
|
+
for _ in range(self.level):
|
|
751
|
+
d = np.minimum((u * k).astype(np.int64), k - 1)
|
|
752
|
+
inside &= self._mask[(d[:, 0] * k + d[:, 1]) * k + d[:, 2]]
|
|
753
|
+
u = u * k - d
|
|
754
|
+
return inside
|
|
755
|
+
|
|
756
|
+
def voxelize(self, shape=None, *, voxel_size=None, grid: Grid | None = None, supersampling=1):
|
|
757
|
+
grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
|
|
758
|
+
ss = int(supersampling)
|
|
759
|
+
fine = grid if ss == 1 else Grid(grid.domain, tuple(n * ss for n in grid.shape))
|
|
760
|
+
data = np.empty(fine.shape, dtype=bool)
|
|
761
|
+
for k0 in range(0, fine.shape[2], 16):
|
|
762
|
+
k1 = min(fine.shape[2], k0 + 16)
|
|
763
|
+
data[:, :, k0:k1] = self.contains(fine.center_points(k0, k1)).reshape(
|
|
764
|
+
fine.shape[0], fine.shape[1], k1 - k0
|
|
765
|
+
)
|
|
766
|
+
if ss == 1:
|
|
767
|
+
return VoxelImage.from_grid(
|
|
768
|
+
data.astype(np.uint8), grid, name="phase", metadata=self.image_metadata()
|
|
769
|
+
)
|
|
770
|
+
frac = _supersampled(data.astype(np.float32), grid, ss)
|
|
771
|
+
return VoxelImage.from_grid(frac, grid, name="fraction", metadata=self.image_metadata())
|
|
772
|
+
|
|
773
|
+
def level_set(self, shape=None, *, voxel_size=None, grid: Grid | None = None) -> VoxelImage:
|
|
774
|
+
"""The signed distance to the solid in the maximum norm (negative inside),
|
|
775
|
+
clipped to a band of four voxels and to the edge of the smallest cubes: the
|
|
776
|
+
solid is a union of such cubes, and the distance from a point to the nearest
|
|
777
|
+
cube of the other state among the 26 around its own is the largest of its
|
|
778
|
+
distances to the faces that separate them."""
|
|
779
|
+
grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
|
|
780
|
+
k = self.subdivisions
|
|
781
|
+
h = self.cell_size / k**self.level
|
|
782
|
+
band = min(h, band_of(grid))
|
|
783
|
+
nx, ny, nz = grid.shape
|
|
784
|
+
out = np.empty(grid.shape, dtype=np.float32)
|
|
785
|
+
offsets = [o for o in np.ndindex(3, 3, 3) if o != (1, 1, 1)]
|
|
786
|
+
step = max(1, (1 << 18) // (nx * ny))
|
|
787
|
+
for k0 in range(0, nz, step):
|
|
788
|
+
k1 = min(nz, k0 + step)
|
|
789
|
+
pts = grid.center_points(k0, k1)
|
|
790
|
+
u = (pts - self.domain.lower) / h
|
|
791
|
+
cell = np.floor(u)
|
|
792
|
+
frac = u - cell
|
|
793
|
+
centre = (cell + 0.5) * h + self.domain.lower
|
|
794
|
+
own = self.contains(centre)
|
|
795
|
+
dist = np.full(len(pts), band)
|
|
796
|
+
for o in offsets:
|
|
797
|
+
shift = np.array(o, dtype=float) - 1.0
|
|
798
|
+
other = self.contains(centre + shift * h) != own
|
|
799
|
+
if not other.any():
|
|
800
|
+
continue
|
|
801
|
+
# to the faces towards that cube, along the axes where it is shifted
|
|
802
|
+
gaps = np.where(shift > 0, 1.0 - frac, frac) * h
|
|
803
|
+
d = np.where(shift != 0, gaps, 0.0).max(axis=1)
|
|
804
|
+
dist = np.where(other, np.minimum(dist, d), dist)
|
|
805
|
+
out[:, :, k0:k1] = np.where(own, -dist, dist).reshape(nx, ny, k1 - k0)
|
|
806
|
+
return VoxelImage.from_grid(out, grid, name="level_set", metadata=self.image_metadata())
|
|
807
|
+
|
|
808
|
+
def convex_pieces(self):
|
|
809
|
+
"""The structure as boxes of one phase each (the cubes of the finest level, merged
|
|
810
|
+
greedily), clipped to the box: the pieces, their phases and their cells (the
|
|
811
|
+
phases), for :func:`morphogen.mesh.exact.polyhedral_mesh`."""
|
|
812
|
+
from morphogen.mesh.exact import grid_boxes
|
|
813
|
+
|
|
814
|
+
step = self.cell_size / self.subdivisions**self.level
|
|
815
|
+
lo, hi = self.domain.lower, self.domain.upper
|
|
816
|
+
edges = []
|
|
817
|
+
for d in range(3):
|
|
818
|
+
n = int(np.ceil((hi[d] - lo[d]) / step - 1e-9))
|
|
819
|
+
e = lo[d] + step * np.arange(n + 1)
|
|
820
|
+
e[-1] = hi[d]
|
|
821
|
+
edges.append(e)
|
|
822
|
+
centres = [0.5 * (e[1:] + e[:-1]) for e in edges]
|
|
823
|
+
grid = np.stack(np.meshgrid(*centres, indexing="ij"), axis=-1)
|
|
824
|
+
labels = self.contains(grid.reshape(-1, 3)).reshape(grid.shape[:3]).astype(np.int64)
|
|
825
|
+
pieces, phase = grid_boxes(labels, edges)
|
|
826
|
+
return pieces, phase, phase.copy()
|
|
827
|
+
|
|
828
|
+
def summary(self) -> dict:
|
|
829
|
+
return {"kept_cubes": len(self.kept) ** self.level, "level": self.level}
|
|
830
|
+
|
|
831
|
+
def _geometry(self) -> dict:
|
|
832
|
+
return {
|
|
833
|
+
"cell_size": self.cell_size,
|
|
834
|
+
"subdivisions": self.subdivisions,
|
|
835
|
+
"kept": [list(c) for c in self.kept],
|
|
836
|
+
"level": self.level,
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
@classmethod
|
|
840
|
+
def _from_geometry(cls, domain, geometry, **kwargs):
|
|
841
|
+
return cls(
|
|
842
|
+
domain,
|
|
843
|
+
geometry["cell_size"],
|
|
844
|
+
geometry["subdivisions"],
|
|
845
|
+
geometry["kept"],
|
|
846
|
+
geometry["level"],
|
|
847
|
+
**kwargs,
|
|
848
|
+
)
|
|
849
|
+
|
|
850
|
+
|
|
851
|
+
@register
|
|
852
|
+
@dataclass(frozen=True)
|
|
853
|
+
class FractalSponge(Model):
|
|
854
|
+
"""Iterated function system on a cubic grid: the Menger sponge and its kin.
|
|
855
|
+
|
|
856
|
+
The cube of edge ``cell_size`` is divided into ``subdivisions^3`` sub-cubes, of which
|
|
857
|
+
the pattern keeps some (``menger``: all but the centre and the face centres, 20 of
|
|
858
|
+
27; ``vicsek``: the centre and the face centres; ``cantor_dust``: the 8 corners; or
|
|
859
|
+
``kept``: indices (i, j, k)); each kept sub-cube is divided alike, ``level`` times.
|
|
860
|
+
The attractor has the similarity dimension ``log N / log k`` (N cubes kept of k^3);
|
|
861
|
+
the domain is tiled by the cube.
|
|
862
|
+
"""
|
|
863
|
+
|
|
864
|
+
name = "fractal_sponge"
|
|
865
|
+
phases: ClassVar[dict[int, str]] = {0: "void", 1: "solid"}
|
|
866
|
+
count_label = "unit cells"
|
|
867
|
+
|
|
868
|
+
pattern: str = param("menger", doc="menger, vicsek or cantor_dust (or 'kept')", kind="str")
|
|
869
|
+
kept: tuple | None = param(
|
|
870
|
+
None, doc="Sub-cubes kept, as [i, j, k] indices (overrides the pattern)", kind="json"
|
|
871
|
+
)
|
|
872
|
+
subdivisions: int = param(3, doc="Sub-cubes per edge at each level", kind="int")
|
|
873
|
+
level: int = param(3, doc="Number of iterations", kind="int")
|
|
874
|
+
cell_size: float = param(1.0, doc="Edge of the cube of the sponge", unit="length")
|
|
875
|
+
|
|
876
|
+
def _validate(self) -> None:
|
|
877
|
+
check_positive(self.cell_size, "cell_size")
|
|
878
|
+
if not 2 <= self.subdivisions <= 9:
|
|
879
|
+
raise ValueError("subdivisions: from 2 to 9")
|
|
880
|
+
if not 1 <= self.level <= 8:
|
|
881
|
+
raise ValueError("level: from 1 to 8")
|
|
882
|
+
if self.kept is None:
|
|
883
|
+
if self.pattern not in PATTERNS:
|
|
884
|
+
raise ValueError(f"pattern: one of {sorted(PATTERNS)}, or give 'kept'")
|
|
885
|
+
if self.subdivisions != 3:
|
|
886
|
+
raise ValueError("the named patterns divide the cube in 3 x 3 x 3")
|
|
887
|
+
else:
|
|
888
|
+
cubes = {tuple(int(v) for v in c) for c in self.kept}
|
|
889
|
+
k = self.subdivisions
|
|
890
|
+
if not cubes or any(len(c) != 3 or not all(0 <= v < k for v in c) for c in cubes):
|
|
891
|
+
raise ValueError(f"kept: sub-cube indices [i, j, k] from 0 to {k - 1}")
|
|
892
|
+
|
|
893
|
+
@property
|
|
894
|
+
def cubes(self) -> list[tuple]:
|
|
895
|
+
if self.kept is not None:
|
|
896
|
+
return sorted({tuple(int(v) for v in c) for c in self.kept})
|
|
897
|
+
return list(PATTERNS[self.pattern])
|
|
898
|
+
|
|
899
|
+
def generate(self, domain: Domain, seed: SeedLike = None) -> FractalStructure:
|
|
900
|
+
_, seed_info = make_rng(seed)
|
|
901
|
+
if domain.periodic:
|
|
902
|
+
ratio = domain.lengths / self.cell_size
|
|
903
|
+
if np.any(np.abs(ratio - np.rint(ratio)) > 1e-6 * np.maximum(ratio, 1.0)):
|
|
904
|
+
raise ValueError("fractal_sponge: a periodic domain holds whole cubes")
|
|
905
|
+
return FractalStructure(
|
|
906
|
+
domain,
|
|
907
|
+
self.cell_size,
|
|
908
|
+
self.subdivisions,
|
|
909
|
+
self.cubes,
|
|
910
|
+
self.level,
|
|
911
|
+
model=self,
|
|
912
|
+
seed=seed_info,
|
|
913
|
+
)
|
|
914
|
+
|
|
915
|
+
def expected_count(self, domain: Domain) -> float:
|
|
916
|
+
return domain.volume / self.cell_size**3
|
|
917
|
+
|
|
918
|
+
def theory(self, domain: Domain | None = None) -> dict[str, float]:
|
|
919
|
+
n, k = len(self.cubes), self.subdivisions
|
|
920
|
+
return {
|
|
921
|
+
"volume_fraction": (n / k**3) ** self.level,
|
|
922
|
+
"fractal_dimension": math.log(n) / math.log(k),
|
|
923
|
+
"smallest_cube": self.cell_size / k**self.level,
|
|
924
|
+
}
|