|
1 | 1 | """Tests for the sparse-solver dispatch in ``pybmodes.fem.solver``. |
2 | 2 |
|
3 | | -The solver gates the sparse shift-invert path on three conditions: |
| 3 | +The solver gates the sparse shift-invert path on four conditions: |
4 | 4 |
|
5 | 5 | ngd > _SPARSE_NDOF_THRESHOLD AND symmetric matrices AND a small |
6 | 6 | subset of modes was requested (``n_modes is not None`` and |
7 | | - ``n_modes < ngd // 2``). |
| 7 | + ``n_modes < ngd // 2``) AND a positive-definite K. |
| 8 | +
|
| 9 | +The last one exists because shift-invert at zero returns the |
| 10 | +eigenvalues smallest in magnitude, which are the lowest only when none |
| 11 | +is negative. Without it an indefinite K (a column loaded past buckling) |
| 12 | +lost its unstable modes on the sparse path while the dense path kept |
| 13 | +them, so the answer changed with mesh refinement alone. |
8 | 14 |
|
9 | 15 | These tests build small synthetic symmetric / asymmetric problems |
10 | 16 | (no FEM pipeline needed) so they're fast and self-contained. |
@@ -144,3 +150,142 @@ def test_dense_fallback_on_asymmetric(caplog: pytest.LogCaptureFixture) -> None: |
144 | 150 | assert eigvals.size == 6 |
145 | 151 | assert eigvecs.shape == (n, 6) |
146 | 152 | assert np.all(np.isfinite(eigvals)) |
| 153 | + |
| 154 | + |
| 155 | +# --------------------------------------------------------------------------- |
| 156 | +# Indefinite K: the sparse path must not change the returned window |
| 157 | +# --------------------------------------------------------------------------- |
| 158 | + |
| 159 | +_N_BIG = _SPARSE_NDOF_THRESHOLD + 1 |
| 160 | + |
| 161 | + |
| 162 | +def _rotated(d: np.ndarray, seed: int) -> np.ndarray: |
| 163 | + """``Q diag(d) Q^T`` with a random orthogonal ``Q``: a fully coupled |
| 164 | + symmetric matrix with a chosen spectrum.""" |
| 165 | + rng = np.random.default_rng(seed) |
| 166 | + q, _r = np.linalg.qr(rng.standard_normal((d.size, d.size))) |
| 167 | + k = q @ np.diag(d) @ q.T |
| 168 | + return 0.5 * (k + k.T) |
| 169 | + |
| 170 | + |
| 171 | +def _lowest(gk: np.ndarray, gm: np.ndarray, n: int) -> np.ndarray: |
| 172 | + from scipy.linalg import eigh |
| 173 | + |
| 174 | + return eigh(gk, gm, eigvals_only=True, subset_by_index=(0, n - 1)) |
| 175 | + |
| 176 | + |
| 177 | +class TestIndefiniteStiffnessKeepsTheLowestWindow: |
| 178 | + def test_large_negative_mode_is_not_dropped(self): |
| 179 | + """The reported case: shift-invert at zero picked [1, 2, 3] here |
| 180 | + because |-100| is larger than 3.""" |
| 181 | + gk = np.diag(np.concatenate([[-100.0], np.arange(1.0, _N_BIG)])) |
| 182 | + vals, _vecs, diag = solve_modes( |
| 183 | + gk, np.eye(_N_BIG), 3, return_diagnostics=True, |
| 184 | + ) |
| 185 | + np.testing.assert_allclose(vals, [-100.0, 1.0, 2.0], rtol=1e-12) |
| 186 | + assert diag.path == "dense_symmetric" |
| 187 | + assert diag.sparse_fallback is False |
| 188 | + |
| 189 | + def test_coupled_stiffness_with_scaled_mass(self): |
| 190 | + rng = np.random.default_rng(4) |
| 191 | + d = np.concatenate([[-50.0, -7.0], rng.uniform(1.0, 400.0, _N_BIG - 2)]) |
| 192 | + gk = _rotated(d, seed=5) |
| 193 | + gm = np.diag(rng.uniform(0.5, 20.0, _N_BIG)) |
| 194 | + vals, vecs = solve_modes(gk, gm, 4) |
| 195 | + np.testing.assert_allclose(vals, _lowest(gk, gm, 4), rtol=1e-9) |
| 196 | + assert vals[0] < 0.0 and vals[1] < 0.0 |
| 197 | + residual = gk @ vecs - (gm @ vecs) * vals |
| 198 | + assert np.max(np.abs(residual)) < 1e-8 * np.max(np.abs(gk)) |
| 199 | + |
| 200 | + def test_zero_modes_stay_in_the_window(self): |
| 201 | + d = np.concatenate([np.zeros(3), np.arange(1.0, _N_BIG - 2)]) |
| 202 | + gk = _rotated(d, seed=6) |
| 203 | + vals, _vecs, diag = solve_modes( |
| 204 | + gk, np.eye(_N_BIG), 5, return_diagnostics=True, |
| 205 | + ) |
| 206 | + assert diag.path == "dense_symmetric" |
| 207 | + assert np.all(np.abs(vals[:3]) < 1e-9 * float(np.max(d))) |
| 208 | + np.testing.assert_allclose(vals[3:], [1.0, 2.0], rtol=1e-9) |
| 209 | + |
| 210 | + def test_positive_definite_stiffness_still_goes_sparse(self): |
| 211 | + gk, gm = _spd_problem(_N_BIG, seed=7) |
| 212 | + vals, _vecs, diag = solve_modes(gk, gm, 4, return_diagnostics=True) |
| 213 | + assert diag.path == "sparse_shift_invert" |
| 214 | + np.testing.assert_allclose(vals, _lowest(gk, gm, 4), rtol=1e-8) |
| 215 | + |
| 216 | + |
| 217 | +class TestPositiveDefiniteCheck: |
| 218 | + @staticmethod |
| 219 | + def _check(a: np.ndarray) -> bool: |
| 220 | + return solver._is_positive_definite(solver._symmetric_sparse(a)) |
| 221 | + |
| 222 | + def test_matches_a_dense_cholesky(self): |
| 223 | + from scipy.linalg import cho_factor |
| 224 | + |
| 225 | + rng = np.random.default_rng(8) |
| 226 | + for shift in (-5.0, -0.5, 0.5, 5.0): |
| 227 | + a = rng.standard_normal((60, 60)) |
| 228 | + k = 0.5 * (a + a.T) + shift * 10.0 * np.eye(60) |
| 229 | + try: |
| 230 | + cho_factor(k) |
| 231 | + expected = True |
| 232 | + except np.linalg.LinAlgError: |
| 233 | + expected = False |
| 234 | + assert self._check(k) is expected, shift |
| 235 | + |
| 236 | + def test_banded_tridiagonal(self): |
| 237 | + n = 200 |
| 238 | + k = 2.0 * np.eye(n) - np.eye(n, k=1) - np.eye(n, k=-1) |
| 239 | + assert self._check(k) # second-difference matrix, SPD |
| 240 | + k[0, 0] = -1.0 |
| 241 | + assert not self._check(k) |
| 242 | + |
| 243 | + def test_singular_and_empty_are_not_definite(self): |
| 244 | + assert not self._check(np.diag([1.0, 0.0, 2.0])) |
| 245 | + assert not self._check(np.zeros((4, 4))) |
| 246 | + |
| 247 | + def test_wide_coupling_is_still_exact(self): |
| 248 | + """A far off-diagonal coupling widens the band to the whole |
| 249 | + matrix; the check must still see it.""" |
| 250 | + n = 40 |
| 251 | + k = np.eye(n) |
| 252 | + k[0, n - 1] = k[n - 1, 0] = 2.0 # makes the 2x2 minor indefinite |
| 253 | + assert not self._check(k) |
| 254 | + k[0, n - 1] = k[n - 1, 0] = 0.5 |
| 255 | + assert self._check(k) |
| 256 | + |
| 257 | + def test_symmetrises_tiny_asymmetry(self): |
| 258 | + k = np.diag([3.0, 2.0, 1.0]) |
| 259 | + k[0, 1], k[1, 0] = 1.0, 1.0 + 1e-14 |
| 260 | + assert self._check(k) |
| 261 | + |
| 262 | + |
| 263 | +def test_buckled_tower_does_not_depend_on_the_mesh(): |
| 264 | + """A real model: the bundled NREL 5MW land tower under gravity with |
| 265 | + 1000 times its RNA mass is far past buckling. On the default mesh |
| 266 | + (dense path) its lowest four eigenvalues are all negative, reported |
| 267 | + as 0 Hz. Refined past the sparse threshold it used to return two |
| 268 | + positive modes among them instead.""" |
| 269 | + import warnings |
| 270 | + |
| 271 | + from pybmodes.cli import _resolve_examples_root |
| 272 | + from pybmodes.models import Tower |
| 273 | + |
| 274 | + bmi = ( |
| 275 | + _resolve_examples_root() / "sample_inputs" / "reference_turbines" |
| 276 | + / "01_nrel5mw_land" / "01_nrel5mw_land_tower.bmi" |
| 277 | + ) |
| 278 | + |
| 279 | + def run(nodes): |
| 280 | + tower = Tower(bmi) |
| 281 | + if nodes is not None: |
| 282 | + tower.refine_mesh(nodes) |
| 283 | + tower._bmi.tip_mass.mass *= 1000.0 |
| 284 | + with warnings.catch_warnings(): |
| 285 | + warnings.simplefilter("ignore") |
| 286 | + return tower.run(n_modes=4, check_model=False, gravity=True) |
| 287 | + |
| 288 | + coarse, fine = run(None), run(120) |
| 289 | + assert fine.diagnostics.path == "dense_symmetric" |
| 290 | + np.testing.assert_array_equal(coarse.frequencies, 0.0) |
| 291 | + np.testing.assert_array_equal(fine.frequencies, 0.0) |
0 commit comments