roomeq-model 0.5.5

RoomEQ configuration, pipeline, and DSP-chain contracts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
//! Room EQ Output Types
//!
//! Types for returning optimization results and DSP chain outputs.

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};

// Re-export Curve for reference in output docs
pub use crate::Curve;

// ============================================================================
// Frequency Response Curve Data
// ============================================================================

/// Frequency response curve data for serialization
///
/// Represents a curve with frequency points and SPL values.
/// SPL values are normalized (mean-subtracted in the 1000-2000 Hz range)
/// for consistent comparison across measurements.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CurveData {
    /// Frequency points in Hz
    pub freq: Vec<f64>,
    /// Sound Pressure Level in dB (normalized)
    pub spl: Vec<f64>,
    /// Phase in degrees (optional)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub phase: Option<Vec<f64>>,
    /// Optional frequency range used for normalization
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub norm_range: Option<(f64, f64)>,
}

impl From<Curve> for CurveData {
    fn from(curve: Curve) -> Self {
        CurveData {
            freq: curve.freq.to_vec(),
            spl: curve.spl.to_vec(),
            phase: curve.phase.map(|p| p.to_vec()),
            norm_range: None,
        }
    }
}

impl From<&Curve> for CurveData {
    fn from(curve: &Curve) -> Self {
        CurveData {
            freq: curve.freq.to_vec(),
            spl: curve.spl.to_vec(),
            phase: curve.phase.as_ref().map(|p| p.to_vec()),
            norm_range: None,
        }
    }
}

impl From<CurveData> for Curve {
    fn from(data: CurveData) -> Self {
        Curve {
            freq: ndarray::Array1::from(data.freq),
            spl: ndarray::Array1::from(data.spl),
            phase: data.phase.map(ndarray::Array1::from),
            ..Default::default()
        }
    }
}

// ============================================================================
// Impulse Response Waveform
// ============================================================================

pub use crate::IrWaveform;

// ============================================================================
// DSP Chain Types
// ============================================================================

/// Backwards-compatible name for the canonical DSP execution/export graph.
pub type DspChainOutput = crate::DspGraph;

/// DSP chain for a single channel
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ChannelDspChain {
    /// Channel name
    pub channel: String,
    /// Ordered list of plugins (AudioEngine PluginConfig format)
    pub plugins: Vec<PluginConfigWrapper>,
    /// Per-driver DSP chains for active crossover (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub drivers: Option<Vec<DriverDspChain>>,
    /// Initial frequency response curve before optimization (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub initial_curve: Option<CurveData>,
    /// Final frequency response curve after applying correction (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub final_curve: Option<CurveData>,
    /// EQ filter response curve (correction magnitude in dB) (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub eq_response: Option<CurveData>,
    /// Effective target curve the optimizer worked against (optional)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target_curve: Option<CurveData>,
    /// Impulse response before correction (optional, requires phase data)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pre_ir: Option<IrWaveform>,
    /// Impulse response after correction (optional, requires phase data)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub post_ir: Option<IrWaveform>,
    /// FIR impulse-response temporal masking metrics (optional, FIR/phase modes)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fir_temporal_masking: Option<crate::TemporalIrMaskingMetrics>,
    /// Direct/early/late correction-energy metrics (optional, FIR/phase modes
    /// or any channel with phase-derived IRs).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub direct_early_late_correction: Option<DirectEarlyLateCorrectionMetrics>,
}

/// DSP chain for an individual driver in a multi-driver speaker
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DriverDspChain {
    /// Driver name (e.g. "woofer", "tweeter")
    pub name: String,
    /// Driver index in the array (0 = lowest frequency)
    pub index: usize,
    /// Ordered list of plugins for this driver (gain, crossover filters)
    pub plugins: Vec<PluginConfigWrapper>,
    /// Initial frequency response curve for this driver before optimization (optional)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub initial_curve: Option<CurveData>,
}

/// Wrapper for AudioEngine PluginConfig (re-exported from src-audio)
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct PluginConfigWrapper {
    pub plugin_type: String,
    pub parameters: serde_json::Value,
}

/// Per-channel EPA psychoacoustic metrics computed on the initial
/// (pre-EQ) and final (post-EQ) frequency responses.
///
/// See [`crate::loss::epa::score::EpaScore`] for the individual fields.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct EpaChannelMetrics {
    /// EPA score computed from the initial (pre-EQ) response.
    pub pre: crate::EpaScore,
    /// EPA score computed from the final (post-EQ) response.
    pub post: crate::EpaScore,
}

/// Aggregate EPA metrics for the whole reproduced channel set.
///
/// Channels are combined with BS.1770-style energy weights before EPA scoring:
/// front/main channels use unit weight, surround channels use +1.5 dB energy
/// weight, and LFE/subwoofer channels are excluded.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct EpaMultichannelMetrics {
    /// EPA score computed from the aggregate initial (pre-EQ) response.
    pub pre: crate::EpaScore,
    /// EPA score computed from the aggregate final (post-EQ) response.
    pub post: crate::EpaScore,
    /// Human-readable aggregation standard/approximation.
    pub standard: String,
}

/// Correction-energy split across direct, early, and late IR windows.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DirectEarlyLateCorrectionMetrics {
    /// Direct-sound window end in milliseconds.
    pub direct_window_ms: f64,
    /// Early-reflection window end in milliseconds.
    pub early_window_ms: f64,
    /// Late summary window end in milliseconds.
    pub late_window_ms: f64,
    /// Correction energy in the direct window, dB relative to total correction energy.
    pub direct_energy_db: f64,
    /// Correction energy in the early window, dB relative to total correction energy.
    pub early_energy_db: f64,
    /// Correction energy in the late window, dB relative to total correction energy.
    pub late_energy_db: f64,
    /// Direct + early correction energy, dB relative to total correction energy.
    pub direct_plus_early_energy_db: f64,
    /// Advisory when FIR/mixed-phase correction may be altering direct/early cues.
    pub advisory: String,
}

/// Resolved preference-layer metadata.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct PreferenceLayerReport {
    /// Optional house curve extracted from the neutral optimizer target.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub house_curve: Option<crate::TargetShape>,
    /// User bass/treble voicing realized after neutral correction.
    pub user_preference: crate::UserPreference,
    /// Optional role/content voicing realized after neutral correction.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub role_targets: Option<crate::RoleTargetConfig>,
    /// Preference filters are excluded from correction quality scores.
    pub excluded_from_neutral_quality_score: bool,
}

/// Resolved correction/preference policy metadata.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct PerceptualPolicyReport {
    /// Policy preset requested by the user or UI.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub preset: Option<crate::PerceptualPolicyPreset>,
    /// Effective loss type after policy resolution.
    pub loss_type: String,
    /// Effective target response after policy resolution.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target_response: Option<crate::TargetResponseConfig>,
    /// Target used by the physical correction optimizer, with voicing stripped.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub neutral_target_response: Option<crate::TargetResponseConfig>,
    /// Separately bypassable post-correction listener/content voicing.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub preference_layer: Option<PreferenceLayerReport>,
    /// Effective audibility deadband.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub audibility_deadband: Option<crate::AudibilityDeadbandConfig>,
    /// Effective high-frequency safeguard.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub high_frequency_correction: Option<crate::HighFrequencyCorrectionConfig>,
}

/// Bootstrap uncertainty population.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum BootstrapUncertaintySource {
    /// Case-bootstrap over listening positions, not measurement noise.
    SpatialSeatSampling,
}

/// Bootstrap uncertainty reporting summary.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct BootstrapUncertaintyReport {
    /// Population whose variability is estimated.
    pub source: BootstrapUncertaintySource,
    /// Whether the estimator treats listening positions as independent cases.
    pub assumes_independent_positions: bool,
    /// Effective spatial sample size under the stated independence model.
    ///
    /// This equals the nominal seat count by default. A configured correlation
    /// adjustment may reduce it; this still is not a covariance/block model.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub effective_spatial_sample_size: Option<f64>,
    /// Repeat-sweep noise, absent unless separately measured.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub repeat_sweep_noise_std_db: Option<f64>,
    /// Calibration uncertainty, absent unless separately supplied.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub calibration_uncertainty_std_db: Option<f64>,
    /// Number of case-bootstrap resamples.
    pub num_resamples: usize,
    /// Two-sided alpha used for confidence bands.
    pub alpha: f64,
    /// Scalarisation used for uncertainty-aware optimization.
    pub scalarisation: crate::BootstrapScalarisation,
    /// CVaR tail fraction when scalarisation is CVaR.
    pub cvar_alpha: f64,
    /// Whether bootstrap confidence width was folded into correction-depth masks.
    pub used_for_correction_depth_mask: bool,
}

/// Validation/listening-test bundle descriptor.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ValidationBundleReport {
    /// JSON artifact path.
    pub artifact: String,
    /// Target loudness for matched validation assets.
    pub target_lufs: f64,
    /// ABX descriptor included.
    pub abx: bool,
    /// MUSHRA descriptor included.
    pub mushra: bool,
    /// Perceptual regression summary included.
    pub perceptual_regression_summary: bool,
    /// Bundle advisories.
    pub advisories: Vec<String>,
}

/// Compact perceptual scorecard for downstream QA and UIs.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct PerceptualMetrics {
    /// Average EPA preference before correction.
    pub epa_preference_pre: f64,
    /// Average EPA preference after correction.
    pub epa_preference_post: f64,
    /// EPA preference delta, positive means perceptual improvement.
    pub epa_preference_delta: f64,
    /// Midrange inter-channel deviation in dB when more than one comparable
    /// channel exists.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub channel_matching_midrange_rms_db: Option<f64>,
    /// Role-aware channel matching RMS, computed only inside comparable
    /// channel groups such as L/R, surrounds, or matching height pairs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub role_channel_matching_rms_db: Option<f64>,
    /// Bass-seat/output consistency RMS across sub/LFE outputs in the
    /// modal/crossover band. Lower is better.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bass_consistency_rms_db: Option<f64>,
    /// Center-channel dialog-band roughness after removing the local mean.
    /// Lower is better for speech intelligibility.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dialog_band_roughness_rms_db: Option<f64>,
    /// Peak positive gain requested by exported gain/EQ plugins. High values
    /// are a clipping/headroom risk even when the final curve looks smooth.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub headroom_peak_boost_db: Option<f64>,
    /// Advisory derived from `headroom_peak_boost_db`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub headroom_risk: Option<String>,
    /// Human-readable timing/GD confidence label.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timing_confidence: Option<String>,
    /// Maximum FIR pre-ringing audible energy across channels, dB relative to
    /// each FIR's main impulse peak.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fir_pre_ringing_audible_db: Option<f64>,
    /// Maximum FIR post-ringing audible energy across channels, dB relative to
    /// each FIR's main impulse peak.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fir_post_ringing_audible_db: Option<f64>,
    /// Maximum FIR temporal masking penalty across channels.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fir_temporal_masking_penalty: Option<f64>,
    /// Maximum direct + early correction energy across channels, dB relative
    /// to total correction energy.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub direct_plus_early_correction_energy_db: Option<f64>,
    /// Worst direct/early cue advisory across channels.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub early_cue_advisory: Option<String>,
}

/// Simple statistical summary for reporting.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct StatisticalSummary {
    /// Arithmetic mean.
    pub mean: f64,
    /// Standard deviation.
    pub std: f64,
}

/// Per-channel supporting-source report.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SupportingSourceReport {
    /// Whether supporting-source processing was enabled for this logical channel.
    pub enabled: bool,
    /// Name of the primary output channel.
    pub primary_output: String,
    /// Name of the supporting output channel.
    pub support_output: String,
    /// Delay applied to the supporting source in ms.
    pub delay_ms: f64,
    /// Length of the supporting-source FIR in taps.
    pub fir_length: usize,
    /// Compensation band in Hz.
    pub compensation_band_hz: (f64, f64),
    /// DRR before compensation (dB) summary, available only with time-gated
    /// impulse-response evidence.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub drr_before_db: Option<StatisticalSummary>,
    /// DRR after compensation (dB) summary, available only with time-gated
    /// impulse-response evidence.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub drr_after_db: Option<StatisticalSummary>,
    /// Whether target constraints (floor/ceiling) were active.
    pub target_constraints_active: bool,
    /// Number of frequency bins where the precedence ceiling was hit.
    pub precedence_limit_hits: usize,
    /// Optional advisories raised during processing (e.g. spatial robustness).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub advisories: Vec<String>,
}

/// Final outcome of an optional RoomEQ processing stage.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum StageStatus {
    /// The stage applied a material change.
    Applied,
    /// The stage was not applicable or no material change was needed.
    Skipped,
    /// The stage ran with reduced capabilities.
    Degraded,
    /// Invalid data or an internal error prevented the stage from running.
    Failed,
}

/// Structured stage status and machine-readable advisories.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct StageOutcome {
    /// Stable snake_case stage identifier.
    pub stage: String,
    /// Final stage status.
    pub status: StageStatus,
    /// Machine-readable reasons, warnings, or migration notices.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub advisories: Vec<String>,
}

/// Versioned optimizer-confidence evidence used by final production
/// acceptance. Superseded attempts remain visible in `runs_by_channel`, while
/// `confidence` is derived only from runs marked `selected_for_output`.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct RoomOptimizerEvidence {
    pub policy_version: String,
    pub confidence: crate::OptimizerConfidence,
    pub runs_by_channel: BTreeMap<String, Vec<crate::OptimizerRunEvidence>>,
}

/// Optimization metadata
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct OptimizationMetadata {
    /// Raw-measurement score before optimization, evaluated over the same
    /// role/crossover-aware band as `post_score`.
    pub pre_score: f64,
    /// Final deployed-response score, evaluated over the channel's
    /// role/crossover-aware band (lower is better).
    pub post_score: f64,
    /// Optimization algorithm used
    pub algorithm: String,
    /// Loss function that the optimizer minimized.
    /// One of `"flat"`, `"score"`, `"epa"`.
    ///
    /// Note: `pre_score` and `post_score` are *not* values of this loss
    /// function — they are always computed by
    /// `crate::roomeq::workflows::compute_flat_loss` over the
    /// role/crossover-aware evaluation window so that routes do not penalize
    /// intentional crossover rolloff. Runs with different `loss_type` values
    /// stay on the same scale within that channel role. To compare *perceptual* outcomes across
    /// loss types use `epa_per_channel.{pre,post}.preference` instead,
    /// which is computed identically for every run.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub loss_type: Option<String>,
    /// Number of iterations
    pub iterations: usize,
    /// Timestamp
    pub timestamp: String,
    /// Inter-channel deviation metric (computed when >1 channel)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub inter_channel_deviation: Option<crate::InterChannelDeviation>,
    /// Per-channel EPA psychoacoustic metrics (pre-EQ and post-EQ).
    /// Computed from each channel's initial and final frequency responses
    /// using the configured `EpaConfig` (or defaults when unset).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub epa_per_channel: Option<HashMap<String, EpaChannelMetrics>>,
    /// Whole-system EPA psychoacoustic metrics computed after BS.1770-style
    /// channel-energy aggregation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub epa_multichannel: Option<EpaMultichannelMetrics>,
    /// Group delay optimisation summary (GD-Opt v2, Phase GD-4).
    /// Present when GD-Opt was attempted (success or skip with advisory).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub group_delay: Option<crate::GroupDelayOptSummary>,
    /// Per-channel mixed-phase decomposition and excess-phase FIR summaries.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mixed_phase_per_channel: Option<HashMap<String, crate::MixedPhaseCorrectionReport>>,
    /// Perceptual scorecard computed from final exported curves/DSP.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub perceptual_metrics: Option<PerceptualMetrics>,
    /// Home-cinema role/layout interpretation used by role-aware scoring.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub home_cinema_layout: Option<crate::HomeCinemaLayoutReport>,
    /// Coverage summary for multi-position measurements beyond sub-only MSO.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub multi_seat_coverage: Option<crate::MultiSeatCoverageReport>,
    /// All-channel multi-seat correction summary for non-sub home-cinema channels.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub multi_seat_correction: Option<crate::MultiSeatCorrectionReport>,
    /// Bass-management policy and applied trim/headroom summary.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bass_management: Option<crate::BassManagementReport>,
    /// Timing/localization diagnostics derived from measured arrivals and
    /// final exported delay plugins.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timing_diagnostics: Option<crate::TimingDiagnosticsReport>,
    /// Cross-talk cancellation / binaural-aware correction artifact summary.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ctc: Option<crate::CtcReport>,
    /// Resolved perceptual policy metadata.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub perceptual_policy: Option<PerceptualPolicyReport>,
    /// Bootstrap uncertainty summary.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bootstrap_uncertainty: Option<BootstrapUncertaintyReport>,
    /// Validation/listening-test bundle descriptor.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub validation_bundle: Option<ValidationBundleReport>,
    /// Supporting-source room-compensation reports, keyed by logical channel.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supporting_source: Option<HashMap<String, SupportingSourceReport>>,
    /// Audibility-first acceptance decision for the final correction chain.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub correction_acceptance: Option<crate::CorrectionAcceptanceReport>,
    /// Backend termination, convergence, budget, seed, constraint, and
    /// confidence evidence for the optimizer runs that produced each channel.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub optimizer_evidence: Option<RoomOptimizerEvidence>,
    /// Structured outcomes for optional/degradable processing stages.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub stage_outcomes: Vec<StageOutcome>,
    /// Fully merged configuration used for this run. The CLI records this
    /// when `--override-config` is supplied so QA and display tooling can
    /// verify that an override did not silently replace unrelated sections.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub effective_config: Option<Box<crate::RoomConfig>>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use ndarray::Array1;

    fn sample_curve() -> Curve {
        Curve {
            freq: Array1::from(vec![100.0, 1000.0, 10000.0]),
            spl: Array1::from(vec![80.0, 82.0, 81.0]),
            phase: Some(Array1::from(vec![0.0, 45.0, 90.0])),
            ..Default::default()
        }
    }

    #[test]
    fn curve_data_from_curve_owned() {
        let curve = sample_curve();
        let data = CurveData::from(curve.clone());
        assert_eq!(data.freq, vec![100.0, 1000.0, 10000.0]);
        assert_eq!(data.spl, vec![80.0, 82.0, 81.0]);
        assert_eq!(data.phase, Some(vec![0.0, 45.0, 90.0]));
        assert!(data.norm_range.is_none());
    }

    #[test]
    fn curve_data_from_curve_ref() {
        let curve = sample_curve();
        let data = CurveData::from(&curve);
        assert_eq!(data.freq, vec![100.0, 1000.0, 10000.0]);
        assert_eq!(data.spl, vec![80.0, 82.0, 81.0]);
        assert_eq!(data.phase, Some(vec![0.0, 45.0, 90.0]));
    }

    #[test]
    fn curve_data_roundtrips_to_curve() {
        let data = CurveData {
            freq: vec![100.0, 1000.0, 10000.0],
            spl: vec![80.0, 82.0, 81.0],
            phase: Some(vec![0.0, 45.0, 90.0]),
            norm_range: Some((1000.0, 2000.0)),
        };
        let curve: Curve = data.clone().into();
        assert_eq!(curve.freq.to_vec(), data.freq);
        assert_eq!(curve.spl.to_vec(), data.spl);
        assert_eq!(curve.phase.as_ref().map(|p| p.to_vec()), data.phase);
    }

    #[test]
    fn curve_data_json_roundtrip() {
        let data = CurveData {
            freq: vec![100.0, 1000.0],
            spl: vec![80.0, 82.0],
            phase: None,
            norm_range: None,
        };
        let json = serde_json::to_string(&data).unwrap();
        let back: CurveData = serde_json::from_str(&json).unwrap();
        assert_eq!(back.freq, data.freq);
        assert_eq!(back.spl, data.spl);
        assert_eq!(back.phase, data.phase);
    }
}