Skip to content

Commit 7131c2d

Browse files
authored
Merge pull request #145 from SMI-Lab-Inha/fix/sparse-indefinite-window
fix: take the sparse solver path only for a positive-definite K
2 parents 9856574 + fb4b298 commit 7131c2d

4 files changed

Lines changed: 247 additions & 14 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,29 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
88

99
## [Unreleased]
1010

11-
(nothing yet)
11+
### Fixed
12+
13+
- **The sparse solver path dropped negative modes.** Above 500 DOF a
14+
symmetric solve went through `eigsh` shift-invert at zero, which
15+
returns the eigenvalues smallest in *magnitude*. Those are the lowest
16+
only when `K` is positive definite. With an indefinite `K`, such as a
17+
tower loaded past buckling by `run(gravity=...)`, a strongly negative
18+
mode was left out and the window backfilled with positive ones, while
19+
the dense path below the threshold kept it. The answer therefore
20+
changed with mesh refinement alone. `K = diag(−100, 1, …, 500)` returned
21+
`[1, 2, 3]` for three modes instead of `[−100, 1, 2]`, and the bundled
22+
NREL 5MW land tower at 1000 times its RNA mass returned four buckled
23+
modes on the default mesh but two buckled and two positive ones once
24+
refined to 120 nodes. `solve_modes` now takes the sparse path only
25+
after a banded Cholesky confirms `K` is positive definite, and sends
26+
anything else to the dense path, which returns the algebraically
27+
lowest modes. The check costs about a millisecond of factorisation at
28+
9000 DOF because the assembled stiffness has a half-bandwidth of 10.
29+
The sparse path also now builds its symmetrised matrices sparsely
30+
instead of densely, which more than pays for the check: a 1000-node
31+
tower solves in 5.3 s instead of 8.2 s. Positive-definite results are
32+
unchanged within the run-to-run scatter of the sparse solver itself
33+
(about 1e-10 relative, from ARPACK's random starting vector).
1234

1335
## [1.19.0] — 2026-09-30
1436

‎VALIDATION.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,8 @@ is behavioural / contract-style.
242242
| Sparse path triggered above threshold | construction | log message announces "sparse shift-invert" | always | (within tol) | [`tests/fem/test_sparse_solver.py`](https://github.com/SMI-Lab-Inha/pyBModes/blob/master/tests/fem/test_sparse_solver.py) | no |
243243
| Sparse path skipped below threshold | construction | log message does not mention "sparse" | always | (within tol) | [`tests/fem/test_sparse_solver.py`](https://github.com/SMI-Lab-Inha/pyBModes/blob/master/tests/fem/test_sparse_solver.py) | no |
244244
| Asymmetric problems fall back to dense general `eig` | construction (asymmetric K) | log message announces "dense general"; sparse not invoked | always | (within tol) | [`tests/fem/test_sparse_solver.py`](https://github.com/SMI-Lab-Inha/pyBModes/blob/master/tests/fem/test_sparse_solver.py) | no |
245+
| Indefinite `K` keeps the algebraically lowest window on every path | construction (diagonal, coupled with scaled mass, zero modes, SPD control) + NREL 5MW land tower under gravity at 1000× RNA mass, default vs 120-node mesh | lowest-k eigenvalues; negative and zero modes kept; SPD still sparse; buckled tower identical on both meshes | `rtol = 1e-9` | exact | [`tests/fem/test_sparse_solver.py`](https://github.com/SMI-Lab-Inha/pyBModes/blob/master/tests/fem/test_sparse_solver.py) | no |
246+
| Positive-definiteness guard (banded Cholesky) agrees with a dense Cholesky | construction (random symmetric, tridiagonal, singular, full-width coupling, tiny asymmetry) | definite / not definite | always | (within tol) | [`tests/fem/test_sparse_solver.py`](https://github.com/SMI-Lab-Inha/pyBModes/blob/master/tests/fem/test_sparse_solver.py) | no |
245247
| `pybmodes patch --dry-run` writes nothing (mtime check) | construction | mtime of every staged file unchanged | exact match | (within tol) | [`tests/test_validate.py`](https://github.com/SMI-Lab-Inha/pyBModes/blob/master/tests/test_validate.py) | yes |
246248
| `pybmodes patch --diff` PR format contains `×` improvement ratio | construction | stdout contains `×`, `RMS improvement:`, `better` literals | exact match | (within tol) | [`tests/test_validate.py`](https://github.com/SMI-Lab-Inha/pyBModes/blob/master/tests/test_validate.py) | yes |
247249
| `pybmodes patch --output` leaves source byte-identical | construction | source-file sha256 unchanged | exact match | (within tol) | [`tests/test_validate.py`](https://github.com/SMI-Lab-Inha/pyBModes/blob/master/tests/test_validate.py) | yes |

‎src/pybmodes/fem/solver.py‎

Lines changed: 75 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,12 @@
2626
``ngd``). Routes through ``scipy.sparse.linalg.eigsh`` with
2727
``sigma=0`` shift-invert; an order-of-magnitude faster than the
2828
dense LAPACK solve for the few-lowest-modes case on a 500+ DOF
29-
tower mesh.
29+
tower mesh. Taken only when ``K`` is positive definite, checked by
30+
a banded Cholesky (:func:`_is_positive_definite`): shift-invert at
31+
zero returns the eigenvalues *smallest in magnitude*, which are the
32+
lowest only when none is negative. An indefinite ``K`` (a column
33+
loaded past buckling) goes to the dense path, which returns the
34+
algebraically lowest modes.
3035
2. **Dense symmetric** — ``scipy.linalg.eigh`` on the symmetrised
3136
matrices, applied to the *inverted* pencil ``M x = μ (K + s M) x``
3237
so that the lowest modes are resolved to relative rather than
@@ -138,13 +143,16 @@
138143
import logging
139144
import warnings
140145
from dataclasses import dataclass
141-
from typing import Literal, overload
146+
from typing import TYPE_CHECKING, Literal, overload
142147

143148
import numpy as np
144149
from scipy.linalg import eig, eigh
145150

146151
from pybmodes.options import DEFAULT_SOLVER_OPTIONS as _SOLVER_OPTIONS
147152

153+
if TYPE_CHECKING:
154+
from scipy.sparse import csc_matrix
155+
148156
_log = logging.getLogger(__name__)
149157

150158
# Above this reduced-system size the dense conditioning estimate
@@ -296,15 +304,30 @@ def solve_modes(
296304
eigvals: np.ndarray | None = None
297305
eigvecs: np.ndarray | None = None
298306

299-
# Sparse path — symmetric, big enough, small-subset request.
300-
if (
307+
# Sparse path — symmetric, big enough, small-subset request, and a
308+
# positive-definite K. Shift-invert at zero returns the eigenvalues
309+
# nearest zero in magnitude; with a negative one among them (a column
310+
# past buckling) that is not the lowest window, and the unstable mode
311+
# would be dropped silently. The dense path keeps it.
312+
sparse_candidate = (
301313
sym
302314
and ngd > _SPARSE_NDOF_THRESHOLD
303315
and n_modes is not None
304316
and n_modes < ngd // 2
305-
):
317+
)
318+
k_sp = _symmetric_sparse(gk) if sparse_candidate else None
319+
if k_sp is not None and not _is_positive_definite(k_sp):
320+
k_sp = None
321+
_log.info(
322+
"solve_modes: K is not positive definite; using the dense "
323+
"path so negative and zero modes stay in the window (ngd=%d)",
324+
ngd,
325+
)
326+
if k_sp is not None and n_modes is not None:
306327
try:
307-
eigvals, eigvecs = _solve_sparse_shift_invert(gk, gm, n_modes)
328+
eigvals, eigvecs = _solve_sparse_shift_invert(
329+
gk, gm, n_modes, k_sp=k_sp,
330+
)
308331
path = "sparse_shift_invert"
309332
_log.info(
310333
"solve_modes: sparse shift-invert path "
@@ -791,8 +814,47 @@ def _mass_matrix_cond(
791814
# Path implementations
792815
# ---------------------------------------------------------------------------
793816

817+
def _symmetric_sparse(a: np.ndarray) -> csc_matrix:
818+
"""``0.5 (A + A^T)`` as a CSC matrix, without another dense copy.
819+
820+
Bit-identical to symmetrising densely first: the same pairwise sum,
821+
and the halving is exact.
822+
"""
823+
from scipy.sparse import csc_matrix
824+
825+
s = csc_matrix(a)
826+
return csc_matrix((s + s.T) * 0.5)
827+
828+
829+
def _is_positive_definite(k_sp: csc_matrix) -> bool:
830+
"""Whether a symmetric sparse ``K`` admits a Cholesky factorisation.
831+
832+
The assembled stiffness is banded (half-bandwidth 10 on a tower mesh,
833+
whatever its size), so the check runs on the band: ``O(n b²)``, about
834+
a millisecond at 9000 DOF where a dense factorisation takes seconds.
835+
The band is measured from ``K`` itself, so a model with wider coupling
836+
is still checked exactly, only less cheaply.
837+
"""
838+
from scipy.linalg import cholesky_banded
839+
from scipy.sparse import triu
840+
841+
upper = triu(k_sp).tocoo()
842+
if upper.nnz == 0:
843+
return False
844+
offset = upper.col - upper.row
845+
b = int(offset.max())
846+
ab = np.zeros((b + 1, k_sp.shape[0]))
847+
np.add.at(ab, (b - offset, upper.col), upper.data)
848+
try:
849+
cholesky_banded(ab, lower=False, check_finite=False)
850+
except np.linalg.LinAlgError:
851+
return False
852+
return True
853+
854+
794855
def _solve_sparse_shift_invert(
795856
gk: np.ndarray, gm: np.ndarray, n_modes: int,
857+
*, k_sp: csc_matrix | None = None,
796858
) -> tuple[np.ndarray, np.ndarray]:
797859
"""Sparse symmetric generalised eigensolve via shift-invert near zero.
798860
@@ -802,15 +864,17 @@ def _solve_sparse_shift_invert(
802864
``OP = (K - σM)^-1 · M = K^-1 M`` under ``mode='normal'``. The
803865
eigenvalues of OP are ``1/λ``; ``which='LM'`` returns the largest,
804866
i.e. the smallest ``λ`` — exactly the modal-analysis ask.
867+
868+
Smallest in *magnitude*: that is the lowest window only when ``K`` is
869+
positive definite, which :func:`solve_modes` checks before calling
870+
this. ``k_sp`` passes in the symmetrised sparse ``K`` that check
871+
already built.
805872
"""
806-
from scipy.sparse import csc_matrix
807873
from scipy.sparse.linalg import eigsh
808874

809875
# Symmetrise to suppress sub-ULP scatter before factorisation.
810-
gk_sym = 0.5 * (gk + gk.T)
811-
gm_sym = 0.5 * (gm + gm.T)
812-
K_sp = csc_matrix(gk_sym)
813-
M_sp = csc_matrix(gm_sym)
876+
K_sp = k_sp if k_sp is not None else _symmetric_sparse(gk)
877+
M_sp = _symmetric_sparse(gm)
814878

815879
eigvals, eigvecs = eigsh(
816880
K_sp,

‎tests/fem/test_sparse_solver.py‎

Lines changed: 147 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,16 @@
11
"""Tests for the sparse-solver dispatch in ``pybmodes.fem.solver``.
22
3-
The solver gates the sparse shift-invert path on three conditions:
3+
The solver gates the sparse shift-invert path on four conditions:
44
55
ngd > _SPARSE_NDOF_THRESHOLD AND symmetric matrices AND a small
66
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.
814
915
These tests build small synthetic symmetric / asymmetric problems
1016
(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:
144150
assert eigvals.size == 6
145151
assert eigvecs.shape == (n, 6)
146152
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

Comments
 (0)