From 7565d5b44abcde0169790b39e0c16613d0aa14e3 Mon Sep 17 00:00:00 2001 From: Michal Januszewski Date: Thu, 3 Dec 2026 11:32:45 -0800 Subject: [PATCH] Add coarse-to-fine multigrid warm-starting in relax_mesh_multiscale. PiperOrigin-RevId: 1035592182 --- mesh.py | 164 +++++++++++++++++++++++++++++++++++++++ tests/mesh_test.py | 189 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 353 insertions(+) diff --git a/mesh.py b/mesh.py index 206a5ca..f56b8a8 100644 --- a/mesh.py +++ b/mesh.py @@ -800,3 +800,167 @@ def relax_mesh( e_kin[-1] if e_kin else 0.0, ) return x_final, e_kin, t + + +@functools.partial(jax.jit, static_argnames=['n_spatial', 'scale']) +def _upsample_mesh_nodes( + coarse: jnp.ndarray, + target_orig: jnp.ndarray, + n_spatial: int, + scale: float, +) -> jnp.ndarray: + """Linearly upsamples `coarse` onto `target_orig`, preserving `NaN` masks.""" + cur = coarse + dtype = cur.dtype + for ax in range(cur.ndim - n_spatial, cur.ndim): + target_len = target_orig.shape[ax] + max_idx = cur.shape[ax] - 1 + coords = jnp.clip( + jnp.arange(target_len, dtype=dtype) / scale, 0.0, float(max_idx) + ) + i0 = jnp.floor(coords).astype(jnp.int32) + i1 = jnp.minimum(i0 + 1, max_idx) + w1_shp = [1] * cur.ndim + w1_shp[ax] = target_len + w1 = (coords - i0.astype(dtype)).reshape(w1_shp) + v0 = jnp.take(cur, i0, axis=ax) + v1 = jnp.take(cur, i1, axis=ax) + v0_fin = jnp.isfinite(v0) + v1_fin = jnp.isfinite(v1) + # Keep exact coarse nodes (w1 == 0) intact so a masked NaN node does not + # pick up its finite neighbor before subsequent spatial axis passes. + cur = jnp.where( + w1 == 0.0, + v0, + jnp.where( + v0_fin & v1_fin, + v0 * (1.0 - w1) + v1 * w1, + jnp.where(v0_fin, v0, v1), + ), + ) + return jnp.where( + jnp.isnan(target_orig), + jnp.nan, + jnp.where(jnp.isfinite(cur), cur, target_orig), + ) + + +def relax_mesh_multiscale( + x: jax.Array | np.ndarray, + prev: jax.Array | np.ndarray | None, + config: IntegrationConfig, + scales: Sequence[int] = (4, 2, 1), + coarse_max_iters: int | None = None, + mesh_force=inplane_force, +) -> tuple[jnp.ndarray, list[float], int]: + """Relaxes a spring mesh using coarse-to-fine multigrid warm-starting. + + Args: + x: [N, z, y, x] initial mesh node positions (`NaN` entries are preserved as + masked nodes across scales) + prev: optional [N, z, y, x] target node positions for 0-length inter-section + springs + config: fine-grid integration parameters + scales: strictly decreasing sequence of positive integer spatial + subsampling factors ending in 1 (for 2D `inplane_force`, applied to YX; + for 3D, applied to ZYX) + coarse_max_iters: optional iteration cap for coarse levels (`s > 1`); + defaults to `config.max_iters` for the coarsest level and + `min(config.max_iters, max(config.num_iters, config.max_iters // 4))` + for intermediate levels; passing 0 skips all coarse levels + mesh_force: internal spring force function (`inplane_force` or + `elastic_mesh_3d`) + + Returns: + tuple of (relaxed fine mesh, cumulative kinetic energy history, total steps) + """ + if ( + not scales + or any(isinstance(s, bool) or not isinstance(s, int) for s in scales) + or scales[-1] != 1 + or any(a <= b for a, b in zip(scales, scales[1:])) + ): + raise ValueError( + 'scales must be a strictly decreasing sequence of positive integers ' + f'ending in 1, got {scales!r}.' + ) + if coarse_max_iters is not None and coarse_max_iters < 0: + raise ValueError( + f'coarse_max_iters must be non-negative, got {coarse_max_iters!r}.' + ) + + if config.max_iters <= 0: + return relax_mesh(x, prev, config, mesh_force=mesh_force) + + dtype = jnp.result_type(x, jnp.float32) + x_arr = jnp.asarray(x, dtype=dtype) + prev_arr = None if prev is None else jnp.asarray(prev, dtype=dtype) + n_spatial = len(config.stride) + fine_spatial = x_arr.shape[-n_spatial:] + + cur_x: jnp.ndarray | None = None + prev_scale: int | None = None + cap_ramped = False + all_e_kin: list[float] = [] + total_steps = 0 + + for s in scales: + if s > 1 and ( + coarse_max_iters == 0 or any(n < 2 * s for n in fine_spatial) + ): + continue + + lvl_cap = config.final_cap if cap_ramped else config.start_cap + if s == 1: + lvl_prev = prev_arr + lvl_x_orig = x_arr + lvl_cfg = ( + dataclasses.replace(config, start_cap=lvl_cap) + if lvl_cap != config.start_cap + else config + ) + else: + slc = (...,) + (slice(None, None, s),) * n_spatial + lvl_prev = None if prev_arr is None else prev_arr[slc] + lvl_x_orig = x_arr[slc] + has_valid = jnp.any(jnp.isfinite(lvl_x_orig)) + if lvl_prev is not None and config.k0 != 0.0: + has_valid = has_valid & jnp.any(jnp.isfinite(lvl_prev)) + if not bool(has_valid): + continue + scaled_stride = tuple(float(st) * s for st in config.stride) + if coarse_max_iters is not None: + c_max = coarse_max_iters + elif cur_x is None: + c_max = config.max_iters + else: + c_max = min( + config.max_iters, max(config.num_iters, config.max_iters // 4) + ) + lvl_cfg = dataclasses.replace( + config, + stride=scaled_stride, # pyrefly: ignore[bad-argument-type] + max_iters=c_max, + stop_v_max=config.stop_v_max * s, + start_cap=lvl_cap, + ) + + if cur_x is None: + lvl_x = lvl_x_orig + else: + assert prev_scale is not None + lvl_x = _upsample_mesh_nodes( + cur_x, lvl_x_orig, n_spatial, prev_scale / s + ) + + cur_x, e_kin, steps = relax_mesh( + lvl_x, lvl_prev, lvl_cfg, mesh_force=mesh_force + ) + if steps < lvl_cfg.max_iters: + cap_ramped = True + prev_scale = s + all_e_kin.extend(e_kin) + total_steps += steps + + assert cur_x is not None + return cur_x, all_e_kin, total_steps diff --git a/tests/mesh_test.py b/tests/mesh_test.py index dda92da..0bba94e 100644 --- a/tests/mesh_test.py +++ b/tests/mesh_test.py @@ -15,6 +15,9 @@ """Tests for mesh.""" +import dataclasses +from unittest import mock + from absl.testing import absltest import jax import jax.numpy as jnp @@ -254,6 +257,192 @@ def test_chunked_fire_n_pos_persistence_and_stepback(self): x_sb, _, _ = mesh.relax_mesh(x, prev, cfg_stepback) np.testing.assert_allclose(x_sb, x_single, atol=0.05) + def test_relax_mesh_multiscale(self): + yy, xx = np.mgrid[:48, :48] + prev = np.zeros((2, 1, 48, 48), dtype=np.float32) + prev[0, 0] = 6.0 * np.sin(yy / 15.0) * np.cos(xx / 15.0) + prev[1, 0] = -4.0 * np.cos(yy / 15.0) + prev[:, 0, :4, :4] = np.nan + + cfg = mesh.IntegrationConfig( + dt=0.01, + gamma=0.0, + k0=0.05, + k=0.1, + stride=(20.0, 20.0), + num_iters=50, + max_iters=5000, + stop_v_max=5e-4, + fire=True, + prefer_orig_order=True, + ) + x0 = np.zeros_like(prev) + ref_x, _, _ = mesh.relax_mesh(x0, prev, cfg) + # Default coarse_max_iters=None exercises coarsest & intermediate budgets. + ms_x, _, _ = mesh.relax_mesh_multiscale(x0, prev, cfg, scales=(4, 2, 1)) + np.testing.assert_allclose(ms_x, ref_x, atol=2e-2) + + # Non-divisible scale transitions (3 -> 2 -> 1) use float upsampling ratios. + ms_nondiv, _, _ = mesh.relax_mesh_multiscale( + x0, prev, cfg, scales=(3, 2, 1), coarse_max_iters=200 + ) + np.testing.assert_allclose(ms_nondiv, ref_x, atol=2e-2) + + # Invalid scale schedules are rejected. + for bad_scales in ( + (), + (4, 2), + (2, 2, 1), + (2, 4, 1), + (0, 1), + (-2, 1), + (2.5, 1), + (True,), + ): + with self.assertRaises(ValueError): + mesh.relax_mesh_multiscale(x0, prev, cfg, scales=bad_scales) + + # NaN-masked x inputs preserve the exact NaN mask without bleeding NaNs. + x0_masked = x0.copy() + x0_masked[:, 0, :6, :6] = np.nan + ref_masked, _, _ = mesh.relax_mesh(x0_masked, prev, cfg) + ms_masked, _, _ = mesh.relax_mesh_multiscale( + x0_masked, prev, cfg, scales=(4, 2, 1), coarse_max_iters=200 + ) + np.testing.assert_array_equal(np.isnan(ms_masked), np.isnan(x0_masked)) + np.testing.assert_allclose( + ms_masked, ref_masked, atol=2e-2, equal_nan=True + ) + + # 3D elastic_mesh_3d multiscale relaxation matches single-scale relax_mesh. + zz, yy3, xx3 = np.mgrid[:8, :8, :8] + prev3 = np.stack( + [ + 2.0 * np.sin(yy3 / 3.0), + -1.5 * np.cos(xx3 / 3.0), + 1.0 * np.sin(zz / 3.0), + ], + axis=0, + ).astype(np.float32) + x0_3d = np.zeros_like(prev3) + cfg3 = dataclasses.replace( + cfg, stride=(20.0, 20.0, 20.0), stop_v_max=1e-3, max_iters=2000 + ) + ref_3d, _, _ = mesh.relax_mesh( + x0_3d, prev3, cfg3, mesh_force=mesh.elastic_mesh_3d + ) + ms_3d, _, _ = mesh.relax_mesh_multiscale( + x0_3d, prev3, cfg3, scales=(2, 1), mesh_force=mesh.elastic_mesh_3d + ) + np.testing.assert_allclose(ms_3d, ref_3d, atol=2e-2) + + def test_relax_mesh_multiscale_edge_cases_and_adaptive_cap(self): + yy, xx = np.mgrid[:32, :32] + prev = np.zeros((2, 1, 32, 32), dtype=np.float32) + prev[0, 0] = 6.0 * np.sin(yy / 10.0) * np.cos(xx / 10.0) + prev[1, 0] = -4.0 * np.cos(yy / 10.0) + x0 = np.zeros_like(prev) + x0[:, 0, 1, 1] = 10.0 # Off-coarse fine displacement. + + cfg = mesh.IntegrationConfig( + dt=0.01, + gamma=0.0, + k0=0.05, + k=0.1, + stride=(20.0, 20.0), + num_iters=50, + max_iters=0, + stop_v_max=5e-4, + fire=True, + ) + # max_iters <= 0 is a strict no-op matching relax_mesh. + for max_iters in (0, -10): + zero_cfg = dataclasses.replace(cfg, max_iters=max_iters) + out_x, e_kin, steps = mesh.relax_mesh_multiscale( + x0, prev, zero_cfg, scales=(4, 2, 1) + ) + self.assertEqual(steps, 0) + self.assertEqual(e_kin, []) + np.testing.assert_array_equal(out_x, x0) + + # Negative coarse_max_iters is rejected. + with self.assertRaises(ValueError): + mesh.relax_mesh_multiscale( + x0, prev, dataclasses.replace(cfg, max_iters=100), coarse_max_iters=-1 + ) + + # coarse_max_iters == 0 skips coarse levels and preserves fine initial x. + fine_cfg = dataclasses.replace(cfg, max_iters=50) + ref_x, ref_e, ref_steps = mesh.relax_mesh(x0, prev, fine_cfg) + ms_x, ms_e, ms_steps = mesh.relax_mesh_multiscale( + x0, prev, fine_cfg, scales=(4, 2, 1), coarse_max_iters=0 + ) + self.assertEqual(ms_steps, ref_steps) + self.assertEqual(ms_e, ref_e) + np.testing.assert_array_equal(ms_x, ref_x) + + # Adaptive force cap stays at start_cap until a coarse level converges. + cap_cfg = dataclasses.replace( + cfg, + num_iters=25, + max_iters=4000, + stop_v_max=1e-3, + start_cap=0.01, + final_cap=10.0, + cap_scale=2.0, + ) + seen_start_caps: list[float] = [] + orig_relax = mesh.relax_mesh + + def _record_relax(*args, **kwargs): + seen_start_caps.append(args[2].start_cap) + return orig_relax(*args, **kwargs) + + # Tiny coarse_max_iters=25 prevents coarse convergence -> keep start_cap. + with mock.patch.object(mesh, 'relax_mesh', side_effect=_record_relax): + mesh.relax_mesh_multiscale( + x0, prev, cap_cfg, scales=(4, 2, 1), coarse_max_iters=25 + ) + self.assertEqual(seen_start_caps, [0.01, 0.01, 0.01]) + + # Sufficient coarse budget lets s=4 converge -> finer levels use final_cap. + seen_start_caps.clear() + with mock.patch.object(mesh, 'relax_mesh', side_effect=_record_relax): + mesh.relax_mesh_multiscale( + x0, prev, cap_cfg, scales=(4, 2, 1), coarse_max_iters=4000 + ) + self.assertEqual(seen_start_caps[0], 0.01) + self.assertEqual(seen_start_caps[1:], [10.0, 10.0]) + + # All-NaN coarse subgrid (sparse anchors between ::4 points) is skipped + # without prematurely ramping start_cap to final_cap. + sparse_prev = np.full_like(prev, np.nan) + sparse_prev[:, 0, 1:4, 1:4] = 5.0 + seen_start_caps.clear() + with mock.patch.object(mesh, 'relax_mesh', side_effect=_record_relax): + mesh.relax_mesh_multiscale( + x0, sparse_prev, cap_cfg, scales=(4, 2, 1), coarse_max_iters=4000 + ) + # s=4 has no finite prev anchors -> skipped; s=2 hits (2, 2) at start_cap. + self.assertEqual(seen_start_caps, [0.01, 10.0]) + + # prev=None (free relaxation) is supported consistently with relax_mesh. + # A curl-free (zero-torque) displacement relaxes uniquely to zero. + free_cfg = dataclasses.replace( + cfg, + k0=0.0, + max_iters=4000, + stop_v_max=1e-4, + remove_drift=True, + ) + x0_free = np.zeros_like(prev) + x0_free[0, 0] = 3.0 * np.sin(xx / 10.0) + x0_free[1, 0] = -3.0 * np.sin(yy / 10.0) + ms_free, _, _ = mesh.relax_mesh_multiscale( + x0_free, None, free_cfg, scales=(4, 2, 1) + ) + np.testing.assert_allclose(ms_free, 0.0, atol=2e-2) + def test_relax_mesh_fused_matches_stepwise_verlet(self): rng = np.random.default_rng(7) x0 = rng.normal(0.0, 2.0, size=(2, 1, 16, 16)).astype(np.float32)