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,696 @@
|
|
|
1
|
+
"""Sections of microstructures computed in their planes, without their 3D images.
|
|
2
|
+
|
|
3
|
+
A section normal to ``axis`` is sampled on the pixel centres of a plane: those of the
|
|
4
|
+
voxel grid of the domain whose cells have the edge ``h = max(L_u, L_v) / resolution``
|
|
5
|
+
(``L_u``, ``L_v``: the edges of the plane), ``rint(L_a / h)`` cells along each edge
|
|
6
|
+
(:func:`volume_grid`), at the cells of index ``min(floor(fraction n), n - 1)`` along the
|
|
7
|
+
axis (:func:`plane_index`: the cells containing ``lower + fraction L``, the middle ones for
|
|
8
|
+
``fraction = 1/2`` as in :func:`morphogen.viz.png.slice_of`; ``fraction`` 0 and 1 give the
|
|
9
|
+
first and the last cells, inside the domain). The structure is evaluated on a grid one
|
|
10
|
+
cell thick (:func:`plane_grid`) whose cell centres are those of that slice, bit for bit:
|
|
11
|
+
a section is the slice of the voxel image at the same resolution, at the cost of ``n^2``
|
|
12
|
+
values instead of ``n^3`` (up to 2048 x 2048 pixels and more).
|
|
13
|
+
|
|
14
|
+
Every 2D array is displayed like :func:`morphogen.viz.png.slice_of`: the first remaining
|
|
15
|
+
axis horizontal, the second vertical, rows from the top (``np.flipud(s.T)`` of the slice
|
|
16
|
+
``s[u, v]``).
|
|
17
|
+
|
|
18
|
+
How the structures are sampled (:attr:`Section.sampling`):
|
|
19
|
+
|
|
20
|
+
* ``plane``: unions of spheres and segments (Boolean and hard-core spheres, fibres, strut
|
|
21
|
+
and random lattices, foams, trees), TPMS, tessellations, Gaussian fields, lattice
|
|
22
|
+
fields (automata, growth, reconstructions, tile assemblies; the cells themselves when
|
|
23
|
+
the grid is their lattice), laminates, honeycombs, nacre, Bouligand plywoods, level-set
|
|
24
|
+
foams, osteons, fractal sponges and scale-rich networks: they only evaluate the points
|
|
25
|
+
of the grid they are given. So are the combinations of such structures, Cox spheres in
|
|
26
|
+
such aggregates, and the coatings and shells of unions of spheres and segments (exact
|
|
27
|
+
distances);
|
|
28
|
+
* ``plane`` too for dead leaves and transparent dead leaves, on a cell as thick as the box
|
|
29
|
+
along the axis (centred on the plane): their kernels wrap the leaves over the grid, a
|
|
30
|
+
periodic grid being the whole box;
|
|
31
|
+
* ``volume``: the slice of the voxel image at the resolution, for the coatings and shells
|
|
32
|
+
computed through the distance transform of the voxels of their structure (any
|
|
33
|
+
structure but unions of spheres and segments), and the combinations, Cox spheres and
|
|
34
|
+
coatings of such structures or of periodic dead leaves; ``coarse`` beyond
|
|
35
|
+
:data:`MAX_VOLUME` voxels: the slice of a coarser voxel image, enlarged (phases and
|
|
36
|
+
labels of the coarse voxels containing the pixel centres, level set interpolated
|
|
37
|
+
linearly).
|
|
38
|
+
|
|
39
|
+
The level set ``phi`` (negative in phase 1) gives the anti-aliased fraction of phase 1 in
|
|
40
|
+
each pixel (:func:`pixel_coverage`). A straight interface passing at the signed distance
|
|
41
|
+
``d = phi / |grad phi|`` from the centre of a pixel of edges ``(h_u, h_v)`` leaves the
|
|
42
|
+
whole pixel in phase 1 for ``d <= -w/2`` and none of it for ``d >= w/2``, ``w = h_u |n_u| +
|
|
43
|
+
h_v |n_v|`` being the width of the pixel across the interface (``n``: its normal); in
|
|
44
|
+
between, linearly (exact for interfaces along the axes),
|
|
45
|
+
|
|
46
|
+
::
|
|
47
|
+
|
|
48
|
+
coverage = clip(1/2 - d / w, 0, 1) = clip(1/2 - phi / (|D_u phi| + |D_v phi|), 0, 1)
|
|
49
|
+
|
|
50
|
+
with ``D_a phi = h_a dphi/da`` estimated by the larger of the one-sided differences of the
|
|
51
|
+
level set with the two neighbours along ``a``: independent of the scale of the level set
|
|
52
|
+
(Gaussian fields, concentrations), and finite at its extrema (features thinner than a
|
|
53
|
+
pixel keep a partial coverage).
|
|
54
|
+
|
|
55
|
+
The structures of several phases (dead leaves of several families, osteons, coatings,
|
|
56
|
+
inclusions, tessellations whose cells have phases) have one implicit function per phase
|
|
57
|
+
(:meth:`~morphogen.models.base.Microstructure.phase_level_set`), each negative in its
|
|
58
|
+
phase: the sections sampled on their plane keep the fraction of each phase in each pixel
|
|
59
|
+
(:func:`phase_coverages`: the coverage of each function, scaled so that they sum to one),
|
|
60
|
+
and their images blend the colours of the phases by them.
|
|
61
|
+
|
|
62
|
+
:func:`level_set_measures` measures the volume fraction and the specific surface of
|
|
63
|
+
phase 1 from the 3D level set at a modest resolution (the smoothed Heaviside and the
|
|
64
|
+
marching cubes of its zero level set).
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
from __future__ import annotations
|
|
68
|
+
|
|
69
|
+
import math
|
|
70
|
+
from dataclasses import dataclass
|
|
71
|
+
|
|
72
|
+
import numpy as np
|
|
73
|
+
|
|
74
|
+
from morphogen.domain import Domain, Grid
|
|
75
|
+
from morphogen.models.bouligand import BouligandStructure
|
|
76
|
+
from morphogen.models.combination import Combined
|
|
77
|
+
from morphogen.models.deadleaves import DeadLeaves
|
|
78
|
+
from morphogen.models.gaussian import GaussianField
|
|
79
|
+
from morphogen.models.honeycomb import PrismaticCells
|
|
80
|
+
from morphogen.models.laminate import Laminate
|
|
81
|
+
from morphogen.models.lattice_field import LatticeField
|
|
82
|
+
from morphogen.models.levelset_foam import DistanceFieldFoam
|
|
83
|
+
from morphogen.models.nacre import NacreStructure
|
|
84
|
+
from morphogen.models.nested import ClusteredSpheres, CoatedStructure, FractalStructure
|
|
85
|
+
from morphogen.models.osteons import OsteonStructure
|
|
86
|
+
from morphogen.models.planar import plane_axes
|
|
87
|
+
from morphogen.models.scale_rich import ScaleRichStructure
|
|
88
|
+
from morphogen.models.scale_rich_3d import ScaleRichBeams, ScaleRichPlates
|
|
89
|
+
from morphogen.models.tessellation import Tessellation
|
|
90
|
+
from morphogen.models.tpms import TPMSStructure
|
|
91
|
+
from morphogen.models.transparent import TransparentDeadLeaves
|
|
92
|
+
from morphogen.models.union import PrimitiveUnion
|
|
93
|
+
from morphogen.viz.png import PALETTE, label_colors
|
|
94
|
+
|
|
95
|
+
__all__ = [
|
|
96
|
+
"CONTOUR",
|
|
97
|
+
"MAX_PHASES",
|
|
98
|
+
"MAX_VOLUME",
|
|
99
|
+
"Section",
|
|
100
|
+
"has_level_set",
|
|
101
|
+
"is_planar",
|
|
102
|
+
"level_set_measures",
|
|
103
|
+
"phase_coverages",
|
|
104
|
+
"pixel_coverage",
|
|
105
|
+
"plane_grid",
|
|
106
|
+
"plane_index",
|
|
107
|
+
"render",
|
|
108
|
+
"section",
|
|
109
|
+
"sections",
|
|
110
|
+
"volume_grid",
|
|
111
|
+
]
|
|
112
|
+
|
|
113
|
+
#: Largest voxel image (in voxels) of the structures that cannot be sampled on a plane;
|
|
114
|
+
#: beyond, their sections are those of a coarser image, enlarged.
|
|
115
|
+
MAX_VOLUME = 256**3
|
|
116
|
+
#: Most phases whose implicit functions the sections evaluate (one function per phase);
|
|
117
|
+
#: beyond, the pixels take the plain colour of the phase of their centre.
|
|
118
|
+
MAX_PHASES = 8
|
|
119
|
+
#: Colour of the contours.
|
|
120
|
+
CONTOUR = np.array([20.0, 20.0, 20.0])
|
|
121
|
+
_AXES = "xyz"
|
|
122
|
+
|
|
123
|
+
#: Structures whose methods only evaluate the points of the grid they are given (point
|
|
124
|
+
#: queries, or kernels of the cell centres of any grid).
|
|
125
|
+
_POINTWISE = (
|
|
126
|
+
PrimitiveUnion,
|
|
127
|
+
TPMSStructure,
|
|
128
|
+
Tessellation,
|
|
129
|
+
GaussianField,
|
|
130
|
+
LatticeField,
|
|
131
|
+
Laminate,
|
|
132
|
+
PrismaticCells,
|
|
133
|
+
BouligandStructure,
|
|
134
|
+
NacreStructure,
|
|
135
|
+
DistanceFieldFoam,
|
|
136
|
+
OsteonStructure,
|
|
137
|
+
FractalStructure,
|
|
138
|
+
ScaleRichStructure,
|
|
139
|
+
ScaleRichPlates,
|
|
140
|
+
ScaleRichBeams,
|
|
141
|
+
)
|
|
142
|
+
#: Structures whose kernels wrap over the grid (sampled on a cell as thick as the box).
|
|
143
|
+
_LEAVES = (DeadLeaves, TransparentDeadLeaves)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
# -- grids ------------------------------------------------------------------------------------
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _axis(axis) -> int:
|
|
150
|
+
if isinstance(axis, bool) or not isinstance(axis, (int, np.integer)) or not 0 <= axis <= 2:
|
|
151
|
+
raise ValueError(f"axis: 0, 1 or 2 (the normal x, y or z), got {axis!r}")
|
|
152
|
+
return int(axis)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _fraction(fraction) -> float:
|
|
156
|
+
try:
|
|
157
|
+
f = float(fraction)
|
|
158
|
+
except (TypeError, ValueError):
|
|
159
|
+
f = math.nan
|
|
160
|
+
if isinstance(fraction, (bool, str)) or not 0.0 <= f <= 1.0:
|
|
161
|
+
raise ValueError(f"fraction: between 0 and 1, got {fraction!r}")
|
|
162
|
+
return f
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _resolution(resolution) -> int:
|
|
166
|
+
try:
|
|
167
|
+
n = int(resolution)
|
|
168
|
+
except (TypeError, ValueError):
|
|
169
|
+
n = 0
|
|
170
|
+
if isinstance(resolution, (bool, str)) or n != resolution or n < 1:
|
|
171
|
+
raise ValueError(f"resolution: a positive integer, got {resolution!r}")
|
|
172
|
+
return n
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def volume_grid(domain: Domain, axis: int = 2, resolution: int = 512) -> Grid:
|
|
176
|
+
"""The voxel grid of ``domain`` whose slices normal to ``axis`` are its sections at
|
|
177
|
+
``resolution``: cells of edge about ``h = max(L_u, L_v) / resolution`` (``L_u``,
|
|
178
|
+
``L_v``: the edges of the plane), ``max(1, rint(L_a / h))`` along each axis, square in
|
|
179
|
+
the plane up to the rounding of its edges to whole pixels."""
|
|
180
|
+
axis, resolution = _axis(axis), _resolution(resolution)
|
|
181
|
+
u, v = plane_axes(axis)
|
|
182
|
+
lengths = domain.lengths
|
|
183
|
+
h = max(lengths[u], lengths[v]) / resolution
|
|
184
|
+
n = np.maximum(1, np.rint(lengths / h)).astype(int)
|
|
185
|
+
return Grid(domain, tuple(int(k) for k in n))
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def plane_index(domain: Domain, axis: int = 2, fraction: float = 0.5, resolution: int = 512) -> int:
|
|
189
|
+
"""Index along ``axis`` of the cells of :func:`volume_grid` holding the section: those
|
|
190
|
+
containing ``lower + fraction L``, ``min(floor(fraction n), n - 1)`` (``n // 2`` for a
|
|
191
|
+
half)."""
|
|
192
|
+
n = volume_grid(domain, axis, resolution).shape[_axis(axis)]
|
|
193
|
+
return min(math.floor(_fraction(fraction) * n), n - 1)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _slab(grid: Grid, axis: int, index: int, thickness: float | None = None) -> Grid:
|
|
197
|
+
"""The cells ``index`` of ``grid`` along ``axis`` as a grid one cell thick: the same
|
|
198
|
+
cells in the plane, of the thickness of the cells (or ``thickness``), centred on the
|
|
199
|
+
coordinate of their centres in ``grid`` bit for bit (``lower + 0.5 t`` computes to it)."""
|
|
200
|
+
centre = float(grid.centers(axis)[index])
|
|
201
|
+
t = float(grid.spacing[axis]) if thickness is None else float(thickness)
|
|
202
|
+
half = 0.5 * t
|
|
203
|
+
lower = centre - half
|
|
204
|
+
for _ in range(8):
|
|
205
|
+
got = lower + half
|
|
206
|
+
if got == centre:
|
|
207
|
+
break
|
|
208
|
+
lower = math.nextafter(lower, math.inf if got < centre else -math.inf)
|
|
209
|
+
d = grid.domain
|
|
210
|
+
origin, size, shape = list(d.origin), list(d.size), list(grid.shape)
|
|
211
|
+
origin[axis], size[axis], shape[axis] = lower, t, 1
|
|
212
|
+
return Grid(Domain(size=size, origin=origin, periodic=d.periodic, unit=d.unit), tuple(shape))
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def plane_grid(domain: Domain, axis: int = 2, fraction: float = 0.5, resolution: int = 512) -> Grid:
|
|
216
|
+
"""A grid one cell thick of the plane normal to ``axis`` at ``fraction`` of the domain
|
|
217
|
+
(0 to 1 from ``domain.lower``): the cells of :func:`volume_grid` (``resolution``
|
|
218
|
+
pixels along the longest edge of the plane, square pixels) of index
|
|
219
|
+
:func:`plane_index` along the axis, whose centres lie exactly on the plane."""
|
|
220
|
+
grid = volume_grid(domain, axis, resolution)
|
|
221
|
+
return _slab(grid, _axis(axis), plane_index(domain, axis, fraction, resolution))
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
# -- sections ---------------------------------------------------------------------------------
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
@dataclass
|
|
228
|
+
class Section:
|
|
229
|
+
"""A section of a microstructure normal to ``axis``, its 2D arrays displayed like
|
|
230
|
+
:func:`morphogen.viz.png.slice_of` (first in-plane axis horizontal, rows from the top).
|
|
231
|
+
|
|
232
|
+
Attributes
|
|
233
|
+
----------
|
|
234
|
+
axis, fraction
|
|
235
|
+
Normal of the plane and the position asked for (0 to 1 from the lower face).
|
|
236
|
+
phase
|
|
237
|
+
Phase at each pixel centre (uint8).
|
|
238
|
+
level_set
|
|
239
|
+
Level set at the pixel centres, negative in phase 1 (float32; None for the
|
|
240
|
+
structures without one).
|
|
241
|
+
coverage
|
|
242
|
+
Anti-aliased fraction of phase 1 in each pixel, from the level set (float32 in
|
|
243
|
+
[0, 1], :func:`pixel_coverage`; None without a level set).
|
|
244
|
+
labels
|
|
245
|
+
Cell or grain labels (int32) of the structures that have them, else None.
|
|
246
|
+
pixel
|
|
247
|
+
Pixel size (the larger of its two edges).
|
|
248
|
+
extent
|
|
249
|
+
In-plane bounds ``(h0, h1, v0, v1)``: horizontal, then vertical.
|
|
250
|
+
names
|
|
251
|
+
Names of the horizontal and vertical axes, e.g. ``("x", "y")``.
|
|
252
|
+
position
|
|
253
|
+
Coordinate of the plane along the axis (the centre of its cells).
|
|
254
|
+
index
|
|
255
|
+
Index of the plane in the voxel grid of the same pixels (:func:`volume_grid`).
|
|
256
|
+
sampling
|
|
257
|
+
``plane`` (evaluated on the plane), ``volume`` (slice of the voxel image) or
|
|
258
|
+
``coarse`` (slice of a coarser voxel image, enlarged).
|
|
259
|
+
coverages
|
|
260
|
+
For the structures of several phases sampled on the plane: the anti-aliased
|
|
261
|
+
fraction of each phase in each pixel, from the implicit function of each phase
|
|
262
|
+
(float32 in [0, 1], by phase, :func:`phase_coverages`); None otherwise.
|
|
263
|
+
"""
|
|
264
|
+
|
|
265
|
+
axis: int
|
|
266
|
+
fraction: float
|
|
267
|
+
phase: np.ndarray
|
|
268
|
+
level_set: np.ndarray | None
|
|
269
|
+
coverage: np.ndarray | None
|
|
270
|
+
labels: np.ndarray | None
|
|
271
|
+
pixel: float
|
|
272
|
+
extent: tuple[float, float, float, float]
|
|
273
|
+
names: tuple[str, str]
|
|
274
|
+
position: float = math.nan
|
|
275
|
+
index: int = 0
|
|
276
|
+
sampling: str = "plane"
|
|
277
|
+
coverages: dict[int, np.ndarray] | None = None
|
|
278
|
+
|
|
279
|
+
@property
|
|
280
|
+
def shape(self) -> tuple[int, int]:
|
|
281
|
+
"""Rows and columns of the arrays."""
|
|
282
|
+
return tuple(int(n) for n in self.phase.shape)
|
|
283
|
+
|
|
284
|
+
@property
|
|
285
|
+
def title(self) -> str:
|
|
286
|
+
"""Name of the plane, e.g. ``"x-y"``."""
|
|
287
|
+
return f"{self.names[0]}-{self.names[1]}"
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def has_level_set(micro) -> bool:
|
|
291
|
+
"""Whether the phase 1 of ``micro`` is described by a level set (two phases, the model
|
|
292
|
+
saying so; structures without a model are tried)."""
|
|
293
|
+
model = getattr(micro, "model", None)
|
|
294
|
+
return True if model is None else bool(getattr(model, "has_level_set", True))
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def is_planar(micro, resolution: int = 512) -> bool:
|
|
298
|
+
"""Whether the sections of ``micro`` reduce to the x-y one: one cell along z at this
|
|
299
|
+
resolution, or a lattice of one cell along z (2D structures, extruded)."""
|
|
300
|
+
if isinstance(micro, LatticeField) and micro.shape[2] == 1:
|
|
301
|
+
return True
|
|
302
|
+
return volume_grid(micro.domain, 2, resolution).shape[2] == 1
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _pointwise(micro) -> bool:
|
|
306
|
+
"""Whether the methods of ``micro`` evaluate exactly the points of any grid (a slab
|
|
307
|
+
of the voxel grid) they are given."""
|
|
308
|
+
if isinstance(micro, _LEAVES):
|
|
309
|
+
return not micro.domain.periodic # their kernels wrap the leaves over the grid
|
|
310
|
+
if isinstance(micro, ClusteredSpheres):
|
|
311
|
+
return micro.aggregate_phase is None or _pointwise(micro.aggregates)
|
|
312
|
+
if isinstance(micro, CoatedStructure):
|
|
313
|
+
# exact distances to unions of spheres and segments; else the EDT of the voxels
|
|
314
|
+
return (
|
|
315
|
+
isinstance(micro.inner, PrimitiveUnion)
|
|
316
|
+
and _pointwise(micro.inner)
|
|
317
|
+
and (micro.bores is None or _pointwise(micro.bores))
|
|
318
|
+
)
|
|
319
|
+
if isinstance(micro, Combined):
|
|
320
|
+
return all(_pointwise(p) for p in micro.parts)
|
|
321
|
+
return isinstance(micro, _POINTWISE)
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def _display(a: np.ndarray) -> np.ndarray:
|
|
325
|
+
"""A slice ``s[u, v]`` as displayed by ``slice_of``."""
|
|
326
|
+
return np.ascontiguousarray(np.flipud(a.T))
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def _evaluate(
|
|
330
|
+
micro, grid: Grid, axis: int, index: int = 0, cells: int | None = None, implicit: bool = False
|
|
331
|
+
):
|
|
332
|
+
"""Phase, level set and labels of ``micro`` on ``grid``, their slices ``index`` along
|
|
333
|
+
``axis`` as arrays ``[u, v]``; ``cells``: the slice of the lattice of a lattice field
|
|
334
|
+
(the grid being a slab of it), whose cells give the phases and labels as they are.
|
|
335
|
+
With ``implicit``, the implicit functions of the phases of a structure of several
|
|
336
|
+
phases as well (by phase; None for the others)."""
|
|
337
|
+
|
|
338
|
+
def take(image):
|
|
339
|
+
return np.take(image.data, index, axis=axis)
|
|
340
|
+
|
|
341
|
+
if cells is not None:
|
|
342
|
+
phase = np.take(micro.phases, cells, axis=axis)
|
|
343
|
+
else:
|
|
344
|
+
phase = take(micro.voxelize(grid=grid))
|
|
345
|
+
level = levels = None
|
|
346
|
+
if has_level_set(micro):
|
|
347
|
+
try:
|
|
348
|
+
level = take(micro.level_set(grid=grid)).astype(np.float32)
|
|
349
|
+
except NotImplementedError:
|
|
350
|
+
level = None
|
|
351
|
+
elif implicit and cells is None:
|
|
352
|
+
levels = _phase_functions(micro, grid, take)
|
|
353
|
+
labels = None
|
|
354
|
+
if micro.has_labels:
|
|
355
|
+
if cells is not None:
|
|
356
|
+
labels = np.take(micro.cell_labels, cells, axis=axis)
|
|
357
|
+
else:
|
|
358
|
+
labels = take(micro.labels(grid=grid))
|
|
359
|
+
labels = labels.astype(np.int32, copy=False)
|
|
360
|
+
return phase.astype(np.uint8, copy=False), level, labels, levels
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _phase_functions(micro, grid: Grid, take) -> dict[int, np.ndarray] | None:
|
|
364
|
+
"""The implicit functions of the phases of a structure of several phases on a grid
|
|
365
|
+
(None for those of two phases, or without them)."""
|
|
366
|
+
phases = getattr(micro, "implicit_phases", lambda: [0, 1])()
|
|
367
|
+
if phases == [0, 1] or len(phases) > MAX_PHASES:
|
|
368
|
+
return None
|
|
369
|
+
try:
|
|
370
|
+
return {
|
|
371
|
+
int(k): take(micro.phase_level_set(k, grid=grid)).astype(np.float32) for k in phases
|
|
372
|
+
}
|
|
373
|
+
except NotImplementedError:
|
|
374
|
+
return None
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def _resampled(values: np.ndarray, coarse: Grid, fine: Grid, axes, linear: bool):
|
|
378
|
+
"""A coarse slice ``[u, v]`` at the pixel centres of a finer grid: the value of the
|
|
379
|
+
coarse cell containing each centre, or linearly interpolated between their centres."""
|
|
380
|
+
out = values
|
|
381
|
+
for k, a in enumerate(axes):
|
|
382
|
+
t = (fine.centers(a) - coarse.origin[a]) / coarse.spacing[a]
|
|
383
|
+
n = coarse.shape[a]
|
|
384
|
+
if not linear:
|
|
385
|
+
idx = np.clip(np.floor(t).astype(np.int64), 0, n - 1)
|
|
386
|
+
out = np.take(out, idx, axis=k)
|
|
387
|
+
continue
|
|
388
|
+
t = np.clip(t - 0.5, 0.0, n - 1.0)
|
|
389
|
+
i0 = np.minimum(np.floor(t).astype(np.int64), max(n - 2, 0))
|
|
390
|
+
i1 = np.minimum(i0 + 1, n - 1)
|
|
391
|
+
w = (t - i0).astype(np.float32)
|
|
392
|
+
shape = [1, 1]
|
|
393
|
+
shape[k] = len(w)
|
|
394
|
+
w = w.reshape(shape)
|
|
395
|
+
out = np.take(out, i0, axis=k) * (1 - w) + np.take(out, i1, axis=k) * w
|
|
396
|
+
return out.astype(values.dtype, copy=False)
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def _from_volume(micro, full: Grid, axis: int, index: int):
|
|
400
|
+
"""The slice of the voxel image (of a coarser one beyond :data:`MAX_VOLUME` voxels,
|
|
401
|
+
enlarged to the pixels of ``full``)."""
|
|
402
|
+
if full.n_voxels <= MAX_VOLUME:
|
|
403
|
+
return (*_evaluate(micro, full, axis, index)[:3], "volume")
|
|
404
|
+
scale = (MAX_VOLUME / full.n_voxels) ** (1.0 / 3.0)
|
|
405
|
+
coarse = Grid(full.domain, tuple(max(1, math.floor(n * scale + 1e-9)) for n in full.shape))
|
|
406
|
+
position = float(full.centers(axis)[index])
|
|
407
|
+
k = int((position - coarse.origin[axis]) // coarse.spacing[axis])
|
|
408
|
+
k = min(max(k, 0), coarse.shape[axis] - 1)
|
|
409
|
+
phase, level, labels, _ = _evaluate(micro, coarse, axis, k)
|
|
410
|
+
axes = plane_axes(axis)
|
|
411
|
+
phase = _resampled(phase, coarse, full, axes, False)
|
|
412
|
+
if level is not None:
|
|
413
|
+
level = _resampled(level, coarse, full, axes, True)
|
|
414
|
+
if labels is not None:
|
|
415
|
+
labels = _resampled(labels, coarse, full, axes, False)
|
|
416
|
+
return phase, level, labels, "coarse"
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def section(micro, axis: int = 2, fraction: float = 0.5, resolution: int = 512) -> Section:
|
|
420
|
+
"""The section of ``micro`` normal to ``axis`` at ``fraction`` of the domain, with
|
|
421
|
+
``resolution`` pixels along the longest edge of the plane: the slice of index
|
|
422
|
+
:func:`plane_index` of ``micro.voxelize(grid=volume_grid(...))`` (and of its level set
|
|
423
|
+
and labels), computed on the plane alone when the structure allows it (see the
|
|
424
|
+
module)."""
|
|
425
|
+
axis, fraction = _axis(axis), _fraction(fraction)
|
|
426
|
+
full = volume_grid(micro.domain, axis, resolution)
|
|
427
|
+
index = plane_index(micro.domain, axis, fraction, resolution)
|
|
428
|
+
levels = None
|
|
429
|
+
if isinstance(micro, _LEAVES):
|
|
430
|
+
grid = _slab(full, axis, index, thickness=float(micro.domain.lengths[axis]))
|
|
431
|
+
phase, level, labels, levels = _evaluate(micro, grid, axis, implicit=True)
|
|
432
|
+
sampling = "plane"
|
|
433
|
+
elif _pointwise(micro):
|
|
434
|
+
on_lattice = isinstance(micro, LatticeField) and tuple(full.shape) == micro.shape
|
|
435
|
+
cells = index if on_lattice else None
|
|
436
|
+
grid = _slab(full, axis, index)
|
|
437
|
+
phase, level, labels, levels = _evaluate(micro, grid, axis, cells=cells, implicit=True)
|
|
438
|
+
sampling = "plane"
|
|
439
|
+
else:
|
|
440
|
+
phase, level, labels, sampling = _from_volume(micro, full, axis, index)
|
|
441
|
+
u, v = plane_axes(axis)
|
|
442
|
+
lo, hi = micro.domain.lower, micro.domain.upper
|
|
443
|
+
level = None if level is None else _display(level)
|
|
444
|
+
coverages = None
|
|
445
|
+
if levels:
|
|
446
|
+
coverages = phase_coverages({k: _display(f) for k, f in levels.items()}, _display(phase))
|
|
447
|
+
return Section(
|
|
448
|
+
axis=axis,
|
|
449
|
+
fraction=fraction,
|
|
450
|
+
phase=_display(phase),
|
|
451
|
+
level_set=level,
|
|
452
|
+
coverage=None if level is None else pixel_coverage(level),
|
|
453
|
+
labels=None if labels is None else _display(labels),
|
|
454
|
+
pixel=float(max(full.spacing[u], full.spacing[v])),
|
|
455
|
+
extent=(float(lo[u]), float(hi[u]), float(lo[v]), float(hi[v])),
|
|
456
|
+
names=(_AXES[u], _AXES[v]),
|
|
457
|
+
position=float(full.centers(axis)[index]),
|
|
458
|
+
index=int(index),
|
|
459
|
+
sampling=sampling,
|
|
460
|
+
coverages=coverages,
|
|
461
|
+
)
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def sections(micro, resolution: int = 512) -> list[Section]:
|
|
465
|
+
"""The middle sections normal to x, y and z (y-z, x-z, x-y), or the x-y one alone
|
|
466
|
+
for planar structures (:func:`is_planar`)."""
|
|
467
|
+
axes = (2,) if is_planar(micro, resolution) else (0, 1, 2)
|
|
468
|
+
return [section(micro, a, 0.5, resolution) for a in axes]
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
# -- images -----------------------------------------------------------------------------------
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def _variation(phi: np.ndarray) -> np.ndarray:
|
|
475
|
+
"""``|D_u phi| + |D_v phi|``: the larger one-sided differences with the neighbours
|
|
476
|
+
along each axis, summed (``h_u |dphi/du| + h_v |dphi/dv|``)."""
|
|
477
|
+
out = np.zeros(phi.shape, dtype=phi.dtype)
|
|
478
|
+
m = np.empty_like(out)
|
|
479
|
+
for a in range(2):
|
|
480
|
+
if phi.shape[a] < 2:
|
|
481
|
+
continue
|
|
482
|
+
|
|
483
|
+
def part(s, a=a):
|
|
484
|
+
return (s, slice(None)) if a == 0 else (slice(None), s)
|
|
485
|
+
|
|
486
|
+
d = np.abs(np.diff(phi, axis=a))
|
|
487
|
+
m[part(slice(None, -1))] = d # with the next pixel
|
|
488
|
+
m[part(slice(-1, None))] = 0.0
|
|
489
|
+
later = m[part(slice(1, None))]
|
|
490
|
+
np.maximum(later, d, out=later) # and with the previous one
|
|
491
|
+
out += m
|
|
492
|
+
return out
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def pixel_coverage(phi) -> np.ndarray:
|
|
496
|
+
"""Fraction of phase 1 in each pixel from the level set at the pixel centres:
|
|
497
|
+
``clip(1/2 - phi / (|D_u phi| + |D_v phi|), 0, 1)`` (see the module), 1 or 0 by the
|
|
498
|
+
sign of ``phi`` where it does not vary."""
|
|
499
|
+
p = np.asarray(phi, dtype=np.float32)
|
|
500
|
+
if p.ndim != 2:
|
|
501
|
+
raise ValueError("pixel_coverage: a 2D level set")
|
|
502
|
+
with np.errstate(divide="ignore", invalid="ignore"): # infinite placeholders: by sign
|
|
503
|
+
width = _variation(p)
|
|
504
|
+
out = 0.5 - p / width
|
|
505
|
+
flat = ~(width > 0)
|
|
506
|
+
out[flat] = np.where(p[flat] < 0, 1.0, np.where(p[flat] > 0, 0.0, 0.5))
|
|
507
|
+
return np.clip(out, 0.0, 1.0, out=out)
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def phase_coverages(levels: dict[int, np.ndarray], phase: np.ndarray) -> dict[int, np.ndarray]:
|
|
511
|
+
"""Fraction of each phase in each pixel from the implicit functions ``levels`` of the
|
|
512
|
+
phases at the pixel centres (by phase, each negative in its phase): the
|
|
513
|
+
:func:`pixel_coverage` of each, scaled so that they sum to one; where none of them
|
|
514
|
+
covers the pixel, the ``phase`` of its centre takes it."""
|
|
515
|
+
cover = {int(k): pixel_coverage(f) for k, f in levels.items()}
|
|
516
|
+
total = np.zeros(np.shape(phase), dtype=np.float32)
|
|
517
|
+
for c in cover.values():
|
|
518
|
+
total += c
|
|
519
|
+
covered = total > 0
|
|
520
|
+
out = {}
|
|
521
|
+
for k, c in cover.items():
|
|
522
|
+
share = np.divide(c, total, out=np.zeros_like(c), where=covered)
|
|
523
|
+
share[~covered & (np.asarray(phase) == k)] = 1.0
|
|
524
|
+
out[k] = share
|
|
525
|
+
return out
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def _changes(values: np.ndarray) -> np.ndarray:
|
|
529
|
+
"""Pixels whose value differs from that of the next pixel along a row or a column."""
|
|
530
|
+
out = np.zeros(values.shape, dtype=bool)
|
|
531
|
+
out[:, :-1] |= values[:, :-1] != values[:, 1:]
|
|
532
|
+
out[:-1, :] |= values[:-1, :] != values[1:, :]
|
|
533
|
+
return out
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
def render(sec: Section, kind: str = "phase", *, contour: bool = False) -> np.ndarray:
|
|
537
|
+
"""RGB image (uint8, rows x columns x 3) of a section.
|
|
538
|
+
|
|
539
|
+
``phase``: the colours of :data:`morphogen.viz.png.PALETTE`, those of phases 0 and 1
|
|
540
|
+
blended by the coverage when the section has a level set (anti-aliased boundaries),
|
|
541
|
+
those of all the phases by their coverages when it has the implicit functions of
|
|
542
|
+
several phases, the plain colours of the phases otherwise; ``labels``: a colour per
|
|
543
|
+
cell or grain (:func:`morphogen.viz.png.label_colors`). ``contour`` draws the zero
|
|
544
|
+
level set as a thin dark line (``1 - |2 coverage - 1|`` of the dark colour; between
|
|
545
|
+
several phases, twice the share of the pixel that is not of its main phase), or
|
|
546
|
+
without a level set the boundaries between the phases or labels shown.
|
|
547
|
+
"""
|
|
548
|
+
several = sec.coverages if kind == "phase" else None
|
|
549
|
+
if kind == "phase":
|
|
550
|
+
index = np.minimum(sec.phase, len(PALETTE) - 1)
|
|
551
|
+
if several:
|
|
552
|
+
colours = PALETTE.astype(np.float32)
|
|
553
|
+
rgb = np.zeros((*sec.phase.shape, 3), dtype=np.float32)
|
|
554
|
+
total = np.zeros(sec.phase.shape, dtype=np.float32)
|
|
555
|
+
for k, c in several.items():
|
|
556
|
+
rgb += c[..., None] * colours[min(k, len(PALETTE) - 1)]
|
|
557
|
+
total += c
|
|
558
|
+
np.copyto(rgb, colours[index], where=(total <= 0)[..., None])
|
|
559
|
+
elif sec.coverage is None:
|
|
560
|
+
rgb = PALETTE[index]
|
|
561
|
+
else:
|
|
562
|
+
colours = PALETTE.astype(np.float32)
|
|
563
|
+
rgb = colours[index]
|
|
564
|
+
c = sec.coverage[..., None]
|
|
565
|
+
blend = colours[0] + c * (colours[1] - colours[0])
|
|
566
|
+
np.copyto(rgb, blend, where=(sec.phase <= 1)[..., None])
|
|
567
|
+
shown = sec.phase
|
|
568
|
+
elif kind == "labels":
|
|
569
|
+
if sec.labels is None:
|
|
570
|
+
raise ValueError("render: this section has no labels")
|
|
571
|
+
rgb = label_colors(sec.labels)
|
|
572
|
+
shown = sec.labels
|
|
573
|
+
else:
|
|
574
|
+
raise ValueError(f"render: kind 'phase' or 'labels', got {kind!r}")
|
|
575
|
+
if contour:
|
|
576
|
+
if several:
|
|
577
|
+
main = np.max(np.stack(list(several.values())), axis=0)
|
|
578
|
+
alpha = np.clip(2.0 * (1.0 - main), 0.0, 1.0)
|
|
579
|
+
elif sec.coverage is not None:
|
|
580
|
+
alpha = 1.0 - np.abs(2.0 * sec.coverage - 1.0)
|
|
581
|
+
else:
|
|
582
|
+
alpha = _changes(shown).astype(np.float32)
|
|
583
|
+
rgb = rgb + alpha[..., None] * (CONTOUR.astype(np.float32) - rgb)
|
|
584
|
+
if rgb.dtype == np.uint8:
|
|
585
|
+
return rgb
|
|
586
|
+
return np.clip(np.rint(rgb), 0, 255).astype(np.uint8)
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
# -- measures ---------------------------------------------------------------------------------
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
def _gradient_norm(phi: np.ndarray, spacing, periodic: bool) -> np.ndarray:
|
|
593
|
+
"""``|grad phi|`` by centred differences (one-sided at the faces of a non-periodic
|
|
594
|
+
grid)."""
|
|
595
|
+
out = np.zeros(phi.shape)
|
|
596
|
+
for a in range(3):
|
|
597
|
+
h = float(spacing[a])
|
|
598
|
+
if phi.shape[a] < 2:
|
|
599
|
+
continue
|
|
600
|
+
if periodic:
|
|
601
|
+
g = (np.roll(phi, -1, axis=a) - np.roll(phi, 1, axis=a)) / (2.0 * h)
|
|
602
|
+
else:
|
|
603
|
+
g = np.gradient(phi, h, axis=a)
|
|
604
|
+
out += g * g
|
|
605
|
+
return np.sqrt(out)
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
def _marching_cubes_area(phi: np.ndarray, spacing, periodic: bool) -> float | None:
|
|
609
|
+
"""Area of the zero level set by the marching cubes of scikit-image (None without
|
|
610
|
+
it); a periodic grid is closed by a copy of its first cells, so that the cells of the
|
|
611
|
+
surface cover exactly one period."""
|
|
612
|
+
try:
|
|
613
|
+
from skimage.measure import marching_cubes, mesh_surface_area
|
|
614
|
+
except ImportError:
|
|
615
|
+
return None
|
|
616
|
+
volume = np.pad(phi, [(0, 1)] * 3, mode="wrap") if periodic else phi
|
|
617
|
+
if not volume.min() < 0.0 < volume.max():
|
|
618
|
+
return 0.0
|
|
619
|
+
verts, faces, _, _ = marching_cubes(volume, level=0.0, spacing=tuple(float(h) for h in spacing))
|
|
620
|
+
return float(mesh_surface_area(verts, faces))
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
def level_set_measures(micro, resolution: int = 128) -> dict[str, float]:
|
|
624
|
+
"""Volume fraction and specific surface of phase 1 from its level set ``phi``.
|
|
625
|
+
|
|
626
|
+
``phi`` is sampled on the voxel grid of the domain with ``resolution`` cells along its
|
|
627
|
+
longest edge (at the cell centres of a periodic domain, at the nodes from face to face
|
|
628
|
+
otherwise, weighted by the trapezoidal rule), and turned into the distance
|
|
629
|
+
``d = phi / |grad phi|`` to its zero level set (centred differences). With
|
|
630
|
+
``eps = h`` (the largest cell edge):
|
|
631
|
+
|
|
632
|
+
* ``volume_fraction``: the mean of the smoothed Heaviside ``H(-d)``, ``H(x) =
|
|
633
|
+
(1 + x / eps + sin(pi x / eps) / pi) / 2`` on ``[-eps, eps]``. Its samples sum
|
|
634
|
+
exactly to the volume for plane interfaces (the spectrum of ``H'`` vanishes at the
|
|
635
|
+
multiples of ``1 / h``); curvature adds about ``0.13 eps^2`` times the integral of
|
|
636
|
+
the mean curvature (``0.39 (eps / R)^2`` of the volume of spheres of radius ``R``),
|
|
637
|
+
more for struts a few cells thick;
|
|
638
|
+
* ``specific_surface``: the area of the zero level set in the domain per unit volume,
|
|
639
|
+
by marching cubes (scikit-image, the ``surface`` extra), else by the coarea formula
|
|
640
|
+
``mean(delta(phi') |grad phi'|)``, ``delta(x) = (1 + cos(pi x / eps)) / (2 eps)`` on
|
|
641
|
+
``[-eps, eps]``, ``phi'`` being ``phi`` over its median gradient at the interface (an
|
|
642
|
+
estimate, low for gaps and struts thinner than ``2 eps``).
|
|
643
|
+
|
|
644
|
+
Only for structures with a level set (ValueError otherwise).
|
|
645
|
+
"""
|
|
646
|
+
name = getattr(getattr(micro, "model", None), "name", None) or type(micro).__name__
|
|
647
|
+
if not has_level_set(micro):
|
|
648
|
+
raise ValueError(
|
|
649
|
+
f"{name}: no level-set function (its phase 1 is not described by one, e.g. "
|
|
650
|
+
"tessellations, dead leaves, several phases); measure its voxel image instead"
|
|
651
|
+
)
|
|
652
|
+
resolution = _resolution(resolution)
|
|
653
|
+
domain = micro.domain
|
|
654
|
+
base = Grid.for_domain(domain, shape=resolution)
|
|
655
|
+
h = base.spacing
|
|
656
|
+
periodic = domain.periodic
|
|
657
|
+
if periodic:
|
|
658
|
+
grid = base
|
|
659
|
+
else: # the nodes of the cells, from face to face
|
|
660
|
+
n = np.array(base.shape) + 1
|
|
661
|
+
nodes = Domain(size=n * h, origin=domain.lower - 0.5 * h, periodic=False, unit=domain.unit)
|
|
662
|
+
grid = Grid(nodes, tuple(int(k) for k in n))
|
|
663
|
+
try:
|
|
664
|
+
phi = micro.level_set(grid=grid).data.astype(np.float64)
|
|
665
|
+
except NotImplementedError as exc:
|
|
666
|
+
raise ValueError(f"{name}: no level-set function ({exc})") from None
|
|
667
|
+
far = float(domain.diagonal) # placeholders of 'no interface' (inf) made finite
|
|
668
|
+
phi = np.clip(np.nan_to_num(phi, nan=far, posinf=far, neginf=-far), -far, far)
|
|
669
|
+
eps = float(h.max())
|
|
670
|
+
norm = _gradient_norm(phi, grid.spacing, periodic)
|
|
671
|
+
d = np.where(phi < 0, -np.inf, np.where(phi > 0, np.inf, 0.0))
|
|
672
|
+
np.divide(phi, norm, out=d, where=norm > 0)
|
|
673
|
+
t = np.clip(-d / eps, -1.0, 1.0)
|
|
674
|
+
heaviside = 0.5 * (1.0 + t + np.sin(np.pi * t) / np.pi)
|
|
675
|
+
if periodic:
|
|
676
|
+
weights = np.ones(grid.shape)
|
|
677
|
+
else: # trapezoidal rule over the nodes
|
|
678
|
+
w = [np.ones(k) for k in grid.shape]
|
|
679
|
+
for a, k in enumerate(grid.shape):
|
|
680
|
+
if k > 1:
|
|
681
|
+
w[a][[0, -1]] = 0.5
|
|
682
|
+
weights = w[0][:, None, None] * w[1][None, :, None] * w[2][None, None, :]
|
|
683
|
+
total = float(np.sum(weights))
|
|
684
|
+
fraction = float(np.sum(weights * heaviside) / total)
|
|
685
|
+
area = _marching_cubes_area(phi, grid.spacing, periodic)
|
|
686
|
+
if area is None: # coarea formula, phi scaled to a distance by its gradient at the surface
|
|
687
|
+
near = np.abs(d) < eps
|
|
688
|
+
scale = float(np.median(norm[near])) if near.any() else 1.0
|
|
689
|
+
x = phi / scale
|
|
690
|
+
band = np.abs(x) < eps
|
|
691
|
+
delta = np.zeros(phi.shape)
|
|
692
|
+
delta[band] = (1.0 + np.cos(np.pi * x[band] / eps)) / (2.0 * eps) * norm[band] / scale
|
|
693
|
+
surface = float(np.sum(weights * delta) / total)
|
|
694
|
+
else:
|
|
695
|
+
surface = area / domain.volume
|
|
696
|
+
return {"volume_fraction": fraction, "specific_surface": surface}
|