Skip to content

Bwfilter - #22

Draft
dajmcdon wants to merge 11 commits into
mainfrom
bwfilter
Draft

dajmcdon wants to merge 11 commits into
mainfrom
bwfilter

Conversation

@dajmcdon

@dajmcdon dajmcdon commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds bwfilter(), which solves the same problem as trendfilter() with a squared ℓ2 penalty in place of the ℓ1 penalty:

min_θ ½ Σ wᵢ(yᵢ − θᵢ)² + λ‖D⁽ᵏ⁺¹⁾θ‖₂²

The solution is (W + 2λDᵀD)θ = Wy, so each λ needs one banded linear solve; there's no ADMM. It reuses the existing LinearSystem solvers 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 is k = 1 (the Hodrick–Prescott filter for evenly spaced data). The returned object has class c("bwfilter", "trendfilter"), so predict(), plot() and summary() work unchanged.

Fixing zero weights for bwfilter() turned up several bugs in the Kalman filter solver that also affect trendfilter(); see below.

Default λ path

  • Starts at λ = Inf: the weighted polynomial fit, computed directly with project_polynomials() (df = k + 1 exactly).
  • The next value comes from the new bw_lambda_max(n, k, solver), which depends only on n and k. It's the smaller of
    • c_k·n^(2k+1)/((k+2)π/2)^(2(k+1)) with c_k = 0.15 + 0.4/(k+1)², which gives df ≈ k + 2 (calibrated numerically: k + 1.95 to k + 2.02 for evenly spaced x);
    • a cap keeping cond(W + 2λDᵀD) below 1e16 for the Kalman filter or 1e12 for QR/Cholesky, the limits where each solver stays accurate.
  • It continues geometrically down to near interpolation, λ_min = 0.008/(n·4^(k+1)). Defaults are in the function signature.
  • It stops early as in glmnet: after mnlam fits, once the deviance ratio passes devmax or stops improving by more than fdev. These are set in bwfilter_control_list(). No early stopping when lambda is supplied. The fit returns dev_ratio.

Degrees of freedom

compute_dof = TRUE returns the exact df, tr((W + 2λDᵀD)⁻¹W), from one banded generalized eigenproblem (LAPACK dsbgv, O(n²k)) that covers every λ. It's off by default because of that cost. This adds src/Makevars and src/Makevars.win to link LAPACK.

Fixes that also affect trendfilter()

  • Kalman filter, zero weights: zero weights are now treated as missing observations (H = 1/w = ∞: prediction only, no update) in both the diffuse initialization (previously NaN) and the main iteration (previously correct only implicitly through IEEE arithmetic).
  • Kalman filter, zero weight among the first k + 1 observations: the diffuse phase then lasts d > k steps, but the main loop indexed D, the noise variance and the ADMM offset c by i − d instead of i − k, and the diffuse steps never added c. This gave wrong solutions whenever x was unevenly spaced or c ≠ 0, which is always the case inside ADMM.
  • Kalman filter, smoother state: r and r1 were never reset between kf_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.
  • Kalman filter, leading zero weights: the exact diffuse initialization ran through every leading zero-weight observation, and its covariances grew polynomially, losing precision to cancellation (errors of order 1 after ~30 leading zeros with k = 3). The filter now starts at the first positive weight and fills in the leading values exactly from (Dθ)ⱼ = cⱼ: the rows of D that involve them can always be satisfied, so they don't affect the rest.
  • Kalman filter, uneven spacing: 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 (for example, 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). These steps now use an orthogonal cyclic shift, which is equivalent.
  • Positive weights required: trendfilter() and bwfilter() 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. bwfilter objects interpolate in log λ, and between Inf and λ₂ by 1/λ.

Solver accuracy vignette

New vignette solver-accuracy.Rmd (adds knitr and rmarkdown to 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 why bw_lambda_max() uses a solver-dependent cap.

Notes for reviewers

  • λ scaling: the penalty is λ‖Dθ‖², not λ/2, so only the norm differs from trendfilter().
  • A gap after the polynomial fit: at large n and k the solver cap binds, so df jumps after the ∞ fit (for example from 4 to 8.3 at n = 1000, k = 3). Normal-equation solvers can't accurately reach anything closer to a polynomial there.
  • Remaining Kalman filter limitation: if the first k + 1 positive weights are themselves far apart (e.g. at 2, 25 and 49 of 50 with uneven x), the diffuse initialization still spans those gaps and loses some precision (~1e-3 in that example). Leading and trailing zero runs are handled exactly.
  • Not yet done: there's no cv_bwfilter(). The printed summary still describes k as the "degree of the estimated piecewise polynomial curve".

Testing

  • Exact solutions: all solvers match a dense closed-form solution for k = 0–3, with even and uneven spacing, weights and zero weights. The df matches the trace of the dense hat matrix.
  • Kalman filter regressions: the single ADMM solve matches a dense solve with c ≠ 0 and zero weights at the start, middle and end; polynomial signals are reproduced exactly with a large first gap up to ρ = 1e8; polynomial signals are reproduced exactly with up to 40 leading zero weights; ADMM with the Kalman filter matches sparse QR with and without zero weights. Each of these fails on the previous code.
  • Weight checks: the "marginal cases" test now expects an error with all-zero weights and with only k positive weights, and checks that exactly k + 1 positive weights gives the interpolating polynomial, for every solver.
  • Results: devtools::test() passes 520 expectations in about 18 s (down from about 300 s). R CMD check gives 0 errors, 0 warnings and 0 notes.

🤖 Generated with Claude Code

dajmcdon and others added 4 commits November 26, 2026 09:28
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
dajmcdon requested review from ryantibs and removed request for ryantibs November 26, 2026 18:41
@dajmcdon
dajmcdon marked this pull request as draft November 26, 2026 22:29
dajmcdon and others added 7 commits November 29, 2026 11:41
- 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>
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.

1 participant