Skip to main content

gammaloop_api/
integrand_info.rs

1use std::fmt;
2
3use color_eyre::Result;
4use eyre::{eyre, Context};
5use gammalooprs::{
6    cff::esurface::EsurfaceExistenceStatus,
7    graph::{
8        threshold_counterterms::ThresholdCountertermVariant, FeynmanGraph, FinalizedCut, Graph,
9    },
10    integrands::process::{ActiveF64Backend, LmbMultiChannelingSetup, ParamBuilder},
11    model::Model,
12    processes::{
13        Amplitude, CrossSection, CutId, ProcessCollection, ThresholdCountertermAssociation,
14        ThresholdCountertermMetadataRegistry, ThresholdCountertermMultiplierMetadata,
15        ThresholdCountertermStatus,
16    },
17    settings::{global::FrozenCompilationMode, runtime::ParameterizationSettings, RuntimeSettings},
18    utils::F,
19    DependentMomentaConstructor,
20};
21use linnet::half_edge::involution::{EdgeVec, Orientation};
22use schemars::JsonSchema;
23use serde::{Deserialize, Serialize};
24
25use crate::state::State;
26use three_dimensional_reps::RepresentationMode;
27
28#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
29#[serde(rename_all = "snake_case")]
30pub enum IntegrandKind {
31    Amplitude,
32    CrossSection,
33}
34
35impl fmt::Display for IntegrandKind {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        match self {
38            Self::Amplitude => f.write_str("amplitude"),
39            Self::CrossSection => f.write_str("cross section"),
40        }
41    }
42}
43
44#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
45pub struct IntegrandGraphInfo {
46    pub graph_id: usize,
47    pub name: String,
48    pub is_master: bool,
49    /// Native residue-map rows for each generated representation, in generation order.
50    pub native_residue_counts: Vec<(RepresentationMode, usize)>,
51    /// Compact, explicit graph directives, flattened only for display/API consumption.
52    ///
53    /// Autogenerated legacy associations are deliberately absent. An explicit threshold with no
54    /// counterterm blocks contributes one `implicit_default` row because that shorthand is part of
55    /// the graph document's semantics.
56    #[serde(default, skip_serializing_if = "Vec::is_empty")]
57    pub threshold_counterterm_directives: Vec<IntegrandThresholdCountertermDirectiveInfo>,
58    #[serde(default, skip_serializing_if = "Option::is_none")]
59    pub threshold_counterterms: Option<ThresholdCountertermMetadataRegistry>,
60}
61
62#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
63pub struct IntegrandThresholdCountertermDirectiveInfo {
64    pub cut_edge_ids: Vec<usize>,
65    pub threshold_edge_ids: Vec<usize>,
66    pub name: String,
67    pub implicit_default: bool,
68    pub requested_subspace: Option<Vec<usize>>,
69    pub requested_parent_lmb: Option<Vec<usize>>,
70    pub disabled: bool,
71    pub multiplier: Option<ThresholdCountertermMultiplierMetadata>,
72}
73
74impl IntegrandThresholdCountertermDirectiveInfo {
75    fn explicit_for_graph(graph: &Graph) -> Vec<Self> {
76        if graph.threshold_counterterms.autogenerated {
77            return Vec::new();
78        }
79
80        graph
81            .threshold_counterterms
82            .cuts
83            .iter()
84            .flat_map(|cut| {
85                cut.thresholds.iter().flat_map(move |threshold| {
86                    let implicit_default = ThresholdCountertermVariant {
87                        name: Some("default".to_string()),
88                        group_id: None,
89                        subspace: None,
90                        parent_lmb: None,
91                        disable: false,
92                        multiplier: None,
93                    };
94                    let variants = if threshold.counterterms.is_empty() {
95                        std::slice::from_ref(&implicit_default)
96                    } else {
97                        &threshold.counterterms
98                    };
99
100                    variants
101                        .iter()
102                        .map(move |variant| Self {
103                            cut_edge_ids: cut.edges.iter().map(|edge| edge.0).collect(),
104                            threshold_edge_ids: threshold.edges.iter().map(|edge| edge.0).collect(),
105                            name: variant
106                                .name
107                                .clone()
108                                .unwrap_or_else(|| "default".to_string()),
109                            implicit_default: threshold.counterterms.is_empty(),
110                            requested_subspace: variant
111                                .subspace
112                                .as_ref()
113                                .map(|edges| edges.iter().map(|edge| edge.0).collect()),
114                            requested_parent_lmb: variant
115                                .parent_lmb
116                                .as_ref()
117                                .map(|edges| edges.iter().map(|edge| edge.0).collect()),
118                            disabled: variant.disable,
119                            multiplier: variant.multiplier.as_ref().map(|multiplier| {
120                                ThresholdCountertermMultiplierMetadata {
121                                    expression: multiplier.expression.clone(),
122                                    function_map: graph
123                                        .threshold_counterterms
124                                        .function_map
125                                        .iter()
126                                        .chain(&multiplier.function_map)
127                                        .map(|(key, value)| (key.clone(), value.clone()))
128                                        .collect(),
129                                    symmetrize: multiplier.symmetrize,
130                                    opaque_derivatives: multiplier.opaque_derivatives,
131                                }
132                            }),
133                        })
134                        .collect::<Vec<_>>()
135                })
136            })
137            .collect()
138    }
139}
140
141#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
142pub struct IntegrandOrientationInfo {
143    pub orientation_id: usize,
144    /// Directions along the group's orientation edges; empty for a complete residue sum.
145    pub signature: Vec<i8>,
146}
147
148#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
149pub struct IntegrandLoopMomentumBasisInfo {
150    pub basis_id: usize,
151    pub channel_id: Option<usize>,
152    pub edge_ids: Vec<usize>,
153    pub matches_generation_basis: bool,
154}
155
156#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
157pub struct IntegrandCutInfo {
158    pub cut_id: usize,
159    pub edge_ids: Vec<usize>,
160    pub raising_power: usize,
161    pub left_thresholds: Vec<IntegrandCutThresholdInfo>,
162    pub right_thresholds: Vec<IntegrandCutThresholdInfo>,
163}
164
165#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
166#[serde(rename_all = "snake_case")]
167pub enum IntegrandThresholdStatus {
168    NoRadialDependence,
169    AlwaysPinched,
170    CanBecomePinched,
171    ProvenNonExisting,
172    PotentiallyExisting,
173}
174
175impl IntegrandThresholdStatus {
176    pub fn as_str(self) -> &'static str {
177        match self {
178            Self::NoRadialDependence => "no_radial_dependence",
179            Self::AlwaysPinched => "always_pinched",
180            Self::CanBecomePinched => "can_become_pinched",
181            Self::ProvenNonExisting => "proven_non_existing",
182            Self::PotentiallyExisting => "potentially_existing",
183        }
184    }
185
186    pub fn is_currently_viable(self) -> bool {
187        matches!(self, Self::CanBecomePinched | Self::PotentiallyExisting)
188    }
189
190    pub fn can_become_pinched(self) -> bool {
191        self == Self::CanBecomePinched
192    }
193}
194
195impl From<ThresholdCountertermStatus> for IntegrandThresholdStatus {
196    fn from(value: ThresholdCountertermStatus) -> Self {
197        match value {
198            ThresholdCountertermStatus::NoRadialDependence => Self::NoRadialDependence,
199            ThresholdCountertermStatus::AlwaysPinched => Self::AlwaysPinched,
200            ThresholdCountertermStatus::CanBecomePinched => Self::CanBecomePinched,
201            ThresholdCountertermStatus::ProvenNonExisting => Self::ProvenNonExisting,
202            ThresholdCountertermStatus::PotentiallyExisting => Self::PotentiallyExisting,
203        }
204    }
205}
206
207#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
208pub struct IntegrandCutThresholdInfo {
209    pub esurface_id: usize,
210    pub status: IntegrandThresholdStatus,
211    pub cut_boundary_edge_ids: Vec<usize>,
212    pub threshold_boundary_edge_ids: Vec<usize>,
213    pub invariant_bound_is_applicable: bool,
214}
215
216impl IntegrandCutThresholdInfo {
217    fn from_association(
218        association: &ThresholdCountertermAssociation,
219        graph: &Graph,
220        cut: &FinalizedCut,
221        model: &Model,
222        param_builder: &ParamBuilder,
223        settings: &RuntimeSettings,
224    ) -> Self {
225        Self {
226            esurface_id: association.topological_threshold_id.0,
227            status: association
228                .classify_for_model(
229                    graph,
230                    cut,
231                    model,
232                    param_builder,
233                    settings,
234                    settings.subtraction.esurface_existence_threshold,
235                )
236                .into(),
237            cut_boundary_edge_ids: association
238                .cut_boundary_edges
239                .iter()
240                .map(|edge_id| edge_id.0)
241                .collect(),
242            threshold_boundary_edge_ids: association
243                .threshold_boundary_edges
244                .iter()
245                .map(|edge_id| edge_id.0)
246                .collect(),
247            invariant_bound_is_applicable: association.invariant_bound_is_applicable,
248        }
249    }
250}
251
252#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
253pub struct IntegrandActiveThresholdCutInfo {
254    pub cut_id: usize,
255    pub can_become_pinched: bool,
256}
257
258#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
259#[serde(rename_all = "snake_case")]
260pub enum IntegrandEsurfaceClassification {
261    NonExisting,
262    Pinched,
263    Existing,
264}
265
266impl IntegrandEsurfaceClassification {
267    pub fn as_str(self) -> &'static str {
268        match self {
269            Self::NonExisting => "non_existing",
270            Self::Pinched => "pinched",
271            Self::Existing => "existing",
272        }
273    }
274}
275
276#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
277pub struct IntegrandThresholdEsurfaceInfo {
278    pub esurface_id: usize,
279    pub representative_graph_id: usize,
280    pub edge_ids: Vec<usize>,
281    pub classification: Option<IntegrandEsurfaceClassification>,
282    pub active_cuts: Vec<IntegrandActiveThresholdCutInfo>,
283}
284
285impl IntegrandCutInfo {
286    fn from_cross_section_cut(
287        graph_term: &gammalooprs::integrands::process::cross_section::CrossSectionGraphTerm,
288        cut_id: CutId,
289        cut: &FinalizedCut,
290        raising_power: usize,
291        model: &Model,
292        param_builder: &ParamBuilder,
293        settings: &RuntimeSettings,
294    ) -> Self {
295        let associations = &graph_term.cut_threshold_associations[cut_id];
296        let threshold_info = |association| {
297            IntegrandCutThresholdInfo::from_association(
298                association,
299                &graph_term.graph,
300                cut,
301                model,
302                param_builder,
303                settings,
304            )
305        };
306
307        Self {
308            // Retain `CutId` for internal indexing and convert only at the API boundary.
309            cut_id: usize::from(cut_id),
310            edge_ids: cut_edge_ids(&graph_term.graph, cut),
311            raising_power,
312            left_thresholds: associations.left.iter().map(&threshold_info).collect(),
313            right_thresholds: associations.right.iter().map(threshold_info).collect(),
314        }
315    }
316
317    fn active_threshold_cut(&self, esurface_id: usize) -> Option<IntegrandActiveThresholdCutInfo> {
318        let mut is_currently_viable = false;
319        let mut can_become_pinched = false;
320
321        for threshold in self
322            .left_thresholds
323            .iter()
324            .chain(self.right_thresholds.iter())
325            .filter(|threshold| threshold.esurface_id == esurface_id)
326        {
327            is_currently_viable |= threshold.status.is_currently_viable();
328            can_become_pinched |= threshold.status.can_become_pinched();
329        }
330
331        is_currently_viable.then_some(IntegrandActiveThresholdCutInfo {
332            cut_id: self.cut_id,
333            can_become_pinched,
334        })
335    }
336}
337
338#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
339pub struct IntegrandGraphGroupInfo {
340    pub group_id: usize,
341    pub graphs: Vec<IntegrandGraphInfo>,
342    /// True when the runtime layout evaluates a complete physical residue sum.
343    pub complete_residue_sum: bool,
344    pub orientation_edge_ids: Vec<usize>,
345    pub orientations: Vec<IntegrandOrientationInfo>,
346    pub loop_momentum_bases: Vec<IntegrandLoopMomentumBasisInfo>,
347    pub threshold_esurface_ids: Vec<usize>,
348    pub threshold_esurfaces: Vec<IntegrandThresholdEsurfaceInfo>,
349    pub cuts: Vec<IntegrandCutInfo>,
350}
351
352fn threshold_esurface_edge_ids(
353    esurfaces: &gammalooprs::cff::esurface::EsurfaceCollection,
354    esurface_id: usize,
355) -> Vec<usize> {
356    esurfaces
357        .iter()
358        .nth(esurface_id)
359        .expect("threshold esurface id should resolve in collection")
360        .energies
361        .iter()
362        .map(|edge_id| edge_id.0)
363        .collect()
364}
365
366#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
367pub struct IntegrandInfo {
368    /// Numeric identifier of the process that owns the integrand.
369    pub process_id: usize,
370    /// Persistent folder name of the owning process.
371    pub process_name: String,
372    /// Canonical name of the resolved integrand.
373    pub integrand_name: String,
374    /// Whether the integrand represents an amplitude or cross section.
375    pub kind: IntegrandKind,
376    /// Representations stored in the generated payload, in generation order.
377    pub generated_representations: Vec<RepresentationMode>,
378    /// Compilation mode frozen into the generated integrand.
379    pub generation_compilation: FrozenCompilationMode,
380    /// Floating-point evaluator backend currently active for the integrand.
381    pub active_f64_backend: ActiveF64Backend,
382    /// Number of graph terms in the generated integrand.
383    pub graph_count: usize,
384    /// Number of graph groups in the generated integrand.
385    pub graph_group_count: usize,
386    /// Bincode size of the saved integrand record, excluding its compiled evaluator.
387    pub record_size_bytes: usize,
388    /// Per-group graphs, orientations, loop-momentum bases, thresholds, and cuts.
389    pub graph_groups: Vec<IntegrandGraphGroupInfo>,
390}
391
392pub(crate) fn collect_integrand_info(
393    state: &State,
394    process_id: usize,
395    integrand_name: &str,
396) -> Result<IntegrandInfo> {
397    let process = &state.process_list.processes[process_id];
398    let resolved = process.get_integrand(integrand_name)?;
399    let generated = resolved.require_generated()?;
400    let generation_compilation = generated.frozen_compilation().clone();
401    let active_f64_backend = generated.active_f64_backend();
402
403    match (generated, &process.collection) {
404        (
405            gammalooprs::integrands::process::ProcessIntegrand::Amplitude(integrand),
406            ProcessCollection::Amplitudes(amplitudes),
407        ) => {
408            let amplitude = amplitudes.get(&resolved.canonical_name).ok_or_else(|| {
409                eyre!(
410                    "Could not resolve amplitude record '{}' in process #{} ({})",
411                    resolved.canonical_name,
412                    process.definition.process_id,
413                    process.definition.folder_name
414                )
415            })?;
416            let model = state.resolve_model_for_integrand(
417                process.definition.process_id,
418                &resolved.canonical_name,
419            )?;
420            Ok(IntegrandInfo {
421                process_id: process.definition.process_id,
422                process_name: process.definition.folder_name.clone(),
423                integrand_name: resolved.canonical_name,
424                kind: IntegrandKind::Amplitude,
425                generated_representations: integrand.data.three_d_representations.clone(),
426                generation_compilation: generation_compilation.clone(),
427                active_f64_backend,
428                graph_count: amplitude.graphs.len(),
429                graph_group_count: amplitude.graph_group_structure.len(),
430                record_size_bytes: integrand_record_size_from_amplitude(amplitude)?,
431                graph_groups: amplitude_graph_groups(integrand, amplitude, &model)?,
432            })
433        }
434        (
435            gammalooprs::integrands::process::ProcessIntegrand::CrossSection(integrand),
436            ProcessCollection::CrossSections(cross_sections),
437        ) => {
438            let cross_section = cross_sections
439                .get(&resolved.canonical_name)
440                .ok_or_else(|| {
441                    eyre!(
442                        "Could not resolve cross-section record '{}' in process #{} ({})",
443                        resolved.canonical_name,
444                        process.definition.process_id,
445                        process.definition.folder_name
446                    )
447                })?;
448            let model = state.resolve_model_for_integrand(
449                process.definition.process_id,
450                &resolved.canonical_name,
451            )?;
452            Ok(IntegrandInfo {
453                process_id: process.definition.process_id,
454                process_name: process.definition.folder_name.clone(),
455                integrand_name: resolved.canonical_name,
456                kind: IntegrandKind::CrossSection,
457                generated_representations: integrand.data.three_d_representations.clone(),
458                generation_compilation,
459                active_f64_backend,
460                graph_count: integrand.data.graph_terms.len(),
461                graph_group_count: integrand.data.graph_group_structure.len(),
462                record_size_bytes: integrand_record_size_from_cross_section(cross_section)?,
463                graph_groups: cross_section_graph_groups(integrand, cross_section, &model)?,
464            })
465        }
466        _ => Err(eyre!(
467            "Process/integrand type mismatch for '{}' in process #{} ({})",
468            resolved.canonical_name,
469            process.definition.process_id,
470            process.definition.folder_name
471        )),
472    }
473}
474
475fn orientation_signature(orientation: &EdgeVec<Orientation>) -> Vec<i8> {
476    orientation
477        .iter()
478        .map(|(_, orientation)| match *orientation {
479            Orientation::Default => 1,
480            Orientation::Reversed => -1,
481            Orientation::Undirected => 0,
482        })
483        .collect()
484}
485
486fn orientation_edge_ids(orientation: &EdgeVec<Orientation>) -> Vec<usize> {
487    orientation.iter().map(|(edge_id, _)| edge_id.0).collect()
488}
489
490fn cut_edge_ids(graph: &Graph, cut: &FinalizedCut) -> Vec<usize> {
491    cut.cut
492        .iter_edges(&graph.underlying)
493        .map(|(_, edge)| {
494            graph
495                .underlying
496                .iter_edges()
497                .find_map(|(_, edge_id, edge_data)| {
498                    (edge_data.data.name == edge.data.name).then_some(edge_id.0)
499                })
500                .expect("cut edge should resolve in graph")
501        })
502        .collect()
503}
504
505fn cut_raising_powers(
506    graph: &gammalooprs::integrands::process::cross_section::CrossSectionGraphTerm,
507) -> typed_index_collections::TiVec<CutId, usize> {
508    let mut raising_powers: typed_index_collections::TiVec<CutId, usize> =
509        vec![1; graph.cuts.len()].into();
510    for cut_group in graph.cut_group_data.cut_groups.iter() {
511        let raising_power = cut_group.related_esurface_group.max_occurence;
512        for cut_id in &cut_group.cuts {
513            raising_powers[*cut_id] = raising_power;
514        }
515    }
516    raising_powers
517}
518
519fn sampling_channel_ids(
520    lmbs: &typed_index_collections::TiVec<
521        gammalooprs::graph::LmbIndex,
522        gammalooprs::graph::LoopMomentumBasis,
523    >,
524    multi_channeling_setup: &LmbMultiChannelingSetup,
525    graph_name: &str,
526    parameterization_settings: &ParameterizationSettings,
527) -> Result<Vec<Option<usize>>> {
528    let mut channel_ids = vec![None; lmbs.len()];
529    for channel_id in
530        multi_channeling_setup.sampling_channel_ids(graph_name, parameterization_settings)?
531    {
532        if let Some(lmb_index) = multi_channeling_setup.sampling_channel_lmb_id(
533            channel_id,
534            graph_name,
535            parameterization_settings,
536        )? {
537            channel_ids[usize::from(lmb_index)] = Some(channel_id.index());
538        }
539    }
540    Ok(channel_ids)
541}
542
543fn amplitude_graph_groups(
544    integrand: &gammalooprs::integrands::process::amplitude::AmplitudeIntegrand,
545    amplitude: &Amplitude,
546    model: &Model,
547) -> Result<Vec<IntegrandGraphGroupInfo>> {
548    let parameterization_settings = integrand
549        .settings
550        .sampling
551        .get_parameterization_settings()
552        .unwrap_or_default();
553    let external_momenta = integrand
554        .settings
555        .kinematics
556        .externals
557        .get_dependent_externals::<f64>(DependentMomentaConstructor::Amplitude(
558            &integrand.data.external_signature,
559        ))
560        .context("While constructing amplitude external momenta for integrand information")?;
561    let e_cm = F(integrand.settings.kinematics.e_cm);
562    let existence_tolerance = F(integrand.settings.subtraction.esurface_existence_threshold);
563    let real_mass_vectors = integrand
564        .data
565        .graph_terms
566        .iter()
567        .map(|graph_term| graph_term.graph.get_real_mass_vector::<f64>(model))
568        .collect::<Vec<_>>();
569    integrand
570        .data
571        .graph_group_structure
572        .iter_enumerated()
573        .map(|(group_id, group)| {
574            let master_graph_id = group
575                .into_iter()
576                .next()
577                .expect("graph group should not be empty");
578            let master_graph = &integrand.data.graph_terms[master_graph_id];
579            let channel_ids = sampling_channel_ids(
580                &master_graph.lmbs,
581                &master_graph.multi_channeling_setup,
582                &master_graph.graph.name,
583                &parameterization_settings,
584            )?;
585            // Amplitude overlap centers are solved from the canonical union across all members
586            // of the graph group. Report that same union rather than the master graph's local
587            // raised-surface numbering.
588            let threshold_esurfaces = integrand.data.group_derived_data[group_id]
589                .esurface_map
590                .iter_enumerated()
591                .filter_map(|(group_esurface_id, raised_esurface_map)| {
592                    let (representative_graph_id, raised_esurface_id) = raised_esurface_map
593                        .iter_enumerated()
594                        .filter_map(|(graph_group_position, raised_esurface_id)| {
595                            raised_esurface_id.map(|raised_esurface_id| {
596                                let graph_id = group[graph_group_position];
597                                (graph_id, raised_esurface_id)
598                            })
599                        })
600                        .find(|(graph_id, raised_esurface_id)| {
601                            integrand.data.graph_terms[*graph_id]
602                                .threshold_counterterm
603                                .generated_mask[*raised_esurface_id]
604                        })?;
605                    let graph_term = &integrand.data.graph_terms[representative_graph_id];
606                    let local_esurface_id =
607                        graph_term.threshold_counterterm.raised_data.raised_groups
608                            [raised_esurface_id]
609                            .esurface_ids[0];
610
611                    let mut classification = IntegrandEsurfaceClassification::NonExisting;
612                    for (graph_group_position, raised_esurface_id) in raised_esurface_map
613                        .iter_enumerated()
614                        .filter_map(|(graph_group_position, raised_esurface_id)| {
615                            raised_esurface_id.map(|raised_esurface_id| {
616                                (graph_group_position, raised_esurface_id)
617                            })
618                        })
619                    {
620                        let graph_id = group[graph_group_position];
621                        let candidate = &integrand.data.graph_terms[graph_id];
622                        let candidate_esurface_id =
623                            candidate.threshold_counterterm.raised_data.raised_groups
624                                [raised_esurface_id]
625                                .esurface_ids[0];
626                        let candidate_status = candidate.esurfaces[candidate_esurface_id]
627                            .existence_status(
628                                &external_momenta,
629                                &candidate.graph.loop_momentum_basis,
630                                &real_mass_vectors[graph_id],
631                                &e_cm,
632                                &existence_tolerance,
633                            );
634                        match candidate_status {
635                            EsurfaceExistenceStatus::Existing => {
636                                classification = IntegrandEsurfaceClassification::Existing;
637                                break;
638                            }
639                            EsurfaceExistenceStatus::Pinched => {
640                                classification = IntegrandEsurfaceClassification::Pinched;
641                            }
642                            EsurfaceExistenceStatus::NonExisting => {}
643                        }
644                    }
645
646                    Some(IntegrandThresholdEsurfaceInfo {
647                        esurface_id: group_esurface_id.0,
648                        representative_graph_id,
649                        edge_ids: threshold_esurface_edge_ids(
650                            &graph_term.esurfaces,
651                            local_esurface_id.0,
652                        ),
653                        classification: Some(classification),
654                        active_cuts: Vec::new(),
655                    })
656                })
657                .collect::<Vec<_>>();
658            let threshold_esurface_ids = threshold_esurfaces
659                .iter()
660                .map(|threshold| threshold.esurface_id)
661                .collect();
662            Ok(IntegrandGraphGroupInfo {
663                group_id: usize::from(group_id),
664                graphs: group
665                    .into_iter()
666                    .map(|graph_id| {
667                        let graph_term = &integrand.data.graph_terms[graph_id];
668                        IntegrandGraphInfo {
669                            graph_id,
670                            name: graph_term.graph.name.clone(),
671                            is_master: graph_id == master_graph_id,
672                            native_residue_counts: integrand
673                                .data
674                                .three_d_representations
675                                .iter()
676                                .filter_map(|representation| {
677                                    amplitude.graphs[graph_id]
678                                        .derived_data
679                                        .representations
680                                        .get(representation)
681                                        .map(|source| {
682                                            (
683                                                *representation,
684                                                source.expression.expression.orientations.len(),
685                                            )
686                                        })
687                                })
688                                .collect(),
689                            threshold_counterterm_directives:
690                                IntegrandThresholdCountertermDirectiveInfo::explicit_for_graph(
691                                    &graph_term.graph,
692                                ),
693                            threshold_counterterms: graph_term
694                                .threshold_counterterm_metadata()
695                                .cloned(),
696                        }
697                    })
698                    .collect(),
699                complete_residue_sum: master_graph.explicit_orientation_sum_only,
700                orientation_edge_ids: if master_graph.explicit_orientation_sum_only {
701                    Vec::new()
702                } else {
703                    master_graph
704                        .orientations
705                        .first()
706                        .map(orientation_edge_ids)
707                        .unwrap_or_default()
708                },
709                orientations: if master_graph.explicit_orientation_sum_only {
710                    // The graph retains its native map catalogue, but the evaluator
711                    // executes the complete sum once through its internal entry 0.
712                    vec![IntegrandOrientationInfo {
713                        orientation_id: 0,
714                        signature: Vec::new(),
715                    }]
716                } else {
717                    master_graph
718                        .orientations
719                        .iter()
720                        .enumerate()
721                        .map(|(orientation_id, orientation)| IntegrandOrientationInfo {
722                            orientation_id,
723                            signature: orientation_signature(orientation),
724                        })
725                        .collect()
726                },
727                loop_momentum_bases: master_graph
728                    .lmbs
729                    .iter_enumerated()
730                    .map(|(basis_id, lmb)| IntegrandLoopMomentumBasisInfo {
731                        basis_id: usize::from(basis_id),
732                        channel_id: channel_ids[usize::from(basis_id)],
733                        edge_ids: lmb.loop_edges.iter().map(|edge_id| edge_id.0).collect(),
734                        matches_generation_basis: lmb.loop_edges.len()
735                            == master_graph.graph.loop_momentum_basis.loop_edges.len()
736                            && lmb.loop_edges.iter().all(|edge_id| {
737                                master_graph
738                                    .graph
739                                    .loop_momentum_basis
740                                    .loop_edges
741                                    .contains(edge_id)
742                            }),
743                    })
744                    .collect(),
745                threshold_esurface_ids,
746                threshold_esurfaces,
747                cuts: Vec::new(),
748            })
749        })
750        .collect()
751}
752
753fn cross_section_graph_groups(
754    integrand: &gammalooprs::integrands::process::cross_section::CrossSectionIntegrand,
755    cross_section: &CrossSection,
756    model: &Model,
757) -> Result<Vec<IntegrandGraphGroupInfo>> {
758    if integrand.data.source_graph_ids.len() != integrand.data.graph_terms.len() {
759        return Err(eyre!(
760            "Cross-section source projection has a different length from its runtime terms"
761        ));
762    }
763    let source_graphs = integrand
764        .data
765        .source_graph_ids
766        .iter()
767        .zip(&integrand.data.graph_terms)
768        .map(|(&source_id, term)| {
769            let source = cross_section.supergraphs.get(source_id).ok_or_else(|| {
770                eyre!(
771                    "Runtime graph '{}' refers to missing stored graph {source_id}",
772                    term.graph.name
773                )
774            })?;
775            if source.graph.name != term.graph.name {
776                return Err(eyre!(
777                    "Runtime graph '{}' refers to stored graph '{}' at index {source_id}",
778                    term.graph.name,
779                    source.graph.name
780                ));
781            }
782            Ok(source)
783        })
784        .collect::<Result<Vec<_>>>()?;
785    let parameterization_settings = integrand
786        .settings
787        .sampling
788        .get_parameterization_settings()
789        .unwrap_or_default();
790    integrand
791        .data
792        .graph_group_structure
793        .iter()
794        .enumerate()
795        .map(|(group_id, group)| {
796            let master_graph_id = group
797                .into_iter()
798                .next()
799                .expect("graph group should not be empty");
800            let master_graph = &integrand.data.graph_terms[master_graph_id];
801            let mut active_model_param_builder: ParamBuilder =
802                master_graph.graph.param_builder.clone();
803            active_model_param_builder.update_model_values(model)?;
804            let channel_ids = sampling_channel_ids(
805                &master_graph.lmbs,
806                &master_graph.multi_channeling_setup,
807                &master_graph.graph.name,
808                &parameterization_settings,
809            )?;
810            let cut_raising_powers = cut_raising_powers(master_graph);
811
812            let cuts = master_graph
813                .cuts
814                .iter_enumerated()
815                .map(|(cut_id, cut)| {
816                    IntegrandCutInfo::from_cross_section_cut(
817                        master_graph,
818                        cut_id,
819                        cut,
820                        cut_raising_powers[cut_id],
821                        model,
822                        &active_model_param_builder,
823                        &integrand.settings,
824                    )
825                })
826                .collect::<Vec<_>>();
827
828            let threshold_esurfaces = master_graph
829                .topological_threshold_esurfaces
830                .iter_enumerated()
831                .map(|(topological_threshold_id, esurface)| {
832                    let esurface_id = topological_threshold_id.0;
833                    let active_cuts = cuts
834                        .iter()
835                        .filter_map(|cut| cut.active_threshold_cut(esurface_id))
836                        .collect();
837
838                    IntegrandThresholdEsurfaceInfo {
839                        esurface_id,
840                        representative_graph_id: master_graph_id,
841                        edge_ids: esurface.energies.iter().map(|edge_id| edge_id.0).collect(),
842                        classification: None,
843                        active_cuts,
844                    }
845                })
846                .collect::<Vec<_>>();
847            let threshold_esurface_ids = threshold_esurfaces
848                .iter()
849                .map(|threshold| threshold.esurface_id)
850                .collect();
851
852            Ok(IntegrandGraphGroupInfo {
853                group_id,
854                graphs: group
855                    .into_iter()
856                    .map(|graph_id| {
857                        let graph_term = &integrand.data.graph_terms[graph_id];
858                        let stored = source_graphs[graph_id];
859                        IntegrandGraphInfo {
860                            graph_id,
861                            name: graph_term.graph.name.clone(),
862                            is_master: graph_id == master_graph_id,
863                            native_residue_counts: integrand
864                                .data
865                                .three_d_representations
866                                .iter()
867                                .filter_map(|representation| {
868                                    stored.derived_data.expressions.get(representation).map(
869                                        |source| {
870                                            (*representation, source.expression.orientations.len())
871                                        },
872                                    )
873                                })
874                                .collect(),
875                            threshold_counterterm_directives:
876                                IntegrandThresholdCountertermDirectiveInfo::explicit_for_graph(
877                                    &graph_term.graph,
878                                ),
879                            threshold_counterterms: graph_term
880                                .threshold_counterterm_metadata()
881                                .cloned(),
882                        }
883                    })
884                    .collect(),
885                complete_residue_sum: master_graph.explicit_orientation_sum_only,
886                orientation_edge_ids: if master_graph.explicit_orientation_sum_only {
887                    Vec::new()
888                } else {
889                    master_graph
890                        .orientations
891                        .first()
892                        .map(orientation_edge_ids)
893                        .unwrap_or_default()
894                },
895                orientations: if master_graph.explicit_orientation_sum_only {
896                    // The graph retains its native map catalogue, but the evaluator
897                    // executes the complete sum once through its internal entry 0.
898                    vec![IntegrandOrientationInfo {
899                        orientation_id: 0,
900                        signature: Vec::new(),
901                    }]
902                } else {
903                    master_graph
904                        .orientations
905                        .iter()
906                        .enumerate()
907                        .map(|(orientation_id, orientation)| IntegrandOrientationInfo {
908                            orientation_id,
909                            signature: orientation_signature(orientation),
910                        })
911                        .collect()
912                },
913                loop_momentum_bases: master_graph
914                    .lmbs
915                    .iter_enumerated()
916                    .map(|(basis_id, lmb)| IntegrandLoopMomentumBasisInfo {
917                        basis_id: usize::from(basis_id),
918                        channel_id: channel_ids[usize::from(basis_id)],
919                        edge_ids: lmb.loop_edges.iter().map(|edge_id| edge_id.0).collect(),
920                        matches_generation_basis: lmb.loop_edges.len()
921                            == master_graph.graph.loop_momentum_basis.loop_edges.len()
922                            && lmb.loop_edges.iter().all(|edge_id| {
923                                master_graph
924                                    .graph
925                                    .loop_momentum_basis
926                                    .loop_edges
927                                    .contains(edge_id)
928                            }),
929                    })
930                    .collect(),
931                threshold_esurface_ids,
932                threshold_esurfaces,
933                cuts,
934            })
935        })
936        .collect()
937}
938
939fn integrand_record_size_from_amplitude(amplitude: &Amplitude) -> Result<usize> {
940    let mut record = amplitude.clone();
941    record.integrand = None;
942    let encoded =
943        bincode::encode_to_vec(&record, bincode::config::standard()).with_context(|| {
944            format!(
945                "While serializing amplitude '{}' for integrand info",
946                amplitude.name
947            )
948        })?;
949    Ok(encoded.len())
950}
951
952fn integrand_record_size_from_cross_section(cross_section: &CrossSection) -> Result<usize> {
953    let mut record = cross_section.clone();
954    record.integrand = None;
955    let encoded =
956        bincode::encode_to_vec(&record, bincode::config::standard()).with_context(|| {
957            format!(
958                "While serializing cross-section '{}' for integrand info",
959                cross_section.name
960            )
961        })?;
962    Ok(encoded.len())
963}