Skip to main content

gammalooprs/integrands/process/
mod.rs

1use std::collections::{BTreeMap, BTreeSet};
2use std::fs;
3use std::path::Path;
4use std::result::Result as StdResult;
5
6use crate::cff::OrientationID;
7use crate::graph::{FeynmanGraph, Graph, GraphGroup, GroupId, LmbIndex, LoopMomentumBasis};
8use crate::integrands::evaluation::{
9    EvaluationMetaData, EvaluationResult, GenericEvaluationResult, GraphEvaluationResult,
10    LoopMomentaEscalationMetrics, PreciseEvaluationResult, RawBatchEvaluationResult,
11    RawPreciseBatchEvaluationResult, RotatedEvaluation, StabilityFailureReason, StabilityResult,
12    StabilityStatus, StatisticsCounter,
13};
14use crate::model::Model;
15use crate::momentum::sample::{BareMomentumSample, LoopIndex, LoopMomenta, MomentumSample};
16use crate::momentum::{Rotation, ThreeMomentum};
17use crate::observables::{
18    AdditionalWeightKey, EventProcessingRuntime, GenericEvent, HistogramProcessInfo,
19    ObservableAccumulationError, ObservableAccumulatorBundle, ObservableFileFormat,
20    ObservableSnapshotBundle,
21};
22use crate::processes::{
23    CutGroupId, GraphGenerationStats, GraphGroupSelectionSpec, StandaloneExportSettings,
24};
25use crate::subtraction::lu_counterterm::LUSharedOverlaps;
26use crate::utils::{
27    ArbPrec, F, FloatLike, RuntimeCache, SamplingFloat, SamplingPrecision, f128,
28    format_for_compare_digits, get_n_dim_for_n_loop_momenta,
29};
30use bincode_trait_derive::{Decode, Encode};
31use color_eyre::owo_colors::OwoColorize;
32use colored::Colorize;
33use enum_dispatch::enum_dispatch;
34use eyre::{Context, eyre};
35use gammaloop_sample::{DiscreteGraphSample, GammaLoopSample, parameterize};
36use itertools::Itertools;
37use linnet::half_edge::involution::EdgeVec;
38use linnet::half_edge::involution::Orientation;
39use linnet::half_edge::subgraph::{SubSetLike, subset::SubSet};
40use momtrop::SampleGenerator;
41use serde::{Deserialize, Serialize};
42use smallvec::SmallVec;
43use spenso::algebra::algebraic_traits::IsZero;
44use spenso::algebra::complex::Complex;
45use std::sync::Arc;
46use std::sync::Once;
47use std::time::{Duration, Instant};
48use symbolica::atom::Atom;
49use symbolica::numerical_integration::{ContinuousGrid, DiscreteGrid, Grid, Sample};
50use tracing::{debug, warn};
51use typed_index_collections::TiVec;
52pub mod amplitude;
53pub mod cache_debugging;
54pub mod cross_section;
55pub(crate) mod fermi_surface;
56pub mod gammaloop_sample;
57pub mod ir;
58pub mod sampling;
59pub(crate) mod standalone;
60use crate::{
61    DependentMomentaConstructor, GammaLoopContext,
62    settings::RuntimeSettings,
63    settings::global::RepresentationMode,
64    settings::runtime::DiscreteGraphSamplingSettings,
65    settings::runtime::DiscreteGraphSamplingType,
66    settings::runtime::IntegratorSettings,
67    settings::runtime::ParameterizationSettings,
68    settings::runtime::Precision,
69    settings::runtime::RotationSetting,
70    settings::runtime::StabilityLevelSetting,
71    settings::runtime::StabilitySettings,
72    settings::runtime::{IntegratedPhase, SamplingChannelWeight, SamplingSettings},
73};
74use color_eyre::Result;
75use sampling::context::PreparedLUHost;
76use sampling::selection::SamplingChannelPrograms;
77pub use sampling::{
78    CompiledSamplingChannel, CompiledSamplingMap, GaussianReferenceFunction,
79    ImplicitSurfaceContextPreparer, ImplicitSurfaceRadialContextEvaluator,
80    ImplicitSurfaceRadialEvaluator, ImplicitSurfaceRadialMap, PreparedSurfaceStatus,
81    ReferenceMoments, ReferenceSampleEvaluation, ReferenceSamplingReport,
82    ResolvedNamedSamplingChannel, ResolvedSamplingBlock, ResolvedSamplingChannelSelection,
83    SamplingCatalogueEntry, SamplingChannelBridge, SamplingChannelBridgeAcceptanceReport,
84    SamplingChannelBridgeError, SamplingChannelBridgeEvaluation, SamplingChannelCatalogue,
85    SamplingChannelCompileContext, SamplingChannelCompileError, SamplingChannelId,
86    SamplingChannelInspection, SamplingChannelPreset, SamplingChannelRuntimeContexts,
87    SamplingChannelScore, SamplingChannelSelector, SamplingCoverageReport, SamplingCutSide,
88    SamplingDualValue, SamplingExpressionEvaluator, SamplingGeometryKey, SamplingJacobian,
89    SamplingMapAcceptanceReport, SamplingMapAffine, SamplingMapComponent, SamplingMapComposition,
90    SamplingMapContextTransform, SamplingMapContract, SamplingMapDefinition, SamplingMapEmbedding,
91    SamplingMapEvaluation, SamplingMapKernel, SamplingMapPoint, SamplingMomentumSampleContext,
92    SamplingPartition, SamplingPartitionMode, SamplingScoreFunction, SamplingSelectionError,
93    SamplingSupport, SharedEnergyJointGeometry, SharedEnergyJointMap, SurfaceRadialMap,
94    SurfaceRadialPoint, build_sampling_channel_catalogue,
95    build_sampling_channel_catalogue_with_surfaces,
96    build_sampling_channel_catalogue_with_surfaces_and_coverage, explicitly_selected_graphs,
97    graph_channel_definitions, resolve_sampling_channel_selection,
98    resolve_sampling_channel_selection_replacing_default,
99};
100
101pub mod evaluators;
102pub use evaluators::ActiveF64Backend;
103pub use evaluators::{GenericEvaluator, GenericEvaluatorFloat};
104
105pub mod param_builder;
106mod param_value_pairs;
107pub use param_builder::{ParamBuilder, ParamValuePairs, ThresholdParams, UpdateAndGetParams};
108
109pub mod threshold_multiplier;
110
111#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
112pub enum OrientationProfileMode {
113    #[default]
114    Summed,
115    PerOrientation,
116}
117
118impl OrientationProfileMode {
119    pub fn profiles_per_orientation(self) -> bool {
120        matches!(self, Self::PerOrientation)
121    }
122}
123
124/// Direct input for evaluating an integrand at explicit spatial loop momenta.
125///
126/// `loop_momenta` contains one `(px, py, pz)` value per independent loop momentum;
127/// energies are reconstructed by the integrand and external momenta come from its
128/// kinematics settings. The selected graph or graph group determines the required
129/// loop count and evaluation rejects a different number of entries.
130#[derive(Debug, Clone)]
131pub struct MomentumSpaceEvaluationInput {
132    /// Spatial loop momenta in loop-basis order.
133    pub loop_momenta: Vec<ThreeMomentum<F<f64>>>,
134    /// Multiplicative integration weight associated with this explicit point.
135    pub integrator_weight: F<f64>,
136    /// Optional graph selected within a non-discrete sampling setup.
137    pub graph_id: Option<usize>,
138    /// Optional graph group selected within a discrete sampling setup.
139    pub group_id: Option<GroupId>,
140    /// Optional orientation within the selected graph or graph group.
141    pub orientation: Option<usize>,
142    /// Optional canonical sampling channel selected by discrete sampling.
143    pub channel_id: Option<SamplingChannelId>,
144}
145
146#[derive(Clone, Encode, Decode)]
147#[trait_decode(trait = GammaLoopContext)]
148#[enum_dispatch(HasIntegrand)]
149pub enum ProcessIntegrand {
150    Amplitude(amplitude::AmplitudeIntegrand),
151    CrossSection(cross_section::CrossSectionIntegrand),
152}
153
154fn discrete_sampling_type_name(sampling_type: &DiscreteGraphSamplingType) -> &'static str {
155    match sampling_type {
156        DiscreteGraphSamplingType::Default(_) => "default",
157        DiscreteGraphSamplingType::MultiChanneling(_) => "multi_channeling",
158        DiscreteGraphSamplingType::TropicalSampling(_) => "tropical",
159        DiscreteGraphSamplingType::SamplingMultiChanneling(_) => "sampling_multi_channeling",
160    }
161}
162
163pub(crate) fn discrete_sampling_depth_for_settings(
164    settings: &DiscreteGraphSamplingSettings,
165) -> usize {
166    let orientation_depth = usize::from(settings.sample_orientations);
167    match &settings.sampling_type {
168        DiscreteGraphSamplingType::SamplingMultiChanneling(_) => 2 + orientation_depth,
169        _ => 1 + orientation_depth,
170    }
171}
172
173fn invalid_discrete_sampling_depth_error(
174    settings: &DiscreteGraphSamplingSettings,
175    actual_depth: usize,
176) -> eyre::Report {
177    let mut axes = vec!["graph group"];
178    if settings.sample_orientations {
179        axes.push("orientation");
180    }
181    if matches!(
182        settings.sampling_type,
183        DiscreteGraphSamplingType::SamplingMultiChanneling(_)
184    ) {
185        axes.push("channel");
186    }
187
188    eyre!(
189        "This integrand uses discrete graph sampling (sample_orientations = {}, sampling_type = {}), so x-space evaluation requires {} discrete dimensions [{}], but got {}.",
190        settings.sample_orientations,
191        discrete_sampling_type_name(&settings.sampling_type),
192        axes.len(),
193        axes.join(", "),
194        actual_depth
195    )
196}
197
198pub(crate) fn resolve_discrete_selection_for_sampling(
199    sampling: &SamplingSettings,
200    discrete_dimensions: &[usize],
201    group_count: usize,
202    mut orientation_count_for_group: impl FnMut(GroupId) -> Option<usize>,
203    mut channel_count_for_group: impl FnMut(GroupId) -> Result<Option<usize>>,
204) -> Result<(Option<GroupId>, Option<usize>, Option<SamplingChannelId>)> {
205    match sampling {
206        SamplingSettings::Default(_) | SamplingSettings::MultiChanneling(_) => {
207            if !discrete_dimensions.is_empty() {
208                return Err(eyre!(
209                    "This integrand does not use discrete graph sampling; expected no discrete dimensions, got {:?}.",
210                    discrete_dimensions
211                ));
212            }
213            Ok((None, None, None))
214        }
215        SamplingSettings::DiscreteGraphs(settings) => {
216            let expected_depth = discrete_sampling_depth_for_settings(settings);
217            if discrete_dimensions.len() != expected_depth {
218                return Err(invalid_discrete_sampling_depth_error(
219                    settings,
220                    discrete_dimensions.len(),
221                ));
222            }
223
224            let group_id = GroupId(discrete_dimensions[0]);
225            if group_id.0 >= group_count {
226                return Err(eyre!(
227                    "Discrete graph group index {} is out of range; the integrand has {} groups.",
228                    group_id.0,
229                    group_count
230                ));
231            }
232
233            let orientation = if settings.sample_orientations {
234                let orientation = discrete_dimensions[1];
235                let orientation_count = orientation_count_for_group(group_id).ok_or_else(|| {
236                    eyre!(
237                        "Could not determine orientation count for group {}.",
238                        group_id.0
239                    )
240                })?;
241                if orientation >= orientation_count {
242                    return Err(eyre!(
243                        "Orientation {} is out of range for graph group {}; the group has {} orientations.",
244                        orientation,
245                        group_id.0,
246                        orientation_count
247                    ));
248                }
249                Some(orientation)
250            } else {
251                None
252            };
253
254            let channel = match &settings.sampling_type {
255                DiscreteGraphSamplingType::SamplingMultiChanneling(_) => {
256                    let channel_index = *discrete_dimensions.last().expect("validated depth");
257                    let channel_count = channel_count_for_group(group_id)?.ok_or_else(|| {
258                        eyre!(
259                            "Could not determine channel count for group {}.",
260                            group_id.0
261                        )
262                    })?;
263                    if channel_index >= channel_count {
264                        return Err(eyre!(
265                            "Channel {} is out of range for graph group {}; the group has {} channels.",
266                            channel_index,
267                            group_id.0,
268                            channel_count
269                        ));
270                    }
271                    Some(SamplingChannelId::from(channel_index))
272                }
273                _ => None,
274            };
275
276            Ok((Some(group_id), orientation, channel))
277        }
278    }
279}
280
281impl ProcessIntegrand {
282    pub fn generated_representations(&self) -> &[RepresentationMode] {
283        match self {
284            Self::Amplitude(integrand) => integrand.generated_representations(),
285            Self::CrossSection(integrand) => integrand.generated_representations(),
286        }
287    }
288
289    pub fn clone_with_selected_graph_groups(
290        &self,
291        model: &Model,
292        graph_names: &[String],
293    ) -> Result<Self> {
294        if graph_names.is_empty() {
295            return Ok(self.clone());
296        }
297        if !matches!(
298            self.get_settings().sampling,
299            SamplingSettings::DiscreteGraphs(_)
300        ) {
301            return Err(eyre!(
302                "Runtime graph-group selection requires graphs = 'monte_carlo'."
303            ));
304        }
305        let mut unique_names = BTreeSet::new();
306        for graph_name in graph_names {
307            if !unique_names.insert(graph_name) {
308                return Err(eyre!(
309                    "Runtime graph-group selection contains duplicate graph name '{}'.",
310                    graph_name
311                ));
312            }
313        }
314
315        let selection = GraphGroupSelectionSpec::from_master_graph_names(graph_names.to_vec());
316        let mut selected = match self {
317            Self::Amplitude(integrand) => {
318                let plan =
319                    selection.plan(model, &integrand.data.graph_group_structure, |graph_id| {
320                        integrand
321                            .data
322                            .graph_terms
323                            .get(graph_id)
324                            .map(|term| &term.graph)
325                    })?;
326                Self::Amplitude(integrand.clone_with_graph_group_selection(&plan)?)
327            }
328            Self::CrossSection(integrand) => {
329                let plan =
330                    selection.plan(model, &integrand.data.graph_group_structure, |graph_id| {
331                        integrand
332                            .data
333                            .graph_terms
334                            .get(graph_id)
335                            .map(|term| &term.graph)
336                    })?;
337                Self::CrossSection(integrand.clone_with_graph_group_selection(&plan)?)
338            }
339        };
340        let selected_names = selected
341            .graph_group_master_names()
342            .into_iter()
343            .map(str::to_string)
344            .collect();
345        let SamplingSettings::DiscreteGraphs(sampling) = &mut selected.get_mut_settings().sampling
346        else {
347            unreachable!("validated graph sampling before constructing the selected view")
348        };
349        sampling.graph_names = selected_names;
350        Ok(selected)
351    }
352
353    /// Every graph this integrand holds: each term's graph and the graph of
354    /// its LMB multi-channeling setup.
355    pub fn graphs(&self) -> Vec<&Graph> {
356        match self {
357            Self::Amplitude(integrand) => integrand
358                .data
359                .graph_terms
360                .iter()
361                .flat_map(|term| [&term.graph, &term.multi_channeling_setup.graph])
362                .collect(),
363            Self::CrossSection(integrand) => integrand
364                .data
365                .graph_terms
366                .iter()
367                .flat_map(|term| [&term.graph, &term.multi_channeling_setup.graph])
368                .collect(),
369        }
370    }
371
372    /// Rebind every held graph to `model` (validated by the caller) and drop
373    /// the runtime caches built from the previous model, so the next warm-up
374    /// rebuilds them from the current parameter card and settings overlay.
375    pub fn rebind_model(&mut self, model: &Arc<Model>) {
376        match self {
377            Self::Amplitude(integrand) => {
378                integrand.invalidate_runtime_caches();
379                for term in &mut integrand.data.graph_terms {
380                    term.graph.rebind_model(model);
381                    term.multi_channeling_setup.rebind_model(model);
382                    // Rebuilt from the terms' graphs by the next warm-up.
383                    term.threshold_counterterm.group_catalogue.invalidate();
384                }
385            }
386            Self::CrossSection(integrand) => {
387                integrand.invalidate_runtime_caches();
388                for term in &mut integrand.data.graph_terms {
389                    term.graph.rebind_model(model);
390                    term.multi_channeling_setup.rebind_model(model);
391                }
392            }
393        }
394    }
395
396    pub fn resume_fingerprint(&self) -> Result<String> {
397        let mut bytes = match self {
398            Self::Amplitude(integrand) => {
399                bincode::encode_to_vec(&integrand.data, bincode::config::standard())
400            }
401            Self::CrossSection(integrand) => {
402                bincode::encode_to_vec(&integrand.data, bincode::config::standard())
403            }
404        }
405        .map_err(|err| eyre!("Could not serialize integrand fingerprint payload: {err}"))?;
406
407        let mut hash = 0xcbf29ce484222325u64;
408        for byte in self
409            .variant_tag()
410            .as_bytes()
411            .iter()
412            .copied()
413            .chain(bytes.drain(..))
414        {
415            hash ^= u64::from(byte);
416            hash = hash.wrapping_mul(0x100000001b3);
417        }
418
419        Ok(format!("{hash:016x}"))
420    }
421
422    fn variant_tag(&self) -> &'static str {
423        match self {
424            Self::Amplitude(_) => "amplitude",
425            Self::CrossSection(_) => "cross_section",
426        }
427    }
428
429    pub fn kind_name(&self) -> &'static str {
430        self.variant_tag()
431    }
432
433    pub fn export_standalone(
434        &self,
435        path: impl AsRef<Path>,
436        settings: &StandaloneExportSettings,
437    ) -> Result<()> {
438        match self {
439            Self::Amplitude(a) => a.export_standalone(path, settings),
440            Self::CrossSection(a) => a.export_standalone(path, settings),
441        }
442    }
443
444    pub fn warm_up(&mut self, model: &Model) -> Result<()> {
445        let settings = self.get_mut_settings();
446        if matches!(
447            &settings.sampling,
448            SamplingSettings::DiscreteGraphs(settings) if settings.sample_orientations
449        ) {
450            if !matches!(
451                settings.general.evaluator_method,
452                evaluators::EvaluatorMethod::SingleParametric
453            ) {
454                return Err(eyre!(
455                    "Monte Carlo sampling over orientations requires general.evaluator_method=SingleParametric; got {:?}.",
456                    settings.general.evaluator_method
457                ));
458            }
459            warn!("Monte Carlo sampling over orientations is using the SingleParametric evaluator");
460        }
461
462        match self {
463            Self::Amplitude(a) => a.warm_up(model),
464            Self::CrossSection(a) => a.warm_up(model),
465        }
466    }
467
468    pub fn frozen_compilation(&self) -> &crate::settings::global::FrozenCompilationMode {
469        match self {
470            Self::Amplitude(a) => a.frozen_compilation(),
471            Self::CrossSection(a) => a.frozen_compilation(),
472        }
473    }
474
475    pub fn active_f64_backend(&self) -> ActiveF64Backend {
476        match self {
477            Self::Amplitude(a) => a.active_f64_backend(),
478            Self::CrossSection(a) => a.active_f64_backend(),
479        }
480    }
481
482    pub(crate) fn activate_runtime_backends_after_load(
483        &mut self,
484        allow_symjit_fallback: bool,
485    ) -> Result<Option<String>> {
486        match self {
487            Self::Amplitude(a) => a.activate_runtime_backends_after_load(allow_symjit_fallback),
488            Self::CrossSection(a) => a.activate_runtime_backends_after_load(allow_symjit_fallback),
489        }
490    }
491
492    pub(crate) fn save(&self, path: impl AsRef<Path>, override_existing: bool) -> Result<()> {
493        let path = path.as_ref().join("integrand");
494
495        let r = fs::create_dir_all(&path).with_context(|| {
496            format!(
497                "Trying to create directory to save amplitude {}",
498                path.display()
499            )
500        });
501        if override_existing {
502            r?;
503        }
504        match self {
505            ProcessIntegrand::Amplitude(integrand) => integrand.save(path, override_existing),
506            ProcessIntegrand::CrossSection(integrand) => integrand.save(path, override_existing),
507        }
508    }
509
510    pub(crate) fn compile(
511        &mut self,
512        path: impl AsRef<Path>,
513        override_existing: bool,
514        thread_pool: &rayon::ThreadPool,
515    ) -> Result<Vec<(String, GraphGenerationStats)>> {
516        let path = path.as_ref().join("integrand");
517
518        let r = fs::create_dir_all(&path).with_context(|| {
519            format!(
520                "Trying to create directory to save amplitude {}",
521                path.display()
522            )
523        });
524        if override_existing {
525            r?;
526        }
527        match self {
528            ProcessIntegrand::Amplitude(integrand) => {
529                integrand.compile(path, override_existing, thread_pool)
530            }
531            ProcessIntegrand::CrossSection(integrand) => {
532                integrand.compile(path, override_existing, thread_pool)
533            }
534        }
535    }
536
537    pub fn get_settings(&self) -> &RuntimeSettings {
538        match self {
539            ProcessIntegrand::Amplitude(integrand) => &integrand.settings,
540            ProcessIntegrand::CrossSection(integrand) => &integrand.settings,
541        }
542    }
543
544    /// Invalidate runtime caches before exposing mutable settings. Call
545    /// `warm_up` again before evaluating samples through sampling channels.
546    pub fn get_mut_settings(&mut self) -> &mut RuntimeSettings {
547        match self {
548            ProcessIntegrand::Amplitude(integrand) => {
549                integrand.invalidate_runtime_caches();
550                &mut integrand.settings
551            }
552            ProcessIntegrand::CrossSection(integrand) => {
553                integrand.invalidate_runtime_caches();
554                &mut integrand.settings
555            }
556        }
557    }
558
559    pub fn graph_count(&self) -> usize {
560        match self {
561            ProcessIntegrand::Amplitude(integrand) => integrand.data.graph_terms.len(),
562            ProcessIntegrand::CrossSection(integrand) => integrand.data.graph_terms.len(),
563        }
564    }
565
566    pub fn graph_group_count(&self) -> usize {
567        match self {
568            ProcessIntegrand::Amplitude(integrand) => integrand.data.graph_group_structure.len(),
569            ProcessIntegrand::CrossSection(integrand) => integrand.data.graph_group_structure.len(),
570        }
571    }
572
573    pub fn graph_group_master_names(&self) -> Vec<&str> {
574        match self {
575            ProcessIntegrand::Amplitude(integrand) => integrand
576                .data
577                .graph_group_structure
578                .iter()
579                .map(|group| {
580                    integrand.data.graph_terms[group.master()]
581                        .graph
582                        .name
583                        .as_str()
584                })
585                .collect(),
586            ProcessIntegrand::CrossSection(integrand) => integrand
587                .data
588                .graph_group_structure
589                .iter()
590                .map(|group| {
591                    integrand.data.graph_terms[group.master()]
592                        .graph
593                        .name
594                        .as_str()
595                })
596                .collect(),
597        }
598    }
599
600    pub fn find_graph_id_by_name(&self, graph_name: &str) -> Option<usize> {
601        match self {
602            ProcessIntegrand::Amplitude(integrand) => integrand
603                .data
604                .graph_terms
605                .iter()
606                .position(|term| term.graph.name == graph_name),
607            ProcessIntegrand::CrossSection(integrand) => integrand
608                .data
609                .graph_terms
610                .iter()
611                .position(|term| term.graph.name == graph_name),
612        }
613    }
614
615    pub fn graph_name_by_id(&self, graph_id: usize) -> Option<&str> {
616        match self {
617            ProcessIntegrand::Amplitude(integrand) => integrand
618                .data
619                .graph_terms
620                .get(graph_id)
621                .map(|term| term.graph.name.as_str()),
622            ProcessIntegrand::CrossSection(integrand) => integrand
623                .data
624                .graph_terms
625                .get(graph_id)
626                .map(|term| term.graph.name.as_str()),
627        }
628    }
629
630    pub fn graph_group_id_by_graph_id(&self, graph_id: usize) -> Option<usize> {
631        self.find_group_id_containing_graph(graph_id)
632            .map(usize::from)
633    }
634
635    pub fn cut_edge_ids(&self, graph_id: usize, cut_id: usize) -> Option<Vec<usize>> {
636        match self {
637            ProcessIntegrand::Amplitude(integrand) => {
638                (cut_id == 0 && graph_id < integrand.data.graph_terms.len()).then(Vec::new)
639            }
640            ProcessIntegrand::CrossSection(integrand) => {
641                let graph_term = integrand.data.graph_terms.get(graph_id)?;
642                let cut = graph_term.cuts.get(crate::processes::CutId::from(cut_id))?;
643                Some(
644                    graph_term
645                        .graph
646                        .underlying
647                        .iter_edges_of(&cut.cut)
648                        .map(|(_, edge_id, _)| edge_id.0)
649                        .sorted()
650                        .collect(),
651                )
652            }
653        }
654    }
655
656    pub fn lmb_sample_id_for_channel(
657        &self,
658        graph_id: usize,
659        sampling_channel_id: usize,
660        parameterization_settings: &ParameterizationSettings,
661    ) -> Result<Option<usize>> {
662        match self {
663            ProcessIntegrand::Amplitude(integrand) => {
664                let Some(graph_term) = integrand.data.graph_terms.get(graph_id) else {
665                    return Ok(None);
666                };
667                Ok(graph_term
668                    .multi_channeling_setup
669                    .sampling_channel_lmb_id(
670                        SamplingChannelId::from(sampling_channel_id),
671                        &graph_term.multi_channeling_setup.graph.name,
672                        parameterization_settings,
673                    )?
674                    .map(usize::from))
675            }
676            ProcessIntegrand::CrossSection(integrand) => {
677                let Some(graph_term) = integrand.data.graph_terms.get(graph_id) else {
678                    return Ok(None);
679                };
680                Ok(graph_term
681                    .multi_channeling_setup
682                    .sampling_channel_lmb_id(
683                        SamplingChannelId::from(sampling_channel_id),
684                        &graph_term.multi_channeling_setup.graph.name,
685                        parameterization_settings,
686                    )?
687                    .map(usize::from))
688            }
689        }
690    }
691
692    fn find_group_id_containing_graph(&self, graph_id: usize) -> Option<GroupId> {
693        match self {
694            ProcessIntegrand::Amplitude(integrand) => integrand
695                .data
696                .graph_group_structure
697                .iter_enumerated()
698                .find_map(|(group_id, group)| {
699                    group.into_iter().contains(&graph_id).then_some(group_id)
700                }),
701            ProcessIntegrand::CrossSection(integrand) => integrand
702                .data
703                .graph_group_structure
704                .iter_enumerated()
705                .find_map(|(group_id, group)| {
706                    group.into_iter().contains(&graph_id).then_some(group_id)
707                }),
708        }
709    }
710
711    pub fn resolve_group_id_by_master_name(&self, graph_name: &str) -> Result<GroupId> {
712        match self.find_graph_id_by_name(graph_name) {
713            Some(graph_id) => {
714                let group_id = self
715                    .find_group_id_containing_graph(graph_id)
716                    .ok_or_else(|| {
717                        eyre!("Could not find graph group for graph '{}'.", graph_name)
718                    })?;
719                let master_graph_name = match self {
720                    ProcessIntegrand::Amplitude(integrand) => {
721                        &integrand.data.graph_terms
722                            [integrand.data.graph_group_structure[group_id].master()]
723                        .graph
724                        .name
725                    }
726                    ProcessIntegrand::CrossSection(integrand) => {
727                        &integrand.data.graph_terms
728                            [integrand.data.graph_group_structure[group_id].master()]
729                        .graph
730                        .name
731                    }
732                };
733                if master_graph_name != graph_name {
734                    return Err(eyre!(
735                        "Graph '{}' is not the master graph of its group; use '{}' instead.",
736                        graph_name,
737                        master_graph_name
738                    ));
739                }
740                Ok(group_id)
741            }
742            None => Err(eyre!(
743                "Unknown graph '{}' in momentum-space evaluation.",
744                graph_name
745            )),
746        }
747    }
748
749    pub fn resolve_discrete_selection(
750        &self,
751        discrete_dimensions: &[usize],
752    ) -> Result<(Option<GroupId>, Option<usize>, Option<SamplingChannelId>)> {
753        let group_count = match self {
754            ProcessIntegrand::Amplitude(integrand) => integrand.data.graph_group_structure.len(),
755            ProcessIntegrand::CrossSection(integrand) => integrand.data.graph_group_structure.len(),
756        };
757
758        resolve_discrete_selection_for_sampling(
759            &self.get_settings().sampling,
760            discrete_dimensions,
761            group_count,
762            |group_id| self.group_orientation_count(group_id),
763            |group_id| Ok(self.group_channel_count(group_id)),
764        )
765    }
766
767    pub fn expected_x_space_dimension(&self, discrete_dimensions: &[usize]) -> Result<usize> {
768        let settings = self.get_settings();
769        let (group_id, _, _) = self.resolve_discrete_selection(discrete_dimensions)?;
770        if matches!(
771            &settings.sampling,
772            SamplingSettings::DiscreteGraphs(DiscreteGraphSamplingSettings {
773                sampling_type: DiscreteGraphSamplingType::TropicalSampling(_),
774                ..
775            })
776        ) {
777            let group_id = group_id.ok_or_else(|| {
778                eyre!("Tropical sampling requires a discrete graph-group selection.")
779            })?;
780            let (loop_number, n_edges) = match self {
781                ProcessIntegrand::Amplitude(integrand) => {
782                    let master_graph = &integrand.data.graph_terms
783                        [integrand.data.graph_group_structure[group_id].master()];
784                    (
785                        master_graph.get_graph().get_loop_number(),
786                        master_graph.get_graph().iter_loop_edges().count(),
787                    )
788                }
789                ProcessIntegrand::CrossSection(integrand) => {
790                    let master_graph = &integrand.data.graph_terms
791                        [integrand.data.graph_group_structure[group_id].master()];
792                    (
793                        master_graph.get_graph().get_loop_number(),
794                        master_graph.get_graph().iter_loop_edges().count(),
795                    )
796                }
797            };
798            return Ok(get_n_dim_for_n_loop_momenta(
799                &settings.sampling,
800                loop_number,
801                Some(n_edges),
802            ));
803        }
804
805        let loop_number = match self {
806            ProcessIntegrand::Amplitude(integrand) => {
807                integrand.data.graph_terms[0].graph.get_loop_number()
808            }
809            ProcessIntegrand::CrossSection(integrand) => {
810                integrand.data.graph_terms[0].graph.get_loop_number()
811            }
812        };
813        Ok(get_n_dim_for_n_loop_momenta(
814            &settings.sampling,
815            loop_number,
816            None,
817        ))
818    }
819
820    pub fn discrete_sampling_depth(&self) -> usize {
821        match &self.get_settings().sampling {
822            SamplingSettings::Default(_) | SamplingSettings::MultiChanneling(_) => 0,
823            SamplingSettings::DiscreteGraphs(settings) => {
824                discrete_sampling_depth_for_settings(settings)
825            }
826        }
827    }
828
829    pub fn group_orientation_count(&self, group_id: GroupId) -> Option<usize> {
830        match self {
831            ProcessIntegrand::Amplitude(integrand) => Some(
832                integrand.data.graph_terms[integrand.data.graph_group_structure[group_id].master()]
833                    .get_num_orientations(),
834            ),
835            ProcessIntegrand::CrossSection(integrand) => Some(
836                integrand.data.graph_terms[integrand.data.graph_group_structure[group_id].master()]
837                    .get_num_orientations(),
838            ),
839        }
840    }
841
842    /// Return the canonical sampling-channel IDs for a graph group.
843    ///
844    /// The IDs come directly from the master graph's single catalogue. This
845    /// helper is intended for saved-state acceptance callers constructing
846    /// explicit `(group, orientation, channel)` selections; callers must pass
847    /// the same parameterization settings used by the loaded state.
848    pub fn group_sampling_channel_ids(
849        &self,
850        group_id: GroupId,
851        parameterization_settings: &ParameterizationSettings,
852    ) -> Result<Vec<SamplingChannelId>> {
853        let group = match self {
854            ProcessIntegrand::Amplitude(integrand) => {
855                integrand.data.graph_group_structure.get(group_id)
856            }
857            ProcessIntegrand::CrossSection(integrand) => {
858                integrand.data.graph_group_structure.get(group_id)
859            }
860        }
861        .ok_or_else(|| eyre!("Unknown graph group {}.", group_id.0))?;
862        let master = group.master();
863        match self {
864            ProcessIntegrand::Amplitude(integrand) => {
865                integrand.data.graph_terms[master].sampling_channel_ids(parameterization_settings)
866            }
867            ProcessIntegrand::CrossSection(integrand) => {
868                integrand.data.graph_terms[master].sampling_channel_ids(parameterization_settings)
869            }
870        }
871    }
872
873    pub fn group_channel_count(&self, group_id: GroupId) -> Option<usize> {
874        let parameterization_settings = self
875            .get_settings()
876            .sampling
877            .get_parameterization_settings()
878            .unwrap_or_default();
879        self.group_sampling_channel_ids(group_id, &parameterization_settings)
880            .ok()
881            .map(|channel_ids| channel_ids.len())
882    }
883
884    pub fn graph_orientation_count(&self, graph_id: usize) -> Option<usize> {
885        match self {
886            ProcessIntegrand::Amplitude(integrand) => integrand
887                .data
888                .graph_terms
889                .get(graph_id)
890                .map(|term| term.get_num_orientations()),
891            ProcessIntegrand::CrossSection(integrand) => integrand
892                .data
893                .graph_terms
894                .get(graph_id)
895                .map(|term| term.get_num_orientations()),
896        }
897    }
898
899    pub fn evaluate_momentum_configuration(
900        &mut self,
901        model: &Model,
902        input: &MomentumSpaceEvaluationInput,
903        use_arb_prec: bool,
904    ) -> Result<EvaluationResult> {
905        match self {
906            ProcessIntegrand::Amplitude(integrand) => evaluate_momentum_configuration(
907                integrand,
908                model,
909                input,
910                input.integrator_weight,
911                use_arb_prec,
912                Complex::new_zero(),
913            ),
914            ProcessIntegrand::CrossSection(integrand) => evaluate_momentum_configuration(
915                integrand,
916                model,
917                input,
918                input.integrator_weight,
919                use_arb_prec,
920                Complex::new_zero(),
921            ),
922        }
923    }
924
925    pub fn evaluate_sample_precise(
926        &mut self,
927        sample: &Sample<F<f64>>,
928        model: &Model,
929        wgt: F<f64>,
930        use_arb_prec: bool,
931        max_eval: Complex<F<f64>>,
932    ) -> Result<PreciseEvaluationResult> {
933        match self {
934            ProcessIntegrand::Amplitude(integrand) => {
935                evaluate_sample_precise(integrand, model, sample, wgt, use_arb_prec, max_eval)
936            }
937            ProcessIntegrand::CrossSection(integrand) => {
938                evaluate_sample_precise(integrand, model, sample, wgt, use_arb_prec, max_eval)
939            }
940        }
941    }
942
943    /// Evaluate a normalized reference function through the real process
944    /// parameterization, retaining its Jacobian and integrator weight.
945    ///
946    /// This is intentionally a test-only style overlay: graph routing,
947    /// orientation/channel selection and all sampling maps are still exercised,
948    /// while the physical graph evaluation is replaced by `reference`.
949    pub fn evaluate_reference_sample(
950        &mut self,
951        sample: &Sample<F<f64>>,
952        reference: &GaussianReferenceFunction,
953    ) -> Result<EvaluationResult> {
954        match self {
955            ProcessIntegrand::Amplitude(integrand) => {
956                Ok(evaluate_reference_sample(integrand, sample, reference)?.evaluation)
957            }
958            ProcessIntegrand::CrossSection(integrand) => {
959                Ok(evaluate_reference_sample(integrand, sample, reference)?.evaluation)
960            }
961        }
962    }
963
964    /// Evaluate a normalized reference function from unit-cube coordinates.
965    ///
966    /// This convenience entry point is intended for saved-state acceptance
967    /// harnesses: callers can load a process normally, generate deterministic
968    /// coordinates (for example Halton points), and exercise the complete
969    /// process parameterization without constructing Symbolica `Sample`
970    /// values themselves. The coordinate batch is interpreted as an equally
971    /// weighted quadrature rule, so each sample has unit inverse-density weight
972    /// and the report averages once over the `N` draws; the
973    /// canonical sampling channel selected by
974    /// the loaded settings remains responsible for its map and Jacobian.
975    pub fn evaluate_reference_coordinates(
976        &mut self,
977        coordinates: &[Vec<f64>],
978        reference: &GaussianReferenceFunction,
979    ) -> Result<ReferenceSamplingReport> {
980        if coordinates.is_empty() {
981            return Err(eyre!(
982                "reference acceptance coordinate batch needs at least one sample"
983            ));
984        }
985        let samples = coordinates
986            .iter()
987            .enumerate()
988            .map(|(sample_index, coordinate)| {
989                if coordinate.iter().any(|value| !value.is_finite()) {
990                    return Err(eyre!(
991                        "reference acceptance sample {sample_index} contains a non-finite coordinate"
992                    ));
993                }
994                Ok(Sample::Continuous(
995                    F(1.0),
996                    coordinate.iter().copied().map(F).collect(),
997                ))
998            })
999            .collect::<Result<Vec<_>>>()?;
1000        self.evaluate_reference_samples(&samples, reference)
1001    }
1002
1003    /// Evaluate deterministic coordinates under one explicit discrete
1004    /// selection path. `discrete_indices` is ordered from the outermost
1005    /// `Sample::Discrete` selector to the innermost one, matching the
1006    /// canonical graph/orientation/channel order used by the process sampler.
1007    /// The selection itself is never re-enumerated or filtered here; callers
1008    /// must supply IDs obtained from the loaded process' canonical catalogue.
1009    /// Unit discrete weights make this a partition contribution, which need
1010    /// not integrate to one. A complete acceptance estimator must sum the
1011    /// per-draw contributions or use MC samples with reciprocal selection
1012    /// probabilities. Do not add report errors for channels sharing the same
1013    /// coordinates: their contributions must be combined before squaring.
1014    pub fn evaluate_reference_discrete_coordinates(
1015        &mut self,
1016        discrete_indices: &[usize],
1017        coordinates: &[Vec<f64>],
1018        reference: &GaussianReferenceFunction,
1019    ) -> Result<ReferenceSamplingReport> {
1020        if coordinates.is_empty() {
1021            return Err(eyre!(
1022                "reference acceptance coordinate batch needs at least one sample"
1023            ));
1024        }
1025        let samples = coordinates
1026            .iter()
1027            .enumerate()
1028            .map(|(sample_index, coordinate)| {
1029                if coordinate.iter().any(|value| !value.is_finite()) {
1030                    return Err(eyre!(
1031                        "reference acceptance sample {sample_index} contains a non-finite coordinate"
1032                    ));
1033                }
1034                let mut sample = Sample::Continuous(
1035                    F(1.0),
1036                    coordinate.iter().copied().map(F).collect(),
1037                );
1038                for index in discrete_indices.iter().rev() {
1039                    sample = Sample::Discrete(F(1.0), *index, Some(Box::new(sample)));
1040                }
1041                Ok(sample)
1042            })
1043            .collect::<Result<Vec<_>>>()?;
1044        self.evaluate_reference_samples(&samples, reference)
1045    }
1046
1047    /// Evaluate a batch of samples with a normalized reference function while
1048    /// retaining the process maps, Jacobians and sampling-grid weights.
1049    pub fn evaluate_reference_samples(
1050        &mut self,
1051        samples: &[Sample<F<f64>>],
1052        reference: &GaussianReferenceFunction,
1053    ) -> Result<ReferenceSamplingReport> {
1054        if samples.is_empty() {
1055            return Err(eyre!("reference acceptance needs at least one sample"));
1056        }
1057        let evaluations = samples
1058            .iter()
1059            .map(|sample| self.evaluate_reference_sample_detailed(sample, reference))
1060            .collect::<Result<Vec<_>>>()?;
1061        let report = ReferenceSamplingReport::from_evaluations(evaluations, reference);
1062        if report.finite_sample_count != report.sample_count
1063            || !report.normalization.is_finite()
1064            || !report.normalization_stderr.is_finite()
1065            || !report.second_moment.is_finite()
1066            || !report.second_moment_stderr.is_finite()
1067        {
1068            return Err(eyre!(
1069                "reference acceptance has invalid mapped contributions or statistics: {} finite draws out of {}",
1070                report.finite_sample_count,
1071                report.sample_count
1072            ));
1073        }
1074        Ok(report)
1075    }
1076
1077    /// Detailed variant used by acceptance harnesses that also check raw
1078    /// momentum moments.  The public scalar method above remains convenient
1079    /// for callers interested only in the mapped value.
1080    pub fn evaluate_reference_sample_detailed(
1081        &mut self,
1082        sample: &Sample<F<f64>>,
1083        reference: &GaussianReferenceFunction,
1084    ) -> Result<ReferenceSampleEvaluation> {
1085        match self {
1086            ProcessIntegrand::Amplitude(integrand) => {
1087                evaluate_reference_sample(integrand, sample, reference)
1088            }
1089            ProcessIntegrand::CrossSection(integrand) => {
1090                evaluate_reference_sample(integrand, sample, reference)
1091            }
1092        }
1093    }
1094
1095    pub fn evaluate_momentum_configuration_precise(
1096        &mut self,
1097        model: &Model,
1098        input: &MomentumSpaceEvaluationInput,
1099        use_arb_prec: bool,
1100    ) -> Result<PreciseEvaluationResult> {
1101        match self {
1102            ProcessIntegrand::Amplitude(integrand) => evaluate_momentum_configuration_precise(
1103                integrand,
1104                model,
1105                input,
1106                input.integrator_weight,
1107                use_arb_prec,
1108                Complex::new_zero(),
1109            ),
1110            ProcessIntegrand::CrossSection(integrand) => evaluate_momentum_configuration_precise(
1111                integrand,
1112                model,
1113                input,
1114                input.integrator_weight,
1115                use_arb_prec,
1116                Complex::new_zero(),
1117            ),
1118        }
1119    }
1120
1121    pub fn evaluate_samples_raw(
1122        &mut self,
1123        target: EvaluationTarget<'_>,
1124        samples: &[Sample<F<f64>>],
1125        _iter: usize,
1126        use_arb_prec: bool,
1127        stop_on_interrupt: bool,
1128        max_eval: Complex<F<f64>>,
1129    ) -> Result<RawBatchEvaluationResult> {
1130        self.evaluate_samples_raw_with_estimate(
1131            target,
1132            samples,
1133            _iter,
1134            use_arb_prec,
1135            stop_on_interrupt,
1136            max_eval,
1137            None,
1138        )
1139    }
1140
1141    #[allow(clippy::too_many_arguments)]
1142    pub fn evaluate_samples_raw_with_estimate(
1143        &mut self,
1144        target: EvaluationTarget<'_>,
1145        samples: &[Sample<F<f64>>],
1146        _iter: usize,
1147        use_arb_prec: bool,
1148        stop_on_interrupt: bool,
1149        max_eval: Complex<F<f64>>,
1150        integral_estimate: Option<(f64, f64)>,
1151    ) -> Result<RawBatchEvaluationResult> {
1152        let mut results = Vec::with_capacity(samples.len());
1153        for sample in samples {
1154            if stop_on_interrupt && crate::is_interrupted() {
1155                break;
1156            }
1157            macro_rules! evaluate {
1158                ($integrand:expr) => {
1159                    evaluate_from_source_precise_with_estimate(
1160                        $integrand,
1161                        target,
1162                        EvaluationSource::XSpace(sample),
1163                        sample.get_weight(),
1164                        use_arb_prec,
1165                        max_eval,
1166                        integral_estimate,
1167                        None,
1168                    )
1169                };
1170            }
1171            let precise = match self {
1172                ProcessIntegrand::Amplitude(integrand) => evaluate!(integrand),
1173                ProcessIntegrand::CrossSection(integrand) => evaluate!(integrand),
1174            }?;
1175            let result = match target {
1176                EvaluationTarget::Reference(reference) => reference.integration_report(precise)?,
1177                EvaluationTarget::Physical(_) => precise.try_into_f64()?,
1178                #[cfg(test)]
1179                EvaluationTarget::SamplingLaw(_) => precise.try_into_f64()?,
1180            };
1181
1182            results.push(result);
1183            if stop_on_interrupt && crate::is_interrupted() {
1184                break;
1185            }
1186        }
1187
1188        Ok(RawBatchEvaluationResult {
1189            statistics: StatisticsCounter::from_evaluation_results(&results),
1190            samples: results,
1191        })
1192    }
1193
1194    pub fn evaluate_momentum_configurations_raw(
1195        &mut self,
1196        model: &Model,
1197        inputs: &[MomentumSpaceEvaluationInput],
1198        use_arb_prec: bool,
1199    ) -> Result<RawBatchEvaluationResult> {
1200        let mut results = Vec::with_capacity(inputs.len());
1201        for input in inputs {
1202            let result = match self {
1203                ProcessIntegrand::Amplitude(integrand) => evaluate_momentum_configuration(
1204                    integrand,
1205                    model,
1206                    input,
1207                    input.integrator_weight,
1208                    use_arb_prec,
1209                    Complex::new_zero(),
1210                ),
1211                ProcessIntegrand::CrossSection(integrand) => evaluate_momentum_configuration(
1212                    integrand,
1213                    model,
1214                    input,
1215                    input.integrator_weight,
1216                    use_arb_prec,
1217                    Complex::new_zero(),
1218                ),
1219            }?;
1220
1221            results.push(result);
1222        }
1223
1224        Ok(RawBatchEvaluationResult {
1225            statistics: StatisticsCounter::from_evaluation_results(&results),
1226            samples: results,
1227        })
1228    }
1229
1230    pub fn evaluate_samples_precise_raw(
1231        &mut self,
1232        model: &Model,
1233        samples: &[Sample<F<f64>>],
1234        use_arb_prec: bool,
1235        max_eval: Complex<F<f64>>,
1236    ) -> Result<RawPreciseBatchEvaluationResult> {
1237        let mut results = Vec::with_capacity(samples.len());
1238        for sample in samples {
1239            results.push(self.evaluate_sample_precise(
1240                sample,
1241                model,
1242                sample.get_weight(),
1243                use_arb_prec,
1244                max_eval,
1245            )?);
1246        }
1247
1248        Ok(RawPreciseBatchEvaluationResult { samples: results })
1249    }
1250
1251    pub fn evaluate_momentum_configurations_precise_raw(
1252        &mut self,
1253        model: &Model,
1254        inputs: &[MomentumSpaceEvaluationInput],
1255        use_arb_prec: bool,
1256    ) -> Result<RawPreciseBatchEvaluationResult> {
1257        let mut results = Vec::with_capacity(inputs.len());
1258        for input in inputs {
1259            results.push(self.evaluate_momentum_configuration_precise(
1260                model,
1261                input,
1262                use_arb_prec,
1263            )?);
1264        }
1265
1266        Ok(RawPreciseBatchEvaluationResult { samples: results })
1267    }
1268
1269    /// Create independent observable statistics using this integrand's compiled definitions.
1270    ///
1271    /// Warm the integrand first. An integrand without observables returns an empty
1272    /// accumulator. This does not copy the integrand or its numerical evaluator.
1273    /// See [`EventProcessingRuntime::accumulate_sample`] for accumulation semantics.
1274    ///
1275    /// # Errors
1276    /// Returns an error if observables are configured but the integrand has not been warmed up.
1277    pub fn new_observable_accumulator(
1278        &self,
1279    ) -> StdResult<EventProcessingRuntime, ObservableAccumulationError> {
1280        let runtime = match self {
1281            Self::Amplitude(integrand) => integrand.event_processing_runtime(),
1282            Self::CrossSection(integrand) => integrand.event_processing_runtime(),
1283        };
1284        match runtime {
1285            Some(runtime) => Ok(runtime.cleared_observable_clone()),
1286            None if self.get_settings().observables.is_empty() => {
1287                Ok(EventProcessingRuntime::default())
1288            }
1289            None => Err(ObservableAccumulationError::NotInitialized),
1290        }
1291    }
1292
1293    pub fn process_evaluation_result(&mut self, result: &EvaluationResult) -> Result<()> {
1294        match self {
1295            ProcessIntegrand::Amplitude(integrand) => {
1296                process_evaluation_result_runtime(integrand, result)
1297            }
1298            ProcessIntegrand::CrossSection(integrand) => {
1299                process_evaluation_result_runtime(integrand, result)
1300            }
1301        }
1302    }
1303
1304    pub fn merge_event_processing_runtime(&mut self, other: &mut Self) -> Result<()> {
1305        match (self, other) {
1306            (ProcessIntegrand::Amplitude(lhs), ProcessIntegrand::Amplitude(rhs)) => {
1307                merge_event_processing_runtime(lhs, rhs)
1308            }
1309            (ProcessIntegrand::CrossSection(lhs), ProcessIntegrand::CrossSection(rhs)) => {
1310                merge_event_processing_runtime(lhs, rhs)
1311            }
1312            _ => Err(eyre!(
1313                "Cannot merge event-processing runtime for incompatible process integrands."
1314            )),
1315        }
1316    }
1317
1318    pub fn update_event_processing_runtime(&mut self, iter: usize) {
1319        match self {
1320            ProcessIntegrand::Amplitude(integrand) => {
1321                update_event_processing_runtime(integrand, iter)
1322            }
1323            ProcessIntegrand::CrossSection(integrand) => {
1324                update_event_processing_runtime(integrand, iter)
1325            }
1326        }
1327    }
1328
1329    pub fn observable_accumulator_bundle(&self) -> Option<ObservableAccumulatorBundle> {
1330        match self {
1331            ProcessIntegrand::Amplitude(integrand) => observable_accumulator_bundle(integrand),
1332            ProcessIntegrand::CrossSection(integrand) => observable_accumulator_bundle(integrand),
1333        }
1334    }
1335
1336    pub fn has_observables(&self) -> bool {
1337        match self {
1338            ProcessIntegrand::Amplitude(integrand) => integrand
1339                .event_processing_runtime()
1340                .is_some_and(EventProcessingRuntime::has_observables),
1341            ProcessIntegrand::CrossSection(integrand) => integrand
1342                .event_processing_runtime()
1343                .is_some_and(EventProcessingRuntime::has_observables),
1344        }
1345    }
1346
1347    pub fn observable_snapshot_bundle(&self) -> Option<ObservableSnapshotBundle> {
1348        match self {
1349            ProcessIntegrand::Amplitude(integrand) => observable_snapshot_bundle(integrand),
1350            ProcessIntegrand::CrossSection(integrand) => observable_snapshot_bundle(integrand),
1351        }
1352    }
1353
1354    pub fn write_observable_snapshots(
1355        &self,
1356        path: impl AsRef<Path>,
1357        format: ObservableFileFormat,
1358    ) -> Result<()> {
1359        let Some(bundle) = self.observable_snapshot_bundle() else {
1360            return Ok(());
1361        };
1362
1363        write_observable_snapshot_bundle(&bundle, path.as_ref(), format)
1364    }
1365
1366    pub fn restore_observable_snapshot_bundle(
1367        &mut self,
1368        bundle: &ObservableSnapshotBundle,
1369    ) -> Result<()> {
1370        match self {
1371            ProcessIntegrand::Amplitude(integrand) => {
1372                restore_observable_snapshot_bundle(integrand, bundle)
1373            }
1374            ProcessIntegrand::CrossSection(integrand) => {
1375                restore_observable_snapshot_bundle(integrand, bundle)
1376            }
1377        }
1378    }
1379}
1380
1381fn format_orientation_label(signature: &EdgeVec<Orientation>) -> String {
1382    signature
1383        .iter()
1384        .map(|(_, orientation)| match *orientation {
1385            Orientation::Default => '+',
1386            Orientation::Reversed => '-',
1387            Orientation::Undirected => '0',
1388        })
1389        .collect()
1390}
1391
1392pub(crate) fn resolve_visible_orientation_id(
1393    orientation_filter: &SubSet<OrientationID>,
1394    visible_orientation_id: usize,
1395) -> Option<OrientationID> {
1396    if orientation_filter.is_full() {
1397        Some(OrientationID::from(visible_orientation_id))
1398    } else {
1399        orientation_filter
1400            .included_iter()
1401            .nth(visible_orientation_id)
1402    }
1403}
1404
1405pub(crate) fn filtered_orientation_count(
1406    orientation_filter: &SubSet<OrientationID>,
1407    orientations: &TiVec<OrientationID, EdgeVec<Orientation>>,
1408) -> usize {
1409    if orientation_filter.is_full() {
1410        orientations.len()
1411    } else {
1412        orientation_filter.included_iter().count()
1413    }
1414}
1415
1416pub(crate) fn orientation_labels_for_graph<I: ProcessIntegrandImpl>(
1417    integrand: &I,
1418    graph_id: usize,
1419) -> Result<Vec<String>> {
1420    if graph_id >= integrand.graph_count() {
1421        return Err(eyre!(
1422            "Unknown graph '{}' while resolving orientation labels.",
1423            graph_id
1424        ));
1425    }
1426    let graph = integrand.get_graph(graph_id);
1427    Ok((0..graph.get_num_orientations())
1428        .map(|orientation_id| {
1429            graph
1430                .orientation_label(orientation_id)
1431                .unwrap_or_else(|| format!("#{}", orientation_id))
1432        })
1433        .collect())
1434}
1435
1436#[allow(clippy::too_many_arguments)]
1437pub(crate) fn evaluate_profile_momentum_point_precise<I: ProcessIntegrandImpl>(
1438    integrand: &mut I,
1439    model: &Model,
1440    graph_id: usize,
1441    orientation: Option<usize>,
1442    loop_momenta: Vec<ThreeMomentum<F<f64>>>,
1443    candidate_lmb: Option<&LoopMomentumBasis>,
1444    use_arb_prec: bool,
1445    weight: &F<ArbPrec>,
1446) -> Result<PreciseEvaluationResult> {
1447    let input = MomentumSpaceEvaluationInput {
1448        loop_momenta,
1449        integrator_weight: F(1.0),
1450        graph_id: Some(graph_id),
1451        group_id: None,
1452        orientation,
1453        channel_id: None,
1454    };
1455    evaluate_from_source_precise_with_estimate(
1456        integrand,
1457        EvaluationTarget::Physical(model),
1458        EvaluationSource::Momentum {
1459            input: &input,
1460            candidate_lmb,
1461        },
1462        F(1.0),
1463        use_arb_prec,
1464        Complex::new_re(F(100.0 * integrand.get_settings().kinematics.e_cm)),
1465        None,
1466        Some(weight),
1467    )
1468}
1469
1470fn format_sampling_channel_label(edge_ids: &[usize]) -> String {
1471    let mut sorted = edge_ids.to_vec();
1472    sorted.sort_unstable();
1473    format!(
1474        "({})",
1475        sorted
1476            .iter()
1477            .map(|edge_id| edge_id.to_string())
1478            .collect_vec()
1479            .join(",")
1480    )
1481}
1482
1483pub(crate) fn histogram_process_info_for_integrand<I: ProcessIntegrandImpl>(
1484    integrand: &I,
1485) -> Result<HistogramProcessInfo> {
1486    let parameterization_settings = integrand
1487        .get_settings()
1488        .sampling
1489        .get_parameterization_settings()
1490        .unwrap_or_default();
1491    let graph_names = (0..integrand.graph_count())
1492        .map(|graph_id| integrand.get_graph(graph_id).name())
1493        .collect_vec();
1494    let graph_to_group_id = (0..integrand.graph_count())
1495        .map(|graph_id| {
1496            integrand
1497                .graph_group_id_for_graph(graph_id)
1498                .unwrap_or_else(|| {
1499                    panic!(
1500                        "graph {} is missing a graph-group mapping for histogram process info",
1501                        graph_id
1502                    )
1503                })
1504        })
1505        .collect_vec();
1506    let graph_group_master_names = integrand
1507        .get_group_structure()
1508        .iter_enumerated()
1509        .map(|(group_id, _)| integrand.get_master_graph(group_id).name())
1510        .collect_vec();
1511    let orientation_labels_by_group = integrand
1512        .get_group_structure()
1513        .iter_enumerated()
1514        .map(|(group_id, _)| {
1515            let master = integrand.get_master_graph(group_id);
1516            (0..master.get_num_orientations())
1517                .map(|orientation_id| {
1518                    master
1519                        .orientation_label(orientation_id)
1520                        .unwrap_or_else(|| format!("#{}", orientation_id))
1521                })
1522                .collect_vec()
1523        })
1524        .collect_vec();
1525    let sampling_channel_labels_by_group = integrand
1526        .get_group_structure()
1527        .iter_enumerated()
1528        .map(|(group_id, _)| {
1529            let master = integrand.get_master_graph(group_id);
1530            let channel_ids = master.sampling_channel_ids(&parameterization_settings)?;
1531            channel_ids
1532                .into_iter()
1533                .map(|channel_id| {
1534                    Ok(master
1535                        .sampling_channel_label(channel_id, &parameterization_settings)?
1536                        .unwrap_or_else(|| format!("#{}", channel_id.index())))
1537                })
1538                .collect::<Result<Vec<_>>>()
1539        })
1540        .collect::<Result<Vec<_>>>()?;
1541    Ok(HistogramProcessInfo {
1542        graph_names,
1543        graph_to_group_id,
1544        graph_group_master_names,
1545        orientation_labels_by_group,
1546        sampling_channel_labels_by_group,
1547    })
1548}
1549
1550pub(crate) fn graph_to_group_id_for_group_structure(
1551    group_structure: &TiVec<GroupId, GraphGroup>,
1552) -> Vec<usize> {
1553    group_structure
1554        .iter_enumerated()
1555        .flat_map(|(group_id, group)| {
1556            group
1557                .into_iter()
1558                .map(move |graph_id| (graph_id, group_id.0))
1559        })
1560        .sorted_by_key(|(graph_id, _)| *graph_id)
1561        .map(|(_, group_id)| group_id)
1562        .collect_vec()
1563}
1564
1565pub(crate) struct PreparedBufferedEvent<T: FloatLike> {
1566    pub(crate) buffered_event: Option<GenericEvent<T>>,
1567    pub(crate) selectors_pass: bool,
1568    pub(crate) event_processing_time: Duration,
1569    pub(crate) generated_event_count: usize,
1570    pub(crate) accepted_event_count: usize,
1571}
1572
1573impl<T: FloatLike> Default for PreparedBufferedEvent<T> {
1574    fn default() -> Self {
1575        Self {
1576            buffered_event: None,
1577            selectors_pass: true,
1578            event_processing_time: Duration::ZERO,
1579            generated_event_count: 0,
1580            accepted_event_count: 0,
1581        }
1582    }
1583}
1584
1585pub(crate) fn prepare_buffered_event<T: FloatLike>(
1586    settings: &RuntimeSettings,
1587    rotation: &Rotation,
1588    event_processing_runtime: Option<&mut EventProcessingRuntime>,
1589    build_event: impl FnOnce() -> Result<GenericEvent<T>>,
1590) -> Result<PreparedBufferedEvent<T>> {
1591    let needs_selector_events = event_processing_runtime
1592        .as_ref()
1593        .is_some_and(|runtime| runtime.has_selectors());
1594    let should_buffer_event = rotation.is_identity() && settings.should_buffer_generated_events();
1595    let should_build_event = if rotation.is_identity() {
1596        settings.should_generate_events()
1597    } else {
1598        needs_selector_events
1599    };
1600
1601    if !should_build_event {
1602        return Ok(PreparedBufferedEvent::default());
1603    }
1604
1605    let build_start = Instant::now();
1606    let mut event = build_event()?;
1607    let mut event_processing_time = build_start.elapsed();
1608    let generated_event_count = usize::from(rotation.is_identity());
1609
1610    let selector_start = Instant::now();
1611    let selectors_pass = if let Some(runtime) = event_processing_runtime {
1612        if rotation.is_identity() {
1613            runtime.process_event(&mut event)
1614        } else {
1615            runtime.process_event_for_selectors(&mut event)
1616        }
1617    } else {
1618        true
1619    };
1620    event_processing_time += selector_start.elapsed();
1621
1622    let buffered_event = if selectors_pass && should_buffer_event {
1623        Some(event)
1624    } else {
1625        None
1626    };
1627
1628    // Count selector-accepted physical events even when they are processed only
1629    // transiently for selectors and are not retained in the returned event buffer.
1630    let accepted_event_count = usize::from(rotation.is_identity() && selectors_pass);
1631
1632    Ok(PreparedBufferedEvent {
1633        accepted_event_count,
1634        buffered_event,
1635        selectors_pass,
1636        event_processing_time,
1637        generated_event_count,
1638    })
1639}
1640
1641fn process_evaluation_result_runtime<I: ProcessIntegrandImpl>(
1642    integrand: &mut I,
1643    result: &EvaluationResult,
1644) -> Result<()> {
1645    if let Some(runtime) = integrand.event_processing_runtime_mut() {
1646        runtime.accumulate_sample(&result.event_groups, &result.integrator_weight)?;
1647    }
1648    Ok(())
1649}
1650
1651fn merge_event_processing_runtime<I: ProcessIntegrandImpl>(
1652    integrand: &mut I,
1653    other: &mut I,
1654) -> Result<()> {
1655    match (
1656        integrand.event_processing_runtime_mut(),
1657        other.event_processing_runtime_mut(),
1658    ) {
1659        (Some(lhs), Some(rhs)) => lhs.merge_samples(rhs),
1660        _ => Ok(()),
1661    }
1662}
1663
1664fn update_event_processing_runtime<I: ProcessIntegrandImpl>(integrand: &mut I, iter: usize) {
1665    if let Some(runtime) = integrand.event_processing_runtime_mut() {
1666        runtime.update_results(iter);
1667    }
1668}
1669
1670fn observable_accumulator_bundle<I: ProcessIntegrandImpl>(
1671    integrand: &I,
1672) -> Option<ObservableAccumulatorBundle> {
1673    integrand
1674        .event_processing_runtime()
1675        .filter(|runtime| runtime.has_observables())
1676        .map(EventProcessingRuntime::accumulator_bundle)
1677}
1678
1679fn observable_snapshot_bundle<I: ProcessIntegrandImpl>(
1680    integrand: &I,
1681) -> Option<ObservableSnapshotBundle> {
1682    integrand
1683        .event_processing_runtime()
1684        .filter(|runtime| runtime.has_observables())
1685        .map(EventProcessingRuntime::snapshot_bundle)
1686}
1687
1688fn restore_observable_snapshot_bundle<I: ProcessIntegrandImpl>(
1689    integrand: &mut I,
1690    bundle: &ObservableSnapshotBundle,
1691) -> Result<()> {
1692    let runtime = integrand.event_processing_runtime_mut().ok_or_else(|| {
1693        eyre!("Cannot restore observables before the integrand has been warmed up")
1694    })?;
1695    if !runtime.has_observables() {
1696        return Err(eyre!(
1697            "Cannot restore observable snapshots for an integrand without configured observables"
1698        ));
1699    }
1700    runtime.restore_snapshot_bundle(bundle)
1701}
1702
1703fn full_event_multiplicative_factor_precise<T: FloatLike>(
1704    parameterization_jacobian: Option<F<T>>,
1705    integrator_weight: F<T>,
1706) -> Complex<F<T>> {
1707    let jacobian = parameterization_jacobian.unwrap_or_else(|| integrator_weight.one());
1708    Complex::new_re(jacobian * integrator_weight)
1709}
1710
1711pub(crate) fn apply_full_event_multiplicative_factor_precise<T: FloatLike>(
1712    event_groups: &mut crate::observables::GenericEventGroupList<T>,
1713    full_factor: &Complex<F<T>>,
1714) {
1715    for event_group in event_groups.iter_mut() {
1716        for event in event_group.iter_mut() {
1717            event.apply_multiplicative_factor(full_factor);
1718
1719            if !event.additional_weights.weights.is_empty() {
1720                event
1721                    .additional_weights
1722                    .weights
1723                    .entry(AdditionalWeightKey::FullMultiplicativeFactor)
1724                    .and_modify(|value| *value *= full_factor.clone())
1725                    .or_insert_with(|| full_factor.clone());
1726            }
1727        }
1728    }
1729}
1730
1731pub(crate) fn write_observable_snapshot_bundle(
1732    bundle: &ObservableSnapshotBundle,
1733    path: &Path,
1734    format: ObservableFileFormat,
1735) -> Result<()> {
1736    match format {
1737        ObservableFileFormat::None => Ok(()),
1738        ObservableFileFormat::Hwu => bundle.write_hwu_file(path),
1739        ObservableFileFormat::Json => bundle.to_json_file(path),
1740    }
1741}
1742
1743#[derive(Debug, Clone, Copy)]
1744pub enum IntegrandType {
1745    Amplitude,
1746    CrossSection,
1747}
1748
1749fn create_stability_iterator(
1750    settings: &StabilitySettings,
1751    use_arb_prec: bool,
1752) -> Vec<StabilityLevelSetting> {
1753    if use_arb_prec {
1754        // Force arbitrary precision, reusing the configured Arb thresholds when available.
1755        if let Some(arb_settings_position) = settings
1756            .levels
1757            .iter()
1758            .position(|stability_level_setting| stability_level_setting.precision == Precision::Arb)
1759        {
1760            vec![settings.levels[arb_settings_position]]
1761        } else {
1762            vec![StabilityLevelSetting {
1763                three_dimensional_representation: settings
1764                    .levels
1765                    .first()
1766                    .and_then(|level| level.three_dimensional_representation),
1767                ..StabilityLevelSetting::default_arb()
1768            }]
1769        }
1770    } else {
1771        settings.levels.clone()
1772    }
1773}
1774
1775#[inline]
1776fn complex_from_f64<T: FloatLike>(value: &Complex<F<f64>>) -> Complex<F<T>> {
1777    Complex::new(F::<T>::from_ff64(value.re), F::<T>::from_ff64(value.im))
1778}
1779
1780#[inline]
1781fn complex_to_f64<T: FloatLike>(value: &Complex<F<T>>) -> Complex<F<f64>> {
1782    Complex::new(value.re.into_ff64(), value.im.into_ff64())
1783}
1784
1785type StabilityCheckResult<T> = (
1786    Complex<F<T>>,
1787    Option<F<T>>,
1788    bool,
1789    Option<StabilityFailureReason>,
1790);
1791
1792#[inline]
1793#[cfg(test)]
1794fn stability_check<T: FloatLike>(
1795    ecm_scale: Option<&F<T>>,
1796    results: &[Complex<F<T>>],
1797    stability_settings: &StabilityLevelSetting,
1798    max_eval: Complex<F<T>>,
1799    wgt: F<T>,
1800    is_final_level: bool,
1801    escalate_if_exact_zero: bool,
1802) -> StabilityCheckResult<T> {
1803    stability_check_with_estimate(
1804        ecm_scale,
1805        results,
1806        stability_settings,
1807        max_eval,
1808        wgt,
1809        is_final_level,
1810        escalate_if_exact_zero,
1811        None,
1812        0.0,
1813    )
1814}
1815
1816#[inline]
1817#[allow(clippy::too_many_arguments)]
1818fn stability_check_with_estimate<T: FloatLike>(
1819    ecm_scale: Option<&F<T>>,
1820    results: &[Complex<F<T>>],
1821    stability_settings: &StabilityLevelSetting,
1822    max_eval: Complex<F<T>>,
1823    wgt: F<T>,
1824    is_final_level: bool,
1825    escalate_if_exact_zero: bool,
1826    integral_estimate: Option<(f64, f64)>,
1827    min_abs_wgt_for_escalation: f64,
1828) -> StabilityCheckResult<T> {
1829    stability_check_components_with_estimate(
1830        ecm_scale,
1831        results,
1832        stability_settings,
1833        max_eval,
1834        wgt,
1835        is_final_level,
1836        escalate_if_exact_zero,
1837        true,
1838        true,
1839        integral_estimate,
1840        min_abs_wgt_for_escalation,
1841    )
1842}
1843
1844#[inline]
1845#[cfg(test)]
1846#[allow(clippy::too_many_arguments)]
1847fn stability_check_components<T: FloatLike>(
1848    ecm_scale: Option<&F<T>>,
1849    results: &[Complex<F<T>>],
1850    stability_settings: &StabilityLevelSetting,
1851    max_eval: Complex<F<T>>,
1852    wgt: F<T>,
1853    is_final_level: bool,
1854    escalate_if_exact_zero: bool,
1855    check_real: bool,
1856    check_imag: bool,
1857) -> StabilityCheckResult<T> {
1858    stability_check_components_with_estimate(
1859        ecm_scale,
1860        results,
1861        stability_settings,
1862        max_eval,
1863        wgt,
1864        is_final_level,
1865        escalate_if_exact_zero,
1866        check_real,
1867        check_imag,
1868        None,
1869        0.0,
1870    )
1871}
1872
1873#[inline]
1874#[allow(clippy::too_many_arguments)]
1875fn stability_check_components_with_estimate<T: FloatLike>(
1876    ecm_scale: Option<&F<T>>,
1877    results: &[Complex<F<T>>],
1878    stability_settings: &StabilityLevelSetting,
1879    max_eval: Complex<F<T>>,
1880    wgt: F<T>,
1881    is_final_level: bool,
1882    escalate_if_exact_zero: bool,
1883    check_real: bool,
1884    check_imag: bool,
1885    integral_estimate: Option<(f64, f64)>,
1886    min_abs_wgt_for_escalation: f64,
1887) -> StabilityCheckResult<T> {
1888    // Nonfinite probes cannot establish stability, even at the final precision.
1889    if results.iter().any(|result| {
1890        (check_real && (result.re.is_nan() || result.re.is_infinite()))
1891            || (check_imag && (result.im.is_nan() || result.im.is_infinite()))
1892    }) {
1893        return (
1894            results[0].clone(),
1895            None,
1896            false,
1897            Some(StabilityFailureReason::ErrorThreshold),
1898        );
1899    }
1900
1901    if results.len() == 1 {
1902        return (results[0].clone(), None, true, None);
1903    }
1904
1905    let average = results
1906        .iter()
1907        .skip(1)
1908        .fold(results[0].clone(), |acc, x| acc + x)
1909        / F::<T>::from_f64(results.len() as f64);
1910
1911    // Bound the reported rotation average without cancellation, applying the
1912    // remaining weight before any normal-range test. Native values and their
1913    // measured relative errors remain intact; only suppressed final components
1914    // may waive a relative-error failure at binary64's normal boundary.
1915    let weighted_absolute_average = results
1916        .iter()
1917        .fold(Complex::new_re(average.re.zero()), |sum, result| {
1918            sum + Complex::new((&result.re * &wgt).abs(), (&result.im * &wgt).abs())
1919        })
1920        / F::<T>::from_f64(results.len() as f64);
1921    let minimum_normal = F::<T>::from_f64(f64::MIN_POSITIVE);
1922    let real_underflow = check_real
1923        && weighted_absolute_average.re.0.is_finite()
1924        && weighted_absolute_average.re < minimum_normal;
1925    let imag_underflow = check_imag
1926        && weighted_absolute_average.im.0.is_finite()
1927        && weighted_absolute_average.im < minimum_normal;
1928
1929    let errors = results
1930        .iter()
1931        .map(|res| {
1932            let error_re =
1933                if !check_real || (IsZero::is_zero(&res.re) && IsZero::is_zero(&average.re)) {
1934                    F::<T>::from_f64(0.0)
1935                } else {
1936                    ((&res.re - &average.re) / &average.re).abs()
1937                };
1938            let error_im =
1939                if !check_imag || (IsZero::is_zero(&res.im) && IsZero::is_zero(&average.im)) {
1940                    F::<T>::from_f64(0.0)
1941                } else {
1942                    ((&res.im - &average.im) / &average.im).abs()
1943                };
1944            Complex::new(error_re, error_im)
1945        })
1946        .collect::<Vec<_>>();
1947    let estimated_relative_accuracy = errors.iter().fold(average.re.zero(), |max, error| {
1948        max.max(error.re.clone().max(error.im.clone()))
1949    });
1950
1951    // Do not spend higher precision on a point whose complete weighted probe
1952    // contribution is negligible compared with a well-resolved integral. The
1953    // estimate is supplied by the previous integration iteration and is
1954    // accepted only when its standard error is at most ten percent. The
1955    // integrator supplies the corresponding absolute-component estimate.
1956    // A discrepancy below 1e-2 is treated as insufficient evidence that the
1957    // order of magnitude is reliable, so it must not permit this waiver.
1958    let small_weight_waiver = |max_weight: F<T>| {
1959        min_abs_wgt_for_escalation > 0.0
1960            && !is_final_level
1961            && integral_estimate.is_some_and(|(estimate, error)| {
1962                estimate.is_finite()
1963                    && error.is_finite()
1964                    && error >= 0.0
1965                    && estimate != 0.0
1966                    && error <= 0.10 * estimate.abs()
1967                    && estimated_relative_accuracy >= F::<T>::from_f64(1.0e-2)
1968                    && max_weight.0.is_finite()
1969                    && max_weight < F::<T>::from_f64(min_abs_wgt_for_escalation * estimate.abs())
1970            })
1971    };
1972    let current_max_weight = results
1973        .iter()
1974        .fold(wgt.abs() * average.re.zero(), |max, result| {
1975            let magnitude = if check_real && check_imag {
1976                result.re.abs().max(result.im.abs())
1977            } else if check_real {
1978                result.re.abs()
1979            } else if check_imag {
1980                result.im.abs()
1981            } else {
1982                result.re.zero()
1983            } * wgt.abs();
1984            max.max(magnitude)
1985        });
1986    let small_weight_waiver = small_weight_waiver(current_max_weight);
1987
1988    let mut unstable_reason = None;
1989    let mut unstable_sample = None;
1990    for (index, error) in errors.into_iter().enumerate() {
1991        if !is_final_level
1992            && escalate_if_exact_zero
1993            && !small_weight_waiver
1994            && (!check_real || error.re == F::<T>::from_f64(0.0))
1995            && (!check_imag || error.im == F::<T>::from_f64(0.0))
1996        {
1997            unstable_reason = Some(StabilityFailureReason::ZeroError);
1998            unstable_sample = Some(index);
1999            break;
2000        }
2001
2002        // The optional allowance is dimensionless relative to E_cm, after
2003        // every sample factor. Preserve the measured relative discrepancy;
2004        // another component's scale must not supply the allowance.
2005        let absolute_error = Complex::new(
2006            ((&results[index].re - &average.re) * &wgt).abs(),
2007            ((&results[index].im - &average.im) * &wgt).abs(),
2008        );
2009        let real_absolute = stability_settings.ecm_relative_tolerance_for_re > 0.0
2010            && wgt.0.is_finite()
2011            && weighted_absolute_average.re.0.is_finite()
2012            && absolute_error.re.0.is_finite()
2013            && ecm_scale.is_some_and(|scale| {
2014                scale.0.is_finite()
2015                    && scale > &scale.zero()
2016                    && &absolute_error.re / scale
2017                        <= F::<T>::from_f64(stability_settings.ecm_relative_tolerance_for_re)
2018            });
2019        let imag_absolute = stability_settings.ecm_relative_tolerance_for_im > 0.0
2020            && wgt.0.is_finite()
2021            && weighted_absolute_average.im.0.is_finite()
2022            && absolute_error.im.0.is_finite()
2023            && ecm_scale.is_some_and(|scale| {
2024                scale.0.is_finite()
2025                    && scale > &scale.zero()
2026                    && &absolute_error.im / scale
2027                        <= F::<T>::from_f64(stability_settings.ecm_relative_tolerance_for_im)
2028            });
2029        if (check_real
2030            && error.re > F::<T>::from_f64(stability_settings.required_precision_for_re)
2031            && !real_underflow
2032            && !real_absolute
2033            && !small_weight_waiver)
2034            || (check_imag
2035                && error.im > F::<T>::from_f64(stability_settings.required_precision_for_im)
2036                && !imag_underflow
2037                && !imag_absolute
2038                && !small_weight_waiver)
2039        {
2040            unstable_reason = Some(StabilityFailureReason::ErrorThreshold);
2041            unstable_sample = Some(index);
2042            break;
2043        }
2044    }
2045
2046    if let Some(unstable_index) = unstable_sample {
2047        let unstable_point = &results[unstable_index];
2048
2049        let ((real_formatted, rotated_real_formatted), (imag_formatted, rotated_imag_formatted)) = (
2050            format_for_compare_digits(
2051                average.re.clone().into_ff64(),
2052                unstable_point.re.clone().into_ff64(),
2053            ),
2054            format_for_compare_digits(
2055                average.im.clone().into_ff64(),
2056                unstable_point.im.clone().into_ff64(),
2057            ),
2058        );
2059
2060        debug!("{}", "\nUnstable point detected:".red());
2061        debug!("\taverage result: {} + {}i", real_formatted, imag_formatted,);
2062        debug!(
2063            "\trotated result: {} + {}i",
2064            rotated_real_formatted, rotated_imag_formatted,
2065        );
2066    }
2067
2068    let stable = unstable_sample.is_none();
2069
2070    let has_active_max = (check_real && !IsZero::is_zero(&max_eval.re))
2071        || (check_imag && !IsZero::is_zero(&max_eval.im));
2072    let below_wgt_threshold =
2073        if stability_settings.escalate_for_large_weight_threshold > 0. && has_active_max {
2074            (check_real
2075                && average.re.abs() * wgt.clone()
2076                    < F::<T>::from_f64(stability_settings.escalate_for_large_weight_threshold)
2077                        * max_eval.re)
2078                || (check_imag
2079                    && average.im.abs() * wgt
2080                        < F::<T>::from_f64(stability_settings.escalate_for_large_weight_threshold)
2081                            * max_eval.im)
2082        } else {
2083            true
2084        };
2085
2086    let weight_reason = if stable && !below_wgt_threshold && !small_weight_waiver {
2087        Some(StabilityFailureReason::WeightThreshold)
2088    } else {
2089        None
2090    };
2091
2092    (
2093        average,
2094        Some(estimated_relative_accuracy),
2095        stable && (below_wgt_threshold || small_weight_waiver),
2096        unstable_reason.or(weight_reason),
2097    )
2098}
2099
2100#[inline]
2101#[cfg(test)]
2102fn stability_check_on_norm<T: FloatLike>(
2103    ecm_scale: Option<&F<T>>,
2104    results: &[Complex<F<T>>],
2105    stability_settings: &StabilityLevelSetting,
2106    max_eval: Complex<F<T>>,
2107    wgt: F<T>,
2108    is_final_level: bool,
2109    escalate_if_exact_zero: bool,
2110) -> StabilityCheckResult<T> {
2111    stability_check_on_norm_components_with_estimate(
2112        ecm_scale,
2113        results,
2114        stability_settings,
2115        max_eval,
2116        wgt,
2117        is_final_level,
2118        escalate_if_exact_zero,
2119        true,
2120        true,
2121        None,
2122        0.0,
2123    )
2124}
2125
2126#[inline]
2127#[allow(clippy::too_many_arguments)]
2128fn stability_check_on_norm_components_with_estimate<T: FloatLike>(
2129    ecm_scale: Option<&F<T>>,
2130    results: &[Complex<F<T>>],
2131    stability_settings: &StabilityLevelSetting,
2132    max_eval: Complex<F<T>>,
2133    wgt: F<T>,
2134    is_final_level: bool,
2135    escalate_if_exact_zero: bool,
2136    check_real: bool,
2137    check_imag: bool,
2138    integral_estimate: Option<(f64, f64)>,
2139    min_abs_wgt_for_escalation: f64,
2140) -> StabilityCheckResult<T> {
2141    // Nonfinite probes cannot establish stability, even at the final precision.
2142    if results.iter().any(|result| {
2143        (check_real && (result.re.is_nan() || result.re.is_infinite()))
2144            || (check_imag && (result.im.is_nan() || result.im.is_infinite()))
2145    }) {
2146        return (
2147            results[0].clone(),
2148            None,
2149            false,
2150            Some(StabilityFailureReason::ErrorThreshold),
2151        );
2152    }
2153
2154    if results.len() == 1 {
2155        return (results[0].clone(), None, true, None);
2156    }
2157
2158    let component_magnitude = |x: &Complex<F<T>>| match (check_real, check_imag) {
2159        (true, false) => x.re.abs(),
2160        (false, true) => x.im.abs(),
2161        (true, true) => x.re.hypot(&x.im),
2162        (false, false) => x.re.zero(),
2163    };
2164    let magnitudes = results.iter().map(component_magnitude).collect_vec();
2165    let count = F::<T>::from_f64(results.len() as f64);
2166    // Divide before summing so finite near-MAX probes have a finite mean.
2167    // A true norm overflow must trigger precision rescue, never a NaN accuracy
2168    // whose comparison with the tolerance would silently accept the sample.
2169    let average = magnitudes
2170        .iter()
2171        .fold(F::<T>::from_f64(0.0), |acc, x| acc + x / &count);
2172    if !average.0.is_finite() || magnitudes.iter().any(|value| !value.0.is_finite()) {
2173        return (
2174            results[0].clone(),
2175            None,
2176            false,
2177            Some(StabilityFailureReason::ErrorThreshold),
2178        );
2179    }
2180
2181    // The norm owner returns the primary probe, so bound it as well as the
2182    // average. Scaled component magnitudes avoid squaring tiny weighted values.
2183    let weighted_magnitude = |result: &Complex<F<T>>| (component_magnitude(result) * &wgt).abs();
2184    let weighted_absolute_average = results.iter().fold(average.zero(), |sum, result| {
2185        sum + weighted_magnitude(result) / &count
2186    });
2187    let primary_magnitude = weighted_magnitude(&results[0]);
2188    let minimum_normal = F::<T>::from_f64(f64::MIN_POSITIVE);
2189    let underflow = weighted_absolute_average.0.is_finite()
2190        && primary_magnitude.0.is_finite()
2191        && weighted_absolute_average < minimum_normal
2192        && primary_magnitude < minimum_normal;
2193
2194    // The E_cm-relative allowance must bound every component against the
2195    // primary value returned by this owner, independently of its norm.
2196    let absolute_agreement = (stability_settings.ecm_relative_tolerance_for_re > 0.0
2197        || stability_settings.ecm_relative_tolerance_for_im > 0.0)
2198        && wgt.0.is_finite()
2199        && weighted_absolute_average.0.is_finite()
2200        && ecm_scale.is_some_and(|scale| scale.0.is_finite() && scale > &scale.zero())
2201        && results.iter().all(|result| {
2202            let error_re = ((&result.re - &results[0].re) * &wgt).abs();
2203            let error_im = ((&result.im - &results[0].im) * &wgt).abs();
2204            (!check_real
2205                || (error_re.0.is_finite()
2206                    && error_re / ecm_scale.unwrap()
2207                        <= F::<T>::from_f64(stability_settings.ecm_relative_tolerance_for_re)))
2208                && (!check_imag
2209                    || (error_im.0.is_finite()
2210                        && error_im / ecm_scale.unwrap()
2211                            <= F::<T>::from_f64(stability_settings.ecm_relative_tolerance_for_im)))
2212        });
2213
2214    let errors = magnitudes
2215        .iter()
2216        .map(|res| {
2217            if IsZero::is_zero(res) && IsZero::is_zero(&average) {
2218                (F::<T>::from_f64(0.0), true) // true zero is fishy -> upgrade to next precision
2219            } else {
2220                (((res - &average) / &average).abs(), false)
2221            }
2222        })
2223        .collect::<Vec<_>>();
2224    if errors.iter().any(|(error, _)| !error.0.is_finite()) {
2225        return (
2226            results[0].clone(),
2227            None,
2228            false,
2229            Some(StabilityFailureReason::ErrorThreshold),
2230        );
2231    }
2232    let estimated_relative_accuracy = errors
2233        .iter()
2234        .fold(average.zero(), |max, (error, _)| max.max(error.clone()));
2235
2236    // Low probe discrepancy cannot establish the order of magnitude.
2237    let small_weight_waiver = |max_weight: F<T>| {
2238        min_abs_wgt_for_escalation > 0.0
2239            && !is_final_level
2240            && integral_estimate.is_some_and(|(estimate, error)| {
2241                estimate.is_finite()
2242                    && error.is_finite()
2243                    && error >= 0.0
2244                    && estimate != 0.0
2245                    && error <= 0.10 * estimate.abs()
2246                    && estimated_relative_accuracy >= F::<T>::from_f64(1.0e-2)
2247                    && max_weight.0.is_finite()
2248                    && max_weight < F::<T>::from_f64(min_abs_wgt_for_escalation * estimate.abs())
2249            })
2250    };
2251    let current_max_weight = results.iter().fold(average.zero(), |max, result| {
2252        max.max(weighted_magnitude(result).abs())
2253    });
2254    let small_weight_waiver = small_weight_waiver(current_max_weight);
2255
2256    let mut unstable_reason = None;
2257    let mut unstable_sample = None;
2258    for (index, (error, result_is_exact_zero)) in errors.into_iter().enumerate() {
2259        if !is_final_level
2260            && error == F::<T>::from_f64(0.0)
2261            && result_is_exact_zero
2262            && escalate_if_exact_zero
2263            && !small_weight_waiver
2264        {
2265            unstable_reason = Some(StabilityFailureReason::ZeroError);
2266            unstable_sample = Some(index);
2267            break;
2268        }
2269
2270        if error > F::<T>::from_f64(stability_settings.required_precision_for_re)
2271            && !underflow
2272            && !absolute_agreement
2273            && !small_weight_waiver
2274        {
2275            unstable_reason = Some(StabilityFailureReason::ErrorThreshold);
2276            unstable_sample = Some(index);
2277            break;
2278        }
2279    }
2280
2281    if let Some(unstable_index) = unstable_sample {
2282        let unstable_point = &results[unstable_index];
2283
2284        let (real_formatted, rotated_real_formatted) = format_for_compare_digits(
2285            average.clone().into_ff64(),
2286            unstable_point.re.clone().into_ff64(),
2287        );
2288
2289        debug!("{}", "\nUnstable point detected:".red());
2290        debug!("\tnormed average result: {}", real_formatted,);
2291        debug!("\tnormed rotated result: {}", rotated_real_formatted,);
2292    }
2293
2294    let stable = unstable_sample.is_none();
2295
2296    let max_magnitude = component_magnitude(&max_eval);
2297    let below_wgt_threshold = if stability_settings.escalate_for_large_weight_threshold > 0.
2298        && max_magnitude != max_magnitude.zero()
2299    {
2300        average.abs() * wgt.abs()
2301            < F::<T>::from_f64(stability_settings.escalate_for_large_weight_threshold)
2302                * max_magnitude
2303    } else {
2304        true
2305    };
2306
2307    let weight_reason = if stable && !below_wgt_threshold && !small_weight_waiver {
2308        Some(StabilityFailureReason::WeightThreshold)
2309    } else {
2310        None
2311    };
2312
2313    (
2314        results[0].clone(),
2315        Some(estimated_relative_accuracy),
2316        stable && (below_wgt_threshold || small_weight_waiver),
2317        unstable_reason.or(weight_reason),
2318    )
2319}
2320
2321#[derive(Debug, Clone)]
2322struct PreciseStabilityLevelResult<T: FloatLike> {
2323    pub result: Complex<F<T>>,
2324    pub graph_result: GraphEvaluationResult<T>,
2325    pub stability_level_used: Precision,
2326    pub representation: RepresentationMode,
2327    pub estimated_relative_accuracy: Option<F<T>>,
2328    pub sample_count: usize,
2329    pub total_time: Duration,
2330    pub parameterization_jacobian: Option<F<T>>,
2331    pub is_stable: bool,
2332    pub rotated_results: Vec<RotatedEvaluation>,
2333}
2334
2335impl<T: FloatLike> PreciseStabilityLevelResult<T> {
2336    fn stability_result(&self) -> StabilityResult {
2337        // Preserve the exponent before a nonzero Arb estimate can underflow to f64 zero.
2338        let estimated_decimal_digits = self
2339            .estimated_relative_accuracy
2340            .as_ref()
2341            .filter(|value| value.is_non_zero() && !value.is_nan() && !value.is_infinite())
2342            .map(|value| (-value.abs().log10()).into_ff64());
2343        StabilityResult {
2344            precision: self.stability_level_used,
2345            representation: self.representation,
2346            estimated_relative_accuracy: self
2347                .estimated_relative_accuracy
2348                .as_ref()
2349                .map(F::into_ff64),
2350            estimated_decimal_digits,
2351            status: if self.sample_count == 0 {
2352                StabilityStatus::Unstable(0)
2353            } else {
2354                StabilityStatus::from_sample_count(self.sample_count, self.is_stable)
2355            },
2356            total_time: self.total_time,
2357        }
2358    }
2359}
2360
2361/// Helper struct for the LMB multi-channeling setup
2362#[derive(Clone, Encode, Decode)]
2363#[trait_decode(trait = GammaLoopContext)]
2364pub struct LmbMultiChannelingSetup {
2365    pub lmb_basis_ids: TiVec<SamplingChannelId, LmbIndex>,
2366    /// Canonical group-master graph used to resolve group-level channel overrides.
2367    pub graph: Graph,
2368    pub all_bases: TiVec<LmbIndex, LoopMomentumBasis>,
2369    /// Current masses of the master graph; member masses never define its partition.
2370    pub(crate) master_edge_masses: RuntimeCache<EdgeVec<Complex<F<f64>>>>,
2371    pub(crate) sampling_bridge:
2372        RuntimeCache<Result<SamplingChannelBridge, sampling::maps::SamplingEvaluationError>>,
2373    pub(crate) sampling_bridge_quad:
2374        RuntimeCache<Result<SamplingChannelBridge<f128>, sampling::maps::SamplingEvaluationError>>,
2375    pub(crate) sampling_bridge_fixed256: RuntimeCache<
2376        Result<SamplingChannelBridge<SamplingFloat>, sampling::maps::SamplingEvaluationError>,
2377    >,
2378    pub(crate) sampling_bridge_arb: RuntimeCache<
2379        Result<SamplingChannelBridge<ArbPrec>, sampling::maps::SamplingEvaluationError>,
2380    >,
2381    /// One fixed source precision and strictest accuracy budget for the whole
2382    /// integrand epoch. RuntimeCache contributes no bytes to saved states.
2383    pub(crate) sampling_source: RuntimeCache<(SamplingPrecision, f64)>,
2384    pub(crate) sampling_catalogue: RuntimeCache<SamplingChannelCatalogue>,
2385    pub(crate) sampling_programs: RuntimeCache<Vec<SamplingChannelPrograms>>,
2386}
2387
2388impl LmbMultiChannelingSetup {
2389    /// Rebind the setup's graph to `model` (validated by the caller) and drop
2390    /// the mass and sampling caches computed from the previous model values;
2391    /// warm-up rebuilds them.
2392    pub fn rebind_model(&mut self, model: &Arc<Model>) {
2393        self.graph.rebind_model(model);
2394        self.master_edge_masses.invalidate();
2395        self.invalidate_sampling();
2396    }
2397
2398    /// Refresh master-owned mass evaluators independently of member parameter slots.
2399    /// Keep complex values until the selected score decides whether it supports them.
2400    pub(crate) fn warm_up_masses(
2401        &mut self,
2402        settings: &RuntimeSettings,
2403        model: &Model,
2404    ) -> Result<()> {
2405        self.master_edge_masses.invalidate();
2406        let parameters = &mut self.graph.param_builder;
2407        parameters.m_uv_value(Complex::new_re(F(settings.general.m_uv)));
2408        parameters.renormalization_localization_scale_value(Complex::new_re(F(settings
2409            .general
2410            .renormalization_localization_scale)));
2411        parameters.mu_r_sq_value(Complex::new_re(F(settings.general.mu_r_sq())));
2412        parameters.numerator_sampling_scale_value(Complex::new_re(F(settings
2413            .general
2414            .numerator_sampling_scale)));
2415        parameters.update_model_values(model)?;
2416        self.master_edge_masses
2417            .set(self.graph.new_edgevec(|edge, _, _| {
2418                edge.mass_value(model, &self.graph.param_builder)
2419                    .unwrap_or_else(|| Complex::new_re(F(0.0)))
2420            }));
2421        Ok(())
2422    }
2423
2424    /// Borrow the bridge compiled in the current successful warmup epoch, or
2425    /// replay that precision's cached numerical failure into the stability loop.
2426    /// Explicit constructors remain fresh and never populate this runtime cache.
2427    pub fn sampling_bridge<T: FloatLike>(&self) -> Result<&SamplingChannelBridge<T>> {
2428        T::sampling_bridge_cache(self).as_ref().ok_or_else(|| {
2429            eyre!(
2430                "sampling bridge for graph '{}' is not initialized; call warm_up after loading or changing runtime settings, model parameters, or graph routing",
2431                self.graph.name
2432            )
2433        })?.as_ref().map_err(|error| {
2434            eyre::Report::new(error.clone()).wrap_err(format!(
2435                "sampling binding for graph '{}' at {} precision",
2436                self.graph.name, T::sampling_precision()
2437            ))
2438        })
2439    }
2440
2441    /// Invalidate all numerical bindings and their single canonical program epoch.
2442    pub(crate) fn invalidate_sampling(&mut self) {
2443        self.sampling_bridge.invalidate();
2444        self.sampling_bridge_quad.invalidate();
2445        self.sampling_bridge_fixed256.invalidate();
2446        self.sampling_bridge_arb.invalidate();
2447        self.sampling_source.invalidate();
2448        self.sampling_catalogue.invalidate();
2449        self.sampling_programs.invalidate();
2450    }
2451
2452    /// Expand a graph-resolved selection into the canonical catalogue used by
2453    /// inspection and map construction. Resolve with the actual graph name
2454    /// before invoking this method (the setup may be shared by a graph group).
2455    pub fn sampling_channel_catalogue(
2456        &self,
2457        resolved: &ResolvedSamplingChannelSelection,
2458        parameterization_settings: &ParameterizationSettings,
2459    ) -> Result<SamplingChannelCatalogue> {
2460        self.sampling_channel_catalogue_with_surfaces(resolved, parameterization_settings, &[])
2461    }
2462
2463    /// Resolve the canonical catalogue and return its read-only inspection
2464    /// view.  This is useful to CLI/Python diagnostics and intentionally does
2465    /// not compile maps, prepare kinematics, or enumerate a second channel
2466    /// domain.
2467    pub fn inspect_sampling_channels(
2468        &self,
2469        resolved: &ResolvedSamplingChannelSelection,
2470        parameterization_settings: &ParameterizationSettings,
2471    ) -> Result<SamplingChannelInspection> {
2472        Ok(self
2473            .sampling_channel_catalogue(resolved, parameterization_settings)?
2474            .inspection())
2475    }
2476
2477    /// Report the conservative full-domain and elementary soft coverage of
2478    /// the canonical catalogue.  This is an inspection operation only: it
2479    /// does not discover physical E-surfaces or construct a second channel
2480    /// enumeration.
2481    pub fn sampling_channel_coverage_report(
2482        &self,
2483        resolved: &ResolvedSamplingChannelSelection,
2484        parameterization_settings: &ParameterizationSettings,
2485    ) -> Result<SamplingCoverageReport> {
2486        let catalogue = self.sampling_channel_catalogue(resolved, parameterization_settings)?;
2487        let all_lmbs = self
2488            .all_bases
2489            .iter_enumerated()
2490            .map(|(basis_id, basis)| {
2491                (
2492                    usize::from(basis_id),
2493                    basis.loop_edges.iter().map(|edge| edge.0).collect(),
2494                )
2495            })
2496            .collect::<Vec<_>>();
2497        let massless_edges = self
2498            .graph
2499            .underlying
2500            .iter_edges()
2501            .filter_map(|(_, edge_id, edge)| {
2502                edge.data
2503                    .particle
2504                    .is_massless(&self.graph.model)
2505                    .then_some(edge_id.0)
2506            })
2507            .collect::<Vec<_>>();
2508        Ok(catalogue.coverage_report(&all_lmbs, &massless_edges))
2509    }
2510
2511    /// Resolve the same selection while supplying E-surface candidates already
2512    /// enumerated in the master graph frame. Surface existence and geometry are
2513    /// still prepared per cut/orientation before compilation.
2514    pub fn sampling_channel_catalogue_with_surfaces(
2515        &self,
2516        resolved: &ResolvedSamplingChannelSelection,
2517        parameterization_settings: &ParameterizationSettings,
2518        surface_edges: &[Vec<usize>],
2519    ) -> Result<SamplingChannelCatalogue> {
2520        let mut all_lmbs = self
2521            .all_bases
2522            .iter_enumerated()
2523            .map(|(basis_id, basis)| {
2524                (
2525                    usize::from(basis_id),
2526                    basis.loop_edges.iter().map(|edge| edge.0).collect(),
2527                )
2528            })
2529            .collect::<Vec<_>>();
2530        let explicit_basis_ids = parameterization_settings
2531            .lmb_basis_ids
2532            .get(&self.graph.name);
2533        let optimized_lmbs = if let Some(basis_ids) = explicit_basis_ids {
2534            for &basis_id in basis_ids {
2535                self.validate_lmb_basis_id(basis_id, &self.graph.name)?;
2536            }
2537            // Explicit basis selection is exact and ordered. Automatic soft-coverage
2538            // augmentation applies only when the user has not selected the bases.
2539            all_lmbs = basis_ids.iter().map(|&id| all_lmbs[id].clone()).collect();
2540            for selector in &resolved.selectors {
2541                if let SamplingChannelSelector::Lmb(edges) = selector
2542                    && !all_lmbs.iter().any(|(_, candidate)| candidate == edges)
2543                {
2544                    let matching_ids = self
2545                        .all_bases
2546                        .iter_enumerated()
2547                        .filter_map(|(id, basis)| {
2548                            basis
2549                                .loop_edges
2550                                .iter()
2551                                .map(|edge| edge.0)
2552                                .eq(edges.iter().copied())
2553                                .then_some(usize::from(id))
2554                        })
2555                        .collect::<Vec<_>>();
2556                    if !matching_ids.is_empty() {
2557                        return Err(SamplingSelectionError::ExcludedLmb {
2558                            graph: resolved.graph_name.clone(),
2559                            edges: edges.clone(),
2560                            basis_ids: matching_ids,
2561                            available: all_lmbs,
2562                        }
2563                        .into());
2564                    }
2565                }
2566            }
2567            basis_ids.clone()
2568        } else {
2569            self.lmb_basis_ids
2570                .iter()
2571                .map(|basis| usize::from(*basis))
2572                .collect()
2573        };
2574        let parent_lmb = self
2575            .graph
2576            .loop_momentum_basis
2577            .loop_edges
2578            .iter()
2579            .map(|edge| edge.0)
2580            .collect::<Vec<_>>();
2581        let massless_edges = self
2582            .graph
2583            .underlying
2584            .iter_edges()
2585            .filter_map(|(_, edge_id, edge)| {
2586                edge.data
2587                    .particle
2588                    .is_massless(&self.graph.model)
2589                    .then_some(edge_id.0)
2590            })
2591            .collect::<Vec<_>>();
2592        Ok(build_sampling_channel_catalogue_with_surfaces_and_coverage(
2593            resolved,
2594            &all_lmbs,
2595            &optimized_lmbs,
2596            surface_edges,
2597            &parent_lmb,
2598            if explicit_basis_ids.is_some() {
2599                &[]
2600            } else {
2601                &massless_edges
2602            },
2603        )?)
2604    }
2605
2606    /// Compile the selected catalogue against prepared master-graph
2607    /// kinematics. The context binds each surface's native equation and frame;
2608    /// any cut/side centers, radii and `t*` are prepared from its declared prior
2609    /// blocks inside the compiled map. This rejects missing or stale physical
2610    /// prerequisites before a mapped sample reaches the graph evaluator.
2611    pub fn compile_sampling_channels<T: FloatLike>(
2612        &self,
2613        catalogue: &SamplingChannelCatalogue,
2614        programs: &[SamplingChannelPrograms],
2615        context: &SamplingChannelCompileContext<T>,
2616    ) -> Result<Vec<CompiledSamplingChannel<T>>> {
2617        if context.master_graph != self.graph.name {
2618            return Err(eyre!(
2619                "sampling channel master graph `{}` does not match LMB setup graph `{}`",
2620                context.master_graph,
2621                self.graph.name
2622            ));
2623        }
2624        let mut context = context.clone();
2625        if let Some(masses) = self.master_edge_masses.as_ref() {
2626            context.edge_masses = masses
2627                .iter()
2628                .map(|(edge, mass)| (edge.0, mass.map_ref(|value| F::<T>::from_ff64(*value))))
2629                .collect();
2630        }
2631        catalogue.compile(&context, programs)
2632    }
2633
2634    /// Compile channels after preparing the external data needed by every
2635    /// selected-LMB-to-parent affine routing.  This is the required entry
2636    /// point when a channel catalogue contains more than the parent LMB;
2637    /// callers must pass external data from the same solved cut/orientation
2638    /// context as the map geometry.
2639    pub fn compile_sampling_channels_with_external<T: FloatLike>(
2640        &self,
2641        catalogue: &SamplingChannelCatalogue,
2642        programs: &[SamplingChannelPrograms],
2643        context: &SamplingChannelCompileContext<T>,
2644        external_momenta: &[[T; 4]],
2645    ) -> Result<Vec<CompiledSamplingChannel<T>>> {
2646        let mut context = context.clone();
2647        for (basis_id, edges) in catalogue.lmb_basis_entries() {
2648            if edges != context.parent_lmb.as_slice() {
2649                context.lmb_frame_maps.insert(
2650                    basis_id,
2651                    self.lmb_frame_map(
2652                        &self.all_bases[LmbIndex::from(basis_id)],
2653                        external_momenta,
2654                    )?,
2655                );
2656            }
2657        }
2658        for channel in catalogue.named_entries() {
2659            let edges = match &channel.map {
2660                SamplingMapDefinition::Lmb(edges) => edges,
2661                _ => &channel.definition.parent_lmb,
2662            };
2663            if edges == context.parent_lmb.as_slice() {
2664                continue;
2665            }
2666            let basis = self.sampling_parent_lmb(edges)?;
2667            context
2668                .lmb_frame_maps_by_edges
2669                .insert(edges.clone(), self.lmb_frame_map(&basis, external_momenta)?);
2670        }
2671        self.compile_sampling_channels(catalogue, programs, &context)
2672    }
2673
2674    /// Compile the selected channels and bind them to the raw-frame bridge.
2675    /// The process sampler supplies the prepared frame and external data.
2676    pub fn compile_sampling_channel_bridge<T: FloatLike>(
2677        &self,
2678        catalogue: &SamplingChannelCatalogue,
2679        programs: &[SamplingChannelPrograms],
2680        context: &SamplingChannelCompileContext<T>,
2681    ) -> Result<SamplingChannelBridge<T>> {
2682        let channels = self.compile_sampling_channels(catalogue, programs, context)?;
2683        let mode = match context.parameterization_settings.sampling_channels.weight {
2684            SamplingChannelWeight::MapDensity | SamplingChannelWeight::InverseJacobian => {
2685                SamplingPartitionMode::MapDensity
2686            }
2687            SamplingChannelWeight::Ose => SamplingPartitionMode::Ose,
2688            SamplingChannelWeight::SingularityProxy => SamplingPartitionMode::SingularityProxy,
2689        };
2690        SamplingChannelBridge::new_with_partition_mode(channels, mode).map_err(Into::into)
2691    }
2692
2693    /// External-data variant of [`Self::compile_sampling_channel_bridge`].
2694    pub fn compile_sampling_channel_bridge_with_external<T: FloatLike>(
2695        &self,
2696        catalogue: &SamplingChannelCatalogue,
2697        programs: &[SamplingChannelPrograms],
2698        context: &SamplingChannelCompileContext<T>,
2699        external_momenta: &[[T; 4]],
2700    ) -> Result<SamplingChannelBridge<T>> {
2701        let channels = self.compile_sampling_channels_with_external(
2702            catalogue,
2703            programs,
2704            context,
2705            external_momenta,
2706        )?;
2707        let mode = match context.parameterization_settings.sampling_channels.weight {
2708            SamplingChannelWeight::MapDensity | SamplingChannelWeight::InverseJacobian => {
2709                SamplingPartitionMode::MapDensity
2710            }
2711            SamplingChannelWeight::Ose => SamplingPartitionMode::Ose,
2712            SamplingChannelWeight::SingularityProxy => SamplingPartitionMode::SingularityProxy,
2713        };
2714        SamplingChannelBridge::new_with_partition_mode(channels, mode).map_err(Into::into)
2715    }
2716
2717    fn validate_lmb_basis_id(&self, basis_id: usize, graph_name: &str) -> Result<LmbIndex> {
2718        if basis_id >= self.all_bases.len() {
2719            return Err(eyre!(
2720                "Requested LMB basis id {} is out of range for graph '{}'; the graph has {} generated LMB bases.",
2721                basis_id,
2722                graph_name,
2723                self.all_bases.len()
2724            ));
2725        }
2726        Ok(LmbIndex::from(basis_id))
2727    }
2728
2729    /// Build the one canonical catalogue used by all channel-count and LMB
2730    /// lookup helpers during the runtime migration.  The old generated basis
2731    /// list is only input data for this catalogue; it is never enumerated as a
2732    /// second channel universe.
2733    pub fn canonical_sampling_catalogue(
2734        &self,
2735        graph_name: &str,
2736        parameterization_settings: &ParameterizationSettings,
2737    ) -> Result<SamplingChannelCatalogue> {
2738        let resolved = resolve_sampling_channel_selection(
2739            graph_name,
2740            &parameterization_settings.sampling_channels,
2741        )?;
2742        self.sampling_channel_catalogue(&resolved, parameterization_settings)
2743    }
2744
2745    /// Return the stable IDs from the one canonical catalogue.
2746    pub fn sampling_channel_ids(
2747        &self,
2748        graph_name: &str,
2749        parameterization_settings: &ParameterizationSettings,
2750    ) -> Result<Vec<SamplingChannelId>> {
2751        let catalogue = self.canonical_sampling_catalogue(graph_name, parameterization_settings)?;
2752        Ok((0..catalogue.entries.len())
2753            .map(SamplingChannelId::from)
2754            .collect())
2755    }
2756
2757    pub fn sampling_channel_label(
2758        &self,
2759        channel_id: SamplingChannelId,
2760        graph_name: &str,
2761        parameterization_settings: &ParameterizationSettings,
2762    ) -> Result<String> {
2763        let catalogue = self.canonical_sampling_catalogue(graph_name, parameterization_settings)?;
2764        let entry = catalogue.entries.get(channel_id.index()).ok_or_else(|| {
2765            eyre!(
2766                "Requested sampling channel {} is out of range for graph '{}'",
2767                channel_id.index(),
2768                graph_name
2769            )
2770        })?;
2771        Ok(match entry {
2772            SamplingCatalogueEntry::Lmb {
2773                basis_id, edges, ..
2774            } => {
2775                format!("lmb[{basis_id}] {:?}", edges)
2776            }
2777            SamplingCatalogueEntry::Surface { edges, .. } => format!("surface:{edges:?}"),
2778            SamplingCatalogueEntry::Named(channel) => channel.name.clone(),
2779        })
2780    }
2781
2782    pub fn sampling_channel_is_lmb(
2783        &self,
2784        channel_id: SamplingChannelId,
2785        graph_name: &str,
2786        parameterization_settings: &ParameterizationSettings,
2787    ) -> Result<bool> {
2788        let catalogue = self.canonical_sampling_catalogue(graph_name, parameterization_settings)?;
2789        let entry = catalogue.entries.get(channel_id.index()).ok_or_else(|| {
2790            eyre!(
2791                "Requested sampling channel {} is out of range for graph '{}'",
2792                channel_id.index(),
2793                graph_name
2794            )
2795        })?;
2796        Ok(matches!(entry, SamplingCatalogueEntry::Lmb { .. }))
2797    }
2798
2799    /// Return the generated LMB behind a canonical channel when that channel
2800    /// is an LMB entry. Graph-aware channels intentionally have no LMB index;
2801    /// callers that only expose LMB metadata can skip those entries without
2802    /// creating a second channel enumeration.
2803    pub fn sampling_channel_lmb_id(
2804        &self,
2805        channel_id: SamplingChannelId,
2806        graph_name: &str,
2807        parameterization_settings: &ParameterizationSettings,
2808    ) -> Result<Option<LmbIndex>> {
2809        let catalogue = self.canonical_sampling_catalogue(graph_name, parameterization_settings)?;
2810        let entry = catalogue.entries.get(channel_id.index()).ok_or_else(|| {
2811            eyre!(
2812                "Requested sampling channel {} is out of range for graph '{}'",
2813                channel_id.index(),
2814                graph_name
2815            )
2816        })?;
2817        match entry {
2818            SamplingCatalogueEntry::Lmb { basis_id, .. } => {
2819                self.validate_lmb_basis_id(*basis_id, graph_name).map(Some)
2820            }
2821            SamplingCatalogueEntry::Surface { .. } | SamplingCatalogueEntry::Named(_) => Ok(None),
2822        }
2823    }
2824
2825    /// Resolve a canonical sampling channel to its generated LMB basis.
2826    ///
2827    /// This strict accessor is intentionally named in terms of the canonical
2828    /// sampling catalogue.  It is only valid for channels whose map is an LMB;
2829    /// graph-aware channels must be evaluated through the sampling bridge.
2830    pub fn sampling_channel_lmb_basis_id(
2831        &self,
2832        channel_id: SamplingChannelId,
2833        graph_name: &str,
2834        parameterization_settings: &ParameterizationSettings,
2835    ) -> Result<LmbIndex> {
2836        self.sampling_channel_lmb_id(channel_id, graph_name, parameterization_settings)?
2837            .ok_or_else(|| {
2838                eyre!(
2839                    "Sampling channel {} for graph '{}' is graph-aware and has no generated LMB basis; use the canonical sampling bridge for this channel.",
2840                    channel_id.index(), graph_name
2841                )
2842            })
2843    }
2844
2845    pub fn sampling_channel_edge_ids(
2846        &self,
2847        channel_id: SamplingChannelId,
2848        graph_name: &str,
2849        parameterization_settings: &ParameterizationSettings,
2850    ) -> Result<SmallVec<[usize; 4]>> {
2851        let lmb_index = self
2852            .sampling_channel_lmb_id(channel_id, graph_name, parameterization_settings)?
2853            .ok_or_else(|| {
2854                eyre!(
2855                    "Sampling channel {} for graph '{}' is graph-aware and has no generated LMB basis; use the canonical sampling bridge for this channel.",
2856                    channel_id.index(), graph_name
2857                )
2858            })?;
2859        Ok(self.all_bases[lmb_index]
2860            .loop_edges
2861            .iter()
2862            .map(|edge_id| edge_id.0)
2863            .collect())
2864    }
2865
2866    pub fn selected_lmb_basis_id(
2867        &self,
2868        graph_name: &str,
2869        parameterization_settings: &ParameterizationSettings,
2870    ) -> Result<LmbIndex> {
2871        let channels = self.canonical_lmb_basis_entries(graph_name, parameterization_settings)?;
2872        channels.first().map(|(_, basis_id)| *basis_id).ok_or_else(|| {
2873            eyre!(
2874                "Could not select a default LMB basis for graph '{}'; the optimized LMB subset is empty.",
2875                graph_name
2876            )
2877        })
2878    }
2879
2880    /// Resolve generated bases for default sampling's LMB choice. IDs retain
2881    /// their catalogue positions; this view never creates another channel axis.
2882    /// Multichannel sampling uses the compiled bridge for every channel.
2883    fn canonical_lmb_basis_entries(
2884        &self,
2885        graph_name: &str,
2886        parameterization_settings: &ParameterizationSettings,
2887    ) -> Result<Vec<(SamplingChannelId, LmbIndex)>> {
2888        let catalogue = self.canonical_sampling_catalogue(graph_name, parameterization_settings)?;
2889        let mut channels = Vec::with_capacity(catalogue.entries.len());
2890        for (index, entry) in catalogue.entries.iter().enumerate() {
2891            match entry {
2892                SamplingCatalogueEntry::Lmb { basis_id, .. } => channels.push((
2893                    SamplingChannelId::from(index),
2894                    self.validate_lmb_basis_id(*basis_id, graph_name)?,
2895                )),
2896                SamplingCatalogueEntry::Surface { .. } | SamplingCatalogueEntry::Named(_) => {
2897                    return Err(eyre!(
2898                        "LMB-only weighting was requested for graph '{graph_name}', but canonical sampling channel {} is graph-aware; use the advanced discrete sampling route for this selection",
2899                        index
2900                    ));
2901                }
2902            }
2903        }
2904        Ok(channels)
2905    }
2906
2907    /// Resolve a complete user-ordered parent from a generated edge set without
2908    /// rebuilding its tree or external routing. Reorder a clone only: canonical
2909    /// catalogue IDs and the generated basis order are immutable.
2910    pub(crate) fn sampling_parent_lmb(&self, edges: &[usize]) -> Result<LoopMomentumBasis> {
2911        let selected = edges.iter().copied().collect::<BTreeSet<_>>();
2912        if edges.len() != self.graph.loop_momentum_basis.loop_edges.len()
2913            || selected.len() != edges.len()
2914        {
2915            return Err(eyre!(
2916                "sampling parent requires {} distinct loop edges, received {edges:?}",
2917                self.graph.loop_momentum_basis.loop_edges.len()
2918            ));
2919        }
2920        let candidates = self
2921            .all_bases
2922            .iter()
2923            .filter(|basis| {
2924                basis.loop_edges.len() == edges.len()
2925                    && basis
2926                        .loop_edges
2927                        .iter()
2928                        .all(|edge| selected.contains(&edge.0))
2929            })
2930            .collect_vec();
2931        let [basis] = candidates.as_slice() else {
2932            return Err(eyre!(
2933                "sampling parent {edges:?} matches {} generated bases for graph '{}'; expected one complete basis, available {:?}",
2934                candidates.len(),
2935                self.graph.name,
2936                self.all_bases
2937                    .iter()
2938                    .map(|basis| &basis.loop_edges)
2939                    .collect_vec()
2940            ));
2941        };
2942        let mut basis = (*basis).clone();
2943        for (index, edge) in edges.iter().enumerate() {
2944            let current = basis
2945                .loop_edges
2946                .iter_enumerated()
2947                .find(|(_, candidate)| candidate.0 == *edge)
2948                .unwrap()
2949                .0;
2950            basis.swap_loops(LoopIndex(index), current);
2951        }
2952        Ok(basis)
2953    }
2954
2955    /// Build the exact affine routing from one generated LMB into this setup's
2956    /// parent loop frame.  The integer edge signatures provide the linear
2957    /// block matrix; the supplied external momenta provide its translation.
2958    /// Keeping this operation on the graph-aware setup ensures that a compiled
2959    /// channel never mistakes selected-LMB coordinates for parent-frame
2960    /// coordinates.
2961    pub fn lmb_frame_map<T: FloatLike>(
2962        &self,
2963        channel_lmb: &LoopMomentumBasis,
2964        external_momenta: &[[T; 4]],
2965    ) -> Result<SamplingMapAffine<T>> {
2966        let parent_loop_edges = &self.graph.loop_momentum_basis.loop_edges;
2967        let channel_loop_count = channel_lmb.loop_edges.len();
2968        if parent_loop_edges.len() != channel_loop_count {
2969            return Err(eyre!(
2970                "cannot route LMB {:?} with {} loop blocks into parent frame with {} blocks",
2971                &channel_lmb.loop_edges,
2972                channel_loop_count,
2973                parent_loop_edges.len()
2974            ));
2975        }
2976        let dimension = 3 * channel_loop_count;
2977        let zero = F::<T>::default().zero();
2978        let mut matrix = vec![vec![zero.0.clone(); dimension]; dimension];
2979        let mut translation = vec![zero.0.clone(); dimension];
2980        for (parent_block, &edge_index) in parent_loop_edges.iter().enumerate() {
2981            let signature = &channel_lmb.edge_signatures[edge_index];
2982            let internal = signature.internal.to_momtrop_format();
2983            if internal.len() != channel_loop_count {
2984                return Err(eyre!(
2985                    "LMB {:?} edge {} has internal signature length {}, expected {}",
2986                    &channel_lmb.loop_edges,
2987                    edge_index.0,
2988                    internal.len(),
2989                    channel_loop_count
2990                ));
2991            }
2992            let external = signature.external.to_momtrop_format();
2993            if external.len() != external_momenta.len() {
2994                return Err(eyre!(
2995                    "LMB {:?} edge {} has external signature length {}, but {} external momenta were supplied",
2996                    &channel_lmb.loop_edges,
2997                    edge_index.0,
2998                    external.len(),
2999                    external_momenta.len()
3000                ));
3001            }
3002            for component in 0..3 {
3003                let row = 3 * parent_block + component;
3004                for (channel_block, coefficient) in internal.iter().enumerate() {
3005                    matrix[row][3 * channel_block + component] =
3006                        zero.from_i64(*coefficient as i64).0;
3007                }
3008                translation[row] = external
3009                    .iter()
3010                    .zip(external_momenta)
3011                    .map(|(coefficient, momentum)| {
3012                        zero.from_i64(*coefficient as i64) * F(momentum[component + 1].clone())
3013                    })
3014                    .fold(zero.clone(), |sum, value| sum + value)
3015                    .0;
3016            }
3017        }
3018        SamplingMapAffine::new(matrix, translation)
3019    }
3020
3021    fn reinterpret_loop_momenta_for_lmb_impl<T: FloatLike>(
3022        &self,
3023        lmb_index: LmbIndex,
3024        momentum_sample: &BareMomentumSample<T>,
3025        loop_mom_cache_id: usize,
3026    ) -> BareMomentumSample<T> {
3027        let channel_lmb = &self.all_bases[lmb_index];
3028        let new_loop_moms: LoopMomenta<F<T>> = self
3029            .graph
3030            .loop_momentum_basis
3031            .loop_edges
3032            .iter()
3033            .map(|&edge_index| {
3034                let signature_of_edge_channel_lmb = &channel_lmb.edge_signatures[edge_index];
3035                let loop_part = signature_of_edge_channel_lmb
3036                    .internal
3037                    .apply_typed(&momentum_sample.loop_moms);
3038                if momentum_sample.external_moms.is_empty() {
3039                    loop_part
3040                } else {
3041                    loop_part
3042                        + signature_of_edge_channel_lmb
3043                            .external
3044                            .apply(&momentum_sample.external_moms.raw)
3045                            .spatial
3046                }
3047            })
3048            .collect();
3049
3050        BareMomentumSample {
3051            loop_moms: new_loop_moms,
3052            dual_loop_moms: momentum_sample.dual_loop_moms.clone().map(|_dlm| todo!()),
3053            loop_mom_cache_id,
3054            loop_mom_base_cache_id: momentum_sample.loop_mom_base_cache_id,
3055            external_mom_cache_id: momentum_sample.external_mom_cache_id,
3056            external_mom_base_cache_id: momentum_sample.external_mom_base_cache_id,
3057            external_rotations: momentum_sample.external_rotations.clone(),
3058            external_moms: momentum_sample.external_moms.clone(),
3059            jacobian: momentum_sample.jacobian.clone(),
3060            orientation: momentum_sample.orientation,
3061            parameterization_branch: momentum_sample.parameterization_branch,
3062        }
3063    }
3064
3065    pub(crate) fn reinterpret_loop_momenta_for_lmb<T: FloatLike>(
3066        &self,
3067        lmb_index: LmbIndex,
3068        momentum_sample: &MomentumSample<T>,
3069        loop_mom_cache_id: usize,
3070    ) -> MomentumSample<T> {
3071        MomentumSample {
3072            sample: self.reinterpret_loop_momenta_for_lmb_impl(
3073                lmb_index,
3074                &momentum_sample.sample,
3075                loop_mom_cache_id,
3076            ),
3077        }
3078    }
3079}
3080
3081pub trait ProcessIntegrandImpl {
3082    type G: GraphTerm;
3083
3084    fn warm_up(&mut self, model: &Model) -> Result<()>;
3085
3086    /// Ordered generation choices; the first is the default for omitted level selections.
3087    fn generated_representations(&self) -> &[RepresentationMode] {
3088        &[RepresentationMode::Cff]
3089    }
3090
3091    /// Natural E_cm scale of the returned physical quantity. Custom graphs
3092    /// declare their integrated energy dimension; raw inputs omit spatial measure.
3093    fn stability_reference_scale<T: FloatLike>(
3094        &self,
3095        graph_id: usize,
3096        sample: &MomentumSample<T>,
3097        missing_measure_dimension: i32,
3098    ) -> Result<F<T>> {
3099        let settings = self.get_settings();
3100        let dimension = settings.stability.integrated_energy_dimension.ok_or_else(|| {
3101            eyre!("E_cm-relative physical stability requires `stability.integrated_energy_dimension` (after flux normalization, before output-unit conversion)")
3102        })?;
3103        let exponent = dimension.checked_sub(missing_measure_dimension).ok_or_else(|| {
3104            eyre!("stability energy dimension overflows after subtracting the missing spatial measure")
3105        })?;
3106        let mut scale = F::<T>::from_f64(settings.kinematics.e_cm).powi(exponent);
3107        if matches!(
3108            self.get_dependent_momenta_constructor(),
3109            DependentMomentaConstructor::CrossSection
3110        ) && !settings.general.disable_flux_factor
3111            && sample.external_moms().len() == 2
3112        {
3113            let graph = self.get_graph(graph_id).get_graph();
3114            let unit = settings
3115                .general
3116                .integral_unit
3117                .resolve_for_cross_section(graph.initial_state_cut.iter_edges(graph).count());
3118            scale *= cross_section::barn_conversion_factor(unit, sample.one());
3119        }
3120        Ok(scale)
3121    }
3122
3123    /// Choose the complete numerical proposal before any draw or physical retry.
3124    /// This conservative admission floor is not a pointwise map-error bound;
3125    /// density/root checks still fail explicitly when the fixed law is unresolved.
3126    fn sampling_source_policy(&self) -> Result<(SamplingPrecision, f64)> {
3127        let settings = self.get_settings();
3128        let budget = GammaLoopSample::<ArbPrec>::source_accuracy_budget(settings)?;
3129        let floor = F::<f128>::default().epsilon().sqrt().into_ff64().0;
3130        let parameterization = settings
3131            .sampling
3132            .get_parameterization_settings()
3133            .ok_or_else(|| eyre!("sampling source policy requires a channel parameterization"))?;
3134        let quad_eligible = budget >= floor
3135            && self.graph_count() > 0
3136            && parameterization.sampling_channels.weight != SamplingChannelWeight::SingularityProxy
3137            && (0..self.graph_count()).all(|id| {
3138                self.get_graph(id)
3139                    .sampling_setup()
3140                    .sampling_catalogue
3141                    .as_ref()
3142                    .is_some_and(SamplingChannelCatalogue::supports_fixed_quad_source)
3143            });
3144        let externals = settings
3145            .kinematics
3146            .externals
3147            .get_dependent_externals::<ArbPrec>(self.get_dependent_momenta_constructor())?;
3148        let mut inputs = externals
3149            .iter()
3150            .flat_map(|momentum| {
3151                [
3152                    momentum.temporal.value.clone(),
3153                    momentum.spatial.px.clone(),
3154                    momentum.spatial.py.clone(),
3155                    momentum.spatial.pz.clone(),
3156                ]
3157            })
3158            .collect_vec();
3159        let scale = F::<ArbPrec>::from_f64(settings.kinematics.e_cm);
3160        let b = F::<ArbPrec>::from_f64(parameterization.b);
3161        inputs.extend([
3162            scale.square(),
3163            &scale * &b,
3164            scale,
3165            b,
3166            F::<ArbPrec>::from_f64(parameterization.power),
3167            F::<ArbPrec>::from_f64(settings.lu_h_function.sigma),
3168        ]);
3169        for id in 0..self.graph_count() {
3170            for mass in self
3171                .get_graph(id)
3172                .get_real_mass_vector()?
3173                .iter()
3174                .filter_map(|(_, mass)| mass.as_ref())
3175            {
3176                let mass = F::<ArbPrec>::from_ff64(*mass);
3177                inputs.extend([mass.square(), mass]);
3178            }
3179        }
3180        if inputs
3181            .iter()
3182            .any(|value| value.is_nan() || value.is_infinite())
3183        {
3184            return Err(eyre!(
3185                "sampling source has nonfinite fixed kinematic, mass or parameterization input"
3186            ));
3187        }
3188        let quad_representable = inputs
3189            .iter()
3190            .all(|value| F::<f128>::from_arb(&value.0).is_ok());
3191        let fixed256_floor = F::<SamplingFloat>::default().epsilon().sqrt().into_ff64().0;
3192        Ok((
3193            if quad_eligible && quad_representable {
3194                SamplingPrecision::Quad
3195            } else if budget >= fixed256_floor
3196                && inputs
3197                    .iter()
3198                    .all(|value| F::<SamplingFloat>::from_arb(&value.0).is_ok())
3199            {
3200                SamplingPrecision::Fixed256
3201            } else {
3202                SamplingPrecision::Arb
3203            },
3204            budget,
3205        ))
3206    }
3207
3208    /// Compile fixed graph geometry after process warmup has prepared masses
3209    /// and improved externals. Publish only when the fixed canonical precision
3210    /// has every bridge valid. Native bindings remain available for component
3211    /// diagnostics; they do not define physical retry proposals. Radial roots
3212    /// and conditional cut contexts remain point-dependent runtime data.
3213    /// A failed canonical binding invalidates the epoch.
3214    fn warm_up_sampling(&mut self) -> Result<()> {
3215        for graph in self.get_terms_mut() {
3216            graph.sampling_setup_mut().invalidate_sampling();
3217        }
3218        if !self.get_settings().sampling.uses_sampling_channels() {
3219            return Ok(());
3220        }
3221        let parameterization = self
3222            .get_settings()
3223            .sampling
3224            .get_parameterization_settings()
3225            .expect("sampling channels require a parameterization");
3226        let prepared = (0..self.graph_count())
3227            .map(|id| {
3228                let graph = self.get_graph(id);
3229                let setup = graph.sampling_setup();
3230                let resolved = resolve_sampling_channel_selection(
3231                    &setup.graph.name,
3232                    &parameterization.sampling_channels,
3233                )?;
3234                // Inspect already resolved blocks without requiring a successful
3235                // binding at another precision; the original source will retain
3236                // one fixed canonical map for every physical rescue lane.
3237                let catalogue = setup.sampling_channel_catalogue(&resolved, &parameterization)?;
3238                let programs = catalogue.compile_programs(
3239                    3 * graph.get_graph().get_loop_number(),
3240                    &self.get_settings().lu_h_function,
3241                )?;
3242                Ok((catalogue, programs))
3243            })
3244            .collect::<Result<Vec<_>>>()?;
3245        for (graph, (catalogue, programs)) in self.get_terms_mut().zip(prepared) {
3246            let setup = graph.sampling_setup_mut();
3247            setup.sampling_catalogue.set(catalogue);
3248            setup.sampling_programs.set(programs);
3249        }
3250        let result = (|| {
3251            let (precision, budget) = self.sampling_source_policy()?;
3252            match precision {
3253                SamplingPrecision::Quad => self.prepare_sampling_precision::<f128>(),
3254                SamplingPrecision::Fixed256 => self.prepare_sampling_precision::<SamplingFloat>(),
3255                SamplingPrecision::Arb => self.prepare_sampling_precision::<ArbPrec>(),
3256                SamplingPrecision::Double => unreachable!("Double is never a canonical source"),
3257            }?;
3258            for graph in self.get_terms_mut() {
3259                graph
3260                    .sampling_setup_mut()
3261                    .sampling_source
3262                    .set((precision, budget));
3263            }
3264            crate::debug_tags!(#sampling;
3265                stage = "sampling_source_warmup", precision = %precision, accuracy_budget = budget,
3266                "selected fixed source for the complete integrand epoch"
3267            );
3268            Ok(())
3269        })();
3270        if result.is_ok() {
3271            // Preserve the configured native component APIs and their cached
3272            // numerical diagnostics, without requiring a second proposal law
3273            // to be usable before evaluating the canonical one.
3274            let precisions = self
3275                .get_settings()
3276                .stability
3277                .levels
3278                .iter()
3279                .map(|level| level.precision)
3280                .unique()
3281                .collect_vec();
3282            for precision in precisions {
3283                let native = match precision {
3284                    Precision::Double => self.prepare_sampling_precision::<f64>(),
3285                    Precision::Quad => self.prepare_sampling_precision::<f128>(),
3286                    Precision::Arb => self.prepare_sampling_precision::<ArbPrec>(),
3287                };
3288                if let Err(error) = native {
3289                    crate::debug_tags!(#sampling;
3290                        stage = "sampling_native_component_binding", precision = %precision,
3291                        error = %error, "native component binding unavailable; production uses the canonical draw"
3292                    );
3293                }
3294            }
3295        }
3296        if result.is_err() {
3297            // An epoch with no usable canonical binding publishes neither a
3298            // catalogue nor partial bindings, irrespective of native availability.
3299            for graph in self.get_terms_mut() {
3300                graph.sampling_setup_mut().invalidate_sampling();
3301            }
3302        }
3303        result
3304    }
3305
3306    /// Bind a configured or explicitly requested precision once per warmup epoch,
3307    /// retaining typed numerical failures as well as successes. Programs and
3308    /// canonical IDs are reused; geometry comes from the same native
3309    /// improved external data consumed by physical evaluation. Worker clones own
3310    /// their evaluator buffers, and a precision request never reparses metadata.
3311    fn prepare_sampling_precision<T: FloatLike>(&mut self) -> Result<()> {
3312        if !self.get_settings().sampling.uses_sampling_channels() {
3313            return Ok(());
3314        }
3315        if (0..self.graph_count()).all(|id| {
3316            T::sampling_bridge_cache(self.get_graph(id).sampling_setup())
3317                .as_ref()
3318                .is_some()
3319        }) {
3320            return (0..self.graph_count()).try_for_each(|id| {
3321                self.get_graph(id)
3322                    .sampling_setup()
3323                    .sampling_bridge::<T>()
3324                    .map(|_| ())
3325            });
3326        }
3327        let parameterization = self
3328            .get_settings()
3329            .sampling
3330            .get_parameterization_settings()
3331            .expect("sampling channels require a parameterization");
3332        let externals = self
3333            .get_settings()
3334            .kinematics
3335            .externals
3336            .get_dependent_externals::<T>(self.get_dependent_momenta_constructor())?;
3337        let external_momenta = externals
3338            .iter()
3339            .map(|momentum| {
3340                [
3341                    momentum.temporal.value.0.clone(),
3342                    momentum.spatial.px.0.clone(),
3343                    momentum.spatial.py.0.clone(),
3344                    momentum.spatial.pz.0.clone(),
3345                ]
3346            })
3347            .collect_vec();
3348        // The materialized draw, map consistency and physical host adoption
3349        // share one accuracy budget; native physical retries need no map binding.
3350        let (source_precision, source_budget) = self
3351            .get_graph(0)
3352            .sampling_setup()
3353            .sampling_source
3354            .as_ref()
3355            .copied()
3356            .map_or_else(|| self.sampling_source_policy(), Ok)?;
3357        let density_tolerance = if source_precision == T::sampling_precision() {
3358            source_budget
3359        } else {
3360            GammaLoopSample::<T>::relative_accuracy_budget(self.get_settings())
3361        };
3362        let bridges = (0..self.graph_count()).map(|id| {
3363            let graph = self.get_graph(id);
3364            let setup = graph.sampling_setup();
3365            if T::sampling_bridge_cache(setup).as_ref().is_some() { return Ok(None); }
3366            let catalogue = setup.sampling_catalogue.as_ref().ok_or_else(|| eyre!(
3367                "sampling catalogue for graph '{}' is not initialized; call warm_up after loading or changing runtime settings, model parameters, or graph routing", graph.name()
3368            ))?;
3369            let programs = setup.sampling_programs.as_ref().ok_or_else(|| eyre!(
3370                "sampling programs for graph '{}' are not initialized; call warm_up", graph.name()
3371            ))?;
3372            let bridge = graph.bind_sampling_bridge(catalogue, programs, &parameterization, self.get_settings(), &external_momenta, None)
3373                .and_then(|bridge| bridge.with_relative_density_tolerance(density_tolerance));
3374            match bridge {
3375                Ok(bridge) => Ok(Some(Ok(bridge))),
3376                Err(error) => match error.downcast_ref::<sampling::maps::SamplingEvaluationError>() {
3377                    Some(error) => Ok(Some(Err(error.clone()))),
3378                    None => Err(error),
3379                },
3380            }
3381        }).collect::<Result<Vec<_>>>()?;
3382        for (graph, binding) in self.get_terms_mut().zip(bridges) {
3383            if let Some(binding) = binding {
3384                crate::debug_tags!(#sampling;
3385                    stage = "sampling_bridge_warmup", graph = %graph.name(),
3386                    channels = ?binding.as_ref().ok().map(|bridge| bridge.channels().len()),
3387                    precision = std::any::type_name::<T>(), valid = binding.is_ok(),
3388                    "prepared graph sampling binding"
3389                );
3390                T::sampling_bridge_cache_mut(graph.sampling_setup_mut()).set(binding);
3391            }
3392        }
3393        (0..self.graph_count()).try_for_each(|id| {
3394            self.get_graph(id)
3395                .sampling_setup()
3396                .sampling_bridge::<T>()
3397                .map(|_| ())
3398        })
3399    }
3400
3401    fn get_rotations(&self) -> impl Iterator<Item = &Rotation>;
3402
3403    fn increment_loop_cache_id(&mut self, val: usize);
3404    fn loop_cache_id(&self) -> usize;
3405
3406    fn increment_external_cache_id(&mut self, val: usize);
3407    fn external_cache_id(&self) -> usize;
3408
3409    /// Signal that external momenta configuration has actually changed
3410    /// This increments the external cache ID to invalidate cached computations
3411    ///
3412    /// # Usage
3413    /// Call this method when:
3414    /// - You change the external momenta values in your Monte Carlo sampling
3415    /// - You switch to a different kinematic configuration
3416    /// - You want to force recomputation of cached polarizations/external quantities
3417    ///
3418    /// # Example
3419    /// ```rust,ignore
3420    /// // When you change external momenta in your sampling
3421    /// integrand.signal_external_momenta_changed();
3422    /// let new_sample = parameterize(&sample_point, &mut integrand, &mut first_draw_metadata)?;
3423    ///
3424    /// // Rotations will automatically get new cache IDs
3425    /// let rotated_samples = evaluate_all_rotations(&new_sample, &mut integrand, true)?;
3426    ///
3427    /// // Next iteration - revert to base configuration to reuse cache
3428    /// integrand.revert_to_base_external_cache_id();
3429    /// let next_sample = parameterize(&next_sample_point, &mut integrand, &mut next_draw_metadata)?;
3430    /// ```
3431    fn signal_external_momenta_changed(&mut self) {
3432        self.increment_external_cache_id(1);
3433    }
3434
3435    /// Get the current external cache ID for reuse (doesn't increment)
3436    ///
3437    /// This returns the current cache ID without incrementing it, allowing
3438    /// new samples to reuse cached computations for the same external
3439    /// momenta configuration.
3440    fn get_current_external_cache_id(&self) -> usize {
3441        self.external_cache_id()
3442    }
3443
3444    /// Revert to the base external cache ID for the current configuration
3445    ///
3446    /// This allows new samples to reuse the base cache ID when they represent
3447    /// the same underlying external momenta configuration (e.g., after rotations)
3448    ///
3449    /// # Usage
3450    /// Call this method when you want to create a new sample that represents
3451    /// the same base external momenta configuration as before, allowing reuse
3452    /// of cached polarizations and other external-dependent computations.
3453    ///
3454    /// # Example Cache Flow
3455    /// ```text
3456    /// 1. Initial sample:           cache_id = 0, base_cache_id = 0
3457    /// 2. Rotation 1:               cache_id = 1, base_cache_id = 0
3458    /// 3. Rotation 2:               cache_id = 2, base_cache_id = 0
3459    /// 4. revert_to_base():         cache_id = 0, base_cache_id = 0  // Reuse cache!
3460    /// 5. signal_changed():         cache_id = 3, base_cache_id = 3  // New base config
3461    /// 6. Rotation of new config:   cache_id = 4, base_cache_id = 3
3462    /// 7. revert_to_base():         cache_id = 3, base_cache_id = 3  // Reuse new base
3463    /// ```
3464    fn revert_to_base_external_cache_id(&mut self);
3465
3466    /// Check if external momenta caching is beneficial
3467    ///
3468    /// Returns true if the same external cache ID has been used multiple times,
3469    /// indicating that caching is providing benefits.
3470    fn is_external_caching_beneficial(&self) -> bool {
3471        // Simple heuristic: if we've created samples without incrementing
3472        // cache ID, then caching is being used
3473        self.external_cache_id() < self.loop_cache_id()
3474    }
3475
3476    /// Force a cache consistency check with detailed reporting
3477    fn debug_cache_state(&self, context: &str) {
3478        if std::env::var("GAMMALOOP_DEBUG_CACHE").is_ok() {
3479            let validation = self.validate_cache_consistency();
3480            let stats = self.get_cache_stats();
3481
3482            tracing::info!("🔍 DEBUG CACHE STATE at {}", context);
3483            tracing::info!("   Validation: {}", validation);
3484            tracing::info!("   Statistics: {}", stats);
3485
3486            if !validation.is_valid {
3487                tracing::error!("   ❌ CACHE INCONSISTENCY DETECTED!");
3488                panic!(
3489                    "Cache corruption at {}: {}",
3490                    context, validation.diagnostics
3491                );
3492            }
3493
3494            if validation.has_rotations {
3495                tracing::info!(
3496                    "   🔄 {} rotation variants from base cache_id {}",
3497                    validation.current_external_cache_id - validation.base_external_cache_id,
3498                    validation.base_external_cache_id
3499                );
3500            }
3501
3502            if stats.efficiency_ratio < 0.3 {
3503                tracing::warn!(
3504                    "   ⚠️ Very low cache efficiency: {:.1}%",
3505                    stats.efficiency_ratio * 100.0
3506                );
3507            } else if stats.efficiency_ratio > 0.8 {
3508                tracing::info!(
3509                    "   ✅ Excellent cache efficiency: {:.1}%",
3510                    stats.efficiency_ratio * 100.0
3511                );
3512            }
3513        }
3514    }
3515
3516    /// Get the base external cache ID for the current configuration
3517    fn get_base_external_cache_id(&self) -> usize;
3518
3519    /// Validate cache ID consistency and return diagnostics
3520    fn validate_cache_consistency(&self) -> CacheValidationResult {
3521        let current_id = self.external_cache_id();
3522        let base_id = self.get_base_external_cache_id();
3523        let loop_id = self.loop_cache_id();
3524
3525        let is_valid = base_id <= current_id;
3526        let has_rotations = current_id > base_id;
3527        let cache_efficiency = if loop_id > 0 {
3528            1.0 - (current_id as f64 / loop_id as f64)
3529        } else {
3530            0.0
3531        };
3532
3533        CacheValidationResult {
3534            is_valid,
3535            current_external_cache_id: current_id,
3536            base_external_cache_id: base_id,
3537            loop_cache_id: loop_id,
3538            has_rotations,
3539            cache_efficiency,
3540            diagnostics: if is_valid {
3541                "Cache IDs are consistent".to_string()
3542            } else {
3543                format!(
3544                    "ERROR: Base cache ID ({}) > Current cache ID ({})",
3545                    base_id, current_id
3546                )
3547            },
3548        }
3549    }
3550
3551    /// Get cache usage statistics for monitoring
3552    fn get_cache_stats(&self) -> CacheStats {
3553        let validation = self.validate_cache_consistency();
3554        CacheStats {
3555            total_external_increments: validation.current_external_cache_id,
3556            total_loop_increments: validation.loop_cache_id,
3557            base_configurations: validation.base_external_cache_id + 1,
3558            rotational_variants: validation.current_external_cache_id
3559                - validation.base_external_cache_id,
3560            efficiency_ratio: validation.cache_efficiency,
3561        }
3562    }
3563
3564    fn get_group_masters(&self) -> impl Iterator<Item = &Self::G>;
3565
3566    fn get_terms_mut(&mut self) -> impl Iterator<Item = &mut Self::G>;
3567    fn graph_count(&self) -> usize;
3568    fn get_settings(&self) -> &RuntimeSettings;
3569    fn get_master_graph(&self, group_id: GroupId) -> &Self::G;
3570    fn get_graph(&self, graph_id: usize) -> &Self::G;
3571    fn get_graph_mut(&mut self, graph_id: usize) -> &mut Self::G;
3572    fn graph_group_id_for_graph(&self, graph_id: usize) -> Option<usize>;
3573    fn get_group(&self, group_id: GroupId) -> &GraphGroup;
3574    fn get_group_structure(&self) -> &TiVec<GroupId, GraphGroup>;
3575    fn get_dependent_momenta_constructor(&self) -> DependentMomentaConstructor<'_>;
3576    fn take_event_processing_runtime(&mut self) -> Option<EventProcessingRuntime> {
3577        None
3578    }
3579    fn restore_event_processing_runtime(&mut self, _runtime: Option<EventProcessingRuntime>) {}
3580    fn event_processing_runtime(&self) -> Option<&EventProcessingRuntime> {
3581        None
3582    }
3583    fn event_processing_runtime_mut(&mut self) -> Option<&mut EventProcessingRuntime> {
3584        None
3585    }
3586    fn groups_default_sample_events_by_graph_group(&self) -> bool {
3587        false
3588    }
3589
3590    fn uses_explicit_orientation_sum_only(&self) -> bool {
3591        false
3592    }
3593
3594    // fn get_builder_cache(&self) -> &ParamBuilder<f64>;
3595}
3596
3597pub(crate) fn validate_process_runtime_settings(
3598    settings: &RuntimeSettings,
3599    explicit_orientation_sum_only: bool,
3600    generated_representations: &[RepresentationMode],
3601    fixed_on_shell_spatial_velocities: &[&[String; 3]],
3602) -> Result<()> {
3603    if generated_representations.is_empty() {
3604        return Err(eyre!("integrand has no generated 3D representations"));
3605    }
3606    if settings.stability.levels.is_empty() {
3607        return Err(eyre!(
3608            "`runtime.stability.levels` must contain at least one stability level"
3609        ));
3610    }
3611    for rotation in &settings.stability.rotation_axis {
3612        rotation.validate()?;
3613    }
3614    for velocity in fixed_on_shell_spatial_velocities {
3615        let velocity = velocity
3616            .iter()
3617            .map(|component| {
3618                Atom::parse(component, "gammalooprs::uv", Default::default())
3619                    .map_err(|error| eyre!(error))
3620            })
3621            .collect::<Result<Vec<_>>>()?;
3622        // Axis alignment is an exact statement about the generated reference,
3623        // not a floating-point angular tolerance. Settings f64 values are
3624        // converted to their exact binary rationals for this certificate.
3625        let aligned_with_coordinate_axis = |axis: usize| {
3626            velocity
3627                .iter()
3628                .enumerate()
3629                .all(|(index, value)| index == axis || value.is_zero())
3630        };
3631        for (index, rotation) in settings.stability.rotation_axis.iter().enumerate() {
3632            let preserves_reference = match rotation {
3633                RotationSetting::None {} => true,
3634                RotationSetting::Pi2X {} => aligned_with_coordinate_axis(0),
3635                RotationSetting::Pi2Y {} => aligned_with_coordinate_axis(1),
3636                RotationSetting::Pi2Z {} => aligned_with_coordinate_axis(2),
3637                RotationSetting::EulerAngles { alpha, beta, gamma } => [*alpha, *beta, *gamma]
3638                    .into_iter()
3639                    .enumerate()
3640                    .all(|(axis, angle)| angle == 0.0 || aligned_with_coordinate_axis(axis)),
3641                RotationSetting::AxisAngle { axis, cos_theta } => {
3642                    let axis = axis.map(|component| {
3643                        let exact = rug::Rational::from_f64(component)
3644                            .expect("validated finite rotation axis");
3645                        Atom::num(symbolica::domains::rational::Rational::from(exact))
3646                    });
3647                    *cos_theta == 1.0
3648                        || (0..3).all(|i| {
3649                            let j = (i + 1) % 3;
3650                            (&axis[i] * &velocity[j] - &axis[j] * &velocity[i]).is_zero()
3651                        })
3652                }
3653            };
3654            if !preserves_reference {
3655                return Err(eyre!(
3656                    "runtime.stability.rotation_axis[{index}] changes the generated fixed on-shell subtraction velocity {velocity:?}; use an axis_angle rotation about its spatial direction, or regenerate with a compatible fixed point"
3657                ));
3658            }
3659        }
3660    }
3661    if let Some(parameterization) = settings.sampling.get_parameterization_settings() {
3662        let alpha = parameterization.sampling_channels.alpha;
3663        if !alpha.is_finite() || alpha < 0.0 {
3664            return Err(eyre!(
3665                "sampling.alpha must be finite and nonnegative; got {alpha}"
3666            ));
3667        }
3668    }
3669    for (index, level) in settings.stability.levels.iter().enumerate() {
3670        level
3671            .resolved_representation(generated_representations)
3672            .wrap_err_with(|| {
3673                format!("runtime.stability.levels[{index}].three_dimensional_representation")
3674            })?;
3675        for (component, tolerance) in [
3676            ("re", level.ecm_relative_tolerance_for_re),
3677            ("im", level.ecm_relative_tolerance_for_im),
3678        ] {
3679            if !tolerance.is_finite() || tolerance < 0.0 {
3680                return Err(eyre!(
3681                    "`runtime.stability.levels[{index}].ecm_relative_tolerance_for_{component}` must be finite and nonnegative; got {tolerance}"
3682                ));
3683            }
3684        }
3685    }
3686    if settings.stability.levels.iter().any(|level| {
3687        level.ecm_relative_tolerance_for_re > 0.0 || level.ecm_relative_tolerance_for_im > 0.0
3688    }) && (!settings.kinematics.e_cm.is_finite() || settings.kinematics.e_cm <= 0.0)
3689    {
3690        return Err(eyre!(
3691            "E_cm-relative stability requires finite positive `runtime.kinematics.e_cm`"
3692        ));
3693    }
3694    // The shared process parameter layout always includes M, even when unused.
3695    if settings.general.numerator_sampling_scale == 0.0 {
3696        return Err(eyre!(
3697            "`runtime.general.numerator_sampling_scale` must be nonzero for the auxiliary sampling scale M"
3698        ));
3699    }
3700
3701    if !explicit_orientation_sum_only
3702        && !generated_representations.contains(&RepresentationMode::Ltd)
3703    {
3704        return Ok(());
3705    }
3706
3707    if settings.general.orientation_pat.pat.is_some() {
3708        return Err(eyre!(
3709            "For an integrand requiring a complete residue sum, `runtime.general.orientation_pat` must be unset"
3710        ));
3711    }
3712
3713    if let SamplingSettings::DiscreteGraphs(discrete_settings) = &settings.sampling
3714        && discrete_settings.sample_orientations
3715    {
3716        return Err(eyre!(
3717            "An integrand requiring a complete residue sum does not support runtime individual-orientation Monte Carlo sampling; set `runtime.sampling.orientations = \"summed\"`"
3718        ));
3719    }
3720
3721    Ok(())
3722}
3723
3724fn validate_orientation_catalog_group<'a>(
3725    group_id: GroupId,
3726    catalogs: impl IntoIterator<Item = (String, Vec<&'a str>)>,
3727) -> Result<()> {
3728    let mut catalogs = catalogs.into_iter();
3729    let Some((master_name, master_catalog)) = catalogs.next() else {
3730        return Ok(());
3731    };
3732    for (graph_name, catalog) in catalogs {
3733        if catalog != master_catalog {
3734            let first_difference = master_catalog
3735                .iter()
3736                .zip_longest(&catalog)
3737                .position(|entry| match entry {
3738                    itertools::EitherOrBoth::Both(left, right) => left != right,
3739                    itertools::EitherOrBoth::Left(_) | itertools::EitherOrBoth::Right(_) => true,
3740                })
3741                .unwrap_or_default();
3742            return Err(eyre!(
3743                "Runtime orientation Monte Carlo cannot use graph group {} because graph '{}' and master '{}' have different exact residue-map catalogs ({} versus {} selected maps; first difference at channel {}). Disable `sampling.sample_orientations` so each graph explicitly sums its own complete map catalog.",
3744                group_id.0,
3745                graph_name,
3746                master_name,
3747                catalog.len(),
3748                master_catalog.len(),
3749                first_difference,
3750            ));
3751        }
3752    }
3753    Ok(())
3754}
3755
3756pub(crate) fn validate_group_orientation_catalogs<G: GraphTerm>(
3757    settings: &RuntimeSettings,
3758    graph_terms: &[G],
3759    groups: &TiVec<GroupId, GraphGroup>,
3760) -> Result<()> {
3761    let SamplingSettings::DiscreteGraphs(discrete_settings) = &settings.sampling else {
3762        return Ok(());
3763    };
3764    if !discrete_settings.sample_orientations {
3765        return Ok(());
3766    }
3767
3768    for (group_id, group) in groups.iter_enumerated() {
3769        let master_id = group.master();
3770        validate_orientation_catalog_group(
3771            group_id,
3772            std::iter::once(master_id)
3773                .chain(group.into_iter().filter(|graph_id| *graph_id != master_id))
3774                .map(|graph_id| {
3775                    let graph = &graph_terms[graph_id];
3776                    (graph.name(), graph.selected_production_orientation_keys())
3777                }),
3778        )?;
3779    }
3780    Ok(())
3781}
3782
3783fn get_global_dimension_if_exists<I: ProcessIntegrandImpl>(integrand: &I) -> Option<usize> {
3784    if integrand
3785        .get_settings()
3786        .sampling
3787        .get_parameterization_settings()
3788        .is_none()
3789    {
3790        None
3791    } else {
3792        Some(
3793            integrand
3794                .get_master_graph(GroupId(0))
3795                .get_graph()
3796                .get_loop_number()
3797                * 3,
3798        )
3799    }
3800}
3801
3802pub trait GraphTerm {
3803    /// Prepare physical center decisions at the original Arb point. Geometry
3804    /// is channel-independent for the same selector-accepted cut set; explicit
3805    /// channel selectors retain their source metadata. Amplitudes own their
3806    /// separate overlap preparation.
3807    fn prepare_physical_overlaps(
3808        &mut self,
3809        _sample: &MomentumSample<ArbPrec>,
3810        _context: GraphTermEvaluationContext<'_, '_, ArbPrec>,
3811    ) -> Result<Option<TiVec<CutGroupId, Option<LUSharedOverlaps<ArbPrec>>>>> {
3812        Ok(None)
3813    }
3814
3815    fn evaluate<T: FloatLike>(
3816        &mut self,
3817        sample: &MomentumSample<T>,
3818        context: GraphTermEvaluationContext<'_, '_, T>,
3819    ) -> Result<GraphEvaluationResult<T>>;
3820
3821    fn name(&self) -> String;
3822    fn orientation_label(&self, orientation_id: usize) -> Option<String>;
3823    fn sampling_channel_label(
3824        &self,
3825        channel_id: SamplingChannelId,
3826        parameterization_settings: &ParameterizationSettings,
3827    ) -> Result<Option<String>>;
3828
3829    fn warm_up(&mut self, settings: &RuntimeSettings, model: &Model) -> Result<()>;
3830    fn get_graph(&self) -> &Graph;
3831    fn sampling_setup(&self) -> &LmbMultiChannelingSetup;
3832    fn sampling_setup_mut(&mut self) -> &mut LmbMultiChannelingSetup;
3833    fn get_num_orientations(&self) -> usize;
3834    fn production_orientation_keys(&self) -> &[String];
3835    fn selected_production_orientation_keys(&self) -> Vec<&str>;
3836    fn selected_lmb_basis_id(
3837        &self,
3838        parameterization_settings: &ParameterizationSettings,
3839    ) -> Result<LmbIndex>;
3840    fn get_tropical_sampler(&self) -> &SampleGenerator<3>;
3841    fn get_mut_param_builder(&mut self) -> &mut ParamBuilder<f64>;
3842    fn get_real_mass_vector(&self) -> Result<EdgeVec<Option<F<f64>>>>;
3843
3844    /// Compile the canonical full-frame sampling bridge for this graph.
3845    /// Process implementations own the graph-specific external signature and
3846    /// LMB setup; the sampler only supplies the already-resolved kinematics.
3847    fn compile_sampling_bridge<T: FloatLike>(
3848        &self,
3849        parameterization_settings: &ParameterizationSettings,
3850        settings: &RuntimeSettings,
3851        external_momenta: &[[T; 4]],
3852        orientation: Option<usize>,
3853    ) -> Result<SamplingChannelBridge<T>> {
3854        let resolved = resolve_sampling_channel_selection(
3855            &self.sampling_setup().graph.name,
3856            &parameterization_settings.sampling_channels,
3857        )?;
3858        let catalogue = self
3859            .sampling_setup()
3860            .sampling_channel_catalogue(&resolved, parameterization_settings)?;
3861        let programs = catalogue.compile_programs(
3862            3 * self.get_graph().get_loop_number(),
3863            &settings.lu_h_function,
3864        )?;
3865        self.bind_sampling_bridge(
3866            &catalogue,
3867            &programs,
3868            parameterization_settings,
3869            settings,
3870            external_momenta,
3871            orientation,
3872        )
3873    }
3874
3875    /// Bind the already resolved catalogue and compiled programs to native
3876    /// graph geometry. Canonical warmup and native component diagnostics reuse
3877    /// this one definition.
3878    fn bind_sampling_bridge<T: FloatLike>(
3879        &self,
3880        catalogue: &SamplingChannelCatalogue,
3881        programs: &[SamplingChannelPrograms],
3882        parameterization_settings: &ParameterizationSettings,
3883        settings: &RuntimeSettings,
3884        external_momenta: &[[T; 4]],
3885        orientation: Option<usize>,
3886    ) -> Result<SamplingChannelBridge<T>>;
3887
3888    fn sampling_channel_is_lmb(
3889        &self,
3890        channel_id: SamplingChannelId,
3891        parameterization_settings: &ParameterizationSettings,
3892    ) -> Result<bool>;
3893    fn sampling_channel_ids(
3894        &self,
3895        parameterization_settings: &ParameterizationSettings,
3896    ) -> Result<Vec<SamplingChannelId>>;
3897}
3898
3899#[derive(Clone, Copy)]
3900pub enum EvaluationTarget<'a> {
3901    Physical(&'a Model),
3902    Reference(&'a GaussianReferenceFunction),
3903    #[cfg(test)]
3904    SamplingLaw(&'a SamplingLawProbe<'a>),
3905}
3906
3907/// A fixed normalized density and controlled body failure for exercising the
3908/// real original-source retry owner. It never reads the current proposal's
3909/// Jacobian or partition, and is absent from production builds.
3910#[cfg(test)]
3911pub struct SamplingLawProbe<'a> {
3912    reference: &'a LmbMultiChannelingSetup,
3913    channel_id: SamplingChannelId,
3914    radial_coordinate: usize,
3915    retry_lower_half: bool,
3916    sign_coordinate: Option<usize>,
3917    alternating_graph_sign: bool,
3918    calls: [std::sync::atomic::AtomicUsize; 3],
3919}
3920
3921#[cfg(test)]
3922impl SamplingLawProbe<'_> {
3923    fn evaluate<T: FloatLike>(
3924        &self,
3925        sample: &MomentumSample<T>,
3926        rotation: &Rotation,
3927        canonical: Option<&DiscreteGraphSample<ArbPrec>>,
3928        graph_id: usize,
3929    ) -> Result<GraphEvaluationResult<T>> {
3930        let canonical =
3931            canonical.expect("production sampling probe receives the retained canonical row");
3932        let expected = canonical.sample.materialize::<T>()?.rotate(
3933            rotation,
3934            sample.sample.loop_mom_cache_id,
3935            sample.sample.external_mom_cache_id,
3936        );
3937        assert_eq!(
3938            sample.loop_moms(),
3939            expected.loop_moms(),
3940            "physical retry changed the canonical point"
3941        );
3942        assert_eq!(sample.external_moms(), expected.external_moms());
3943        assert_eq!(
3944            sample.jacobian(),
3945            expected.jacobian(),
3946            "physical retry changed the combined canonical factor"
3947        );
3948        let precision = T::sampling_precision();
3949        let index = match precision {
3950            SamplingPrecision::Double => 0,
3951            SamplingPrecision::Quad => 1,
3952            SamplingPrecision::Arb => 2,
3953            SamplingPrecision::Fixed256 => unreachable!("source precision is not a physical lane"),
3954        };
3955        self.calls[index].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3956        let point = sample
3957            .loop_moms()
3958            .iter()
3959            .flat_map(|momentum| {
3960                let momentum = rotation.inverse_rotate_three(momentum);
3961                [momentum.px.0, momentum.py.0, momentum.pz.0]
3962            })
3963            .collect_vec();
3964        let mut result = GraphEvaluationResult::zero(sample.zero());
3965        if let Some(reference) = self.reference.sampling_bridge::<T>()?.channels()
3966            [self.channel_id.index()]
3967        .map
3968        .inverse(&point)?
3969        {
3970            let half = sample.one() / sample.one().from_usize(2);
3971            result.integrand_result.re = if self.retry_lower_half
3972                && precision == SamplingPrecision::Double
3973                && F(reference.coordinates[self.radial_coordinate].clone()) < half
3974            {
3975                sample.zero() / sample.zero()
3976            } else {
3977                F(reference.inverse_jacobian)
3978            };
3979            if let Some(axis) = self.sign_coordinate {
3980                if F(reference.coordinates[axis].clone()) < half {
3981                    result.integrand_result.re = -result.integrand_result.re;
3982                }
3983                result.integrand_result.im = -result.integrand_result.re.clone();
3984            }
3985            if self.alternating_graph_sign && graph_id % 2 == 1 {
3986                result.integrand_result = -result.integrand_result;
3987            }
3988        }
3989        Ok(result)
3990    }
3991}
3992
3993struct EvaluationContext<'a, 'm> {
3994    representation: RepresentationMode,
3995    target: EvaluationTarget<'a>,
3996    settings: &'a RuntimeSettings,
3997    rotation: &'a Rotation,
3998    evaluation_metadata: &'m mut EvaluationMetaData,
3999}
4000
4001pub struct GraphTermEvaluationContext<'a, 'm, T: FloatLike> {
4002    pub representation: RepresentationMode,
4003    pub model: &'a Model,
4004    pub settings: &'a RuntimeSettings,
4005    pub event_processing_runtime: Option<&'m mut EventProcessingRuntime>,
4006    pub rotation: &'a Rotation,
4007    pub evaluation_metadata: &'m mut EvaluationMetaData,
4008    /// The canonical channel which mapped this point into the parent frame.
4009    /// Its sampling partition is applied outside the physical graph evaluation.
4010    pub sampling_channel: Option<SamplingChannelId>,
4011    pub graph_id: usize,
4012    pub(crate) prepared_lu_hosts: &'m [PreparedLUHost<T>],
4013    pub(crate) canonical_sample: Option<&'a DiscreteGraphSample<ArbPrec>>,
4014    pub(crate) sampling_accuracy_budget: f64,
4015}
4016
4017/// Evaluate one graph term using the canonical sampling channel contract.
4018fn evaluate_graph_term<T: FloatLike, I: ProcessIntegrandImpl>(
4019    integrand: &mut I,
4020    graph_id: usize,
4021    sample: &MomentumSample<T>,
4022    context: &mut EvaluationContext<'_, '_>,
4023    sampling_channel: Option<(SamplingChannelId, &[PreparedLUHost<T>])>,
4024    canonical_sample: Option<&DiscreteGraphSample<ArbPrec>>,
4025) -> Result<GraphEvaluationResult<T>> {
4026    if let Some((channel_id, hosts)) = sampling_channel {
4027        let graph = integrand.get_graph(graph_id);
4028        graph
4029            .sampling_setup()
4030            .sampling_catalogue
4031            .as_ref()
4032            .and_then(|catalogue| catalogue.entries.get(channel_id.index()))
4033            .ok_or_else(|| {
4034                eyre!(
4035                    "sampling channel {} is out of range for graph '{}'",
4036                    channel_id.index(),
4037                    graph.name()
4038                )
4039            })?;
4040        if hosts.iter().any(|host| {
4041            host.source.graph_id != graph_id
4042                || host.source.generating_channel != channel_id
4043                || host.source.target_channel != channel_id
4044        }) {
4045            return Err(eyre!(
4046                "selected LU host records do not belong to graph-group master {graph_id} and generating channel {channel_id:?}"
4047            ));
4048        }
4049        // Fixed canonical preparation owns the completed parent-frame map and
4050        // its selected host records. Physical lanes only adopt these records;
4051        // native map binding is not a prerequisite for evaluating the point.
4052    }
4053    // Every actual target and evaluator call counts, including failed attempts
4054    // and probe rotations. Physical diagnostic/event selection stays separate.
4055    // Host adoption is sampling work even though it runs inside this body.
4056    let sampling_before = context.evaluation_metadata.parameterization_time;
4057    let started = Instant::now();
4058    let result = (|| -> Result<GraphEvaluationResult<T>> {
4059        let model = match context.target {
4060            EvaluationTarget::Physical(model) => model,
4061            #[cfg(test)]
4062            EvaluationTarget::SamplingLaw(probe) => {
4063                return probe.evaluate(sample, context.rotation, canonical_sample, graph_id);
4064            }
4065            EvaluationTarget::Reference(reference) => {
4066                // A reference is defined in the original raw frame, including its
4067                // nonzero center. Stability rotations must not rotate the target
4068                // relative to the integration point.
4069                let raw_momenta = sample
4070                    .loop_moms()
4071                    .0
4072                    .iter()
4073                    .map(|momentum| context.rotation.inverse_rotate_three(momentum))
4074                    .collect::<LoopMomenta<_>>();
4075                let mut value = reference.evaluate(&raw_momenta)?
4076                    / sample.zero().from_usize(integrand.graph_count());
4077                if sample.sample.orientation.is_some() {
4078                    value /= sample
4079                        .zero()
4080                        .from_usize(integrand.get_graph(graph_id).get_num_orientations());
4081                }
4082                let radius_squared = raw_momenta.0.iter().fold(sample.zero(), |sum, momentum| {
4083                    sum + momentum.px.square() + momentum.py.square() + momentum.pz.square()
4084                });
4085                let mut result = GraphEvaluationResult::zero(sample.zero());
4086                result.reference_moments = Some(ReferenceMoments {
4087                    second_moment: value.clone() * radius_squared,
4088                    jacobian_min: 1.0,
4089                    jacobian_max: 1.0,
4090                });
4091                result.integrand_result = Complex::new_re(value);
4092                return Ok(result);
4093            }
4094        };
4095        let mut event_processing_runtime = integrand.take_event_processing_runtime();
4096        let result = {
4097            let graph_context = GraphTermEvaluationContext {
4098                representation: context.representation,
4099                model,
4100                settings: context.settings,
4101                event_processing_runtime: event_processing_runtime.as_mut(),
4102                rotation: context.rotation,
4103                evaluation_metadata: context.evaluation_metadata,
4104                sampling_channel: sampling_channel.map(|(channel_id, _)| channel_id),
4105                graph_id,
4106                prepared_lu_hosts: sampling_channel.map_or(&[], |(_, hosts)| hosts),
4107                canonical_sample,
4108                sampling_accuracy_budget: GammaLoopSample::<T>::relative_accuracy_budget(
4109                    context.settings,
4110                ),
4111            };
4112            integrand
4113                .get_graph_mut(graph_id)
4114                .evaluate(sample, graph_context)
4115        };
4116        integrand.restore_event_processing_runtime(event_processing_runtime);
4117        let mut result = result?;
4118        let graph_group_id = integrand.graph_group_id_for_graph(graph_id);
4119        for event_group in result.event_groups.iter_mut() {
4120            for event in event_group.iter_mut() {
4121                event.cut_info.graph_id = graph_id;
4122                event.cut_info.graph_group_id = graph_group_id;
4123            }
4124        }
4125        Ok(result)
4126    })();
4127    let nested_sampling = context.evaluation_metadata.parameterization_time - sampling_before;
4128    context.evaluation_metadata.integrand_evaluation_time +=
4129        started.elapsed().saturating_sub(nested_sampling);
4130    result
4131}
4132
4133fn selected_lmb_basis_for_default_sampling<I: ProcessIntegrandImpl>(
4134    integrand: &I,
4135    graph_id: usize,
4136    use_lmb_basis: bool,
4137) -> Result<Option<LmbIndex>> {
4138    if !use_lmb_basis {
4139        return Ok(None);
4140    }
4141
4142    let parameterization_settings = integrand
4143        .get_settings()
4144        .sampling
4145        .get_parameterization_settings()
4146        .expect("Default LMB-basis sampling requires a parameterization.");
4147    let group_id = integrand
4148        .graph_group_id_for_graph(graph_id)
4149        .map(GroupId)
4150        .ok_or_else(|| {
4151            eyre!(
4152                "Could not determine graph group for graph {} while selecting an LMB basis.",
4153                graph_id
4154            )
4155        })?;
4156
4157    Ok(Some(
4158        integrand
4159            .get_master_graph(group_id)
4160            .selected_lmb_basis_id(&parameterization_settings)?,
4161    ))
4162}
4163
4164fn evaluate_all_rotations<T: FloatLike, I: ProcessIntegrandImpl>(
4165    integrand: &mut I,
4166    target: EvaluationTarget<'_>,
4167    gammaloop_sample: &GammaLoopSample<T>,
4168    evaluation_metadata: &mut EvaluationMetaData,
4169    record_rotated_results: bool,
4170    canonical_sample: Option<&GammaLoopSample<ArbPrec>>,
4171    representation: RepresentationMode,
4172) -> Result<(Vec<GraphEvaluationResult<T>>, usize, Vec<RotatedEvaluation>)> {
4173    let rotations = integrand.get_rotations().cloned().collect_vec();
4174
4175    let cache = integrand.get_settings().general.enable_cache;
4176
4177    let mut loop_mom_cache_id = integrand.loop_cache_id();
4178    let mut external_mom_cache_id = integrand.external_cache_id();
4179
4180    // rotate the momenta for the stability tests.
4181    let gammaloop_samples: Vec<_> = rotations
4182        .iter()
4183        .map(|rotation| {
4184            if rotation.is_identity() {
4185                return gammaloop_sample.clone();
4186            }
4187            if cache {
4188                loop_mom_cache_id += gammaloop_sample.row_count();
4189                external_mom_cache_id += 1;
4190            }
4191            gammaloop_sample.rotate(rotation, loop_mom_cache_id, external_mom_cache_id)
4192        })
4193        .collect();
4194
4195    if cache {
4196        integrand.increment_loop_cache_id(rotations.len() * gammaloop_sample.row_count());
4197        integrand.increment_external_cache_id(rotations.len());
4198        // External configurations are shared by subsequent draws; restore the
4199        // base even if a later physical rotation returns a typed retry error.
4200        integrand.revert_to_base_external_cache_id();
4201    }
4202
4203    let primary_rotation_index = rotations
4204        .iter()
4205        .position(Rotation::is_identity)
4206        .unwrap_or(0);
4207    let mut evaluation_results: Vec<GraphEvaluationResult<T>> =
4208        Vec::with_capacity(gammaloop_samples.len());
4209    for (gammaloop_sample, rotation) in gammaloop_samples.iter().zip(rotations.iter()) {
4210        debug!("Evaluating rotation: {}", rotation.method);
4211        let result = evaluate_single(
4212            integrand,
4213            target,
4214            gammaloop_sample,
4215            rotation,
4216            evaluation_metadata,
4217            canonical_sample,
4218            representation,
4219        )?;
4220
4221        evaluation_results.push(result);
4222    }
4223
4224    for result in &evaluation_results {
4225        evaluation_metadata.event_processing_time += result.event_processing_time;
4226    }
4227
4228    let rotated_results = if record_rotated_results {
4229        rotations
4230            .iter()
4231            .zip(evaluation_results.iter())
4232            .map(|(rotation, result)| RotatedEvaluation {
4233                rotation: rotation.method.to_string(),
4234                result: complex_to_f64(&result.integrand_result),
4235            })
4236            .collect()
4237    } else {
4238        Vec::new()
4239    };
4240
4241    Ok((evaluation_results, primary_rotation_index, rotated_results))
4242}
4243
4244struct StabilityEvaluationContext<'a, 'm> {
4245    target: EvaluationTarget<'a>,
4246    source: &'a EvaluationSource<'a>,
4247    stability_level: &'a StabilityLevelSetting,
4248    max_eval: &'a Complex<F<f64>>,
4249    wgt: F<f64>,
4250    remaining_weight: Option<&'a F<ArbPrec>>,
4251    check_on_norm: bool,
4252    is_final_level: bool,
4253    evaluation_metadata: &'m mut EvaluationMetaData,
4254    record_rotated_results: bool,
4255    precision_label: &'static str,
4256    escalate_if_exact_zero: bool,
4257    check_real: bool,
4258    check_imag: bool,
4259    integral_estimate: Option<(f64, f64)>,
4260    min_abs_wgt_for_escalation: f64,
4261}
4262
4263impl StabilityEvaluationContext<'_, '_> {
4264    fn ecm_reference_scale<T: FloatLike, I: ProcessIntegrandImpl>(
4265        &self,
4266        integrand: &I,
4267        sample: &GammaLoopSample<T>,
4268    ) -> Result<Option<F<T>>> {
4269        if self.stability_level.ecm_relative_tolerance_for_re > 0.0
4270            || self.stability_level.ecm_relative_tolerance_for_im > 0.0
4271        {
4272            let e_cm = integrand.get_settings().kinematics.e_cm;
4273            if !e_cm.is_finite() || e_cm <= 0.0 {
4274                return Err(eyre!(
4275                    "E_cm-relative stability requires finite positive E_cm"
4276                ));
4277            }
4278            let momentum_sample = sample.get_default_sample();
4279            let missing_measure_dimension = if self.source.is_x_space() {
4280                0
4281            } else {
4282                let loops = momentum_sample.loop_moms().0.len();
4283                if sample
4284                    .groups
4285                    .iter()
4286                    .flat_map(|(_, rows)| rows)
4287                    .any(|row| row.sample.loop_moms().0.len() != loops)
4288                {
4289                    return Err(eyre!(
4290                        "E_cm-relative stability cannot compare a raw momentum sum with different spatial dimensions"
4291                    ));
4292                }
4293                i32::try_from(loops)?.checked_mul(3).ok_or_else(|| {
4294                    eyre!("missing spatial measure dimension exceeds the supported integer range")
4295                })?
4296            };
4297            let scale = match self.target {
4298                EvaluationTarget::Physical(_) => integrand.stability_reference_scale(
4299                    sample.groups[0].1[0].graph_id,
4300                    momentum_sample,
4301                    missing_measure_dimension,
4302                )?,
4303                EvaluationTarget::Reference(_) => {
4304                    F::<T>::from_f64(integrand.get_settings().kinematics.e_cm)
4305                        .powi(-missing_measure_dimension)
4306                }
4307                #[cfg(test)]
4308                EvaluationTarget::SamplingLaw(_) => momentum_sample.one(),
4309            };
4310            if !scale.0.is_finite() || scale <= momentum_sample.zero() {
4311                return Err(eyre!(
4312                    "E_cm-relative stability scale must be finite and positive"
4313                ));
4314            }
4315            Ok(Some(scale))
4316        } else {
4317            Ok(None)
4318        }
4319    }
4320}
4321
4322fn evaluate_stability_level_precise<T: FloatLike, I: ProcessIntegrandImpl>(
4323    integrand: &mut I,
4324    context: &mut StabilityEvaluationContext<'_, '_>,
4325) -> Result<PreciseStabilityLevelResult<T>> {
4326    let level_start = Instant::now();
4327    let representation = context
4328        .stability_level
4329        .resolved_representation(integrand.generated_representations())?;
4330    let evaluated = if context
4331        .evaluation_metadata
4332        .threshold_counterterm_error
4333        .is_some()
4334    {
4335        None
4336    } else {
4337        let evaluated = (|| {
4338            let sample = context
4339                .source
4340                .build_gamma_sample::<T, I>(integrand, context.evaluation_metadata)?;
4341            let ecm_scale = context.ecm_reference_scale(integrand, &sample)?;
4342            debug!("{} parameterization succeeded", context.precision_label);
4343            debug!("jacobian: {:+16e}", sample.get_default_sample().jacobian());
4344            let rotations = evaluate_all_rotations(
4345                integrand,
4346                context.target,
4347                &sample,
4348                context.evaluation_metadata,
4349                context.record_rotated_results,
4350                context.source.canonical_sample(),
4351                representation,
4352            )?;
4353            Ok::<_, eyre::Report>((sample, ecm_scale, rotations))
4354        })();
4355        match evaluated {
4356            Ok(evaluated) => Some(evaluated),
4357            Err(error)
4358                if matches!(context.target, EvaluationTarget::Physical(_))
4359                    && matches!(
4360                        error.downcast_ref::<sampling::maps::SamplingEvaluationError>(),
4361                        Some(
4362                            sampling::maps::SamplingEvaluationError::UncertifiedOverlap { .. }
4363                                | sampling::maps::SamplingEvaluationError::UncertifiedRoot { .. }
4364                        )
4365                    ) =>
4366            {
4367                // A failed native pass may have populated only part of its
4368                // point caches; use fresh identities for the following lane.
4369                integrand.increment_loop_cache_id(integrand.get_rotations().count() + 1);
4370                integrand.revert_to_base_external_cache_id();
4371                context
4372                    .evaluation_metadata
4373                    .record_threshold_counterterm_error(format!("{error:#}"));
4374                None
4375            }
4376            Err(error) => return Err(error),
4377        }
4378    };
4379    if context
4380        .evaluation_metadata
4381        .threshold_counterterm_error
4382        .is_some()
4383    {
4384        // An uncertified cut/overlap invalidates the whole sample, including
4385        // partial channels and events. Retry native precision through the same
4386        // driver; an exhausted failure remains explicitly marked NaN.
4387        let mut graph_result = GraphEvaluationResult::zero(F::<T>::from_f64(0.0));
4388        graph_result.integrand_result = Complex::new(F::from_f64(f64::NAN), F::from_f64(f64::NAN));
4389        return Ok(PreciseStabilityLevelResult {
4390            result: graph_result.integrand_result.clone(),
4391            graph_result,
4392            stability_level_used: context.stability_level.precision,
4393            representation,
4394            estimated_relative_accuracy: None,
4395            sample_count: 0,
4396            total_time: level_start.elapsed(),
4397            parameterization_jacobian: context.source.is_x_space().then(|| F::from_f64(1.0)),
4398            is_stable: false,
4399            rotated_results: Vec::new(),
4400        });
4401    }
4402    let (gammaloop_sample, ecm_scale, (graph_results, primary_rotation_index, rotated_results)) =
4403        evaluated.expect("a successful level has evaluated rotations");
4404    let results = graph_results
4405        .iter()
4406        .map(|result| result.integrand_result.clone())
4407        .collect_vec();
4408
4409    let mut max_eval = complex_from_f64::<T>(context.max_eval);
4410    if matches!(context.target, EvaluationTarget::Reference(_)) {
4411        // Integration reports a second observable in Im. Its scale must not
4412        // alter the Gaussian value's existing independent stability check.
4413        max_eval.im = max_eval.im.zero();
4414    }
4415    let mut wgt = F::<T>::from_ff64(context.wgt);
4416    if let Some(remaining_weight) = context.remaining_weight {
4417        // A profiler applies its measure after native evaluation. Include it
4418        // in every stability bound before accepting an underflowed component.
4419        wgt *= F::<T>::from_arb(&remaining_weight.0)?;
4420    }
4421
4422    let (average_result, mut estimated_relative_accuracy, mut is_stable, _instability_reason) =
4423        if context.check_on_norm {
4424            stability_check_on_norm_components_with_estimate(
4425                ecm_scale.as_ref(),
4426                &results,
4427                context.stability_level,
4428                max_eval,
4429                wgt.clone(),
4430                context.is_final_level,
4431                context.escalate_if_exact_zero,
4432                context.check_real,
4433                context.check_imag,
4434                context.integral_estimate,
4435                context.min_abs_wgt_for_escalation,
4436            )
4437        } else {
4438            stability_check_components_with_estimate(
4439                ecm_scale.as_ref(),
4440                &results,
4441                context.stability_level,
4442                max_eval,
4443                wgt.clone(),
4444                context.is_final_level,
4445                context.escalate_if_exact_zero,
4446                context.check_real,
4447                context.check_imag,
4448                context.integral_estimate,
4449                context.min_abs_wgt_for_escalation,
4450            )
4451        };
4452
4453    let mut graph_result = graph_results[primary_rotation_index].clone();
4454    graph_result.integrand_result = average_result.clone();
4455    if graph_result.absolute_integrand_result.is_some() {
4456        // The physical absolute integral is a separate observable: cancellation
4457        // between different channel points must not hide an unstable absolute
4458        // contribution. Reuse the configured component/norm criterion, without
4459        // borrowing the signed integral's maximum-weight escalation scale.
4460        // Helicity amplitudes acquire a common phase under rotation. Their
4461        // cancellation guard therefore uses sum_c |z_c|, while the public
4462        // |Re|/|Im| report remains the primary probe's physical components.
4463        let check_channel_norm = graph_result.channel_norm_sum.is_some();
4464        let absolute_results = graph_results
4465            .iter()
4466            .map(|result| {
4467                if check_channel_norm {
4468                    result.channel_norm_sum.clone().map(Complex::new_re)
4469                } else {
4470                    result.absolute_integrand_result.clone()
4471                }
4472                .ok_or_else(|| {
4473                    eyre!("sampling-channel absolute contribution missing from a rotation")
4474                })
4475            })
4476            .collect::<Result<Vec<_>>>()?;
4477        let (absolute_check_real, absolute_check_imag) = if check_channel_norm {
4478            (true, false)
4479        } else {
4480            (context.check_real, context.check_imag)
4481        };
4482        let mut absolute_level = *context.stability_level;
4483        if check_channel_norm {
4484            // Either component can carry the norm after a phase rotation; a
4485            // one-component absolute allowance must not relax this monitor.
4486            absolute_level.ecm_relative_tolerance_for_re = absolute_level
4487                .ecm_relative_tolerance_for_re
4488                .min(absolute_level.ecm_relative_tolerance_for_im);
4489        }
4490        let check = if context.check_on_norm {
4491            stability_check_on_norm_components_with_estimate::<T>
4492        } else {
4493            stability_check_components_with_estimate::<T>
4494        };
4495        let (absolute, accuracy, stable, _) = check(
4496            ecm_scale.as_ref(),
4497            &absolute_results,
4498            &absolute_level,
4499            Complex::new_re(average_result.re.zero()),
4500            wgt.clone(),
4501            context.is_final_level,
4502            context.escalate_if_exact_zero,
4503            absolute_check_real,
4504            absolute_check_imag,
4505            context.integral_estimate,
4506            context.min_abs_wgt_for_escalation,
4507        );
4508        if !check_channel_norm {
4509            graph_result.absolute_integrand_result = Some(absolute);
4510        }
4511        estimated_relative_accuracy = estimated_relative_accuracy
4512            .into_iter()
4513            .chain(accuracy)
4514            .reduce(|left, right| left.max(right));
4515        is_stable &= stable;
4516    }
4517    if matches!(context.target, EvaluationTarget::Reference(_)) {
4518        // The Gaussian value and its raw-momentum moment are independent
4519        // observables. Reuse the scalar stability owner for the moment too;
4520        // agreement of the value alone cannot certify rotation invariance.
4521        let moments = graph_results
4522            .iter()
4523            .map(|result| {
4524                result
4525                    .reference_moments
4526                    .as_ref()
4527                    .map(|moments| Complex::new_re(moments.second_moment.clone()))
4528                    .ok_or_else(|| eyre!("reference acceptance produced no mapped moment"))
4529            })
4530            .collect::<Result<Vec<_>>>()?;
4531        let mut moment_level = *context.stability_level;
4532        moment_level.required_precision_for_re = moment_level
4533            .required_precision_for_re
4534            .min(moment_level.required_precision_for_im);
4535        moment_level.required_precision_for_im = moment_level.required_precision_for_re;
4536        // Like its relative precision, the independent moment uses the stricter
4537        // component allowance: a Re-only allowance does not relax this oracle.
4538        moment_level.ecm_relative_tolerance_for_re = moment_level
4539            .ecm_relative_tolerance_for_re
4540            .min(moment_level.ecm_relative_tolerance_for_im);
4541        moment_level.ecm_relative_tolerance_for_im = moment_level.ecm_relative_tolerance_for_re;
4542        // The raw second moment has two additional energy dimensions. Its
4543        // independent oracle uses E_cm^2 times the reference normalization scale.
4544        let moment_scale = ecm_scale.as_ref().map(|scale| {
4545            scale * F::<T>::from_f64(integrand.get_settings().kinematics.e_cm).square()
4546        });
4547        if moment_scale
4548            .as_ref()
4549            .is_some_and(|scale| !scale.0.is_finite() || scale <= &scale.zero())
4550        {
4551            return Err(eyre!(
4552                "E_cm-relative reference-moment scale must be finite and positive"
4553            ));
4554        }
4555        let (moment, accuracy, stable, _) = stability_check_with_estimate(
4556            moment_scale.as_ref(),
4557            &moments,
4558            &moment_level,
4559            Complex::new_re(average_result.re.zero()),
4560            wgt.clone(),
4561            context.is_final_level,
4562            context.escalate_if_exact_zero,
4563            context.integral_estimate,
4564            context.min_abs_wgt_for_escalation,
4565        );
4566        graph_result
4567            .reference_moments
4568            .as_mut()
4569            .unwrap()
4570            .second_moment = moment.re;
4571        estimated_relative_accuracy = estimated_relative_accuracy
4572            .into_iter()
4573            .chain(accuracy)
4574            .reduce(|left, right| left.max(right));
4575        is_stable &= stable;
4576    }
4577
4578    Ok(PreciseStabilityLevelResult {
4579        result: average_result,
4580        graph_result,
4581        stability_level_used: context.stability_level.precision,
4582        representation,
4583        estimated_relative_accuracy,
4584        sample_count: results.len(),
4585        total_time: level_start.elapsed(),
4586        parameterization_jacobian: context
4587            .source
4588            .is_x_space()
4589            .then(|| gammaloop_sample.get_default_sample().one()),
4590        is_stable,
4591        rotated_results,
4592    })
4593}
4594
4595/// Result of cache validation checks
4596#[derive(Debug, Clone)]
4597pub struct CacheValidationResult {
4598    pub is_valid: bool,
4599    pub current_external_cache_id: usize,
4600    pub base_external_cache_id: usize,
4601    pub loop_cache_id: usize,
4602    pub has_rotations: bool,
4603    pub cache_efficiency: f64,
4604    pub diagnostics: String,
4605}
4606
4607impl std::fmt::Display for CacheValidationResult {
4608    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4609        write!(
4610            f,
4611            "Cache Validation: {} | Current: {} | Base: {} | Loop: {} | Rotations: {} | Efficiency: {:.1}%",
4612            if self.is_valid { "✓" } else { "✗" },
4613            self.current_external_cache_id,
4614            self.base_external_cache_id,
4615            self.loop_cache_id,
4616            if self.has_rotations { "Yes" } else { "No" },
4617            self.cache_efficiency * 100.0
4618        )
4619    }
4620}
4621
4622/// Cache usage statistics
4623#[derive(Debug, Clone)]
4624pub struct CacheStats {
4625    pub total_external_increments: usize,
4626    pub total_loop_increments: usize,
4627    pub base_configurations: usize,
4628    pub rotational_variants: usize,
4629    pub efficiency_ratio: f64,
4630}
4631
4632impl std::fmt::Display for CacheStats {
4633    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4634        write!(
4635            f,
4636            "Cache Stats: {} base configs, {} rotations, {} loop increments, {:.1}% efficiency",
4637            self.base_configurations,
4638            self.rotational_variants,
4639            self.total_loop_increments,
4640            self.efficiency_ratio * 100.0
4641        )
4642    }
4643}
4644
4645/// Helper macro for cache debugging
4646#[macro_export]
4647macro_rules! debug_cache {
4648    ($integrand:expr, $msg:expr) => {
4649        let validation = $integrand.validate_cache_consistency();
4650        tracing::debug!("{}: {}", $msg, validation);
4651    };
4652}
4653
4654/// Helper macro for cache monitoring with custom conditions
4655#[macro_export]
4656macro_rules! monitor_cache {
4657    ($integrand:expr, $condition:expr, $msg:expr) => {
4658        if $condition {
4659            let stats = $integrand.get_cache_stats();
4660            tracing::info!("{}: {}", $msg, stats);
4661        }
4662    };
4663}
4664
4665/// Helper macro for missed cache hit detection in debug mode
4666#[macro_export]
4667macro_rules! debug_cache_search {
4668    ($integrand:expr, $msg:expr) => {
4669        if std::env::var("GAMMALOOP_DEBUG_CACHE").is_ok() {
4670            let validation = $integrand.validate_cache_consistency();
4671            if !validation.is_valid {
4672                tracing::error!(
4673                    "CACHE CORRUPTION DETECTED at {}: {}",
4674                    $msg,
4675                    validation.diagnostics
4676                );
4677            } else {
4678                tracing::debug!("Cache search at {}: {}", $msg, validation);
4679            }
4680        }
4681    };
4682}
4683
4684/// Helper macro for cache efficiency warnings
4685#[macro_export]
4686macro_rules! warn_cache_efficiency {
4687    ($integrand:expr, $threshold:expr, $msg:expr) => {
4688        let stats = $integrand.get_cache_stats();
4689        if stats.efficiency_ratio < $threshold {
4690            tracing::warn!(
4691                "⚠️ Low cache efficiency at {}: {:.1}% (threshold: {:.1}%)",
4692                $msg,
4693                stats.efficiency_ratio * 100.0,
4694                $threshold * 100.0
4695            );
4696            tracing::warn!("   Cache stats: {}", stats);
4697        }
4698    };
4699}
4700
4701fn evaluate_single<T: FloatLike, I: ProcessIntegrandImpl>(
4702    integrand: &mut I,
4703    target: EvaluationTarget<'_>,
4704    gammaloop_sample: &GammaLoopSample<T>,
4705    rotation: &Rotation,
4706    evaluation_metadata: &mut EvaluationMetaData,
4707    canonical_sample: Option<&GammaLoopSample<ArbPrec>>,
4708    representation: RepresentationMode,
4709) -> Result<GraphEvaluationResult<T>> {
4710    let settings = integrand.get_settings().clone();
4711    let zero = gammaloop_sample.get_default_sample().zero();
4712    let mut context = EvaluationContext {
4713        representation,
4714        target,
4715        settings: &settings,
4716        rotation,
4717        evaluation_metadata,
4718    };
4719    let mut result = GraphEvaluationResult::zero(zero.clone());
4720    let mut absolute = Complex::new_re(zero.clone());
4721    let mut channel_norm_sum = (matches!(target, EvaluationTarget::Physical(_))
4722        && settings.stability.check_on_norm
4723        && !matches!(
4724            integrand.get_dependent_momenta_constructor(),
4725            DependentMomentaConstructor::CrossSection
4726        ))
4727    .then(|| zero.clone());
4728    let mut has_sampling_channels = false;
4729    for (group_index, (group_id, rows)) in gammaloop_sample.groups.iter().enumerate() {
4730        let mut grouped_events = crate::observables::GenericEventGroup::default();
4731        let mut channel_values = BTreeMap::new();
4732        for (row_index, row) in rows.iter().enumerate() {
4733            let canonical_row =
4734                canonical_sample.map(|sample| &sample.groups[group_index].1[row_index]);
4735            let mut graph_result = evaluate_graph_term(
4736                integrand,
4737                row.graph_id,
4738                &row.sample,
4739                &mut context,
4740                row.channel_id
4741                    .map(|id| (id, row.prepared_lu_hosts.as_slice())),
4742                canonical_row,
4743            )?;
4744            // Preserve tropical's integrand-only compensation. All ordinary
4745            // map/partition factors reach integrand, events and reference moments
4746            // once through the same per-row owner, including explicit sums.
4747            graph_result.integrand_result *= Complex::new_re(row.integrand_prefactor.clone());
4748            graph_result.apply_sampling_factor(row.sample.jacobian());
4749            has_sampling_channels |= row.channel_id.is_some();
4750            // The source owner prepares one master point per channel and clones
4751            // it across group members. Sum their complete physical bodies here;
4752            // only distinct channel points contribute separate absolute values.
4753            *channel_values
4754                .entry(row.channel_id)
4755                .or_insert_with(|| Complex::new_re(zero.clone())) +=
4756                graph_result.integrand_result.clone();
4757            if group_id.is_some() {
4758                for mut events in graph_result.event_groups.drain(..) {
4759                    grouped_events.append(&mut events);
4760                }
4761            }
4762            result.merge_in_place(graph_result);
4763        }
4764        if !grouped_events.is_empty() {
4765            result.event_groups.push(grouped_events);
4766        }
4767        for value in channel_values.into_values() {
4768            if let Some(norm) = &mut channel_norm_sum {
4769                *norm += value.re.hypot(&value.im);
4770            }
4771            absolute += Complex::new(value.re.abs(), value.im.abs());
4772        }
4773    }
4774    result.channel_norm_sum = channel_norm_sum.map(|norm| {
4775        if has_sampling_channels {
4776            norm
4777        } else {
4778            result
4779                .integrand_result
4780                .re
4781                .hypot(&result.integrand_result.im)
4782        }
4783    });
4784    result.absolute_integrand_result = Some(if has_sampling_channels {
4785        absolute
4786    } else {
4787        Complex::new(
4788            result.integrand_result.re.abs(),
4789            result.integrand_result.im.abs(),
4790        )
4791    });
4792    Ok(result)
4793}
4794
4795fn create_grid_for_graph<G: GraphTerm>(
4796    graph_term: &G,
4797    settings: &DiscreteGraphSamplingSettings,
4798    integrator_settings: &IntegratorSettings,
4799) -> Grid<F<f64>> {
4800    match &settings.sampling_type {
4801        DiscreteGraphSamplingType::Default(_) | DiscreteGraphSamplingType::MultiChanneling(_) => {
4802            let continuous_grid = create_default_continous_grid(graph_term, integrator_settings);
4803
4804            if settings.sample_orientations {
4805                let continuous_grids = (0..graph_term.get_num_orientations())
4806                    .map(|_| Some(continuous_grid.clone()))
4807                    .collect();
4808
4809                Grid::Discrete(
4810                    DiscreteGrid::new(
4811                        continuous_grids,
4812                        F(integrator_settings.max_prob_ratio),
4813                        integrator_settings.train_on_avg,
4814                    )
4815                    .expect("orientation sampling requires at least one orientation"),
4816                )
4817            } else {
4818                continuous_grid
4819            }
4820        }
4821        DiscreteGraphSamplingType::SamplingMultiChanneling(multichanneling_settings) => {
4822            let continuous_grid = create_default_continous_grid(graph_term, integrator_settings);
4823            let channel_count = graph_term
4824                .sampling_channel_ids(&multichanneling_settings.parameterization_settings)
4825                .map(|channel_ids| channel_ids.len())
4826                .unwrap_or_else(|error| panic!("cannot build the sampling channel grid: {error}"));
4827            let lmb_channel_grid = Grid::Discrete(
4828                DiscreteGrid::new(
4829                    (0..channel_count)
4830                        .map(|_| Some(continuous_grid.clone()))
4831                        .collect_vec(),
4832                    F(integrator_settings.max_prob_ratio),
4833                    integrator_settings.train_on_avg,
4834                )
4835                .expect("discrete multichanneling requires at least one LMB channel"),
4836            );
4837
4838            if settings.sample_orientations {
4839                Grid::Discrete(
4840                    DiscreteGrid::new(
4841                        (0..graph_term.get_num_orientations())
4842                            .map(|_| Some(lmb_channel_grid.clone()))
4843                            .collect(),
4844                        F(integrator_settings.max_prob_ratio),
4845                        integrator_settings.train_on_avg,
4846                    )
4847                    .expect("orientation sampling requires at least one orientation"),
4848                )
4849            } else {
4850                lmb_channel_grid
4851            }
4852        }
4853
4854        DiscreteGraphSamplingType::TropicalSampling(_) => {
4855            let dimension = get_n_dim_for_n_loop_momenta(
4856                &SamplingSettings::DiscreteGraphs(settings.clone()),
4857                graph_term.get_graph().get_loop_number(),
4858                Some(graph_term.get_graph().iter_loop_edges().count()),
4859            );
4860
4861            let continious_grid = Grid::Continuous(
4862                ContinuousGrid::new(
4863                    dimension,
4864                    integrator_settings.n_bins,
4865                    integrator_settings.min_samples_for_update,
4866                    integrator_settings.bin_number_evolution.clone(),
4867                    integrator_settings.train_on_avg,
4868                )
4869                .expect("tropical sampling requires valid continuous-grid settings"),
4870            );
4871
4872            if settings.sample_orientations {
4873                let continuous_grids = (0..graph_term.get_num_orientations())
4874                    .map(|_| Some(continious_grid.clone()))
4875                    .collect();
4876
4877                Grid::Discrete(
4878                    DiscreteGrid::new(
4879                        continuous_grids,
4880                        F(integrator_settings.max_prob_ratio),
4881                        integrator_settings.train_on_avg,
4882                    )
4883                    .expect("orientation sampling requires at least one orientation"),
4884                )
4885            } else {
4886                continious_grid
4887            }
4888        }
4889    }
4890}
4891
4892fn create_default_continous_grid<G: GraphTerm>(
4893    graph_term: &G,
4894    integrator_settings: &IntegratorSettings,
4895) -> Grid<F<f64>> {
4896    Grid::Continuous(
4897        ContinuousGrid::new(
4898            graph_term.get_graph().get_loop_number() * 3,
4899            integrator_settings.n_bins,
4900            integrator_settings.min_samples_for_update,
4901            integrator_settings.bin_number_evolution.clone(),
4902            integrator_settings.train_on_avg,
4903        )
4904        .expect("graph integration requires valid continuous-grid settings"),
4905    )
4906}
4907
4908fn create_grid<I: ProcessIntegrandImpl>(integrand: &I) -> Grid<F<f64>> {
4909    let settings = integrand.get_settings();
4910    match &settings.sampling {
4911        SamplingSettings::Default(_) => Grid::Continuous(
4912            ContinuousGrid::new(
4913                get_global_dimension_if_exists(integrand).unwrap(),
4914                settings.integrator.n_bins,
4915                settings.integrator.min_samples_for_update,
4916                settings.integrator.bin_number_evolution.clone(),
4917                settings.integrator.train_on_avg,
4918            )
4919            .expect("process integration requires valid continuous-grid settings"),
4920        ),
4921        SamplingSettings::MultiChanneling(_) => Grid::Continuous(
4922            ContinuousGrid::new(
4923                get_global_dimension_if_exists(integrand).unwrap(),
4924                settings.integrator.n_bins,
4925                settings.integrator.min_samples_for_update,
4926                settings.integrator.bin_number_evolution.clone(),
4927                settings.integrator.train_on_avg,
4928            )
4929            .expect("multichannel integration requires valid continuous-grid settings"),
4930        ),
4931        SamplingSettings::DiscreteGraphs(discrete_graph_sampling_settings) => Grid::Discrete(
4932            DiscreteGrid::new(
4933                integrand
4934                    .get_group_masters()
4935                    .map(|term| {
4936                        Some(create_grid_for_graph(
4937                            term,
4938                            discrete_graph_sampling_settings,
4939                            &settings.integrator,
4940                        ))
4941                    })
4942                    .collect(),
4943                F(settings.integrator.max_prob_ratio),
4944                settings.integrator.train_on_avg,
4945            )
4946            .expect("discrete graph sampling requires at least one graph group"),
4947        ),
4948    }
4949}
4950
4951#[derive(Clone, Copy)]
4952enum EvaluationSource<'a> {
4953    XSpace(&'a Sample<F<f64>>),
4954    Momentum {
4955        input: &'a MomentumSpaceEvaluationInput,
4956        candidate_lmb: Option<&'a LoopMomentumBasis>,
4957    },
4958    /// Borrowed from the one original-source preparation outside the physical
4959    /// retry stack. Retain source kind for reporting, not for native remapping.
4960    Prepared {
4961        sample: &'a GammaLoopSample<ArbPrec>,
4962        original: &'a EvaluationSource<'a>,
4963    },
4964}
4965
4966impl<'a> EvaluationSource<'a> {
4967    fn canonical_sample(&self) -> Option<&'a GammaLoopSample<ArbPrec>> {
4968        match self {
4969            Self::Prepared { sample, .. } => Some(sample),
4970            _ => None,
4971        }
4972    }
4973
4974    fn is_x_space(&self) -> bool {
4975        match self {
4976            Self::XSpace(_) => true,
4977            Self::Momentum { .. } => false,
4978            Self::Prepared { original, .. } => original.is_x_space(),
4979        }
4980    }
4981
4982    /// Prepare every participating row once at the fixed proposal precision.
4983    /// Failure ends before physical bodies: choosing another map precision after
4984    /// inspecting the active point would change the generated proposal law.
4985    fn prepare_draw<I: ProcessIntegrandImpl>(
4986        &self,
4987        integrand: &mut I,
4988        metadata: &mut EvaluationMetaData,
4989    ) -> Result<Option<GammaLoopSample<ArbPrec>>> {
4990        if matches!(self, Self::Prepared { .. }) {
4991            return Ok(None);
4992        }
4993        let started = Instant::now();
4994        let history = std::mem::take(&mut metadata.radial_root_diagnostics);
4995        metadata.sampling_proposal_policies.begin_collection();
4996        let result = (|| {
4997            let precision = if integrand.get_settings().sampling.uses_sampling_channels()
4998                && !matches!(self, Self::Momentum { input, .. } if input.channel_id.is_none())
4999            {
5000                integrand
5001                    .get_graph(0)
5002                    .sampling_setup()
5003                    .sampling_source
5004                    .as_ref()
5005                    .ok_or_else(|| eyre!("fixed sampling source is not initialized; call warm_up"))?
5006                    .0
5007            } else {
5008                SamplingPrecision::Arb
5009            };
5010            match (self, precision) {
5011                (Self::XSpace(sample), SamplingPrecision::Quad) => {
5012                    parameterize::<f128, I>(sample, integrand, metadata)?.into_canonical(
5013                        &integrand.get_settings().kinematics.externals,
5014                        integrand.get_dependent_momenta_constructor(),
5015                    )
5016                }
5017                (
5018                    Self::Momentum {
5019                        input,
5020                        candidate_lmb,
5021                    },
5022                    SamplingPrecision::Quad,
5023                ) => {
5024                    integrand.prepare_sampling_precision::<f128>()?;
5025                    build_direct_gamma_sample::<f128, I>(
5026                        integrand,
5027                        input,
5028                        *candidate_lmb,
5029                        metadata,
5030                    )?
5031                    .into_canonical(
5032                        &integrand.get_settings().kinematics.externals,
5033                        integrand.get_dependent_momenta_constructor(),
5034                    )
5035                }
5036                (Self::XSpace(sample), SamplingPrecision::Fixed256) => {
5037                    parameterize::<SamplingFloat, I>(sample, integrand, metadata)?.into_canonical(
5038                        &integrand.get_settings().kinematics.externals,
5039                        integrand.get_dependent_momenta_constructor(),
5040                    )
5041                }
5042                (
5043                    Self::Momentum {
5044                        input,
5045                        candidate_lmb,
5046                    },
5047                    SamplingPrecision::Fixed256,
5048                ) => {
5049                    integrand.prepare_sampling_precision::<SamplingFloat>()?;
5050                    build_direct_gamma_sample::<SamplingFloat, I>(
5051                        integrand,
5052                        input,
5053                        *candidate_lmb,
5054                        metadata,
5055                    )?
5056                    .into_canonical(
5057                        &integrand.get_settings().kinematics.externals,
5058                        integrand.get_dependent_momenta_constructor(),
5059                    )
5060                }
5061                (Self::XSpace(sample), SamplingPrecision::Arb) => {
5062                    parameterize::<ArbPrec, I>(sample, integrand, metadata)
5063                }
5064                (
5065                    Self::Momentum {
5066                        input,
5067                        candidate_lmb,
5068                    },
5069                    SamplingPrecision::Arb,
5070                ) => {
5071                    if input.channel_id.is_some() {
5072                        integrand.prepare_sampling_precision::<ArbPrec>()?;
5073                    }
5074                    build_direct_gamma_sample::<ArbPrec, I>(
5075                        integrand,
5076                        input,
5077                        *candidate_lmb,
5078                        metadata,
5079                    )
5080                }
5081                _ => unreachable!("prepared sources and Double source policies are excluded"),
5082            }
5083        })();
5084        // Canonical roots and foreign inverses never consume native physical
5085        // retry occurrences. Preserve the discrete decisions and inclusive cost.
5086        metadata.radial_root_diagnostics = history;
5087        metadata.sampling_proposal_policies.seal();
5088        let elapsed = started.elapsed();
5089        metadata.canonical_sampling_preparation_time += elapsed;
5090        metadata.parameterization_time += elapsed;
5091        result
5092            .map(Some)
5093            .wrap_err("canonical sampling preparation failed at the fixed source precision")
5094    }
5095
5096    fn build_gamma_sample<T: FloatLike, I: ProcessIntegrandImpl>(
5097        &self,
5098        integrand: &mut I,
5099        metadata: &mut EvaluationMetaData,
5100    ) -> Result<GammaLoopSample<T>> {
5101        // Raw callers outside the stability driver still use the same fixed
5102        // proposal preparation; the production driver retains its output once.
5103        let prepared = if !matches!(self, Self::Prepared { .. }) {
5104            self.prepare_draw(integrand, metadata)?
5105        } else {
5106            None
5107        };
5108        let started = Instant::now();
5109        let result = (|| {
5110            let mut sample = prepared
5111                .as_ref()
5112                .or(self.canonical_sample())
5113                .expect("every original source has a canonical row")
5114                .materialize::<T>(GammaLoopSample::<T>::relative_accuracy_budget(
5115                    integrand.get_settings(),
5116                ))?;
5117            // Distinct graph/channel rows may share one evaluator cache. Give
5118            // every completed point its own identity, including base identities
5119            // used by rotation-aware caches; retries start with a fresh range.
5120            let first_id = integrand.loop_cache_id();
5121            for (index, row) in sample
5122                .groups
5123                .iter_mut()
5124                .flat_map(|(_, rows)| rows)
5125                .enumerate()
5126            {
5127                row.sample.sample.loop_mom_cache_id = first_id + index;
5128                row.sample.sample.loop_mom_base_cache_id = first_id + index;
5129            }
5130            if integrand.get_settings().general.enable_cache {
5131                integrand.increment_loop_cache_id(sample.row_count());
5132            }
5133            Ok(sample)
5134        })();
5135        metadata.parameterization_time += started.elapsed();
5136        result
5137    }
5138
5139    fn loop_norm_sum<I: ProcessIntegrandImpl>(
5140        &self,
5141        integrand: &mut I,
5142        metadata: &mut EvaluationMetaData,
5143    ) -> Result<F<f64>> {
5144        if let Self::Momentum { input, .. } = self {
5145            return Ok(sum_loop_norms(input.loop_momenta.iter()));
5146        }
5147        // Inspect only canonical momenta: a norm prepass must not reject an
5148        // otherwise usable Arb draw because its Jacobian is outside f64 range.
5149        let prepared = if self.canonical_sample().is_none() {
5150            self.prepare_draw(integrand, metadata)?
5151        } else {
5152            None
5153        };
5154        let sample = self
5155            .canonical_sample()
5156            .or(prepared.as_ref())
5157            .expect("mapped source has prepared rows");
5158        let started = Instant::now();
5159        let zero = sample.get_default_sample().zero();
5160        let largest = sample
5161            .groups
5162            .iter()
5163            .flat_map(|(_, rows)| rows)
5164            .map(|row| {
5165                row.sample
5166                    .loop_moms()
5167                    .0
5168                    .iter()
5169                    .fold(zero.clone(), |sum, momentum| sum + momentum.norm())
5170            })
5171            .fold(zero.clone(), |a, b| if a > b { a } else { b });
5172        metadata.parameterization_time += started.elapsed();
5173        Ok(largest.into_ff64())
5174    }
5175
5176    fn debug_sample<I: ProcessIntegrandImpl>(
5177        &self,
5178        integrand: &mut I,
5179        metadata: &mut EvaluationMetaData,
5180    ) -> Result<GammaLoopSample<f64>> {
5181        self.build_gamma_sample::<f64, I>(integrand, metadata)
5182    }
5183}
5184
5185fn sum_loop_norms<'a>(loop_momenta: impl Iterator<Item = &'a ThreeMomentum<F<f64>>>) -> F<f64> {
5186    loop_momenta.fold(F(0.0), |acc, momentum| acc + momentum.norm())
5187}
5188
5189fn build_direct_gamma_sample<T: FloatLike, I: ProcessIntegrandImpl>(
5190    integrand: &mut I,
5191    input: &MomentumSpaceEvaluationInput,
5192    candidate_lmb: Option<&LoopMomentumBasis>,
5193    metadata: &mut EvaluationMetaData,
5194) -> Result<GammaLoopSample<T>> {
5195    if integrand.uses_explicit_orientation_sum_only() && input.orientation.is_some() {
5196        return Err(eyre!(
5197            "This integrand requires the complete residue sum, so explicit orientation selection is not supported"
5198        ));
5199    }
5200
5201    let expected_loop_count = if let Some(graph_id) = input.graph_id {
5202        let group_id = integrand
5203            .get_group_structure()
5204            .iter_enumerated()
5205            .find_map(|(group_id, group)| group.into_iter().contains(&graph_id).then_some(group_id))
5206            .ok_or_else(|| eyre!("Unknown graph '{}' in momentum-space evaluation.", graph_id))?;
5207        integrand
5208            .get_master_graph(group_id)
5209            .get_graph()
5210            .get_loop_number()
5211    } else if let Some(group_id) = input.group_id {
5212        if group_id.0 >= integrand.get_group_structure().len() {
5213            return Err(eyre!(
5214                "Unknown graph group '{}' in momentum-space evaluation.",
5215                group_id.0
5216            ));
5217        }
5218        integrand
5219            .get_master_graph(group_id)
5220            .get_graph()
5221            .get_loop_number()
5222    } else {
5223        integrand
5224            .get_group_masters()
5225            .next()
5226            .map(|graph| graph.get_graph().get_loop_number())
5227            .ok_or_else(|| eyre!("Cannot evaluate an integrand with no graph terms."))?
5228    };
5229
5230    if input.loop_momenta.len() != expected_loop_count {
5231        return Err(eyre!(
5232            "Expected {} loop momenta in momentum-space evaluation, got {}.",
5233            expected_loop_count,
5234            input.loop_momenta.len()
5235        ));
5236    }
5237
5238    // A direct input already denotes a binary64 point. Preserve those exact
5239    // tokens in every lane; the decimal conversion policy for settings is unchanged.
5240    let loop_momenta = input
5241        .loop_momenta
5242        .iter()
5243        .map(|momentum| {
5244            ThreeMomentum::new(
5245                F(T::from_f64_exact_binary(momentum.px.0)),
5246                F(T::from_f64_exact_binary(momentum.py.0)),
5247                F(T::from_f64_exact_binary(momentum.pz.0)),
5248            )
5249        })
5250        .collect::<LoopMomenta<F<T>>>();
5251    let sample = MomentumSample::new(
5252        loop_momenta,
5253        integrand.loop_cache_id(),
5254        &integrand.get_settings().kinematics.externals,
5255        integrand.get_current_external_cache_id(),
5256        F::<T>::from_f64(1.0),
5257        integrand.get_dependent_momenta_constructor(),
5258        input.orientation,
5259    )?;
5260
5261    if let Some(graph_id) = input.graph_id {
5262        if input.group_id.is_some() || input.channel_id.is_some() {
5263            return Err(eyre!(
5264                "Explicit graph selection is mutually exclusive with discrete graph/channel selections in momentum-space evaluation."
5265            ));
5266        }
5267        // Profile rays use a candidate basis. Convert only after the exact
5268        // input tokens have reached the fixed source precision, and target this
5269        // graph rather than its group master. The canonical row then owns the
5270        // completed point for every native materialization and stability rotation.
5271        let sample = if let Some(from) = candidate_lmb {
5272            let to = &integrand
5273                .get_graph(graph_id)
5274                .get_graph()
5275                .loop_momentum_basis;
5276            sample.lmb_transform(from, to)
5277        } else {
5278            sample
5279        };
5280        return Ok(GammaLoopSample {
5281            groups: vec![(
5282                None,
5283                vec![DiscreteGraphSample {
5284                    graph_id,
5285                    channel_id: None,
5286                    prepared_lu_hosts: vec![],
5287                    physical_overlaps: None,
5288                    integrand_prefactor: sample.one(),
5289                    sample,
5290                }],
5291            )],
5292        });
5293    }
5294
5295    if candidate_lmb.is_some() {
5296        return Err(eyre!(
5297            "Candidate LMB evaluation requires explicit graph selection."
5298        ));
5299    }
5300
5301    match &integrand.get_settings().sampling {
5302        SamplingSettings::Default(_) | SamplingSettings::MultiChanneling(_) => {
5303            if input.group_id.is_some() || input.channel_id.is_some() {
5304                return Err(eyre!(
5305                    "Discrete graph/channel selections are not supported for this sampling mode."
5306                ));
5307            }
5308
5309            GammaLoopSample::from_default(integrand, sample, false, None)
5310        }
5311        SamplingSettings::DiscreteGraphs(settings) => {
5312            let Some(group_id) = input.group_id else {
5313                if input.orientation.is_some() || input.channel_id.is_some() {
5314                    return Err(eyre!(
5315                        "Explicit orientation or channel selections require selecting a graph group in momentum-space evaluation."
5316                    ));
5317                }
5318                return GammaLoopSample::from_default(integrand, sample, false, None);
5319            };
5320            match &settings.sampling_type {
5321                DiscreteGraphSamplingType::Default(_) => {
5322                    if input.channel_id.is_some() {
5323                        return Err(eyre!(
5324                            "Channel selection is not available for this discrete-graph sampling mode."
5325                        ));
5326                    }
5327                    GammaLoopSample::from_default(integrand, sample, false, Some(group_id))
5328                }
5329                DiscreteGraphSamplingType::MultiChanneling(_) => {
5330                    if input.channel_id.is_some() {
5331                        return Err(eyre!(
5332                            "Channel selection is not available for this discrete-graph sampling mode."
5333                        ));
5334                    }
5335                    // Direct momentum input already contains the desired
5336                    // parent-frame point; only unit-cube samples replay maps.
5337                    GammaLoopSample::from_default(integrand, sample, false, Some(group_id))
5338                }
5339                DiscreteGraphSamplingType::TropicalSampling(_) => {
5340                    if input.channel_id.is_some() {
5341                        return Err(eyre!(
5342                            "Channel selection is not available for tropical discrete-graph sampling."
5343                        ));
5344                    }
5345                    GammaLoopSample::from_tropical(integrand, group_id, sample)
5346                }
5347                DiscreteGraphSamplingType::SamplingMultiChanneling(_) => {
5348                    let Some(channel_id) = input.channel_id else {
5349                        // An unselected raw point evaluates the complete physical
5350                        // graph without a proposal partition or artificial channel.
5351                        return GammaLoopSample::from_default(
5352                            integrand,
5353                            sample,
5354                            false,
5355                            Some(group_id),
5356                        );
5357                    };
5358                    let graph = integrand.get_master_graph(group_id);
5359                    let bridge = graph.sampling_setup().sampling_bridge::<T>()?;
5360                    let mut contexts = SamplingChannelRuntimeContexts::for_draw(
5361                        bridge.channels().len(),
5362                        integrand.get_group(group_id).master(),
5363                        channel_id,
5364                        metadata,
5365                    );
5366                    let mapped = bridge.inverse_with_runtime_contexts(
5367                        channel_id,
5368                        &sample
5369                            .loop_moms()
5370                            .0
5371                            .iter()
5372                            .flat_map(|momentum| {
5373                                [
5374                                    momentum.px.0.clone(),
5375                                    momentum.py.0.clone(),
5376                                    momentum.pz.0.clone(),
5377                                ]
5378                            })
5379                            .collect::<Vec<_>>(),
5380                        &mut contexts,
5381                    )?
5382                    .ok_or_else(|| eyre!(
5383                        "raw momentum point is outside sampling channel {}; select a full-support sibling for direct-momentum evaluation",
5384                        channel_id.0,
5385                    ))?;
5386                    let partition_weight =
5387                        mapped.partition.weight(channel_id.0).ok_or_else(|| {
5388                            eyre!(
5389                                "sampling channel partition has no weight for channel {}",
5390                                channel_id.0
5391                            )
5392                        })?;
5393                    if !partition_weight.is_finite() || partition_weight <= partition_weight.zero()
5394                    {
5395                        return Err(eyre!(
5396                            "sampling channel partition has invalid weight {partition_weight}"
5397                        ));
5398                    }
5399                    let mut sample = sample;
5400                    // Direct inputs have no parameterization Jacobian. Retain
5401                    // only the selected partition in the same per-row factor.
5402                    sample.sample.jacobian = F(partition_weight);
5403                    GammaLoopSample::from_selected(
5404                        integrand,
5405                        group_id,
5406                        channel_id,
5407                        sample,
5408                        mapped.prepared_lu_hosts,
5409                    )
5410                }
5411            }
5412        }
5413    }
5414}
5415
5416fn log_rotated_samples<I: ProcessIntegrandImpl>(
5417    integrand: &mut I,
5418    gammaloop_sample: &GammaLoopSample<f64>,
5419    rotated_results: &[RotatedEvaluation],
5420) {
5421    let mut loop_mom_cache_id = integrand.loop_cache_id();
5422    let mut external_mom_cache_id = integrand.external_cache_id();
5423    let mut shift = 0;
5424
5425    let rotated_samples: Vec<_> = integrand
5426        .get_rotations()
5427        .map(|rotation| {
5428            if rotation.is_identity() {
5429                return gammaloop_sample.clone();
5430            }
5431            loop_mom_cache_id += gammaloop_sample.row_count();
5432            shift += 1;
5433            external_mom_cache_id += 1;
5434            gammaloop_sample.rotate(rotation, loop_mom_cache_id, external_mom_cache_id)
5435        })
5436        .collect();
5437    integrand.increment_external_cache_id(shift);
5438    integrand.increment_loop_cache_id(shift * gammaloop_sample.row_count());
5439
5440    for (sample, result) in rotated_samples.iter().zip(rotated_results.iter()) {
5441        let default_sample = sample.get_default_sample();
5442        debug!(
5443            "loop_moms: {}, external_moms: {}",
5444            format!("{}", default_sample.loop_moms()).blue(),
5445            format!("{:?}", default_sample.external_moms()).blue()
5446        );
5447
5448        debug!(
5449            "result of current level: {}",
5450            format!("{:16e}", result.result).blue()
5451        );
5452    }
5453}
5454
5455fn evaluate_from_source_precise<I: ProcessIntegrandImpl>(
5456    integrand: &mut I,
5457    target: EvaluationTarget<'_>,
5458    source: EvaluationSource<'_>,
5459    wgt: F<f64>,
5460    use_arb_prec: bool,
5461    max_eval: Complex<F<f64>>,
5462) -> Result<PreciseEvaluationResult> {
5463    evaluate_from_source_precise_with_estimate(
5464        integrand,
5465        target,
5466        source,
5467        wgt,
5468        use_arb_prec,
5469        max_eval,
5470        None,
5471        None,
5472    )
5473}
5474
5475#[allow(clippy::too_many_arguments)]
5476fn evaluate_from_source_precise_with_estimate<I: ProcessIntegrandImpl>(
5477    integrand: &mut I,
5478    target: EvaluationTarget<'_>,
5479    source: EvaluationSource<'_>,
5480    wgt: F<f64>,
5481    use_arb_prec: bool,
5482    max_eval: Complex<F<f64>>,
5483    integral_estimate: Option<(f64, f64)>,
5484    remaining_weight: Option<&F<ArbPrec>>,
5485) -> Result<PreciseEvaluationResult> {
5486    let stability = &integrand.get_settings().stability;
5487    if matches!(target, EvaluationTarget::Physical(_))
5488        && stability.integrated_energy_dimension.is_none()
5489        && stability.levels.iter().any(|level| {
5490            level.ecm_relative_tolerance_for_re > 0.0 || level.ecm_relative_tolerance_for_im > 0.0
5491        })
5492    {
5493        return Err(eyre!(
5494            "E_cm-relative physical stability requires `stability.integrated_energy_dimension` (after flux normalization, before output-unit conversion)"
5495        ));
5496    }
5497    let start_eval = std::time::Instant::now();
5498    let mut escalate_if_exact_zero = integrand.get_settings().stability.escalate_if_exact_zero;
5499    if escalate_if_exact_zero
5500        && integrand
5501            .get_settings()
5502            .selectors
5503            .values()
5504            .any(|selector| selector.active)
5505    {
5506        warn_selectors_disable_zero_once();
5507        escalate_if_exact_zero = false;
5508    }
5509    let mut evaluation_metadata = EvaluationMetaData::new_empty();
5510    if matches!(target, EvaluationTarget::Reference(_))
5511        && matches!(&integrand.get_settings().sampling, SamplingSettings::DiscreteGraphs(settings)
5512            if matches!(settings.sampling_type, DiscreteGraphSamplingType::TropicalSampling(_)))
5513    {
5514        return Err(eyre!(
5515            "reference acceptance does not support tropical sampling"
5516        ));
5517    }
5518    let prepared = (|| {
5519        let mut anchor = source.prepare_draw(integrand, &mut evaluation_metadata)?;
5520        if let (Some(sample), EvaluationTarget::Physical(model)) = (&mut anchor, target) {
5521            sample.prepare_physical_overlaps(integrand, model, &mut evaluation_metadata)?;
5522        }
5523        Ok::<_, eyre::Report>(anchor)
5524    })();
5525    let (anchor, preparation_error) = match prepared {
5526        Ok(anchor) => (anchor, None),
5527        Err(error)
5528            if matches!(target, EvaluationTarget::Physical(_))
5529                && matches!(
5530                    error.downcast_ref::<sampling::maps::SamplingEvaluationError>(),
5531                    Some(
5532                        sampling::maps::SamplingEvaluationError::UncertifiedOverlap { .. }
5533                            | sampling::maps::SamplingEvaluationError::UncertifiedRoot { .. }
5534                    )
5535                ) =>
5536        {
5537            // The canonical proposal/center authority must not be changed in a
5538            // native retry. An unresolved preparation prevents every physical
5539            // lane; preserve its diagnostic without evaluating partial bodies.
5540            (None, Some(format!("{error:#}")))
5541        }
5542        Err(error) => return Err(error),
5543    };
5544    let original_source = source;
5545    let source = match &anchor {
5546        Some(sample) => EvaluationSource::Prepared {
5547            sample,
5548            original: &original_source,
5549        },
5550        None => original_source,
5551    };
5552    let (stability_iterator, loop_momenta_escalation) = if preparation_error.is_some() {
5553        (
5554            create_stability_iterator(&integrand.get_settings().stability, use_arb_prec),
5555            None,
5556        )
5557    } else {
5558        stability_iterator_for_source(integrand, &source, use_arb_prec, &mut evaluation_metadata)
5559    };
5560
5561    let mut final_result = None;
5562
5563    let mut stability_results = Vec::with_capacity(stability_iterator.len());
5564    let mut sampling_failures = Vec::new();
5565    let total_levels = stability_iterator.len();
5566    for (level_index, stability_level) in stability_iterator.into_iter().enumerate() {
5567        evaluation_metadata.clear_threshold_counterterm_error();
5568        if let Some(error) = &preparation_error {
5569            evaluation_metadata.record_threshold_counterterm_error(error.clone());
5570        }
5571        let representation =
5572            stability_level.resolved_representation(integrand.generated_representations())?;
5573        let is_final_level = level_index + 1 == total_levels;
5574        let record_rotated_results = integrand
5575            .get_settings()
5576            .stability
5577            .recording
5578            .map(|recording| recording.record_rotated_results)
5579            .unwrap_or(false);
5580        // A fixed-helicity amplitude changes by a global phase under spatial
5581        // rotations. Norm stability therefore checks its full complex value,
5582        // independently of which component the integrator accumulates.
5583        let check_both_components = !matches!(target, EvaluationTarget::Physical(_))
5584            || (integrand.get_settings().stability.check_on_norm
5585                && !matches!(
5586                    integrand.get_dependent_momenta_constructor(),
5587                    DependentMomentaConstructor::CrossSection
5588                ));
5589        let mut context = StabilityEvaluationContext {
5590            target,
5591            source: &source,
5592            stability_level: &stability_level,
5593            max_eval: &max_eval,
5594            wgt,
5595            remaining_weight,
5596            check_on_norm: integrand.get_settings().stability.check_on_norm,
5597            is_final_level,
5598            evaluation_metadata: &mut evaluation_metadata,
5599            record_rotated_results,
5600            precision_label: match stability_level.precision {
5601                Precision::Double => "f64",
5602                Precision::Quad => "f128",
5603                Precision::Arb => "ArbPrec",
5604            },
5605            escalate_if_exact_zero,
5606            check_real: check_both_components
5607                || !matches!(
5608                    integrand.get_settings().integrator.integrated_phase,
5609                    IntegratedPhase::Imag
5610                ),
5611            check_imag: check_both_components
5612                || !matches!(
5613                    integrand.get_settings().integrator.integrated_phase,
5614                    IntegratedPhase::Real
5615                ),
5616            integral_estimate: matches!(target, EvaluationTarget::Physical(_))
5617                .then_some(integral_estimate)
5618                .flatten(),
5619            min_abs_wgt_for_escalation: integrand
5620                .get_settings()
5621                .stability
5622                .min_abs_wgt_for_escalation,
5623        };
5624        let level_start = Instant::now();
5625        let mut is_stable = false;
5626        let mut rotated_results = Vec::new();
5627        macro_rules! evaluate_native_level {
5628            ($scalar:ty, $variant:ident) => {
5629                evaluate_stability_level_precise::<$scalar, I>(integrand, &mut context).map(
5630                    |mut result| {
5631                        is_stable = result.is_stable;
5632                        stability_results.push(result.stability_result());
5633                        debug!(
5634                            "level: {}. result: {}",
5635                            format!(
5636                                "{} / {}",
5637                                result.stability_level_used, result.representation
5638                            )
5639                            .green(),
5640                            format!("{:16e}", result.result).blue()
5641                        );
5642                        rotated_results = std::mem::take(&mut result.rotated_results);
5643                        PreciseEvaluationResult::$variant(finalize_precise_evaluation_result(
5644                            result,
5645                            wgt,
5646                            evaluation_metadata.clone(),
5647                        ))
5648                    },
5649                )
5650            };
5651        }
5652        let result_of_level = match stability_level.precision {
5653            Precision::Double => evaluate_native_level!(f64, Double),
5654            Precision::Quad => evaluate_native_level!(f128, Quad),
5655            Precision::Arb => evaluate_native_level!(ArbPrec, Arb),
5656        };
5657        let result_of_level = match result_of_level {
5658            Ok(result) => result,
5659            Err(error)
5660                if error
5661                    .downcast_ref::<sampling::maps::SamplingEvaluationError>()
5662                    .is_some() =>
5663            {
5664                stability_results.push(StabilityResult {
5665                    precision: stability_level.precision,
5666                    representation,
5667                    estimated_relative_accuracy: None,
5668                    estimated_decimal_digits: None,
5669                    status: StabilityStatus::Unstable(0),
5670                    total_time: level_start.elapsed(),
5671                });
5672                crate::debug_tags!(#sampling;
5673                    stage = "native_sampling_retry", precision = %stability_level.precision, representation = %representation,
5674                    error = %error, final_level = is_final_level,
5675                    "sampling reconstruction failed at this precision"
5676                );
5677                // A partial rotation/channel pass may have populated numerical
5678                // caches. Start the next reconstruction with fresh point IDs;
5679                // dropped GraphEvaluationResults contain all its uncommitted events.
5680                integrand.increment_loop_cache_id(integrand.get_rotations().count() + 1);
5681                integrand.revert_to_base_external_cache_id();
5682                sampling_failures.push(format!(
5683                    "{} / {representation}: {error:#}",
5684                    stability_level.precision
5685                ));
5686                if is_final_level {
5687                    return Err(error.wrap_err(format!(
5688                        "sampling reconstruction failed; attempts [{}]; numerical errors [{}]",
5689                        stability_results
5690                            .iter()
5691                            .map(|result| format!(
5692                                "{} / {}: {:?}",
5693                                result.precision, result.representation, result.status
5694                            ))
5695                            .join("; "),
5696                        sampling_failures.join("; ")
5697                    )));
5698                }
5699                continue;
5700            }
5701            Err(error) => return Err(error),
5702        };
5703
5704        if matches!(target, EvaluationTarget::Reference(_)) && is_final_level && !is_stable {
5705            return Err(eyre!(
5706                "reference value or moment remained unstable after the final {} precision level",
5707                stability_level.precision
5708            ));
5709        }
5710        final_result = Some(result_of_level);
5711
5712        if is_stable {
5713            break;
5714        } else {
5715            debug!(
5716                "unstable at level: {} / {}",
5717                stability_level.precision, representation
5718            );
5719            if evaluation_metadata.threshold_counterterm_error.is_some() {
5720                debug!("threshold preparation or evaluation requires precision escalation");
5721            } else if let Ok(gammaloop_sample) =
5722                source.debug_sample(integrand, &mut evaluation_metadata)
5723            {
5724                log_rotated_samples(integrand, &gammaloop_sample, &rotated_results);
5725            } else {
5726                debug!("failed to reconstruct sample for instability logging");
5727            }
5728        }
5729    }
5730
5731    let mut result = final_result.ok_or_else(|| eyre!("no stability level was evaluated"))?;
5732    let metadata = match &mut result {
5733        PreciseEvaluationResult::Double(result) => &mut result.evaluation_metadata,
5734        PreciseEvaluationResult::Quad(result) => &mut result.evaluation_metadata,
5735        PreciseEvaluationResult::Arb(result) => &mut result.evaluation_metadata,
5736    };
5737    metadata.total_timing = start_eval.elapsed();
5738    // A last unstable-level debug replay occurs after its result was cloned.
5739    // Copy the sole source owner's accumulated counters, never one lane's time.
5740    metadata.parameterization_time = evaluation_metadata.parameterization_time;
5741    metadata.canonical_sampling_preparation_time =
5742        evaluation_metadata.canonical_sampling_preparation_time;
5743    metadata.integrand_evaluation_time = evaluation_metadata.integrand_evaluation_time;
5744    metadata.loop_momenta_escalation = loop_momenta_escalation;
5745    metadata.stability_results = stability_results;
5746    Ok(result)
5747}
5748
5749fn evaluate_from_source<I: ProcessIntegrandImpl>(
5750    integrand: &mut I,
5751    model: &Model,
5752    source: EvaluationSource<'_>,
5753    wgt: F<f64>,
5754    use_arb_prec: bool,
5755    max_eval: Complex<F<f64>>,
5756) -> Result<EvaluationResult> {
5757    evaluate_from_source_precise(
5758        integrand,
5759        EvaluationTarget::Physical(model),
5760        source,
5761        wgt,
5762        use_arb_prec,
5763        max_eval,
5764    )?
5765    .try_into_f64()
5766}
5767
5768fn stability_iterator_for_source<I: ProcessIntegrandImpl>(
5769    integrand: &mut I,
5770    source: &EvaluationSource<'_>,
5771    use_arb_prec: bool,
5772    metadata: &mut EvaluationMetaData,
5773) -> (
5774    Vec<StabilityLevelSetting>,
5775    Option<LoopMomentaEscalationMetrics>,
5776) {
5777    let mut stability_iterator =
5778        create_stability_iterator(&integrand.get_settings().stability, use_arb_prec);
5779    let escalation_factor = integrand
5780        .get_settings()
5781        .stability
5782        .loop_momenta_norm_escalation_factor;
5783    let record_loop_momenta_escalation = integrand
5784        .get_settings()
5785        .stability
5786        .recording
5787        .map(|recording| recording.record_loop_momenta_escalation)
5788        .unwrap_or(false);
5789    let mut loop_momenta_escalation = None;
5790    if escalation_factor > 0.0
5791        && stability_iterator.len() > 1
5792        && let Ok(sum_norm) = source.loop_norm_sum(integrand, metadata)
5793    {
5794        let threshold =
5795            F::<f64>::from_f64(escalation_factor * integrand.get_settings().kinematics.e_cm);
5796        if record_loop_momenta_escalation {
5797            loop_momenta_escalation = Some(LoopMomentaEscalationMetrics {
5798                sum_norm: sum_norm.0,
5799                threshold: threshold.0,
5800            });
5801        }
5802        if sum_norm > threshold {
5803            let escalated_level_index = stability_iterator
5804                .iter()
5805                .position(|level| level.precision == Precision::Quad)
5806                .or_else(|| stability_iterator.len().checked_sub(1));
5807            if let Some(level_index) = escalated_level_index {
5808                stability_iterator = stability_iterator[level_index..].to_vec();
5809            }
5810        }
5811    }
5812
5813    (stability_iterator, loop_momenta_escalation)
5814}
5815
5816fn finalize_precise_evaluation_result<T: FloatLike>(
5817    result: PreciseStabilityLevelResult<T>,
5818    integrator_weight: F<f64>,
5819    mut evaluation_metadata: EvaluationMetaData,
5820) -> GenericEvaluationResult<T> {
5821    let re_is_nan = result.result.re.is_nan()
5822        || result.result.re.is_infinite()
5823        || result
5824            .graph_result
5825            .absolute_integrand_result
5826            .as_ref()
5827            .is_some_and(|value| value.re.is_nan() || value.re.is_infinite());
5828    let im_is_nan = result.result.im.is_nan()
5829        || result.result.im.is_infinite()
5830        || result
5831            .graph_result
5832            .absolute_integrand_result
5833            .as_ref()
5834            .is_some_and(|value| value.im.is_nan() || value.im.is_infinite());
5835    if re_is_nan || im_is_nan {
5836        warn!(
5837            stage = "process_final_nonfinite_sample",
5838            result = %result.result,
5839            re_is_nan,
5840            im_is_nan,
5841            "process evaluation is nonfinite"
5842        );
5843    }
5844    evaluation_metadata.generated_event_count = result.graph_result.generated_event_count;
5845    evaluation_metadata.accepted_event_count = result.graph_result.accepted_event_count;
5846    evaluation_metadata.relative_instability_error = Complex::new_zero();
5847    evaluation_metadata.is_nan = re_is_nan || im_is_nan;
5848    let nanless_result = if re_is_nan && !im_is_nan {
5849        Complex::new(result.result.re.zero(), result.result.im)
5850    } else if im_is_nan && !re_is_nan {
5851        Complex::new(result.result.re, result.result.im.zero())
5852    } else if re_is_nan && im_is_nan {
5853        Complex::new(result.result.re.zero(), result.result.im.zero())
5854    } else {
5855        result.result
5856    };
5857
5858    let mut event_groups = result.graph_result.event_groups;
5859    let integrator_weight = F::<T>::from_ff64(integrator_weight);
5860    let parameterization_jacobian = result.parameterization_jacobian;
5861    // Event contributions include native Jacobians/partitions, but the outer
5862    // sampler weight is applied only when committing observable statistics.
5863    let full_factor = full_event_multiplicative_factor_precise(
5864        parameterization_jacobian.clone(),
5865        integrator_weight.one(),
5866    );
5867    apply_full_event_multiplicative_factor_precise(&mut event_groups, &full_factor);
5868
5869    GenericEvaluationResult {
5870        reference_moments: result.graph_result.reference_moments,
5871        integrand_result: nanless_result,
5872        absolute_integrand_result: result.graph_result.absolute_integrand_result.map(|value| {
5873            Complex::new(
5874                if re_is_nan { value.re.zero() } else { value.re },
5875                if im_is_nan { value.im.zero() } else { value.im },
5876            )
5877        }),
5878        parameterization_jacobian,
5879        integrator_weight,
5880        event_groups,
5881        evaluation_metadata,
5882    }
5883}
5884
5885fn warn_selectors_disable_zero_once() {
5886    static ONCE: Once = Once::new();
5887    ONCE.call_once(|| {
5888        warn!(
5889            "disabling `stability.escalate_if_exact_zero` during evaluation because selectors can legitimately zero the event weight"
5890        );
5891    });
5892}
5893
5894fn evaluate_sample<I: ProcessIntegrandImpl>(
5895    integrand: &mut I,
5896    model: &Model,
5897    sample: &Sample<F<f64>>,
5898    wgt: F<f64>,
5899    _iter: usize,
5900    use_arb_prec: bool,
5901    max_eval: Complex<F<f64>>,
5902) -> Result<EvaluationResult> {
5903    evaluate_from_source(
5904        integrand,
5905        model,
5906        EvaluationSource::XSpace(sample),
5907        wgt,
5908        use_arb_prec,
5909        max_eval,
5910    )
5911}
5912
5913fn evaluate_reference_sample<I: ProcessIntegrandImpl>(
5914    integrand: &mut I,
5915    sample: &Sample<F<f64>>,
5916    reference: &GaussianReferenceFunction,
5917) -> Result<ReferenceSampleEvaluation> {
5918    let result = evaluate_from_source_precise(
5919        integrand,
5920        EvaluationTarget::Reference(reference),
5921        EvaluationSource::XSpace(sample),
5922        sample.get_weight(),
5923        false,
5924        Complex::new_zero(),
5925    )?;
5926    // Select precision once in the common loop, then narrow its value and
5927    // moment together at the existing f64 acceptance reporting boundary.
5928    macro_rules! report {
5929        ($result:expr) => {{
5930            let mut result = $result;
5931            if result.evaluation_metadata.is_nan {
5932                return Err(eyre!(
5933                    "reference acceptance cannot report a nonfinite finalized value"
5934                ));
5935            }
5936            let moments = result
5937                .reference_moments
5938                .take()
5939                .ok_or_else(|| eyre!("reference acceptance produced no mapped moment"))?
5940                .try_into_f64()?;
5941            Ok(ReferenceSampleEvaluation {
5942                evaluation: result.try_into_f64()?,
5943                moments,
5944            })
5945        }};
5946    }
5947    match result {
5948        PreciseEvaluationResult::Double(result) => report!(result),
5949        PreciseEvaluationResult::Quad(result) => report!(result),
5950        PreciseEvaluationResult::Arb(result) => report!(result),
5951    }
5952}
5953
5954fn evaluate_sample_precise<I: ProcessIntegrandImpl>(
5955    integrand: &mut I,
5956    model: &Model,
5957    sample: &Sample<F<f64>>,
5958    wgt: F<f64>,
5959    use_arb_prec: bool,
5960    max_eval: Complex<F<f64>>,
5961) -> Result<crate::integrands::evaluation::PreciseEvaluationResult> {
5962    evaluate_from_source_precise(
5963        integrand,
5964        EvaluationTarget::Physical(model),
5965        EvaluationSource::XSpace(sample),
5966        wgt,
5967        use_arb_prec,
5968        max_eval,
5969    )
5970}
5971
5972fn evaluate_momentum_configuration<I: ProcessIntegrandImpl>(
5973    integrand: &mut I,
5974    model: &Model,
5975    input: &MomentumSpaceEvaluationInput,
5976    wgt: F<f64>,
5977    use_arb_prec: bool,
5978    max_eval: Complex<F<f64>>,
5979) -> Result<EvaluationResult> {
5980    evaluate_from_source(
5981        integrand,
5982        model,
5983        EvaluationSource::Momentum {
5984            input,
5985            candidate_lmb: None,
5986        },
5987        wgt,
5988        use_arb_prec,
5989        max_eval,
5990    )
5991}
5992
5993fn evaluate_momentum_configuration_precise<I: ProcessIntegrandImpl>(
5994    integrand: &mut I,
5995    model: &Model,
5996    input: &MomentumSpaceEvaluationInput,
5997    wgt: F<f64>,
5998    use_arb_prec: bool,
5999    max_eval: Complex<F<f64>>,
6000) -> Result<crate::integrands::evaluation::PreciseEvaluationResult> {
6001    evaluate_from_source_precise(
6002        integrand,
6003        EvaluationTarget::Physical(model),
6004        EvaluationSource::Momentum {
6005            input,
6006            candidate_lmb: None,
6007        },
6008        wgt,
6009        use_arb_prec,
6010        max_eval,
6011    )
6012}
6013
6014#[cfg(test)]
6015pub(crate) mod tests {
6016    use super::{
6017        GraphTerm, LmbMultiChannelingSetup, RuntimeCache, SamplingChannelCompileContext,
6018        SamplingChannelId, SamplingSelectionError, create_stability_iterator,
6019        filtered_orientation_count, resolve_sampling_channel_selection,
6020        resolve_visible_orientation_id, validate_orientation_catalog_group,
6021        validate_process_runtime_settings,
6022    };
6023    use crate::cff::OrientationID;
6024    use crate::{
6025        finalized_runtime_dot,
6026        graph::{FeynmanGraph, Graph, GroupId, LMBext, LmbIndex, LoopMomentumBasis},
6027        initialisation::test_initialise,
6028        momentum::{
6029            ThreeMomentum,
6030            sample::{BareMomentumSample, ExternalFourMomenta, LoopMomenta, MomentumSample},
6031            signature::LoopExtSignature,
6032        },
6033        settings::{
6034            RuntimeSettings,
6035            global::{OrientationPattern, RepresentationMode},
6036            runtime::{
6037                DiscreteGraphSamplingSettings, DiscreteGraphSamplingType, HFunctionSettings,
6038                MultiChannelingSettings, ParameterizationSettings, Precision,
6039                SamplingChannelDefinition, SamplingChannelSelection, SamplingSettings,
6040                StabilitySettings,
6041            },
6042        },
6043        utils::F,
6044    };
6045    use linnet::half_edge::{
6046        involution::{EdgeIndex, EdgeVec, Orientation},
6047        subgraph::{ModifySubSet, SubSetLike, subset::SubSet},
6048    };
6049    use std::sync::OnceLock;
6050    use typed_index_collections::TiVec;
6051
6052    /// Use the existing generated scalar cut fixture for a fixed-source body
6053    /// retry. Its normalized q target makes a missing/doubled J*w observable.
6054    pub(crate) fn check_fixed_quad_source_transport(
6055        runtime: &mut super::ProcessIntegrand,
6056        model: &crate::model::Model,
6057        source: &symbolica::numerical_integration::Sample<F<f64>>,
6058    ) -> color_eyre::Result<()> {
6059        use super::{
6060            EvaluationSource, EvaluationTarget, GraphTerm, ProcessIntegrand, ProcessIntegrandImpl,
6061            SamplingLawProbe, evaluate_from_source_precise,
6062        };
6063        use crate::{
6064            integrands::evaluation::EvaluationMetaData,
6065            settings::runtime::{Precision, StabilityLevelSetting},
6066            utils::{ArbPrec, QuadFloat, SamplingFloat, SamplingPrecision},
6067        };
6068        use spenso::algebra::complex::Complex;
6069        use std::sync::atomic::{AtomicUsize, Ordering};
6070        let original_sampling = runtime.get_settings().sampling.clone();
6071        for fixed256 in [false, true] {
6072            runtime.get_mut_settings().sampling = original_sampling.clone();
6073            if fixed256 {
6074                let mut parser: crate::settings::runtime::SamplingSettingsParser =
6075                    toml::from_str(&toml::to_string(&original_sampling)?)?;
6076                parser.sampling_channel_weight =
6077                    crate::settings::runtime::SamplingChannelWeight::SingularityProxy;
6078                for definitions in parser.channel_definitions.values_mut() {
6079                    for definition in definitions.values_mut() {
6080                        definition.singularity_proxy = Some("1".into());
6081                    }
6082                }
6083                runtime.get_mut_settings().sampling = toml::from_str(&toml::to_string(&parser)?)?;
6084            }
6085            let expected_source = if fixed256 {
6086                SamplingPrecision::Fixed256
6087            } else {
6088                SamplingPrecision::Quad
6089            };
6090            let settings = runtime.get_mut_settings();
6091            settings.stability.levels = vec![
6092                StabilityLevelSetting::default_double(),
6093                StabilityLevelSetting::default_quad(),
6094                StabilityLevelSetting::default_arb(),
6095            ];
6096            settings.stability.rotation_axis.clear();
6097            settings.stability.escalate_if_exact_zero = false;
6098            settings.stability.loop_momenta_norm_escalation_factor = 0.0;
6099            runtime.warm_up(model)?;
6100            let ProcessIntegrand::CrossSection(integrand) = runtime else {
6101                unreachable!("generated cut fixture")
6102            };
6103            let policy = integrand
6104                .get_graph(0)
6105                .sampling_setup()
6106                .sampling_source
6107                .as_ref()
6108                .copied()
6109                .unwrap();
6110            assert_eq!(policy.0, expected_source);
6111            let saved_catalogue = integrand
6112                .get_graph(0)
6113                .sampling_setup()
6114                .sampling_catalogue
6115                .as_ref()
6116                .unwrap()
6117                .clone();
6118            integrand
6119                .get_graph_mut(0)
6120                .sampling_setup_mut()
6121                .sampling_catalogue
6122                .as_mut()
6123                .unwrap()
6124                .entries
6125                .push(
6126                    super::sampling::selection::SamplingCatalogueEntry::Surface {
6127                        edges: vec![1, 2],
6128                        parent_lmb: vec![1],
6129                    },
6130                );
6131            assert_eq!(
6132                integrand.sampling_source_policy()?.0,
6133                SamplingPrecision::Fixed256
6134            );
6135            integrand
6136                .get_graph_mut(0)
6137                .sampling_setup_mut()
6138                .sampling_catalogue
6139                .set(saved_catalogue);
6140            let saved_externals = integrand.settings.kinematics.externals.clone();
6141            let mut external_values = saved_externals.get_dependent_externals::<ArbPrec>(
6142                integrand.get_dependent_momenta_constructor(),
6143            )?;
6144            external_values[crate::momentum::sample::ExternalIndex(0)]
6145                .spatial
6146                .px = F::<ArbPrec>::default().from_usize(2).powi(2000);
6147            let crate::settings::runtime::kinematic::Externals::Constant { arb_cache, .. } =
6148                &mut integrand.settings.kinematics.externals;
6149            arb_cache.set(external_values);
6150            assert_eq!(
6151                integrand.sampling_source_policy()?.0,
6152                SamplingPrecision::Fixed256
6153            );
6154            integrand.settings.kinematics.externals = saved_externals;
6155            assert_eq!(integrand.sampling_source_policy()?, policy);
6156            let mut metadata = EvaluationMetaData::new_empty();
6157            let expected = if fixed256 {
6158                super::parameterize::<SamplingFloat, _>(source, integrand, &mut metadata)?
6159                    .into_canonical(
6160                        &integrand.get_settings().kinematics.externals,
6161                        integrand.get_dependent_momenta_constructor(),
6162                    )?
6163            } else {
6164                super::parameterize::<QuadFloat, _>(source, integrand, &mut metadata)?
6165                    .into_canonical(
6166                        &integrand.get_settings().kinematics.externals,
6167                        integrand.get_dependent_momenta_constructor(),
6168                    )?
6169            };
6170            let source_kind = EvaluationSource::XSpace(source);
6171            let anchor = source_kind.prepare_draw(integrand, &mut metadata)?.unwrap();
6172            assert_eq!(format!("{anchor:?}"), format!("{expected:?}"));
6173            if !fixed256 {
6174                use super::{
6175                    GaussianReferenceFunction, MomentumSpaceEvaluationInput,
6176                    StabilityEvaluationContext,
6177                };
6178                use crate::settings::runtime::IntegralUnit;
6179
6180                // Exercise the real source/target scale owners with this already
6181                // generated one-incoming cut and its explicitly selected channel.
6182                let original_settings = integrand.settings.clone();
6183                let mut level = StabilityLevelSetting::default_arb();
6184                level.ecm_relative_tolerance_for_re = 1e-4;
6185                level.ecm_relative_tolerance_for_im = 1e-4;
6186                integrand.settings.stability.levels = vec![level];
6187                integrand.settings.stability.integrated_energy_dimension = None;
6188                let error = evaluate_from_source_precise(
6189                    integrand,
6190                    EvaluationTarget::Physical(model),
6191                    source_kind,
6192                    F(1.0),
6193                    false,
6194                    Complex::new_zero(),
6195                )
6196                .unwrap_err();
6197                assert!(error.to_string().contains("integrated_energy_dimension"));
6198
6199                let default_sample = anchor.get_default_sample();
6200                assert_eq!(default_sample.external_moms().len(), 1);
6201                let loops = default_sample.loop_moms().0.len();
6202                let direct = MomentumSpaceEvaluationInput {
6203                    loop_momenta: default_sample
6204                        .loop_moms()
6205                        .iter()
6206                        .map(|momentum| {
6207                            ThreeMomentum::new(
6208                                momentum.px.into_ff64(),
6209                                momentum.py.into_ff64(),
6210                                momentum.pz.into_ff64(),
6211                            )
6212                        })
6213                        .collect(),
6214                    integrator_weight: F(1.0),
6215                    graph_id: None,
6216                    group_id: Some(GroupId(0)),
6217                    orientation: None,
6218                    channel_id: Some(SamplingChannelId(0)),
6219                };
6220                integrand.settings.sampling =
6221                    SamplingSettings::DiscreteGraphs(DiscreteGraphSamplingSettings {
6222                        sampling_type: DiscreteGraphSamplingType::SamplingMultiChanneling(
6223                            MultiChannelingSettings {
6224                                parameterization_settings: original_settings
6225                                    .sampling
6226                                    .get_parameterization_settings()
6227                                    .unwrap(),
6228                            },
6229                        ),
6230                        ..Default::default()
6231                    });
6232                integrand.warm_up(model)?;
6233                let raw_source = EvaluationSource::Momentum {
6234                    input: &direct,
6235                    candidate_lmb: None,
6236                };
6237                let raw = raw_source.prepare_draw(integrand, &mut metadata)?.unwrap();
6238                let prepared_raw = EvaluationSource::Prepared {
6239                    sample: &raw,
6240                    original: &raw_source,
6241                };
6242                assert!(!prepared_raw.is_x_space());
6243                let reference_function =
6244                    GaussianReferenceFunction::centered(original_settings.kinematics.e_cm, loops)?;
6245                let maximum = Complex::new_zero();
6246                for energy in [
6247                    original_settings.kinematics.e_cm,
6248                    2.0 * original_settings.kinematics.e_cm,
6249                ] {
6250                    integrand.settings.kinematics.e_cm = energy;
6251                    let e_cm = F::<ArbPrec>::from_f64(energy);
6252                    for (evaluation_source, sample, missing) in [
6253                        (&source_kind, &anchor, 0),
6254                        (&prepared_raw, &raw, 3 * loops as i32),
6255                    ] {
6256                        let mut context = StabilityEvaluationContext {
6257                            target: EvaluationTarget::Reference(&reference_function),
6258                            source: evaluation_source,
6259                            stability_level: &level,
6260                            max_eval: &maximum,
6261                            wgt: F(1.0),
6262                            remaining_weight: None,
6263                            check_on_norm: false,
6264                            is_final_level: true,
6265                            evaluation_metadata: &mut metadata,
6266                            record_rotated_results: false,
6267                            precision_label: "ArbPrec",
6268                            escalate_if_exact_zero: false,
6269                            check_real: true,
6270                            check_imag: true,
6271                            integral_estimate: None,
6272                            min_abs_wgt_for_escalation: 0.0,
6273                        };
6274                        integrand.settings.stability.integrated_energy_dimension = None;
6275                        assert_eq!(
6276                            context.ecm_reference_scale(integrand, sample)?.unwrap(),
6277                            e_cm.powi(-missing)
6278                        );
6279                        context.target = EvaluationTarget::Physical(model);
6280                        assert!(context.ecm_reference_scale(integrand, sample).is_err());
6281                        for (disabled_flux, dimension) in [(false, 1), (true, 2)] {
6282                            integrand.settings.general.disable_flux_factor = disabled_flux;
6283                            integrand.settings.stability.integrated_energy_dimension =
6284                                Some(dimension);
6285                            // The actual decay branch has no barn conversion,
6286                            // including when an explicit barn unit was supplied.
6287                            for unit in [
6288                                IntegralUnit::None,
6289                                IntegralUnit::Picobarn,
6290                                IntegralUnit::Femtobarn,
6291                            ] {
6292                                integrand.settings.general.integral_unit = unit;
6293                                assert_eq!(
6294                                    context.ecm_reference_scale(integrand, sample)?.unwrap(),
6295                                    e_cm.powi(dimension - missing)
6296                                );
6297                            }
6298                        }
6299                    }
6300                }
6301                integrand.settings = original_settings.clone();
6302                integrand.settings.stability.levels = vec![level];
6303                integrand.settings.stability.integrated_energy_dimension = None;
6304                integrand.warm_up(model)?;
6305                let reference_result = evaluate_from_source_precise(
6306                    integrand,
6307                    EvaluationTarget::Reference(&reference_function),
6308                    source_kind,
6309                    F(1.0),
6310                    false,
6311                    Complex::new_zero(),
6312                )?;
6313                assert!(match &reference_result {
6314                    super::PreciseEvaluationResult::Double(result) =>
6315                        result.reference_moments.is_some(),
6316                    super::PreciseEvaluationResult::Quad(result) =>
6317                        result.reference_moments.is_some(),
6318                    super::PreciseEvaluationResult::Arb(result) =>
6319                        result.reference_moments.is_some(),
6320                });
6321                reference_result.try_into_f64()?;
6322                integrand.settings = original_settings;
6323                integrand.warm_up(model)?;
6324            }
6325            let reference = integrand.get_graph(0).sampling_setup().clone();
6326            let probe = SamplingLawProbe {
6327                reference: &reference,
6328                channel_id: SamplingChannelId(0),
6329                radial_coordinate: 0,
6330                retry_lower_half: true,
6331                sign_coordinate: None,
6332                alternating_graph_sign: false,
6333                calls: std::array::from_fn(|_| AtomicUsize::new(0)),
6334            };
6335            let value = evaluate_from_source_precise(
6336                integrand,
6337                EvaluationTarget::SamplingLaw(&probe),
6338                EvaluationSource::XSpace(source),
6339                F(1.0),
6340                false,
6341                Complex::new_zero(),
6342            )?
6343            .try_into_f64()?;
6344            assert_eq!(
6345                value.evaluation_metadata.final_precision(),
6346                Some(Precision::Quad)
6347            );
6348            assert_eq!(probe.calls[0].load(Ordering::Relaxed), 1);
6349            assert_eq!(probe.calls[1].load(Ordering::Relaxed), 1);
6350            assert_eq!(probe.calls[2].load(Ordering::Relaxed), 0);
6351            assert!((value.integrand_result.re.0 - 1.0).abs() < 1.0e-8);
6352            let prepared = EvaluationSource::Prepared {
6353                sample: &anchor,
6354                original: &source_kind,
6355            };
6356            let arb_sample = prepared.build_gamma_sample::<ArbPrec, _>(integrand, &mut metadata)?;
6357            let arb_value = super::evaluate_single(
6358                integrand,
6359                EvaluationTarget::SamplingLaw(&probe),
6360                &arb_sample,
6361                &crate::momentum::Rotation::new(crate::momentum::RotationMethod::Identity),
6362                &mut metadata,
6363                Some(&anchor),
6364                RepresentationMode::Cff,
6365            )?;
6366            assert_eq!(probe.calls[2].load(Ordering::Relaxed), 1);
6367            assert!((arb_value.integrand_result.re.into_ff64().0 - 1.0).abs() < 1.0e-8);
6368            for calls in &probe.calls {
6369                calls.store(0, Ordering::Relaxed);
6370            }
6371            assert!(
6372                integrand
6373                    .get_graph(0)
6374                    .sampling_setup()
6375                    .sampling_bridge::<ArbPrec>()
6376                    .is_ok()
6377            );
6378            // A signed normalized density q(k) has integral zero and absolute
6379            // integral one when its reference radial CDF selects the sign.
6380            // Pair u with 1-u: two distinct channel points cancel in the signed
6381            // estimator, while their absolute contributions must still add.
6382            let mut absolute_runtime = integrand.clone();
6383            let catalogue = absolute_runtime
6384                .get_graph_mut(0)
6385                .sampling_setup_mut()
6386                .sampling_catalogue
6387                .as_mut()
6388                .unwrap();
6389            catalogue.entries.push(catalogue.entries[0].clone());
6390            let mut signed_probe = SamplingLawProbe {
6391                reference: &reference,
6392                channel_id: SamplingChannelId(0),
6393                radial_coordinate: 0,
6394                retry_lower_half: false,
6395                sign_coordinate: Some(0),
6396                alternating_graph_sign: false,
6397                calls: std::array::from_fn(|_| AtomicUsize::new(0)),
6398            };
6399            let (selection, original_coordinates) =
6400                super::gammaloop_sample::unwrap_sample::<f64>(source);
6401            for lower in [0.125, 0.25, 0.375] {
6402                let mut rows = Vec::new();
6403                for (channel, radial) in [lower, 1.0 - lower].into_iter().enumerate() {
6404                    let mut coordinates = original_coordinates.clone();
6405                    coordinates[0] = F(radial);
6406                    let source = symbolica::numerical_integration::Sample::Uniform(
6407                        F(1.0),
6408                        selection.clone(),
6409                        coordinates,
6410                    );
6411                    let mut draw = EvaluationSource::XSpace(&source)
6412                        .prepare_draw(&mut absolute_runtime, &mut metadata)?
6413                        .unwrap();
6414                    let mut row = draw.groups[0].1.remove(0);
6415                    row.sample.sample.jacobian /= row.sample.one().from_usize(2);
6416                    row.channel_id = Some(SamplingChannelId(channel));
6417                    row.prepared_lu_hosts.clear();
6418                    rows.push(row);
6419                }
6420                let draw = super::GammaLoopSample {
6421                    groups: vec![(Some(GroupId(0)), rows)],
6422                };
6423                let identity =
6424                    crate::momentum::Rotation::new(crate::momentum::RotationMethod::Identity);
6425                let value = super::evaluate_single(
6426                    &mut absolute_runtime,
6427                    EvaluationTarget::SamplingLaw(&signed_probe),
6428                    &draw,
6429                    &identity,
6430                    &mut metadata,
6431                    Some(&draw),
6432                    RepresentationMode::Cff,
6433                )?;
6434                assert!(value.integrand_result.re.into_ff64().0.abs() < 1.0e-8);
6435                assert!(value.integrand_result.im.into_ff64().0.abs() < 1.0e-8);
6436                let absolute = value.absolute_integrand_result.unwrap();
6437                assert!((absolute.re.into_ff64().0 - 1.0).abs() < 1.0e-8);
6438                assert!((absolute.im.into_ff64().0 - 1.0).abs() < 1.0e-8);
6439                // Selected-channel MC has probability 1/2. Its individual
6440                // absolute weighted samples are also one, not two or one-half.
6441                for row in &draw.groups[0].1 {
6442                    let selected = super::GammaLoopSample {
6443                        groups: vec![(Some(GroupId(0)), vec![row.clone()])],
6444                    };
6445                    let value = super::evaluate_single(
6446                        &mut absolute_runtime,
6447                        EvaluationTarget::SamplingLaw(&signed_probe),
6448                        &selected,
6449                        &identity,
6450                        &mut metadata,
6451                        Some(&selected),
6452                        RepresentationMode::Cff,
6453                    )?;
6454                    assert!(
6455                        (2.0 * value.absolute_integrand_result.unwrap().re.into_ff64().0 - 1.0)
6456                            .abs()
6457                            < 1.0e-8
6458                    );
6459                }
6460                // Opposite graph pieces at the SAME physical channel point
6461                // cancel before abs, including the imaginary component.
6462                let mut grouped = absolute_runtime.clone();
6463                grouped
6464                    .data
6465                    .graph_terms
6466                    .push(grouped.data.graph_terms[0].clone());
6467                grouped.data.graph_to_group_id.push(0);
6468                let mut grouped_draw = draw.clone();
6469                for row in &draw.groups[0].1 {
6470                    let mut partner = row.clone();
6471                    partner.graph_id = 1;
6472                    grouped_draw.groups[0].1.push(partner);
6473                }
6474                signed_probe.alternating_graph_sign = true;
6475                let canceled = super::evaluate_single(
6476                    &mut grouped,
6477                    EvaluationTarget::SamplingLaw(&signed_probe),
6478                    &grouped_draw,
6479                    &identity,
6480                    &mut metadata,
6481                    Some(&grouped_draw),
6482                    RepresentationMode::Cff,
6483                )?;
6484                signed_probe.alternating_graph_sign = false;
6485                assert_eq!(canceled.integrand_result, Complex::new_re(draw.zero()));
6486                assert_eq!(
6487                    canceled.absolute_integrand_result,
6488                    Some(Complex::new_re(draw.zero()))
6489                );
6490            }
6491            // Exercise the pre-stability numerical failure boundary on this
6492            // generated physical cut without requiring a platform-dependent
6493            // Clarabel termination status. The original proposal stays fixed.
6494            let healthy_setup = integrand.get_graph(0).sampling_setup().clone();
6495            let overlap_failure = super::sampling::maps::SamplingEvaluationError::UncertifiedOverlap {
6496                detail: "Threshold SOCP returned AlmostPrimalInfeasible without a strictly interior center".into(),
6497            };
6498            let setup = integrand.get_graph_mut(0).sampling_setup_mut();
6499            if fixed256 {
6500                setup.sampling_bridge_fixed256.set(Err(overlap_failure));
6501            } else {
6502                setup.sampling_bridge_quad.set(Err(overlap_failure));
6503            }
6504            let failed = evaluate_from_source_precise(
6505                integrand,
6506                EvaluationTarget::Physical(model),
6507                EvaluationSource::XSpace(source),
6508                F(1.0),
6509                false,
6510                Complex::new_zero(),
6511            )?
6512            .try_into_f64()?;
6513            assert!(failed.evaluation_metadata.is_nan);
6514            assert!(failed.event_groups.is_empty());
6515            assert_eq!(
6516                failed.evaluation_metadata.final_precision(),
6517                Some(Precision::Arb)
6518            );
6519            assert_eq!(
6520                failed
6521                    .evaluation_metadata
6522                    .stability_results
6523                    .iter()
6524                    .map(|result| (result.precision, result.status.clone()))
6525                    .collect::<Vec<_>>(),
6526                [Precision::Double, Precision::Quad, Precision::Arb]
6527                    .into_iter()
6528                    .map(|precision| (
6529                        precision,
6530                        crate::integrands::evaluation::StabilityStatus::Unstable(0)
6531                    ))
6532                    .collect::<Vec<_>>()
6533            );
6534            assert!(
6535                failed
6536                    .evaluation_metadata
6537                    .threshold_counterterm_error
6538                    .as_ref()
6539                    .unwrap()
6540                    .contains("AlmostPrimalInfeasible")
6541            );
6542            assert!(
6543                serde_json::to_string(&failed.evaluation_metadata)?
6544                    .contains("AlmostPrimalInfeasible")
6545            );
6546            assert_eq!(
6547                failed.evaluation_metadata.evaluator_evaluation_time,
6548                std::time::Duration::ZERO
6549            );
6550            *integrand.get_graph_mut(0).sampling_setup_mut() = healthy_setup.clone();
6551            let following = evaluate_from_source_precise(
6552                integrand,
6553                EvaluationTarget::Physical(model),
6554                EvaluationSource::XSpace(source),
6555                F(1.0),
6556                false,
6557                Complex::new_zero(),
6558            )?
6559            .try_into_f64()?;
6560            assert!(!following.evaluation_metadata.is_nan);
6561            assert!(
6562                following
6563                    .evaluation_metadata
6564                    .threshold_counterterm_error
6565                    .is_none()
6566            );
6567            assert!(following.integrand_result.re.0.is_finite());
6568            assert!(following.integrand_result.im.0.is_finite());
6569            // Missing fixed-source metadata is a programming/configuration
6570            // error, not a failed numerical sample to record and skip.
6571            integrand
6572                .get_graph_mut(0)
6573                .sampling_setup_mut()
6574                .sampling_source = RuntimeCache::default();
6575            let malformed = evaluate_from_source_precise(
6576                integrand,
6577                EvaluationTarget::Physical(model),
6578                EvaluationSource::XSpace(source),
6579                F(1.0),
6580                false,
6581                Complex::new_zero(),
6582            )
6583            .unwrap_err();
6584            assert!(format!("{malformed:#}").contains("fixed sampling source is not initialized"));
6585            *integrand.get_graph_mut(0).sampling_setup_mut() = healthy_setup;
6586
6587            let unavailable = super::sampling::maps::SamplingEvaluationError::Unrepresentable {
6588                operation: "test-only fixed source poison",
6589                detail: "cannot redraw at Arb".into(),
6590            };
6591            let setup = integrand.get_graph_mut(0).sampling_setup_mut();
6592            if fixed256 {
6593                setup.sampling_bridge_fixed256.set(Err(unavailable));
6594            } else {
6595                setup.sampling_bridge_quad.set(Err(unavailable));
6596            }
6597            let failure = evaluate_from_source_precise(
6598                integrand,
6599                EvaluationTarget::SamplingLaw(&probe),
6600                EvaluationSource::XSpace(source),
6601                F(1.0),
6602                false,
6603                Complex::new_zero(),
6604            )
6605            .unwrap_err();
6606            assert!(format!("{failure:#}").contains("fixed source precision"));
6607            assert!(
6608                probe
6609                    .calls
6610                    .iter()
6611                    .all(|calls| calls.load(Ordering::Relaxed) == 0)
6612            );
6613            let input = super::MomentumSpaceEvaluationInput {
6614                loop_momenta: vec![ThreeMomentum::new(F(0.1), F(0.2), F(0.3))],
6615                integrator_weight: F(1.0),
6616                graph_id: Some(0),
6617                group_id: None,
6618                orientation: None,
6619                channel_id: None,
6620            };
6621            let raw = EvaluationSource::Momentum {
6622                input: &input,
6623                candidate_lmb: None,
6624            }
6625            .prepare_draw(integrand, &mut metadata)?
6626            .unwrap();
6627            assert_eq!(
6628                raw.get_default_sample().loop_moms().0[0].px,
6629                F(0.1).to_arb_exact()?
6630            );
6631            let selected_input = super::MomentumSpaceEvaluationInput {
6632                channel_id: Some(SamplingChannelId(0)),
6633                ..input
6634            };
6635            assert!(
6636                EvaluationSource::Momentum {
6637                    input: &selected_input,
6638                    candidate_lmb: None
6639                }
6640                .prepare_draw(integrand, &mut metadata)
6641                .is_err()
6642            );
6643        }
6644        runtime.get_mut_settings().sampling = original_sampling;
6645        // Fixed inputs and accuracy select an epoch, never an active point.
6646        let floor = F::<QuadFloat>::default().epsilon().sqrt().into_ff64().0;
6647        let settings = runtime.get_mut_settings();
6648        for level in &mut settings.stability.levels {
6649            level.required_precision_for_re = floor * 10.0;
6650            level.required_precision_for_im = floor * 10.0;
6651        }
6652        runtime.warm_up(model)?;
6653        let ProcessIntegrand::CrossSection(integrand) = runtime else {
6654            unreachable!()
6655        };
6656        let (precision, budget) = integrand.sampling_source_policy()?;
6657        assert!(budget >= floor);
6658        assert_eq!(precision, SamplingPrecision::Quad);
6659        runtime.get_mut_settings().stability.levels[2].required_precision_for_re = 1.0e-20;
6660        runtime.warm_up(model)?;
6661        let ProcessIntegrand::CrossSection(integrand) = runtime else {
6662            unreachable!()
6663        };
6664        assert_eq!(
6665            integrand
6666                .get_graph(0)
6667                .sampling_setup()
6668                .sampling_source
6669                .as_ref()
6670                .unwrap()
6671                .0,
6672            SamplingPrecision::Fixed256
6673        );
6674        let fixed256_floor = F::<SamplingFloat>::default().epsilon().sqrt().into_ff64().0;
6675        runtime.get_mut_settings().stability.levels[2].required_precision_for_re = fixed256_floor;
6676        runtime.warm_up(model)?;
6677        let ProcessIntegrand::CrossSection(integrand) = runtime else {
6678            unreachable!()
6679        };
6680        assert_eq!(
6681            integrand.sampling_source_policy()?.0,
6682            SamplingPrecision::Arb
6683        );
6684        assert!(
6685            integrand
6686                .get_graph(0)
6687                .sampling_setup()
6688                .sampling_bridge_fixed256
6689                .as_ref()
6690                .is_none()
6691        );
6692        Ok(())
6693    }
6694
6695    /// Exercise source-private lifetime boundaries from the generated host fixture.
6696    pub(crate) fn check_host_source_transport<I: super::ProcessIntegrandImpl>(
6697        integrand: &mut I,
6698        model: &crate::model::Model,
6699        source: &symbolica::numerical_integration::Sample<F<f64>>,
6700        graph_id: usize,
6701        channel_id: SamplingChannelId,
6702    ) -> color_eyre::Result<()> {
6703        use super::{EvaluationSource, gammaloop_sample::unwrap_sample};
6704        use crate::{
6705            integrands::evaluation::EvaluationMetaData,
6706            momentum::{Rotatable, Rotation, RotationMethod},
6707            utils::{QuadFloat, newton_solver::RadialRootDiagnostics},
6708        };
6709        use symbolica::numerical_integration::Sample;
6710
6711        assert_eq!(
6712            integrand
6713                .get_graph(0)
6714                .sampling_setup()
6715                .sampling_source
6716                .as_ref()
6717                .unwrap()
6718                .0,
6719            super::SamplingPrecision::Fixed256,
6720        );
6721        integrand.prepare_sampling_precision::<super::ArbPrec>()?;
6722        let mut metadata = EvaluationMetaData::new_empty();
6723        // Seed an existing physical occurrence so successful and failed source
6724        // preparation/debug operations must preserve nonempty history as well.
6725        metadata
6726            .radial_root_diagnostics
6727            .solve(
6728                &crate::utils::newton_solver::RadialRootIdentity::new(
6729                    "existing physical occurrence".into(),
6730                ),
6731                &F(0.0),
6732                &F(2.0),
6733                |r| (*r - F(1.0), F(1.0)),
6734                &F(1.0e-8),
6735                32,
6736                8,
6737                &F(1.0),
6738            )
6739            .unwrap();
6740        let original_source = EvaluationSource::XSpace(source);
6741        let mut anchor = original_source
6742            .prepare_draw(integrand, &mut metadata)?
6743            .unwrap();
6744        let sampling_preparation_time = metadata.canonical_sampling_preparation_time;
6745        assert!(sampling_preparation_time > std::time::Duration::ZERO);
6746        assert_eq!(metadata.parameterization_time, sampling_preparation_time);
6747        anchor.prepare_physical_overlaps(integrand, model, &mut metadata)?;
6748        // Clear only the test control's retained host so the physical owner must
6749        // solve its original Arb cut equation independently at this same point.
6750        let mut independent = anchor.clone();
6751        for (_, rows) in &mut independent.groups {
6752            for row in rows {
6753                row.prepared_lu_hosts.clear();
6754                row.physical_overlaps = None;
6755            }
6756        }
6757        let mut independent_metadata = EvaluationMetaData::new_empty();
6758        independent.prepare_physical_overlaps(integrand, model, &mut independent_metadata)?;
6759        let identity = Rotation::new(RotationMethod::Identity);
6760        let adopted_arb = super::evaluate_single(
6761            integrand,
6762            super::EvaluationTarget::Physical(model),
6763            &anchor,
6764            &identity,
6765            &mut EvaluationMetaData::new_empty(),
6766            Some(&anchor),
6767            RepresentationMode::Cff,
6768        )?;
6769        let independent_arb = super::evaluate_single(
6770            integrand,
6771            super::EvaluationTarget::Physical(model),
6772            &independent,
6773            &identity,
6774            &mut independent_metadata,
6775            Some(&independent),
6776            RepresentationMode::Cff,
6777        )?;
6778        for (adopted, solved) in [
6779            (
6780                &adopted_arb.integrand_result.re,
6781                &independent_arb.integrand_result.re,
6782            ),
6783            (
6784                &adopted_arb.integrand_result.im,
6785                &independent_arb.integrand_result.im,
6786            ),
6787        ] {
6788            let scale = adopted
6789                .abs()
6790                .max(solved.abs())
6791                .max(adopted.one() / adopted.from_usize(10).powi(25));
6792            assert!((adopted - solved).abs() <= scale / adopted.from_usize(10).powi(12));
6793        }
6794        assert_eq!(metadata.generated_event_count, 0);
6795        assert_eq!(metadata.accepted_event_count, 0);
6796        let preparation_time = metadata.canonical_physical_preparation_time;
6797        let prepared_source = EvaluationSource::Prepared {
6798            sample: &anchor,
6799            original: &original_source,
6800        };
6801        assert!(
6802            prepared_source
6803                .prepare_draw(integrand, &mut metadata)?
6804                .is_none()
6805        );
6806        let original = prepared_source.build_gamma_sample::<f64, _>(integrand, &mut metadata)?;
6807        assert_eq!(
6808            metadata.canonical_sampling_preparation_time,
6809            sampling_preparation_time
6810        );
6811        let prepared_lu_hosts = &original.groups[0].1[0].prepared_lu_hosts;
6812        assert_eq!(original.groups[0].1[0].channel_id, Some(channel_id));
6813        assert!(!prepared_lu_hosts.is_empty());
6814        for host in prepared_lu_hosts {
6815            assert_eq!(host.source.graph_id, graph_id);
6816            assert_eq!(host.source.generating_channel, channel_id);
6817            assert_eq!(host.source.target_channel, channel_id);
6818        }
6819        let history = format!("{:?}", metadata.radial_root_diagnostics);
6820        assert_ne!(history, format!("{:?}", RadialRootDiagnostics::default()));
6821        let rotation = Rotation::new(RotationMethod::Pi2Z);
6822        let rotated = original.rotate(&rotation, 17, 23);
6823        let canonical_overlaps = anchor.groups[0].1[0].physical_overlaps.as_ref().unwrap();
6824        assert!(std::sync::Arc::ptr_eq(
6825            canonical_overlaps,
6826            rotated.groups[0].1[0].physical_overlaps.as_ref().unwrap(),
6827        ));
6828        let retained = &rotated.groups[0].1[0].prepared_lu_hosts;
6829        assert_eq!(retained.len(), prepared_lu_hosts.len());
6830        for (before, after) in prepared_lu_hosts.iter().zip(retained) {
6831            assert_eq!(before.plan, after.plan);
6832            assert_eq!(before.source, after.source);
6833            assert_eq!(before.prior, after.prior);
6834            assert_eq!(before.solution.solution, after.solution.solution);
6835            assert_eq!(
6836                before.solution.derivative_at_solution,
6837                after.solution.derivative_at_solution
6838            );
6839            assert_eq!(
6840                before.solution.error_of_function,
6841                after.solution.error_of_function
6842            );
6843            assert_eq!(
6844                before.solution.num_iterations_used,
6845                after.solution.num_iterations_used
6846            );
6847            for t in [F(0.0), F(1.0), before.solution.solution] {
6848                assert_eq!(before.ray.evaluate(&t), after.ray.evaluate(&t));
6849            }
6850        }
6851        let original_momenta = original.get_default_sample().loop_moms();
6852        let rotated_momenta = rotated.get_default_sample().loop_moms();
6853        assert!(original_momenta.0.iter().any(|p| p != &p.rotate(&rotation)));
6854        for (before, after) in original_momenta.0.iter().zip(&rotated_momenta.0) {
6855            assert_eq!(*after, before.rotate(&rotation));
6856        }
6857        assert_eq!(rotated.get_default_sample().sample.loop_mom_cache_id, 17);
6858
6859        // Successful physical adoption must also respect a nonidentity probe.
6860        // Keep the original source/host payload and compare the complete raised
6861        // estimator and normal identity/probe event policy, without another
6862        // generation or grid.
6863        let mut baseline_metadata = metadata.clone();
6864        let baseline = super::evaluate_single(
6865            integrand,
6866            super::EvaluationTarget::Physical(model),
6867            &original,
6868            &Rotation::new(RotationMethod::Identity),
6869            &mut baseline_metadata,
6870            Some(&anchor),
6871            RepresentationMode::Cff,
6872        )?;
6873        let mut rotated_metadata = metadata.clone();
6874        let physical_rotated = super::evaluate_single(
6875            integrand,
6876            super::EvaluationTarget::Physical(model),
6877            &rotated,
6878            &rotation,
6879            &mut rotated_metadata,
6880            Some(&anchor),
6881            RepresentationMode::Cff,
6882        )?;
6883        assert_eq!(
6884            baseline_metadata.canonical_physical_preparation_time,
6885            preparation_time
6886        );
6887        assert_eq!(
6888            rotated_metadata.canonical_physical_preparation_time,
6889            preparation_time
6890        );
6891        // Both identity and stability-probe evaluator work contributes to E;
6892        // preparing or adopting the retained source does not repeat C_S.
6893        for physical_metadata in [&baseline_metadata, &rotated_metadata] {
6894            assert!(
6895                physical_metadata.evaluator_evaluation_time > metadata.evaluator_evaluation_time
6896            );
6897            assert_eq!(
6898                physical_metadata.canonical_sampling_preparation_time,
6899                sampling_preparation_time
6900            );
6901        }
6902        for result in [&baseline, &physical_rotated] {
6903            assert!(result.integrand_result.re.0.is_finite());
6904            assert!(result.integrand_result.im.0.is_finite());
6905            assert!(result.integrand_result.re.0.abs() + result.integrand_result.im.0.abs() > 0.0);
6906        }
6907        for (a, b) in [
6908            (
6909                baseline.integrand_result.re.0,
6910                physical_rotated.integrand_result.re.0,
6911            ),
6912            (
6913                baseline.integrand_result.im.0,
6914                physical_rotated.integrand_result.im.0,
6915            ),
6916        ] {
6917            assert!(
6918                (a - b).abs() <= 1.0e-8 * a.abs().max(b.abs()).max(1.0e-25),
6919                "rotated physical contribution {b} != {a}"
6920            );
6921        }
6922        let baseline_events = baseline
6923            .event_groups
6924            .iter()
6925            .flat_map(|group| group.iter())
6926            .collect::<Vec<_>>();
6927        assert!(!baseline_events.is_empty());
6928        assert!(
6929            baseline_events
6930                .iter()
6931                .all(|event| event.weight.re.0.is_finite() && event.weight.im.0.is_finite())
6932        );
6933        // prepare_buffered_event intentionally retains/counts identity events
6934        // only; a rotated probe builds transient selector data when needed.
6935        // The surrounding fixture compares identity selected/direct event weights.
6936        assert!(physical_rotated.event_groups.is_empty());
6937        assert_eq!(physical_rotated.generated_event_count, 0);
6938        assert_eq!(physical_rotated.accepted_event_count, 0);
6939
6940        // Losing a canonical accepted cut is not a request to choose a new
6941        // overlap. The real physical boundary must reject it before CT work.
6942        let mut incomplete = anchor.clone();
6943        let overlaps = std::sync::Arc::make_mut(
6944            incomplete.groups[0].1[0]
6945                .physical_overlaps
6946                .as_mut()
6947                .unwrap(),
6948        );
6949        let accepted = overlaps.iter_mut().find(|entry| entry.is_some()).unwrap();
6950        *accepted = None;
6951        let mut incomplete_metadata = metadata.clone();
6952        let error = super::evaluate_single(
6953            integrand,
6954            super::EvaluationTarget::Physical(model),
6955            &original,
6956            &Rotation::new(RotationMethod::Identity),
6957            &mut incomplete_metadata,
6958            Some(&incomplete),
6959            RepresentationMode::Cff,
6960        )
6961        .unwrap_err();
6962        assert!(
6963            error
6964                .downcast_ref::<super::sampling::maps::SamplingEvaluationError>()
6965                .is_some(),
6966            "{error:?}"
6967        );
6968        assert!(
6969            error.to_string().contains("selector/cut membership"),
6970            "{error:?}"
6971        );
6972        assert_eq!(
6973            incomplete_metadata.canonical_physical_preparation_time,
6974            preparation_time
6975        );
6976
6977        // A claimed selected record with another graph ID is corruption,
6978        // not an ordinary graph-group member for which no authority is supplied.
6979        let mut corrupted = original.clone();
6980        let claimed_hosts = &mut corrupted.groups[0].1[0].prepared_lu_hosts;
6981        claimed_hosts[0].source.graph_id = graph_id.wrapping_add(1);
6982        let reference =
6983            super::GaussianReferenceFunction::new(1.0, vec![0.0; 3 * original_momenta.0.len()])?;
6984        let error = super::evaluate_single(
6985            integrand,
6986            super::EvaluationTarget::Reference(&reference),
6987            &corrupted,
6988            &rotation,
6989            &mut metadata,
6990            None,
6991            RepresentationMode::Cff,
6992        )
6993        .unwrap_err();
6994        assert!(
6995            error.to_string().contains("graph-group master"),
6996            "{error:?}"
6997        );
6998        assert_eq!(history, format!("{:?}", metadata.radial_root_diagnostics));
6999
7000        // A valid alternate parent still does not belong to the selected
7001        // immutable channel. Exercise actual physical adoption, where this
7002        // mismatch and a forged active representative must fail before roots/events.
7003        for forge_parent in [true, false] {
7004            let mut corrupted = original.clone();
7005            let claimed_hosts = &mut corrupted.groups[0].1[0].prepared_lu_hosts;
7006            let plan = std::sync::Arc::make_mut(&mut claimed_hosts[0].plan);
7007            let expected = if forge_parent {
7008                assert!(plan.parent_lmb.len() >= 2);
7009                plan.parent_lmb.swap(0, 1);
7010                "selected channel definition"
7011            } else {
7012                plan.representative_cut_id.0 = plan.representative_cut_id.0.wrapping_add(1);
7013                "incompatible active representative"
7014            };
7015            let error = super::evaluate_single(
7016                integrand,
7017                super::EvaluationTarget::Physical(model),
7018                &corrupted,
7019                &rotation,
7020                &mut metadata,
7021                None,
7022                RepresentationMode::Cff,
7023            )
7024            .unwrap_err();
7025            assert!(error.to_string().contains(expected), "{error:?}");
7026            assert_eq!(history, format!("{:?}", metadata.radial_root_diagnostics));
7027        }
7028
7029        // Norm/debug now consume this same retained draw and cannot prepare
7030        // roots or advance the physical retry occurrence/history owner.
7031        let before_time = metadata.parameterization_time;
7032        prepared_source.loop_norm_sum(integrand, &mut metadata)?;
7033        assert_eq!(history, format!("{:?}", metadata.radial_root_diagnostics));
7034        prepared_source.debug_sample(integrand, &mut metadata)?;
7035        assert_eq!(history, format!("{:?}", metadata.radial_root_diagnostics));
7036        let mut large_factor = anchor.clone();
7037        large_factor.groups[0].1[0].sample.sample.jacobian *=
7038            F::<crate::utils::ArbPrec>::from_f64(2.0).powi(2048);
7039        let large_factor_source = EvaluationSource::Prepared {
7040            sample: &large_factor,
7041            original: &original_source,
7042        };
7043        assert_eq!(
7044            large_factor_source.loop_norm_sum(integrand, &mut metadata)?,
7045            prepared_source.loop_norm_sum(integrand, &mut metadata)?
7046        );
7047        assert!(
7048            large_factor_source
7049                .debug_sample(integrand, &mut metadata)
7050                .is_err()
7051        );
7052        assert_eq!(history, format!("{:?}", metadata.radial_root_diagnostics));
7053        let (selection, mut coordinates) = unwrap_sample::<f64>(source);
7054        coordinates[0] = F(f64::NAN);
7055        let invalid = Sample::Uniform(F(1.0), selection, coordinates);
7056        assert!(
7057            EvaluationSource::XSpace(&invalid)
7058                .loop_norm_sum(integrand, &mut metadata)
7059                .is_err()
7060        );
7061        assert_eq!(history, format!("{:?}", metadata.radial_root_diagnostics));
7062        assert!(
7063            EvaluationSource::XSpace(&invalid)
7064                .debug_sample(integrand, &mut metadata)
7065                .is_err()
7066        );
7067        assert_eq!(history, format!("{:?}", metadata.radial_root_diagnostics));
7068        assert!(metadata.parameterization_time >= before_time);
7069
7070        // Quad materializes the original canonical record directly; no earlier
7071        // Double geometry is promoted and no map/root is replayed.
7072        let quad = prepared_source.build_gamma_sample::<QuadFloat, _>(integrand, &mut metadata)?;
7073        let native = &quad.groups[0].1[0].prepared_lu_hosts;
7074        assert_eq!(native.len(), prepared_lu_hosts.len());
7075        for (before, after) in prepared_lu_hosts.iter().zip(native) {
7076            assert_eq!(before.plan, after.plan);
7077            assert_eq!(before.source, after.source);
7078            assert_eq!(before.prior.len(), after.prior.len());
7079        }
7080        let mut direct_momenta = original_momenta.0.clone();
7081        direct_momenta[0].px = F(0.1);
7082        let direct = super::MomentumSpaceEvaluationInput {
7083            loop_momenta: direct_momenta,
7084            integrator_weight: F(1.0),
7085            graph_id: Some(graph_id),
7086            group_id: None,
7087            channel_id: None,
7088            orientation: None,
7089        };
7090        let raw_source = EvaluationSource::Momentum {
7091            input: &direct,
7092            candidate_lmb: None,
7093        };
7094        let mut raw_anchor = raw_source.prepare_draw(integrand, &mut metadata)?.unwrap();
7095        raw_anchor.prepare_physical_overlaps(integrand, model, &mut metadata)?;
7096        assert!(
7097            raw_anchor
7098                .groups
7099                .iter()
7100                .flat_map(|(_, rows)| rows)
7101                .all(|row| {
7102                    row.channel_id.is_none()
7103                        && row.prepared_lu_hosts.is_empty()
7104                        && row.physical_overlaps.is_some()
7105                })
7106        );
7107        let raw_prepared = EvaluationSource::Prepared {
7108            sample: &raw_anchor,
7109            original: &raw_source,
7110        };
7111        let raw_quad = raw_prepared.build_gamma_sample::<QuadFloat, _>(integrand, &mut metadata)?;
7112        assert_eq!(
7113            raw_quad.get_default_sample().loop_moms().0[0].px.0,
7114            <QuadFloat as crate::utils::FloatLike>::from_f64_exact_binary(0.1)
7115        );
7116        assert!(
7117            raw_quad
7118                .groups
7119                .iter()
7120                .flat_map(|(_, rows)| rows)
7121                .all(|row| row.channel_id.is_none() && row.prepared_lu_hosts.is_empty())
7122        );
7123        // The UV/IR profile path enters through this same source owner. Large
7124        // exact input tokens make affine shifts smaller than binary64 spacing;
7125        // compare every physical edge after the production canonical routing.
7126        let selected_graph = integrand.get_graph(graph_id).get_graph().clone();
7127        let profile_input = super::MomentumSpaceEvaluationInput {
7128            loop_momenta: direct
7129                .loop_momenta
7130                .iter()
7131                .map(|_| {
7132                    ThreeMomentum::new(F(2_f64.powi(80)), F(-2_f64.powi(81)), F(2_f64.powi(82)))
7133                })
7134                .collect(),
7135            ..direct
7136        };
7137        let unrouted_source = EvaluationSource::Momentum {
7138            input: &profile_input,
7139            candidate_lmb: None,
7140        };
7141        let unrouted = unrouted_source
7142            .prepare_draw(integrand, &mut metadata)?
7143            .unwrap();
7144        let input_sample = unrouted.get_default_sample();
7145        let external_spatial = input_sample
7146            .sample
7147            .external_moms
7148            .iter()
7149            .map(|momentum| momentum.spatial.clone())
7150            .collect::<crate::momentum::sample::ExternalThreeMomenta<_>>();
7151        // Cross-section preprocessing promotes initial-state cut loops to
7152        // external momenta. Reuse its physical basis catalogue: a fresh spanning
7153        // tree enumeration would reintroduce those external loops.
7154        let setup = integrand.get_graph(graph_id).sampling_setup();
7155        assert_eq!(
7156            setup.graph.loop_momentum_basis,
7157            selected_graph.loop_momentum_basis
7158        );
7159        let candidates = setup.all_bases.clone();
7160        assert!(!candidates.is_empty());
7161        assert!(candidates.iter().any(|candidate| {
7162            candidate.loop_edges != selected_graph.loop_momentum_basis.loop_edges
7163        }));
7164        for candidate in &candidates {
7165            assert_eq!(candidate.loop_edges.len(), profile_input.loop_momenta.len());
7166            let profile_source = EvaluationSource::Momentum {
7167                input: &profile_input,
7168                candidate_lmb: Some(candidate),
7169            };
7170            let canonical = profile_source
7171                .prepare_draw(integrand, &mut metadata)?
7172                .unwrap();
7173            assert_eq!(canonical.groups[0].1[0].graph_id, graph_id);
7174            let prepared = EvaluationSource::Prepared {
7175                sample: &canonical,
7176                original: &profile_source,
7177            };
7178            let native =
7179                prepared.build_gamma_sample::<super::ArbPrec, _>(integrand, &mut metadata)?;
7180            let routed = native.get_default_sample();
7181            for (_, edge_id, _) in selected_graph.underlying.iter_edges() {
7182                let expected: ThreeMomentum<F<super::ArbPrec>> = candidate.edge_signatures[edge_id]
7183                    .compute_momentum(input_sample.loop_moms(), &external_spatial);
7184                let actual: ThreeMomentum<F<super::ArbPrec>> =
7185                    selected_graph.loop_momentum_basis.edge_signatures[edge_id]
7186                        .compute_momentum(routed.loop_moms(), &external_spatial);
7187                assert_eq!(
7188                    actual, expected,
7189                    "canonical profile source changed edge {edge_id:?}"
7190                );
7191            }
7192        }
7193        Ok(())
7194    }
7195
7196    /// Reuse the generated kite fixture while retaining the real source,
7197    /// partition and native stability owners. The final target alone is a probe.
7198    pub(super) fn check_joint_policy_source_replay(
7199        integrand: &super::ProcessIntegrand,
7200        model: &crate::model::Model,
7201        joint_id: super::SamplingChannelId,
7202        cube: &[f64],
7203    ) -> color_eyre::Result<()> {
7204        use super::{
7205            EvaluationSource, EvaluationTarget, GraphTerm, ProcessIntegrand, ProcessIntegrandImpl,
7206            SamplingLawProbe, evaluate_from_source_precise,
7207        };
7208        use crate::{
7209            integrands::evaluation::StabilityStatus,
7210            settings::runtime::{
7211                Precision, SamplingChannelWeight, SamplingSettingsParser, StabilityLevelSetting,
7212                SumMode,
7213            },
7214            utils::{ArbPrec, SamplingFloat, SamplingPrecision},
7215        };
7216        use spenso::algebra::complex::Complex;
7217        use std::sync::atomic::{AtomicUsize, Ordering};
7218        use symbolica::numerical_integration::Sample;
7219
7220        let mut runtime = integrand.clone();
7221        let mut parser: SamplingSettingsParser =
7222            toml::from_str(&toml::to_string(&runtime.get_settings().sampling)?)?;
7223        parser.graphs = SumMode::MonteCarlo;
7224        parser.orientations = SumMode::Summed;
7225        parser.sampling_channels = SumMode::MonteCarlo;
7226        parser.sampling_channel_weight = SamplingChannelWeight::SingularityProxy;
7227        for definitions in parser.channel_definitions.values_mut() {
7228            for definition in definitions.values_mut() {
7229                definition.singularity_proxy = Some("1".into());
7230            }
7231        }
7232        runtime.get_mut_settings().sampling = toml::from_str(&toml::to_string(&parser)?)?;
7233        let stability = &mut runtime.get_mut_settings().stability;
7234        stability.rotation_axis.clear();
7235        stability.escalate_if_exact_zero = false;
7236        stability.loop_momenta_norm_escalation_factor = 0.0;
7237        stability.levels = vec![
7238            StabilityLevelSetting::default_double(),
7239            StabilityLevelSetting::default_quad(),
7240        ];
7241        runtime.warm_up(model)?;
7242        let ProcessIntegrand::Amplitude(amplitude) = &mut runtime else {
7243            unreachable!("the fixture is the generated kite amplitude")
7244        };
7245        amplitude.prepare_sampling_precision::<ArbPrec>()?;
7246        let reference = amplitude.get_graph(0).sampling_setup().clone();
7247        assert_eq!(reference.sampling_bridge::<f64>()?.channels().len(), 2);
7248        let ordinary_name = reference
7249            .sampling_bridge::<f64>()?
7250            .channels()
7251            .iter()
7252            .find(|channel| channel.contract().support == super::SamplingSupport::Full)
7253            .unwrap()
7254            .name
7255            .clone();
7256        let mut probe = SamplingLawProbe {
7257            reference: &reference,
7258            channel_id: joint_id,
7259            radial_coordinate: 3,
7260            retry_lower_half: true,
7261            sign_coordinate: None,
7262            alternating_graph_sign: false,
7263            calls: std::array::from_fn(|_| AtomicUsize::new(0)),
7264        };
7265        for graph in amplitude.get_terms_mut() {
7266            let unavailable = super::sampling::maps::SamplingEvaluationError::Unrepresentable {
7267                operation: "test-only native map poison",
7268                detail: "physical retry must consume the canonical draw".into(),
7269            };
7270            graph
7271                .sampling_setup_mut()
7272                .sampling_bridge
7273                .set(Err(unavailable.clone()));
7274            graph
7275                .sampling_setup_mut()
7276                .sampling_bridge_quad
7277                .set(Err(unavailable));
7278        }
7279        for radial in [0.25, 0.75] {
7280            for calls in &probe.calls {
7281                calls.store(0, Ordering::Relaxed);
7282            }
7283            let mut coordinates = cube.to_vec();
7284            coordinates[3] = radial;
7285            // The outer weight includes the inverse channel probability 2.
7286            // Both support-gated constant proxies equal one on q_rho's patch.
7287            let source = Sample::Discrete(
7288                F(2.0),
7289                0,
7290                Some(Box::new(Sample::Discrete(
7291                    F(1.0),
7292                    joint_id.index(),
7293                    Some(Box::new(Sample::Continuous(
7294                        F(1.0),
7295                        coordinates.into_iter().map(F).collect(),
7296                    ))),
7297                ))),
7298            );
7299            let ProcessIntegrand::Amplitude(amplitude) = &mut runtime else {
7300                unreachable!()
7301            };
7302            let result = evaluate_from_source_precise(
7303                amplitude,
7304                EvaluationTarget::SamplingLaw(&probe),
7305                EvaluationSource::XSpace(&source),
7306                F(2.0),
7307                false,
7308                Complex::new_zero(),
7309            )?
7310            .try_into_f64()?;
7311            let retried = radial < 0.5;
7312            assert!(
7313                !result.evaluation_metadata.is_nan
7314                    && result.integrand_result.re.0.is_finite()
7315                    && result.integrand_result.im.0.is_finite(),
7316                "nonfinite final retry result at radial {radial}: {result:?}"
7317            );
7318            assert_eq!(
7319                probe.calls[0].load(Ordering::Relaxed),
7320                1,
7321                "Double body call count at radial {radial}: {:?}",
7322                result.evaluation_metadata.stability_results
7323            );
7324            assert_eq!(
7325                probe.calls[1].load(Ordering::Relaxed),
7326                usize::from(retried),
7327                "Quad body call count at radial {radial}: {:?}",
7328                result.evaluation_metadata.stability_results
7329            );
7330            assert_eq!(
7331                probe.calls[2].load(Ordering::Relaxed),
7332                0,
7333                "canonical preparation must not evaluate the target"
7334            );
7335            assert_eq!(
7336                result.evaluation_metadata.final_precision(),
7337                Some(if retried {
7338                    Precision::Quad
7339                } else {
7340                    Precision::Double
7341                })
7342            );
7343            assert_eq!(
7344                result.evaluation_metadata.stability_results.len(),
7345                1 + usize::from(retried)
7346            );
7347            if retried {
7348                let first = &result.evaluation_metadata.stability_results[0];
7349                assert_eq!(first.precision, Precision::Double);
7350                // A single identity probe is reported as Unknown regardless
7351                // of its acceptance. Body calls and the two native levels
7352                // above establish the intended nonfinite-Double retry.
7353                assert_eq!(first.status, StabilityStatus::Unknown);
7354            }
7355            assert!(
7356                (result.integrand_result.re.0 * result.integrator_weight.0 - 1.0).abs() < 1.0e-8
7357            );
7358            let policies = result
7359                .evaluation_metadata
7360                .sampling_proposal_policies
7361                .clone();
7362            assert!(!policies.is_collecting());
7363            assert_eq!(policies.len(), 1);
7364            let mut replay_metadata = result.evaluation_metadata.clone();
7365            let before = replay_metadata.parameterization_time;
7366            EvaluationSource::XSpace(&source).debug_sample(amplitude, &mut replay_metadata)?;
7367            assert!(replay_metadata.parameterization_time >= before);
7368            assert_eq!(
7369                replay_metadata.integrand_evaluation_time,
7370                result.evaluation_metadata.integrand_evaluation_time
7371            );
7372            assert_eq!(replay_metadata.sampling_proposal_policies, policies);
7373
7374            let mut quad_only = runtime.clone();
7375            quad_only.get_mut_settings().stability.levels =
7376                vec![StabilityLevelSetting::default_quad()];
7377            quad_only.warm_up(model)?;
7378            let ProcessIntegrand::Amplitude(amplitude) = &mut quad_only else {
7379                unreachable!()
7380            };
7381            let direct = evaluate_from_source_precise(
7382                amplitude,
7383                EvaluationTarget::SamplingLaw(&probe),
7384                EvaluationSource::XSpace(&source),
7385                F(2.0),
7386                false,
7387                Complex::new_zero(),
7388            )?
7389            .try_into_f64()?;
7390            assert!((result.integrand_result.re.0 - direct.integrand_result.re.0).abs() < 1.0e-10);
7391            assert_eq!(
7392                result.evaluation_metadata.sampling_proposal_policies,
7393                direct.evaluation_metadata.sampling_proposal_policies
7394            );
7395
7396            // An active-point norm may choose Quad immediately, but cannot
7397            // bypass the canonical phase or initialize policy in that lane.
7398            let mut norm_escalated = runtime.clone();
7399            norm_escalated
7400                .get_mut_settings()
7401                .stability
7402                .loop_momenta_norm_escalation_factor = 1.0e-6;
7403            norm_escalated.warm_up(model)?;
7404            let ProcessIntegrand::Amplitude(amplitude) = &mut norm_escalated else {
7405                unreachable!()
7406            };
7407            let escalated = evaluate_from_source_precise(
7408                amplitude,
7409                EvaluationTarget::SamplingLaw(&probe),
7410                EvaluationSource::XSpace(&source),
7411                F(2.0),
7412                false,
7413                Complex::new_zero(),
7414            )?
7415            .try_into_f64()?;
7416            assert_eq!(
7417                escalated.evaluation_metadata.final_precision(),
7418                Some(Precision::Quad)
7419            );
7420            assert_eq!(escalated.evaluation_metadata.stability_results.len(), 1);
7421            assert_eq!(
7422                escalated.evaluation_metadata.sampling_proposal_policies,
7423                policies
7424            );
7425            assert_eq!(escalated.integrand_result, direct.integrand_result);
7426        }
7427
7428        // Ordinary channels also retain one fixed canonical proposal, while
7429        // requiring no joint decisions even if unused joint definitions remain.
7430        parser.default_channel_selection = vec![ordinary_name];
7431        parser.channel_selection.clear();
7432        runtime.get_mut_settings().sampling = toml::from_str(&toml::to_string(&parser)?)?;
7433        runtime.warm_up(model)?;
7434        let ProcessIntegrand::Amplitude(amplitude) = &mut runtime else {
7435            unreachable!()
7436        };
7437        assert_eq!(
7438            amplitude.sampling_source_policy()?.0,
7439            SamplingPrecision::Fixed256
7440        );
7441        assert!(
7442            amplitude
7443                .get_graph(0)
7444                .sampling_setup()
7445                .sampling_bridge::<SamplingFloat>()
7446                .is_ok()
7447        );
7448        probe.retry_lower_half = false;
7449        let source = Sample::Uniform(F(1.0), vec![0, 0], cube.iter().copied().map(F).collect());
7450        let result = evaluate_from_source_precise(
7451            amplitude,
7452            EvaluationTarget::SamplingLaw(&probe),
7453            EvaluationSource::XSpace(&source),
7454            F(1.0),
7455            false,
7456            Complex::new_zero(),
7457        )?
7458        .try_into_f64()?;
7459        assert!(
7460            result
7461                .evaluation_metadata
7462                .sampling_proposal_policies
7463                .is_empty()
7464        );
7465        assert!(
7466            amplitude
7467                .get_graph(0)
7468                .sampling_setup()
7469                .sampling_bridge::<SamplingFloat>()
7470                .is_ok()
7471        );
7472        // A failed fixed proposal cannot choose a native map as a fallback,
7473        // regardless of which physical precision would otherwise be usable.
7474        for calls in &probe.calls {
7475            calls.store(0, Ordering::Relaxed);
7476        }
7477        amplitude
7478            .get_graph_mut(0)
7479            .sampling_setup_mut()
7480            .sampling_bridge_fixed256
7481            .set(Err(
7482                super::sampling::maps::SamplingEvaluationError::Unrepresentable {
7483                    operation: "test-only canonical map poison",
7484                    detail: "fixed proposal unavailable".into(),
7485                },
7486            ));
7487        let failure = evaluate_from_source_precise(
7488            amplitude,
7489            EvaluationTarget::SamplingLaw(&probe),
7490            EvaluationSource::XSpace(&source),
7491            F(1.0),
7492            false,
7493            Complex::new_zero(),
7494        )
7495        .unwrap_err();
7496        assert!(
7497            format!("{failure:#}").contains("fixed source precision"),
7498            "{failure:?}"
7499        );
7500        assert!(
7501            probe
7502                .calls
7503                .iter()
7504                .all(|calls| calls.load(Ordering::Relaxed) == 0)
7505        );
7506        Ok(())
7507    }
7508
7509    #[test]
7510    fn active_dependent_retry_changes_a_normalized_radial_law() {
7511        // Even identical unit determinants and inverse densities do not fix a
7512        // law when an active-dependent retry changes a continuous chart. Circle
7513        // maps x and x+delta are each uniform, but switching only x<delta leaves
7514        // [0,delta) empty. A normalized narrow target has mean zero rather than
7515        // one although the same-point J*q identity holds exactly in both maps.
7516        for denominator in [32, 1024, 16384] {
7517            let delta = 1.0 / f64::from(denominator);
7518            let original = 0.5 * delta;
7519            let switched = original + delta;
7520            assert!(original < delta && switched >= delta);
7521            assert_eq!(delta * (1.0 / delta), 1.0);
7522            assert_eq!(delta * 0.0, 0.0);
7523        }
7524
7525        // For f=q_rho, uniform R in (0,rho) has unit weight. If only the
7526        // lower-half draws replay with 2rho, they stay inside f's support but
7527        // receive weight two. This oracle is independent of map code.
7528        let retained: f64 = [0.25, 0.75].into_iter().map(|_| 1.0).sum::<f64>() / 2.0;
7529        let switched = [0.25, 0.75]
7530            .into_iter()
7531            .map(|u| {
7532                let radius = if u < 0.5 { 2.0 } else { 1.0 };
7533                let reference_density = if radius * u < 1.0 { 1.0 } else { 0.0 };
7534                radius * reference_density
7535            })
7536            .sum::<f64>()
7537            / 2.0;
7538        assert_eq!(retained, 1.0);
7539        assert_eq!(switched, 1.5);
7540        // Equal channel probabilities and a full ordinary sibling with its
7541        // unchanged unit conditional mean give a complete mean of 5/4.
7542        assert_eq!((switched + 1.0) / 2.0, 1.25);
7543    }
7544
7545    #[test]
7546    fn precise_stability_reporting_preserves_underflowed_estimates() {
7547        use super::{PreciseStabilityLevelResult, Precision};
7548        use crate::{
7549            integrands::evaluation::{
7550                EvaluationResult, GraphEvaluationResult, NumericalStabilityLevel,
7551                NumericalStabilityMedian, StatisticsCounter,
7552            },
7553            utils::ArbPrec,
7554        };
7555        use spenso::algebra::complex::Complex;
7556        use std::time::Duration;
7557
7558        let one = F::<ArbPrec>::default().one();
7559        for exponent in [400, 700] {
7560            // Construct a nonzero estimate in its active precision; the public
7561            // relative value may underflow, but its decimal exponent must survive.
7562            let level = PreciseStabilityLevelResult {
7563                result: Complex::new_re(one.clone()),
7564                graph_result: GraphEvaluationResult::zero(one.zero()),
7565                stability_level_used: Precision::Arb,
7566                representation: RepresentationMode::Cff,
7567                estimated_relative_accuracy: Some(one.from_usize(10).powi(-exponent)),
7568                sample_count: 2,
7569                total_time: Duration::ZERO,
7570                parameterization_jacobian: None,
7571                is_stable: true,
7572                rotated_results: Vec::new(),
7573            };
7574            let mut evaluation = EvaluationResult::zero();
7575            evaluation
7576                .evaluation_metadata
7577                .stability_results
7578                .push(level.stability_result());
7579            let metadata = serde_json::to_value(&evaluation.evaluation_metadata).unwrap();
7580            let reported = metadata["stability_results"][0]["estimated_decimal_digits"]
7581                .as_f64()
7582                .unwrap();
7583            assert!((reported - f64::from(exponent)).abs() < 1.0e-10);
7584            let statistics = StatisticsCounter::from_evaluation_results(&[evaluation]);
7585            let Some(NumericalStabilityMedian::InRange {
7586                log10_relative_accuracy,
7587            }) = statistics
7588                .numerical_stability_snapshot()
7589                .median(NumericalStabilityLevel::ArbPrec)
7590            else {
7591                panic!("a finite precision estimate must retain its histogram value");
7592            };
7593            assert!((log10_relative_accuracy + f64::from(exponent)).abs() < 11.0);
7594        }
7595    }
7596
7597    #[test]
7598    fn stability_checks_reject_nonfinite_probes_at_every_level() {
7599        use super::{StabilityFailureReason, StabilityLevelSetting};
7600        use spenso::algebra::complex::Complex;
7601
7602        let level = StabilityLevelSetting::default_double();
7603        for check_on_norm in [false, true] {
7604            let check = if check_on_norm {
7605                super::stability_check_on_norm::<f64>
7606            } else {
7607                super::stability_check::<f64>
7608            };
7609            for is_final_level in [false, true] {
7610                for nonfinite in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
7611                    for invalid in [(nonfinite, 2.0), (2.0, nonfinite)] {
7612                        for probes in [
7613                            vec![invalid, (2.0, 3.0)],
7614                            vec![(2.0, 3.0), invalid],
7615                            vec![invalid],
7616                        ] {
7617                            let results = probes
7618                                .into_iter()
7619                                .map(|(re, im)| Complex::new(F(re), F(im)))
7620                                .collect::<Vec<_>>();
7621                            let (result, accuracy, stable, reason) = check(
7622                                None,
7623                                &results,
7624                                &level,
7625                                Complex::new_zero(),
7626                                F(1.0),
7627                                is_final_level,
7628                                false,
7629                            );
7630                            assert!(
7631                                !stable,
7632                                "nonfinite probe accepted: norm={check_on_norm}, final={is_final_level}, probes={results:?}"
7633                            );
7634                            assert!(accuracy.is_none());
7635                            assert_eq!(reason, Some(StabilityFailureReason::ErrorThreshold));
7636                            // Preserve even a nonfinite primary for the existing
7637                            // validity flag and later component sanitization.
7638                            assert_eq!(result.re.0.to_bits(), results[0].re.0.to_bits());
7639                            assert_eq!(result.im.0.to_bits(), results[0].im.0.to_bits());
7640                        }
7641                    }
7642                }
7643            }
7644        }
7645    }
7646
7647    #[test]
7648    fn real_only_stability_ignores_inactive_imaginary_probe() {
7649        use super::StabilityFailureReason;
7650        use crate::settings::runtime::StabilityLevelSetting;
7651        use spenso::algebra::complex::Complex;
7652
7653        let level = StabilityLevelSetting::default_double();
7654        let results = vec![Complex::new(F(2.0), F(1.0)), Complex::new(F(2.0), F(2.0))];
7655        let (_, _, real_stable, _) = super::stability_check_components(
7656            None,
7657            &results,
7658            &level,
7659            Complex::new(F(10.0), F(10.0)),
7660            F(1.0),
7661            false,
7662            false,
7663            true,
7664            false,
7665        );
7666        let (_, _, both_stable, reason) = super::stability_check_components(
7667            None,
7668            &results,
7669            &level,
7670            Complex::new(F(10.0), F(10.0)),
7671            F(1.0),
7672            false,
7673            false,
7674            true,
7675            true,
7676        );
7677        assert!(real_stable);
7678        assert!(!both_stable);
7679        assert_eq!(reason, Some(StabilityFailureReason::ErrorThreshold));
7680
7681        let nonfinite_im = vec![Complex::new(F(2.0), F(f64::NAN))];
7682        let (_, _, stable, _) = super::stability_check_components(
7683            None,
7684            &nonfinite_im,
7685            &level,
7686            Complex::new(F(10.0), F(10.0)),
7687            F(1.0),
7688            true,
7689            false,
7690            true,
7691            false,
7692        );
7693        assert!(stable);
7694    }
7695
7696    #[test]
7697    fn negligible_weight_waiver_requires_ten_percent_absolute_estimate() {
7698        use super::StabilityFailureReason;
7699        use crate::settings::runtime::StabilityLevelSetting;
7700        use spenso::algebra::complex::Complex;
7701
7702        let level = StabilityLevelSetting::default_double();
7703        let results = vec![Complex::new_re(F(1.0)), Complex::new_re(F(1.1))];
7704        let (_, _, waived, reason) = super::stability_check_components_with_estimate(
7705            None,
7706            &results,
7707            &level,
7708            Complex::new_zero(),
7709            F(1.0),
7710            false,
7711            false,
7712            true,
7713            false,
7714            Some((10.0, 0.5)),
7715            0.2,
7716        );
7717        assert!(waived);
7718        assert_eq!(reason, None);
7719
7720        let (_, _, unstable, reason) = super::stability_check_components_with_estimate(
7721            None,
7722            &results,
7723            &level,
7724            Complex::new_zero(),
7725            F(1.0),
7726            false,
7727            false,
7728            true,
7729            false,
7730            Some((10.0, 1.1)),
7731            0.2,
7732        );
7733        assert!(!unstable);
7734        assert_eq!(reason, Some(StabilityFailureReason::ErrorThreshold));
7735
7736        let (_, _, unstable, reason) = super::stability_check_components_with_estimate(
7737            None,
7738            &[Complex::new_re(F(1.0)), Complex::new_re(F(1.001))],
7739            &level,
7740            Complex::new_zero(),
7741            F(1.0),
7742            false,
7743            false,
7744            true,
7745            false,
7746            Some((10.0, 0.5)),
7747            0.2,
7748        );
7749        assert!(!unstable);
7750        assert_eq!(reason, Some(StabilityFailureReason::ErrorThreshold));
7751    }
7752
7753    #[test]
7754    fn stability_checks_preserve_finite_controls_at_every_level() {
7755        use super::{StabilityFailureReason, StabilityLevelSetting, StabilityStatus};
7756        use spenso::algebra::complex::Complex;
7757
7758        let level = StabilityLevelSetting::default_double();
7759        for check_on_norm in [false, true] {
7760            let check = if check_on_norm {
7761                super::stability_check_on_norm::<f64>
7762            } else {
7763                super::stability_check::<f64>
7764            };
7765            for is_final_level in [false, true] {
7766                for count in [1, 2] {
7767                    for (re, im) in [(0.0, 0.0), (2.0, 3.0)] {
7768                        let results = vec![Complex::new(F(re), F(im)); count];
7769                        let (result, accuracy, stable, reason) = check(
7770                            None,
7771                            &results,
7772                            &level,
7773                            Complex::new_zero(),
7774                            F(1.0),
7775                            is_final_level,
7776                            false,
7777                        );
7778                        assert_eq!(result, results[0]);
7779                        assert!(stable);
7780                        assert_eq!(reason, None);
7781                        if count == 1 {
7782                            assert!(accuracy.is_none());
7783                            assert_eq!(
7784                                StabilityStatus::from_sample_count(count, stable),
7785                                StabilityStatus::Unknown
7786                            );
7787                        } else {
7788                            assert_eq!(accuracy, Some(F(0.0)));
7789                        }
7790                    }
7791                }
7792
7793                let results = [Complex::new(F(2.0), F(3.0)), Complex::new(F(4.0), F(6.0))];
7794                let (result, accuracy, stable, reason) = check(
7795                    None,
7796                    &results,
7797                    &level,
7798                    Complex::new_zero(),
7799                    F(1.0),
7800                    is_final_level,
7801                    false,
7802                );
7803                assert!(!stable);
7804                assert!(accuracy.unwrap() > F(level.required_precision_for_re));
7805                assert_eq!(reason, Some(StabilityFailureReason::ErrorThreshold));
7806                assert_eq!(
7807                    result,
7808                    if check_on_norm {
7809                        results[0]
7810                    } else {
7811                        Complex::new(F(3.0), F(4.5))
7812                    }
7813                );
7814            }
7815        }
7816    }
7817
7818    #[test]
7819    fn stability_checks_bound_complete_underflow_without_cancellation() {
7820        use crate::{settings::runtime::StabilityLevelSetting, utils::ArbPrec};
7821        use spenso::algebra::complex::Complex;
7822
7823        let level = StabilityLevelSetting::default_arb();
7824        let one = F::<ArbPrec>::default().one();
7825        let minimum = F::<ArbPrec>::from_f64(f64::MIN_POSITIVE);
7826        // One probe is normal-sized, but the cancellation-free bound on the
7827        // returned average is 7/8 of MIN_POSITIVE, as in GL638 sample 3559.
7828        let probes = [
7829            Complex::new_re(&minimum / one.from_usize(2)),
7830            Complex::new_re(-&minimum * one.from_usize(5) / one.from_usize(4)),
7831        ];
7832        let average = (&probes[0] + &probes[1]) / one.from_usize(2);
7833        for norm in [false, true] {
7834            let check = if norm {
7835                super::stability_check_on_norm::<ArbPrec>
7836            } else {
7837                super::stability_check::<ArbPrec>
7838            };
7839            for (weight, expected) in [
7840                (one.clone(), true),
7841                (one.from_usize(2), false),
7842                (one.from_usize(10).powi(100), false),
7843            ] {
7844                let (result, accuracy, stable, _) = check(
7845                    None,
7846                    &probes,
7847                    &level,
7848                    Complex::new_re(one.zero()),
7849                    weight,
7850                    true,
7851                    false,
7852                );
7853                assert_eq!(stable, expected);
7854                assert!(accuracy.unwrap() > F::from_f64(level.required_precision_for_re));
7855                assert_eq!(
7856                    result,
7857                    if norm {
7858                        probes[0].clone()
7859                    } else {
7860                        average.clone()
7861                    }
7862                );
7863            }
7864            // Norm checking returns the primary rather than the average, so a
7865            // normal-sized primary cannot inherit the average's waiver.
7866            assert_eq!(
7867                check(
7868                    None,
7869                    &[probes[1].clone(), probes[0].clone()],
7870                    &level,
7871                    Complex::new_re(one.zero()),
7872                    one.clone(),
7873                    true,
7874                    false,
7875                )
7876                .2,
7877                !norm,
7878            );
7879            for invalid_weight in [f64::NAN, f64::INFINITY] {
7880                assert!(
7881                    !check(
7882                        None,
7883                        &probes,
7884                        &level,
7885                        Complex::new_re(one.zero()),
7886                        F::from_f64(invalid_weight),
7887                        true,
7888                        false,
7889                    )
7890                    .2
7891                );
7892            }
7893        }
7894        // A small signed average does not bound large cancelling probes.
7895        assert!(
7896            !super::stability_check(
7897                None,
7898                &[Complex::new_re(one.clone()), Complex::new_re(-one.clone())],
7899                &level,
7900                Complex::new_re(one.zero()),
7901                one,
7902                true,
7903                false,
7904            )
7905            .2
7906        );
7907    }
7908
7909    #[test]
7910    fn stability_underflow_waivers_are_componentwise() {
7911        use crate::{settings::runtime::StabilityLevelSetting, utils::ArbPrec};
7912        use spenso::algebra::complex::Complex;
7913
7914        let level = StabilityLevelSetting::default_arb();
7915        let one = F::<ArbPrec>::default().one();
7916        let tiny = F::<ArbPrec>::from_f64(f64::MIN_POSITIVE) / one.from_usize(4);
7917        for swap in [false, true] {
7918            for (second_normal, expected) in [(1, true), (2, false)] {
7919                let mut probes = [
7920                    Complex::new(tiny.clone(), one.clone()),
7921                    Complex::new(-tiny.clone(), one.from_usize(second_normal)),
7922                ];
7923                if swap {
7924                    for probe in &mut probes {
7925                        std::mem::swap(&mut probe.re, &mut probe.im);
7926                    }
7927                }
7928                assert_eq!(
7929                    super::stability_check(
7930                        None,
7931                        &probes,
7932                        &level,
7933                        Complex::new_re(one.zero()),
7934                        one.clone(),
7935                        true,
7936                        false,
7937                    )
7938                    .2,
7939                    expected,
7940                );
7941            }
7942        }
7943    }
7944
7945    #[test]
7946    fn stability_ecm_tolerance_preserves_energy_and_unit_scaling() {
7947        use crate::settings::runtime::{IntegralUnit, StabilityLevelSetting};
7948        use crate::utils::ArbPrec;
7949        use spenso::algebra::complex::Complex;
7950
7951        let one = F::<ArbPrec>::default().one();
7952        let mut level = StabilityLevelSetting::default_arb();
7953        level.ecm_relative_tolerance_for_re = 1e-5;
7954        for energy in [600, 1200] {
7955            // Cross sections, widths and a scalar two-loop amplitude have
7956            // different dimensions; the decision concerns a dimensionless ratio.
7957            for dimension in [-6, -2, 0, 1, 2] {
7958                for missing_measure in [0, 6] {
7959                    for unit in [
7960                        IntegralUnit::None,
7961                        IntegralUnit::Picobarn,
7962                        IntegralUnit::Femtobarn,
7963                    ] {
7964                        let scale = one.from_usize(energy).powi(dimension - missing_measure)
7965                            * super::cross_section::barn_conversion_factor(unit, one.clone());
7966                        let small = &scale / one.from_usize(1_000_000);
7967                        let probes = [
7968                            Complex::new_re(small.clone()),
7969                            Complex::new_re(&small * one.from_usize(3)),
7970                        ];
7971                        for norm in [false, true] {
7972                            let check = if norm {
7973                                super::stability_check_on_norm::<ArbPrec>
7974                            } else {
7975                                super::stability_check::<ArbPrec>
7976                            };
7977                            for (weight, expected) in [(1, true), (-1, true), (100, false)] {
7978                                let (result, accuracy, stable, _) = check(
7979                                    Some(&scale),
7980                                    &probes,
7981                                    &level,
7982                                    Complex::new_re(one.zero()),
7983                                    one.from_i64(weight),
7984                                    true,
7985                                    false,
7986                                );
7987                                assert_eq!(stable, expected);
7988                                assert!(
7989                                    accuracy.unwrap()
7990                                        > F::from_f64(level.required_precision_for_re)
7991                                );
7992                                assert_eq!(
7993                                    result.re,
7994                                    if norm {
7995                                        small.clone()
7996                                    } else {
7997                                        &small * one.from_usize(2)
7998                                    }
7999                                );
8000                            }
8001                        }
8002                    }
8003                }
8004            }
8005        }
8006        // A body below binary64 range must be multiplied in native precision:
8007        // its huge outer factor can put the disagreement well above the allowance.
8008        let tiny = one.from_usize(10).powi(-1000);
8009        let probes = [
8010            Complex::new_re(tiny.clone()),
8011            Complex::new_re(&tiny * one.from_usize(3)),
8012        ];
8013        level.ecm_relative_tolerance_for_re = 1e-201;
8014        assert!(
8015            !super::stability_check(
8016                Some(&one),
8017                &probes,
8018                &level,
8019                Complex::new_re(one.zero()),
8020                one.from_usize(10).powi(800),
8021                true,
8022                false
8023            )
8024            .2
8025        );
8026    }
8027
8028    #[test]
8029    fn stability_ecm_tolerance_bounds_the_returned_components() {
8030        use crate::settings::runtime::StabilityLevelSetting;
8031        use spenso::algebra::complex::Complex;
8032
8033        let scale = F(1.0);
8034        let mut level = StabilityLevelSetting::default_double();
8035        let probes = [Complex::new(F(1.0), F(0.0)), Complex::new(F(3.0), F(0.0))];
8036        for (allowance, expected_component, expected_norm) in [
8037            (0.0, false, false),
8038            (0.5, false, false),
8039            (1.0, true, false),
8040            (2.0, true, true),
8041        ] {
8042            level.ecm_relative_tolerance_for_re = allowance;
8043            for (norm, expected, returned) in
8044                [(false, expected_component, 2.0), (true, expected_norm, 1.0)]
8045            {
8046                let check = if norm {
8047                    super::stability_check_on_norm::<f64>
8048                } else {
8049                    super::stability_check::<f64>
8050                };
8051                let (value, accuracy, stable, _) = check(
8052                    Some(&scale),
8053                    &probes,
8054                    &level,
8055                    Complex::new_zero(),
8056                    F(1.0),
8057                    true,
8058                    false,
8059                );
8060                assert_eq!(stable, expected);
8061                assert_eq!(value.re, F(returned));
8062                assert!(accuracy.unwrap() > F(level.required_precision_for_re));
8063            }
8064        }
8065        // A real allowance cannot excuse an independently unstable imaginary
8066        // component; swapping Re and Im swaps the applicable setting too.
8067        for swap in [false, true] {
8068            let mut mixed = [Complex::new(F(1.0), F(4.0)), Complex::new(F(3.0), F(8.0))];
8069            level.ecm_relative_tolerance_for_re = 1.0;
8070            level.ecm_relative_tolerance_for_im = 0.0;
8071            if swap {
8072                for probe in &mut mixed {
8073                    std::mem::swap(&mut probe.re, &mut probe.im);
8074                }
8075                std::mem::swap(
8076                    &mut level.ecm_relative_tolerance_for_re,
8077                    &mut level.ecm_relative_tolerance_for_im,
8078                );
8079            }
8080            assert!(
8081                !super::stability_check(
8082                    Some(&scale),
8083                    &mixed,
8084                    &level,
8085                    Complex::new_zero(),
8086                    F(1.0),
8087                    true,
8088                    false
8089                )
8090                .2
8091            );
8092        }
8093        level.ecm_relative_tolerance_for_re = 0.5;
8094        let cancelling = [Complex::new_re(F(1.0)), Complex::new_re(F(-1.0))];
8095        assert!(
8096            !super::stability_check(
8097                Some(&scale),
8098                &cancelling,
8099                &level,
8100                Complex::new_zero(),
8101                F(1.0),
8102                true,
8103                false
8104            )
8105            .2
8106        );
8107        for check in [
8108            super::stability_check::<f64>,
8109            super::stability_check_on_norm::<f64>,
8110        ] {
8111            level.ecm_relative_tolerance_for_re = 10.0;
8112            for invalid in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
8113                assert!(
8114                    !check(
8115                        Some(&scale),
8116                        &probes,
8117                        &level,
8118                        Complex::new_zero(),
8119                        F(invalid),
8120                        true,
8121                        false
8122                    )
8123                    .2
8124                );
8125                assert!(
8126                    !check(
8127                        Some(&F(invalid)),
8128                        &probes,
8129                        &level,
8130                        Complex::new_zero(),
8131                        F(1.0),
8132                        true,
8133                        false
8134                    )
8135                    .2
8136                );
8137            }
8138        }
8139        // Finite differences do not make overflowing complete products safe.
8140        level.required_precision_for_re = 0.0;
8141        let large = [
8142            Complex::new_re(F(1e200)),
8143            Complex::new_re(F(1e200 * (1.0 - 1e-14))),
8144        ];
8145        assert!(
8146            !super::stability_check(
8147                Some(&F(1e308)),
8148                &large,
8149                &level,
8150                Complex::new_zero(),
8151                F(1e110),
8152                true,
8153                false
8154            )
8155            .2
8156        );
8157    }
8158
8159    #[test]
8160    fn stability_ecm_runtime_validation_precedes_orientation_checks() {
8161        let mut settings = RuntimeSettings::default();
8162        for component in ["re", "im"] {
8163            for invalid in [-1.0, f64::NAN, f64::INFINITY] {
8164                let level = &mut settings.stability.levels[0];
8165                level.ecm_relative_tolerance_for_re = 0.0;
8166                level.ecm_relative_tolerance_for_im = 0.0;
8167                if component == "re" {
8168                    level.ecm_relative_tolerance_for_re = invalid;
8169                } else {
8170                    level.ecm_relative_tolerance_for_im = invalid;
8171                }
8172                for explicit in [false, true] {
8173                    let error = validate_process_runtime_settings(
8174                        &settings,
8175                        explicit,
8176                        &[RepresentationMode::Cff],
8177                        &[],
8178                    )
8179                    .unwrap_err();
8180                    assert!(
8181                        error
8182                            .to_string()
8183                            .contains(&format!("levels[0].ecm_relative_tolerance_for_{component}"))
8184                    );
8185                }
8186            }
8187        }
8188        settings.stability.levels[0].ecm_relative_tolerance_for_re = 1e-100;
8189        settings.stability.levels[0].ecm_relative_tolerance_for_im = 0.0;
8190        for invalid in [0.0, -1.0, f64::NAN, f64::INFINITY] {
8191            settings.kinematics.e_cm = invalid;
8192            assert!(
8193                validate_process_runtime_settings(
8194                    &settings,
8195                    false,
8196                    &[RepresentationMode::Cff],
8197                    &[]
8198                )
8199                .unwrap_err()
8200                .to_string()
8201                .contains("kinematics.e_cm")
8202            );
8203        }
8204        settings.kinematics.e_cm = 600.0;
8205        // The physical dimension is admitted at its target boundary; generic
8206        // warmup also serves reference functions with their known dimensions.
8207        assert!(settings.stability.integrated_energy_dimension.is_none());
8208        validate_process_runtime_settings(&settings, false, &[RepresentationMode::Cff], &[])
8209            .unwrap();
8210    }
8211
8212    #[test]
8213    fn precise_event_normalization_preserves_prior_factors_and_partial_weights() {
8214        use crate::{
8215            observables::{
8216                AdditionalWeightKey, GenericEvent, GenericEventGroup, GenericEventGroupList,
8217            },
8218            utils::ArbPrec,
8219        };
8220        use spenso::algebra::complex::Complex;
8221
8222        let one = F::<ArbPrec>::default().one();
8223        let original = Complex::new_re(one.from_usize(3));
8224        let counterterm = Complex::new_re(-one.clone());
8225        let prior_factor = Complex::new_re(one.from_usize(5));
8226        let mut event = GenericEvent::<ArbPrec> {
8227            weight: (&original + &counterterm) * &prior_factor,
8228            ..Default::default()
8229        };
8230        event.additional_weights.weights.extend([
8231            (AdditionalWeightKey::Original, original.clone()),
8232            (
8233                AdditionalWeightKey::ThresholdCounterterm { subset_index: 0 },
8234                counterterm.clone(),
8235            ),
8236            (
8237                AdditionalWeightKey::FullMultiplicativeFactor,
8238                prior_factor.clone(),
8239            ),
8240        ]);
8241        let mut events = GenericEventGroupList(vec![GenericEventGroup(vec![event])]);
8242        let final_factor = super::full_event_multiplicative_factor_precise(
8243            Some(one.from_usize(7)),
8244            one.from_usize(11),
8245        );
8246        super::apply_full_event_multiplicative_factor_precise(&mut events, &final_factor);
8247        let event = &events[0][0];
8248        let weights = &event.additional_weights.weights;
8249        assert_eq!(weights[&AdditionalWeightKey::Original], original);
8250        assert_eq!(
8251            weights[&AdditionalWeightKey::ThresholdCounterterm { subset_index: 0 }],
8252            counterterm
8253        );
8254        assert_eq!(
8255            weights[&AdditionalWeightKey::FullMultiplicativeFactor],
8256            &prior_factor * &final_factor
8257        );
8258        assert_eq!(
8259            event.weight,
8260            (&original + &counterterm) * &weights[&AdditionalWeightKey::FullMultiplicativeFactor]
8261        );
8262        assert_eq!(event.weight, Complex::new_re(one.from_usize(770)));
8263    }
8264
8265    #[test]
8266    fn native_sampling_product_and_precise_reporting_preserve_full_range() {
8267        use crate::{
8268            integrands::evaluation::{
8269                EvaluationMetaData, GraphEvaluationResult, PreciseEvaluationResult,
8270            },
8271            integrands::process::sampling::reference::ReferenceMoments,
8272            observables::{GenericEvent, GenericEventGroup, GenericEventGroupList},
8273            settings::runtime::Precision,
8274            utils::ArbPrec,
8275        };
8276        use spenso::algebra::complex::Complex;
8277        use std::time::Duration;
8278
8279        let one = F::<ArbPrec>::default().one();
8280        let large = one.from_usize(10).powi(400);
8281        let small = large.clone().inv();
8282        assert!(large.clone().into_ff64().0.is_infinite());
8283        assert_eq!(small.clone().into_ff64().0, 0.0);
8284        let mut graph = GraphEvaluationResult::zero(one.zero());
8285        graph.integrand_result = Complex::new_re(small.clone());
8286        graph.reference_moments = Some(ReferenceMoments {
8287            second_moment: small.clone(),
8288            jacobian_min: 1.0,
8289            jacobian_max: 1.0,
8290        });
8291        graph.event_groups = GenericEventGroupList(vec![GenericEventGroup(vec![GenericEvent {
8292            weight: Complex::new_re(small.clone()),
8293            ..Default::default()
8294        }])]);
8295        // This is the same single owner used by selected and summed physical
8296        // maps and reference moments, before any reporting conversion.
8297        graph.apply_sampling_factor(large.clone());
8298        assert!((&graph.integrand_result.re - &one).abs() < one.epsilon() * one.from_usize(4));
8299        assert_eq!(graph.event_groups[0][0].weight, graph.integrand_result);
8300        assert_eq!(
8301            graph.reference_moments.as_ref().unwrap().second_moment,
8302            graph.integrand_result.re
8303        );
8304        let level = super::PreciseStabilityLevelResult {
8305            result: graph.integrand_result.clone(),
8306            graph_result: graph,
8307            stability_level_used: Precision::Arb,
8308            representation: RepresentationMode::Cff,
8309            estimated_relative_accuracy: None,
8310            sample_count: 1,
8311            total_time: Duration::ZERO,
8312            parameterization_jacobian: Some(one.clone()),
8313            is_stable: true,
8314            rotated_results: Vec::new(),
8315        };
8316        let mut metadata = EvaluationMetaData::new_empty();
8317        metadata.canonical_sampling_preparation_time = Duration::from_micros(7);
8318        metadata.parameterization_time = Duration::from_micros(7) + Duration::from_micros(11);
8319        metadata.integrand_evaluation_time = Duration::from_micros(19) + Duration::from_micros(23);
8320        let result = super::finalize_precise_evaluation_result(level.clone(), F(1.0), metadata);
8321        assert_eq!(
8322            result.evaluation_metadata.parameterization_time,
8323            Duration::from_micros(18)
8324        );
8325        assert_eq!(
8326            result
8327                .evaluation_metadata
8328                .canonical_sampling_preparation_time,
8329            Duration::from_micros(7)
8330        );
8331        assert_eq!(
8332            result.evaluation_metadata.integrand_evaluation_time,
8333            Duration::from_micros(42)
8334        );
8335        assert_eq!(
8336            result.clone().try_into_f64().unwrap().integrand_result.re,
8337            F(1.0)
8338        );
8339        assert_eq!(result.event_groups[0][0].weight, result.integrand_result);
8340        // Cancellation can leave a finite signed result while the physical
8341        // absolute channel sum exceeds the ordinary reporting range.
8342        let mut excessive_absolute = result.clone();
8343        excessive_absolute.absolute_integrand_result = Some(Complex::new_re(large.clone()));
8344        assert!(excessive_absolute.try_into_f64().is_err());
8345        for extreme in [large.clone(), small.clone()] {
8346            let mut extreme_level = level.clone();
8347            extreme_level.result = Complex::new_re(extreme.clone());
8348            extreme_level.graph_result.integrand_result = extreme_level.result.clone();
8349            let precise = PreciseEvaluationResult::Arb(super::finalize_precise_evaluation_result(
8350                extreme_level,
8351                F(1.0),
8352                EvaluationMetaData::new_empty(),
8353            ));
8354            let PreciseEvaluationResult::Arb(value) = &precise else {
8355                unreachable!()
8356            };
8357            assert_eq!(value.integrand_result.re, extreme);
8358            assert!(!value.evaluation_metadata.is_nan);
8359            if extreme == large {
8360                assert!(
8361                    format!("{:#}", precise.try_into_f64().unwrap_err())
8362                        .contains("f64 integration/reporting boundary")
8363                );
8364            } else {
8365                assert_eq!(precise.try_into_f64().unwrap().integrand_result.re, F(0.0));
8366            }
8367        }
8368        // Correct final rounding is allowed for signed and absolute values,
8369        // including fully weighted event totals, while precise output stays native.
8370        let mut underflow = result.clone();
8371        underflow.integrand_result = Complex::new(small.clone(), -small.clone());
8372        underflow.absolute_integrand_result = Some(Complex::new(small.clone(), small.clone()));
8373        underflow.event_groups[0][0].weight = underflow.integrand_result.clone();
8374        let rounded = underflow.clone().try_into_f64().unwrap();
8375        assert_eq!(rounded.integrand_result, Complex::new_zero());
8376        assert_eq!(rounded.absolute_integrand_result, Some(Complex::new_zero()));
8377        assert_eq!(rounded.event_groups[0][0].weight, Complex::new_zero());
8378        assert_eq!(underflow.integrand_result.re, small);
8379
8380        let mut subnormal = result.clone();
8381        subnormal.integrand_result = Complex::new_re(one.from_usize(10).powi(320).inv());
8382        let subnormal_value = subnormal.integrand_result.re.into_ff64();
8383        assert!(subnormal_value.0 > 0.0 && subnormal_value.0 < f64::MIN_POSITIVE);
8384        assert_eq!(
8385            subnormal.try_into_f64().unwrap().integrand_result.re,
8386            subnormal_value
8387        );
8388
8389        // An outer-grid factor can rescue an otherwise underflowed intermediate;
8390        // reject that loss rather than silently returning a zero observation.
8391        underflow.integrator_weight = one.from_usize(10).powi(100);
8392        let error = format!("{:#}", underflow.clone().try_into_f64().unwrap_err());
8393        assert!(error.contains("integrand_result.re"));
8394        assert!(error.contains("complete contribution"));
8395        underflow.integrand_result = Complex::new_re(one.zero());
8396        assert!(
8397            format!("{:#}", underflow.clone().try_into_f64().unwrap_err())
8398                .contains("absolute_integrand_result.re")
8399        );
8400        underflow.absolute_integrand_result = None;
8401        // Events now retain their unapplied outer factor too: a raw event that
8402        // underflows cannot be silently dropped if accumulation would promote it.
8403        assert!(
8404            format!("{:#}", underflow.clone().try_into_f64().unwrap_err())
8405                .contains("event_groups[0][0].weight.re")
8406        );
8407        underflow.integrator_weight = one.clone();
8408        underflow.parameterization_jacobian = Some(one.from_usize(10).powi(100));
8409        underflow.integrand_result = Complex::new_im(-small.clone());
8410        assert!(
8411            format!("{:#}", underflow.clone().try_into_f64().unwrap_err())
8412                .contains("integrand_result.im")
8413        );
8414
8415        // Separately reported factors must themselves survive conversion: a
8416        // final underflow does not excuse an infinite serialized Jacobian.
8417        let mut unrepresentable_factor = result.clone();
8418        unrepresentable_factor.integrand_result = Complex::new_re(&small * &small);
8419        unrepresentable_factor.parameterization_jacobian = Some(large.clone());
8420        assert!(
8421            format!(
8422                "{:#}",
8423                unrepresentable_factor.clone().try_into_f64().unwrap_err()
8424            )
8425            .contains("parameterization_jacobian")
8426        );
8427        unrepresentable_factor.parameterization_jacobian = Some(small.clone());
8428        assert!(
8429            format!(
8430                "{:#}",
8431                unrepresentable_factor.clone().try_into_f64().unwrap_err()
8432            )
8433            .contains("parameterization_jacobian")
8434        );
8435        unrepresentable_factor.parameterization_jacobian = None;
8436        unrepresentable_factor.integrator_weight = large.clone();
8437        assert!(
8438            format!(
8439                "{:#}",
8440                unrepresentable_factor.clone().try_into_f64().unwrap_err()
8441            )
8442            .contains("integrator_weight")
8443        );
8444        unrepresentable_factor.integrator_weight = small.clone();
8445        assert!(
8446            format!("{:#}", unrepresentable_factor.try_into_f64().unwrap_err())
8447                .contains("integrator_weight")
8448        );
8449
8450        // Auxiliary event entries deliberately remain factorized. Their raw
8451        // components cannot be rounded away before the stored multiplier acts.
8452        let mut auxiliary = result.clone();
8453        auxiliary.event_groups[0][0]
8454            .additional_weights
8455            .weights
8456            .insert(
8457                crate::observables::AdditionalWeightKey::Original,
8458                Complex::new_re(small.clone()),
8459            );
8460        assert!(
8461            format!("{:#}", auxiliary.clone().try_into_f64().unwrap_err())
8462                .contains("additional_weights[Original].re")
8463        );
8464
8465        let full_factor_key = crate::observables::AdditionalWeightKey::FullMultiplicativeFactor;
8466        auxiliary.event_groups[0][0]
8467            .additional_weights
8468            .weights
8469            .insert(full_factor_key, Complex::new_re(one.clone()));
8470        assert_eq!(
8471            auxiliary.clone().try_into_f64().unwrap().event_groups[0][0]
8472                .additional_weights
8473                .weights[&crate::observables::AdditionalWeightKey::Original],
8474            Complex::new_zero(),
8475        );
8476        // An unknown component of a complex multiplier cannot certify a tail,
8477        // even when its other component is finite and small.
8478        auxiliary.event_groups[0][0]
8479            .additional_weights
8480            .weights
8481            .insert(
8482                full_factor_key,
8483                Complex::new(F::<ArbPrec>::from_f64(f64::NAN), one.clone()),
8484            );
8485        assert!(
8486            format!("{:#}", auxiliary.clone().try_into_f64().unwrap_err())
8487                .contains("additional_weights[Original].re")
8488        );
8489        // A complex multiplier can promote this tiny real component into a
8490        // meaningful imaginary contribution. It must survive before rounding.
8491        auxiliary.event_groups[0][0]
8492            .additional_weights
8493            .weights
8494            .insert(
8495                full_factor_key,
8496                Complex::new_im(one.from_usize(10).powi(100)),
8497            );
8498        assert!(
8499            format!("{:#}", auxiliary.try_into_f64().unwrap_err())
8500                .contains("additional_weights[Original].re")
8501        );
8502
8503        // A cancelling total does not make individually unrepresentable event
8504        // weights representable. Native APIs retain them; ordinary output errors.
8505        let mut cancelling_events = result;
8506        cancelling_events.event_groups[0].0 = vec![
8507            GenericEvent {
8508                weight: Complex::new_re(large.clone()),
8509                ..Default::default()
8510            },
8511            GenericEvent {
8512                weight: Complex::new_re(-large),
8513                ..Default::default()
8514            },
8515        ];
8516        assert!(cancelling_events.try_into_f64().is_err());
8517    }
8518
8519    #[test]
8520    fn complex_norm_stability_retains_finite_extreme_scales() {
8521        use spenso::algebra::complex::Complex;
8522
8523        let level = crate::settings::runtime::StabilityLevelSetting::default_double();
8524        for scale in [1e-200, 1.0, 1e200] {
8525            let primary = Complex::new_im(F(scale));
8526            for (rotated_scale, weight, stable) in [
8527                (scale, 1.0, true),
8528                (scale, -1.0, true),
8529                (2.0 * scale, 1.0, false),
8530                (2.0 * scale, -1.0, false),
8531            ] {
8532                let (result, accuracy, actual_stable, _) = super::stability_check_on_norm(
8533                    None,
8534                    &[primary, Complex::new_re(F(rotated_scale))],
8535                    &level,
8536                    Complex::new_zero(),
8537                    F(weight),
8538                    false,
8539                    false,
8540                );
8541                assert_eq!(result, primary);
8542                assert_eq!(actual_stable, stable, "scale={scale}");
8543                assert!(accuracy.unwrap().0.is_finite());
8544                if !stable {
8545                    // A tiny but normal binary64 contribution cannot pass merely
8546                    // because squaring its components would underflow to zero.
8547                    assert!(accuracy.unwrap().0 > 0.3);
8548                }
8549            }
8550        }
8551        for (probes, stable) in [
8552            ([Complex::new_re(F(1e308)); 2], true),
8553            (
8554                [Complex::new_re(F(1e308)), Complex::new_re(F(9e307))],
8555                false,
8556            ),
8557            ([Complex::new(F(f64::MAX), F(f64::MAX)); 2], false),
8558        ] {
8559            let (_, accuracy, actual_stable, _) = super::stability_check_on_norm(
8560                None,
8561                &probes,
8562                &level,
8563                Complex::new_zero(),
8564                F(1.0),
8565                false,
8566                false,
8567            );
8568            assert_eq!(actual_stable, stable, "probes={probes:?}");
8569            assert!(accuracy.is_none_or(|value| value.0.is_finite()));
8570        }
8571    }
8572
8573    #[test]
8574    fn amplitude_channel_norm_preserves_helicity_phase_covariance() {
8575        use spenso::algebra::complex::Complex;
8576
8577        let level = crate::settings::runtime::StabilityLevelSetting::default_double();
8578        let mut signed = Vec::new();
8579        let mut absolute = Vec::new();
8580        let mut channel_norm = Vec::new();
8581        for phase in [
8582            Complex::new(F(1.0), F(0.0)),
8583            Complex::new(
8584                F(std::f64::consts::FRAC_1_SQRT_2),
8585                F(std::f64::consts::FRAC_1_SQRT_2),
8586            ),
8587        ] {
8588            // Orthogonal channels have a phase-dependent componentwise absolute
8589            // sum: (1, 1) rotates to (sqrt(2), sqrt(2)), although both physical
8590            // channel norms and their signed total norm remain unchanged.
8591            let channels = [phase, Complex::new_im(F(1.0)) * phase];
8592            signed.push(channels[0] + channels[1]);
8593            absolute.push(channels.iter().fold(Complex::new_zero(), |sum, value| {
8594                sum + Complex::new(value.re.abs(), value.im.abs())
8595            }));
8596            channel_norm.push(Complex::new_re(
8597                channels
8598                    .iter()
8599                    .fold(F(0.0), |sum, value| sum + value.re.hypot(&value.im)),
8600            ));
8601        }
8602        for (probes, stable) in [(&signed, true), (&channel_norm, true), (&absolute, false)] {
8603            assert_eq!(
8604                super::stability_check_on_norm(
8605                    None,
8606                    probes,
8607                    &level,
8608                    Complex::new_zero(),
8609                    F(1.0),
8610                    false,
8611                    false,
8612                )
8613                .2,
8614                stable
8615            );
8616        }
8617        assert_eq!(absolute[0], Complex::new(F(1.0), F(1.0)));
8618        assert_eq!(channel_norm[0], Complex::new_re(F(2.0)));
8619
8620        // A private norm monitor follows the same real map factor as the
8621        // physical result, using its magnitude even for a negative factor.
8622        let mut result = super::GraphEvaluationResult::zero(F(0.0));
8623        result.integrand_result = signed[0];
8624        result.absolute_integrand_result = Some(absolute[0]);
8625        result.channel_norm_sum = Some(channel_norm[0].re);
8626        result.apply_sampling_factor(F(-3.0));
8627        assert_eq!(result.integrand_result, Complex::new(F(-3.0), F(-3.0)));
8628        assert_eq!(
8629            result.absolute_integrand_result,
8630            Some(Complex::new(F(3.0), F(3.0)))
8631        );
8632        assert_eq!(result.channel_norm_sum, Some(F(6.0)));
8633        let other = result.clone();
8634        result.merge_in_place(other);
8635        assert_eq!(result.channel_norm_sum, Some(F(12.0)));
8636    }
8637
8638    #[test]
8639    fn absolute_channel_instability_cannot_hide_behind_signed_cancellation() {
8640        use crate::settings::runtime::StabilityLevelSetting;
8641        use spenso::algebra::complex::Complex;
8642
8643        let mut level = StabilityLevelSetting::default_double();
8644        level.ecm_relative_tolerance_for_re = 0.1;
8645        level.ecm_relative_tolerance_for_im = 0.1;
8646        let signed = [Complex::new_zero(), Complex::new_zero()];
8647        let absolute = [Complex::new(F(2.0), F(4.0)), Complex::new(F(3.0), F(6.0))];
8648        for check in [
8649            super::stability_check::<f64>,
8650            super::stability_check_on_norm::<f64>,
8651        ] {
8652            assert!(
8653                check(
8654                    Some(&F(1.0)),
8655                    &signed,
8656                    &level,
8657                    Complex::new_zero(),
8658                    F(1.0),
8659                    false,
8660                    false
8661                )
8662                .2
8663            );
8664            assert!(
8665                !check(
8666                    Some(&F(1.0)),
8667                    &absolute,
8668                    &level,
8669                    Complex::new_zero(),
8670                    F(1.0),
8671                    false,
8672                    false
8673                )
8674                .2
8675            );
8676        }
8677        // Equal and opposite channels can keep the signed total exactly zero
8678        // while their individual norms change. The private amplitude monitor
8679        // must still reject this variation.
8680        let channel_norm = [Complex::new_re(F(2.0)), Complex::new_re(F(3.0))];
8681        assert!(
8682            !super::stability_check_on_norm(
8683                None,
8684                &channel_norm,
8685                &level,
8686                Complex::new_zero(),
8687                F(1.0),
8688                false,
8689                false,
8690            )
8691            .2
8692        );
8693    }
8694
8695    #[test]
8696    fn explicit_orientation_sum_rejects_runtime_filters_and_unavailable_representations() {
8697        let mut settings = RuntimeSettings::default();
8698        settings.general.orientation_pat = OrientationPattern::from_user_pattern("(+)").unwrap();
8699        let error =
8700            validate_process_runtime_settings(&settings, true, &[RepresentationMode::Cff], &[])
8701                .unwrap_err();
8702        assert!(error.to_string().contains("orientation_pat` must be unset"));
8703
8704        validate_process_runtime_settings(&settings, false, &[RepresentationMode::Cff], &[])
8705            .unwrap();
8706
8707        settings.general.orientation_pat = OrientationPattern::default();
8708        settings.stability.levels[0].three_dimensional_representation =
8709            Some(RepresentationMode::Ltd);
8710        let error =
8711            validate_process_runtime_settings(&settings, false, &[RepresentationMode::Cff], &[])
8712                .unwrap_err();
8713        assert!(format!("{error:#}").contains("was not generated"));
8714
8715        settings.stability.levels[0].three_dimensional_representation = None;
8716        settings.general.orientation_pat = OrientationPattern::from_user_pattern("(+)").unwrap();
8717        let generated = [RepresentationMode::Ltd, RepresentationMode::Cff];
8718        assert!(validate_process_runtime_settings(&settings, false, &generated, &[]).is_err());
8719        settings.general.orientation_pat = OrientationPattern::default();
8720        settings.sampling = SamplingSettings::DiscreteGraphs(DiscreteGraphSamplingSettings {
8721            sample_orientations: true,
8722            ..Default::default()
8723        });
8724        assert!(
8725            validate_process_runtime_settings(&settings, false, &generated, &[])
8726                .unwrap_err()
8727                .to_string()
8728                .contains("individual-orientation")
8729        );
8730    }
8731
8732    #[test]
8733    fn runtime_requires_at_least_one_stability_level() {
8734        let mut settings = RuntimeSettings::default();
8735        settings.stability.levels.clear();
8736        let error =
8737            validate_process_runtime_settings(&settings, false, &[RepresentationMode::Cff], &[])
8738                .unwrap_err();
8739        assert!(error.to_string().contains("runtime.stability.levels"));
8740    }
8741
8742    #[test]
8743    fn fixed_on_shell_frame_requires_exactly_preserving_rotation_probes() {
8744        use crate::settings::runtime::RotationSetting;
8745        crate::initialisation::test_initialise().unwrap();
8746        let mut settings = RuntimeSettings::default();
8747        let nonaxial = ["1/4", "1/2", "1/2"].map(str::to_owned);
8748        for axis in [[1.0, 2.0, 2.0], [-1.0, -2.0, -2.0]] {
8749            settings.stability.rotation_axis = vec![RotationSetting::AxisAngle {
8750                axis,
8751                cos_theta: 0.0,
8752            }];
8753            validate_process_runtime_settings(
8754                &settings,
8755                false,
8756                &[RepresentationMode::Cff],
8757                &[&nonaxial],
8758            )
8759            .unwrap();
8760        }
8761        for rotation in [
8762            RotationSetting::Pi2X {},
8763            RotationSetting::Pi2Y {},
8764            RotationSetting::Pi2Z {},
8765            RotationSetting::EulerAngles {
8766                alpha: 0.1,
8767                beta: 0.2,
8768                gamma: 0.3,
8769            },
8770            RotationSetting::AxisAngle {
8771                axis: [1.0, 2.0, 2.0000000000000004],
8772                cos_theta: 0.0,
8773            },
8774        ] {
8775            settings.stability.rotation_axis = vec![rotation];
8776            validate_process_runtime_settings(&settings, false, &[RepresentationMode::Cff], &[])
8777                .unwrap();
8778            let error = validate_process_runtime_settings(
8779                &settings,
8780                false,
8781                &[RepresentationMode::Cff],
8782                &[&nonaxial],
8783            )
8784            .unwrap_err();
8785            assert!(
8786                error
8787                    .to_string()
8788                    .contains("fixed on-shell subtraction velocity")
8789            );
8790        }
8791        let axial = ["0", "0", "3/4"].map(str::to_owned);
8792        settings.stability.rotation_axis = vec![
8793            RotationSetting::Pi2Z {},
8794            RotationSetting::EulerAngles {
8795                alpha: 0.0,
8796                beta: 0.0,
8797                gamma: 0.3,
8798            },
8799        ];
8800        validate_process_runtime_settings(&settings, false, &[RepresentationMode::Cff], &[&axial])
8801            .unwrap();
8802        assert!(
8803            validate_process_runtime_settings(
8804                &settings,
8805                false,
8806                &[RepresentationMode::Cff],
8807                &[&axial, &nonaxial]
8808            )
8809            .is_err()
8810        );
8811        settings.stability.rotation_axis = vec![
8812            RotationSetting::None {},
8813            RotationSetting::AxisAngle {
8814                axis: [1.0, 0.0, 0.0],
8815                cos_theta: 1.0,
8816            },
8817        ];
8818        validate_process_runtime_settings(
8819            &settings,
8820            false,
8821            &[RepresentationMode::Cff],
8822            &[&axial, &nonaxial],
8823        )
8824        .unwrap();
8825    }
8826
8827    #[test]
8828    fn numerator_sampling_scale_requires_nonzero_runtime_value() {
8829        let mut settings = RuntimeSettings::default();
8830        validate_process_runtime_settings(&settings, false, &[RepresentationMode::Cff], &[])
8831            .unwrap();
8832
8833        for scale in [0.0, -0.0] {
8834            settings.general.numerator_sampling_scale = scale;
8835            for explicit_orientation_sum_only in [false, true] {
8836                let error = validate_process_runtime_settings(
8837                    &settings,
8838                    explicit_orientation_sum_only,
8839                    &[RepresentationMode::Cff],
8840                    &[],
8841                )
8842                .unwrap_err();
8843                assert!(error.to_string().contains("sampling scale M"));
8844            }
8845        }
8846
8847        settings.general.numerator_sampling_scale = -2.0;
8848        validate_process_runtime_settings(&settings, false, &[RepresentationMode::Cff], &[])
8849            .unwrap();
8850    }
8851
8852    #[test]
8853    fn grouped_orientation_sampling_requires_identical_exact_map_catalogs() {
8854        let master = ["O[+0]|M[0]", "O[+0]|M[1]"];
8855        validate_orientation_catalog_group(
8856            GroupId(3),
8857            [
8858                ("master".to_string(), master.to_vec()),
8859                ("matching".to_string(), master.to_vec()),
8860            ],
8861        )
8862        .unwrap();
8863
8864        let error = validate_orientation_catalog_group(
8865            GroupId(3),
8866            [
8867                ("master".to_string(), master.to_vec()),
8868                ("different".to_string(), vec!["O[+0]|M[0]", "O[+0]|M[2]"]),
8869            ],
8870        )
8871        .unwrap_err();
8872        assert!(
8873            error
8874                .to_string()
8875                .contains("different exact residue-map catalogs")
8876        );
8877        assert!(error.to_string().contains("first difference at channel 1"));
8878    }
8879
8880    #[test]
8881    fn runtime_cache_serializes_as_empty() {
8882        let encoded = bincode::encode_to_vec(
8883            RuntimeCache::<usize>::default(),
8884            bincode::config::standard(),
8885        )
8886        .expect("runtime cache should encode");
8887        assert!(encoded.is_empty());
8888
8889        let (decoded, consumed): (RuntimeCache<usize>, usize) =
8890            bincode::decode_from_slice(&encoded, bincode::config::standard())
8891                .expect("runtime cache should decode");
8892        assert_eq!(consumed, 0);
8893        assert!(decoded.as_ref().is_none());
8894        let mut source = RuntimeCache::default();
8895        source.set((super::Precision::Quad, 1.0e-13));
8896        let encoded_source = bincode::encode_to_vec(&source, bincode::config::standard()).unwrap();
8897        assert!(encoded_source.is_empty());
8898        let (decoded_source, consumed): (RuntimeCache<(super::Precision, f64)>, usize) =
8899            bincode::decode_from_slice(&encoded_source, bincode::config::standard()).unwrap();
8900        assert_eq!(consumed, 0);
8901        assert!(decoded_source.as_ref().is_none());
8902        // Cached preparation failures are as transient as compiled bridges;
8903        // neither payload needs a codec or may enter a saved state.
8904        let mut failure: RuntimeCache<
8905            Result<super::SamplingChannelBridge, super::sampling::maps::SamplingEvaluationError>,
8906        > = RuntimeCache::default();
8907        failure.set(Err(
8908            super::sampling::maps::SamplingEvaluationError::UncertainGeometry {
8909                detail: "numeric binding fixture".into(),
8910            },
8911        ));
8912        assert!(
8913            bincode::encode_to_vec(&failure, bincode::config::standard())
8914                .unwrap()
8915                .is_empty()
8916        );
8917    }
8918
8919    #[test]
8920    fn arbitrary_precision_override_prefers_the_configured_arb_level() {
8921        let mut settings = StabilitySettings::default();
8922        let arb_level = settings
8923            .levels
8924            .iter_mut()
8925            .find(|level| level.precision == Precision::Arb)
8926            .expect("default stability settings should include Arb");
8927        arb_level.required_precision_for_re = 2.5e-7;
8928        arb_level.three_dimensional_representation = Some(RepresentationMode::Ltd);
8929        let configured_arb_level = *arb_level;
8930
8931        assert_eq!(
8932            create_stability_iterator(&settings, true),
8933            vec![configured_arb_level]
8934        );
8935        assert_eq!(create_stability_iterator(&settings, false), settings.levels);
8936    }
8937
8938    #[test]
8939    fn representation_fallback_keeps_repeated_precisions_and_forced_arb_choice() {
8940        use crate::settings::runtime::StabilityLevelSetting;
8941
8942        let ltd = StabilityLevelSetting {
8943            three_dimensional_representation: Some(RepresentationMode::Ltd),
8944            ..StabilityLevelSetting::default_double()
8945        };
8946        let cff = StabilityLevelSetting {
8947            three_dimensional_representation: Some(RepresentationMode::Cff),
8948            ..StabilityLevelSetting::default_double()
8949        };
8950        let mut settings = StabilitySettings {
8951            levels: vec![ltd, cff],
8952            ..Default::default()
8953        };
8954        assert_eq!(create_stability_iterator(&settings, false), vec![ltd, cff]);
8955        let forced = create_stability_iterator(&settings, true);
8956        assert_eq!(forced.len(), 1);
8957        assert_eq!(forced[0].precision, Precision::Arb);
8958        assert_eq!(
8959            forced[0].three_dimensional_representation,
8960            Some(RepresentationMode::Ltd)
8961        );
8962
8963        settings.levels[0].three_dimensional_representation = None;
8964        let forced = create_stability_iterator(&settings, true);
8965        assert_eq!(forced[0].three_dimensional_representation, None);
8966        assert_eq!(
8967            forced[0]
8968                .resolved_representation(&[RepresentationMode::Ltd, RepresentationMode::Cff])
8969                .unwrap(),
8970            RepresentationMode::Ltd
8971        );
8972    }
8973
8974    #[test]
8975    fn filtered_orientation_helpers_map_visible_indices_into_subset_order() {
8976        let orientations = TiVec::<OrientationID, EdgeVec<Orientation>>::from_iter([
8977            EdgeVec::from_iter([Orientation::Default]),
8978            EdgeVec::from_iter([Orientation::Reversed]),
8979            EdgeVec::from_iter([Orientation::Undirected]),
8980            EdgeVec::from_iter([Orientation::Default]),
8981        ]);
8982        let mut filter = SubSet::empty(orientations.len());
8983        filter.add(OrientationID(1));
8984        filter.add(OrientationID(3));
8985
8986        assert_eq!(filtered_orientation_count(&filter, &orientations), 2);
8987        assert_eq!(
8988            resolve_visible_orientation_id(&filter, 0),
8989            Some(OrientationID(1))
8990        );
8991        assert_eq!(
8992            resolve_visible_orientation_id(&filter, 1),
8993            Some(OrientationID(3))
8994        );
8995        assert_eq!(resolve_visible_orientation_id(&filter, 2), None);
8996    }
8997
8998    #[test]
8999    fn discrete_acceptance_selection_decodes_canonical_channel_id() {
9000        let settings = SamplingSettings::DiscreteGraphs(DiscreteGraphSamplingSettings {
9001            sample_orientations: true,
9002            sampling_type: DiscreteGraphSamplingType::SamplingMultiChanneling(
9003                MultiChannelingSettings::default(),
9004            ),
9005            ..Default::default()
9006        });
9007
9008        let selected = super::resolve_discrete_selection_for_sampling(
9009            &settings,
9010            &[2, 5, 7],
9011            3,
9012            |_| Some(6),
9013            |_| Ok::<Option<usize>, eyre::Report>(Some(8)),
9014        )
9015        .unwrap();
9016        assert_eq!(selected.0, Some(GroupId(2)));
9017        assert_eq!(selected.1, Some(5));
9018        assert_eq!(selected.2, Some(SamplingChannelId::from(7)));
9019
9020        let error = super::resolve_discrete_selection_for_sampling(
9021            &settings,
9022            &[2, 5, 8],
9023            3,
9024            |_| Some(6),
9025            |_| Ok::<Option<usize>, eyre::Report>(Some(8)),
9026        )
9027        .unwrap_err();
9028        assert!(error.to_string().contains("Channel 8 is out of range"));
9029    }
9030
9031    #[test]
9032    fn sampling_channel_basis_ids_use_graph_override_or_optimized_channels() {
9033        test_initialise().unwrap();
9034        static GRAPH: OnceLock<Graph> = OnceLock::new();
9035        let graph = GRAPH
9036            .get_or_init(|| {
9037                finalized_runtime_dot!(
9038                    digraph lmb_basis_selection {
9039                        graph [projector=1]
9040                        edge [num=1 mass=0]
9041                        node [num=1]
9042                        A -> B [id=0 lmb_id=0 source="{ufo_order:0}" sink="{ufo_order:0}"]
9043                        A -> B [id=1 lmb_id=1 source="{ufo_order:1}" sink="{ufo_order:1}"]
9044                        A -> B [id=2 source="{ufo_order:2}" sink="{ufo_order:2}"]
9045                    }
9046                )
9047                .unwrap()
9048            })
9049            .clone();
9050        let lmb = |edge_id| LoopMomentumBasis {
9051            tree: graph.underlying.empty_subgraph(),
9052            loop_edges: vec![EdgeIndex::from(edge_id)].into(),
9053            ext_edges: Vec::new().into(),
9054            edge_signatures: graph.underlying.new_edgevec(|_, _, _| {
9055                LoopExtSignature::from((Vec::<isize>::new(), Vec::<isize>::new()))
9056            }),
9057        };
9058        let all_bases = vec![lmb(0), lmb(1), lmb(2)].into();
9059        let setup = LmbMultiChannelingSetup {
9060            master_edge_masses: Default::default(),
9061            sampling_bridge: Default::default(),
9062            sampling_bridge_quad: Default::default(),
9063            sampling_bridge_fixed256: Default::default(),
9064            sampling_bridge_arb: Default::default(),
9065            sampling_source: Default::default(),
9066            sampling_catalogue: Default::default(),
9067            sampling_programs: Default::default(),
9068            lmb_basis_ids: vec![LmbIndex::from(2), LmbIndex::from(0)].into(),
9069            graph,
9070            all_bases,
9071        };
9072        let default_settings = ParameterizationSettings::default();
9073        let override_settings = ParameterizationSettings {
9074            lmb_basis_ids: std::collections::BTreeMap::from([(setup.graph.name.clone(), vec![1])]),
9075            ..Default::default()
9076        };
9077        let out_of_range_settings = ParameterizationSettings {
9078            lmb_basis_ids: std::collections::BTreeMap::from([(setup.graph.name.clone(), vec![3])]),
9079            ..Default::default()
9080        };
9081
9082        assert_eq!(
9083            setup
9084                .selected_lmb_basis_id(&setup.graph.name, &default_settings)
9085                .unwrap(),
9086            LmbIndex::from(2)
9087        );
9088        assert_eq!(
9089            setup
9090                .selected_lmb_basis_id(&setup.graph.name, &override_settings)
9091                .unwrap(),
9092            LmbIndex::from(1)
9093        );
9094        assert_eq!(
9095            setup
9096                .sampling_channel_ids(&setup.graph.name, &override_settings)
9097                .unwrap(),
9098            vec![SamplingChannelId::from(0)]
9099        );
9100        // The canonical IDs retain their one-domain ordering while resolving
9101        // to the generated LMB basis shown in diagnostics.
9102        assert_eq!(
9103            [SamplingChannelId::from(0)]
9104                .into_iter()
9105                .map(|channel_id| {
9106                    setup
9107                        .sampling_channel_lmb_id(channel_id, &setup.graph.name, &override_settings)
9108                        .unwrap()
9109                })
9110                .collect::<Vec<_>>(),
9111            vec![Some(LmbIndex::from(1))]
9112        );
9113        assert_eq!(
9114            setup
9115                .sampling_channel_lmb_basis_id(
9116                    SamplingChannelId::from(0),
9117                    &setup.graph.name,
9118                    &override_settings,
9119                )
9120                .unwrap(),
9121            LmbIndex::from(1)
9122        );
9123        assert_eq!(
9124            setup
9125                .sampling_channel_edge_ids(
9126                    SamplingChannelId::from(0),
9127                    &setup.graph.name,
9128                    &override_settings,
9129                )
9130                .unwrap()
9131                .as_slice(),
9132            &[1]
9133        );
9134        assert!(
9135            setup
9136                .selected_lmb_basis_id(&setup.graph.name, &out_of_range_settings)
9137                .is_err()
9138        );
9139
9140        for preset in ["auto:lmb", "auto:optimized_lmb", "auto:surfaces"] {
9141            let mut ordered_settings = ParameterizationSettings {
9142                lmb_basis_ids: std::collections::BTreeMap::from([(
9143                    setup.graph.name.clone(),
9144                    vec![2, 1],
9145                )]),
9146                ..Default::default()
9147            };
9148            ordered_settings.sampling_channels.default_channel_selection = vec![preset.into()];
9149            let ids = setup
9150                .sampling_channel_ids(&setup.graph.name, &ordered_settings)
9151                .unwrap();
9152            let edges = ids
9153                .into_iter()
9154                .map(|id| {
9155                    setup
9156                        .sampling_channel_edge_ids(id, &setup.graph.name, &ordered_settings)
9157                        .unwrap()
9158                        .to_vec()
9159                })
9160                .collect::<Vec<_>>();
9161            assert_eq!(
9162                edges,
9163                vec![vec![2], vec![1]],
9164                "{preset} must preserve the exact user override"
9165            );
9166        }
9167
9168        let mut explicit_settings = override_settings.clone();
9169        explicit_settings
9170            .sampling_channels
9171            .default_channel_selection = vec!["lmb(1)".into()];
9172        assert_eq!(
9173            setup
9174                .selected_lmb_basis_id(&setup.graph.name, &explicit_settings)
9175                .unwrap(),
9176            LmbIndex::from(1)
9177        );
9178        explicit_settings
9179            .sampling_channels
9180            .default_channel_selection = vec!["lmb(2)".into()];
9181        let error = setup
9182            .canonical_sampling_catalogue(&setup.graph.name, &explicit_settings)
9183            .unwrap_err();
9184        assert!(
9185            matches!(error.downcast_ref::<SamplingSelectionError>(), Some(SamplingSelectionError::ExcludedLmb { edges, basis_ids, .. }) if edges == &[2] && basis_ids == &[2])
9186        );
9187        explicit_settings
9188            .sampling_channels
9189            .default_channel_selection = vec!["lmb(99)".into()];
9190        let error = setup
9191            .canonical_sampling_catalogue(&setup.graph.name, &explicit_settings)
9192            .unwrap_err();
9193        assert!(
9194            matches!(error.downcast_ref::<SamplingSelectionError>(), Some(SamplingSelectionError::MissingLmb { edges, .. }) if edges == &[99])
9195        );
9196
9197        explicit_settings
9198            .lmb_basis_ids
9199            .insert(setup.graph.name.clone(), vec![2, 1]);
9200        explicit_settings
9201            .sampling_channels
9202            .default_channel_selection = vec!["lmb(1)".into(), "lmb(2)".into()];
9203        let catalogue = setup
9204            .canonical_sampling_catalogue(&setup.graph.name, &explicit_settings)
9205            .unwrap();
9206        assert_eq!(
9207            catalogue
9208                .lmb_basis_entries()
9209                .map(|(id, _)| id)
9210                .collect::<Vec<_>>(),
9211            vec![1, 2]
9212        );
9213
9214        let mut physical_settings = ParameterizationSettings::default();
9215        let parent_lmb = setup
9216            .graph
9217            .loop_momentum_basis
9218            .loop_edges
9219            .iter()
9220            .map(|edge| edge.0)
9221            .collect::<Vec<_>>();
9222        physical_settings
9223            .sampling_channels
9224            .default_channel_selection = vec!["cut".into()];
9225        physical_settings
9226            .sampling_channels
9227            .channel_definitions
9228            .entry(setup.graph.name.clone())
9229            .or_default()
9230            .insert(
9231                "cut".into(),
9232                SamplingChannelDefinition {
9233                    channel_weight: None,
9234                    around: "phase_space(cut(0))".into(),
9235                    subspace_lmb: parent_lmb.clone(),
9236                    parent_lmb,
9237                    on_cut: vec![],
9238                    singularity_proxy: None,
9239                    radial_profile: None,
9240                },
9241            );
9242        let catalogue = setup
9243            .canonical_sampling_catalogue(&setup.graph.name, &physical_settings)
9244            .unwrap();
9245        let dimension = 3 * setup.graph.get_loop_number();
9246        let programs = catalogue
9247            .compile_programs(dimension, &HFunctionSettings::default())
9248            .unwrap();
9249        let context = SamplingChannelCompileContext::<f64>::new(
9250            setup.graph.name.clone(),
9251            setup
9252                .graph
9253                .loop_momentum_basis
9254                .loop_edges
9255                .iter()
9256                .map(|edge| edge.0)
9257                .collect(),
9258            physical_settings,
9259            1.0,
9260            setup.graph.get_loop_number(),
9261        );
9262        // Physical labels alone do not provide their native cut geometry.
9263        assert!(
9264            setup
9265                .compile_sampling_channel_bridge(&catalogue, &programs, &context)
9266                .is_err()
9267        );
9268
9269        // Graph-aware entries occupy the same canonical channel axis as LMB
9270        // entries.  In particular, inserting a named channel before the
9271        // generated LMBs must not make channel id 1 resolve as basis 1 by
9272        // positional filtering.
9273        let mut mixed_settings = ParameterizationSettings::default();
9274        mixed_settings.sampling_channels.default_channel_selection =
9275            vec!["named".into(), "auto:lmb".into()];
9276        mixed_settings
9277            .sampling_channels
9278            .channel_definitions
9279            .entry(setup.graph.name.clone())
9280            .or_default()
9281            .insert(
9282                "named".into(),
9283                SamplingChannelDefinition {
9284                    channel_weight: None,
9285                    around: "lmb(0)".into(),
9286                    subspace_lmb: Vec::new(),
9287                    parent_lmb: vec![0],
9288                    on_cut: Vec::new(),
9289                    singularity_proxy: None,
9290                    radial_profile: None,
9291                },
9292            );
9293        assert_eq!(
9294            setup
9295                .sampling_channel_ids(&setup.graph.name, &mixed_settings)
9296                .unwrap(),
9297            vec![
9298                SamplingChannelId::from(0),
9299                SamplingChannelId::from(1),
9300                SamplingChannelId::from(2),
9301                SamplingChannelId::from(3),
9302            ]
9303        );
9304        assert!(
9305            setup
9306                .sampling_channel_lmb_basis_id(
9307                    SamplingChannelId::from(0),
9308                    &setup.graph.name,
9309                    &mixed_settings,
9310                )
9311                .is_err()
9312        );
9313        assert_eq!(
9314            setup
9315                .sampling_channel_lmb_id(
9316                    SamplingChannelId::from(1),
9317                    &setup.graph.name,
9318                    &mixed_settings,
9319                )
9320                .unwrap(),
9321            Some(LmbIndex::from(0))
9322        );
9323    }
9324
9325    #[test]
9326    fn canonical_lmb_density_partition_matches_inverse_jacobians() {
9327        test_initialise().unwrap();
9328        let mut graph: Graph = finalized_runtime_dot!(
9329            digraph lmb_prefactor_partition {
9330                graph [projector=1]
9331                edge [num=1 mass=0]
9332                node [num=1]
9333                ext [style=invis]
9334                ext -> A [id=0 sink="{ufo_order:0}"]
9335                A -> B [id=1 lmb_id=0 source="{ufo_order:1}" sink="{ufo_order:0}"]
9336                A -> B [id=2 source="{ufo_order:2}" sink="{ufo_order:1}"]
9337                B -> ext [id=3 source="{ufo_order:2}"]
9338            }
9339        )
9340        .unwrap();
9341        let all_bases = graph.generate_loop_momentum_bases();
9342        assert!(all_bases.len() >= 2);
9343        graph.loop_momentum_basis = all_bases[LmbIndex::from(0)].clone();
9344        let mut setup = LmbMultiChannelingSetup {
9345            master_edge_masses: Default::default(),
9346            sampling_bridge: Default::default(),
9347            sampling_bridge_quad: Default::default(),
9348            sampling_bridge_fixed256: Default::default(),
9349            sampling_bridge_arb: Default::default(),
9350            sampling_source: Default::default(),
9351            sampling_catalogue: Default::default(),
9352            sampling_programs: Default::default(),
9353            lmb_basis_ids: vec![LmbIndex::from(0), LmbIndex::from(1)].into(),
9354            graph: graph.clone(),
9355            all_bases,
9356        };
9357        let loop_moms: LoopMomenta<F<f64>> = graph
9358            .loop_momentum_basis
9359            .loop_edges
9360            .iter()
9361            .enumerate()
9362            .map(|(index, _)| {
9363                let offset = index as f64;
9364                ThreeMomentum::new(F(0.4 + offset), F(-0.3), F(0.2 - offset))
9365            })
9366            .collect();
9367        let external_moms: ExternalFourMomenta<F<f64>> =
9368            (0..graph.loop_momentum_basis.ext_edges.len())
9369                .map(|_| [F(0.0), F(0.2), F(-0.3), F(0.4)].into())
9370                .collect();
9371        let sample = MomentumSample {
9372            sample: BareMomentumSample {
9373                loop_moms,
9374                dual_loop_moms: None,
9375                loop_mom_cache_id: 0,
9376                loop_mom_base_cache_id: 0,
9377                external_moms,
9378                external_mom_cache_id: 0,
9379                external_mom_base_cache_id: 0,
9380                external_rotations: Vec::new(),
9381                jacobian: F(1.0),
9382                orientation: None,
9383                parameterization_branch: None,
9384            },
9385        };
9386        let mut parameterization_settings = ParameterizationSettings::default();
9387        parameterization_settings
9388            .sampling_channels
9389            .default_channel_selection = vec!["auto:lmb".into()];
9390        let resolved = resolve_sampling_channel_selection(
9391            &graph.name,
9392            &parameterization_settings.sampling_channels,
9393        )
9394        .unwrap();
9395        let context = SamplingChannelCompileContext::new(
9396            graph.name.clone(),
9397            graph
9398                .loop_momentum_basis
9399                .loop_edges
9400                .iter()
9401                .map(|edge| edge.0)
9402                .collect(),
9403            parameterization_settings.clone(),
9404            1.0,
9405            sample.loop_moms().0.len(),
9406        );
9407        let external = sample
9408            .external_moms()
9409            .iter()
9410            .map(|momentum| {
9411                [
9412                    momentum.temporal.value.0,
9413                    momentum.spatial.px.0,
9414                    momentum.spatial.py.0,
9415                    momentum.spatial.pz.0,
9416                ]
9417            })
9418            .collect::<Vec<_>>();
9419        let bridge = setup
9420            .compile_sampling_channel_bridge_with_external(
9421                &setup
9422                    .sampling_channel_catalogue(&resolved, &context.parameterization_settings)
9423                    .unwrap(),
9424                &setup
9425                    .sampling_channel_catalogue(&resolved, &context.parameterization_settings)
9426                    .unwrap()
9427                    .compile_programs(3 * context.n_loop_momenta, &HFunctionSettings::default())
9428                    .unwrap(),
9429                &context,
9430                &external,
9431            )
9432            .unwrap();
9433        let raw = sample
9434            .loop_moms()
9435            .iter()
9436            .flat_map(|momentum| [momentum.px.0, momentum.py.0, momentum.pz.0])
9437            .collect::<Vec<_>>();
9438        // Check map-density weights against independent inverse parameterizations
9439        // in every generated LMB at the same parent momentum point. This retains
9440        // the former prefactor partition's pointwise normalization test without
9441        // keeping a separate LMB weighting implementation in production.
9442        let scores = setup
9443            .all_bases
9444            .iter()
9445            .map(|basis| {
9446                let momenta = basis
9447                    .loop_edges
9448                    .iter()
9449                    .map(|edge| {
9450                        let signature = &graph.loop_momentum_basis.edge_signatures[*edge];
9451                        signature.internal.apply_typed(sample.loop_moms())
9452                            + signature
9453                                .external
9454                                .apply(&sample.external_moms().raw)
9455                                .spatial
9456                    })
9457                    .collect::<Vec<_>>();
9458                crate::utils::global_inv_parameterize(&momenta, F(1.0), &parameterization_settings)
9459                    .1
9460                    .0
9461            })
9462            .collect::<Vec<_>>();
9463        let total = scores.iter().sum::<f64>();
9464        for (channel_id, score) in scores.iter().enumerate().take(bridge.channels().len()) {
9465            let evaluation = bridge
9466                .inverse(SamplingChannelId::from(channel_id), &raw)
9467                .unwrap()
9468                .expect("full-support channel inverse");
9469            assert!((evaluation.partition.weights.iter().sum::<f64>() - 1.0).abs() < 1.0e-14);
9470            let actual = evaluation.partition.weight(channel_id).unwrap();
9471            let expected = score / total;
9472            assert!(
9473                (actual - expected).abs() < 1.0e-14,
9474                "channel {channel_id}: {actual} != {expected}"
9475            );
9476        }
9477        // The master owns OSE masses even if a member/context supplies different ones.
9478        // Refresh twice to catch a stale runtime cache after a model/mass change.
9479        let model = crate::utils::load_generic_model("sm");
9480        let mut context = context;
9481        context.parameterization_settings.sampling_channels.weight =
9482            crate::settings::runtime::SamplingChannelWeight::Ose;
9483        context.edge_masses = graph
9484            .new_edgevec(|_, _, _| spenso::algebra::complex::Complex::new_re(F(1000.0)))
9485            .iter()
9486            .map(|(edge, mass)| (edge.0, *mass))
9487            .collect();
9488        for mass in [2.0, 5.0] {
9489            let edge = *setup.all_bases[LmbIndex::from(0)]
9490                .loop_edges
9491                .first()
9492                .unwrap();
9493            setup.graph.underlying[edge].mass = crate::graph::edge::EdgeMass::Value(
9494                spenso::algebra::complex::Complex::new_re(F(mass)),
9495            );
9496            setup
9497                .warm_up_masses(&RuntimeSettings::default(), &model)
9498                .unwrap();
9499            assert_eq!(setup.master_edge_masses.as_ref().unwrap()[edge].re, F(mass));
9500            assert_ne!(graph.get_real_mass_vector::<f64>(&model)[edge], F(mass));
9501            let catalogue = setup
9502                .sampling_channel_catalogue(&resolved, &context.parameterization_settings)
9503                .unwrap();
9504            let programs = catalogue
9505                .compile_programs(3 * context.n_loop_momenta, &HFunctionSettings::default())
9506                .unwrap();
9507            let bridge = setup
9508                .compile_sampling_channel_bridge_with_external(
9509                    &catalogue, &programs, &context, &external,
9510                )
9511                .unwrap();
9512            let energies = setup.graph.get_energy_cache(
9513                &model,
9514                sample.loop_moms(),
9515                sample.external_moms(),
9516                &setup.graph.loop_momentum_basis,
9517            );
9518            let scores = setup
9519                .all_bases
9520                .iter()
9521                .map(|basis| {
9522                    basis
9523                        .loop_edges
9524                        .iter()
9525                        .map(|edge| energies[*edge].0)
9526                        .product::<f64>()
9527                        .powf(-3.0)
9528                })
9529                .collect::<Vec<_>>();
9530            let partition = bridge.partition(&raw).unwrap();
9531            let total = scores.iter().sum::<f64>();
9532            for (actual, score) in partition.weights.iter().zip(scores) {
9533                assert!((actual - score / total).abs() < 1e-13);
9534            }
9535        }
9536    }
9537
9538    #[test]
9539    fn process_catalogue_bridge_integrates_normalized_gaussian() {
9540        test_initialise().unwrap();
9541        let mut graph: Graph = crate::finalized_runtime_dot!(
9542            digraph process_sampling_acceptance {
9543 graph [projector=1]
9544                edge [num=1 mass=0]
9545                node [num=1]
9546                ext [style=invis]
9547                ext -> A [id=0 sink="{ufo_order:0}"]
9548                A -> B [id=1 source="{ufo_order:1}" sink="{ufo_order:0}" lmb_id=0]
9549                A -> B [id=2 source="{ufo_order:2}" sink="{ufo_order:1}"]
9550                B -> ext [id=3 source="{ufo_order:2}"]
9551            }
9552        , &crate::utils::load_generic_model("sm"))
9553        .unwrap();
9554        let generated_bases = graph.generate_loop_momentum_bases();
9555        assert!(!generated_bases.is_empty());
9556        graph.loop_momentum_basis = generated_bases[LmbIndex::from(0)].clone();
9557        let all_bases = vec![graph.loop_momentum_basis.clone()].into();
9558        let parent_lmb = graph
9559            .loop_momentum_basis
9560            .loop_edges
9561            .iter()
9562            .map(|edge| edge.0)
9563            .collect::<Vec<_>>();
9564        let setup = LmbMultiChannelingSetup {
9565            master_edge_masses: Default::default(),
9566            sampling_bridge: Default::default(),
9567            sampling_bridge_quad: Default::default(),
9568            sampling_bridge_fixed256: Default::default(),
9569            sampling_bridge_arb: Default::default(),
9570            sampling_source: Default::default(),
9571            sampling_catalogue: Default::default(),
9572            sampling_programs: Default::default(),
9573            lmb_basis_ids: vec![LmbIndex::from(0)].into(),
9574            graph: graph.clone(),
9575            all_bases,
9576        };
9577
9578        let selection = SamplingChannelSelection::default();
9579        let resolved = resolve_sampling_channel_selection(&graph.name, &selection).unwrap();
9580        let parameterization_settings = ParameterizationSettings {
9581            sampling_channels: selection,
9582            ..Default::default()
9583        };
9584        let context = SamplingChannelCompileContext::new(
9585            graph.name.clone(),
9586            parent_lmb,
9587            parameterization_settings,
9588            100.0,
9589            graph.loop_momentum_basis.loop_edges.len(),
9590        );
9591        let bridge = setup
9592            .compile_sampling_channel_bridge(
9593                &setup
9594                    .sampling_channel_catalogue(&resolved, &context.parameterization_settings)
9595                    .unwrap(),
9596                &setup
9597                    .sampling_channel_catalogue(&resolved, &context.parameterization_settings)
9598                    .unwrap()
9599                    .compile_programs(3 * context.n_loop_momenta, &HFunctionSettings::default())
9600                    .unwrap(),
9601                &context,
9602            )
9603            .unwrap();
9604        assert_eq!(
9605            setup
9606                .sampling_channel_ids(&graph.name, &context.parameterization_settings)
9607                .unwrap()
9608                .len(),
9609            bridge.channels().len(),
9610            "omitted defaults must resolve identically for channel counts and compiled maps"
9611        );
9612        assert_eq!(bridge.channels().len(), 1);
9613
9614        let dimensions = bridge.dimensions();
9615        let width = 1.5;
9616        let normalisation =
9617            (2.0 * std::f64::consts::PI * width * width).powf(-0.5 * dimensions as f64);
9618        let samples = 2048usize;
9619        let mut integral = 0.0;
9620        for sample in 1..=samples {
9621            let coordinates = (0..dimensions)
9622                .map(|axis| {
9623                    let base = [2_u64, 3, 5, 7, 11, 13, 17, 19][axis];
9624                    let mut index = sample;
9625                    let mut fraction = 1.0;
9626                    let mut value = 0.0;
9627                    while index > 0 {
9628                        fraction /= base as f64;
9629                        value += fraction * (index as u64 % base) as f64;
9630                        index /= base as usize;
9631                    }
9632                    value
9633                })
9634                .collect::<Vec<_>>();
9635            let evaluation = bridge
9636                .forward(SamplingChannelId::from(0), &coordinates)
9637                .unwrap();
9638            assert!((evaluation.partition.weights.iter().sum::<f64>() - 1.0).abs() < 1.0e-14);
9639            let radius_squared = evaluation
9640                .raw_coordinates
9641                .iter()
9642                .map(|component| component * component)
9643                .sum::<f64>();
9644            integral += normalisation
9645                * (-0.5 * radius_squared / width.powi(2)).exp()
9646                * evaluation.map.jacobian;
9647        }
9648        integral /= samples as f64;
9649        assert!(
9650            (integral - 1.0).abs() < 5.0e-2,
9651            "process sampling bridge Gaussian integral = {integral}"
9652        );
9653    }
9654}