Repository navigation
Conversation
Solves (W + 2 lambda D'D) theta = W y with D = D^(k+1), one banded linear solve per lambda via the existing LinearSystem solvers (Kalman filter, sparse QR, sparse Cholesky; tridiagonal for k = 0). Exact effective degrees of freedom and default lambda bounds come from a banded generalized eigenproblem (LAPACK dsbgv). Adds bwfilter_control_list(), tests, docs, and links LAPACK via src/Makevars. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Degrees of freedom (O(n^2) banded eigenproblem) are now computed only
when compute_dof = TRUE.
- Default lambda_max follows glmnet's ridge rule (l1 lambda_max / 1e-3);
default lambda_min_ratio is 1e-4^(k + 1) so the path covers a similar
df range for every k.
- Kalman filter: treat zero weights (infinite observation variance) as
missing observations in the diffuse initialization, which previously
produced NaNs. Fixes trendfilter() too; removes bwfilter's solver
fallback.
- get_lambda_max(): solve D^T u = W (y - P_W y) instead of scaling by
W^{-1/2}, so zero weights no longer give NaN (and an all-zero lambda
sequence). Unchanged for positive weights.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…pping - Default lambda path starts at Inf: the weighted polynomial fit, computed directly with project_polynomials() (df = k + 1 exactly). - Next value from new bw_lambda_max(n, k, solver): the smaller of a near-polynomial target 8 n^(2k+1) / ((k+2) pi / 2)^(2(k+1)) and a cap keeping cond(W + 2 lambda D'D) below 1e16 (Kalman filter) or 1e12 (sparse QR / Cholesky). Defaults for lambda_max and lambda_min_ratio now live in the function signature. - glmnet-style early stopping of the default path (devmax, fdev, mnlam in bwfilter_control_list()); returns dev_ratio. - predict(): handle a leading Inf (1 / lambda interpolation toward the polynomial fit) and interpolate bwfilter paths in log(lambda). - NEWS entries, including the earlier zero-weight fixes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Normalizing lambda to [0, 1] before approx() lost all information about values below ~eps * lambda[1], so very wide user-supplied sequences collapsed to duplicates. Interpolation weights are invariant to affine maps, so working with the raw values gives identical results at typical ranges and stays exact at any range. trendfilter() keeps linear interpolation (its path is piecewise linear in lambda); bwfilter() keeps log(lambda). Adds tests comparing against the previous implementation, a 24-decade grid, and trendfilter() predictions. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
dajmcdon
marked this pull request as draft
November 26, 2026 22:29
- Default k = 1L (the Hodrick-Prescott filter for evenly spaced data). - Rename to the Bohlmann-Whittaker filter; note that a single SVD could give the solution at many lambda, and that the Kalman filter is used by default for speed and robustness at large n. - Clarify that nlambda counts the leading lambda = Inf fit. - Keep one nlambda check (>= 1) and warn when nlambda > 1000. - Tests: expect the k = 1 default; make the solver-cap test meaningful (n = 3000, where the cap binds for Cholesky but not the Kalman filter); nlambda = 0 errors. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The default path already starts at lambda = Inf (the polynomial fit, k + 1 df), so the next value can be much more lenient. Use c_k n^(2k+1) / ((k+2) pi / 2)^(2(k+1)) with c_k = 0.15 + 0.4 / (k+1)^2, calibrated against the exact spectrum: df is k + 1.95 to k + 2.02 for evenly spaced x and equal weights (n = 30 to 1000, k = 0 to 4). The conditioning cap is unchanged and now binds less often. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Cap ADMM at 10 iterations (and use nlambda = 2 for the lambda sequence check). ADMM converges slowly with zero weights, so these two tests took ~270s; the full suite now runs in ~32s. Both still fail with the old Kalman filter code. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…state With a zero weight among the first k + 1 observations, the diffuse phase lasts d > k steps, but the main loop indexed D, RQR, and the ADMM offset c by i - d instead of i - k, and diffuse steps never added c. Wrong whenever x is unevenly spaced or c != 0 (always, inside ADMM). Each step now uses row max(i - k, 0); the first k transitions are uninformative anyway. Also reset r and r1 at the start of kf_iter(): ADMM reuses the system, so each solve started the backward recursion from the previous solve's state. trendfilter() with the Kalman filter now matches sparse QR and converges with zero weights. Make the missing-observation handling explicit in f1step(). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The first k transitions start from the diffuse initial state and carry no information, but they applied D's first row k times. When that row's last coefficient is small (e.g., a large first gap in x), the diffuse variance fell below tolerance, the diffuse phase never finished, and the solution was wrong (off by ~1e-2 even at condition number 7e5). Any invertible transition is equivalent there, so use a cyclic shift with no noise. Against a 200-bit reference and polynomial signals (exact solution y), the Kalman filter is now the most accurate solver: ~1e-11 at condition number 1e18, where sparse QR and Cholesky lose all accuracy. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Fits bwfilter() to polynomial signals of degree k, which lie in the null space of the penalty, so the exact solution is y for every lambda. The table shows sparse QR and Cholesky errors growing with the condition number while the Kalman filter stays accurate to ~1e-10. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
trendfilter() and bwfilter() now abort unless at least k + 1 weights are positive, the minimum for a unique solution. With all-zero weights, trendfilter() used to normalize weights to 0/0 and silently return NaNs after 10,000 ADMM iterations; bwfilter() required k + 2. The marginal-cases test now expects an error and checks the k + 1 interpolating fit. The Kalman filter now starts at the first positive weight and back-fills the leading values exactly from (D theta)_j = c_j: the rows of D involving only-leading values can always be satisfied, so they do not affect the rest. Running the exact diffuse initialization through a long run of leading zeros lost precision to cancellation (errors of order 1 after ~30 zeros with k = 3); it now matches a 200-bit reference to 1e-10 or better. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds
bwfilter(), which solves the same problem astrendfilter()with a squared ℓ2 penalty in place of the ℓ1 penalty:The solution is (W + 2λDᵀD)θ = Wy, so each λ needs one banded linear solve; there's no ADMM. It reuses the existing
LinearSystemsolvers with the order set to k+1: Kalman filter (the default), sparse QR and sparse Cholesky, plus a tridiagonal solve for k = 0. The default isk = 1(the Hodrick–Prescott filter for evenly spaced data). The returned object has classc("bwfilter", "trendfilter"), sopredict(),plot()andsummary()work unchanged.Fixing zero weights for
bwfilter()turned up several bugs in the Kalman filter solver that also affecttrendfilter(); see below.Default λ path
λ = Inf: the weighted polynomial fit, computed directly withproject_polynomials()(df = k + 1 exactly).bw_lambda_max(n, k, solver), which depends only on n and k. It's the smaller ofmnlamfits, once the deviance ratio passesdevmaxor stops improving by more thanfdev. These are set inbwfilter_control_list(). No early stopping whenlambdais supplied. The fit returnsdev_ratio.Degrees of freedom
compute_dof = TRUEreturns the exact df, tr((W + 2λDᵀD)⁻¹W), from one banded generalized eigenproblem (LAPACKdsbgv, O(n²k)) that covers every λ. It's off by default because of that cost. This addssrc/Makevarsandsrc/Makevars.winto link LAPACK.Fixes that also affect
trendfilter()randr1were never reset betweenkf_iter()calls. ADMM reuses the system, so every solve after the first started from the previous solve's state. With k = 2 and evenly spaced x, the Kalman filter's ADMM result differed from sparse QR's by about 0.2. It now matches to ~1e-12, and zero-weight fits that used to hit the 10,000-iteration cap converge.trendfilter()andbwfilter()now abort unless at least k + 1 weights are positive, the minimum for a unique solution. With all-zero weights,trendfilter()normalized the weights to 0/0 and silently returned NaNs after 10,000 ADMM iterations.bwfilter()previously required k + 2.get_lambda_max()with zero weights: it returned NaN, which silently produced an all-zero λ sequence. It now solves Dᵀu = W(y − P_W y) with no inverse weights. Results with positive weights are unchanged.interpolate_lambda(): it now interpolates on the raw λ values instead of normalizing first. The old version lost precision once λ_k/λ₁ dropped below about 1e-16.trendfilter()keeps linear interpolation, since its path is piecewise linear in λ, and results at typical ranges are identical.bwfilterobjects interpolate in log λ, and betweenInfand λ₂ by 1/λ.Solver accuracy vignette
New vignette
solver-accuracy.Rmd(addsknitrandrmarkdownto Suggests). It fits polynomial signals of degree k, which lie in the null space of the penalty, so the exact solution is y for every λ. Sparse QR and Cholesky errors grow with the condition number (≈ 0.5 and 40 at cond ≈ 3e18), while the Kalman filter stays accurate to about 1e-10. This is whybw_lambda_max()uses a solver-dependent cap.Notes for reviewers
trendfilter().cv_bwfilter(). The printed summary still describes k as the "degree of the estimated piecewise polynomial curve".Testing
devtools::test()passes 520 expectations in about 18 s (down from about 300 s).R CMD checkgives 0 errors, 0 warnings and 0 notes.🤖 Generated with Claude Code