Skip to main content

gammalooprs/graph/
mod.rs

1use feynkit_graph::expressions::evaluate_overall_factor;
2use feynkit_graph::{DiagramEndpoint, DiagramHalfEdge, DiagramSpectatorCut, EdgeId};
3use idenso::tensor::SymbolicTensor;
4use std::{
5    collections::{BTreeMap, BTreeSet},
6    ops::Index,
7    sync::Arc,
8};
9
10use ahash::AHashSet;
11use bincode::Decode as BincodeDecode;
12use bincode::Encode as BincodeEncode;
13use bincode::de::Decoder;
14use bincode::enc::Encoder;
15use bincode::error::{DecodeError, EncodeError};
16use bincode_trait_derive::{Decode, Encode};
17use color_eyre::Result;
18use eyre::ensure;
19use gammaloop_tracing_filter::LogMessage;
20use itertools::Itertools;
21use linnet::{
22    half_edge::{
23        HedgeGraph,
24        involution::{EdgeData, EdgeIndex, Hedge, HedgePair},
25        subgraph::{
26            HedgeNode, ModifySubSet, OrientedCut, SuBitGraph, SubGraphLike, SubSetLike, SubSetOps,
27        },
28    },
29    parser::DotGraph,
30};
31use tracing::debug;
32
33use rand::{Rng, SeedableRng, rngs::SmallRng};
34// use petgraph::Direction::Outgoing;
35use spenso::shadowing::symbolica_utils::LogPrint;
36use spenso::structure::IndexedStructure;
37use symbolica::atom::{Atom, AtomCore};
38use tracing::warn;
39use typed_index_collections::TiVec;
40
41use crate::{
42    GammaLoopContext,
43    cff::surface::SurfaceCache,
44    define_index,
45    integrands::process::{LmbMultiChannelingSetup, ParamBuilder, SamplingChannelId},
46    model::{Model, ModelFingerprint},
47    momentum::{Dep, ExternalMomenta, PolDef, sample::ExternalIndex},
48    numerator::{GetSingleAtom, GlobalPrefactor},
49    processes::DotExportSettings,
50    settings::runtime::kinematic::{Externals, improvement::PhaseSpaceImprovementSettings},
51    utils::{F, Length, ose_atom_from_index},
52    uv::{UltravioletGraph, uv_graph::UVE},
53};
54
55pub(crate) mod attribute_warnings;
56pub mod autogen;
57pub mod cuts;
58pub mod global;
59pub mod threshold_counterterms;
60
61#[derive(Clone, Copy, bincode_trait_derive::Encode, bincode_trait_derive::Decode, Default)]
62pub struct VertexOrder(pub u8);
63
64define_index! {pub struct GroupId;}
65
66/// Canonical physical cut metadata translated mechanically from FeynKit.
67#[derive(Clone, bincode_trait_derive::Encode, bincode_trait_derive::Decode)]
68pub struct FinalizedCut {
69    pub cut: OrientedCut,
70    pub left: SuBitGraph,
71    pub right: SuBitGraph,
72}
73
74/// Topology-only threshold candidate translated from finalized FeynKit metadata.
75///
76/// This is deliberately distinct from [`FinalizedCut`]: it is the complete
77/// s-channel topology inventory and is not a process-selected physical cut.
78#[derive(Clone, bincode_trait_derive::Encode, bincode_trait_derive::Decode)]
79pub struct FinalizedTopologyThresholdCandidate {
80    pub cut: OrientedCut,
81    pub left: SuBitGraph,
82    pub right: SuBitGraph,
83}
84
85#[derive(Clone)]
86pub struct Graph {
87    /// Canonical model records bound to the graph's stable particle IDs. Numerical
88    /// evaluation still uses the current runtime parameter card. Graphs of one
89    /// import or state share this handle; persistence stores only the model's
90    /// structural fingerprint and rebinds to the decode context's model.
91    pub model: Arc<Model>,
92    pub overall_factor: Atom,
93    pub name: String,
94    pub group_id: Option<GroupId>,
95    pub is_group_master: bool,
96    pub tree_edges: SuBitGraph,
97    pub underlying: HedgeGraph<Edge, Vertex, HedgeData>,
98    pub loop_momentum_basis: LoopMomentumBasis,
99    pub param_builder: ParamBuilder,
100    pub global_prefactor: GlobalPrefactor,
101    pub surface_cache: SurfaceCache,
102    /// The cross section initial state cut
103    /// Only relevant for cross sections, but stored here for the parsing
104    pub initial_state_cut: OrientedCut,
105    pub polarizations: Vec<(PolDef, Atom)>,
106    /// Physical cuts selected and filtered by canonical FeynKit generation.
107    pub finalized_cuts: Vec<FinalizedCut>,
108    /// Complete topology-only threshold inventory finalized by FeynKit.
109    pub finalized_topology_threshold_candidates: Vec<FinalizedTopologyThresholdCandidate>,
110    /// Spectator cuts of a selection-only cross-section graph, in FeynKit's edge
111    /// frame. Such a graph has no finalized cuts and supports no integrand.
112    pub finalized_spectator_cuts: Vec<DiagramSpectatorCut>,
113    /// Compact graph-local threshold-counterterm directives from the DOT input.
114    pub threshold_counterterms: autogen::Autogen<threshold_counterterms::ThresholdCountertermSpec>,
115}
116
117// Keep the standalone graph crate independent of the application's bincode codec.
118// Each crossed edge stores its ID and whether the selected half is its target.
119type SpectatorCutPayload = (Vec<(usize, bool)>, Vec<usize>, Vec<usize>);
120
121impl BincodeEncode for Graph {
122    fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
123        let Self {
124            model,
125            overall_factor,
126            name,
127            group_id,
128            is_group_master,
129            tree_edges,
130            underlying,
131            loop_momentum_basis,
132            param_builder,
133            global_prefactor,
134            surface_cache,
135            initial_state_cut,
136            polarizations,
137            finalized_cuts,
138            finalized_topology_threshold_candidates,
139            finalized_spectator_cuts,
140            threshold_counterterms,
141        } = self;
142        // Identity prefix: decoding checks it before any model-dependent field.
143        BincodeEncode::encode(name, encoder)?;
144        BincodeEncode::encode(&model.structure_fingerprint(), encoder)?;
145        BincodeEncode::encode(overall_factor, encoder)?;
146        BincodeEncode::encode(group_id, encoder)?;
147        BincodeEncode::encode(is_group_master, encoder)?;
148        BincodeEncode::encode(tree_edges, encoder)?;
149        BincodeEncode::encode(underlying, encoder)?;
150        BincodeEncode::encode(loop_momentum_basis, encoder)?;
151        BincodeEncode::encode(param_builder, encoder)?;
152        BincodeEncode::encode(global_prefactor, encoder)?;
153        BincodeEncode::encode(surface_cache, encoder)?;
154        BincodeEncode::encode(initial_state_cut, encoder)?;
155        BincodeEncode::encode(polarizations, encoder)?;
156        BincodeEncode::encode(finalized_cuts, encoder)?;
157        BincodeEncode::encode(finalized_topology_threshold_candidates, encoder)?;
158        let spectator_payloads = finalized_spectator_cuts
159            .iter()
160            .map(|record| {
161                let crossed = record
162                    .cut
163                    .iter()
164                    .map(|half| (half.edge.0, half.endpoint == DiagramEndpoint::Target))
165                    .collect::<Vec<_>>();
166                (crossed, &record.left_spectators, &record.right_spectators)
167            })
168            .collect::<Vec<_>>();
169        BincodeEncode::encode(&spectator_payloads, encoder)?;
170        BincodeEncode::encode(threshold_counterterms, encoder)
171    }
172}
173
174impl<C: GammaLoopContext> BincodeDecode<C> for Graph {
175    fn decode<D: Decoder<Context = C>>(decoder: &mut D) -> Result<Self, DecodeError> {
176        let name: String = BincodeDecode::decode(decoder)?;
177        let fingerprint: ModelFingerprint = BincodeDecode::decode(decoder)?;
178        let model = Arc::clone(decoder.context().get_model());
179        if model.structure_fingerprint() != fingerprint {
180            return Err(DecodeError::OtherString(format!(
181                "graph '{name}' was saved for model structure {fingerprint}, but model '{}' has \
182                 structure {}; its particle and vertex identifiers would resolve to different \
183                 records. Load it with the model it was generated with, or regenerate it",
184                model.name(),
185                model.structure_fingerprint(),
186            )));
187        }
188        let graph = Self {
189            model,
190            name,
191            overall_factor: BincodeDecode::decode(decoder)?,
192            group_id: BincodeDecode::decode(decoder)?,
193            is_group_master: BincodeDecode::decode(decoder)?,
194            tree_edges: BincodeDecode::decode(decoder)?,
195            underlying: BincodeDecode::decode(decoder)?,
196            loop_momentum_basis: BincodeDecode::decode(decoder)?,
197            param_builder: BincodeDecode::decode(decoder)?,
198            global_prefactor: BincodeDecode::decode(decoder)?,
199            surface_cache: BincodeDecode::decode(decoder)?,
200            initial_state_cut: BincodeDecode::decode(decoder)?,
201            polarizations: BincodeDecode::decode(decoder)?,
202            finalized_cuts: BincodeDecode::decode(decoder)?,
203            finalized_topology_threshold_candidates: BincodeDecode::decode(decoder)?,
204            finalized_spectator_cuts: {
205                let payloads: Vec<SpectatorCutPayload> = BincodeDecode::decode(decoder)?;
206                payloads
207                    .into_iter()
208                    .map(
209                        |(crossed, left_spectators, right_spectators)| DiagramSpectatorCut {
210                            cut: crossed
211                                .into_iter()
212                                .map(|(edge, is_target)| DiagramHalfEdge {
213                                    edge: EdgeId(edge),
214                                    endpoint: if is_target {
215                                        DiagramEndpoint::Target
216                                    } else {
217                                        DiagramEndpoint::Source
218                                    },
219                                })
220                                .collect(),
221                            left_spectators,
222                            right_spectators,
223                        },
224                    )
225                    .collect()
226            },
227            threshold_counterterms: BincodeDecode::decode(decoder)?,
228        };
229        graph.validate_external_order().map_err(|error| {
230            DecodeError::OtherString(format!("{error}; regenerate the saved state"))
231        })?;
232        Ok(graph)
233    }
234}
235
236impl LogMessage for Graph {
237    fn log_display(&self) -> String {
238        self.name.to_string()
239    }
240}
241
242// impl Deref for Graph {
243//     type Target = HedgeGraph<Edge, Vertex>;
244// }
245
246pub mod feynman_graph;
247pub use feynman_graph::FeynmanGraph;
248pub mod ext;
249
250#[derive(Clone, Copy)]
251pub(crate) enum LmbChannelFallback {
252    CurrentGraphBasis,
253    FirstBasis,
254}
255
256#[derive(Clone, Copy, Debug, PartialEq, Eq)]
257pub(crate) enum ThresholdPinchStatus {
258    Always,
259    CanBecome,
260    NotProven,
261}
262
263impl Graph {
264    /// Check that `model` resolves this graph's typed identifiers to the same
265    /// records as the graph's own model. Parameter values may differ.
266    pub fn ensure_bound_to(&self, model: &Model) -> Result<()> {
267        ensure!(
268            self.model.structure_fingerprint() == model.structure_fingerprint(),
269            "graph '{}' is bound to model '{}', whose particle and vertex records differ \
270             from model '{}'",
271            self.name,
272            self.model.name(),
273            model.name(),
274        );
275        Ok(())
276    }
277
278    /// Point this graph at `model`, which must have the same records. Callers
279    /// validate every graph with [`Self::ensure_bound_to`] first, so that a
280    /// replacement rebinds either all graphs or none.
281    pub fn rebind_model(&mut self, model: &Arc<Model>) {
282        debug_assert_eq!(
283            self.model.structure_fingerprint(),
284            model.structure_fingerprint()
285        );
286        self.model = Arc::clone(model);
287    }
288
289    pub(crate) fn with_global_numerator_only(
290        &self,
291        name: String,
292        numerator: SymbolicTensor<IndexedStructure>,
293    ) -> Self {
294        let mut graph = self.clone();
295        graph.name = name;
296        graph.overall_factor = Atom::one();
297        graph.global_prefactor.num = numerator;
298        graph.polarizations.clear();
299        let unit = crate::numerator::AppliedFeynmanRule::new(Atom::one())
300            .expect("literal one is a scalar tensor")
301            .expr;
302        graph.global_prefactor.projector = unit.clone();
303        graph.underlying = self.underlying.map_data_ref(
304            |_, _, vertex| {
305                let mut vertex = vertex.clone();
306                vertex.num = autogen::Autogen::explicit(unit.clone());
307                vertex
308            },
309            |_, _, _, edge| {
310                edge.map(|edge| {
311                    let mut edge = edge.clone();
312                    edge.num = autogen::Autogen::explicit(unit.clone());
313                    edge
314                })
315            },
316            |_, hedge_data| hedge_data.clone(),
317        );
318        graph
319    }
320
321    pub fn debug_dot(&self) -> String {
322        DotGraph::from(self).debug_dot()
323    }
324
325    pub fn debug_dot_with_settings(&self, settings: &DotExportSettings) -> eyre::Result<String> {
326        Ok(self.to_dot_graph_with_settings(settings)?.debug_dot())
327    }
328
329    pub fn pretty_dot(&self) -> String {
330        self.dot_impl(
331            &self.full_filter(),
332            "",
333            &|_a| None,
334            &|e| {
335                Some(format!(
336                    "label=\"{}\"",
337                    parse::NumeratorInterface::export(&e.num.value)
338                        .0
339                        .log_print(None)
340                ))
341            },
342            &|v| {
343                Some(format!(
344                    "label=\"{}\"",
345                    parse::NumeratorInterface::export(&v.num.value)
346                        .0
347                        .log_print(None)
348                ))
349            },
350        )
351    }
352
353    pub(crate) fn global_numerator(&self) -> color_eyre::Result<SymbolicTensor<IndexedStructure>> {
354        let factor =
355            SymbolicTensor::infer_indexed(evaluate_overall_factor(self.overall_factor.as_view()))?;
356        eyre::ensure!(
357            factor.is_scalar(),
358            "the overall graph factor must be scalar"
359        );
360        Ok(self
361            .global_prefactor
362            .num
363            .clone()
364            .multiply(self.global_prefactor.projector.clone())?
365            .multiply(factor)?)
366    }
367
368    pub(crate) fn production_numerator_atom_for_full_3d_expression(&self) -> Atom {
369        let reduced = self.full_filter().subtract(&self.initial_state_cut);
370        let numerator = self
371            .numerator(&reduced, &self.empty_subgraph())
372            .expect("validated graph numerator must have a compatible tensor interface")
373            .state
374            .expr
375            .multiply(
376                self.global_numerator()
377                    .expect("validated global numerator must be a tensor"),
378            )
379            .expect("the complete production numerator must have compatible ports");
380        crate::numerator::AppliedFeynmanRule::from_tensor(numerator)
381            .get_single_atom()
382            .expect("Graph numerator should be available")
383    }
384
385    pub(crate) fn external_momentum_edge_order(&self) -> Vec<EdgeIndex> {
386        if self.initial_state_cut.nedges(&self.underlying) == 0 {
387            let external_filter: SuBitGraph = self.external_filter();
388            external_filter
389                .included_iter()
390                .sorted()
391                .map(|hedge| self.underlying[&hedge])
392                .collect_vec()
393        } else {
394            self.initial_state_cut
395                .iter_left_hedges()
396                .sorted()
397                .map(|hedge| self.underlying[&hedge])
398                .collect_vec()
399        }
400    }
401
402    pub(crate) fn canonicalize_lmb_external_order(&self, lmb: &mut LoopMomentumBasis) {
403        lmb.canonicalize_external_order(&self.external_momentum_edge_order());
404    }
405
406    /// Check that the graph's basis indexes externals in runtime order.
407    ///
408    /// Sample momenta, helicities and external states are indexed in
409    /// [`Self::external_momentum_edge_order`], and consumers address them
410    /// through positions in `loop_momentum_basis.ext_edges`. A basis in any
411    /// other order silently pairs a leg with another leg's momentum.
412    pub(crate) fn validate_external_order(&self) -> Result<()> {
413        let runtime_order = self.external_momentum_edge_order();
414        ensure!(
415            self.loop_momentum_basis
416                .ext_edges
417                .raw
418                .starts_with(&runtime_order),
419            "graph '{}' has loop-momentum basis externals {:?}, but runtime externals are \
420             ordered {:?}",
421            self.name,
422            self.loop_momentum_basis.ext_edges.raw,
423            runtime_order
424        );
425        Ok(())
426    }
427
428    pub(crate) fn dummy_stripped_external_flows_of<S: SubGraphLike>(&self, subgraph: &S) -> S::Base
429    where
430        S::Base: ModifySubSet<HedgePair> + ModifySubSet<Hedge>,
431    {
432        let mut externals = self.underlying.full_crown(subgraph);
433        for (pair, _, edge) in self.underlying.iter_edges() {
434            if edge.data.is_dummy {
435                externals.sub(pair);
436            }
437        }
438        externals
439    }
440
441    pub(crate) fn random_externals(&self, model: &Model, seed: u64) -> Externals {
442        let mut rng = SmallRng::seed_from_u64(seed);
443        let mom_range = -10.0..10.0;
444
445        let mut momenta = vec![ExternalMomenta::Dependent(Dep::Dep)];
446        let mut helicities = vec![];
447        let ext: SuBitGraph = self.external_filter();
448
449        for (_, _, d) in self.iter_edges_of(&ext) {
450            let hel = d.data.random_helicity(model, seed);
451            helicities.push(hel);
452            if helicities.len() == 2 {
453                continue;
454            }
455            let mom = ExternalMomenta::Independent([
456                F(rng.random_range(mom_range.clone())),
457                F(rng.random_range(mom_range.clone())),
458                F(rng.random_range(mom_range.clone())),
459                F(rng.random_range(mom_range.clone())),
460            ]);
461
462            momenta.push(mom);
463        }
464        Externals::Constant {
465            momenta,
466            helicities,
467            improvement_settings: PhaseSpaceImprovementSettings::default(),
468            f_64_cache: None,
469            f_128_cache: None,
470            arb_cache: Default::default(),
471        }
472    }
473
474    // pub(crate) fn new(
475    //     name: SmartString<LazyCompact>,
476    //     multiplicity: Atom,
477    //     underlying: HedgeGraph<Edge, Vertex, NumHedgeData>,
478    // ) -> Result<Self> {
479    //     Ok(Self {
480    //         name: name.to_string(),
481    //         overall_factor: multiplicity,
482    //         loop_momentum_basis: underlying.lmb(&underlying.full_filter()),
483    //         group_id: None,
484    //         is_group_master: false,
485    //         underlying,
486    //         global_prefactor: GlobalPrefactor::default(),
487    //         polarizations: vec![],
488    //     })
489    // }
490
491    pub(crate) fn build_multi_channeling_channels(
492        &self,
493        lmbs: &TiVec<LmbIndex, LoopMomentumBasis>,
494        override_lmb_heuristics: bool,
495    ) -> LmbMultiChannelingSetup {
496        let channels = self.select_amplitude_lmb_channel_indices(
497            lmbs,
498            override_lmb_heuristics,
499            LmbChannelFallback::CurrentGraphBasis,
500        );
501
502        debug!(
503            "number of lmbs: {}, number of channels: {}",
504            lmbs.len(),
505            channels.len()
506        );
507
508        LmbMultiChannelingSetup {
509            master_edge_masses: Default::default(),
510            sampling_bridge: Default::default(),
511            sampling_bridge_quad: Default::default(),
512            sampling_bridge_fixed256: Default::default(),
513            sampling_bridge_arb: Default::default(),
514            sampling_source: Default::default(),
515            sampling_catalogue: Default::default(),
516            sampling_programs: Default::default(),
517            lmb_basis_ids: channels,
518            graph: self.clone(),
519            all_bases: lmbs.clone(),
520        }
521    }
522
523    pub(crate) fn select_amplitude_lmb_channel_indices(
524        &self,
525        lmbs: &TiVec<LmbIndex, LoopMomentumBasis>,
526        override_lmb_heuristics: bool,
527        fallback: LmbChannelFallback,
528    ) -> TiVec<SamplingChannelId, LmbIndex> {
529        if override_lmb_heuristics {
530            return lmbs
531                .iter_enumerated()
532                .map(|(lmb_index, _)| lmb_index)
533                .collect();
534        }
535
536        let Some((_, first_lmb)) = lmbs.iter_enumerated().next() else {
537            return TiVec::new();
538        };
539        let num_loops = first_lmb.loop_edges.len();
540        if num_loops == 0 {
541            return self.fallback_lmb_channel_indices(lmbs, fallback);
542        }
543
544        let mut universe = BTreeMap::<Vec<EdgeIndex>, usize>::new();
545        let mut candidate_covers = Vec::<(LmbIndex, BTreeSet<usize>)>::new();
546        for (lmb_index, lmb) in lmbs.iter_enumerated() {
547            let mut cover = BTreeSet::<usize>::new();
548            let massless_loop_edges = lmb
549                .loop_edges
550                .iter()
551                .copied()
552                .filter(|edge_id| matches!(self.underlying[*edge_id].mass, edge::EdgeMass::Zero))
553                .collect_vec();
554
555            for mut combination in massless_loop_edges.into_iter().combinations(num_loops) {
556                combination.sort();
557                let next_universe_id = universe.len();
558                let universe_id = *universe.entry(combination).or_insert(next_universe_id);
559                cover.insert(universe_id);
560            }
561
562            if !cover.is_empty() {
563                candidate_covers.push((lmb_index, cover));
564            }
565        }
566
567        if universe.is_empty() {
568            return self.fallback_lmb_channel_indices(lmbs, fallback);
569        }
570
571        let channels = Self::minimum_lmb_set_cover(universe.len(), &candidate_covers);
572        if channels.is_empty() {
573            self.fallback_lmb_channel_indices(lmbs, fallback)
574        } else {
575            channels.into_iter().sorted().collect()
576        }
577    }
578
579    fn fallback_lmb_channel_indices(
580        &self,
581        lmbs: &TiVec<LmbIndex, LoopMomentumBasis>,
582        fallback: LmbChannelFallback,
583    ) -> TiVec<SamplingChannelId, LmbIndex> {
584        let fallback_index = match fallback {
585            LmbChannelFallback::CurrentGraphBasis => lmbs
586                .iter_enumerated()
587                .find(|(_, lmb)| lmb.loop_edges == self.loop_momentum_basis.loop_edges)
588                .map(|(lmb_index, _)| lmb_index)
589                .or_else(|| {
590                    warn!(
591                        "lmb not in the list of all lmb, falling back to the first generated basis"
592                    );
593                    lmbs.iter_enumerated()
594                        .next()
595                        .map(|(lmb_index, _)| lmb_index)
596                }),
597            LmbChannelFallback::FirstBasis => lmbs
598                .iter_enumerated()
599                .next()
600                .map(|(lmb_index, _)| lmb_index),
601        };
602
603        fallback_index.into_iter().collect()
604    }
605
606    fn minimum_lmb_set_cover(
607        universe_len: usize,
608        candidate_covers: &[(LmbIndex, BTreeSet<usize>)],
609    ) -> Vec<LmbIndex> {
610        let mut candidates_by_element = vec![Vec::<usize>::new(); universe_len];
611        for (candidate_pos, (_, cover)) in candidate_covers.iter().enumerate() {
612            for element in cover {
613                candidates_by_element[*element].push(candidate_pos);
614            }
615        }
616
617        let remaining = (0..universe_len).collect::<BTreeSet<_>>();
618        let mut chosen = Vec::<usize>::new();
619        let mut best = None;
620        Self::search_minimum_lmb_set_cover(
621            remaining,
622            &mut chosen,
623            &mut best,
624            candidate_covers,
625            &candidates_by_element,
626        );
627        best.unwrap_or_default()
628    }
629
630    fn search_minimum_lmb_set_cover(
631        remaining: BTreeSet<usize>,
632        chosen: &mut Vec<usize>,
633        best: &mut Option<Vec<LmbIndex>>,
634        candidate_covers: &[(LmbIndex, BTreeSet<usize>)],
635        candidates_by_element: &[Vec<usize>],
636    ) {
637        if remaining.is_empty() {
638            let mut candidate = chosen
639                .iter()
640                .map(|candidate_pos| candidate_covers[*candidate_pos].0)
641                .collect_vec();
642            candidate.sort();
643            let better = best.as_ref().is_none_or(|current_best| {
644                candidate.len() < current_best.len()
645                    || (candidate.len() == current_best.len() && candidate < *current_best)
646            });
647            if better {
648                *best = Some(candidate);
649            }
650            return;
651        }
652
653        if let Some(current_best) = best.as_ref()
654            && chosen.len() >= current_best.len()
655        {
656            return;
657        }
658
659        let Some(element) = remaining
660            .iter()
661            .copied()
662            .min_by_key(|element| candidates_by_element[*element].len())
663        else {
664            return;
665        };
666        if candidates_by_element[element].is_empty() {
667            return;
668        }
669
670        for candidate_pos in &candidates_by_element[element] {
671            if chosen.contains(candidate_pos) {
672                continue;
673            }
674            let cover = &candidate_covers[*candidate_pos].1;
675            if cover.is_disjoint(&remaining) {
676                continue;
677            }
678
679            let mut next_remaining = remaining.clone();
680            for covered_element in cover {
681                next_remaining.remove(covered_element);
682            }
683            chosen.push(*candidate_pos);
684            Self::search_minimum_lmb_set_cover(
685                next_remaining,
686                chosen,
687                best,
688                candidate_covers,
689                candidates_by_element,
690            );
691            chosen.pop();
692        }
693    }
694
695    pub(crate) fn get_edge_subgraph(&self, edge: EdgeIndex) -> SuBitGraph {
696        let mut subgraph: SuBitGraph = self.underlying.empty_subgraph();
697
698        match self[&edge].1 {
699            HedgePair::Paired { source, sink } => {
700                subgraph.add(source);
701                subgraph.add(sink);
702            }
703            HedgePair::Unpaired { hedge, .. } => {
704                subgraph.add(hedge);
705            }
706            HedgePair::Split { .. } => unreachable!(),
707        }
708
709        subgraph
710    }
711
712    pub(crate) fn iter_loop_edges(
713        &self,
714    ) -> impl Iterator<Item = (HedgePair, EdgeIndex, EdgeData<&Edge>)> {
715        self.underlying.iter_edges().filter(|(_, edge_index, _)| {
716            self.loop_momentum_basis.edge_signatures[*edge_index]
717                .internal
718                .iter()
719                .any(|sign| sign.is_sign())
720        })
721    }
722
723    pub(crate) fn iter_non_loop_edges(
724        &self,
725    ) -> impl Iterator<Item = (HedgePair, EdgeIndex, EdgeData<&Edge>)> {
726        self.underlying.iter_edges().filter(|(_, edge_index, _)| {
727            self.loop_momentum_basis.edge_signatures[*edge_index]
728                .internal
729                .iter()
730                .all(|sign| sign.is_zero())
731        })
732    }
733
734    pub(crate) fn get_source_and_target(&self) -> (HedgeNode, HedgeNode) {
735        let mut source_nodes = AHashSet::new();
736        let mut target_nodes = AHashSet::new();
737
738        for (hedge_pair, _, _) in self.underlying.iter_edges_of(&self.initial_state_cut) {
739            match hedge_pair {
740                HedgePair::Split { source, sink, .. } => {
741                    let source_node = self.underlying.node_id(sink);
742                    let sink_node = self.underlying.node_id(source);
743
744                    source_nodes.insert(source_node);
745                    target_nodes.insert(sink_node);
746                }
747                _ => {
748                    unreachable!();
749                }
750            }
751        }
752
753        // They don't need to be the same!
754        // assert_eq!(
755        //     source_nodes.len(),
756        //     target_nodes.len(),
757        //     "The number of source and target nodes should be the same{}",
758        //     self.debug_dot()
759        // );
760
761        let source_node_vec = source_nodes.into_iter().collect_vec();
762        let target_node_vec = target_nodes.into_iter().collect_vec();
763
764        //println!("source nodes: {:?}", source_node_vec);
765        //println!("target nodes: {:?}", target_node_vec);
766        //panic!("stop");
767
768        let source_node = self
769            .underlying
770            .combine_to_single_hedgenode(&source_node_vec);
771
772        let target_node = self
773            .underlying
774            .combine_to_single_hedgenode(&target_node_vec);
775
776        (source_node, target_node)
777    }
778
779    #[cfg(test)]
780    pub(crate) fn edge_name_to_index(&self, name: &str) -> Option<EdgeIndex> {
781        for (_, edge_index, edge_data) in self.underlying.iter_edges() {
782            if edge_data.data.name.value == name {
783                return Some(edge_index);
784            }
785        }
786
787        None
788    }
789
790    pub(crate) fn get_raised_edge_groups(&self) -> Vec<Vec<EdgeIndex>> {
791        let mut result = Vec::<Vec<EdgeIndex>>::new();
792
793        for (_, edge_index, _) in self.iter_loop_edges() {
794            let group_position = result.iter().position(|group| {
795                group.iter().all(|e| {
796                    self.loop_momentum_basis.edges_are_raised(*e, edge_index)
797                        && self[edge_index].particle.mass_atom(&self.model)
798                            == self[*e].particle.mass_atom(&self.model)
799                })
800            });
801
802            if let Some(pos) = group_position {
803                result[pos].push(edge_index);
804            } else {
805                result.push(vec![edge_index]);
806            }
807        }
808
809        result.iter_mut().for_each(|group| group.sort());
810
811        result
812    }
813
814    pub fn get_edges_in_initial_state_cut(&self) -> Vec<EdgeIndex> {
815        self.initial_state_cut
816            .iter_left_hedges()
817            .map(|hedge| self.underlying[&hedge])
818            .collect_vec()
819    }
820    pub(crate) fn classify_threshold_pinch(
821        &self,
822        model: &Model,
823        cut_boundary_edges: &[EdgeIndex],
824        threshold_boundary_edges: &[EdgeIndex],
825    ) -> ThresholdPinchStatus {
826        // The caller has already intersected both cut boundaries with the connected sandwich.
827        // These edge sets therefore carry the same graph-relative information that the former
828        // `is_always_pinch` implementation derived from the two cuts and sandwich internally.
829        // Keep every mass representation symbolic here. A non-zero difference is not a
830        // model-independent conclusion; resolved values handle that case during generation.
831        let boundary_mass_sum = |edges: &[EdgeIndex]| {
832            edges
833                .iter()
834                .map(|edge_id| self[*edge_id].mass_atom(model))
835                .fold(Atom::new(), |sum, mass| sum + mass)
836        };
837
838        let mass_sums_are_identical = (boundary_mass_sum(cut_boundary_edges)
839            - boundary_mass_sum(threshold_boundary_edges))
840        .expand()
841        .is_zero();
842
843        if !mass_sums_are_identical {
844            return ThresholdPinchStatus::NotProven;
845        }
846
847        if cut_boundary_edges.len() > 1 && threshold_boundary_edges.len() > 1 {
848            ThresholdPinchStatus::CanBecome
849        } else {
850            ThresholdPinchStatus::Always
851        }
852    }
853}
854
855pub mod edge;
856pub mod parse;
857pub use autogen::Autogen;
858pub use edge::Edge;
859pub mod hedge_data;
860pub use hedge_data::HedgeData;
861pub(crate) mod three_d_source;
862pub(crate) use three_d_source::{ExactUvSubLmbFrame, FourDDenominator, GraphThreeDSource};
863pub mod vertex;
864pub use vertex::Vertex;
865
866pub mod lmb;
867pub use lmb::{LMBext, LmbError, LmbIndex, LoopMomentumBasis};
868
869#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
870pub struct GraphGroup {
871    master: usize,
872    remaining: Vec<usize>,
873}
874
875impl GraphGroup {
876    pub(crate) fn master(&self) -> usize {
877        self.master
878    }
879
880    pub(crate) fn iter_enumerated(&self) -> impl Iterator<Item = (GraphGroupPosition, usize)> + '_ {
881        self.into_iter()
882            .enumerate()
883            .map(|(i, graph_id)| (GraphGroupPosition(i), graph_id))
884    }
885
886    pub(crate) fn find_position(&self, graph_id: usize) -> Option<GraphGroupPosition> {
887        self.into_iter()
888            .position(|id| id == graph_id)
889            .map(GraphGroupPosition)
890    }
891
892    /// Renumber the graphs `new_id` retains; `None` when the master is not retained.
893    pub(crate) fn project(&self, new_id: impl Fn(usize) -> Option<usize>) -> Option<Self> {
894        Some(Self {
895            master: new_id(self.master)?,
896            remaining: self.remaining.iter().filter_map(|&id| new_id(id)).collect(),
897        })
898    }
899}
900
901impl<'a> IntoIterator for &'a GraphGroup {
902    type Item = usize;
903    type IntoIter = std::iter::Chain<
904        std::array::IntoIter<usize, 1>,
905        std::iter::Copied<std::slice::Iter<'a, usize>>,
906    >;
907
908    fn into_iter(self) -> Self::IntoIter {
909        [self.master]
910            .into_iter()
911            .chain(self.remaining.iter().copied())
912    }
913}
914
915impl Length for GraphGroup {
916    fn len(&self) -> usize {
917        1 + self.remaining.len()
918    }
919}
920
921impl Index<GraphGroupPosition> for GraphGroup {
922    type Output = usize;
923
924    fn index(&self, index: GraphGroupPosition) -> &Self::Output {
925        if index.0 == 0 {
926            &self.master
927        } else {
928            &self.remaining[index.0 - 1]
929        }
930    }
931}
932
933define_index! {pub struct GraphGroupPosition;}
934
935#[derive(
936    Debug, Copy, Clone, PartialEq, Eq, bincode_trait_derive::Encode, bincode_trait_derive::Decode,
937)]
938#[trait_decode(trait = symbolica::state::HasStateMap)]
939pub struct ExternalConnection {
940    pub incoming_index: ExternalIndex,
941    pub outgoing_index: ExternalIndex,
942}
943
944pub fn get_cff_inverse_energy_product_impl<E, V, H, S: SubSetLike>(
945    graph: &HedgeGraph<E, V, H>,
946    subgraph: &S,
947    contract_edges: &[EdgeIndex],
948) -> Atom {
949    feynkit_cff::CffExpression::inverse_energy_product(graph.iter_edges_of(subgraph).filter_map(
950        |(pair, edge, _)| {
951            (matches!(pair, HedgePair::Paired { .. }) && !contract_edges.contains(&edge))
952                .then(|| ose_atom_from_index(edge))
953        },
954    ))
955}
956
957#[cfg(test)]
958mod tests {
959    use super::*;
960    use crate::{
961        GammaLoopContextContainer, finalized_runtime_dot, initialisation::test_initialise,
962        momentum::signature::LoopExtSignature,
963    };
964    use std::io::Cursor;
965    use std::sync::OnceLock;
966    use symbolica::state::State;
967
968    fn test_lmb(graph: &Graph, loop_edges: &[usize]) -> LoopMomentumBasis {
969        LoopMomentumBasis {
970            tree: graph.underlying.empty_subgraph(),
971            loop_edges: loop_edges.iter().copied().map(EdgeIndex::from).collect(),
972            ext_edges: Vec::new().into(),
973            edge_signatures: graph.underlying.new_edgevec(|_, _, _| {
974                LoopExtSignature::from((Vec::<isize>::new(), Vec::<isize>::new()))
975            }),
976        }
977    }
978
979    fn selector_test_graph() -> Graph {
980        static GRAPH: OnceLock<Graph> = OnceLock::new();
981        GRAPH
982            .get_or_init(|| {
983                test_initialise().unwrap();
984                finalized_runtime_dot!(
985                    digraph lmb_selector {
986                        graph [projector=1]
987                        edge [num=1 mass=0]
988                        node [num=1]
989                        A -> B [id=0 lmb_id=0 source="{ufo_order:0}" sink="{ufo_order:0}"]
990                        A -> B [id=1 lmb_id=1 source="{ufo_order:1}" sink="{ufo_order:1}"]
991                        A -> B [id=2 lmb_id=2 source="{ufo_order:2}" sink="{ufo_order:2}"]
992                        A -> B [id=3 lmb_id=3 source="{ufo_order:3}" sink="{ufo_order:3}"]
993                        A -> B [id=4 mass=1 source="{ufo_order:4}" sink="{ufo_order:4}"]
994                    }
995                )
996                .unwrap()
997            })
998            .clone()
999    }
1000
1001    #[test]
1002    fn exact_lmb_set_cover_prefers_smallest_deterministic_solution() {
1003        let candidates = [
1004            (LmbIndex::from(0), BTreeSet::from([0])),
1005            (LmbIndex::from(1), BTreeSet::from([1])),
1006            (LmbIndex::from(2), BTreeSet::from([0, 1])),
1007            (LmbIndex::from(3), BTreeSet::from([0, 1])),
1008        ];
1009
1010        assert_eq!(
1011            Graph::minimum_lmb_set_cover(2, &candidates),
1012            vec![LmbIndex::from(2)]
1013        );
1014    }
1015
1016    #[test]
1017    fn amplitude_lmb_selector_covers_massless_combinations_and_skips_duplicates() {
1018        let mut graph = selector_test_graph();
1019        graph.loop_momentum_basis = test_lmb(&graph, &[0, 1]);
1020        let lmbs: TiVec<LmbIndex, LoopMomentumBasis> = vec![
1021            test_lmb(&graph, &[0, 1]),
1022            test_lmb(&graph, &[2, 3]),
1023            test_lmb(&graph, &[0, 2]),
1024            test_lmb(&graph, &[0, 1]),
1025            test_lmb(&graph, &[0, 4]),
1026        ]
1027        .into();
1028
1029        let selected = graph.select_amplitude_lmb_channel_indices(
1030            &lmbs,
1031            false,
1032            LmbChannelFallback::CurrentGraphBasis,
1033        );
1034
1035        assert_eq!(
1036            selected.into_iter().collect_vec(),
1037            vec![LmbIndex::from(0), LmbIndex::from(1), LmbIndex::from(2)]
1038        );
1039    }
1040
1041    #[test]
1042    fn amplitude_lmb_selector_override_keeps_all_bases() {
1043        let graph = selector_test_graph();
1044        let lmbs: TiVec<LmbIndex, LoopMomentumBasis> = vec![
1045            test_lmb(&graph, &[0, 1]),
1046            test_lmb(&graph, &[2, 3]),
1047            test_lmb(&graph, &[0, 4]),
1048        ]
1049        .into();
1050
1051        let selected = graph.select_amplitude_lmb_channel_indices(
1052            &lmbs,
1053            true,
1054            LmbChannelFallback::CurrentGraphBasis,
1055        );
1056
1057        assert_eq!(
1058            selected.into_iter().collect_vec(),
1059            vec![LmbIndex::from(0), LmbIndex::from(1), LmbIndex::from(2)]
1060        );
1061    }
1062
1063    #[test]
1064    fn amplitude_lmb_selector_falls_back_when_no_massless_combination_exists() {
1065        let mut graph = selector_test_graph();
1066        graph.loop_momentum_basis = test_lmb(&graph, &[0, 4]);
1067        let lmbs: TiVec<LmbIndex, LoopMomentumBasis> =
1068            vec![test_lmb(&graph, &[1, 4]), test_lmb(&graph, &[0, 4])].into();
1069
1070        let selected_current = graph.select_amplitude_lmb_channel_indices(
1071            &lmbs,
1072            false,
1073            LmbChannelFallback::CurrentGraphBasis,
1074        );
1075        let selected_first = graph.select_amplitude_lmb_channel_indices(
1076            &lmbs,
1077            false,
1078            LmbChannelFallback::FirstBasis,
1079        );
1080
1081        assert_eq!(
1082            selected_current.into_iter().collect_vec(),
1083            vec![LmbIndex::from(1)]
1084        );
1085        assert_eq!(
1086            selected_first.into_iter().collect_vec(),
1087            vec![LmbIndex::from(0)]
1088        );
1089    }
1090
1091    #[test]
1092    fn threshold_pinch_classification_distinguishes_fixed_and_multiparticle_boundaries() {
1093        let graph = selector_test_graph();
1094        let model = crate::utils::load_generic_model("sm");
1095
1096        assert_eq!(
1097            graph.classify_threshold_pinch(&model, &[EdgeIndex::from(0)], &[EdgeIndex::from(1)],),
1098            ThresholdPinchStatus::Always,
1099        );
1100        assert_eq!(
1101            graph.classify_threshold_pinch(
1102                &model,
1103                &[EdgeIndex::from(0), EdgeIndex::from(1)],
1104                &[EdgeIndex::from(2), EdgeIndex::from(3)],
1105            ),
1106            ThresholdPinchStatus::CanBecome,
1107        );
1108        assert_eq!(
1109            graph.classify_threshold_pinch(&model, &[EdgeIndex::from(0)], &[EdgeIndex::from(4)],),
1110            ThresholdPinchStatus::NotProven,
1111        );
1112    }
1113
1114    fn count_occurrences(haystack: &[u8], needle: &[u8]) -> usize {
1115        haystack
1116            .windows(needle.len())
1117            .filter(|window| *window == needle)
1118            .count()
1119    }
1120
1121    #[test]
1122    fn graphs_of_one_import_share_one_model_and_persist_only_its_identity() {
1123        test_initialise().unwrap();
1124        let model = crate::utils::load_generic_model("sm");
1125        let graphs = Graph::import_dot(
1126            stringify!(
1127                digraph tree_a {
1128                    num="spenso::g(spenso::dind(spenso::cof(3, hedge(1))), spenso::cof(3, hedge(2)))/3"
1129                    ext [style=invis]
1130                    ext -> v1:1 [particle="d" id=1];
1131                    ext -> v3:2 [particle="d~" id=2];
1132                    v1:3 -> ext [particle="a" id=3];
1133                    v2:4 -> ext [particle="a" id=4];
1134                    v3:0 -> ext [particle="a" id=0];
1135                    v1 -> v2 [particle="d" id=5];
1136                    v2 -> v3 [particle="d" id=6];
1137                }
1138                digraph tree_b {
1139                    num="spenso::g(spenso::dind(spenso::cof(3, hedge(1))), spenso::cof(3, hedge(2)))/3"
1140                    ext [style=invis]
1141                    ext -> v1:1 [particle="d" id=1];
1142                    ext -> v3:2 [particle="d~" id=2];
1143                    v1:3 -> ext [particle="a" id=3];
1144                    v2:4 -> ext [particle="a" id=4];
1145                    v3:0 -> ext [particle="a" id=0];
1146                    v1 -> v2 [particle="d" id=5];
1147                    v2 -> v3 [particle="d" id=6];
1148                }
1149            ),
1150            &model,
1151        )
1152        .unwrap();
1153        assert_eq!(graphs.len(), 2);
1154
1155        let json = model.to_json().unwrap();
1156        let encoded = bincode::encode_to_vec(&graphs, bincode::config::standard()).unwrap();
1157        let model_copies = count_occurrences(&encoded, json.as_bytes());
1158        assert!(
1159            Arc::ptr_eq(&graphs[0].model, &graphs[1].model),
1160            "graphs of one import must share one model"
1161        );
1162        assert_eq!(model_copies, 0, "graphs must not persist the model itself");
1163
1164        let mut symbolica_state = Vec::new();
1165        State::export(&mut symbolica_state).unwrap();
1166        let state_map = State::import(&mut Cursor::new(symbolica_state), None).unwrap();
1167        let session_model = Arc::new(model.clone());
1168        let (decoded, consumed): (Vec<Graph>, _) = bincode::decode_from_slice_with_context(
1169            &encoded,
1170            bincode::config::standard(),
1171            GammaLoopContextContainer {
1172                state_map: &state_map,
1173                model: &session_model,
1174            },
1175        )
1176        .unwrap();
1177        assert_eq!(consumed, encoded.len());
1178        assert!(
1179            decoded
1180                .iter()
1181                .all(|graph| Arc::ptr_eq(&graph.model, &session_model)),
1182            "decoded graphs must bind to the state's model"
1183        );
1184
1185        let other_model = Arc::new(crate::utils::load_generic_model("scalars"));
1186        let decoded: Result<(Vec<Graph>, usize), _> = bincode::decode_from_slice_with_context(
1187            &encoded,
1188            bincode::config::standard(),
1189            GammaLoopContextContainer {
1190                state_map: &state_map,
1191                model: &other_model,
1192            },
1193        );
1194        let error = decoded
1195            .err()
1196            .expect("graphs must not bind to a structurally different model")
1197            .to_string();
1198        assert!(error.contains("tree_a"), "{error}");
1199
1200        // The identity prefix is checked before any model-dependent field, so
1201        // a wrong model is reported even when the remaining bytes are invalid.
1202        let mut truncated = bincode::encode_to_vec(
1203            (&graphs[0].name, graphs[0].model.structure_fingerprint()),
1204            bincode::config::standard(),
1205        )
1206        .unwrap();
1207        assert!(encoded[..].windows(truncated.len()).any(|w| w == truncated));
1208        truncated.extend([0xff; 64]);
1209        let decoded: Result<(Graph, usize), _> = bincode::decode_from_slice_with_context(
1210            &truncated,
1211            bincode::config::standard(),
1212            GammaLoopContextContainer {
1213                state_map: &state_map,
1214                model: &other_model,
1215            },
1216        );
1217        let error = decoded
1218            .err()
1219            .expect("a wrong model must be rejected from the prefix")
1220            .to_string();
1221        assert!(error.contains("graph 'tree_a'"), "{error}");
1222        assert!(error.contains("saved for model structure"), "{error}");
1223        assert!(
1224            error.contains(&other_model.structure_fingerprint().to_string()),
1225            "{error}"
1226        );
1227    }
1228}