Skip to main content

gammalooprs/integrate/
mod.rs

1#![allow(dead_code)]
2
3//! This module steers the integration process.
4//! It contains two main ways of integrating the integrand.
5//! The havana_integrate function is mostly used for local runs.
6//! The master node in combination with batch_integrate is for distributed runs.
7
8mod display;
9mod render_ratatui;
10mod render_tabled;
11mod status_update;
12
13use crate::integrands::process;
14use crate::integrands::process::EvaluationTarget;
15use bincode::Decode;
16use bincode::Encode;
17use color_eyre::{Report, Result};
18use colored::Colorize;
19use itertools::Itertools;
20use itertools::izip;
21use linnet::half_edge::involution::{EdgeVec, Orientation};
22use rayon::ThreadPoolBuilder;
23use serde::Deserialize;
24use serde::Serialize;
25use spenso::algebra::algebraic_traits::IsZero;
26use symbolica::domains::float::Constructible;
27use symbolica::numerical_integration::{
28    DiscreteGrid, Grid, MonteCarloRng, Sample, StatisticsAccumulator,
29};
30
31use crate::Integrand;
32use crate::graph::GroupId;
33use crate::integrands::HasIntegrand;
34use crate::integrands::evaluation::StatisticsCounter;
35use crate::integrands::evaluation::{EvaluationMetaData, EvaluationResult};
36use crate::integrands::process::GaussianReferenceFunction;
37use crate::integrands::process::{GraphTerm, ProcessIntegrand};
38use crate::model::{Model, SerializableInputParamCard};
39use crate::observables::{
40    EventGroupList, ObservableAccumulatorBundle, ObservableFileFormat, ObservableSnapshotBundle,
41};
42use crate::settings::IntegratorSettings;
43use crate::settings::RuntimeSettings;
44use crate::settings::runtime::{
45    AbsoluteIntegrationResult, ComponentDiscreteBreakdown, DiscreteBreakdown,
46    DiscreteBreakdownEntry, DiscreteCoordinate, DiscreteGraphSamplingType, IntegralEstimate,
47    IntegratedPhase, IntegrationResult, IntegrationTableComponentResult, MaxWeightInfoEntry,
48    SamplingSettings, SlotIntegrationResult,
49};
50use crate::utils;
51use crate::utils::F;
52use crate::{
53    clear_iteration_abort_request, is_interrupted, is_iteration_abort_requested, set_interrupted,
54};
55use rayon::prelude::*;
56pub use render_ratatui::RatatuiDashboardState;
57pub use render_tabled::TabledRenderOptions;
58use spenso::algebra::complex::Complex;
59pub use status_update::{
60    ContributionSortMode, IntegrationStatusKind, IntegrationStatusPhaseDisplay,
61    IntegrationStatusViewOptions, StatusUpdate,
62};
63use status_update::{
64    StatusUpdateBuildRequest, build_saved_status_update, build_status_update,
65    evaluate_target_accuracy,
66};
67use std::fs;
68use std::io::Write;
69use std::path::Path;
70use std::path::PathBuf;
71use std::time::Duration;
72use std::time::Instant;
73use tabled::{
74    Tabled,
75    builder::Builder,
76    settings::{
77        Alignment, Modify, Panel, Style,
78        object::{Columns, Rows},
79        style::HorizontalLine,
80    },
81};
82#[allow(unused_imports)]
83use tracing::{debug, error, info, trace, warn};
84
85#[derive(Clone, Copy, Debug, Default)]
86pub struct WorkspaceSnapshotControl {
87    pub write_iteration_archives: bool,
88}
89
90#[derive(Clone, Copy, Debug)]
91pub struct IterationBatchingSettings {
92    pub batch_size: Option<usize>,
93    pub batch_timing_seconds: f64,
94    pub min_time_between_status_updates_seconds: f64,
95    pub emit_live_status_updates: bool,
96    pub emit_initial_status_update: bool,
97}
98
99impl Default for IterationBatchingSettings {
100    fn default() -> Self {
101        Self {
102            batch_size: None,
103            batch_timing_seconds: 5.0,
104            min_time_between_status_updates_seconds: 0.0,
105            emit_live_status_updates: true,
106            emit_initial_status_update: true,
107        }
108    }
109}
110
111pub struct IntegrationSlot {
112    pub meta: SlotMeta,
113    pub settings: RuntimeSettings,
114    pub model: Model,
115    pub integrand: Integrand,
116    pub target: Option<Complex<F<f64>>>,
117    /// Acceptance target retained independently of worker-local process clones.
118    pub reference_gaussian: Option<GaussianReferenceFunction>,
119}
120
121impl IntegrationSlot {
122    pub fn new(
123        meta: SlotMeta,
124        settings: RuntimeSettings,
125        model: Model,
126        integrand: Integrand,
127        target: Option<Complex<F<f64>>>,
128    ) -> Self {
129        Self {
130            meta,
131            settings,
132            model,
133            integrand,
134            target,
135            reference_gaussian: None,
136        }
137    }
138}
139
140pub struct HavanaIntegrateRequest {
141    pub slots: Vec<IntegrationSlot>,
142    pub sampling_correlation_mode: SamplingCorrelationMode,
143    pub n_cores: usize,
144    pub state: Option<IntegrationState>,
145    pub workspace: Option<PathBuf>,
146    pub output_control: WorkspaceSnapshotControl,
147    pub batching: IterationBatchingSettings,
148    pub view_options: IntegrationStatusViewOptions,
149}
150
151// const N_INTEGRAND_ACCUMULATORS: usize = 2;
152
153#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Encode, Decode)]
154pub struct SlotMeta {
155    pub process_name: String,
156    pub integrand_name: String,
157}
158
159impl SlotMeta {
160    pub fn key(&self) -> String {
161        format!("{}@{}", self.process_name, self.integrand_name)
162    }
163}
164
165#[derive(Serialize, Deserialize, Clone)]
166pub struct IntegrationWorkspaceManifest {
167    #[serde(default)]
168    pub version: u32,
169    pub slots: Vec<SlotMeta>,
170    pub targets: Vec<Option<Complex<F<f64>>>>,
171    pub effective_model_parameters: Vec<SerializableInputParamCard<F<f64>>>,
172    pub integrand_fingerprints: Vec<String>,
173    /// Empty for physical workspaces; otherwise one resolved descriptor per slot.
174    #[serde(default, skip_serializing_if = "Vec::is_empty")]
175    pub reference_gaussians: Vec<Option<GaussianReferenceFunction>>,
176    #[serde(default, skip_serializing_if = "Option::is_none")]
177    pub reference_observable_convention: Option<String>,
178    pub training_slot: usize,
179    pub integrator_settings_slot: usize,
180    pub sampling_correlation_mode: SamplingCorrelationMode,
181}
182
183impl IntegrationWorkspaceManifest {
184    // Version 3 records physical absolute contributions before distinct
185    // sampling-channel points are summed. Older absolute moments cannot resume.
186    pub const CURRENT_VERSION: u32 = 3;
187
188    /// A missing descriptor requests physics. Resume never silently changes that
189    /// request into acceptance, and an unknown reporting convention cannot reuse grids.
190    pub fn validate_reference_config(
191        &self,
192        requested: &[Option<GaussianReferenceFunction>],
193    ) -> Result<()> {
194        if !self.reference_gaussians.is_empty()
195            && self.reference_gaussians.len() != self.slots.len()
196        {
197            return Err(Report::msg(
198                "Workspace reference descriptors must match its slots",
199            ));
200        }
201        for reference in self.reference_gaussians.iter().flatten() {
202            let scale = reference.expected_second_moment::<f64>().0;
203            if reference.center().is_empty() || !scale.is_finite() || scale <= 0.0 {
204                return Err(Report::msg(
205                    "Workspace reference descriptor must contain a resolved center and finite positive moment scale",
206                ));
207            }
208        }
209        let has_reference = requested.iter().any(Option::is_some);
210        let expected_convention =
211            has_reference.then_some(GaussianReferenceFunction::INTEGRATION_CONVENTION);
212        let same_config = if self.reference_gaussians.is_empty() {
213            !has_reference
214        } else {
215            self.reference_gaussians == requested
216        };
217        if !same_config || self.reference_observable_convention.as_deref() != expected_convention {
218            return Err(Report::msg(format!(
219                "Workspace physical/reference configuration does not match the request. Repeat the same --reference-gaussian descriptor to resume acceptance, or use --restart for a different target. Saved descriptors: {}",
220                serde_json::to_string(&self.reference_gaussians)?
221            )));
222        }
223        Ok(())
224    }
225
226    pub fn validate_version(&self) -> Result<()> {
227        if self.version == Self::CURRENT_VERSION {
228            return Ok(());
229        }
230
231        let reason = if self.version == 0 {
232            "is unversioned".to_string()
233        } else if self.version < Self::CURRENT_VERSION {
234            format!("uses the older format version {}", self.version)
235        } else {
236            format!("uses the newer format version {}", self.version)
237        };
238        Err(Report::msg(format!(
239            "Integration workspace {reason} and cannot be resumed by this GammaLoop build (supported version {}); use --restart to create a new workspace",
240            Self::CURRENT_VERSION
241        )))
242    }
243}
244
245impl crate::utils::serde_utils::SmartSerde for IntegrationWorkspaceManifest {}
246
247#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Encode, Decode)]
248#[serde(rename_all = "snake_case")]
249pub enum SamplingCorrelationMode {
250    Correlated,
251    Uncorrelated,
252}
253
254impl SamplingCorrelationMode {
255    fn state_index(self, slot_index: usize) -> usize {
256        match self {
257            Self::Correlated => 0,
258            Self::Uncorrelated => slot_index,
259        }
260    }
261
262    fn state_count(self, n_slots: usize) -> usize {
263        match self {
264            Self::Correlated => 1,
265            Self::Uncorrelated => n_slots,
266        }
267    }
268}
269
270#[derive(Serialize, Deserialize, Encode, Decode, Clone)]
271pub(crate) struct DiscreteGridAccumulatorSummary {
272    #[bincode(with_serde)]
273    pub(crate) bins: Vec<DiscreteGridBinAccumulatorSummary>,
274}
275
276#[derive(Serialize, Deserialize, Encode, Decode, Clone)]
277pub(crate) struct DiscreteGridBinAccumulatorSummary {
278    #[bincode(with_serde)]
279    pub(crate) accumulator: StatisticsAccumulator<F<f64>>,
280    pub(crate) sub_summary: Option<Box<DiscreteGridAccumulatorSummary>>,
281}
282
283#[derive(Serialize, Deserialize, Encode, Decode, Clone, Default)]
284struct PersistedDiscreteBreakdownMetadata {
285    axis_label: String,
286    #[bincode(with_serde)]
287    fixed_coordinates: Vec<DiscreteCoordinate>,
288    bin_labels: Vec<String>,
289}
290
291#[derive(Clone, Serialize, Deserialize, Encode, Decode)]
292struct SamplingSlotState {
293    #[bincode(with_serde)]
294    grid: Grid<F<f64>>,
295    discrete_axis_labels: Vec<String>,
296}
297
298impl SamplingSlotState {
299    fn new(grid: Grid<F<f64>>, discrete_axis_labels: Vec<String>) -> Self {
300        Self {
301            grid,
302            discrete_axis_labels,
303        }
304    }
305
306    fn from_integrand(integrand: &Integrand) -> Self {
307        let grid = integrand.create_grid();
308        let discrete_axis_labels = match integrand {
309            Integrand::ProcessIntegrand(process_integrand) => {
310                discrete_axis_labels(&process_integrand.get_settings().sampling)
311                    .into_iter()
312                    .map(str::to_string)
313                    .collect_vec()
314            }
315            #[cfg(test)]
316            Integrand::TestProbe(_) => Vec::new(),
317        };
318        Self::new(grid, discrete_axis_labels)
319    }
320}
321
322#[derive(Default)]
323struct MonitoredDiscreteSetup {
324    path: Option<Vec<usize>>,
325    axis_label: Option<String>,
326    bin_descriptions: Option<Vec<String>>,
327    warning: Option<String>,
328}
329
330#[derive(Tabled)]
331pub struct IntegralResult {
332    id: String,
333    n_samples: String,
334    #[tabled(rename = "n_samples[%]")]
335    n_samples_perc: String,
336    #[tabled(rename = "<I>")]
337    integral: String,
338    #[tabled(rename = "sqrt(σ)")]
339    variance: String,
340    err: String,
341    #[tabled(rename = "err[%]")]
342    err_perc: String,
343    #[tabled(rename = "PDF")]
344    pdf: String,
345}
346
347#[derive(Serialize, Deserialize, Encode, Decode, Clone)]
348pub struct ComplexAccumulator {
349    #[bincode(with_serde)]
350    pub re: StatisticsAccumulator<F<f64>>,
351    #[bincode(with_serde)]
352    pub im: StatisticsAccumulator<F<f64>>,
353    #[bincode(with_serde)]
354    pub absolute_re: StatisticsAccumulator<F<f64>>,
355    #[bincode(with_serde)]
356    pub absolute_im: StatisticsAccumulator<F<f64>>,
357}
358
359impl ComplexAccumulator {
360    pub(crate) fn new() -> Self {
361        Self {
362            re: StatisticsAccumulator::new(),
363            im: StatisticsAccumulator::new(),
364            absolute_re: StatisticsAccumulator::new(),
365            absolute_im: StatisticsAccumulator::new(),
366        }
367    }
368
369    /// used to escalate the stability test on high evaluation values
370    pub(crate) fn get_worst_case(&self) -> Complex<F<f64>> {
371        Complex::new(
372            self.re
373                .max_eval_positive
374                .abs()
375                .max(self.re.max_eval_negative.abs()),
376            self.im
377                .max_eval_positive
378                .abs()
379                .max(self.im.max_eval_negative.abs()),
380        )
381    }
382
383    /// add a sample to the accumulator
384    pub(crate) fn add_sample(
385        &mut self,
386        result: Complex<F<f64>>,
387        absolute_result: Option<Complex<F<f64>>>,
388        sample_weight: F<f64>,
389        sample: Option<&Sample<F<f64>>>,
390    ) {
391        let weighted_re = result.re * sample_weight;
392        let weighted_im = result.im * sample_weight;
393        self.re.add_sample(weighted_re, sample);
394        self.im.add_sample(weighted_im, sample);
395        // One outer cube is one statistical sample, including every explicitly
396        // summed channel. Squaring their summed absolute contribution retains
397        // covariance; abs of the signed channel sum would be another integral.
398        let absolute = absolute_result
399            .unwrap_or_else(|| Complex::new(result.re.abs(), result.im.abs()))
400            * sample_weight.abs();
401        self.absolute_re.add_sample(absolute.re, sample);
402        self.absolute_im.add_sample(absolute.im, sample);
403    }
404
405    pub(crate) fn merge(&mut self, other: &Self) {
406        self.re.merge_samples_no_reset(&other.re);
407        self.im.merge_samples_no_reset(&other.im);
408        self.absolute_re.merge_samples_no_reset(&other.absolute_re);
409        self.absolute_im.merge_samples_no_reset(&other.absolute_im);
410    }
411
412    pub(crate) fn update_iter(&mut self, use_weighted_average: bool) {
413        self.re.update_iter(use_weighted_average);
414        self.im.update_iter(use_weighted_average);
415        self.absolute_re.update_iter(use_weighted_average);
416        self.absolute_im.update_iter(use_weighted_average);
417    }
418
419    pub(crate) fn max_weight_rows(
420        &self,
421        slot_meta: &SlotMeta,
422        discrete_axis_labels: &[String],
423    ) -> Vec<[String; 3]> {
424        let max_evals = [
425            &self.re.max_eval_positive,
426            &self.re.max_eval_negative,
427            &self.im.max_eval_positive,
428            &self.im.max_eval_negative,
429        ];
430
431        let max_eval_samples = [
432            &self.re.max_eval_positive_xs,
433            &self.re.max_eval_negative_xs,
434            &self.im.max_eval_positive_xs,
435            &self.im.max_eval_negative_xs,
436        ];
437
438        let sign_strs = ["+", "-", "+", "-"];
439        let phase_strs = ["re", "re", "im", "im"];
440
441        izip!(
442            max_evals.iter(),
443            max_eval_samples.iter(),
444            sign_strs.iter(),
445            phase_strs.iter()
446        )
447        .filter_map(|(max_eval, max_eval_sample, sign_str, phase_str)| {
448            if max_eval.is_non_zero() {
449                Some([
450                    format!(
451                        "{} {} [{}] ",
452                        slot_label(slot_meta),
453                        format!("{:<2}", phase_str).blue(),
454                        format!("{:<1}", sign_str).blue()
455                    ),
456                    format!("{:+.16e}", max_eval),
457                    if let Some(sample) = max_eval_sample {
458                        format_max_eval_sample(sample, discrete_axis_labels, &[])
459                    } else {
460                        "N/A".to_string()
461                    },
462                ])
463            } else {
464                None
465            }
466        })
467        .collect()
468    }
469}
470
471impl DiscreteGridAccumulatorSummary {
472    fn from_grid(grid: &Grid<F<f64>>) -> Option<Self> {
473        match grid {
474            Grid::Discrete(discrete_grid) => Some(Self {
475                bins: discrete_grid
476                    .bins
477                    .iter()
478                    .map(|bin| DiscreteGridBinAccumulatorSummary {
479                        accumulator: StatisticsAccumulator::new(),
480                        sub_summary: bin
481                            .sub_grid
482                            .as_ref()
483                            .and_then(Self::from_grid)
484                            .map(Box::new),
485                    })
486                    .collect(),
487            }),
488            Grid::Continuous(_) | Grid::Uniform(_, _) => None,
489        }
490    }
491
492    fn merge_iteration_grid(&mut self, grid: &Grid<F<f64>>) {
493        let Grid::Discrete(discrete_grid) = grid else {
494            return;
495        };
496
497        for (summary_bin, grid_bin) in self.bins.iter_mut().zip(discrete_grid.bins.iter()) {
498            summary_bin
499                .accumulator
500                .merge_samples_no_reset(&grid_bin.accumulator);
501            if let (Some(sub_summary), Some(sub_grid)) =
502                (summary_bin.sub_summary.as_mut(), grid_bin.sub_grid.as_ref())
503            {
504                sub_summary.merge_iteration_grid(sub_grid);
505            }
506        }
507    }
508
509    fn from_shallow_grid(grid: &DiscreteGrid<F<f64>>) -> Self {
510        Self {
511            bins: grid
512                .bins
513                .iter()
514                .map(|_| DiscreteGridBinAccumulatorSummary {
515                    accumulator: StatisticsAccumulator::new(),
516                    sub_summary: None,
517                })
518                .collect(),
519        }
520    }
521
522    fn merge_shallow_iteration_grid(&mut self, grid: &DiscreteGrid<F<f64>>) {
523        assert_eq!(
524            self.bins.len(),
525            grid.bins.len(),
526            "absolute monitor grid shape changed unexpectedly"
527        );
528        for (summary_bin, grid_bin) in self.bins.iter_mut().zip(&grid.bins) {
529            assert!(
530                summary_bin.sub_summary.is_none() && grid_bin.sub_grid.is_none(),
531                "absolute monitor grids must not contain descendants"
532            );
533            summary_bin
534                .accumulator
535                .merge_samples_no_reset(&grid_bin.accumulator);
536        }
537    }
538
539    fn update_iter(&mut self) {
540        for bin in &mut self.bins {
541            bin.accumulator.update_iter(false);
542            if let Some(sub_summary) = bin.sub_summary.as_mut() {
543                sub_summary.update_iter();
544            }
545        }
546    }
547
548    fn first_non_trivial_breakdown(
549        &self,
550        metadata: &PersistedDiscreteBreakdownMetadata,
551        pdfs: &[F<f64>],
552    ) -> Option<DiscreteBreakdown> {
553        (!self.bins.is_empty()).then(|| DiscreteBreakdown {
554            axis_label: metadata.axis_label.clone(),
555            fixed_coordinates: metadata.fixed_coordinates.clone(),
556            entries: self
557                .bins
558                .iter()
559                .enumerate()
560                .map(|(bin_index, bin)| DiscreteBreakdownEntry {
561                    bin_index,
562                    bin_label: metadata.bin_labels.get(bin_index).cloned(),
563                    pdf: pdfs.get(bin_index).copied().unwrap_or(F(0.0)),
564                    value: bin.accumulator.avg,
565                    error: bin.accumulator.err,
566                    chi_sq: bin.accumulator.chi_sq,
567                    processed_samples: bin.accumulator.processed_samples,
568                })
569                .collect(),
570        })
571    }
572}
573
574struct IntegralResultCells {
575    integrand: String,
576    value: String,
577    relative_error: String,
578    chi_sq: String,
579    delta_sigma: Option<String>,
580    delta_percent: Option<String>,
581    mwi: String,
582}
583
584const DEFAULT_MAX_SHARED_TABLE_WIDTH: usize = 250;
585
586fn slot_label(slot_meta: &SlotMeta) -> String {
587    format!("itg {}", slot_meta.key())
588}
589
590fn slot_key_label(slot_meta: &SlotMeta) -> String {
591    slot_meta.key()
592}
593
594fn format_max_eval_coordinate(value: F<f64>) -> String {
595    let formatted = format!("{:.16e}", value.0);
596    let Some((mantissa, exponent)) = formatted.rsplit_once('e') else {
597        return formatted;
598    };
599    let exponent = exponent.parse::<i32>().unwrap_or_default();
600    format!("{mantissa}e{exponent:+03}")
601}
602
603fn format_max_eval_coordinates(xs: &[F<f64>]) -> String {
604    if xs.len() <= 3 {
605        return format!(
606            "[ {} ]",
607            xs.iter()
608                .map(|value| format_max_eval_coordinate(*value))
609                .join(" ")
610        );
611    }
612
613    let rows = xs
614        .chunks(3)
615        .map(|chunk| {
616            chunk
617                .iter()
618                .map(|value| format_max_eval_coordinate(*value))
619                .join(" ")
620        })
621        .join("\n");
622    format!("[\n{rows} ]")
623}
624
625pub(crate) fn discrete_axis_label(axis_labels: &[String], depth: usize) -> &str {
626    axis_labels.get(depth).map(String::as_str).unwrap_or("idx")
627}
628
629fn append_max_eval_sample_parts(
630    sample: &Sample<F<f64>>,
631    axis_labels: &[String],
632    depth: usize,
633    parts: &mut Vec<String>,
634) {
635    match sample {
636        Sample::Continuous(_, xs) => {
637            parts.push(format!("xs: {}", format_max_eval_coordinates(xs)));
638        }
639        Sample::Discrete(_, index, Some(nested_sample)) => {
640            parts.push(format!(
641                "{}: {}",
642                discrete_axis_label(axis_labels, depth),
643                index
644            ));
645            append_max_eval_sample_parts(nested_sample, axis_labels, depth + 1, parts);
646        }
647        Sample::Discrete(_, index, None) => {
648            parts.push(format!(
649                "{}: {}",
650                discrete_axis_label(axis_labels, depth),
651                index
652            ));
653        }
654        Sample::Uniform(_, indices, xs) => {
655            for (offset, index) in indices.iter().enumerate() {
656                parts.push(format!(
657                    "{}: {}",
658                    discrete_axis_label(axis_labels, depth + offset),
659                    index
660                ));
661            }
662            parts.push(format!("xs: {}", format_max_eval_coordinates(xs)));
663        }
664    }
665}
666
667fn format_max_eval_sample(
668    sample: &Sample<F<f64>>,
669    axis_labels: &[String],
670    prefix_path: &[usize],
671) -> String {
672    let mut parts = prefix_path
673        .iter()
674        .enumerate()
675        .map(|(depth, index)| format!("{}: {}", discrete_axis_label(axis_labels, depth), index))
676        .collect_vec();
677    append_max_eval_sample_parts(sample, axis_labels, prefix_path.len(), &mut parts);
678    if parts.is_empty() {
679        String::from("N/A")
680    } else {
681        parts.join(", ")
682    }
683}
684
685fn format_iteration_points(points: usize) -> String {
686    format_abbreviated_count(points)
687}
688
689fn format_total_points(points: usize) -> String {
690    format_abbreviated_count(points)
691}
692
693#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
694enum ComponentKind {
695    Real,
696    Imag,
697}
698
699impl ComponentKind {
700    fn all_for_display(display: IntegrationStatusPhaseDisplay) -> Vec<Self> {
701        let mut components = Vec::new();
702        if display.shows_real() {
703            components.push(Self::Real);
704        }
705        if display.shows_imag() {
706            components.push(Self::Imag);
707        }
708        components
709    }
710
711    fn tag(self) -> &'static str {
712        match self {
713            Self::Real => "re",
714            Self::Imag => "im",
715        }
716    }
717
718    fn colorized_tag(self) -> String {
719        self.tag().blue().bold().to_string()
720    }
721}
722
723#[derive(Clone, Copy, Debug, Eq, PartialEq)]
724enum ContributionKind {
725    All,
726    Sum,
727    Bin(usize),
728}
729
730impl ContributionKind {
731    fn label(self, integration_state: &IntegrationState) -> String {
732        match self {
733            Self::All => "All".bold().green().to_string(),
734            Self::Sum => "Sum".bold().green().to_string(),
735            Self::Bin(bin_index) => contribution_bin_label(integration_state, bin_index),
736        }
737    }
738}
739
740#[derive(Clone, Debug)]
741struct DiscreteLevelContext {
742    path: Vec<usize>,
743    pdfs: Vec<F<f64>>,
744}
745
746fn first_non_trivial_discrete_path(grid: &Grid<F<f64>>) -> Option<Vec<usize>> {
747    match grid {
748        Grid::Discrete(discrete_grid) => {
749            if discrete_grid.bins.len() > 1 {
750                Some(Vec::new())
751            } else {
752                discrete_grid
753                    .bins
754                    .first()
755                    .and_then(|bin| bin.sub_grid.as_ref())
756                    .and_then(first_non_trivial_discrete_path)
757                    .map(|mut path| {
758                        path.insert(0, 0);
759                        path
760                    })
761            }
762        }
763        Grid::Continuous(_) | Grid::Uniform(_, _) => None,
764    }
765}
766
767fn discrete_grid_at_path<'a>(
768    grid: &'a Grid<F<f64>>,
769    path: &[usize],
770) -> Option<&'a DiscreteGrid<F<f64>>> {
771    match (grid, path.split_first()) {
772        (Grid::Discrete(discrete_grid), None) => Some(discrete_grid),
773        (Grid::Discrete(discrete_grid), Some((bin_index, rest))) => discrete_grid
774            .bins
775            .get(*bin_index)?
776            .sub_grid
777            .as_ref()
778            .and_then(|sub_grid| discrete_grid_at_path(sub_grid, rest)),
779        (Grid::Continuous(_) | Grid::Uniform(_, _), _) => None,
780    }
781}
782
783fn shallow_discrete_monitor_grid(
784    grid: &Grid<F<f64>>,
785    path: &[usize],
786) -> Result<DiscreteGrid<F<f64>>> {
787    let source = discrete_grid_at_path(grid, path).ok_or_else(|| {
788        Report::msg(format!(
789            "monitored discrete path {path:?} does not match the sampling grid"
790        ))
791    })?;
792    if source.bins.is_empty() {
793        return Err(Report::msg(format!(
794            "monitored discrete path {path:?} resolves to an empty grid"
795        )));
796    }
797
798    let mut monitor =
799        DiscreteGrid::new(vec![None; source.bins.len()], F(1.0), false).map_err(Report::msg)?;
800    for (monitor_bin, source_bin) in monitor.bins.iter_mut().zip(&source.bins) {
801        monitor_bin.pdf = source_bin.pdf;
802    }
803    Ok(monitor)
804}
805
806fn discrete_sample_at_path<'a>(
807    sample: &'a Sample<F<f64>>,
808    path: &[usize],
809) -> Result<&'a Sample<F<f64>>> {
810    let mut local_sample = sample;
811    for (depth, expected_index) in path.iter().copied().enumerate() {
812        let Sample::Discrete(_, sampled_index, sub_sample) = local_sample else {
813            return Err(Report::msg(format!(
814                "sample does not contain the discrete monitor path {path:?} at depth {depth}"
815            )));
816        };
817        if *sampled_index != expected_index {
818            return Err(Report::msg(format!(
819                "sample index {sampled_index} does not match monitored path index {expected_index} at depth {depth}"
820            )));
821        }
822        local_sample = sub_sample.as_deref().ok_or_else(|| {
823            Report::msg(format!(
824                "sample ends before the discrete monitor path {path:?} at depth {depth}"
825            ))
826        })?;
827    }
828    Ok(local_sample)
829}
830
831fn add_shallow_monitor_sample(
832    monitor: Option<&mut DiscreteGrid<F<f64>>>,
833    monitored_path: Option<&[usize]>,
834    sample: &Sample<F<f64>>,
835    evaluation: F<f64>,
836) -> Result<()> {
837    let (monitor, path) = match (monitor, monitored_path) {
838        (Some(monitor), Some(path)) => (monitor, path),
839        (None, None) => return Ok(()),
840        _ => {
841            return Err(Report::msg(
842                "absolute monitor grid and monitored path are inconsistent",
843            ));
844        }
845    };
846    let local_sample = discrete_sample_at_path(sample, path)?;
847    let Sample::Discrete(_, bin_index, _) = local_sample else {
848        return Err(Report::msg(format!(
849            "sample at monitored discrete path {path:?} is not discrete"
850        )));
851    };
852    if *bin_index >= monitor.bins.len() {
853        return Err(Report::msg(format!(
854            "sample bin {bin_index} is out of bounds for absolute monitor with {} bins at path {path:?}",
855            monitor.bins.len()
856        )));
857    }
858    monitor
859        .add_training_sample(local_sample, evaluation.abs())
860        .map_err(Report::msg)
861}
862
863fn summary_at_path<'a>(
864    summary: &'a DiscreteGridAccumulatorSummary,
865    path: &[usize],
866) -> Option<&'a DiscreteGridAccumulatorSummary> {
867    match path.split_first() {
868        None => Some(summary),
869        Some((bin_index, rest)) => summary
870            .bins
871            .get(*bin_index)?
872            .sub_summary
873            .as_deref()
874            .and_then(|sub_summary| summary_at_path(sub_summary, rest)),
875    }
876}
877
878fn first_non_trivial_discrete_context(
879    sampling_grid: &Grid<F<f64>>,
880) -> Option<DiscreteLevelContext> {
881    let path = first_non_trivial_discrete_path(sampling_grid)?;
882    let discrete_grid = discrete_grid_at_path(sampling_grid, &path)?;
883    Some(DiscreteLevelContext {
884        path,
885        pdfs: discrete_grid.bins.iter().map(|bin| bin.pdf).collect(),
886    })
887}
888
889fn discrete_axis_labels(sampling: &SamplingSettings) -> Vec<&'static str> {
890    match sampling {
891        SamplingSettings::Default(_) | SamplingSettings::MultiChanneling(_) => Vec::new(),
892        SamplingSettings::DiscreteGraphs(settings) => {
893            let mut labels = vec!["graph"];
894            match &settings.sampling_type {
895                DiscreteGraphSamplingType::Default(_)
896                | DiscreteGraphSamplingType::MultiChanneling(_)
897                | DiscreteGraphSamplingType::TropicalSampling(_) => {
898                    if settings.sample_orientations {
899                        labels.push("orientation");
900                    }
901                }
902                DiscreteGraphSamplingType::SamplingMultiChanneling(_) => {
903                    if settings.sample_orientations {
904                        labels.push("orientation");
905                    }
906                    labels.push("sampling channel");
907                }
908            }
909            labels
910        }
911    }
912}
913
914fn orientation_description(orientation: &EdgeVec<Orientation>) -> String {
915    orientation
916        .iter()
917        .map(|(_, orientation)| match *orientation {
918            Orientation::Default => '+',
919            Orientation::Reversed => '-',
920            Orientation::Undirected => '0',
921        })
922        .collect()
923}
924
925fn graph_group_description<I>(graph_names: I) -> String
926where
927    I: IntoIterator<Item = String>,
928{
929    let graph_names = graph_names.into_iter().collect_vec();
930    if graph_names.len() <= 1 {
931        return graph_names.into_iter().next().unwrap_or_default();
932    }
933
934    format!("[{}]", graph_names.join(","))
935}
936
937fn first_non_trivial_discrete_bin_descriptions_for_process_integrand(
938    integrand: &ProcessIntegrand,
939    path: &[usize],
940    axis_label: &str,
941) -> Option<Vec<String>> {
942    match (integrand, axis_label) {
943        (ProcessIntegrand::Amplitude(integrand), "graph") => {
944            Some(
945                integrand
946                    .data
947                    .graph_group_structure
948                    .iter()
949                    .map(|group| {
950                        graph_group_description(group.into_iter().map(|graph_id| {
951                            integrand.data.graph_terms[graph_id].graph.name.clone()
952                        }))
953                    })
954                    .collect(),
955            )
956        }
957        (ProcessIntegrand::CrossSection(integrand), "graph") => {
958            Some(
959                integrand
960                    .data
961                    .graph_group_structure
962                    .iter()
963                    .map(|group| {
964                        graph_group_description(group.into_iter().map(|graph_id| {
965                            integrand.data.graph_terms[graph_id].graph.name.clone()
966                        }))
967                    })
968                    .collect(),
969            )
970        }
971        (ProcessIntegrand::Amplitude(integrand), "orientation") => {
972            let group_id = GroupId(*path.first()?);
973            let group = integrand.data.graph_group_structure.get(group_id)?;
974            let master = group.master();
975            Some(
976                integrand.data.graph_terms[master]
977                    .orientations
978                    .iter()
979                    .map(orientation_description)
980                    .collect(),
981            )
982        }
983        (ProcessIntegrand::CrossSection(integrand), "orientation") => {
984            let group_id = GroupId(*path.first()?);
985            let group = integrand.data.graph_group_structure.get(group_id)?;
986            let master = group.master();
987            Some(
988                integrand.data.graph_terms[master]
989                    .orientations
990                    .iter()
991                    .map(orientation_description)
992                    .collect(),
993            )
994        }
995        (ProcessIntegrand::Amplitude(integrand), "sampling channel") => {
996            let group_id = GroupId(*path.first()?);
997            let group = integrand.data.graph_group_structure.get(group_id)?;
998            let master = group.master();
999            let graph_term = &integrand.data.graph_terms[master];
1000            let parameterization_settings = integrand
1001                .settings
1002                .sampling
1003                .get_parameterization_settings()
1004                .unwrap_or_default();
1005            let channel_ids = graph_term
1006                .sampling_channel_ids(&parameterization_settings)
1007                .ok()?;
1008            Some(
1009                channel_ids
1010                    .iter()
1011                    .map(|&channel_id| {
1012                        graph_term
1013                            .sampling_channel_label(channel_id, &parameterization_settings)
1014                            .ok()
1015                            .flatten()
1016                            .unwrap_or_else(|| format!("#{}", channel_id.index()))
1017                    })
1018                    .collect(),
1019            )
1020        }
1021        (ProcessIntegrand::CrossSection(integrand), "sampling channel") => {
1022            let group_id = GroupId(*path.first()?);
1023            let group = integrand.data.graph_group_structure.get(group_id)?;
1024            let master = group.master();
1025            let graph_term = &integrand.data.graph_terms[master];
1026            let parameterization_settings = integrand
1027                .settings
1028                .sampling
1029                .get_parameterization_settings()
1030                .unwrap_or_default();
1031            let channel_ids = graph_term
1032                .sampling_channel_ids(&parameterization_settings)
1033                .ok()?;
1034            Some(
1035                channel_ids
1036                    .iter()
1037                    .map(|&channel_id| {
1038                        graph_term
1039                            .sampling_channel_label(channel_id, &parameterization_settings)
1040                            .ok()
1041                            .flatten()
1042                            .unwrap_or_else(|| format!("#{}", channel_id.index()))
1043                    })
1044                    .collect(),
1045            )
1046        }
1047        _ => None,
1048    }
1049}
1050
1051fn first_non_trivial_discrete_bin_descriptions_for_integrand(
1052    integrand: &Integrand,
1053    path: &[usize],
1054    axis_label: &str,
1055) -> Option<Vec<String>> {
1056    match integrand {
1057        Integrand::ProcessIntegrand(process_integrand) => {
1058            first_non_trivial_discrete_bin_descriptions_for_process_integrand(
1059                process_integrand,
1060                path,
1061                axis_label,
1062            )
1063        }
1064        #[cfg(test)]
1065        Integrand::TestProbe(_) => None,
1066    }
1067}
1068
1069fn discrete_coordinate_label(
1070    integrand: &Integrand,
1071    path_prefix: &[usize],
1072    axis_label: &str,
1073    bin_index: usize,
1074) -> Option<String> {
1075    first_non_trivial_discrete_bin_descriptions_for_integrand(integrand, path_prefix, axis_label)?
1076        .get(bin_index)
1077        .cloned()
1078}
1079
1080fn build_persisted_discrete_breakdown_metadata(
1081    integrand: &Integrand,
1082    path: &[usize],
1083    discrete_axis_labels: &[String],
1084) -> Option<PersistedDiscreteBreakdownMetadata> {
1085    let axis_label = discrete_axis_labels.get(path.len())?.clone();
1086    let bin_labels =
1087        first_non_trivial_discrete_bin_descriptions_for_integrand(integrand, path, &axis_label)?;
1088
1089    let fixed_coordinates = path
1090        .iter()
1091        .enumerate()
1092        .map(|(axis_index, &bin_index)| {
1093            let fixed_axis_label = discrete_axis_labels.get(axis_index)?.clone();
1094            Some(DiscreteCoordinate {
1095                axis_label: fixed_axis_label.clone(),
1096                bin_index,
1097                bin_label: discrete_coordinate_label(
1098                    integrand,
1099                    &path[..axis_index],
1100                    &fixed_axis_label,
1101                    bin_index,
1102                ),
1103            })
1104        })
1105        .collect::<Option<Vec<_>>>()?;
1106
1107    Some(PersistedDiscreteBreakdownMetadata {
1108        axis_label,
1109        fixed_coordinates,
1110        bin_labels,
1111    })
1112}
1113
1114fn monitored_discrete_layout(
1115    grid: &Grid<F<f64>>,
1116    discrete_axis_labels: &[String],
1117    monitor_explicit_graph_subset: bool,
1118) -> Option<(Vec<usize>, String, usize)> {
1119    let path = if monitor_explicit_graph_subset
1120        && discrete_axis_labels
1121            .first()
1122            .is_some_and(|label| label == "graph")
1123        && matches!(grid, Grid::Discrete(_))
1124    {
1125        Vec::new()
1126    } else {
1127        first_non_trivial_discrete_path(grid)?
1128    };
1129    let axis_label = discrete_axis_labels.get(path.len())?.clone();
1130    let discrete_grid = discrete_grid_at_path(grid, &path)?;
1131    Some((path, axis_label, discrete_grid.bins.len()))
1132}
1133
1134fn coalesce_first_non_trivial_discrete_bin_descriptions(
1135    axis_label: &str,
1136    slot_descriptions: &[(String, Vec<String>)],
1137) -> (Option<Vec<String>>, Option<String>) {
1138    let Some((reference_slot, reference_descriptions)) = slot_descriptions.first() else {
1139        return (None, None);
1140    };
1141
1142    if let Some((slot_key, _)) = slot_descriptions
1143        .iter()
1144        .skip(1)
1145        .find(|(_, descriptions)| descriptions != reference_descriptions)
1146    {
1147        return (
1148            None,
1149            Some(format!(
1150                "Selected integrands do not share the same semantic labels for the monitored discrete dimension '{axis_label}' ({} vs {}). Falling back to raw bin indices in integration reporting.",
1151                reference_slot.blue(),
1152                slot_key.blue()
1153            )),
1154        );
1155    }
1156
1157    (Some(reference_descriptions.clone()), None)
1158}
1159
1160fn resolve_first_non_trivial_discrete_bin_descriptions(
1161    slots: &[IntegrationSlot],
1162    monitored_path: &[usize],
1163    axis_label: &str,
1164) -> (Option<Vec<String>>, Option<String>) {
1165    let Some(slot_descriptions) = slots
1166        .iter()
1167        .map(|slot| {
1168            first_non_trivial_discrete_bin_descriptions_for_integrand(
1169                &slot.integrand,
1170                monitored_path,
1171                axis_label,
1172            )
1173            .map(|descriptions| (slot.meta.key(), descriptions))
1174        })
1175        .collect::<Option<Vec<_>>>()
1176    else {
1177        return (None, None);
1178    };
1179
1180    coalesce_first_non_trivial_discrete_bin_descriptions(axis_label, &slot_descriptions)
1181}
1182
1183fn resolve_monitored_discrete_setup(
1184    sampling_correlation_mode: SamplingCorrelationMode,
1185    slots: &[IntegrationSlot],
1186    sampling_states: &[SamplingSlotState],
1187) -> MonitoredDiscreteSetup {
1188    let Some(reference_state) = sampling_states.first() else {
1189        return MonitoredDiscreteSetup::default();
1190    };
1191    let Some(reference_slot) = slots.first() else {
1192        return MonitoredDiscreteSetup::default();
1193    };
1194    let monitor_explicit_graph_subset = !reference_slot
1195        .settings
1196        .sampling
1197        .selected_graph_names()
1198        .is_empty();
1199
1200    let Some((reference_path, reference_axis_label, reference_bin_count)) =
1201        monitored_discrete_layout(
1202            &reference_state.grid,
1203            &reference_state.discrete_axis_labels,
1204            monitor_explicit_graph_subset,
1205        )
1206    else {
1207        return MonitoredDiscreteSetup::default();
1208    };
1209
1210    if sampling_correlation_mode == SamplingCorrelationMode::Uncorrelated {
1211        for (slot_index, sampling_state) in sampling_states.iter().enumerate().skip(1) {
1212            let Some((path, axis_label, bin_count)) = monitored_discrete_layout(
1213                &sampling_state.grid,
1214                &sampling_state.discrete_axis_labels,
1215                !slots[slot_index]
1216                    .settings
1217                    .sampling
1218                    .selected_graph_names()
1219                    .is_empty(),
1220            ) else {
1221                return MonitoredDiscreteSetup {
1222                    warning: Some(
1223                        "Selected integrands do not all expose a compatible first non-trivial monitored discrete dimension. Shared discrete-bin monitoring tables will be disabled."
1224                            .to_string(),
1225                    ),
1226                    ..MonitoredDiscreteSetup::default()
1227                };
1228            };
1229
1230            if path != reference_path
1231                || axis_label != reference_axis_label
1232                || bin_count != reference_bin_count
1233            {
1234                return MonitoredDiscreteSetup {
1235                    warning: Some(format!(
1236                        "Selected integrands do not share a compatible first non-trivial monitored discrete layout (mismatch at {}). Shared discrete-bin monitoring tables will be disabled.",
1237                        slots[slot_index].meta.key().blue()
1238                    )),
1239                    ..MonitoredDiscreteSetup::default()
1240                };
1241            }
1242        }
1243    }
1244
1245    let (descriptions, label_warning) = resolve_first_non_trivial_discrete_bin_descriptions(
1246        slots,
1247        &reference_path,
1248        &reference_axis_label,
1249    );
1250
1251    MonitoredDiscreteSetup {
1252        path: Some(reference_path),
1253        axis_label: Some(reference_axis_label),
1254        bin_descriptions: descriptions,
1255        warning: label_warning,
1256    }
1257}
1258
1259fn render_orientation_description(description: &str) -> String {
1260    description
1261        .chars()
1262        .map(|sign| match sign {
1263            '+' => "+".green().bold().to_string(),
1264            '-' => "-".red().bold().to_string(),
1265            '0' => "0".dimmed().to_string(),
1266            other => other.to_string(),
1267        })
1268        .join("")
1269}
1270
1271fn render_graph_description(description: &str) -> String {
1272    if let Some(inner) = description
1273        .strip_prefix('[')
1274        .and_then(|trimmed| trimmed.strip_suffix(']'))
1275    {
1276        let names = inner
1277            .split(',')
1278            .filter(|name| !name.is_empty())
1279            .collect_vec();
1280        if names.is_empty() {
1281            return description.bold().green().to_string();
1282        }
1283
1284        let rendered = names
1285            .into_iter()
1286            .enumerate()
1287            .map(|(index, name)| {
1288                if index == 0 {
1289                    name.bold().green().to_string()
1290                } else {
1291                    name.bold().blue().to_string()
1292                }
1293            })
1294            .join(",");
1295        return format!("[{rendered}]");
1296    }
1297
1298    description.bold().green().to_string()
1299}
1300
1301fn render_bin_description(axis_label: &str, description: &str) -> String {
1302    match axis_label {
1303        "orientation" => render_orientation_description(description),
1304        "graph" => render_graph_description(description),
1305        _ => description.bold().green().to_string(),
1306    }
1307}
1308
1309fn contribution_bin_label(integration_state: &IntegrationState, bin_index: usize) -> String {
1310    if let (Some(axis_label), Some(descriptions)) = (
1311        integration_state
1312            .first_non_trivial_discrete_label
1313            .as_deref(),
1314        integration_state
1315            .first_non_trivial_discrete_bin_descriptions
1316            .as_ref(),
1317    ) && let Some(description) = descriptions.get(bin_index)
1318    {
1319        return format!(
1320            "#{bin_index}: {}",
1321            render_bin_description(axis_label, description)
1322        );
1323    }
1324
1325    format!("#{bin_index}")
1326}
1327
1328fn contribution_header_label(
1329    integration_state: &IntegrationState,
1330    discrete_monitoring_enabled: bool,
1331) -> String {
1332    if discrete_monitoring_enabled
1333        && let Some(label) = integration_state
1334            .first_non_trivial_discrete_label
1335            .as_deref()
1336    {
1337        return format!("Contribution (idx={label})")
1338            .bold()
1339            .blue()
1340            .to_string();
1341    }
1342
1343    "Contribution".bold().blue().to_string()
1344}
1345
1346fn format_percentage_sig(value: f64, significant_digits: usize) -> String {
1347    if !value.is_finite() {
1348        return "None".red().to_string();
1349    }
1350
1351    if value == 0.0 {
1352        let decimals = significant_digits.saturating_sub(1);
1353        return format!("{:.*}%", decimals, 0.0);
1354    }
1355
1356    let abs_value = value.abs();
1357    let exponent = abs_value.log10().floor() as i32;
1358    if exponent < -2 || exponent >= significant_digits as i32 {
1359        return format!("{:.*e}%", significant_digits.saturating_sub(1), value);
1360    }
1361
1362    let decimals = (significant_digits as i32 - exponent - 1).max(0) as usize;
1363    format!("{value:.decimals$}%")
1364}
1365
1366#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1367enum UncertaintyNotation {
1368    Dynamic,
1369    Scientific,
1370}
1371
1372fn format_significant_percentage(
1373    value: f64,
1374    significant_digits: usize,
1375    scientific_threshold: Option<(f64, f64)>,
1376) -> String {
1377    if !value.is_finite() {
1378        return "None".red().to_string();
1379    }
1380
1381    if value == 0.0 {
1382        return format!("{:.*}%", significant_digits.saturating_sub(1), 0.0);
1383    }
1384
1385    let abs_value = value.abs();
1386    if scientific_threshold.is_some_and(|(upper, lower)| abs_value >= upper || abs_value < lower) {
1387        return format!("{:.*e}%", significant_digits.saturating_sub(1), value);
1388    }
1389
1390    let exponent = abs_value.log10().floor() as i32;
1391    let decimals = (significant_digits as i32 - exponent - 1).max(0) as usize;
1392    format!("{value:.decimals$}%")
1393}
1394
1395fn should_use_scientific_uncertainty_notation(avg: F<f64>, err: F<f64>) -> bool {
1396    let avg_abs = avg.abs().0;
1397    let err_abs = err.abs().0;
1398    avg_abs >= 1e6
1399        || (avg_abs != 0.0 && avg_abs < 1e-5)
1400        || (avg.is_zero() && !(1e-4..1e5).contains(&err_abs))
1401}
1402
1403fn format_uncertainty_with_notation(
1404    avg: F<f64>,
1405    err: F<f64>,
1406    notation: UncertaintyNotation,
1407) -> String {
1408    if !matches!(notation, UncertaintyNotation::Scientific)
1409        && !should_use_scientific_uncertainty_notation(avg, err)
1410    {
1411        return utils::format_uncertainty(avg, err);
1412    }
1413
1414    if !avg.0.is_finite() || !err.0.is_finite() {
1415        return utils::format_uncertainty(avg, err);
1416    }
1417
1418    let exponent = if avg.is_non_zero() {
1419        avg.abs().0.log10().floor() as i32
1420    } else if err.is_non_zero() {
1421        err.abs().0.log10().floor() as i32
1422    } else {
1423        0
1424    };
1425    let scale = 10_f64.powi(exponent);
1426    let mantissa = utils::format_uncertainty(F(avg.0 / scale), F(err.0 / scale));
1427    format!("{mantissa}e{exponent}")
1428}
1429
1430fn format_signed_uncertainty(avg: F<f64>, err: F<f64>, notation: UncertaintyNotation) -> String {
1431    let formatted = format_uncertainty_with_notation(avg, err, notation);
1432    if avg.0.is_sign_negative() {
1433        formatted
1434    } else {
1435        format!("+{formatted}")
1436    }
1437}
1438
1439fn format_abbreviated_count(value: usize) -> String {
1440    if value < 1_000 {
1441        return value.to_string();
1442    }
1443
1444    let value = value as f64;
1445    if value < 1_000_000.0 {
1446        return format!("{:.2}K", value / 1_000.0);
1447    }
1448    if value < 1_000_000_000.0 {
1449        return format!("{:.2}M", value / 1_000_000.0);
1450    }
1451    if value < 1_000_000_000_000.0 {
1452        return format!("{:.2}B", value / 1_000_000_000.0);
1453    }
1454
1455    format!("{:.3}T", value / 1_000_000_000_000.0)
1456}
1457
1458fn build_integral_result_cells(
1459    itg: &StatisticsAccumulator<F<f64>>,
1460    slot_meta: &SlotMeta,
1461    i_iter: usize,
1462    tag: &str,
1463    trgt: Option<F<f64>>,
1464) -> IntegralResultCells {
1465    let relative_error = format_relative_error_cell(itg);
1466    let chi_sq = format_chi_sq_cell(itg, i_iter);
1467    let (delta_sigma, delta_percent) = format_delta_cells(itg, trgt);
1468    let mwi = format_mwi_cell(itg);
1469
1470    IntegralResultCells {
1471        integrand: format!(
1472            "{} {}:",
1473            slot_label(slot_meta),
1474            format!("{:-2}", tag).blue().bold(),
1475        ),
1476        value: format_signed_uncertainty(itg.avg, itg.err, UncertaintyNotation::Scientific)
1477            .blue()
1478            .bold()
1479            .to_string(),
1480        relative_error,
1481        chi_sq,
1482        delta_sigma,
1483        delta_percent,
1484        mwi,
1485    }
1486}
1487
1488fn format_relative_error_cell(itg: &StatisticsAccumulator<F<f64>>) -> String {
1489    format_relative_error_from_estimate(itg.avg, itg.err)
1490}
1491
1492fn format_relative_error_from_estimate(avg: F<f64>, err: F<f64>) -> String {
1493    if avg.is_zero() {
1494        return String::new();
1495    }
1496
1497    let formatted =
1498        format_significant_percentage((err / avg).abs().0 * 100.0, 3, Some((1.0e4, 1.0e-4)));
1499    if (err / avg).abs().0 > 0.01 {
1500        formatted.red().to_string()
1501    } else {
1502        formatted.green().to_string()
1503    }
1504}
1505
1506fn format_chi_sq_cell(itg: &StatisticsAccumulator<F<f64>>, i_iter: usize) -> String {
1507    let chi_sq = format!("{:.3}", itg.chi_sq.0 / (i_iter as f64));
1508    if itg.chi_sq / F::<f64>::new_from_usize(i_iter) > F(5.) {
1509        chi_sq.red().to_string()
1510    } else {
1511        chi_sq
1512    }
1513}
1514
1515fn format_delta_cells(
1516    itg: &StatisticsAccumulator<F<f64>>,
1517    trgt: Option<F<f64>>,
1518) -> (Option<String>, Option<String>) {
1519    format_delta_cells_from_estimate(itg.avg, itg.err, trgt)
1520}
1521
1522fn format_delta_cells_from_estimate(
1523    avg: F<f64>,
1524    err: F<f64>,
1525    trgt: Option<F<f64>>,
1526) -> (Option<String>, Option<String>) {
1527    let Some(t) = trgt else {
1528        return (None, None);
1529    };
1530
1531    let delta_in_sigmas = if err.is_zero() {
1532        0.0
1533    } else {
1534        (t - avg).abs().0 / err.0
1535    };
1536    let delta_in_percent = if t.abs().is_non_zero() {
1537        (t - avg).abs().0 / t.abs().0 * 100.
1538    } else {
1539        0.
1540    };
1541    let is_outside_target =
1542        delta_in_sigmas > 5. || (t.abs().is_non_zero() && ((t - avg).abs() / t.abs()).0 > 0.01);
1543    let sigma_text = format!("Δ = {:.3}σ", delta_in_sigmas);
1544    let percent_text = format!("Δ = {:.3}%", delta_in_percent);
1545    if is_outside_target {
1546        (
1547            Some(sigma_text.red().to_string()),
1548            Some(percent_text.red().to_string()),
1549        )
1550    } else {
1551        (
1552            Some(sigma_text.green().to_string()),
1553            Some(percent_text.green().to_string()),
1554        )
1555    }
1556}
1557
1558fn format_mwi_cell(itg: &StatisticsAccumulator<F<f64>>) -> String {
1559    let mwi_value = max_weight_impact(itg);
1560    let formatted = format!("{:.4e}", mwi_value.0);
1561    if mwi_value > F(1.) {
1562        formatted.red().to_string()
1563    } else {
1564        formatted
1565    }
1566}
1567
1568fn max_weight_impact(itg: &StatisticsAccumulator<F<f64>>) -> F<f64> {
1569    if itg.avg.abs().0 == 0. || itg.processed_samples == 0 {
1570        return F(0.0);
1571    }
1572
1573    itg.max_eval_negative.abs().max(itg.max_eval_positive.abs())
1574        / (itg.avg.abs() * F::<f64>::new_from_usize(itg.processed_samples))
1575}
1576
1577fn build_table_component_result(
1578    slot_meta: &SlotMeta,
1579    iter: usize,
1580    component: &str,
1581    accumulator: &StatisticsAccumulator<F<f64>>,
1582    target_component: Option<F<f64>>,
1583) -> IntegrationTableComponentResult {
1584    let cells =
1585        build_integral_result_cells(accumulator, slot_meta, iter, component, target_component);
1586    IntegrationTableComponentResult {
1587        component: component.to_string(),
1588        value: accumulator.avg,
1589        error: accumulator.err,
1590        relative_error_percent: accumulator
1591            .avg
1592            .is_non_zero()
1593            .then(|| (accumulator.err / accumulator.avg).abs().0 * 100.0),
1594        chi_sq_per_dof: if iter > 0 {
1595            accumulator.chi_sq.0 / (iter as f64)
1596        } else {
1597            0.0
1598        },
1599        target_delta_sigma: cells.delta_sigma.as_ref().map(|_| {
1600            if accumulator.err.is_zero() {
1601                0.0
1602            } else if let Some(target_value) = target_component {
1603                (target_value - accumulator.avg).abs().0 / accumulator.err.0
1604            } else {
1605                0.0
1606            }
1607        }),
1608        target_delta_percent: target_component.map(|target_value| {
1609            if target_value.is_zero() {
1610                0.0
1611            } else {
1612                (target_value - accumulator.avg).abs().0 / target_value.abs().0 * 100.0
1613            }
1614        }),
1615        max_weight_impact: max_weight_impact(accumulator).0,
1616    }
1617}
1618
1619fn build_table_result_summary(
1620    slot_meta: &SlotMeta,
1621    accumulator: &ComplexAccumulator,
1622    iter: usize,
1623    target: Option<Complex<F<f64>>>,
1624) -> Vec<IntegrationTableComponentResult> {
1625    [
1626        ("re", &accumulator.re, target.as_ref().map(|value| value.re)),
1627        ("im", &accumulator.im, target.as_ref().map(|value| value.im)),
1628    ]
1629    .into_iter()
1630    .map(|(component, accumulator, target_component)| {
1631        build_table_component_result(slot_meta, iter, component, accumulator, target_component)
1632    })
1633    .collect()
1634}
1635
1636fn build_absolute_table_result_summary(
1637    slot_meta: &SlotMeta,
1638    accumulator: &ComplexAccumulator,
1639    iter: usize,
1640) -> Vec<IntegrationTableComponentResult> {
1641    [
1642        ("|re|", &accumulator.absolute_re),
1643        ("|im|", &accumulator.absolute_im),
1644    ]
1645    .into_iter()
1646    .map(|(component, accumulator)| {
1647        build_table_component_result(slot_meta, iter, component, accumulator, None)
1648    })
1649    .collect()
1650}
1651
1652fn build_max_weight_info_summary(
1653    discrete_axis_labels: &[String],
1654    accumulator: &ComplexAccumulator,
1655) -> Vec<MaxWeightInfoEntry> {
1656    [
1657        (
1658            "re",
1659            "+",
1660            accumulator.re.max_eval_positive,
1661            accumulator.re.max_eval_positive_xs.as_ref(),
1662        ),
1663        (
1664            "re",
1665            "-",
1666            accumulator.re.max_eval_negative,
1667            accumulator.re.max_eval_negative_xs.as_ref(),
1668        ),
1669        (
1670            "im",
1671            "+",
1672            accumulator.im.max_eval_positive,
1673            accumulator.im.max_eval_positive_xs.as_ref(),
1674        ),
1675        (
1676            "im",
1677            "-",
1678            accumulator.im.max_eval_negative,
1679            accumulator.im.max_eval_negative_xs.as_ref(),
1680        ),
1681    ]
1682    .into_iter()
1683    .filter_map(|(component, sign, max_eval, sample)| {
1684        if max_eval.is_zero() {
1685            return None;
1686        }
1687
1688        Some(MaxWeightInfoEntry {
1689            component: component.to_string(),
1690            sign: sign.to_string(),
1691            max_eval,
1692            coordinates: sample
1693                .map(|sample| format_max_eval_sample(sample, discrete_axis_labels, &[])),
1694        })
1695    })
1696    .collect()
1697}
1698
1699fn build_absolute_max_weight_info_summary(
1700    discrete_axis_labels: &[String],
1701    accumulator: &ComplexAccumulator,
1702) -> Vec<MaxWeightInfoEntry> {
1703    [
1704        ("re", &accumulator.absolute_re),
1705        ("im", &accumulator.absolute_im),
1706    ]
1707    .into_iter()
1708    .filter_map(|(component, accumulator)| {
1709        if accumulator.max_eval_positive.is_zero() {
1710            return None;
1711        }
1712        Some(MaxWeightInfoEntry {
1713            component: component.to_string(),
1714            sign: "+".to_string(),
1715            max_eval: accumulator.max_eval_positive,
1716            coordinates: accumulator
1717                .max_eval_positive_xs
1718                .as_ref()
1719                .map(|sample| format_max_eval_sample(sample, discrete_axis_labels, &[])),
1720        })
1721    })
1722    .collect()
1723}
1724
1725#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1726struct LiveIterationProgress {
1727    completed_points: usize,
1728    target_points: usize,
1729}
1730
1731fn build_iteration_status_header_left(
1732    elapsed_time: Duration,
1733    iter: usize,
1734    live_progress: Option<LiveIterationProgress>,
1735) -> String {
1736    let iteration_label = if live_progress.is_some() {
1737        format!("Iteration #{:-4} ( running   )", iter)
1738            .bold()
1739            .green()
1740    } else {
1741        format!("Iteration #{:-4} ( completed )", iter)
1742            .bold()
1743            .green()
1744    };
1745
1746    format!(
1747        "[ {} ] {}",
1748        format!(
1749            "{:^7}",
1750            utils::format_wdhms(elapsed_time.as_secs() as usize)
1751        )
1752        .bold(),
1753        iteration_label,
1754    )
1755}
1756
1757fn build_iteration_status_header_middle(
1758    cur_points: usize,
1759    total_points: usize,
1760    live_progress: Option<LiveIterationProgress>,
1761) -> String {
1762    let per_iteration = if let Some(progress) = live_progress {
1763        let percentage = if progress.target_points == 0 {
1764            String::from("0.0%")
1765        } else {
1766            format!(
1767                "{:.1}%",
1768                (progress.completed_points as f64) / (progress.target_points as f64) * 100.0
1769            )
1770            .green()
1771            .to_string()
1772        };
1773        format!(
1774            "Iteration progress {}/{} {}",
1775            format_iteration_points(progress.completed_points),
1776            format_iteration_points(progress.target_points),
1777            percentage
1778        )
1779    } else if cur_points > 0 {
1780        format!(
1781            "# samples per iteration = {}",
1782            format_iteration_points(cur_points)
1783        )
1784        .blue()
1785        .bold()
1786        .to_string()
1787    } else {
1788        String::new()
1789    };
1790
1791    let total = format!("# samples total = {}", format_total_points(total_points))
1792        .bold()
1793        .green()
1794        .to_string();
1795    if per_iteration.is_empty() {
1796        total
1797    } else {
1798        format!("{per_iteration} {total}")
1799    }
1800}
1801
1802fn build_iteration_status_header_tail(
1803    cores: usize,
1804    elapsed_time: Duration,
1805    n_samples_evaluated: usize,
1806) -> String {
1807    let sample_core_time = if n_samples_evaluated == 0 {
1808        "N/A /sample/core".red().to_string()
1809    } else {
1810        format!(
1811            "{} /sample/core",
1812            utils::format_evaluation_time_from_f64(
1813                elapsed_time.as_secs_f64() / (n_samples_evaluated as f64) * (cores as f64),
1814            )
1815            .bold()
1816            .green()
1817        )
1818    };
1819
1820    format!(
1821        "{sample_core_time} {}",
1822        format!("({cores} cores)").bold().blue()
1823    )
1824}
1825
1826fn max_weight_row_descriptors(
1827    phase_display: IntegrationStatusPhaseDisplay,
1828) -> Vec<(ComponentKind, &'static str, bool)> {
1829    let mut rows = Vec::new();
1830    if phase_display.shows_real() {
1831        rows.push((ComponentKind::Real, "+", true));
1832        rows.push((ComponentKind::Real, "-", false));
1833    }
1834    if phase_display.shows_imag() {
1835        rows.push((ComponentKind::Imag, "+", true));
1836        rows.push((ComponentKind::Imag, "-", false));
1837    }
1838    rows
1839}
1840
1841type MaxEvalEntry<'a> = Option<(F<f64>, Option<&'a Sample<F<f64>>>)>;
1842
1843fn max_eval_entry(accumulator: &StatisticsAccumulator<F<f64>>, positive: bool) -> MaxEvalEntry<'_> {
1844    let (value, sample) = if positive {
1845        (
1846            accumulator.max_eval_positive,
1847            accumulator.max_eval_positive_xs.as_ref(),
1848        )
1849    } else {
1850        (
1851            accumulator.max_eval_negative,
1852            accumulator.max_eval_negative_xs.as_ref(),
1853        )
1854    };
1855
1856    if value.is_zero() {
1857        None
1858    } else {
1859        Some((value, sample))
1860    }
1861}
1862
1863/// struct to keep track of state, used in the havana_integrate function
1864/// the idea is to save this to disk after each iteration, so that the integration can be resumed
1865#[derive(Clone, Serialize, Deserialize, Encode, Decode)]
1866pub struct IntegrationState {
1867    pub num_points: usize,
1868    #[bincode(with_serde)]
1869    pub all_integrals: Vec<ComplexAccumulator>,
1870    #[bincode(with_serde)]
1871    slot_re_summaries: Vec<Option<DiscreteGridAccumulatorSummary>>,
1872    #[bincode(with_serde)]
1873    slot_im_summaries: Vec<Option<DiscreteGridAccumulatorSummary>>,
1874    #[bincode(with_serde)]
1875    pub(crate) slot_absolute_re_summaries: Vec<Option<DiscreteGridAccumulatorSummary>>,
1876    #[bincode(with_serde)]
1877    pub(crate) slot_absolute_im_summaries: Vec<Option<DiscreteGridAccumulatorSummary>>,
1878    pub stats: StatisticsCounter,
1879    pub slot_stats: Vec<StatisticsCounter>,
1880    pub slot_metas: Vec<SlotMeta>,
1881    pub sampling_correlation_mode: SamplingCorrelationMode,
1882    sampling_states: Vec<SamplingSlotState>,
1883    monitored_discrete_path: Option<Vec<usize>>,
1884    pub first_non_trivial_discrete_label: Option<String>,
1885    pub first_non_trivial_discrete_bin_descriptions: Option<Vec<String>>,
1886    slot_first_non_trivial_discrete_breakdown_metadata:
1887        Vec<Option<PersistedDiscreteBreakdownMetadata>>,
1888    pub iter: usize,
1889    pub elapsed_seconds: f64,
1890    pub n_cores: usize,
1891}
1892
1893impl IntegrationState {
1894    fn new_from_settings(
1895        sampling_correlation_mode: SamplingCorrelationMode,
1896        sampling_states: Vec<SamplingSlotState>,
1897        slot_metas: Vec<SlotMeta>,
1898        monitored_discrete_path: Option<Vec<usize>>,
1899        first_non_trivial_discrete_label: Option<String>,
1900        first_non_trivial_discrete_bin_descriptions: Option<Vec<String>>,
1901        slot_first_non_trivial_discrete_breakdown_metadata: Vec<
1902            Option<PersistedDiscreteBreakdownMetadata>,
1903        >,
1904    ) -> Self {
1905        let num_points = 0;
1906        let iter = 0;
1907        let all_integrals = vec![ComplexAccumulator::new(); slot_metas.len()];
1908        let slot_re_summaries = (0..slot_metas.len())
1909            .map(|slot_index| {
1910                DiscreteGridAccumulatorSummary::from_grid(
1911                    &sampling_states[sampling_correlation_mode.state_index(slot_index)].grid,
1912                )
1913            })
1914            .collect();
1915        let slot_im_summaries = (0..slot_metas.len())
1916            .map(|slot_index| {
1917                DiscreteGridAccumulatorSummary::from_grid(
1918                    &sampling_states[sampling_correlation_mode.state_index(slot_index)].grid,
1919                )
1920            })
1921            .collect();
1922        let absolute_summary_for_slot = |slot_index| {
1923            monitored_discrete_path.as_deref().map(|path| {
1924                let grid = &sampling_states[sampling_correlation_mode.state_index(slot_index)].grid;
1925                let discrete_grid = discrete_grid_at_path(grid, path)
1926                    .expect("validated monitored discrete path must match every sampling grid");
1927                DiscreteGridAccumulatorSummary::from_shallow_grid(discrete_grid)
1928            })
1929        };
1930        let slot_absolute_re_summaries = (0..slot_metas.len())
1931            .map(&absolute_summary_for_slot)
1932            .collect();
1933        let slot_absolute_im_summaries = (0..slot_metas.len())
1934            .map(absolute_summary_for_slot)
1935            .collect();
1936        let stats = StatisticsCounter::new_empty();
1937        let slot_stats = vec![StatisticsCounter::new_empty(); slot_metas.len()];
1938
1939        Self {
1940            num_points,
1941            all_integrals,
1942            slot_re_summaries,
1943            slot_im_summaries,
1944            slot_absolute_re_summaries,
1945            slot_absolute_im_summaries,
1946            stats,
1947            slot_stats,
1948            slot_metas,
1949            sampling_correlation_mode,
1950            sampling_states,
1951            monitored_discrete_path,
1952            first_non_trivial_discrete_label,
1953            first_non_trivial_discrete_bin_descriptions,
1954            slot_first_non_trivial_discrete_breakdown_metadata,
1955            iter,
1956            elapsed_seconds: 0.0,
1957            n_cores: 1,
1958        }
1959    }
1960
1961    fn update_iter(&mut self, use_weighted_average: bool) {
1962        self.all_integrals
1963            .iter_mut()
1964            .for_each(|acc| acc.update_iter(use_weighted_average));
1965    }
1966
1967    fn sampling_state_for_slot(&self, slot_index: usize) -> &SamplingSlotState {
1968        &self.sampling_states[self.sampling_correlation_mode.state_index(slot_index)]
1969    }
1970
1971    fn sampling_state_for_slot_mut(&mut self, slot_index: usize) -> &mut SamplingSlotState {
1972        let sampling_state_index = self.sampling_correlation_mode.state_index(slot_index);
1973        &mut self.sampling_states[sampling_state_index]
1974    }
1975
1976    fn monitored_discrete_context_for_slot(
1977        &self,
1978        slot_index: usize,
1979    ) -> Option<DiscreteLevelContext> {
1980        let path = self.monitored_discrete_path.clone()?;
1981        let discrete_grid =
1982            discrete_grid_at_path(&self.sampling_state_for_slot(slot_index).grid, &path)?;
1983        Some(DiscreteLevelContext {
1984            path,
1985            pdfs: discrete_grid.bins.iter().map(|bin| bin.pdf).collect(),
1986        })
1987    }
1988
1989    fn monitored_discrete_context(&self) -> Option<DiscreteLevelContext> {
1990        self.monitored_discrete_context_for_slot(0)
1991    }
1992}
1993
1994struct CoreIterationState {
1995    slot_integrands: Vec<Integrand>,
1996    stats: StatisticsCounter,
1997    slot_stats: Vec<StatisticsCounter>,
1998    integrals: Vec<ComplexAccumulator>,
1999    sampling_correlation_mode: SamplingCorrelationMode,
2000    sampling_states: Vec<CoreSamplingSlotState>,
2001    slot_re_grids: Vec<Grid<F<f64>>>,
2002    slot_im_grids: Vec<Grid<F<f64>>>,
2003    monitored_discrete_path: Option<Vec<usize>>,
2004    slot_absolute_re_grids: Vec<Option<DiscreteGrid<F<f64>>>>,
2005    slot_absolute_im_grids: Vec<Option<DiscreteGrid<F<f64>>>>,
2006    remaining_points: usize,
2007    completed_points: usize,
2008    failed_samples: Vec<(usize, Sample<F<f64>>, EvaluationMetaData)>,
2009}
2010
2011struct CoreSamplingSlotState {
2012    sampling_grid: Grid<F<f64>>,
2013    rng: MonteCarloRng,
2014}
2015
2016impl CoreIterationState {
2017    fn new(
2018        slot_integrands: Vec<Integrand>,
2019        sampling_correlation_mode: SamplingCorrelationMode,
2020        sampling_grid_templates: &[Grid<F<f64>>],
2021        monitored_discrete_path: Option<&[usize]>,
2022        seed: u64,
2023        sample_skip: usize,
2024        remaining_points: usize,
2025    ) -> Self {
2026        let n_slots = slot_integrands.len();
2027        let sampling_states = (0..sampling_correlation_mode.state_count(n_slots))
2028            .map(|sampling_state_index| {
2029                let slot_index = match sampling_correlation_mode {
2030                    SamplingCorrelationMode::Correlated => 0,
2031                    SamplingCorrelationMode::Uncorrelated => sampling_state_index,
2032                };
2033                let mut rng = MonteCarloRng::new(slot_seed(seed, slot_index), 0);
2034                let mut sampling_grid =
2035                    sampling_grid_templates[sampling_state_index].clone_without_samples();
2036
2037                for _ in 0..sample_skip {
2038                    let mut sample = Sample::new();
2039                    sampling_grid.sample(&mut rng, &mut sample);
2040                }
2041
2042                CoreSamplingSlotState { sampling_grid, rng }
2043            })
2044            .collect_vec();
2045        let absolute_monitor_for_slot = |slot_index| {
2046            monitored_discrete_path.map(|path| {
2047                shallow_discrete_monitor_grid(
2048                    &sampling_grid_templates[sampling_correlation_mode.state_index(slot_index)],
2049                    path,
2050                )
2051                .expect("validated monitored discrete path must match every sampling grid")
2052            })
2053        };
2054
2055        Self {
2056            slot_integrands,
2057            stats: StatisticsCounter::new_empty(),
2058            slot_stats: vec![StatisticsCounter::new_empty(); n_slots],
2059            integrals: vec![ComplexAccumulator::new(); n_slots],
2060            sampling_correlation_mode,
2061            sampling_states,
2062            slot_re_grids: (0..n_slots)
2063                .map(|slot_index| {
2064                    sampling_grid_templates[sampling_correlation_mode.state_index(slot_index)]
2065                        .clone_without_samples()
2066                })
2067                .collect(),
2068            slot_im_grids: (0..n_slots)
2069                .map(|slot_index| {
2070                    sampling_grid_templates[sampling_correlation_mode.state_index(slot_index)]
2071                        .clone_without_samples()
2072                })
2073                .collect(),
2074            monitored_discrete_path: monitored_discrete_path.map(|path| path.to_vec()),
2075            slot_absolute_re_grids: (0..n_slots).map(&absolute_monitor_for_slot).collect(),
2076            slot_absolute_im_grids: (0..n_slots).map(absolute_monitor_for_slot).collect(),
2077            remaining_points,
2078            completed_points: 0,
2079            failed_samples: Vec::new(),
2080        }
2081    }
2082
2083    fn evaluate_chunk(
2084        &mut self,
2085        slot_settings: &[&RuntimeSettings],
2086        slot_targets: &[EvaluationTarget<'_>],
2087        iter: usize,
2088        current_max_evals: &[Complex<F<f64>>],
2089        current_integral_estimates: &[Option<(f64, f64)>],
2090        chunk_size: usize,
2091    ) -> Result<usize> {
2092        let n_points = chunk_size.min(self.remaining_points);
2093        if n_points == 0 {
2094            return Ok(0);
2095        }
2096
2097        let chunk_start = Instant::now();
2098        let mut batch_evaluation_time = Duration::ZERO;
2099        let mut batch_stats = StatisticsCounter::new_empty();
2100        let mut processed_points = 0;
2101        let mut total_sample_evaluations = 0;
2102        let monitored_discrete_path = self.monitored_discrete_path.clone();
2103
2104        match self.sampling_correlation_mode {
2105            SamplingCorrelationMode::Correlated => {
2106                let mut samples = Vec::with_capacity(n_points);
2107                for _ in 0..n_points {
2108                    if is_interrupted() {
2109                        break;
2110                    }
2111
2112                    let mut sample = Sample::new();
2113                    let sampling_state = &mut self.sampling_states[0];
2114                    sampling_state
2115                        .sampling_grid
2116                        .sample(&mut sampling_state.rng, &mut sample);
2117                    processed_points += 1;
2118                    samples.push(sample);
2119                }
2120
2121                if processed_points == 0 {
2122                    return Ok(0);
2123                }
2124
2125                let mut slot_results = Vec::with_capacity(self.slot_integrands.len());
2126
2127                for (slot_index, integrand) in self.slot_integrands.iter_mut().enumerate() {
2128                    let evaluation_start = Instant::now();
2129                    let mut raw_batch = integrand.evaluate_samples_raw_with_estimate(
2130                        &samples,
2131                        slot_targets[slot_index],
2132                        iter,
2133                        false,
2134                        true,
2135                        current_max_evals[slot_index],
2136                        current_integral_estimates[slot_index],
2137                    )?;
2138                    if raw_batch.samples.len() < samples.len() {
2139                        return Ok(0);
2140                    }
2141                    for result in &mut raw_batch.samples {
2142                        integrand.process_evaluation_result(result)?;
2143                        // Slot integration retains moments, not the event payload.
2144                        result.event_groups.clear();
2145                    }
2146                    batch_evaluation_time += evaluation_start.elapsed();
2147                    total_sample_evaluations += raw_batch.samples.len();
2148                    batch_stats = batch_stats.merged(&raw_batch.statistics);
2149                    self.slot_stats[slot_index] =
2150                        self.slot_stats[slot_index].merged(&raw_batch.statistics);
2151                    slot_results.push(raw_batch.samples);
2152                }
2153
2154                for (sample_index, sample) in samples.iter().enumerate() {
2155                    for (
2156                        slot_index,
2157                        (
2158                            core_accumulator,
2159                            re_grid,
2160                            im_grid,
2161                            absolute_re_grid,
2162                            absolute_im_grid,
2163                            results,
2164                        ),
2165                    ) in izip!(
2166                        self.integrals.iter_mut(),
2167                        self.slot_re_grids.iter_mut(),
2168                        self.slot_im_grids.iter_mut(),
2169                        self.slot_absolute_re_grids.iter_mut(),
2170                        self.slot_absolute_im_grids.iter_mut(),
2171                        slot_results.iter(),
2172                    )
2173                    .enumerate()
2174                    {
2175                        let result = &results[sample_index];
2176                        if result.evaluation_metadata.is_nan {
2177                            self.failed_samples.push((
2178                                slot_index,
2179                                sample.clone(),
2180                                result.evaluation_metadata.clone(),
2181                            ));
2182                        }
2183                        let jacobian = result.parameterization_jacobian.unwrap_or(F(1.0));
2184                        let effective_integrand_result =
2185                            result.integrand_result * Complex::new_re(jacobian);
2186                        let effective_absolute_result = result
2187                            .absolute_integrand_result
2188                            .map(|value| value * jacobian.abs());
2189
2190                        core_accumulator.add_sample(
2191                            effective_integrand_result,
2192                            effective_absolute_result,
2193                            sample.get_weight(),
2194                            Some(sample),
2195                        );
2196                        re_grid
2197                            .add_training_sample(sample, effective_integrand_result.re)
2198                            .map_err(Report::msg)?;
2199                        im_grid
2200                            .add_training_sample(sample, effective_integrand_result.im)
2201                            .map_err(Report::msg)?;
2202                        add_shallow_monitor_sample(
2203                            absolute_re_grid.as_mut(),
2204                            monitored_discrete_path.as_deref(),
2205                            sample,
2206                            effective_absolute_result
2207                                .map_or(effective_integrand_result.re.abs(), |value| value.re),
2208                        )?;
2209                        add_shallow_monitor_sample(
2210                            absolute_im_grid.as_mut(),
2211                            monitored_discrete_path.as_deref(),
2212                            sample,
2213                            effective_absolute_result
2214                                .map_or(effective_integrand_result.im.abs(), |value| value.im),
2215                        )?;
2216
2217                        if slot_index == 0 {
2218                            let training_eval = match slot_settings[0].integrator.integrated_phase {
2219                                IntegratedPhase::Real => effective_integrand_result.re,
2220                                IntegratedPhase::Imag => effective_integrand_result.im,
2221                                IntegratedPhase::Both => unimplemented!(),
2222                            };
2223
2224                            self.sampling_states[0]
2225                                .sampling_grid
2226                                .add_training_sample(sample, training_eval)
2227                                .map_err(Report::msg)?;
2228                        }
2229                    }
2230                }
2231            }
2232            SamplingCorrelationMode::Uncorrelated => {
2233                for slot_index in 0..self.slot_integrands.len() {
2234                    let mut samples = Vec::with_capacity(n_points);
2235                    for _ in 0..n_points {
2236                        if is_interrupted() {
2237                            break;
2238                        }
2239
2240                        let mut sample = Sample::new();
2241                        let sampling_state = &mut self.sampling_states[slot_index];
2242                        sampling_state
2243                            .sampling_grid
2244                            .sample(&mut sampling_state.rng, &mut sample);
2245                        samples.push(sample);
2246                    }
2247
2248                    if slot_index == 0 {
2249                        processed_points = samples.len();
2250                    } else if samples.len() != processed_points {
2251                        return Err(Report::msg(
2252                            "uncorrelated slot batch sizes diverged unexpectedly",
2253                        ));
2254                    }
2255
2256                    if samples.is_empty() {
2257                        continue;
2258                    }
2259
2260                    let evaluation_start = Instant::now();
2261                    let raw_batch = self.slot_integrands[slot_index]
2262                        .evaluate_samples_raw_with_estimate(
2263                            &samples,
2264                            slot_targets[slot_index],
2265                            iter,
2266                            false,
2267                            true,
2268                            current_max_evals[slot_index],
2269                            current_integral_estimates[slot_index],
2270                        )?;
2271                    if raw_batch.samples.len() < samples.len() {
2272                        return Ok(0);
2273                    }
2274                    batch_evaluation_time += evaluation_start.elapsed();
2275                    total_sample_evaluations += raw_batch.samples.len();
2276                    batch_stats = batch_stats.merged(&raw_batch.statistics);
2277                    self.slot_stats[slot_index] =
2278                        self.slot_stats[slot_index].merged(&raw_batch.statistics);
2279
2280                    for (sample, result) in samples.iter().zip(raw_batch.samples.iter()) {
2281                        self.slot_integrands[slot_index].process_evaluation_result(result)?;
2282                        if result.evaluation_metadata.is_nan {
2283                            self.failed_samples.push((
2284                                slot_index,
2285                                sample.clone(),
2286                                result.evaluation_metadata.clone(),
2287                            ));
2288                        }
2289                        let jacobian = result.parameterization_jacobian.unwrap_or(F(1.0));
2290                        let effective_integrand_result =
2291                            result.integrand_result * Complex::new_re(jacobian);
2292                        let effective_absolute_result = result
2293                            .absolute_integrand_result
2294                            .map(|value| value * jacobian.abs());
2295
2296                        self.integrals[slot_index].add_sample(
2297                            effective_integrand_result,
2298                            effective_absolute_result,
2299                            sample.get_weight(),
2300                            Some(sample),
2301                        );
2302                        self.slot_re_grids[slot_index]
2303                            .add_training_sample(sample, effective_integrand_result.re)
2304                            .map_err(Report::msg)?;
2305                        self.slot_im_grids[slot_index]
2306                            .add_training_sample(sample, effective_integrand_result.im)
2307                            .map_err(Report::msg)?;
2308                        add_shallow_monitor_sample(
2309                            self.slot_absolute_re_grids[slot_index].as_mut(),
2310                            monitored_discrete_path.as_deref(),
2311                            sample,
2312                            effective_absolute_result
2313                                .map_or(effective_integrand_result.re.abs(), |value| value.re),
2314                        )?;
2315                        add_shallow_monitor_sample(
2316                            self.slot_absolute_im_grids[slot_index].as_mut(),
2317                            monitored_discrete_path.as_deref(),
2318                            sample,
2319                            effective_absolute_result
2320                                .map_or(effective_integrand_result.im.abs(), |value| value.im),
2321                        )?;
2322
2323                        let training_eval =
2324                            match slot_settings[slot_index].integrator.integrated_phase {
2325                                IntegratedPhase::Real => effective_integrand_result.re,
2326                                IntegratedPhase::Imag => effective_integrand_result.im,
2327                                IntegratedPhase::Both => unimplemented!(),
2328                            };
2329                        self.sampling_states[slot_index]
2330                            .sampling_grid
2331                            .add_training_sample(sample, training_eval)
2332                            .map_err(Report::msg)?;
2333                    }
2334                }
2335
2336                if processed_points == 0 {
2337                    return Ok(0);
2338                }
2339            }
2340        }
2341
2342        self.remaining_points -= processed_points;
2343        self.completed_points += processed_points;
2344        self.stats = self.stats.merged(&batch_stats);
2345        self.stats.add_integrator_overhead(
2346            chunk_start.elapsed().saturating_sub(batch_evaluation_time),
2347            total_sample_evaluations,
2348        );
2349
2350        Ok(processed_points)
2351    }
2352
2353    fn write_failed_samples(
2354        &mut self,
2355        workspace: Option<&Path>,
2356        slots: &[SlotMeta],
2357        iteration: usize,
2358    ) -> Result<()> {
2359        if self.failed_samples.is_empty() {
2360            return Ok(());
2361        }
2362        if let Some(workspace) = workspace {
2363            let directory = workspace.join("numerical_stability");
2364            fs::create_dir_all(&directory)?;
2365            let mut file = fs::OpenOptions::new()
2366                .create(true)
2367                .append(true)
2368                .open(directory.join("failed_samples.jsonl"))?;
2369            for (slot_index, sample, metadata) in &self.failed_samples {
2370                serde_json::to_writer(
2371                    &mut file,
2372                    &serde_json::json!({
2373                        "schema_version": 1,
2374                        "iteration": iteration,
2375                        "slot": slots[*slot_index],
2376                        "sample": sample,
2377                        "evaluation_metadata": metadata,
2378                    }),
2379                )?;
2380                file.write_all(b"\n")?;
2381            }
2382            file.flush()?;
2383        }
2384        self.failed_samples.clear();
2385        Ok(())
2386    }
2387}
2388
2389fn initial_batch_size(batching: IterationBatchingSettings) -> usize {
2390    batching.batch_size.unwrap_or(100).max(1)
2391}
2392
2393fn next_batch_size(
2394    batching: IterationBatchingSettings,
2395    current_batch_size: usize,
2396    round_elapsed: Duration,
2397) -> usize {
2398    if let Some(batch_size) = batching.batch_size {
2399        return batch_size.max(1);
2400    }
2401
2402    let round_seconds = round_elapsed.as_secs_f64();
2403    if round_seconds <= 0.0 {
2404        return current_batch_size.max(1);
2405    }
2406
2407    let estimated = ((current_batch_size as f64) * batching.batch_timing_seconds / round_seconds)
2408        .round() as usize;
2409    estimated.max(1)
2410}
2411
2412fn total_completed_points(core_states: &[CoreIterationState]) -> usize {
2413    core_states.iter().map(|state| state.completed_points).sum()
2414}
2415
2416fn total_remaining_points(core_states: &[CoreIterationState]) -> usize {
2417    core_states.iter().map(|state| state.remaining_points).sum()
2418}
2419
2420fn slot_seed(global_seed: u64, slot_index: usize) -> u64 {
2421    let slot = (slot_index as u64).wrapping_add(1);
2422    let mut mixed = global_seed.wrapping_add(0x9e37_79b9_7f4a_7c15u64.wrapping_mul(slot));
2423    mixed ^= mixed >> 30;
2424    mixed = mixed.wrapping_mul(0xbf58_476d_1ce4_e5b9);
2425    mixed ^= mixed >> 27;
2426    mixed = mixed.wrapping_mul(0x94d0_49bb_1331_11eb);
2427    mixed ^ (mixed >> 31)
2428}
2429
2430fn apply_iteration_core_states(
2431    integration_state: &mut IntegrationState,
2432    slots: &[IntegrationSlot],
2433    cores: usize,
2434    cur_points: usize,
2435    elapsed_seconds: f64,
2436    core_states: &[CoreIterationState],
2437) {
2438    let n_slots = integration_state.slot_metas.len();
2439
2440    for core_state in core_states {
2441        integration_state.stats = integration_state.stats.merged(&core_state.stats);
2442        for (integral, core_integral) in integration_state
2443            .all_integrals
2444            .iter_mut()
2445            .zip(core_state.integrals.iter())
2446        {
2447            integral.merge(core_integral);
2448        }
2449        for (slot_stats, core_slot_stats) in integration_state
2450            .slot_stats
2451            .iter_mut()
2452            .zip(core_state.slot_stats.iter())
2453        {
2454            *slot_stats = slot_stats.merged(core_slot_stats);
2455        }
2456    }
2457
2458    let mut merged_sampling_grids = integration_state
2459        .sampling_states
2460        .iter()
2461        .map(|sampling_state| sampling_state.grid.clone_without_samples())
2462        .collect_vec();
2463    let mut merged_re_grids = (0..n_slots)
2464        .map(|slot_index| {
2465            integration_state
2466                .sampling_state_for_slot(slot_index)
2467                .grid
2468                .clone_without_samples()
2469        })
2470        .collect_vec();
2471    let mut merged_im_grids = (0..n_slots)
2472        .map(|slot_index| {
2473            integration_state
2474                .sampling_state_for_slot(slot_index)
2475                .grid
2476                .clone_without_samples()
2477        })
2478        .collect_vec();
2479    let mut merged_absolute_re_grids = (0..n_slots)
2480        .map(|slot_index| {
2481            integration_state
2482                .monitored_discrete_path
2483                .as_deref()
2484                .map(|path| {
2485                    shallow_discrete_monitor_grid(
2486                        &integration_state.sampling_state_for_slot(slot_index).grid,
2487                        path,
2488                    )
2489                    .expect("validated monitored discrete path must match every sampling grid")
2490                })
2491        })
2492        .collect_vec();
2493    let mut merged_absolute_im_grids = merged_absolute_re_grids.clone();
2494
2495    for core_state in core_states {
2496        for (sampling_state, merged_grid) in core_state
2497            .sampling_states
2498            .iter()
2499            .zip(merged_sampling_grids.iter_mut())
2500        {
2501            merged_grid
2502                .merge(&sampling_state.sampling_grid)
2503                .expect("could not merge grids");
2504        }
2505        for slot_index in 0..n_slots {
2506            merged_re_grids[slot_index]
2507                .merge(&core_state.slot_re_grids[slot_index])
2508                .expect("could not merge real accumulation grids");
2509            merged_im_grids[slot_index]
2510                .merge(&core_state.slot_im_grids[slot_index])
2511                .expect("could not merge imaginary accumulation grids");
2512            match (
2513                merged_absolute_re_grids[slot_index].as_mut(),
2514                core_state.slot_absolute_re_grids[slot_index].as_ref(),
2515            ) {
2516                (Some(merged), Some(core)) => merged
2517                    .merge(core)
2518                    .expect("could not merge absolute real monitor grids"),
2519                (None, None) => {}
2520                _ => panic!("absolute real monitor grid presence is inconsistent"),
2521            }
2522            match (
2523                merged_absolute_im_grids[slot_index].as_mut(),
2524                core_state.slot_absolute_im_grids[slot_index].as_ref(),
2525            ) {
2526                (Some(merged), Some(core)) => merged
2527                    .merge(core)
2528                    .expect("could not merge absolute imaginary monitor grids"),
2529                (None, None) => {}
2530                _ => panic!("absolute imaginary monitor grid presence is inconsistent"),
2531            }
2532        }
2533    }
2534
2535    for (summary, grid) in integration_state
2536        .slot_re_summaries
2537        .iter_mut()
2538        .zip(merged_re_grids.iter())
2539    {
2540        if let Some(summary) = summary.as_mut() {
2541            summary.merge_iteration_grid(grid);
2542            summary.update_iter();
2543        }
2544    }
2545    for (summary, grid) in integration_state
2546        .slot_im_summaries
2547        .iter_mut()
2548        .zip(merged_im_grids.iter())
2549    {
2550        if let Some(summary) = summary.as_mut() {
2551            summary.merge_iteration_grid(grid);
2552            summary.update_iter();
2553        }
2554    }
2555    for (summary, grid) in integration_state
2556        .slot_absolute_re_summaries
2557        .iter_mut()
2558        .zip(&merged_absolute_re_grids)
2559    {
2560        match (summary.as_mut(), grid.as_ref()) {
2561            (Some(summary), Some(grid)) => {
2562                summary.merge_shallow_iteration_grid(grid);
2563                summary.update_iter();
2564            }
2565            (None, None) => {}
2566            _ => panic!("absolute real summary and monitor grid presence is inconsistent"),
2567        }
2568    }
2569    for (summary, grid) in integration_state
2570        .slot_absolute_im_summaries
2571        .iter_mut()
2572        .zip(&merged_absolute_im_grids)
2573    {
2574        match (summary.as_mut(), grid.as_ref()) {
2575            (Some(summary), Some(grid)) => {
2576                summary.merge_shallow_iteration_grid(grid);
2577                summary.update_iter();
2578            }
2579            (None, None) => {}
2580            _ => panic!("absolute imaginary summary and monitor grid presence is inconsistent"),
2581        }
2582    }
2583
2584    for (slot_index, merged_grid) in merged_sampling_grids.into_iter().enumerate() {
2585        let actual_slot_index = match integration_state.sampling_correlation_mode {
2586            SamplingCorrelationMode::Correlated => 0,
2587            SamplingCorrelationMode::Uncorrelated => slot_index,
2588        };
2589        let discrete_axis_labels = integration_state
2590            .sampling_state_for_slot(actual_slot_index)
2591            .discrete_axis_labels
2592            .clone();
2593        let sampling_state = integration_state.sampling_state_for_slot_mut(actual_slot_index);
2594        *sampling_state = SamplingSlotState {
2595            grid: merged_grid,
2596            discrete_axis_labels,
2597        };
2598        sampling_state.grid.update(
2599            F(slots[actual_slot_index]
2600                .settings
2601                .integrator
2602                .discrete_dim_learning_rate),
2603            F(slots[actual_slot_index]
2604                .settings
2605                .integrator
2606                .continuous_dim_learning_rate),
2607        );
2608    }
2609
2610    integration_state.update_iter(false);
2611    integration_state.iter += 1;
2612    integration_state.elapsed_seconds = elapsed_seconds;
2613    integration_state.n_cores = cores;
2614    integration_state.num_points += cur_points;
2615}
2616
2617fn build_preview_integration_state(
2618    integration_state: &IntegrationState,
2619    slots: &[IntegrationSlot],
2620    cores: usize,
2621    completed_points: usize,
2622    elapsed_seconds: f64,
2623    core_states: &[CoreIterationState],
2624) -> IntegrationState {
2625    let mut preview = integration_state.clone();
2626    apply_iteration_core_states(
2627        &mut preview,
2628        slots,
2629        cores,
2630        completed_points,
2631        elapsed_seconds,
2632        core_states,
2633    );
2634    preview
2635}
2636
2637fn write_interrupted_numerical_stability_outputs(
2638    workspace: Option<&Path>,
2639    integration_state: &IntegrationState,
2640    slots: &[IntegrationSlot],
2641    cores: usize,
2642    completed_points: usize,
2643    elapsed_seconds: f64,
2644    core_states: &[CoreIterationState],
2645) -> Result<Vec<PathBuf>> {
2646    if workspace.is_none() || completed_points == 0 {
2647        return Ok(Vec::new());
2648    }
2649
2650    let preview_state = build_preview_integration_state(
2651        integration_state,
2652        slots,
2653        cores,
2654        completed_points,
2655        elapsed_seconds,
2656        core_states,
2657    );
2658    write_numerical_stability_outputs(
2659        workspace,
2660        &preview_state,
2661        WorkspaceSnapshotControl {
2662            write_iteration_archives: false,
2663        },
2664    )
2665}
2666
2667/// Integrate function used for local runs
2668pub fn havana_integrate<S>(
2669    request: HavanaIntegrateRequest,
2670    mut status_emitter: S,
2671) -> Result<IntegrationResult>
2672where
2673    S: FnMut(StatusUpdate) -> Result<()>,
2674{
2675    let HavanaIntegrateRequest {
2676        mut slots,
2677        sampling_correlation_mode,
2678        n_cores,
2679        state,
2680        workspace,
2681        output_control,
2682        batching,
2683        view_options,
2684    } = request;
2685
2686    if slots.is_empty() {
2687        return Err(Report::msg(
2688            "At least one integrand must be selected for integration",
2689        ));
2690    }
2691
2692    let slot_metas = slots.iter().map(|slot| slot.meta.clone()).collect_vec();
2693    let targets = slots.iter().map(|slot| slot.target).collect_vec();
2694    let sampling_states = match sampling_correlation_mode {
2695        SamplingCorrelationMode::Correlated => {
2696            vec![SamplingSlotState::from_integrand(&slots[0].integrand)]
2697        }
2698        SamplingCorrelationMode::Uncorrelated => slots
2699            .iter()
2700            .map(|slot| SamplingSlotState::from_integrand(&slot.integrand))
2701            .collect_vec(),
2702    };
2703    let monitored_discrete_setup =
2704        resolve_monitored_discrete_setup(sampling_correlation_mode, &slots, &sampling_states);
2705    let slot_first_non_trivial_discrete_breakdown_metadata =
2706        if let Some(path) = monitored_discrete_setup.path.as_deref() {
2707            slots
2708                .iter()
2709                .enumerate()
2710                .map(|(slot_index, slot)| {
2711                    build_persisted_discrete_breakdown_metadata(
2712                        &slot.integrand,
2713                        path,
2714                        &sampling_states[sampling_correlation_mode.state_index(slot_index)]
2715                            .discrete_axis_labels,
2716                    )
2717                })
2718                .collect_vec()
2719        } else {
2720            vec![None; slot_metas.len()]
2721        };
2722    if let Some(label_warning) = monitored_discrete_setup.warning.as_ref() {
2723        warn!("{label_warning}");
2724    }
2725
2726    let mut integration_state = if let Some(integration_state) = state {
2727        integration_state
2728    } else {
2729        IntegrationState::new_from_settings(
2730            sampling_correlation_mode,
2731            sampling_states.clone(),
2732            slot_metas.clone(),
2733            monitored_discrete_setup.path.clone(),
2734            monitored_discrete_setup.axis_label.clone(),
2735            monitored_discrete_setup.bin_descriptions.clone(),
2736            slot_first_non_trivial_discrete_breakdown_metadata,
2737        )
2738    };
2739    integration_state.monitored_discrete_path = monitored_discrete_setup.path;
2740    integration_state.first_non_trivial_discrete_label = monitored_discrete_setup.axis_label;
2741    integration_state.first_non_trivial_discrete_bin_descriptions =
2742        monitored_discrete_setup.bin_descriptions;
2743    if integration_state.slot_metas != slot_metas {
2744        return Err(Report::msg(
2745            "Saved integration state slots do not match the currently selected integrands",
2746        ));
2747    }
2748    if integration_state.sampling_correlation_mode != sampling_correlation_mode {
2749        return Err(Report::msg(
2750            "Saved integration state sampling mode does not match the current integration mode",
2751        ));
2752    }
2753    if integration_state.sampling_states.len()
2754        != sampling_correlation_mode.state_count(slot_metas.len())
2755    {
2756        return Err(Report::msg(
2757            "Saved integration state sampling metadata is inconsistent with the selected slots",
2758        ));
2759    }
2760    if integration_state
2761        .slot_first_non_trivial_discrete_breakdown_metadata
2762        .len()
2763        != slot_metas.len()
2764    {
2765        return Err(Report::msg(
2766            "Saved integration state discrete breakdown metadata is inconsistent with the selected slots",
2767        ));
2768    }
2769    if integration_state.slot_absolute_re_summaries.len() != slot_metas.len()
2770        || integration_state.slot_absolute_im_summaries.len() != slot_metas.len()
2771    {
2772        return Err(Report::msg(
2773            "Saved integration state absolute summaries are inconsistent with the selected slots",
2774        ));
2775    }
2776    for slot_index in 0..slot_metas.len() {
2777        let expected_bin_count = integration_state
2778            .monitored_discrete_path
2779            .as_deref()
2780            .map(|path| {
2781                discrete_grid_at_path(
2782                    &integration_state.sampling_state_for_slot(slot_index).grid,
2783                    path,
2784                )
2785                .map(|grid| grid.bins.len())
2786                .ok_or_else(|| {
2787                    Report::msg(format!(
2788                        "Saved integration state monitor path does not match slot {} sampling grid",
2789                        integration_state.slot_metas[slot_index].key()
2790                    ))
2791                })
2792            })
2793            .transpose()?;
2794        for summary in [
2795            &integration_state.slot_absolute_re_summaries[slot_index],
2796            &integration_state.slot_absolute_im_summaries[slot_index],
2797        ] {
2798            let valid = match (summary, expected_bin_count) {
2799                (None, None) => true,
2800                (Some(summary), Some(bin_count)) => {
2801                    summary.bins.len() == bin_count
2802                        && summary.bins.iter().all(|bin| bin.sub_summary.is_none())
2803                }
2804                _ => false,
2805            };
2806            if !valid {
2807                return Err(Report::msg(format!(
2808                    "Saved integration state absolute summary does not match slot {} monitor grid",
2809                    integration_state.slot_metas[slot_index].key()
2810                )));
2811            }
2812        }
2813    }
2814
2815    let primary = &slots[0];
2816    let sampling_str = primary.settings.sampling.describe_settings();
2817    let dimension = primary.integrand.get_n_dim();
2818    let discrete_depth = primary.settings.sampling.discrete_depth();
2819    let is_tropical_sampling = primary
2820        .settings
2821        .sampling
2822        .get_parameterization_settings()
2823        .is_none();
2824    let representation_stack = primary
2825        .settings
2826        .stability
2827        .levels
2828        .iter()
2829        .map(|level| {
2830            let representation = match &primary.integrand {
2831                Integrand::ProcessIntegrand(integrand) => {
2832                    level.resolved_representation(integrand.generated_representations())?
2833                }
2834                #[cfg(test)]
2835                Integrand::TestProbe(_) => level
2836                    .resolved_representation(&[crate::settings::global::RepresentationMode::Cff])?,
2837            };
2838            Ok(format!("{} / {}", level.precision, representation))
2839        })
2840        .collect::<Result<Vec<_>>>()?
2841        .join(" → ");
2842    let integration_seed = primary.settings.integrator.seed;
2843    let integrated_phase = primary.settings.integrator.integrated_phase;
2844    let target_relative_accuracy = primary.settings.integrator.target_relative_accuracy;
2845    let target_absolute_accuracy = primary.settings.integrator.target_absolute_accuracy;
2846    let n_start = primary.settings.integrator.n_start;
2847    let n_increase = primary.settings.integrator.n_increase;
2848    let n_max = primary.settings.integrator.n_max;
2849
2850    let cont_dim_str = if is_tropical_sampling {
2851        format!("a median continious dimension of {}", dimension)
2852    } else {
2853        format!("{} continuous dimensions", dimension)
2854    };
2855
2856    let graph_string = if discrete_depth > 0 {
2857        let num_graphs = match &integration_state.sampling_state_for_slot(0).grid {
2858            Grid::Discrete(g) => g.bins.len(),
2859            _ => unreachable!(),
2860        };
2861        format!(
2862            "{discrete_depth} nested discrete grids with {} {} and ",
2863            num_graphs,
2864            if num_graphs > 1 { "graphs" } else { "graph" }
2865        )
2866    } else {
2867        String::new()
2868    };
2869
2870    let correlation_str = match sampling_correlation_mode {
2871        SamplingCorrelationMode::Correlated => "correlated",
2872        SamplingCorrelationMode::Uncorrelated => "uncorrelated",
2873    };
2874    let grid_str = format!("{graph_string}{cont_dim_str} using {sampling_str} ({correlation_str})");
2875
2876    let cores = n_cores.max(1);
2877    let n_slots = integration_state.slot_metas.len();
2878    let elapsed_seconds_offset = integration_state.elapsed_seconds;
2879
2880    let t_start = Instant::now();
2881
2882    info!(
2883        "Integrating using [{}] with {} {} over {} ...",
2884        representation_stack,
2885        cores,
2886        if cores > 1 { "cores" } else { "core" },
2887        grid_str
2888    );
2889    info!("");
2890
2891    let pool = ThreadPoolBuilder::new().num_threads(cores).build().unwrap();
2892
2893    let mut n_samples_evaluated = 0;
2894    let mut emitted_latest_observable_paths = vec![Vec::new(); n_slots];
2895    let mut emitted_latest_numerical_stability_paths = Vec::new();
2896    clear_iteration_abort_request();
2897    'integrateLoop: while integration_state.num_points < n_max {
2898        // ensure we do not overshoot
2899        let cur_points = {
2900            let cur_points_not_final_iter = n_start + n_increase * integration_state.iter;
2901            if cur_points_not_final_iter + integration_state.num_points > n_max {
2902                n_max - integration_state.num_points
2903            } else {
2904                cur_points_not_final_iter
2905            }
2906        };
2907
2908        // the number of points per core is the same for all cores, except for the last one
2909        let target_points_per_core = (cur_points - 1) / cores + 1;
2910        let n_points_per_core = (0..cores)
2911            .map(|core_id| {
2912                if core_id + 1 == cores {
2913                    cur_points - target_points_per_core * (cores - 1)
2914                } else {
2915                    target_points_per_core
2916                }
2917            })
2918            .collect_vec();
2919
2920        let iteration_start = Instant::now();
2921        let mut current_batch_size = initial_batch_size(batching);
2922        let mut last_live_status = None;
2923        if batching.emit_initial_status_update && !is_interrupted() {
2924            status_emitter(build_status_update(StatusUpdateBuildRequest {
2925                kind: IntegrationStatusKind::Live,
2926                integration_state: &integration_state,
2927                cores,
2928                elapsed_time: t_start.elapsed(),
2929                iteration_elapsed_time: iteration_start.elapsed(),
2930                cur_points: 0,
2931                total_points_display: integration_state.num_points,
2932                n_samples_evaluated,
2933                targets: &targets,
2934                render_options: &view_options,
2935                live_progress: Some(status_update::LiveIterationProgress {
2936                    completed_points: 0,
2937                    target_points: cur_points,
2938                }),
2939            }))?;
2940        }
2941
2942        let current_max_evals = integration_state
2943            .all_integrals
2944            .iter()
2945            .map(ComplexAccumulator::get_worst_case)
2946            .collect_vec();
2947        let current_integral_estimates = integration_state
2948            .all_integrals
2949            .iter()
2950            .zip(&slots)
2951            .map(|(integral, slot)| {
2952                let accumulator = match slot.settings.integrator.integrated_phase {
2953                    IntegratedPhase::Real => &integral.absolute_re,
2954                    IntegratedPhase::Imag => &integral.absolute_im,
2955                    IntegratedPhase::Both => return None,
2956                };
2957                (accumulator.processed_samples > 0)
2958                    .then_some((accumulator.avg.0, accumulator.err.0))
2959            })
2960            .collect_vec();
2961
2962        let mut worker_states = n_points_per_core
2963            .iter()
2964            .enumerate()
2965            .map(|(core_id, &n_points)| {
2966                CoreIterationState::new(
2967                    slots.iter().map(|slot| slot.integrand.clone()).collect(),
2968                    integration_state.sampling_correlation_mode,
2969                    &integration_state
2970                        .sampling_states
2971                        .iter()
2972                        .map(|sampling_state| sampling_state.grid.clone())
2973                        .collect_vec(),
2974                    integration_state.monitored_discrete_path.as_deref(),
2975                    integration_seed + integration_state.iter as u64,
2976                    target_points_per_core * core_id,
2977                    n_points,
2978                )
2979            })
2980            .collect_vec();
2981        while total_remaining_points(&worker_states) > 0 {
2982            let round_started_at = Instant::now();
2983            let processed_per_core: Vec<Result<usize>> = {
2984                let slot_settings = slots.iter().map(|slot| &slot.settings).collect_vec();
2985                let slot_targets = slots
2986                    .iter()
2987                    .map(|slot| {
2988                        slot.reference_gaussian
2989                            .as_ref()
2990                            .map(EvaluationTarget::Reference)
2991                            .unwrap_or(EvaluationTarget::Physical(&slot.model))
2992                    })
2993                    .collect_vec();
2994                pool.install(|| {
2995                    worker_states
2996                        .par_iter_mut()
2997                        .map(|worker_state| {
2998                            worker_state.evaluate_chunk(
2999                                &slot_settings,
3000                                &slot_targets,
3001                                integration_state.iter,
3002                                &current_max_evals,
3003                                &current_integral_estimates,
3004                                current_batch_size,
3005                            )
3006                        })
3007                        .collect()
3008                })
3009            };
3010            // Keep replayable numerical failures independently of iteration
3011            // checkpoints, including rounds interrupted or aborted afterward.
3012            // Only this coordinator writes, so worker records cannot interleave.
3013            for worker_state in &mut worker_states {
3014                worker_state.write_failed_samples(
3015                    workspace.as_deref(),
3016                    &integration_state.slot_metas,
3017                    integration_state.iter + 1,
3018                )?;
3019            }
3020            let processed_this_round = processed_per_core
3021                .into_iter()
3022                .collect::<Result<Vec<_>>>()?
3023                .into_iter()
3024                .sum::<usize>();
3025
3026            if processed_this_round == 0 {
3027                break;
3028            }
3029
3030            let completed_points = total_completed_points(&worker_states);
3031            if batching.emit_live_status_updates
3032                && completed_points < cur_points
3033                && !is_interrupted()
3034                && !is_iteration_abort_requested()
3035            {
3036                let now = Instant::now();
3037                let should_emit_live_status = last_live_status.is_none_or(|previous| {
3038                    now.duration_since(previous).as_secs_f64()
3039                        >= batching.min_time_between_status_updates_seconds
3040                });
3041                if should_emit_live_status {
3042                    let preview_state = build_preview_integration_state(
3043                        &integration_state,
3044                        &slots,
3045                        cores,
3046                        completed_points,
3047                        elapsed_seconds_offset + t_start.elapsed().as_secs_f64(),
3048                        &worker_states,
3049                    );
3050                    status_emitter(build_status_update(StatusUpdateBuildRequest {
3051                        kind: IntegrationStatusKind::Live,
3052                        integration_state: &preview_state,
3053                        cores,
3054                        elapsed_time: t_start.elapsed(),
3055                        iteration_elapsed_time: iteration_start.elapsed(),
3056                        cur_points: completed_points,
3057                        total_points_display: integration_state.num_points + completed_points,
3058                        n_samples_evaluated: n_samples_evaluated + completed_points,
3059                        targets: &targets,
3060                        render_options: &view_options,
3061                        live_progress: Some(status_update::LiveIterationProgress {
3062                            completed_points,
3063                            target_points: cur_points,
3064                        }),
3065                    }))?;
3066                    last_live_status = Some(now);
3067                }
3068            }
3069
3070            if is_interrupted() {
3071                warn!("{}", "Integration interrupted by user".yellow());
3072                emitted_latest_numerical_stability_paths =
3073                    write_interrupted_numerical_stability_outputs(
3074                        workspace.as_deref(),
3075                        &integration_state,
3076                        &slots,
3077                        cores,
3078                        total_completed_points(&worker_states),
3079                        elapsed_seconds_offset + t_start.elapsed().as_secs_f64(),
3080                        &worker_states,
3081                    )?;
3082                break 'integrateLoop;
3083            }
3084
3085            if is_iteration_abort_requested() {
3086                break;
3087            }
3088
3089            if total_remaining_points(&worker_states) > 0 {
3090                current_batch_size =
3091                    next_batch_size(batching, current_batch_size, round_started_at.elapsed());
3092            }
3093        }
3094
3095        let abort_current_iteration = is_iteration_abort_requested();
3096        clear_iteration_abort_request();
3097
3098        if is_interrupted() {
3099            warn!("{}", "Integration interrupted by user".yellow());
3100            emitted_latest_numerical_stability_paths =
3101                write_interrupted_numerical_stability_outputs(
3102                    workspace.as_deref(),
3103                    &integration_state,
3104                    &slots,
3105                    cores,
3106                    total_completed_points(&worker_states),
3107                    elapsed_seconds_offset + t_start.elapsed().as_secs_f64(),
3108                    &worker_states,
3109                )?;
3110            break 'integrateLoop;
3111        }
3112
3113        let completed_points = total_completed_points(&worker_states);
3114        if abort_current_iteration && completed_points < cur_points {
3115            if completed_points == 0 {
3116                warn!(
3117                    "{}",
3118                    "Current iteration abort requested before any samples completed; restarting the iteration."
3119                        .yellow()
3120                );
3121                continue;
3122            }
3123            warn!(
3124                "{}",
3125                format!(
3126                    "Current iteration aborted by user after {} completed samples.",
3127                    completed_points
3128                )
3129                .yellow()
3130            );
3131            continue;
3132        }
3133
3134        n_samples_evaluated += completed_points;
3135        apply_iteration_core_states(
3136            &mut integration_state,
3137            &slots,
3138            cores,
3139            completed_points,
3140            elapsed_seconds_offset + t_start.elapsed().as_secs_f64(),
3141            &worker_states,
3142        );
3143
3144        // merge runtime state per slot into the owner core
3145        let (owner_core_slice, other_cores) = worker_states.split_at_mut(1);
3146        let owner_core = &mut owner_core_slice[0].slot_integrands;
3147        for other_core in other_cores {
3148            for (owner_slot, other_slot) in owner_core
3149                .iter_mut()
3150                .zip(other_core.slot_integrands.iter_mut())
3151            {
3152                owner_slot.merge_runtime_results(other_slot)?;
3153            }
3154        }
3155        for (slot, integrand) in slots.iter_mut().zip(owner_core.iter()) {
3156            slot.integrand = integrand.clone();
3157        }
3158
3159        // Update observable accumulators, persist authoritative resume state, then refresh
3160        // the latest user-facing snapshots.
3161        for slot in &mut slots {
3162            slot.integrand
3163                .update_runtime_results(integration_state.iter);
3164        }
3165
3166        if let Some(ref workspace_path) = workspace {
3167            for (slot_index, slot) in slots.iter().enumerate() {
3168                write_observable_resume_state(
3169                    &slot.integrand,
3170                    Some(workspace_path.as_path()),
3171                    &integration_state.slot_metas[slot_index],
3172                    integration_state.iter,
3173                    output_control,
3174                )?;
3175            }
3176            write_integration_state_to_workspace(workspace_path, &integration_state)?;
3177            write_integration_result_snapshots(
3178                workspace_path,
3179                &integration_state,
3180                &targets,
3181                output_control,
3182            )?;
3183            emitted_latest_numerical_stability_paths = write_numerical_stability_outputs(
3184                Some(workspace_path.as_path()),
3185                &integration_state,
3186                output_control,
3187            )?;
3188        }
3189
3190        for (slot_index, slot) in slots.iter().enumerate() {
3191            let workspace_path = workspace
3192                .as_deref()
3193                .map(|root| slot_workspace_path(root, &integration_state.slot_metas[slot_index]));
3194            emitted_latest_observable_paths[slot_index] =
3195                write_latest_observables_output(&slot.integrand, workspace_path.as_deref())?;
3196            write_observable_snapshot_archive(
3197                &slot.integrand,
3198                workspace_path.as_deref(),
3199                integration_state.iter,
3200                output_control,
3201            )?;
3202        }
3203
3204        status_emitter(build_status_update(StatusUpdateBuildRequest {
3205            kind: IntegrationStatusKind::Iteration,
3206            integration_state: &integration_state,
3207            cores,
3208            elapsed_time: t_start.elapsed(),
3209            iteration_elapsed_time: iteration_start.elapsed(),
3210            cur_points: completed_points,
3211            total_points_display: integration_state.num_points,
3212            n_samples_evaluated,
3213            targets: &targets,
3214            render_options: &view_options,
3215            live_progress: None,
3216        }))?;
3217
3218        let target_accuracy_status = evaluate_target_accuracy(
3219            &integration_state,
3220            integration_state.num_points,
3221            t_start.elapsed(),
3222            &targets,
3223            match integrated_phase {
3224                IntegratedPhase::Real | IntegratedPhase::Both => {
3225                    IntegrationStatusPhaseDisplay::Real
3226                }
3227                IntegratedPhase::Imag => IntegrationStatusPhaseDisplay::Imag,
3228            },
3229            target_relative_accuracy,
3230            target_absolute_accuracy,
3231        );
3232        if target_accuracy_status.is_reached() {
3233            let reached_target = match (
3234                target_accuracy_status.relative_reached,
3235                target_accuracy_status.absolute_reached,
3236            ) {
3237                (true, true) => "relative and absolute",
3238                (true, false) => "relative",
3239                (false, true) => "absolute",
3240                (false, false) => unreachable!(),
3241            };
3242            info!(
3243                "Stopping integration after reaching the configured {reached_target} accuracy target."
3244            );
3245            break;
3246        }
3247    }
3248    // Reset the interrupted flag
3249    set_interrupted(false);
3250    clear_iteration_abort_request();
3251
3252    if integration_state.num_points > 0 {
3253        let final_view_options = view_options.for_final();
3254        status_emitter(build_status_update(StatusUpdateBuildRequest {
3255            kind: IntegrationStatusKind::Final,
3256            integration_state: &integration_state,
3257            cores,
3258            elapsed_time: t_start.elapsed(),
3259            iteration_elapsed_time: Duration::ZERO,
3260            cur_points: 0,
3261            total_points_display: integration_state.num_points,
3262            n_samples_evaluated,
3263            targets: &targets,
3264            render_options: &final_view_options,
3265            live_progress: None,
3266        }))?;
3267    } else {
3268        info!("");
3269        warn!(
3270            "{}",
3271            "No final integration results to display since no iteration completed.".yellow()
3272        );
3273        info!("");
3274    }
3275
3276    if !slots.is_empty() {
3277        emit_results_output_summary(
3278            workspace.as_deref(),
3279            &slots,
3280            &emitted_latest_observable_paths,
3281            &emitted_latest_numerical_stability_paths,
3282        );
3283    }
3284
3285    Ok(build_integration_result(&integration_state, &targets))
3286}
3287
3288/// Batch integrate function used for distributed runs, used by the worker nodes.
3289/// Evaluates a batch of points and returns the results in a manner specified by the user.
3290pub(crate) fn batch_integrate(
3291    integrand: &mut Integrand,
3292    model: &Model,
3293    input: BatchIntegrateInput,
3294) -> Result<BatchResult> {
3295    let samples = match input.samples {
3296        SampleInput::SampleList { samples } => samples,
3297        SampleInput::Grid {
3298            mut grid,
3299            num_points,
3300            seed,
3301            thread_id,
3302        } => {
3303            let mut rng = MonteCarloRng::new(seed, thread_id);
3304
3305            (0..num_points)
3306                .map(|_| {
3307                    let mut sample = Sample::new();
3308                    grid.sample(&mut rng, &mut sample);
3309                    sample
3310                })
3311                .collect_vec()
3312        }
3313    };
3314
3315    let (evaluation_results, metadata_statistics) = evaluate_sample_list(
3316        integrand,
3317        &samples,
3318        model,
3319        input.num_cores,
3320        input.iter,
3321        input.max_eval,
3322    )?;
3323
3324    let integrand_output = generate_integrand_output(
3325        integrand,
3326        &evaluation_results,
3327        &samples,
3328        input.integrand_output_settings,
3329        input.settings.integrator.integrated_phase,
3330    );
3331
3332    let event_output = generate_event_output(
3333        integrand,
3334        evaluation_results,
3335        input.event_output_settings,
3336        input.settings,
3337    );
3338
3339    Ok(BatchResult {
3340        statistics: metadata_statistics,
3341        integrand_data: integrand_output,
3342        event_data: event_output,
3343    })
3344}
3345
3346/// Map the evaluation result on to the right output specified by the user.
3347fn generate_integrand_output(
3348    integrand: &Integrand,
3349    evaluation_results: &[EvaluationResult],
3350    samples: &[Sample<F<f64>>],
3351    integrand_output_settings: IntegralOutputSettings,
3352    integrated_phase: IntegratedPhase,
3353) -> BatchIntegrateOutput {
3354    fn effective_integrand_result(result: &EvaluationResult) -> Complex<F<f64>> {
3355        let jacobian = result.parameterization_jacobian.unwrap_or(F(1.0));
3356        result.integrand_result * Complex::new_re(jacobian)
3357    }
3358
3359    match integrand_output_settings {
3360        IntegralOutputSettings::Default => {
3361            let integrand_values = evaluation_results
3362                .iter()
3363                .map(effective_integrand_result)
3364                .collect();
3365
3366            BatchIntegrateOutput::Default(integrand_values, samples.to_vec())
3367        }
3368        IntegralOutputSettings::Accumulator => {
3369            let mut real_accumulator = StatisticsAccumulator::new();
3370            let mut imag_accumulator = StatisticsAccumulator::new();
3371            let mut grid = integrand.create_grid();
3372
3373            for (result, sample) in evaluation_results.iter().zip(samples.iter()) {
3374                let effective_result = effective_integrand_result(result);
3375                real_accumulator
3376                    .add_sample(effective_result.re * sample.get_weight(), Some(sample));
3377                imag_accumulator
3378                    .add_sample(effective_result.im * sample.get_weight(), Some(sample));
3379
3380                match integrated_phase {
3381                    IntegratedPhase::Real => {
3382                        grid.add_training_sample(sample, effective_result.re)
3383                            .unwrap();
3384                    }
3385                    IntegratedPhase::Imag => {
3386                        grid.add_training_sample(sample, effective_result.im)
3387                            .unwrap();
3388                    }
3389                    IntegratedPhase::Both => {
3390                        unimplemented!()
3391                    }
3392                }
3393            }
3394
3395            BatchIntegrateOutput::Accumulator(
3396                Box::new((real_accumulator, imag_accumulator)),
3397                Box::new(grid),
3398            )
3399        }
3400    }
3401}
3402
3403/// Process events into histograms or event lists, as specified by the user.
3404fn generate_event_output(
3405    integrand: &Integrand,
3406    evaluation_results: Vec<EvaluationResult>,
3407    event_output_settings: EventOutputSettings,
3408    _settings: &RuntimeSettings,
3409) -> EventOutput {
3410    match event_output_settings {
3411        EventOutputSettings::None => EventOutput::None,
3412
3413        EventOutputSettings::EventList => {
3414            let mut event_groups = EventGroupList::default();
3415            for mut result in evaluation_results {
3416                let factor = Complex::new_re(result.integrator_weight);
3417                process::apply_full_event_multiplicative_factor_precise(
3418                    &mut result.event_groups,
3419                    &factor,
3420                );
3421                event_groups.append(&mut result.event_groups);
3422            }
3423            EventOutput::EventList { event_groups }
3424        }
3425        EventOutputSettings::Histogram => integrand
3426            .observable_accumulator_bundle()
3427            .map(|histograms| EventOutput::Histogram { histograms })
3428            .unwrap_or(EventOutput::None),
3429    }
3430}
3431
3432pub fn slot_workspace_path(workspace: &Path, slot_meta: &SlotMeta) -> PathBuf {
3433    workspace.join("integrands").join(slot_meta.key())
3434}
3435
3436pub fn workspace_manifest_path(workspace: &Path) -> PathBuf {
3437    workspace.join("manifest.json")
3438}
3439
3440pub fn workspace_state_dir(workspace: &Path) -> PathBuf {
3441    workspace.join("state")
3442}
3443
3444pub fn workspace_state_path(workspace: &Path) -> PathBuf {
3445    workspace_state_dir(workspace).join("integration_state.bin")
3446}
3447
3448fn workspace_observable_state_dir(workspace: &Path, slot_meta: &SlotMeta) -> PathBuf {
3449    workspace_state_dir(workspace)
3450        .join("observables")
3451        .join(slot_meta.key())
3452}
3453
3454pub fn latest_observable_resume_state_path(workspace: &Path, slot_meta: &SlotMeta) -> PathBuf {
3455    workspace_observable_state_dir(workspace, slot_meta).join("latest.json")
3456}
3457
3458fn archived_observable_resume_state_path(
3459    workspace: &Path,
3460    slot_meta: &SlotMeta,
3461    iter: usize,
3462) -> PathBuf {
3463    workspace_observable_state_dir(workspace, slot_meta).join(format!("iter_{iter:04}.json"))
3464}
3465
3466pub fn workspace_result_snapshot_path(workspace: &Path) -> PathBuf {
3467    workspace.join("integration_result.json")
3468}
3469
3470pub fn workspace_result_archive_path(workspace: &Path, iter: usize) -> PathBuf {
3471    workspace
3472        .join("results")
3473        .join(format!("integration_result_iter_{iter:04}.json"))
3474}
3475
3476fn observable_output_extension(format: ObservableFileFormat) -> Option<&'static str> {
3477    match format {
3478        ObservableFileFormat::None => None,
3479        ObservableFileFormat::Hwu => Some("hwu"),
3480        ObservableFileFormat::Json => Some("json"),
3481    }
3482}
3483
3484fn latest_observable_output_path(workspace: &Path, format: ObservableFileFormat) -> PathBuf {
3485    let extension = observable_output_extension(format)
3486        .expect("user-facing observable outputs must use a real file format");
3487    workspace.join(format!("observables_final.{extension}"))
3488}
3489
3490fn archived_observable_output_path(
3491    workspace: &Path,
3492    format: ObservableFileFormat,
3493    iter: usize,
3494) -> PathBuf {
3495    let extension = observable_output_extension(format)
3496        .expect("user-facing observable outputs must use a real file format");
3497    workspace.join(format!("observables_final_iter_{iter:04}.{extension}"))
3498}
3499
3500fn numerical_stability_output_extension(format: ObservableFileFormat) -> Option<&'static str> {
3501    match format {
3502        ObservableFileFormat::None => None,
3503        ObservableFileFormat::Hwu => Some("hwu"),
3504        ObservableFileFormat::Json => Some("json"),
3505    }
3506}
3507
3508fn numerical_stability_scope_file_stem(scope: &str, iter: Option<usize>) -> String {
3509    match iter {
3510        Some(iter) => format!("{scope}_iter_{iter:04}"),
3511        None => scope.to_string(),
3512    }
3513}
3514
3515fn numerical_stability_output_path(
3516    workspace: &Path,
3517    scope: &str,
3518    format: ObservableFileFormat,
3519    iter: Option<usize>,
3520) -> PathBuf {
3521    let extension = numerical_stability_output_extension(format)
3522        .expect("numerical stability outputs must use a real file format");
3523    workspace.join("numerical_stability").join(format!(
3524        "{}.{extension}",
3525        numerical_stability_scope_file_stem(scope, iter)
3526    ))
3527}
3528
3529#[allow(clippy::infallible_destructuring_match)]
3530fn user_facing_observables_output_formats(integrand: &Integrand) -> Vec<ObservableFileFormat> {
3531    let process_integrand = match integrand {
3532        Integrand::ProcessIntegrand(process_integrand) => process_integrand,
3533        #[cfg(test)]
3534        Integrand::TestProbe(_) => return Vec::new(),
3535    };
3536    if !integrand.has_observables() {
3537        return Vec::new();
3538    }
3539
3540    process_integrand
3541        .get_settings()
3542        .integrator
3543        .observables_output
3544        .resolved_formats()
3545}
3546
3547#[allow(clippy::infallible_destructuring_match)]
3548fn user_facing_observables_output_enabled(integrand: &Integrand) -> bool {
3549    let process_integrand = match integrand {
3550        Integrand::ProcessIntegrand(process_integrand) => process_integrand,
3551        #[cfg(test)]
3552        Integrand::TestProbe(_) => return false,
3553    };
3554    if !integrand.has_observables() {
3555        return false;
3556    }
3557
3558    !process_integrand
3559        .get_settings()
3560        .integrator
3561        .observables_output
3562        .resolved_formats()
3563        .is_empty()
3564}
3565
3566fn write_atomic_bytes(path: &Path, bytes: &[u8]) -> Result<()> {
3567    let parent = path
3568        .parent()
3569        .ok_or_else(|| Report::msg("Atomic write target is missing a parent directory"))?;
3570    fs::create_dir_all(parent)?;
3571    let tmp_path = path.with_extension(format!(
3572        "{}.tmp",
3573        path.extension()
3574            .and_then(|ext| ext.to_str())
3575            .unwrap_or("tmp")
3576    ));
3577    fs::write(&tmp_path, bytes)?;
3578    fs::rename(&tmp_path, path)?;
3579    Ok(())
3580}
3581
3582fn write_atomic_json<T: Serialize>(path: &Path, value: &T) -> Result<()> {
3583    write_atomic_bytes(path, &serde_json::to_vec_pretty(value)?)
3584}
3585
3586fn write_observable_resume_state(
3587    integrand: &Integrand,
3588    workspace: Option<&Path>,
3589    slot_meta: &SlotMeta,
3590    iter: usize,
3591    output_control: WorkspaceSnapshotControl,
3592) -> Result<Option<PathBuf>> {
3593    let Some(bundle) = integrand.observable_snapshot_bundle() else {
3594        return Ok(None);
3595    };
3596    let Some(workspace) = workspace else {
3597        return Ok(None);
3598    };
3599    let latest_path = latest_observable_resume_state_path(workspace, slot_meta);
3600    write_atomic_json(&latest_path, &bundle)?;
3601    if output_control.write_iteration_archives {
3602        let archived_path = archived_observable_resume_state_path(workspace, slot_meta, iter);
3603        write_atomic_json(&archived_path, &bundle)?;
3604    }
3605    Ok(Some(latest_path))
3606}
3607
3608fn write_observable_snapshot_archive(
3609    integrand: &Integrand,
3610    workspace: Option<&Path>,
3611    iter: usize,
3612    output_control: WorkspaceSnapshotControl,
3613) -> Result<()> {
3614    if !user_facing_observables_output_enabled(integrand) {
3615        return Ok(());
3616    }
3617    if !output_control.write_iteration_archives {
3618        return Ok(());
3619    }
3620    let Some(workspace) = workspace else {
3621        return Ok(());
3622    };
3623
3624    for format in user_facing_observables_output_formats(integrand) {
3625        let path = archived_observable_output_path(workspace, format, iter);
3626        integrand.write_observable_snapshots(&path, format)?;
3627    }
3628
3629    Ok(())
3630}
3631
3632fn write_latest_observables_output(
3633    integrand: &Integrand,
3634    workspace: Option<&Path>,
3635) -> Result<Vec<PathBuf>> {
3636    if !user_facing_observables_output_enabled(integrand) {
3637        return Ok(Vec::new());
3638    }
3639    let Some(workspace) = workspace else {
3640        return Ok(Vec::new());
3641    };
3642
3643    let mut emitted_paths = Vec::new();
3644    for format in user_facing_observables_output_formats(integrand) {
3645        let path = latest_observable_output_path(workspace, format);
3646        integrand.write_observable_snapshots(&path, format)?;
3647        emitted_paths.push(path);
3648    }
3649
3650    Ok(emitted_paths)
3651}
3652
3653fn write_numerical_stability_snapshot(
3654    bundle: &ObservableSnapshotBundle,
3655    path: &Path,
3656    format: ObservableFileFormat,
3657) -> Result<()> {
3658    match format {
3659        ObservableFileFormat::None => Ok(()),
3660        ObservableFileFormat::Json => write_atomic_json(path, bundle),
3661        ObservableFileFormat::Hwu => {
3662            let parent = path
3663                .parent()
3664                .ok_or_else(|| Report::msg("Numerical stability output is missing a parent"))?;
3665            fs::create_dir_all(parent)?;
3666            bundle.write_hwu_file(path)
3667        }
3668    }
3669}
3670
3671fn write_numerical_stability_outputs(
3672    workspace: Option<&Path>,
3673    integration_state: &IntegrationState,
3674    output_control: WorkspaceSnapshotControl,
3675) -> Result<Vec<PathBuf>> {
3676    let Some(workspace) = workspace else {
3677        return Ok(Vec::new());
3678    };
3679
3680    let mut emitted_paths = Vec::new();
3681    let mut scopes = vec![(
3682        "global".to_string(),
3683        integration_state
3684            .stats
3685            .numerical_stability_snapshot()
3686            .as_observable_snapshot_bundle(),
3687    )];
3688    scopes.extend(
3689        integration_state
3690            .slot_metas
3691            .iter()
3692            .zip(integration_state.slot_stats.iter())
3693            .map(|(slot_meta, stats)| {
3694                (
3695                    slot_meta.key(),
3696                    stats
3697                        .numerical_stability_snapshot()
3698                        .as_observable_snapshot_bundle(),
3699                )
3700            }),
3701    );
3702
3703    for (scope, bundle) in scopes {
3704        for format in [ObservableFileFormat::Json, ObservableFileFormat::Hwu] {
3705            let latest_path = numerical_stability_output_path(workspace, &scope, format, None);
3706            write_numerical_stability_snapshot(&bundle, &latest_path, format)?;
3707            emitted_paths.push(latest_path);
3708            if output_control.write_iteration_archives {
3709                let archive_path = numerical_stability_output_path(
3710                    workspace,
3711                    &scope,
3712                    format,
3713                    Some(integration_state.iter),
3714                );
3715                write_numerical_stability_snapshot(&bundle, &archive_path, format)?;
3716            }
3717        }
3718    }
3719
3720    Ok(emitted_paths)
3721}
3722
3723fn write_integration_state_to_workspace(
3724    workspace_path: &Path,
3725    integration_state: &IntegrationState,
3726) -> Result<()> {
3727    let state_path = workspace_state_path(workspace_path);
3728    let state_bytes = bincode::encode_to_vec(integration_state, bincode::config::standard())
3729        .map_err(|err| {
3730            Report::msg(format!(
3731                "Could not serialize integration state for {}: {err}",
3732                state_path.display()
3733            ))
3734        })?;
3735    write_atomic_bytes(&state_path, &state_bytes)?;
3736    Ok(())
3737}
3738
3739fn write_integration_result_snapshots(
3740    workspace_path: &Path,
3741    integration_state: &IntegrationState,
3742    targets: &[Option<Complex<F<f64>>>],
3743    output_control: WorkspaceSnapshotControl,
3744) -> Result<()> {
3745    let result = build_integration_result(integration_state, targets);
3746    write_atomic_json(&workspace_result_snapshot_path(workspace_path), &result)?;
3747    if output_control.write_iteration_archives {
3748        write_atomic_json(
3749            &workspace_result_archive_path(workspace_path, integration_state.iter),
3750            &result,
3751        )?;
3752    }
3753    Ok(())
3754}
3755
3756fn workspace_relative_display_path(root: &Path, path: &Path) -> String {
3757    path.strip_prefix(root)
3758        .unwrap_or(path)
3759        .display()
3760        .to_string()
3761}
3762
3763fn emit_results_output_summary(
3764    workspace: Option<&Path>,
3765    slots: &[IntegrationSlot],
3766    emitted_paths: &[Vec<PathBuf>],
3767    numerical_stability_paths: &[PathBuf],
3768) {
3769    let rendered = render_results_output_summary_table(
3770        workspace,
3771        slots,
3772        emitted_paths,
3773        numerical_stability_paths,
3774    );
3775    let Some(rendered) = rendered else {
3776        return;
3777    };
3778
3779    info!("\n{rendered}");
3780}
3781
3782fn render_results_output_summary_table(
3783    workspace: Option<&Path>,
3784    slots: &[IntegrationSlot],
3785    emitted_paths: &[Vec<PathBuf>],
3786    numerical_stability_paths: &[PathBuf],
3787) -> Option<String> {
3788    let mut summary_rows = Vec::new();
3789    if let Some(workspace) = workspace {
3790        summary_rows.push((
3791            "workspace path".to_string(),
3792            workspace.display().to_string(),
3793        ));
3794        summary_rows.push((
3795            "results".to_string(),
3796            workspace_relative_display_path(workspace, &workspace_result_snapshot_path(workspace)),
3797        ));
3798    }
3799
3800    for (slot, slot_emitted_paths) in slots.iter().zip(emitted_paths.iter()) {
3801        for final_path in slot_emitted_paths {
3802            if !final_path.exists() {
3803                continue;
3804            }
3805            let display_path = workspace
3806                .map(|root| workspace_relative_display_path(root, final_path))
3807                .unwrap_or_else(|| final_path.display().to_string());
3808            let row_label = if slot_emitted_paths.len() > 1 {
3809                let format_label = final_path
3810                    .extension()
3811                    .and_then(|extension| extension.to_str())
3812                    .unwrap_or("output");
3813                format!("{} ({format_label})", slot_key_label(&slot.meta))
3814            } else {
3815                slot_key_label(&slot.meta)
3816            };
3817            summary_rows.push((row_label, display_path));
3818        }
3819    }
3820
3821    for path in numerical_stability_paths {
3822        if !path.exists() {
3823            continue;
3824        }
3825        let display_path = workspace
3826            .map(|root| workspace_relative_display_path(root, path))
3827            .unwrap_or_else(|| path.display().to_string());
3828        let scope = path
3829            .file_stem()
3830            .and_then(|stem| stem.to_str())
3831            .unwrap_or("numerical_stability");
3832        summary_rows.push((format!("numerical stability ({scope})"), display_path));
3833    }
3834
3835    if summary_rows.is_empty() {
3836        return None;
3837    }
3838
3839    let mut builder = Builder::default();
3840    builder.push_record(["type".to_string(), "path".to_string()]);
3841    for (row_type, row_path) in summary_rows {
3842        builder.push_record([
3843            row_type.blue().bold().to_string(),
3844            row_path.green().to_string(),
3845        ]);
3846    }
3847
3848    let mut table = builder.build();
3849    table.with(Panel::header(
3850        "Integration results emitted".green().bold().to_string(),
3851    ));
3852    table.with(
3853        Style::rounded().horizontals([(
3854            1,
3855            HorizontalLine::new('─')
3856                .intersection('┼')
3857                .left('├')
3858                .right('┤'),
3859        )]),
3860    );
3861    table.with(Modify::new(Rows::first()).with(Alignment::left()));
3862    table.with(Modify::new(Columns::new(0..2)).with(Alignment::left()));
3863
3864    Some(utils::normalize_tabled_separator_rows(&table.to_string()))
3865}
3866
3867/// This function actually evaluates the list of samples in parallel.
3868fn evaluate_sample_list(
3869    integrand: &mut Integrand,
3870    samples: &[Sample<F<f64>>],
3871    model: &Model,
3872    num_cores: usize,
3873    iter: usize,
3874    max_eval: Complex<F<f64>>,
3875) -> Result<(Vec<EvaluationResult>, StatisticsCounter)> {
3876    let list_size = samples.len();
3877    let nvec_per_core = (list_size - 1) / num_cores + 1;
3878    let num_chunks = samples.chunks(nvec_per_core).len();
3879
3880    let sample_chunks = samples.par_chunks(nvec_per_core);
3881    let integrands = (0..num_chunks)
3882        .map(|_| integrand.clone())
3883        .collect_vec()
3884        .into_par_iter();
3885
3886    let evaluation_results_per_core: Vec<
3887        Result<(Vec<EvaluationResult>, StatisticsCounter, Integrand)>,
3888    > = sample_chunks
3889        .zip(integrands)
3890        .map(|(chunk, mut integrand)| {
3891            let raw_batch = integrand.evaluate_samples_raw(
3892                chunk,
3893                EvaluationTarget::Physical(model),
3894                iter,
3895                false,
3896                false,
3897                max_eval,
3898            )?;
3899            for result in &raw_batch.samples {
3900                integrand.process_evaluation_result(result)?;
3901            }
3902            Ok((raw_batch.samples, raw_batch.statistics, integrand))
3903        })
3904        .collect();
3905    let mut evaluation_results_per_core: Vec<(
3906        Vec<EvaluationResult>,
3907        StatisticsCounter,
3908        Integrand,
3909    )> = evaluation_results_per_core
3910        .into_iter()
3911        .collect::<Result<_>>()?;
3912
3913    for (_, _, worker_integrand) in evaluation_results_per_core.iter_mut() {
3914        integrand.merge_runtime_results(worker_integrand)?;
3915    }
3916
3917    let (evaluation_results, meta_data_statistics) = evaluation_results_per_core.into_iter().fold(
3918        (Vec::new(), StatisticsCounter::new_empty()),
3919        |(mut all_results, stats), (results, worker_stats, _)| {
3920            all_results.extend(results);
3921            (all_results, stats.merged(&worker_stats))
3922        },
3923    );
3924
3925    Ok((evaluation_results, meta_data_statistics))
3926}
3927
3928/// Different ways of passing samples to the batch_integrate function
3929/// One is simply a list of samples, the other is a grid and the desired number of samples
3930/// The worker then generates the samples itself.
3931#[derive(Serialize, Deserialize)]
3932pub enum SampleInput {
3933    SampleList {
3934        samples: Vec<Sample<F<f64>>>,
3935    },
3936    Grid {
3937        grid: Box<Grid<F<f64>>>,
3938        num_points: usize,
3939        seed: u64,
3940        thread_id: usize,
3941    },
3942}
3943
3944type AccumulatorPair = (StatisticsAccumulator<F<f64>>, StatisticsAccumulator<F<f64>>);
3945
3946#[derive(Serialize, Deserialize)]
3947pub enum BatchIntegrateOutput {
3948    Default(Vec<Complex<F<f64>>>, Vec<Sample<F<f64>>>),
3949    Accumulator(Box<AccumulatorPair>, Box<Grid<F<f64>>>),
3950}
3951
3952/// Different ways of processing events, EventList is a list of events, Histogram does accumulation of events on the worker nodes, so the
3953/// master node only has to merge the histograms.
3954#[derive(Serialize, Deserialize)]
3955pub enum EventOutput {
3956    None,
3957    EventList {
3958        event_groups: EventGroupList,
3959    },
3960    Histogram {
3961        histograms: ObservableAccumulatorBundle,
3962    },
3963}
3964
3965/// The result of evaluating a batch of points
3966#[derive(Serialize, Deserialize, Encode, Decode)]
3967pub struct BatchResult {
3968    pub statistics: StatisticsCounter,
3969    #[bincode(with_serde)]
3970    pub integrand_data: BatchIntegrateOutput,
3971    #[bincode(with_serde)]
3972    pub event_data: EventOutput,
3973}
3974
3975/// Input for the batch_integrate function, created by the master node
3976pub struct BatchIntegrateInput<'a> {
3977    // global run info:
3978    pub max_eval: Complex<F<f64>>,
3979    pub iter: usize,
3980    pub settings: &'a RuntimeSettings,
3981    // input data:
3982    pub samples: SampleInput,
3983    pub integrand_output_settings: IntegralOutputSettings,
3984    pub event_output_settings: EventOutputSettings,
3985    pub num_cores: usize,
3986}
3987
3988/// Choose whether to output the integrand results, or a statistics accumulator
3989#[derive(Serialize, Deserialize)]
3990pub enum IntegralOutputSettings {
3991    Default,
3992    Accumulator,
3993}
3994
3995/// Choose whether to output an eventlist, a histogram, or nothing
3996#[derive(Serialize, Deserialize)]
3997pub enum EventOutputSettings {
3998    None,
3999    EventList,
4000    Histogram,
4001}
4002
4003#[derive(Serialize, Deserialize, Encode, Decode)]
4004pub struct SerializableBatchIntegrateInput {
4005    #[bincode(with_serde)]
4006    pub max_eval: Complex<F<f64>>,
4007    pub iter: usize,
4008    #[bincode(with_serde)]
4009    pub samples: SampleInput,
4010    #[bincode(with_serde)]
4011    pub integrand_output_settings: IntegralOutputSettings,
4012    #[bincode(with_serde)]
4013    pub event_output_settings: EventOutputSettings,
4014    pub num_cores: usize,
4015}
4016
4017impl SerializableBatchIntegrateInput {
4018    pub(crate) fn into_batch_integrate_input(
4019        self,
4020        settings: &RuntimeSettings,
4021    ) -> BatchIntegrateInput<'_> {
4022        BatchIntegrateInput {
4023            max_eval: self.max_eval,
4024            iter: self.iter,
4025            samples: self.samples,
4026            integrand_output_settings: self.integrand_output_settings,
4027            event_output_settings: self.event_output_settings,
4028            num_cores: self.num_cores,
4029            settings,
4030        }
4031    }
4032}
4033
4034/// Master node which accumulates data from jobs, and creates the input for jobs
4035#[derive(Clone)]
4036pub struct MasterNode {
4037    grid: Grid<F<f64>>,
4038    integrator_settings: IntegratorSettings,
4039    master_accumulator_re: StatisticsAccumulator<F<f64>>,
4040    master_accumulator_im: StatisticsAccumulator<F<f64>>,
4041    statistics: StatisticsCounter,
4042    observable_accumulators: Option<ObservableAccumulatorBundle>,
4043    event_groups: EventGroupList,
4044    current_iter: usize,
4045}
4046
4047impl MasterNode {
4048    pub(crate) fn new(grid: Grid<F<f64>>, integrator_settings: IntegratorSettings) -> Self {
4049        MasterNode {
4050            grid,
4051            integrator_settings,
4052            master_accumulator_im: StatisticsAccumulator::new(),
4053            master_accumulator_re: StatisticsAccumulator::new(),
4054            statistics: StatisticsCounter::new_empty(),
4055            observable_accumulators: None,
4056            event_groups: EventGroupList::default(),
4057            current_iter: 0,
4058        }
4059    }
4060
4061    /// Update the grid with the data from another grid.
4062    fn update_grid_with_grid(&mut self, other_grid: &Grid<F<f64>>) -> Result<(), String> {
4063        self.grid.merge(other_grid)
4064    }
4065
4066    /// Update the grid with the data from a set of samples.
4067    fn update_grid_with_samples(
4068        &mut self,
4069        samples_points: &[Sample<F<f64>>],
4070        results: &[Complex<F<f64>>],
4071    ) -> Result<(), String> {
4072        let integrated_phase = self.integrator_settings.integrated_phase;
4073
4074        for (sample_point, result) in samples_points.iter().zip(results.iter()) {
4075            match integrated_phase {
4076                IntegratedPhase::Real => self.grid.add_training_sample(sample_point, result.re)?,
4077                IntegratedPhase::Imag => self.grid.add_training_sample(sample_point, result.im)?,
4078                IntegratedPhase::Both => {
4079                    unimplemented!("integrated phase both not yet implemented")
4080                }
4081            }
4082        }
4083
4084        Ok(())
4085    }
4086
4087    /// Update the accumulators with the data from another set of accumulators.
4088    pub(crate) fn update_accumulators_with_accumulators(
4089        &mut self,
4090        mut real_accumulator: StatisticsAccumulator<F<f64>>,
4091        mut imaginary_accumulator: StatisticsAccumulator<F<f64>>,
4092    ) {
4093        self.master_accumulator_re
4094            .merge_samples(&mut real_accumulator);
4095
4096        self.master_accumulator_im
4097            .merge_samples(&mut imaginary_accumulator);
4098    }
4099
4100    /// Update the accumulators with the data from a set of samples.
4101    fn update_accumuators_with_samples(
4102        &mut self,
4103        sample_points: &[Sample<F<f64>>],
4104        results: &[Complex<F<f64>>],
4105    ) {
4106        for (sample_point, result) in sample_points.iter().zip(results.iter()) {
4107            self.master_accumulator_re
4108                .add_sample(result.re * sample_point.get_weight(), Some(sample_point));
4109
4110            self.master_accumulator_im
4111                .add_sample(result.im * sample_point.get_weight(), Some(sample_point));
4112        }
4113    }
4114
4115    /// Update the metadata statistics with the data from another set of metadata statistics.
4116    fn update_metadata_statistics(&mut self, statistics: StatisticsCounter) {
4117        self.statistics = self.statistics.merged(&statistics);
4118    }
4119
4120    /// Finish the current iteration. This should be called after all jobs have been processed.
4121    pub(crate) fn update_iter(&mut self) {
4122        self.grid.update(
4123            F(self.integrator_settings.discrete_dim_learning_rate),
4124            F(self.integrator_settings.continuous_dim_learning_rate),
4125        );
4126        self.master_accumulator_re.update_iter(false);
4127        self.master_accumulator_im.update_iter(false);
4128        if let Some(observable_accumulators) = self.observable_accumulators.as_mut() {
4129            observable_accumulators.update_results();
4130        }
4131
4132        self.current_iter += 1;
4133    }
4134
4135    /// Write the input for a batch job to a file.
4136    pub(crate) fn write_batch_input(
4137        &mut self,
4138        num_cores: usize,
4139        num_samples: usize,
4140        export_grid: bool,
4141        output_accumulator: bool,
4142        workspace_path: &str,
4143        job_id: usize,
4144    ) -> Result<(), Report> {
4145        let max_eval = Complex::new(
4146            self.master_accumulator_re
4147                .max_eval_positive
4148                .max(self.master_accumulator_re.max_eval_negative),
4149            self.master_accumulator_im
4150                .max_eval_positive
4151                .max(self.master_accumulator_im.max_eval_negative),
4152        );
4153
4154        let samples = if export_grid {
4155            SampleInput::Grid {
4156                grid: Box::new(self.grid.clone()),
4157                num_points: num_samples,
4158                seed: self.integrator_settings.seed,
4159                thread_id: job_id,
4160            }
4161        } else {
4162            let mut rng = rand::rng();
4163            let mut samples_temp = vec![Sample::new(); num_samples];
4164            for sample in samples_temp.iter_mut() {
4165                self.grid.sample(&mut rng, sample);
4166            }
4167            SampleInput::SampleList {
4168                samples: samples_temp,
4169            }
4170        };
4171
4172        let integrand_output_settings = if output_accumulator {
4173            IntegralOutputSettings::Accumulator
4174        } else {
4175            IntegralOutputSettings::Default
4176        };
4177
4178        let input = SerializableBatchIntegrateInput {
4179            num_cores,
4180            max_eval,
4181            iter: self.current_iter,
4182            samples,
4183            integrand_output_settings,
4184            event_output_settings: EventOutputSettings::None,
4185        };
4186
4187        let input_bytes = bincode::encode_to_vec(&input, bincode::config::standard())?;
4188        let job_name = format!("job_{}", job_id);
4189        let job_path = std::path::Path::new(workspace_path).join(job_name);
4190
4191        std::fs::write(job_path, input_bytes)?;
4192
4193        Ok(())
4194    }
4195
4196    /// Process the output of a batch job.
4197    pub(crate) fn process_batch_output(&mut self, output: BatchResult) -> Result<(), String> {
4198        self.update_metadata_statistics(output.statistics);
4199
4200        match output.integrand_data {
4201            BatchIntegrateOutput::Default(results, samples) => {
4202                self.update_accumuators_with_samples(&samples, &results);
4203                self.update_grid_with_samples(&samples, &results)?;
4204            }
4205            BatchIntegrateOutput::Accumulator(accumulators, grid) => {
4206                let (real_accumulator, imag_accumulator) = *accumulators;
4207                self.update_accumulators_with_accumulators(real_accumulator, imag_accumulator);
4208                self.update_grid_with_grid(&grid)?;
4209            }
4210        }
4211
4212        match output.event_data {
4213            EventOutput::None => {}
4214            EventOutput::EventList { mut event_groups } => {
4215                self.event_groups.append(&mut event_groups);
4216            }
4217            EventOutput::Histogram { mut histograms } => {
4218                if let Some(existing) = self.observable_accumulators.as_mut() {
4219                    existing
4220                        .merge_samples(&mut histograms)
4221                        .map_err(|err| err.to_string())?;
4222                } else {
4223                    self.observable_accumulators = Some(histograms);
4224                }
4225            }
4226        }
4227
4228        Ok(())
4229    }
4230
4231    /// Display the current status of the integration. Usually called after each iteration.
4232    pub(crate) fn display_status(&self) {
4233        let status_block = [
4234            render_integral_result(
4235                &self.master_accumulator_re,
4236                "itg",
4237                self.current_iter,
4238                "re",
4239                None,
4240            ),
4241            render_integral_result(
4242                &self.master_accumulator_im,
4243                "itg",
4244                self.current_iter,
4245                "im",
4246                None,
4247            ),
4248            self.statistics.render_status_table(),
4249        ]
4250        .join("\n");
4251
4252        info!("\n{status_block}");
4253    }
4254}
4255
4256pub fn emit_integration_status_via_tracing(
4257    kind: IntegrationStatusKind,
4258    status_block: impl AsRef<str>,
4259) -> Result<()> {
4260    let status_block = status_block.as_ref();
4261    match kind {
4262        IntegrationStatusKind::Live => {}
4263        IntegrationStatusKind::Iteration => {
4264            info!("\n{status_block}");
4265            info!("");
4266        }
4267        IntegrationStatusKind::Final => {
4268            info!("");
4269            info!("{}", "Final integration results:".bold().green());
4270            info!("");
4271            info!("\n{status_block}");
4272            info!("");
4273        }
4274    }
4275
4276    Ok(())
4277}
4278
4279pub fn render_saved_integration_summary(
4280    integration_state: &IntegrationState,
4281    targets: &[Option<Complex<F<f64>>>],
4282    view_options: &IntegrationStatusViewOptions,
4283    tabled_options: &TabledRenderOptions,
4284) -> String {
4285    render_tabled::render_status_update(
4286        &build_saved_status_update(integration_state, targets, view_options),
4287        tabled_options,
4288    )
4289}
4290
4291pub fn render_status_update_tabled(
4292    update: &StatusUpdate,
4293    tabled_options: &TabledRenderOptions,
4294) -> String {
4295    render_tabled::render_status_update(update, tabled_options)
4296}
4297
4298fn integral_estimate(
4299    re: &StatisticsAccumulator<F<f64>>,
4300    im: &StatisticsAccumulator<F<f64>>,
4301) -> IntegralEstimate {
4302    IntegralEstimate {
4303        neval: re.processed_samples,
4304        real_zero: re.num_zero_evaluations,
4305        im_zero: im.num_zero_evaluations,
4306        result: Complex::new(re.avg, im.avg),
4307        error: Complex::new(re.err, im.err),
4308        real_chisq: re.chi_sq,
4309        im_chisq: im.chi_sq,
4310    }
4311}
4312
4313pub fn build_integration_result(
4314    integration_state: &IntegrationState,
4315    targets: &[Option<Complex<F<f64>>>],
4316) -> IntegrationResult {
4317    let integration_statistics = integration_state.stats.snapshot();
4318    let slots = integration_state
4319        .slot_metas
4320        .iter()
4321        .enumerate()
4322        .map(|(slot_index, slot_meta)| {
4323            let accumulator = &integration_state.all_integrals[slot_index];
4324            let discrete_context =
4325                integration_state.monitored_discrete_context_for_slot(slot_index);
4326            SlotIntegrationResult {
4327                key: slot_meta.key(),
4328                process: slot_meta.process_name.clone(),
4329                integrand: slot_meta.integrand_name.clone(),
4330                target: targets[slot_index],
4331                integral: integral_estimate(&accumulator.re, &accumulator.im),
4332                table_results: build_table_result_summary(
4333                    slot_meta,
4334                    accumulator,
4335                    integration_state.iter,
4336                    targets[slot_index],
4337                ),
4338                integration_statistics: integration_statistics.clone(),
4339                max_weight_info: build_max_weight_info_summary(
4340                    &integration_state
4341                        .sampling_state_for_slot(slot_index)
4342                        .discrete_axis_labels,
4343                    accumulator,
4344                ),
4345                grid_breakdown: ComponentDiscreteBreakdown {
4346                    re: discrete_context.as_ref().and_then(|context| {
4347                        integration_state.slot_re_summaries[slot_index]
4348                            .as_ref()
4349                            .zip(
4350                                integration_state
4351                                    .slot_first_non_trivial_discrete_breakdown_metadata[slot_index]
4352                                    .as_ref(),
4353                            )
4354                            .and_then(|(summary, metadata)| {
4355                                summary_at_path(summary, &context.path).and_then(|summary| {
4356                                    summary.first_non_trivial_breakdown(metadata, &context.pdfs)
4357                                })
4358                            })
4359                    }),
4360                    im: discrete_context.as_ref().and_then(|context| {
4361                        integration_state.slot_im_summaries[slot_index]
4362                            .as_ref()
4363                            .zip(
4364                                integration_state
4365                                    .slot_first_non_trivial_discrete_breakdown_metadata[slot_index]
4366                                    .as_ref(),
4367                            )
4368                            .and_then(|(summary, metadata)| {
4369                                summary_at_path(summary, &context.path).and_then(|summary| {
4370                                    summary.first_non_trivial_breakdown(metadata, &context.pdfs)
4371                                })
4372                            })
4373                    }),
4374                },
4375                absolute: AbsoluteIntegrationResult {
4376                    integral: integral_estimate(&accumulator.absolute_re, &accumulator.absolute_im),
4377                    table_results: build_absolute_table_result_summary(
4378                        slot_meta,
4379                        accumulator,
4380                        integration_state.iter,
4381                    ),
4382                    max_weight_info: build_absolute_max_weight_info_summary(
4383                        &integration_state
4384                            .sampling_state_for_slot(slot_index)
4385                            .discrete_axis_labels,
4386                        accumulator,
4387                    ),
4388                    grid_breakdown: ComponentDiscreteBreakdown {
4389                        re: discrete_context.as_ref().and_then(|context| {
4390                            integration_state.slot_absolute_re_summaries[slot_index]
4391                                .as_ref()
4392                                .zip(
4393                                    integration_state
4394                                        .slot_first_non_trivial_discrete_breakdown_metadata
4395                                        [slot_index]
4396                                        .as_ref(),
4397                                )
4398                                .and_then(|(summary, metadata)| {
4399                                    summary.first_non_trivial_breakdown(metadata, &context.pdfs)
4400                                })
4401                        }),
4402                        im: discrete_context.as_ref().and_then(|context| {
4403                            integration_state.slot_absolute_im_summaries[slot_index]
4404                                .as_ref()
4405                                .zip(
4406                                    integration_state
4407                                        .slot_first_non_trivial_discrete_breakdown_metadata
4408                                        [slot_index]
4409                                        .as_ref(),
4410                                )
4411                                .and_then(|(summary, metadata)| {
4412                                    summary.first_non_trivial_breakdown(metadata, &context.pdfs)
4413                                })
4414                        }),
4415                    },
4416                },
4417            }
4418        })
4419        .collect();
4420
4421    IntegrationResult { slots }
4422}
4423
4424pub fn print_integral_result(
4425    itg: &StatisticsAccumulator<F<f64>>,
4426    label: &str,
4427    i_iter: usize,
4428    tag: &str,
4429    trgt: Option<F<f64>>,
4430) {
4431    info!("{}", render_integral_result(itg, label, i_iter, tag, trgt));
4432}
4433
4434#[allow(clippy::format_in_format_args)]
4435fn render_integral_result(
4436    itg: &StatisticsAccumulator<F<f64>>,
4437    label: &str,
4438    i_iter: usize,
4439    tag: &str,
4440    trgt: Option<F<f64>>,
4441) -> String {
4442    let slot_meta = SlotMeta {
4443        process_name: label.to_string(),
4444        integrand_name: String::new(),
4445    };
4446    let mut cells = build_integral_result_cells(itg, &slot_meta, i_iter, tag, trgt);
4447    cells.integrand = format!("{label} {}:", format!("{:-2}", tag).blue().bold());
4448    let delta = match (cells.delta_sigma.as_ref(), cells.delta_percent.as_ref()) {
4449        (Some(delta_sigma), Some(delta_percent)) => format!("{delta_sigma}, {delta_percent}"),
4450        _ => String::new(),
4451    };
4452
4453    format!(
4454        "|  {} {} {} {} {} {}",
4455        cells.integrand, cells.value, cells.relative_error, cells.chi_sq, delta, cells.mwi
4456    )
4457}
4458
4459#[cfg(test)]
4460mod tests {
4461    use super::*;
4462    use crate::integrands::TestProbeIntegrand;
4463    use colored::control;
4464    use ratatui::{Terminal, backend::TestBackend};
4465    use std::fs;
4466    use symbolica::numerical_integration::ContinuousGrid;
4467
4468    fn integration_workspace_manifest(version: Option<u32>) -> IntegrationWorkspaceManifest {
4469        let mut manifest = serde_json::json!({
4470            "slots": [],
4471            "targets": [],
4472            "effective_model_parameters": [],
4473            "integrand_fingerprints": [],
4474            "training_slot": 0,
4475            "integrator_settings_slot": 0,
4476            "sampling_correlation_mode": "correlated"
4477        });
4478        if let Some(version) = version {
4479            manifest["version"] = version.into();
4480        }
4481        serde_json::from_value(manifest).unwrap()
4482    }
4483
4484    #[test]
4485    fn integration_workspace_manifest_accepts_only_the_current_version() {
4486        integration_workspace_manifest(Some(IntegrationWorkspaceManifest::CURRENT_VERSION))
4487            .validate_version()
4488            .unwrap();
4489
4490        let unversioned = integration_workspace_manifest(None);
4491        assert_eq!(unversioned.version, 0);
4492        let unversioned_error = unversioned.validate_version().unwrap_err().to_string();
4493        assert!(unversioned_error.contains("unversioned"));
4494        assert!(unversioned_error.contains("--restart"));
4495
4496        let previous = integration_workspace_manifest(Some(2));
4497        let previous_error = previous.validate_version().unwrap_err().to_string();
4498        assert!(previous_error.contains("--restart"));
4499
4500        let future =
4501            integration_workspace_manifest(Some(IntegrationWorkspaceManifest::CURRENT_VERSION + 1));
4502        let future_error = future.validate_version().unwrap_err().to_string();
4503        assert!(future_error.contains("newer format version"));
4504        assert!(future_error.contains("--restart"));
4505    }
4506
4507    fn make_accumulator(
4508        re_avg: f64,
4509        re_err: f64,
4510        re_chi_sq: f64,
4511        im_avg: f64,
4512        im_err: f64,
4513        im_chi_sq: f64,
4514    ) -> ComplexAccumulator {
4515        let mut accumulator = ComplexAccumulator::new();
4516        accumulator.re.avg = F(re_avg);
4517        accumulator.re.err = F(re_err);
4518        accumulator.re.chi_sq = F(re_chi_sq);
4519        accumulator.re.processed_samples = 100_000;
4520        accumulator.re.max_eval_positive = F(1.0);
4521        accumulator.im.avg = F(im_avg);
4522        accumulator.im.err = F(im_err);
4523        accumulator.im.chi_sq = F(im_chi_sq);
4524        accumulator.im.processed_samples = 100_000;
4525        accumulator.im.max_eval_positive = F(1.0);
4526        accumulator.absolute_re.avg = F(re_avg.abs() * 2.0);
4527        accumulator.absolute_re.err = F(re_err.abs());
4528        accumulator.absolute_re.chi_sq = F(re_chi_sq);
4529        accumulator.absolute_re.processed_samples = 100_000;
4530        accumulator.absolute_re.max_eval_positive = F(2.0);
4531        accumulator.absolute_im.avg = F(im_avg.abs() * 2.0);
4532        accumulator.absolute_im.err = F(im_err.abs());
4533        accumulator.absolute_im.chi_sq = F(im_chi_sq);
4534        accumulator.absolute_im.processed_samples = 100_000;
4535        accumulator.absolute_im.max_eval_positive = F(2.0);
4536        accumulator
4537    }
4538
4539    #[test]
4540    fn absolute_channel_sum_retains_outer_cube_covariance() {
4541        let mut accumulator = ComplexAccumulator::new();
4542        // The two channel points give (+a,-a): signed cancellation is exact,
4543        // but the physical absolute observation is 2a. Its variance includes
4544        // the perfect cross-channel covariance on each shared outer cube.
4545        for a in [1.0, 2.0, 3.0] {
4546            accumulator.add_sample(
4547                Complex::new_zero(),
4548                Some(Complex::new(F(2.0 * a), F(4.0 * a))),
4549                F(1.0),
4550                None,
4551            );
4552        }
4553        accumulator.update_iter(false);
4554        assert_eq!(accumulator.re.avg, F(0.0));
4555        assert_eq!(accumulator.im.avg, F(0.0));
4556        assert_eq!(accumulator.absolute_re.avg, F(4.0));
4557        assert_eq!(accumulator.absolute_im.avg, F(8.0));
4558        assert_eq!(accumulator.absolute_re.processed_samples, 3);
4559        assert!((accumulator.absolute_re.err - F((4.0_f64 / 3.0).sqrt())).abs() < F(1.0e-12));
4560        assert!((accumulator.absolute_im.err - F((16.0_f64 / 3.0).sqrt())).abs() < F(1.0e-12));
4561    }
4562
4563    #[test]
4564    fn complex_accumulator_tracks_componentwise_absolute_weighted_samples_and_merges() {
4565        let first_sample = Sample::Continuous(F(1.0), vec![F(0.25)]);
4566        let second_sample = Sample::Continuous(F(1.0), vec![F(0.75)]);
4567        let mut accumulator = ComplexAccumulator::new();
4568        let mut other = ComplexAccumulator::new();
4569
4570        accumulator.add_sample(
4571            Complex::new(F(-2.0), F(3.0)),
4572            None,
4573            F(2.0),
4574            Some(&first_sample),
4575        );
4576        other.add_sample(
4577            Complex::new(F(1.0), F(-4.0)),
4578            None,
4579            F(2.0),
4580            Some(&second_sample),
4581        );
4582        accumulator.merge(&other);
4583        accumulator.update_iter(false);
4584
4585        assert_eq!(accumulator.re.avg, F(-1.0));
4586        assert_eq!(accumulator.im.avg, F(-1.0));
4587        assert_eq!(accumulator.absolute_re.avg, F(3.0));
4588        assert_eq!(accumulator.absolute_im.avg, F(7.0));
4589        assert!((accumulator.absolute_re.err - F(1.0)).abs() < F(1.0e-12));
4590        assert!((accumulator.absolute_im.err - F(1.0)).abs() < F(1.0e-12));
4591        assert_eq!(accumulator.absolute_re.processed_samples, 2);
4592        assert_eq!(accumulator.absolute_im.processed_samples, 2);
4593        assert_eq!(accumulator.absolute_re.max_eval_positive, F(4.0));
4594        assert_eq!(accumulator.absolute_im.max_eval_positive, F(8.0));
4595        assert_eq!(
4596            accumulator
4597                .absolute_re
4598                .max_eval_positive_xs
4599                .as_ref()
4600                .map(|sample| format!("{sample:?}")),
4601            Some(format!("{first_sample:?}"))
4602        );
4603        assert_eq!(
4604            accumulator
4605                .absolute_im
4606                .max_eval_positive_xs
4607                .as_ref()
4608                .map(|sample| format!("{sample:?}")),
4609            Some(format!("{second_sample:?}"))
4610        );
4611    }
4612
4613    #[test]
4614    fn shallow_absolute_monitor_uses_local_path_pdfs_and_has_no_descendants() {
4615        let continuous_grid =
4616            || Grid::Continuous(ContinuousGrid::new(1, 8, 10, None, false).unwrap());
4617        let monitored_grid = Grid::Discrete(
4618            DiscreteGrid::new(
4619                vec![Some(continuous_grid()), Some(continuous_grid())],
4620                F(10.0),
4621                false,
4622            )
4623            .unwrap(),
4624        );
4625        let mut production_grid =
4626            Grid::Discrete(DiscreteGrid::new(vec![Some(monitored_grid)], F(10.0), false).unwrap());
4627        let Grid::Discrete(root) = &mut production_grid else {
4628            unreachable!()
4629        };
4630        let Some(Grid::Discrete(monitored)) = root.bins[0].sub_grid.as_mut() else {
4631            unreachable!()
4632        };
4633        monitored.bins[0].pdf = F(0.25);
4634        monitored.bins[1].pdf = F(0.75);
4635
4636        let mut monitor = shallow_discrete_monitor_grid(&production_grid, &[0])
4637            .expect("nested discrete path should produce a shallow monitor");
4638        assert_eq!(monitor.bins[0].pdf, F(0.25));
4639        assert_eq!(monitor.bins[1].pdf, F(0.75));
4640        assert!(monitor.bins.iter().all(|bin| bin.sub_grid.is_none()));
4641
4642        let sample = |bin_index, local_weight, x| {
4643            Sample::Discrete(
4644                F(local_weight),
4645                0,
4646                Some(Box::new(Sample::Discrete(
4647                    F(local_weight),
4648                    bin_index,
4649                    Some(Box::new(Sample::Continuous(F(1.0), vec![F(x)]))),
4650                ))),
4651            )
4652        };
4653        for (sample, evaluation) in [
4654            (sample(0, 4.0, 0.1), F(-3.0)),
4655            (sample(0, 4.0, 0.2), F(5.0)),
4656            (sample(1, 4.0 / 3.0, 0.3), F(-6.0)),
4657            (sample(1, 4.0 / 3.0, 0.4), F(10.0)),
4658        ] {
4659            add_shallow_monitor_sample(Some(&mut monitor), Some(&[0]), &sample, evaluation)
4660                .expect("valid local discrete sample should be accumulated");
4661        }
4662
4663        let mut summary = DiscreteGridAccumulatorSummary::from_shallow_grid(&monitor);
4664        summary.merge_shallow_iteration_grid(&monitor);
4665        summary.update_iter();
4666        assert!(summary.bins.iter().all(|bin| bin.sub_summary.is_none()));
4667        assert_eq!(summary.bins[0].accumulator.avg, F(4.0));
4668        assert_eq!(summary.bins[1].accumulator.avg, F(8.0));
4669        assert_eq!(summary.bins[0].accumulator.processed_samples, 2);
4670        assert_eq!(summary.bins[1].accumulator.processed_samples, 2);
4671
4672        let mismatched_sample =
4673            Sample::Discrete(F(1.0), 1, Some(Box::new(Sample::Discrete(F(1.0), 0, None))));
4674        assert!(
4675            add_shallow_monitor_sample(Some(&mut monitor), Some(&[0]), &mismatched_sample, F(1.0),)
4676                .is_err()
4677        );
4678    }
4679
4680    #[test]
4681    fn shallow_monitor_creation_does_not_change_production_sampling_sequence() {
4682        let continuous_grid =
4683            || Grid::Continuous(ContinuousGrid::new(1, 8, 10, None, false).unwrap());
4684        let monitored_grid = Grid::Discrete(
4685            DiscreteGrid::new(
4686                vec![Some(continuous_grid()), Some(continuous_grid())],
4687                F(10.0),
4688                false,
4689            )
4690            .unwrap(),
4691        );
4692        let sampling_grid =
4693            Grid::Discrete(DiscreteGrid::new(vec![Some(monitored_grid)], F(10.0), false).unwrap());
4694        let settings = RuntimeSettings::default();
4695        let integrand = Integrand::TestProbe(TestProbeIntegrand::new(settings, 3));
4696        let mut without_monitor = CoreIterationState::new(
4697            vec![integrand.clone()],
4698            SamplingCorrelationMode::Correlated,
4699            std::slice::from_ref(&sampling_grid),
4700            None,
4701            37,
4702            11,
4703            0,
4704        );
4705        let mut with_monitor = CoreIterationState::new(
4706            vec![integrand],
4707            SamplingCorrelationMode::Correlated,
4708            std::slice::from_ref(&sampling_grid),
4709            Some(&[0]),
4710            37,
4711            11,
4712            0,
4713        );
4714
4715        for _ in 0..16 {
4716            let mut without_sample = Sample::new();
4717            let mut with_sample = Sample::new();
4718            let without_state = &mut without_monitor.sampling_states[0];
4719            without_state
4720                .sampling_grid
4721                .sample(&mut without_state.rng, &mut without_sample);
4722            let with_state = &mut with_monitor.sampling_states[0];
4723            with_state
4724                .sampling_grid
4725                .sample(&mut with_state.rng, &mut with_sample);
4726            assert_eq!(format!("{without_sample:?}"), format!("{with_sample:?}"));
4727        }
4728    }
4729
4730    struct StatisticsFixture {
4731        precision: crate::settings::runtime::Precision,
4732        total_time: Duration,
4733        integrand_time: Duration,
4734        evaluator_time: Duration,
4735        parameterization_time: Duration,
4736        event_time: Duration,
4737        generated_event_count: usize,
4738        accepted_event_count: usize,
4739    }
4740
4741    fn make_statistics_counter(fixture: StatisticsFixture) -> StatisticsCounter {
4742        let mut evaluation = EvaluationResult::zero();
4743        evaluation.evaluation_metadata.total_timing = fixture.total_time;
4744        evaluation.evaluation_metadata.integrand_evaluation_time = fixture.integrand_time;
4745        evaluation.evaluation_metadata.evaluator_evaluation_time = fixture.evaluator_time;
4746        evaluation.evaluation_metadata.parameterization_time = fixture.parameterization_time;
4747        evaluation.evaluation_metadata.event_processing_time = fixture.event_time;
4748        evaluation.evaluation_metadata.generated_event_count = fixture.generated_event_count;
4749        evaluation.evaluation_metadata.accepted_event_count = fixture.accepted_event_count;
4750        let estimated_relative_accuracy = match fixture.precision {
4751            crate::settings::runtime::Precision::Double => Some(F(2.4e-16)),
4752            crate::settings::runtime::Precision::Quad => Some(F(1.3e-26)),
4753            crate::settings::runtime::Precision::Arb => None,
4754        };
4755        evaluation.evaluation_metadata.stability_results.push(
4756            crate::integrands::evaluation::StabilityResult {
4757                representation: crate::settings::global::RepresentationMode::Cff,
4758                precision: fixture.precision,
4759                estimated_relative_accuracy,
4760                estimated_decimal_digits: estimated_relative_accuracy
4761                    .filter(|accuracy| accuracy.0 != 0.0 && accuracy.0.is_finite())
4762                    .map(|accuracy| F(-accuracy.0.abs().log10())),
4763                status: crate::integrands::evaluation::StabilityStatus::Stable(2),
4764                total_time: fixture.total_time,
4765            },
4766        );
4767        StatisticsCounter::from_evaluation_results(&[evaluation])
4768    }
4769
4770    fn make_integration_state() -> IntegrationState {
4771        let sampling_grid = Grid::Continuous(ContinuousGrid::new(1, 64, 100, None, false).unwrap());
4772        let mut state = IntegrationState::new_from_settings(
4773            SamplingCorrelationMode::Correlated,
4774            vec![SamplingSlotState::new(sampling_grid, Vec::new())],
4775            vec![
4776                SlotMeta {
4777                    process_name: "proc_a".to_string(),
4778                    integrand_name: "itg_a".to_string(),
4779                },
4780                SlotMeta {
4781                    process_name: "proc_b".to_string(),
4782                    integrand_name: "itg_b".to_string(),
4783                },
4784            ],
4785            None,
4786            None,
4787            None,
4788            vec![None, None],
4789        );
4790        state.iter = 1;
4791        state.num_points = 100_000;
4792        state.slot_stats = vec![
4793            make_statistics_counter(StatisticsFixture {
4794                precision: crate::settings::runtime::Precision::Double,
4795                total_time: Duration::from_micros(462),
4796                integrand_time: Duration::from_micros(414),
4797                evaluator_time: Duration::from_micros(279),
4798                parameterization_time: Duration::from_nanos(5_800),
4799                event_time: Duration::from_micros(12),
4800                generated_event_count: 7,
4801                accepted_event_count: 5,
4802            }),
4803            make_statistics_counter(StatisticsFixture {
4804                precision: crate::settings::runtime::Precision::Quad,
4805                total_time: Duration::from_micros(900),
4806                integrand_time: Duration::from_micros(810),
4807                evaluator_time: Duration::from_micros(120),
4808                parameterization_time: Duration::from_micros(34),
4809                event_time: Duration::from_micros(40),
4810                generated_event_count: 9,
4811                accepted_event_count: 6,
4812            }),
4813        ];
4814        state.stats = state.slot_stats[0].merged(&state.slot_stats[1]);
4815        state
4816            .stats
4817            .add_integrator_overhead(Duration::from_micros(110), 2);
4818        state.all_integrals = vec![
4819            make_accumulator(7.5e-5, 9.8e-5, 0.394, 3.2e-5, 1.5e-5, 0.378),
4820            make_accumulator(2.1e-5, 2.0e-6, 0.221, -1.7e-5, 3.0e-6, 0.187),
4821        ];
4822        state
4823    }
4824
4825    fn make_preview_test_slots(slot_metas: &[SlotMeta]) -> Vec<IntegrationSlot> {
4826        slot_metas
4827            .iter()
4828            .cloned()
4829            .map(|meta| {
4830                let settings = RuntimeSettings::default();
4831                IntegrationSlot::new(
4832                    meta,
4833                    settings.clone(),
4834                    Model::empty("integration-test"),
4835                    Integrand::TestProbe(TestProbeIntegrand::new(settings, 3)),
4836                    None,
4837                )
4838            })
4839            .collect()
4840    }
4841
4842    fn make_preview_test_core_state(state: &IntegrationState) -> CoreIterationState {
4843        let slot_stats = vec![
4844            make_statistics_counter(StatisticsFixture {
4845                precision: crate::settings::runtime::Precision::Arb,
4846                total_time: Duration::from_millis(8),
4847                integrand_time: Duration::from_millis(7),
4848                evaluator_time: Duration::from_millis(3),
4849                parameterization_time: Duration::from_micros(150),
4850                event_time: Duration::from_micros(500),
4851                generated_event_count: 40,
4852                accepted_event_count: 30,
4853            }),
4854            make_statistics_counter(StatisticsFixture {
4855                precision: crate::settings::runtime::Precision::Arb,
4856                total_time: Duration::from_millis(12),
4857                integrand_time: Duration::from_millis(10),
4858                evaluator_time: Duration::from_millis(2),
4859                parameterization_time: Duration::from_micros(300),
4860                event_time: Duration::from_millis(1),
4861                generated_event_count: 60,
4862                accepted_event_count: 45,
4863            }),
4864        ];
4865        let grid_template = state
4866            .sampling_state_for_slot(0)
4867            .grid
4868            .clone_without_samples();
4869        CoreIterationState {
4870            slot_integrands: Vec::new(),
4871            stats: slot_stats[0].merged(&slot_stats[1]),
4872            slot_stats,
4873            integrals: vec![ComplexAccumulator::new(); state.slot_metas.len()],
4874            sampling_correlation_mode: SamplingCorrelationMode::Correlated,
4875            sampling_states: vec![CoreSamplingSlotState {
4876                sampling_grid: grid_template.clone(),
4877                rng: MonteCarloRng::new(7, 0),
4878            }],
4879            slot_re_grids: (0..state.slot_metas.len())
4880                .map(|_| grid_template.clone())
4881                .collect(),
4882            slot_im_grids: (0..state.slot_metas.len())
4883                .map(|_| grid_template.clone())
4884                .collect(),
4885            monitored_discrete_path: None,
4886            slot_absolute_re_grids: vec![None; state.slot_metas.len()],
4887            slot_absolute_im_grids: vec![None; state.slot_metas.len()],
4888            remaining_points: 0,
4889            completed_points: 12,
4890            failed_samples: Vec::new(),
4891        }
4892    }
4893
4894    #[test]
4895    fn failed_sample_records_preserve_replay_and_append_across_iterations() {
4896        use crate::integrands::evaluation::{StabilityResult, StabilityStatus};
4897        use crate::settings::runtime::Precision;
4898
4899        let directory = std::env::temp_dir().join(format!(
4900            "gammaloop_failed_sample_records_{}",
4901            std::process::id()
4902        ));
4903        if directory.exists() {
4904            fs::remove_dir_all(&directory).unwrap();
4905        }
4906        let state = make_integration_state();
4907        let mut worker = make_preview_test_core_state(&state);
4908        let sample = Sample::Discrete(
4909            F(7.5),
4910            0,
4911            Some(Box::new(Sample::Discrete(
4912                F(2.5),
4913                3,
4914                Some(Box::new(Sample::Continuous(
4915                    F(1.25),
4916                    vec![F(0.12345678901234567), F(0.9)],
4917                ))),
4918            ))),
4919        );
4920        let mut metadata = EvaluationMetaData::new_empty();
4921        metadata.is_nan = true;
4922        metadata.record_threshold_counterterm_error("AlmostPrimalInfeasible: no interior center");
4923        for precision in [Precision::Double, Precision::Quad, Precision::Arb] {
4924            metadata.stability_results.push(StabilityResult {
4925                representation: crate::settings::global::RepresentationMode::Cff,
4926                precision,
4927                estimated_relative_accuracy: None,
4928                estimated_decimal_digits: None,
4929                status: StabilityStatus::Unstable(1),
4930                total_time: Duration::ZERO,
4931            });
4932        }
4933        let path = directory.join("numerical_stability/failed_samples.jsonl");
4934        worker
4935            .write_failed_samples(Some(&directory), &state.slot_metas, 1)
4936            .unwrap();
4937        assert!(
4938            !path.exists(),
4939            "successful batches should not create a failure log"
4940        );
4941        for iteration in [1, 2] {
4942            worker
4943                .failed_samples
4944                .push((1, sample.clone(), metadata.clone()));
4945            worker
4946                .write_failed_samples(Some(&directory), &state.slot_metas, iteration)
4947                .unwrap();
4948            assert!(worker.failed_samples.is_empty());
4949            worker
4950                .write_failed_samples(Some(&directory), &state.slot_metas, iteration)
4951                .unwrap();
4952        }
4953        let records = fs::read_to_string(path).unwrap();
4954        assert_eq!(
4955            records.lines().count(),
4956            2,
4957            "drained records must not be duplicated"
4958        );
4959        for (index, line) in records.lines().enumerate() {
4960            let row: serde_json::Value = serde_json::from_str(line).unwrap();
4961            assert_eq!(row["iteration"], index + 1);
4962            assert_eq!(row["slot"]["process_name"], "proc_b");
4963            assert_eq!(row["evaluation_metadata"]["is_nan"], true);
4964            assert_eq!(
4965                row["evaluation_metadata"]["stability_results"]
4966                    .as_array()
4967                    .unwrap()
4968                    .len(),
4969                3
4970            );
4971            assert!(
4972                row["evaluation_metadata"]["threshold_counterterm_error"]
4973                    .as_str()
4974                    .unwrap()
4975                    .contains("AlmostPrimalInfeasible")
4976            );
4977            let replay: Sample<F<f64>> = serde_json::from_value(row["sample"].clone()).unwrap();
4978            assert_eq!(replay.get_weight(), sample.get_weight());
4979            assert_eq!(
4980                serde_json::to_value(replay).unwrap(),
4981                serde_json::to_value(&sample).unwrap()
4982            );
4983        }
4984        fs::remove_dir_all(directory).unwrap();
4985    }
4986
4987    fn make_discrete_integration_state() -> IntegrationState {
4988        let make_continuous_grid =
4989            || Grid::Continuous(ContinuousGrid::new(1, 64, 100, None, false).unwrap());
4990        let sampling_grid = Grid::Discrete(
4991            DiscreteGrid::new(
4992                vec![Some(make_continuous_grid()), Some(make_continuous_grid())],
4993                F(10.0),
4994                false,
4995            )
4996            .unwrap(),
4997        );
4998        let mut state = IntegrationState::new_from_settings(
4999            SamplingCorrelationMode::Correlated,
5000            vec![SamplingSlotState::new(
5001                sampling_grid,
5002                vec!["graph".to_string()],
5003            )],
5004            vec![
5005                SlotMeta {
5006                    process_name: "proc_a".to_string(),
5007                    integrand_name: "itg_a".to_string(),
5008                },
5009                SlotMeta {
5010                    process_name: "proc_b".to_string(),
5011                    integrand_name: "itg_b".to_string(),
5012                },
5013            ],
5014            Some(vec![]),
5015            Some("graph".to_string()),
5016            Some(vec!["GL0".to_string(), "GL1".to_string()]),
5017            vec![
5018                Some(PersistedDiscreteBreakdownMetadata {
5019                    axis_label: "graph".to_string(),
5020                    fixed_coordinates: Vec::new(),
5021                    bin_labels: vec!["GL0".to_string(), "GL1".to_string()],
5022                }),
5023                Some(PersistedDiscreteBreakdownMetadata {
5024                    axis_label: "graph".to_string(),
5025                    fixed_coordinates: Vec::new(),
5026                    bin_labels: vec!["GL0".to_string(), "GL1".to_string()],
5027                }),
5028            ],
5029        );
5030        state.first_non_trivial_discrete_bin_descriptions =
5031            Some(vec!["GL0".to_string(), "GL1".to_string()]);
5032        state.iter = 2;
5033        state.num_points = 210_000;
5034        state.slot_stats = vec![
5035            make_statistics_counter(StatisticsFixture {
5036                precision: crate::settings::runtime::Precision::Double,
5037                total_time: Duration::from_micros(462),
5038                integrand_time: Duration::from_micros(414),
5039                evaluator_time: Duration::from_micros(279),
5040                parameterization_time: Duration::from_nanos(5_800),
5041                event_time: Duration::from_micros(12),
5042                generated_event_count: 7,
5043                accepted_event_count: 5,
5044            }),
5045            make_statistics_counter(StatisticsFixture {
5046                precision: crate::settings::runtime::Precision::Quad,
5047                total_time: Duration::from_micros(900),
5048                integrand_time: Duration::from_micros(810),
5049                evaluator_time: Duration::from_micros(120),
5050                parameterization_time: Duration::from_micros(34),
5051                event_time: Duration::from_micros(40),
5052                generated_event_count: 9,
5053                accepted_event_count: 6,
5054            }),
5055        ];
5056        state.stats = state.slot_stats[0].merged(&state.slot_stats[1]);
5057        state
5058            .stats
5059            .add_integrator_overhead(Duration::from_micros(110), 2);
5060        state.all_integrals = vec![
5061            make_accumulator(7.5e-5, 9.8e-5, 0.394, 3.2e-5, 1.5e-5, 0.378),
5062            make_accumulator(2.1e-5, 2.0e-6, 0.221, -1.7e-5, 3.0e-6, 0.187),
5063        ];
5064        if let Grid::Discrete(discrete_grid) = &mut state.sampling_state_for_slot_mut(0).grid {
5065            discrete_grid.bins[0].pdf = F(0.75);
5066            discrete_grid.bins[1].pdf = F(0.25);
5067        }
5068
5069        for summaries in [&mut state.slot_re_summaries, &mut state.slot_im_summaries] {
5070            for (slot_index, summary) in summaries.iter_mut().enumerate() {
5071                let summary = summary.as_mut().expect("discrete summary expected");
5072                summary.bins[0].accumulator.avg = F(1.0e-5 * (slot_index as f64 + 1.0));
5073                summary.bins[0].accumulator.err = F(2.0e-6);
5074                summary.bins[0].accumulator.chi_sq = F(0.2);
5075                summary.bins[0].accumulator.processed_samples = 150;
5076                summary.bins[0].accumulator.max_eval_positive = F(0.75);
5077                summary.bins[0].accumulator.max_eval_positive_xs =
5078                    Some(Sample::Continuous(F(1.0), vec![F(0.25)]));
5079                summary.bins[1].accumulator.avg = F(5.0e-6 * (slot_index as f64 + 1.0));
5080                summary.bins[1].accumulator.err = F(1.0e-6);
5081                summary.bins[1].accumulator.chi_sq = F(0.1);
5082                summary.bins[1].accumulator.processed_samples = 50;
5083                summary.bins[1].accumulator.max_eval_positive = F(0.25);
5084                summary.bins[1].accumulator.max_eval_positive_xs =
5085                    Some(Sample::Continuous(F(1.0), vec![F(0.75)]));
5086            }
5087        }
5088        for (summaries, component_scale) in [
5089            (&mut state.slot_absolute_re_summaries, 4.0),
5090            (&mut state.slot_absolute_im_summaries, 3.0),
5091        ] {
5092            for (slot_index, summary) in summaries.iter_mut().enumerate() {
5093                let summary = summary.as_mut().expect("shallow absolute summary expected");
5094                let slot_scale = slot_index as f64 + 1.0;
5095                summary.bins[0].accumulator.avg = F(component_scale * 1.0e-5 * slot_scale);
5096                summary.bins[0].accumulator.err = F(3.0e-6);
5097                summary.bins[0].accumulator.chi_sq = F(0.3);
5098                summary.bins[0].accumulator.processed_samples = 150;
5099                summary.bins[0].accumulator.max_eval_positive = F(1.25);
5100                summary.bins[0].accumulator.max_eval_positive_xs =
5101                    Some(Sample::Continuous(F(1.0), vec![F(0.35)]));
5102                summary.bins[1].accumulator.avg = F(component_scale * 0.5e-5 * slot_scale);
5103                summary.bins[1].accumulator.err = F(1.5e-6);
5104                summary.bins[1].accumulator.chi_sq = F(0.15);
5105                summary.bins[1].accumulator.processed_samples = 50;
5106                summary.bins[1].accumulator.max_eval_positive = F(0.5);
5107                summary.bins[1].accumulator.max_eval_positive_xs =
5108                    Some(Sample::Continuous(F(1.0), vec![F(0.85)]));
5109            }
5110        }
5111
5112        state
5113    }
5114
5115    fn make_single_graph_discrete_integration_state() -> IntegrationState {
5116        let mut state = make_discrete_integration_state();
5117        let Grid::Discrete(grid) = &mut state.sampling_state_for_slot_mut(0).grid else {
5118            unreachable!("discrete fixture must use a discrete grid")
5119        };
5120        grid.bins.truncate(1);
5121        grid.bins[0].pdf = F(1.0);
5122        for summaries in [
5123            &mut state.slot_re_summaries,
5124            &mut state.slot_im_summaries,
5125            &mut state.slot_absolute_re_summaries,
5126            &mut state.slot_absolute_im_summaries,
5127        ] {
5128            for summary in summaries.iter_mut().flatten() {
5129                summary.bins.truncate(1);
5130            }
5131        }
5132        state.first_non_trivial_discrete_bin_descriptions = Some(vec!["GL22".to_string()]);
5133        for metadata in &mut state.slot_first_non_trivial_discrete_breakdown_metadata {
5134            if let Some(metadata) = metadata.as_mut() {
5135                metadata.bin_labels = vec!["GL22".to_string()];
5136            }
5137        }
5138        state
5139    }
5140
5141    fn default_view_options() -> IntegrationStatusViewOptions {
5142        IntegrationStatusViewOptions {
5143            phase_display: IntegrationStatusPhaseDisplay::Both,
5144            training_phase_display: IntegrationStatusPhaseDisplay::Real,
5145            training_slot: 0,
5146            slot_training_phase_displays: vec![IntegrationStatusPhaseDisplay::Real],
5147            per_slot_training_phase: false,
5148            target_relative_accuracy: None,
5149            target_absolute_accuracy: None,
5150            show_statistics: true,
5151            show_max_weight_details: true,
5152            show_top_discrete_grid: false,
5153            show_discrete_contributions_sum: false,
5154            contribution_sort: ContributionSortMode::Error,
5155            show_max_weight_info_for_discrete_bins: false,
5156        }
5157    }
5158
5159    fn default_tabled_options() -> TabledRenderOptions {
5160        TabledRenderOptions {
5161            max_table_width: DEFAULT_MAX_SHARED_TABLE_WIDTH,
5162            show_statistics: true,
5163            show_max_weight_details: true,
5164            show_top_discrete_grid: false,
5165            show_discrete_contributions_sum: false,
5166            show_max_weight_info_for_discrete_bins: false,
5167        }
5168    }
5169
5170    fn tabled_options_for_view(view_options: &IntegrationStatusViewOptions) -> TabledRenderOptions {
5171        TabledRenderOptions {
5172            show_statistics: view_options.show_statistics,
5173            show_max_weight_details: view_options.show_max_weight_details,
5174            show_top_discrete_grid: view_options.show_top_discrete_grid,
5175            show_discrete_contributions_sum: view_options.show_discrete_contributions_sum,
5176            show_max_weight_info_for_discrete_bins: view_options
5177                .show_max_weight_info_for_discrete_bins,
5178            ..default_tabled_options()
5179        }
5180    }
5181
5182    #[test]
5183    fn correlated_core_iteration_state_populates_slot_statistics() {
5184        let settings_a = RuntimeSettings::default();
5185        let settings_b = RuntimeSettings::default();
5186        let integrand_a = Integrand::TestProbe(TestProbeIntegrand::new(settings_a.clone(), 3));
5187        let integrand_b = Integrand::TestProbe(TestProbeIntegrand::new(settings_b.clone(), 3));
5188        let sampling_grid_template = SamplingSlotState::from_integrand(&integrand_a).grid;
5189        let mut core_state = CoreIterationState::new(
5190            vec![integrand_a, integrand_b],
5191            SamplingCorrelationMode::Correlated,
5192            &[sampling_grid_template],
5193            None,
5194            1337,
5195            0,
5196            8,
5197        );
5198        let model = Model::empty("unit-volume-test");
5199        let slot_settings = [&settings_a, &settings_b];
5200        let slot_targets = [EvaluationTarget::Physical(&model); 2];
5201        let current_max_evals = [Complex::new(F(0.0), F(0.0)), Complex::new(F(0.0), F(0.0))];
5202
5203        let processed = core_state
5204            .evaluate_chunk(
5205                &slot_settings,
5206                &slot_targets,
5207                0,
5208                &current_max_evals,
5209                &[None, None],
5210                8,
5211            )
5212            .expect("correlated chunk evaluation should succeed");
5213
5214        assert_eq!(processed, 8);
5215        assert!(
5216            core_state
5217                .slot_stats
5218                .iter()
5219                .all(|stats| stats.snapshot().num_evals == processed),
5220            "{:?}",
5221            core_state
5222                .slot_stats
5223                .iter()
5224                .map(|stats| stats.snapshot().num_evals)
5225                .collect_vec()
5226        );
5227    }
5228
5229    fn render_update(request: StatusUpdateBuildRequest<'_>) -> String {
5230        let tabled_options = tabled_options_for_view(request.render_options);
5231        render_status_update_tabled(&build_status_update(request), &tabled_options)
5232    }
5233
5234    fn render_ratatui_update(
5235        request: StatusUpdateBuildRequest<'_>,
5236        configure: impl FnOnce(&mut RatatuiDashboardState),
5237    ) -> String {
5238        let mut dashboard = RatatuiDashboardState::new();
5239        dashboard.update(build_status_update(request));
5240        configure(&mut dashboard);
5241
5242        let backend = TestBackend::new(180, 48);
5243        let mut terminal = Terminal::new(backend).expect("test terminal");
5244        terminal
5245            .draw(|frame| dashboard.draw(frame))
5246            .expect("ratatui draw");
5247
5248        let buffer = terminal.backend().buffer();
5249        (0..buffer.area.height)
5250            .map(|y| {
5251                let mut line = String::new();
5252                for x in 0..buffer.area.width {
5253                    line.push_str(buffer[(x, y)].symbol());
5254                }
5255                line.trim_end().to_string()
5256            })
5257            .collect::<Vec<_>>()
5258            .join("\n")
5259    }
5260
5261    #[test]
5262    fn max_weight_details_table_renders_titled_table_without_wrapping_parentheses() {
5263        let mut accumulator = ComplexAccumulator::new();
5264        accumulator.re.max_eval_positive = F(2.3840672847728);
5265        accumulator.re.max_eval_positive_xs = Some(Sample::Discrete(
5266            F(1.0),
5267            0,
5268            Some(Box::new(Sample::Discrete(
5269                F(1.0),
5270                0,
5271                Some(Box::new(Sample::Continuous(
5272                    F(1.0),
5273                    vec![
5274                        F(0.9695746085826609),
5275                        F(0.5327714835649985),
5276                        F(0.003410284786539597),
5277                    ],
5278                ))),
5279            ))),
5280        ));
5281
5282        let mut state = IntegrationState::new_from_settings(
5283            SamplingCorrelationMode::Correlated,
5284            vec![SamplingSlotState::new(
5285                Grid::Continuous(ContinuousGrid::new(1, 64, 100, None, false).unwrap()),
5286                Vec::new(),
5287            )],
5288            vec![SlotMeta {
5289                process_name: "proc".to_string(),
5290                integrand_name: "itg".to_string(),
5291            }],
5292            None,
5293            None,
5294            None,
5295            vec![None],
5296        );
5297        state.all_integrals = vec![accumulator];
5298        let view_options = IntegrationStatusViewOptions {
5299            show_statistics: false,
5300            show_top_discrete_grid: false,
5301            show_discrete_contributions_sum: false,
5302            ..default_view_options()
5303        };
5304        let rendered = render_status_update_tabled(
5305            &build_status_update(
5306                StatusUpdateBuildRequest::new(
5307                    IntegrationStatusKind::Iteration,
5308                    &state,
5309                    &[None],
5310                    &view_options,
5311                )
5312                .with_timing(
5313                    1,
5314                    Duration::from_secs(0),
5315                    Duration::from_secs(0),
5316                    0,
5317                    0,
5318                    0,
5319                ),
5320            ),
5321            &default_tabled_options(),
5322        );
5323
5324        assert!(rendered.contains("Maximum weight details"), "{rendered}");
5325        assert!(rendered.contains("Integrand"), "{rendered}");
5326        assert!(rendered.contains("Max eval"), "{rendered}");
5327        assert!(rendered.contains("Max eval coordinates"), "{rendered}");
5328        assert!(rendered.contains("proc@itg"), "{rendered}");
5329        assert!(rendered.contains("re [+]"), "{rendered}");
5330        assert!(rendered.contains("idx: 0, idx: 0, xs: [ "), "{rendered}");
5331        assert!(rendered.contains("e-01"), "{rendered}");
5332        assert!(rendered.contains("e-03 ]"), "{rendered}");
5333        assert!(!rendered.contains(", 0.532"), "{rendered}");
5334        assert!(!rendered.contains("( graph:"), "{rendered}");
5335    }
5336
5337    #[test]
5338    fn iteration_status_block_uses_compact_header_and_optional_statistics() {
5339        let state = make_integration_state();
5340        let view_options = IntegrationStatusViewOptions {
5341            show_statistics: false,
5342            show_max_weight_details: false,
5343            ..default_view_options()
5344        };
5345        let rendered = render_update(
5346            StatusUpdateBuildRequest::new(
5347                IntegrationStatusKind::Iteration,
5348                &state,
5349                &[Some(Complex::new(F(1.0e-4), F(2.0e-5))), None],
5350                &view_options,
5351            )
5352            .with_timing(
5353                4,
5354                Duration::from_secs(1),
5355                Duration::from_secs(1),
5356                100_000,
5357                100_000,
5358                100_000,
5359            ),
5360        );
5361
5362        assert!(
5363            rendered.contains("Iteration #   1 ( completed )"),
5364            "{rendered}"
5365        );
5366        assert!(
5367            rendered.contains("# samples per iteration = 100.00K # samples total = 100.00K"),
5368            "{rendered}"
5369        );
5370        assert!(rendered.contains("/sample/core (4 cores)"), "{rendered}");
5371        assert!(rendered.contains("Contribution"), "{rendered}");
5372        assert!(rendered.contains("proc_a@itg_a"), "{rendered}");
5373        assert!(rendered.contains("proc_b@itg_b"), "{rendered}");
5374        assert!(rendered.contains("+7.5(9.8)e-5"), "{rendered}");
5375        assert!(rendered.contains("Δ = 0.255σ"), "{rendered}");
5376        assert!(!rendered.contains("Integration statistics"), "{rendered}");
5377        let lines = rendered.lines().collect::<Vec<_>>();
5378        assert_eq!(lines[1].matches('│').count(), 2, "{rendered}");
5379        assert!(lines[2].contains('┬'), "{rendered}");
5380        assert!(
5381            lines.last().is_some_and(|line| line.contains('┴')),
5382            "{rendered}"
5383        );
5384    }
5385
5386    #[test]
5387    fn iteration_status_block_omits_delta_columns_when_no_target_is_provided() {
5388        let state = make_integration_state();
5389        let view_options = IntegrationStatusViewOptions {
5390            show_statistics: true,
5391            show_max_weight_details: false,
5392            ..default_view_options()
5393        };
5394        let rendered = render_update(
5395            StatusUpdateBuildRequest::new(
5396                IntegrationStatusKind::Iteration,
5397                &state,
5398                &[None, None],
5399                &view_options,
5400            )
5401            .with_timing(
5402                4,
5403                Duration::from_secs(1),
5404                Duration::from_secs(1),
5405                100_000,
5406                100_000,
5407                100_000,
5408            ),
5409        );
5410
5411        assert!(!rendered.contains("Δ [σ]"), "{rendered}");
5412        assert!(!rendered.contains("Δ ="), "{rendered}");
5413        assert!(rendered.contains("Integration statistics"), "{rendered}");
5414        assert!(rendered.contains("mwi"), "{rendered}");
5415    }
5416
5417    #[test]
5418    fn tabled_all_rows_insert_value_only_absolute_continuations_and_filter_phases() {
5419        let state = make_discrete_integration_state();
5420        let targets = [Some(Complex::new(F(1.0e-4), F(2.0e-5))), None];
5421        let view_options = IntegrationStatusViewOptions {
5422            show_statistics: true,
5423            show_max_weight_details: true,
5424            show_top_discrete_grid: false,
5425            show_discrete_contributions_sum: false,
5426            ..default_view_options()
5427        };
5428        let update = build_status_update(StatusUpdateBuildRequest::new(
5429            IntegrationStatusKind::Iteration,
5430            &state,
5431            &targets,
5432            &view_options,
5433        ));
5434        let rendered = render_update(StatusUpdateBuildRequest::new(
5435            IntegrationStatusKind::Iteration,
5436            &state,
5437            &targets,
5438            &view_options,
5439        ));
5440        let lines = rendered.lines().collect_vec();
5441
5442        let row_text = |component, view| {
5443            update
5444                .main_results
5445                .find_row(status_update::ContributionKind::All, component)
5446                .and_then(|row| row.slot_cell(0))
5447                .and_then(|cell| cell.statistics(view).value.as_ref())
5448                .map(|value| value.display.to_plain_string())
5449                .expect("All row value should exist")
5450        };
5451        let signed_re = row_text(
5452            status_update::ComponentKind::Real,
5453            status_update::IntegralView::Signed,
5454        );
5455        let absolute_re = row_text(
5456            status_update::ComponentKind::Real,
5457            status_update::IntegralView::Absolute,
5458        );
5459        let signed_im = row_text(
5460            status_update::ComponentKind::Imag,
5461            status_update::IntegralView::Signed,
5462        );
5463        let absolute_im = row_text(
5464            status_update::ComponentKind::Imag,
5465            status_update::IntegralView::Absolute,
5466        );
5467        let line_index = |needle: &str| {
5468            lines
5469                .iter()
5470                .position(|line| line.contains(needle))
5471                .unwrap_or_else(|| panic!("missing {needle:?} in:\n{rendered}"))
5472        };
5473        let signed_re_line = line_index(&signed_re);
5474        let absolute_re_line = line_index(&absolute_re);
5475        let signed_im_line = line_index(&signed_im);
5476        let absolute_im_line = line_index(&absolute_im);
5477        assert!(signed_re_line < absolute_re_line);
5478        assert!(absolute_re_line < signed_im_line);
5479        assert!(signed_im_line < absolute_im_line);
5480        assert!(lines[absolute_re_line].contains("|re|"));
5481        assert!(lines[absolute_im_line].contains("|im|"));
5482
5483        for (component, absolute_line) in [
5484            (status_update::ComponentKind::Real, absolute_re_line),
5485            (status_update::ComponentKind::Imag, absolute_im_line),
5486        ] {
5487            let row = update
5488                .main_results
5489                .find_row(status_update::ContributionKind::All, component)
5490                .expect("All row should exist");
5491            let statistics = row
5492                .slot_cell(0)
5493                .expect("slot cells should exist")
5494                .statistics(status_update::IntegralView::Absolute);
5495            for metadata in [
5496                statistics.relative_error.as_ref(),
5497                statistics.chi_sq.as_ref(),
5498                statistics.max_weight_impact.as_ref(),
5499            ]
5500            .into_iter()
5501            .flatten()
5502            {
5503                let metadata = metadata.display.to_plain_string();
5504                assert!(
5505                    !lines[absolute_line].contains(&metadata),
5506                    "absolute continuation unexpectedly contains {metadata:?}: {}",
5507                    lines[absolute_line]
5508                );
5509            }
5510            let (delta_sigma, delta_percent) =
5511                update.target_deltas_for_row_slot(row, 0, status_update::IntegralView::Absolute);
5512            assert!(delta_sigma.is_none());
5513            assert!(delta_percent.is_none());
5514        }
5515        assert_eq!(rendered.matches("Maximum weight details").count(), 1);
5516        assert_eq!(
5517            rendered.matches("Integration statistics [global]").count(),
5518            1
5519        );
5520
5521        for (phase, included, excluded) in [
5522            (IntegrationStatusPhaseDisplay::Real, "|re|", "|im|"),
5523            (IntegrationStatusPhaseDisplay::Imag, "|im|", "|re|"),
5524        ] {
5525            let phase_options = IntegrationStatusViewOptions {
5526                phase_display: phase,
5527                show_statistics: false,
5528                show_max_weight_details: false,
5529                ..default_view_options()
5530            };
5531            let phase_rendered = render_update(StatusUpdateBuildRequest::new(
5532                IntegrationStatusKind::Iteration,
5533                &state,
5534                &targets,
5535                &phase_options,
5536            ));
5537            assert!(phase_rendered.contains(included), "{phase_rendered}");
5538            assert!(!phase_rendered.contains(excluded), "{phase_rendered}");
5539        }
5540    }
5541
5542    #[test]
5543    fn absolute_sum_status_adds_shallow_means_and_combines_errors_in_quadrature() {
5544        let state = make_discrete_integration_state();
5545        let targets = [Some(Complex::new(F(1.0e-4), F(2.0e-5))), None];
5546        let view_options = IntegrationStatusViewOptions {
5547            show_discrete_contributions_sum: true,
5548            ..default_view_options()
5549        };
5550        let update = build_status_update(StatusUpdateBuildRequest::new(
5551            IntegrationStatusKind::Iteration,
5552            &state,
5553            &targets,
5554            &view_options,
5555        ));
5556        let row = update
5557            .main_results
5558            .find_row(
5559                status_update::ContributionKind::Sum,
5560                status_update::ComponentKind::Real,
5561            )
5562            .expect("absolute Sum row should exist");
5563        let value = row
5564            .slot_cell(0)
5565            .expect("slot cells should exist")
5566            .statistics(status_update::IntegralView::Absolute)
5567            .value
5568            .as_ref()
5569            .expect("absolute Sum estimate should exist")
5570            .raw;
5571
5572        assert!((value.0 - F(6.0e-5)).abs() < F(1.0e-18));
5573        let expected_error = (F(3.0e-6) * F(3.0e-6) + F(1.5e-6) * F(1.5e-6)).sqrt();
5574        assert!((value.1 - expected_error).abs() < F(1.0e-18));
5575        let (delta_sigma, delta_percent) =
5576            update.target_deltas_for_row_slot(row, 0, status_update::IntegralView::Absolute);
5577        assert!(delta_sigma.is_none());
5578        assert!(delta_percent.is_none());
5579    }
5580
5581    #[test]
5582    fn tabled_statistics_panel_uses_global_scope_label() {
5583        let state = make_integration_state();
5584        let view_options = IntegrationStatusViewOptions {
5585            show_statistics: true,
5586            show_max_weight_details: false,
5587            ..default_view_options()
5588        };
5589        let rendered = render_update(
5590            StatusUpdateBuildRequest::new(
5591                IntegrationStatusKind::Iteration,
5592                &state,
5593                &[None, None],
5594                &view_options,
5595            )
5596            .with_timing(
5597                4,
5598                Duration::from_secs(1),
5599                Duration::from_secs(1),
5600                100_000,
5601                100_000,
5602                100_000,
5603            ),
5604        );
5605
5606        assert!(
5607            rendered.contains("Integration statistics [global]"),
5608            "{rendered}"
5609        );
5610    }
5611
5612    #[test]
5613    fn live_iteration_status_block_uses_progress_header() {
5614        let mut state = make_integration_state();
5615        state.iter = 2;
5616        state.num_points = 125_000;
5617        let view_options = IntegrationStatusViewOptions {
5618            show_statistics: false,
5619            show_max_weight_details: false,
5620            ..default_view_options()
5621        };
5622        let rendered = render_update(
5623            StatusUpdateBuildRequest::new(
5624                IntegrationStatusKind::Live,
5625                &state,
5626                &[Some(Complex::new(F(1.0e-4), F(2.0e-5))), None],
5627                &view_options,
5628            )
5629            .with_timing(
5630                4,
5631                Duration::from_secs(1),
5632                Duration::from_secs(1),
5633                25_000,
5634                125_000,
5635                125_000,
5636            )
5637            .with_live_progress(Some(status_update::LiveIterationProgress {
5638                completed_points: 25_000,
5639                target_points: 100_000,
5640            })),
5641        );
5642
5643        assert!(
5644            rendered.contains("Iteration #   2 ( running   )"),
5645            "{rendered}"
5646        );
5647        assert!(
5648            rendered.contains("Iteration progress 25.00K/100.00K"),
5649            "{rendered}"
5650        );
5651        assert!(rendered.contains("25.0%"), "{rendered}");
5652        assert!(rendered.contains("# samples total = 125.00K"), "{rendered}");
5653    }
5654
5655    #[test]
5656    fn iteration_status_block_shows_discrete_contributions_and_discrete_max_weights() {
5657        let state = make_discrete_integration_state();
5658        let view_options = IntegrationStatusViewOptions {
5659            show_statistics: false,
5660            show_max_weight_details: true,
5661            show_top_discrete_grid: true,
5662            show_discrete_contributions_sum: true,
5663            contribution_sort: ContributionSortMode::Index,
5664            show_max_weight_info_for_discrete_bins: true,
5665            ..default_view_options()
5666        };
5667        let rendered = render_update(
5668            StatusUpdateBuildRequest::new(
5669                IntegrationStatusKind::Iteration,
5670                &state,
5671                &[Some(Complex::new(F(1.0e-4), F(2.0e-5))), None],
5672                &view_options,
5673            )
5674            .with_timing(
5675                4,
5676                Duration::from_secs(2),
5677                Duration::from_secs(2),
5678                110_000,
5679                210_000,
5680                210_000,
5681            ),
5682        );
5683
5684        assert!(rendered.contains("Sum"), "{rendered}");
5685        assert!(rendered.contains("Contribution (idx=graph)"), "{rendered}");
5686        assert!(
5687            !rendered.contains("│             (idx=graph)             │"),
5688            "{rendered}"
5689        );
5690        assert!(rendered.contains("#0: GL0"), "{rendered}");
5691        assert!(rendered.contains("75.0%"), "{rendered}");
5692        assert!(rendered.contains("25.0%"), "{rendered}");
5693        assert!(
5694            rendered.contains("Maximum weight details by discrete bin"),
5695            "{rendered}"
5696        );
5697        assert!(
5698            rendered.contains("xs: [ 2.5000000000000000e-01 ]"),
5699            "{rendered}"
5700        );
5701    }
5702
5703    #[test]
5704    fn grouped_graph_descriptions_include_all_group_members() {
5705        let description =
5706            graph_group_description(["GL0".to_string(), "GL1".to_string(), "GL2".to_string()]);
5707
5708        assert_eq!(description, "[GL0,GL1,GL2]");
5709    }
5710
5711    #[test]
5712    fn explicit_single_graph_subset_monitors_the_root_graph_axis() {
5713        let grid = Grid::Discrete(
5714            DiscreteGrid::new(
5715                vec![Some(Grid::Continuous(
5716                    ContinuousGrid::new(1, 64, 100, None, false).unwrap(),
5717                ))],
5718                F(10.0),
5719                false,
5720            )
5721            .unwrap(),
5722        );
5723        let labels = vec!["graph".to_string()];
5724
5725        assert!(monitored_discrete_layout(&grid, &labels, false).is_none());
5726        assert_eq!(
5727            monitored_discrete_layout(&grid, &labels, true),
5728            Some((Vec::new(), "graph".to_string(), 1))
5729        );
5730    }
5731
5732    #[test]
5733    fn tabled_single_graph_subset_keeps_the_graph_row() {
5734        let state = make_single_graph_discrete_integration_state();
5735        let view_options = IntegrationStatusViewOptions {
5736            show_statistics: false,
5737            show_max_weight_details: false,
5738            show_top_discrete_grid: true,
5739            contribution_sort: ContributionSortMode::Index,
5740            ..default_view_options()
5741        };
5742        let rendered = render_update(StatusUpdateBuildRequest::new(
5743            IntegrationStatusKind::Iteration,
5744            &state,
5745            &[None, None],
5746            &view_options,
5747        ));
5748
5749        assert!(rendered.contains("Contribution (idx=graph)"), "{rendered}");
5750        assert!(rendered.contains("#0: GL22"), "{rendered}");
5751        assert!(!rendered.contains("GL1"), "{rendered}");
5752    }
5753
5754    #[test]
5755    fn iteration_status_block_hides_spanned_metadata_header_separators() {
5756        let state = make_discrete_integration_state();
5757        let view_options = IntegrationStatusViewOptions {
5758            show_statistics: false,
5759            show_max_weight_details: false,
5760            show_top_discrete_grid: true,
5761            show_discrete_contributions_sum: true,
5762            contribution_sort: ContributionSortMode::Index,
5763            show_max_weight_info_for_discrete_bins: false,
5764            ..default_view_options()
5765        };
5766        let rendered = render_update(
5767            StatusUpdateBuildRequest::new(
5768                IntegrationStatusKind::Iteration,
5769                &state,
5770                &[Some(Complex::new(F(1.0e-4), F(2.0e-5))), None],
5771                &view_options,
5772            )
5773            .with_timing(
5774                4,
5775                Duration::from_secs(2),
5776                Duration::from_secs(2),
5777                110_000,
5778                210_000,
5779                210_000,
5780            ),
5781        );
5782
5783        let header_line = rendered
5784            .lines()
5785            .find(|line| line.contains("χ²/dof") && line.contains("mwi"))
5786            .expect("expected spanned metadata header line");
5787
5788        let chi_to_mwi =
5789            &header_line[header_line.find("χ²/dof").unwrap()..header_line.find("mwi").unwrap()];
5790        assert!(!chi_to_mwi.contains('│'), "{rendered}");
5791
5792        let delta_sigma_to_percent =
5793            &header_line[header_line.find("Δ [σ]").unwrap()..header_line.find("Δ [%]").unwrap()];
5794        assert!(!delta_sigma_to_percent.contains('│'), "{rendered}");
5795    }
5796
5797    #[test]
5798    fn integration_result_always_contains_first_non_trivial_discrete_breakdown() {
5799        let state = make_discrete_integration_state();
5800        let result =
5801            build_integration_result(&state, &[Some(Complex::new(F(1.0e-4), F(2.0e-5))), None]);
5802
5803        let slot = result
5804            .slot("proc_a@itg_a")
5805            .expect("discrete slot must be present");
5806        let breakdown = slot
5807            .grid_breakdown
5808            .re
5809            .as_ref()
5810            .expect("discrete breakdown must be persisted");
5811
5812        assert_eq!(breakdown.axis_label, "graph");
5813        assert!(breakdown.fixed_coordinates.is_empty());
5814        assert_eq!(breakdown.entries.len(), 2);
5815        assert_eq!(breakdown.entries[0].bin_index, 0);
5816        assert_eq!(breakdown.entries[0].bin_label.as_deref(), Some("GL0"));
5817        assert_eq!(breakdown.entries[0].pdf, F(0.75));
5818        assert_eq!(breakdown.entries[0].processed_samples, 150);
5819        assert_eq!(breakdown.entries[1].bin_index, 1);
5820        assert_eq!(breakdown.entries[1].bin_label.as_deref(), Some("GL1"));
5821        assert_eq!(breakdown.entries[1].pdf, F(0.25));
5822        assert_eq!(breakdown.entries[1].processed_samples, 50);
5823    }
5824
5825    #[test]
5826    fn integration_result_persists_absolute_bundle_and_shallow_breakdown() {
5827        let mut state = make_discrete_integration_state();
5828        let accumulator = &mut state.all_integrals[0];
5829        accumulator.absolute_re.avg = F(3.5e-4);
5830        accumulator.absolute_re.err = F(2.5e-5);
5831        accumulator.absolute_re.chi_sq = F(0.42);
5832        accumulator.absolute_re.processed_samples = 200;
5833        accumulator.absolute_re.max_eval_positive = F(8.0);
5834        accumulator.absolute_re.max_eval_positive_xs = Some(Sample::Discrete(
5835            F(4.0),
5836            0,
5837            Some(Box::new(Sample::Continuous(F(1.0), vec![F(0.25)]))),
5838        ));
5839        accumulator.absolute_im.avg = F(1.25e-4);
5840        accumulator.absolute_im.err = F(1.0e-5);
5841        accumulator.absolute_im.chi_sq = F(0.24);
5842        accumulator.absolute_im.processed_samples = 200;
5843        accumulator.absolute_im.max_eval_positive = F(5.0);
5844
5845        let re_summary = state.slot_absolute_re_summaries[0]
5846            .as_mut()
5847            .expect("absolute real summary should exist");
5848        re_summary.bins[0].accumulator.avg = F(2.0e-4);
5849        re_summary.bins[0].accumulator.err = F(2.0e-5);
5850        re_summary.bins[0].accumulator.processed_samples = 150;
5851        re_summary.bins[1].accumulator.avg = F(1.5e-4);
5852        re_summary.bins[1].accumulator.err = F(1.5e-5);
5853        re_summary.bins[1].accumulator.processed_samples = 50;
5854        let im_summary = state.slot_absolute_im_summaries[0]
5855            .as_mut()
5856            .expect("absolute imaginary summary should exist");
5857        im_summary.bins[0].accumulator.avg = F(7.5e-5);
5858        im_summary.bins[0].accumulator.processed_samples = 150;
5859        im_summary.bins[1].accumulator.avg = F(5.0e-5);
5860        im_summary.bins[1].accumulator.processed_samples = 50;
5861
5862        let result =
5863            build_integration_result(&state, &[Some(Complex::new(F(1.0e-4), F(2.0e-5))), None]);
5864        let absolute = &result
5865            .slot("proc_a@itg_a")
5866            .expect("absolute result slot should be present")
5867            .absolute;
5868
5869        assert_eq!(absolute.integral.result.re, F(3.5e-4));
5870        assert_eq!(absolute.integral.result.im, F(1.25e-4));
5871        assert_eq!(absolute.integral.neval, 200);
5872        assert_eq!(absolute.table_results[0].component, "|re|");
5873        assert_eq!(absolute.table_results[1].component, "|im|");
5874        assert!(
5875            absolute
5876                .table_results
5877                .iter()
5878                .all(|row| row.target_delta_sigma.is_none() && row.target_delta_percent.is_none())
5879        );
5880        assert_eq!(absolute.max_weight_info.len(), 2);
5881        assert!(
5882            absolute
5883                .max_weight_info
5884                .iter()
5885                .all(|entry| entry.sign == "+" && entry.max_eval > F(0.0))
5886        );
5887        let breakdown = absolute
5888            .grid_breakdown
5889            .re
5890            .as_ref()
5891            .expect("absolute shallow breakdown should be persisted");
5892        assert_eq!(breakdown.entries.len(), 2);
5893        assert_eq!(breakdown.entries[0].pdf, F(0.75));
5894        assert_eq!(breakdown.entries[0].value, F(2.0e-4));
5895        assert_eq!(breakdown.entries[1].pdf, F(0.25));
5896        assert_eq!(breakdown.entries[1].value, F(1.5e-4));
5897
5898        let json = serde_json::to_string(&result).expect("integration result should serialize");
5899        assert!(json.contains("\"absolute\""));
5900        let decoded: IntegrationResult =
5901            serde_json::from_str(&json).expect("integration result should deserialize");
5902        assert_eq!(
5903            decoded
5904                .slot("proc_a@itg_a")
5905                .expect("round-tripped slot should exist")
5906                .absolute
5907                .integral
5908                .result
5909                .re,
5910            F(3.5e-4)
5911        );
5912    }
5913
5914    #[test]
5915    fn integration_state_roundtrip_preserves_absolute_accumulators_and_summaries() {
5916        let mut state = make_discrete_integration_state();
5917        state.all_integrals[0].absolute_re.avg = F(4.5);
5918        state.slot_absolute_re_summaries[0]
5919            .as_mut()
5920            .expect("absolute summary should exist")
5921            .bins[1]
5922            .accumulator
5923            .avg = F(2.25);
5924
5925        let encoded = bincode::encode_to_vec(&state, bincode::config::standard())
5926            .expect("integration state should serialize");
5927        let (decoded, consumed): (IntegrationState, usize) =
5928            bincode::decode_from_slice(&encoded, bincode::config::standard())
5929                .expect("integration state should deserialize");
5930
5931        assert_eq!(consumed, encoded.len());
5932        assert_eq!(decoded.all_integrals[0].absolute_re.avg, F(4.5));
5933        assert_eq!(
5934            decoded.slot_absolute_re_summaries[0]
5935                .as_ref()
5936                .expect("round-tripped absolute summary should exist")
5937                .bins[1]
5938                .accumulator
5939                .avg,
5940            F(2.25)
5941        );
5942        assert!(
5943            decoded.slot_absolute_re_summaries[0]
5944                .as_ref()
5945                .expect("round-tripped absolute summary should exist")
5946                .bins
5947                .iter()
5948                .all(|bin| bin.sub_summary.is_none())
5949        );
5950    }
5951
5952    #[test]
5953    fn orientation_descriptions_use_colored_signs() {
5954        let mut state = make_discrete_integration_state();
5955        state.first_non_trivial_discrete_label = Some("orientation".to_string());
5956        state.first_non_trivial_discrete_bin_descriptions =
5957            Some(vec!["+-0".to_string(), "0++".to_string()]);
5958        for metadata in &mut state.slot_first_non_trivial_discrete_breakdown_metadata {
5959            if let Some(metadata) = metadata.as_mut() {
5960                metadata.axis_label = "orientation".to_string();
5961                metadata.bin_labels = vec!["+-0".to_string(), "0++".to_string()];
5962            }
5963        }
5964
5965        control::set_override(true);
5966        let expected_plus = "+".green().bold().to_string();
5967        let expected_minus = "-".red().bold().to_string();
5968
5969        let view_options = IntegrationStatusViewOptions {
5970            show_statistics: false,
5971            show_max_weight_details: false,
5972            show_top_discrete_grid: true,
5973            show_discrete_contributions_sum: false,
5974            contribution_sort: ContributionSortMode::Index,
5975            show_max_weight_info_for_discrete_bins: false,
5976            ..default_view_options()
5977        };
5978        let ansi = render_tabled::render_status_update(
5979            &build_status_update(
5980                StatusUpdateBuildRequest::new(
5981                    IntegrationStatusKind::Iteration,
5982                    &state,
5983                    &[None, None],
5984                    &view_options,
5985                )
5986                .with_timing(
5987                    1,
5988                    Duration::from_secs(0),
5989                    Duration::from_secs(0),
5990                    0,
5991                    0,
5992                    0,
5993                ),
5994            ),
5995            &tabled_options_for_view(&view_options),
5996        );
5997        control::set_override(false);
5998
5999        assert!(ansi.contains(&expected_plus), "{ansi}");
6000        assert!(ansi.contains(&expected_minus), "{ansi}");
6001        assert!(ansi.contains("0"), "{ansi}");
6002    }
6003
6004    #[test]
6005    fn mismatched_bin_descriptions_fall_back_to_indices_with_warning() {
6006        let (descriptions, warning) = coalesce_first_non_trivial_discrete_bin_descriptions(
6007            "graph",
6008            &[
6009                (
6010                    "proc_a@itg_a".to_string(),
6011                    vec!["GL0".to_string(), "GL1".to_string()],
6012                ),
6013                (
6014                    "proc_b@itg_b".to_string(),
6015                    vec!["GX0".to_string(), "GX1".to_string()],
6016                ),
6017            ],
6018        );
6019
6020        assert!(descriptions.is_none());
6021        let warning = warning.expect("mismatch should produce a warning");
6022        assert!(warning.contains("graph"), "{warning}");
6023        assert!(warning.contains("proc_a@itg_a"), "{warning}");
6024        assert!(warning.contains("proc_b@itg_b"), "{warning}");
6025    }
6026
6027    #[test]
6028    fn format_max_eval_sample_keeps_full_discrete_coordinates() {
6029        let axis_labels = vec!["graph".to_string(), "sampling channel".to_string()];
6030        let full_sample = Sample::Discrete(
6031            F(1.0),
6032            0,
6033            Some(Box::new(Sample::Discrete(
6034                F(1.0),
6035                1,
6036                Some(Box::new(Sample::Continuous(F(1.0), vec![F(0.25)]))),
6037            ))),
6038        );
6039        let nested_sample = Sample::Discrete(
6040            F(1.0),
6041            1,
6042            Some(Box::new(Sample::Continuous(F(1.0), vec![F(0.75)]))),
6043        );
6044
6045        assert_eq!(
6046            display::format_max_eval_sample(&full_sample, &axis_labels, &[]),
6047            "graph: 0, sampling channel: 1, xs: [ 2.5000000000000000e-01 ]"
6048        );
6049        assert_eq!(
6050            display::format_max_eval_sample(&nested_sample, &axis_labels, &[0]),
6051            "graph: 0, sampling channel: 1, xs: [ 7.5000000000000000e-01 ]"
6052        );
6053    }
6054
6055    #[test]
6056    fn format_max_eval_sample_wraps_long_coordinate_lists() {
6057        let axis_labels = vec!["graph".to_string(), "orientation".to_string()];
6058        let sample = Sample::Discrete(
6059            F(1.0),
6060            0,
6061            Some(Box::new(Sample::Discrete(
6062                F(1.0),
6063                9,
6064                Some(Box::new(Sample::Continuous(
6065                    F(1.0),
6066                    vec![
6067                        F(0.125),
6068                        F(0.25),
6069                        F(0.375),
6070                        F(0.5),
6071                        F(0.625),
6072                        F(0.75),
6073                        F(0.875),
6074                    ],
6075                ))),
6076            ))),
6077        );
6078
6079        assert_eq!(
6080            display::format_max_eval_sample(&sample, &axis_labels, &[]),
6081            "graph: 0, orientation: 9, xs: [\n1.2500000000000000e-01 2.5000000000000000e-01 3.7500000000000000e-01\n5.0000000000000000e-01 6.2500000000000000e-01 7.5000000000000000e-01\n8.7500000000000000e-01 ]"
6082        );
6083    }
6084
6085    #[test]
6086    fn discrete_bin_prefixes_use_fixed_width_within_each_range() {
6087        assert_eq!(status_update::format_discrete_bin_prefix(2, 99), "#2: ");
6088        assert_eq!(status_update::format_discrete_bin_prefix(12, 99), "#12:");
6089        assert_eq!(status_update::format_discrete_bin_prefix(2, 999), "#2:  ");
6090        assert_eq!(status_update::format_discrete_bin_prefix(12, 999), "#12: ");
6091        assert_eq!(status_update::format_discrete_bin_prefix(123, 999), "#123:");
6092        assert_eq!(
6093            status_update::format_discrete_bin_prefix(2, 9_999),
6094            "#2:   "
6095        );
6096        assert_eq!(
6097            status_update::format_discrete_bin_prefix(1234, 9_999),
6098            "#1234:"
6099        );
6100    }
6101
6102    #[test]
6103    fn final_summary_omits_discrete_max_weight_block_when_disabled() {
6104        let state = make_discrete_integration_state();
6105        let rendered = render_saved_integration_summary(
6106            &state,
6107            &[None, None],
6108            &IntegrationStatusViewOptions {
6109                show_statistics: true,
6110                show_max_weight_details: true,
6111                show_top_discrete_grid: false,
6112                show_discrete_contributions_sum: false,
6113                contribution_sort: ContributionSortMode::Index,
6114                show_max_weight_info_for_discrete_bins: false,
6115                ..default_view_options()
6116            },
6117            &default_tabled_options(),
6118        );
6119
6120        assert!(rendered.contains("Maximum weight details"), "{rendered}");
6121        assert!(
6122            !rendered.contains("Maximum weight details by discrete bin"),
6123            "{rendered}"
6124        );
6125        assert!(
6126            !rendered.contains("# samples per iteration = 0"),
6127            "{rendered}"
6128        );
6129    }
6130
6131    #[test]
6132    fn results_output_summary_renders_tabled_workspace_rows() {
6133        let workspace = Path::new("/tmp/gl_workspace");
6134        let rendered = render_results_output_summary_table(Some(workspace), &[], &[], &[])
6135            .expect("workspace summary should render");
6136
6137        assert!(
6138            rendered.contains("Integration results emitted"),
6139            "{rendered}"
6140        );
6141        assert!(rendered.contains("type"), "{rendered}");
6142        assert!(rendered.contains("path"), "{rendered}");
6143        assert!(rendered.contains("workspace path"), "{rendered}");
6144        assert!(rendered.contains("/tmp/gl_workspace"), "{rendered}");
6145        assert!(rendered.contains("results"), "{rendered}");
6146        assert!(rendered.contains("integration_result.json"), "{rendered}");
6147        assert!(rendered.contains("├"), "{rendered}");
6148        assert!(!rendered.contains("iteration snapshots"), "{rendered}");
6149        assert!(!rendered.contains("iter_*"), "{rendered}");
6150    }
6151
6152    #[test]
6153    fn results_output_summary_skips_missing_observable_outputs() {
6154        let settings = RuntimeSettings::default();
6155        let slot = IntegrationSlot::new(
6156            SlotMeta {
6157                process_name: "proc".to_string(),
6158                integrand_name: "default".to_string(),
6159            },
6160            settings.clone(),
6161            Model::empty("integration-test"),
6162            Integrand::TestProbe(TestProbeIntegrand::new(settings, 3)),
6163            None,
6164        );
6165        let rendered = render_results_output_summary_table(
6166            None,
6167            &[slot],
6168            &[vec![PathBuf::from(
6169                "/tmp/definitely_missing_observables_final.json",
6170            )]],
6171            &[],
6172        );
6173
6174        assert!(rendered.is_none(), "{rendered:?}");
6175    }
6176
6177    #[test]
6178    fn results_output_summary_lists_all_emitted_observable_files() {
6179        let base = std::env::temp_dir().join(format!(
6180            "gammaloop_results_output_summary_{}",
6181            std::process::id()
6182        ));
6183        if base.exists() {
6184            let _ = fs::remove_dir_all(&base);
6185        }
6186        let workspace = base.join("workspace");
6187        let slot_dir = workspace.join("integrands").join("proc@default");
6188        fs::create_dir_all(&slot_dir).unwrap();
6189        fs::write(workspace_result_snapshot_path(&workspace), b"{}").unwrap();
6190        let json_path = slot_dir.join("observables_final.json");
6191        let hwu_path = slot_dir.join("observables_final.hwu");
6192        fs::write(&json_path, b"{}").unwrap();
6193        fs::write(&hwu_path, b"# hwu\n").unwrap();
6194
6195        let settings = RuntimeSettings::default();
6196        let slot = IntegrationSlot::new(
6197            SlotMeta {
6198                process_name: "proc".to_string(),
6199                integrand_name: "default".to_string(),
6200            },
6201            settings.clone(),
6202            Model::empty("integration-test"),
6203            Integrand::TestProbe(TestProbeIntegrand::new(settings, 3)),
6204            None,
6205        );
6206        let rendered = render_results_output_summary_table(
6207            Some(&workspace),
6208            &[slot],
6209            &[vec![hwu_path.clone(), json_path.clone()]],
6210            &[],
6211        )
6212        .expect("summary should render");
6213
6214        assert!(rendered.contains("proc@default (hwu)"), "{rendered}");
6215        assert!(rendered.contains("proc@default (json)"), "{rendered}");
6216        assert!(rendered.contains("observables_final.hwu"), "{rendered}");
6217        assert!(rendered.contains("observables_final.json"), "{rendered}");
6218
6219        fs::remove_dir_all(&base).unwrap();
6220    }
6221
6222    #[test]
6223    fn ratatui_overview_shows_eta_and_all_slot_metrics() {
6224        let state = make_integration_state();
6225        let view_options = IntegrationStatusViewOptions {
6226            show_statistics: true,
6227            show_max_weight_details: false,
6228            ..default_view_options()
6229        };
6230        let rendered = render_ratatui_update(
6231            StatusUpdateBuildRequest::new(
6232                IntegrationStatusKind::Live,
6233                &state,
6234                &[Some(Complex::new(F(1.0e-4), F(2.0e-5))), None],
6235                &view_options,
6236            )
6237            .with_timing(
6238                4,
6239                Duration::from_secs(15),
6240                Duration::from_secs(10),
6241                25_000,
6242                125_000,
6243                125_000,
6244            )
6245            .with_live_progress(Some(status_update::LiveIterationProgress {
6246                completed_points: 25_000,
6247                target_points: 100_000,
6248            })),
6249            |_| {},
6250        );
6251
6252        assert!(rendered.contains("Iteration progress"), "{rendered}");
6253        assert!(rendered.contains("ETA 30s"), "{rendered}");
6254        assert!(rendered.contains("25.00K / 100.00K (25.0%)"), "{rendered}");
6255        assert!(rendered.contains("# samples total 125.00K"), "{rendered}");
6256        assert!(rendered.contains("#samples/s"), "{rendered}");
6257        assert!(
6258            rendered.contains("480µs /sample/core (4 cores)"),
6259            "{rendered}"
6260        );
6261        assert!(rendered.contains("/sample/core (4 cores)"), "{rendered}");
6262        assert!(rendered.contains("Integrands"), "{rendered}");
6263        assert!(rendered.contains("Focused integrand"), "{rendered}");
6264        assert!(rendered.contains("Results summary"), "{rendered}");
6265        assert!(
6266            rendered.contains("Integration statistics [global]"),
6267            "{rendered}"
6268        );
6269        assert!(rendered.contains("% err"), "{rendered}");
6270        assert!(rendered.contains("chi^2"), "{rendered}");
6271        assert!(rendered.contains("m.w.i"), "{rendered}");
6272        assert!(
6273            rendered.contains("Timing composition [global]"),
6274            "{rendered}"
6275        );
6276        assert!(rendered.contains("Precision mix [global]"), "{rendered}");
6277    }
6278
6279    #[test]
6280    fn live_preview_merges_and_finalizes_absolute_accumulators_without_mutating_saved_state() {
6281        let mut state = make_integration_state();
6282        state.all_integrals = vec![ComplexAccumulator::new(); state.slot_metas.len()];
6283        let slots = make_preview_test_slots(&state.slot_metas);
6284        let mut core_state = make_preview_test_core_state(&state);
6285        core_state.integrals[0].add_sample(Complex::new(F(-2.0), F(3.0)), None, F(2.0), None);
6286        core_state.integrals[0].add_sample(Complex::new(F(1.0), F(-4.0)), None, F(2.0), None);
6287
6288        let preview_state = build_preview_integration_state(
6289            &state,
6290            &slots,
6291            4,
6292            core_state.completed_points,
6293            1.5,
6294            &[core_state],
6295        );
6296
6297        assert_eq!(state.all_integrals[0].absolute_re.processed_samples, 0);
6298        assert_eq!(state.all_integrals[0].absolute_im.processed_samples, 0);
6299        assert_eq!(preview_state.all_integrals[0].absolute_re.avg, F(3.0));
6300        assert_eq!(preview_state.all_integrals[0].absolute_im.avg, F(7.0));
6301        assert_eq!(
6302            preview_state.all_integrals[0].absolute_re.processed_samples,
6303            2
6304        );
6305        assert_eq!(
6306            preview_state.all_integrals[0].absolute_im.processed_samples,
6307            2
6308        );
6309    }
6310
6311    #[test]
6312    fn live_status_updates_use_current_batch_statistics_in_bottom_panels() {
6313        let state = make_integration_state();
6314        let slots = make_preview_test_slots(&state.slot_metas);
6315        let core_state = make_preview_test_core_state(&state);
6316        let preview_state = build_preview_integration_state(
6317            &state,
6318            &slots,
6319            4,
6320            core_state.completed_points,
6321            1.5,
6322            &[core_state],
6323        );
6324        let view_options = IntegrationStatusViewOptions {
6325            show_statistics: true,
6326            show_max_weight_details: false,
6327            ..default_view_options()
6328        };
6329
6330        let initial_update = build_status_update(
6331            StatusUpdateBuildRequest::new(
6332                IntegrationStatusKind::Live,
6333                &state,
6334                &[Some(Complex::new(F(1.0e-4), F(2.0e-5))), None],
6335                &view_options,
6336            )
6337            .with_timing(
6338                4,
6339                Duration::from_secs(1),
6340                Duration::from_millis(400),
6341                0,
6342                state.num_points,
6343                state.num_points,
6344            )
6345            .with_live_progress(Some(status_update::LiveIterationProgress {
6346                completed_points: 0,
6347                target_points: 100,
6348            })),
6349        );
6350        let preview_update = build_status_update(
6351            StatusUpdateBuildRequest::new(
6352                IntegrationStatusKind::Live,
6353                &preview_state,
6354                &[Some(Complex::new(F(1.0e-4), F(2.0e-5))), None],
6355                &view_options,
6356            )
6357            .with_timing(
6358                4,
6359                Duration::from_millis(1500),
6360                Duration::from_millis(900),
6361                12,
6362                preview_state.num_points,
6363                preview_state.num_points,
6364            )
6365            .with_live_progress(Some(status_update::LiveIterationProgress {
6366                completed_points: 12,
6367                target_points: 100,
6368            })),
6369        );
6370
6371        let initial_statistics = initial_update
6372            .statistics
6373            .as_ref()
6374            .expect("statistics should be present");
6375        let preview_statistics = preview_update
6376            .statistics
6377            .as_ref()
6378            .expect("statistics should be present");
6379        let initial_snapshot = initial_statistics.global_snapshot();
6380        let preview_snapshot = preview_statistics.global_snapshot();
6381
6382        assert!(preview_snapshot.num_evals > initial_snapshot.num_evals);
6383        assert!(preview_snapshot.generated_event_count > initial_snapshot.generated_event_count);
6384        assert!(preview_snapshot.accepted_event_count > initial_snapshot.accepted_event_count);
6385
6386        let initial_timing_mix = initial_statistics
6387            .timing_mix_segments(status_update::StatisticsScope::Global)
6388            .iter()
6389            .map(|segment| segment.percentage)
6390            .collect_vec();
6391        let preview_timing_mix = preview_statistics
6392            .timing_mix_segments(status_update::StatisticsScope::Global)
6393            .iter()
6394            .map(|segment| segment.percentage)
6395            .collect_vec();
6396        assert_ne!(preview_timing_mix, initial_timing_mix);
6397
6398        let initial_precision_mix = initial_statistics
6399            .precision_mix_segments(status_update::StatisticsScope::Global)
6400            .iter()
6401            .map(|segment| segment.percentage)
6402            .collect_vec();
6403        let preview_precision_mix = preview_statistics
6404            .precision_mix_segments(status_update::StatisticsScope::Global)
6405            .iter()
6406            .map(|segment| segment.percentage)
6407            .collect_vec();
6408        assert_ne!(preview_precision_mix, initial_precision_mix);
6409        assert!(
6410            preview_precision_mix
6411                .iter()
6412                .any(|percentage| (*percentage - 50.0).abs() < f64::EPSILON),
6413            "{preview_precision_mix:?}"
6414        );
6415
6416        let preview_render = render_ratatui_update(
6417            StatusUpdateBuildRequest::new(
6418                IntegrationStatusKind::Live,
6419                &preview_state,
6420                &[Some(Complex::new(F(1.0e-4), F(2.0e-5))), None],
6421                &view_options,
6422            )
6423            .with_timing(
6424                4,
6425                Duration::from_millis(1500),
6426                Duration::from_millis(900),
6427                12,
6428                preview_state.num_points,
6429                preview_state.num_points,
6430            )
6431            .with_live_progress(Some(status_update::LiveIterationProgress {
6432                completed_points: 12,
6433                target_points: 100,
6434            })),
6435            |_| {},
6436        );
6437        let preview_total_time = crate::utils::format_evaluation_time_from_f64(
6438            preview_snapshot.average_total_time_seconds,
6439        );
6440        assert!(
6441            preview_render.contains(&preview_total_time),
6442            "{preview_render}"
6443        );
6444        assert!(
6445            preview_render.contains("Precision mix [global]"),
6446            "{preview_render}"
6447        );
6448        assert!(
6449            preview_render.contains("Timing composition [global]"),
6450            "{preview_render}"
6451        );
6452    }
6453
6454    #[test]
6455    fn ratatui_statistics_panels_can_toggle_to_focused_slot_scope() {
6456        let state = make_integration_state();
6457        let view_options = IntegrationStatusViewOptions {
6458            show_statistics: true,
6459            show_max_weight_details: false,
6460            ..default_view_options()
6461        };
6462        let rendered = render_ratatui_update(
6463            StatusUpdateBuildRequest::new(
6464                IntegrationStatusKind::Live,
6465                &state,
6466                &[Some(Complex::new(F(1.0e-4), F(2.0e-5))), None],
6467                &view_options,
6468            )
6469            .with_timing(
6470                4,
6471                Duration::from_secs(15),
6472                Duration::from_secs(10),
6473                25_000,
6474                125_000,
6475                125_000,
6476            ),
6477            |dashboard| {
6478                dashboard.focus_next_slot();
6479                dashboard.toggle_statistics_scope();
6480            },
6481        );
6482
6483        assert!(
6484            rendered.contains("Integration statistics [proc_b@itg_b]"),
6485            "{rendered}"
6486        );
6487        assert!(
6488            rendered.contains("Timing composition [proc_b@itg_b]"),
6489            "{rendered}"
6490        );
6491        assert!(
6492            rendered.contains("Precision mix [proc_b@itg_b]"),
6493            "{rendered}"
6494        );
6495        assert!(rendered.contains("Scope i"), "{rendered}");
6496    }
6497
6498    #[test]
6499    fn slot_scoped_statistics_rows_hide_shared_integrator_overhead() {
6500        let state = make_integration_state();
6501        let update = build_status_update(
6502            StatusUpdateBuildRequest::new(
6503                IntegrationStatusKind::Iteration,
6504                &state,
6505                &[None, None],
6506                &default_view_options(),
6507            )
6508            .with_timing(
6509                4,
6510                Duration::from_secs(1),
6511                Duration::from_secs(1),
6512                100_000,
6513                100_000,
6514                100_000,
6515            ),
6516        );
6517        let statistics = update.statistics.expect("statistics section should exist");
6518        let rows = statistics.table_rows(status_update::StatisticsScope::Slot(1));
6519        let integrator_entry = rows[2]
6520            .entries
6521            .last()
6522            .expect("integrator entry should be present");
6523
6524        assert_eq!(integrator_entry.label.to_plain_string(), "integrator");
6525        assert_eq!(integrator_entry.value.to_plain_string(), "N/A");
6526    }
6527
6528    #[test]
6529    fn ratatui_overview_chart_phase_toggle_updates_convergence_label() {
6530        let state = make_integration_state();
6531        let view_options = IntegrationStatusViewOptions {
6532            show_statistics: false,
6533            show_max_weight_details: false,
6534            ..default_view_options()
6535        };
6536        let rendered = render_ratatui_update(
6537            StatusUpdateBuildRequest::new(
6538                IntegrationStatusKind::Live,
6539                &state,
6540                &[Some(Complex::new(F(1.0e-4), F(2.0e-5))), None],
6541                &view_options,
6542            )
6543            .with_timing(
6544                4,
6545                Duration::from_secs(15),
6546                Duration::from_secs(10),
6547                25_000,
6548                125_000,
6549                125_000,
6550            )
6551            .with_live_progress(Some(status_update::LiveIterationProgress {
6552                completed_points: 25_000,
6553                target_points: 100_000,
6554            })),
6555            |dashboard| dashboard.toggle_chart_component(),
6556        );
6557
6558        assert!(
6559            rendered.contains("Convergence ⟨I⟩ : im (not selected for training)"),
6560            "{rendered}"
6561        );
6562    }
6563
6564    #[test]
6565    fn ratatui_integrand_targets_are_trimmed_for_display() {
6566        let state = make_integration_state();
6567        let view_options = IntegrationStatusViewOptions {
6568            show_statistics: false,
6569            show_max_weight_details: false,
6570            ..default_view_options()
6571        };
6572        let rendered = render_ratatui_update(
6573            StatusUpdateBuildRequest::new(
6574                IntegrationStatusKind::Live,
6575                &state,
6576                &[
6577                    Some(Complex::new(
6578                        F(7.600000000000001e-6),
6579                        F(7.430000000000004e-5),
6580                    )),
6581                    Some(Complex::new(F(6.629999999999999e-5), F(0.0))),
6582                ],
6583                &view_options,
6584            )
6585            .with_timing(
6586                4,
6587                Duration::from_secs(15),
6588                Duration::from_secs(10),
6589                25_000,
6590                125_000,
6591                125_000,
6592            )
6593            .with_live_progress(Some(status_update::LiveIterationProgress {
6594                completed_points: 25_000,
6595                target_points: 100_000,
6596            })),
6597            |_| {},
6598        );
6599
6600        assert!(rendered.contains("trgt"), "{rendered}");
6601        assert!(rendered.contains("+7.6e-6"), "{rendered}");
6602        assert!(rendered.contains("+7.43e-5"), "{rendered}");
6603        assert!(rendered.contains("+6.63e-5"), "{rendered}");
6604        assert!(rendered.contains("+0e0"), "{rendered}");
6605    }
6606
6607    #[test]
6608    fn ratatui_overview_shows_eta_to_target_when_configured() {
6609        let state = make_integration_state();
6610        let view_options = IntegrationStatusViewOptions {
6611            target_relative_accuracy: Some(0.05),
6612            show_statistics: false,
6613            show_max_weight_details: false,
6614            ..default_view_options()
6615        };
6616        let rendered = render_ratatui_update(
6617            StatusUpdateBuildRequest::new(
6618                IntegrationStatusKind::Live,
6619                &state,
6620                &[Some(Complex::new(F(1.0e-4), F(0.0))), None],
6621                &view_options,
6622            )
6623            .with_timing(
6624                4,
6625                Duration::from_secs(25),
6626                Duration::from_secs(10),
6627                25_000,
6628                125_000,
6629                125_000,
6630            )
6631            .with_live_progress(Some(status_update::LiveIterationProgress {
6632                completed_points: 25_000,
6633                target_points: 100_000,
6634            })),
6635            |_| {},
6636        );
6637
6638        assert!(rendered.contains("ETA to ⟨I⟩ target"), "{rendered}");
6639        assert!(rendered.contains("(% err <= 5%)"), "{rendered}");
6640    }
6641
6642    #[test]
6643    fn eta_to_target_specification_formats_relative_and_absolute_targets() {
6644        let state = make_integration_state();
6645        let relative_view_options = IntegrationStatusViewOptions {
6646            target_relative_accuracy: Some(0.05),
6647            ..default_view_options()
6648        };
6649        let update = build_status_update(
6650            StatusUpdateBuildRequest::new(
6651                IntegrationStatusKind::Live,
6652                &state,
6653                &[Some(Complex::new(F(1.0e-4), F(0.0))), None],
6654                &relative_view_options,
6655            )
6656            .with_timing(
6657                4,
6658                Duration::from_secs(25),
6659                Duration::from_secs(10),
6660                25_000,
6661                125_000,
6662                125_000,
6663            )
6664            .with_live_progress(Some(status_update::LiveIterationProgress {
6665                completed_points: 25_000,
6666                target_points: 100_000,
6667            })),
6668        );
6669        assert_eq!(
6670            update.meta.eta_to_target_specification(),
6671            Some("% err <= 5%")
6672        );
6673
6674        let relative_scientific_view_options = IntegrationStatusViewOptions {
6675            target_relative_accuracy: Some(1.0e-6),
6676            ..default_view_options()
6677        };
6678        let update = build_status_update(
6679            StatusUpdateBuildRequest::new(
6680                IntegrationStatusKind::Live,
6681                &state,
6682                &[Some(Complex::new(F(1.0e-4), F(0.0))), None],
6683                &relative_scientific_view_options,
6684            )
6685            .with_timing(
6686                4,
6687                Duration::from_secs(25),
6688                Duration::from_secs(10),
6689                25_000,
6690                125_000,
6691                125_000,
6692            )
6693            .with_live_progress(Some(status_update::LiveIterationProgress {
6694                completed_points: 25_000,
6695                target_points: 100_000,
6696            })),
6697        );
6698        assert_eq!(
6699            update.meta.eta_to_target_specification(),
6700            Some("% err <= 1e-4%")
6701        );
6702
6703        let absolute_view_options = IntegrationStatusViewOptions {
6704            target_absolute_accuracy: Some(1.0e-6),
6705            ..default_view_options()
6706        };
6707        let update = build_status_update(
6708            StatusUpdateBuildRequest::new(
6709                IntegrationStatusKind::Live,
6710                &state,
6711                &[Some(Complex::new(F(1.0e-4), F(0.0))), None],
6712                &absolute_view_options,
6713            )
6714            .with_timing(
6715                4,
6716                Duration::from_secs(25),
6717                Duration::from_secs(10),
6718                25_000,
6719                125_000,
6720                125_000,
6721            )
6722            .with_live_progress(Some(status_update::LiveIterationProgress {
6723                completed_points: 25_000,
6724                target_points: 100_000,
6725            })),
6726        );
6727        assert_eq!(
6728            update.meta.eta_to_target_specification(),
6729            Some("err <= 1e-6")
6730        );
6731
6732        let combined_view_options = IntegrationStatusViewOptions {
6733            target_relative_accuracy: Some(0.05),
6734            target_absolute_accuracy: Some(1.0e-6),
6735            ..default_view_options()
6736        };
6737        let update = build_status_update(
6738            StatusUpdateBuildRequest::new(
6739                IntegrationStatusKind::Live,
6740                &state,
6741                &[Some(Complex::new(F(1.0e-4), F(0.0))), None],
6742                &combined_view_options,
6743            )
6744            .with_timing(
6745                4,
6746                Duration::from_secs(25),
6747                Duration::from_secs(10),
6748                25_000,
6749                125_000,
6750                125_000,
6751            )
6752            .with_live_progress(Some(status_update::LiveIterationProgress {
6753                completed_points: 25_000,
6754                target_points: 100_000,
6755            })),
6756        );
6757        assert_eq!(
6758            update.meta.eta_to_target_specification(),
6759            Some("% err <= 5% or err <= 1e-6")
6760        );
6761    }
6762
6763    #[test]
6764    fn target_accuracy_status_uses_either_absolute_or_relative_condition() {
6765        let state = make_integration_state();
6766
6767        let reached_by_absolute = status_update::evaluate_target_accuracy(
6768            &state,
6769            100_000,
6770            Duration::from_secs(10),
6771            &[None, None],
6772            IntegrationStatusPhaseDisplay::Real,
6773            None,
6774            Some(1.0e-4),
6775        );
6776        assert!(reached_by_absolute.is_reached());
6777
6778        let reached_by_relative = status_update::evaluate_target_accuracy(
6779            &state,
6780            100_000,
6781            Duration::from_secs(10),
6782            &[Some(Complex::new(F(1.0e-3), F(0.0))), None],
6783            IntegrationStatusPhaseDisplay::Real,
6784            Some(0.1),
6785            None,
6786        );
6787        assert!(reached_by_relative.is_reached());
6788    }
6789
6790    #[test]
6791    fn target_accuracy_status_requires_all_slots_to_reach_relative_target() {
6792        let mut state = make_integration_state();
6793        state.all_integrals[0].re.avg = F(1.0);
6794        state.all_integrals[0].re.err = F(1.0e-5);
6795        state.all_integrals[1].re.avg = F(1.0);
6796        state.all_integrals[1].re.err = F(2.0e-3);
6797
6798        let status = status_update::evaluate_target_accuracy(
6799            &state,
6800            100_000,
6801            Duration::from_secs(10),
6802            &[None, None],
6803            IntegrationStatusPhaseDisplay::Real,
6804            Some(1.0e-3),
6805            None,
6806        );
6807
6808        assert!(!status.is_reached());
6809        assert!(!status.relative_reached);
6810        assert!(status.eta_to_target.is_some());
6811    }
6812
6813    #[test]
6814    fn target_accuracy_status_requires_all_displayed_components_to_reach_target() {
6815        let mut state = make_integration_state();
6816        state.all_integrals[0].re.avg = F(1.0);
6817        state.all_integrals[0].re.err = F(1.0e-5);
6818        state.all_integrals[0].im.avg = F(1.0);
6819        state.all_integrals[0].im.err = F(2.0e-3);
6820
6821        let status = status_update::evaluate_target_accuracy(
6822            &state,
6823            100_000,
6824            Duration::from_secs(10),
6825            &[Some(Complex::new(F(1.0), F(1.0))), None],
6826            IntegrationStatusPhaseDisplay::Both,
6827            Some(1.0e-3),
6828            None,
6829        );
6830
6831        assert!(!status.is_reached());
6832        assert!(!status.relative_reached);
6833        assert!(status.eta_to_target.is_some());
6834    }
6835
6836    #[test]
6837    fn target_accuracy_status_reports_infinite_eta_for_unreachable_absolute_target() {
6838        let state = make_integration_state();
6839        let status = status_update::evaluate_target_accuracy(
6840            &state,
6841            100_000,
6842            Duration::from_secs(10),
6843            &[None, None],
6844            IntegrationStatusPhaseDisplay::Real,
6845            None,
6846            Some(1.0e-99),
6847        );
6848
6849        assert!(!status.is_reached());
6850        assert_eq!(status.eta_to_target, Some(Duration::MAX));
6851    }
6852
6853    #[test]
6854    fn target_accuracy_status_prefers_finite_relative_eta_over_infinite_absolute_eta() {
6855        let state = make_integration_state();
6856        let status = status_update::evaluate_target_accuracy(
6857            &state,
6858            100_000,
6859            Duration::from_secs(10),
6860            &[None, None],
6861            IntegrationStatusPhaseDisplay::Real,
6862            Some(1.0e-3),
6863            Some(1.0e-99),
6864        );
6865
6866        assert!(!status.is_reached());
6867        assert!(status.eta_to_target.is_some());
6868        assert_ne!(status.eta_to_target, Some(Duration::MAX));
6869    }
6870
6871    #[test]
6872    fn ratatui_overview_displays_infinite_eta_to_target() {
6873        let state = make_integration_state();
6874        let view_options = IntegrationStatusViewOptions {
6875            target_absolute_accuracy: Some(1.0e-99),
6876            show_statistics: false,
6877            show_max_weight_details: false,
6878            ..default_view_options()
6879        };
6880        let rendered = render_ratatui_update(
6881            StatusUpdateBuildRequest::new(
6882                IntegrationStatusKind::Live,
6883                &state,
6884                &[Some(Complex::new(F(1.0e-4), F(0.0))), None],
6885                &view_options,
6886            )
6887            .with_timing(
6888                4,
6889                Duration::from_secs(25),
6890                Duration::from_secs(10),
6891                25_000,
6892                125_000,
6893                125_000,
6894            )
6895            .with_live_progress(Some(status_update::LiveIterationProgress {
6896                completed_points: 25_000,
6897                target_points: 100_000,
6898            })),
6899            |_| {},
6900        );
6901
6902        assert!(rendered.contains("ETA to ⟨I⟩ target"), "{rendered}");
6903        assert!(rendered.contains("∞"), "{rendered}");
6904    }
6905
6906    #[test]
6907    fn ratatui_overview_prefers_finite_relative_eta_over_infinite_absolute_eta() {
6908        let state = make_integration_state();
6909        let view_options = IntegrationStatusViewOptions {
6910            target_relative_accuracy: Some(1.0e-3),
6911            target_absolute_accuracy: Some(1.0e-99),
6912            show_statistics: false,
6913            show_max_weight_details: false,
6914            ..default_view_options()
6915        };
6916        let rendered = render_ratatui_update(
6917            StatusUpdateBuildRequest::new(
6918                IntegrationStatusKind::Live,
6919                &state,
6920                &[Some(Complex::new(F(1.0e-4), F(0.0))), None],
6921                &view_options,
6922            )
6923            .with_timing(
6924                4,
6925                Duration::from_secs(25),
6926                Duration::from_secs(10),
6927                25_000,
6928                125_000,
6929                125_000,
6930            )
6931            .with_live_progress(Some(status_update::LiveIterationProgress {
6932                completed_points: 25_000,
6933                target_points: 100_000,
6934            })),
6935            |_| {},
6936        );
6937
6938        assert!(rendered.contains("ETA to ⟨I⟩ target"), "{rendered}");
6939        assert!(!rendered.contains("∞"), "{rendered}");
6940    }
6941
6942    #[test]
6943    fn ratatui_recent_history_window_tracks_current_iteration_points() {
6944        let mut dashboard = RatatuiDashboardState::new();
6945        let mut state = make_integration_state();
6946        let view_options = IntegrationStatusViewOptions {
6947            show_statistics: false,
6948            show_max_weight_details: false,
6949            ..default_view_options()
6950        };
6951
6952        state.iter = 1;
6953        dashboard.update(build_status_update(
6954            StatusUpdateBuildRequest::new(
6955                IntegrationStatusKind::Live,
6956                &state,
6957                &[None, None],
6958                &view_options,
6959            )
6960            .with_timing(
6961                4,
6962                Duration::from_secs(10),
6963                Duration::from_secs(10),
6964                500_000,
6965                1_000_000,
6966                1_000_000,
6967            )
6968            .with_live_progress(Some(status_update::LiveIterationProgress {
6969                completed_points: 500_000,
6970                target_points: 1_000_000,
6971            })),
6972        ));
6973
6974        state.iter = 2;
6975        dashboard.update(build_status_update(
6976            StatusUpdateBuildRequest::new(
6977                IntegrationStatusKind::Live,
6978                &state,
6979                &[None, None],
6980                &view_options,
6981            )
6982            .with_timing(
6983                4,
6984                Duration::from_secs(20),
6985                Duration::from_secs(5),
6986                0,
6987                2_000_000,
6988                2_000_000,
6989            )
6990            .with_live_progress(Some(status_update::LiveIterationProgress {
6991                completed_points: 0,
6992                target_points: 1_000_000,
6993            })),
6994        ));
6995        dashboard.update(build_status_update(
6996            StatusUpdateBuildRequest::new(
6997                IntegrationStatusKind::Live,
6998                &state,
6999                &[None, None],
7000                &view_options,
7001            )
7002            .with_timing(
7003                4,
7004                Duration::from_secs(25),
7005                Duration::from_secs(10),
7006                200_000,
7007                2_200_000,
7008                2_200_000,
7009            )
7010            .with_live_progress(Some(status_update::LiveIterationProgress {
7011                completed_points: 200_000,
7012                target_points: 1_000_000,
7013            })),
7014        ));
7015
7016        dashboard.toggle_chart_history_window();
7017        for _ in 0..5 {
7018            dashboard.narrow_chart_history_window();
7019        }
7020
7021        assert_eq!(
7022            dashboard.visible_history_sample_bounds(),
7023            Some((2_000_000, 2_200_000))
7024        );
7025    }
7026
7027    #[test]
7028    fn ratatui_full_history_preserves_origin_after_compaction() {
7029        let mut dashboard = RatatuiDashboardState::new();
7030        let mut state = make_integration_state();
7031        let view_options = IntegrationStatusViewOptions {
7032            show_statistics: false,
7033            show_max_weight_details: false,
7034            ..default_view_options()
7035        };
7036
7037        for index in 0..4_300 {
7038            state.iter = 1 + index / 40;
7039            let total_points = index * 1_000;
7040            dashboard.update(build_status_update(
7041                StatusUpdateBuildRequest::new(
7042                    IntegrationStatusKind::Live,
7043                    &state,
7044                    &[None, None],
7045                    &view_options,
7046                )
7047                .with_timing(
7048                    4,
7049                    Duration::from_secs(index as u64),
7050                    Duration::from_secs(10),
7051                    total_points % 1_000_000,
7052                    total_points,
7053                    total_points,
7054                )
7055                .with_live_progress(Some(status_update::LiveIterationProgress {
7056                    completed_points: total_points % 1_000_000,
7057                    target_points: 1_000_000,
7058                })),
7059            ));
7060        }
7061
7062        dashboard.toggle_chart_history_window();
7063        dashboard.toggle_chart_history_window();
7064
7065        assert_eq!(
7066            dashboard.visible_history_sample_bounds(),
7067            Some((0, 4_299_000))
7068        );
7069    }
7070
7071    #[test]
7072    fn ratatui_convergence_title_shows_active_y_span() {
7073        let state = make_integration_state();
7074        let view_options = IntegrationStatusViewOptions {
7075            show_statistics: false,
7076            show_max_weight_details: false,
7077            ..default_view_options()
7078        };
7079        let rendered = render_ratatui_update(
7080            StatusUpdateBuildRequest::new(
7081                IntegrationStatusKind::Live,
7082                &state,
7083                &[None, None],
7084                &view_options,
7085            )
7086            .with_timing(
7087                4,
7088                Duration::from_secs(15),
7089                Duration::from_secs(10),
7090                25_000,
7091                125_000,
7092                125_000,
7093            )
7094            .with_live_progress(Some(status_update::LiveIterationProgress {
7095                completed_points: 25_000,
7096                target_points: 100_000,
7097            })),
7098            |dashboard| dashboard.widen_chart_y_sigma_span(),
7099        );
7100
7101        assert!(rendered.contains("y ±5σ"), "{rendered}");
7102    }
7103
7104    #[test]
7105    fn ratatui_convergence_axis_uses_small_dimensionful_uncertainty_verbatim() {
7106        let mut state = make_integration_state();
7107        state.all_integrals[0] = make_accumulator(-2.12e-15, 5.2e-16, 1.0, 1.0e-15, 1.0e-16, 1.0);
7108        let view_options = IntegrationStatusViewOptions {
7109            show_statistics: false,
7110            show_max_weight_details: false,
7111            ..default_view_options()
7112        };
7113        let rendered = render_ratatui_update(
7114            StatusUpdateBuildRequest::new(
7115                IntegrationStatusKind::Live,
7116                &state,
7117                &[None, None],
7118                &view_options,
7119            )
7120            .with_timing(
7121                4,
7122                Duration::from_secs(15),
7123                Duration::from_secs(10),
7124                25_000,
7125                125_000,
7126                125_000,
7127            )
7128            .with_live_progress(Some(status_update::LiveIterationProgress {
7129                completed_points: 25_000,
7130                target_points: 100_000,
7131            })),
7132            |_| {},
7133        );
7134
7135        assert!(rendered.contains("-4.200e-15"), "{rendered}");
7136        assert!(rendered.contains("-4.000e-17"), "{rendered}");
7137        assert!(!rendered.contains("e-12"), "{rendered}");
7138    }
7139
7140    #[test]
7141    fn ratatui_convergence_waits_for_non_zero_uncertainty() {
7142        let mut state = make_integration_state();
7143        state.all_integrals[0] = make_accumulator(1.0e-15, 0.0, 1.0, 1.0e-15, 0.0, 1.0);
7144        let view_options = IntegrationStatusViewOptions {
7145            show_statistics: false,
7146            show_max_weight_details: false,
7147            ..default_view_options()
7148        };
7149        let rendered = render_ratatui_update(
7150            StatusUpdateBuildRequest::new(
7151                IntegrationStatusKind::Live,
7152                &state,
7153                &[None, None],
7154                &view_options,
7155            )
7156            .with_timing(
7157                4,
7158                Duration::from_secs(15),
7159                Duration::from_secs(10),
7160                25_000,
7161                125_000,
7162                125_000,
7163            )
7164            .with_live_progress(Some(status_update::LiveIterationProgress {
7165                completed_points: 25_000,
7166                target_points: 100_000,
7167            })),
7168            |_| {},
7169        );
7170
7171        assert!(
7172            rendered.contains("Waiting for a finite central value and non-zero MC uncertainty"),
7173            "{rendered}"
7174        );
7175    }
7176
7177    #[test]
7178    fn ratatui_discrete_tab_renders_selected_bin_detail() {
7179        let state = make_discrete_integration_state();
7180        let view_options = IntegrationStatusViewOptions {
7181            show_statistics: false,
7182            show_max_weight_details: false,
7183            show_top_discrete_grid: false,
7184            show_discrete_contributions_sum: false,
7185            show_max_weight_info_for_discrete_bins: false,
7186            ..default_view_options()
7187        };
7188        let rendered = render_ratatui_update(
7189            StatusUpdateBuildRequest::new(
7190                IntegrationStatusKind::Iteration,
7191                &state,
7192                &[Some(Complex::new(F(1.0e-4), F(2.0e-5))), None],
7193                &view_options,
7194            )
7195            .with_timing(
7196                4,
7197                Duration::from_secs(12),
7198                Duration::from_secs(12),
7199                110_000,
7200                210_000,
7201                210_000,
7202            ),
7203            |dashboard| dashboard.select_tab(1),
7204        );
7205
7206        assert!(rendered.contains("Selected bin"), "{rendered}");
7207        assert!(
7208            rendered.contains("Discrete bins ⟨I⟩ for focused integrand"),
7209            "{rendered}"
7210        );
7211        assert!(rendered.contains("sample %"), "{rendered}");
7212        assert!(rendered.contains("GL0"), "{rendered}");
7213        assert!(rendered.contains("GL1"), "{rendered}");
7214        assert!(rendered.contains("pdf"), "{rendered}");
7215        assert!(rendered.contains("Per integrand details"), "{rendered}");
7216        assert!(rendered.contains("# samples"), "{rendered}");
7217    }
7218
7219    #[test]
7220    fn ratatui_single_graph_subset_keeps_the_graph_row() {
7221        let state = make_single_graph_discrete_integration_state();
7222        let view_options = IntegrationStatusViewOptions {
7223            show_statistics: false,
7224            show_max_weight_details: false,
7225            ..default_view_options()
7226        };
7227        let rendered = render_ratatui_update(
7228            StatusUpdateBuildRequest::new(
7229                IntegrationStatusKind::Iteration,
7230                &state,
7231                &[None, None],
7232                &view_options,
7233            ),
7234            |dashboard| dashboard.select_tab(1),
7235        );
7236
7237        assert!(
7238            rendered.contains("Discrete bins ⟨I⟩ for focused integrand"),
7239            "{rendered}"
7240        );
7241        assert!(rendered.contains("GL22"), "{rendered}");
7242        assert!(!rendered.contains("GL1"), "{rendered}");
7243    }
7244
7245    #[test]
7246    fn ratatui_max_weight_tab_preserves_full_scientific_exponent() {
7247        let mut state = make_discrete_integration_state();
7248        let max_eval = 3.8477312059601813_f64;
7249        let expected = format!("{:+.16e}", max_eval);
7250        state.all_integrals[0].re.max_eval_positive = F(max_eval);
7251        state.all_integrals[0].re.max_eval_positive_xs = Some(Sample::Discrete(
7252            F(1.0),
7253            0,
7254            Some(Box::new(Sample::Continuous(
7255                F(1.0),
7256                vec![F(0.4502578156709256)],
7257            ))),
7258        ));
7259
7260        let view_options = IntegrationStatusViewOptions {
7261            show_statistics: false,
7262            ..default_view_options()
7263        };
7264        let rendered = render_ratatui_update(
7265            StatusUpdateBuildRequest::new(
7266                IntegrationStatusKind::Iteration,
7267                &state,
7268                &[Some(Complex::new(F(1.0e-4), F(2.0e-5))), None],
7269                &view_options,
7270            )
7271            .with_timing(
7272                4,
7273                Duration::from_secs(12),
7274                Duration::from_secs(12),
7275                110_000,
7276                210_000,
7277                210_000,
7278            ),
7279            |dashboard| dashboard.select_tab(2),
7280        );
7281
7282        assert!(rendered.contains(&expected), "{rendered}");
7283        assert!(rendered.contains("graph: 0, xs: ["), "{rendered}");
7284    }
7285
7286    #[test]
7287    fn target_accuracy_status_treats_zero_relative_reference_as_inactive() {
7288        let state = make_integration_state();
7289        let targets = vec![Some(Complex::new(F(0.0), F(0.0))); state.all_integrals.len()];
7290        let status = status_update::evaluate_target_accuracy(
7291            &state,
7292            100_000,
7293            Duration::from_secs(10),
7294            &targets,
7295            IntegrationStatusPhaseDisplay::Real,
7296            Some(0.05),
7297            None,
7298        );
7299
7300        assert!(!status.relative_reached);
7301        assert!(!status.absolute_reached);
7302        assert_eq!(status.eta_to_target, None);
7303
7304        // A missing reference still uses that integral's nonzero mean.
7305        let status = status_update::evaluate_target_accuracy(
7306            &state,
7307            100_000,
7308            Duration::from_secs(10),
7309            &[Some(Complex::new(F(0.0), F(0.0))), None],
7310            IntegrationStatusPhaseDisplay::Real,
7311            Some(0.05),
7312            None,
7313        );
7314        assert!(status.eta_to_target.is_some());
7315    }
7316}
7317
7318#[test]
7319fn test_threading() {
7320    use symbolica::numerical_integration::ContinuousGrid;
7321
7322    fn test_fn(x: f64) -> f64 {
7323        x * x * (x * 6.).sin()
7324    }
7325
7326    let mut acc_1 = StatisticsAccumulator::<f64>::new();
7327    let mut acc_2 = StatisticsAccumulator::<f64>::new();
7328
7329    let samples_per_sample = 4;
7330    let samples_per_iter = 100000;
7331    let n_iter = 10;
7332
7333    let mut rng = MonteCarloRng::new(42, 0);
7334
7335    let mut grid = Grid::<f64>::Continuous(ContinuousGrid::new(1, 64, 100, None, false).unwrap());
7336
7337    for _i_iter in 0..n_iter {
7338        let mut multiplice_accs = vec![StatisticsAccumulator::<f64>::new(); samples_per_sample];
7339        for _i_sample in 0..samples_per_iter {
7340            let n_samples = (0..samples_per_sample)
7341                .map(|_| {
7342                    let mut sample = Sample::new();
7343                    grid.sample(&mut rng, &mut sample);
7344                    sample
7345                })
7346                .collect_vec();
7347
7348            let n_evals = n_samples
7349                .iter()
7350                .map(|s| match s {
7351                    Sample::Continuous(_, xs) => test_fn(xs[0]),
7352                    _ => unreachable!(),
7353                })
7354                .collect_vec();
7355
7356            for (i_eval, (sample, eval)) in n_samples.iter().zip(&n_evals).enumerate() {
7357                acc_1.add_sample(eval * sample.get_weight(), Some(sample));
7358                multiplice_accs[i_eval].add_sample(eval * sample.get_weight(), Some(sample));
7359            }
7360        }
7361
7362        for acc in multiplice_accs {
7363            acc_2.merge_samples(&mut acc.clone());
7364        }
7365        acc_1.update_iter(false);
7366        acc_2.update_iter(false);
7367    }
7368
7369    println!("acc1: {:?}", acc_1);
7370    println!("acc2: {:?}", acc_2);
7371}