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,677 @@
|
|
|
1
|
+
"""Exact cells of Voronoi and Laguerre (power) tessellations restricted to a box.
|
|
2
|
+
|
|
3
|
+
The cell of germ ``g_i`` (weight ``w_i``) is the convex polyhedron of the points whose
|
|
4
|
+
power distance ``|x - g_i|^2 - w_i`` is the smallest: the intersection of the
|
|
5
|
+
half-spaces ``2 (g_j - g_i) . x <= |g_j|^2 - |g_i|^2 - w_j + w_i`` bounded by the
|
|
6
|
+
bisector planes of its neighbours. Each cell is computed as a half-space intersection
|
|
7
|
+
(Qhull) with the planes of nearby germs, then checked: no other germ may be closer to one
|
|
8
|
+
of its vertices, otherwise the missing germs are added and the cell computed again.
|
|
9
|
+
|
|
10
|
+
Restricted to the box, a tessellation is a complex of convex *pieces*: one per cell, or
|
|
11
|
+
several for the cells of a periodic tessellation that cross the faces of the box (one
|
|
12
|
+
piece per periodic image). Pieces share their *facets*: bisector polygons between two
|
|
13
|
+
pieces, or polygons on the faces of the box. Vertices computed by neighbouring pieces are
|
|
14
|
+
merged, so that the facets are shared exactly; for periodic tessellations, the vertices
|
|
15
|
+
of opposite faces of the box are made translates of each other.
|
|
16
|
+
|
|
17
|
+
A periodic tessellation can also be taken as a set of *whole cells* (:func:`periodic_cells`):
|
|
18
|
+
each cell once, around its germ in the box, uncut. Their union fills the volume of the
|
|
19
|
+
box and tiles space by the translations of the box; its boundary is made of facets
|
|
20
|
+
between a cell and a translate of another one, which come in pairs of translates, so
|
|
21
|
+
that a mesh of the union naturally has matching nodes on them (periodization at the
|
|
22
|
+
design rather than at the meshing).
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import itertools
|
|
28
|
+
import math
|
|
29
|
+
from dataclasses import dataclass, field
|
|
30
|
+
|
|
31
|
+
import numpy as np
|
|
32
|
+
from scipy.optimize import linprog
|
|
33
|
+
from scipy.sparse import coo_matrix
|
|
34
|
+
from scipy.sparse.csgraph import connected_components
|
|
35
|
+
from scipy.spatial import HalfspaceIntersection, QhullError, cKDTree
|
|
36
|
+
|
|
37
|
+
#: Box faces: x0, x1, y0, y1, z0, z1 (references 1 to 6).
|
|
38
|
+
BOX_FACES = ((0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1))
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass
|
|
42
|
+
class CellComplex:
|
|
43
|
+
"""Convex pieces of the cells of a tessellation restricted to a box.
|
|
44
|
+
|
|
45
|
+
``facets[f]`` is a loop of vertex indices, counter-clockwise around the normal that
|
|
46
|
+
points from piece ``facet_pieces[f, 0]`` to piece ``facet_pieces[f, 1]`` (``-1``:
|
|
47
|
+
outside the box, for the facets on its faces). ``facet_box[f]`` is 0 inside the box,
|
|
48
|
+
1-6 on the faces x0, x1, y0, y1, z0, z1. ``piece_cell[p]`` is the cell (germ index)
|
|
49
|
+
of piece ``p``, ``piece_facets[p]`` its facets.
|
|
50
|
+
|
|
51
|
+
``whole``: the pieces are the whole cells of a periodic tessellation
|
|
52
|
+
(:func:`periodic_cells`); the facets with no second piece then bound their union, and
|
|
53
|
+
``facet_shift[f]`` is the translation (in box lengths) of the cell beyond them.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
vertices: np.ndarray
|
|
57
|
+
facets: list[np.ndarray]
|
|
58
|
+
facet_pieces: np.ndarray
|
|
59
|
+
facet_box: np.ndarray
|
|
60
|
+
piece_cell: np.ndarray
|
|
61
|
+
piece_facets: list[np.ndarray]
|
|
62
|
+
lower: np.ndarray
|
|
63
|
+
upper: np.ndarray
|
|
64
|
+
periodic: bool = False
|
|
65
|
+
metadata: dict = field(default_factory=dict)
|
|
66
|
+
whole: bool = False
|
|
67
|
+
facet_shift: np.ndarray | None = None
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def n_vertices(self) -> int:
|
|
71
|
+
return len(self.vertices)
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def n_facets(self) -> int:
|
|
75
|
+
return len(self.facets)
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
def n_pieces(self) -> int:
|
|
79
|
+
return len(self.piece_cell)
|
|
80
|
+
|
|
81
|
+
def facet_vectors(self) -> tuple[np.ndarray, np.ndarray]:
|
|
82
|
+
"""Area vectors (normal times area, oriented as the loops) and centroids."""
|
|
83
|
+
area = np.zeros((self.n_facets, 3))
|
|
84
|
+
centre = np.zeros((self.n_facets, 3))
|
|
85
|
+
for f, loop in enumerate(self.facets):
|
|
86
|
+
p = self.vertices[loop]
|
|
87
|
+
c = p.mean(axis=0)
|
|
88
|
+
q = np.roll(p, -1, axis=0)
|
|
89
|
+
cross = np.cross(p - c, q - c)
|
|
90
|
+
a = 0.5 * cross.sum(axis=0)
|
|
91
|
+
tri_area = 0.5 * np.linalg.norm(cross, axis=1)
|
|
92
|
+
total = tri_area.sum()
|
|
93
|
+
area[f] = a
|
|
94
|
+
# area-weighted centroid of the fan triangles
|
|
95
|
+
centre[f] = (
|
|
96
|
+
((p + q + c) / 3.0 * tri_area[:, None]).sum(axis=0) / total if total > 0 else c
|
|
97
|
+
)
|
|
98
|
+
return area, centre
|
|
99
|
+
|
|
100
|
+
def piece_volumes(self) -> np.ndarray:
|
|
101
|
+
"""Volumes of the pieces (divergence theorem over their facets)."""
|
|
102
|
+
area, centre = self.facet_vectors()
|
|
103
|
+
flux = np.einsum("ij,ij->i", area, centre) / 3.0
|
|
104
|
+
vol = np.zeros(self.n_pieces)
|
|
105
|
+
np.add.at(vol, self.facet_pieces[:, 0], flux)
|
|
106
|
+
inner = self.facet_pieces[:, 1] >= 0
|
|
107
|
+
np.add.at(vol, self.facet_pieces[inner, 1], -flux[inner])
|
|
108
|
+
return vol
|
|
109
|
+
|
|
110
|
+
def cell_volumes(self, n_cells: int | None = None) -> np.ndarray:
|
|
111
|
+
"""Volume of each cell inside the box (summed over its pieces)."""
|
|
112
|
+
n = int(self.piece_cell.max()) + 1 if n_cells is None else int(n_cells)
|
|
113
|
+
out = np.zeros(n)
|
|
114
|
+
np.add.at(out, self.piece_cell, self.piece_volumes())
|
|
115
|
+
return out
|
|
116
|
+
|
|
117
|
+
def grain_boundary_area(self) -> float:
|
|
118
|
+
"""Area of the facets between different cells."""
|
|
119
|
+
area, _ = self.facet_vectors()
|
|
120
|
+
a, b = self.facet_pieces[:, 0], self.facet_pieces[:, 1]
|
|
121
|
+
inner = (b >= 0) & (self.piece_cell[a] != self.piece_cell[np.maximum(b, 0)])
|
|
122
|
+
return float(np.linalg.norm(area[inner], axis=1).sum())
|
|
123
|
+
|
|
124
|
+
def interface_facets(self) -> np.ndarray:
|
|
125
|
+
"""Facets between pieces of different cells (grain boundaries)."""
|
|
126
|
+
a, b = self.facet_pieces[:, 0], self.facet_pieces[:, 1]
|
|
127
|
+
return np.flatnonzero((b >= 0) & (self.piece_cell[a] != self.piece_cell[np.maximum(b, 0)]))
|
|
128
|
+
|
|
129
|
+
def edges(self) -> np.ndarray:
|
|
130
|
+
"""Unique edges (sorted vertex pairs) of the facets."""
|
|
131
|
+
pairs = [np.stack([loop, np.roll(loop, -1)], axis=1) for loop in self.facets]
|
|
132
|
+
e = np.sort(np.concatenate(pairs), axis=1)
|
|
133
|
+
return np.unique(e, axis=0)
|
|
134
|
+
|
|
135
|
+
def summary(self) -> dict:
|
|
136
|
+
e = self.edges()
|
|
137
|
+
lengths = np.linalg.norm(self.vertices[e[:, 0]] - self.vertices[e[:, 1]], axis=1)
|
|
138
|
+
return {
|
|
139
|
+
"n_cells": int(np.unique(self.piece_cell).size),
|
|
140
|
+
"n_pieces": self.n_pieces,
|
|
141
|
+
"n_facets": self.n_facets,
|
|
142
|
+
"n_vertices": self.n_vertices,
|
|
143
|
+
"shortest_edge": float(lengths.min()) if lengths.size else float("nan"),
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
# -- geometry of one piece -------------------------------------------------------------------
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _chebyshev_centre(a: np.ndarray, b: np.ndarray) -> tuple[np.ndarray, float]:
|
|
151
|
+
"""Centre and radius of the largest ball inside ``a x <= b``."""
|
|
152
|
+
norms = np.linalg.norm(a, axis=1)
|
|
153
|
+
res = linprog(
|
|
154
|
+
c=[0.0, 0.0, 0.0, -1.0],
|
|
155
|
+
A_ub=np.column_stack([a, norms]),
|
|
156
|
+
b_ub=b,
|
|
157
|
+
bounds=[(None, None)] * 3 + [(0.0, None)],
|
|
158
|
+
method="highs",
|
|
159
|
+
)
|
|
160
|
+
if res.status != 0:
|
|
161
|
+
return np.zeros(3), 0.0
|
|
162
|
+
return res.x[:3], float(res.x[3])
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _loop_on_plane(points: np.ndarray, normal: np.ndarray) -> np.ndarray:
|
|
166
|
+
"""Order of planar points counter-clockwise around ``normal``."""
|
|
167
|
+
c = points.mean(axis=0)
|
|
168
|
+
u = points[0] - c
|
|
169
|
+
if np.linalg.norm(u) < 1e-300:
|
|
170
|
+
u = np.array([1.0, 0.0, 0.0])
|
|
171
|
+
n = normal / np.linalg.norm(normal)
|
|
172
|
+
u = u - n * (u @ n)
|
|
173
|
+
if np.linalg.norm(u) < 1e-300:
|
|
174
|
+
u = np.cross(n, [1.0, 0.0, 0.0])
|
|
175
|
+
if np.linalg.norm(u) < 1e-12:
|
|
176
|
+
u = np.cross(n, [0.0, 1.0, 0.0])
|
|
177
|
+
u /= np.linalg.norm(u)
|
|
178
|
+
v = np.cross(n, u)
|
|
179
|
+
d = points - c
|
|
180
|
+
return np.argsort(np.arctan2(d @ v, d @ u), kind="stable")
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _piece(a: np.ndarray, b: np.ndarray, interior: np.ndarray, tol: float):
|
|
184
|
+
"""Vertices of ``a x <= b`` and, for each plane, its facet (vertex indices ordered
|
|
185
|
+
counter-clockwise around the outward normal ``a``), or ``None`` if empty."""
|
|
186
|
+
try:
|
|
187
|
+
hs = HalfspaceIntersection(np.column_stack([a, -b]), interior)
|
|
188
|
+
except QhullError:
|
|
189
|
+
try:
|
|
190
|
+
hs = HalfspaceIntersection(np.column_stack([a, -b]), interior, qhull_options="QJ")
|
|
191
|
+
except QhullError:
|
|
192
|
+
return None
|
|
193
|
+
pts = hs.intersections
|
|
194
|
+
# merge duplicates (degenerate vertices are produced once per simplicial facet)
|
|
195
|
+
labels = _merge_points(pts, tol)
|
|
196
|
+
n_v = int(labels.max()) + 1
|
|
197
|
+
sums = np.zeros((n_v, 3))
|
|
198
|
+
np.add.at(sums, labels, pts)
|
|
199
|
+
verts = sums / np.bincount(labels, minlength=n_v)[:, None]
|
|
200
|
+
norms = np.linalg.norm(a, axis=1)
|
|
201
|
+
dist = (verts @ a.T - b) / norms # (n_vertices, n_planes), <= 0 inside
|
|
202
|
+
facets = {}
|
|
203
|
+
for k in range(len(b)):
|
|
204
|
+
on = np.flatnonzero(np.abs(dist[:, k]) <= 4.0 * tol)
|
|
205
|
+
if on.size >= 3:
|
|
206
|
+
loop = on[_loop_on_plane(verts[on], a[k])]
|
|
207
|
+
facets[k] = loop
|
|
208
|
+
if len(facets) < 4:
|
|
209
|
+
return None
|
|
210
|
+
return verts, facets
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
# -- the complex -----------------------------------------------------------------------------
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
class _UnionFind:
|
|
217
|
+
def __init__(self, n: int):
|
|
218
|
+
self.parent = np.arange(n)
|
|
219
|
+
|
|
220
|
+
def find(self, i: int) -> int:
|
|
221
|
+
root = i
|
|
222
|
+
while self.parent[root] != root:
|
|
223
|
+
root = self.parent[root]
|
|
224
|
+
while self.parent[i] != root:
|
|
225
|
+
self.parent[i], i = root, self.parent[i]
|
|
226
|
+
return root
|
|
227
|
+
|
|
228
|
+
def union(self, i: int, j: int) -> None:
|
|
229
|
+
ri, rj = self.find(i), self.find(j)
|
|
230
|
+
if ri != rj:
|
|
231
|
+
self.parent[max(ri, rj)] = min(ri, rj)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _merge_points(points: np.ndarray, tol: float) -> np.ndarray:
|
|
235
|
+
"""Cluster index of each point (points closer than ``tol`` are merged)."""
|
|
236
|
+
if len(points) == 0:
|
|
237
|
+
return np.zeros(0, dtype=np.int64)
|
|
238
|
+
pairs = cKDTree(points).query_pairs(tol, output_type="ndarray")
|
|
239
|
+
n = len(points)
|
|
240
|
+
graph = coo_matrix((np.ones(len(pairs)), (pairs[:, 0], pairs[:, 1])), shape=(n, n))
|
|
241
|
+
_, labels = connected_components(graph, directed=False)
|
|
242
|
+
return labels
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def power_complex(
|
|
246
|
+
germs,
|
|
247
|
+
weights=None,
|
|
248
|
+
lower=(0.0, 0.0, 0.0),
|
|
249
|
+
upper=(1.0, 1.0, 1.0),
|
|
250
|
+
periodic: bool = False,
|
|
251
|
+
*,
|
|
252
|
+
neighbours: int = 30,
|
|
253
|
+
) -> CellComplex:
|
|
254
|
+
"""Exact cells of the power diagram of ``germs`` (Voronoi without ``weights``)
|
|
255
|
+
restricted to the box ``[lower, upper]``, periodic or not."""
|
|
256
|
+
lower = np.asarray(lower, dtype=float)
|
|
257
|
+
upper = np.asarray(upper, dtype=float)
|
|
258
|
+
size = upper - lower
|
|
259
|
+
g = np.asarray(germs, dtype=float).reshape(-1, 3) - lower
|
|
260
|
+
n = len(g)
|
|
261
|
+
if n == 0:
|
|
262
|
+
raise ValueError("power_complex: no germs")
|
|
263
|
+
w = np.zeros(n) if weights is None else np.asarray(weights, dtype=float).reshape(n)
|
|
264
|
+
scale = float(size.max())
|
|
265
|
+
tol = 1e-9 * scale
|
|
266
|
+
if periodic:
|
|
267
|
+
g = np.mod(g, size)
|
|
268
|
+
shifts = np.array(list(itertools.product((-1, 0, 1), repeat=3)), dtype=float)
|
|
269
|
+
pts = (g[None, :, :] + shifts[:, None, :] * size).reshape(-1, 3)
|
|
270
|
+
ids = np.tile(np.arange(n), len(shifts))
|
|
271
|
+
wts = np.tile(w, len(shifts))
|
|
272
|
+
else:
|
|
273
|
+
pts, ids, wts = g, np.arange(n), w
|
|
274
|
+
wmax = float(wts.max())
|
|
275
|
+
lift = np.sqrt(np.maximum(wmax - wts, 0.0))
|
|
276
|
+
tree = cKDTree(np.column_stack([pts, lift]))
|
|
277
|
+
# largest power distance from a point of the box to its cell: bounds the germs whose
|
|
278
|
+
# cells reach the box (sampled on a grid, plus the sampling error)
|
|
279
|
+
m = max(4, min(40, round(2.0 * n ** (1.0 / 3.0)) + 4))
|
|
280
|
+
axes = [np.linspace(0.0, s, m) for s in size]
|
|
281
|
+
grid = np.stack(np.meshgrid(*axes, indexing="ij"), axis=-1).reshape(-1, 3)
|
|
282
|
+
d, _ = tree.query(np.column_stack([grid, np.zeros(len(grid))]))
|
|
283
|
+
power_max = float(np.max(d**2)) - wmax
|
|
284
|
+
spacing = float(np.linalg.norm(size / (m - 1)))
|
|
285
|
+
reach = math.sqrt(max(power_max + wmax, 0.0)) + spacing
|
|
286
|
+
outside = np.maximum(np.maximum(-pts, pts - size), 0.0)
|
|
287
|
+
candidates = np.flatnonzero(np.linalg.norm(outside, axis=1) <= reach + tol)
|
|
288
|
+
box_a = np.array([[-1, 0, 0], [1, 0, 0], [0, -1, 0], [0, 1, 0], [0, 0, -1], [0, 0, 1]], float)
|
|
289
|
+
box_b = np.array([0.0, size[0], 0.0, size[1], 0.0, size[2]])
|
|
290
|
+
k = min(neighbours, len(pts) - 1)
|
|
291
|
+
raw = [] # (candidate, vertices, {plane key: loop})
|
|
292
|
+
for c in candidates:
|
|
293
|
+
pc, wc = pts[c], wts[c]
|
|
294
|
+
_, near = tree.query(np.concatenate([pc, [lift[c]]]), k=k + 1)
|
|
295
|
+
near = [j for j in np.atleast_1d(near) if j != c and j < len(pts)]
|
|
296
|
+
while True:
|
|
297
|
+
nb = np.asarray(near, dtype=np.int64)
|
|
298
|
+
a = np.vstack([2.0 * (pts[nb] - pc), box_a]) if nb.size else box_a.copy()
|
|
299
|
+
b = np.concatenate(
|
|
300
|
+
[(pts[nb] ** 2).sum(axis=1) - pc @ pc - wts[nb] + wc, box_b] if nb.size else [box_b]
|
|
301
|
+
)
|
|
302
|
+
inside = (
|
|
303
|
+
np.all(pc > tol)
|
|
304
|
+
and np.all(pc < size - tol)
|
|
305
|
+
and (nb.size == 0 or np.all(a[: nb.size] @ pc < b[: nb.size] - tol * scale))
|
|
306
|
+
)
|
|
307
|
+
if inside:
|
|
308
|
+
centre, radius = pc, 1.0
|
|
309
|
+
else:
|
|
310
|
+
centre, radius = _chebyshev_centre(a, b)
|
|
311
|
+
if radius <= 10.0 * tol:
|
|
312
|
+
piece = None
|
|
313
|
+
break
|
|
314
|
+
piece = _piece(a, b, centre, tol)
|
|
315
|
+
if piece is None:
|
|
316
|
+
break
|
|
317
|
+
verts, _ = piece
|
|
318
|
+
# a vertex closer (in power distance) to another germ: that germ was missing
|
|
319
|
+
dist, owner = tree.query(np.column_stack([verts, np.zeros(len(verts))]))
|
|
320
|
+
own = ((verts - pc) ** 2).sum(axis=1) - wc + wmax
|
|
321
|
+
missing = set(
|
|
322
|
+
int(o)
|
|
323
|
+
for o, dd, oo in zip(owner, dist**2, own, strict=True)
|
|
324
|
+
if dd < oo - 1e-9 * scale**2 and o != c
|
|
325
|
+
)
|
|
326
|
+
missing -= set(near)
|
|
327
|
+
if not missing:
|
|
328
|
+
break
|
|
329
|
+
near += sorted(missing)
|
|
330
|
+
if piece is None:
|
|
331
|
+
continue
|
|
332
|
+
verts, facets = piece
|
|
333
|
+
keyed = {}
|
|
334
|
+
for plane, loop in facets.items():
|
|
335
|
+
key = ("n", int(nb[plane])) if plane < nb.size else ("b", plane - nb.size + 1)
|
|
336
|
+
keyed[key] = loop
|
|
337
|
+
raw.append((int(c), verts, keyed))
|
|
338
|
+
return _assemble(raw, ids, size, lower, periodic, tol)
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def periodic_cells(
|
|
342
|
+
germs,
|
|
343
|
+
weights=None,
|
|
344
|
+
lower=(0.0, 0.0, 0.0),
|
|
345
|
+
upper=(1.0, 1.0, 1.0),
|
|
346
|
+
*,
|
|
347
|
+
neighbours: int = 30,
|
|
348
|
+
) -> CellComplex:
|
|
349
|
+
"""Whole cells of the periodic power diagram of ``germs`` (Voronoi without
|
|
350
|
+
``weights``) of period ``upper - lower``: one piece per non-empty cell, around its germ
|
|
351
|
+
brought into the box (see the module). Facets between two cells of the set are shared;
|
|
352
|
+
the others bound the union and come in pairs of translates."""
|
|
353
|
+
lower = np.asarray(lower, dtype=float)
|
|
354
|
+
upper = np.asarray(upper, dtype=float)
|
|
355
|
+
size = upper - lower
|
|
356
|
+
g = np.mod(np.asarray(germs, dtype=float).reshape(-1, 3) - lower, size)
|
|
357
|
+
g[g >= size] = 0.0
|
|
358
|
+
n = len(g)
|
|
359
|
+
if n == 0:
|
|
360
|
+
raise ValueError("periodic_cells: no germs")
|
|
361
|
+
w = np.zeros(n) if weights is None else np.asarray(weights, dtype=float).reshape(n)
|
|
362
|
+
scale = float(size.max())
|
|
363
|
+
tol = 1e-9 * scale
|
|
364
|
+
shifts = np.array(list(itertools.product((-1, 0, 1), repeat=3)), dtype=np.int64)
|
|
365
|
+
pts = (g[None, :, :] + shifts[:, None, :] * size).reshape(-1, 3)
|
|
366
|
+
ids = np.tile(np.arange(n), len(shifts))
|
|
367
|
+
image = np.repeat(shifts, n, axis=0)
|
|
368
|
+
wts = np.tile(w, len(shifts))
|
|
369
|
+
zero = int(np.flatnonzero(np.all(shifts == 0, axis=1))[0])
|
|
370
|
+
wmax = float(wts.max())
|
|
371
|
+
lift = np.sqrt(np.maximum(wmax - wts, 0.0))
|
|
372
|
+
tree = cKDTree(np.column_stack([pts, lift]))
|
|
373
|
+
box_a = np.array([[-1, 0, 0], [1, 0, 0], [0, -1, 0], [0, 1, 0], [0, 0, -1], [0, 0, 1]], float)
|
|
374
|
+
voronoi = bool(np.all(w == w[0]))
|
|
375
|
+
raw = []
|
|
376
|
+
for c in range(n):
|
|
377
|
+
own_index = zero * n + c
|
|
378
|
+
pc, wc = pts[own_index], wts[own_index]
|
|
379
|
+
# a box around the germ keeps the first intersections bounded; it must not bound
|
|
380
|
+
# the cell in the end
|
|
381
|
+
box_b = np.concatenate(
|
|
382
|
+
[[-(pc[d] - 2.0 * size[d]), pc[d] + 2.0 * size[d]] for d in range(3)]
|
|
383
|
+
)
|
|
384
|
+
k = min(neighbours, len(pts) - 1)
|
|
385
|
+
_, near = tree.query(np.concatenate([pc, [lift[own_index]]]), k=k + 1)
|
|
386
|
+
near = [int(j) for j in np.atleast_1d(near) if j != own_index and j < len(pts)]
|
|
387
|
+
piece = None
|
|
388
|
+
for _ in range(20):
|
|
389
|
+
nb = np.asarray(near, dtype=np.int64)
|
|
390
|
+
a = np.vstack([2.0 * (pts[nb] - pc), box_a])
|
|
391
|
+
b = np.concatenate([(pts[nb] ** 2).sum(axis=1) - pc @ pc - wts[nb] + wc, box_b])
|
|
392
|
+
centre, radius = (pc, 1.0) if voronoi else _chebyshev_centre(a, b)
|
|
393
|
+
if radius <= 10.0 * tol:
|
|
394
|
+
piece = None
|
|
395
|
+
break
|
|
396
|
+
piece = _piece(a, b, centre, tol)
|
|
397
|
+
if piece is None:
|
|
398
|
+
break
|
|
399
|
+
verts, facets = piece
|
|
400
|
+
dist, owner = tree.query(np.column_stack([verts, np.zeros(len(verts))]))
|
|
401
|
+
own = ((verts - pc) ** 2).sum(axis=1) - wc + wmax
|
|
402
|
+
missing = {
|
|
403
|
+
int(o)
|
|
404
|
+
for o, dd, oo in zip(owner, dist**2, own, strict=True)
|
|
405
|
+
if dd < oo - 1e-9 * scale**2 and o != own_index
|
|
406
|
+
} - set(near)
|
|
407
|
+
bounded = all(plane < nb.size for plane in facets)
|
|
408
|
+
if not missing and bounded:
|
|
409
|
+
break
|
|
410
|
+
if missing:
|
|
411
|
+
near += sorted(missing)
|
|
412
|
+
else: # the box bounds the cell: more neighbours
|
|
413
|
+
k = min(2 * k, len(pts) - 1)
|
|
414
|
+
_, more = tree.query(np.concatenate([pc, [lift[own_index]]]), k=k + 1)
|
|
415
|
+
near = [int(j) for j in np.atleast_1d(more) if j != own_index and j < len(pts)]
|
|
416
|
+
else:
|
|
417
|
+
raise RuntimeError("periodic_cells: a cell could not be closed by its neighbours")
|
|
418
|
+
if piece is None:
|
|
419
|
+
continue # an empty Laguerre cell
|
|
420
|
+
verts, facets = piece
|
|
421
|
+
keyed = {int(nb[plane]): loop for plane, loop in facets.items() if plane < nb.size}
|
|
422
|
+
raw.append((c, verts, keyed))
|
|
423
|
+
return _assemble_whole(raw, ids, image, size, lower, tol)
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def _merge_periodic(points: np.ndarray, size: np.ndarray, tol: float) -> np.ndarray:
|
|
427
|
+
"""Cluster index of points on the torus of period ``size`` (closer than ``tol``)."""
|
|
428
|
+
pairs = cKDTree(points, boxsize=size).query_pairs(tol, output_type="ndarray")
|
|
429
|
+
n = len(points)
|
|
430
|
+
graph = coo_matrix((np.ones(len(pairs)), (pairs[:, 0], pairs[:, 1])), shape=(n, n))
|
|
431
|
+
return connected_components(graph, directed=False)[1]
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def torus_classes(points: np.ndarray, lower, size, tol: float) -> tuple[np.ndarray, np.ndarray]:
|
|
435
|
+
"""Points that are translates of each other by the periods ``size``: the class of
|
|
436
|
+
each point and its translation (in periods) from the first point of its class."""
|
|
437
|
+
p = np.asarray(points, dtype=float) - np.asarray(lower, dtype=float)
|
|
438
|
+
size = np.asarray(size, dtype=float)
|
|
439
|
+
wrapped = np.mod(p, size)
|
|
440
|
+
wrapped[wrapped >= size] = 0.0
|
|
441
|
+
labels = _merge_periodic(wrapped, size, tol)
|
|
442
|
+
first = np.full(int(labels.max()) + 1 if len(labels) else 0, -1)
|
|
443
|
+
first[labels[::-1]] = np.arange(len(labels))[::-1]
|
|
444
|
+
shift = np.rint((p - p[first[labels]]) / size).astype(np.int64)
|
|
445
|
+
return labels, shift
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def _assemble_whole(raw, ids, image, size, lower, tol) -> CellComplex:
|
|
449
|
+
"""Vertices and facets of whole cells: the vertices are translates of torus points by
|
|
450
|
+
whole periods, so that the facets bounding the union are exact translates."""
|
|
451
|
+
all_pts = np.concatenate([v for _, v, _ in raw])
|
|
452
|
+
offsets = np.cumsum([0] + [len(v) for _, v, _ in raw])
|
|
453
|
+
labels, shift = torus_classes(all_pts, np.zeros(3), size, 50.0 * tol)
|
|
454
|
+
n_lab = int(labels.max()) + 1
|
|
455
|
+
# one position per torus point (the mean of its copies brought back by their shifts)
|
|
456
|
+
base = all_pts - shift * size
|
|
457
|
+
sums = np.zeros((n_lab, 3))
|
|
458
|
+
np.add.at(sums, labels, base)
|
|
459
|
+
canonical = sums / np.bincount(labels, minlength=n_lab)[:, None]
|
|
460
|
+
key_index: dict = {}
|
|
461
|
+
vertex_of = np.empty(len(all_pts), dtype=np.int64)
|
|
462
|
+
for i, (lab, s) in enumerate(zip(labels.tolist(), map(tuple, shift.tolist()), strict=True)):
|
|
463
|
+
vertex_of[i] = key_index.setdefault((lab, s), len(key_index))
|
|
464
|
+
verts = np.empty((len(key_index), 3))
|
|
465
|
+
for (lab, s), v in key_index.items():
|
|
466
|
+
verts[v] = canonical[lab] + np.asarray(s) * size
|
|
467
|
+
piece_of = {c: p for p, (c, _, _) in enumerate(raw)}
|
|
468
|
+
facet_index: dict = {}
|
|
469
|
+
facets: list[np.ndarray] = []
|
|
470
|
+
facet_pieces: list[list[int]] = []
|
|
471
|
+
facet_shift: list[tuple] = []
|
|
472
|
+
piece_facets: list[list[int]] = []
|
|
473
|
+
for p, (c, _, keyed) in enumerate(raw):
|
|
474
|
+
mine = []
|
|
475
|
+
for j, loop in keyed.items():
|
|
476
|
+
gl = vertex_of[offsets[p] + loop]
|
|
477
|
+
gl = gl[np.concatenate([[True], gl[1:] != gl[:-1]])]
|
|
478
|
+
if gl.size > 1 and gl[0] == gl[-1]:
|
|
479
|
+
gl = gl[:-1]
|
|
480
|
+
if np.unique(gl).size < 3:
|
|
481
|
+
continue
|
|
482
|
+
other, s = int(ids[j]), tuple(int(v) for v in image[j])
|
|
483
|
+
if s == (0, 0, 0):
|
|
484
|
+
key = ("in", min(c, other), max(c, other))
|
|
485
|
+
if key in facet_index:
|
|
486
|
+
f = facet_index[key]
|
|
487
|
+
facet_pieces[f][1] = p
|
|
488
|
+
merged = np.union1d(facets[f], gl)
|
|
489
|
+
if merged.size != np.unique(facets[f]).size:
|
|
490
|
+
facets[f] = _reloop(verts, merged, facets[f])
|
|
491
|
+
mine.append(f)
|
|
492
|
+
continue
|
|
493
|
+
facet_pieces.append([p, -2 if other in piece_of else -3])
|
|
494
|
+
else:
|
|
495
|
+
key = ("out", c, other, s)
|
|
496
|
+
facet_pieces.append([p, -1])
|
|
497
|
+
f = len(facets)
|
|
498
|
+
facet_index[key] = f
|
|
499
|
+
facets.append(gl)
|
|
500
|
+
facet_shift.append(s)
|
|
501
|
+
mine.append(f)
|
|
502
|
+
piece_facets.append(mine)
|
|
503
|
+
facet_pieces = np.array(facet_pieces, dtype=np.int64)
|
|
504
|
+
# boundary facets without their translate, interior facets with one side: slivers
|
|
505
|
+
# of degenerate vertices (dropped if their area is below the tolerance)
|
|
506
|
+
drop = set(np.flatnonzero(facet_pieces[:, 1] < -1).tolist())
|
|
507
|
+
for key, f in facet_index.items():
|
|
508
|
+
if (
|
|
509
|
+
key[0] == "out"
|
|
510
|
+
and ("out", key[2], key[1], tuple(-v for v in key[3])) not in facet_index
|
|
511
|
+
):
|
|
512
|
+
drop.add(f)
|
|
513
|
+
scale = float(size.max())
|
|
514
|
+
if any(_loop_area(verts[facets[f]]) > 1e-6 * scale**2 for f in drop):
|
|
515
|
+
raise RuntimeError(
|
|
516
|
+
"periodic_cells: a facet has no counterpart; the tessellation is degenerate"
|
|
517
|
+
)
|
|
518
|
+
keep = np.array([f not in drop for f in range(len(facets))])
|
|
519
|
+
remap = np.cumsum(keep) - 1
|
|
520
|
+
cx = CellComplex(
|
|
521
|
+
vertices=verts + lower,
|
|
522
|
+
facets=[f for f, k in zip(facets, keep, strict=True) if k],
|
|
523
|
+
facet_pieces=facet_pieces[keep],
|
|
524
|
+
facet_box=np.zeros(int(keep.sum()), dtype=np.int64),
|
|
525
|
+
piece_cell=np.array([ids[c] for c, _, _ in raw], dtype=np.int64),
|
|
526
|
+
piece_facets=[
|
|
527
|
+
np.array([remap[f] for f in pf if keep[f]], dtype=np.int64) for pf in piece_facets
|
|
528
|
+
],
|
|
529
|
+
lower=lower,
|
|
530
|
+
upper=lower + size,
|
|
531
|
+
periodic=True,
|
|
532
|
+
whole=True,
|
|
533
|
+
facet_shift=np.array(
|
|
534
|
+
[s for s, k in zip(facet_shift, keep, strict=True) if k], dtype=np.int64
|
|
535
|
+
).reshape(-1, 3),
|
|
536
|
+
)
|
|
537
|
+
_orient_and_close(cx)
|
|
538
|
+
return cx
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def _assemble(raw, ids, size, lower, periodic, tol) -> CellComplex:
|
|
542
|
+
"""Global vertices and shared facets of the pieces."""
|
|
543
|
+
scale = float(size.max())
|
|
544
|
+
# global vertices: merge the copies computed by neighbouring pieces
|
|
545
|
+
all_pts = np.concatenate([v for _, v, _ in raw])
|
|
546
|
+
offsets = np.cumsum([0] + [len(v) for _, v, _ in raw])
|
|
547
|
+
labels = _merge_points(all_pts, 50.0 * tol)
|
|
548
|
+
n_v = int(labels.max()) + 1
|
|
549
|
+
sums = np.zeros((n_v, 3))
|
|
550
|
+
np.add.at(sums, labels, all_pts)
|
|
551
|
+
verts = sums / np.bincount(labels, minlength=n_v)[:, None]
|
|
552
|
+
for d in range(3): # exactly on the faces of the box
|
|
553
|
+
verts[np.abs(verts[:, d]) <= 100.0 * tol, d] = 0.0
|
|
554
|
+
verts[np.abs(verts[:, d] - size[d]) <= 100.0 * tol, d] = size[d]
|
|
555
|
+
if periodic:
|
|
556
|
+
_match_periodic_faces(verts, size, 1e3 * tol)
|
|
557
|
+
piece_of = {c: p for p, (c, _, _) in enumerate(raw)}
|
|
558
|
+
facet_index: dict = {}
|
|
559
|
+
facets: list[np.ndarray] = []
|
|
560
|
+
facet_pieces: list[list[int]] = []
|
|
561
|
+
facet_box: list[int] = []
|
|
562
|
+
piece_facets: list[list[int]] = []
|
|
563
|
+
for p, (c, _, keyed) in enumerate(raw):
|
|
564
|
+
mine = []
|
|
565
|
+
for key, loop in keyed.items():
|
|
566
|
+
gl = labels[offsets[p] + loop]
|
|
567
|
+
gl = gl[np.concatenate([[True], gl[1:] != gl[:-1]])]
|
|
568
|
+
if gl.size > 1 and gl[0] == gl[-1]:
|
|
569
|
+
gl = gl[:-1]
|
|
570
|
+
if np.unique(gl).size < 3:
|
|
571
|
+
continue
|
|
572
|
+
if key[0] == "b":
|
|
573
|
+
f = len(facets)
|
|
574
|
+
facets.append(gl)
|
|
575
|
+
facet_pieces.append([p, -1])
|
|
576
|
+
facet_box.append(key[1])
|
|
577
|
+
mine.append(f)
|
|
578
|
+
continue
|
|
579
|
+
other = key[1]
|
|
580
|
+
pair = (min(c, other), max(c, other))
|
|
581
|
+
if pair in facet_index:
|
|
582
|
+
f = facet_index[pair]
|
|
583
|
+
facet_pieces[f][1] = p
|
|
584
|
+
# the loop seen from the second piece: union of the two vertex sets
|
|
585
|
+
merged = np.union1d(facets[f], gl)
|
|
586
|
+
if merged.size != np.unique(facets[f]).size:
|
|
587
|
+
facets[f] = _reloop(verts, merged, facets[f])
|
|
588
|
+
else:
|
|
589
|
+
f = len(facets)
|
|
590
|
+
facet_index[pair] = f
|
|
591
|
+
facets.append(gl)
|
|
592
|
+
facet_pieces.append([p, -2 if other in piece_of else -3])
|
|
593
|
+
facet_box.append(0)
|
|
594
|
+
mine.append(f)
|
|
595
|
+
piece_facets.append(mine)
|
|
596
|
+
facet_pieces = np.array(facet_pieces, dtype=np.int64)
|
|
597
|
+
unmatched = np.flatnonzero(facet_pieces[:, 1] < -1)
|
|
598
|
+
if unmatched.size:
|
|
599
|
+
# facets whose second piece was not computed: tiny sliver facets of a vertex
|
|
600
|
+
# shared by several cells, dropped (their area is below the tolerance)
|
|
601
|
+
area = np.array([_loop_area(verts[facets[f]]) for f in unmatched])
|
|
602
|
+
if np.any(area > 1e-6 * scale**2):
|
|
603
|
+
raise RuntimeError(
|
|
604
|
+
"power_complex: a facet has a single piece; the tessellation is degenerate"
|
|
605
|
+
)
|
|
606
|
+
drop = set(unmatched.tolist())
|
|
607
|
+
keep = np.array([f not in drop for f in range(len(facets))])
|
|
608
|
+
remap = np.cumsum(keep) - 1
|
|
609
|
+
facets = [f for f, k in zip(facets, keep, strict=True) if k]
|
|
610
|
+
facet_pieces = facet_pieces[keep]
|
|
611
|
+
facet_box = [b for b, k in zip(facet_box, keep, strict=True) if k]
|
|
612
|
+
piece_facets = [[int(remap[f]) for f in pf if keep[f]] for pf in piece_facets]
|
|
613
|
+
complex_ = CellComplex(
|
|
614
|
+
vertices=verts + lower,
|
|
615
|
+
facets=facets,
|
|
616
|
+
facet_pieces=facet_pieces,
|
|
617
|
+
facet_box=np.array(facet_box, dtype=np.int64),
|
|
618
|
+
piece_cell=np.array([ids[c] for c, _, _ in raw], dtype=np.int64),
|
|
619
|
+
piece_facets=[np.array(pf, dtype=np.int64) for pf in piece_facets],
|
|
620
|
+
lower=lower,
|
|
621
|
+
upper=lower + size,
|
|
622
|
+
periodic=periodic,
|
|
623
|
+
)
|
|
624
|
+
_orient_and_close(complex_)
|
|
625
|
+
return complex_
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
def _loop_area(p: np.ndarray) -> float:
|
|
629
|
+
c = p.mean(axis=0)
|
|
630
|
+
return 0.5 * float(np.linalg.norm(np.cross(p - c, np.roll(p, -1, axis=0) - c).sum(axis=0)))
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
def _reloop(verts, members, reference) -> np.ndarray:
|
|
634
|
+
"""Loop of ``members`` (coplanar) oriented as the loop ``reference``."""
|
|
635
|
+
p = verts[reference]
|
|
636
|
+
c = p.mean(axis=0)
|
|
637
|
+
normal = np.cross(p - c, np.roll(p, -1, axis=0) - c).sum(axis=0)
|
|
638
|
+
return members[_loop_on_plane(verts[members], normal)]
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
def _match_periodic_faces(verts: np.ndarray, size: np.ndarray, tol: float) -> None:
|
|
642
|
+
"""Make the vertices of opposite faces of the box exact translates of each other."""
|
|
643
|
+
for axis in range(3):
|
|
644
|
+
others = [d for d in range(3) if d != axis]
|
|
645
|
+
lo = np.flatnonzero(verts[:, axis] == 0.0)
|
|
646
|
+
hi = np.flatnonzero(verts[:, axis] == size[axis])
|
|
647
|
+
if lo.size == 0 or hi.size == 0:
|
|
648
|
+
continue
|
|
649
|
+
dist, near = cKDTree(verts[lo][:, others]).query(verts[hi][:, others])
|
|
650
|
+
ok = dist <= tol
|
|
651
|
+
verts[hi[ok][:, None], others] = verts[lo[near[ok]]][:, others]
|
|
652
|
+
|
|
653
|
+
|
|
654
|
+
def _orient_and_close(cx: CellComplex) -> None:
|
|
655
|
+
"""Orient every facet from its first piece outwards, and check that every piece is a
|
|
656
|
+
closed surface (each edge shared by two of its facets, in opposite directions)."""
|
|
657
|
+
centres = np.zeros((cx.n_pieces, 3))
|
|
658
|
+
for p, pf in enumerate(cx.piece_facets):
|
|
659
|
+
centres[p] = np.concatenate([cx.vertices[cx.facets[f]] for f in pf]).mean(axis=0)
|
|
660
|
+
for f, loop in enumerate(cx.facets):
|
|
661
|
+
p = cx.vertices[loop]
|
|
662
|
+
c = p.mean(axis=0)
|
|
663
|
+
normal = np.cross(p - c, np.roll(p, -1, axis=0) - c).sum(axis=0)
|
|
664
|
+
if normal @ (c - centres[cx.facet_pieces[f, 0]]) < 0:
|
|
665
|
+
cx.facets[f] = loop[::-1].copy()
|
|
666
|
+
bad = 0
|
|
667
|
+
for p, pf in enumerate(cx.piece_facets):
|
|
668
|
+
edges = {}
|
|
669
|
+
for f in pf:
|
|
670
|
+
loop = cx.facets[f] if cx.facet_pieces[f, 0] == p else cx.facets[f][::-1]
|
|
671
|
+
for a, b in zip(loop, np.roll(loop, -1), strict=True):
|
|
672
|
+
edges[(int(a), int(b))] = edges.get((int(a), int(b)), 0) + 1
|
|
673
|
+
for (a, b), count in edges.items():
|
|
674
|
+
if count != 1 or edges.get((b, a), 0) != 1:
|
|
675
|
+
bad += 1
|
|
676
|
+
break
|
|
677
|
+
cx.metadata["open_pieces"] = bad
|