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
morphogen/mesh/exact.py
ADDED
|
@@ -0,0 +1,1717 @@
|
|
|
1
|
+
"""Conforming meshes of the exact geometry of microstructures, without a background grid.
|
|
2
|
+
|
|
3
|
+
The level-set route of :func:`morphogen.mesh.conforming.conforming_mesh` samples the level
|
|
4
|
+
set of a microstructure at the nodes of a regular grid: the interface is as accurate as the
|
|
5
|
+
grid is fine, and features thinner than its spacing are lost. The meshes here are built on
|
|
6
|
+
the geometry itself.
|
|
7
|
+
|
|
8
|
+
**Faceted microstructures** (:func:`polyhedral_mesh`): microstructures made of convex
|
|
9
|
+
polyhedra that partition their box — the plates and voids of scale-rich networks, the
|
|
10
|
+
extruded ligaments of planar ones, the cubes of fractal sponges, the slabs of laminates —
|
|
11
|
+
give their pieces (``convex_pieces()``). Their faces need not match: a plate is bounded on
|
|
12
|
+
one side by a single face, on the other by the faces of every void and plate that ends on
|
|
13
|
+
it. The faces are grouped by plane, and the pieces facing each other across a plane share
|
|
14
|
+
the overlay of their faces (each face clipped by those of the other side, Sutherland-Hodgman
|
|
15
|
+
on the plane), so that every facet is shared by exactly two pieces (or lies on a face of the
|
|
16
|
+
box); the vertices lying on the edges of a facet (T-junctions) are inserted into its loop.
|
|
17
|
+
This face-to-face complex is split into tetrahedra (cones from the centroids of the pieces
|
|
18
|
+
over their fanned facets, :func:`morphogen.mesh.polycrystal.initial_mesh`), and MMG
|
|
19
|
+
remeshes it to the requested size keeping the facets between phases and the faces of the
|
|
20
|
+
box (their edges as ridges, within a Hausdorff distance of a millionth of the size: planar
|
|
21
|
+
facets have nothing to approximate, and its smoothing would bend them): the interfaces are
|
|
22
|
+
those of the exact geometry, sharp edges and corners included, at any thickness.
|
|
23
|
+
|
|
24
|
+
**Implicit microstructures** (:func:`adaptive_mesh`): the others give their level set at
|
|
25
|
+
any point of space (``level_set_at``: the signed distance to their boundary, or a function
|
|
26
|
+
with the same zero set), and the mesh is refined where the interface needs it, without a
|
|
27
|
+
grid. An octree of the box (:mod:`morphogen.mesh.octree`) splits its cells along whose
|
|
28
|
+
lines of three points ``a``, ``m``, ``b`` (edges, middle lines of the faces, axes) the
|
|
29
|
+
level set crosses zero twice (a feature thinner than the cell), crosses it once at a point
|
|
30
|
+
that its linear interpolation misplaces by more than the Hausdorff distance (the deviation
|
|
31
|
+
``e = phi_m - (phi_a + phi_b) / 2`` of the parabola through the three values, over the
|
|
32
|
+
slope), or bends toward zero by more than that distance while the interface may be near
|
|
33
|
+
(``|phi_a| + |phi_m|`` or ``|phi_m| + |phi_b|`` below ``L l / 2``, ``L`` the slope of the
|
|
34
|
+
level set: 1 for a distance, ``l`` the length of the line): a feature hidden between the
|
|
35
|
+
samples; or where the level set, at the zero of its linear interpolation along a segment
|
|
36
|
+
of the cell that may be an edge of its tetrahedra (:data:`morphogen.mesh.octree.SEGMENTS`),
|
|
37
|
+
exceeds the Hausdorff distance (a kink between the ends, the medial surface of a sheet,
|
|
38
|
+
that the parabola misses). A distance bends away from zero on the medial surfaces of the
|
|
39
|
+
phases (the middle of a sheet), where nothing else is refined. The octree is balanced and
|
|
40
|
+
split into tetrahedra (the six of the Kuhn triangulation in its plain cells, cones from the
|
|
41
|
+
centres of the others over their fanned faces), then MMG discretizes the zero level set
|
|
42
|
+
(``mmg3d -ls``) and remeshes the result within the Hausdorff distance, without detecting
|
|
43
|
+
ridges by angles (the facets of the cut bend at the scale of the octree: their ridges
|
|
44
|
+
would keep flat elements; the edges of the box are given); the nodes of the interface are
|
|
45
|
+
finally moved onto the exact zero level set (Newton's method along the gradient), as near
|
|
46
|
+
as the elements allow without flipping or flattening. Periodic meshes:
|
|
47
|
+
the octree is balanced across the periodic faces, so that opposite faces get the same
|
|
48
|
+
triangles; their edges that the interface crosses are split at its exact zeros (or their
|
|
49
|
+
ends moved onto them), alike on translated faces, and MMG keeps these faces as they are:
|
|
50
|
+
they match, and their nodes lie on the interface.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
from __future__ import annotations
|
|
54
|
+
|
|
55
|
+
import itertools
|
|
56
|
+
import logging
|
|
57
|
+
import subprocess
|
|
58
|
+
import tempfile
|
|
59
|
+
import time
|
|
60
|
+
from pathlib import Path
|
|
61
|
+
|
|
62
|
+
import numpy as np
|
|
63
|
+
from numba import njit
|
|
64
|
+
from scipy.sparse import coo_matrix
|
|
65
|
+
from scipy.sparse.csgraph import connected_components
|
|
66
|
+
from scipy.spatial import cKDTree
|
|
67
|
+
|
|
68
|
+
from morphogen.io import medit
|
|
69
|
+
from morphogen.mesh.conforming import (
|
|
70
|
+
REF_INSIDE,
|
|
71
|
+
REF_OUTSIDE,
|
|
72
|
+
_matching_refs,
|
|
73
|
+
_on_faces,
|
|
74
|
+
_periodic_axes,
|
|
75
|
+
_run_mmg,
|
|
76
|
+
mmg_executable,
|
|
77
|
+
)
|
|
78
|
+
from morphogen.mesh.polyhedra import CellComplex, _merge_points
|
|
79
|
+
from morphogen.mesh.tetra import TetMesh, tet_quality, tet_volumes
|
|
80
|
+
|
|
81
|
+
log = logging.getLogger("morphogen")
|
|
82
|
+
|
|
83
|
+
#: The values of the level sets within this fraction of the Hausdorff distance of zero, at
|
|
84
|
+
#: the nodes of the octree, are moved this far off it before the cut (no interface
|
|
85
|
+
#: through a node)
|
|
86
|
+
_OFF_NODES = 1e-3
|
|
87
|
+
|
|
88
|
+
#: Relative tolerance of the geometry (times the largest side of the box): points closer
|
|
89
|
+
#: are one, faces on planes closer are coplanar
|
|
90
|
+
TOLERANCE = 1e-9
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
# -- convex polygons of a plane of space -------------------------------------------------------
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@njit(cache=True)
|
|
97
|
+
def _clip_coplanar(a, b, nb, tol):
|
|
98
|
+
"""The part of the convex polygon ``a`` inside the convex polygon ``b`` of the same
|
|
99
|
+
plane (``b`` counter-clockwise about ``nb``): Sutherland-Hodgman against the half-planes
|
|
100
|
+
of the edges of ``b``, the points within ``tol`` of an edge kept inside."""
|
|
101
|
+
out = a.copy()
|
|
102
|
+
m = b.shape[0]
|
|
103
|
+
for j in range(m):
|
|
104
|
+
k = out.shape[0]
|
|
105
|
+
if k == 0:
|
|
106
|
+
break
|
|
107
|
+
q0 = b[j]
|
|
108
|
+
q1 = b[(j + 1) % m]
|
|
109
|
+
ex, ey, ez = q1[0] - q0[0], q1[1] - q0[1], q1[2] - q0[2]
|
|
110
|
+
ix = nb[1] * ez - nb[2] * ey # nb x e: inward for a counter-clockwise polygon
|
|
111
|
+
iy = nb[2] * ex - nb[0] * ez
|
|
112
|
+
iz = nb[0] * ey - nb[1] * ex
|
|
113
|
+
s = np.sqrt(ix * ix + iy * iy + iz * iz)
|
|
114
|
+
if s == 0.0:
|
|
115
|
+
continue
|
|
116
|
+
ix, iy, iz = ix / s, iy / s, iz / s
|
|
117
|
+
new = np.empty((k + m + 2, 3))
|
|
118
|
+
n = 0
|
|
119
|
+
for i in range(k):
|
|
120
|
+
p0 = out[i]
|
|
121
|
+
p1 = out[(i + 1) % k]
|
|
122
|
+
d0 = (p0[0] - q0[0]) * ix + (p0[1] - q0[1]) * iy + (p0[2] - q0[2]) * iz
|
|
123
|
+
d1 = (p1[0] - q0[0]) * ix + (p1[1] - q0[1]) * iy + (p1[2] - q0[2]) * iz
|
|
124
|
+
if d0 >= -tol:
|
|
125
|
+
new[n] = p0
|
|
126
|
+
n += 1
|
|
127
|
+
if d1 < -tol:
|
|
128
|
+
t = d0 / (d0 - d1)
|
|
129
|
+
new[n] = p0 + t * (p1 - p0)
|
|
130
|
+
n += 1
|
|
131
|
+
elif d1 >= -tol:
|
|
132
|
+
t = d0 / (d0 - d1)
|
|
133
|
+
new[n] = p0 + t * (p1 - p0)
|
|
134
|
+
n += 1
|
|
135
|
+
out = new[:n]
|
|
136
|
+
# consecutive points that coincide
|
|
137
|
+
k = out.shape[0]
|
|
138
|
+
keep = np.ones(k, dtype=np.bool_)
|
|
139
|
+
for i in range(k):
|
|
140
|
+
p, q = out[i], out[(i + 1) % k]
|
|
141
|
+
if abs(p[0] - q[0]) <= tol and abs(p[1] - q[1]) <= tol and abs(p[2] - q[2]) <= tol:
|
|
142
|
+
keep[i] = False
|
|
143
|
+
return out[keep]
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _area_vector(loop: np.ndarray) -> np.ndarray:
|
|
147
|
+
"""Half the sum of the cross products of a planar loop: its area times its normal."""
|
|
148
|
+
p = np.asarray(loop, dtype=float)
|
|
149
|
+
c = p.mean(axis=0)
|
|
150
|
+
return 0.5 * np.cross(p - c, np.roll(p, -1, axis=0) - c).sum(axis=0)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
# -- the face-to-face complex of convex pieces -----------------------------------------------
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _faces_of(pieces) -> tuple[list, np.ndarray, np.ndarray, np.ndarray]:
|
|
157
|
+
"""The faces of the pieces (``(vertices, face offsets, labels, normals, planes)``):
|
|
158
|
+
their loops (counter-clockwise about their outward normals), pieces, outward unit
|
|
159
|
+
normals and offsets (the planes given: exact; faces of no area dropped)."""
|
|
160
|
+
loops, owner, normals, offsets = [], [], [], []
|
|
161
|
+
for p, (verts, fofs, _labels, face_normals, face_planes) in enumerate(pieces):
|
|
162
|
+
for f in range(len(fofs) - 1):
|
|
163
|
+
loop = np.asarray(verts[fofs[f] : fofs[f + 1]], dtype=float)
|
|
164
|
+
if len(loop) < 3:
|
|
165
|
+
continue
|
|
166
|
+
area = _area_vector(loop)
|
|
167
|
+
if not np.linalg.norm(area) > 0.0:
|
|
168
|
+
continue
|
|
169
|
+
n = np.asarray(face_normals[f], dtype=float)
|
|
170
|
+
if area @ n < 0: # the loop turns the other way
|
|
171
|
+
loop = loop[::-1].copy()
|
|
172
|
+
loops.append(loop)
|
|
173
|
+
owner.append(p)
|
|
174
|
+
normals.append(n)
|
|
175
|
+
offsets.append(float(face_planes[f]))
|
|
176
|
+
return loops, np.asarray(owner, dtype=np.int64), np.asarray(normals), np.asarray(offsets)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _planes(normals: np.ndarray, offsets: np.ndarray, scale: float, tol: float):
|
|
180
|
+
"""The plane of each face (cluster index) and the side of the face on it (+1 or -1):
|
|
181
|
+
the normals turned so that their largest component is positive, clustered with the
|
|
182
|
+
offsets (relative to ``scale``) within ``tol``."""
|
|
183
|
+
k = np.argmax(np.abs(normals), axis=1)
|
|
184
|
+
side = np.sign(normals[np.arange(len(normals)), k])
|
|
185
|
+
side[side == 0] = 1.0
|
|
186
|
+
key = np.column_stack([normals * side[:, None], (offsets * side / scale)[:, None]])
|
|
187
|
+
pairs = cKDTree(key).query_pairs(tol, output_type="ndarray")
|
|
188
|
+
n = len(key)
|
|
189
|
+
graph = coo_matrix((np.ones(len(pairs)), (pairs[:, 0], pairs[:, 1])), shape=(n, n))
|
|
190
|
+
_, cluster = connected_components(graph, directed=False)
|
|
191
|
+
return cluster, side.astype(np.int64), key
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _box_face(key: np.ndarray, lower, upper, scale: float, tol: float) -> int:
|
|
195
|
+
"""The face of the box (1-6: x0, x1, y0, y1, z0, z1) of a plane (its canonical normal
|
|
196
|
+
and offset over ``scale``), or 0."""
|
|
197
|
+
for d in range(3):
|
|
198
|
+
e = np.zeros(3)
|
|
199
|
+
e[d] = 1.0
|
|
200
|
+
if np.linalg.norm(key[:3] - e) > 1e3 * tol:
|
|
201
|
+
continue
|
|
202
|
+
for s, bound in ((0, lower[d]), (1, upper[d])):
|
|
203
|
+
if abs(key[3] * scale - bound) <= 1e3 * tol * scale:
|
|
204
|
+
return 1 + 2 * d + s
|
|
205
|
+
return 0
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def face_to_face(pieces, cells, lower, upper, *, tol: float | None = None) -> CellComplex:
|
|
209
|
+
"""The face-to-face complex of convex polyhedra partitioning the box ``[lower, upper]``
|
|
210
|
+
(``(vertices, face offsets, labels, normals, planes)`` tuples, the faces counter-
|
|
211
|
+
clockwise about their outward normals), ``cells[p]`` the cell of piece ``p``: the
|
|
212
|
+
overlay of the faces facing each other on every plane, the vertices on the edges of
|
|
213
|
+
the facets inserted into their loops (see the module)."""
|
|
214
|
+
lower = np.asarray(lower, dtype=float)
|
|
215
|
+
upper = np.asarray(upper, dtype=float)
|
|
216
|
+
scale = float(np.max(upper - lower))
|
|
217
|
+
tol = TOLERANCE * scale if tol is None else float(tol)
|
|
218
|
+
loops, owner, normals, offsets = _faces_of(pieces)
|
|
219
|
+
cluster, side, key = _planes(normals, offsets, scale, TOLERANCE * 10)
|
|
220
|
+
facets, facet_pieces, facet_box = [], [], []
|
|
221
|
+
order = np.argsort(cluster, kind="stable")
|
|
222
|
+
bounds = np.flatnonzero(np.diff(cluster[order])) + 1
|
|
223
|
+
for group in np.split(order, bounds):
|
|
224
|
+
a = group[side[group] > 0]
|
|
225
|
+
b = group[side[group] < 0]
|
|
226
|
+
if len(a) == 0 or len(b) == 0: # a face of the box
|
|
227
|
+
box = _box_face(key[group[0]], lower, upper, scale, TOLERANCE * 10)
|
|
228
|
+
if box == 0:
|
|
229
|
+
raise ValueError("face_to_face: a face of a piece is neither shared nor on "
|
|
230
|
+
"the box: the pieces do not partition the box") # fmt: skip
|
|
231
|
+
for f in group:
|
|
232
|
+
facets.append(loops[f])
|
|
233
|
+
facet_pieces.append((owner[f], -1))
|
|
234
|
+
facet_box.append(box)
|
|
235
|
+
continue
|
|
236
|
+
lo_b = np.array([loops[f].min(axis=0) for f in b]) - tol
|
|
237
|
+
hi_b = np.array([loops[f].max(axis=0) for f in b]) + tol
|
|
238
|
+
for fa in a:
|
|
239
|
+
la = loops[fa]
|
|
240
|
+
lo_a, hi_a = la.min(axis=0), la.max(axis=0)
|
|
241
|
+
near = np.flatnonzero(np.all(lo_b <= hi_a, axis=1) & np.all(hi_b >= lo_a, axis=1))
|
|
242
|
+
for j in near:
|
|
243
|
+
fb = b[j]
|
|
244
|
+
part = _clip_coplanar(la, loops[fb], normals[fb], tol)
|
|
245
|
+
if len(part) < 3 or np.linalg.norm(_area_vector(part)) <= tol * tol:
|
|
246
|
+
continue
|
|
247
|
+
facets.append(part)
|
|
248
|
+
facet_pieces.append((owner[fa], owner[fb]))
|
|
249
|
+
facet_box.append(0)
|
|
250
|
+
# the vertices: merged, then inserted into the loops whose edges they lie on
|
|
251
|
+
counts = [len(f) for f in facets]
|
|
252
|
+
points = np.concatenate(facets)
|
|
253
|
+
label = _merge_points(points, tol)
|
|
254
|
+
first = np.full(label.max() + 1, -1, dtype=np.int64)
|
|
255
|
+
first[label[::-1]] = np.arange(len(label))[::-1]
|
|
256
|
+
vertices = points[first]
|
|
257
|
+
index = np.split(label, np.cumsum(counts)[:-1])
|
|
258
|
+
tree = cKDTree(vertices)
|
|
259
|
+
loops_idx = [_simple(_with_t_junctions(_simple(np.asarray(ix, dtype=np.int64)), vertices,
|
|
260
|
+
tree, tol)) for ix in index] # fmt: skip
|
|
261
|
+
keep = [i for i, ix in enumerate(loops_idx) if len(ix) >= 3]
|
|
262
|
+
facets_idx = [loops_idx[i] for i in keep]
|
|
263
|
+
facet_pieces = np.asarray(facet_pieces, dtype=np.int64)[keep]
|
|
264
|
+
facet_box = np.asarray(facet_box, dtype=np.int64)[keep]
|
|
265
|
+
piece_facets = [[] for _ in pieces]
|
|
266
|
+
for f, (pa, pb) in enumerate(facet_pieces):
|
|
267
|
+
piece_facets[pa].append(f)
|
|
268
|
+
if pb >= 0:
|
|
269
|
+
piece_facets[pb].append(f)
|
|
270
|
+
return CellComplex(
|
|
271
|
+
vertices=vertices,
|
|
272
|
+
facets=facets_idx,
|
|
273
|
+
facet_pieces=facet_pieces,
|
|
274
|
+
facet_box=facet_box,
|
|
275
|
+
piece_cell=np.asarray(cells, dtype=np.int64),
|
|
276
|
+
piece_facets=[np.asarray(f, dtype=np.int64) for f in piece_facets],
|
|
277
|
+
lower=lower,
|
|
278
|
+
upper=upper,
|
|
279
|
+
periodic=False,
|
|
280
|
+
)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _with_t_junctions(loop: np.ndarray, vertices: np.ndarray, tree, tol: float) -> np.ndarray:
|
|
284
|
+
"""The loop with the vertices that lie on its edges (strictly between their ends)
|
|
285
|
+
inserted in order (``tree``: a k-d tree of the vertices)."""
|
|
286
|
+
out = []
|
|
287
|
+
for a, b in zip(loop, np.roll(loop, -1), strict=True):
|
|
288
|
+
out.append(int(a))
|
|
289
|
+
pa, pb = vertices[a], vertices[b]
|
|
290
|
+
ab = pb - pa
|
|
291
|
+
length2 = float(ab @ ab)
|
|
292
|
+
if length2 <= tol * tol:
|
|
293
|
+
continue
|
|
294
|
+
near = tree.query_ball_point(0.5 * (pa + pb), 0.5 * np.sqrt(length2) + tol)
|
|
295
|
+
inside = {}
|
|
296
|
+
for w in near:
|
|
297
|
+
if w in (a, b):
|
|
298
|
+
continue
|
|
299
|
+
t = float((vertices[w] - pa) @ ab) / length2
|
|
300
|
+
if 0.0 < t < 1.0 and np.linalg.norm(pa + t * ab - vertices[w]) <= 10.0 * tol:
|
|
301
|
+
inside[w] = t
|
|
302
|
+
out.extend(sorted(inside, key=inside.get))
|
|
303
|
+
return np.asarray(out, dtype=np.int64)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _simple(loop: np.ndarray) -> np.ndarray:
|
|
307
|
+
"""The loop without repeated consecutive vertices."""
|
|
308
|
+
if len(loop) == 0:
|
|
309
|
+
return loop
|
|
310
|
+
keep = loop != np.roll(loop, -1)
|
|
311
|
+
return loop[keep]
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
@njit(cache=True)
|
|
315
|
+
def _greedy_boxes(labels):
|
|
316
|
+
"""A partition of a grid of labels into boxes of one label each (greedily: the first
|
|
317
|
+
free cell grown along the last axis, then the second, then the first): rows ``(i0, j0,
|
|
318
|
+
k0, i1, j1, k1, label)``, the upper bounds excluded."""
|
|
319
|
+
nx, ny, nz = labels.shape
|
|
320
|
+
done = np.zeros(labels.shape, dtype=np.bool_)
|
|
321
|
+
out = np.empty((labels.size, 7), dtype=np.int64)
|
|
322
|
+
n = 0
|
|
323
|
+
for i in range(nx):
|
|
324
|
+
for j in range(ny):
|
|
325
|
+
for k in range(nz):
|
|
326
|
+
if done[i, j, k]:
|
|
327
|
+
continue
|
|
328
|
+
lab = labels[i, j, k]
|
|
329
|
+
k1 = k + 1
|
|
330
|
+
while k1 < nz and not done[i, j, k1] and labels[i, j, k1] == lab:
|
|
331
|
+
k1 += 1
|
|
332
|
+
j1 = j + 1
|
|
333
|
+
while j1 < ny:
|
|
334
|
+
ok = True
|
|
335
|
+
for kk in range(k, k1):
|
|
336
|
+
if done[i, j1, kk] or labels[i, j1, kk] != lab:
|
|
337
|
+
ok = False
|
|
338
|
+
break
|
|
339
|
+
if not ok:
|
|
340
|
+
break
|
|
341
|
+
j1 += 1
|
|
342
|
+
i1 = i + 1
|
|
343
|
+
while i1 < nx:
|
|
344
|
+
ok = True
|
|
345
|
+
for jj in range(j, j1):
|
|
346
|
+
for kk in range(k, k1):
|
|
347
|
+
if done[i1, jj, kk] or labels[i1, jj, kk] != lab:
|
|
348
|
+
ok = False
|
|
349
|
+
break
|
|
350
|
+
if not ok:
|
|
351
|
+
break
|
|
352
|
+
if not ok:
|
|
353
|
+
break
|
|
354
|
+
i1 += 1
|
|
355
|
+
done[i:i1, j:j1, k:k1] = True
|
|
356
|
+
out[n] = (i, j, k, i1, j1, k1, lab)
|
|
357
|
+
n += 1
|
|
358
|
+
return out[:n]
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def grid_boxes(labels, edges) -> tuple[list, np.ndarray]:
|
|
362
|
+
"""Convex pieces of a structure made of the cells of a rectilinear grid (``labels``: a
|
|
363
|
+
phase per cell; ``edges``: the coordinates of the planes of the grid along each axis):
|
|
364
|
+
boxes of one phase each (:func:`_greedy_boxes`), and their phases."""
|
|
365
|
+
from morphogen.models.scale_rich_3d import box_polyhedron
|
|
366
|
+
|
|
367
|
+
boxes = _greedy_boxes(np.ascontiguousarray(labels, dtype=np.int64))
|
|
368
|
+
lo = np.column_stack([edges[d][boxes[:, d]] for d in range(3)])
|
|
369
|
+
hi = np.column_stack([edges[d][boxes[:, 3 + d]] for d in range(3)])
|
|
370
|
+
return [box_polyhedron(a, b) for a, b in zip(lo, hi, strict=True)], boxes[:, 6]
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
# -- the meshes ------------------------------------------------------------------------------
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _width(poly) -> float:
|
|
377
|
+
"""Twice the radius of the largest ball in a convex polyhedron (its Chebyshev ball)."""
|
|
378
|
+
from morphogen.mesh.polyhedra import _chebyshev_centre
|
|
379
|
+
|
|
380
|
+
_, _, _, normals, planes = poly
|
|
381
|
+
return 2.0 * _chebyshev_centre(np.asarray(normals, float), np.asarray(planes, float))[1]
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def pieces_mesh(
|
|
385
|
+
pieces,
|
|
386
|
+
phase,
|
|
387
|
+
lower,
|
|
388
|
+
upper,
|
|
389
|
+
*,
|
|
390
|
+
size: float,
|
|
391
|
+
min_size: float | None = None,
|
|
392
|
+
hausdorff: float | None = None,
|
|
393
|
+
gradation: float = 2.0,
|
|
394
|
+
phases: str = "all",
|
|
395
|
+
cells=None,
|
|
396
|
+
thin: float | None = None,
|
|
397
|
+
order: int = 1,
|
|
398
|
+
periodic: bool = False,
|
|
399
|
+
executable: str | None = None,
|
|
400
|
+
workdir=None,
|
|
401
|
+
timeout: float | None = None,
|
|
402
|
+
) -> TetMesh:
|
|
403
|
+
"""Conforming tetrahedral mesh of convex pieces partitioning the box (the
|
|
404
|
+
``(vertices, face offsets, labels, normals, planes)`` of each, its ``phase``): the
|
|
405
|
+
face-to-face complex of the pieces (:func:`face_to_face`), cones from their centroids,
|
|
406
|
+
remeshed by MMG keeping their facets and the faces of the box (every element knows its
|
|
407
|
+
phase, and its cell when ``cells`` are given: ``mesh.cell``). Pieces thinner than the
|
|
408
|
+
elements (plates) get flat elements, one through their thickness, of aspect ratio
|
|
409
|
+
``size`` over the thickness; ``thin``: the elements of a piece at most ``thin`` times
|
|
410
|
+
its width (twice the radius of its largest ball) and at least ``min_size`` (default
|
|
411
|
+
``size / 10``), meshed through their thickness (as many elements as the square of the
|
|
412
|
+
ratio of the size to the thickness, per unit area). ``phases``: ``"all"``,
|
|
413
|
+
``"solid"`` (phase 1) or ``"matrix"`` (phase 0); ``periodic``: matching opposite
|
|
414
|
+
faces (meshed alike by ``mmg2d``, kept by MMG). ``hausdorff``: how far MMG may move
|
|
415
|
+
the nodes off the facets, which are planar (default ``1e-6 size``: not at all, the
|
|
416
|
+
facets exact; with the usual ``size / 20``, its smoothing bends their ridges into
|
|
417
|
+
curves, their nodes a few thousandths of the size off the planes)."""
|
|
418
|
+
from morphogen.mesh.polycrystal import _ridges, initial_mesh
|
|
419
|
+
|
|
420
|
+
if phases not in ("all", "solid", "matrix"):
|
|
421
|
+
raise ValueError("phases: 'all', 'solid' (phase 1) or 'matrix' (phase 0)")
|
|
422
|
+
periodic = bool(periodic)
|
|
423
|
+
if order not in (1, 2):
|
|
424
|
+
raise ValueError("order: 1 or 2")
|
|
425
|
+
size = float(size)
|
|
426
|
+
if not size > 0:
|
|
427
|
+
raise ValueError("size: must be positive")
|
|
428
|
+
phase = np.asarray(phase, dtype=np.int64)
|
|
429
|
+
given = cells is not None
|
|
430
|
+
cells = np.asarray(cells, dtype=np.int64) if given else phase
|
|
431
|
+
if len(phase) != len(pieces) or len(cells) != len(pieces):
|
|
432
|
+
raise ValueError("one phase and one cell per piece")
|
|
433
|
+
lower = np.asarray(lower, dtype=float)
|
|
434
|
+
upper = np.asarray(upper, dtype=float)
|
|
435
|
+
hmin = float(min_size) if min_size is not None else size / 10.0
|
|
436
|
+
hausd = float(hausdorff) if hausdorff is not None else 1e-6 * size
|
|
437
|
+
exe = mmg_executable(executable)
|
|
438
|
+
t0 = time.perf_counter()
|
|
439
|
+
# a reference per piece: MMG keeps every facet (with references by phase, its swaps
|
|
440
|
+
# cross some of the interfaces between the pieces of different phases)
|
|
441
|
+
cx = face_to_face(pieces, np.arange(len(pieces)), lower, upper)
|
|
442
|
+
t_cx = time.perf_counter() - t0
|
|
443
|
+
sizing = ["-hmax", f"{size:.10g}", "-hmin", f"{hmin:.10g}", "-hausd", f"{hausd:.10g}",
|
|
444
|
+
"-hgrad", f"{float(gradation):.10g}", "-v", "-1"] # fmt: skip
|
|
445
|
+
with tempfile.TemporaryDirectory(dir=workdir) as tmp:
|
|
446
|
+
folder = Path(tmp)
|
|
447
|
+
# periodic: matching triangulations of opposite faces (mmg2d), kept by MMG
|
|
448
|
+
xyz, tets, refs, tri, tri_refs, n_box = initial_mesh(
|
|
449
|
+
cx, size=size, sizing=sizing, periodic=periodic, folder=folder, timeout=timeout
|
|
450
|
+
)
|
|
451
|
+
used = np.unique(tets)
|
|
452
|
+
renum = np.full(len(xyz), -1, dtype=np.int64)
|
|
453
|
+
renum[used] = np.arange(len(used))
|
|
454
|
+
ridges = _ridges(cx) # the edges where the interfaces or faces of the box bend
|
|
455
|
+
corners = np.unique(ridges)
|
|
456
|
+
required = renum[corners]
|
|
457
|
+
if periodic:
|
|
458
|
+
tol = TOLERANCE * float((upper - lower).max())
|
|
459
|
+
pts = xyz[used]
|
|
460
|
+
on_face = np.any((np.abs(pts - lower) <= tol) | (np.abs(pts - upper) <= tol), axis=1)
|
|
461
|
+
required = np.union1d(required, np.flatnonzero(on_face))
|
|
462
|
+
sol = None
|
|
463
|
+
if thin is not None:
|
|
464
|
+
# sizes: at most a multiple of the width of the thinnest piece around each
|
|
465
|
+
# vertex, so that thin pieces get elements of their thickness
|
|
466
|
+
width = np.array([_width(poly) for poly in pieces])
|
|
467
|
+
local = np.clip(width[refs - 1] * float(thin), hmin, size)
|
|
468
|
+
h = np.full(len(xyz), size)
|
|
469
|
+
for k in range(4):
|
|
470
|
+
np.minimum.at(h, tets[:, k], local)
|
|
471
|
+
sol = folder / "pieces.sol"
|
|
472
|
+
medit.write_sol(sol, h[used])
|
|
473
|
+
medit.write_mesh(folder / "pieces.mesh", xyz[used], renum[tets], renum[tri],
|
|
474
|
+
tet_refs=refs, tri_refs=tri_refs, edges=renum[ridges],
|
|
475
|
+
ridges=np.arange(len(ridges)), corners=renum[corners],
|
|
476
|
+
required_vertices=required,
|
|
477
|
+
required_triangles=np.arange(n_box) if periodic else None) # fmt: skip
|
|
478
|
+
t1 = time.perf_counter()
|
|
479
|
+
data = _run_mmg(exe, folder / "pieces.mesh", sol, folder / "out.mesh", sizing, timeout)
|
|
480
|
+
t_mmg = time.perf_counter() - t1
|
|
481
|
+
nodes = data["Vertices"]
|
|
482
|
+
tol = TOLERANCE * float((upper - lower).max())
|
|
483
|
+
for d in range(3): # the nodes of the faces exactly on them
|
|
484
|
+
nodes[np.abs(nodes[:, d] - lower[d]) <= tol, d] = lower[d]
|
|
485
|
+
nodes[np.abs(nodes[:, d] - upper[d]) <= tol, d] = upper[d]
|
|
486
|
+
elements = data["Tetrahedra"]
|
|
487
|
+
piece = data["Tetrahedra_refs"] - 1
|
|
488
|
+
flip = tet_volumes(nodes, elements) < 0
|
|
489
|
+
elements[flip] = elements[flip][:, [0, 2, 1, 3]]
|
|
490
|
+
used, inverse = np.unique(elements, return_inverse=True)
|
|
491
|
+
mesh = TetMesh(
|
|
492
|
+
nodes=nodes[used],
|
|
493
|
+
elements=inverse.reshape(elements.shape),
|
|
494
|
+
phase=phase[piece],
|
|
495
|
+
lower=lower,
|
|
496
|
+
upper=upper,
|
|
497
|
+
periodic=periodic,
|
|
498
|
+
cell=cells[piece] if given else None,
|
|
499
|
+
metadata={
|
|
500
|
+
"mesher": "exact convex pieces (mmg3d)",
|
|
501
|
+
"size": size,
|
|
502
|
+
"pieces": len(pieces),
|
|
503
|
+
"facets": cx.n_facets,
|
|
504
|
+
"phases": phases,
|
|
505
|
+
"matching_faces": periodic,
|
|
506
|
+
"time_complex_s": round(t_cx, 3),
|
|
507
|
+
"time_mmg_s": round(t_mmg, 3),
|
|
508
|
+
},
|
|
509
|
+
)
|
|
510
|
+
if phases == "solid":
|
|
511
|
+
mesh = mesh.subset([1])
|
|
512
|
+
elif phases == "matrix":
|
|
513
|
+
mesh = mesh.subset([0])
|
|
514
|
+
if order == 2:
|
|
515
|
+
mesh = mesh.quadratic()
|
|
516
|
+
log.info("exact mesh of %d pieces: %d elements, %d nodes (MMG %.1f s)", len(pieces),
|
|
517
|
+
mesh.n_elements, mesh.n_nodes, t_mmg) # fmt: skip
|
|
518
|
+
return mesh
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
def polyhedral_mesh(micro, *, size: float, by_piece: bool = False, **options) -> TetMesh:
|
|
522
|
+
"""Conforming tetrahedral mesh of a faceted microstructure from its exact convex pieces
|
|
523
|
+
(``micro.convex_pieces()``: the pieces, their phases and cells; ``by_piece``: every
|
|
524
|
+
element knows the cell of its piece, ``mesh.cell``), periodic (matching faces) when
|
|
525
|
+
the microstructure is; see :func:`pieces_mesh` for the options."""
|
|
526
|
+
if not callable(getattr(micro, "convex_pieces", None)):
|
|
527
|
+
raise TypeError(f"{type(micro).__name__}: no convex pieces, no polyhedral mesh")
|
|
528
|
+
pieces, phase, cells = micro.convex_pieces()
|
|
529
|
+
domain = micro.domain
|
|
530
|
+
if options.get("periodic") is None:
|
|
531
|
+
options["periodic"] = bool(domain.periodic)
|
|
532
|
+
if options["periodic"] and not domain.periodic:
|
|
533
|
+
raise ValueError("matching periodic faces need a periodic microstructure")
|
|
534
|
+
return pieces_mesh(pieces, phase, domain.lower, domain.upper, size=size,
|
|
535
|
+
cells=cells if by_piece else None, **options) # fmt: skip
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
# -- the adaptive meshes of level sets --------------------------------------------------------
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def _to_split(fa, fm, fb, length, *, hmin: float, hausd: float, lipschitz: float):
|
|
542
|
+
"""Whether segments (the level set at their ends and middles, their lengths) must be
|
|
543
|
+
split to resolve the interface (see the module): two crossings (a thin feature), one
|
|
544
|
+
crossing whose linear interpolation is off by more than ``hausd`` (the deviation of
|
|
545
|
+
the parabola through the three values, over the slope), or no crossing but a bend
|
|
546
|
+
toward zero larger than ``hausd`` where the slope ``lipschitz`` allows the interface
|
|
547
|
+
(a feature between the samples; the kinks of a distance on the medial surfaces of the
|
|
548
|
+
phases bend away from zero: they stay); none shorter than 1.5 ``hmin``. A kink between
|
|
549
|
+
a sample and a crossing misplaces the zero beyond what the parabola tells: the level
|
|
550
|
+
set at the linear zeros finds it (in :func:`adaptive_mesh`)."""
|
|
551
|
+
e = fm - 0.5 * (fa + fb)
|
|
552
|
+
sa, sm, sb = np.sign(fa), np.sign(fm), np.sign(fb)
|
|
553
|
+
half = 0.5 * lipschitz * length
|
|
554
|
+
same = (sa == sm) & (sm == sb)
|
|
555
|
+
covered = same & (np.abs(fa) + np.abs(fm) >= half) & (np.abs(fm) + np.abs(fb) >= half)
|
|
556
|
+
two = (sa == sb) & (sm != sa)
|
|
557
|
+
one = sa != sb
|
|
558
|
+
jump = np.where(one, fa - fb, 1.0) # (not zero where the line crosses)
|
|
559
|
+
t = np.clip(fa / jump, 0.0, 1.0)
|
|
560
|
+
shift = np.abs(4.0 * t * (1.0 - t) * e / jump) * length
|
|
561
|
+
toward = same & ~covered & (e * sa < 0) & (np.abs(e) > hausd)
|
|
562
|
+
return (two | (one & (shift > hausd)) | toward) & (length > 1.5 * hmin)
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
def _unique_edges(simplices: np.ndarray) -> np.ndarray:
|
|
566
|
+
"""The edges (sorted pairs of vertices) of triangles or tetrahedra."""
|
|
567
|
+
k = simplices.shape[1]
|
|
568
|
+
pairs = [(i, j) for i in range(k) for j in range(i + 1, k)]
|
|
569
|
+
edges = np.sort(simplices[:, pairs].reshape(-1, 2), axis=1)
|
|
570
|
+
return np.unique(edges, axis=0)
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def _cut_faces(phi, nodes, tets, tri, refs, faces, group, *, earlier=(), zero=0.0, near=0.15,
|
|
574
|
+
iterations=60): # fmt: skip
|
|
575
|
+
"""The mesh with the triangles of the ``faces`` (references) of the box cut exactly
|
|
576
|
+
along the zero level set ``phi``: their edges between nodes of opposite signs split at
|
|
577
|
+
the zero (bisection of ``phi`` along the edge), or one of their ends moved to it when it
|
|
578
|
+
lies within ``near`` of the edge (along the edge, on the faces of the box it lies on),
|
|
579
|
+
alike for the translates of an edge (``group``: a label per node, shared by the
|
|
580
|
+
translates); the tetrahedra around a split edge split in two. ``earlier``: the values
|
|
581
|
+
at the nodes of the level sets cut before (several phases), whose zeros never move and
|
|
582
|
+
whose negative triangles (their phases) are not cut; the nodes added or moved take
|
|
583
|
+
their linear interpolation, so that their traces stay as they were. Values within
|
|
584
|
+
``zero`` of zero are zeros. Returns the nodes, tetrahedra, triangles, their references,
|
|
585
|
+
the values of ``phi`` at the nodes (zero on the trace), those of the earlier level sets,
|
|
586
|
+
and the numbers of nodes moved and added."""
|
|
587
|
+
values = np.asarray(phi(nodes), dtype=float)
|
|
588
|
+
values[np.abs(values) <= zero] = 0.0
|
|
589
|
+
first = np.full(group.max() + 1, -1, dtype=np.int64)
|
|
590
|
+
first[group[::-1]] = np.arange(len(group))[::-1]
|
|
591
|
+
values = values[first[group]] # the same on the translates
|
|
592
|
+
earlier = [np.asarray(e, dtype=float).copy() for e in earlier]
|
|
593
|
+
nodes, tets, tri, refs, group = nodes.copy(), tets.copy(), tri.copy(), refs.copy(), group.copy()
|
|
594
|
+
moved = added = 0
|
|
595
|
+
|
|
596
|
+
def active():
|
|
597
|
+
"""The triangles of the faces out of the phases cut before."""
|
|
598
|
+
on = tri[np.isin(refs, faces)]
|
|
599
|
+
for e in earlier:
|
|
600
|
+
on = on[np.all(e[on] >= 0.0, axis=1)]
|
|
601
|
+
return on
|
|
602
|
+
|
|
603
|
+
def crossing():
|
|
604
|
+
edges = _unique_edges(active())
|
|
605
|
+
fa, fb = values[edges[:, 0]], values[edges[:, 1]]
|
|
606
|
+
return edges[fa * fb < 0]
|
|
607
|
+
|
|
608
|
+
def root(edges):
|
|
609
|
+
a, b = nodes[edges[:, 0]], nodes[edges[:, 1]]
|
|
610
|
+
lo, hi = np.zeros(len(edges)), np.ones(len(edges))
|
|
611
|
+
flo = values[edges[:, 0]]
|
|
612
|
+
for _ in range(iterations):
|
|
613
|
+
mid = 0.5 * (lo + hi)
|
|
614
|
+
fm = phi(a + mid[:, None] * (b - a))
|
|
615
|
+
same = np.sign(fm) == np.sign(flo)
|
|
616
|
+
lo, flo, hi = np.where(same, mid, lo), np.where(same, fm, flo), np.where(same, hi, mid)
|
|
617
|
+
return 0.5 * (lo + hi)
|
|
618
|
+
|
|
619
|
+
def faces_of(points):
|
|
620
|
+
lo, hi = nodes.min(axis=0), nodes.max(axis=0)
|
|
621
|
+
tol = TOLERANCE * float((hi - lo).max())
|
|
622
|
+
return (np.abs(points - lo) <= tol) | (np.abs(points - hi) <= tol)
|
|
623
|
+
|
|
624
|
+
frozen = np.zeros(len(nodes), dtype=bool) # the nodes of the earlier traces
|
|
625
|
+
for e in earlier:
|
|
626
|
+
frozen |= e == 0.0
|
|
627
|
+
# 1. the ends close to a zero move onto it (along an edge of the same faces), one end
|
|
628
|
+
# per crossed edge at most, and only where nodes of its sign remain around it on the
|
|
629
|
+
# faces (the trace keeps its topology: no node of one sign erased)
|
|
630
|
+
edges = crossing()
|
|
631
|
+
if len(edges):
|
|
632
|
+
t = root(edges)
|
|
633
|
+
side = faces_of(nodes)
|
|
634
|
+
on = active()
|
|
635
|
+
face_edges = _unique_edges(on)
|
|
636
|
+
same = np.zeros(len(nodes), dtype=np.int64) # neighbours of the same sign
|
|
637
|
+
sa, sb = np.sign(values[face_edges[:, 0]]), np.sign(values[face_edges[:, 1]])
|
|
638
|
+
np.add.at(same, face_edges[:, 0], (sa == sb) & (sa != 0))
|
|
639
|
+
np.add.at(same, face_edges[:, 1], (sa == sb) & (sa != 0))
|
|
640
|
+
# the changes of sign around a node (its triangles whose two other nodes have
|
|
641
|
+
# opposite signs): more than two, it is a saddle of the trace, and it stays
|
|
642
|
+
changes = np.zeros(len(nodes), dtype=np.int64)
|
|
643
|
+
sign = np.sign(values[on])
|
|
644
|
+
for i, j, k in ((0, 1, 2), (1, 2, 0), (2, 0, 1)):
|
|
645
|
+
np.add.at(changes, on[:, i], sign[:, j] * sign[:, k] < 0)
|
|
646
|
+
cand = []
|
|
647
|
+
for end, frac in ((0, t), (1, 1.0 - t)):
|
|
648
|
+
v = edges[:, end]
|
|
649
|
+
other = edges[:, 1 - end]
|
|
650
|
+
ok = (frac <= near) & np.all(side[v] <= side[other], axis=1) # stays on its faces
|
|
651
|
+
ok &= ~np.all(side[v], axis=1) & (same[v] > 0) & ~frozen[v] & (changes[v] <= 2)
|
|
652
|
+
cand += [(frac[k], int(v[k]), k) for k in np.flatnonzero(ok)]
|
|
653
|
+
accepted: dict[int, int] = {}
|
|
654
|
+
blocked = set()
|
|
655
|
+
for frac, v, k in sorted(cand):
|
|
656
|
+
if v in accepted or (v in blocked and frac > 1e-3):
|
|
657
|
+
continue # (a zero within a thousandth of a node is taken there)
|
|
658
|
+
accepted[v] = k
|
|
659
|
+
blocked.update((int(edges[k, 0]), int(edges[k, 1]))) # its edge: one end
|
|
660
|
+
chosen = np.array(sorted(accepted), dtype=np.int64)
|
|
661
|
+
target = np.zeros((len(nodes), 3))
|
|
662
|
+
interp = [np.zeros(len(nodes)) for _ in earlier]
|
|
663
|
+
for v, k in accepted.items():
|
|
664
|
+
a, b = edges[k]
|
|
665
|
+
target[v] = nodes[a] + t[k] * (nodes[b] - nodes[a])
|
|
666
|
+
for e, out in zip(earlier, interp, strict=True):
|
|
667
|
+
out[v] = e[a] + t[k] * (e[b] - e[a])
|
|
668
|
+
# one node of each group moves, the translates follow; no move that flips
|
|
669
|
+
rep = np.full(group.max() + 1, -1, dtype=np.int64)
|
|
670
|
+
rep[group[chosen]] = chosen
|
|
671
|
+
shift = np.zeros((group.max() + 1, 3))
|
|
672
|
+
shift[group[chosen]] = target[rep[group[chosen]]] - nodes[rep[group[chosen]]]
|
|
673
|
+
follow = np.flatnonzero(np.isin(group, group[chosen]))
|
|
674
|
+
trial = nodes.copy()
|
|
675
|
+
trial[follow] += shift[group[follow]]
|
|
676
|
+
around = np.flatnonzero(np.isin(tets, follow).any(axis=1))
|
|
677
|
+
bad = tet_volumes(trial, tets[around]) <= 0
|
|
678
|
+
if bad.any():
|
|
679
|
+
undo = np.isin(group, group[np.unique(tets[around][bad])])
|
|
680
|
+
trial[undo] = nodes[undo]
|
|
681
|
+
follow = follow[~undo[follow]]
|
|
682
|
+
before = values.copy()
|
|
683
|
+
values[follow] = 0.0
|
|
684
|
+
# a trace that touches itself, or branches: the moves of its nodes are undone (the
|
|
685
|
+
# edges they cross are split instead)
|
|
686
|
+
for _ in range(20):
|
|
687
|
+
pinched = _pinched(active(), values)
|
|
688
|
+
back = np.isin(group, group[np.intersect1d(pinched, follow)])
|
|
689
|
+
if not back.any():
|
|
690
|
+
break
|
|
691
|
+
trial[back] = nodes[back]
|
|
692
|
+
values[back] = before[back]
|
|
693
|
+
follow = follow[~back[follow]]
|
|
694
|
+
for e, out in zip(earlier, interp, strict=True):
|
|
695
|
+
lead = rep[group[follow]]
|
|
696
|
+
e[follow] = out[lead]
|
|
697
|
+
nodes = trial
|
|
698
|
+
moved = len(follow)
|
|
699
|
+
# 2. the other crossed edges split at their zeros, in rounds of disjoint stars
|
|
700
|
+
for _ in range(64):
|
|
701
|
+
edges = crossing()
|
|
702
|
+
if not len(edges):
|
|
703
|
+
break
|
|
704
|
+
t = root(edges)
|
|
705
|
+
# the parameter of an edge for all its translates: that of its first one
|
|
706
|
+
key = np.sort(group[edges], axis=1)
|
|
707
|
+
_, inv = np.unique(key, axis=0, return_inverse=True)
|
|
708
|
+
inv = inv.ravel()
|
|
709
|
+
lead = np.full(inv.max() + 1, -1, dtype=np.int64)
|
|
710
|
+
lead[inv[::-1]] = np.arange(len(inv))[::-1]
|
|
711
|
+
a_lead = group[edges[lead[inv], 0]]
|
|
712
|
+
t = np.where(a_lead == group[edges[:, 0]], t[lead[inv]], 1.0 - t[lead[inv]])
|
|
713
|
+
tet_edges = np.sort(tets[:, [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]], axis=2)
|
|
714
|
+
m = len(nodes)
|
|
715
|
+
tkey = (tet_edges[..., 0] * m + tet_edges[..., 1]).ravel()
|
|
716
|
+
ekey = edges[:, 0] * m + edges[:, 1]
|
|
717
|
+
order = np.argsort(tkey, kind="stable")
|
|
718
|
+
lo = np.searchsorted(tkey[order], ekey, side="left")
|
|
719
|
+
hi = np.searchsorted(tkey[order], ekey, side="right")
|
|
720
|
+
used = np.zeros(len(tets), dtype=bool)
|
|
721
|
+
new_tets, new_tri, new_nodes = [], [], []
|
|
722
|
+
new_earlier: list = [[] for _ in earlier]
|
|
723
|
+
drop_tets = np.zeros(len(tets), dtype=bool)
|
|
724
|
+
tri_of: dict = {}
|
|
725
|
+
for f, (i, j, k_) in enumerate(np.sort(tri, axis=1).tolist()):
|
|
726
|
+
for e in ((i, j), (i, k_), (j, k_)):
|
|
727
|
+
tri_of.setdefault(e, []).append(f)
|
|
728
|
+
# an edge and its translates split in the same round (splits of two edges of one
|
|
729
|
+
# triangle in turn leave it split along a diagonal that depends on their order)
|
|
730
|
+
units = np.split(np.argsort(inv, kind="stable"),
|
|
731
|
+
np.flatnonzero(np.diff(np.sort(inv))) + 1) # fmt: skip
|
|
732
|
+
for unit in units:
|
|
733
|
+
arounds = [order[lo[k] : hi[k]] // 6 for k in unit]
|
|
734
|
+
if any(used[around].any() for around in arounds):
|
|
735
|
+
continue
|
|
736
|
+
for k, around in zip(unit, arounds, strict=True):
|
|
737
|
+
used[around] = True
|
|
738
|
+
a, b = edges[k]
|
|
739
|
+
p = len(nodes) + len(new_nodes)
|
|
740
|
+
new_nodes.append(nodes[a] + t[k] * (nodes[b] - nodes[a]))
|
|
741
|
+
for e, out in zip(earlier, new_earlier, strict=True):
|
|
742
|
+
out.append(e[a] + t[k] * (e[b] - e[a]))
|
|
743
|
+
for e in around:
|
|
744
|
+
tet = tets[e]
|
|
745
|
+
drop_tets[e] = True
|
|
746
|
+
new_tets.append(np.where(tet == b, p, tet))
|
|
747
|
+
new_tets.append(np.where(tet == a, p, tet))
|
|
748
|
+
for f in tri_of.get((int(min(a, b)), int(max(a, b))), []):
|
|
749
|
+
face = tri[f]
|
|
750
|
+
new_tri.append((f, np.where(face == b, p, face),
|
|
751
|
+
np.where(face == a, p, face))) # fmt: skip
|
|
752
|
+
if not new_nodes:
|
|
753
|
+
break
|
|
754
|
+
nodes = np.vstack([nodes, np.array(new_nodes)])
|
|
755
|
+
tets = np.vstack([tets[~drop_tets], np.array(new_tets, dtype=np.int64)])
|
|
756
|
+
gone = np.zeros(len(tri), dtype=bool)
|
|
757
|
+
extra, extra_refs = [], []
|
|
758
|
+
for f, t1, t2 in new_tri:
|
|
759
|
+
gone[f] = True
|
|
760
|
+
extra += [t1, t2]
|
|
761
|
+
extra_refs += [refs[f], refs[f]]
|
|
762
|
+
tri = np.vstack([tri[~gone], np.array(extra, dtype=np.int64).reshape(-1, 3)])
|
|
763
|
+
refs = np.concatenate([refs[~gone], np.array(extra_refs, dtype=np.int64)])
|
|
764
|
+
values = np.concatenate([values, np.zeros(len(new_nodes))])
|
|
765
|
+
earlier = [np.concatenate([e, np.array(out)]) for e, out in
|
|
766
|
+
zip(earlier, new_earlier, strict=True)] # fmt: skip
|
|
767
|
+
frozen = np.concatenate([frozen, np.zeros(len(new_nodes), dtype=bool)])
|
|
768
|
+
group = np.concatenate([group, np.full(len(new_nodes), -1)])
|
|
769
|
+
added += len(new_nodes)
|
|
770
|
+
flip = tet_volumes(nodes, tets) < 0
|
|
771
|
+
tets[flip] = tets[flip][:, [0, 2, 1, 3]]
|
|
772
|
+
return nodes, tets, tri, refs, values, earlier, moved, added
|
|
773
|
+
|
|
774
|
+
|
|
775
|
+
def _split_across(phi, nodes, tets, tri, face, done, index, iterations=60):
|
|
776
|
+
"""The edges of tetrahedra between two nodes of the faces (``face``) that are not edges
|
|
777
|
+
of the faces (they cross the box near its edges) and that the level set ``phi`` (the
|
|
778
|
+
``index``-th of ``done``, its values at the nodes) crosses, split at its zero; the
|
|
779
|
+
values of the others at the new nodes (inside the box): their own. Returns the nodes,
|
|
780
|
+
tetrahedra, the number of nodes added and the values."""
|
|
781
|
+
edges = _unique_edges(tets)
|
|
782
|
+
edges = edges[face[edges[:, 0]] & face[edges[:, 1]]]
|
|
783
|
+
on = _unique_edges(tri)
|
|
784
|
+
m = len(nodes)
|
|
785
|
+
inner = ~np.isin(edges[:, 0] * m + edges[:, 1], on[:, 0] * m + on[:, 1])
|
|
786
|
+
edges = edges[inner]
|
|
787
|
+
values = done[index]
|
|
788
|
+
edges = edges[values[edges[:, 0]] * values[edges[:, 1]] < 0]
|
|
789
|
+
if not len(edges):
|
|
790
|
+
return nodes, tets, 0, done
|
|
791
|
+
a, b = nodes[edges[:, 0]], nodes[edges[:, 1]]
|
|
792
|
+
lo, hi = np.zeros(len(edges)), np.ones(len(edges))
|
|
793
|
+
flo = values[edges[:, 0]]
|
|
794
|
+
for _ in range(iterations):
|
|
795
|
+
mid = 0.5 * (lo + hi)
|
|
796
|
+
fm = phi(a + mid[:, None] * (b - a))
|
|
797
|
+
same = np.sign(fm) == np.sign(flo)
|
|
798
|
+
lo, flo, hi = np.where(same, mid, lo), np.where(same, fm, flo), np.where(same, hi, mid)
|
|
799
|
+
points = a + (0.5 * (lo + hi))[:, None] * (b - a)
|
|
800
|
+
tets = tets.copy()
|
|
801
|
+
for (i, j), point in zip(edges.tolist(), points, strict=True):
|
|
802
|
+
p = len(nodes)
|
|
803
|
+
nodes = np.vstack([nodes, point])
|
|
804
|
+
around = np.flatnonzero(np.any(tets == i, axis=1) & np.any(tets == j, axis=1))
|
|
805
|
+
halves = [np.where(tets[around] == j, p, tets[around]),
|
|
806
|
+
np.where(tets[around] == i, p, tets[around])] # fmt: skip
|
|
807
|
+
keep = np.ones(len(tets), dtype=bool)
|
|
808
|
+
keep[around] = False
|
|
809
|
+
tets = np.vstack([tets[keep], *halves])
|
|
810
|
+
added = len(edges)
|
|
811
|
+
done = [np.concatenate([d, np.full(added, np.nan)]) for d in done]
|
|
812
|
+
done[index][-added:] = 0.0
|
|
813
|
+
flip = tet_volumes(nodes, tets) < 0
|
|
814
|
+
tets[flip] = tets[flip][:, [0, 2, 1, 3]]
|
|
815
|
+
return nodes, tets, added, done
|
|
816
|
+
|
|
817
|
+
|
|
818
|
+
def _manifold_balls(tets, values, nodes_at, tiny) -> int:
|
|
819
|
+
"""The values of the level set made manifold around the zeros ``nodes_at`` (the nodes
|
|
820
|
+
of the matching faces that the traces go through): around such a node, the nodes of its
|
|
821
|
+
tetrahedra of each sign must form one component (MMG moves the zero off a node where
|
|
822
|
+
two sheets of the interface touch, and would cut the faces that it keeps); the nodes
|
|
823
|
+
of the smaller components, but those of the faces, take the other sign (``tiny``).
|
|
824
|
+
Returns the number of nodes changed."""
|
|
825
|
+
if not len(nodes_at):
|
|
826
|
+
return 0
|
|
827
|
+
order = np.argsort(tets.ravel(), kind="stable")
|
|
828
|
+
owners = order // 4
|
|
829
|
+
start = np.searchsorted(tets.ravel()[order], nodes_at, side="left")
|
|
830
|
+
stop = np.searchsorted(tets.ravel()[order], nodes_at, side="right")
|
|
831
|
+
fixed = np.zeros(len(values), dtype=bool)
|
|
832
|
+
fixed[nodes_at] = True
|
|
833
|
+
changed = 0
|
|
834
|
+
for a, lo, hi in zip(nodes_at.tolist(), start.tolist(), stop.tolist(), strict=True):
|
|
835
|
+
ball = tets[owners[lo:hi]]
|
|
836
|
+
link = [t[t != a] for t in ball]
|
|
837
|
+
for sign in (-1.0, 1.0):
|
|
838
|
+
parent: dict = {}
|
|
839
|
+
|
|
840
|
+
def find(x, parent=parent):
|
|
841
|
+
while parent.setdefault(x, x) != x:
|
|
842
|
+
parent[x] = parent[parent[x]]
|
|
843
|
+
x = parent[x]
|
|
844
|
+
return x
|
|
845
|
+
|
|
846
|
+
for tri in link:
|
|
847
|
+
members = [int(x) for x in tri if values[x] * sign > 0]
|
|
848
|
+
for x in members:
|
|
849
|
+
find(x)
|
|
850
|
+
for x, y in itertools.combinations(members, 2):
|
|
851
|
+
parent[find(x)] = find(y)
|
|
852
|
+
groups: dict = {}
|
|
853
|
+
for x in parent:
|
|
854
|
+
groups.setdefault(find(x), []).append(x)
|
|
855
|
+
if len(groups) < 2:
|
|
856
|
+
continue
|
|
857
|
+
parts = sorted(groups.values(), key=len, reverse=True)
|
|
858
|
+
keep = next((g for g in parts if fixed[g].any()), parts[0])
|
|
859
|
+
for g in parts:
|
|
860
|
+
if g is keep or fixed[g].any():
|
|
861
|
+
continue
|
|
862
|
+
values[g] = -sign * tiny
|
|
863
|
+
changed += len(g)
|
|
864
|
+
return changed
|
|
865
|
+
|
|
866
|
+
|
|
867
|
+
def _pinched(tri, values) -> np.ndarray:
|
|
868
|
+
"""The nodes where the zero level set of the piecewise linear interpolation of
|
|
869
|
+
``values`` on triangles is not a set of simple curves: the ends of the edges of zeros
|
|
870
|
+
whose triangles all have one sign on their third vertex (the trace touches itself), the
|
|
871
|
+
vertices of triangles of zeros, and the zeros where more than two edges of zeros
|
|
872
|
+
meet."""
|
|
873
|
+
tri = np.asarray(tri, dtype=np.int64)
|
|
874
|
+
a = tri[:, [0, 1, 0]].ravel()
|
|
875
|
+
b = tri[:, [1, 2, 2]].ravel()
|
|
876
|
+
c = tri[:, [2, 0, 1]].ravel()
|
|
877
|
+
zero = (values[a] == 0.0) & (values[b] == 0.0)
|
|
878
|
+
if not zero.any():
|
|
879
|
+
return np.zeros(0, dtype=np.int64)
|
|
880
|
+
key = np.column_stack([np.minimum(a, b), np.maximum(a, b)])[zero]
|
|
881
|
+
side = np.sign(values[c[zero]])
|
|
882
|
+
edges, inverse = np.unique(key, axis=0, return_inverse=True)
|
|
883
|
+
inverse = inverse.ravel()
|
|
884
|
+
pos = np.zeros(len(edges), dtype=bool)
|
|
885
|
+
neg = np.zeros(len(edges), dtype=bool)
|
|
886
|
+
np.logical_or.at(pos, inverse, side > 0)
|
|
887
|
+
np.logical_or.at(neg, inverse, side < 0)
|
|
888
|
+
bad = [edges[pos != neg].ravel()]
|
|
889
|
+
bad.append(tri[np.all(values[tri] == 0.0, axis=1)].ravel()) # triangles of zeros
|
|
890
|
+
degree = np.bincount(edges.ravel(), minlength=len(values)) # branching traces
|
|
891
|
+
bad.append(np.flatnonzero(degree > 2))
|
|
892
|
+
return np.unique(np.concatenate(bad))
|
|
893
|
+
|
|
894
|
+
|
|
895
|
+
def _groups(points, lower, upper, axes, tol) -> np.ndarray:
|
|
896
|
+
"""A label per point, shared by the translates of the points of the faces along the
|
|
897
|
+
periodic axes (their positions folded onto the lower faces)."""
|
|
898
|
+
folded = np.asarray(points, dtype=float).copy()
|
|
899
|
+
for d in range(3):
|
|
900
|
+
if axes[d]:
|
|
901
|
+
folded[np.abs(folded[:, d] - upper[d]) <= tol, d] = lower[d]
|
|
902
|
+
key = np.round((folded - lower) / (1e-3 * tol)).astype(np.int64)
|
|
903
|
+
return np.unique(key, axis=0, return_inverse=True)[1].ravel()
|
|
904
|
+
|
|
905
|
+
|
|
906
|
+
def _box_ridges(nodes, tri, lower, upper, tol):
|
|
907
|
+
"""The edges of the triangles of the faces of the box (``tri``) along its edges, and
|
|
908
|
+
its corners: MMG's ridges and corners, so that the box keeps its edges when MMG does not
|
|
909
|
+
detect ridges by angles."""
|
|
910
|
+
on = np.zeros((len(nodes), 6), dtype=bool)
|
|
911
|
+
for d in range(3):
|
|
912
|
+
on[:, 2 * d] = np.abs(nodes[:, d] - lower[d]) <= tol
|
|
913
|
+
on[:, 2 * d + 1] = np.abs(nodes[:, d] - upper[d]) <= tol
|
|
914
|
+
edges = np.sort(np.concatenate([tri[:, [0, 1]], tri[:, [1, 2]], tri[:, [2, 0]]]), axis=1)
|
|
915
|
+
edges = np.unique(edges, axis=0)
|
|
916
|
+
along = (on[edges[:, 0]] & on[edges[:, 1]]).sum(axis=1) >= 2
|
|
917
|
+
return edges[along], np.flatnonzero(on.sum(axis=1) == 3)
|
|
918
|
+
|
|
919
|
+
|
|
920
|
+
def _project(phi, nodes, elements, moving, *, step, limit, lower, upper, tol, group=None,
|
|
921
|
+
rounds=4): # fmt: skip
|
|
922
|
+
"""The nodes ``moving`` moved onto the zero level set by Newton's method along its
|
|
923
|
+
gradient (central differences of ``step``), on the faces of the box they lie on; the
|
|
924
|
+
moves larger than ``limit`` undone, and those that would flip an element or flatten it
|
|
925
|
+
(to a quality below 0.02 and a fifth of its own) halved until they do not, four times
|
|
926
|
+
at most, then undone (for all the nodes of a ``group``: the translates of a node of a
|
|
927
|
+
periodic face move alike). ``phi`` may give several functions at each point (a column
|
|
928
|
+
each, the surfaces of the pieces that meet along a sharp edge): the nodes then move to
|
|
929
|
+
where they all vanish, by the smallest move at each step (the pseudo-inverse of their
|
|
930
|
+
Jacobian). Returns the nodes, the number moved and the largest move."""
|
|
931
|
+
if group is not None: # one node of each group moves, the others follow
|
|
932
|
+
rep = np.full(group.max() + 1, -1, dtype=np.int64)
|
|
933
|
+
rep[group[moving][::-1]] = moving[::-1]
|
|
934
|
+
moving = np.unique(rep[group[moving]])
|
|
935
|
+
x0 = nodes[moving]
|
|
936
|
+
x = x0.copy()
|
|
937
|
+
fixed = np.zeros(x.shape, dtype=bool)
|
|
938
|
+
for d in range(3):
|
|
939
|
+
fixed[:, d] = (np.abs(x[:, d] - lower[d]) <= tol) | (np.abs(x[:, d] - upper[d]) <= tol)
|
|
940
|
+
for _ in range(rounds):
|
|
941
|
+
f = np.asarray(phi(x), dtype=float)
|
|
942
|
+
if f.ndim == 1:
|
|
943
|
+
g = np.empty_like(x)
|
|
944
|
+
for d in range(3):
|
|
945
|
+
e = np.zeros(3)
|
|
946
|
+
e[d] = step
|
|
947
|
+
g[:, d] = (phi(x + e) - phi(x - e)) / (2.0 * step)
|
|
948
|
+
g[fixed] = 0.0
|
|
949
|
+
g2 = np.einsum("ij,ij->i", g, g)
|
|
950
|
+
ok = g2 > 1e-12
|
|
951
|
+
x[ok] -= (f[ok] / g2[ok])[:, None] * g[ok]
|
|
952
|
+
continue
|
|
953
|
+
jacobian = np.empty((len(x), f.shape[1], 3))
|
|
954
|
+
for d in range(3):
|
|
955
|
+
e = np.zeros(3)
|
|
956
|
+
e[d] = step
|
|
957
|
+
jacobian[:, :, d] = (np.asarray(phi(x + e)) - np.asarray(phi(x - e))) / (2.0 * step)
|
|
958
|
+
jacobian *= ~fixed[:, None, :]
|
|
959
|
+
x -= np.einsum("ndk,nk->nd", np.linalg.pinv(jacobian), f)
|
|
960
|
+
move = np.linalg.norm(x - x0, axis=1)
|
|
961
|
+
ok = np.isfinite(move) & (move <= limit)
|
|
962
|
+
shift = np.zeros_like(nodes)
|
|
963
|
+
shift[moving[ok]] = x[ok] - x0[ok]
|
|
964
|
+
touched = np.zeros(len(nodes), dtype=bool)
|
|
965
|
+
touched[moving[ok]] = True
|
|
966
|
+
if group is not None: # the translates follow
|
|
967
|
+
by_group = np.zeros((group.max() + 1, 3))
|
|
968
|
+
by_group[group[moving[ok]]] = shift[moving[ok]]
|
|
969
|
+
member = np.zeros(group.max() + 1, dtype=bool)
|
|
970
|
+
member[group[moving[ok]]] = True
|
|
971
|
+
touched = member[group]
|
|
972
|
+
shift[touched] = by_group[group[touched]]
|
|
973
|
+
# the moves that flip an element, or flatten it (below a fiftieth, and a fifth of its
|
|
974
|
+
# quality), halved (the node as near the surface as the elements allow), then undone
|
|
975
|
+
near = np.flatnonzero(touched[elements].any(axis=1))
|
|
976
|
+
q0 = tet_quality(nodes, elements[near])
|
|
977
|
+
scale = touched.astype(float) # the fraction of its move that each node makes
|
|
978
|
+
out = nodes + scale[:, None] * shift
|
|
979
|
+
for _ in range(100):
|
|
980
|
+
out = nodes + scale[:, None] * shift
|
|
981
|
+
vol = tet_volumes(out, elements[near])
|
|
982
|
+
q = tet_quality(out, elements[near])
|
|
983
|
+
bad = (vol <= 0) | ((q < 0.02) & (q < 0.2 * q0))
|
|
984
|
+
if not bad.any():
|
|
985
|
+
break
|
|
986
|
+
back = np.unique(elements[near][bad])
|
|
987
|
+
back = back[scale[back] > 0]
|
|
988
|
+
if group is not None:
|
|
989
|
+
back = np.flatnonzero(np.isin(group, group[back]) & (scale > 0))
|
|
990
|
+
scale[back] = np.where(scale[back] > 0.1, 0.5 * scale[back], 0.0)
|
|
991
|
+
else: # (never seen) the moves of the nodes of the elements still bad undone
|
|
992
|
+
while bad.any():
|
|
993
|
+
back = np.unique(elements[near][bad])
|
|
994
|
+
if group is not None:
|
|
995
|
+
back = np.flatnonzero(np.isin(group, group[back]))
|
|
996
|
+
scale[back] = 0.0
|
|
997
|
+
out = nodes + scale[:, None] * shift
|
|
998
|
+
q = tet_quality(out, elements[near])
|
|
999
|
+
bad = (tet_volumes(out, elements[near]) <= 0) | ((q < 0.02) & (q < 0.2 * q0))
|
|
1000
|
+
touched = scale > 0
|
|
1001
|
+
moved = np.flatnonzero(touched)
|
|
1002
|
+
largest = float(np.linalg.norm(out[moved] - nodes[moved], axis=1).max()) if moved.size else 0.0
|
|
1003
|
+
return out, int(moved.size), largest
|
|
1004
|
+
|
|
1005
|
+
|
|
1006
|
+
class _Cut:
|
|
1007
|
+
"""A phase cut out of what the cuts before left by its level set ``function``: one of
|
|
1008
|
+
the pieces of :func:`morphogen.mesh.conforming._mmg_pieces`, which cuts them in turn
|
|
1009
|
+
without remeshing, then remeshes once."""
|
|
1010
|
+
|
|
1011
|
+
def __init__(self, phase: int, function):
|
|
1012
|
+
self.phase, self.function = int(phase), function
|
|
1013
|
+
|
|
1014
|
+
def at(self, points, band: float) -> np.ndarray:
|
|
1015
|
+
return np.clip(self.function(np.asarray(points, dtype=float)), -band, band)
|
|
1016
|
+
|
|
1017
|
+
|
|
1018
|
+
def _kept(phases, present: list[int]) -> tuple[str, list[int] | None]:
|
|
1019
|
+
"""The phases kept of a structure of the phases ``present``: ``"all"``, ``"solid"``
|
|
1020
|
+
or ``"matrix"`` (of the phases 0 and 1, kept by MMG), or a list (kept from the whole
|
|
1021
|
+
mesh). Returns the name of the two-phase request (``"all"`` otherwise) and the list of
|
|
1022
|
+
the phases to keep (None: all)."""
|
|
1023
|
+
if isinstance(phases, str):
|
|
1024
|
+
if phases not in ("all", "solid", "matrix"):
|
|
1025
|
+
raise ValueError(
|
|
1026
|
+
"phases: 'all', 'solid' (phase 1), 'matrix' (phase 0) or the phases to keep"
|
|
1027
|
+
)
|
|
1028
|
+
if phases != "all" and present != [0, 1]:
|
|
1029
|
+
raise ValueError(
|
|
1030
|
+
f"phases: 'all' or the phases to keep among {present} (a structure of "
|
|
1031
|
+
"several phases)"
|
|
1032
|
+
)
|
|
1033
|
+
return phases, None
|
|
1034
|
+
wanted = sorted({int(k) for k in phases})
|
|
1035
|
+
unknown = sorted(set(wanted) - set(present))
|
|
1036
|
+
if unknown:
|
|
1037
|
+
raise ValueError(f"phases: {unknown} are not phases of this structure ({present})")
|
|
1038
|
+
if present == [0, 1]: # two phases: MMG keeps one
|
|
1039
|
+
return {(1,): "solid", (0,): "matrix"}.get(tuple(wanted), "all"), None
|
|
1040
|
+
return "all", wanted
|
|
1041
|
+
|
|
1042
|
+
|
|
1043
|
+
def _sharp_groups(sharp, sharp_pieces, n: int) -> dict[tuple, np.ndarray]:
|
|
1044
|
+
"""The nodes of the sharp edges by the pieces that meet there: two for the nodes of
|
|
1045
|
+
one sharp edge, more where sharp edges join."""
|
|
1046
|
+
found: dict[int, set] = {}
|
|
1047
|
+
for (a, b), pair in zip(sharp.tolist(), sharp_pieces.tolist(), strict=True):
|
|
1048
|
+
for node in (a, b):
|
|
1049
|
+
found.setdefault(node, set()).update(pair)
|
|
1050
|
+
groups: dict[tuple, list[int]] = {}
|
|
1051
|
+
for node, pieces in found.items():
|
|
1052
|
+
groups.setdefault(tuple(sorted(pieces)), []).append(node)
|
|
1053
|
+
return {key: np.array(sorted(nodes), dtype=np.int64) for key, nodes in groups.items()}
|
|
1054
|
+
|
|
1055
|
+
|
|
1056
|
+
def adaptive_mesh(
|
|
1057
|
+
micro,
|
|
1058
|
+
*,
|
|
1059
|
+
size: float,
|
|
1060
|
+
hausdorff: float | None = None,
|
|
1061
|
+
min_size: float | None = None,
|
|
1062
|
+
gradation: float = 1.8,
|
|
1063
|
+
phases="all",
|
|
1064
|
+
order: int = 1,
|
|
1065
|
+
periodic=None,
|
|
1066
|
+
lipschitz: float | None = None,
|
|
1067
|
+
project: bool = True,
|
|
1068
|
+
remove_islands: float | None = None,
|
|
1069
|
+
ridges: bool = False,
|
|
1070
|
+
sharp_edges: bool | None = None,
|
|
1071
|
+
retries: int = 2,
|
|
1072
|
+
executable: str | None = None,
|
|
1073
|
+
workdir=None,
|
|
1074
|
+
timeout: float | None = None,
|
|
1075
|
+
) -> TetMesh:
|
|
1076
|
+
"""Conforming tetrahedral mesh of the exact implicit functions of the phases of a
|
|
1077
|
+
microstructure (``micro.phase_level_sets_at``; an object with a ``level_set_at``
|
|
1078
|
+
only: its two phases), refined where they need it, without a grid (see the module).
|
|
1079
|
+
|
|
1080
|
+
Parameters
|
|
1081
|
+
----------
|
|
1082
|
+
size
|
|
1083
|
+
Largest element size.
|
|
1084
|
+
hausdorff
|
|
1085
|
+
Largest distance between the meshed and the exact interfaces (default ``size /
|
|
1086
|
+
20``): the edges near the interface are split until the level set departs from its
|
|
1087
|
+
linear interpolation by at most this distance.
|
|
1088
|
+
min_size
|
|
1089
|
+
Smallest element size (default: ``hausdorff``): features thinner than about it are
|
|
1090
|
+
meshed less accurately.
|
|
1091
|
+
gradation
|
|
1092
|
+
Largest ratio of the sizes of neighbouring elements.
|
|
1093
|
+
phases
|
|
1094
|
+
``"all"``, ``"solid"`` (phase 1) or ``"matrix"`` (phase 0) of a structure of the
|
|
1095
|
+
phases 0 and 1; or the phases to keep (a list), of any structure.
|
|
1096
|
+
order
|
|
1097
|
+
1 (4-node tetrahedra) or 2 (10-node tetrahedra, curved onto the interfaces by
|
|
1098
|
+
:func:`morphogen.mesh.curved.curved_mesh` when ``project``, straight otherwise).
|
|
1099
|
+
periodic
|
|
1100
|
+
Matching opposite faces (default: when the microstructure is periodic), or three
|
|
1101
|
+
booleans: along those axes.
|
|
1102
|
+
lipschitz
|
|
1103
|
+
Bound of the slope of the level set (default: the microstructure's
|
|
1104
|
+
``lipschitz``, 1 for a signed distance): the edges farther from the interface than
|
|
1105
|
+
it allows are not refined.
|
|
1106
|
+
project
|
|
1107
|
+
Move the nodes of the interface onto the exact zero level set.
|
|
1108
|
+
remove_islands
|
|
1109
|
+
Relative volume below which MMG removes isolated components (``-rmc``; none by
|
|
1110
|
+
default: the geometry is exact; non-periodic meshes of two phases only).
|
|
1111
|
+
ridges
|
|
1112
|
+
Let MMG detect ridges on the cut (dihedral angles above 45°): the sharp edges of the
|
|
1113
|
+
geometry (the intersections of spheres, the rims of dead leaves) stay sharp, at the
|
|
1114
|
+
price of flat elements where the facets of the cut bend at the scale of the octree
|
|
1115
|
+
(0.5 % of the elements of a sheet gyroid below a quality of 10⁻³). Off by default:
|
|
1116
|
+
those edges are rounded within the Hausdorff distance, the edges of the box kept.
|
|
1117
|
+
sharp_edges
|
|
1118
|
+
Follow the sharp edges of the phases of the structures that give their smooth
|
|
1119
|
+
pieces (:meth:`~morphogen.models.base.Microstructure.implicit_pieces`: the unions
|
|
1120
|
+
of spheres and segments, their coatings and bores) with edges of the mesh: the
|
|
1121
|
+
octree is refined on the surfaces of the pieces, the box cut by each in turn, and
|
|
1122
|
+
the lines where two cuts meet kept as ridges (``mesh.sharp``), their nodes moved
|
|
1123
|
+
onto both surfaces. By default when two pieces of a phase meet; false rounds these
|
|
1124
|
+
edges within the Hausdorff distance. Two primitives that enter each other by less
|
|
1125
|
+
than the Hausdorff distance are in the same piece (their edge is rounded).
|
|
1126
|
+
retries
|
|
1127
|
+
Periodic meshes whose opposite faces do not match (MMG remeshes a face where the
|
|
1128
|
+
interface touches itself on it) are made again on another octree (one more root
|
|
1129
|
+
cell along each axis), up to this number of times.
|
|
1130
|
+
"""
|
|
1131
|
+
return _adaptive_mesh(
|
|
1132
|
+
micro,
|
|
1133
|
+
size=size,
|
|
1134
|
+
hausdorff=hausdorff,
|
|
1135
|
+
min_size=min_size,
|
|
1136
|
+
gradation=gradation,
|
|
1137
|
+
phases=phases,
|
|
1138
|
+
order=order,
|
|
1139
|
+
periodic=periodic,
|
|
1140
|
+
lipschitz=lipschitz,
|
|
1141
|
+
project=project,
|
|
1142
|
+
remove_islands=remove_islands,
|
|
1143
|
+
ridges=ridges,
|
|
1144
|
+
sharp_edges=sharp_edges,
|
|
1145
|
+
retries=retries,
|
|
1146
|
+
executable=executable,
|
|
1147
|
+
workdir=workdir,
|
|
1148
|
+
timeout=timeout,
|
|
1149
|
+
attempt=0,
|
|
1150
|
+
)
|
|
1151
|
+
|
|
1152
|
+
|
|
1153
|
+
def _adaptive_mesh(
|
|
1154
|
+
micro,
|
|
1155
|
+
*,
|
|
1156
|
+
size: float,
|
|
1157
|
+
hausdorff: float | None = None,
|
|
1158
|
+
min_size: float | None = None,
|
|
1159
|
+
gradation: float = 1.8,
|
|
1160
|
+
phases="all",
|
|
1161
|
+
order: int = 1,
|
|
1162
|
+
periodic=None,
|
|
1163
|
+
lipschitz: float | None = None,
|
|
1164
|
+
project: bool = True,
|
|
1165
|
+
remove_islands: float | None = None,
|
|
1166
|
+
ridges: bool = False,
|
|
1167
|
+
sharp_edges: bool | None = None,
|
|
1168
|
+
retries: int = 2,
|
|
1169
|
+
executable: str | None = None,
|
|
1170
|
+
workdir=None,
|
|
1171
|
+
timeout: float | None = None,
|
|
1172
|
+
attempt: int,
|
|
1173
|
+
at_once: bool = False,
|
|
1174
|
+
) -> TetMesh:
|
|
1175
|
+
""":func:`adaptive_mesh`, on an octree of ``attempt`` more root cells per side
|
|
1176
|
+
(``at_once``: the two phases cut first and remeshed once, as several are)."""
|
|
1177
|
+
from morphogen.mesh.conforming import REF_PHASE, _mmg_pieces
|
|
1178
|
+
from morphogen.mesh.octree import LINES, SEGMENTS, Octree
|
|
1179
|
+
from morphogen.models.implicit import functions_at, implicit_phases_of
|
|
1180
|
+
|
|
1181
|
+
if order not in (1, 2):
|
|
1182
|
+
raise ValueError("order: 1 or 2")
|
|
1183
|
+
size = float(size)
|
|
1184
|
+
if not size > 0:
|
|
1185
|
+
raise ValueError("size: must be positive")
|
|
1186
|
+
hausd = float(hausdorff) if hausdorff is not None else size / 20.0
|
|
1187
|
+
hmin = float(min_size) if min_size is not None else hausd
|
|
1188
|
+
if not (hausd > 0 and 0 < hmin <= size):
|
|
1189
|
+
raise ValueError("hausdorff and min_size: positive, min_size at most size")
|
|
1190
|
+
present = implicit_phases_of(micro)
|
|
1191
|
+
two, keep = _kept(phases, present)
|
|
1192
|
+
domain = micro.domain
|
|
1193
|
+
axes = _periodic_axes(domain.periodic if periodic is None else periodic)
|
|
1194
|
+
if any(axes) and not domain.periodic:
|
|
1195
|
+
raise ValueError("matching periodic faces need a periodic microstructure")
|
|
1196
|
+
lip = float(lipschitz if lipschitz is not None else getattr(micro, "lipschitz", 1.0))
|
|
1197
|
+
lower = np.asarray(domain.lower, dtype=float)
|
|
1198
|
+
upper = np.asarray(domain.upper, dtype=float)
|
|
1199
|
+
tol = TOLERANCE * float((upper - lower).max())
|
|
1200
|
+
reach = max(lip, 1.0) * size # the lines of the octree are at most ``size`` long
|
|
1201
|
+
# the phases cut one after the other out of the rest: phase 0, or the last one
|
|
1202
|
+
rest = 0 if 0 in present else present[-1]
|
|
1203
|
+
keys = [k for k in present if k != rest]
|
|
1204
|
+
if not keys:
|
|
1205
|
+
raise ValueError(f"{type(micro).__name__}: a single phase, no interface to mesh")
|
|
1206
|
+
several = len(keys) > 1
|
|
1207
|
+
try:
|
|
1208
|
+
functions_at(micro, np.reshape(lower, (1, 3)), reach)
|
|
1209
|
+
except NotImplementedError:
|
|
1210
|
+
raise TypeError(
|
|
1211
|
+
f"{type(micro).__name__}: no point-wise functions of its phases "
|
|
1212
|
+
"(phase_level_sets_at), so no adaptive mesh; see morphogen.mesh.exact.exact_mesh"
|
|
1213
|
+
) from None
|
|
1214
|
+
# the smooth pieces of the phases, whose sharp edges the mesh follows
|
|
1215
|
+
pieces = None
|
|
1216
|
+
if sharp_edges is None or sharp_edges:
|
|
1217
|
+
found = getattr(micro, "implicit_pieces", lambda depth: None)(hausd)
|
|
1218
|
+
if found is None and sharp_edges:
|
|
1219
|
+
raise ValueError(
|
|
1220
|
+
f"sharp_edges: {type(micro).__name__} does not give the smooth pieces of its "
|
|
1221
|
+
"phases (the unions of spheres and segments and their coatings do)"
|
|
1222
|
+
)
|
|
1223
|
+
if found is not None:
|
|
1224
|
+
counts: dict[int, int] = {}
|
|
1225
|
+
for piece in found[0]:
|
|
1226
|
+
counts[piece.phase] = counts.get(piece.phase, 0) + 1
|
|
1227
|
+
if sharp_edges or max(counts.values(), default=0) > 1:
|
|
1228
|
+
pieces, rest = found
|
|
1229
|
+
|
|
1230
|
+
def phis(points, r: float = reach) -> dict:
|
|
1231
|
+
"""The functions of the phases at the points, exact within ``r`` of the
|
|
1232
|
+
interfaces."""
|
|
1233
|
+
out = functions_at(micro, points, r)
|
|
1234
|
+
sets = {k: np.asarray(out[k], dtype=float) for k in present if k in out}
|
|
1235
|
+
if rest not in sets: # the phase that the others leave
|
|
1236
|
+
sets[rest] = -np.minimum.reduce([sets[k] for k in keys])
|
|
1237
|
+
return sets
|
|
1238
|
+
|
|
1239
|
+
def level(k):
|
|
1240
|
+
"""The level set that cuts phase ``k`` out of the rest: half its own minus the
|
|
1241
|
+
smallest of those of the phases cut after it and of the rest — the boundaries of
|
|
1242
|
+
``k`` with these only, clearly negative on its boundaries with the phases cut
|
|
1243
|
+
before (two phases: that of the phase cut)."""
|
|
1244
|
+
later = [*keys[keys.index(k) + 1 :], rest]
|
|
1245
|
+
|
|
1246
|
+
def function(points):
|
|
1247
|
+
sets = phis(points)
|
|
1248
|
+
return 0.5 * (sets[k] - np.minimum.reduce([sets[j] for j in later]))
|
|
1249
|
+
|
|
1250
|
+
return function
|
|
1251
|
+
|
|
1252
|
+
def between(a, b, r: float = reach):
|
|
1253
|
+
"""Half the difference of the level sets of two phases: zero on their interface."""
|
|
1254
|
+
|
|
1255
|
+
def function(points):
|
|
1256
|
+
sets = phis(points, r)
|
|
1257
|
+
return 0.5 * (sets[a] - sets[b])
|
|
1258
|
+
|
|
1259
|
+
return function
|
|
1260
|
+
|
|
1261
|
+
def surfaces(points, r: float) -> list:
|
|
1262
|
+
"""The functions that the octree resolves, exact within ``r``: those of the phases
|
|
1263
|
+
cut, or of the smooth pieces."""
|
|
1264
|
+
if pieces is not None:
|
|
1265
|
+
return [piece.at(points, r) for piece in pieces]
|
|
1266
|
+
sets = phis(points, r)
|
|
1267
|
+
return [sets[k] for k in keys]
|
|
1268
|
+
|
|
1269
|
+
exe = mmg_executable(executable)
|
|
1270
|
+
t0 = time.perf_counter()
|
|
1271
|
+
# the octree: root cells of about the size, split where their lines miss a level set
|
|
1272
|
+
n = np.maximum(1, np.ceil((upper - lower) / size - 1e-9)).astype(int) + attempt
|
|
1273
|
+
depth = int(np.ceil(np.log2(float(np.max((upper - lower) / n)) / hmin) - 1e-9))
|
|
1274
|
+
tree = Octree(lower, upper, n, axes, max(depth, 0))
|
|
1275
|
+
|
|
1276
|
+
def test(points, sides):
|
|
1277
|
+
# the cells of a level together: their lines need the level sets within their
|
|
1278
|
+
# length, beyond which the tests see them clipped (the cost of the functions of
|
|
1279
|
+
# many objects, leaves or primitives, grows as the cube of that reach)
|
|
1280
|
+
r = min(reach, max(lip, 1.0) * float(np.max(sides)))
|
|
1281
|
+
fields = surfaces(points.reshape(-1, 3), r)
|
|
1282
|
+
split = np.zeros(len(points), dtype=bool)
|
|
1283
|
+
for values in fields:
|
|
1284
|
+
f = values.reshape(-1, 27)
|
|
1285
|
+
for d, (i0, i1, i2) in LINES:
|
|
1286
|
+
split |= _to_split(f[:, i0], f[:, i1], f[:, i2], sides[:, d], hmin=hmin,
|
|
1287
|
+
hausd=hausd, lipschitz=lip) # fmt: skip
|
|
1288
|
+
# the others: along the segments that may be edges of their tetrahedra, a kink
|
|
1289
|
+
# between the samples misplaces the zero of the linear interpolation, which the
|
|
1290
|
+
# level set tells
|
|
1291
|
+
rest_cells = np.flatnonzero(~split & (sides.min(axis=1) > 1.5 * hmin))
|
|
1292
|
+
for chunk in np.array_split(rest_cells, max(1, -(-len(rest_cells) // 8192))):
|
|
1293
|
+
cells, where, which = [], [], []
|
|
1294
|
+
for i, values in enumerate(fields):
|
|
1295
|
+
f = values.reshape(-1, 27)[chunk]
|
|
1296
|
+
fa, fb = f[:, SEGMENTS[:, 0]], f[:, SEGMENTS[:, 1]]
|
|
1297
|
+
c, j = np.nonzero(fa * fb < 0)
|
|
1298
|
+
t = fa[c, j] / (fa[c, j] - fb[c, j])
|
|
1299
|
+
a, b = points[chunk[c], SEGMENTS[j, 0]], points[chunk[c], SEGMENTS[j, 1]]
|
|
1300
|
+
cells.append(chunk[c])
|
|
1301
|
+
where.append(a + t[:, None] * (b - a))
|
|
1302
|
+
which.append(np.full(len(c), i))
|
|
1303
|
+
cells = np.concatenate(cells)
|
|
1304
|
+
if len(cells):
|
|
1305
|
+
which = np.concatenate(which)
|
|
1306
|
+
at = surfaces(np.concatenate(where), r)
|
|
1307
|
+
value = np.zeros(len(cells))
|
|
1308
|
+
for i in range(len(fields)):
|
|
1309
|
+
value[which == i] = at[i][which == i]
|
|
1310
|
+
split[cells[np.abs(value) > hausd]] = True
|
|
1311
|
+
return split
|
|
1312
|
+
|
|
1313
|
+
splits = tree.refine(test)
|
|
1314
|
+
balanced = tree.balance()
|
|
1315
|
+
nodes, tets, tri, tri_refs, _ = tree.tetrahedra()
|
|
1316
|
+
n_octree = len(tets)
|
|
1317
|
+
t_tree = time.perf_counter() - t0
|
|
1318
|
+
required: list[int] = _matching_refs(axes)
|
|
1319
|
+
on_faces = _on_faces(axes, lower, upper)
|
|
1320
|
+
moved = added = 0
|
|
1321
|
+
sharp = sharp_pieces = None
|
|
1322
|
+
# several phases, or pieces: cut in turn without remeshing, then remeshed once
|
|
1323
|
+
once = pieces is not None or several or at_once
|
|
1324
|
+
t1 = time.perf_counter()
|
|
1325
|
+
if (several or at_once) and pieces is None:
|
|
1326
|
+
# the lines where three phases meet kept as ridges, the faces of the box cut by MMG
|
|
1327
|
+
# alike on opposite sides (see morphogen.mesh.conforming._mmg_pieces)
|
|
1328
|
+
data, _, _ = _mmg_pieces(
|
|
1329
|
+
exe, nodes, tets, tri, tri_refs, [_Cut(k, level(k)) for k in keys], rest,
|
|
1330
|
+
(lower, upper), axes, on_faces, reach, size=size, min_size=hmin,
|
|
1331
|
+
hausdorff=hausd, gradation=gradation, workdir=workdir, timeout=timeout,
|
|
1332
|
+
) # fmt: skip
|
|
1333
|
+
elif pieces is not None:
|
|
1334
|
+
# the box cut by the surface of each piece in turn, the lines where two cuts meet
|
|
1335
|
+
# kept as ridges (see morphogen.mesh.conforming._mmg_pieces)
|
|
1336
|
+
try:
|
|
1337
|
+
data, sharp, sharp_pieces = _mmg_pieces(
|
|
1338
|
+
exe, nodes, tets, tri, tri_refs, pieces, rest, (lower, upper), axes, on_faces,
|
|
1339
|
+
reach, size=size, min_size=hmin, hausdorff=hausd, gradation=gradation,
|
|
1340
|
+
workdir=workdir, timeout=timeout,
|
|
1341
|
+
) # fmt: skip
|
|
1342
|
+
except (RuntimeError, subprocess.TimeoutExpired) as error:
|
|
1343
|
+
if sharp_edges:
|
|
1344
|
+
raise
|
|
1345
|
+
log.warning("adaptive mesh: the sharp edges could not be followed (%s); they are "
|
|
1346
|
+
"rounded instead", str(error).splitlines()[0]) # fmt: skip
|
|
1347
|
+
return _adaptive_mesh(
|
|
1348
|
+
micro, size=size, hausdorff=hausdorff, min_size=min_size, gradation=gradation,
|
|
1349
|
+
phases=phases, order=order, periodic=periodic, lipschitz=lipschitz,
|
|
1350
|
+
project=project, remove_islands=remove_islands, ridges=ridges,
|
|
1351
|
+
sharp_edges=False, retries=retries, executable=executable, workdir=workdir,
|
|
1352
|
+
timeout=timeout, attempt=attempt, at_once=at_once,
|
|
1353
|
+
) # fmt: skip
|
|
1354
|
+
else:
|
|
1355
|
+
try:
|
|
1356
|
+
cut = _cut_two(
|
|
1357
|
+
exe, nodes, tets, tri, tri_refs, level(keys[0]), (keys[0], rest), axes,
|
|
1358
|
+
required, on_faces, lower, upper, tol, hausd, hmin, size, gradation, two,
|
|
1359
|
+
ridges, remove_islands, workdir, timeout,
|
|
1360
|
+
) # fmt: skip
|
|
1361
|
+
except (RuntimeError, subprocess.TimeoutExpired) as error:
|
|
1362
|
+
# MMG could not remesh along the cut: cut first, then remeshed once
|
|
1363
|
+
log.warning("adaptive mesh: MMG failed on the cut of the phases (%s); cut without "
|
|
1364
|
+
"remeshing, then remeshed once", str(error).splitlines()[0]) # fmt: skip
|
|
1365
|
+
once = True
|
|
1366
|
+
data, _, _ = _mmg_pieces(
|
|
1367
|
+
exe, nodes, tets, tri, tri_refs, [_Cut(k, level(k)) for k in keys], rest,
|
|
1368
|
+
(lower, upper), axes, on_faces, reach, size=size, min_size=hmin,
|
|
1369
|
+
hausdorff=hausd, gradation=gradation, workdir=workdir, timeout=timeout,
|
|
1370
|
+
) # fmt: skip
|
|
1371
|
+
else:
|
|
1372
|
+
nodes, tets, phase, moved, added = cut
|
|
1373
|
+
if once:
|
|
1374
|
+
nodes, tets = data["Vertices"], data["Tetrahedra"]
|
|
1375
|
+
for d in range(3): # the nodes of the faces exactly on them
|
|
1376
|
+
nodes[np.abs(nodes[:, d] - lower[d]) <= tol, d] = lower[d]
|
|
1377
|
+
nodes[np.abs(nodes[:, d] - upper[d]) <= tol, d] = upper[d]
|
|
1378
|
+
phase = data["Tetrahedra_refs"] - REF_PHASE
|
|
1379
|
+
t_cut = time.perf_counter() - t1
|
|
1380
|
+
xyz, elements = nodes, tets
|
|
1381
|
+
flip = tet_volumes(xyz, elements) < 0
|
|
1382
|
+
elements[flip] = elements[flip][:, [0, 2, 1, 3]]
|
|
1383
|
+
used, inverse = np.unique(elements, return_inverse=True)
|
|
1384
|
+
xyz, elements = xyz[used], inverse.reshape(elements.shape)
|
|
1385
|
+
if sharp is not None: # the sharp edges, between the nodes of the mesh
|
|
1386
|
+
numbers = np.full(len(nodes), -1, dtype=np.int64)
|
|
1387
|
+
numbers[used] = np.arange(len(used))
|
|
1388
|
+
there = (numbers[sharp] >= 0).all(axis=1)
|
|
1389
|
+
sharp, sharp_pieces = numbers[sharp[there]], sharp_pieces[there]
|
|
1390
|
+
projected, largest = 0, 0.0
|
|
1391
|
+
if project:
|
|
1392
|
+
# the nodes lie within a few Hausdorff distances of their surfaces: the functions
|
|
1393
|
+
# there (and as far as the moves allowed, a quarter of the size)
|
|
1394
|
+
near = min(reach, max(lip, 1.0) * max(8.0 * hausd, 2.0 * hmin, 0.3 * size))
|
|
1395
|
+
projected, largest, xyz = _onto_surfaces(
|
|
1396
|
+
xyz, elements, phase, present, two, between, once, pieces, sharp, sharp_pieces,
|
|
1397
|
+
near, on_faces, axes, lower, upper, tol, hausd, hmin, size,
|
|
1398
|
+
) # fmt: skip
|
|
1399
|
+
metadata = {
|
|
1400
|
+
"mesher": "adaptive level set (octree, mmg3d -ls)",
|
|
1401
|
+
"size": size,
|
|
1402
|
+
"hausdorff": hausd,
|
|
1403
|
+
"min_size": hmin,
|
|
1404
|
+
"lipschitz": lip,
|
|
1405
|
+
"level_sets": [int(k) for k in keys],
|
|
1406
|
+
"octree_splits": splits,
|
|
1407
|
+
"octree_balance_splits": balanced,
|
|
1408
|
+
"octree_elements": n_octree,
|
|
1409
|
+
"face_nodes_moved": moved,
|
|
1410
|
+
"face_nodes_added": added,
|
|
1411
|
+
"projected_nodes": projected,
|
|
1412
|
+
"largest_projection": largest,
|
|
1413
|
+
"phases": phases if isinstance(phases, str) else [int(k) for k in phases],
|
|
1414
|
+
"matching_faces": [d for d in range(3) if axes[d]],
|
|
1415
|
+
"time_octree_s": round(t_tree, 3),
|
|
1416
|
+
"time_mmg_s": round(t_cut, 3),
|
|
1417
|
+
}
|
|
1418
|
+
if pieces is not None:
|
|
1419
|
+
metadata["sharp_edges"] = {"pieces": len(pieces), "edges": len(sharp), "depth": hausd}
|
|
1420
|
+
elif once:
|
|
1421
|
+
metadata["cut_once"] = True # several phases, or the cut of two failed
|
|
1422
|
+
mesh = TetMesh(
|
|
1423
|
+
nodes=xyz,
|
|
1424
|
+
elements=elements,
|
|
1425
|
+
phase=phase,
|
|
1426
|
+
lower=lower,
|
|
1427
|
+
upper=upper,
|
|
1428
|
+
periodic=all(axes),
|
|
1429
|
+
metadata=metadata,
|
|
1430
|
+
sharp=sharp,
|
|
1431
|
+
sharp_pieces=sharp_pieces,
|
|
1432
|
+
)
|
|
1433
|
+
if any(axes) and not mesh.matching_faces():
|
|
1434
|
+
if not once: # the faces cut exactly before MMG: cut by MMG alike, as on the grid
|
|
1435
|
+
log.info("adaptive mesh: the faces do not match; the phases cut at once")
|
|
1436
|
+
return _adaptive_mesh(
|
|
1437
|
+
micro, size=size, hausdorff=hausdorff, min_size=min_size, gradation=gradation,
|
|
1438
|
+
phases=phases, order=order, periodic=periodic, lipschitz=lipschitz,
|
|
1439
|
+
project=project, remove_islands=remove_islands, ridges=ridges,
|
|
1440
|
+
sharp_edges=sharp_edges, retries=retries, executable=executable,
|
|
1441
|
+
workdir=workdir, timeout=timeout, attempt=attempt, at_once=True,
|
|
1442
|
+
) # fmt: skip
|
|
1443
|
+
if attempt < retries:
|
|
1444
|
+
log.info("adaptive mesh: the faces do not match; again on another octree")
|
|
1445
|
+
return _adaptive_mesh(
|
|
1446
|
+
micro,
|
|
1447
|
+
size=size,
|
|
1448
|
+
hausdorff=hausdorff,
|
|
1449
|
+
min_size=min_size,
|
|
1450
|
+
gradation=gradation,
|
|
1451
|
+
phases=phases,
|
|
1452
|
+
order=order,
|
|
1453
|
+
periodic=periodic,
|
|
1454
|
+
lipschitz=lipschitz,
|
|
1455
|
+
project=project,
|
|
1456
|
+
remove_islands=remove_islands,
|
|
1457
|
+
ridges=ridges,
|
|
1458
|
+
sharp_edges=sharp_edges,
|
|
1459
|
+
retries=retries,
|
|
1460
|
+
executable=executable,
|
|
1461
|
+
workdir=workdir,
|
|
1462
|
+
timeout=timeout,
|
|
1463
|
+
attempt=attempt + 1,
|
|
1464
|
+
at_once=at_once,
|
|
1465
|
+
)
|
|
1466
|
+
log.warning("adaptive mesh: the opposite faces of the box do not match")
|
|
1467
|
+
if two != "all" and once: # the cuts made at once keep every phase
|
|
1468
|
+
keep = [1] if two == "solid" else [0]
|
|
1469
|
+
if order == 2: # curved on the interfaces (the nodes of the sharp edges on both)
|
|
1470
|
+
from morphogen.mesh.curved import curved_mesh
|
|
1471
|
+
|
|
1472
|
+
mesh = curved_mesh(mesh, micro) if project else mesh.quadratic()
|
|
1473
|
+
if keep is not None:
|
|
1474
|
+
mesh = mesh.subset(keep)
|
|
1475
|
+
log.info("adaptive mesh: %d elements, %d nodes (octree of %d elements, %.1f s)",
|
|
1476
|
+
mesh.n_elements, mesh.n_nodes, n_octree, time.perf_counter() - t0) # fmt: skip
|
|
1477
|
+
return mesh
|
|
1478
|
+
|
|
1479
|
+
|
|
1480
|
+
def _cut_two(exe, nodes, tets, tri, tri_refs, function, phases, axes, required, on_faces,
|
|
1481
|
+
lower, upper, tol, hausd, hmin, size, gradation, two, ridges, remove_islands,
|
|
1482
|
+
workdir, timeout): # fmt: skip
|
|
1483
|
+
"""The octree of a structure of two phases cut by the zero of its level set
|
|
1484
|
+
``function`` (negative in the first of the two ``phases``) and remeshed by MMG in one
|
|
1485
|
+
pass, the matching faces cut exactly before (see the module). Returns the nodes, the
|
|
1486
|
+
tetrahedra, their phases, and the numbers of nodes of the faces moved and added."""
|
|
1487
|
+
moved = added = 0
|
|
1488
|
+
face_points = np.zeros((0, 3))
|
|
1489
|
+
if any(axes): # the matching faces cut exactly, alike: MMG keeps them
|
|
1490
|
+
group = _groups(nodes, lower, upper, axes, tol)
|
|
1491
|
+
nodes, tets, tri, tri_refs, values, _, moved, added = _cut_faces(
|
|
1492
|
+
function, nodes, tets, tri, tri_refs, required, group, zero=1e-6 * hausd
|
|
1493
|
+
)
|
|
1494
|
+
# the edges between nodes of the faces through the box (near its edges) that the
|
|
1495
|
+
# level set crosses: split at its zeros (MMG frees the nodes of the faces at the
|
|
1496
|
+
# ends of a cut edge, and remeshes the faces there)
|
|
1497
|
+
face = on_faces(nodes)
|
|
1498
|
+
nodes, tets, more, done = _split_across(function, nodes, tets, tri, face, [values], 0)
|
|
1499
|
+
face = np.concatenate([face, np.zeros(more, dtype=bool)])
|
|
1500
|
+
added += more
|
|
1501
|
+
# the values of the faces as the cut left them: the pass of MMG takes them there
|
|
1502
|
+
face_points, face_values = nodes[face], done[0][face]
|
|
1503
|
+
values = np.asarray(function(nodes), dtype=float).copy()
|
|
1504
|
+
if len(face_points):
|
|
1505
|
+
dist, where = cKDTree(face_points).query(nodes, distance_upper_bound=10.0 * tol)
|
|
1506
|
+
hit = dist <= 10.0 * tol
|
|
1507
|
+
values[hit] = face_values[where[hit]]
|
|
1508
|
+
tiny = _OFF_NODES * hausd # no interface through a node, but on the cut faces
|
|
1509
|
+
trace = (values == 0.0) & on_faces(nodes)
|
|
1510
|
+
values = np.where(np.abs(values) < tiny, np.where(values < 0, -tiny, tiny), values)
|
|
1511
|
+
values[trace] = 0.0
|
|
1512
|
+
if trace.any(): # the traces of the faces are nodes: the interface manifold there
|
|
1513
|
+
_manifold_balls(tets, values, np.flatnonzero(trace), tiny)
|
|
1514
|
+
sizing = ["-hmax", f"{size:.10g}", "-hmin", f"{hmin:.10g}", "-hausd", f"{hausd:.10g}",
|
|
1515
|
+
"-hgrad", f"{gradation:.10g}", "-v", "-1"] # fmt: skip
|
|
1516
|
+
if two != "all": # MMG keeps one subdomain
|
|
1517
|
+
sizing += ["-nsd", str(REF_INSIDE if two == "solid" else REF_OUTSIDE)]
|
|
1518
|
+
if not ridges: # the edges of the box given, no detection by angles (see the module)
|
|
1519
|
+
sizing += ["-nr"]
|
|
1520
|
+
fixed = np.isin(tri_refs, required)
|
|
1521
|
+
if remove_islands and not fixed.any():
|
|
1522
|
+
sizing += ["-rmc", f"{float(remove_islands):.10g}"]
|
|
1523
|
+
edges, corners = _box_ridges(nodes, tri, lower, upper, tol)
|
|
1524
|
+
with tempfile.TemporaryDirectory(dir=workdir) as tmp:
|
|
1525
|
+
folder = Path(tmp)
|
|
1526
|
+
medit.write_mesh(folder / "cut.mesh", nodes, tets, tri,
|
|
1527
|
+
tet_refs=np.ones(len(tets), dtype=np.int64), tri_refs=tri_refs,
|
|
1528
|
+
required_triangles=np.flatnonzero(fixed) if fixed.any() else None,
|
|
1529
|
+
required_vertices=np.flatnonzero(on_faces(nodes)) if fixed.any()
|
|
1530
|
+
else None, edges=edges, ridges=np.arange(len(edges)),
|
|
1531
|
+
corners=corners) # fmt: skip
|
|
1532
|
+
medit.write_sol(folder / "cut.sol", values)
|
|
1533
|
+
data = _run_mmg(exe, folder / "cut.mesh", folder / "cut.sol", folder / "cut.o.mesh",
|
|
1534
|
+
["-ls", "0", *sizing], timeout) # fmt: skip
|
|
1535
|
+
nodes, tets, tet_refs = data["Vertices"], data["Tetrahedra"], data["Tetrahedra_refs"]
|
|
1536
|
+
for d in range(3): # the nodes of the faces exactly on them
|
|
1537
|
+
nodes[np.abs(nodes[:, d] - lower[d]) <= tol, d] = lower[d]
|
|
1538
|
+
nodes[np.abs(nodes[:, d] - upper[d]) <= tol, d] = upper[d]
|
|
1539
|
+
phase = np.where(tet_refs == REF_INSIDE, phases[0], phases[1])
|
|
1540
|
+
return nodes, tets, phase, moved, added
|
|
1541
|
+
|
|
1542
|
+
|
|
1543
|
+
def _onto_surfaces(xyz, elements, phase, present, two, between, once, pieces, sharp,
|
|
1544
|
+
sharp_pieces, reach, on_faces, axes, lower, upper, tol, hausd, hmin,
|
|
1545
|
+
size): # fmt: skip
|
|
1546
|
+
"""The nodes of the interfaces moved onto their exact surfaces (:func:`_project`):
|
|
1547
|
+
the nodes between two phases (or on the boundary of the one that MMG kept) onto the
|
|
1548
|
+
interface of the two; those of the sharp edges onto the surfaces of the pieces that
|
|
1549
|
+
meet there. Those where three phases meet stay, as do the nodes of the matching faces
|
|
1550
|
+
cut exactly before MMG (they lie on the interfaces already); the nodes of the faces
|
|
1551
|
+
that the cuts made at ``once`` left move within their faces, alike on the opposite
|
|
1552
|
+
ones. Returns the number of nodes moved, the largest move and the nodes."""
|
|
1553
|
+
count = np.zeros((len(xyz), len(present)), dtype=bool)
|
|
1554
|
+
slot = {k: i for i, k in enumerate(present)}
|
|
1555
|
+
for k, i in slot.items():
|
|
1556
|
+
count[np.unique(elements[phase == k]), i] = True
|
|
1557
|
+
n_phases = count.sum(axis=1)
|
|
1558
|
+
if two != "all" and not once: # MMG kept one phase: the interface is a boundary
|
|
1559
|
+
boundary = np.zeros(len(xyz), dtype=bool)
|
|
1560
|
+
boundary[np.unique(_free_faces(elements))] = True
|
|
1561
|
+
boundary &= ~_on_box(xyz, lower, upper, tol) | on_faces(xyz)
|
|
1562
|
+
n_phases = np.where(boundary, 2, n_phases)
|
|
1563
|
+
count[boundary, slot[0] if two == "solid" else slot[1]] = True
|
|
1564
|
+
candidates = n_phases == 2
|
|
1565
|
+
if not once: # the matching faces: cut exactly already
|
|
1566
|
+
candidates &= ~on_faces(xyz)
|
|
1567
|
+
groups = {}
|
|
1568
|
+
if sharp is not None and len(sharp):
|
|
1569
|
+
groups = _sharp_groups(sharp, sharp_pieces, len(xyz))
|
|
1570
|
+
for nodes_at in groups.values():
|
|
1571
|
+
candidates[nodes_at] = False
|
|
1572
|
+
group = _groups(xyz, lower, upper, axes, tol) if any(axes) else None
|
|
1573
|
+
step = min(hausd, hmin) / 10.0
|
|
1574
|
+
projected, largest = 0, 0.0
|
|
1575
|
+
for a, b in itertools.combinations(present, 2): # onto the interface of the two
|
|
1576
|
+
moving = np.flatnonzero(candidates & count[:, slot[a]] & count[:, slot[b]])
|
|
1577
|
+
if not moving.size:
|
|
1578
|
+
continue
|
|
1579
|
+
xyz, done, most = _project(between(b, a, reach), xyz, elements, moving, step=step,
|
|
1580
|
+
limit=0.25 * size, lower=lower, upper=upper, tol=tol,
|
|
1581
|
+
group=group) # fmt: skip
|
|
1582
|
+
projected, largest = projected + done, max(largest, most)
|
|
1583
|
+
for meeting, moving in groups.items(): # onto the surfaces of the pieces that meet
|
|
1584
|
+
surfaces = [pieces[k] for k in meeting]
|
|
1585
|
+
|
|
1586
|
+
def where(points, surfaces=surfaces):
|
|
1587
|
+
return np.stack([piece.at(points, reach) for piece in surfaces], axis=1)
|
|
1588
|
+
|
|
1589
|
+
xyz, done, most = _project(where, xyz, elements, moving, step=step, limit=0.25 * size,
|
|
1590
|
+
lower=lower, upper=upper, tol=tol, group=group) # fmt: skip
|
|
1591
|
+
projected, largest = projected + done, max(largest, most)
|
|
1592
|
+
return projected, largest, xyz
|
|
1593
|
+
|
|
1594
|
+
|
|
1595
|
+
#: Barycentric coordinates of the nodes of a 10-node tetrahedron (corners, then the middles
|
|
1596
|
+
#: of the edges in the order of :data:`morphogen.mesh.tetra.TET_EDGES`)
|
|
1597
|
+
_P2_POINTS = np.vstack([np.eye(4), 0.5 * (np.eye(4)[[0, 1, 0, 0, 1, 2]] +
|
|
1598
|
+
np.eye(4)[[1, 2, 2, 3, 3, 3]])]) # fmt: skip
|
|
1599
|
+
|
|
1600
|
+
|
|
1601
|
+
def _p2_jacobians(nodes, elements, points=_P2_POINTS) -> np.ndarray:
|
|
1602
|
+
"""The determinants of the Jacobians of 10-node tetrahedra at points (barycentric
|
|
1603
|
+
coordinates; default: their ten nodes)."""
|
|
1604
|
+
from morphogen.mesh.tetra import TET_EDGES
|
|
1605
|
+
|
|
1606
|
+
grad_l = np.array([[-1.0, -1.0, -1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]])
|
|
1607
|
+
x = nodes[elements] # (m, 10, 3)
|
|
1608
|
+
out = np.empty((len(elements), len(points)))
|
|
1609
|
+
for p, lam in enumerate(points):
|
|
1610
|
+
grads = [(4.0 * lam[i] - 1.0) * grad_l[i] for i in range(4)]
|
|
1611
|
+
grads += [4.0 * (lam[j] * grad_l[i] + lam[i] * grad_l[j]) for i, j in TET_EDGES]
|
|
1612
|
+
jac = np.einsum("mad,ae->mde", x, np.array(grads))
|
|
1613
|
+
out[:, p] = np.linalg.det(jac)
|
|
1614
|
+
return out
|
|
1615
|
+
|
|
1616
|
+
|
|
1617
|
+
def _free_faces(elements: np.ndarray) -> np.ndarray:
|
|
1618
|
+
"""The triangles of tetrahedra that belong to a single one."""
|
|
1619
|
+
faces = np.concatenate([elements[:, [0, 2, 1]], elements[:, [0, 1, 3]],
|
|
1620
|
+
elements[:, [1, 2, 3]], elements[:, [0, 3, 2]]]) # fmt: skip
|
|
1621
|
+
key = np.sort(faces, axis=1)
|
|
1622
|
+
_, first, counts = np.unique(key, axis=0, return_index=True, return_counts=True)
|
|
1623
|
+
return faces[first[counts == 1]]
|
|
1624
|
+
|
|
1625
|
+
|
|
1626
|
+
def _on_box(points, lower, upper, tol) -> np.ndarray:
|
|
1627
|
+
"""Whether points lie on a face of the box."""
|
|
1628
|
+
return np.any((np.abs(points - lower) <= tol) | (np.abs(points - upper) <= tol), axis=1)
|
|
1629
|
+
|
|
1630
|
+
|
|
1631
|
+
# -- the route of each microstructure --------------------------------------------------------
|
|
1632
|
+
|
|
1633
|
+
|
|
1634
|
+
def exact_route(micro, grains: bool | None = None) -> str:
|
|
1635
|
+
"""How :func:`exact_mesh` meshes a microstructure: ``"cells"`` (the exact cells of
|
|
1636
|
+
Voronoi and Laguerre tessellations, grain by grain), ``"pieces"`` (exact convex pieces:
|
|
1637
|
+
faceted microstructures), ``"level_set"`` (the adaptive mesh of the exact point-wise
|
|
1638
|
+
functions of its phases, :meth:`~morphogen.models.base.Microstructure.
|
|
1639
|
+
phase_level_sets_at`: the other structures, of two phases or more, the tessellations
|
|
1640
|
+
with a grain-boundary phase, and those meshed by their phases, ``grains`` false), or
|
|
1641
|
+
``""`` (none: the structures whose functions are those of grids only, and those whose
|
|
1642
|
+
cells carry crystal orientations but tessellations, whose meshes come from their voxel
|
|
1643
|
+
images)."""
|
|
1644
|
+
from morphogen.models.implicit import point_functions
|
|
1645
|
+
from morphogen.models.tessellation import Tessellation
|
|
1646
|
+
|
|
1647
|
+
if isinstance(micro, Tessellation):
|
|
1648
|
+
if not micro.boundary_thickness > 0 and grains is not False:
|
|
1649
|
+
return "cells"
|
|
1650
|
+
return "level_set" if point_functions(micro) else ""
|
|
1651
|
+
if callable(getattr(micro, "convex_pieces", None)):
|
|
1652
|
+
return "pieces"
|
|
1653
|
+
if getattr(micro, "orientations", None) is not None:
|
|
1654
|
+
return "" # crystals turned by their cells: a mesh by cell (their images)
|
|
1655
|
+
return "level_set" if point_functions(micro) else ""
|
|
1656
|
+
|
|
1657
|
+
|
|
1658
|
+
def exact_mesh(
|
|
1659
|
+
micro,
|
|
1660
|
+
*,
|
|
1661
|
+
size: float,
|
|
1662
|
+
min_size: float | None = None,
|
|
1663
|
+
hausdorff: float | None = None,
|
|
1664
|
+
gradation: float | None = None,
|
|
1665
|
+
phases="all",
|
|
1666
|
+
order: int = 1,
|
|
1667
|
+
periodic=None,
|
|
1668
|
+
grains: bool | None = None,
|
|
1669
|
+
sharp_edges: bool | None = None,
|
|
1670
|
+
executable: str | None = None,
|
|
1671
|
+
workdir=None,
|
|
1672
|
+
timeout: float | None = None,
|
|
1673
|
+
**options,
|
|
1674
|
+
) -> TetMesh:
|
|
1675
|
+
"""Conforming tetrahedral mesh of the exact geometry of a microstructure, without a
|
|
1676
|
+
background grid (see the module): the exact cells of tessellations
|
|
1677
|
+
(:func:`morphogen.mesh.polycrystal.polycrystal_mesh`), the exact convex pieces of
|
|
1678
|
+
faceted microstructures (:func:`polyhedral_mesh`), or the adaptive mesh of the exact
|
|
1679
|
+
functions of the phases of the others (:func:`adaptive_mesh`); ``options`` go to the
|
|
1680
|
+
mesher of the route (:func:`exact_route`, which ``grains`` false turns from the cells of
|
|
1681
|
+
a tessellation to the functions of its phases). ``phases``: ``"all"``, ``"solid"``,
|
|
1682
|
+
``"matrix"`` or the phases to keep (a list). ``hausdorff``: the distance of the curved
|
|
1683
|
+
interfaces of level sets to their facets; the planar facets of cells and pieces are
|
|
1684
|
+
kept, whatever it is. ``sharp_edges``: the sharp edges of the smooth pieces of level
|
|
1685
|
+
sets (:func:`adaptive_mesh`); the edges of cells and convex pieces are those of their
|
|
1686
|
+
facets, kept."""
|
|
1687
|
+
route = exact_route(micro, grains)
|
|
1688
|
+
keep = None
|
|
1689
|
+
if not isinstance(phases, str) and route in ("cells", "pieces"): # kept from the whole
|
|
1690
|
+
keep, phases = sorted({int(k) for k in phases}), "all"
|
|
1691
|
+
common = dict(size=size, min_size=min_size, phases=phases, order=order,
|
|
1692
|
+
executable=executable, workdir=workdir, timeout=timeout) # fmt: skip
|
|
1693
|
+
if gradation is not None:
|
|
1694
|
+
common["gradation"] = gradation
|
|
1695
|
+
if route == "cells":
|
|
1696
|
+
from morphogen.mesh.polycrystal import polycrystal_mesh
|
|
1697
|
+
|
|
1698
|
+
mesh = polycrystal_mesh(micro, periodic=periodic, exact=True, **common, **options)
|
|
1699
|
+
elif route == "pieces":
|
|
1700
|
+
if periodic is not None and np.ndim(periodic) == 0:
|
|
1701
|
+
options["periodic"] = bool(periodic)
|
|
1702
|
+
mesh = polyhedral_mesh(micro, **common, **options)
|
|
1703
|
+
elif route == "level_set":
|
|
1704
|
+
common["hausdorff"] = hausdorff
|
|
1705
|
+
return adaptive_mesh(micro, periodic=periodic, sharp_edges=sharp_edges, **common,
|
|
1706
|
+
**options) # fmt: skip
|
|
1707
|
+
else:
|
|
1708
|
+
raise TypeError(
|
|
1709
|
+
f"{type(micro).__name__}: neither exact cells, convex pieces nor point-wise "
|
|
1710
|
+
"functions of its phases, so no exact mesh (mesh its voxel image instead)"
|
|
1711
|
+
)
|
|
1712
|
+
if keep is not None:
|
|
1713
|
+
unknown = sorted(set(keep) - {int(k) for k in np.unique(mesh.phase)})
|
|
1714
|
+
if unknown:
|
|
1715
|
+
raise ValueError(f"phases: {unknown} are not phases of this structure")
|
|
1716
|
+
mesh = mesh.subset(keep)
|
|
1717
|
+
return mesh
|