Skip to content

Add snapshot-based balanced POD for continuous-time LTI systems - #219

Open
TommyDanMa wants to merge 3 commits into
SciML:mainfrom
TommyDanMa:feat/bpod-pr
Open

TommyDanMa wants to merge 3 commits into
SciML:mainfrom
TommyDanMa:feat/bpod-pr

Conversation

@TommyDanMa

@TommyDanMa TommyDanMa commented Nov 14, 2026 •

Copy link
Copy Markdown

Summary

Adds snapshot-based Balanced Proper Orthogonal Decomposition (BPOD) for continuous-time linear time-invariant systems, using Rowley's (2005) direct primal/adjoint snapshot formulation.

Related to #11.

The new public function is:

bpod(A, B, C, X, Y, D = nothing; n = nothing, atol = 0, rtol = 1e-3)

It accepts already-weighted primal and adjoint snapshot factors, computes the SVD of Y' * X, and constructs the balanced Petrov-Galerkin projectors and reduced system.

The result reuses the existing BalancedTruncation type, containing reduced A, B, C, D, retained approximate Hankel singular values, and the left/right projectors.

The implementation:

  • Follows the order-selection and numerical-rank conventions of baltrunc.
  • Supports Float32, Float64, compatible mixed precision, and common sparse/banded matrix representations.
  • Validates dimensions, finite inputs, and numerical rank.
  • Includes a documented end-to-end example generating quadrature-weighted impulse snapshots.

Numerical validation

Tests cover:

  • Agreement with classical balanced truncation using exact Gramian factors.
  • Independent Cholesky-based balancing identities and full-order transfer-function equivalence.
  • Convergence using forward and adjoint impulse snapshots.
  • Coarse quadrature as a negative control: biorthogonality alone does not establish accurate balancing.
  • Reduced frequency-response comparisons.
  • Rank-deficient factors, unequal snapshot counts, repeated singular values, input validation, precision, and structured matrix storage.
  • Cases where poor finite-horizon snapshots produce unstable reduced models.

Validation status

The full Core suite and documentation build remain blocked by the unrelated MethodOfLines 1.6 incompatibility documented in #216. PR #218 proposes a fix. The same DEIM failure was reproduced on the upstream baseline without these BPOD changes.

The complete documentation build, including final rendering and link checks, has therefore not been verified.

Scope and limitations

This PR implements the snapshot-based reduction core. The caller supplies weighted factors X and Y; snapshot generation, ODE integration, analytic tail correction, and ModelingToolkit integration are outside the scope.

The dense interaction SVD may become expensive when snapshot counts are large. Finite-horizon and quadrature errors affect the reduced model, and stability is not guaranteed for approximate factors.

I would particularly welcome maintainer feedback on whether this low-level snapshot-factor API is the appropriate initial scope for #11, and whether automatic snapshot generation should be considered as a follow-up PR.

@TommyDanMa
TommyDanMa marked this pull request as ready for review November 14, 2026 19:17
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member

🤖 Automated comment from an AI agent running as @ChrisRackauckas — not written or reviewed by Chris.

PR: #219

Reviewed head: 52f33cb
Raw SHA-256: 0c43ed6a1dc54f3e1daf70ea6a208e0d20cabf09045055cec4c6c194785b4ab5
Source SHA-256: c179653cbca767ef866ad17d2c11abfba7a111a4a4c2370432ef813d2763f047
Source: standard-review-v1 (harness-log)
Reviewer session: 01a1ffc4-6950-7d61-9310-75819be5afb6
Slot: 1
Confidence: unknown
Own risk fixed before author rating/discussion: yes
Redaction: ran (substitutions=0)

Risk assessment

  • Risk: medium-low (ML7)
  • Verdict: CHANGES
  • Reviewed head: 52f33cb

Review report

VERDICT: CHANGES
Round: 1
Head: 52f33cb
Slot: 1
CI: CI unreadable; review only; merge gates unchanged
Session: 01a1ffc4-6950-7d61-9310-75819be5afb6
Reviewer: codex-cli 0.170.0; model: gpt-6.2-sol

Risk

medium-low (ML7: additive bpod API with a docstring, rendered documentation entry, and numerical tests)

Blocking findings

  • Blocking priorities: P1, P2, P2
  • [P1] src/bpod.jl:194 Mixed precision rejects valid single-output row matrices. With Float64 A, X, and Y, both C = Float32[1, 0]' and transpose(Float32[1, 0]) threw MethodError for _coerce_operator(::Vector{Float32}, ::Type{Float64}). The Float64 row produced the expected reduced output coefficient 1.0. The wrapper branch recurses into a vector, while the helper accepts only matrices. Convert the wrapper with a storage-preserving array conversion and add regression tests for both row forms.
  • [P2] src/bpod.jl:186 Projection can silently return an infinite pole from finite inputs with a representable exact result. For a one-state system with A = -1e300, X = 1e100, Y = 1e-100, B = sqrt(-2A) * X, and C = sqrt(-2A) * Y, the exact one-state projection has pole -1e300 and DC gain about 2. The probe returned pole -Inf and gain 0.0 because A * Tr overflowed. Use a scale-aware projection or reject non-finite reduced coefficients explicitly, and cover this case.
  • [P2] src/bpod.jl:226 The finiteness check inspects padding in SymTridiagonal. SymTridiagonal(Float32[-1, -2], Float32[0.25, NaN]) materialized as a finite matrix, but bpod rejected it with A contains non-finite entries. The final off-diagonal storage element is outside the matrix. Validate the logical diagonals, for example with diag(A) and diag(A, 1), and test this storage layout.

Non-blocking findings

  • test/bpod.jl:111 The H₂ helper masks the sign of the computed energy. A scratch mutation that negated the trace produced the same 0.2886751345948129 for a scalar difference with analytic energy 1/12. Check the signed trace and allow a clamp to zero only within a justified roundoff bound.
  • src/bpod.jl:174 A valid integer type can escape the documented error path. n = big(typemax(Int)) + 1 raised InexactError in the order helper. Compare n against the available rank before narrowing it to Int.
  • src/bpod.jl:35 and docs/src/tutorials/balanced_pod.md:21 claim the SVD dominates the cost. From the matrix dimensions, forming Y' * X costs O(nx * nX * nY) and can dominate when the state count is much larger than both snapshot counts. State the two costs and qualify the claim.

What I ran

  • Julia 1.12.4 with the review depot preserved. GROUP=Core julia --project -e 'using Pkg; Pkg.test()' passed bpod 190/190 and balanced truncation 15/15, then stopped at test/deim.jl:50 with DimensionMismatch: solution states must match the system unknowns. Core passed on current origin/main, including DEIM 77/77. With the PR test dependencies at the actual merge base, the same DEIM call failed with 12 snapshot rows and 2 symbolic unknowns. Current origin/main counts scalar unknowns for this check.
  • GROUP=QA julia --project -e 'using Pkg; Pkg.test()' passed JET 5/5 and package QA 21/21.
  • julia --project=docs docs/make.jl passed on current origin/main. Both PR-head runs stopped before rendering after the existing DEIM tutorial hit the same DimensionMismatch at docs/src/tutorials/deim_FitzHugh-Nagumo.md:137. All five balanced POD tutorial blocks ran in isolation.
  • Package probes (julia --project ../operators.jl and julia --project ../probes.jl) reproduced the blocking cases. The independent closed-form impulse-spectrum and transfer-map probe passed 13/13 checks on unequal grids. Its error against the exact finite-horizon spectrum decreased from 0.07260 to 0.001223 over three step halvings.
  • git diff --check, Runic in check mode on changed Julia files, and typos on changed files passed. uv run --locked python --version printed Python 3.13.13 and warned that --locked had no effect outside a Python project. This Julia checkout has no uv.lock.

What I did not verify

  • The remaining PR-head Core tests after the DEIM error and the rendered PR documentation. I stopped a duplicate Core run after more than 27 minutes in dbdsqr through the existing TSVD path, as observed in two debugger snapshots. That run produced no second Core result.
  • Other Julia versions and 32-bit execution.

AUTHOR_GRADE: {"task":"feature","score":3,"difficulty":3,"rounds":1,"author_harness":"unknown","author_model":"unknown","note":"The balanced POD and analytic convergence tests pass, but supported operator inputs fail and a finite scalar projection can silently return an infinite pole."}

Head link: 52f33cb


🤖 Posted by an AI agent — harness: codex-cli 0.170.0 · model: gpt-6.2-sol
Conversation: local session 01a1ffc4-6950-7d61-9310-75819be5afb6 (no session URL)

ChrisRackauckas and others added 2 commits November 23, 2026 11:19
Co-Authored-By: Chris Rackauckas <accounts@chrisrackauckas.com>
Co-Authored-By: Codex <noreply@openai.com>
Agent-Harness: Codex CLI 0.170.0
Agent-Model: gpt-6.1-terra
Agent-Job: SciML__ModelOrderReduction.jl__219--20261123T153908Z-codex-gpt-6.1-terra
Agent-Session: local session 01a2090f-ada7-7c82-b3a3-538d685ba97e (no session URL)
Co-Authored-By: Chris Rackauckas <accounts@chrisrackauckas.com>
Co-Authored-By: Codex <noreply@openai.com>
Agent-Harness: Codex CLI 0.170.0
Agent-Model: gpt-6.1-terra
Agent-Job: SciML__ModelOrderReduction.jl__219--20261123T153908Z-codex-gpt-6.1-terra
Agent-Session: local session 01a2090f-ada7-7c82-b3a3-538d685ba97e (no session URL)
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member

🤖 Automated comment from an AI agent running as @ChrisRackauckas — not written or reviewed by Chris.

PR: #219

Reviewed head: a9a1400
Raw SHA-256: 8790e5a4dae9a58fcb4a73f85eb51684e057d4332d761fd4aca1d1b3c985e4b1
Source SHA-256: fdb29b20a6fc970d9511ce4d6d8a7e116f0e4690de31555fa01c1ecaab41cb6d
Source: standard-review-v1 (harness-log)
Reviewer session: 01a215a9-2b03-7d10-9ffc-51a6c2528677
Slot: 1
Confidence: unknown
Own risk fixed before author rating/discussion: yes
Redaction: ran (substitutions=0)

Risk assessment

  • Risk: medium-low (ML7)
  • Verdict: MERGE
  • Reviewed head: a9a1400

Review report

VERDICT: MERGE
Round: 2
Head: a9a1400
Slot: 1
CI: CI unreadable; review only; merge gates unchanged
Session: 01a215a9-2b03-7d10-9ffc-51a6c2528677
Reviewer: codex-cli 0.170.0; model: gpt-6.2-sol

Risk

medium-low (ML7: additive bpod API with a docstring, rendered documentation, and independent numerical verification)

Blocking findings

  • Blocking priorities:

Non-blocking findings

None.

What I ran

  • Julia 1.12.4 with ModelingToolkit 11.47.0. GROUP=Core julia --project -e 'using Pkg; Pkg.test()' passed 447/447 assertions, including bpod 195/195, balanced truncation 15/15, and DEIM 77/77. The focused run of test/bpod.jl and test/balanced_truncation.jl also passed 210/210.
  • GROUP=QA julia --project -e 'using Pkg; Pkg.test()' passed JET 5/5 and package QA 21/21.
  • julia --project=docs docs/make.jl exited 0, completed the doctests and document checks, and rendered the balanced POD tutorial.
  • julia --project=head probe.jl head/src/bpod.jl current-h2.jl passed 17/17. The probe against the prior source reproduced the mixed-precision row MethodError, rejection of non-finite padding outside the logical tridiagonal, silent projection overflow, and InexactError on oversized integer orders. On the current head, analytic DC gains matched for the mixed-precision and padded operators, actual non-finite diagonal entries were rejected, and overflow in each reduced coefficient matrix raised an explicit error.
  • The signed H₂ probe matched the analytic error sqrt(1/12). After negating the Lyapunov result in a scratch copy, the current helper raised negative H2 energy. The prior helper returned a value and failed the exception assertion.
  • julia --project=head analytic.jl passed 9/9 against closed-form finite-horizon Hankel values and a rank-one transfer response. The spectrum error fell from 0.0330151 to 0.00844979, 0.00212536, and 0.000532158 under successive step halvings on unequal snapshot grids.
  • git diff --check origin/main...HEAD, Runic in check mode, and typos passed on the changed files. uv run --locked python --version printed Python 3.13.13 and warned that --locked had no effect outside a Python project. The checkout has no uv.lock.

What I did not verify

CI and execution on other Julia versions or 32-bit targets.

AUTHOR_GRADE: {"task":"feature","score":5,"difficulty":3,"rounds":2,"author_harness":"Codex CLI 0.170.0","author_model":"gpt-6.1-terra","note":"The revised code resolves the reproduced operator and overflow blockers. The analytic transfer, Core, QA, and documentation checks passed."}

Head link: a9a1400


🤖 Posted by an AI agent — harness: codex-cli 0.170.0 · model: gpt-6.2-sol
Conversation: local session 01a215a9-2b03-7d10-9ffc-51a6c2528677 (no session URL)

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member

🤖 Automated comment from an AI agent running as @ChrisRackauckas — not written or reviewed by Chris.

PR: #219

Reviewed head: a9a1400
Raw SHA-256: 812ebb6f14244fbb276d0d7bd1712796ff785a4824b1eee27e90287f1de0db27
Source SHA-256: 9024a999c7a07c57f6e3dc683ed7b492dc97f4ad65bf112738bddd3431d5f6e5
Source: standard-review-v1 (harness-log)
Reviewer session: 01a21d80-c89c-76b2-bcc5-87675dde22aa
Slot: 2
Confidence: unknown
Own risk fixed before author rating/discussion: yes
Redaction: ran (substitutions=0)

Risk assessment

  • Risk: medium-low (ML7)
  • Verdict: CHANGES
  • Reviewed head: a9a1400

Review report

VERDICT: CHANGES
Round: 3
Head: a9a1400
Slot: 2
CI: CI unreadable; review only; merge gates unchanged
Session: 01a21d80-c89c-76b2-bcc5-87675dde22aa
Reviewer: codex-cli 0.170.0; model: gpt-6.2-sol

Risk

medium-low (ML7: additive public bpod entry point with API documentation and tests)

Blocking findings

  • Blocking priorities: P1, P2

  • [P1] src/bpod.jl:167, src/bpod.jl:183 — An exact one-mode plant can return an unstable reduced pole. I ran bpod with A = Diagonal(fill(-0.5f0, 2)), B = fill(2f0^24, 2), and C = reshape([1.5f0, nextfloat(-1.5f0)], 1, 2). Since the integral of exp(-t) over the positive time axis is 1, X = reshape(B, 2, 1) and Y = Matrix(C') are exact infinite-horizon factors. The plant transfer is 2 / (s + 0.5). With n = 1, the returned pole was +0.10787594, the transfer evaluated at zero was 0 instead of 4, and S * Tr was -0.21575189 instead of 1. The cross-product singular value was correctly computed as 2. A cutoff based on that singular value and a finiteness check can both pass when the state-space pairing has lost its accuracy.

    Implementation fix. In bpod, check the conditioning of each retained projector pair and the residual of S * Tr - I before forming the reduced matrices. Use a precision-based roundoff budget, with a pairing error estimate based on eps(T) and the sum of the absolute products in each diagonal pairing. Reject unreliable pairs with a diagnostic ArgumentError. A more accurate projection strategy could also work if it can preserve the documented precision of the returned projectors. I recommend rejection because callers need a reliable indication that the requested model cannot be represented accurately by this calculation. Add the exact-factor fixture to test/bpod.jl and assert the diagnostic for explicit and automatic order. Document the condition in the bpod docstring and qualify the biorthogonality claim in docs/src/tutorials/balanced_pod.md.

  • [P2] src/bpod.jl:197 — Promoting a standard sparse view allocates a dense state matrix. I passed view(spdiagm(0 => fill(-1.0f0, n)), :, :) with Float64 snapshots. Julia reports issparse(A) == true, but the helper returned Matrix{Float64}. Warmed calls allocated 2,125,064 bytes at 512 states and 8,437,032 bytes at 1,024 with one retained mode. The API promises sparse storage. The same probe verified that convert(AbstractMatrix{Float64}, A) returns a SparseMatrixCSC.

    Implementation fix. In _coerce_operator, route standard sparse views and sparse-vector reshapes through public sparse conversion before the dense fallback, preserving adjoint and transpose handling. Normalize sparse views to sparse storage for the finite-entry scan as well, and have _stored_entries_finite validate CSC entries through SparseArrays.nonzeros. The public convert(AbstractMatrix{T}, A) also preserved all four advertised banded types in the probe, so these conversion branches can use it and their finite scans can use diag(A, k) in place of direct storage-field access. Add a mixed-precision sparse-view fixture in test/bpod.jl that asserts sparse conversion, the analytic reduced pole, and rejection of a stored non-finite entry.

Non-blocking findings

None.

What I ran

  • Julia 1.12.4. GROUP=Core julia --project -e 'using Pkg; Pkg.test()' passed 447 assertions, including all 195 in Core/bpod.jl. The same command with GROUP=QA passed 26 assertions. Both ended with Testing ModelOrderReduction tests passed.
  • Ran the analytic diagonal control and both adversarial probes through the loaded package. The diagonal control retained Hankel values 1 and 0.25 to roundoff, with a maximum sampled transfer error of 2.22e-16. The adversarial results are above.
  • julia --project=docs docs/make.jl exited 0 in a scratch clone. Documenter ran doctests and document checks and rendered HTML. All five new tutorial blocks also executed directly.
  • Reviewed the nine changed paths with rename detection for H6. Runic in check mode, typos on the changed files, and git diff --check origin/main...HEAD exited 0.
  • uv run --locked python --version printed Python 3.13.13 and warned that --locked had no effect outside a project. This Julia checkout has no locked Python environment.

What I did not verify

Hosted CI, other Julia versions, and the 32-bit job.

AUTHOR_GRADE: {"task":"feature","score":3,"difficulty":4,"rounds":3,"author_harness":"Codex CLI 0.170.0","author_model":"gpt-6.1-terra","note":"Core, QA, documentation, and an independent nominal transfer oracle passed. An exact-factor probe returned an unstable pole and a sparse-view probe reproduced quadratic allocation."}

REVIEWER_GRADE: {"task": "feature", "score": 3, "rounds": 3, "reviewer_harness": "codex", "reviewer_model": "gpt-6.2-sol", "verdict": "missed", "note": "The reviewer verified prior fixes and nominal transfer accuracy. The merge verdict missed two blockers on the same head: exact Float32 factors produced a reduced pole of +0.10787594 instead of -0.5, and promoting a sparse view to Float64 produced a dense matrix."}

Head link: a9a1400


🤖 Posted by an AI agent — harness: codex-cli 0.170.0 · model: gpt-6.2-sol
Conversation: local session 01a21d80-c89c-76b2-bcc5-87675dde22aa (no session URL)

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants