diff --git a/scripts/test.sh b/scripts/test.sh index d683c9f93..d39c2f78d 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -411,6 +411,8 @@ if [ $PARALLEL_ONLY -eq 0 ]; then # Shell Inner/Outer cell labels follow the Internal surface, not a radius test: # the same assertions hold on one rank, so the file also runs serially. batch 3 tests/parallel/test_1175_shell_region_labels.py + # So is points_in_domain by the exact locator, a swarm's claims agreeing with global_evaluate. + batch 3 tests/parallel/test_1213_points_in_domain_exact_parallel.py # So is the adjoint dual on a field in a Dirichlet datum, the same at any rank count (#787). batch 3 tests/parallel/test_0787_field_dual_through_dirichlet_datum_parallel.py # So is Stokes.set_active_region's refusal (#1154). diff --git a/src/underworld3/discretisation/discretisation_mesh.py b/src/underworld3/discretisation/discretisation_mesh.py index ae7384a50..2965f6df5 100644 --- a/src/underworld3/discretisation/discretisation_mesh.py +++ b/src/underworld3/discretisation/discretisation_mesh.py @@ -7670,10 +7670,12 @@ def _mark_local_boundary_faces_inside_and_out(self): def points_in_domain(self, points, strict_validation=True): """ - Determine if the given points lie in this domain. - Uses a mesh-boundary skeletonization array to determine whether the point is - inside the boundary or outside. If close to the boundary, it checks if points - are in a cell. + Determine if the given points lie in this rank's part of the domain. + On a straight-sided simplex mesh, a point is in it when a local cell + contains it (the exact locator), or lies within the evaluation face + tolerance of a local cell. Other meshes use a mesh-boundary + skeletonization array to decide inside from outside, and check the + points close to the boundary against the cells. Parameters ---------- @@ -7681,7 +7683,9 @@ def points_in_domain(self, points, strict_validation=True): Coordinate array in any physical unit system (will be auto-converted). Plain numbers are assumed to be in model coordinates. strict_validation : bool - Whether to perform strict validation near boundaries + Whether to perform strict validation near boundaries. Only other + meshes read it: on a straight-sided simplex mesh the claim is + containment (or the face tolerance near the boundary) either way. """ return self._classify_points_in_domain(points, strict_validation)[0] @@ -7700,21 +7704,29 @@ def _classify_points_in_domain(self, points, strict_validation=True, exact_locat Coordinate array in any physical unit system (will be auto-converted). strict_validation : bool - Whether to perform strict validation near boundaries. + Whether to perform strict validation near boundaries. Ignored on a + straight-sided simplex mesh, where the claim is containment either + way. + exact_location : bool + Evaluation's classification (passed by ``evaluate_nd``): on a + simplex mesh in serial, the face tolerance is tested against the + cell the walk left the mesh through. Returns ------- in_or_not : numpy.ndarray of bool Exactly what :meth:`points_in_domain` returns. cells : numpy.ndarray of int - Owning cell for the points the classification actually located, - at the evaluation face tolerance (:meth:`_robust_owning_cells`). - ``-1`` everywhere else — for an EXTERIOR point that means "not in - the local mesh"; for an INTERIOR point it means "not looked up", - because the boundary-sign test settled it without a search. A - caller that needs a cell for every interior point locates the - ``-1`` entries itself, and only when it needs them: nothing here - searches on the classifier's behalf. + On a straight-sided simplex mesh, every point is located, so this + holds the owning cell of every claimed point (the containing cell, + or the one the face tolerance claimed it for) and ``-1`` exactly + where ``in_or_not`` is False; a caller need not locate those points + again. On other meshes, the owning cell for the points the + classification actually located, at the evaluation face tolerance + (:meth:`_robust_owning_cells`), and ``-1`` everywhere else: for an + EXTERIOR point that means "not in the local mesh"; for an INTERIOR + point it means "not looked up", because the boundary-sign test + settled it without a search. """ # Convert points to model coordinates using the unified conversion function # This handles all coordinate formats: plain numbers, unit-aware coordinates, lists, tuples, arrays @@ -7751,17 +7763,49 @@ def _classify_points_in_domain(self, points, strict_validation=True, exact_locat # surface-mesh contract, query points are assumed to lie on # the manifold; the closest-local-cell test is the right # filter, not an inside/outside split. - if exact_location and self._simplex_locator() is not None: - # For evaluation (``exact_location``, passed by evaluate_nd only): - # a point is interior when a local cell contains it, or the face - # tolerance of _robust_owning_cells claims it. The boundary-sign - # test below can call a contained point exterior on a strongly - # sheared mesh (#1123). points_in_domain, which the swarm's - # migration reads, keeps the boundary-sign test, so no swarm claim - # changes here; making the two agree is the follow-up that passes a - # particle's previous cell to the walk. - cells = numpy.asarray(self._robust_owning_cells(model_points, for_evaluation=True), - dtype=numpy.int64) + if self._simplex_locator() is not None: + # On a simplex mesh the exact locator decides, for evaluation and for + # points_in_domain alike: a point is interior when a local cell + # contains it, or the face tolerance of _robust_owning_cells claims + # it. The boundary-face sign test below stood in for containment far + # from the local boundary, and on a strongly sheared mesh it called a + # contained point exterior (#1123): a swarm's migration then put that + # particle on no rank, while global_evaluate's ownership had it. + # Style Charter section 12: containment, not a sign test. + if exact_location: + # evaluation: the serial exit-cell tolerance test (#1175) + cells = numpy.asarray( + self._robust_owning_cells(model_points, for_evaluation=True), + dtype=numpy.int64) + return cells >= 0, cells + # Claims: exact containment first. A point no local cell contains + # takes the face tolerance development applied near the boundary, + # so claims change only by contained points: in parallel the + # evaluation tolerance (_robust_owning_cells), in serial the + # cell-wall test's own (_get_closest_local_cells_internal). + locator = self._simplex_locator() + cells, _, _ = self._walk_to_owning_cells(locator, model_points) + lost = numpy.flatnonzero(cells < 0) + # Only near the local boundary, as development applied it: the face + # tolerance cannot claim a point farther away, and testing every + # point outside the domain cost 7.6 of 11 s on 1e6 points. + if lost.shape[0] > 0 and self.boundary_face_control_points_kdtree is not None: + dist2, _ = self.boundary_face_control_points_kdtree.query( + model_points[lost], k=1, sqr_dists=True) + lost = lost[numpy.asarray(dist2).ravel() < 2 * max_radius ** 2] + if lost.shape[0] > 0: + if self._eval_use_robust_location(): + # _robust_owning_cells' own tolerance search, without walking + # these points a second time + cells[lost] = numpy.asarray( + self._get_closest_local_cells_internal( + model_points[lost], tol=self._EVAL_FACE_TOL), + dtype=numpy.int64) + else: + near = numpy.asarray( + self._get_closest_local_cells_internal(model_points[lost]), + dtype=numpy.int64) + cells[lost] = near return cells >= 0, cells if self.boundary_face_control_points_kdtree is None: in_or_not = self._get_closest_local_cells_internal(model_points) != -1 diff --git a/tests/parallel/sheared_box_fixture.py b/tests/parallel/sheared_box_fixture.py new file mode 100644 index 000000000..23974c5ce --- /dev/null +++ b/tests/parallel/sheared_box_fixture.py @@ -0,0 +1,77 @@ +"""#1123's sheared 3-D box, built the same on every platform and never tangled. + +The box is a structured grid of n^3 cubes, each split into six tetrahedra along +the axis-ordered paths from one corner to the opposite one, so the mesh does not +depend on gmsh. (gmsh's box differed between builds: 1094 cells on macOS against +1086 on Linux, and with the old wave amplitude 0.03 one macOS cell was turned +inside out, so the locator tests had no right answer there.) + +The map is #1123's linear shear A (det 0.196, smallest singular value 0.175) plus +sine terms of amplitude SHEAR_WAVE. The sine terms' gradient is a scaled +permutation matrix of norm 2 pi SHEAR_WAVE = 0.157 at 0.025, below 0.175, so the +map is invertible; `sheared_box` asserts, collectively, that no cell turned over. +""" +import itertools + +import numpy as np +from petsc4py import PETSc + +import underworld3 as uw + +SHEAR = np.array([[1.0, 1.2, 0.3], [0.1, 0.7, 0.5], [0.0, 0.2, 0.5]]) +SHEAR_WAVE = 0.025 + + +def kuhn_box(n): + """A DM of the unit cube in n^3 cubes, six tetrahedra each, on rank 0 (the + Mesh distributes it). Collective.""" + coords = np.zeros((0, 3)) + cells = np.zeros((0, 4), dtype=PETSc.IntType) + if PETSc.COMM_WORLD.getRank() == 0: + def node(i, j, k): + return (i * (n + 1) + j) * (n + 1) + k + coords = np.array([[i / n, j / n, k / n] + for i in range(n + 1) for j in range(n + 1) for k in range(n + 1)]) + tets = [] + for i, j, k in itertools.product(range(n), repeat=3): + for order in itertools.permutations(range(3)): + corner = [i, j, k] + path = [node(*corner)] + for axis in order: + corner[axis] += 1 + path.append(node(*corner)) + tets.append(path) + cells = np.asarray(tets, dtype=PETSc.IntType) + dm = PETSc.DMPlex().createFromCellList(3, cells, coords, interpolate=True, comm=PETSc.COMM_WORLD) + dm.createLabel("All_Boundaries") + dm.markBoundaryFaces("All_Boundaries", 1001) + return dm + + +def cell_orientations(mesh): + """The sign of each local cell's volume.""" + from underworld3.utilities._plex_topology import closure_points + cs, ce = mesh.dm.getHeightStratum(0) + if ce == cs: + return np.zeros(0) + Xl = np.asarray(mesh._coords).reshape(-1, mesh.cdim) + V = Xl[mesh._coord_rows_for_points( + mesh.dm, closure_points(mesh.dm, np.arange(cs, ce), 0).ravel())].reshape(ce - cs, -1, mesh.cdim) + return np.sign(np.linalg.det(V[:, 1:, :] - V[:, :1, :])) + + +def sheared_box(n=6, qdegree=3): + """The sheared box; fails loudly if any cell turned over. Collective.""" + from mpi4py import MPI + + mesh = uw.discretisation.Mesh(kuhn_box(n), degree=1, qdegree=qdegree) + before = cell_orientations(mesh) + X = np.asarray(mesh.X.coords).copy() + Y = X @ SHEAR.T + Y[:, 0] += SHEAR_WAVE * np.sin(2 * np.pi * X[:, 1]) + Y[:, 1] += SHEAR_WAVE * np.sin(2 * np.pi * X[:, 2]) + Y[:, 2] += SHEAR_WAVE * np.sin(2 * np.pi * X[:, 0]) + mesh.deform(Y) + flipped = uw.mpi.comm.allreduce(int((cell_orientations(mesh) != before).sum()), op=MPI.SUM) + assert flipped == 0, f"the sheared fixture turned {flipped} cells over" + return mesh diff --git a/tests/parallel/test_1213_points_in_domain_exact_parallel.py b/tests/parallel/test_1213_points_in_domain_exact_parallel.py new file mode 100644 index 000000000..4437e6268 --- /dev/null +++ b/tests/parallel/test_1213_points_in_domain_exact_parallel.py @@ -0,0 +1,69 @@ +"""points_in_domain uses the exact locator on simplex meshes, so a swarm's claims +agree with global_evaluate's ownership. + +points_in_domain, which a swarm's migration reads, decided a point far from the +local boundary by a boundary-face sign test standing in for containment (Style +Charter section 12). On #1123's sheared box the sign test calls a contained point +exterior: at np 2, development leaves one inside point owned by no rank, so its +particle is on no rank. Now a point is in a rank's domain when a local cell +contains it, or when development's face tolerance near the boundary claims it. + +The truth is a brute-force barycentric test over every local cell, in numpy. + + python scripts/mpi_supervisor.py --silence 300 -- mpirun -n 2 python -m pytest --with-mpi tests/parallel/test_1213_points_in_domain_exact_parallel.py +""" +import numpy as np +import pytest +from mpi4py import MPI + +import underworld3 as uw +from underworld3.utilities._plex_topology import closure_points + +import sheared_box_fixture + +pytestmark = [pytest.mark.level_2, pytest.mark.tier_b, pytest.mark.timeout(300)] + + +def _inside_some_local_cell(mesh, P): + cs, ce = mesh.dm.getHeightStratum(0) + inside = np.zeros(P.shape[0], dtype=bool) + if ce == cs: + return inside + Xl = np.asarray(mesh._coords).reshape(-1, mesh.cdim) + V = Xl[mesh._coord_rows_for_points( + mesh.dm, closure_points(mesh.dm, np.arange(cs, ce), 0).ravel())].reshape(ce - cs, -1, mesh.cdim) + Ti = np.linalg.inv(np.transpose(V[:, 1:, :] - V[:, :1, :], (0, 2, 1))) + for start in range(0, P.shape[0], 256): + Q = P[start:start + 256] + lam = np.einsum("cij,ncj->nci", Ti, Q[:, None, :] - V[None, :, 0, :]) + inside[start:start + 256] = (np.minimum(lam.min(axis=2), 1.0 - lam.sum(axis=2)) >= 0.0).any(axis=1) + return inside + + +def _near_edges(mesh): + dm = mesh.dm + es, ee = dm.getDepthStratum(1) + vs = dm.getDepthStratum(0)[0] + Xv = np.asarray(mesh._coords).reshape(-1, 3) + mids = np.array([0.5 * (Xv[dm.getCone(e)[0] - vs] + Xv[dm.getCone(e)[1] - vs]) + for e in range(es, ee)]).reshape(-1, 3) + mids = np.unique(np.round(np.vstack(uw.mpi.comm.allgather(mids)), 13), axis=0) + rng = np.random.default_rng(3) + unit = lambda n: n / np.linalg.norm(n, axis=1)[:, None] + return np.vstack([mids + d * unit(rng.normal(size=mids.shape)) for d in (1e-8, 1e-6, 1e-4)]) + + +def test_every_inside_point_is_in_some_ranks_domain_and_its_particle_survives(): + mesh = sheared_box_fixture.sheared_box() + P = _near_edges(mesh) + inside = uw.mpi.comm.allreduce(_inside_some_local_cell(mesh, P).astype(np.int64), op=MPI.SUM) > 0 + owned = np.asarray(mesh.points_in_domain(P, strict_validation=True), dtype=np.int64) + owners = uw.mpi.comm.allreduce(owned, op=MPI.SUM) + missed = int((inside & (owners == 0)).sum()) + assert missed == 0, f"{missed} inside points in no rank's domain" + + swarm = uw.swarm.Swarm(mesh) + seed = P[inside] if uw.mpi.rank == 0 else np.zeros((0, 3)) + swarm.add_particles_with_global_coordinates(seed, migrate=True, delete_lost_points=True) + total = uw.mpi.comm.allreduce(swarm.dm.getLocalSize(), op=MPI.SUM) + assert total == int(inside.sum()), f"{total} particles kept of {int(inside.sum())} inside"