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,570 @@
|
|
|
1
|
+
"""Regularization of cell complexes: removal of the features smaller than a length.
|
|
2
|
+
|
|
3
|
+
A tessellation has edges, facets and pieces of every size; a mesh must resolve them with
|
|
4
|
+
elements of their size, or with flat elements. Following the idea of Quey, Dawson and
|
|
5
|
+
Barbe (2011), the features smaller than ``delta`` are removed before meshing:
|
|
6
|
+
|
|
7
|
+
* *caps* — pieces that rise less than ``delta`` above a face of the box (cells that
|
|
8
|
+
barely cross it) — are flattened onto that face: their other facets become faces of
|
|
9
|
+
the box for the neighbouring pieces. A cap that overhangs its facet on the face cannot
|
|
10
|
+
be flattened this way; it joins the cell of the neighbour with which it shares its
|
|
11
|
+
largest facet (its volume changes cell, the geometry is kept);
|
|
12
|
+
* short edges are contracted to a point, the shortest first; when contracting an edge
|
|
13
|
+
alone would leave an invalid piece (a tiny facet with several short edges), its nearest
|
|
14
|
+
neighbours are contracted with it.
|
|
15
|
+
|
|
16
|
+
Each change is kept only if every piece it touches remains a valid star polyhedron (the
|
|
17
|
+
cones from its centroid over its facets have positive volumes) touching the faces of the
|
|
18
|
+
box by facets, not along lines. The vertices on the faces of the box stay on them. The
|
|
19
|
+
faces of a periodic complex remain exact translates of each other: a vertex of a face
|
|
20
|
+
moves and merges together with its periodic images, and the facet of a flattened cap's
|
|
21
|
+
cell on the opposite face is split as the cap's facet was. The facets become slightly
|
|
22
|
+
non-planar.
|
|
23
|
+
|
|
24
|
+
The whole cells of a periodic tessellation (``CellComplex.whole``) have no caps: only their
|
|
25
|
+
short edges are contracted, every vertex moving and merging together with its
|
|
26
|
+
translates, so that the facets bounding their union remain pairs of translates.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import heapq
|
|
32
|
+
|
|
33
|
+
import numpy as np
|
|
34
|
+
from scipy.spatial import cKDTree
|
|
35
|
+
|
|
36
|
+
from morphogen.mesh.polyhedra import CellComplex
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class _Complex:
|
|
40
|
+
"""Mutable copy of a cell complex."""
|
|
41
|
+
|
|
42
|
+
def __init__(self, cx: CellComplex):
|
|
43
|
+
self.cx = cx
|
|
44
|
+
self.V = cx.vertices.copy()
|
|
45
|
+
self.facets = [list(map(int, f)) for f in cx.facets]
|
|
46
|
+
self.fp = [list(map(int, p)) for p in cx.facet_pieces]
|
|
47
|
+
self.fbox = [int(b) for b in cx.facet_box]
|
|
48
|
+
self.pfac = [set(map(int, pf)) for pf in cx.piece_facets]
|
|
49
|
+
self.alive_f = [True] * len(self.facets)
|
|
50
|
+
self.alive_p = [True] * len(self.pfac)
|
|
51
|
+
self.cell = np.array(cx.piece_cell, dtype=np.int64)
|
|
52
|
+
self.lower, self.upper = cx.lower, cx.upper
|
|
53
|
+
self.size = cx.upper - cx.lower
|
|
54
|
+
self.whole = bool(cx.whole)
|
|
55
|
+
self.tol = 1e-9 * float(self.size.max())
|
|
56
|
+
self.vfac: list[set] = [set() for _ in range(len(self.V))]
|
|
57
|
+
for f, loop in enumerate(self.facets):
|
|
58
|
+
for v in loop:
|
|
59
|
+
self.vfac[v].add(f)
|
|
60
|
+
|
|
61
|
+
# -- geometry ------------------------------------------------------------------------
|
|
62
|
+
|
|
63
|
+
def planes(self, v: int) -> set:
|
|
64
|
+
"""Faces of the box (axis, side) containing vertex ``v`` (none for whole cells)."""
|
|
65
|
+
out = set()
|
|
66
|
+
if self.whole:
|
|
67
|
+
return out
|
|
68
|
+
for d in range(3):
|
|
69
|
+
if abs(self.V[v, d] - self.lower[d]) <= self.tol:
|
|
70
|
+
out.add((d, 0))
|
|
71
|
+
elif abs(self.V[v, d] - self.upper[d]) <= self.tol:
|
|
72
|
+
out.add((d, 1))
|
|
73
|
+
return out
|
|
74
|
+
|
|
75
|
+
def oriented(self, f: int, p: int) -> list:
|
|
76
|
+
return self.facets[f] if self.fp[f][0] == p else self.facets[f][::-1]
|
|
77
|
+
|
|
78
|
+
def piece_vertices(self, p: int) -> list:
|
|
79
|
+
return sorted({v for f in self.pfac[p] for v in self.facets[f]})
|
|
80
|
+
|
|
81
|
+
def piece_ok(self, p: int, min_volume: float) -> bool:
|
|
82
|
+
"""Closed star polyhedron: every edge of its facets is shared by two facets in
|
|
83
|
+
opposite directions, and the cones from its centroid over the facet fans have
|
|
84
|
+
positive volumes."""
|
|
85
|
+
if len(self.pfac[p]) < 4:
|
|
86
|
+
return False
|
|
87
|
+
edges: dict = {}
|
|
88
|
+
for f in self.pfac[p]:
|
|
89
|
+
loop = self.oriented(f, p)
|
|
90
|
+
for a, b in zip(loop, loop[1:] + loop[:1], strict=True):
|
|
91
|
+
edges[(a, b)] = edges.get((a, b), 0) + 1
|
|
92
|
+
for (a, b), count in edges.items():
|
|
93
|
+
if count != 1 or edges.get((b, a), 0) != 1:
|
|
94
|
+
return False
|
|
95
|
+
# an edge on a face of the box belongs to a facet of the piece on that face (a
|
|
96
|
+
# piece touching the box along a line only is not a valid subdomain)
|
|
97
|
+
box_edges = set()
|
|
98
|
+
for f in self.pfac[p]:
|
|
99
|
+
if self.fbox[f] > 0:
|
|
100
|
+
loop = self.facets[f]
|
|
101
|
+
box_edges.update(zip(loop, loop[1:] + loop[:1], strict=True))
|
|
102
|
+
box_edges.update(zip(loop[1:] + loop[:1], loop, strict=True))
|
|
103
|
+
for f in self.pfac[p]:
|
|
104
|
+
if self.fbox[f] > 0:
|
|
105
|
+
continue
|
|
106
|
+
loop = self.facets[f]
|
|
107
|
+
for a, b in zip(loop, loop[1:] + loop[:1], strict=True):
|
|
108
|
+
if (a, b) not in box_edges and self.planes(a) & self.planes(b):
|
|
109
|
+
return False
|
|
110
|
+
verts = self.piece_vertices(p)
|
|
111
|
+
g = self.V[verts].mean(axis=0)
|
|
112
|
+
total = 0.0
|
|
113
|
+
for f in self.pfac[p]:
|
|
114
|
+
loop = self.oriented(f, p)
|
|
115
|
+
if len(set(loop)) < 3:
|
|
116
|
+
return False
|
|
117
|
+
pts = self.V[loop]
|
|
118
|
+
c = pts.mean(axis=0)
|
|
119
|
+
nxt = np.roll(pts, -1, axis=0)
|
|
120
|
+
vol = np.cross(pts - c, nxt - c) @ (g - c) / 6.0
|
|
121
|
+
# outward triangles: the centroid lies behind them
|
|
122
|
+
if np.any(vol >= -min_volume):
|
|
123
|
+
return False
|
|
124
|
+
total -= vol.sum()
|
|
125
|
+
return total > 0
|
|
126
|
+
|
|
127
|
+
def facet_area(self, f: int) -> float:
|
|
128
|
+
p = self.V[self.facets[f]]
|
|
129
|
+
c = p.mean(axis=0)
|
|
130
|
+
return 0.5 * float(np.linalg.norm(np.cross(p - c, np.roll(p, -1, axis=0) - c).sum(axis=0)))
|
|
131
|
+
|
|
132
|
+
# -- edits ---------------------------------------------------------------------------
|
|
133
|
+
|
|
134
|
+
def snapshot(self, facets, pieces, verts):
|
|
135
|
+
verts = set(verts)
|
|
136
|
+
for f in facets:
|
|
137
|
+
verts.update(self.facets[f])
|
|
138
|
+
return (
|
|
139
|
+
{
|
|
140
|
+
f: (list(self.facets[f]), self.alive_f[f], list(self.fp[f]), self.fbox[f])
|
|
141
|
+
for f in facets
|
|
142
|
+
},
|
|
143
|
+
{p: (set(self.pfac[p]), self.alive_p[p]) for p in pieces},
|
|
144
|
+
{v: (self.V[v].copy(), set(self.vfac[v])) for v in verts},
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
def restore(self, snap):
|
|
148
|
+
fs, ps, vs = snap
|
|
149
|
+
for f, (loop, alive, fp, fb) in fs.items():
|
|
150
|
+
self.facets[f], self.alive_f[f], self.fp[f], self.fbox[f] = loop, alive, fp, fb
|
|
151
|
+
for p, (pf, alive) in ps.items():
|
|
152
|
+
self.pfac[p], self.alive_p[p] = pf, alive
|
|
153
|
+
for v, (x, vf) in vs.items():
|
|
154
|
+
self.V[v], self.vfac[v] = x, vf
|
|
155
|
+
|
|
156
|
+
def clean_facet(self, f: int) -> None:
|
|
157
|
+
"""Remove repeated vertices; kill the facet if fewer than three remain."""
|
|
158
|
+
loop = self.facets[f]
|
|
159
|
+
out = [v for i, v in enumerate(loop) if v != loop[i - 1]] if len(loop) > 1 else loop
|
|
160
|
+
if len(out) > 1 and out[0] == out[-1]:
|
|
161
|
+
out = out[:-1]
|
|
162
|
+
self.facets[f] = out
|
|
163
|
+
if len(set(out)) < 3 or len(set(out)) != len(out):
|
|
164
|
+
self.kill_facet(f)
|
|
165
|
+
|
|
166
|
+
def kill_facet(self, f: int) -> None:
|
|
167
|
+
if not self.alive_f[f]:
|
|
168
|
+
return
|
|
169
|
+
self.alive_f[f] = False
|
|
170
|
+
for p in self.fp[f]:
|
|
171
|
+
if p >= 0:
|
|
172
|
+
self.pfac[p].discard(f)
|
|
173
|
+
for v in set(self.facets[f]):
|
|
174
|
+
self.vfac[v].discard(f)
|
|
175
|
+
|
|
176
|
+
def add_vertex(self, x) -> int:
|
|
177
|
+
self.V = np.vstack([self.V, np.asarray(x, dtype=float)[None, :]])
|
|
178
|
+
self.vfac.append(set())
|
|
179
|
+
return len(self.V) - 1
|
|
180
|
+
|
|
181
|
+
def add_facet(self, loop: list, pieces: list, box: int) -> int:
|
|
182
|
+
f = len(self.facets)
|
|
183
|
+
self.facets.append(list(loop))
|
|
184
|
+
self.fp.append(list(pieces))
|
|
185
|
+
self.fbox.append(int(box))
|
|
186
|
+
self.alive_f.append(True)
|
|
187
|
+
for p in pieces:
|
|
188
|
+
if p >= 0:
|
|
189
|
+
self.pfac[p].add(f)
|
|
190
|
+
for v in loop:
|
|
191
|
+
self.vfac[v].add(f)
|
|
192
|
+
return f
|
|
193
|
+
|
|
194
|
+
def discard_new(self, n_vertices: int, n_facets: int) -> None:
|
|
195
|
+
"""Forget the vertices and facets added since the counts given (after restore)."""
|
|
196
|
+
for f in range(n_facets, len(self.facets)):
|
|
197
|
+
self.alive_f[f] = False
|
|
198
|
+
for v in range(n_vertices, len(self.V)):
|
|
199
|
+
self.vfac[v] = set()
|
|
200
|
+
|
|
201
|
+
def merge(self, a: int, b: int, x) -> None:
|
|
202
|
+
"""Vertex ``b`` disappears into ``a``, moved to ``x``."""
|
|
203
|
+
self.V[a] = x
|
|
204
|
+
for f in list(self.vfac[b]):
|
|
205
|
+
self.facets[f] = [a if v == b else v for v in self.facets[f]]
|
|
206
|
+
self.vfac[a].add(f)
|
|
207
|
+
self.vfac[b] = set()
|
|
208
|
+
for f in list(self.vfac[a]):
|
|
209
|
+
if self.alive_f[f]:
|
|
210
|
+
self.clean_facet(f)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _translates(cx: _Complex) -> dict:
|
|
214
|
+
"""Translates of the vertices of whole cells: ``v -> {offset: copy}``. They are exact
|
|
215
|
+
but for rounding, while distinct vertices are farther apart than the tolerance of
|
|
216
|
+
their assembly (an edge may be shorter than a micrometre of a unit box)."""
|
|
217
|
+
from morphogen.mesh.polyhedra import torus_classes
|
|
218
|
+
|
|
219
|
+
labels, shift = torus_classes(cx.V, cx.lower, cx.size, 0.1 * cx.tol)
|
|
220
|
+
members: dict = {}
|
|
221
|
+
for v, lab in enumerate(labels.tolist()):
|
|
222
|
+
members.setdefault(lab, []).append(v)
|
|
223
|
+
out: dict = {}
|
|
224
|
+
for group in members.values():
|
|
225
|
+
if len(group) < 2:
|
|
226
|
+
continue
|
|
227
|
+
for v in group:
|
|
228
|
+
out[v] = {tuple(int(k) for k in shift[u] - shift[v]): u for u in group if u != v}
|
|
229
|
+
return out
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _images(cx: _Complex) -> dict:
|
|
233
|
+
"""Periodic images of the vertices of the faces: ``v -> {offset: image}``."""
|
|
234
|
+
if cx.whole:
|
|
235
|
+
return _translates(cx)
|
|
236
|
+
on = [v for v in range(len(cx.V)) if cx.planes(v)]
|
|
237
|
+
if not on:
|
|
238
|
+
return {}
|
|
239
|
+
tree = cKDTree(cx.V[on])
|
|
240
|
+
out: dict = {}
|
|
241
|
+
for v in on:
|
|
242
|
+
for d, side in cx.planes(v):
|
|
243
|
+
shift = np.zeros(3)
|
|
244
|
+
shift[d] = cx.size[d] if side == 0 else -cx.size[d]
|
|
245
|
+
dist, j = tree.query(cx.V[v] + shift)
|
|
246
|
+
if dist <= 1e3 * cx.tol:
|
|
247
|
+
key = tuple(int(s) for s in np.sign(shift))
|
|
248
|
+
out.setdefault(v, {})[key] = on[j]
|
|
249
|
+
# images across several faces (box edges and corners): compose the offsets
|
|
250
|
+
changed = True
|
|
251
|
+
while changed:
|
|
252
|
+
changed = False
|
|
253
|
+
for v, imgs in list(out.items()):
|
|
254
|
+
for k1, w in list(imgs.items()):
|
|
255
|
+
for k2, u in out.get(w, {}).items():
|
|
256
|
+
k = tuple(np.add(k1, k2))
|
|
257
|
+
if any(k) and k not in imgs and u != v and max(map(abs, k)) <= 1:
|
|
258
|
+
imgs[k] = u
|
|
259
|
+
changed = True
|
|
260
|
+
return out
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _touching(cx: _Complex, verts) -> set:
|
|
264
|
+
pieces = set()
|
|
265
|
+
for v in verts:
|
|
266
|
+
for f in cx.vfac[v]:
|
|
267
|
+
pieces.update(p for p in cx.fp[f] if p >= 0)
|
|
268
|
+
return pieces
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _opposite_facet(cx: _Complex, f: int, off: tuple, images: dict) -> int | None:
|
|
272
|
+
"""The facet of the opposite face whose vertices are the images of those of ``f``."""
|
|
273
|
+
imgs = [images.get(v, {}).get(off) for v in cx.facets[f]]
|
|
274
|
+
if any(i is None for i in imgs):
|
|
275
|
+
return None
|
|
276
|
+
d = int(np.flatnonzero(off)[0])
|
|
277
|
+
ref = 2 * d + 1 + (1 if off[d] > 0 else 0)
|
|
278
|
+
cand = [
|
|
279
|
+
g
|
|
280
|
+
for g in set.intersection(*(cx.vfac[i] for i in imgs))
|
|
281
|
+
if cx.alive_f[g] and cx.fbox[g] == ref and set(cx.facets[g]) == set(imgs)
|
|
282
|
+
]
|
|
283
|
+
return cand[0] if len(cand) == 1 else None
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _relabel(cx: _Complex, p: int) -> bool:
|
|
287
|
+
"""Give a piece to the cell of the neighbour with which it shares its largest facet."""
|
|
288
|
+
best, cell = 0.0, None
|
|
289
|
+
for f in cx.pfac[p]:
|
|
290
|
+
q = cx.fp[f][1] if cx.fp[f][0] == p else cx.fp[f][0]
|
|
291
|
+
if q >= 0 and cx.cell[q] != cx.cell[p]:
|
|
292
|
+
area = cx.facet_area(f)
|
|
293
|
+
if area > best:
|
|
294
|
+
best, cell = area, cx.cell[q]
|
|
295
|
+
if cell is None:
|
|
296
|
+
return False
|
|
297
|
+
cx.cell[p] = cell
|
|
298
|
+
return True
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _flatten_caps(cx: _Complex, delta: float, min_volume: float, images: dict) -> tuple:
|
|
302
|
+
"""Flatten the pieces that rise less than ``delta`` above a face of the box. In a
|
|
303
|
+
periodic complex, the facet of the same cell on the opposite face is split alike (new
|
|
304
|
+
vertices, images of the flattened ones), so that opposite faces remain translates.
|
|
305
|
+
The caps that cannot be flattened (overhanging the face) join a neighbouring cell.
|
|
306
|
+
Returns the numbers of flattened and relabelled caps."""
|
|
307
|
+
done = relabelled = 0
|
|
308
|
+
for p in range(len(cx.pfac)):
|
|
309
|
+
if not cx.alive_p[p]:
|
|
310
|
+
continue
|
|
311
|
+
box_facets = [f for f in cx.pfac[p] if cx.fbox[f] > 0]
|
|
312
|
+
verts = cx.piece_vertices(p)
|
|
313
|
+
best = None
|
|
314
|
+
for ref in {cx.fbox[f] for f in box_facets}:
|
|
315
|
+
d, side = (ref - 1) // 2, (ref - 1) % 2
|
|
316
|
+
plane = cx.lower[d] if side == 0 else cx.upper[d]
|
|
317
|
+
height = float(np.max(np.abs(cx.V[verts, d] - plane)))
|
|
318
|
+
if height < delta and (best is None or height < best[0]):
|
|
319
|
+
best = (height, d, side, plane, ref)
|
|
320
|
+
if best is None:
|
|
321
|
+
continue
|
|
322
|
+
_, d, side, plane, ref = best
|
|
323
|
+
moved = [v for v in verts if abs(cx.V[v, d] - plane) > cx.tol]
|
|
324
|
+
opposite, off = None, None
|
|
325
|
+
if images:
|
|
326
|
+
# a piece on one face only, whose other vertices lie inside the box
|
|
327
|
+
if len(box_facets) == 1 and not any(cx.planes(v) for v in moved):
|
|
328
|
+
off = tuple(int(k == d) * (1 if side == 0 else -1) for k in range(3))
|
|
329
|
+
opposite = _opposite_facet(cx, box_facets[0], off, images)
|
|
330
|
+
if opposite is None:
|
|
331
|
+
relabelled += _relabel(cx, p)
|
|
332
|
+
continue
|
|
333
|
+
facets = set(cx.pfac[p])
|
|
334
|
+
pieces = _touching(cx, moved) | {p}
|
|
335
|
+
if opposite is not None:
|
|
336
|
+
pieces.add(cx.fp[opposite][0])
|
|
337
|
+
for q in pieces:
|
|
338
|
+
facets |= cx.pfac[q]
|
|
339
|
+
snap = cx.snapshot(facets, pieces, moved)
|
|
340
|
+
n_vertices, n_facets = len(cx.V), len(cx.facets)
|
|
341
|
+
for v in moved:
|
|
342
|
+
cx.V[v, d] = plane
|
|
343
|
+
# the piece disappears: its facets on the face go, the others join the face
|
|
344
|
+
joined = []
|
|
345
|
+
for f in list(cx.pfac[p]):
|
|
346
|
+
if cx.fbox[f] > 0:
|
|
347
|
+
cx.kill_facet(f)
|
|
348
|
+
continue
|
|
349
|
+
other = cx.fp[f][1] if cx.fp[f][0] == p else cx.fp[f][0]
|
|
350
|
+
if cx.fp[f][0] == p: # the loop pointed away from p, into the other piece
|
|
351
|
+
cx.facets[f] = cx.facets[f][::-1]
|
|
352
|
+
cx.fp[f] = [other, -1]
|
|
353
|
+
cx.fbox[f] = ref
|
|
354
|
+
if cx.facet_area(f) <= 1e-12 * float(cx.size.max()) ** 2:
|
|
355
|
+
cx.kill_facet(f)
|
|
356
|
+
else:
|
|
357
|
+
joined.append(f)
|
|
358
|
+
cx.pfac[p] = set()
|
|
359
|
+
cx.alive_p[p] = False
|
|
360
|
+
new_images = []
|
|
361
|
+
if opposite is not None:
|
|
362
|
+
# the facet of the cell on the opposite face, split as the joined facets
|
|
363
|
+
owner, ref_b = cx.fp[opposite][0], cx.fbox[opposite]
|
|
364
|
+
cx.kill_facet(opposite)
|
|
365
|
+
shift = np.zeros(3)
|
|
366
|
+
shift[d] = off[d] * cx.size[d]
|
|
367
|
+
back = tuple(-k for k in off)
|
|
368
|
+
for v in sorted({v for f in joined for v in cx.facets[f]} & set(moved)):
|
|
369
|
+
u = cx.add_vertex(cx.V[v] + shift)
|
|
370
|
+
images[v], images[u] = {off: u}, {back: v}
|
|
371
|
+
new_images += [v, u]
|
|
372
|
+
for f in joined: # the outward normal of the opposite face is reversed
|
|
373
|
+
cx.add_facet([images[v][off] for v in cx.facets[f]][::-1], [owner, -1], ref_b)
|
|
374
|
+
if all(cx.piece_ok(q, min_volume) for q in pieces if q != p and cx.alive_p[q]):
|
|
375
|
+
done += 1
|
|
376
|
+
else:
|
|
377
|
+
cx.restore(snap)
|
|
378
|
+
cx.discard_new(n_vertices, n_facets)
|
|
379
|
+
for v in new_images:
|
|
380
|
+
images.pop(v, None)
|
|
381
|
+
relabelled += _relabel(cx, p)
|
|
382
|
+
return done, relabelled
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def _contract(cx: _Complex, cluster: set, min_volume: float, images: dict) -> list | None:
|
|
386
|
+
"""Contract a set of vertices to one point, with their periodic images; the change is
|
|
387
|
+
kept if every piece it touches remains valid. Returns the vertices kept (the point
|
|
388
|
+
and its images), or None."""
|
|
389
|
+
planes = {v: cx.planes(v) for v in cluster}
|
|
390
|
+
union = set().union(*planes.values())
|
|
391
|
+
if len({d for d, _ in union}) < len(union):
|
|
392
|
+
return None # opposite faces of the box
|
|
393
|
+
most = max(len(s) for s in planes.values())
|
|
394
|
+
# the most constrained vertex, with the most periodic images
|
|
395
|
+
keep = min(cluster, key=lambda v: (-len(planes[v]), -len(images.get(v, {})), v))
|
|
396
|
+
if not all(s <= planes[keep] for s in planes.values()):
|
|
397
|
+
return None # on different faces of the box
|
|
398
|
+
# the point: the mean of the most constrained vertices, on their faces
|
|
399
|
+
target = cx.V[[v for v in cluster if len(planes[v]) == most]].mean(axis=0)
|
|
400
|
+
for d, side in union:
|
|
401
|
+
target[d] = cx.lower[d] if side == 0 else cx.upper[d]
|
|
402
|
+
groups = [(keep, [v for v in cluster if v != keep])]
|
|
403
|
+
if images and (union or cx.whole):
|
|
404
|
+
# a vertex of a face (of whole cells: any vertex) moves with its images, and the
|
|
405
|
+
# images merge alike
|
|
406
|
+
ik = images.get(keep, {})
|
|
407
|
+
on_faces = [images.get(v, {}) for v in cluster if v != keep and (planes[v] or cx.whole)]
|
|
408
|
+
if not all(set(iv) <= set(ik) for iv in on_faces):
|
|
409
|
+
return None # the images differ: the faces differ here
|
|
410
|
+
for off, image in ik.items():
|
|
411
|
+
groups.append((image, [iv[off] for iv in on_faces if off in iv]))
|
|
412
|
+
verts = {v for keep_v, gone in groups for v in [keep_v, *gone]}
|
|
413
|
+
pieces = _touching(cx, verts)
|
|
414
|
+
facets = set()
|
|
415
|
+
for q in pieces:
|
|
416
|
+
facets |= cx.pfac[q]
|
|
417
|
+
for v in verts:
|
|
418
|
+
facets |= cx.vfac[v]
|
|
419
|
+
snap = cx.snapshot(facets, pieces, verts)
|
|
420
|
+
origin = cx.V[keep].copy()
|
|
421
|
+
for keep_v, gone in groups:
|
|
422
|
+
x = target + (cx.V[keep_v] - origin) # the same move for the images
|
|
423
|
+
cx.V[keep_v] = x
|
|
424
|
+
for v in gone:
|
|
425
|
+
cx.merge(keep_v, v, x)
|
|
426
|
+
if all(cx.piece_ok(q, min_volume) for q in pieces if cx.alive_p[q] and cx.pfac[q]):
|
|
427
|
+
return [keep_v for keep_v, _ in groups]
|
|
428
|
+
cx.restore(snap)
|
|
429
|
+
return None
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def _neighbours(cx: _Complex, cluster: set) -> set:
|
|
433
|
+
out = set()
|
|
434
|
+
for v in cluster:
|
|
435
|
+
for f in cx.vfac[v]:
|
|
436
|
+
loop = cx.facets[f]
|
|
437
|
+
i = loop.index(v)
|
|
438
|
+
out.update((loop[i - 1], loop[(i + 1) % len(loop)]))
|
|
439
|
+
return out - cluster
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def _collapse_edges(
|
|
443
|
+
cx: _Complex, delta: float, min_volume: float, images: dict, max_cluster: int = 6
|
|
444
|
+
) -> int:
|
|
445
|
+
"""Contract the edges shorter than ``delta`` (with their periodic images), the
|
|
446
|
+
shortest first. When contracting an edge alone would leave an invalid piece (several
|
|
447
|
+
tiny edges around a small facet), its nearest neighbours are contracted with it, up to
|
|
448
|
+
``max_cluster`` vertices within ``delta`` of their centre."""
|
|
449
|
+
heap = []
|
|
450
|
+
|
|
451
|
+
def push(a, b):
|
|
452
|
+
length = float(np.linalg.norm(cx.V[a] - cx.V[b]))
|
|
453
|
+
if length < delta:
|
|
454
|
+
heapq.heappush(heap, (length, min(a, b), max(a, b)))
|
|
455
|
+
|
|
456
|
+
for f, loop in enumerate(cx.facets):
|
|
457
|
+
if cx.alive_f[f]:
|
|
458
|
+
for a, b in zip(loop, loop[1:] + loop[:1], strict=True):
|
|
459
|
+
push(a, b)
|
|
460
|
+
done = 0
|
|
461
|
+
while heap:
|
|
462
|
+
_, a, b = heapq.heappop(heap)
|
|
463
|
+
if a == b or not cx.vfac[a] or not cx.vfac[b]:
|
|
464
|
+
continue
|
|
465
|
+
if not any(b in cx.facets[f] for f in cx.vfac[a]):
|
|
466
|
+
continue # no longer an edge
|
|
467
|
+
cluster = {a, b}
|
|
468
|
+
kept = _contract(cx, cluster, min_volume, images)
|
|
469
|
+
while kept is None and len(cluster) < max_cluster:
|
|
470
|
+
centre = cx.V[list(cluster)].mean(axis=0)
|
|
471
|
+
near = _neighbours(cx, cluster)
|
|
472
|
+
if not near:
|
|
473
|
+
break
|
|
474
|
+
w = min(near, key=lambda v: float(np.linalg.norm(cx.V[v] - centre)))
|
|
475
|
+
if np.linalg.norm(cx.V[w] - centre) >= delta:
|
|
476
|
+
break
|
|
477
|
+
cluster.add(w)
|
|
478
|
+
kept = _contract(cx, cluster, min_volume, images)
|
|
479
|
+
if kept is None:
|
|
480
|
+
continue
|
|
481
|
+
done += len(cluster) - 1
|
|
482
|
+
for keep_v in kept:
|
|
483
|
+
for f in list(cx.vfac[keep_v]):
|
|
484
|
+
loop = cx.facets[f]
|
|
485
|
+
i = loop.index(keep_v)
|
|
486
|
+
push(keep_v, loop[i - 1])
|
|
487
|
+
push(keep_v, loop[(i + 1) % len(loop)])
|
|
488
|
+
return done
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def _fix_t_junctions(cx: _Complex) -> int:
|
|
492
|
+
"""Insert into every facet edge the vertices lying on it, so that neighbouring facets
|
|
493
|
+
are subdivided alike."""
|
|
494
|
+
used = sorted({v for f, loop in enumerate(cx.facets) if cx.alive_f[f] for v in loop})
|
|
495
|
+
if not used:
|
|
496
|
+
return 0
|
|
497
|
+
tree = cKDTree(cx.V[used])
|
|
498
|
+
added = 0
|
|
499
|
+
changed = True
|
|
500
|
+
while changed:
|
|
501
|
+
changed = False
|
|
502
|
+
for f, loop in enumerate(cx.facets):
|
|
503
|
+
if not cx.alive_f[f]:
|
|
504
|
+
continue
|
|
505
|
+
out = []
|
|
506
|
+
for a, b in zip(loop, loop[1:] + loop[:1], strict=True):
|
|
507
|
+
out.append(a)
|
|
508
|
+
pa, pb = cx.V[a], cx.V[b]
|
|
509
|
+
ab = pb - pa
|
|
510
|
+
length2 = float(ab @ ab)
|
|
511
|
+
near = tree.query_ball_point(0.5 * (pa + pb), 0.5 * np.sqrt(length2) + cx.tol)
|
|
512
|
+
inside = []
|
|
513
|
+
for k in near:
|
|
514
|
+
w = used[k]
|
|
515
|
+
if w in (a, b):
|
|
516
|
+
continue
|
|
517
|
+
t = float((cx.V[w] - pa) @ ab) / length2
|
|
518
|
+
if 0.0 < t < 1.0 and np.linalg.norm(pa + t * ab - cx.V[w]) <= 1e3 * cx.tol:
|
|
519
|
+
inside.append((t, w))
|
|
520
|
+
for _, w in sorted(inside):
|
|
521
|
+
if w not in out and w not in loop:
|
|
522
|
+
out.append(w)
|
|
523
|
+
cx.vfac[w].add(f)
|
|
524
|
+
added += 1
|
|
525
|
+
changed = True
|
|
526
|
+
cx.facets[f] = out
|
|
527
|
+
return added
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
def regularize(cx: CellComplex, delta: float) -> CellComplex:
|
|
531
|
+
"""Complex without the caps and edges smaller than ``delta`` (see the module)."""
|
|
532
|
+
if not delta > 0:
|
|
533
|
+
return cx
|
|
534
|
+
m = _Complex(cx)
|
|
535
|
+
min_volume = 1e-15 * float(np.prod(m.size))
|
|
536
|
+
images = _images(m) if cx.periodic else {}
|
|
537
|
+
caps, relabelled = (0, 0) if m.whole else _flatten_caps(m, delta, min_volume, images)
|
|
538
|
+
edges = _collapse_edges(m, delta, min_volume, images)
|
|
539
|
+
tj = _fix_t_junctions(m)
|
|
540
|
+
# compact
|
|
541
|
+
alive_f = [f for f in range(len(m.facets)) if m.alive_f[f]]
|
|
542
|
+
alive_p = [p for p in range(len(m.pfac)) if m.alive_p[p] and m.pfac[p]]
|
|
543
|
+
fmap = {f: k for k, f in enumerate(alive_f)}
|
|
544
|
+
pmap = {p: k for k, p in enumerate(alive_p)}
|
|
545
|
+
used = sorted({v for f in alive_f for v in m.facets[f]})
|
|
546
|
+
vmap = {v: k for k, v in enumerate(used)}
|
|
547
|
+
return CellComplex(
|
|
548
|
+
vertices=m.V[used],
|
|
549
|
+
facets=[np.array([vmap[v] for v in m.facets[f]], dtype=np.int64) for f in alive_f],
|
|
550
|
+
facet_pieces=np.array(
|
|
551
|
+
[[pmap[p] if p >= 0 else -1 for p in m.fp[f]] for f in alive_f], dtype=np.int64
|
|
552
|
+
),
|
|
553
|
+
facet_box=np.array([m.fbox[f] for f in alive_f], dtype=np.int64),
|
|
554
|
+
piece_cell=m.cell[alive_p],
|
|
555
|
+
piece_facets=[
|
|
556
|
+
np.array(sorted(fmap[f] for f in m.pfac[p]), dtype=np.int64) for p in alive_p
|
|
557
|
+
],
|
|
558
|
+
lower=cx.lower,
|
|
559
|
+
upper=cx.upper,
|
|
560
|
+
periodic=cx.periodic,
|
|
561
|
+
whole=cx.whole,
|
|
562
|
+
metadata={
|
|
563
|
+
**cx.metadata,
|
|
564
|
+
"regularization": float(delta),
|
|
565
|
+
"flattened_caps": caps,
|
|
566
|
+
"relabelled_caps": relabelled,
|
|
567
|
+
"contracted_edges": edges,
|
|
568
|
+
"t_junctions": tj,
|
|
569
|
+
},
|
|
570
|
+
)
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Triangulated surfaces extracted from level-set or phase images (marching cubes)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
from morphogen.image import VoxelImage
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class SurfaceMesh:
|
|
14
|
+
vertices: np.ndarray # (n, 3)
|
|
15
|
+
faces: np.ndarray # (m, 3), counter-clockwise seen from outside
|
|
16
|
+
|
|
17
|
+
def face_normals(self) -> np.ndarray:
|
|
18
|
+
v = self.vertices[self.faces]
|
|
19
|
+
n = np.cross(v[:, 1] - v[:, 0], v[:, 2] - v[:, 0])
|
|
20
|
+
norm = np.linalg.norm(n, axis=1, keepdims=True)
|
|
21
|
+
return n / np.where(norm > 0, norm, 1.0)
|
|
22
|
+
|
|
23
|
+
def area(self) -> float:
|
|
24
|
+
v = self.vertices[self.faces]
|
|
25
|
+
return float(
|
|
26
|
+
0.5 * np.linalg.norm(np.cross(v[:, 1] - v[:, 0], v[:, 2] - v[:, 0]), axis=1).sum()
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
def volume(self) -> float:
|
|
30
|
+
"""Enclosed volume (divergence theorem; positive for outward-oriented surfaces)."""
|
|
31
|
+
v = self.vertices[self.faces]
|
|
32
|
+
return float(np.einsum("ij,ij->i", v[:, 0], np.cross(v[:, 1], v[:, 2])).sum() / 6.0)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _marching_cubes():
|
|
36
|
+
try:
|
|
37
|
+
from skimage.measure import marching_cubes
|
|
38
|
+
except ImportError: # pragma: no cover - depends on the environment
|
|
39
|
+
raise ImportError(
|
|
40
|
+
"surface meshes need the optional 'scikit-image' package: "
|
|
41
|
+
"pip install 'morphogen[surface]'"
|
|
42
|
+
) from None
|
|
43
|
+
return marching_cubes
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def surface_mesh(
|
|
47
|
+
image: VoxelImage, *, level: float = 0.0, phase: int = 1, closed: bool = True
|
|
48
|
+
) -> SurfaceMesh:
|
|
49
|
+
"""Surface of phase 1 from a level-set image (negative inside) or a phase image.
|
|
50
|
+
|
|
51
|
+
Phase images (integers) and partial-volume images (floats named ``fraction``) are
|
|
52
|
+
converted to ``0.5 - indicator``. With ``closed=True`` the solid is closed by caps on
|
|
53
|
+
the faces of the box (watertight surface, e.g. for additive manufacturing).
|
|
54
|
+
"""
|
|
55
|
+
marching_cubes = _marching_cubes()
|
|
56
|
+
data = image.data
|
|
57
|
+
if data.dtype.kind in "iub":
|
|
58
|
+
field = 0.5 - (data == phase).astype(np.float32)
|
|
59
|
+
level = 0.0
|
|
60
|
+
elif image.name == "fraction":
|
|
61
|
+
field = 0.5 - data.astype(np.float32)
|
|
62
|
+
level = 0.0
|
|
63
|
+
else:
|
|
64
|
+
field = data.astype(np.float32)
|
|
65
|
+
# values exactly at the level put vertices on grid nodes, where several edges then
|
|
66
|
+
# share a position and the surface is no longer manifold: push them slightly outside
|
|
67
|
+
# (far enough for the vertices to stay distinct in single precision)
|
|
68
|
+
scale = float(np.abs(field).max()) if field.size else 1.0
|
|
69
|
+
field = np.where(field == level, np.float32(level + 1e-3 * max(scale, 1e-30)), field)
|
|
70
|
+
spacing = np.asarray(image.spacing, dtype=float)
|
|
71
|
+
origin = np.asarray(image.origin, dtype=float) + 0.5 * spacing
|
|
72
|
+
if closed:
|
|
73
|
+
outside = np.float32(max(float(np.abs(field).max()), 1.0) + abs(level) + 1.0)
|
|
74
|
+
field = np.pad(field, 1, mode="constant", constant_values=outside)
|
|
75
|
+
origin = origin - spacing
|
|
76
|
+
verts, faces, _, _ = marching_cubes(
|
|
77
|
+
field,
|
|
78
|
+
level=level,
|
|
79
|
+
spacing=tuple(spacing),
|
|
80
|
+
gradient_direction="ascent",
|
|
81
|
+
allow_degenerate=False,
|
|
82
|
+
)
|
|
83
|
+
verts = verts + origin
|
|
84
|
+
if closed:
|
|
85
|
+
# cap vertices lie on edges joining the outer voxel centres to the padding:
|
|
86
|
+
# move them onto the faces of the box
|
|
87
|
+
lower = np.asarray(image.origin, dtype=float)
|
|
88
|
+
upper = lower + spacing * np.array(image.shape)
|
|
89
|
+
first = lower + 0.5 * spacing
|
|
90
|
+
last = upper - 0.5 * spacing
|
|
91
|
+
eps = 1e-9 * spacing
|
|
92
|
+
verts = np.where(verts < first - eps, lower, verts)
|
|
93
|
+
verts = np.where(verts > last + eps, upper, verts)
|
|
94
|
+
mesh = SurfaceMesh(verts, faces.astype(np.int64))
|
|
95
|
+
if mesh.volume() < 0:
|
|
96
|
+
mesh = SurfaceMesh(verts, faces[:, ::-1].astype(np.int64))
|
|
97
|
+
return mesh
|