Wavefront Control & PredictionPractical Guide & Tuning ManualAR(P) · Block-EOF · Self-Learning

CACAO Predictive Control Guide: AR, Block-EOF & Cascaded Self-Learning

A human-readable guide to the physics, algorithms, real-time architecture, and practical parameter tuning of CACAO's three predictive control layers—from fast per-mode diagonal AR(P), to spatial-temporal cross-mode Block-EOF (with ZOH ridge, difference-space DC pinning, wind-layer physics priors, regime memory, Filtered-X, and multi-rate velocity), to Cascaded Online Self-Learning (Global RLS + Clustered libgric with causal James-Stein safety gates).

Control Ladder
3 Predictive Tiers
AR(P) → Block-EOF → Self-Learning
Core Units
6 Real-Time Daemons
mfilt, mk/apply AR & EOF, selflearn
RT Inference
24–114 µs / frame
Fits cleanly inside 1–2 kHz loops
Safety Guarantee
1.000x Null Noise
Causal OOS Stein gates & modalwhite

1. Why Predictive Control? Physical Motivation & the PSOL Prerequisite Loop OperationCalibration

Every real adaptive optics loop suffers an unavoidable delay τ (typically 2.0–2.8 WFS frames, combining WFS integration, camera readout, MVM compute, and DM settling). A classical leaky integrator (INT) only reacts after an error has already passed through the focal plane. Pushing integrator gain higher cannot eliminate servo lag: once the loop phase lag approaches 180°, the waterbed effect amplifies high-frequency WFS noise and drives ringing.

In practice, servo lag causes three concrete scientific penalties:

The Pseudo Open-Loop (PSOL) Architecture

Instead of predicting closed-loop WFS residuals directly (which change whenever you adjust loop gain), CACAO's predictive controllers work in Pseudo Open-Loop (PSOL) coordinates reconstructed every frame inside PSOL (cacao-fpsexec-mfilt):

Real-Time PSOL Reconstruction & Blending inside modalfilter.c1. Open-loop estimate: modevalOL[m](t) = (comp.WFSfact * mWFSfact[m]) * modevalWFS[m](t) - DM_eff[m](t) 2. Predictive target: modevalPF[m](t) ≈ modevalOL[m](t + PFlatency) [computed by applyARPF / applyEOFPF / selflearn] 3. Effective mix: mixf[m] = clamp(PF.mixcoeff * mPFmixfact[m] * outPFstat[m], 0, 1) 4. Blended DM command: dmC[m](t) = mixf[m] * (WFSfact*mWFSfact[m]*zpo[m] - modevalPF[m](t)) + (1 - mixf[m]) * dmC_integrator[m](t)

Because modevalOL estimates the true incoming atmospheric + vibration wavefront (independent of controller gain), an online solver can learn temporal and spatial-temporal dynamics cleanly while the loop stays closed, and modalfilter smoothly blends the predictive command with the baseline leaky integrator via modalfilter.PF.mixcoeff and per-mode rolloff mPFmixfact = mgainfactCACAO_PF_MGAIN_EXP. Sign convention note: modevalOL and modevalPF carry the positive turbulence sign in DM units, so modalfilter subtracts modevalPF from the scaled zero-point offset to cancel the wavefront.

flowchart LR
    WFS["PyWFS / SHWFS
(dark-sub + norm)"] --> M1["modalfilter (PSOL Observer)
OL = WFSfact*mWFSfact*WFS - DM_eff"] M1 -->|"aolN_modevalOL_buff
(256-fr double buffer)"| MK["Async Solver (0.25-1 s)
mkARPF or mkEOFPF
(+ windlayers / H_eff)"] MK -->|"arPFmat or eofPFmat
(+ optional eofPFmat_vel)"| APP["Real-Time Predictor
applyARPF (24 us) or
applyEOFPF (80-108 us)"] M1 -->|"aolN_modevalOL (live)"| APP APP -->|"Optional cascade:
aolN_modevalPF_eof"| SL["Cascaded Self-Learning
cacaopc-selflearn
Global RLS + libgric + Stein gates"] SL -->|"aolN_modevalPF
+ outPFstat"| BLEND["modalfilter Blender
cmd = mix*(zpo/g - PF) + (1-mix)*Int"] APP -.->|"Direct (no selflearn):
aolN_modevalPF"| BLEND BLEND -->|"aolN_modevalDM
(or traj -> mvalpacer)"| DM["DM (+ Pre-Shaper)"] M1 -.->|"WFS & DM buffers"| WH["modalwhite
Q_vw, Q_xmode, Alerts"]

Rule #1 — Garbage PSOL = Garbage Prediction: A predictor can only be as accurate as modevalOL. Before blaming AR, EOF, or Self-Learning, verify four observer prerequisites:

  1. Accurate latency (MLAT & testOL): Hardware + software lag (modalfilter.comp.latencyhardwfr, modalfilter.comp.latencysoftwfr) must be aligned within < 0.1 frame, otherwise the DM subtraction leaks DM motion into modevalOL and creates fake self-oscillation.
  2. Dynamic DM plant model (3DRM/FACT): On fast MEMS DMs, 2-tap fractional lag or diagonal FIR (PSOL/DIAG) suffices. On resonant continuous-facesheet plate DMs (e.g., 64×64 ALPAO), enable 3D MIMO FIR (modalfilter.comp.dynpsol.enable, modalfilter.comp.dynpsol.kernel) — this cuts live PSOL error by 12.2× (34.1% → 2.8%).
  3. Optical-gain scaling (OG/POKE / 2WFS/LIVE): On Pyramid WFSs, on-sky optical gain g_opt < 1 shrinks WFS amplitude. Supply live aolN_mWFSfact = 1/g_opt (keeping scalar modalfilter.comp.WFSfact = 1.0) so WFS residuals match DM units.
  4. WFS dark subtraction (--wfs-dark-adu / CACAO_WFS_DARKSUB): Mandatory on faint stars so camera bias pedestals do not distort WFS flux normalization and optical gain.

2. Choosing Your Controller Tier: AR vs. Block-EOF vs. Cascaded Self-Learning Loop Operation

CACAO's predictive controllers form a deliberate capability ladder. Each tier adds specific physical modeling power and comes with its own warmup horizon, sample requirement, and real-time CPU footprint:

Controller TierPhysics CapturedWarmup & Sample RuleRT Apply Cost (1–2 kHz)When to Choose It
Tier 0 · Leaky Integrator
INT + MOPT
Pure feedback damping; zero temporal lookahead. Autotuned MOPT optimizes per-mode (gain, leak) from PSDs.0 frames (instant)~23 µs (1,255 m)Loop bring-up, ultra-low calibration budgets, or fallback path blended alongside predictive control (1 - mix).
Tier 1 · Diagonal AR(P)
PF/AR
Per-mode temporal correlation & single-mode vibrations (B = 1, zero cross-mode coupling).N_min = 256 (0.25 s @ 1 kHz)
Rule: N_train / P ≥ 128
24–34 µs for AR(16)
(~33% total CPU)
Sub-second cold-start locking, rapidly changing conditions, minimal CPU budgets, and automatic bootstrap inside Block-EOF.
Tier 2 · Cross-Mode Block-EOF
EOF
Spatial-temporal Taylor frozen-flow wind advection across coupled mode blocks (B = 64 or 128), plus ZOH ridge, difference-space DC pinning, wind physics prior, regime memory, FX-DM, & multi-rate velocity.Locks in 0.25 s via AR(16) bootstrap; full EOF at N/D ≥ 8–12 (6 s for B=64, 12 s for B=128; instant with EOF/WIND)76–108 µs
(0.7–1.0 CPU core)
Recommended default anchor for science ExAO, coronagraphy, wind-lag suppression (~3× lower noise gain than AR), and faint-star slow-WFS operation.
Tier 3 · Block-EOF + Cascaded Self-Learning
SELFLEARN
Everything in Block-EOF plus fast per-frame tracking of global gain drift (SL/GLOBAL) and state-dependent nonlinear PyWFS optical gain / regime shifts (SL/CLUST via libgric).keywarmup = 200 fr + causal Stein gates auto-open only when OOS error drops89 µs @ 128 m
114 µs @ 256 m
(full decoupled stack)
Unmodulated 0 λ/D PyWFS, strong nonlinear optical gain (−36.4% residual vs. fixed EOF), or combined OG + vibration stress.

Two Non-Negotiable Architectural Rules: (1) Always cascade Self-Learning on top of Fixed-Basis Block-EOF (u_total = u_EOF + δu_L0 + δu_L1)—never run Self-Learning standalone, which degrades pure turbulence (33.5 vs. 19.2 nm) and leaks 18.35 nm (1.10×) on pure white noise. (2) Keep the outer modal basis fixed for PSOL, Block-EOF, and Self-Learning; any adaptive basis rotation (CMODES) must remain strictly decoupled inside modalfilter.

3. Diagonal Autoregressive Control — AR(P) Loop Operation

Implemented in cacao-fpsexec-cacaopc-mkARPF (async solver) and cacao-fpsexec-cacaopc-applyARPF (real-time SIMD dot product), PF/AR fits an independent scalar linear predictor of order P for every mode m using only that mode's own recent PSOL history:

Per-Mode Wiener-Ridge AR(P) Formulation (mkARPF.c / applyARPF.c)Prediction: y_hat_m(t + d) = sum_{k=0}^{P-1} w_{m,k} * x_m(t - k) Normal Eq.: (G_m + lam * I) w_m = rhs_m + lam * w_prior, lam = reglambda * tr(G_m) / P Safety guards: ||w_m||_2^2 <= maxnorm2 (auto lam *= 3 backoff), |sum_k w_{m,k}| <= maxdcgain < 1 Live publish: w_pub = (1 - loopgain) * w_pub + loopgain * w_m (first update uses 1.0)

Why AR(16) Is the Diagonal Sweet Spot (The Cauchy–Schwarz Intuition)

You might expect a 4-tap predictor to predict a smooth low-order mode 2.4 frames ahead. In reality, benchmarking AR(4) through AR(64) reveals a crisp physical constraint—the Cauchy–Schwarz tradeoff between phase lead and L2 noise gain:

Too Short: AR(4) & AR(8)

To estimate a derivative over only 4 frames and extrapolate +2.4 frames forward requires huge positive/negative tap weights that violate ||w||_2^2 ≤ 1.35. Regularization collapses AR(4) to a smoothing filter with −0.11 fr effective lead (worse than zero-order hold!) and the highest noise gain (0.70). AR(8) reaches +1.04 fr lead but still slips a V-spider petal during strong gusts.

Pareto Optimum: AR(16)

Spreading the negative differentiating lobe smoothly over taps k = 6..15 achieves +1.52 fr effective phase lead while simultaneously cutting noise-gain squared by 17% (0.64 → 0.53). It locks within 0.25 s (N_min = 256), survives 1.85 μm gusts with zero petal slips, and runs in 24–34 μs/frame (33% total CPU across 2 stages).

Too Long: AR(32) & AR(64)

Beyond ~16–20 ms, >97% of single-mode atmospheric autocorrelation is already captured. At N_min = 256, AR(64) has only N/P = 4 samples per parameter and catastrophically overfits (−8% OOS variance reduction), triggering cold-start petal jumps. Even warm-started at N = 4096, it gains <0.2 pp Vis Strehl over AR(16) at 14× the CPU cost (O(N_train * P^2) Gram build).

Key mkARPF & applyARPF Parameters

FPS ParameterDefaultAccessWhat It DoesPractical Tuning Guidance
.PForder8INITNumber of temporal lookback taps P (1..64) per mode.Start with 16 (Pareto optimum). 4 lags ZOH; 8 misses strong gusts; 32–64 adds <0.2 pp Vis SR at 4–14× CPU and overfits unless NBtrain ≥ 4096.
.PFlatency2.3LIVEFractional prediction horizon d [WFS frames]. Target is linearly interpolated between t+floor(d) and t+floor(d)+1.Match measured total loop delay from MLAT / testOL (typically 2.2–2.5 fr). Too small leaves positive lag; too large over-extrapolates and raises noise gain.
.NBtrain2048INITRolling PSOL ring buffer length [frames] used to build each P×P Gram.Keep NBtrain / P ≥ 128 (e.g., 2048–4096 for AR(16)). Shorter windows track faster wind changes but increase weight variance.
.minsamples512LIVEMinimum non-zero PSOL frames required before publishing the first AR filter.Keep minsamples / P ≥ 16 (256 is safe for AR(16) at 0.25 s startup; for AR(32)+ you need ≥ 1024 or progressive bootstrap).
.reglambda0.005LIVERelative Tikhonov ridge damping λ = reglambda * tr(G)/P.Stage-asymmetric tuning works best: 1e-4–1e-3 on high-SNR Stage 1; 5e-3–1e-2 on lower-SNR Stage 2 to suppress high-order mode ringing.
.maxnorm21.35LIVEHard ceiling on per-mode noise amplification ||w||_2^2; solver triples λ (up to 12×) until satisfied.1.35 is safe for broadband turbulence; raise to 1.8–2.0 only on high-SNR loops with narrowband vibrations. Lower toward 1.0 on faint stars.
.maxdcgain0.985LIVEStrict upper bound on |sum(w)| (< 1.0) preventing null-mode DC drift.Keep 0.985–0.995. Never set ≥ 1.0, or weakly sensed modes will slowly integrate into the DM rail.
.loopgain0.30LIVEEMA smoothing factor blending each new solve into live aolN_arPFmat (first publish always uses 1.0).0.25–0.40 suppresses update-to-update jitter without sluggishness.
.priorgain0.00LIVEDC gain of optional exponentially decaying low-pass shrinkage prior (decay via mkARPF.priordecay).Leave at 0.0 for standard operation; raise to 0.5–0.8 only when testing very short windows on faint stars to pull weights toward smoothing.
.rampsteps64LIVENumber of frames over which outPFstat linearly ramps from 0 to 1 once the first filter arrives.Keep 32–64 frames (32–64 ms @ 1 kHz) for a completely bumpless hand-off from integrator to predictor.

Watch live mkARPF outputs: mkARPF.out.n_samples, mkARPF.out.rms_zoh, mkARPF.out.rms_pred, and mkARPF.out.var_red_pct. Healthy broadband turbulence yields var_red_pct of +20% to +45%.

4. Cross-Mode Transition Matrix — Block-EOF Loop Operation

Implemented in cacao-fpsexec-cacaopc-mkEOFPF (OpenBLAS dsyrk/dgemm + LAPACKE Cholesky + eoflin_phys.c) and cacao-fpsexec-cacaopc-applyEOFPF (OpenMP + AVX SIMD), EOF implements Guyon & Males (2017) Empirical Orthogonal Functions (a vector autoregressive VAR(P) transition matrix) partitioned into spatial-frequency blocks of B coupled modes.

Physical Motivation: Why Cross-Mode Coupling Beats Any Diagonal AR Order

Under Taylor frozen-flow turbulence, wind advects wavefront phase across the telescope pupil. For any sine/cosine Fourier or KL mode pair (c, s) of spatial wave vector k moving at wind velocity v, advancing time by d frames is an exact 2D rotation:

Frozen-Flow Quadrature Coupling & Block-EOF Normal EquationsFrozen-flow physics: [c(t+d); s(t+d)] = R(k · v · d) [c(t); s(t)] (skew-symmetric cross-mode energy flow) Block regressor: x_blk(t) = [a_{s0..s0+B-1}(t), ..., a_{s0..s0+B-1}(t-P+1)] in R^{D}, D = P * B Regularized solve: (G_emp + w_phys*G_phys + lam*I) W = R_emp + w_phys*R_phys + lam * W_target where W_target = [I_B; 0; ...] if zoh_ridge=ON, else 0

A diagonal AR(P) filter cannot see the quadrature partner s(t) and must instead approximate the time derivative by taking noisy finite differences of c(t) alone. Cross-mode Block-EOF reads the approaching wavefront directly off neighboring spatial modes—delivering +81.6% vs. +45.6% Stage-1 Block-0 variance reduction at ~3× lower L2 noise gain (||F_m||_2^2 ~ 0.7–0.9 vs. > 2.1 for unconstrained AR).

Automatic Progressive Cold-Start Bootstrap (state 0 → 1 → 2)

Because each block fits D = P × B = 512..1024 weights per mode, activating unpriored Block-EOF too early (N < D) causes severe overfitting. mkEOFPF prevents this automatically via a 3-state lifecycle reported in mkEOFPF.out.eof_active:

State 0 · Accumulating (0–0.25 s)

n_samples < diagminsamples (256). Loop runs cleanly on the baseline modal leaky integrator while modalfilter fills the PSOL buffer.

State 1 · Diagonal AR(16) Bootstrap

At 256 frames (0.25 s @ 1 kHz), mkEOFPF fits diagonal AR(diagorder=16) directly into the Block-EOF matrix layout (extra taps P..P_diag-1 sit in trailing diag_tail columns), locking petals immediately while clean PSOL samples accumulate.

State 2 · Full Cross-Mode Block-EOF

Once eff_samples ≥ minsamples (or immediately if EOF/WIND provides a live physics prior), blocks promote smoothly via EMA (mkEOFPF.loopgain) into full cross-mode prediction. High-order unpriored blocks stay on diagonal bootstrap until enough data exist.

Core mkEOFPF & applyEOFPF Parameters

FPS ParameterDefaultAccessWhat It DoesPractical Tuning Guidance
.blocksize128INITNumber of contiguous spatial modes B coupled inside each block (D = P * B predictors per mode).128 for maximum steady-state contrast (needs minsamples ≥ 12,000, ~1.0 core); 64 converges 2× faster (6,000 fr, 0.7 core) with nearly identical Stage-1 WFE. Use 16–32 when pairing with longer PForder = 32.
.PForder8INITCross-mode temporal lookback depth P (1..64).8 is optimal for B = 64–128: spatial neighbors already supply phase-lead information without needing deep temporal lags. Keep D = P * B ≤ 1024 for fast Cholesky solves.
.diagorder16INITPer-mode diagonal AR order used during cold-start bootstrap (state = 1) before N ≥ minsamples.Keep at 16 (paired with mkEOFPF.diagminsamples = 256) so Subaru V-spider petals lock within 0.25 s while the cross-mode training buffer fills.
.NBtrain16384INITSliding PSOL training window [frames] (up to 65,536).Maintain NBtrain / (P * B) ≥ 12–16: e.g., 16384 @ 1 kHz Stage 1 and 32768 @ 2 kHz Stage 2 for B=128, P=8 (or use gram_halflife > 0 to extend memory without larger RAM).
.minsamples12000LIVEMinimum frames before promoting from diagonal bootstrap (state=1) to full cross-mode Block-EOF (state=2).Critical overfitting guard: enforce minsamples / (P * B) ≥ 8–12 (6,000 for B=64/P=8; 12,000 for B=128/P=8). With EOF/WIND active, the physics prior supplies n_prior virtual samples immediately.
.reglambda1.0e-4LIVERelative Tikhonov ridge λ = reglambda * tr(G)/D for cross-mode blocks.Use stage-asymmetric values: 1e-4 on high-SNR Stage 1 (strong atmospheric signal); 5e-3–1e-2 on lower-SNR Stage 2 or faint stars. Raise if out.overfit_ratio > 1.25.
.zoh_ridgeONLIVEShrinks ridge penalty toward the identity zero-order-hold map [I; 0; ...] instead of zero.ON for Stage 1 (prevents DC-gain collapse on strong low-order turbulence); OFF for Stage 2 (Stage 2 sees zero-mean high-pass residuals where shrinking toward 0 avoids amplifying noise).
.maxnorm22.0LIVEp95 row L2 norm-squared cap ||F_m||_2^2 triggering automatic λ backoff.2.0 gives healthy headroom for cross-mode advection without ringing; tighten to 1.2–1.5 on photon-starved loops.
.updateperiod4LIVENumber of incoming double-buffer flips between full Block-EOF re-solves.With tbuffsize = 256: 4 (~1.0 s @ 1 kHz) on Stage 1 and 8 (~1.0 s @ 2 kHz) on Stage 2 keeps background solver CPU < 1 core.
.nthreads4LIVEOpenMP thread count parallelizing real-time inference across spatial blocks.4 threads achieves 88–108 μs across 1,255–1,965 modes with zero RT timeouts; avoid oversubscribing physical cores when running two AO stages concurrently.

Composable Block-EOF Extensions (When & How to Enable Each)

All extensions execute inside mkEOFPF with zero changes to applyEOFPF's hot path (except .mr_enable, which adds the optional velocity stream):

Extension ParameterDefaultAccessMechanismWhen to Use & Tuning Rules
.diff_nmode0INITNumber of leading modes (e.g., 16–32) solved in temporal-difference coordinates dx(t) = x(t) - x(t-1) with exact pinned DC gain (mkEOFPF.diff_maxdcgain = 0.9995, mkEOFPF.diff_order, mkEOFPF.diff_reg).Set to 16–32 when heavy thermal petaling or slow tip/tilt drift causes DC sag in standard position-space EOF; weights pack transparently into eofPFmat with zero RT apply overhead.
.gram_halflife0.0LIVEExtended-memory chunk-Gram exponential half-life [frames] (0 = sliding NBtrain window).Set to 15,000–30,000 frames in steady seeing to build deep statistical leverage beyond NBtrain; keep shorter (4,000–8,000) when wind drifts rapidly.
.regime_kmax0INITMulti-anchor regime-weighted Gram library size K (0=off, 2..16=on), blended via mkEOFPF.regime_kappa, mkEOFPF.regime_bw, and mkEOFPF.regime_rlim.Enable (4–8 anchors) during intermittent gust/lull cycles or recurring wind headings so returning to a prior regime restores its Gram instantly without re-learning from scratch.
.n_prior1024.0LIVEEquivalent sample weight of the mlt-windlayers Fourier frozen-flow physics Gram (requires mkEOFPF.wl_layers and mkEOFPF.dmmodes).Set 512–2048 on Stage 1 for instant cold-start cross-mode prediction (+70% VR at t=0). Pair with mkEOFPF.wl_switch_decay = 0.20–0.25 to discount stale empirical Grams 6.2× faster on sudden wind switches. Do not mix with .dm_kernel (EOF/FX).
.dm_kernelINITPass-2 dynamic DM plant kernel FITS (H_diag / H_mimo) for Filtered-X EOF coordinates (EOF/FX).Use only on unshaped ringing DMs (cuts ringing Q_vw 26.4×). When dmpreshaper + PSOL/MIMO already linearize the plate, leave empty and use EOF/WIND instead.
.mr_enableOFFLIVESolves an additional zero-DC centered velocity matrix outPFvel via Catmull-Rom interpolation with extra ridge mkEOFPF.mr_vel_reg_mult (default 3.5) and cap mkEOFPF.mr_vel_maxnorm2.Turn ON only for faint-star slow-WFS loops (250–500 Hz) paired with MRDM (mvalpacer) so the DM executes smooth high-rate ramps instead of 250 Hz staircase jumps.

5. Cascaded Online Self-Learning (Global RLS + Clustered libgric) Loop Operation

Even an ideal linear Block-EOF predictor assumes the plant is linear and stationary over its 10–30 s training window. Real extreme-AO loops break both assumptions: an unmodulated 0 λ/D Pyramid WFS exhibits an odd S-curve saturation and instantaneous optical-gain drops whenever tip/tilt excursions move the PSF off the pyramid apex, while seeing bursts and narrowband vibrations evolve on sub-second timescales.

Implemented in cacao-fpsexec-cacaopc-selflearn (SELFLEARN), Cascaded Online Self-Learning solves this by learning a strictly bounded, zero-DC residual refinement on top of Fixed-Basis Block-EOF every single frame:

2-Level Hierarchical Cascade & Causal Stein Gate (selflearn_core.c)Cascade sum: u_total(t) = u_EOF(t) + apply_gain * clamp(alpha_L0 * sh0 * d_L0(t) + alpha_L1 * d_L1(t, z_t), ±max_tweak) Zero-DC features: phi_{t,m} = [dOL_m(t..t-3), w_m(t), (opt: odd PyWFS NL terms), dOL_{0..q-1}(t), (opt: w_{0..q-1}(t))] Causal target: y_t(s) = OL(s + d) - u_EOF(s) [evaluated strictly causally at frame t = s + floor(d) + 1] Level 0 (Global): (G0 + lam0*I) w0 = b0 [100% of frames, exponential forgetting gamma0 = 0.998] Level 1 (GRIC): (G1_k + lam1*I) w1_k = b1_k [trained on unbiased residual y_t - y_L0_fit; soft LWPR blend across K clusters] Stein gate: alpha_L = clamp( EMA(y · y_hat) / EMA(y_hat · y_hat), 0, 1 ) [closes to 0.00 on pure white noise]

Four Built-In Stability Invariants (Why It Cannot Blow Up Your Loop)

1. Zero-DC Increment Basis

Every PSOL regressor is a first difference dOL(t) = OL(t) - OL(t-1), which vanishes identically at DC. There is no unconstrained intercept, so Self-Learning can never wind up a mode into the DM rail.

2. Physical Stability Ball Projection

After every exact SPD Cholesky update, weights are projected back onto a physical stability ball: AR increment ||w_AR||_2^2 ≤ max_ar_norm2 and WFS optical-gain weight w_phys ∈ [-0.35, +max_wfs_gain] (with nonlinear odd terms jointly L1-bounded).

3. Independent Causal OOS Stein Gates

Before updating weights with frame s's newly revealed target, the engine scores the strictly out-of-sample prediction made d frames earlier. If a layer has no genuine predictive skill (e.g., pure white noise), its Stein gate alpha_l0 / alpha_l1 automatically shrinks to 0.00 (verified: 1.43 nm / 1.000× leakage on 40 nm pure white-noise null test).

4. Distance Fail-Safe & Outlier Skip

If the current state key z_t lands farther than selflearn.gate_mult × rlim from every known libgric cluster anchor, Level-1 smoothly gates off and falls back cleanly to Level 0 + Block-EOF. Glitches exceeding outlier_sig skip RLS updates entirely.

Choosing .key_mode for GRIC State-Space Clustering

.key_modeEnum / DimState Vector FeaturesBest Physical Use Case
0 (default)TT2_E2 (4D)[w_0, w_1, log E_lo, log E_hi]Default for PyWFS: directly tracks tip/tilt excursion off pyramid apex plus low/high spatial-frequency residual energy.
1E1_LOGE (1D)[log E_tot]Pure seeing / Strehl-dependent scalar optical gain tracking with minimal cluster fragmentation.
2WFS_LO4 (4D)[w_0, w_1, w_2, w_3]Tip/tilt + focus/astigmatism nonlinear cross-coupling on unmodulated PyWFS or strong low-order static aberrations.
3TT2_DM2_E2 (6D)[w_0, w_1, dm_0, dm_1, log E_lo, log E_hi]Adds DM tip/tilt position when hysteresis or edge-actuator saturation depends on absolute DM stroke.
4REGIME_E2_VEL (3D)[log E_lo, log E_hi, log E_dOL]Separates slow/calm vs. fast-wind/gust dynamical regimes using rolling 64-frame PSOL velocity energy.
5EXTERNAL (≤16D)Custom 1D SHM stream via selflearn.inkeyFeed external telemetry (e.g., wind vector, focal-plane Strehl, or telescope elevation) directly into libgric.

Key cacaopc-selflearn Parameters & Live A/B Controls

FPS ParameterDefaultAccessWhat It DoesPractical Tuning Guidance
.inbasePFINITUpstream Block-EOF prediction stream (aolN_modevalPF_eof) that Self-Learning refines additively.Always wire to applyEOFPF's output! Never leave blank for science runs (standalone RLS lacks cross-mode frozen-flow advection and fails the white-noise null test).
.NBmodeMax64INITLeading modal span M refined by Self-Learning (higher modes pass Block-EOF through untouched).64–128 covers the low/mid spatial frequencies where PyWFS optical-gain nonlinearity and vibrations concentrate (89 μs @ 128 m; 114 μs @ 256 m).
.nl_mode0INITFeature basis: 0 = linear zero-DC increments + WFS; 1 = +3 odd PyWFS nonlinear terms (S-curve saturation, log-energy OG, TT off-apex OG); 2 = +shared low-order WFS crosstalk.Use 0 for modulated 3 λ/D PyWFS; set 1 (or 2) for unmodulated 0 λ/D PyWFS where S-curve saturation and TT-modulated optical gain dominate.
.key_mode0INITLow-D state-space key clustered by libgric: 0=TT2_E2 (4D), 1=E1_LOGE (1D), 2=WFS_LO4 (4D), 3=TT2_DM2_E2 (6D), 4=REGIME_E2_VEL (3D), 5=EXTERNAL.0 (TT2_E2) is the best all-around choice for PyWFS nonlinearity (tracks tip/tilt apex excursion + low/high WFS energy); use 4 (REGIME) for seeing/wind-speed regime switches.
.kmax16INITMaximum number of libgric state-space cluster anchors (1..64).8–16 clusters capture distinct tip-tilt / seeing regimes without fragmenting per-cluster sample counts. Pair with selflearn.rlim = 1.8–2.5.
.lam020.0INITLevel-0 Global Online Adaptive Filter RLS ridge prior.20.0 responds smoothly in ~100–300 frames; raise to 50–100 on noisy faint stars.
.lam1200.0INITLevel-1 per-cluster RLS shrinkage ridge toward Level 0 (always keep lam1 ≥ 5–10 × lam0).150–300 forces clusters to deviate from Level 0 only when a cluster accumulates strong, repeatable state-dependent evidence.
.gamma00.998INITLevel-0 exponential forgetting factor (effective memory 1/(1-γ0) = 500 fr) and Level-1 selflearn.gamma1 (0.995 = 200 fr per active cluster).Use 0.997–0.999 for global drift; set gamma1 = 0.995–0.999 (higher preserves rarely visited clusters longer).
.gate_eta0.995INITEMA decay of the causal out-of-sample James-Stein shrinkage gates (alpha_l0, alpha_l1).0.995 (~200-frame window) reacts quickly when regimes change while holding steady at 0.00 under pure noise.
.max_wfs_gain0.5INITHard physical stability cap on learned WFS optical-gain weight (also bounds odd NL terms inside a stability ball).Set 0.35–0.45 on closed-loop PyWFS (0.40 default in cacaoloop) to guarantee closed-loop gain margin even under 3–5× optical-gain swings.
.max_tweak0.25INITHard per-mode absolute clamp on applied residual tweak [modal units].Keep 0.15–0.25 (and selflearn.max_ar_norm2 = 2.0) so a sudden glitch can never inject a large DM kick.
.shadowOFFLIVEShadow commissioning mode: runs GRIC clustering, RLS updates, and OOS scoring without adding any tweak to the DM.Always start with shadow=ON for 5–10 s to inspect out.oos_vr_l0_pct, out.oos_vr_l1_pct, and out.alpha_l0/l1 before engaging live output.
.enable_l0ONLIVELive A/B switch for Level-0 Global Online Adaptive Filter (and selflearn.enable_l1 for Level-1 Clustered Self-Learning).Toggle independently on sky to measure exact WFE/Strehl gain of Global RLS alone vs. Global + Clustered.
.apply_gain1.0LIVELive scalar blend multiplier [0..1] on the Stein-gated tweak (plus selflearn.learnON and selflearn.reset).Ramp smoothly 0.25 → 0.5 → 1.0 on first on-sky test; set learnON=OFF to freeze weights during photometric/coronagraphic sequences.

6. Step-by-Step Setup & Safe Commissioning Workflow CalibrationLoop OperationAnalysis

Follow this six-step bring-up sequence whenever deploying predictive control on a new AO loop, instrument mode, or simulation bench. Each step has a quantitative go/no-go check before you engage live DM commands.

1Validate Baseline Loop & Unbiased PSOL Observer

Close the baseline leaky integrator, verify MLAT / testOL latency alignment (< 0.1 fr mismatch), enable 3D dynamic PSOL (modalfilter.comp.dynpsol.enable) on plate DMs, verify optical-gain scaling (mWFSfact = 1/g_opt), and turn on WFS dark subtraction (--wfs-dark-adu) for faint stars.

Go check: During a small modal poke or testOL probe, aolN_modevalOL shows zero probe leakage and stays stationary regardless of loop gain.

2Enable PSOL Double-Buffer Telemetry

Set modalfilter.comp.OLmodes=ON, modalfilter.comp.tbuff=ON, and modalfilter.comp.tbuffsize=256. This publishes both per-frame aolN_modevalOL (triggering applyARPF / applyEOFPF) and the 256-frame ping-pong buffer aolN_modevalOL_buff (triggering mkARPF / mkEOFPF).

3Start Solver & Applier in Shadow (Observation) Mode

Start mkEOFPF-N + applyEOFPF-N (or mkARPF-N + applyARPF-N) while keeping modalfilter.PF.enable=OFF (or modalfilter.PF.mixcoeff=0.0). Watch the built-in out-of-sample diagnostics as the buffer fills:

Go check: mkEOFPF.out.eof_active reaches 1 (bootstrap) then 2 (EOF); mkEOFPF.out.var_red_oos_pct is strongly positive (+20% to +70%); and mkEOFPF.out.overfit_ratio stays within 1.00–1.20.

4Engage Predictive Control Smoothly in modalfilter

Set modalfilter.PF.NBblock=1, modalfilter.PF.maxwaitus=3000, modalfilter.PF.enable=ON, and ramp modalfilter.PF.mixcoeff from 0.3 → 0.6 → 0.90 (with per-mode rolloff CACAO_PF_MGAIN_EXP = 0.50 so noisy high-order modes blend conservatively).

Go check: modalfilter.PF.timeout_cnt stays at 0, WFS modal RMS drops across low/mid modes, and no high-frequency ringing appears.

5Optionally Layer Cascaded Self-Learning (Shadow → Live)

Route applyEOFPF-N.outdata = aolN_modevalPF_eof and applyEOFPF-N.outPFstat = aolN_outPFstat_eof into selflearn.inbasePF / selflearn.inbaseStat, with selflearn-N.outdata = aolN_modevalPF and out_mode = 0. Start with selflearn.shadow=ON for 5–10 s, verify selflearn.out.oos_vr_l0_pct > 0 and selflearn.out.alpha_l0 > 0.2, then switch selflearn.shadow=OFF and ramp selflearn.apply_gain 0.25 → 1.0.

6Audit Optimality with modalwhite

Run WHITE (cacao-fpsexec-modalwhite) non-intrusively on aolN_modevalWFS_buff and aolN_modevalDM_buff. An optimal linear predictor leaves an MA(d-1) innovation whose autocorrelation and cross-mode correlation vanish for all lags k ≥ ceil(τ).

Go check: modalwhite.out.alert_flags == 0, modalwhite.out.Q_vw_b0 and modalwhite.out.Q_xmode_b0 drop dramatically relative to the integrator baseline, and modalwhite.out.recov_wfe_nm is near the noise floor.

Quick Command-Line Recipes (cacao-work & Live FPS)

# 1. Steady High-Contrast 2-Stage Block-EOF (B=128, P=8) + AR(16) bootstrap + ZOH ridge on Stg1
./scripts/run-ao3k-scexao.sh --predictive --pf-mode eof --pf-blocksize 128 --pf-order 8 \
    --pf-reg 1e-4 --pf-reg2 1e-2 --pf-maxnorm2 2.0 --pf-zoh-ridge --no-pf-zoh-ridge2 \
    --pf-nbtrain1 16384 --pf-nbtrain2 32768 --pf-minsamples1 12000 --pf-minsamples2 24000 \
    --modalwhite --phys-time 10.0

# 2. Dynamic Wind / Fast Cold-Start: Block-EOF(B=64, P=8) + live windlayers physics prior
./scripts/run-ao3k-scexao.sh --predictive --pf-mode eof --pf-blocksize 64 --pf-order 8 \
    --pf-reg 1e-4 --pf-reg2 1e-2 --windlayers1 --pf-n-prior 1024 --pf-wl-switch-decay 0.20 \
    --pf-minsamples1 6000 --pf-minsamples2 12000 --modalwhite --phys-time 10.0

# 3. Unmodulated 0 l/D PyWFS with Cascaded Self-Learning (Global RLS + Clustered libgric)
CACAO_SELFLEARN_ENABLE=1 CACAO_SELFLEARN_MODES=128 CACAO_SELFLEARN_NL_MODE=1 \
CACAO_SELFLEARN_KEYMODE=0 CACAO_SELFLEARN_KMAX=16 CACAO_SELFLEARN_MAX_WFS_GAIN=0.40 \
./scripts/run-ao3k-scexao.sh --wfs2-mod-rad 0.0 --predictive --pf-mode eof \
    --pf-blocksize 64 --pf-order 8 --live-2wfs1dm-sec 2.0 --modalwhite --phys-time 10.0

# 4. Live FPS commissioning toggles (zero restart needed on a running CACAO loop)
milk-fps-set selflearn-1 .shadow ON              # observe OOS VR & Stein gates safely
milk-fps-set selflearn-1 .shadow OFF .apply_gain 0.5
milk-fps-set selflearn-1 .enable_l1 OFF          # live A/B: Global RLS alone vs. Clustered
milk-fps-set mfilt-1     .PF.mixcoeff 0.90       # adjust predictive blend live

7. Ready-to-Use Parameter Presets by Observing Regime Loop Operation

Use these verified starting configurations to match your telescope, guide-star brightness, WFS modulation, and wind stationarity:

Observing RegimeRecommended StackKey Starting ParametersExpected Behavior & Watch-Outs
Fast Cold-Start / Rapidly Changing SeeingPF/AR (AR(16))PForder=16, NBtrain=2048–4096, minsamples=256, reg1=1e-4, reg2=1e-2, maxnorm2=1.35, mix=0.90Locks in 0.25 s, survives gusts with zero petal slips, 24–34 μs RT cost. Does not capture cross-mode wind advection.
Bright-Star Steady High-Contrast ExAO (Default)EOF (B=128, P=8 + ZOH Stg1)blocksize=128, PForder=8, diagorder=16, NBtrain=16384/32768, minsamples=12000/24000, reg=1e-4 / 1e-2, zoh_ridge=ON(S1)/OFF(S2), maxnorm2=2.0Deepest 10–20 λ/D coronagraph contrast (−13–14% vs. matched AR(16)) and −41% LLOWFS stroke at ~1.0 CPU core.
Meandering Wind / Sudden Heading SwitchesEOF (B=64, P=8) + WIND + EOF/MEMblocksize=64, PForder=8, minsamples=6000, n_prior=1024, wl_switch_decay=0.20, optional regime_kmax=6Instant cold-start (+70% VR) and 6.2× lower WFE across +60° wind switches. Never combine EOF/WIND with EOF/FX.
Unmodulated 0 λ/D PyWFS / Nonlinear Optical GainEOF + SELFLEARN (SL/GLOBAL + SL/CLUST)NBmodeMax=128, nl_mode=1, key_mode=0 (TT2_E2), kmax=12–16, rlim=2.0, lam0=20, lam1=200, max_wfs_gain=0.40, max_tweak=0.25Cuts unmodulated PyWFS residual −36.4% over fixed EOF while Stein gates guarantee 1.000× white-noise safety.
Faint Star (m ≥ 9–10) Photon/RON-LimitedSlow WFS (250–500 Hz) + EOF + MRDMwfs1_rate=250 Hz, wfs_dark_adu ON, WFSnormfloor=0.001, blocksize=64, reg=1e-3–5e-3, mr_enable=ON, mr_vel_reg_mult=3.5, mvalpacer upstream of dmpreshaper+12 pts Stage-1 H-Strehl over 1 kHz EOF (80.4% vs. 50.7% best integrator). Stay ≥ 250 Hz on 4-spider pupils to avoid island petaling.
Heavy Low-Order Thermal Petaling / Slow DriftEOF with Difference-Space Leading Modesdiff_nmode=16–32, diff_order=16, diff_reg=0.05, diff_maxnorm2=4.0, diff_maxdcgain=0.9995, zoh_ridge=ONPins exact DC gain on lowest-order modes so slow island/TT drifts never sag, while retaining cross-mode velocity coupling.
Unshaped Resonant Plate DM (No Pre-Shaper)EOF + EOF/FX + PSOL MIMOdm_kernel=H_mimo.fits (Pass-1/2), dynpsol.enable=ON, n_prior=0 (keep EOF/WIND OFF)Convolves EOF regressors through the DM impulse response, cutting ringing whiteness Q_vw by 26.4×.

8. Live Diagnostics & Troubleshooting Cookbook AnalysisLoop Operation

Every CACAO predictive unit exports live health counters over FPS shared memory so you can diagnose mistuning objectively without guessing.

Key Live Health Counters to Monitor

Unit & OutputHealthy RangeWhat It Measures
mkEOFPF.out.eof_active1 → 20=warming up, 1=diagonal AR bootstrap, 2=full cross-mode Block-EOF active.
mkEOFPF.out.var_red_oos_pct+15% to +75%Strict out-of-sample lag variance reduction vs. ZOH on each newly arrived buffer before training on it. Negative means overfitting or bad lag!
mkEOFPF.out.overfit_ratio1.00 – 1.20Ratio rms_pred_oos / rms_pred_insample. Values > 1.30 warn that reglambda is too low or NBtrain is too short for P*B.
mkEOFPF.out.oos_rho_d_b0|ρ(d)| < 0.08Signed lag-d autocorrelation of Block-0 OOS residual: > +0.10 = under-corrected lag; < −0.10 = over-gain / ringing.
selflearn.out.alpha_l0 / selflearn.out.alpha_l10.00 (null) or 0.2–0.9Causal OOS James-Stein shrinkage gates. Near 0.00 when EOF already whitened the loop or under white noise; opens automatically when nonlinear OG or extra residual structure appears.
modalwhite.out.alert_flags0Controller-agnostic bitmask: 1=uncorrected lag, 2=high-freq ringing, 4=cross-mode coupling left on table, 8=ZPO / DM fightback.
modalfilter.PF.timeout_cnt0Frames where modalfilter timed out waiting for applyARPF / applyEOFPF / selflearn. Must remain 0.

Symptom → Root Cause → Fix Matrix

Observed SymptomLikely Root CauseConcrete Parameter Fix
Overfitting
overfit_ratio > 1.3 or var_red_oos_pct < 0
Too few independent samples for D = P * B, or reglambda too small for current SNR.Increase reglambda (e.g., 3–10×), reduce blocksize (128 → 64) or PForder, increase minsamples (N/D ≥ 10), or enable gram_halflife / EOF/WIND.
Ringing
alert_flags & 2, rho_d_b0 < -0.1, Stage-2 HF bursts
Regularization too weak on lower-SNR Stage-2 modes, maxnorm2 too loose, or zoh_ridge=ON on Stage-2 high-pass residuals.Raise Stage-2 reglambda to 1e-2, set zoh_ridge=OFF on Stage 2, lower maxnorm2 toward 1.35, or raise CACAO_PF_MGAIN_EXP (0.5 → 0.7) to roll off high-order mix.
Cold-Start Petal Slip
1 λ island jump in first 1–2 s
High-order AR(32/64) activated at N=256 (starved), OR minsamples waited too long in integrator mode before locking.Use AR(16) with minsamples=256, or use mkEOFPF with default diagorder=16 / diagminsamples=256 bootstrap (and EOF/WIND if available).
Lag Remains
alert_flags & 1, rho_d_b0 > +0.1
PFlatency underestimates true delay, PSOL WFSfact / optical gain is mismatched, or PF.mixcoeff is low.Re-check testOL latency and set PFlatency to match; verify live mWFSfact = 1/g_opt; verify PF.mixcoeff=0.90 and zoh_ridge=ON on Stage 1.
Cross-Mode Residual
alert_flags & 4, high Q_xmode_b0
Running diagonal AR(P) (B=1) under strong frozen-flow wind, or blocksize too small for spatial advection coupling.Switch from mkARPF to mkEOFPF with blocksize=64 or 128, PForder=8.
ZPO Fightback
alert_flags & 8, high Q_wu_lo20
Stage-2 WFS zero-point offset (wfszpo) is unscaled when on-sky PyWFS optical gain drops below 1.Enable 2WFS/LIVE / ZPO/OG so acquWFS-2.WFSzpogain = 0.95 * g_opt tracks live optical gain.
SL Gates = 0.00
alpha_l0/l1 ≈ 0
Either EOF is already near-optimal (good! safety gate is doing its job), or selflearn.latency mismatches loop delay, or nl_mode=0 on an unmodulated PyWFS.First verify selflearn.latency matches PFlatency and inbasePF is live. On unmodulated PyWFS, set nl_mode=1 and key_mode=0. If oos_vr_tot_pct ≤ 0 persists, leave gates closed—there is no extra predictable signal to exploit.
RT Timeouts
PF.timeout_cnt > 0
applyEOFPF + selflearn exceeded PF.maxwaitus, or background mkEOFPF threads contended with RT cores.Pin RT processes to isolated cores, lower CACAO_PF_MKTHREADS, set applyEOFPF.nthreads=4, reduce selflearn.NBmodeMax (256 → 128), and confirm PF.maxwaitus ≥ 2000–3000.

9. Supporting Benchmark Reports, Algorithm Specs & Source Map Analysis

Related Technical Studies & Specifications