Phased C/CMake engineering plan (Phases A-E) across milk, cacao, milk-mltools, and cacao-work to deploy the 3-layer decoupled AO control architecture: lock-free ping-pong SHM & RT pacing in milk, decoupled inner Q-rotation + re-projected AR(48) notch + cascaded self-learning + hardware-dependent multi-rate DM pacing (f_DM) + per-actuator spatially-varying DM anti-vibration pre-shaping (KMODE=3/4 & hybrid roadmap) in cacao, and async milk-fpsexec-mlt-cmodes + multi-rate audits in milk-mltools.
Referenced Simulation Reports
No matching simulation reports staged locally yet.
Implementation Plan: Unified AO Real-Time Control Architecture (milk, cacao, milk-mltools)
- Target Repositories:
milk(feat/bash-engine),cacao(feat/bash-engine),milk-mltools(main), and integration/CI incacao-work(main) - Companion Synthesis & Benchmarks: Control Architecture & Benchmark Synthesis Report · Interactive AO Loop Algorithmic Options Map
- Design Principle: Enforce strict architectural decoupling across Core Real-Time Control (Fixed Outer Modal Basis), Inner Control-Mode Optimization (On-the-Fly Rotation Matrix inside
modalfilter), and DM Control & Actuation (Hardware-Dependent Multi-Rate Pacing at user-providedf_DMupstream of2–4 kHzPlate Anti-Vibration Pre-Shaping).
1. End-to-End Target Runtime Architecture & SHM Contract
flowchart LR
subgraph MILK["milk (Engine & Lock-Free Primitives)"]
SEQLOCK["milk_shm_seqlock.h\nPing-Pong 2-Slice SHM"]
RT["milk_rt.h / milk_rt.c\nAbs-Time Sleep & SemWait"]
GRIC["FindGRIC.cmake +\nLAPACKE Plugin Wiring"]
end
subgraph MLT["milk-mltools (Async 0.2-5 s Solvers)"]
CMODES_U["milk-fpsexec-mlt-cmodes\nNoise-Whitened Q + AR(48) ID"]
WIND_U["milk-fpsexec-mlt-windlayers\nWind Velocity & Altitude"]
SYSID_U["milk-fpsexec-mlt-sysid\n2WFS1DM OG / ZPO / Offload"]
AUDIT_U["mlt-tlmsync + mltools.bash\nMulti-Rate & Null Audits"]
end
subgraph CACAO["cacao (Hard Real-Time Control Path)"]
WFS["acquireWFSim\nDark Sub + NormFloor"]
MFILT["modalfilter.c\nInner Q + 16-Mode AR(48)\nOuter Fixed-Basis PSOL"]
EOF["mkEOFPF / applyEOFPF\nBlock-EOF + Zero-DC Vel"]
SL["cacaopc-selflearn\nCascaded Global -> Clustered RLS"]
PACER["mvalpacer (user f_DM)\nZero-Latency Centered Ramps"]
DISP["mvalC2dm -> DMch2disp"]
PRESH["dmpreshaper (2-8 kHz)\nModal (K0-2) & Per-Actuator\nSISO/Stencil-MIMO (K3-4)"]
end
WFS --> MFILT
MFILT -->|"aolN_modevalOL (Fixed Basis)"| EOF
EOF -->|"aolN_modevalPF_eof"| SL
SL -->|"aolN_modevalPF"| MFILT
EOF -->|"aolN_modevalPF_vel"| MFILT
MFILT -->|"aolN_modevalOL_buff / WFS_buff"| CMODES_U
CMODES_U -->|"Ping-Pong aolN_cmodes_Q + params"| MFILT
MFILT -->|"aolN_modevalDM_traj [M x 2]"| PACER
PACER -->|"aolN_modevalDM (f_DM)"| DISP
DISP --> PRESH
SEQLOCK -.-> CMODES_U
SEQLOCK -.-> MFILT
RT -.-> PACER
RT -.-> PRESH
GRIC -.-> SL
Current Baseline Inventory vs. Remaining Implementation Scope
| Feature Area | Already Implemented & Verified | Remaining Production Scope (This Plan) |
|---|---|---|
Multi-Rate DM Pacing (MRDM, user f_DM) |
AOloopControl_DM_mvalpacer.c (zero-latency j=0 wake), mkEOFPF/applyEOFPF zero-DC temporal-difference velocity (EOF/VEL), modalfilter.c exact exposure-averaged ramp PSOL, test_18_multirate_dm.py (3/3), 23-run live GPU AO3k (f_DM = 1 kHz) shootout |
Make DM rate strictly hardware-dependent & user-supplied (.dm_rate_hz / --mr-dm1-rate <hz>, fail fast if unset), derive K_sub = round(f_DM * T_WFS) dynamically across changing f_WFS, refactor onto milk_rt.h, add stall ramp-decay watchdog, formalize acquireWFSim dark-pedestal fallback, wire cacaoloop.bash |
Cascaded Online Self-Learning (SELFLEARN) |
selflearn_core.{c,h}, AOloopControl_PredictiveControl_selflearn.c, libgric CMake integration, test_17_selflearn.py |
Enforce cascaded-on-EOF default (allow_standalone=OFF), standardize applyEOFPF -> selflearn -> modalfilter stream chain in cacaoloop & runner scripts, add modalwhite pure white-noise null gate |
Inner Control-Mode Optimization (CMODES) |
Offline 7-regime + live basis-swap + RT CPU timing validation (47.5 nm bumpless swaps, +2.4 us @ 128 modes) |
New C implementation: atomic ping-pong SHM helper in milk, decoupled inner Q rotation + re-projected 16-mode AR(48) notch in cacao (modalfilter.c), async milk-fpsexec-mlt-cmodes solver in milk-mltools, new test_19_cmodes.py |
DM Mechanical Anti-Vibration Pre-Shaper (PRESH) & Autotuner (MOPT) |
dmpreshaper, compdmpreshaper (deconv_exp=ON two-sided Toeplitz exposure deconvolution, energy_weight=ON, KMODE=0 modal MIMO, KMODE=1 modal SISO, KMODE=2 uniform SISO, KMODE=3 per-actuator SISO, KMODE=4 per-actuator spatially-varying (2R+1)×(2R+1) local-stencil MIMO, .fill_uncal), measdynresp, factordynrm, modalopt.c, modalwhite.c, test_10_dmpreshaper.py (3/3 HIL pass including 68-act interior+free-rim KMODE=3/4 at 2 & 4 kHz), 8 kHz AO3k GPU demo |
Add Work Package C3b (Hybrid Global-Modal KMODE=0 + Per-Actuator Residual KMODE=3/4 composition, parallel/sparse multi-poke full-DM zonal 3D RM calibration for N_act ≈ 3000+ in < 2 min, and 64×64 AO3k per-actuator HIL benchmark), harmonize dmpreshaper timing onto milk_rt.h, wire MOPT compatibility with rotated CMODES inner basis, add unified status row in cacao-modalstatsTUI-bin |
2. Repository 1: milk (Engine, Lock-Free SHM & Real-Time Primitives)
milk stays strictly AO-agnostic and provides reusable low-level primitives consumed by both cacao and milk-mltools.
Work Package M1 · Lock-Free Ping-Pong Double-Buffered SHM Seqlock Helper
- Files:
src/engine/libmilkcommon/milk_shm_seqlock.h(new header-only C11 atomic helper, installed alongsidemilk_rt.hinlibmilkcommon/CMakeLists.txt) - Problem: Multi-element matrix swaps (
aolN_cmodes_Q [M_rot x M_rot x 2]plusaolN_cmodes_params) must update atomically without mutexes or torn reads on a2 kHzreal-time thread. - API:
uint32_t milk_shm_pingpong_begin_write(IMAGE *im): selects inactive slicew = (uint32_t)((im->md[0].cnt1 + 1u) & 1u), setsmd[0].write = 1.void milk_shm_pingpong_commit_write(IMAGE *im, uint32_t write_slice): executes__atomic_thread_fence(__ATOMIC_RELEASE), writesim->md[0].cnt1 = write_slice, incrementsim->md[0].cnt0, updateswritetime/atime, clearsmd[0].write = 0, and posts semaphores.int milk_shm_pingpong_try_acquire(const IMAGE *im, uint64_t *last_cnt0, uint32_t *read_slice): checkscnt0 != *last_cnt0with__ATOMIC_ACQUIRE, returns1with committedread_slice = (uint32_t)(cnt1 & 1u)(< 10 ns, zero syscalls, zero heap allocations).- Compatibility: Uses standard 3D
ImageStreamIO[Nx, Ny, 2]streams sostreamFITSlog,milk-shmim, and Python bindings inspect them natively.
Work Package M2 · Shared High-Precision Real-Time Pacer Primitives
- Files:
src/engine/libmilkcommon/milk_rt.h,src/engine/libmilkcommon/milk_rt.c - Problem:
AOloopControl_DM_mvalpacer.candAOloopControl_DM_preshaper.cduplicateCLOCK_MONOTONIC+clock_nanosleep(TIMER_ABSTIME)+_mm_pause()spin-wait loops andImageStreamIO_semtimedwaitwrappers. - API:
uint64_t milkrt_now_ns(void)int milkrt_sleep_until_ns(uint64_t target_ns, uint32_t spin_us, PROCESSINFO *pinfo)(returns-2on clean process exit)int milkrt_semtimedwait_ms(IMAGE *im, int sem_idx, uint64_t timeout_ms, PROCESSINFO *pinfo)- Target:
< 5 usp99 wake jitter across1–4 kHzpacing on Linux RT/PREEMPT kernels.
Work Package M3 · Relocatable libgric & LAPACKE Plugin Build Support
- Files:
cmake/FindGRIC.cmake(new),src/engine/libmilkcommon/CMakeLists.txt - Scope:
- Standardize
find_package(GRIC)acrosscacao(AOloopControl_PredictiveControl/CMakeLists.txt) andmilk-mltools(mltools/CMakeLists.txt) searching${CMAKE_INSTALL_PREFIX},$ENV{MILK_INSTALL_ROOT}, and/usr/local. - Confirm
MILK_CMAKE_REQUEST_LAPACKEandMILK_CMAKE_REQUEST_BLASpropagate link flags (LAPACKE_dsyevd,cblas_sgemv) cleanly to out-of-tree plugin modules (milk-mltools) and verifystreamFITSloghandles[NBmode x 2]trajectory streams (aolN_modevalDM_traj) with exact timestamps.
3. Repository 2: cacao (Real-Time Core Control, Inner Modes & Multi-Rate DM)
All hard real-time execution stays in cacao with a strict < 120 us CPU budget at 256 modes (< 24% of a 2 kHz frame).
Work Package C1 · Decoupled Inner Control-Mode Rotation & AR(48) Notch in modalfilter.c
- Files:
AOloopControl/modalfilter.c,AOloopControl/AOloopControl.h - Hard Architectural Invariant:
- The outer modal basis (
aolN_modevalWFS,aolN_modevalOL,aolN_modevalDM,aolN_modevalPF,aolN_modevalPF_vel) never rotates. - Rotation matrix
Q(M_rot <= 256, default128) operates strictly insidemodalfilter.con modes0 .. M_rot - 1; higher modesM_rot .. NBmode - 1pass through the existing diagonal integrator untouched. - Exact Hot-Path Math inside
modal_filter_step():
- Atomic Ping-Pong Basis Swap (
aolN_cmodes_Q+aolN_cmodes_params):
- When
milk_shm_pingpong_try_acquire()signals a new committed basis frommlt-cmodes: - Sanity check: reject swap if any non-finite value or
||Q_wfs_new^T Q_dm_new - I||_F / sqrt(M_rot) > 1e-2. - Compute transition matrix
T = Q_dm_new^T * Q_dm_old(orthogonal case:Q_new^T Q_old,[M_rot x M_rot]viacblas_sgemm— only runs on slow swap frames every2–5 s, never every frame!). - Bumpless integrator state transfer:
u_rot_new = T * u_rot_old(guaranteesQ_dm_new u_rot_new == Q_dm_old u_rot_oldwith0.0 nmstatic step). - Mandatory
AR(48)history re-projection: for each lagk = 0 .. P_notch - 1, rotate stored residual vectorH_new[k] = T * H_old[k](eliminates the286.8 nmunprojected swap transient, keeping swaps bumpless at47.5 nm). - Atomically switch
Q_cur,g_rot,a_rot, andw_notch, increment.out.cmodes_swaps.
- Forward Projection (
cblas_sgemv):e_rot = Q_wfs^T * (zpo - wfs_in)(0 .. M_rot - 1). - Inner Rotated Leaky Integrator + 16-Mode
AR(48)Telescope-Vibration Notch:
u_rot[i] = clamp(a_rot[i] * u_rot[i] + g_rot[i] * e_rot[i], -lim_rot[i], +lim_rot[i]).- For
i < K_notch(default16, max32, orderP_notch = 48): computedn[i] = clamp(sum_k w_notch[i, k] * H[k, i], -max_notch, +max_notch)and pushe_rot[i]into ring bufferH.
- Back-Projection to Fixed Outer Basis (
cblas_sgemv):mvalDMc[0 .. M_rot - 1] = Q_dm * (u_rot + dn). - Outer Fixed-Basis PSOL & Predictive Control Blend: Existing
PSOL,EOF, andSELFLEARNpaths run unchanged onmvaloutapplyand blend viaPFmixcoeff.
- New FPS Parameters & SHM Streams:
| FPS Parameter / Stream | Type / Dims | Flags | Default & Purpose |
|---|---|---|---|
.cmodes.enable |
FPTYPE_ONOFF |
WRITERUN |
OFF — toggle inner Q-rotated modal filter live |
.cmodes.notch_enable |
FPTYPE_ONOFF |
WRITERUN |
OFF — toggle 16-mode AR(48) telescope-vibration notch |
.cmodes.nbmode |
FPTYPE_UINT32 |
init | 128 (max 256) — dimension M_rot of inner rotated subspace |
.cmodes.nbnotch |
FPTYPE_UINT32 |
WRITERUN |
16 (max 32) — leading rotated modes receiving AR(48) notch |
.cmodes.notch_order |
FPTYPE_UINT32 |
init | 48 (max 64) — AR notch tap depth P_notch |
.cmodes.max_notch |
FPTYPE_FLOAT32 |
WRITERUN |
0.15 — per-mode hard clamp on notch correction [modal units] |
aolN_cmodes_Q |
float32 [M_rot x 2*M_rot x 2] |
ping-pong | Dual [Q_wfs; Q_dm] matrices (Q_wfs == Q_dm for orthogonal Q) |
aolN_cmodes_params |
float32 [(2 + P_notch) x M_rot x 2] |
ping-pong | Packed [g_rot, a_rot, w_notch[0..P-1]] synced with aolN_cmodes_Q |
.out.cmodes_swaps, .out.cmodes_orth_err, .out.cmodes_notch_rms |
outputs | DEFAULT_OUTPUT |
Live swap counter, orthogonality residual, and notch RMS telemetry |
- RT Latency Budget: Two
128 x 128cblas_sgemv+16 x 48dot products =+2.4 us(21.2 ustotal with Fixed Block-EOF =4.2%of2 kHz); at256 x 256,+8.5 us.
Work Package C2 · Cascaded Online Self-Learning Production Hardening
- Files:
AOloopControl_PredictiveControl/AOloopControl_PredictiveControl_selflearn.c,selflearn_core.{c,h},AOloopControl/commands.d/cacaoloop.bash - Key Changes:
- Enforce Cascaded-Only Safe Default: Add
.allow_standalone(ONOFF, defaultOFF). WhenOFF,cacaopc-selflearnrequires a live.inbasePF(aolN_modevalPF_eof) fromapplyEOFPFbefore publishing non-zero corrections — structurally preventing the18.35 nmstandalone white-noise failure mode. - Standardize Descriptive Parameter Names & Diagnostics: Expose clear FPS aliases/descriptions for Global Online Adaptive Filter (
.enable_l0/ single-model RLS) and Clustered State-Dependent Self-Learning (.enable_l1/libgricmulti-cluster RLS), plus.out.noise_amp_ratiotelemetry. - Zero-Friction Stream Wiring (
applyEOFPF -> selflearn -> modalfilter):
- When self-learning is enabled on loop
N:applyEOFPF-Nwrites.outdata = aolN_modevalPF_eofand.outPFstat = aolN_outPFstat_eof(while still writing.outvel = aolN_modevalPF_veldirectly tomodalfilter). selflearn-Ntriggers onaolN_modevalPF_eof(oraolN_modevalOLwith bounded wait onaolN_modevalPF_eof), adds bounded cascaded Global + Clustered residual tweak, and publishes finalaolN_modevalPF+aolN_outPFstattomodalfilter(zero changes required insidemodalfilter's semaphore wait).
- SIMD / OpenMP Hot-Loop Tuning: Ensure
sl_engine_step()stays<= 89 us@128modes and<= 114 us@256modes with-fno-finite-math-onlypreserved for NaN/Inf safety guards.
Work Package C3 · Hardware-Dependent Multi-Rate DM Pacing (f_DM) & Faint-Star Slow-WFS Finalization
- Files:
AOloopControl_DM/AOloopControl_DM_mvalpacer.c,AOloopControl_DM/AOloopControl_DM_preshaper.c,AOloopControl_IOtools/acquireWFSim.c,AOloopControl/commands.d/cacaoloop.bash,benches/ao3k_scexao/sim-ao3k-scexao.milk - Key Changes:
- Mandatory User-Provided Hardware DM Update Rate (
f_DM) — No Hardcoded1 kHz:
- Because maximum safe/effective command rates vary widely by DM hardware (e.g.,
500–1000 Hzfor large magnetic plate DMs such as AO3k ALPAO 64×64, vs2000–4000 Hzfor fast MEMS/piezo DMs),mvalpacermust never hardcode1 kHz. - Set default
.dm_rate_hz = 0.0(unset) inAOloopControl_DM_mvalpacer.c: when multi-rate pacing is enabled without a user-supplied positive.dm_rate_hz(and without an explicit.k_suboverride), fail fast with an explicit error requiring the user to specify the hardware DM rate in Hz. - Replace bare boolean
--mr-dm1incacaoloop.bash/sim-ao3k-scexao.milkwith explicit rate option--mr-dm1-rate <hz>(andCACAO_PF_MR_DM_RATE_HZ,0= multi-rate OFF; if legacy--mr-dm1is passed without a rate, exit with usage error requesting--mr-dm1-rate <hz>). - Validate hardware constraints at startup: pass through (
K_sub = 1) wheneverf_DM <= f_WFS, and reject/clamp ifdmpreshaperis active downstream withf_DM > f_presh.
- Dynamic
K_subDerivation from Userf_DM& Live WFS Cadence:
- Wall-clock hardware mode (
.trigstreamunset): measure live incoming WFS periodT_WFSvia EWMA ofCLOCK_MONOTONICarrival deltas onaolN_modevalDM_traj, computeK_sub = clamp(round(f_DM * T_WFS), 1, 32), and pace sub-steps atdt_sub = T_WFS / K_sub(effective DM update rate≈ f_DM). Changingf_WFSon sky (1000 -> 500 -> 250 Hz) automatically re-derivesK_sub(1 -> 2 -> 4atf_DM = 1 kHz, or2 -> 4 -> 8atf_DM = 2 kHz) without restartingmvalpacer, and publishes.out.k_sub_efffor exact ramp-PSOL sync inmodalfilter.c. - Lockstep simulation mode (
.trigstreamset, bench clockf_trig): derivetrig_decim = max(1, round(f_trig / f_DM))andK_sub = max(1, round(f_DM / f_WFS))directly from the user-suppliedf_DM.
- Unified Timing Backend: Replace duplicated
CLOCK_MONOTONIC/semtimedwaithelpers inmvalpacer.canddmpreshaper.cwithmilk_rt.h(M2). - Stall Watchdog & Ramp-Decay Failsafe in
mvalpacer.c: If no newaolN_modevalDM_trajarrives within2 * T_WFS, exponentially decayu_ramp -> 0(holding safeu_midrather than extrapolating linearly on a dropped WFS frame). Add.out.substep_jitter_us,.out.late_substeps,.out.wfs_dt_ms,.out.k_sub_eff, and.out.eff_dm_rate_hz. - Faint-Star WFS Dark-Pedestal Safeguard in
acquireWFSim.c: Add optional scalar fallback.WFSdarkadu(FLOAT32, default0.0) subtracted when noaolN_wfsdarkcube is loaded, and warn ifWFSnormfloor > 0.05while.out.fluxtotalfalls into faint-star regime (< 5000 ADU). - Strict Hardware Signal-Flow Enforcement: In
cacaoloop.bash, enforce startup sequencemvalpacer (user f_DM) -> mvalC2dm -> DMch2disp -> dmpreshaper (f_presh >= f_DM) -> DM, settingmfilt.PF.mr_pacer_out = ONto guarantee single-writer ownership ofaolN_modevalDM.
Work Package C3b · Per-Actuator Spatially-Varying DM Pre-Shaping (KMODE=3, 4) & Full-DM Calibration
- Files:
computeCalib/compute_dm_preshaper.c,AOloopControl_DM/AOloopControl_DM_preshaper.c,AOloopControl_acquireCalib/measure_dyn_resp.c,tests/test_10_dmpreshaper.py - Motivation: On continuous-facesheet plate DMs (such as the 64×64 ALPAO DM with free circular rim) and actuators with individual gain/damping spread, dynamics are not translation-invariant: free-rim actuators exhibit stronger overshoot and one-sided wave reflections than interior actuators (
91–132%relative kernel difference measured on the 12×12 free-rim plate HIL bench). - Implemented & Verified Foundation (
KMODE = 0..4+ Deconvolution Synthesis): - Synthesis upgrades (
compdmpreshaper): Two-sided finite-support Toeplitz WFS-exposure deconvolution (.deconv_exp=ON, dimensionless.lambda_deconv = 2.8e-2scaled by1/n_box) and physical WFS/actuator energy weighting (.energy_weight=ON), active across all modes. KMODE = 3(Per-Actuator Diagonal SISO,[dmx, dmy, M_buf]): Independent temporal pre-shaper kernel per actuator ((ix, iy)) directly in actuator space (noP_FWD/P_PINVprojection,< 1 usSIMD ring update,.fill_uncalIDW interpolation for uncalibrated guard/corner actuators). Live 12×12 GPU HIL (68 active actuators, interior + free-rim probes):0.27%DC parity, overshoot+5.40% -> +2.70%, ringing1.87% -> 0.98%(1.91×).KMODE = 4(Per-Actuator Spatially-Varying Local-Stencil MIMO,[N_nb, dmx*dmy, M_buf]): Solves an independent physical-energy-weighted local Cholesky MIMO system for every calibrated actuator over its(2R+1)×(2R+1)neighborhood (.stencil_radR ∈ 1..5,N_nb = (2R+1)^2, gather layout for race-free OpenMP parallelization and zero-cost sparse-row skipping,.fill_uncalnearest-calibrated stencil copy, arbitrary-rate hardware resampling). Naturally captures free-rim one-sided asymmetric stencils and individual actuator heterogeneity. Live 12×12 GPU HIL (R = 2, 5×5 stencil):0.24%DC parity, overshoot+5.40% -> +0.72%(+6.25% -> +0.66%at the free rim,9.5×cut), ringing1.87% -> 0.42%(4.49×at 2 kHz,4.51×resampled at 4 kHz), and 2D cross-actuator mechanical wave coupling cut2.11×peak /2.55×RMS (2.03×lower wave RMS thanKMODE = 3).- Remaining Production Scope (Next Steps for AO3k 64×64 Scale):
- Sparse Spatially-Tiled / Hadamard Parallel 3D RM Calibration (
measure_dyn_resp.c): PokingN_act ≈ 3,200actuators one-by-one takes~10–15 min; add a spatially tiled comb-poke mode (simultaneously poking actuators spaced by>= 2R + 4pitches where cross-actuator wave overlap is negligible, or block-Hadamard encoding) to acquire full 64×64 per-actuator 3D RMs in< 90 s. - Hybrid Global-Modal + Per-Actuator Local Residual Mode (
KMODE = 5, planned): Combine a low-order global modal MIMO kernel (KMODE = 0, 16–32 long-range plate modes capturing cross-aperture reflections) with a per-actuator local-stencil residual (KMODE = 3/4) summed in a single unified look-ahead ring buffer so both global drum/rim standing waves and local actuator/edge defects are cancelled simultaneously with< 60 usRT budget at4–8 kHz. - AO3k 64×64 Per-Actuator Live GPU Benchmark: Add a 64×64 AO3k
KMODE = 3vs.KMODE = 4vs.KMODE = 0comparison (single interior + rim pokes, closed-loop Kolmogorov wavefronts, and RT CPU profiling at4–8 kHz) to thedm_preshaper_demostudy.
Work Package C4 · Whiteness Null Safety Gate, MOPT Interop & TUI Telemetry
- Files:
AOloopControl/modalwhite.c,AOloopControl/modalopt.c,AOloopControl/tui/modalstatsTUI.c - Scope:
modalwhite.c: Add.out.wn_amp_ratio(DM-to-WFS noise amplification monitor) and lag-dautocorrelation alert when an online learner leaks correlated noise (> 1.02x).modalopt.c: Add optional.inQ(aolN_cmodes_Q) input soMOPTcan projectaolN_modevalOL_buffinto the rotated inner basis and publish optimal(g_rot, a_rot)directly whenCMODES/ROTis active without predictive control.modalstatsTUI.c: Add a single-line control-stack indicator bar (BASE:EOF | SL:G+C [a0=0.42 a1=0.31] | CMODES:Q+AR48 [swaps=4] | DM:MR(f_DM)->PS [clips=0]).
4. Repository 3: milk-mltools (Async Statistical Solvers & Offline Audits)
Work Package ML1 · New Async FPS Unit: milk-fpsexec-mlt-cmodes
- Files:
mltools/cmodes_core.h,mltools/cmodes_core.c,mltools/cmodes_unit.c,mltools/mltools.h,mltools/mltools.c,mltools/CMakeLists.txt - Build & Registration:
- Add
MILK_CMAKE_REQUEST_LAPACKEandMILK_CMAKE_REQUEST_BLASannotations incmodes_core.c. - Register
runnable_mlt_cmodesinmltools.cand add CTest smoke testadd_test(NAME mlt-cmodes-h1 COMMAND milk-fpsexec-mlt-cmodes -h1). - Algorithm Pipeline (Async
0.5–5 sCadence, OpenMP + LAPACKE):
- Telemetry Ingestion: Wakes on
aolN_modevalOL_buff(and optionalaolN_modevalWFS_buff) double-buffer flips, updating an exponentially weighted modal signal covarianceC_sig(tau_cov = 5–20 s, resettable on regime jump) and high-frequency[0.35, 0.48] f_sWFS noise covarianceC_noise. - Prior-Blended Noise-Whitened Eigendecomposition (
LAPACKE_dsyevd):
- Optional dimensionless Kolmogorov covariance shrinkage (
C_eff = C_sig + w_prior * C_prior) preventing overfitting at low SNR (m = 10). - Whitened symmetric eigendecomposition
C_noise^{-1/2} C_eff C_noise^{-1/2} = U Λ U^TproducingQ_wfsandQ_dm(Q_wfs^T Q_dm = I), ordered by descending WFS SNR or pupil-phase variance.
- Sign & Permutation Continuity + Hysteresis Gate:
- Align columns of
Q_newtoQ_oldvia maximum-overlap greedy/Procrustes matching so near-degenerate eigenvalues never induce random sign flips. - Suppress swap if subspace drift
< .swap_thresh(0.05 rad) or elapsed time< .min_swap_sec(2.0 s).
- Selective
AR(48)Narrowband Telescope-Vibration Notch Solver:
- Run radix-2 Welch PSD (
mlt_fft1d_c2cfromao_math.h) on the topK_notch(16) rotated residual modes. - Activate ridge-regularized Levinson-Durbin / Yule-Walker
AR(48)notch weights only on modes with narrowband spectral line excess> .vib_snr_db(6 dB) above local broadband continuum; zero out weights on broadband turbulence or pure white-noise modes (preserving the1.000xwhite-noise null guarantee!).
- Atomic Publication: Write
[Q_wfs; Q_dm]intoaolN_cmodes_Qand[g_rot, a_rot, w_notch]intoaolN_cmodes_paramsusingmilk_shm_pingpong_begin_write()/commit_write().
Work Package ML2 · Multi-Rate Telemetry Sync & Pure-MILK Orchestration Helpers
- Files:
mltools/tlm_sync_unit.c,mltools/commands.d/mltools.bash - Scope:
- Extend
mlt-tlmsyncto co-index heterogeneous-rate streams (f_WFSWFS, userf_DMmvalpacerDM,f_preshdmpreshaperDM, science PSF) and emit multi-rate health metrics (HF OPD ripple> 100 Hz, DM plate-resonance band energy, pre-shaper stroke & clip count) in JSON/FITS outputs. - Add orchestration helpers in
mltools/commands.d/mltools.bash: mlt.cmodes_start <loop> [nbmode=128] [nbnotch=16]/mlt.cmodes_stop/mlt.cmodes_statusmlt.selflearn_ab <loop>(synchronized A/B toggle ofSL/GLOBALandSL/CLUSTwith Stein-gate and OOS VR reporting)mlt.multirate_audit <telemetry_dir>(post-run PSD & stroke headroom report)
5. Phased Execution Roadmap & Quantitative Acceptance Gates (cacao-work)
flowchart LR
PA["Phase A: milk\nPing-Pong Seqlock,\nmilk_rt, FindGRIC"] --> PB["Phase B: cacao\nMulti-Rate DM &\nFaint-Star Hardening"]
PA --> PC["Phase C: cacao\nCascaded Self-Learning\n& White-Noise Gate"]
PA --> PD["Phase D: cacao + mltools\nDecoupled Inner CMODES\n(Q + Re-Projected AR48)"]
PB --> PE["Phase E: cacao-work\nFull 3-Layer Live GPU\nShootout, CI & Website"]
PC --> PE
PD --> PE
| Phase | Repos | Key Deliverables | Automated Verification & Go/No-Go Gate |
|---|---|---|---|
| Phase A · Engine Foundations | milk |
milk_shm_seqlock.h, milk_rt.{h,c}, FindGRIC.cmake, LAPACKE plugin check |
New C/pytest engine tests: 0 torn reads over 10^6 concurrent swaps; < 5 us p99 sleep jitter at 1–4 kHz; clean relocatable ./scripts/build-all.sh |
| Phase B · Multi-Rate DM, Per-Actuator Pre-Shaper & Faint-Star Production | cacao, cacao-work |
Mandatory user-provided .dm_rate_hz / --mr-dm1-rate <hz> (no hardcoded 1 kHz), dynamic K_sub = round(f_DM * T_WFS), milk_rt.h refactor, stall ramp-decay watchdog, acquireWFSim dark-pedestal fallback, cacaoloop.bash wiring; per-actuator KMODE=3/4 pre-shaper (done & HIL-verified) + sparse tiled 64×64 zonal 3D RM calibration & hybrid global+local KMODE=5 |
pytest tests/test_10_dmpreshaper.py (3/3 incl. KMODE=3/4 interior+rim & 4 kHz resampling) & pytest tests/test_18_multirate_dm.py (>= 7/7: missing-rate rejection, multi-rate sweeps at f_DM = 1/2/4 kHz, stall decay & live f_WFS rate switch); AO3k live GPU (f_DM = 1 kHz) m=10 250 Hz >= 80% H-Strehl (>= 86% 2-stage), 0 clips, 0.000 fr lag; m=6 -35% HF / -40% plate band; 64×64 KMODE=4 RT ingest <= 80 us |
| Phase C · Cascaded Self-Learning & Null Gate | cacao, milk-mltools, cacao-work |
Enforce cascaded-on-EOF default (allow_standalone=OFF), applyEOFPF -> selflearn -> modalfilter wiring in cacaoloop & sim-ao3k-scexao.milk, modalwhite null monitor |
pytest tests/test_17_selflearn.py extended: 40 nm pure white-noise null <= 1.01x (<= 2.0 nm DM leak, Stein gates < 0.05); unmod PyWFS >= 30% WFE cut vs EOF; RT CPU <= 95 us @ 128 m / <= 125 us @ 256 m |
Phase D · Decoupled Inner Control Modes (CMODES) |
cacao, milk-mltools, cacao-work |
Inner Q + re-projected AR(48) notch in modalfilter.c; async milk-fpsexec-mlt-cmodes; modalopt rotated-basis interop; mltools.bash helpers |
New pytest tests/test_19_cmodes.py: mid-run swap peak < 55 nm (bumpless vs > 250 nm unprojected); +30 nm narrowband vibs >= 12% WFE cut over EOF; outer modevalOL invariant < 1e-5; RT overhead <= 5 us @ 128 m (<= 12 us @ 256 m) |
| Phase E · Full-Stack Live GPU Integration & Website Promotion | cacao, milk-mltools, cacao-work |
Full 2-stage live GPU shootout combining all 3 layers; modalstatsTUI stack bar; CLI flags in options_catalog.py; flip CMODES from planned to verified on website |
Full decoupled stack beats or ties every single-layer configuration across all regimes + faint-star m=10; test_05, test_10, test_17, test_18, test_19, and test_mltools_e2e.py all 100% green |
6. Key Risks & Mitigations
| Risk | Failure Mode if Unmitigated | Built-In Mitigation |
|---|---|---|
Torn basis read during Q swap |
Corrupted Q produces transient modal blow-up |
Lock-free 2-slice ping-pong seqlock (M1) + orthogonality/finiteness check in modalfilter.c before swap |
AR(48) ring-buffer mismatch after Q swap |
286.8 nm residual spike on every basis update |
Mandatory in-place history re-projection H_new[k] = (Q_new^T Q_old) H_old[k] (47.5 nm bumpless) |
| Unanchored self-learning noise amplification | 18.35 nm (1.10x) white-noise leakage |
.allow_standalone=OFF default enforcing cascade on Fixed Block-EOF + dual causal Stein gates + modalwhite CI null gate |
Missing or hardware-mismatched DM rate f_DM |
Driving a slow DM too fast excites hardware saturation or plate resonances | No silent 1 kHz default: .dm_rate_hz = 0 fails fast unless user explicitly supplies hardware f_DM; validates f_DM <= f_presh when dmpreshaper is active |
| Dropped WFS frame under multi-rate ramp | Constant velocity extrapolates DM toward rail | 2 * T_WFS stall watchdog in mvalpacer smoothly decaying u_ramp -> 0 while holding safe u_mid |
| Subaru 4-spider island petaling at low WFS rate | > 1000 nm petal runaway at 100 Hz (0.6" seeing) |
Enforce >= 250 Hz Stage-1 faint-star floor in runner presets and pair with Stage-2 fast loop (2 kHz) when available |
| Branch & Commit Hygiene | Tangled cross-repo diffs blocking upstream merge | Keep milk (feat/bash-engine), cacao (feat/bash-engine), and milk-mltools (main) commits atomic per work package (M1–M3, C1–C4, ML1–ML2) |
Reproducibility & GitHub Provenance
- Reference Benchmarks Driving Every Requirement:
- Control Architecture & Benchmark Synthesis Report
- Interactive AO Loop Algorithmic Options Map
- Target Build & Test Verification Command:
cd /home/guyon/src/cacao-work && ./scripts/build-all.sh && source env.sh
"${PYTHON_BIN}" -m pytest -v tests/test_05_ao_web_report.py tests/test_10_dmpreshaper.py \
tests/test_17_selflearn.py tests/test_18_multirate_dm.py tests/test_19_cmodes.py