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,1409 @@
|
|
|
1
|
+
"""Scale-rich networks: ligaments of power-law thicknesses grown one after another until
|
|
2
|
+
they meet (Both, Chen, Gao, Mooij, Charara, Wadhwa, Portela & Barabási 2026).
|
|
3
|
+
|
|
4
|
+
Mechanical metamaterials are usually ruled by one length, that of their cell. Scale-rich
|
|
5
|
+
networks give up that length: their ligaments span orders of magnitude in thickness,
|
|
6
|
+
length and connectivity within one sample, as the veins of leaves and dragonfly wings, the
|
|
7
|
+
threads of spider webs or the roads of a city. Both et al. (Nature 659, 345, 2026) grow
|
|
8
|
+
them from two parameters:
|
|
9
|
+
|
|
10
|
+
* the ligament ``t = 1, 2, ..., T`` is ``lambda_t = lambda_0 t^-alpha`` thick
|
|
11
|
+
(``initial_thickness`` and ``decay``);
|
|
12
|
+
* it nucleates at a point drawn uniformly in the voids left by the ligaments before it,
|
|
13
|
+
along an angle ``theta_t``, and grows both ways until it meets the face of another
|
|
14
|
+
ligament or the boundary of the box.
|
|
15
|
+
|
|
16
|
+
The voids are convex cells (at first the rectangle of the box), each bounded by faces of
|
|
17
|
+
ligaments and of the box. A ligament lies in the cell of its nucleation point: it is the
|
|
18
|
+
strip of width ``lambda_t`` along its line clipped by that cell, which it splits into two
|
|
19
|
+
convex cells (the scheme of the reference implementation of the authors). The point is
|
|
20
|
+
drawn uniformly in the box until it falls in a void, the same law as a void drawn in
|
|
21
|
+
proportion to its area then a point uniform in it. Ligaments and voids partition the box
|
|
22
|
+
exactly, so that the relative density ``1 - sum(void areas) / A`` is exact; the ligaments
|
|
23
|
+
never overlap. A ligament fits when its cell holds the two points at
|
|
24
|
+
``(lambda_t + epsilon) / 2`` on either side of its nucleation point (``epsilon``:
|
|
25
|
+
``min_spacing``, the least width of the voids beside a new ligament); when
|
|
26
|
+
``max_attempts`` draws in a row do not fit, the network is jammed and stops growing. The
|
|
27
|
+
length of a ligament is that of its centre line in its cell; its neighbours are the
|
|
28
|
+
ligaments (or the box) on which its two ends lie. As roads in the dual graphs of road
|
|
29
|
+
networks (Rosvall et al. 2005), the ligaments are the nodes of the network and their
|
|
30
|
+
junctions its links: the degree ``k`` of a ligament counts the ligaments on which it ends
|
|
31
|
+
and those that end on it.
|
|
32
|
+
|
|
33
|
+
Laws (Both et al. 2026): the thicknesses follow ``P(lambda) ~ lambda^-(1 + 1/alpha)``
|
|
34
|
+
exactly; a ligament splits a cell of area about ``A_t / t``, so that its length decays
|
|
35
|
+
as ``t^-1/2`` (``A_t``: the area of the voids) and the lengths have the tail ``P(l) ~
|
|
36
|
+
l^-3``; a long ligament is met by the ligaments that end on it in proportion to its
|
|
37
|
+
length (a spatial preferential attachment), and the degrees have the tail ``P(k) ~ k^-3``.
|
|
38
|
+
The relative density is ``sum_t lambda_t l_t / A`` (``l_t`` the length of ``t``), see
|
|
39
|
+
:meth:`ScaleRichNetwork.theory`.
|
|
40
|
+
|
|
41
|
+
Orientations: uniform (the scale-rich networks of the paper), drawn among ``angles``
|
|
42
|
+
(aligned networks, e.g. ``[0, 90]``), or polarized by a ``pole`` (the ligaments along the
|
|
43
|
+
direction of the pole turned by ``pole_angle``: radial, tangential or spiral, for the
|
|
44
|
+
``polarized_fraction`` first of them), each spread by ``angle_spread`` (a normal law).
|
|
45
|
+
The nucleation density may follow a gradient along an axis of the plane or away from the
|
|
46
|
+
pole (``nucleation_gradient``). Their combinations draw the designs of Fig. 6 of the
|
|
47
|
+
paper, as the radial gradient of the pomelo peel protecting a payload.
|
|
48
|
+
|
|
49
|
+
The network lies in the plane of the two axes other than ``axis`` and is extruded along
|
|
50
|
+
it through the box: the prismatic specimens of the paper (plane strain), one voxel thick
|
|
51
|
+
for planar images. Its ligaments end on the faces of the box, which is not periodic; a
|
|
52
|
+
``frame`` of material around the network, on which they end, makes the sample the cell of
|
|
53
|
+
a periodic medium (FFT solvers, Bloch waves), stiffened by the frame.
|
|
54
|
+
|
|
55
|
+
With ``dimension: 3``, the network grows in space: plates that split convex polyhedral
|
|
56
|
+
voids (closed cells), or beams (open cells), see :mod:`morphogen.models.scale_rich_3d`.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
from __future__ import annotations
|
|
60
|
+
|
|
61
|
+
import itertools
|
|
62
|
+
import math
|
|
63
|
+
from dataclasses import dataclass
|
|
64
|
+
from statistics import NormalDist
|
|
65
|
+
from typing import ClassVar
|
|
66
|
+
|
|
67
|
+
import numpy as np
|
|
68
|
+
from numba import njit, prange
|
|
69
|
+
|
|
70
|
+
from morphogen._utils import check_fraction, check_positive, exactly_one
|
|
71
|
+
from morphogen.domain import Domain, Grid
|
|
72
|
+
from morphogen.image import VoxelImage
|
|
73
|
+
from morphogen.models.base import Microstructure, Model, param, register, register_kind
|
|
74
|
+
from morphogen.models.planar import pixel_centres, plane_axes
|
|
75
|
+
from morphogen.models.scale_rich_3d import (
|
|
76
|
+
AREA_CONSTANT,
|
|
77
|
+
BOX,
|
|
78
|
+
ScaleRichBeams,
|
|
79
|
+
ScaleRichPlates,
|
|
80
|
+
area_sum,
|
|
81
|
+
beam_density_estimate,
|
|
82
|
+
beam_thickness_estimate,
|
|
83
|
+
first_area,
|
|
84
|
+
grow_beams,
|
|
85
|
+
grow_plates,
|
|
86
|
+
)
|
|
87
|
+
from morphogen.orientations import OrientationDistribution, orthonormal_basis, uniform_unit_vectors
|
|
88
|
+
from morphogen.seeding import SeedLike, make_rng
|
|
89
|
+
|
|
90
|
+
#: Tolerance on the relative density of a realization solved for a ``volume_fraction``
|
|
91
|
+
DENSITY_TOL = 2e-4
|
|
92
|
+
#: ``lim sqrt(t / A) E[l_t]``: the mean length of the ligament ``t`` of a thin network
|
|
93
|
+
#: (``lambda_0 -> 0``) in a box of area ``A``, measured with uniform orientations: 1.1663
|
|
94
|
+
#: and 1.1658 (standard errors 0.0004) over the ligaments ``t >= 2000`` of 120
|
|
95
|
+
#: realizations of 20,000 in a square and in a 2 x 1 rectangle. The first ligament is
|
|
96
|
+
#: ``l_0`` (:func:`first_length`, 0.9464 in a square), the next ones approach the limit
|
|
97
|
+
#: (1.05, 1.09, 1.12 at ``t`` = 2, 3, 5)
|
|
98
|
+
LENGTH_CONSTANT = 1.166
|
|
99
|
+
#: Uniform draws of a nucleation point: its two coordinates, its rejection by the density
|
|
100
|
+
#: of nucleation, and two for its angle (the angle, and the normal of its spread)
|
|
101
|
+
_DRAWS = 5
|
|
102
|
+
|
|
103
|
+
# -- convex polygons (counter-clockwise vertices, the label of the face of each edge) -------
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
@njit(cache=True)
|
|
107
|
+
def polygon_area(xy) -> float:
|
|
108
|
+
"""Area of a polygon (counter-clockwise: positive) by the shoelace formula."""
|
|
109
|
+
m = xy.shape[0]
|
|
110
|
+
s = 0.0
|
|
111
|
+
for j in range(m):
|
|
112
|
+
k = (j + 1) % m
|
|
113
|
+
s += xy[j, 0] * xy[k, 1] - xy[k, 0] * xy[j, 1]
|
|
114
|
+
return 0.5 * s
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@njit(cache=True)
|
|
118
|
+
def _merged(xy, faces, tol):
|
|
119
|
+
"""The polygon without its edges shorter than ``tol`` (a vertex that coincides with
|
|
120
|
+
the next one goes, the next one keeping the face of its outgoing edge)."""
|
|
121
|
+
m = xy.shape[0]
|
|
122
|
+
keep = np.ones(m, dtype=np.bool_)
|
|
123
|
+
for j in range(m):
|
|
124
|
+
k = (j + 1) % m
|
|
125
|
+
if abs(xy[j, 0] - xy[k, 0]) <= tol and abs(xy[j, 1] - xy[k, 1]) <= tol:
|
|
126
|
+
keep[j] = False
|
|
127
|
+
if keep.all():
|
|
128
|
+
return xy, faces
|
|
129
|
+
if not keep.any():
|
|
130
|
+
return xy[:1].copy(), faces[:1].copy()
|
|
131
|
+
return xy[keep].copy(), faces[keep].copy()
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
@njit(cache=True)
|
|
135
|
+
def clip_polygon(xy, faces, nx, ny, c, label, tol):
|
|
136
|
+
"""The part of a convex polygon where ``nx x + ny y <= c``: its vertices and the faces
|
|
137
|
+
of its edges, the edge along the line labelled ``label`` (Sutherland-Hodgman)."""
|
|
138
|
+
m = xy.shape[0]
|
|
139
|
+
out = np.empty((m + 2, 2))
|
|
140
|
+
out_faces = np.empty(m + 2, dtype=np.int64)
|
|
141
|
+
k = 0
|
|
142
|
+
for j in range(m):
|
|
143
|
+
jn = (j + 1) % m
|
|
144
|
+
dj = nx * xy[j, 0] + ny * xy[j, 1] - c
|
|
145
|
+
dn = nx * xy[jn, 0] + ny * xy[jn, 1] - c
|
|
146
|
+
if dj <= 0.0:
|
|
147
|
+
out[k, 0], out[k, 1] = xy[j, 0], xy[j, 1]
|
|
148
|
+
out_faces[k] = faces[j]
|
|
149
|
+
k += 1
|
|
150
|
+
if dn > 0.0: # leaves the half-plane: the rest of the edge, then the line
|
|
151
|
+
t = dj / (dj - dn)
|
|
152
|
+
out[k, 0] = xy[j, 0] + t * (xy[jn, 0] - xy[j, 0])
|
|
153
|
+
out[k, 1] = xy[j, 1] + t * (xy[jn, 1] - xy[j, 1])
|
|
154
|
+
out_faces[k] = label
|
|
155
|
+
k += 1
|
|
156
|
+
elif dn <= 0.0: # enters it: the rest of the edge
|
|
157
|
+
t = dj / (dj - dn)
|
|
158
|
+
out[k, 0] = xy[j, 0] + t * (xy[jn, 0] - xy[j, 0])
|
|
159
|
+
out[k, 1] = xy[j, 1] + t * (xy[jn, 1] - xy[j, 1])
|
|
160
|
+
out_faces[k] = faces[j]
|
|
161
|
+
k += 1
|
|
162
|
+
return _merged(out[:k], out_faces[:k], tol)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
@njit(cache=True)
|
|
166
|
+
def chord(xy, faces, px, py, dx, dy):
|
|
167
|
+
"""Where the line ``p + s d`` leaves a convex polygon holding ``p``: ``s0 <= 0 <=
|
|
168
|
+
s1``, and the faces of the edges it leaves by."""
|
|
169
|
+
m = xy.shape[0]
|
|
170
|
+
s0, s1 = -np.inf, np.inf
|
|
171
|
+
f0, f1 = BOX, BOX
|
|
172
|
+
for j in range(m):
|
|
173
|
+
jn = (j + 1) % m
|
|
174
|
+
mx = -(xy[jn, 1] - xy[j, 1]) # the inward normal of the edge (not unit)
|
|
175
|
+
my = xy[jn, 0] - xy[j, 0]
|
|
176
|
+
h = mx * (px - xy[j, 0]) + my * (py - xy[j, 1])
|
|
177
|
+
md = mx * dx + my * dy
|
|
178
|
+
if md < 0.0:
|
|
179
|
+
s = -h / md
|
|
180
|
+
if s < s1:
|
|
181
|
+
s1, f1 = s, faces[j]
|
|
182
|
+
elif md > 0.0:
|
|
183
|
+
s = -h / md
|
|
184
|
+
if s > s0:
|
|
185
|
+
s0, f0 = s, faces[j]
|
|
186
|
+
return s0, s1, f0, f1
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
@njit(cache=True)
|
|
190
|
+
def fits(xy, px, py, nx, ny, half) -> bool:
|
|
191
|
+
"""Whether a convex polygon holds the points ``p +- half n``."""
|
|
192
|
+
m = xy.shape[0]
|
|
193
|
+
for j in range(m):
|
|
194
|
+
jn = (j + 1) % m
|
|
195
|
+
ex, ey = xy[jn, 0] - xy[j, 0], xy[jn, 1] - xy[j, 1]
|
|
196
|
+
mx, my = -ey, ex
|
|
197
|
+
h = mx * (px - xy[j, 0]) + my * (py - xy[j, 1])
|
|
198
|
+
if h - half * abs(mx * nx + my * ny) < 0.0:
|
|
199
|
+
return False
|
|
200
|
+
return True
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
@njit(cache=True)
|
|
204
|
+
def inside_polygon(xy, px, py) -> bool:
|
|
205
|
+
"""Whether a convex polygon (counter-clockwise) holds the point ``p``."""
|
|
206
|
+
m = xy.shape[0]
|
|
207
|
+
for j in range(m):
|
|
208
|
+
jn = (j + 1) % m
|
|
209
|
+
cross = (xy[jn, 0] - xy[j, 0]) * (py - xy[j, 1]) - (xy[jn, 1] - xy[j, 1]) * (px - xy[j, 0])
|
|
210
|
+
if cross < 0.0:
|
|
211
|
+
return False
|
|
212
|
+
return True
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
class _Voids:
|
|
216
|
+
"""The voids of a growing network registered in a grid of buckets of the rectangle, to
|
|
217
|
+
find the void that holds a point (or none: the point lies in a ligament)."""
|
|
218
|
+
|
|
219
|
+
def __init__(self, lower, upper, n_buckets: int) -> None:
|
|
220
|
+
self.lo = np.asarray(lower, dtype=float)
|
|
221
|
+
size = np.asarray(upper, dtype=float) - self.lo
|
|
222
|
+
g = np.clip(np.ceil(math.sqrt(max(n_buckets, 1)) * size / math.sqrt(np.prod(size))),
|
|
223
|
+
1, 256) # fmt: skip
|
|
224
|
+
self.g0, self.g1 = int(g[0]), int(g[1])
|
|
225
|
+
self.h0, self.h1 = float(size[0] / g[0]), float(size[1] / g[1])
|
|
226
|
+
self.buckets: list[set[int]] = [set() for _ in range(self.g0 * self.g1)]
|
|
227
|
+
self.boxes: dict[int, tuple] = {}
|
|
228
|
+
self.cells: list[np.ndarray] = []
|
|
229
|
+
|
|
230
|
+
def _range(self, v, lo, h, n) -> int:
|
|
231
|
+
return min(max(math.floor((v - lo) / h), 0), n - 1)
|
|
232
|
+
|
|
233
|
+
def put(self, cid: int, xy: np.ndarray) -> None:
|
|
234
|
+
"""Registers the void ``cid`` (a new one, or in place of the old ``cid``)."""
|
|
235
|
+
if cid < len(self.cells):
|
|
236
|
+
self.drop(cid)
|
|
237
|
+
self.cells[cid] = xy
|
|
238
|
+
else:
|
|
239
|
+
self.cells.append(xy)
|
|
240
|
+
x0, y0 = xy.min(axis=0)
|
|
241
|
+
x1, y1 = xy.max(axis=0)
|
|
242
|
+
i0, i1 = (
|
|
243
|
+
self._range(x0, self.lo[0], self.h0, self.g0),
|
|
244
|
+
self._range(x1, self.lo[0], self.h0, self.g0),
|
|
245
|
+
)
|
|
246
|
+
j0, j1 = (
|
|
247
|
+
self._range(y0, self.lo[1], self.h1, self.g1),
|
|
248
|
+
self._range(y1, self.lo[1], self.h1, self.g1),
|
|
249
|
+
)
|
|
250
|
+
self.boxes[cid] = (x0, y0, x1, y1, i0, i1, j0, j1)
|
|
251
|
+
for i in range(i0, i1 + 1):
|
|
252
|
+
for j in range(j0, j1 + 1):
|
|
253
|
+
self.buckets[i * self.g1 + j].add(cid)
|
|
254
|
+
|
|
255
|
+
def drop(self, cid: int) -> None:
|
|
256
|
+
*_, i0, i1, j0, j1 = self.boxes.pop(cid)
|
|
257
|
+
for i in range(i0, i1 + 1):
|
|
258
|
+
for j in range(j0, j1 + 1):
|
|
259
|
+
self.buckets[i * self.g1 + j].discard(cid)
|
|
260
|
+
|
|
261
|
+
def locate(self, px: float, py: float) -> int:
|
|
262
|
+
i = self._range(px, self.lo[0], self.h0, self.g0)
|
|
263
|
+
j = self._range(py, self.lo[1], self.h1, self.g1)
|
|
264
|
+
for cid in self.buckets[i * self.g1 + j]:
|
|
265
|
+
x0, y0, x1, y1 = self.boxes[cid][:4]
|
|
266
|
+
if x0 <= px <= x1 and y0 <= py <= y1 and inside_polygon(self.cells[cid], px, py):
|
|
267
|
+
return cid
|
|
268
|
+
return -1
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
# -- the growth --------------------------------------------------------------------------
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
@dataclass
|
|
275
|
+
class Growth:
|
|
276
|
+
"""The ligaments and voids of a scale-rich network (coordinates of the plane)."""
|
|
277
|
+
|
|
278
|
+
nucleation: np.ndarray # (N, 2) the nucleation points
|
|
279
|
+
angle: np.ndarray # (N,) radians, of the centre lines
|
|
280
|
+
thickness: np.ndarray # (N,)
|
|
281
|
+
ends: np.ndarray # (N, 2, 2) the ends of the centre lines
|
|
282
|
+
neighbours: np.ndarray # (N, 2) the ligaments of the ends (BOX: the boundary)
|
|
283
|
+
body_offsets: np.ndarray # (N + 1,) CSR of the vertices of the ligaments
|
|
284
|
+
body_vertices: np.ndarray # (M, 2)
|
|
285
|
+
cell_offsets: np.ndarray # (C + 1,) CSR of the vertices of the voids
|
|
286
|
+
cell_vertices: np.ndarray # (K, 2)
|
|
287
|
+
cell_faces: np.ndarray # (K,) the face of each edge (ligament index or BOX)
|
|
288
|
+
jammed: bool = False
|
|
289
|
+
attempts: int = 0
|
|
290
|
+
|
|
291
|
+
@property
|
|
292
|
+
def n(self) -> int:
|
|
293
|
+
return len(self.thickness)
|
|
294
|
+
|
|
295
|
+
@property
|
|
296
|
+
def n_cells(self) -> int:
|
|
297
|
+
return len(self.cell_offsets) - 1
|
|
298
|
+
|
|
299
|
+
def bodies(self) -> list[np.ndarray]:
|
|
300
|
+
"""The vertices of each ligament (convex polygons, counter-clockwise)."""
|
|
301
|
+
o = self.body_offsets
|
|
302
|
+
return [self.body_vertices[o[i] : o[i + 1]] for i in range(self.n)]
|
|
303
|
+
|
|
304
|
+
def cells(self) -> list[np.ndarray]:
|
|
305
|
+
"""The vertices of each void (convex polygons, counter-clockwise)."""
|
|
306
|
+
o = self.cell_offsets
|
|
307
|
+
return [self.cell_vertices[o[i] : o[i + 1]] for i in range(self.n_cells)]
|
|
308
|
+
|
|
309
|
+
def body_areas(self) -> np.ndarray:
|
|
310
|
+
return np.array([polygon_area(b) for b in self.bodies()])
|
|
311
|
+
|
|
312
|
+
def cell_areas(self) -> np.ndarray:
|
|
313
|
+
return np.array([polygon_area(c) for c in self.cells()])
|
|
314
|
+
|
|
315
|
+
@property
|
|
316
|
+
def lengths(self) -> np.ndarray:
|
|
317
|
+
"""The lengths of the centre lines of the ligaments."""
|
|
318
|
+
return np.linalg.norm(self.ends[:, 1] - self.ends[:, 0], axis=1)
|
|
319
|
+
|
|
320
|
+
def links(self) -> np.ndarray:
|
|
321
|
+
"""The pairs of ligaments joined: each ligament with those on which its ends lie
|
|
322
|
+
(the edges of the dual graph, each once)."""
|
|
323
|
+
i = np.repeat(np.arange(self.n), 2)
|
|
324
|
+
j = self.neighbours.ravel()
|
|
325
|
+
keep = j >= 0
|
|
326
|
+
return np.column_stack([i[keep], j[keep]])
|
|
327
|
+
|
|
328
|
+
def degrees(self) -> np.ndarray:
|
|
329
|
+
"""The number of ligaments each ligament meets (its degree in the dual graph)."""
|
|
330
|
+
e = self.links()
|
|
331
|
+
return np.bincount(e.ravel(), minlength=self.n).astype(np.int64)
|
|
332
|
+
|
|
333
|
+
def orientation_tensor(self) -> np.ndarray:
|
|
334
|
+
"""``M = sum A_t d_t d_t / sum A_t``: the directions ``d_t`` of the ligaments
|
|
335
|
+
weighted by their areas ``A_t`` (Both et al. 2026, eq. 1, normalized)."""
|
|
336
|
+
a = self.body_areas()
|
|
337
|
+
d = np.column_stack([np.cos(self.angle), np.sin(self.angle)])
|
|
338
|
+
if not a.sum() > 0:
|
|
339
|
+
return np.full((2, 2), np.nan)
|
|
340
|
+
return np.einsum("t,ti,tj->ij", a, d, d) / a.sum()
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _csr(items: list[np.ndarray]) -> tuple[np.ndarray, np.ndarray]:
|
|
344
|
+
offsets = np.zeros(len(items) + 1, dtype=np.int64)
|
|
345
|
+
offsets[1:] = np.cumsum([len(a) for a in items])
|
|
346
|
+
data = np.concatenate(items) if items else np.empty((0, 2))
|
|
347
|
+
return offsets, data
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def grow(
|
|
351
|
+
lower,
|
|
352
|
+
upper,
|
|
353
|
+
n_ligaments: int,
|
|
354
|
+
thickness,
|
|
355
|
+
entropy: int,
|
|
356
|
+
*,
|
|
357
|
+
orientation=None,
|
|
358
|
+
density=None,
|
|
359
|
+
min_spacing: float = 0.0,
|
|
360
|
+
max_attempts: int = 1000,
|
|
361
|
+
) -> Growth:
|
|
362
|
+
"""Grow a scale-rich network in the rectangle ``[lower, upper]`` of the plane.
|
|
363
|
+
|
|
364
|
+
``thickness(t)`` is the thickness of the ligament ``t = 1, 2, ...``; ``orientation(t,
|
|
365
|
+
x, y, u, v)`` its angle (radians) at its nucleation point from two uniform numbers
|
|
366
|
+
(default: ``pi u``, uniform); ``density(x, y)`` the relative density of nucleation in
|
|
367
|
+
``[0, 1]`` (default: uniform), by rejection. A nucleation point is drawn uniformly in
|
|
368
|
+
the rectangle until it falls in a void (the law of a void drawn in proportion to its
|
|
369
|
+
area, then a point uniform in it); each ligament draws from its own generator
|
|
370
|
+
(``SeedSequence(entropy, spawn_key=(t,))``): its draws do not depend on the ligaments
|
|
371
|
+
before it, so that a small change of the thicknesses changes the network only where a
|
|
372
|
+
point or an end falls close to a moved side (the relative density of
|
|
373
|
+
:class:`ScaleRichNetwork` is solved on realizations of the same seed). The growth stops,
|
|
374
|
+
jammed, after ``max_attempts`` nucleation points in a row where the ligament does not
|
|
375
|
+
fit, or when the voids vanish.
|
|
376
|
+
"""
|
|
377
|
+
lo = np.asarray(lower, dtype=float).reshape(2)
|
|
378
|
+
hi = np.asarray(upper, dtype=float).reshape(2)
|
|
379
|
+
size = hi - lo
|
|
380
|
+
area = float(np.prod(size))
|
|
381
|
+
tol = 1e-12 * float(np.max(size))
|
|
382
|
+
box = np.array([[lo[0], lo[1]], [hi[0], lo[1]], [hi[0], hi[1]], [lo[0], hi[1]]])
|
|
383
|
+
voids = _Voids(lo, hi, n_buckets=max(1, int(n_ligaments) // 2))
|
|
384
|
+
voids.put(0, box)
|
|
385
|
+
cells_faces = [np.full(4, BOX, dtype=np.int64)]
|
|
386
|
+
void_area = area
|
|
387
|
+
|
|
388
|
+
nucleation, angle, lam, ends, neighbours, bodies = [], [], [], [], [], []
|
|
389
|
+
attempts = 0
|
|
390
|
+
jammed = False
|
|
391
|
+
for t in range(1, int(n_ligaments) + 1):
|
|
392
|
+
width = float(thickness(t))
|
|
393
|
+
half = 0.5 * (width + min_spacing)
|
|
394
|
+
gen = np.random.Generator(np.random.PCG64(np.random.SeedSequence(entropy, spawn_key=(t,))))
|
|
395
|
+
failures = k = 0
|
|
396
|
+
block = gen.random((16, _DRAWS))
|
|
397
|
+
while True:
|
|
398
|
+
if k == len(block):
|
|
399
|
+
if void_area <= 1e-12 * area:
|
|
400
|
+
jammed = True
|
|
401
|
+
break
|
|
402
|
+
block, k = gen.random((256, _DRAWS)), 0
|
|
403
|
+
draw = block[k]
|
|
404
|
+
k += 1
|
|
405
|
+
px, py = lo[0] + draw[0] * size[0], lo[1] + draw[1] * size[1]
|
|
406
|
+
if density is not None and draw[2] >= density(px, py):
|
|
407
|
+
continue
|
|
408
|
+
i = voids.locate(px, py)
|
|
409
|
+
if i < 0:
|
|
410
|
+
continue # in a ligament
|
|
411
|
+
attempts += 1
|
|
412
|
+
if orientation is None:
|
|
413
|
+
theta = math.pi * draw[3]
|
|
414
|
+
else:
|
|
415
|
+
theta = orientation(t, px, py, draw[3], draw[4])
|
|
416
|
+
dx, dy = math.cos(theta), math.sin(theta)
|
|
417
|
+
nx, ny = -dy, dx
|
|
418
|
+
if fits(voids.cells[i], px, py, nx, ny, half):
|
|
419
|
+
break
|
|
420
|
+
failures += 1
|
|
421
|
+
if failures >= max_attempts:
|
|
422
|
+
jammed = True
|
|
423
|
+
break
|
|
424
|
+
if jammed:
|
|
425
|
+
break
|
|
426
|
+
xy, faces = voids.cells[i], cells_faces[i]
|
|
427
|
+
s0, s1, f0, f1 = chord(xy, faces, px, py, dx, dy)
|
|
428
|
+
c = nx * px + ny * py
|
|
429
|
+
label = t - 1
|
|
430
|
+
minus_xy, minus_f = clip_polygon(xy, faces, nx, ny, c - 0.5 * width, label, tol)
|
|
431
|
+
plus_xy, plus_f = clip_polygon(xy, faces, -nx, -ny, -(c + 0.5 * width), label, tol)
|
|
432
|
+
body, body_f = clip_polygon(xy, faces, nx, ny, c + 0.5 * width, label, tol)
|
|
433
|
+
body, _ = clip_polygon(body, body_f, -nx, -ny, -(c - 0.5 * width), label, tol)
|
|
434
|
+
void_area += polygon_area(minus_xy) + polygon_area(plus_xy) - polygon_area(xy)
|
|
435
|
+
voids.put(i, minus_xy)
|
|
436
|
+
cells_faces[i] = minus_f
|
|
437
|
+
voids.put(len(voids.cells), plus_xy)
|
|
438
|
+
cells_faces.append(plus_f)
|
|
439
|
+
nucleation.append((px, py))
|
|
440
|
+
angle.append(math.atan2(dy, dx) % math.pi)
|
|
441
|
+
lam.append(width)
|
|
442
|
+
ends.append(((px + s0 * dx, py + s0 * dy), (px + s1 * dx, py + s1 * dy)))
|
|
443
|
+
neighbours.append((f0, f1))
|
|
444
|
+
bodies.append(body)
|
|
445
|
+
|
|
446
|
+
body_offsets, body_vertices = _csr(bodies)
|
|
447
|
+
cell_offsets, cell_vertices = _csr(voids.cells)
|
|
448
|
+
n = len(lam)
|
|
449
|
+
return Growth(
|
|
450
|
+
nucleation=np.asarray(nucleation, dtype=float).reshape(n, 2),
|
|
451
|
+
angle=np.asarray(angle, dtype=float),
|
|
452
|
+
thickness=np.asarray(lam, dtype=float),
|
|
453
|
+
ends=np.asarray(ends, dtype=float).reshape(n, 2, 2),
|
|
454
|
+
neighbours=np.asarray(neighbours, dtype=np.int64).reshape(n, 2),
|
|
455
|
+
body_offsets=body_offsets,
|
|
456
|
+
body_vertices=body_vertices,
|
|
457
|
+
cell_offsets=cell_offsets,
|
|
458
|
+
cell_vertices=cell_vertices,
|
|
459
|
+
cell_faces=np.concatenate(cells_faces).astype(np.int64),
|
|
460
|
+
jammed=jammed,
|
|
461
|
+
attempts=attempts,
|
|
462
|
+
)
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
# -- theory ------------------------------------------------------------------------------
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def first_length(a: float, b: float) -> float:
|
|
469
|
+
"""The mean length of the first ligament in an ``a x b`` rectangle: the chord through
|
|
470
|
+
a uniform point along a uniform direction, ``int l^2 dG / (pi a b)`` over the lines
|
|
471
|
+
``G``. With ``d = sqrt(a^2 + b^2)``::
|
|
472
|
+
|
|
473
|
+
l_0 = (2 / pi) (a asinh(b / a) + b asinh(a / b) - (a^2 (d - a) + b^2 (d - b)) / (3 a b))
|
|
474
|
+
|
|
475
|
+
0.946402 for the unit square (Kellerer 1971)."""
|
|
476
|
+
a, b = float(a), float(b)
|
|
477
|
+
d = math.hypot(a, b)
|
|
478
|
+
corners = (a * a * (d - a) + b * b * (d - b)) / (3.0 * a * b)
|
|
479
|
+
return (2.0 / math.pi) * (a * math.asinh(b / a) + b * math.asinh(a / b) - corners)
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def length_sum(decay: float, n_ligaments: int, a: float, b: float) -> float:
|
|
483
|
+
"""``sum_t l_t t^-alpha / sqrt(A)`` of a thin network of ``T`` ligaments in an ``a x
|
|
484
|
+
b`` rectangle: ``l_0 / sqrt(A) + c sum_{t=2..T} t^-(alpha + 1/2)``
|
|
485
|
+
(:data:`LENGTH_CONSTANT`), the relative density per unit of ``lambda_0 / sqrt(A)``."""
|
|
486
|
+
area = a * b
|
|
487
|
+
tail = 0.0
|
|
488
|
+
if n_ligaments >= 2:
|
|
489
|
+
t = np.arange(2, int(n_ligaments) + 1, dtype=float)
|
|
490
|
+
tail = float(np.sum(t ** (-(decay + 0.5))))
|
|
491
|
+
return first_length(a, b) / math.sqrt(area) + LENGTH_CONSTANT * tail
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def density_estimate(first_order: float, dimension: int = 2) -> float:
|
|
495
|
+
"""The relative density of a network from its first order ``rho_1 = sum_t lambda_t
|
|
496
|
+
E[l_t] / A`` (thin ligaments): a ligament splits a void of area ``A_v / t`` (``A_v``
|
|
497
|
+
the area of the voids), so that ``dA_v/dt = -lambda_t c sqrt(A_v / t)`` and
|
|
498
|
+
``sqrt(A_v / A) = 1 - rho_1 / 2``: ``rho = rho_1 (1 - rho_1 / 4)``, jammed (1) from
|
|
499
|
+
``rho_1 = 2`` on. In ``d`` dimensions (plates in 3D: ``rho_1 = sum_t lambda_t E[a_t] /
|
|
500
|
+
V``, the area ``a_t`` of a plate about ``c_3 (V_v / t)^(2/3)``), ``(V_v / V)^(1/d) = 1 -
|
|
501
|
+
rho_1 / d``: ``rho = 1 - (1 - rho_1 / d)^d``, jammed from ``rho_1 = d`` on."""
|
|
502
|
+
r, d = float(first_order), int(dimension)
|
|
503
|
+
return 1.0 if r >= d else 1.0 - (1.0 - r / d) ** d
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
# -- the field of the ligaments on points of the plane: a grid of buckets ------------------
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
@njit(cache=True)
|
|
510
|
+
def _half_planes(vertices, offsets):
|
|
511
|
+
"""Outward unit normals ``n`` and offsets ``c`` of the edges of convex polygons
|
|
512
|
+
(counter-clockwise): ``phi(x) = max_e (n_e . x - c_e)``, negative inside."""
|
|
513
|
+
m = vertices.shape[0]
|
|
514
|
+
nx = np.zeros(m)
|
|
515
|
+
ny = np.zeros(m)
|
|
516
|
+
c = np.full(m, np.inf) # degenerate edges: no constraint
|
|
517
|
+
for p in range(offsets.shape[0] - 1):
|
|
518
|
+
a, b = offsets[p], offsets[p + 1]
|
|
519
|
+
k = b - a
|
|
520
|
+
for j in range(k):
|
|
521
|
+
i0, i1 = a + j, a + (j + 1) % k
|
|
522
|
+
ex, ey = vertices[i1, 0] - vertices[i0, 0], vertices[i1, 1] - vertices[i0, 1]
|
|
523
|
+
length = math.hypot(ex, ey)
|
|
524
|
+
if length > 0.0:
|
|
525
|
+
nx[i0], ny[i0] = ey / length, -ex / length
|
|
526
|
+
c[i0] = nx[i0] * vertices[i0, 0] + ny[i0] * vertices[i0, 1]
|
|
527
|
+
return nx, ny, c
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
@njit(cache=True)
|
|
531
|
+
def _register(boxes, reach, lo0, lo1, h0, h1, g0, g1):
|
|
532
|
+
"""The polygons of each bucket of a ``g0 x g1`` grid: those whose box, widened by
|
|
533
|
+
``reach``, meets it (compressed rows)."""
|
|
534
|
+
n = boxes.shape[0]
|
|
535
|
+
counts = np.zeros(g0 * g1, dtype=np.int64)
|
|
536
|
+
for pass_ in range(2):
|
|
537
|
+
if pass_ == 1:
|
|
538
|
+
offsets = np.zeros(g0 * g1 + 1, dtype=np.int64)
|
|
539
|
+
for b in range(g0 * g1):
|
|
540
|
+
offsets[b + 1] = offsets[b] + counts[b]
|
|
541
|
+
items = np.empty(offsets[-1], dtype=np.int64)
|
|
542
|
+
fill = offsets[:-1].copy()
|
|
543
|
+
for p in range(n):
|
|
544
|
+
i0 = min(max(math.floor((boxes[p, 0] - reach - lo0) / h0), 0), g0 - 1)
|
|
545
|
+
i1 = min(max(math.floor((boxes[p, 2] + reach - lo0) / h0), 0), g0 - 1)
|
|
546
|
+
j0 = min(max(math.floor((boxes[p, 1] - reach - lo1) / h1), 0), g1 - 1)
|
|
547
|
+
j1 = min(max(math.floor((boxes[p, 3] + reach - lo1) / h1), 0), g1 - 1)
|
|
548
|
+
for i in range(i0, i1 + 1):
|
|
549
|
+
for j in range(j0, j1 + 1):
|
|
550
|
+
if pass_ == 0:
|
|
551
|
+
counts[i * g1 + j] += 1
|
|
552
|
+
else:
|
|
553
|
+
items[fill[i * g1 + j]] = p
|
|
554
|
+
fill[i * g1 + j] += 1
|
|
555
|
+
return offsets, items
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
@njit(parallel=True, cache=True)
|
|
559
|
+
def _field(px, py, reach, boxes, offsets, nx, ny, c, b_off, b_items, lo0, lo1, h0, h1, g0, g1):
|
|
560
|
+
"""``min(reach, min_p phi_p(x))`` at points of the plane: negative in the ligaments, the
|
|
561
|
+
distance to the nearest one near them (``reach``: far from every one)."""
|
|
562
|
+
out = np.empty(px.shape[0])
|
|
563
|
+
for q in prange(px.shape[0]):
|
|
564
|
+
x, y = px[q], py[q]
|
|
565
|
+
i = min(max(math.floor((x - lo0) / h0), 0), g0 - 1)
|
|
566
|
+
j = min(max(math.floor((y - lo1) / h1), 0), g1 - 1)
|
|
567
|
+
b = i * g1 + j
|
|
568
|
+
best = reach
|
|
569
|
+
for k in range(b_off[b], b_off[b + 1]):
|
|
570
|
+
p = b_items[k]
|
|
571
|
+
if (x < boxes[p, 0] - reach or x > boxes[p, 2] + reach
|
|
572
|
+
or y < boxes[p, 1] - reach or y > boxes[p, 3] + reach): # fmt: skip
|
|
573
|
+
continue
|
|
574
|
+
phi = -np.inf
|
|
575
|
+
for e in range(offsets[p], offsets[p + 1]):
|
|
576
|
+
v = nx[e] * x + ny[e] * y - c[e]
|
|
577
|
+
if v > phi:
|
|
578
|
+
phi = v
|
|
579
|
+
if phi >= best:
|
|
580
|
+
break
|
|
581
|
+
if phi < best:
|
|
582
|
+
best = phi
|
|
583
|
+
out[q] = best
|
|
584
|
+
return out
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
class _Index:
|
|
588
|
+
"""The ligaments of a network registered in a grid of buckets of the plane, to
|
|
589
|
+
evaluate their field (:func:`_field`) within ``reach`` of them."""
|
|
590
|
+
|
|
591
|
+
def __init__(self, growth: Growth, lower, upper, reach: float) -> None:
|
|
592
|
+
self.reach = float(reach)
|
|
593
|
+
v, o = growth.body_vertices, growth.body_offsets
|
|
594
|
+
self.offsets = o
|
|
595
|
+
self.nx, self.ny, self.c = _half_planes(v, o)
|
|
596
|
+
n = growth.n
|
|
597
|
+
boxes = np.empty((n, 4))
|
|
598
|
+
for p in range(n):
|
|
599
|
+
pts = v[o[p] : o[p + 1]]
|
|
600
|
+
boxes[p, :2], boxes[p, 2:] = pts.min(axis=0), pts.max(axis=0)
|
|
601
|
+
self.boxes = boxes
|
|
602
|
+
lo, hi = np.asarray(lower, dtype=float), np.asarray(upper, dtype=float)
|
|
603
|
+
size = hi - lo
|
|
604
|
+
cells = max(1.0, math.sqrt(max(n, 1)))
|
|
605
|
+
g = np.clip(np.ceil(cells * size / math.sqrt(float(np.prod(size)))), 1, 1024)
|
|
606
|
+
self.g = (int(g[0]), int(g[1]))
|
|
607
|
+
self.lo = lo
|
|
608
|
+
self.h = size / g
|
|
609
|
+
self.b_off, self.b_items = _register(
|
|
610
|
+
boxes, self.reach, lo[0], lo[1], self.h[0], self.h[1], *self.g
|
|
611
|
+
)
|
|
612
|
+
|
|
613
|
+
def field(self, points) -> np.ndarray:
|
|
614
|
+
pts = np.ascontiguousarray(np.asarray(points, dtype=float).reshape(-1, 2))
|
|
615
|
+
if not len(self.boxes):
|
|
616
|
+
return np.full(len(pts), self.reach)
|
|
617
|
+
return _field(pts[:, 0].copy(), pts[:, 1].copy(), self.reach, self.boxes, self.offsets,
|
|
618
|
+
self.nx, self.ny, self.c, self.b_off, self.b_items, self.lo[0],
|
|
619
|
+
self.lo[1], self.h[0], self.h[1], *self.g) # fmt: skip
|
|
620
|
+
|
|
621
|
+
|
|
622
|
+
# -- the microstructure ------------------------------------------------------------------
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
def _array(value, shape_tail, dtype=float) -> np.ndarray:
|
|
626
|
+
return np.asarray(value, dtype=dtype).reshape(-1, *shape_tail)
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
@register_kind
|
|
630
|
+
class ScaleRichStructure(Microstructure):
|
|
631
|
+
"""A scale-rich network extruded along ``axis``: its ligaments (phase 1, convex
|
|
632
|
+
polygons of the plane of the two other axes, which never overlap) and its voids
|
|
633
|
+
(phase 0, convex cells), which partition the face of the box exactly
|
|
634
|
+
(:func:`grow`); or, with a ``frame``, the face within a frame of that thickness
|
|
635
|
+
(phase 1 too), on which the ligaments end."""
|
|
636
|
+
|
|
637
|
+
kind = "scale_rich_structure"
|
|
638
|
+
|
|
639
|
+
def __init__(self, domain: Domain, axis: int, growth: Growth, frame: float = 0.0,
|
|
640
|
+
**kwargs) -> None: # fmt: skip
|
|
641
|
+
super().__init__(domain, **kwargs)
|
|
642
|
+
self.axis = int(axis)
|
|
643
|
+
self.growth = growth
|
|
644
|
+
self.frame = float(frame)
|
|
645
|
+
self._indices: dict[float, _Index] = {}
|
|
646
|
+
|
|
647
|
+
# -- the network -------------------------------------------------------------------
|
|
648
|
+
|
|
649
|
+
@property
|
|
650
|
+
def plane(self) -> tuple[np.ndarray, np.ndarray]:
|
|
651
|
+
"""The lower and upper corners of the face of the box in the plane."""
|
|
652
|
+
b, c = plane_axes(self.axis)
|
|
653
|
+
d = self.domain
|
|
654
|
+
return d.lower[[b, c]], d.upper[[b, c]]
|
|
655
|
+
|
|
656
|
+
@property
|
|
657
|
+
def area(self) -> float:
|
|
658
|
+
lo, hi = self.plane
|
|
659
|
+
return float(np.prod(hi - lo))
|
|
660
|
+
|
|
661
|
+
@property
|
|
662
|
+
def n_ligaments(self) -> int:
|
|
663
|
+
return self.growth.n
|
|
664
|
+
|
|
665
|
+
@property
|
|
666
|
+
def thicknesses(self) -> np.ndarray:
|
|
667
|
+
return self.growth.thickness
|
|
668
|
+
|
|
669
|
+
@property
|
|
670
|
+
def lengths(self) -> np.ndarray:
|
|
671
|
+
"""The lengths of the centre lines of the ligaments in their voids."""
|
|
672
|
+
return self.growth.lengths
|
|
673
|
+
|
|
674
|
+
def degrees(self) -> np.ndarray:
|
|
675
|
+
"""The degree of each ligament in the dual graph: the ligaments it meets."""
|
|
676
|
+
return self.growth.degrees()
|
|
677
|
+
|
|
678
|
+
def links(self) -> np.ndarray:
|
|
679
|
+
"""The pairs of ligaments that meet (an end of the first on the second)."""
|
|
680
|
+
return self.growth.links()
|
|
681
|
+
|
|
682
|
+
@property
|
|
683
|
+
def volume_fraction(self) -> float:
|
|
684
|
+
"""The fraction of the face in the ligaments and the frame, exact (``1 - sum(void
|
|
685
|
+
areas) / A``)."""
|
|
686
|
+
return float(1.0 - self.growth.cell_areas().sum() / self.area)
|
|
687
|
+
|
|
688
|
+
def orientation_tensor(self) -> np.ndarray:
|
|
689
|
+
"""The orientation tensor of the ligaments (2 x 2, trace 1, axes of the plane)."""
|
|
690
|
+
return self.growth.orientation_tensor()
|
|
691
|
+
|
|
692
|
+
@property
|
|
693
|
+
def geometric_anisotropy(self) -> float:
|
|
694
|
+
"""``mu_1 / mu_2``, the ratio of the eigenvalues of the orientation tensor: 1 for
|
|
695
|
+
ligaments of isotropic directions, 0 when they are all parallel (Both et al.
|
|
696
|
+
2026)."""
|
|
697
|
+
mu = np.linalg.eigvalsh(self.orientation_tensor())
|
|
698
|
+
return float(mu[0] / mu[1]) if mu[1] > 0 else math.nan
|
|
699
|
+
|
|
700
|
+
def statistics(self, min_tail: int = 50) -> dict:
|
|
701
|
+
"""The power-law tails of the thicknesses, lengths and degrees of the ligaments
|
|
702
|
+
(:func:`morphogen.analysis.power_laws.power_law_tail`, degrees as integers): Both
|
|
703
|
+
et al. find ``1 + 1/alpha``, 3 and 3 for their exponents. No thicknesses with a
|
|
704
|
+
decay of 0 (one thickness)."""
|
|
705
|
+
from morphogen.analysis.power_laws import power_law_tail
|
|
706
|
+
|
|
707
|
+
tail = min(int(min_tail), max(2, self.n_ligaments // 2))
|
|
708
|
+
out = {}
|
|
709
|
+
if np.ptp(self.thicknesses) > 0: # a decay of 0: one thickness, no tail
|
|
710
|
+
out["thickness"] = power_law_tail(self.thicknesses, min_tail=tail)
|
|
711
|
+
out["length"] = power_law_tail(self.lengths, min_tail=tail)
|
|
712
|
+
out["degree"] = power_law_tail(self.degrees(), discrete=True, min_tail=tail)
|
|
713
|
+
return out
|
|
714
|
+
|
|
715
|
+
def convex_pieces(self) -> tuple[list[tuple], np.ndarray, np.ndarray]:
|
|
716
|
+
"""The convex pieces that partition the box: the ligaments (phase 1, cells 1 to N)
|
|
717
|
+
and the voids (phase 0, cell 0) extruded along the axis into prisms, and the frame
|
|
718
|
+
(phase 1, cell N + 1), for the exact meshes of
|
|
719
|
+
:func:`morphogen.mesh.exact.polyhedral_mesh`."""
|
|
720
|
+
from morphogen.models.scale_rich_3d import prism
|
|
721
|
+
|
|
722
|
+
g = self.growth
|
|
723
|
+
axes = plane_axes(self.axis)
|
|
724
|
+
z0, z1 = float(self.domain.lower[self.axis]), float(self.domain.upper[self.axis])
|
|
725
|
+
pieces, phase, cells = [], [], []
|
|
726
|
+
for t, body in enumerate(g.bodies()):
|
|
727
|
+
if len(body) >= 3 and polygon_area(body) > 0:
|
|
728
|
+
pieces.append(prism(body, axes, self.axis, z0, z1))
|
|
729
|
+
phase.append(1)
|
|
730
|
+
cells.append(t + 1)
|
|
731
|
+
for cell in g.cells():
|
|
732
|
+
if len(cell) >= 3 and polygon_area(cell) > 0:
|
|
733
|
+
pieces.append(prism(cell, axes, self.axis, z0, z1))
|
|
734
|
+
phase.append(0)
|
|
735
|
+
cells.append(0)
|
|
736
|
+
if self.frame > 0:
|
|
737
|
+
(u0, v0), (u1, v1) = self.plane
|
|
738
|
+
f = self.frame
|
|
739
|
+
for (a0, b0), (a1, b1) in (((u0, v0), (u0 + f, v1)), ((u1 - f, v0), (u1, v1)),
|
|
740
|
+
((u0 + f, v0), (u1 - f, v0 + f)),
|
|
741
|
+
((u0 + f, v1 - f), (u1 - f, v1))): # fmt: skip
|
|
742
|
+
rect = [(a0, b0), (a1, b0), (a1, b1), (a0, b1)]
|
|
743
|
+
pieces.append(prism(rect, axes, self.axis, z0, z1))
|
|
744
|
+
phase.append(1)
|
|
745
|
+
cells.append(g.n + 1)
|
|
746
|
+
return pieces, np.asarray(phase, dtype=np.int64), np.asarray(cells, dtype=np.int64)
|
|
747
|
+
|
|
748
|
+
# -- the phases on points and voxels -------------------------------------------------
|
|
749
|
+
|
|
750
|
+
def _index(self, reach: float) -> _Index:
|
|
751
|
+
key = round(float(reach), 12)
|
|
752
|
+
if key not in self._indices:
|
|
753
|
+
lo, hi = self.plane
|
|
754
|
+
self._indices.clear()
|
|
755
|
+
self._indices[key] = _Index(self.growth, lo, hi, reach)
|
|
756
|
+
return self._indices[key]
|
|
757
|
+
|
|
758
|
+
def plane_field(self, points, reach: float = 0.0) -> np.ndarray:
|
|
759
|
+
"""At points of the plane: ``max_e (n_e . x - c_e)`` of the ligament holding them
|
|
760
|
+
(negative: the distance to its nearest side, or less), or the least such value of
|
|
761
|
+
the ligaments within ``reach`` (the distance to the nearest one, or less), capped at
|
|
762
|
+
``reach``; with a frame, the least of this and the signed distance to the inner
|
|
763
|
+
side of the frame."""
|
|
764
|
+
out = self._index(reach).field(points)
|
|
765
|
+
if self.frame > 0:
|
|
766
|
+
pts = np.asarray(points, dtype=float).reshape(-1, 2)
|
|
767
|
+
lo, hi = self.plane
|
|
768
|
+
inner = np.minimum(pts - lo, hi - pts).min(axis=1)
|
|
769
|
+
out = np.minimum(out, inner - self.frame)
|
|
770
|
+
return out
|
|
771
|
+
|
|
772
|
+
def contains(self, points) -> np.ndarray:
|
|
773
|
+
pts = np.asarray(points, dtype=float).reshape(-1, 3)
|
|
774
|
+
b, c = plane_axes(self.axis)
|
|
775
|
+
out = self.plane_field(pts[:, [b, c]]) < 0
|
|
776
|
+
return out & np.all((pts >= self.domain.lower) & (pts <= self.domain.upper), axis=1)
|
|
777
|
+
|
|
778
|
+
def level_set_at(self, points, reach: float = np.inf) -> np.ndarray:
|
|
779
|
+
""":meth:`plane_field` of the points within ``reach`` (default: the diagonal of the
|
|
780
|
+
box), the network extruded along the axis."""
|
|
781
|
+
if not np.isfinite(reach):
|
|
782
|
+
reach = float(self.domain.diagonal)
|
|
783
|
+
pts = np.asarray(points, dtype=float).reshape(-1, 3)
|
|
784
|
+
b, c = plane_axes(self.axis)
|
|
785
|
+
return self.plane_field(pts[:, [b, c]], float(reach))
|
|
786
|
+
|
|
787
|
+
def _image(self, grid: Grid, reach: float) -> np.ndarray:
|
|
788
|
+
plane, shape = pixel_centres(grid, plane_axes(self.axis))
|
|
789
|
+
return self.plane_field(plane, reach).astype(np.float32).reshape(shape)
|
|
790
|
+
|
|
791
|
+
def _extruded(self, image2d: np.ndarray, grid: Grid) -> np.ndarray:
|
|
792
|
+
out = np.broadcast_to(image2d[:, :, None], (*image2d.shape, grid.shape[self.axis]))
|
|
793
|
+
return np.ascontiguousarray(np.moveaxis(out, 2, self.axis))
|
|
794
|
+
|
|
795
|
+
def voxelize(self, shape=None, *, voxel_size=None, grid: Grid | None = None, supersampling=1):
|
|
796
|
+
grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
|
|
797
|
+
ss = int(supersampling)
|
|
798
|
+
if ss == 1:
|
|
799
|
+
data = self._extruded((self._image(grid, 0.0) < 0).astype(np.uint8), grid)
|
|
800
|
+
return VoxelImage.from_grid(data, grid, name="phase", metadata=self.image_metadata())
|
|
801
|
+
if not 1 <= ss <= 6:
|
|
802
|
+
raise ValueError("supersampling must be an integer between 1 and 6")
|
|
803
|
+
b, c = plane_axes(self.axis)
|
|
804
|
+
fine_shape = list(grid.shape)
|
|
805
|
+
fine_shape[b] *= ss
|
|
806
|
+
fine_shape[c] *= ss
|
|
807
|
+
fine = Grid(grid.domain, tuple(fine_shape))
|
|
808
|
+
inside = (self._image(fine, 0.0) < 0).astype(np.float32)
|
|
809
|
+
nb, nc = grid.shape[b], grid.shape[c]
|
|
810
|
+
coarse = inside.reshape(nb, ss, nc, ss).mean(axis=(1, 3), dtype=np.float32)
|
|
811
|
+
data = self._extruded(coarse, grid)
|
|
812
|
+
return VoxelImage.from_grid(data, grid, name="fraction", metadata=self.image_metadata())
|
|
813
|
+
|
|
814
|
+
def level_set(self, shape=None, *, voxel_size=None, grid: Grid | None = None) -> VoxelImage:
|
|
815
|
+
"""Negative in the ligaments, positive in the voids: the distance to the sides of
|
|
816
|
+
the ligaments near them (a lower bound near their corners), within the largest
|
|
817
|
+
half thickness and four voxels of them."""
|
|
818
|
+
grid = self.grid(shape, voxel_size=voxel_size, grid=grid)
|
|
819
|
+
thick = float(self.thicknesses.max()) if self.n_ligaments else 0.0
|
|
820
|
+
reach = 0.5 * thick + 4.0 * float(np.max(grid.spacing))
|
|
821
|
+
data = self._extruded(self._image(grid, reach), grid)
|
|
822
|
+
return VoxelImage.from_grid(data, grid, name="level_set", metadata=self.image_metadata())
|
|
823
|
+
|
|
824
|
+
# -- description --------------------------------------------------------------------
|
|
825
|
+
|
|
826
|
+
def summary(self) -> dict:
|
|
827
|
+
"""The counts, thicknesses, lengths, degrees and anisotropy of the network (the
|
|
828
|
+
columns of the tables of results)."""
|
|
829
|
+
g = self.growth
|
|
830
|
+
out = {"ligaments": g.n, "jammed": int(g.jammed), "volume_fraction": self.volume_fraction}
|
|
831
|
+
if g.n:
|
|
832
|
+
deg = g.degrees()
|
|
833
|
+
out.update(
|
|
834
|
+
{
|
|
835
|
+
"initial_thickness": float(g.thickness[0]),
|
|
836
|
+
"final_thickness": float(g.thickness[-1]),
|
|
837
|
+
"mean_length": float(g.lengths.mean()),
|
|
838
|
+
"mean_degree": float(deg.mean()),
|
|
839
|
+
"max_degree": int(deg.max()),
|
|
840
|
+
"geometric_anisotropy": self.geometric_anisotropy,
|
|
841
|
+
}
|
|
842
|
+
)
|
|
843
|
+
return out
|
|
844
|
+
|
|
845
|
+
def _geometry(self) -> dict:
|
|
846
|
+
g = self.growth
|
|
847
|
+
return {
|
|
848
|
+
"axis": self.axis,
|
|
849
|
+
"nucleation": g.nucleation.tolist(),
|
|
850
|
+
"angle": g.angle.tolist(),
|
|
851
|
+
"thickness": g.thickness.tolist(),
|
|
852
|
+
"ends": g.ends.tolist(),
|
|
853
|
+
"neighbours": g.neighbours.tolist(),
|
|
854
|
+
"bodies": {"offsets": g.body_offsets.tolist(), "vertices": g.body_vertices.tolist()},
|
|
855
|
+
"cells": {
|
|
856
|
+
"offsets": g.cell_offsets.tolist(),
|
|
857
|
+
"vertices": g.cell_vertices.tolist(),
|
|
858
|
+
"faces": g.cell_faces.tolist(),
|
|
859
|
+
},
|
|
860
|
+
"jammed": bool(g.jammed),
|
|
861
|
+
"attempts": int(g.attempts),
|
|
862
|
+
"frame": self.frame,
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
@classmethod
|
|
866
|
+
def _from_geometry(cls, domain, geometry, **kwargs):
|
|
867
|
+
bodies, cells = geometry["bodies"], geometry["cells"]
|
|
868
|
+
growth = Growth(
|
|
869
|
+
nucleation=_array(geometry["nucleation"], (2,)),
|
|
870
|
+
angle=np.asarray(geometry["angle"], dtype=float).reshape(-1),
|
|
871
|
+
thickness=np.asarray(geometry["thickness"], dtype=float).reshape(-1),
|
|
872
|
+
ends=_array(geometry["ends"], (2, 2)),
|
|
873
|
+
neighbours=_array(geometry["neighbours"], (2,), np.int64),
|
|
874
|
+
body_offsets=np.asarray(bodies["offsets"], dtype=np.int64),
|
|
875
|
+
body_vertices=_array(bodies["vertices"], (2,)),
|
|
876
|
+
cell_offsets=np.asarray(cells["offsets"], dtype=np.int64),
|
|
877
|
+
cell_vertices=_array(cells["vertices"], (2,)),
|
|
878
|
+
cell_faces=np.asarray(cells["faces"], dtype=np.int64),
|
|
879
|
+
jammed=bool(geometry.get("jammed", False)),
|
|
880
|
+
attempts=int(geometry.get("attempts", 0)),
|
|
881
|
+
)
|
|
882
|
+
return cls(domain, geometry["axis"], growth, geometry.get("frame", 0.0), **kwargs)
|
|
883
|
+
|
|
884
|
+
|
|
885
|
+
# -- the model ---------------------------------------------------------------------------
|
|
886
|
+
|
|
887
|
+
|
|
888
|
+
@register
|
|
889
|
+
@dataclass(frozen=True)
|
|
890
|
+
class ScaleRichNetwork(Model):
|
|
891
|
+
"""Scale-rich network (Both et al. 2026): ligaments ``lambda_0 t^-alpha`` thick grown
|
|
892
|
+
one after another from points of the voids until they meet: by default (``dimension:
|
|
893
|
+
2``) in the plane of the axes other than ``axis`` and extruded along it (see
|
|
894
|
+
:mod:`morphogen.models.scale_rich`); with ``dimension: 3``, plates or beams in the box
|
|
895
|
+
(see :mod:`morphogen.models.scale_rich_3d`). The initial thickness is given, or solved on
|
|
896
|
+
each realization for a relative density (``volume_fraction``). Orientations uniform,
|
|
897
|
+
among ``angles`` (2D) or drawn from a law (3D), or polarized by a ``pole``; a gradient
|
|
898
|
+
of the nucleation density. Non-periodic: the ligaments end on the boundary of the box
|
|
899
|
+
(or on a frame)."""
|
|
900
|
+
|
|
901
|
+
name = "scale_rich_network"
|
|
902
|
+
phases: ClassVar[dict[int, str]] = {0: "voids", 1: "ligaments"}
|
|
903
|
+
supports_periodic: ClassVar[bool] = False
|
|
904
|
+
count_label = "ligaments"
|
|
905
|
+
|
|
906
|
+
n_ligaments: int = param(500, doc="Number of ligaments T, plates or beams in 3D (fewer if "
|
|
907
|
+
"the network jams)", kind="int") # fmt: skip
|
|
908
|
+
dimension: int = param(
|
|
909
|
+
2, doc="2: a network of the plane extruded along axis (prisms); 3: plates or beams "
|
|
910
|
+
"in the box", kind="int",
|
|
911
|
+
) # fmt: skip
|
|
912
|
+
element: str = param(
|
|
913
|
+
"plates", doc="The ligaments in 3D: plates (closed cells) or beams (open cells, "
|
|
914
|
+
"struts)", kind="str",
|
|
915
|
+
) # fmt: skip
|
|
916
|
+
decay: float = param(0.5, doc="Exponent alpha of the thicknesses lambda_0 t^-alpha")
|
|
917
|
+
initial_thickness: float | None = param(
|
|
918
|
+
None, doc="Thickness lambda_0 of the first ligament (the diameter of a beam)",
|
|
919
|
+
unit="length",
|
|
920
|
+
) # fmt: skip
|
|
921
|
+
volume_fraction: float | None = param(
|
|
922
|
+
None, doc="Relative density, reached on each realization (solves lambda_0)",
|
|
923
|
+
kind="fraction",
|
|
924
|
+
) # fmt: skip
|
|
925
|
+
min_spacing: float = param(
|
|
926
|
+
0.0, doc="Least width epsilon of the voids beside a new ligament, at its nucleation "
|
|
927
|
+
"point", unit="length",
|
|
928
|
+
) # fmt: skip
|
|
929
|
+
angles: tuple[float, ...] | None = param(
|
|
930
|
+
None, doc="In 2D: angles of the ligaments in the plane, drawn among these (degrees; "
|
|
931
|
+
"default: uniform)", kind="floats", unit="deg",
|
|
932
|
+
) # fmt: skip
|
|
933
|
+
orientation: OrientationDistribution | None = param(
|
|
934
|
+
None, doc="In 3D: law of the normals of the plates or of the axes of the beams "
|
|
935
|
+
"(default: isotropic)", kind="orientation",
|
|
936
|
+
) # fmt: skip
|
|
937
|
+
angle_spread: float = param(
|
|
938
|
+
0.0, doc="Standard deviation of the angles (3D: of the tilt of the directions) about "
|
|
939
|
+
"those given or polarized", unit="deg",
|
|
940
|
+
) # fmt: skip
|
|
941
|
+
pole: tuple[float, ...] | None = param(
|
|
942
|
+
None, doc="Point polarizing the ligaments (two coordinates of the plane in 2D, three "
|
|
943
|
+
"in 3D): they make pole_angle with the direction of the pole", kind="floats",
|
|
944
|
+
unit="length",
|
|
945
|
+
) # fmt: skip
|
|
946
|
+
pole_angle: float = param(
|
|
947
|
+
0.0, doc="Angle of the polarized ligaments to the direction of the pole (0: radial, "
|
|
948
|
+
"90: tangential; 3D: plates through it or on spheres about it, beams along it or "
|
|
949
|
+
"around it, at a uniform azimuth)", unit="deg",
|
|
950
|
+
) # fmt: skip
|
|
951
|
+
polarized_fraction: float = param(
|
|
952
|
+
1.0, doc="Fraction of the ligaments, the first ones, polarized by the pole",
|
|
953
|
+
kind="fraction",
|
|
954
|
+
) # fmt: skip
|
|
955
|
+
nucleation_gradient: tuple[float, ...] | None = param(
|
|
956
|
+
None, doc="Relative nucleation densities at the lower and upper faces along "
|
|
957
|
+
"gradient_axis (at the pole and the farthest corner with radial_gradient)",
|
|
958
|
+
kind="floats",
|
|
959
|
+
) # fmt: skip
|
|
960
|
+
gradient_axis: int | None = param(
|
|
961
|
+
None, doc="Axis of the gradient of nucleation (in 2D, of the plane; default: the "
|
|
962
|
+
"first axis of the plane, x in 3D)", kind="int",
|
|
963
|
+
) # fmt: skip
|
|
964
|
+
radial_gradient: bool = param(
|
|
965
|
+
False, doc="The gradient of nucleation away from the pole", kind="bool"
|
|
966
|
+
)
|
|
967
|
+
frame: float = param(
|
|
968
|
+
0.0, doc="Thickness of a frame of material around the network, on which its "
|
|
969
|
+
"ligaments end (0: none): the sample as the cell of a periodic medium", unit="length",
|
|
970
|
+
) # fmt: skip
|
|
971
|
+
axis: int = param(2, doc="In 2D: axis of the prisms (0: x, 1: y, 2: z)", kind="int")
|
|
972
|
+
max_attempts: int = param(
|
|
973
|
+
1000, doc="Draws in a row that do not fit, after which the network is jammed",
|
|
974
|
+
kind="int",
|
|
975
|
+
) # fmt: skip
|
|
976
|
+
|
|
977
|
+
def _validate(self) -> None:
|
|
978
|
+
if self.n_ligaments < 1:
|
|
979
|
+
raise ValueError("n_ligaments: at least one ligament")
|
|
980
|
+
if self.dimension not in (2, 3):
|
|
981
|
+
raise ValueError("dimension: 2 (a planar network extruded) or 3")
|
|
982
|
+
if self.element not in ("plates", "beams"):
|
|
983
|
+
raise ValueError("element: plates or beams")
|
|
984
|
+
if self.dimension == 2 and self.element != "plates":
|
|
985
|
+
raise ValueError("element: beams in 3D only (dimension: 3); the ligaments of a "
|
|
986
|
+
"planar network are extruded into plates") # fmt: skip
|
|
987
|
+
check_positive(self.decay, "decay", allow_zero=True)
|
|
988
|
+
check_positive(self.frame, "frame", allow_zero=True)
|
|
989
|
+
exactly_one("initial_thickness", self.initial_thickness,
|
|
990
|
+
"volume_fraction", self.volume_fraction) # fmt: skip
|
|
991
|
+
if self.initial_thickness is not None:
|
|
992
|
+
check_positive(self.initial_thickness, "initial_thickness")
|
|
993
|
+
if self.volume_fraction is not None:
|
|
994
|
+
check_fraction(self.volume_fraction, "volume_fraction")
|
|
995
|
+
check_positive(self.min_spacing, "min_spacing", allow_zero=True)
|
|
996
|
+
if self.angles is not None:
|
|
997
|
+
if self.dimension == 3:
|
|
998
|
+
raise ValueError("angles: in 2D only; in 3D, an orientation law")
|
|
999
|
+
if not self.angles or not all(math.isfinite(a) for a in self.angles):
|
|
1000
|
+
raise ValueError("angles: a list of finite angles in degrees")
|
|
1001
|
+
if self.orientation is not None and self.dimension == 2:
|
|
1002
|
+
raise ValueError("orientation: in 3D only; in 2D, angles")
|
|
1003
|
+
check_positive(self.angle_spread, "angle_spread", allow_zero=True)
|
|
1004
|
+
if self.pole is not None:
|
|
1005
|
+
d = self.dimension
|
|
1006
|
+
if len(self.pole) != d or not all(math.isfinite(v) for v in self.pole):
|
|
1007
|
+
where = "of the plane" if d == 2 else "of space"
|
|
1008
|
+
raise ValueError(f"pole: the {d} coordinates of a point {where}")
|
|
1009
|
+
if not math.isfinite(self.pole_angle):
|
|
1010
|
+
raise ValueError("pole_angle: a finite angle in degrees")
|
|
1011
|
+
if not 0.0 <= self.polarized_fraction <= 1.0:
|
|
1012
|
+
raise ValueError("polarized_fraction: from 0 to 1")
|
|
1013
|
+
if self.polarized_fraction < 1.0 and self.pole is None:
|
|
1014
|
+
raise ValueError("polarized_fraction: the fraction polarized by a pole")
|
|
1015
|
+
if self.axis not in (0, 1, 2):
|
|
1016
|
+
raise ValueError("axis: 0, 1 or 2")
|
|
1017
|
+
if self.gradient_axis is not None:
|
|
1018
|
+
axes = plane_axes(self.axis) if self.dimension == 2 else (0, 1, 2)
|
|
1019
|
+
if self.gradient_axis not in axes:
|
|
1020
|
+
where = "of the plane" if self.dimension == 2 else "of space"
|
|
1021
|
+
raise ValueError(f"gradient_axis: an axis {where}, {tuple(axes)}")
|
|
1022
|
+
if self.nucleation_gradient is not None:
|
|
1023
|
+
w = self.nucleation_gradient
|
|
1024
|
+
if len(w) != 2 or not all(math.isfinite(v) and v >= 0 for v in w) or max(w) <= 0:
|
|
1025
|
+
raise ValueError("nucleation_gradient: two non-negative densities, not both 0")
|
|
1026
|
+
if self.radial_gradient and (self.pole is None or self.nucleation_gradient is None):
|
|
1027
|
+
raise ValueError("radial_gradient: a pole and a nucleation_gradient")
|
|
1028
|
+
if self.max_attempts < 1:
|
|
1029
|
+
raise ValueError("max_attempts: at least 1")
|
|
1030
|
+
|
|
1031
|
+
@property
|
|
1032
|
+
def isotropic(self) -> bool:
|
|
1033
|
+
"""Uniform orientations and nucleation: the laws of :meth:`theory` hold."""
|
|
1034
|
+
return (self.angles is None and self.orientation is None and self.pole is None
|
|
1035
|
+
and self.nucleation_gradient is None) # fmt: skip
|
|
1036
|
+
|
|
1037
|
+
@property
|
|
1038
|
+
def plates(self) -> bool:
|
|
1039
|
+
"""Plates in 3D (closed cells), or the extruded ligaments of a planar network."""
|
|
1040
|
+
return self.element == "plates"
|
|
1041
|
+
|
|
1042
|
+
# -- the growth -----------------------------------------------------------------------
|
|
1043
|
+
|
|
1044
|
+
def _orientation(self):
|
|
1045
|
+
"""The angles of the ligaments of a planar network (:func:`grow`)."""
|
|
1046
|
+
if self.angles is None and self.pole is None:
|
|
1047
|
+
return None
|
|
1048
|
+
spread = math.radians(self.angle_spread)
|
|
1049
|
+
angles = None if self.angles is None else [math.radians(a) for a in self.angles]
|
|
1050
|
+
polar = 0 if self.pole is None else math.ceil(self.polarized_fraction * self.n_ligaments)
|
|
1051
|
+
turn = math.radians(self.pole_angle)
|
|
1052
|
+
pole = self.pole
|
|
1053
|
+
normal = NormalDist()
|
|
1054
|
+
|
|
1055
|
+
def orientation(t, x, y, u, v):
|
|
1056
|
+
if t <= polar:
|
|
1057
|
+
base = math.atan2(pole[1] - y, pole[0] - x) + turn
|
|
1058
|
+
elif angles is not None:
|
|
1059
|
+
base = angles[min(int(u * len(angles)), len(angles) - 1)]
|
|
1060
|
+
else:
|
|
1061
|
+
return math.pi * u
|
|
1062
|
+
if spread > 0.0:
|
|
1063
|
+
base += spread * normal.inv_cdf(min(max(v, 1e-16), 1.0 - 1e-16))
|
|
1064
|
+
return base
|
|
1065
|
+
|
|
1066
|
+
return orientation
|
|
1067
|
+
|
|
1068
|
+
def _directions(self):
|
|
1069
|
+
"""The normals of the plates or the axes of the beams in 3D (:func:`grow_plates`):
|
|
1070
|
+
polarized by the pole, at the angle ``beta`` (``pole_angle``) to its direction
|
|
1071
|
+
``r`` and a uniform azimuth (plates: ``n . r = sin beta``, beams: ``d . r = cos
|
|
1072
|
+
beta``), drawn from the orientation law or uniform; tilted by a normal law of
|
|
1073
|
+
``angle_spread``."""
|
|
1074
|
+
if self.orientation is None and self.pole is None:
|
|
1075
|
+
return None
|
|
1076
|
+
spread = math.radians(self.angle_spread)
|
|
1077
|
+
law = self.orientation
|
|
1078
|
+
polar = 0 if self.pole is None else math.ceil(self.polarized_fraction * self.n_ligaments)
|
|
1079
|
+
beta = math.radians(self.pole_angle)
|
|
1080
|
+
# the share of the direction of the pole in the normal of a plate, the axis of a beam
|
|
1081
|
+
along, side = math.cos(beta), math.sin(beta)
|
|
1082
|
+
if self.plates:
|
|
1083
|
+
along, side = side, along
|
|
1084
|
+
pole = None if self.pole is None else np.asarray(self.pole, dtype=float)
|
|
1085
|
+
|
|
1086
|
+
def directions(t, points, gen):
|
|
1087
|
+
k = len(points)
|
|
1088
|
+
if t <= polar:
|
|
1089
|
+
r = pole - points
|
|
1090
|
+
norm = np.linalg.norm(r, axis=1, keepdims=True)
|
|
1091
|
+
r = np.where(norm > 0, r / np.where(norm > 0, norm, 1.0), (0.0, 0.0, 1.0))
|
|
1092
|
+
e1, e2 = orthonormal_basis(r)
|
|
1093
|
+
psi = 2.0 * np.pi * gen.random(k)[:, None]
|
|
1094
|
+
d = along * r + side * (np.cos(psi) * e1 + np.sin(psi) * e2)
|
|
1095
|
+
elif law is not None:
|
|
1096
|
+
d = np.asarray(law.sample(gen, k), dtype=float).reshape(k, 3)
|
|
1097
|
+
else:
|
|
1098
|
+
d = uniform_unit_vectors(gen, k)
|
|
1099
|
+
if spread > 0.0:
|
|
1100
|
+
e1, e2 = orthonormal_basis(d)
|
|
1101
|
+
g = spread * gen.standard_normal((k, 2))
|
|
1102
|
+
tilt = np.hypot(g[:, 0], g[:, 1])[:, None]
|
|
1103
|
+
way = (g[:, :1] * e1 + g[:, 1:] * e2) / np.where(tilt > 0, tilt, 1.0)
|
|
1104
|
+
d = np.cos(tilt) * d + np.sin(tilt) * way
|
|
1105
|
+
return d / np.linalg.norm(d, axis=1, keepdims=True)
|
|
1106
|
+
|
|
1107
|
+
return directions
|
|
1108
|
+
|
|
1109
|
+
def _density(self, lower, upper):
|
|
1110
|
+
"""The relative density of nucleation at a point (2 or 3 coordinates)."""
|
|
1111
|
+
if self.nucleation_gradient is None:
|
|
1112
|
+
return None
|
|
1113
|
+
w0, w1 = (float(w) for w in self.nucleation_gradient)
|
|
1114
|
+
top = max(w0, w1)
|
|
1115
|
+
lower = [float(v) for v in lower]
|
|
1116
|
+
upper = [float(v) for v in upper]
|
|
1117
|
+
if self.radial_gradient:
|
|
1118
|
+
pole = [float(v) for v in self.pole]
|
|
1119
|
+
corners = itertools.product(*zip(lower, upper, strict=True))
|
|
1120
|
+
far = max(math.dist(c, pole) for c in corners)
|
|
1121
|
+
|
|
1122
|
+
def density(*x):
|
|
1123
|
+
s = min(math.dist(x, pole) / far, 1.0) if far > 0 else 0.0
|
|
1124
|
+
return (w0 + (w1 - w0) * s) / top
|
|
1125
|
+
|
|
1126
|
+
return density
|
|
1127
|
+
if self.dimension == 2:
|
|
1128
|
+
axes = plane_axes(self.axis)
|
|
1129
|
+
k = axes.index(axes[0] if self.gradient_axis is None else self.gradient_axis)
|
|
1130
|
+
else:
|
|
1131
|
+
k = 0 if self.gradient_axis is None else int(self.gradient_axis)
|
|
1132
|
+
lo, span = lower[k], upper[k] - lower[k]
|
|
1133
|
+
|
|
1134
|
+
def density(*x):
|
|
1135
|
+
s = (x[k] - lo) / span
|
|
1136
|
+
return (w0 + (w1 - w0) * s) / top
|
|
1137
|
+
|
|
1138
|
+
return density
|
|
1139
|
+
|
|
1140
|
+
def _grow(self, lower, upper, thickness: float, entropy: int):
|
|
1141
|
+
decay = float(self.decay)
|
|
1142
|
+
|
|
1143
|
+
def law(t):
|
|
1144
|
+
return thickness * t ** (-decay)
|
|
1145
|
+
|
|
1146
|
+
common = {
|
|
1147
|
+
"density": self._density(lower, upper),
|
|
1148
|
+
"min_spacing": float(self.min_spacing),
|
|
1149
|
+
"max_attempts": int(self.max_attempts),
|
|
1150
|
+
}
|
|
1151
|
+
if self.dimension == 2:
|
|
1152
|
+
return grow(lower, upper, self.n_ligaments, law, entropy,
|
|
1153
|
+
orientation=self._orientation(), **common) # fmt: skip
|
|
1154
|
+
grow3 = grow_plates if self.plates else grow_beams
|
|
1155
|
+
return grow3(lower, upper, self.n_ligaments, law, entropy,
|
|
1156
|
+
directions=self._directions(), **common) # fmt: skip
|
|
1157
|
+
|
|
1158
|
+
def _region(self, domain: Domain) -> tuple[np.ndarray, np.ndarray]:
|
|
1159
|
+
"""The corners of the region of the network within the frame: the face of the box
|
|
1160
|
+
in the plane (2D), or the box."""
|
|
1161
|
+
if self.dimension == 2:
|
|
1162
|
+
b, c = plane_axes(self.axis)
|
|
1163
|
+
lower, upper = domain.lower[[b, c]], domain.upper[[b, c]]
|
|
1164
|
+
else:
|
|
1165
|
+
lower, upper = domain.lower, domain.upper
|
|
1166
|
+
lower, upper = lower + self.frame, upper - self.frame
|
|
1167
|
+
if not np.all(upper > lower):
|
|
1168
|
+
raise ValueError("frame: thinner than half the sides of the box")
|
|
1169
|
+
return lower, upper
|
|
1170
|
+
|
|
1171
|
+
def _sides(self, domain: Domain) -> tuple[float, ...]:
|
|
1172
|
+
"""The sides of the region of the network (within the frame)."""
|
|
1173
|
+
lower, upper = self._region(domain)
|
|
1174
|
+
return tuple(float(v) for v in upper - lower)
|
|
1175
|
+
|
|
1176
|
+
def _total(self, domain: Domain) -> float:
|
|
1177
|
+
"""The area of the face of the box (2D), or its volume."""
|
|
1178
|
+
if self.dimension == 2:
|
|
1179
|
+
b, c = plane_axes(self.axis)
|
|
1180
|
+
return float(domain.lengths[b] * domain.lengths[c])
|
|
1181
|
+
return float(domain.volume)
|
|
1182
|
+
|
|
1183
|
+
def _relative_density(self, growth, domain: Domain) -> float:
|
|
1184
|
+
total = self._total(domain)
|
|
1185
|
+
if self.dimension == 2:
|
|
1186
|
+
return float(1.0 - growth.cell_areas().sum() / total)
|
|
1187
|
+
if self.plates:
|
|
1188
|
+
return float(1.0 - growth.cell_volumes().sum() / total)
|
|
1189
|
+
return ScaleRichBeams(domain, growth, frame=self.frame).volume_fraction
|
|
1190
|
+
|
|
1191
|
+
def thickness_estimate(self, domain: Domain) -> float:
|
|
1192
|
+
"""The initial thickness of the ``volume_fraction`` by the theory (uniform
|
|
1193
|
+
orientations and nucleation), ``rho`` the density of the network within the frame
|
|
1194
|
+
(of area ``A``, volume ``V``): in 2D, ``lambda_0 = 2 sqrt(A) (1 - sqrt(1 - rho)) /
|
|
1195
|
+
S`` (:func:`density_estimate`, :func:`length_sum`); with plates, ``lambda_0 = 3
|
|
1196
|
+
V^(1/3) (1 - (1 - rho)^(1/3)) / S`` (:func:`area_sum`); with beams, the mean field
|
|
1197
|
+
of :func:`beam_density_estimate`."""
|
|
1198
|
+
if self.volume_fraction is None:
|
|
1199
|
+
return float(self.initial_thickness)
|
|
1200
|
+
sides = self._sides(domain)
|
|
1201
|
+
inner = float(np.prod(sides))
|
|
1202
|
+
rho = 1.0 - (1.0 - self.volume_fraction) * self._total(domain) / inner
|
|
1203
|
+
if rho <= 0:
|
|
1204
|
+
raise ValueError("volume_fraction: below the fraction of the frame alone")
|
|
1205
|
+
if self.dimension == 2:
|
|
1206
|
+
s = length_sum(self.decay, self.n_ligaments, *sides)
|
|
1207
|
+
return 2.0 * math.sqrt(inner) * (1.0 - math.sqrt(1.0 - rho)) / s
|
|
1208
|
+
if self.plates:
|
|
1209
|
+
s = area_sum(self.decay, self.n_ligaments, *sides)
|
|
1210
|
+
return 3.0 * inner ** (1.0 / 3.0) * (1.0 - (1.0 - rho) ** (1.0 / 3.0)) / s
|
|
1211
|
+
return beam_thickness_estimate(rho, self.decay, self.n_ligaments, sides)
|
|
1212
|
+
|
|
1213
|
+
def _solve(self, entropy: int, domain: Domain):
|
|
1214
|
+
"""The initial thickness of the realization of ``entropy`` at the relative density:
|
|
1215
|
+
regula falsi (Illinois) from the estimate of the theory, to :data:`DENSITY_TOL`. The
|
|
1216
|
+
draws of each ligament do not depend on the thicknesses (:func:`grow`), but a
|
|
1217
|
+
nucleation point or an end close to a moved side may change the network from it on:
|
|
1218
|
+
the density may jump where the tolerance is not met, and the side of the jump
|
|
1219
|
+
closer to the target is kept."""
|
|
1220
|
+
target = float(self.volume_fraction)
|
|
1221
|
+
lower, upper = self._region(domain)
|
|
1222
|
+
size = float(np.max(domain.lengths))
|
|
1223
|
+
runs: dict[float, tuple] = {}
|
|
1224
|
+
|
|
1225
|
+
def excess(lam: float) -> float:
|
|
1226
|
+
if lam not in runs:
|
|
1227
|
+
g = self._grow(lower, upper, lam, entropy)
|
|
1228
|
+
runs[lam] = (self._relative_density(g, domain) - target, g)
|
|
1229
|
+
return runs[lam][0]
|
|
1230
|
+
|
|
1231
|
+
guess = self.thickness_estimate(domain)
|
|
1232
|
+
a, b = 0.9 * guess, 1.1 * guess
|
|
1233
|
+
while excess(a) > 0:
|
|
1234
|
+
a *= 0.7
|
|
1235
|
+
while excess(b) < 0:
|
|
1236
|
+
if runs[b][1].jammed or b > size:
|
|
1237
|
+
raise ValueError(
|
|
1238
|
+
f"volume_fraction: {target} is beyond the network, which jams at about "
|
|
1239
|
+
f"{excess(b) + target:.3f} (fewer ligaments, a smaller decay or no "
|
|
1240
|
+
"min_spacing)"
|
|
1241
|
+
)
|
|
1242
|
+
a, b = b, 1.4 * b
|
|
1243
|
+
fa, fb = excess(a), excess(b)
|
|
1244
|
+
side = 0
|
|
1245
|
+
for _ in range(60):
|
|
1246
|
+
if min(abs(excess(a)), abs(excess(b))) <= DENSITY_TOL or b - a <= 1e-9 * guess:
|
|
1247
|
+
break
|
|
1248
|
+
c = (a * fb - b * fa) / (fb - fa)
|
|
1249
|
+
if not a < c < b:
|
|
1250
|
+
c = 0.5 * (a + b)
|
|
1251
|
+
fc = excess(c)
|
|
1252
|
+
if fc > 0:
|
|
1253
|
+
b, fb = c, fc
|
|
1254
|
+
if side == 1:
|
|
1255
|
+
fa *= 0.5 # Illinois: the stale end weighs less
|
|
1256
|
+
side = 1
|
|
1257
|
+
else:
|
|
1258
|
+
a, fa = c, fc
|
|
1259
|
+
if side == -1:
|
|
1260
|
+
fb *= 0.5
|
|
1261
|
+
side = -1
|
|
1262
|
+
lam = min((a, b), key=lambda x: abs(excess(x)))
|
|
1263
|
+
return float(lam), runs[lam][1]
|
|
1264
|
+
|
|
1265
|
+
def generate(self, domain: Domain, seed: SeedLike = None) -> Microstructure:
|
|
1266
|
+
self._check_domain(domain)
|
|
1267
|
+
rng, seed_info = make_rng(seed)
|
|
1268
|
+
entropy = int(rng.integers(0, 2**63))
|
|
1269
|
+
if self.initial_thickness is not None:
|
|
1270
|
+
lam0 = float(self.initial_thickness)
|
|
1271
|
+
growth = self._grow(*self._region(domain), lam0, entropy)
|
|
1272
|
+
else:
|
|
1273
|
+
lam0, growth = self._solve(entropy, domain)
|
|
1274
|
+
if self.dimension == 2:
|
|
1275
|
+
micro = ScaleRichStructure(domain, self.axis, growth, frame=self.frame, model=self,
|
|
1276
|
+
seed=seed_info) # fmt: skip
|
|
1277
|
+
micro.metadata["summary"] = self._summary(micro, lam0)
|
|
1278
|
+
return micro
|
|
1279
|
+
kind = ScaleRichPlates if self.plates else ScaleRichBeams
|
|
1280
|
+
micro = kind(domain, growth, frame=self.frame, model=self, seed=seed_info)
|
|
1281
|
+
micro.metadata["summary"] = self._summary_3d(micro, lam0)
|
|
1282
|
+
return micro
|
|
1283
|
+
|
|
1284
|
+
@staticmethod
|
|
1285
|
+
def _summary(micro: ScaleRichStructure, lam0: float) -> dict:
|
|
1286
|
+
g = micro.growth
|
|
1287
|
+
out = {
|
|
1288
|
+
"ligaments": g.n,
|
|
1289
|
+
"jammed": int(g.jammed),
|
|
1290
|
+
"attempts": g.attempts,
|
|
1291
|
+
"initial_thickness": lam0,
|
|
1292
|
+
"volume_fraction": micro.volume_fraction,
|
|
1293
|
+
"voids": g.n_cells,
|
|
1294
|
+
"boundary_ends": int(np.count_nonzero(g.neighbours == BOX)),
|
|
1295
|
+
}
|
|
1296
|
+
if not g.n:
|
|
1297
|
+
return out
|
|
1298
|
+
lengths, degrees = g.lengths, g.degrees()
|
|
1299
|
+
mu, vectors = np.linalg.eigh(g.orientation_tensor())
|
|
1300
|
+
main = vectors[:, 1] # the direction of the larger eigenvalue
|
|
1301
|
+
out.update(
|
|
1302
|
+
{
|
|
1303
|
+
"final_thickness": float(g.thickness[-1]),
|
|
1304
|
+
"mean_length": float(lengths.mean()),
|
|
1305
|
+
"max_length": float(lengths.max()),
|
|
1306
|
+
"mean_degree": float(degrees.mean()),
|
|
1307
|
+
"max_degree": int(degrees.max()),
|
|
1308
|
+
"geometric_anisotropy": float(mu[0] / mu[1]),
|
|
1309
|
+
"principal_angle": float(math.degrees(math.atan2(main[1], main[0])) % 180.0),
|
|
1310
|
+
}
|
|
1311
|
+
)
|
|
1312
|
+
return out
|
|
1313
|
+
|
|
1314
|
+
@staticmethod
|
|
1315
|
+
def _summary_3d(micro, lam0: float) -> dict:
|
|
1316
|
+
g = micro.growth
|
|
1317
|
+
plates = isinstance(micro, ScaleRichPlates)
|
|
1318
|
+
out = {
|
|
1319
|
+
"ligaments": g.n,
|
|
1320
|
+
"jammed": int(g.jammed),
|
|
1321
|
+
"attempts": g.attempts,
|
|
1322
|
+
"initial_thickness": lam0,
|
|
1323
|
+
"volume_fraction": micro.volume_fraction,
|
|
1324
|
+
}
|
|
1325
|
+
if plates:
|
|
1326
|
+
out["voids"] = g.n_cells
|
|
1327
|
+
out["boundary_plates"] = int(np.count_nonzero(g.boundary_contacts()))
|
|
1328
|
+
else:
|
|
1329
|
+
out["boundary_ends"] = int(np.count_nonzero(g.neighbours == BOX))
|
|
1330
|
+
if not g.n:
|
|
1331
|
+
return out
|
|
1332
|
+
sizes = g.areas if plates else g.lengths
|
|
1333
|
+
degrees = g.degrees()
|
|
1334
|
+
mu = np.linalg.eigvalsh(g.orientation_tensor())
|
|
1335
|
+
name = "area" if plates else "length"
|
|
1336
|
+
out.update(
|
|
1337
|
+
{
|
|
1338
|
+
"final_thickness": float(g.thickness[-1]),
|
|
1339
|
+
f"mean_{name}": float(sizes.mean()),
|
|
1340
|
+
f"max_{name}": float(sizes.max()),
|
|
1341
|
+
"mean_degree": float(degrees.mean()),
|
|
1342
|
+
"max_degree": int(degrees.max()),
|
|
1343
|
+
"geometric_anisotropy": float(mu[0] / mu[2]),
|
|
1344
|
+
}
|
|
1345
|
+
)
|
|
1346
|
+
return out
|
|
1347
|
+
|
|
1348
|
+
# -- theory ------------------------------------------------------------------------
|
|
1349
|
+
|
|
1350
|
+
def expected_count(self, domain: Domain) -> float:
|
|
1351
|
+
return float(self.n_ligaments)
|
|
1352
|
+
|
|
1353
|
+
def theory(self, domain: Domain | None = None) -> dict[str, float]:
|
|
1354
|
+
"""The exponent ``1 + 1/alpha`` of the law of the thicknesses (exact, ``alpha >
|
|
1355
|
+
0``), and the asymptotic exponents of the tails of the sizes and degrees: 3 for
|
|
1356
|
+
the lengths and degrees of a planar network (Both et al. 2026), 5/2 for the areas
|
|
1357
|
+
and degrees of plates (``(2d - 1) / (d - 1)`` in ``d`` dimensions). With the
|
|
1358
|
+
domain, for uniform orientations and nucleation: in 2D, the mean length of the
|
|
1359
|
+
first ligament (:func:`first_length`, exact), the first order ``rho_1 = lambda_0
|
|
1360
|
+
S / sqrt(A)`` of the relative density (:func:`length_sum`), its mean-field
|
|
1361
|
+
estimate ``rho_1 (1 - rho_1 / 4)`` (:func:`density_estimate`), the initial
|
|
1362
|
+
thickness at which ``T`` ligaments jam (``rho_1 = 2``) and, for ``alpha > 1/2``,
|
|
1363
|
+
at which an endless growth jams (``S`` with ``zeta(alpha + 1/2)``: the boundary
|
|
1364
|
+
of the phase diagram of the paper); with plates, the mean area of the first plate
|
|
1365
|
+
(:func:`first_area`, exact), ``rho_1 = lambda_0 S / V^(1/3)`` (:func:`area_sum`),
|
|
1366
|
+
``1 - (1 - rho_1 / 3)^3``, jammed at ``rho_1 = 3``, endless for ``alpha > 1/3``
|
|
1367
|
+
(``zeta(alpha + 2/3)``); with beams, the mean-field estimate of
|
|
1368
|
+
:func:`beam_density_estimate`. With a ``volume_fraction``, the initial thickness
|
|
1369
|
+
that the theory gives it. With a frame, the network fills the region within it,
|
|
1370
|
+
and the relative densities count the frame."""
|
|
1371
|
+
out: dict[str, float] = {}
|
|
1372
|
+
if self.decay > 0:
|
|
1373
|
+
out["thickness_exponent"] = 1.0 + 1.0 / self.decay
|
|
1374
|
+
if self.dimension == 2:
|
|
1375
|
+
out.update({"length_exponent": 3.0, "degree_exponent": 3.0})
|
|
1376
|
+
elif self.plates:
|
|
1377
|
+
out.update({"area_exponent": 2.5, "degree_exponent": 2.5})
|
|
1378
|
+
if domain is None or not self.isotropic:
|
|
1379
|
+
return out
|
|
1380
|
+
sides = self._sides(domain)
|
|
1381
|
+
inner = float(np.prod(sides)) / self._total(domain) # the share within the frame
|
|
1382
|
+
lam0 = self.thickness_estimate(domain)
|
|
1383
|
+
if self.volume_fraction is not None:
|
|
1384
|
+
out["initial_thickness"] = lam0
|
|
1385
|
+
if self.dimension == 3 and not self.plates:
|
|
1386
|
+
rho = beam_density_estimate(lam0, self.decay, self.n_ligaments, sides)
|
|
1387
|
+
out["volume_fraction"] = 1.0 - inner + inner * rho
|
|
1388
|
+
return out
|
|
1389
|
+
d = self.dimension
|
|
1390
|
+
root = float(np.prod(sides)) ** (1.0 / d) # sqrt(A) or V^(1/3)
|
|
1391
|
+
if d == 2:
|
|
1392
|
+
s = length_sum(self.decay, self.n_ligaments, *sides)
|
|
1393
|
+
out["first_length"] = first_length(*sides)
|
|
1394
|
+
first, constant, shift = out["first_length"] / root, LENGTH_CONSTANT, 0.5
|
|
1395
|
+
else:
|
|
1396
|
+
s = area_sum(self.decay, self.n_ligaments, *sides)
|
|
1397
|
+
out["first_area"] = first_area(*sides)
|
|
1398
|
+
first, constant, shift = out["first_area"] / root**2, AREA_CONSTANT, 1.0 - 1.0 / d
|
|
1399
|
+
out["jamming_thickness"] = d * root / s
|
|
1400
|
+
if self.decay > 1.0 - shift:
|
|
1401
|
+
from scipy.special import zeta
|
|
1402
|
+
|
|
1403
|
+
endless = first + constant * (zeta(self.decay + shift) - 1.0)
|
|
1404
|
+
out["endless_jamming_thickness"] = float(d * root / endless)
|
|
1405
|
+
rho1 = lam0 * s / root
|
|
1406
|
+
out["volume_fraction_first_order"] = 1.0 - inner + inner * rho1
|
|
1407
|
+
if rho1 < d:
|
|
1408
|
+
out["volume_fraction"] = 1.0 - inner + inner * density_estimate(rho1, d)
|
|
1409
|
+
return out
|