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,374 @@
|
|
|
1
|
+
"""Haversian (cortical) bone: osteons remodelled one after another.
|
|
2
|
+
|
|
3
|
+
Cortical bone is renewed by basic multicellular units that tunnel along the bone axis,
|
|
4
|
+
resorb a cylinder of bone and refill it with concentric lamellae around a vascular
|
|
5
|
+
(Haversian) canal: a secondary osteon, bounded by a cement line. Each new osteon cuts
|
|
6
|
+
through the older ones, whose fragments, with the remains of older bone, form the
|
|
7
|
+
interstitial bone (Currey 2002). The model is a dead-leaves model of aligned cylinders
|
|
8
|
+
(Matheron 1968; Jeulin 1989): osteons of radius ``R`` arrive at Poisson positions of
|
|
9
|
+
the cross-section in random order, the last on top; a point covered by none is
|
|
10
|
+
interstitial bone. Within the top osteon, it lies in the canal (``d < rho R``), the
|
|
11
|
+
cement line (``d > R - c``) or the lamellar bone in between (``d``: its distance to
|
|
12
|
+
the axis of the osteon).
|
|
13
|
+
|
|
14
|
+
With ``lambda`` osteons per unit area chosen for a ``coverage`` ``p = 1 - exp(-lambda pi
|
|
15
|
+
E[R^2])``, the top osteon is an osteon weighted by its area, and a point falls in each
|
|
16
|
+
of its parts with the share of its area (exact):
|
|
17
|
+
|
|
18
|
+
* Haversian canals (the vascular porosity): ``p rho^2``;
|
|
19
|
+
* cement lines: ``p E[R^2 - max(R - c, rho R)^2] / E[R^2]``;
|
|
20
|
+
* lamellar bone of the osteons: the rest of ``p``; interstitial bone: ``1 - p``.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import itertools
|
|
26
|
+
import math
|
|
27
|
+
from dataclasses import dataclass
|
|
28
|
+
from typing import ClassVar
|
|
29
|
+
|
|
30
|
+
import numpy as np
|
|
31
|
+
from numba import njit
|
|
32
|
+
from scipy.spatial import cKDTree
|
|
33
|
+
|
|
34
|
+
from morphogen._utils import check_fraction, check_positive
|
|
35
|
+
from morphogen.distributions import Distribution
|
|
36
|
+
from morphogen.domain import Domain, Grid
|
|
37
|
+
from morphogen.image import VoxelImage
|
|
38
|
+
from morphogen.models.base import Microstructure, Model, param, register, register_kind
|
|
39
|
+
from morphogen.models.planar import pixel_centres, plane_axes
|
|
40
|
+
from morphogen.seeding import SeedLike, make_rng
|
|
41
|
+
|
|
42
|
+
INTERSTITIAL, LAMELLAR, CEMENT, CANAL = 0, 1, 2, 3
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@njit(cache=True)
|
|
46
|
+
def _osteon_levels(offsets, ptr, osteons, radii, canal_ratio, cement, reach, out):
|
|
47
|
+
"""The level sets of the lamellar bone, cement lines, canals and interstitial bone at
|
|
48
|
+
points of the cross-section (``out``: (n, 4)), their candidate osteons from the top one down
|
|
49
|
+
(``osteons[ptr[p]:ptr[p + 1]]``, the offsets of the points from their axes): for each
|
|
50
|
+
phase, the minimum over the osteons ``i`` of ``max(s_i, -min_{j above i} (d_j -
|
|
51
|
+
r_j))``, ``s_i`` the signed distance to the disc or annulus of the phase in osteon
|
|
52
|
+
``i``, within ``[-reach, reach]``."""
|
|
53
|
+
for p in range(len(ptr) - 1):
|
|
54
|
+
lowest = np.inf
|
|
55
|
+
best0 = np.inf
|
|
56
|
+
best1 = np.inf
|
|
57
|
+
best2 = np.inf
|
|
58
|
+
for k in range(ptr[p], ptr[p + 1]):
|
|
59
|
+
i = osteons[k]
|
|
60
|
+
d = math.hypot(offsets[k, 0], offsets[k, 1])
|
|
61
|
+
r = radii[i]
|
|
62
|
+
above = -lowest
|
|
63
|
+
inner = canal_ratio * r
|
|
64
|
+
outer = r - cement
|
|
65
|
+
best0 = min(best0, max(max(inner - d, d - outer), above)) # lamellar
|
|
66
|
+
best1 = min(best1, max(max(outer - d, d - r), above)) # cement line
|
|
67
|
+
best2 = min(best2, max(d - inner, above)) # canal
|
|
68
|
+
lowest = min(lowest, d - r)
|
|
69
|
+
if lowest <= -reach:
|
|
70
|
+
break
|
|
71
|
+
out[p, 0] = min(max(best0, -reach), reach)
|
|
72
|
+
out[p, 1] = min(max(best1, -reach), reach)
|
|
73
|
+
out[p, 2] = min(max(best2, -reach), reach)
|
|
74
|
+
out[p, 3] = min(max(-lowest, -reach), reach) # interstitial: no osteon
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@register_kind
|
|
78
|
+
class OsteonStructure(Microstructure):
|
|
79
|
+
"""Osteons along ``axis``: discs of the cross-section (centres, radii) in the order
|
|
80
|
+
of their arrival, the last on top, with a canal of ``canal_ratio`` times their
|
|
81
|
+
radius and a cement line of ``cement`` thickness."""
|
|
82
|
+
|
|
83
|
+
kind = "osteons"
|
|
84
|
+
|
|
85
|
+
def __init__(self, domain, axis, centres, radii, canal_ratio, cement, **kwargs):
|
|
86
|
+
super().__init__(domain, **kwargs)
|
|
87
|
+
self.axis = int(axis)
|
|
88
|
+
self.centres = np.asarray(centres, dtype=float).reshape(-1, 2)
|
|
89
|
+
self.radii = np.asarray(radii, dtype=float).reshape(-1)
|
|
90
|
+
self.canal_ratio = float(canal_ratio)
|
|
91
|
+
self.cement = float(cement)
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def n_osteons(self) -> int:
|
|
95
|
+
return len(self.radii)
|
|
96
|
+
|
|
97
|
+
def _top(self, plane: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
|
98
|
+
"""The last osteon over each point of the cross-section (-1: none) and the
|
|
99
|
+
distance of the point to its axis."""
|
|
100
|
+
b, c = plane_axes(self.axis)
|
|
101
|
+
lower, lengths = self.domain.lower[[b, c]], self.domain.lengths[[b, c]]
|
|
102
|
+
periodic = self.domain.periodic
|
|
103
|
+
q = plane - lower
|
|
104
|
+
if periodic:
|
|
105
|
+
q = np.mod(q, lengths)
|
|
106
|
+
q[q >= lengths] = 0.0
|
|
107
|
+
top = np.full(len(q), -1, dtype=np.int64)
|
|
108
|
+
dist = np.full(len(q), np.inf)
|
|
109
|
+
if not len(q) or not self.n_osteons:
|
|
110
|
+
return top, dist
|
|
111
|
+
tree = cKDTree(q, boxsize=lengths if periodic else None)
|
|
112
|
+
centres = self.centres - lower
|
|
113
|
+
if periodic:
|
|
114
|
+
centres = np.mod(centres, lengths)
|
|
115
|
+
centres[centres >= lengths] = 0.0
|
|
116
|
+
for i in range(self.n_osteons): # in order of arrival: the later on top
|
|
117
|
+
hits = tree.query_ball_point(centres[i], self.radii[i], return_sorted=False)
|
|
118
|
+
if not hits:
|
|
119
|
+
continue
|
|
120
|
+
hits = np.asarray(hits, dtype=np.int64)
|
|
121
|
+
v = q[hits] - centres[i]
|
|
122
|
+
if periodic:
|
|
123
|
+
v -= lengths * np.round(v / lengths)
|
|
124
|
+
top[hits] = i
|
|
125
|
+
dist[hits] = np.hypot(v[:, 0], v[:, 1])
|
|
126
|
+
return top, dist
|
|
127
|
+
|
|
128
|
+
def _phases(self, plane: np.ndarray) -> np.ndarray:
|
|
129
|
+
top, dist = self._top(plane)
|
|
130
|
+
out = np.full(len(plane), INTERSTITIAL, dtype=np.uint8)
|
|
131
|
+
ok = top >= 0
|
|
132
|
+
r = self.radii[top[ok]]
|
|
133
|
+
d = dist[ok]
|
|
134
|
+
out[ok] = np.where(
|
|
135
|
+
d < self.canal_ratio * r, CANAL, np.where(d > r - self.cement, CEMENT, LAMELLAR)
|
|
136
|
+
)
|
|
137
|
+
return out
|
|
138
|
+
|
|
139
|
+
def phase_level_sets_at(self, points, reach: float = np.inf) -> dict[int, np.ndarray]:
|
|
140
|
+
"""The level sets of the lamellar bone (1), cement lines (2), canals (3) and
|
|
141
|
+
interstitial bone (0) at points: in the cross-section, the parts of each osteon not
|
|
142
|
+
covered by later ones, and the space no osteon covers (see :func:`_osteon_levels`),
|
|
143
|
+
within ``[-reach, reach]`` (default: the largest radius)."""
|
|
144
|
+
pts = np.asarray(points, dtype=float).reshape(-1, 3)
|
|
145
|
+
b, c = plane_axes(self.axis)
|
|
146
|
+
lower, lengths = self.domain.lower[[b, c]], self.domain.lengths[[b, c]]
|
|
147
|
+
periodic = self.domain.periodic
|
|
148
|
+
rmax = float(self.radii.max(initial=0.0))
|
|
149
|
+
reach = rmax if not np.isfinite(reach) else float(reach)
|
|
150
|
+
out = np.full((len(pts), 4), reach)
|
|
151
|
+
out[:, 3] = -reach # no osteon: interstitial
|
|
152
|
+
if self.n_osteons:
|
|
153
|
+
centres = self.centres - lower
|
|
154
|
+
q = pts[:, [b, c]] - lower
|
|
155
|
+
if periodic:
|
|
156
|
+
centres = np.mod(centres, lengths)
|
|
157
|
+
centres[centres >= lengths] = 0.0
|
|
158
|
+
q = np.mod(q, lengths)
|
|
159
|
+
q[q >= lengths] = 0.0
|
|
160
|
+
tree = cKDTree(centres, boxsize=lengths if periodic else None)
|
|
161
|
+
chunk = 8192
|
|
162
|
+
for s in range(0, len(q), chunk):
|
|
163
|
+
lists = tree.query_ball_point(q[s : s + chunk], rmax + reach)
|
|
164
|
+
counts = np.fromiter((len(x) for x in lists), dtype=np.int64, count=len(lists))
|
|
165
|
+
ost = np.fromiter(itertools.chain.from_iterable(lists), dtype=np.int64,
|
|
166
|
+
count=int(counts.sum())) # fmt: skip
|
|
167
|
+
owner = np.repeat(np.arange(len(lists)), counts)
|
|
168
|
+
order = np.lexsort((-ost, owner)) # from the top osteon down
|
|
169
|
+
ost, owner = ost[order], owner[order]
|
|
170
|
+
offsets = q[s : s + chunk][owner] - centres[ost]
|
|
171
|
+
if periodic:
|
|
172
|
+
offsets -= lengths * np.round(offsets / lengths)
|
|
173
|
+
ptr = np.concatenate([[0], np.cumsum(counts)])
|
|
174
|
+
_osteon_levels(np.ascontiguousarray(offsets), ptr, ost, self.radii,
|
|
175
|
+
self.canal_ratio, self.cement, reach,
|
|
176
|
+
out[s : s + chunk]) # fmt: skip
|
|
177
|
+
return {INTERSTITIAL: out[:, 3], LAMELLAR: out[:, 0], CEMENT: out[:, 1], CANAL: out[:, 2]}
|
|
178
|
+
|
|
179
|
+
def level_set_at(self, points, reach: float = np.inf) -> np.ndarray:
|
|
180
|
+
"""The function of the lamellar bone (phase 1) at the points
|
|
181
|
+
(:meth:`phase_level_sets_at`)."""
|
|
182
|
+
return self.phase_level_sets_at(points, reach)[LAMELLAR]
|
|
183
|
+
|
|
184
|
+
def contains(self, points) -> np.ndarray:
|
|
185
|
+
"""Whether points lie in the lamellar bone of the osteons (phase 1)."""
|
|
186
|
+
pts = np.asarray(points, dtype=float).reshape(-1, 3)
|
|
187
|
+
b, c = plane_axes(self.axis)
|
|
188
|
+
return self._phases(pts[:, [b, c]]) == LAMELLAR
|
|
189
|
+
|
|
190
|
+
# -- implicit functions ----------------------------------------------------------------
|
|
191
|
+
|
|
192
|
+
def implicit_phases(self) -> list[int]:
|
|
193
|
+
return [INTERSTITIAL, LAMELLAR, CEMENT, CANAL]
|
|
194
|
+
|
|
195
|
+
def _implicit(self, grid: Grid) -> np.ndarray:
|
|
196
|
+
"""The implicit functions of the four phases in the cross-section of a grid (kept
|
|
197
|
+
for the grid last asked): the rings of each osteon (its canal, its lamellae, its
|
|
198
|
+
cement line: differences of distances to its axis) where no later osteon covers
|
|
199
|
+
them, and the interstitial bone that none covers."""
|
|
200
|
+
from morphogen.models.implicit import band_of, grid_key, lattice_boxes, ordered_cover
|
|
201
|
+
|
|
202
|
+
key = grid_key(grid)
|
|
203
|
+
cached = getattr(self, "_fields", None)
|
|
204
|
+
if cached is not None and cached[0] == key:
|
|
205
|
+
return cached[1]
|
|
206
|
+
band = band_of(grid)
|
|
207
|
+
axes = plane_axes(self.axis)
|
|
208
|
+
lengths = self.domain.lengths if self.domain.periodic else None
|
|
209
|
+
shape = tuple(grid.shape[a] for a in axes)
|
|
210
|
+
|
|
211
|
+
def objects():
|
|
212
|
+
for i in range(self.n_osteons - 1, -1, -1): # the later on top
|
|
213
|
+
radius = self.radii[i]
|
|
214
|
+
canal, cement = self.canal_ratio * radius, radius - self.cement
|
|
215
|
+
reach = radius + band
|
|
216
|
+
for slices, (du, dv) in lattice_boxes(self.centres[i], reach, grid, lengths, axes):
|
|
217
|
+
r = np.hypot(du, dv).astype(np.float32)
|
|
218
|
+
parts = [None] * 4
|
|
219
|
+
parts[LAMELLAR] = np.maximum(canal - r, r - cement)
|
|
220
|
+
parts[CEMENT] = np.maximum(cement - r, r - radius)
|
|
221
|
+
parts[CANAL] = r - canal
|
|
222
|
+
yield slices, r - radius, parts
|
|
223
|
+
|
|
224
|
+
parts, top = ordered_cover(shape, band, objects(), 4)
|
|
225
|
+
parts[INTERSTITIAL] = -top
|
|
226
|
+
self._fields = (key, parts)
|
|
227
|
+
return parts
|
|
228
|
+
|
|
229
|
+
def phase_level_set(
|
|
230
|
+
self, phase: int, shape=None, *, voxel_size=None, grid: Grid | None = None
|
|
231
|
+
) -> VoxelImage:
|
|
232
|
+
"""The implicit function of a phase (see :meth:`Microstructure.phase_level_set`),
|
|
233
|
+
the same along the axis of the osteons."""
|
|
234
|
+
phase = int(phase)
|
|
235
|
+
if phase not in self.implicit_phases():
|
|
236
|
+
raise ValueError(f"phase {phase}: the phases are {self.implicit_phases()}")
|
|
237
|
+
grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
|
|
238
|
+
plane = self._implicit(grid)[phase]
|
|
239
|
+
out = np.broadcast_to(plane[:, :, None], (*plane.shape, grid.shape[self.axis]))
|
|
240
|
+
data = np.ascontiguousarray(np.moveaxis(out, 2, self.axis))
|
|
241
|
+
return VoxelImage.from_grid(data, grid, name="level_set", metadata=self.image_metadata())
|
|
242
|
+
|
|
243
|
+
def level_set(self, shape=None, *, voxel_size=None, grid: Grid | None = None) -> VoxelImage:
|
|
244
|
+
"""The implicit function of the lamellar bone of the osteons (phase 1)."""
|
|
245
|
+
return self.phase_level_set(LAMELLAR, shape, voxel_size=voxel_size, grid=grid)
|
|
246
|
+
|
|
247
|
+
def _image(self, grid: Grid) -> np.ndarray:
|
|
248
|
+
plane, shape = pixel_centres(grid, plane_axes(self.axis))
|
|
249
|
+
image = self._phases(plane).reshape(shape)
|
|
250
|
+
out = np.broadcast_to(image[:, :, None], (*shape, grid.shape[self.axis]))
|
|
251
|
+
return np.ascontiguousarray(np.moveaxis(out, 2, self.axis))
|
|
252
|
+
|
|
253
|
+
def voxelize(self, shape=None, *, voxel_size=None, grid: Grid | None = None, supersampling=1):
|
|
254
|
+
grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
|
|
255
|
+
ss = int(supersampling)
|
|
256
|
+
if ss == 1:
|
|
257
|
+
data = self._image(grid)
|
|
258
|
+
return VoxelImage.from_grid(data, grid, name="phase", metadata=self.image_metadata())
|
|
259
|
+
if not 1 <= ss <= 6:
|
|
260
|
+
raise ValueError("supersampling must be an integer between 1 and 6")
|
|
261
|
+
fine = Grid(grid.domain, tuple(n * ss for n in grid.shape))
|
|
262
|
+
ph = (self._image(fine) == LAMELLAR).astype(np.float32)
|
|
263
|
+
nx, ny, nz = grid.shape
|
|
264
|
+
data = ph.reshape(nx, ss, ny, ss, nz, ss).mean(axis=(1, 3, 5), dtype=np.float32)
|
|
265
|
+
return VoxelImage.from_grid(data, grid, name="fraction", metadata=self.image_metadata())
|
|
266
|
+
|
|
267
|
+
def summary(self) -> dict:
|
|
268
|
+
return {"n_osteons": self.n_osteons}
|
|
269
|
+
|
|
270
|
+
def _geometry(self) -> dict:
|
|
271
|
+
return {
|
|
272
|
+
"axis": self.axis,
|
|
273
|
+
"centres": self.centres.tolist(),
|
|
274
|
+
"radii": self.radii.tolist(),
|
|
275
|
+
"canal_ratio": self.canal_ratio,
|
|
276
|
+
"cement": self.cement,
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
@classmethod
|
|
280
|
+
def _from_geometry(cls, domain, geometry, **kwargs):
|
|
281
|
+
return cls(
|
|
282
|
+
domain,
|
|
283
|
+
geometry["axis"],
|
|
284
|
+
geometry["centres"],
|
|
285
|
+
geometry["radii"],
|
|
286
|
+
geometry["canal_ratio"],
|
|
287
|
+
geometry["cement"],
|
|
288
|
+
**kwargs,
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
@register
|
|
293
|
+
@dataclass(frozen=True)
|
|
294
|
+
class Osteons(Model):
|
|
295
|
+
"""Haversian bone: aligned osteons with canals and cement lines, remodelled one
|
|
296
|
+
after another over a fraction ``coverage`` of the cross-section (a dead-leaves
|
|
297
|
+
model of cylinders along ``axis``)."""
|
|
298
|
+
|
|
299
|
+
name = "osteons"
|
|
300
|
+
phases: ClassVar[dict[int, str]] = {
|
|
301
|
+
INTERSTITIAL: "interstitial bone",
|
|
302
|
+
LAMELLAR: "osteons (lamellar bone)",
|
|
303
|
+
CEMENT: "cement lines",
|
|
304
|
+
CANAL: "Haversian canals",
|
|
305
|
+
}
|
|
306
|
+
has_level_set = False
|
|
307
|
+
count_label = "osteons"
|
|
308
|
+
|
|
309
|
+
radius: Distribution = param(
|
|
310
|
+
1.0, doc="Radius of the osteons", kind="distribution", unit="length"
|
|
311
|
+
)
|
|
312
|
+
coverage: float = param(
|
|
313
|
+
0.7, doc="Fraction of the cross-section remodelled into osteons", kind="fraction"
|
|
314
|
+
)
|
|
315
|
+
canal_ratio: float = param(
|
|
316
|
+
0.2, doc="Radius of the Haversian canals, relative to the osteons", kind="fraction"
|
|
317
|
+
)
|
|
318
|
+
cement_thickness: float = param(0.03, doc="Thickness of the cement lines", unit="length")
|
|
319
|
+
axis: int = param(2, doc="Axis of the osteons (the bone axis: 0: x, 1: y, 2: z)", kind="int")
|
|
320
|
+
|
|
321
|
+
def _validate(self) -> None:
|
|
322
|
+
check_fraction(self.coverage, "coverage")
|
|
323
|
+
check_fraction(self.canal_ratio, "canal_ratio")
|
|
324
|
+
check_positive(self.cement_thickness, "cement_thickness", allow_zero=True)
|
|
325
|
+
if self.axis not in (0, 1, 2):
|
|
326
|
+
raise ValueError("axis: 0, 1 or 2")
|
|
327
|
+
|
|
328
|
+
@property
|
|
329
|
+
def intensity(self) -> float:
|
|
330
|
+
"""Osteons per unit area of the cross-section."""
|
|
331
|
+
return -math.log1p(-self.coverage) / (math.pi * self.radius.moment(2))
|
|
332
|
+
|
|
333
|
+
def generate(self, domain: Domain, seed: SeedLike = None) -> OsteonStructure:
|
|
334
|
+
rng, seed_info = make_rng(seed)
|
|
335
|
+
b, c = plane_axes(self.axis)
|
|
336
|
+
rmax = self.radius.upper()
|
|
337
|
+
margin = 0.0 if domain.periodic else rmax
|
|
338
|
+
lower = domain.lower[[b, c]] - margin
|
|
339
|
+
size = domain.lengths[[b, c]] + 2.0 * margin
|
|
340
|
+
n = int(rng.poisson(self.intensity * size[0] * size[1]))
|
|
341
|
+
centres = lower + rng.random((n, 2)) * size
|
|
342
|
+
radii = self.radius.sample(rng, n)
|
|
343
|
+
if domain.periodic and np.any(2.0 * radii > size.min()):
|
|
344
|
+
raise ValueError("osteons: a periodic box wider than the osteons")
|
|
345
|
+
return OsteonStructure(
|
|
346
|
+
domain,
|
|
347
|
+
self.axis,
|
|
348
|
+
centres,
|
|
349
|
+
radii,
|
|
350
|
+
self.canal_ratio,
|
|
351
|
+
self.cement_thickness,
|
|
352
|
+
model=self,
|
|
353
|
+
seed=seed_info,
|
|
354
|
+
)
|
|
355
|
+
|
|
356
|
+
def expected_count(self, domain: Domain) -> float:
|
|
357
|
+
"""Mean number of osteons across the domain (cut ones included)."""
|
|
358
|
+
b, c = plane_axes(self.axis)
|
|
359
|
+
return float(self.intensity * domain.lengths[b] * domain.lengths[c])
|
|
360
|
+
|
|
361
|
+
def theory(self, domain: Domain | None = None) -> dict[str, float]:
|
|
362
|
+
p, rho, t = self.coverage, self.canal_ratio, self.cement_thickness
|
|
363
|
+
r2 = self.radius.moment(2)
|
|
364
|
+
inner = self.radius.expect(lambda r: np.maximum(r - t, rho * r) ** 2)
|
|
365
|
+
canal = p * rho * rho
|
|
366
|
+
cement = p * (r2 - inner) / r2
|
|
367
|
+
return {
|
|
368
|
+
"intensity": self.intensity,
|
|
369
|
+
"volume_fraction_0": 1.0 - p,
|
|
370
|
+
"volume_fraction_1": p - canal - cement,
|
|
371
|
+
"volume_fraction_2": cement,
|
|
372
|
+
"volume_fraction_3": canal,
|
|
373
|
+
"porosity": canal,
|
|
374
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""The smooth pieces of the phases of structures made of spheres and segments.
|
|
2
|
+
|
|
3
|
+
The implicit function of a union of primitives is the smallest of their distances,
|
|
4
|
+
``min_i d_i``: smooth where one primitive is the nearest, folded where two are as near.
|
|
5
|
+
Its zero level set, the boundary of the union, has a *sharp edge* along the line where
|
|
6
|
+
the surfaces of two overlapping primitives meet (the groove between two spheres, the
|
|
7
|
+
line where two fibres cross). A function sampled on a grid cannot hold such an edge: a
|
|
8
|
+
mesher that cuts the box by the zero of ``min_i d_i`` rounds it over a cell.
|
|
9
|
+
|
|
10
|
+
Each primitive alone is smooth. The primitives of a union are therefore grouped into
|
|
11
|
+
*pieces* such that two primitives that overlap are never in the same piece — a colouring
|
|
12
|
+
of the graph of their overlaps (:func:`colours`), periodic images included. The distance
|
|
13
|
+
to a piece is smooth near its surface, the phase is the union of its pieces, and a mesher
|
|
14
|
+
that cuts the box by the surface of each piece in turn gets every sharp edge as the line
|
|
15
|
+
where two of its cuts meet (:func:`morphogen.mesh.conforming.conforming_mesh`). A coating
|
|
16
|
+
of thickness ``t`` is the union of the same primitives with their radii increased by
|
|
17
|
+
``t``, the core of a shell that of the primitives with their radii decreased: other
|
|
18
|
+
pieces, coloured again since thicker primitives overlap more.
|
|
19
|
+
|
|
20
|
+
A structure gives its pieces by :meth:`~morphogen.models.base.Microstructure.
|
|
21
|
+
implicit_pieces`, in the order of the cuts: a point belongs to the phase of the first
|
|
22
|
+
piece that holds it, or to the phase of what is left.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
from dataclasses import dataclass
|
|
28
|
+
|
|
29
|
+
import numpy as np
|
|
30
|
+
from numba import njit
|
|
31
|
+
from scipy.spatial import cKDTree
|
|
32
|
+
|
|
33
|
+
from morphogen.kernels.rsa import segment_distance2
|
|
34
|
+
from morphogen.primitives import Segments, Spheres
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass
|
|
38
|
+
class Piece:
|
|
39
|
+
"""A smooth piece of a phase: primitives that do not overlap (a union), and the
|
|
40
|
+
``phase`` of the points that it holds."""
|
|
41
|
+
|
|
42
|
+
phase: int
|
|
43
|
+
union: object # a PrimitiveUnion
|
|
44
|
+
|
|
45
|
+
def at(self, points, band: float) -> np.ndarray:
|
|
46
|
+
"""The signed distance to the piece (negative inside) at ``points``, clipped to
|
|
47
|
+
``[-band, band]``."""
|
|
48
|
+
return self.union.signed_distance(points, float(band))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@njit(cache=True)
|
|
52
|
+
def _penetrations(start, ray, radii, first, second, out):
|
|
53
|
+
"""The depth by which the capsules ``first[k]`` and ``second[k]`` enter each other:
|
|
54
|
+
the sum of their radii less the distance of their axes."""
|
|
55
|
+
for k in range(first.shape[0]):
|
|
56
|
+
i, j = first[k], second[k]
|
|
57
|
+
distance = np.sqrt(segment_distance2(start[i], ray[i], start[j], ray[j]))
|
|
58
|
+
out[k] = radii[i] + radii[j] - distance
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _capsules(spheres: Spheres, segments: Segments, offset: float):
|
|
62
|
+
"""The primitives as capsules (spheres first): starts, rays to their ends, radii
|
|
63
|
+
increased by ``offset``."""
|
|
64
|
+
start = np.concatenate([spheres.centers, segments.start])
|
|
65
|
+
ray = np.concatenate([np.zeros_like(spheres.centers), segments.end - segments.start])
|
|
66
|
+
radii = np.concatenate([spheres.radii, segments.radii]) + float(offset)
|
|
67
|
+
return np.ascontiguousarray(start), np.ascontiguousarray(ray), np.ascontiguousarray(radii)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def overlaps(union, offset: float = 0.0, depth: float = 0.0) -> np.ndarray:
|
|
71
|
+
"""The pairs of primitives of a union (spheres first, then segments) that enter each
|
|
72
|
+
other by more than ``depth``, their radii increased by ``offset``; through the faces
|
|
73
|
+
of a periodic box as well. Rows ``(i, j)`` with ``i < j``."""
|
|
74
|
+
start, ray, radii = _capsules(union.spheres, union.segments, offset)
|
|
75
|
+
n = len(radii)
|
|
76
|
+
alive = radii > 0.0
|
|
77
|
+
if n < 2:
|
|
78
|
+
return np.zeros((0, 2), dtype=np.int64)
|
|
79
|
+
middle = start + 0.5 * ray
|
|
80
|
+
reach = 0.5 * np.linalg.norm(ray, axis=1) + np.maximum(radii, 0.0)
|
|
81
|
+
# the primitives and their images around the box, with the primitive of each
|
|
82
|
+
index = [np.arange(n)]
|
|
83
|
+
shifts = [np.zeros((n, 3))]
|
|
84
|
+
if union.domain.periodic:
|
|
85
|
+
lengths = np.asarray(union.domain.lengths, dtype=float)
|
|
86
|
+
lower = np.asarray(union.domain.lower, dtype=float) - 2.0 * reach.max()
|
|
87
|
+
upper = np.asarray(union.domain.upper, dtype=float) + 2.0 * reach.max()
|
|
88
|
+
most = int(np.ceil(4.0 * reach.max() / lengths.min())) + 1
|
|
89
|
+
for shift in np.ndindex(*(2 * most + 1,) * 3):
|
|
90
|
+
move = (np.array(shift) - most) * lengths
|
|
91
|
+
if not move.any():
|
|
92
|
+
continue
|
|
93
|
+
moved = middle + move
|
|
94
|
+
near = np.all((moved + reach[:, None] >= lower) & (moved - reach[:, None] <= upper), 1)
|
|
95
|
+
index.append(np.flatnonzero(near))
|
|
96
|
+
shifts.append(np.broadcast_to(move, (int(near.sum()), 3)))
|
|
97
|
+
index = np.concatenate(index)
|
|
98
|
+
shifts = np.concatenate(shifts)
|
|
99
|
+
tree = cKDTree(middle[index] + shifts)
|
|
100
|
+
found = tree.query_ball_point(middle, reach + reach.max())
|
|
101
|
+
first = np.repeat(np.arange(n), [len(f) for f in found])
|
|
102
|
+
second = np.concatenate([np.asarray(f, dtype=np.int64) for f in found])
|
|
103
|
+
keep = (index[second] != first) & alive[first] & alive[index[second]]
|
|
104
|
+
keep &= np.linalg.norm(middle[first] - tree.data[second], axis=1) < (
|
|
105
|
+
reach[first] + reach[index[second]]
|
|
106
|
+
)
|
|
107
|
+
first, second = first[keep], second[keep]
|
|
108
|
+
if not len(first):
|
|
109
|
+
return np.zeros((0, 2), dtype=np.int64)
|
|
110
|
+
# the capsules and their images in one array, for the kernel
|
|
111
|
+
all_start = np.ascontiguousarray(start[index] + shifts)
|
|
112
|
+
all_ray = np.ascontiguousarray(ray[index])
|
|
113
|
+
all_radii = np.ascontiguousarray(radii[index])
|
|
114
|
+
deep = np.empty(len(first))
|
|
115
|
+
_penetrations(all_start, all_ray, all_radii, first, second, deep)
|
|
116
|
+
pairs = np.stack([first, index[second]], axis=1)[deep > float(depth)]
|
|
117
|
+
return np.unique(np.sort(pairs, axis=1), axis=0)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def colours(n: int, pairs: np.ndarray) -> np.ndarray:
|
|
121
|
+
"""A colour for each of ``n`` vertices of a graph such that the two vertices of each
|
|
122
|
+
of its edges ``pairs`` differ: the vertices of largest degree first, each takes the
|
|
123
|
+
smallest colour that its neighbours do not have (Welsh & Powell 1967)."""
|
|
124
|
+
colour = np.full(n, -1, dtype=np.int64)
|
|
125
|
+
neighbours: list[list[int]] = [[] for _ in range(n)]
|
|
126
|
+
for i, j in np.asarray(pairs, dtype=np.int64):
|
|
127
|
+
neighbours[i].append(int(j))
|
|
128
|
+
neighbours[j].append(int(i))
|
|
129
|
+
order = sorted(range(n), key=lambda k: (-len(neighbours[k]), k))
|
|
130
|
+
for k in order:
|
|
131
|
+
taken = {colour[q] for q in neighbours[k]}
|
|
132
|
+
c = 0
|
|
133
|
+
while c in taken:
|
|
134
|
+
c += 1
|
|
135
|
+
colour[k] = c
|
|
136
|
+
return colour
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def union_pieces(union, offset: float = 0.0, depth: float = 0.0) -> list:
|
|
140
|
+
"""The pieces of a union of spheres and segments whose radii are increased by
|
|
141
|
+
``offset`` (decreased, if negative: the primitives that vanish are left out): unions
|
|
142
|
+
of primitives that do not enter each other by more than ``depth``, as few as the
|
|
143
|
+
colouring finds."""
|
|
144
|
+
from morphogen.models.union import PrimitiveUnion
|
|
145
|
+
|
|
146
|
+
spheres, segments = union.spheres, union.segments
|
|
147
|
+
n_s = len(spheres)
|
|
148
|
+
radii = np.concatenate([spheres.radii, segments.radii]) + float(offset)
|
|
149
|
+
colour = colours(len(radii), overlaps(union, offset, depth))
|
|
150
|
+
out = []
|
|
151
|
+
for c in range(int(colour.max(initial=-1)) + 1):
|
|
152
|
+
mask = (colour == c) & (radii > 0.0)
|
|
153
|
+
if not mask.any():
|
|
154
|
+
continue
|
|
155
|
+
s, g = mask[:n_s], mask[n_s:]
|
|
156
|
+
out.append(
|
|
157
|
+
PrimitiveUnion(
|
|
158
|
+
union.domain,
|
|
159
|
+
Spheres(spheres.centers[s], spheres.radii[s] + offset),
|
|
160
|
+
Segments(segments.start[g], segments.end[g], segments.radii[g] + offset,
|
|
161
|
+
segments.round_caps),
|
|
162
|
+
)
|
|
163
|
+
) # fmt: skip
|
|
164
|
+
return out
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
__all__ = ["Piece", "colours", "overlaps", "union_pieces"]
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Tessellations of a plane: the cells of the layered and prismatic bio-inspired models
|
|
2
|
+
(the tablets of nacre, honeycombs, the cells of wood).
|
|
3
|
+
|
|
4
|
+
A point ``x`` of the plane belongs to the cell of its nearest germ ``g_i``. Its distance
|
|
5
|
+
to the side shared with the cell of ``g_j`` is ``(|x - g_j|^2 - |x - g_i|^2) /
|
|
6
|
+
(2 |g_j - g_i|)``, and the smallest of these is its distance to the boundary of its
|
|
7
|
+
(convex) cell; the germs whose side is closer than ``r`` lie within ``|x - g_i| + 2 r``
|
|
8
|
+
of the point, so that the nearest germs suffice (as for the tessellations of space).
|
|
9
|
+
On a periodic rectangle the germs are taken once: a cell is not bounded by its own
|
|
10
|
+
images, so that a rectangle one cell wide makes the cells continuous across it.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import math
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
from scipy.spatial import cKDTree
|
|
19
|
+
|
|
20
|
+
from morphogen import settings
|
|
21
|
+
from morphogen.kernels.rsa import random_sequential_addition
|
|
22
|
+
|
|
23
|
+
#: Fraction of the plane covered by discs at the jamming limit of their random sequential
|
|
24
|
+
#: addition (Feder 1980): the densest random packing that RSA reaches.
|
|
25
|
+
RSA_JAMMING_2D = 0.547
|
|
26
|
+
|
|
27
|
+
#: Points per k-d tree query (bounds the memory of large grids).
|
|
28
|
+
_CHUNK = 1 << 18
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class PlanarCells:
|
|
32
|
+
"""Voronoi cells of germs in a rectangle of the plane, periodic or not (the germs of
|
|
33
|
+
a window larger than the rectangle, then)."""
|
|
34
|
+
|
|
35
|
+
def __init__(self, germs, lengths, periodic: bool, origin=(0.0, 0.0)) -> None:
|
|
36
|
+
self.germs = np.asarray(germs, dtype=float).reshape(-1, 2)
|
|
37
|
+
self.lengths = np.asarray(lengths, dtype=float).reshape(2)
|
|
38
|
+
self.origin = np.asarray(origin, dtype=float).reshape(2)
|
|
39
|
+
self.periodic = bool(periodic)
|
|
40
|
+
if not len(self.germs):
|
|
41
|
+
raise ValueError("planar cells: no germs")
|
|
42
|
+
self._tree: cKDTree | None = None
|
|
43
|
+
|
|
44
|
+
def _local(self, points) -> np.ndarray:
|
|
45
|
+
p = np.asarray(points, dtype=float).reshape(-1, 2) - self.origin
|
|
46
|
+
if self.periodic:
|
|
47
|
+
p = np.mod(p, self.lengths)
|
|
48
|
+
p[p >= self.lengths] = 0.0
|
|
49
|
+
return p
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def tree(self) -> cKDTree:
|
|
53
|
+
if self._tree is None:
|
|
54
|
+
box = self.lengths if self.periodic else None
|
|
55
|
+
self._tree = cKDTree(self._local(self.germs), boxsize=box)
|
|
56
|
+
return self._tree
|
|
57
|
+
|
|
58
|
+
def locate(self, points, reach: float = math.inf) -> tuple[np.ndarray, np.ndarray]:
|
|
59
|
+
"""Cell (germ index) of each point and its distance to the boundary of the cell,
|
|
60
|
+
exact up to ``reach`` and at least ``reach`` beyond (``inf``: a single cell)."""
|
|
61
|
+
q = self._local(points)
|
|
62
|
+
n = len(self.germs)
|
|
63
|
+
labels = np.zeros(len(q), dtype=np.int64)
|
|
64
|
+
out = np.full(len(q), np.inf)
|
|
65
|
+
if n == 1 or not len(q):
|
|
66
|
+
return labels, out
|
|
67
|
+
germs = self._local(self.germs)
|
|
68
|
+
for start in range(0, len(q), _CHUNK):
|
|
69
|
+
todo, k = np.arange(start, min(len(q), start + _CHUNK)), min(n, 12)
|
|
70
|
+
while todo.size:
|
|
71
|
+
dist, idx = self.tree.query(q[todo], k=k, workers=settings.workers())
|
|
72
|
+
labels[todo] = idx[:, 0]
|
|
73
|
+
v = germs[idx] - q[todo, None, :] # the germs seen from the points
|
|
74
|
+
if self.periodic:
|
|
75
|
+
v -= self.lengths * np.round(v / self.lengths)
|
|
76
|
+
gap = np.linalg.norm(v[:, 1:] - v[:, :1], axis=2)
|
|
77
|
+
d = (dist[:, 1:] ** 2 - dist[:, :1] ** 2) / (2.0 * np.maximum(gap, 1e-300))
|
|
78
|
+
out[todo] = d.min(axis=1)
|
|
79
|
+
# the farthest germ found must lie beyond l_i + 2 min(d, reach)
|
|
80
|
+
bound = dist[:, 0] + 2.0 * np.minimum(out[todo], reach)
|
|
81
|
+
again = (dist[:, -1] <= bound) & (k < n)
|
|
82
|
+
todo, k = todo[again], min(n, 2 * k)
|
|
83
|
+
return labels, out
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def hardcore_germs(n: int, lengths, distance: float, rng) -> np.ndarray:
|
|
87
|
+
"""``n`` points of the periodic rectangle ``[0, lengths)``, at least ``distance``
|
|
88
|
+
apart (random sequential addition of discs; uniform points for no distance)."""
|
|
89
|
+
lengths = np.asarray(lengths, dtype=float).reshape(2)
|
|
90
|
+
if n <= 0:
|
|
91
|
+
return np.empty((0, 2))
|
|
92
|
+
if not distance > 0:
|
|
93
|
+
return rng.random((n, 2)) * lengths
|
|
94
|
+
thin = 1e-9 * float(lengths.min()) # a slab: the distances are those in the plane
|
|
95
|
+
box = np.array([lengths[0], lengths[1], thin])
|
|
96
|
+
pos = random_sequential_addition(
|
|
97
|
+
np.full(n, 0.5 * distance), box, 0.0, rng, max_attempts=4000 * n + 100_000
|
|
98
|
+
)
|
|
99
|
+
return pos[:, :2]
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def jamming_distance(n: int, area: float) -> float:
|
|
103
|
+
"""Distance between ``n`` points of an ``area`` at the jamming limit of their
|
|
104
|
+
random sequential addition."""
|
|
105
|
+
return math.sqrt(4.0 * RSA_JAMMING_2D * area / (math.pi * max(n, 1)))
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def plane_axes(axis: int) -> tuple[int, int]:
|
|
109
|
+
"""The two axes orthogonal to ``axis``, in increasing order."""
|
|
110
|
+
b, c = (a for a in range(3) if a != axis)
|
|
111
|
+
return b, c
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def pixel_centres(grid, axes: tuple[int, int]) -> tuple[np.ndarray, tuple[int, int]]:
|
|
115
|
+
"""Centres of the voxels of a grid projected on the plane of ``axes``: an array of
|
|
116
|
+
points (row-major over the two axes) and the shape of the pixel image."""
|
|
117
|
+
b, c = axes
|
|
118
|
+
u = grid.domain.lower[b] + (np.arange(grid.shape[b]) + 0.5) * grid.spacing[b]
|
|
119
|
+
v = grid.domain.lower[c] + (np.arange(grid.shape[c]) + 0.5) * grid.spacing[c]
|
|
120
|
+
uu, vv = np.meshgrid(u, v, indexing="ij")
|
|
121
|
+
return np.column_stack([uu.ravel(), vv.ravel()]), (len(u), len(v))
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def axis_centres(grid, axis: int) -> np.ndarray:
|
|
125
|
+
"""Coordinates of the voxel centres along ``axis``."""
|
|
126
|
+
return grid.domain.lower[axis] + (np.arange(grid.shape[axis]) + 0.5) * grid.spacing[axis]
|