Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions src/underworld3/discretisation/discretisation_mesh.py
Original file line number Diff line number Diff line change
Expand Up @@ -9039,6 +9039,9 @@ def _relax_generation(engine_obj, carry, rcarry):
# is that offset; each generation's map comes back from `to_dm`.
_nested_Ps = []
_nested_parent_cells = []
# per pass: whether a repair flipped a cell (a global count, so the same on
# every rank); no span through such a pass has a cell-parent map (#961)
_repaired_passes = []
_vS0, _vE0 = base_finest.getDepthStratum(0)
_coarse_vmap = {i: _vS0 + i for i in range(_vE0 - _vS0)}

Expand Down Expand Up @@ -9199,6 +9202,7 @@ def _relax_generation(engine_obj, carry, rcarry):
current_dm, n_flips = reconnect.flip_to_reduce_max_angle(
current_dm)
_nested_parent_cells.append(None)
_repaired_passes.append(n_flips > 0)
if verbose:
uw.pprint(0, f"[adapt] edge_split pass {level}: repaired "
f"with {n_flips} flip(s)")
Expand All @@ -9211,6 +9215,7 @@ def _relax_generation(engine_obj, carry, rcarry):
# parents from the composed vertex transfer instead
# of falling back to the geometric builder.
_nested_parent_cells.append(None)
_repaired_passes.append(False)
snap_level_boundaries(current_dm)
if _relax_mode == "per-generation":
_mg = Mesh(current_dm.clone(),
Expand Down Expand Up @@ -9403,7 +9408,8 @@ def _relax_generation(engine_obj, carry, rcarry):
base_finest, level_dms, _nested_Ps, _nested_parent_cells,
ratio=mg_coarsening_ratio, verbose=verbose,
resolution_hint=(_pct5_of_dm if engine == "edge_split"
else None))
else None),
repaired=_repaired_passes)

# Exact per-generation prolongations when the engine could supply them
# (cell-list path). Empty for the native transform path, which falls
Expand Down Expand Up @@ -9445,7 +9451,7 @@ def _relax_generation(engine_obj, carry, rcarry):

def _subsample_mg_levels(self, base_finest, level_dms, nested_Ps,
nested_parent_cells, ratio=2.0, verbose=False,
resolution_hint=None):
resolution_hint=None, repaired=None):
"""Keep one multigrid level per DOUBLING OF RESOLUTION, not one per pass.

A refinement engine takes as many passes as it needs to reach the size
Expand Down Expand Up @@ -9548,7 +9554,13 @@ def resolution(dm):
recorded = (nested_parent_cells[i]
if i == start and i < len(nested_parent_cells)
else None)
if recorded is not None:
# A repair flips cells after the split, so a fine cell can straddle two
# coarse cells; the map is then dropped for the whole span, on every
# rank. Deriving it anyway found a parent wherever the local flips
# happened not to straddle, so ranks disagreed (#961).
if repaired is not None and any(repaired[start:i + 1]):
parent_cells.append(None)
elif recorded is not None:
parent_cells.append(recorded)
elif composed[-1] is not None:
from underworld3.utilities.nvb import (
Expand Down
43 changes: 38 additions & 5 deletions src/underworld3/utilities/nvb.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,8 +211,9 @@ def nested_cell_parents(coarse_dm, fine_dm, vertex_transfer):
index and no orphaned coarse DOF.

Returns an ``(n_fine_cells,)`` array of coarse cell points, or ``None`` if
any fine cell's parent is not uniquely determined (the caller should then
fall back rather than guess).
any fine cell's parent, on any rank, is not uniquely determined (the caller
should then fall back rather than guess). COLLECTIVE: every rank gets the same
verdict.
"""
rows, cols, _ = vertex_transfer
cvS, cvE = coarse_dm.getDepthStratum(0)
Expand All @@ -233,6 +234,7 @@ def nested_cell_parents(coarse_dm, fine_dm, vertex_transfer):
refs[r].append(cpt)

parents = np.empty(fcE - fcS, dtype=np.int64)
unique = True
for k, c in enumerate(range(fcS, fcE)):
cand = None
for q in fine_dm.getTransitiveClosure(c)[0]:
Expand All @@ -243,12 +245,34 @@ def nested_cell_parents(coarse_dm, fine_dm, vertex_transfer):
if cand is not None and len(cand) == 1:
break
if not cand or len(cand) != 1:
return None
unique = False
break
parents[k] = next(iter(cand))
# one verdict on every rank: a map on some ranks and None on others sends the
# ranks down different transfer builders, which are collective (#961)
if not _on_every_rank(fine_dm, unique):
return None
return parents


def _on_every_rank(dm, ok):
"""Whether ``ok`` holds on every rank of ``dm``'s communicator. COLLECTIVE."""
from mpi4py import MPI
return bool(dm.getComm().tompi4py().allreduce(bool(ok), op=MPI.LAND))


def nested_prolongation_from_dms(coarse_dm, fine_dm):
"""The exact P1 prolongation of one bisection pass, or ``None`` when some rank
cannot recover it. COLLECTIVE: every rank gets the same verdict, so the callers'
fallbacks, which are collective, are taken on all ranks or none (#961). See
:func:`_nested_prolongation_local`."""
transfer = _nested_prolongation_local(coarse_dm, fine_dm)
if not _on_every_rank(fine_dm, transfer is not None):
return None
return transfer


def _nested_prolongation_local(coarse_dm, fine_dm):
"""Recover a refinement pass's exact P1 prolongation from the two DMs.

Every fine vertex of a bisection pass is an **inherited** coarse vertex or
Expand Down Expand Up @@ -280,21 +304,30 @@ def nested_prolongation_from_dms(coarse_dm, fine_dm):
cvS, cvE = coarse_dm.getDepthStratum(0)
ceS, ceE = coarse_dm.getDepthStratum(1)
cdim = coarse_dm.getCoordinateDim()
# Both coordinate vectors are collective the first time they are read: every rank
# reads them here, before any rank can return early (#961). A rank with no cells
# that returned before reading the fine coordinates left its peers waiting in that
# read while it went on to the verdict's reduction.
cxyz = np.ascontiguousarray(
coarse_dm.getCoordinatesLocal().array.reshape(-1, cdim))
fxyz = np.ascontiguousarray(
fine_dm.getCoordinatesLocal().array.reshape(-1, cdim))

edges = [(c[0] - cvS, c[1] - cvS)
for e in range(ceS, ceE)
for c in (coarse_dm.getCone(e),)
if len(c) == 2 and all(cvS <= q < cvE for q in c)]
if not edges:
# a rank that owns nothing has nothing to explain: an empty transfer, so it
# does not veto the others' (#961)
if fine_dm.getDepthStratum(0)[1] == fine_dm.getDepthStratum(0)[0]:
empty = np.empty(0, dtype=np.int64)
return empty, empty.copy(), np.empty(0, dtype=float)
return None
edges = np.asarray(edges, dtype=np.int64)

fvS, fvE = fine_dm.getDepthStratum(0)
feS, feE = fine_dm.getDepthStratum(1)
fxyz = np.ascontiguousarray(
fine_dm.getCoordinatesLocal().array.reshape(-1, cdim))
n_f = fvE - fvS
if fxyz.shape[0] != n_f:
return None
Expand Down
17 changes: 12 additions & 5 deletions tests/parallel/ptest_0844_reconnect_parallel.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,13 @@ def _global(x, op=MPI.SUM):
return uw.mpi.comm.allreduce(x, op=op)


def _everywhere(ok):
"""Whether ``ok`` holds on every rank. An assert on a rank-local fact ahead of a
collective leaves the other ranks waiting in it when it fails on one rank, so the
failure reads as a hang (#961); reduce first, then assert."""
return bool(uw.mpi.comm.allreduce(bool(ok), op=MPI.LAND))


def _owned_cells_and_area(dm):
cS, cE = dm.getHeightStratum(0)
owned = _owned(dm, range(cS, cE))
Expand Down Expand Up @@ -99,7 +106,7 @@ def test_geometry_and_conformity_survive():

out, _ = reconnect.flip_to_reduce_max_angle(dm)

assert out.getChart() == chart
assert _everywhere(out.getChart() == chart)
ncells_after, area_after = _owned_cells_and_area(out)
assert _global(ncells_after) == _global(ncells)
assert _global(area_after) == pytest.approx(_global(area), rel=1e-12)
Expand Down Expand Up @@ -148,8 +155,8 @@ def metric(centroids):
assert _global(sum(1 for f in range(fS, fE)
if len(child.dm.getSupport(f)) > 2)) == 0
# Flips move no vertex, so the exact vertex prolongation must survive.
assert child._adapt_prolongation and all(
P is not None for P in child._adapt_prolongation)
assert _everywhere(child._adapt_prolongation and all(
P is not None for P in child._adapt_prolongation))

# The cell-parent map must NOT survive a repair, because a flipped cell can
# straddle two coarse cells and using it would transfer from the wrong
Expand All @@ -163,10 +170,10 @@ def metric(centroids):
repair=repair, mg_coarsening_ratio=1.0)
arms[repair] = arm._adapt_parent_cells

assert any(pc is not None for pc in arms[False]), (
assert _everywhere(any(pc is not None for pc in arms[False])), (
"no parent-cell map survived WITHOUT repair, so the assertion below "
"cannot distinguish repair from anything else")
assert all(pc is None for pc in arms[True]), (
assert _everywhere(all(pc is None for pc in arms[True])), (
"a parent-cell map survived a repair pass; a flipped cell spans two "
"coarse cells and the transfer would read the wrong parent")

Expand Down
72 changes: 72 additions & 0 deletions tests/parallel/test_0874_nested_transfer_verdict_parallel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
"""The nested-transfer helpers give every rank the same verdict (#961).

``nvb.nested_cell_parents`` and ``nvb.nested_prolongation_from_dms`` return ``None`` when
the map or the transfer cannot be recovered, and their callers then take a fallback that
is collective (the geometric transfer builder). Each used to decide on its own rank's
cells: one rank returned ``None`` and the others an array, so the ranks went down
different builders (ptest_0844_reconnect hung at np 2 and 4, #961). The verdict is now
reduced over all ranks. On every rank:

- a vertex transfer spoiled on rank 0 only gives ``None`` for the cell-parent map;
- the transfer recovered from a regular refinement, and its cell-parent map, are found;
- a rank that owns no cells returns an empty transfer, not ``None``, so it does not veto
the others. A box of two triangles leaves a rank empty from np 2. On development that
rank's early return hung the job rather than failing it, which the CI supervisor
reports as a failure.

mpirun -n 2 python -m pytest --with-mpi tests/parallel/test_0874_nested_transfer_verdict_parallel.py
"""
import numpy as np
import pytest

import underworld3 as uw
from underworld3.utilities import nvb

pytestmark = [pytest.mark.mpi(min_size=2), pytest.mark.level_2, pytest.mark.tier_b,
pytest.mark.timeout(300)]


def _coarse_and_fine():
base = uw.meshing.UnstructuredSimplexBox(minCoords=(0.0, 0.0), maxCoords=(1.0, 1.0),
cellSize=0.2, regular=True, qdegree=2)
coarse = base.dm
return coarse, coarse.refine()


def test_a_transfer_spoiled_on_one_rank_gives_no_map_on_any():
coarse, fine = _coarse_and_fine()
transfer = nvb.nested_prolongation_from_dms(coarse, fine)
found = uw.mpi.comm.allgather(transfer is not None)
parents = nvb.nested_cell_parents(coarse, fine, transfer) if all(found) else None
good = uw.mpi.comm.allgather(parents is not None)
spoiled = None
if all(found):
rows, cols, vals = transfer
if uw.mpi.rank == 0 and cols.size:
# rank 0's fine vertices now refer, alternately, to two coarse vertices at
# opposite corners of its patch, which share no coarse cell: no fine cell there
# has a parent at all
X = coarse.getCoordinatesLocal().array.reshape(-1, 2)
a, b = int(np.argmin(X.sum(axis=1))), int(np.argmax(X.sum(axis=1)))
cols = np.where(np.arange(cols.size) % 2 == 0, a, b).astype(cols.dtype)
spoiled = nvb.nested_cell_parents(coarse, fine, (rows, cols, vals))
verdicts = uw.mpi.comm.allgather(spoiled is None)
assert all(found) and all(good), (found, good)
assert all(verdicts), verdicts


def test_a_rank_that_owns_nothing_does_not_veto_the_transfer():
# a box of two triangles: from np 2 some rank owns no cell (cells per rank [0, 2] at
# np 2, hyperion). On development that rank left its peers waiting in the fine
# coordinates' first read, which is collective, and the job hung
base = uw.meshing.UnstructuredSimplexBox(minCoords=(0.0, 0.0), maxCoords=(1.0, 1.0),
cellSize=1.0, regular=True, qdegree=2)
coarse = base.dm
fine = coarse.refine()
cs, ce = coarse.getHeightStratum(0)
empty = uw.mpi.comm.allgather(ce == cs)
transfer = nvb.nested_prolongation_from_dms(coarse, fine)
found = uw.mpi.comm.allgather(transfer is not None)
assert any(empty), ("no rank owns nothing at this rank count: the case has lost its "
"power", empty)
assert all(found), (found, empty)
54 changes: 54 additions & 0 deletions tests/test_0874_repair_drops_parent_maps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
"""A repaired edge_split pass leaves no cell-parent map on any level through it (#961).

``mesh.adapt(engine="edge_split", repair=True)`` flips cells after each split. A flipped
cell can straddle two coarse cells, so no level whose span includes a repaired pass may
carry a cell-parent map: the any-degree transfer has to use the geometric builder. The
subsampler used to derive the map for every retained span from the composed vertex
transfer, and kept it wherever the derivation found a unique parent for each cell. On one
rank that held exactly when no local flip straddled two coarse cells, so at np 2 one rank
kept a map and the other did not (ptest_0844_reconnect, #961).

The fixture makes that case deterministic and serial: a repair pass that reports flips
but changes nothing. Every cell then has a unique parent, so deriving the map succeeds,
and only the record of the repair can drop it.

- A repaired pass leaves every retained level without a map.
- The same adapt without repair keeps maps, so the first assertion is not vacuous.
"""
import numpy as np
import pytest

import underworld3 as uw
from underworld3.utilities import reconnect

pytestmark = [pytest.mark.level_2, pytest.mark.tier_b]

CENTRE = np.array([0.4, 0.55])


def _metric(centroids):
d = np.linalg.norm(np.asarray(centroids) - CENTRE, axis=1)
return 1.0 / np.where(d < 0.2, 0.04, 0.15) ** 2


def _base():
return uw.meshing.UnstructuredSimplexBox(minCoords=(0.0, 0.0), maxCoords=(1.0, 1.0),
cellSize=0.2, regular=False, refinement=1,
qdegree=3)


def test_a_repaired_pass_leaves_no_parent_map(monkeypatch):
# a repair that reports one flip per pass and moves nothing
monkeypatch.setattr(reconnect, "flip_to_reduce_max_angle", lambda dm, **kw: (dm, 1))
child = _base().adapt(_metric, max_levels=2, engine="edge_split", repair=True,
mg_coarsening_ratio=1.0)
assert len(child._adapt_parent_cells) > 1
assert all(pc is None for pc in child._adapt_parent_cells), [
None if pc is None else len(pc) for pc in child._adapt_parent_cells]


def test_without_repair_the_maps_are_kept():
child = _base().adapt(_metric, max_levels=2, engine="edge_split", repair=False,
mg_coarsening_ratio=1.0)
assert all(pc is not None for pc in child._adapt_parent_cells), [
None if pc is None else len(pc) for pc in child._adapt_parent_cells]
Loading