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,406 @@
|
|
|
1
|
+
"""Transparent dead leaves (Jeulin 1997): a random function of falling transparent leaves,
|
|
2
|
+
and its excursion above a threshold.
|
|
3
|
+
|
|
4
|
+
Each leaf (a sphere) carries a value ``v`` (a grey level, uniform on [0, 1] or Bernoulli);
|
|
5
|
+
when it falls on a point, the value there becomes ``α v + (1 - α) Z``: the leaf lets the
|
|
6
|
+
fraction ``1 - α`` of what it covers show through (``α = 1``: opaque leaves, the dead
|
|
7
|
+
leaves). After infinitely many leaves, ``Z(x) = Σ_n α (1 - α)^{n - 1} v_n``, ``v_1`` the
|
|
8
|
+
value of the last leaf fallen on ``x``. Going back in time, as in the perfect simulation
|
|
9
|
+
of the dead leaves (:mod:`morphogen.models.deadleaves`), the leaves are drawn one by one,
|
|
10
|
+
each under the earlier ones, until the weight ``(1 - α)^n`` left to each centre of a
|
|
11
|
+
check grid is below the tolerance, then a third more; what is left of the weight of a
|
|
12
|
+
point takes the mean value of the leaves.
|
|
13
|
+
|
|
14
|
+
Theory. ``E[Z] = E[v]`` and ``Var Z = σ^2 α / (2 - α)`` (``σ^2 = Var v``). The leaves hitting
|
|
15
|
+
``x`` or ``x + h`` cover both with the probability ``r(h) = K(h) / (2K(0) - K(h))`` (``K``:
|
|
16
|
+
the mean geometric covariogram of the leaves), so that each of them multiplies
|
|
17
|
+
``E[(1 - α)^{a + b}]``, ``a`` and ``b`` the leaves fallen on each point above it, by ``m = r (1
|
|
18
|
+
- α)^2 + (1 - r)(1 - α)``; the shared leaves give
|
|
19
|
+
|
|
20
|
+
Cov(Z(x), Z(x + h)) = σ^2 α^2 r / (1 - m) = σ^2 α r / (1 + r (1 - α)),
|
|
21
|
+
|
|
22
|
+
the correlation ``r (2 - α) / (1 + r (1 - α))`` (``r`` for opaque leaves). Phase 1 is
|
|
23
|
+
``{Z > t}``; its fraction ``P(Z > t)`` follows from the law of the series, here from 10^6
|
|
24
|
+
draws of its terms down to a weight of 10^-4 (the rest by its mean): the threshold of a
|
|
25
|
+
volume fraction to about 10^-3.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import math
|
|
31
|
+
from dataclasses import dataclass
|
|
32
|
+
from functools import lru_cache
|
|
33
|
+
from typing import ClassVar
|
|
34
|
+
|
|
35
|
+
import numpy as np
|
|
36
|
+
from scipy.spatial import cKDTree
|
|
37
|
+
|
|
38
|
+
from morphogen import settings
|
|
39
|
+
from morphogen._utils import check_fraction, check_positive, exactly_one
|
|
40
|
+
from morphogen.distributions import Distribution
|
|
41
|
+
from morphogen.domain import Domain, Grid
|
|
42
|
+
from morphogen.image import VoxelImage
|
|
43
|
+
from morphogen.kernels.leaves import transparent_cover
|
|
44
|
+
from morphogen.models.affine import ANISOTROPY, Anisotropy, anisotropic
|
|
45
|
+
from morphogen.models.base import Microstructure, Model, param, register, register_kind
|
|
46
|
+
from morphogen.seeding import SeedLike, make_rng
|
|
47
|
+
|
|
48
|
+
#: Laws of the values of the leaves.
|
|
49
|
+
VALUES = ("uniform", "bernoulli")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _field(centers, radii, values, alpha, grid: Grid, periodic: bool, mean: float, z=None, w=None,
|
|
53
|
+
tol: float = 0.0): # fmt: skip
|
|
54
|
+
"""The field of the leaves at the voxel centres of a grid (and the weights left)."""
|
|
55
|
+
if z is None:
|
|
56
|
+
z = np.zeros(grid.shape)
|
|
57
|
+
w = np.ones(grid.shape)
|
|
58
|
+
left = transparent_cover(
|
|
59
|
+
np.ascontiguousarray(centers, dtype=float),
|
|
60
|
+
np.ascontiguousarray(radii, dtype=float),
|
|
61
|
+
np.ascontiguousarray(values, dtype=float),
|
|
62
|
+
float(alpha),
|
|
63
|
+
np.asarray(grid.domain.lower, dtype=float),
|
|
64
|
+
np.asarray(grid.spacing, dtype=float),
|
|
65
|
+
np.asarray(grid.shape, dtype=np.int64),
|
|
66
|
+
periodic,
|
|
67
|
+
z,
|
|
68
|
+
w,
|
|
69
|
+
float(tol),
|
|
70
|
+
)
|
|
71
|
+
return z, w, left
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@register_kind
|
|
75
|
+
class TransparentDeadLeaves(Microstructure):
|
|
76
|
+
"""Transparent leaves in their order of fall backwards (the first on top), the
|
|
77
|
+
random function ``Z`` they make, and its excursion ``Z > threshold`` (phase 1)."""
|
|
78
|
+
|
|
79
|
+
kind = "transparent_dead_leaves"
|
|
80
|
+
|
|
81
|
+
def __init__(self, domain: Domain, centers, radii, values, *, alpha: float,
|
|
82
|
+
threshold: float, mean_value: float, **kwargs) -> None: # fmt: skip
|
|
83
|
+
super().__init__(domain, **kwargs)
|
|
84
|
+
self.centers = np.ascontiguousarray(centers, dtype=float).reshape(-1, 3)
|
|
85
|
+
self.radii = np.asarray(radii, dtype=float).reshape(-1)
|
|
86
|
+
self.values = np.asarray(values, dtype=float).reshape(-1)
|
|
87
|
+
self.alpha = float(alpha)
|
|
88
|
+
self.threshold = float(threshold)
|
|
89
|
+
self.mean_value = float(mean_value)
|
|
90
|
+
self._tree = None
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
def n_leaves(self) -> int:
|
|
94
|
+
return len(self.radii)
|
|
95
|
+
|
|
96
|
+
def field(self, shape=None, *, voxel_size=None, grid: Grid | None = None) -> VoxelImage:
|
|
97
|
+
"""The random function ``Z`` at the voxel centres (float32)."""
|
|
98
|
+
grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
|
|
99
|
+
z, w, _ = _field(self.centers, self.radii, self.values, self.alpha, grid,
|
|
100
|
+
self.domain.periodic, self.mean_value) # fmt: skip
|
|
101
|
+
z += w * self.mean_value # what the leaves leave of the weight: the mean value
|
|
102
|
+
return VoxelImage.from_grid(z.astype(np.float32), grid, name="field",
|
|
103
|
+
metadata=self.image_metadata()) # fmt: skip
|
|
104
|
+
|
|
105
|
+
def voxelize(self, shape=None, *, voxel_size=None, grid: Grid | None = None, supersampling=1):
|
|
106
|
+
grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
|
|
107
|
+
ss = int(supersampling)
|
|
108
|
+
if ss == 1:
|
|
109
|
+
data = (self.field(grid=grid).data > self.threshold).astype(np.uint8)
|
|
110
|
+
return VoxelImage.from_grid(data, grid, name="phase", metadata=self.image_metadata())
|
|
111
|
+
if not 1 <= ss <= 6:
|
|
112
|
+
raise ValueError("supersampling must be an integer between 1 and 6")
|
|
113
|
+
fine = Grid(grid.domain, tuple(n * ss for n in grid.shape))
|
|
114
|
+
ph = (self.field(grid=fine).data > self.threshold).astype(np.float32)
|
|
115
|
+
nx, ny, nz = grid.shape
|
|
116
|
+
data = ph.reshape(nx, ss, ny, ss, nz, ss).mean(axis=(1, 3, 5), dtype=np.float32)
|
|
117
|
+
return VoxelImage.from_grid(data, grid, name="fraction", metadata=self.image_metadata())
|
|
118
|
+
|
|
119
|
+
def _local(self, points: np.ndarray) -> np.ndarray:
|
|
120
|
+
p = np.asarray(points, dtype=float) - self.domain.lower
|
|
121
|
+
if self.domain.periodic:
|
|
122
|
+
p = np.mod(p, self.domain.lengths)
|
|
123
|
+
p[p >= self.domain.lengths] = 0.0
|
|
124
|
+
return p
|
|
125
|
+
|
|
126
|
+
def values_at(self, points) -> np.ndarray:
|
|
127
|
+
"""The random function at points: the leaves covering each, in their order."""
|
|
128
|
+
pts = self._local(np.asarray(points, dtype=float).reshape(-1, 3))
|
|
129
|
+
out = np.full(len(pts), self.mean_value)
|
|
130
|
+
if not self.n_leaves:
|
|
131
|
+
return out
|
|
132
|
+
if self._tree is None:
|
|
133
|
+
if self.domain.periodic:
|
|
134
|
+
self._tree = cKDTree(self._local(self.centers), boxsize=self.domain.lengths)
|
|
135
|
+
else:
|
|
136
|
+
self._tree = cKDTree(self.centers - self.domain.lower)
|
|
137
|
+
found = self._tree.query_ball_point(pts, float(self.radii.max()),
|
|
138
|
+
workers=settings.workers()) # fmt: skip
|
|
139
|
+
keep = 1.0 - self.alpha
|
|
140
|
+
for i, cand in enumerate(found):
|
|
141
|
+
if not cand:
|
|
142
|
+
continue
|
|
143
|
+
cand = np.sort(np.asarray(cand))
|
|
144
|
+
d = self._tree.data[cand] - pts[i]
|
|
145
|
+
if self.domain.periodic:
|
|
146
|
+
d -= self.domain.lengths * np.round(d / self.domain.lengths)
|
|
147
|
+
inside = cand[np.einsum("ij,ij->i", d, d) <= self.radii[cand] ** 2]
|
|
148
|
+
weights = self.alpha * keep ** np.arange(len(inside))
|
|
149
|
+
rest = keep ** len(inside) * self.mean_value
|
|
150
|
+
out[i] = float(np.sum(weights * self.values[inside])) + rest
|
|
151
|
+
return out
|
|
152
|
+
|
|
153
|
+
def contains(self, points) -> np.ndarray:
|
|
154
|
+
return self.values_at(points) > self.threshold
|
|
155
|
+
|
|
156
|
+
def level_set(self, shape=None, *, voxel_size=None, grid: Grid | None = None) -> VoxelImage:
|
|
157
|
+
"""The implicit function of the excursion ``Z > threshold`` (negative inside). The
|
|
158
|
+
function ``Z`` is constant between the spheres of the leaves: the boundary of the
|
|
159
|
+
excursion is made of the parts of these spheres across which ``Z`` passes the
|
|
160
|
+
threshold. At a point, the leaf whose sphere is such a part nearby is one that,
|
|
161
|
+
added to the leaves that cover the point or taken from them, changes its side:
|
|
162
|
+
the function is the distance to the nearest of these spheres, with the sign of the
|
|
163
|
+
side of the point (clipped to a band of four voxels). It vanishes exactly on the
|
|
164
|
+
boundary; away from it, it is a distance to a sphere near that boundary."""
|
|
165
|
+
from morphogen.models.implicit import band_of, lattice_boxes, ordered_cover
|
|
166
|
+
|
|
167
|
+
grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
|
|
168
|
+
band = band_of(grid)
|
|
169
|
+
lengths = self.domain.lengths if self.domain.periodic else None
|
|
170
|
+
if self.alpha == 1.0: # opaque leaves: the dead leaves, of the side of their value
|
|
171
|
+
|
|
172
|
+
def objects():
|
|
173
|
+
for i in range(self.n_leaves):
|
|
174
|
+
reach = self.radii[i] + band
|
|
175
|
+
for slices, (dx, dy, dz) in lattice_boxes(
|
|
176
|
+
self.centers[i], reach, grid, lengths
|
|
177
|
+
):
|
|
178
|
+
d = (np.sqrt(dx * dx + dy * dy + dz * dz) - self.radii[i]).astype(
|
|
179
|
+
np.float32
|
|
180
|
+
)
|
|
181
|
+
yield slices, d, [d if self.values[i] > self.threshold else None]
|
|
182
|
+
|
|
183
|
+
parts, top = ordered_cover(grid.shape, band, objects(), 1)
|
|
184
|
+
data = parts[0]
|
|
185
|
+
if self.mean_value > self.threshold: # what no leaf covers
|
|
186
|
+
data = np.minimum(data, -top)
|
|
187
|
+
return VoxelImage.from_grid(
|
|
188
|
+
data, grid, name="level_set", metadata=self.image_metadata()
|
|
189
|
+
)
|
|
190
|
+
z = np.asarray(self.field(grid=grid).data)
|
|
191
|
+
inside = z > self.threshold
|
|
192
|
+
z = z.astype(np.float64)
|
|
193
|
+
keep = 1.0 - self.alpha
|
|
194
|
+
head = np.zeros(grid.shape) # the sum of the leaves above the current one
|
|
195
|
+
weight = np.ones(grid.shape) # what they let through
|
|
196
|
+
dist = np.full(grid.shape, band, dtype=np.float32)
|
|
197
|
+
for i in range(self.n_leaves):
|
|
198
|
+
radius, value = self.radii[i], self.alpha * self.values[i]
|
|
199
|
+
for slices, (dx, dy, dz) in lattice_boxes(
|
|
200
|
+
self.centers[i], radius + band, grid, lengths
|
|
201
|
+
):
|
|
202
|
+
d = np.sqrt(dx * dx + dy * dy + dz * dz) - radius
|
|
203
|
+
covers = d <= 0
|
|
204
|
+
a, w, zz = head[slices], weight[slices], z[slices]
|
|
205
|
+
# the field without the leaf where it covers, with it elsewhere
|
|
206
|
+
other = np.where(covers, a + (zz - a - w * value) / keep,
|
|
207
|
+
a + w * value + keep * (zz - a)) # fmt: skip
|
|
208
|
+
flips = (other > self.threshold) != inside[slices]
|
|
209
|
+
view = dist[slices]
|
|
210
|
+
np.minimum(view, np.where(flips, np.abs(d), band), out=view)
|
|
211
|
+
a += np.where(covers, w * value, 0.0)
|
|
212
|
+
w *= np.where(covers, keep, 1.0)
|
|
213
|
+
data = np.where(inside, -dist, dist).astype(np.float32)
|
|
214
|
+
return VoxelImage.from_grid(data, grid, name="level_set", metadata=self.image_metadata())
|
|
215
|
+
|
|
216
|
+
def summary(self) -> dict:
|
|
217
|
+
return {"n_leaves": self.n_leaves}
|
|
218
|
+
|
|
219
|
+
def _geometry(self) -> dict:
|
|
220
|
+
return {
|
|
221
|
+
"centers": self.centers.tolist(),
|
|
222
|
+
"radii": self.radii.tolist(),
|
|
223
|
+
"values": self.values.tolist(),
|
|
224
|
+
"alpha": self.alpha,
|
|
225
|
+
"threshold": self.threshold,
|
|
226
|
+
"mean_value": self.mean_value,
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
@classmethod
|
|
230
|
+
def _from_geometry(cls, domain, geometry, **kwargs):
|
|
231
|
+
return cls(domain, geometry["centers"], geometry["radii"], geometry["values"],
|
|
232
|
+
alpha=geometry["alpha"], threshold=geometry["threshold"],
|
|
233
|
+
mean_value=geometry["mean_value"], **kwargs) # fmt: skip
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
@lru_cache(maxsize=64)
|
|
237
|
+
def _law(alpha: float, values: str, p: float) -> np.ndarray:
|
|
238
|
+
"""10^6 draws of ``Z`` (sorted): its terms down to a weight of 10^-4, the rest by its
|
|
239
|
+
mean."""
|
|
240
|
+
keep = 1.0 - alpha
|
|
241
|
+
terms = 1 if keep == 0.0 else math.ceil(math.log(1e-4) / math.log(keep))
|
|
242
|
+
mean = 0.5 if values == "uniform" else p
|
|
243
|
+
rng = np.random.default_rng(1997)
|
|
244
|
+
out = np.empty(10**6)
|
|
245
|
+
weights = alpha * keep ** np.arange(terms)
|
|
246
|
+
for start in range(0, len(out), 50_000):
|
|
247
|
+
n = min(50_000, len(out) - start)
|
|
248
|
+
if values == "uniform":
|
|
249
|
+
v = rng.random((n, terms))
|
|
250
|
+
else:
|
|
251
|
+
v = (rng.random((n, terms)) < p).astype(float)
|
|
252
|
+
out[start : start + n] = v @ weights + keep**terms * mean
|
|
253
|
+
return np.sort(out)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
@register
|
|
257
|
+
@anisotropic
|
|
258
|
+
@dataclass(frozen=True)
|
|
259
|
+
class TransparentDeadLeavesModel(Model):
|
|
260
|
+
"""Transparent dead leaves of spheres (Jeulin 1997): the excursion of the random
|
|
261
|
+
function of leaves letting ``1 - α`` of what they cover show through."""
|
|
262
|
+
|
|
263
|
+
name = "transparent_dead_leaves"
|
|
264
|
+
phases: ClassVar[dict[int, str]] = {0: "below the threshold", 1: "above the threshold"}
|
|
265
|
+
count_label = "leaves"
|
|
266
|
+
|
|
267
|
+
radius: Distribution = param(doc="Radius of the leaves", kind="distribution", unit="length")
|
|
268
|
+
transparency: float = param(
|
|
269
|
+
0.5,
|
|
270
|
+
doc="Weight alpha of a leaf in the value it covers (1: opaque leaves, the dead "
|
|
271
|
+
"leaves; small: very transparent leaves)",
|
|
272
|
+
kind="fraction",
|
|
273
|
+
)
|
|
274
|
+
values: str = param("uniform", doc="Values of the leaves: uniform (on [0, 1]) or bernoulli",
|
|
275
|
+
kind="str") # fmt: skip
|
|
276
|
+
value_probability: float = param(
|
|
277
|
+
0.5, doc="Probability of the value 1 of bernoulli leaves", kind="fraction"
|
|
278
|
+
)
|
|
279
|
+
threshold: float | None = param(None, doc="Phase 1: the field above it")
|
|
280
|
+
volume_fraction: float | None = param(
|
|
281
|
+
None, doc="Fraction of phase 1 (sets the threshold)", kind="fraction"
|
|
282
|
+
)
|
|
283
|
+
tolerance: float = param(
|
|
284
|
+
1e-3, doc="Weight left to a point by the leaves drawn (then its mean value)"
|
|
285
|
+
)
|
|
286
|
+
anisotropy: Anisotropy | None = param(None, doc=ANISOTROPY, kind="anisotropy", kw_only=True)
|
|
287
|
+
|
|
288
|
+
def _validate(self) -> None:
|
|
289
|
+
check_fraction(self.transparency, "transparency", open_interval=False)
|
|
290
|
+
if self.transparency == 0.0:
|
|
291
|
+
raise ValueError("transparency: must lie in (0, 1]")
|
|
292
|
+
if self.values not in VALUES:
|
|
293
|
+
raise ValueError(f"values: {' or '.join(VALUES)}, got {self.values!r}")
|
|
294
|
+
check_fraction(self.value_probability, "value_probability")
|
|
295
|
+
exactly_one("threshold", self.threshold, "volume_fraction", self.volume_fraction)
|
|
296
|
+
if self.volume_fraction is not None:
|
|
297
|
+
check_fraction(self.volume_fraction, "volume_fraction")
|
|
298
|
+
check_positive(self.tolerance, "tolerance")
|
|
299
|
+
if self.tolerance >= 0.5:
|
|
300
|
+
raise ValueError("tolerance: below 0.5")
|
|
301
|
+
|
|
302
|
+
@property
|
|
303
|
+
def mean_value(self) -> float:
|
|
304
|
+
return 0.5 if self.values == "uniform" else float(self.value_probability)
|
|
305
|
+
|
|
306
|
+
@property
|
|
307
|
+
def value_variance(self) -> float:
|
|
308
|
+
p = self.value_probability
|
|
309
|
+
return 1.0 / 12.0 if self.values == "uniform" else float(p * (1.0 - p))
|
|
310
|
+
|
|
311
|
+
def _sample(self) -> np.ndarray:
|
|
312
|
+
return _law(float(self.transparency), self.values, float(self.value_probability))
|
|
313
|
+
|
|
314
|
+
def field_threshold(self) -> float:
|
|
315
|
+
"""The threshold of phase 1: given, or the quantile of the law of ``Z`` that leaves
|
|
316
|
+
the volume fraction above it."""
|
|
317
|
+
if self.threshold is not None:
|
|
318
|
+
return float(self.threshold)
|
|
319
|
+
return float(np.quantile(self._sample(), 1.0 - self.volume_fraction))
|
|
320
|
+
|
|
321
|
+
def excursion_fraction(self) -> float:
|
|
322
|
+
"""``P(Z > threshold)``, from the law of ``Z``."""
|
|
323
|
+
z = self._sample()
|
|
324
|
+
return float(1.0 - np.searchsorted(z, self.field_threshold(), side="right") / len(z))
|
|
325
|
+
|
|
326
|
+
def same_leaf_probability(self, h) -> np.ndarray:
|
|
327
|
+
"""``r(h) = K(h) / (2 K(0) - K(h))`` for spheres of the law of the radii."""
|
|
328
|
+
h = np.asarray(h, dtype=float)
|
|
329
|
+
x, w = self.radius.quadrature(64)
|
|
330
|
+
u = h[..., None] / x
|
|
331
|
+
k = np.sum(w * x**3 * np.where(u < 2.0, 1.0 - 0.75 * u + u**3 / 16.0, 0.0), axis=-1)
|
|
332
|
+
k0 = np.sum(w * x**3)
|
|
333
|
+
return k / (2.0 * k0 - k)
|
|
334
|
+
|
|
335
|
+
def field_covariance(self, h) -> np.ndarray:
|
|
336
|
+
"""``Cov(Z(x), Z(x + h)) = σ^2 α r / (1 + r (1 - α))``."""
|
|
337
|
+
r = self.same_leaf_probability(h)
|
|
338
|
+
a = self.transparency
|
|
339
|
+
return self.value_variance * a * r / (1.0 + r * (1.0 - a))
|
|
340
|
+
|
|
341
|
+
def _volume(self) -> float:
|
|
342
|
+
return 4.0 / 3.0 * math.pi * self.radius.moment(3)
|
|
343
|
+
|
|
344
|
+
def generate(self, domain: Domain, seed: SeedLike = None) -> TransparentDeadLeaves:
|
|
345
|
+
self._check_domain(domain)
|
|
346
|
+
rng, seed_info = make_rng(seed)
|
|
347
|
+
periodic = domain.periodic
|
|
348
|
+
window = domain if periodic else domain.dilated(self.radius.upper())
|
|
349
|
+
# leaves until the weight left to the centres of a check grid (a third of the
|
|
350
|
+
# median radius) falls below the tolerance, then a third more
|
|
351
|
+
step = self.radius.median() / 3.0
|
|
352
|
+
shape = tuple(int(np.clip(math.ceil(s / step), 8, 128)) for s in domain.lengths)
|
|
353
|
+
check = Grid(domain, shape)
|
|
354
|
+
z, w = np.zeros(shape), np.ones(shape)
|
|
355
|
+
batch = max(64, int(0.5 * window.volume / self._volume()))
|
|
356
|
+
centers, radii, values, n, left = [], [], [], 0, z.size
|
|
357
|
+
while left:
|
|
358
|
+
c, r, v = self._draw(rng, window, batch)
|
|
359
|
+
z, w, left = _field(c, r, v, self.transparency, check, periodic, self.mean_value,
|
|
360
|
+
z, w, self.tolerance) # fmt: skip
|
|
361
|
+
centers.append(c)
|
|
362
|
+
radii.append(r)
|
|
363
|
+
values.append(v)
|
|
364
|
+
n += batch
|
|
365
|
+
if n > 10**8:
|
|
366
|
+
raise RuntimeError("transparent_dead_leaves: the leaves do not cover the domain")
|
|
367
|
+
c, r, v = self._draw(rng, window, n // 3 + 1)
|
|
368
|
+
centers.append(c)
|
|
369
|
+
radii.append(r)
|
|
370
|
+
values.append(v)
|
|
371
|
+
return TransparentDeadLeaves(
|
|
372
|
+
domain,
|
|
373
|
+
np.concatenate(centers),
|
|
374
|
+
np.concatenate(radii),
|
|
375
|
+
np.concatenate(values),
|
|
376
|
+
alpha=self.transparency,
|
|
377
|
+
threshold=self.field_threshold(),
|
|
378
|
+
mean_value=self.mean_value,
|
|
379
|
+
model=self,
|
|
380
|
+
seed=seed_info,
|
|
381
|
+
)
|
|
382
|
+
|
|
383
|
+
def _draw(self, rng, window: Domain, k: int):
|
|
384
|
+
centers = window.lower + rng.random((k, 3)) * window.lengths
|
|
385
|
+
radii = self.radius.sample(rng, k)
|
|
386
|
+
if self.values == "uniform":
|
|
387
|
+
values = rng.random(k)
|
|
388
|
+
else:
|
|
389
|
+
values = (rng.random(k) < self.value_probability).astype(float)
|
|
390
|
+
return centers, radii, values
|
|
391
|
+
|
|
392
|
+
def theory(self, domain: Domain | None = None) -> dict[str, float]:
|
|
393
|
+
a = self.transparency
|
|
394
|
+
x, _ = self.radius.quadrature(64)
|
|
395
|
+
h = np.linspace(0.0, 2.0 * float(x.max()), 4001)
|
|
396
|
+
rho = self.field_covariance(h) / (self.value_variance * a / (2.0 - a))
|
|
397
|
+
integrand = rho * 4.0 * math.pi * h**2
|
|
398
|
+
area = float(np.sum(0.5 * (integrand[1:] + integrand[:-1]) * np.diff(h)))
|
|
399
|
+
return {
|
|
400
|
+
"field_mean": self.mean_value,
|
|
401
|
+
"field_variance": self.value_variance * a / (2.0 - a),
|
|
402
|
+
"field_integral_range": area,
|
|
403
|
+
"threshold": self.field_threshold(),
|
|
404
|
+
"volume_fraction": self.excursion_fraction(),
|
|
405
|
+
"mean_leaf_volume": self._volume(),
|
|
406
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""Microstructures made of a union of spheres and segments (grains, fibres, struts)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
from morphogen.domain import Domain, Grid
|
|
8
|
+
from morphogen.image import VoxelImage
|
|
9
|
+
from morphogen.kernels.union import UnionAccelerator
|
|
10
|
+
from morphogen.models.base import Microstructure, register_kind
|
|
11
|
+
from morphogen.primitives import Segments, Spheres, restricted_to_box, with_periodic_images
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@register_kind
|
|
15
|
+
class PrimitiveUnion(Microstructure):
|
|
16
|
+
"""Phase 1 is the union of the spheres and segments, phase 0 its complement.
|
|
17
|
+
|
|
18
|
+
For periodic domains the primitives are stored once (reference points inside the
|
|
19
|
+
box) and their periodic images are added when the structure is rasterized.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
kind = "primitive_union"
|
|
23
|
+
|
|
24
|
+
def __init__(
|
|
25
|
+
self,
|
|
26
|
+
domain: Domain,
|
|
27
|
+
spheres: Spheres | None = None,
|
|
28
|
+
segments: Segments | None = None,
|
|
29
|
+
**kwargs,
|
|
30
|
+
) -> None:
|
|
31
|
+
super().__init__(domain, **kwargs)
|
|
32
|
+
self.spheres = spheres if spheres is not None else Spheres(np.empty((0, 3)), np.empty(0))
|
|
33
|
+
self.segments = (
|
|
34
|
+
segments
|
|
35
|
+
if segments is not None
|
|
36
|
+
else Segments(np.empty((0, 3)), np.empty((0, 3)), np.empty(0))
|
|
37
|
+
)
|
|
38
|
+
self._cache: dict = {}
|
|
39
|
+
|
|
40
|
+
# -- acceleration structures -----------------------------------------------------
|
|
41
|
+
|
|
42
|
+
def _covering(self, margin: float) -> tuple[Spheres, Segments]:
|
|
43
|
+
"""Primitives (with periodic images if needed) covering the box plus ``margin``."""
|
|
44
|
+
if self.domain.periodic:
|
|
45
|
+
return (
|
|
46
|
+
with_periodic_images(self.spheres, self.domain, margin),
|
|
47
|
+
with_periodic_images(self.segments, self.domain, margin),
|
|
48
|
+
)
|
|
49
|
+
return (
|
|
50
|
+
restricted_to_box(self.spheres, self.domain, margin),
|
|
51
|
+
restricted_to_box(self.segments, self.domain, margin),
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
def _accelerator(self, band: float = 0.0, min_cell: float = 0.0) -> UnionAccelerator:
|
|
55
|
+
key = (round(band, 12), round(min_cell, 12))
|
|
56
|
+
if key not in self._cache:
|
|
57
|
+
spheres, segments = self._covering(band)
|
|
58
|
+
lo = self.domain.lower - band
|
|
59
|
+
hi = self.domain.upper + band
|
|
60
|
+
self._cache.clear()
|
|
61
|
+
self._cache[key] = UnionAccelerator(
|
|
62
|
+
spheres, segments, lo, hi, band=band, min_cell=min_cell
|
|
63
|
+
)
|
|
64
|
+
return self._cache[key]
|
|
65
|
+
|
|
66
|
+
# -- discretization ----------------------------------------------------------------
|
|
67
|
+
|
|
68
|
+
def voxelize(self, shape=None, *, voxel_size=None, grid: Grid | None = None, supersampling=1):
|
|
69
|
+
grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
|
|
70
|
+
acc = self._accelerator(0.0, 2.0 * float(grid.spacing.max()))
|
|
71
|
+
counts = acc.count(grid.origin, grid.spacing, grid.shape, supersampling)
|
|
72
|
+
if supersampling == 1:
|
|
73
|
+
return VoxelImage.from_grid(counts, grid, name="phase", metadata=self.image_metadata())
|
|
74
|
+
data = counts.astype(np.float32) / np.float32(supersampling**3)
|
|
75
|
+
return VoxelImage.from_grid(data, grid, name="fraction", metadata=self.image_metadata())
|
|
76
|
+
|
|
77
|
+
def level_set(
|
|
78
|
+
self, shape=None, *, voxel_size=None, grid: Grid | None = None, band: float | None = None
|
|
79
|
+
) -> VoxelImage:
|
|
80
|
+
"""Signed distance to the union (negative inside), exact outside the grains and
|
|
81
|
+
clipped to ``[-band, band]`` (default: 4 voxels)."""
|
|
82
|
+
grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
|
|
83
|
+
band = 4.0 * float(grid.spacing.max()) if band is None else float(band)
|
|
84
|
+
acc = self._accelerator(band, 2.0 * float(grid.spacing.max()))
|
|
85
|
+
data = acc.distance(grid.origin, grid.spacing, grid.shape)
|
|
86
|
+
return VoxelImage.from_grid(data, grid, name="level_set", metadata=self.image_metadata())
|
|
87
|
+
|
|
88
|
+
def contains(self, points) -> np.ndarray:
|
|
89
|
+
pts = np.asarray(points, dtype=float).reshape(-1, 3)
|
|
90
|
+
if self.domain.periodic:
|
|
91
|
+
pts = self.domain.wrap(pts)
|
|
92
|
+
return self._accelerator(0.0).inside(pts)
|
|
93
|
+
|
|
94
|
+
def level_set_at(self, points, reach: float = np.inf) -> np.ndarray:
|
|
95
|
+
"""The signed distance to the union (negative inside), clipped to ``[-reach,
|
|
96
|
+
reach]`` (default: a tenth of the smallest side of the box)."""
|
|
97
|
+
if not np.isfinite(reach):
|
|
98
|
+
reach = 0.1 * float(self.domain.lengths.min())
|
|
99
|
+
return self.signed_distance(points, float(reach))
|
|
100
|
+
|
|
101
|
+
def signed_distance(self, points, band: float) -> np.ndarray:
|
|
102
|
+
"""Signed distance at arbitrary points, clipped to ``[-band, band]``."""
|
|
103
|
+
pts = np.asarray(points, dtype=float).reshape(-1, 3)
|
|
104
|
+
if self.domain.periodic:
|
|
105
|
+
pts = self.domain.wrap(pts)
|
|
106
|
+
return self._accelerator(float(band)).signed_distance(pts)
|
|
107
|
+
|
|
108
|
+
def implicit_pieces(self, depth: float = 0.0) -> tuple[list, int] | None:
|
|
109
|
+
"""The primitives grouped so that no two of a group overlap: the pieces of phase
|
|
110
|
+
1, in what phase 0 leaves (see :mod:`morphogen.models.pieces`); None for the
|
|
111
|
+
unions of more phases."""
|
|
112
|
+
from morphogen.models.pieces import Piece, union_pieces
|
|
113
|
+
|
|
114
|
+
if self.implicit_phases() != [0, 1]:
|
|
115
|
+
return None
|
|
116
|
+
return [Piece(1, part) for part in union_pieces(self, 0.0, depth)], 0
|
|
117
|
+
|
|
118
|
+
# -- description -------------------------------------------------------------------
|
|
119
|
+
|
|
120
|
+
def summary(self) -> dict:
|
|
121
|
+
out = {}
|
|
122
|
+
if len(self.spheres):
|
|
123
|
+
out["n_spheres"] = len(self.spheres)
|
|
124
|
+
if len(self.segments):
|
|
125
|
+
out["n_segments"] = len(self.segments)
|
|
126
|
+
out.update(self.metadata.get("summary", {}))
|
|
127
|
+
return out
|
|
128
|
+
|
|
129
|
+
def _geometry(self) -> dict:
|
|
130
|
+
geo = {}
|
|
131
|
+
if len(self.spheres):
|
|
132
|
+
geo["spheres"] = self.spheres.to_dict()
|
|
133
|
+
if len(self.segments):
|
|
134
|
+
geo["segments"] = self.segments.to_dict()
|
|
135
|
+
return geo
|
|
136
|
+
|
|
137
|
+
@classmethod
|
|
138
|
+
def _from_geometry(cls, domain, geometry, **kwargs):
|
|
139
|
+
spheres = Spheres.from_dict(geometry["spheres"]) if "spheres" in geometry else None
|
|
140
|
+
segments = Segments.from_dict(geometry["segments"]) if "segments" in geometry else None
|
|
141
|
+
return cls(domain, spheres, segments, **kwargs)
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Topology optimization of periodic cells by inverse homogenization.
|
|
2
|
+
|
|
3
|
+
* :mod:`morphogen.optimization.cell`: homogenized tensors of voxel cells with graded
|
|
4
|
+
moduli and their exact sensitivities (FFT-preconditioned conjugate gradients);
|
|
5
|
+
* :mod:`morphogen.optimization.filters`: density filter, Heaviside projection, symmetry;
|
|
6
|
+
* :mod:`morphogen.optimization.mma`: method of moving asymptotes (Svanberg);
|
|
7
|
+
* :mod:`morphogen.optimization.topology`: objectives (bulk and shear moduli, Poisson's
|
|
8
|
+
ratio, conductivity, target tensor) and methods (OC, MMA, BESO, hybrid cellular
|
|
9
|
+
automaton);
|
|
10
|
+
* :mod:`morphogen.optimization.run`: configuration files and outputs
|
|
11
|
+
(``morphogen optimize``).
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from morphogen.optimization.cell import PeriodicCell
|
|
15
|
+
from morphogen.optimization.filters import DensityFilter, Symmetry, heaviside
|
|
16
|
+
from morphogen.optimization.mma import MMA
|
|
17
|
+
from morphogen.optimization.run import load_optimization_config, run_optimization
|
|
18
|
+
from morphogen.optimization.topology import (
|
|
19
|
+
METHODS,
|
|
20
|
+
OBJECTIVES,
|
|
21
|
+
CellDesign,
|
|
22
|
+
CellOptimization,
|
|
23
|
+
count_hinges,
|
|
24
|
+
initial_density,
|
|
25
|
+
tensor_properties,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"METHODS",
|
|
30
|
+
"MMA",
|
|
31
|
+
"OBJECTIVES",
|
|
32
|
+
"CellDesign",
|
|
33
|
+
"CellOptimization",
|
|
34
|
+
"DensityFilter",
|
|
35
|
+
"PeriodicCell",
|
|
36
|
+
"Symmetry",
|
|
37
|
+
"count_hinges",
|
|
38
|
+
"heaviside",
|
|
39
|
+
"initial_density",
|
|
40
|
+
"load_optimization_config",
|
|
41
|
+
"run_optimization",
|
|
42
|
+
"tensor_properties",
|
|
43
|
+
]
|