Skip to main content

feynkit_generator/
generation.rs

1use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
2use std::fmt;
3use std::hash::{Hash, Hasher};
4use std::sync::{Arc, LazyLock, Mutex, RwLock};
5
6use feynkit_graph::CanonicalDiagramKey;
7use feynkit_graph::expressions::evaluate_overall_factor;
8use feynkit_graph::symbols;
9use feynkit_graph::{
10    DiagramCut, DiagramCutSide, DiagramEdge, DiagramEndpoint, DiagramError, DiagramHalfEdge,
11    DiagramId, DiagramSpectatorCut, DiagramThresholdCandidate, DiagramVertex, EdgeId,
12    ExternalState, FeynmanDiagram, ForwardGraph, LegSeededCut, NumeratorInterface, VertexSlot,
13};
14use feynkit_model::{Model, ModelError, Particle, ParticleId, VertexRule, VertexRuleId};
15use idenso::color::CS;
16use idenso::dirac::AGS;
17use idenso::epsilon::EPSILON_SYMBOL;
18use idenso::representations::Bispinor;
19use idenso::tensor::SymbolicTensor;
20use idenso::tensor::composition;
21use idenso::tensor::inference::InterfaceInference;
22use idenso::{CookMode, CookSettings};
23use linnet::half_edge::involution::Flow;
24use linnet::half_edge::subgraph::{InternalSubGraph, SuBitGraph, SubSetLike};
25use linnet::half_edge::{HedgeGraph, NodeIndex};
26use linnet::permutation::Permutation;
27use rayon::ThreadPoolBuildError;
28#[cfg(not(target_arch = "wasm32"))]
29use rayon::ThreadPoolBuilder;
30#[cfg(not(target_arch = "wasm32"))]
31use rayon::iter::{
32    IndexedParallelIterator, IntoParallelIterator, IntoParallelRefIterator, ParallelIterator,
33};
34use serde::{Deserialize, Serialize};
35use spenso::network::library::symbolic::ETS;
36use spenso::structure::abstract_index::{AIND_SYMBOLS, AbstractIndex};
37use spenso::structure::partial::{PartialIndex, PartialStructure, PartialStructureExt};
38use spenso::structure::representation::{LibraryRep, Minkowski, RepName};
39use spenso::structure::slot::{IsAbstractSlot, ParseableAind, SlotMatch, SlotMatcher};
40use symbolica::atom::{Atom, AtomCore, AtomView, FunctionBuilder, Symbol, UserData};
41use symbolica::graph::{GenerationSettings, Graph, HalfEdge};
42use symbolica::symbol;
43use thiserror::Error;
44
45use feynkit_amplitude::{AmplitudeError, ColorRepresentation, ColorSum};
46
47use crate::{
48    FilterScope, GenerationFilter, GenerationFilterKind, GenerationOptions, GenerationType,
49    GroupingError, NumeratorGrouping, ParticleSelector, Process, ProcessError, SelectorError,
50    SelfEnergyFilterOptions, SewnFilterOptions, SnailFilterOptions, TadpoleFilterOptions,
51    VertexSelector, grouping, momentum_symbol,
52};
53
54#[cfg(test)]
55#[path = "main_generation_regressions.rs"]
56mod main_generation_regressions;
57
58#[derive(Debug, Error)]
59pub enum GenerationError {
60    #[error(transparent)]
61    Process(#[from] ProcessError),
62    #[error(transparent)]
63    Amplitude(#[from] Box<feynkit_amplitude::AmplitudeError>),
64    #[error("generation was cancelled; cannot construct a complete amplitude")]
65    IncompleteAmplitude,
66    #[error(transparent)]
67    Model(#[from] ModelError),
68    #[error(transparent)]
69    Selector(#[from] SelectorError),
70    #[error(transparent)]
71    Diagram(#[from] DiagramError),
72    #[error("failed to build generation thread pool: {0}")]
73    ThreadPool(#[from] ThreadPoolBuildError),
74    #[error("graph automorphism factor cannot be represented by u64: {0}")]
75    SymmetryFactor(String),
76    #[error("could not assign an interaction to node {node} with signature {signature:?}")]
77    MissingInteraction { node: usize, signature: Vec<String> },
78    #[error("option {option} for filter {filter} in the {scope} scope is not implemented")]
79    UnsupportedFilterOption {
80        scope: FilterScope,
81        filter: GenerationFilterKind,
82        option: &'static str,
83    },
84    #[error("filter {filter} is not valid in the {scope} scope for {generation_type:?} generation")]
85    InvalidFilterScope {
86        scope: FilterScope,
87        filter: GenerationFilterKind,
88        generation_type: GenerationType,
89    },
90    #[error("duplicate filter {filter} in the {scope} scope")]
91    DuplicateFilter {
92        scope: FilterScope,
93        filter: GenerationFilterKind,
94    },
95    #[error(
96        "filter {filter} in the {scope} scope has an invalid range: {minimum} is greater than {maximum}"
97    )]
98    InvalidFilterRange {
99        scope: FilterScope,
100        filter: GenerationFilterKind,
101        minimum: usize,
102        maximum: usize,
103    },
104    #[error(
105        "a vacuum cross section (no initial states) has no Cutkosky cut, so its final state must be empty"
106    )]
107    VacuumCrossSectionFinalState,
108    #[error(
109        "a vacuum cross section (no initial states) has no Cutkosky cut, so cut-amplitude filters cannot apply"
110    )]
111    VacuumCutAmplitudeFilters,
112    #[error(
113        "every cross-section final-state alternative is empty; without non-zero perturbative orders admitting massless unresolved particles, no s-channel cut can match it"
114    )]
115    EmptyCrossSectionFinalStates,
116    #[error("generation thread count must be greater than zero, received {0}")]
117    InvalidThreadCount(usize),
118    #[error(
119        "left/right symmetrization of an amplitude permutes legs across both states, so it requires initial- and final-state symmetrization (initial: {initial}, final: {final_state})"
120    )]
121    OneSidedLeftRightAmplitudeSymmetrization { initial: bool, final_state: bool },
122    #[error("numerator grouping requires canonical comparison or at least one numerical sample")]
123    InvalidNumericalSampleCount,
124    #[error(
125        "scalar-rescaling numerator grouping requires at least two numerical samples: with one, any two nonzero sampled numerators look proportional"
126    )]
127    SingleSampleScalarRescaling,
128    #[error("arithmetic overflow while computing {0}")]
129    ArithmeticOverflow(&'static str),
130    #[error("forced cut edge set {edges:?} does not match any generated physical cut")]
131    UnknownForcedCut { edges: Vec<usize> },
132    #[error(transparent)]
133    Grouping(#[from] GroupingError),
134    #[error("invalid generation grouping provenance: {0}")]
135    InvalidGroups(String),
136    #[error(
137        "a loop-momentum basis was requested for {member}, which numerator grouping merged into master {master}; request a basis for {master} in its own edge numbering, or disable numerator grouping"
138    )]
139    LoopMomentumBasisOfGroupedMember { member: String, master: String },
140    #[error(
141        "no generated diagram matches the loop-momentum basis target {target}; check the generated diagram names or IDs"
142    )]
143    UnknownLoopMomentumBasisTarget { target: String },
144    #[error(
145        "fermion flow branches at vertex {vertex} with degree {degree}; branching fermion chains are not supported"
146    )]
147    UnsupportedFermionBranching { vertex: usize, degree: usize },
148    #[error("spanning-tree edge between nodes {node} and {parent} is missing")]
149    MissingSpanningTreeEdge { node: usize, parent: usize },
150    #[error("external node {node} has no incident edge")]
151    MissingExternalEdge { node: usize },
152    #[error("external leg {index} has no resolved particle")]
153    MissingExternalParticle { index: usize },
154    #[error("projector refers to unknown process external leg {index}")]
155    UnknownProjectorExternalIndex { index: usize },
156    #[error("external fermion flow must have exactly two legs, found {legs:?}")]
157    InvalidExternalFermionLegCount { legs: Vec<usize> },
158    #[error(
159        "external fermion flow between legs {legs:?} must connect a fermion and an antifermion, found particles {particles:?}"
160    )]
161    InvalidExternalFermionPair {
162        legs: [usize; 2],
163        particles: [i64; 2],
164    },
165    #[error("sewn external fermion leg {leg} has degree {degree}, expected two")]
166    InvalidExternalFermionLoopDegree { leg: usize, degree: usize },
167    #[error("failed to reconstruct the normalized fermion-flow graph: {0}")]
168    GraphConstruction(String),
169    #[error("failed to parse the {owner} numerator '{expression}': {message}")]
170    NumeratorParse {
171        owner: String,
172        expression: String,
173        message: String,
174    },
175    #[error("the {owner} numerator references UFO leg {leg}, but it has {legs} legs")]
176    InvalidNumeratorLeg {
177        owner: String,
178        leg: i64,
179        legs: usize,
180    },
181    #[error("the {owner} numerator contains an invalid UFO index '{index}'")]
182    InvalidNumeratorIndex { owner: String, index: String },
183    #[error("the {owner} numerator has an invalid UFO tensor {tensor}: {message}")]
184    InvalidNumeratorTensor {
185        owner: String,
186        tensor: String,
187        message: String,
188    },
189    #[error("the {owner} numerator uses unsupported UFO tensor {tensor}")]
190    UnsupportedNumeratorTensor { owner: String, tensor: String },
191    #[error("the {owner} numerator references momentum but has no incident edge")]
192    MissingNumeratorMomentum { owner: String },
193    #[error(
194        "could not assign particle '{particle}' at UFO leg {leg} of interaction '{interaction}' on vertex {vertex}"
195    )]
196    MissingInteractionLeg {
197        vertex: usize,
198        interaction: String,
199        leg: usize,
200        particle: String,
201    },
202    #[error(
203        "could not identify a unique CP-conjugate rule for interaction '{interaction}' on vertex {vertex}; compatible rules: {candidates:?}"
204    )]
205    InvalidCpInteractionRule {
206        vertex: usize,
207        interaction: String,
208        candidates: Vec<String>,
209    },
210}
211
212#[derive(Debug, Clone)]
213pub struct GroupMember {
214    /// Stable generated-order index assigned before zero-numerator removal.
215    pub source_diagram: usize,
216    /// Stable content-derived ID of the source diagram.
217    pub source_id: DiagramId,
218    /// Finalized display name of the source diagram.
219    pub source_name: String,
220    /// Index into [`GenerationResult::diagrams`] after zero-numerator removal.
221    pub diagram: usize,
222    /// The numerator of this member divided by the numerator of the master.
223    pub ratio: Atom,
224    /// Numerator-independent factor contributed by this source diagram.
225    pub overall_factor: Atom,
226}
227
228#[derive(Debug, Clone)]
229pub struct DiagramGroup {
230    /// Post-zero-removal index of the numerator reference diagram.
231    pub master: usize,
232    /// Deterministically ordered members, including the master with ratio one.
233    pub members: Vec<GroupMember>,
234}
235
236#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
237pub struct GenerationReport {
238    pub topology_count: usize,
239    pub interaction_assignment_count: usize,
240    /// Number of diagrams retained after exact zero-numerator removal.
241    pub retained_count: usize,
242    pub zero_numerator_count: usize,
243    pub completed: bool,
244}
245
246#[derive(Debug, Clone)]
247pub struct GenerationResult {
248    /// Final retained master diagrams in deterministic order.
249    pub diagrams: Vec<FeynmanDiagram>,
250    pub groups: Vec<DiagramGroup>,
251    pub report: GenerationReport,
252}
253
254impl GenerationResult {
255    /// Convert complete unsewn diagrams into a coherent symbolic amplitude.
256    pub fn into_amplitude(
257        self,
258        options: feynkit_amplitude::AmplitudeOptions,
259    ) -> Result<feynkit_amplitude::Amplitude, GenerationError> {
260        if !self.report.completed {
261            return Err(GenerationError::IncompleteAmplitude);
262        }
263        Ok(
264            feynkit_amplitude::Amplitude::new(self.diagrams.into_iter().map(Arc::new), options)
265                .map_err(Box::new)?,
266        )
267    }
268
269    /// Validate collapsed group provenance against the finalized master list.
270    pub fn validate_groups(&self) -> Result<(), GenerationError> {
271        if self.groups.len() != self.diagrams.len() {
272            return Err(GenerationError::InvalidGroups(format!(
273                "{} groups do not cover {} collapsed diagrams",
274                self.groups.len(),
275                self.diagrams.len()
276            )));
277        }
278        let mut masters = BTreeSet::new();
279        for (group_index, group) in self.groups.iter().enumerate() {
280            if group.master >= self.diagrams.len() || !masters.insert(group.master) {
281                return Err(GenerationError::InvalidGroups(format!(
282                    "group {group_index} has invalid or duplicate master {}",
283                    group.master
284                )));
285            }
286            if group.members.is_empty()
287                || group
288                    .members
289                    .iter()
290                    .any(|member| member.diagram != group.master)
291            {
292                return Err(GenerationError::InvalidGroups(format!(
293                    "group {group_index} has no members or a member assigned to another master"
294                )));
295            }
296            self.diagrams[group.master].validate()?;
297        }
298        if masters != (0..self.diagrams.len()).collect::<BTreeSet<_>>() {
299            return Err(GenerationError::InvalidGroups(
300                "collapsed diagram masters are not covered exactly once".to_owned(),
301            ));
302        }
303        Ok(())
304    }
305}
306
307/// Extra massless particles allowed by perturbative unresolved-cut selection.
308#[derive(Debug, Clone, PartialEq, Eq)]
309pub struct UnresolvedCutContent {
310    pub particles: BTreeSet<ParticleId>,
311    pub maximum_multiplicity: usize,
312}
313
314/// Resolve the canonical unresolved-cut policy stored in generation options.
315pub fn unresolved_cut_content(
316    model: &Model,
317    options: &GenerationOptions,
318) -> Result<Option<UnresolvedCutContent>, GenerationError> {
319    let Some(required) = options
320        .graph_filters
321        .iter()
322        .find_map(|filter| match filter {
323            GenerationFilter::PerturbativeOrders(required) => Some(required),
324            _ => None,
325        })
326    else {
327        return Ok(None);
328    };
329    let mut particles = BTreeSet::new();
330    for rule in model.vertex_rules() {
331        let orders = rule.coupling_orders(model);
332        if !required.keys().any(|name| orders.contains_key(name)) {
333            continue;
334        }
335        for particle in &rule.particles {
336            if model.particle_is_massless(*particle) {
337                particles.insert(*particle);
338            }
339        }
340    }
341    let maximum_multiplicity = required.values().try_fold(0_usize, |sum, order| {
342        sum.checked_add(*order)
343            .ok_or(GenerationError::ArithmeticOverflow(
344                "the unresolved cut multiplicity",
345            ))
346    })?;
347    Ok(Some(UnresolvedCutContent {
348        particles,
349        maximum_multiplicity,
350    }))
351}
352
353#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
354struct NumeratorHalfEdge {
355    edge: usize,
356    // Native half-edge IDs need not equal 2 * edge + endpoint after sewing.
357    hedge: usize,
358    flow: Flow,
359    spin: i64,
360    color: i64,
361}
362
363#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
364enum NumeratorOwner {
365    Vertex(usize),
366    Edge(usize),
367}
368
369#[derive(Debug, Clone, Copy, PartialEq, Eq)]
370enum NumeratorSector {
371    Spin,
372    Color,
373}
374
375impl fmt::Display for NumeratorOwner {
376    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
377        match self {
378            Self::Vertex(vertex) => write!(formatter, "vertex {vertex}"),
379            Self::Edge(edge) => write!(formatter, "edge {edge}"),
380        }
381    }
382}
383
384struct NumeratorInstantiation<'a> {
385    owner: NumeratorOwner,
386    legs: &'a [NumeratorHalfEdge],
387}
388
389impl NumeratorInstantiation<'_> {
390    fn propagator_expression(
391        &self,
392        propagator: &Atom,
393        color: i64,
394    ) -> Result<Atom, GenerationError> {
395        let spin = self.instantiate(propagator, NumeratorSector::Spin)?;
396        Ok(match self.edge_color_identity(color)? {
397            None => spin,
398            Some(color) => spin * color,
399        })
400    }
401
402    /// Bind canonical template labels simultaneously. Momentum IDs may alias;
403    /// half-edge and dummy-owner labels retain their distinct identities.
404    fn bind_template(&self, expression: &Atom) -> Result<Atom, GenerationError> {
405        let mut error = None;
406        let expression = expression.replace_map_bottom_up(|term, _, out| {
407            let AtomView::Fun(function) = term else {
408                return;
409            };
410            let head = function.get_symbol();
411            let mut arguments = function.iter();
412            let owner = if head == symbols::hedge_index() || head == symbols::momentum() {
413                let leg = usize::try_from(
414                    arguments
415                        .next()
416                        .expect("localized template momentum and half-edge heads carry a leg ID"),
417                )
418                .expect("localized template leg IDs are nonnegative integers");
419                if head == symbols::momentum() {
420                    self.legs[leg].edge
421                } else {
422                    self.legs[leg].hedge
423                }
424            } else if head == symbols::vertex_index() || head == symbols::edge_index() {
425                arguments.next();
426                match self.owner {
427                    NumeratorOwner::Vertex(owner) | NumeratorOwner::Edge(owner) => owner,
428                }
429            } else {
430                return;
431            };
432            match i64::try_from(owner) {
433                Ok(owner) => {
434                    **out = FunctionBuilder::new(head)
435                        .add_arg(owner)
436                        .add_args(arguments)
437                        .finish();
438                }
439                Err(_) => {
440                    error = Some(GenerationError::ArithmeticOverflow(
441                        "a symbolic numerator owner",
442                    ));
443                }
444            }
445        });
446        error.map_or(Ok(expression), Err)
447    }
448
449    // UFO `idx(shift, leg)` and `dummy(index)` values are local to one
450    // propagator or interaction. Localize them before exposing the annotation
451    // so equal endpoint indices contract and unrelated dummy indices cannot.
452    fn instantiate(
453        &self,
454        expression: &Atom,
455        sector: NumeratorSector,
456    ) -> Result<Atom, GenerationError> {
457        let mut atom = expression.clone();
458        let mut error = None;
459        atom = atom.replace_map(|term, _, out| {
460            if error.is_some() {
461                return;
462            }
463            match self.localize_momentum(term) {
464                Ok(Some(replacement)) => {
465                    **out = replacement;
466                }
467                Ok(None) => {}
468                Err(localization_error) => error = Some(localization_error),
469            }
470        });
471        if let Some(error) = error {
472            return Err(error);
473        }
474        atom = atom.replace_map(|term, _, out| {
475            if error.is_some() {
476                return;
477            }
478            match self.localize_indices(term) {
479                Ok(Some(replacement)) => {
480                    **out = replacement;
481                }
482                Ok(None) => {}
483                Err(localization_error) => error = Some(localization_error),
484            }
485        });
486        if let Some(error) = error {
487            return Err(error);
488        }
489
490        atom = match sector {
491            NumeratorSector::Spin => self.lower_spin(atom)?,
492            NumeratorSector::Color => self.lower_color(atom)?,
493        };
494
495        Ok(atom)
496    }
497
498    fn localize_momentum(&self, term: AtomView<'_>) -> Result<Option<Atom>, GenerationError> {
499        match term {
500            AtomView::Fun(function) if Self::is_model_symbol(function.get_symbol(), "P") => {
501                let arguments = function.iter().collect::<Vec<_>>();
502                let momentum = match arguments.as_slice() {
503                    [] | [_] => {
504                        let (leg, reversed) = self.implicit_momentum_leg()?;
505                        let index = arguments
506                            .first()
507                            .map(|index| self.localize_index_argument(*index))
508                            .transpose()?;
509                        let momentum = self.momentum(leg, index)?;
510                        if reversed { -momentum } else { momentum }
511                    }
512                    [index, momentum_leg] => {
513                        let leg = self.leg(self.local_leg_number(*momentum_leg)?)?;
514                        let momentum =
515                            self.momentum(leg, Some(self.localize_index_argument(*index)?))?;
516                        // The UFO all-incoming convention reverses momentum on
517                        // the source half-edge of an interaction.
518                        if leg.flow == Flow::Source {
519                            -momentum
520                        } else {
521                            momentum
522                        }
523                    }
524                    _ => return Err(self.invalid_index(term)),
525                };
526                Ok(Some(momentum))
527            }
528            AtomView::Fun(function)
529                if Self::is_model_symbol(function.get_symbol(), "PSlash") =>
530            {
531                let arguments = function.iter().collect::<Vec<_>>();
532                if !(2..=3).contains(&arguments.len()) {
533                    return Err(self.invalid_index(term));
534                }
535                // An explicit leg follows the same all-incoming rule as P(mu, N).
536                let (leg, reversed) = if let Some(momentum_leg) = arguments.get(2) {
537                    let leg = self.leg(self.local_leg_number(*momentum_leg)?)?;
538                    (leg, leg.flow == Flow::Source)
539                } else {
540                    self.implicit_momentum_leg()?
541                };
542                let mut localized = FunctionBuilder::new(function.get_symbol());
543                for index in &arguments[..2] {
544                    localized = localized.add_arg(self.localize_index_argument(*index)?);
545                }
546                // Spin lowering expects a bare momentum slot, so the sign stays outside.
547                let slash = localized.add_arg(self.momentum(leg, None)?).finish();
548                Ok(Some(if reversed { -slash } else { slash }))
549            }
550            AtomView::Fun(function)
551                if Self::is_model_symbol(function.get_symbol(), "Slash")
552                    && function.get_nargs() == 1
553                    && function.iter().next().is_some_and(|argument| {
554                        matches!(argument, AtomView::Var(variable) if Self::is_model_symbol(variable.get_symbol(), "P"))
555                    }) =>
556            {
557                let (leg, reversed) = self.implicit_momentum_leg()?;
558                let slash = FunctionBuilder::new(function.get_symbol())
559                    .add_arg(self.momentum(leg, None)?)
560                    .finish();
561                Ok(Some(if reversed { -slash } else { slash }))
562            }
563            _ => Ok(None),
564        }
565    }
566
567    fn localize_indices(&self, term: AtomView<'_>) -> Result<Option<Atom>, GenerationError> {
568        let AtomView::Fun(function) = term else {
569            return Ok(None);
570        };
571        if Self::is_model_symbol(function.get_symbol(), "idx") {
572            return self.localize_index_function(term).map(Some);
573        }
574        if Self::is_model_symbol(function.get_symbol(), "dummy") {
575            return self.localize_dummy_function(term).map(Some);
576        }
577        let symbol = function.get_symbol();
578        let name = symbol.get_stripped_name();
579        if !Self::is_model_symbol(symbol, name)
580            || !matches!(
581                name,
582                "Identity"
583                    | "IdentityL"
584                    | "Gamma"
585                    | "Gamma5"
586                    | "ProjM"
587                    | "ProjP"
588                    | "Sigma"
589                    | "C"
590                    | "Metric"
591                    | "Epsilon"
592                    | "T"
593                    | "f"
594                    | "d"
595                    | "EpsilonBar"
596                    | "T6"
597                    | "K6"
598                    | "K6Bar"
599            )
600        {
601            return Ok(None);
602        }
603
604        let mut localized = FunctionBuilder::new(function.get_symbol());
605        for argument in function.iter() {
606            localized = localized.add_arg(self.localize_index_argument(argument)?);
607        }
608        Ok(Some(localized.finish()))
609    }
610
611    fn lower_spin(&self, mut atom: Atom) -> Result<Atom, GenerationError> {
612        // Force the canonical Idenso/Spenso registrations before constructing
613        // any of their heads. Symbolica attributes cannot be added after a
614        // bare symbol with the same name has already been interned.
615        let _ = (
616            AGS.gamma,
617            AGS.gamma5,
618            AGS.charge_conjugation,
619            AGS.projm,
620            AGS.projp,
621            AGS.sigma,
622            ETS.metric,
623            *EPSILON_SYMBOL,
624        );
625
626        let mut next_dummy = self.maximum_local_dummy(&atom)?;
627        let mut error = None;
628        atom = atom.replace_map(|term, _, out| {
629            if error.is_some() {
630                return;
631            }
632            let AtomView::Fun(function) = term else {
633                return;
634            };
635            let symbol = function.get_symbol();
636            let name = symbol.get_stripped_name();
637            if !Self::is_model_symbol(symbol, name) {
638                return;
639            }
640            let arguments = function
641                .iter()
642                .map(|argument| argument.to_owned())
643                .collect::<Vec<_>>();
644            let lowered = match name {
645                "Identity" => self.exact_arguments(term, &arguments, 2).map(|args| {
646                    ETS.metric(
647                        self.bispinor(args[0].clone()),
648                        self.bispinor(args[1].clone()),
649                    )
650                }),
651                "IdentityL" | "Metric" => self.exact_arguments(term, &arguments, 2).map(|args| {
652                    ETS.metric(
653                        self.minkowski(args[0].clone()),
654                        self.minkowski(args[1].clone()),
655                    )
656                }),
657                "Gamma" => self.exact_arguments(term, &arguments, 3).map(|args| {
658                    FunctionBuilder::new(AGS.gamma)
659                        .add_arg(self.bispinor(args[1].clone()))
660                        .add_arg(self.bispinor(args[2].clone()))
661                        .add_arg(self.minkowski(args[0].clone()))
662                        .finish()
663                }),
664                "Gamma5" => self.exact_arguments(term, &arguments, 2).map(|args| {
665                    FunctionBuilder::new(AGS.gamma5)
666                        .add_arg(self.bispinor(args[0].clone()))
667                        .add_arg(self.bispinor(args[1].clone()))
668                        .finish()
669                }),
670                "ProjM" => self.exact_arguments(term, &arguments, 2).map(|args| {
671                    FunctionBuilder::new(AGS.projm)
672                        .add_arg(self.bispinor(args[0].clone()))
673                        .add_arg(self.bispinor(args[1].clone()))
674                        .finish()
675                }),
676                "ProjP" => self.exact_arguments(term, &arguments, 2).map(|args| {
677                    FunctionBuilder::new(AGS.projp)
678                        .add_arg(self.bispinor(args[0].clone()))
679                        .add_arg(self.bispinor(args[1].clone()))
680                        .finish()
681                }),
682                "Sigma" => self.exact_arguments(term, &arguments, 4).map(|args| {
683                    FunctionBuilder::new(AGS.sigma)
684                        .add_arg(self.bispinor(args[2].clone()))
685                        .add_arg(self.bispinor(args[3].clone()))
686                        .add_arg(self.minkowski(args[0].clone()))
687                        .add_arg(self.minkowski(args[1].clone()))
688                        .finish()
689                }),
690                "PSlash" => {
691                    self.exact_arguments(term, &arguments, 3).and_then(|args| {
692                        next_dummy = next_dummy.checked_add(1).ok_or(
693                            GenerationError::ArithmeticOverflow("a symbolic slash dummy index"),
694                        )?;
695                        let index = self.minkowski(self.dummy(next_dummy)?);
696                        let momentum = self.index_momentum(args[2].as_view(), index.clone())?;
697                        Ok(FunctionBuilder::new(AGS.gamma)
698                            .add_arg(self.bispinor(args[0].clone()))
699                            .add_arg(self.bispinor(args[1].clone()))
700                            .add_arg(index)
701                            .finish()
702                            * momentum)
703                    })
704                }
705                // UFO's real Levi-Civita tensor has ε^{0123} = −1 (ALOHA,
706                // matching FeynRules), so Tr[γ5 γ^μ γ^ν γ^ρ γ^σ] = 4i ε^{μνρσ}
707                // for the same γ5 = diag(−1,−1,1,1). Idenso's epsilon is
708                // normalized by Tr[…] = 4 ε^{μνρσ}, i.e. ε^{0123} = −i.
709                "Epsilon" => self.exact_arguments(term, &arguments, 4).map(|args| {
710                    let epsilon = args
711                        .iter()
712                        .fold(
713                            FunctionBuilder::new(*EPSILON_SYMBOL),
714                            |builder, argument| builder.add_arg(self.minkowski(argument.clone())),
715                        )
716                        .finish();
717                    -Atom::i() * epsilon
718                }),
719                "C" => self.exact_arguments(term, &arguments, 2).map(|args| {
720                    FunctionBuilder::new(AGS.charge_conjugation)
721                        .add_arg(self.bispinor(args[0].clone()))
722                        .add_arg(self.bispinor(args[1].clone()))
723                        .finish()
724                }),
725                "T" | "f" | "d" | "EpsilonBar" | "T6" | "K6" | "K6Bar" => {
726                    Err(self.invalid_tensor(term, "a color tensor appeared in a Lorentz structure"))
727                }
728                _ => return,
729            };
730            match lowered {
731                Ok(replacement) => **out = replacement,
732                Err(lowering_error) => error = Some(lowering_error),
733            }
734        });
735        if let Some(error) = error {
736            return Err(error);
737        }
738
739        // P(mu, leg) has already become gammalooprs::Q(edge, mu).
740        // Attach the Minkowski representation after all UFO indices have been
741        // localized. PSlash momenta already carry the freshly allocated slot.
742        atom = atom.replace_map(|term, _, out| {
743            let AtomView::Fun(function) = term else {
744                return;
745            };
746            if function.get_symbol() != momentum_symbol() || function.get_nargs() != 2 {
747                return;
748            }
749            let mut arguments = function.iter();
750            let edge = arguments.next().expect("the arity was checked");
751            let index = arguments.next().expect("the arity was checked");
752            if Self::is_representation(index, "mink") {
753                return;
754            }
755            **out = FunctionBuilder::new(momentum_symbol())
756                .add_arg(edge)
757                .add_arg(self.minkowski(index.to_owned()))
758                .finish();
759        });
760        self.reject_residual_tensors(&atom)?;
761        Ok(atom)
762    }
763
764    fn lower_color(&self, mut atom: Atom) -> Result<Atom, GenerationError> {
765        let _ = (CS.t, CS.f, ETS.metric, *EPSILON_SYMBOL);
766        atom = atom.expand();
767        if let AtomView::Add(terms) = atom.as_view() {
768            return terms.iter().try_fold(Atom::Zero, |sum, term| {
769                Ok(sum + self.lower_color(term.to_owned())?)
770            });
771        }
772        let dummy_symbol = match self.owner {
773            NumeratorOwner::Vertex(_) => symbols::vertex_index(),
774            NumeratorOwner::Edge(_) => symbols::edge_index(),
775        };
776        // Contract identities touching a local dummy before assigning oriented
777        // slots. Each step removes one identity, including chains of identities;
778        // the remaining tensors or external legs determine its representation.
779        loop {
780            let factors = match atom.as_view() {
781                AtomView::Mul(product) => product.iter().collect::<Vec<_>>(),
782                factor => vec![factor],
783            };
784            let mut contraction = None;
785            for term in factors {
786                let AtomView::Fun(function) = term else {
787                    continue;
788                };
789                if !Self::is_model_symbol(function.get_symbol(), "Identity")
790                    || function.get_nargs() != 2
791                {
792                    continue;
793                }
794                let args = function.iter().collect::<Vec<_>>();
795                if args[0] == args[1] {
796                    continue;
797                }
798                for (left, right) in [(args[0], args[1]), (args[1], args[0])] {
799                    if !matches!(left, AtomView::Fun(index) if index.get_symbol() == dummy_symbol) {
800                        continue;
801                    }
802                    let mut occurrences = 0;
803                    let mut powered = false;
804                    atom.visitor(&mut |index| {
805                        if let AtomView::Pow(_) = index {
806                            index.visitor(&mut |nested| {
807                                powered |= nested == left;
808                                true
809                            });
810                            return false;
811                        }
812                        occurrences += usize::from(index == left);
813                        true
814                    });
815                    if occurrences == 2 && !powered {
816                        contraction = Some((term.to_owned(), left.to_owned(), right.to_owned()));
817                        break;
818                    }
819                }
820                if contraction.is_some() {
821                    break;
822                }
823            }
824            let Some((identity, dummy, other)) = contraction else {
825                break;
826            };
827            atom = (atom / identity).replace(dummy.to_pattern()).with(other);
828        }
829        let mut representations = HashMap::<String, ColorRepresentation>::new();
830        for leg in self.legs {
831            if let Some(representation) = ColorRepresentation::from_ufo(leg.color) {
832                let index = self.index(*leg, 1)?;
833                self.assign_color_representation(
834                    &mut representations,
835                    index.as_view(),
836                    representation,
837                )?;
838            }
839        }
840
841        let mut identities = Vec::<(Atom, Atom)>::new();
842        let mut error = None;
843        atom = atom.replace_map(|term, _, _| {
844            if error.is_some() {
845                return;
846            }
847            let AtomView::Fun(function) = term else {
848                return;
849            };
850            let symbol = function.get_symbol();
851            let name = symbol.get_stripped_name();
852            if !Self::is_model_symbol(symbol, name) {
853                return;
854            }
855            let arguments = function
856                .iter()
857                .map(|argument| argument.to_owned())
858                .collect::<Vec<_>>();
859            let result = match name {
860                "Identity" => self.exact_arguments(term, &arguments, 2).map(|args| {
861                    identities.push((args[0].clone(), args[1].clone()));
862                }),
863                "T" => self.exact_arguments(term, &arguments, 3).and_then(|args| {
864                    self.assign_color_representation(
865                        &mut representations,
866                        args[0].as_view(),
867                        ColorRepresentation::Adjoint,
868                    )?;
869                    self.assign_color_representation(
870                        &mut representations,
871                        args[1].as_view(),
872                        ColorRepresentation::Fundamental,
873                    )?;
874                    self.assign_color_representation(
875                        &mut representations,
876                        args[2].as_view(),
877                        ColorRepresentation::AntiFundamental,
878                    )
879                }),
880                "f" | "d" => self.exact_arguments(term, &arguments, 3).and_then(|args| {
881                    for argument in args {
882                        self.assign_color_representation(
883                            &mut representations,
884                            argument.as_view(),
885                            ColorRepresentation::Adjoint,
886                        )?;
887                    }
888                    Ok(())
889                }),
890                "Epsilon" | "EpsilonBar" => {
891                    self.exact_arguments(term, &arguments, 3).and_then(|args| {
892                        let representation = if name == "Epsilon" {
893                            ColorRepresentation::Fundamental
894                        } else {
895                            ColorRepresentation::AntiFundamental
896                        };
897                        for argument in args {
898                            self.assign_color_representation(
899                                &mut representations,
900                                argument.as_view(),
901                                representation,
902                            )?;
903                        }
904                        Ok(())
905                    })
906                }
907                "T6" | "K6" | "K6Bar" => Err(self.unsupported_tensor(term)),
908                "IdentityL" | "Gamma" | "Gamma5" | "ProjM" | "ProjP" | "Sigma" | "C" | "Metric"
909                | "PSlash" => {
910                    Err(self.invalid_tensor(term, "a Lorentz tensor appeared in a color structure"))
911                }
912                _ => return,
913            };
914            if let Err(lowering_error) = result {
915                error = Some(lowering_error);
916            }
917        });
918        if let Some(error) = error {
919            return Err(error);
920        }
921
922        loop {
923            let mut changed = false;
924            for (left, right) in &identities {
925                let left_representation = representations
926                    .get(&Self::index_key(left.as_view()))
927                    .copied();
928                let right_representation = representations
929                    .get(&Self::index_key(right.as_view()))
930                    .copied();
931                match (left_representation, right_representation) {
932                    (Some(left_rep), Some(right_rep)) if left_rep.dual() != right_rep => {
933                        return Err(self.invalid_tensor(
934                            FunctionBuilder::new(symbol!("UFO::Identity"))
935                                .add_arg(left)
936                                .add_arg(right)
937                                .finish()
938                                .as_view(),
939                            "the two color identity indices do not carry dual representations",
940                        ));
941                    }
942                    (Some(_), Some(_)) => {}
943                    (Some(left), None) => {
944                        self.assign_color_representation(
945                            &mut representations,
946                            right.as_view(),
947                            left.dual(),
948                        )?;
949                        changed = true;
950                    }
951                    (None, Some(right)) => {
952                        self.assign_color_representation(
953                            &mut representations,
954                            left.as_view(),
955                            right.dual(),
956                        )?;
957                        changed = true;
958                    }
959                    (None, None) => {}
960                }
961            }
962            if !changed {
963                break;
964            }
965        }
966        for (left, right) in &identities {
967            if !representations.contains_key(&Self::index_key(left.as_view()))
968                || !representations.contains_key(&Self::index_key(right.as_view()))
969            {
970                return Err(self.invalid_tensor(
971                    FunctionBuilder::new(symbol!("UFO::Identity"))
972                        .add_arg(left)
973                        .add_arg(right)
974                        .finish()
975                        .as_view(),
976                    "its color representation cannot be inferred",
977                ));
978            }
979        }
980
981        error = None;
982        atom = atom.replace_map(|term, _, out| {
983            if error.is_some() {
984                return;
985            }
986            let AtomView::Fun(function) = term else {
987                return;
988            };
989            let symbol = function.get_symbol();
990            let name = symbol.get_stripped_name();
991            if !Self::is_model_symbol(symbol, name) {
992                return;
993            }
994            let arguments = function
995                .iter()
996                .map(|argument| argument.to_owned())
997                .collect::<Vec<_>>();
998            let lowered = match name {
999                "Identity" => self.exact_arguments(term, &arguments, 2).map(|args| {
1000                    let left = representations[&Self::index_key(args[0].as_view())];
1001                    let right = representations[&Self::index_key(args[1].as_view())];
1002                    ETS.metric(
1003                        left.representation().to_symbolic([args[0].clone()]),
1004                        right.representation().to_symbolic([args[1].clone()]),
1005                    )
1006                }),
1007                "T" => self.exact_arguments(term, &arguments, 3).map(|args| {
1008                    FunctionBuilder::new(CS.t)
1009                        .add_arg(
1010                            ColorRepresentation::Adjoint
1011                                .representation()
1012                                .to_symbolic([args[0].clone()]),
1013                        )
1014                        .add_arg(
1015                            ColorRepresentation::Fundamental
1016                                .representation()
1017                                .to_symbolic([args[1].clone()]),
1018                        )
1019                        .add_arg(
1020                            ColorRepresentation::AntiFundamental
1021                                .representation()
1022                                .to_symbolic([args[2].clone()]),
1023                        )
1024                        .finish()
1025                }),
1026                "f" | "d" => self.exact_arguments(term, &arguments, 3).map(|args| {
1027                    let adjoint_indices = args.iter().map(|argument| {
1028                        ColorRepresentation::Adjoint
1029                            .representation()
1030                            .to_symbolic([argument.clone()])
1031                    });
1032                    if name == "d" {
1033                        // UFO d^{abc} = 2 Tr({T^a,T^b} T^c), whereas Idenso
1034                        // stores the normalized symmetric generator trace.
1035                        Atom::num(4)
1036                            * CS.symmetric_generator_trace(
1037                                ColorRepresentation::Fundamental
1038                                    .representation()
1039                                    .to_symbolic([]),
1040                                adjoint_indices,
1041                            )
1042                    } else {
1043                        adjoint_indices
1044                            .fold(FunctionBuilder::new(CS.f), |builder, argument| {
1045                                builder.add_arg(argument)
1046                            })
1047                            .finish()
1048                    }
1049                }),
1050                "Epsilon" | "EpsilonBar" => self.exact_arguments(term, &arguments, 3).map(|args| {
1051                    let representation = if name == "Epsilon" {
1052                        ColorRepresentation::Fundamental
1053                    } else {
1054                        ColorRepresentation::AntiFundamental
1055                    };
1056                    idenso::epsilon::epsilon(args.iter().map(|argument| {
1057                        representation
1058                            .representation()
1059                            .to_symbolic([argument.clone()])
1060                    }))
1061                }),
1062                _ => return,
1063            };
1064            match lowered {
1065                Ok(replacement) => **out = replacement,
1066                Err(lowering_error) => error = Some(lowering_error),
1067            }
1068        });
1069        if let Some(error) = error {
1070            return Err(error);
1071        }
1072        self.reject_residual_tensors(&atom)?;
1073        Ok(atom)
1074    }
1075
1076    fn edge_color_identity(&self, color: i64) -> Result<Option<Atom>, GenerationError> {
1077        let Some(source_representation) = ColorRepresentation::from_ufo(color) else {
1078            return Ok(None);
1079        };
1080        let source = self
1081            .legs
1082            .iter()
1083            .copied()
1084            .find(|leg| leg.flow == Flow::Source)
1085            .ok_or_else(|| GenerationError::MissingNumeratorMomentum {
1086                owner: self.owner.to_string(),
1087            })?;
1088        let sink = self
1089            .legs
1090            .iter()
1091            .copied()
1092            .find(|leg| leg.flow == Flow::Sink)
1093            .ok_or_else(|| GenerationError::MissingNumeratorMomentum {
1094                owner: self.owner.to_string(),
1095            })?;
1096        let identity = ETS.metric(
1097            source_representation
1098                .representation()
1099                .to_symbolic([self.index(source, 1)?]),
1100            source_representation
1101                .dual()
1102                .representation()
1103                .to_symbolic([self.index(sink, 1)?]),
1104        );
1105        Ok(Some(identity))
1106    }
1107
1108    fn maximum_local_dummy(&self, atom: &Atom) -> Result<usize, GenerationError> {
1109        let mut maximum = 0;
1110        let mut error = None;
1111        let _ = atom.replace_map(|term, _, _| {
1112            if error.is_some() {
1113                return;
1114            }
1115            let AtomView::Fun(function) = term else {
1116                return;
1117            };
1118            let expected = match self.owner {
1119                NumeratorOwner::Vertex(_) => symbols::vertex_index(),
1120                NumeratorOwner::Edge(_) => symbols::edge_index(),
1121            };
1122            if function.get_symbol() != expected || function.get_nargs() != 2 {
1123                return;
1124            }
1125            let Some(local) = function.iter().nth(1) else {
1126                return;
1127            };
1128            match usize::try_from(local) {
1129                Ok(local) => maximum = maximum.max(local),
1130                Err(_) => error = Some(self.invalid_index(term)),
1131            }
1132        });
1133        error.map_or(Ok(maximum), Err)
1134    }
1135
1136    fn exact_arguments<'a>(
1137        &self,
1138        tensor: AtomView<'_>,
1139        arguments: &'a [Atom],
1140        expected: usize,
1141    ) -> Result<&'a [Atom], GenerationError> {
1142        if arguments.len() == expected {
1143            Ok(arguments)
1144        } else {
1145            Err(self.invalid_tensor(
1146                tensor,
1147                &format!("expected {expected} arguments, found {}", arguments.len()),
1148            ))
1149        }
1150    }
1151
1152    fn index_momentum(&self, momentum: AtomView<'_>, index: Atom) -> Result<Atom, GenerationError> {
1153        let AtomView::Fun(function) = momentum else {
1154            return Err(self.invalid_tensor(momentum, "expected a localized momentum"));
1155        };
1156        if function.get_symbol() != momentum_symbol() || function.get_nargs() != 1 {
1157            return Err(self.invalid_tensor(momentum, "expected a rank-one localized momentum"));
1158        }
1159        Ok(FunctionBuilder::new(momentum_symbol())
1160            .add_arg(function.iter().next().expect("the arity was checked"))
1161            .add_arg(index)
1162            .finish())
1163    }
1164
1165    fn bispinor(&self, index: Atom) -> Atom {
1166        Bispinor {}.new_rep(4).to_symbolic([index])
1167    }
1168
1169    fn minkowski(&self, index: Atom) -> Atom {
1170        Minkowski {}.new_rep(4).to_symbolic([index])
1171    }
1172
1173    fn is_representation(index: AtomView<'_>, name: &str) -> bool {
1174        matches!(
1175            index,
1176            AtomView::Fun(function)
1177                if function.get_symbol().get_namespace() == "spenso"
1178                    && function.get_symbol().get_stripped_name() == name
1179                    && matches!(function.get_nargs(), 1 | 2)
1180        )
1181    }
1182
1183    fn assign_color_representation(
1184        &self,
1185        representations: &mut HashMap<String, ColorRepresentation>,
1186        index: AtomView<'_>,
1187        representation: ColorRepresentation,
1188    ) -> Result<(), GenerationError> {
1189        let key = Self::index_key(index);
1190        let local_dummy = matches!(index, AtomView::Fun(function)
1191            if [symbols::vertex_index(), symbols::edge_index()]
1192                .contains(&function.get_symbol()));
1193        match representations.insert(key, representation) {
1194            // A contracted fundamental index joins dual slots. External ports
1195            // retain the exact orientation fixed by their particle record.
1196            Some(previous) if previous != representation
1197                && !(local_dummy && previous == representation.dual()) => Err(self.invalid_tensor(
1198                index,
1199                &format!(
1200                    "index is used as both {previous:?} and {representation:?} color representations"
1201                ),
1202            )),
1203            _ => Ok(()),
1204        }
1205    }
1206
1207    fn index_key(index: AtomView<'_>) -> String {
1208        index.to_canonical_string()
1209    }
1210
1211    fn reject_residual_tensors(&self, atom: &Atom) -> Result<(), GenerationError> {
1212        let mut residual = None;
1213        let _ = atom.replace_map(|term, _, _| {
1214            if residual.is_some() {
1215                return;
1216            }
1217            let AtomView::Fun(function) = term else {
1218                return;
1219            };
1220            let symbol = function.get_symbol();
1221            let name = symbol.get_stripped_name();
1222            if Self::is_model_symbol(symbol, name)
1223                && matches!(
1224                    name,
1225                    "Identity"
1226                        | "IdentityL"
1227                        | "Gamma"
1228                        | "Gamma5"
1229                        | "ProjM"
1230                        | "ProjP"
1231                        | "Sigma"
1232                        | "C"
1233                        | "Metric"
1234                        | "PSlash"
1235                        | "Epsilon"
1236                        | "T"
1237                        | "f"
1238                        | "d"
1239                        | "EpsilonBar"
1240                        | "T6"
1241                        | "K6"
1242                        | "K6Bar"
1243                )
1244            {
1245                residual = Some(self.unsupported_tensor(term));
1246            }
1247        });
1248        residual.map_or(Ok(()), Err)
1249    }
1250
1251    fn invalid_tensor(&self, tensor: AtomView<'_>, message: &str) -> GenerationError {
1252        GenerationError::InvalidNumeratorTensor {
1253            owner: self.owner.to_string(),
1254            tensor: tensor.to_string(),
1255            message: message.to_owned(),
1256        }
1257    }
1258
1259    fn unsupported_tensor(&self, tensor: AtomView<'_>) -> GenerationError {
1260        GenerationError::UnsupportedNumeratorTensor {
1261            owner: self.owner.to_string(),
1262            tensor: tensor.to_string(),
1263        }
1264    }
1265
1266    fn localize_index_argument(&self, argument: AtomView<'_>) -> Result<Atom, GenerationError> {
1267        if let Ok(index) = i64::try_from(argument) {
1268            return if index > 0 {
1269                self.index(self.leg(index)?, 1)
1270            } else if index < 0 {
1271                self.dummy(
1272                    usize::try_from(index.unsigned_abs()).map_err(|_| {
1273                        GenerationError::ArithmeticOverflow("a symbolic dummy index")
1274                    })?,
1275                )
1276            } else {
1277                Err(self.invalid_index(argument))
1278            };
1279        }
1280        if let AtomView::Fun(function) = argument {
1281            if Self::is_model_symbol(function.get_symbol(), "idx") {
1282                return self.localize_index_function(argument);
1283            }
1284            if Self::is_model_symbol(function.get_symbol(), "dummy") {
1285                return self.localize_dummy_function(argument);
1286            }
1287        }
1288        Ok(argument.to_owned())
1289    }
1290
1291    fn localize_index_function(&self, index: AtomView<'_>) -> Result<Atom, GenerationError> {
1292        let AtomView::Fun(function) = index else {
1293            return Err(self.invalid_index(index));
1294        };
1295        let arguments = function.iter().collect::<Vec<_>>();
1296        let [shift, leg] = arguments.as_slice() else {
1297            return Err(self.invalid_index(index));
1298        };
1299        let shift = i64::try_from(*shift).map_err(|_| self.invalid_index(index))?;
1300        if shift <= 0 {
1301            return Err(self.invalid_index(index));
1302        }
1303        self.index(
1304            self.leg(i64::try_from(*leg).map_err(|_| self.invalid_index(index))?)?,
1305            shift,
1306        )
1307    }
1308
1309    fn localize_dummy_function(&self, dummy: AtomView<'_>) -> Result<Atom, GenerationError> {
1310        let AtomView::Fun(function) = dummy else {
1311            return Err(self.invalid_index(dummy));
1312        };
1313        let arguments = function.iter().collect::<Vec<_>>();
1314        let [index] = arguments.as_slice() else {
1315            return Err(self.invalid_index(dummy));
1316        };
1317        let index = i64::try_from(*index).map_err(|_| self.invalid_index(dummy))?;
1318        if index <= 0 {
1319            return Err(self.invalid_index(dummy));
1320        }
1321        self.dummy(
1322            usize::try_from(index)
1323                .map_err(|_| GenerationError::ArithmeticOverflow("a symbolic dummy index"))?,
1324        )
1325    }
1326
1327    fn local_leg_number(&self, argument: AtomView<'_>) -> Result<i64, GenerationError> {
1328        if let Ok(leg) = i64::try_from(argument) {
1329            return Ok(leg);
1330        }
1331        let AtomView::Fun(function) = argument else {
1332            return Err(self.invalid_index(argument));
1333        };
1334        if !Self::is_model_symbol(function.get_symbol(), "idx") {
1335            return Err(self.invalid_index(argument));
1336        }
1337        let arguments = function.iter().collect::<Vec<_>>();
1338        let [_, leg] = arguments.as_slice() else {
1339            return Err(self.invalid_index(argument));
1340        };
1341        i64::try_from(*leg).map_err(|_| self.invalid_index(argument))
1342    }
1343
1344    fn leg(&self, one_based: i64) -> Result<NumeratorHalfEdge, GenerationError> {
1345        if one_based > 0 {
1346            let index = usize::try_from(one_based)
1347                .map_err(|_| GenerationError::ArithmeticOverflow("a symbolic UFO leg"))?;
1348            if let Some(leg) = self.legs.get(index - 1) {
1349                return Ok(*leg);
1350            }
1351        }
1352        Err(GenerationError::InvalidNumeratorLeg {
1353            owner: self.owner.to_string(),
1354            leg: one_based,
1355            legs: self.legs.len(),
1356        })
1357    }
1358
1359    /// The half-edge carrying an implicit momentum, and whether that momentum
1360    /// runs against the edge orientation.
1361    fn implicit_momentum_leg(&self) -> Result<(NumeratorHalfEdge, bool), GenerationError> {
1362        let leg = self.legs.first().copied().ok_or_else(|| {
1363            GenerationError::MissingNumeratorMomentum {
1364                owner: self.owner.to_string(),
1365            }
1366        })?;
1367        // A propagator's implicit momentum runs from its first slot to its
1368        // second. A conjugate fallback binds its first slot to the sink, so
1369        // that momentum is minus the edge momentum.
1370        let reversed = matches!(self.owner, NumeratorOwner::Edge(_)) && leg.flow == Flow::Sink;
1371        Ok((leg, reversed))
1372    }
1373
1374    fn index(&self, leg: NumeratorHalfEdge, shift: i64) -> Result<Atom, GenerationError> {
1375        let hedge = i64::try_from(leg.hedge)
1376            .map_err(|_| GenerationError::ArithmeticOverflow("a symbolic half-edge identifier"))?;
1377        Ok(if shift == 0 {
1378            symbols::hedge_index().call((hedge,))
1379        } else {
1380            symbols::hedge_index().call((hedge, shift))
1381        })
1382    }
1383
1384    fn dummy(&self, local: usize) -> Result<Atom, GenerationError> {
1385        let (symbol, owner) = match self.owner {
1386            NumeratorOwner::Vertex(vertex) => (symbols::vertex_index(), vertex),
1387            NumeratorOwner::Edge(edge) => (symbols::edge_index(), edge),
1388        };
1389        let owner = i64::try_from(owner)
1390            .map_err(|_| GenerationError::ArithmeticOverflow("a symbolic numerator owner"))?;
1391        let local = i64::try_from(local)
1392            .map_err(|_| GenerationError::ArithmeticOverflow("a symbolic dummy index"))?;
1393        Ok(if local == 0 {
1394            symbol.call((owner,))
1395        } else {
1396            symbol.call((owner, local))
1397        })
1398    }
1399
1400    fn momentum(
1401        &self,
1402        leg: NumeratorHalfEdge,
1403        index: Option<Atom>,
1404    ) -> Result<Atom, GenerationError> {
1405        let edge = i64::try_from(leg.edge)
1406            .map_err(|_| GenerationError::ArithmeticOverflow("a symbolic edge identifier"))?;
1407        let mut momentum = FunctionBuilder::new(momentum_symbol()).add_arg(edge);
1408        if let Some(index) = index {
1409            momentum = momentum.add_arg(index);
1410        }
1411        Ok(momentum.finish())
1412    }
1413
1414    fn invalid_index(&self, index: AtomView<'_>) -> GenerationError {
1415        GenerationError::InvalidNumeratorIndex {
1416            owner: self.owner.to_string(),
1417            index: index.to_string(),
1418        }
1419    }
1420
1421    fn is_model_symbol(symbol: symbolica::atom::Symbol, name: &str) -> bool {
1422        symbol.get_stripped_name() == name
1423            && (symbol.get_namespace() == "feynkit_generator_numerator"
1424                || symbol.get_namespace() == "UFO"
1425                || symbol.get_namespace().starts_with("UFO::"))
1426    }
1427}
1428
1429#[derive(Clone)]
1430pub(crate) struct Generator {
1431    model: Arc<Model>,
1432    numerators: Arc<NumeratorCache>,
1433}
1434
1435/// Localized factors depend on the immutable model and their index assignment,
1436/// not on the rest of the diagram. Keep them for this generator's lifetime.
1437#[derive(Default)]
1438struct NumeratorCache {
1439    interactions: RwLock<HashMap<InteractionNumeratorKey, SymbolicTensor<PartialStructure>>>,
1440    propagators: RwLock<HashMap<PropagatorNumeratorKey, SymbolicTensor<PartialStructure>>>,
1441    interaction_templates: RwLock<HashMap<InteractionNumeratorKey, Arc<NumeratorTemplate>>>,
1442    propagator_templates: RwLock<HashMap<ParticleId, Arc<NumeratorTemplate>>>,
1443}
1444
1445/// The same model-bound owner retains a rule's admission independently of the
1446/// graph's owner IDs. Dynamic source notation must be lowered at its actual owner.
1447enum NumeratorTemplate {
1448    Dynamic,
1449    Admitted {
1450        tensor: Box<SymbolicTensor<PartialStructure>>,
1451        labels: Vec<(AbstractIndex, Atom)>,
1452    },
1453}
1454
1455impl NumeratorTemplate {
1456    fn supports(expression: &Atom) -> bool {
1457        if !InterfaceInference::normalization_is_intrinsic(expression.as_view()) {
1458            return false;
1459        }
1460        let mut supported = true;
1461        let mut slots = SlotMatcher::default();
1462        expression.visitor(&mut |node| {
1463            // Admission may materialize these occurrences into fresh dummies,
1464            // even when a surrounding power or chain has no public ports.
1465            // Keep their allocation in the actual owner's construction.
1466            supported &= slots.compact_representation(node).is_none();
1467            if let AtomView::Fun(function) = node {
1468                // The occurrence-order owner cannot enumerate ports hidden in
1469                // bundles. Reject them before an additive term can move first
1470                // under owner-dependent normalization.
1471                supported &= function.get_symbol() != AIND_SYMBOLS.aind;
1472                // These labels must originate in localization. Literal graph
1473                // IDs could capture a generated label in the canonical frame.
1474                supported &= ![
1475                    symbols::hedge_index(),
1476                    symbols::vertex_index(),
1477                    symbols::edge_index(),
1478                    symbols::momentum(),
1479                    AIND_SYMBOLS.openind,
1480                ]
1481                .contains(&function.get_symbol());
1482            }
1483            if let SlotMatch::Explicit(slot) = slots.classify(node) {
1484                supported &= InterfaceInference::normalization_is_intrinsic(slot.index());
1485            }
1486            if let AtomView::Var(variable) = node
1487                && let UserData::Atom(payload) = variable.get_symbol().get_data()
1488            {
1489                supported &= Self::supports(payload);
1490            }
1491            supported
1492        });
1493        supported
1494    }
1495
1496    fn admitted(tensor: SymbolicTensor<PartialStructure>) -> Result<Self, GenerationError> {
1497        let tensor = tensor.finish_parts().map_err(DiagramError::from)?;
1498        // Anonymous occurrences need the checked positional correspondence
1499        // owner. Intrinsic explicit templates have a complete label bijection.
1500        if !tensor.structure().open_positions().is_empty()
1501            || !InterfaceInference::normalization_is_intrinsic(tensor.expression().as_view())
1502            || composition::interface_in_atom_order(tensor.expression(), tensor.structure())
1503                .is_err()
1504        {
1505            return Ok(Self::Dynamic);
1506        }
1507        let cooking = CookSettings::indices().with_mode(CookMode::ReversibleEncoding);
1508        let mut indices = HashSet::new();
1509        let mut slots = SlotMatcher::default();
1510        let mut fixed_dimensions = true;
1511        let mut collectable_indices = true;
1512        tensor.expression().visitor(&mut |node| {
1513            if let SlotMatch::Explicit(slot) = slots.classify(node) {
1514                if !slot.is_concrete_index() {
1515                    match AbstractIndex::try_from(slot.index()) {
1516                        Ok(index) => {
1517                            indices.insert(index);
1518                        }
1519                        // Slot-shaped opaque scalar metadata need not contain
1520                        // an abstract index, even in an admitted expression.
1521                        Err(_) => collectable_indices = false,
1522                    }
1523                }
1524                fixed_dimensions &= Self::supports(&cooking.uncook(slot.dimension()));
1525            }
1526            collectable_indices
1527        });
1528        if !collectable_indices {
1529            return Ok(Self::Dynamic);
1530        }
1531        for slot in tensor.structure().logical_slots() {
1532            if let PartialIndex::Explicit(index) = slot.aind {
1533                indices.insert(index);
1534            }
1535        }
1536        let labels = indices
1537            .into_iter()
1538            .map(|index| (index, cooking.uncook(index.to_atom().as_view())))
1539            .collect::<Vec<_>>();
1540        let mut fixed_labels = true;
1541        for (_, label) in &labels {
1542            fixed_labels &= InterfaceInference::normalization_is_intrinsic(label.as_view());
1543            label.visitor(&mut |node| {
1544                // An opaque index depending on a momentum ID could itself
1545                // alias when incident legs share an edge.
1546                fixed_labels &= node.get_symbol() != Some(symbols::momentum());
1547                fixed_labels
1548            });
1549        }
1550        if !fixed_dimensions || !fixed_labels {
1551            return Ok(Self::Dynamic);
1552        }
1553        let public_keys = tensor
1554            .structure()
1555            .logical_slots()
1556            .into_iter()
1557            .filter_map(|slot| match slot.aind {
1558                PartialIndex::Explicit(index) => {
1559                    Some(slot.rep().base().slot::<AbstractIndex, _>(index))
1560                }
1561                PartialIndex::Open(_) => None,
1562            })
1563            .collect::<HashSet<_>>();
1564        let representations = public_keys
1565            .iter()
1566            .map(|slot| slot.rep().rep.base())
1567            .collect::<HashSet<_>>();
1568        let mut scoped_alias = false;
1569        tensor.expression().visitor(&mut |scope| {
1570            if matches!(scope, AtomView::Add(_) | AtomView::Pow(_)) {
1571                for &representation in &representations {
1572                    let paired = InterfaceInference::has_explicit_index_pairs(
1573                        scope,
1574                        representation,
1575                        |leaf| {
1576                            let AtomView::Fun(function) = leaf else {
1577                                return true;
1578                            };
1579                            !function.iter().any(|argument| {
1580                                slots
1581                                    .parse::<LibraryRep, AbstractIndex>(argument)
1582                                    .is_ok_and(|slot| {
1583                                        let key =
1584                                            slot.rep().base().slot::<AbstractIndex, _>(slot.aind());
1585                                        public_keys.contains(&key)
1586                                    })
1587                            })
1588                        },
1589                    );
1590                    // A local bound pair must not be mistaken for a later
1591                    // public occurrence by the source-order helper. Multi-port
1592                    // leaves and detached chain scopes can be inconclusive;
1593                    // retain actual-owner admission in those cases too.
1594                    if !matches!(paired, Ok(false)) {
1595                        scoped_alias = true;
1596                        return false;
1597                    }
1598                }
1599            }
1600            !scoped_alias
1601        });
1602        if scoped_alias {
1603            return Ok(Self::Dynamic);
1604        }
1605        // Complete the source metadata before the retained template is cloned.
1606        // The identity map keeps its established interface and collision history.
1607        let tensor = tensor
1608            .with_renamed_indices(tensor.expression().clone(), &HashMap::new())
1609            .map_err(DiagramError::from)?;
1610        Ok(Self::Admitted {
1611            tensor: Box::new(tensor),
1612            labels,
1613        })
1614    }
1615
1616    fn instantiate(
1617        &self,
1618        instantiation: &NumeratorInstantiation<'_>,
1619    ) -> Result<SymbolicTensor<PartialStructure>, GenerationError> {
1620        let Self::Admitted { tensor, .. } = self else {
1621            unreachable!("dynamic rules are constructed at their actual owner")
1622        };
1623        NumeratorInterface::translate(tensor, |atom| instantiation.bind_template(atom))
1624    }
1625}
1626
1627#[derive(PartialEq, Eq, Hash)]
1628struct InteractionNumeratorKey {
1629    rule: VertexRuleId,
1630    owner: NumeratorOwner,
1631    legs: Vec<NumeratorHalfEdge>,
1632}
1633
1634#[derive(PartialEq, Eq, Hash)]
1635struct PropagatorNumeratorKey {
1636    particle: ParticleId,
1637    edge: usize,
1638    hedges: [usize; 2],
1639}
1640
1641/// Feynman-rule numerators for a finalized topology, using its attached model.
1642pub trait FeynmanDiagramRulesExt {
1643    /// Instantiate vertex and propagator numerators in an imported diagram's
1644    /// existing half-edge frame, using its interaction-slot assignments.
1645    ///
1646    /// The diagram's routing, overall factor, numerator prefactor and projector
1647    /// are retained. Existing local numerator fragments are replaced with the
1648    /// model's Feynman rules, just as during diagram generation.
1649    fn apply_feynman_rules(&self) -> Result<FeynmanDiagram, GenerationError>;
1650
1651    /// Construct the automatic external-state projector in the finalized frame.
1652    /// Paired initial states include color completeness without averaging;
1653    /// unsewn amplitude color ports remain open. Callers with an explicit
1654    /// projector retain that supplied expression instead.
1655    fn external_state_projector(&self)
1656    -> Result<SymbolicTensor<PartialStructure>, GenerationError>;
1657}
1658
1659impl FeynmanDiagramRulesExt for FeynmanDiagram {
1660    fn apply_feynman_rules(&self) -> Result<FeynmanDiagram, GenerationError> {
1661        self.validate()?;
1662        Generator::new(self.model_arc()).construct_numerators(self.clone())
1663    }
1664
1665    fn external_state_projector(
1666        &self,
1667    ) -> Result<SymbolicTensor<PartialStructure>, GenerationError> {
1668        let generator = Generator::new(self.model_arc());
1669        let mut projector = Atom::one();
1670        for (edge, endpoints, data) in self.edges() {
1671            let Some(external) = &data.external else {
1672                continue;
1673            };
1674            for (vertex, endpoint, state) in [
1675                (
1676                    endpoints.source,
1677                    DiagramEndpoint::Source,
1678                    ExternalState::Outgoing,
1679                ),
1680                (
1681                    endpoints.target,
1682                    DiagramEndpoint::Target,
1683                    ExternalState::Incoming,
1684                ),
1685            ] {
1686                if vertex.is_none() {
1687                    continue;
1688                }
1689                let state = if endpoints.source.is_some() && endpoints.target.is_some() {
1690                    state
1691                } else {
1692                    external.state
1693                };
1694                let hedge = self
1695                    .half_edge_id(DiagramHalfEdge { edge, endpoint })
1696                    .expect("finalized external endpoint")
1697                    .0;
1698                projector *=
1699                    generator.external_wavefunction(state, data.particle, edge.0, hedge)?;
1700            }
1701            if endpoints.source.is_some() && endpoints.target.is_some() {
1702                let hedges = [DiagramEndpoint::Source, DiagramEndpoint::Target].map(|endpoint| {
1703                    self.half_edge_id(DiagramHalfEdge { edge, endpoint })
1704                        .expect("finalized paired endpoint")
1705                        .0
1706                });
1707                projector *= generator.external_color_sum(data.particle, hedges)?;
1708            }
1709        }
1710        Ok(NumeratorInterface::admit(projector, None)?)
1711    }
1712}
1713
1714impl Generator {
1715    pub fn new(model: impl Into<Arc<Model>>) -> Self {
1716        Self {
1717            model: model.into(),
1718            numerators: Arc::default(),
1719        }
1720    }
1721
1722    pub fn generate(
1723        &self,
1724        process: &Process,
1725        options: &GenerationOptions,
1726        generation_type: GenerationType,
1727    ) -> Result<GenerationResult, GenerationError> {
1728        process.validate()?;
1729        if generation_type == GenerationType::Amplitude
1730            && process.outgoing_alternatives().len() != 1
1731        {
1732            return Err(ProcessError::MultipleAmplitudeFinalStates.into());
1733        }
1734        process.validate_in(&self.model)?;
1735        let options = process
1736            .restrict_options(&self.model, options)?
1737            .resolve_selectors(&self.model)?;
1738        let options = &options;
1739        self.validate_options(generation_type, options)?;
1740        process.validate_covariant_cut_filters(&self.model, options, generation_type)?;
1741        if generation_type == GenerationType::CrossSection {
1742            self.validate_cross_section_states(process, options)?;
1743        }
1744        let expanded_process = process.clone().with_final_state_alternatives(
1745            process.covariant_cut_states(&self.model, generation_type)?,
1746        )?;
1747        let process = &expanded_process;
1748        let resolved = ResolvedProcess::new(&self.model, process, generation_type, options)?;
1749        let signatures = InteractionSignatures::new(&self.model, options)?;
1750        let external_edges = resolved.external_edges(&self.model)?;
1751        let external_permutations = interchangeable_external_permutations(&external_edges)?;
1752        let generation_signatures: Vec<_> = signatures.keys().cloned().collect();
1753
1754        let progress_count = Arc::new(Mutex::new(0));
1755        let progress_options = options.clone();
1756        options.report_progress("topologies", 0, None);
1757        // Fast cut filter switch multiplicity is no longer a separate CLI option;
1758        // FeynKit owns the physical-cut filtering strategy.
1759        let mut settings = GenerationSettings::new()
1760            .max_loops(*options.loop_count().end())
1761            .allow_self_loops(options.allow_self_loops)
1762            .allow_zero_flow_edges(options.allow_zero_flow_edges)
1763            .progress_fn(Box::new(move |_| {
1764                let mut count = progress_count.lock().unwrap();
1765                *count += 1;
1766                progress_options.report_progress("topologies", *count, None);
1767                !progress_options.cancellation_requested()
1768            }));
1769        if let Some(filter) = options.filter.clone() {
1770            let filter_options = options.clone();
1771            settings = settings.filter_fn(Box::new(move |graph, completed_vertices| {
1772                !filter_options.cancellation_requested() && filter(graph, completed_vertices)
1773            }));
1774        }
1775        if let Some(maximum) = options.max_vertices {
1776            // Symbolica counts the degree-one external nodes as vertices. The
1777            // public FeynKit option counts interaction vertices instead.
1778            settings = settings.max_vertices(maximum.checked_add(external_edges.len()).ok_or(
1779                GenerationError::ArithmeticOverflow("the Symbolica vertex limit"),
1780            )?);
1781        }
1782        if let Some(maximum) = options.max_bridges(*options.loop_count().start()) {
1783            settings = settings.max_bridges(maximum);
1784        }
1785        let abort_options = options.clone();
1786        settings = settings.abort_check(Box::new(move || abort_options.cancellation_requested()));
1787
1788        let generated = Graph::generate(&external_edges, &generation_signatures, settings);
1789        let (raw_graphs, mut completed) = match generated {
1790            Ok(graphs) => (graphs, true),
1791            Err(graphs) => (graphs, false),
1792        };
1793        if options.cancellation_requested() {
1794            completed = false;
1795        }
1796
1797        let mut raw_graphs: Vec<_> = raw_graphs.into_iter().collect();
1798        // Sort for reproducible generated IDs, then discard contributions below
1799        // the requested loop range before more expensive processing.
1800        raw_graphs.sort_by(|left, right| left.0.cmp(&right.0));
1801        raw_graphs.retain(|(graph, _)| options.loop_count().contains(&graph.num_loops()));
1802        let mut filtered_graphs = Vec::with_capacity(raw_graphs.len());
1803        let total = raw_graphs.len();
1804        options.report_progress("topology_filters", 0, Some(total));
1805        for (index, entry) in raw_graphs.into_iter().enumerate() {
1806            if options.cancellation_requested() {
1807                completed = false;
1808                break;
1809            }
1810            if self.passes_topology_filters(&entry.0, options)? {
1811                filtered_graphs.push(entry);
1812            }
1813            options.report_progress("topology_filters", index + 1, Some(total));
1814        }
1815        let raw_graphs = filtered_graphs;
1816        let topology_count = raw_graphs.len();
1817
1818        let assignments = Mutex::new(0);
1819        options.report_progress("interactions", 0, Some(topology_count));
1820        let color_graph = |(graph, symmetry): &(
1821            Graph<NodeColor, EdgeColor>,
1822            symbolica::domains::integer::Integer,
1823        )| {
1824            if options.cancellation_requested() {
1825                return Ok(None);
1826            }
1827            let symmetry = match u64::try_from(symmetry.clone()) {
1828                Ok(symmetry) => symmetry,
1829                Err(error) => {
1830                    return Err(GenerationError::SymmetryFactor(error.to_string()));
1831                }
1832            };
1833            let result = self
1834                .assign_interactions(graph, &signatures, external_permutations != 1)
1835                .map(|graphs| (graphs, symmetry));
1836            let mut count = assignments.lock().unwrap();
1837            *count += 1;
1838            options.report_progress("interactions", *count, Some(topology_count));
1839            result.map(Some)
1840        };
1841        // An explicit single thread runs every stage on the caller without a
1842        // Rayon pool. Otherwise respect an explicit thread count, or Rayon's
1843        // default logical-CPU count. Browser kernels process the same graphs serially.
1844        #[cfg(not(target_arch = "wasm32"))]
1845        let pool = if options.threads == Some(1) {
1846            None
1847        } else {
1848            let mut pool = ThreadPoolBuilder::new();
1849            if let Some(threads) = options.threads {
1850                pool = pool.num_threads(threads);
1851            }
1852            Some(pool.build()?)
1853        };
1854        #[cfg(target_arch = "wasm32")]
1855        let colored = raw_graphs
1856            .iter()
1857            .map(color_graph)
1858            .collect::<Result<Vec<_>, _>>()?;
1859        #[cfg(not(target_arch = "wasm32"))]
1860        let colored = if let Some(pool) = &pool {
1861            pool.install(|| {
1862                raw_graphs
1863                    .par_iter()
1864                    .map(color_graph)
1865                    .collect::<Result<Vec<_>, _>>()
1866            })?
1867        } else {
1868            raw_graphs
1869                .iter()
1870                .map(color_graph)
1871                .collect::<Result<Vec<_>, _>>()?
1872        };
1873        if options.cancellation_requested() {
1874            completed = false;
1875        }
1876        let mut colored: Vec<_> = colored
1877            .into_iter()
1878            .flatten()
1879            .flat_map(|(graphs, symmetry)| {
1880                graphs
1881                    .into_iter()
1882                    .map(move |(graph, multiplicity)| ColoredTopology {
1883                        graph,
1884                        symmetry,
1885                        multiplicity,
1886                        cut_partitions: Vec::new(),
1887                        topology_threshold_candidates: Vec::new(),
1888                        spectator_cuts: Vec::new(),
1889                    })
1890            })
1891            .collect();
1892        colored.sort_by(|left, right| left.graph.cmp(&right.graph));
1893        let interaction_assignment_count = colored.len();
1894
1895        let mut diagram_inputs = Vec::new();
1896        options.report_progress("interaction_filters", 0, Some(interaction_assignment_count));
1897        for (index, mut topology) in colored.into_iter().enumerate() {
1898            options.report_progress(
1899                "interaction_filters",
1900                index,
1901                Some(interaction_assignment_count),
1902            );
1903            if options.cancellation_requested() {
1904                completed = false;
1905                break;
1906            }
1907            topology.graph = resolved.canonicalize_numerator_graph(
1908                &topology.graph,
1909                &self.model,
1910                &options.numerator_grouping,
1911            )?;
1912            // Vacuum graphs have no s-channel cut; as on main, they are kept
1913            // without cut filtering.
1914            let selects_cuts =
1915                generation_type == GenerationType::CrossSection && !resolved.incoming.is_empty();
1916            // The interaction filters do not depend on cuts. Evaluate them before
1917            // the cut search, the most expensive step, which still sees the
1918            // graph before its CP rules are repaired. Only a successful
1919            // rejection skips the graph here; an error is reported, as before,
1920            // only once the graph has a cut.
1921            let early = selects_cuts.then(|| {
1922                let repaired = ResolvedProcess::repair_cp_interaction_rules(
1923                    topology.graph.clone(),
1924                    &self.model,
1925                )?;
1926                let fermion_loop_count = self.closed_fermion_loop_count(&repaired, false)?;
1927                let passes =
1928                    self.passes_interaction_filters(&repaired, fermion_loop_count, options)?;
1929                Ok::<_, GenerationError>((repaired, passes))
1930            });
1931            if matches!(early, Some(Ok((_, false)))) {
1932                continue;
1933            }
1934            if selects_cuts {
1935                let inventory = resolved.cut_partitions(&topology.graph, &self.model, options)?;
1936                topology.cut_partitions = inventory.physical;
1937                topology.topology_threshold_candidates = inventory.topology_threshold_candidates;
1938                // As on main, any cut satisfying the spectator range selects
1939                // the graph, but only spectator-free cuts are physical cuts.
1940                let mut spectator_cuts = inventory.spectator;
1941                let has_physical_cut =
1942                    Self::retain_cut_amplitude_cuts(&mut topology.cut_partitions, options)?;
1943                if !((has_physical_cut && inventory.physical_satisfies_spectator_range)
1944                    || Self::retain_cut_amplitude_cuts(&mut spectator_cuts, options)?)
1945                    || !resolved.passes_sewn_filter(&topology.graph, options)
1946                {
1947                    continue;
1948                }
1949                // A graph that only a spectator cut selects becomes a
1950                // selection-only diagram: it records the spectator cuts in
1951                // place of physical cuts and threshold candidates.
1952                if !has_physical_cut {
1953                    topology.topology_threshold_candidates.clear();
1954                    topology.spectator_cuts = spectator_cuts
1955                        .iter()
1956                        .map(|cut| resolved.spectator_cut(&topology.graph, cut))
1957                        .collect();
1958                }
1959            }
1960            topology.graph = match early {
1961                Some(early) => early?.0,
1962                None => {
1963                    let repaired =
1964                        ResolvedProcess::repair_cp_interaction_rules(topology.graph, &self.model)?;
1965                    let fermion_loop_count = self.closed_fermion_loop_count(&repaired, false)?;
1966                    if !self.passes_interaction_filters(&repaired, fermion_loop_count, options)? {
1967                        continue;
1968                    }
1969                    repaired
1970                }
1971            };
1972            let grassmann_loop_count = self.closed_fermion_loop_count(&topology.graph, true)?;
1973            // Canonicalization fixes the stable vertex/edge-ID frame used by
1974            // cuts and routing.  The physical representative must still have
1975            // each fermion chain oriented consistently before its numerator
1976            // is instantiated.  Reversing an edge keeps its stable ID, so the
1977            // only cut metadata that needs transport is the source/target
1978            // endpoint attached to each half-edge.
1979            let normalized = resolved.normalize_fermion_flows(&topology.graph, &self.model)?;
1980            let representative = ColoredTopology {
1981                graph: normalized.graph,
1982                symmetry: topology.symmetry,
1983                multiplicity: topology.multiplicity,
1984                cut_partitions: transport_cut_metadata(
1985                    &topology.cut_partitions,
1986                    &normalized.reversed_edges,
1987                ),
1988                topology_threshold_candidates: transport_threshold_candidate_metadata(
1989                    &topology.topology_threshold_candidates,
1990                    &normalized.reversed_edges,
1991                ),
1992                spectator_cuts: transport_spectator_cut_metadata(
1993                    &topology.spectator_cuts,
1994                    &normalized.reversed_edges,
1995                ),
1996            };
1997            // Without numerator comparisons, the normalized physical graph is
1998            // already the representative. Its orientation-independent key also
1999            // provides the same deterministic ordering.
2000            let (topology, reversed_edges) =
2001                if matches!(options.numerator_grouping, NumeratorGrouping::None) {
2002                    (representative.clone(), BTreeSet::new())
2003                } else {
2004                    (topology, normalized.reversed_edges)
2005                };
2006            diagram_inputs.push((
2007                topology,
2008                representative,
2009                grassmann_loop_count,
2010                normalized.signs,
2011                reversed_edges,
2012            ));
2013        }
2014        if !options.cancellation_requested() {
2015            options.report_progress(
2016                "interaction_filters",
2017                interaction_assignment_count,
2018                Some(interaction_assignment_count),
2019            );
2020        }
2021        let total = diagram_inputs.len();
2022        options.report_progress("numerators", 0, Some(total));
2023        let width = diagram_inputs.len().saturating_sub(1).to_string().len();
2024        let constructed = Mutex::new(0);
2025        let construct = |(
2026            index,
2027            (comparison, representative, grassmann_loop_count, signs, reversed_edges),
2028        ): (
2029            usize,
2030            (
2031                ColoredTopology,
2032                ColoredTopology,
2033                usize,
2034                FermionSigns,
2035                BTreeSet<EdgeId>,
2036            ),
2037        )| {
2038            if options.cancellation_requested() {
2039                return Ok::<_, GenerationError>(None);
2040            }
2041            let name = format!("{}{index:0width$}", options.graph_prefix);
2042            let identical = comparison == representative;
2043            let signs = FermionSigns {
2044                internal_loop_negative: grassmann_loop_count % 2 == 1,
2045                ..signs
2046            };
2047            let internal_reversals = comparison
2048                .graph
2049                .edges()
2050                .iter()
2051                .enumerate()
2052                .filter(|(_, edge)| {
2053                    [edge.vertices.0, edge.vertices.1].iter().all(|vertex| {
2054                        matches!(
2055                            comparison.graph.nodes()[*vertex].data,
2056                            ColoredNode::Interaction(_)
2057                        )
2058                    })
2059                })
2060                .map(|(edge, _)| reversed_edges.contains(&EdgeId(edge)))
2061                .collect::<Vec<_>>();
2062            let comparison = self.to_diagram(
2063                name.clone(),
2064                generation_type,
2065                comparison,
2066                external_permutations,
2067                signs,
2068                options,
2069            )?;
2070            let representative = if identical {
2071                comparison.clone()
2072            } else {
2073                self.to_diagram(
2074                    name,
2075                    generation_type,
2076                    representative,
2077                    external_permutations,
2078                    signs,
2079                    options,
2080                )?
2081            };
2082            // Finalization orders external carriers before the internal edges.
2083            // Transport the comparison-to-representative reversals into that
2084            // finalized edge frame; process flow fixes all external carriers.
2085            let reversed_edges = comparison
2086                .edges()
2087                .filter(|(_, _, edge)| edge.external.is_none())
2088                .zip(internal_reversals)
2089                .filter_map(|((edge, _, _), reversed)| reversed.then_some(edge))
2090                .collect();
2091            let pair = DiagramPair {
2092                comparison,
2093                representative,
2094                reversed_edges,
2095            };
2096            let mut count = constructed.lock().unwrap();
2097            *count += 1;
2098            options.report_progress("numerators", *count, Some(total));
2099            Ok(Some(pair))
2100        };
2101        #[cfg(target_arch = "wasm32")]
2102        let diagram_pairs = diagram_inputs
2103            .into_iter()
2104            .enumerate()
2105            .map(construct)
2106            .collect::<Result<Vec<_>, _>>()?;
2107        #[cfg(not(target_arch = "wasm32"))]
2108        let diagram_pairs = if let Some(pool) = &pool {
2109            pool.install(|| {
2110                diagram_inputs
2111                    .into_par_iter()
2112                    .enumerate()
2113                    .map(construct)
2114                    .collect::<Result<Vec<_>, _>>()
2115            })?
2116        } else {
2117            diagram_inputs
2118                .into_iter()
2119                .enumerate()
2120                .map(construct)
2121                .collect::<Result<Vec<_>, _>>()?
2122        };
2123        let diagram_pairs = diagram_pairs.into_iter().flatten().collect::<Vec<_>>();
2124        if options.cancellation_requested() {
2125            completed = false;
2126        }
2127        options.report_progress("selection", 0, None);
2128        // Flow normalization can produce the same full tensor payload from
2129        // distinct source topologies. Combine their weights before assigning
2130        // names or applying optional numerator comparisons.
2131        let (mut keyed_diagrams, normalization_zero_count) =
2132            DiagramPair::combine_duplicates(diagram_pairs)?;
2133        keyed_diagrams.sort_by(|left, right| left.0.cmp(&right.0));
2134        let width = keyed_diagrams
2135            .len()
2136            .saturating_sub(1)
2137            .to_string()
2138            .len()
2139            .max(1);
2140        let mut comparison_diagrams = Vec::with_capacity(keyed_diagrams.len());
2141        let mut representatives = Vec::with_capacity(keyed_diagrams.len());
2142        let mut matched_forced_cuts = vec![false; options.forced_cuts.len()];
2143        let mut unmatched_basis_names = options
2144            .named_loop_momentum_bases
2145            .keys()
2146            .collect::<BTreeSet<_>>();
2147        let mut unmatched_basis_ids = options
2148            .loop_momentum_bases
2149            .keys()
2150            .copied()
2151            .collect::<BTreeSet<_>>();
2152        // Names and ID selectors refer to the unforced diagram list; forced
2153        // cuts only drop cuts and the diagrams left without any.
2154        for (index, (_, mut pair)) in keyed_diagrams.into_iter().enumerate() {
2155            let name = format!("{}{index:0width$}", options.graph_prefix);
2156            let unforced_ids = [pair.representative.id(), pair.comparison.id()];
2157            unmatched_basis_names.remove(&name);
2158            for id in unforced_ids {
2159                unmatched_basis_ids.remove(&id);
2160            }
2161            if !options.forced_cuts.is_empty() {
2162                let cuts = pair
2163                    .comparison
2164                    .cuts()
2165                    .iter()
2166                    .filter(|cut| {
2167                        let edges = cut
2168                            .cut
2169                            .iter()
2170                            .map(|half_edge| half_edge.edge)
2171                            .collect::<BTreeSet<_>>();
2172                        let mut forced = false;
2173                        for (requested, matched) in
2174                            options.forced_cuts.iter().zip(&mut matched_forced_cuts)
2175                        {
2176                            if *requested == edges {
2177                                *matched = true;
2178                                forced = true;
2179                            }
2180                        }
2181                        forced
2182                    })
2183                    .cloned()
2184                    .collect::<Vec<_>>();
2185                if cuts.is_empty() {
2186                    continue;
2187                }
2188                pair.comparison = pair.comparison.with_cuts(cuts)?;
2189                let partitions =
2190                    transport_cut_metadata(pair.comparison.cuts(), &pair.reversed_edges)
2191                        .into_iter()
2192                        .map(|cut| (cut.left.half_edges, cut.right.half_edges))
2193                        .collect();
2194                pair.representative = pair.representative.with_cut_partitions(partitions)?;
2195            }
2196            // A caller may refer to the original diagram or replay the ID returned
2197            // by an earlier generation with the same cuts. Prefer the returned
2198            // representative, then its comparison ID, when routing keys conflict.
2199            let ids = [
2200                pair.representative.id(),
2201                pair.comparison.id(),
2202                unforced_ids[0],
2203                unforced_ids[1],
2204            ];
2205            for id in [ids[0], ids[1]] {
2206                unmatched_basis_ids.remove(&id);
2207            }
2208            let selected_by_id = options
2209                .selected_diagram_ids
2210                .as_ref()
2211                .is_some_and(|selected| ids.iter().any(|id| selected.contains(id)));
2212            let selected_by_name = options
2213                .selected_diagram_names
2214                .as_ref()
2215                .is_some_and(|selected| selected.contains(&name));
2216            let has_selection =
2217                options.selected_diagram_ids.is_some() || options.selected_diagram_names.is_some();
2218            if (has_selection && !selected_by_id && !selected_by_name)
2219                || ids.iter().any(|id| options.vetoed_diagram_ids.contains(id))
2220                || options.vetoed_diagram_names.contains(&name)
2221            {
2222                continue;
2223            }
2224            pair.comparison = pair.comparison.with_name(&name);
2225            pair.representative = pair.representative.with_name(&name);
2226            let requested_basis = ids
2227                .iter()
2228                .find_map(|id| options.loop_momentum_bases.get(id))
2229                .or_else(|| options.named_loop_momentum_bases.get(&name));
2230            // Grouping labels loop momenta by basis position, so every comparison
2231            // graph keeps its default routing and the group ratios do not depend on
2232            // a requested basis. Only the runtime representative is rerouted; the
2233            // basis is honoured below when this graph becomes a group master.
2234            if let Some(edges) = requested_basis {
2235                pair.representative = pair.representative.with_loop_momentum_edges(edges)?;
2236            }
2237            comparison_diagrams.push(pair.comparison);
2238            representatives.push((pair.representative, pair.reversed_edges, requested_basis));
2239        }
2240        if let Some((missing, _)) = options
2241            .forced_cuts
2242            .iter()
2243            .zip(&matched_forced_cuts)
2244            .find(|(_, matched)| !**matched)
2245        {
2246            return Err(GenerationError::UnknownForcedCut {
2247                edges: missing.iter().map(|edge| edge.0).collect(),
2248            });
2249        }
2250        if completed
2251            && !options.cancellation_requested()
2252            && let Some(name) = unmatched_basis_names.first()
2253        {
2254            return Err(GenerationError::UnknownLoopMomentumBasisTarget {
2255                target: format!("{name:?}"),
2256            });
2257        }
2258        let grouping = if options.cancellation_requested() {
2259            completed = false;
2260            &NumeratorGrouping::None
2261        } else {
2262            &options.numerator_grouping
2263        };
2264        let group = || {
2265            grouping::group_diagrams(
2266                comparison_diagrams,
2267                &self.model,
2268                grouping,
2269                options.symmetrizes_left_right(),
2270                options,
2271            )
2272        };
2273        #[cfg(target_arch = "wasm32")]
2274        let grouped = group()?;
2275        #[cfg(not(target_arch = "wasm32"))]
2276        let grouped = if let Some(pool) = &pool {
2277            pool.install(group)?
2278        } else {
2279            group()?
2280        };
2281        if options.cancellation_requested() {
2282            completed = false;
2283        }
2284
2285        // Numerator-aware grouping must use the canonical comparison graphs:
2286        // normalizing their charged flows changes the momentum convention and
2287        // prevents mirror representatives from collapsing.  Runtime exposure,
2288        // however, uses the normalized representative selected by each group.
2289        // Transport the merged canonical cut inventories into that
2290        // representative's orientation and retain the comparison-derived
2291        // grouping factor and routing choice.
2292        let zero_numerator_count = grouped.zero_numerator_count + normalization_zero_count;
2293        let mut groups = grouped.groups;
2294        let total = groups.len();
2295        options.report_progress_with_zero_count("grouping", 0, Some(total), zero_numerator_count);
2296        let mut diagrams = Vec::with_capacity(grouped.diagrams.len());
2297        for (output_index, (comparison_master, group)) in grouped
2298            .diagrams
2299            .into_iter()
2300            .zip(groups.iter_mut())
2301            .enumerate()
2302        {
2303            if group.master != output_index {
2304                return Err(GenerationError::InvalidGroups(format!(
2305                    "group {output_index} points to unexpected master {}",
2306                    group.master
2307                )));
2308            }
2309            let source_diagram = group
2310                .members
2311                .first()
2312                .ok_or_else(|| {
2313                    GenerationError::InvalidGroups(format!(
2314                        "group {output_index} has no representative member"
2315                    ))
2316                })?
2317                .source_diagram;
2318            let (source_representative, reversed_edges, requested_basis) =
2319                representatives.get(source_diagram).ok_or_else(|| {
2320                    GenerationError::InvalidGroups(format!(
2321                        "group {output_index} references unknown source diagram {source_diagram}"
2322                    ))
2323                })?;
2324            let cuts = transport_cut_metadata(comparison_master.cuts(), reversed_edges);
2325            let thresholds = transport_threshold_candidate_metadata(
2326                comparison_master.topology_threshold_candidates(),
2327                reversed_edges,
2328            );
2329            let mut representative = source_representative.clone();
2330            if cuts != representative.cuts() {
2331                representative = representative.with_cut_partitions(
2332                    cuts.into_iter()
2333                        .map(|cut| (cut.left.half_edges, cut.right.half_edges))
2334                        .collect(),
2335                )?;
2336            }
2337            if thresholds != representative.topology_threshold_candidates() {
2338                representative = representative.with_topology_threshold_partitions(
2339                    thresholds
2340                        .into_iter()
2341                        .map(|candidate| (candidate.left, candidate.right))
2342                        .collect(),
2343                )?;
2344            }
2345            // A selection-only master keeps the spectator cuts that selected it;
2346            // physical cuts installed above have already superseded them.
2347            let spectator_cuts = transport_spectator_cut_metadata(
2348                comparison_master.spectator_cuts(),
2349                reversed_edges,
2350            );
2351            if !spectator_cuts.is_empty() && spectator_cuts != representative.spectator_cuts() {
2352                representative = representative.with_spectator_cuts(spectator_cuts)?;
2353            }
2354            // Merged cut metadata can assign a new stable ID to the master.
2355            // Resolve that ID against the final runtime representative.
2356            let master_id = representative.id();
2357            let grouped_basis = if unmatched_basis_ids.remove(&master_id) {
2358                options.loop_momentum_bases.get(&master_id)
2359            } else {
2360                None
2361            };
2362            // The grouping factor is defined in the comparison routing.
2363            // Installing the runtime basis does not recompute the group.
2364            let desired_edges = grouped_basis
2365                .or(*requested_basis)
2366                .unwrap_or(&comparison_master.loop_momentum_basis().loop_edges);
2367            if &representative.loop_momentum_basis().loop_edges != desired_edges {
2368                representative = representative.with_loop_momentum_edges(desired_edges)?;
2369            }
2370            representative = representative
2371                .with_name(comparison_master.name())
2372                .with_overall_factor(comparison_master.overall_factor().clone());
2373            diagrams.push(representative);
2374
2375            for member in &mut group.members {
2376                let (source, _, member_basis) =
2377                    representatives.get(member.source_diagram).ok_or_else(|| {
2378                        GenerationError::InvalidGroups(format!(
2379                            "group {output_index} references unknown source diagram {}",
2380                            member.source_diagram
2381                        ))
2382                    })?;
2383                // Only a master is evaluated, so another member's basis cannot be honoured.
2384                if member.source_diagram != source_diagram && member_basis.is_some() {
2385                    return Err(GenerationError::LoopMomentumBasisOfGroupedMember {
2386                        member: source.name().to_owned(),
2387                        master: comparison_master.name().to_owned(),
2388                    });
2389                }
2390                member.source_id = source.id();
2391                member.source_name = source.name().to_owned();
2392            }
2393            options.report_progress_with_zero_count(
2394                "grouping",
2395                output_index + 1,
2396                Some(total),
2397                zero_numerator_count,
2398            );
2399        }
2400
2401        if completed
2402            && !options.cancellation_requested()
2403            && let Some(id) = unmatched_basis_ids.first()
2404        {
2405            return Err(GenerationError::UnknownLoopMomentumBasisTarget {
2406                target: id.to_string(),
2407            });
2408        }
2409        let result = GenerationResult {
2410            report: GenerationReport {
2411                topology_count,
2412                interaction_assignment_count,
2413                retained_count: diagrams.len(),
2414                zero_numerator_count,
2415                completed,
2416            },
2417            diagrams,
2418            groups,
2419        };
2420        result.validate_groups()?;
2421        options.report_progress_with_zero_count(
2422            if completed { "complete" } else { "cancelled" },
2423            result.diagrams.len(),
2424            Some(result.diagrams.len()),
2425            zero_numerator_count,
2426        );
2427        Ok(result)
2428    }
2429
2430    /// Reject cross-section state requests that no Cutkosky cut can satisfy.
2431    ///
2432    /// Vacuum cross sections (no initial states) are generated without cut
2433    /// filtering, so a final state or a cut-amplitude filter would be silently
2434    /// ignored. Graph-scope defaults such as the blob and spectator ranges stay
2435    /// valid. With initial states, an empty final state matches only
2436    /// unresolved cut content, so perturbative orders must admit a particle.
2437    fn validate_cross_section_states(
2438        &self,
2439        process: &Process,
2440        options: &GenerationOptions,
2441    ) -> Result<(), GenerationError> {
2442        let empty_final_state = process.outgoing_alternatives().iter().all(Vec::is_empty);
2443        if process.incoming().is_empty() {
2444            if !empty_final_state {
2445                return Err(GenerationError::VacuumCrossSectionFinalState);
2446            }
2447            if !options.cut_amplitude_filters.is_empty() {
2448                return Err(GenerationError::VacuumCutAmplitudeFilters);
2449            }
2450        } else if empty_final_state
2451            && unresolved_cut_content(&self.model, options)?.is_none_or(|unresolved| {
2452                unresolved.maximum_multiplicity == 0 || unresolved.particles.is_empty()
2453            })
2454        {
2455            return Err(GenerationError::EmptyCrossSectionFinalStates);
2456        }
2457        Ok(())
2458    }
2459
2460    fn validate_options(
2461        &self,
2462        generation_type: GenerationType,
2463        options: &GenerationOptions,
2464    ) -> Result<(), GenerationError> {
2465        if options.threads == Some(0) {
2466            return Err(GenerationError::InvalidThreadCount(0));
2467        }
2468        let (initial, final_state) = (options.symmetrizes_initial(), options.symmetrizes_final());
2469        if generation_type == GenerationType::Amplitude
2470            && options.symmetrizes_left_right()
2471            && !(initial && final_state)
2472        {
2473            return Err(GenerationError::OneSidedLeftRightAmplitudeSymmetrization {
2474                initial,
2475                final_state,
2476            });
2477        }
2478        // Canonical comparison alone is an exact grouping mode without samples; scalar
2479        // rescaling compares sample ratios, so it never decides from one sample.
2480        options.numerator_grouping.validate_sample_count()?;
2481        self.validate_filters(FilterScope::Graph, generation_type, &options.graph_filters)?;
2482        self.validate_filters(
2483            FilterScope::CutAmplitude,
2484            generation_type,
2485            &options.cut_amplitude_filters,
2486        )
2487    }
2488
2489    fn validate_filters(
2490        &self,
2491        scope: FilterScope,
2492        generation_type: GenerationType,
2493        filters: &[GenerationFilter],
2494    ) -> Result<(), GenerationError> {
2495        let mut seen = BTreeSet::new();
2496        for filter in filters {
2497            let kind = filter.kind();
2498            if !seen.insert(kind) {
2499                return Err(GenerationError::DuplicateFilter {
2500                    scope,
2501                    filter: kind,
2502                });
2503            }
2504
2505            match scope {
2506                FilterScope::Graph => match filter {
2507                    GenerationFilter::SelfEnergy(options) => {
2508                        if options.only_scaleless {
2509                            return Err(GenerationError::UnsupportedFilterOption {
2510                                scope,
2511                                filter: kind,
2512                                option: "only_scaleless",
2513                            });
2514                        }
2515                    }
2516                    GenerationFilter::Tadpoles(options) => {
2517                        if options.only_scaleless {
2518                            return Err(GenerationError::UnsupportedFilterOption {
2519                                scope,
2520                                filter: kind,
2521                                option: "only_scaleless",
2522                            });
2523                        }
2524                    }
2525                    GenerationFilter::ZeroSnails(options) => {
2526                        if options.only_scaleless {
2527                            return Err(GenerationError::UnsupportedFilterOption {
2528                                scope,
2529                                filter: kind,
2530                                option: "only_scaleless",
2531                            });
2532                        }
2533                    }
2534                    GenerationFilter::ParticleVeto(_)
2535                    | GenerationFilter::VertexAllow(_)
2536                    | GenerationFilter::VertexVeto(_)
2537                    | GenerationFilter::MaxNumberOfBridges(_)
2538                    | GenerationFilter::LoopOneParticleIrreducible
2539                    | GenerationFilter::CouplingOrders(_)
2540                    | GenerationFilter::LoopCountRange(_)
2541                    | GenerationFilter::FermionLoopCountRange(_)
2542                    | GenerationFilter::FactorizedLoopTopologiesCountRange(_) => {}
2543                    GenerationFilter::BlobRange(_) | GenerationFilter::SpectatorRange(_)
2544                        if generation_type == GenerationType::CrossSection => {}
2545                    GenerationFilter::BlobRange(_) | GenerationFilter::SpectatorRange(_) => {
2546                        return Err(GenerationError::InvalidFilterScope {
2547                            scope,
2548                            filter: kind,
2549                            generation_type,
2550                        });
2551                    }
2552                    GenerationFilter::PerturbativeOrders(_) | GenerationFilter::Sewn(_)
2553                        if generation_type == GenerationType::CrossSection => {}
2554                    GenerationFilter::PerturbativeOrders(_) | GenerationFilter::Sewn(_) => {
2555                        return Err(GenerationError::InvalidFilterScope {
2556                            scope,
2557                            filter: kind,
2558                            generation_type,
2559                        });
2560                    }
2561                },
2562                FilterScope::CutAmplitude => {
2563                    if generation_type != GenerationType::CrossSection {
2564                        return Err(GenerationError::InvalidFilterScope {
2565                            scope,
2566                            filter: kind,
2567                            generation_type,
2568                        });
2569                    }
2570                    match filter {
2571                        GenerationFilter::CouplingOrders(_)
2572                        | GenerationFilter::LoopCountRange(_) => {}
2573                        GenerationFilter::SelfEnergy(_)
2574                        | GenerationFilter::Tadpoles(_)
2575                        | GenerationFilter::ZeroSnails(_)
2576                        | GenerationFilter::Sewn(_)
2577                        | GenerationFilter::ParticleVeto(_)
2578                        | GenerationFilter::VertexAllow(_)
2579                        | GenerationFilter::VertexVeto(_)
2580                        | GenerationFilter::MaxNumberOfBridges(_)
2581                        | GenerationFilter::LoopOneParticleIrreducible
2582                        | GenerationFilter::BlobRange(_)
2583                        | GenerationFilter::SpectatorRange(_)
2584                        | GenerationFilter::PerturbativeOrders(_)
2585                        | GenerationFilter::FermionLoopCountRange(_)
2586                        | GenerationFilter::FactorizedLoopTopologiesCountRange(_) => {
2587                            return Err(GenerationError::InvalidFilterScope {
2588                                scope,
2589                                filter: kind,
2590                                generation_type,
2591                            });
2592                        }
2593                    }
2594                }
2595            }
2596
2597            self.validate_filter_range(scope, filter)?;
2598            match filter {
2599                GenerationFilter::ParticleVeto(selectors) => {
2600                    for selector in selectors {
2601                        selector.resolve(&self.model)?;
2602                    }
2603                }
2604                GenerationFilter::VertexAllow(selectors)
2605                | GenerationFilter::VertexVeto(selectors) => {
2606                    for selector in selectors {
2607                        selector.resolve(&self.model)?;
2608                    }
2609                }
2610                GenerationFilter::CouplingOrders(required) => {
2611                    for name in required.keys() {
2612                        self.model.order(name)?;
2613                    }
2614                }
2615                GenerationFilter::PerturbativeOrders(required) => {
2616                    for name in required.keys() {
2617                        self.model.order(name)?;
2618                    }
2619                }
2620                GenerationFilter::SelfEnergy(_)
2621                | GenerationFilter::Tadpoles(_)
2622                | GenerationFilter::ZeroSnails(_)
2623                | GenerationFilter::Sewn(_)
2624                | GenerationFilter::MaxNumberOfBridges(_)
2625                | GenerationFilter::LoopOneParticleIrreducible
2626                | GenerationFilter::LoopCountRange(_)
2627                | GenerationFilter::BlobRange(_)
2628                | GenerationFilter::SpectatorRange(_)
2629                | GenerationFilter::FermionLoopCountRange(_)
2630                | GenerationFilter::FactorizedLoopTopologiesCountRange(_) => {}
2631            }
2632        }
2633        Ok(())
2634    }
2635
2636    fn validate_filter_range(
2637        &self,
2638        scope: FilterScope,
2639        filter: &GenerationFilter,
2640    ) -> Result<(), GenerationError> {
2641        let invalid = match filter {
2642            GenerationFilter::CouplingOrders(required) => {
2643                required
2644                    .values()
2645                    .find_map(|(minimum, maximum)| match maximum {
2646                        Some(maximum) if minimum > maximum => Some((*minimum, *maximum)),
2647                        _ => None,
2648                    })
2649            }
2650            GenerationFilter::LoopCountRange((minimum, maximum))
2651            | GenerationFilter::FermionLoopCountRange((minimum, maximum))
2652            | GenerationFilter::FactorizedLoopTopologiesCountRange((minimum, maximum)) => {
2653                (minimum > maximum).then_some((*minimum, *maximum))
2654            }
2655            GenerationFilter::BlobRange(range) | GenerationFilter::SpectatorRange(range) => {
2656                (range.start() > range.end()).then_some((*range.start(), *range.end()))
2657            }
2658            GenerationFilter::SelfEnergy(_)
2659            | GenerationFilter::Tadpoles(_)
2660            | GenerationFilter::ZeroSnails(_)
2661            | GenerationFilter::Sewn(_)
2662            | GenerationFilter::ParticleVeto(_)
2663            | GenerationFilter::VertexAllow(_)
2664            | GenerationFilter::VertexVeto(_)
2665            | GenerationFilter::MaxNumberOfBridges(_)
2666            | GenerationFilter::LoopOneParticleIrreducible
2667            | GenerationFilter::PerturbativeOrders(_) => None,
2668        };
2669        if let Some((minimum, maximum)) = invalid {
2670            return Err(GenerationError::InvalidFilterRange {
2671                scope,
2672                filter: filter.kind(),
2673                minimum,
2674                maximum,
2675            });
2676        }
2677        Ok(())
2678    }
2679
2680    fn assign_interactions(
2681        &self,
2682        graph: &Graph<NodeColor, EdgeColor>,
2683        signatures: &InteractionSignatures,
2684        has_interchangeable_externals: bool,
2685    ) -> Result<Vec<InteractionAssignment>, GenerationError> {
2686        let mut assignments: Vec<Vec<ColoredNode>> = vec![Vec::new()];
2687        for (node_index, node) in graph.nodes().iter().enumerate() {
2688            let choices = if let Some(external) = &node.data.external {
2689                vec![ColoredNode::External(external.clone())]
2690            } else {
2691                let mut signature = Vec::new();
2692                for edge_id in &node.edges {
2693                    let edge = &graph.edges()[*edge_id];
2694                    let direction = edge.directed.then_some(edge.vertices.0 == node_index);
2695                    signature.push(EdgeColor {
2696                        particle: edge.data.particle,
2697                        direction,
2698                    });
2699                    // A self-loop contributes both half-edges to the
2700                    // interaction signature.
2701                    if edge.vertices.0 == edge.vertices.1 {
2702                        signature.push(EdgeColor {
2703                            particle: edge.data.particle,
2704                            direction: direction.map(|value| !value),
2705                        });
2706                    }
2707                }
2708                signature.sort();
2709                signatures
2710                    .rules(&signature)
2711                    .ok_or_else(|| GenerationError::MissingInteraction {
2712                        node: node_index,
2713                        signature: signature
2714                            .iter()
2715                            .map(|edge| {
2716                                format!("{:?}:particle#{}", edge.direction, edge.particle.index())
2717                            })
2718                            .collect(),
2719                    })?
2720                    .iter()
2721                    .cloned()
2722                    .map(ColoredNode::Interaction)
2723                    .collect()
2724            };
2725
2726            assignments = assignments
2727                .into_iter()
2728                .flat_map(|assignment| {
2729                    choices.iter().cloned().map(move |choice| {
2730                        let mut next = assignment.clone();
2731                        next.push(choice);
2732                        next
2733                    })
2734                })
2735                .collect();
2736        }
2737
2738        let mut grouped = BTreeMap::new();
2739        for assignment in assignments {
2740            let mut colored = Graph::new();
2741            for node in assignment {
2742                colored.add_node(node);
2743            }
2744            for edge in graph.edges() {
2745                colored
2746                    .add_edge(edge.vertices.0, edge.vertices.1, edge.directed, edge.data)
2747                    .map_err(|error| GenerationError::GraphConstruction(error.to_string()))?;
2748            }
2749            *grouped.entry(colored.canonize().graph).or_insert(0) += 1;
2750        }
2751        if !has_interchangeable_externals || grouped.len() < 2 {
2752            return Ok(grouped.into_iter().collect());
2753        }
2754        // Symbolica returns one topology per orbit of the interchangeable
2755        // external legs. Assignments related by such a permutation belong to
2756        // the same orbit, represented by its smallest labelled form.
2757        let classes = graph
2758            .nodes()
2759            .iter()
2760            .filter_map(|node| {
2761                let external = node.data.external.as_ref()?;
2762                Some((external.index, node.data.clone()))
2763            })
2764            .collect::<BTreeMap<_, _>>();
2765        let mut orbits = BTreeMap::new();
2766        for (colored, count) in grouped {
2767            let mut interchangeable = Graph::new();
2768            for node in colored.nodes() {
2769                interchangeable.add_node(match &node.data {
2770                    ColoredNode::External(external) => (classes[&external.index].clone(), None),
2771                    ColoredNode::Interaction(rule) => (NodeColor::default(), Some(*rule)),
2772                });
2773            }
2774            for edge in colored.edges() {
2775                interchangeable
2776                    .add_edge(edge.vertices.0, edge.vertices.1, edge.directed, edge.data)
2777                    .map_err(|error| GenerationError::GraphConstruction(error.to_string()))?;
2778            }
2779            orbits
2780                .entry(interchangeable.canonize().graph)
2781                .and_modify(|(_, total)| *total += count)
2782                .or_insert((colored, count));
2783        }
2784        Ok(orbits.into_values().collect())
2785    }
2786
2787    fn passes_topology_filters(
2788        &self,
2789        graph: &Graph<NodeColor, EdgeColor>,
2790        options: &GenerationOptions,
2791    ) -> Result<bool, GenerationError> {
2792        let self_energy = options
2793            .graph_filters
2794            .iter()
2795            .find_map(|filter| match filter {
2796                GenerationFilter::SelfEnergy(options) => Some(options),
2797                _ => None,
2798            });
2799        let tadpoles = options
2800            .graph_filters
2801            .iter()
2802            .find_map(|filter| match filter {
2803                GenerationFilter::Tadpoles(options) => Some(options),
2804                _ => None,
2805            });
2806        let zero_snails = options
2807            .graph_filters
2808            .iter()
2809            .find_map(|filter| match filter {
2810                GenerationFilter::ZeroSnails(options) => Some(options),
2811                _ => None,
2812            });
2813        let factorized_loop_range = options
2814            .graph_filters
2815            .iter()
2816            .find_map(|filter| match filter {
2817                GenerationFilter::FactorizedLoopTopologiesCountRange(range) => Some(range),
2818                _ => None,
2819            });
2820        if self.veto_special_topologies(
2821            graph,
2822            self_energy,
2823            tadpoles,
2824            zero_snails,
2825            factorized_loop_range,
2826        )? {
2827            return Ok(false);
2828        }
2829
2830        for filter in &options.graph_filters {
2831            match filter {
2832                GenerationFilter::LoopOneParticleIrreducible if graph.num_loops() > 0 => {
2833                    let mut tree = graph.get_spanning_tree(0);
2834                    tree.chain_decomposition();
2835                    if tree.count_bridges() != 0 {
2836                        return Ok(false);
2837                    }
2838                }
2839                GenerationFilter::ParticleVeto(vetoed)
2840                    if graph.edges().iter().any(|edge| {
2841                        vetoed.iter().any(|selector| match selector {
2842                            ParticleSelector::Id { particle, .. } => {
2843                                *particle == edge.data.particle
2844                                    || self.model.particle_by_id(*particle).is_ok_and(|selected| {
2845                                        selected.antiparticle == edge.data.particle
2846                                    })
2847                            }
2848                            ParticleSelector::Name(_) | ParticleSelector::Pdg(_) => {
2849                                unreachable!("generation selectors are resolved before use")
2850                            }
2851                        })
2852                    }) =>
2853                {
2854                    return Ok(false);
2855                }
2856                GenerationFilter::LoopCountRange((minimum, maximum))
2857                    if !(*minimum..=*maximum).contains(&graph.num_loops()) =>
2858                {
2859                    return Ok(false);
2860                }
2861                GenerationFilter::ParticleVeto(_)
2862                | GenerationFilter::VertexAllow(_)
2863                | GenerationFilter::VertexVeto(_)
2864                | GenerationFilter::MaxNumberOfBridges(_)
2865                | GenerationFilter::LoopOneParticleIrreducible
2866                | GenerationFilter::CouplingOrders(_)
2867                | GenerationFilter::LoopCountRange(_)
2868                | GenerationFilter::FermionLoopCountRange(_)
2869                | GenerationFilter::SelfEnergy(_)
2870                | GenerationFilter::Tadpoles(_)
2871                | GenerationFilter::ZeroSnails(_)
2872                | GenerationFilter::Sewn(_)
2873                | GenerationFilter::BlobRange(_)
2874                | GenerationFilter::SpectatorRange(_)
2875                | GenerationFilter::FactorizedLoopTopologiesCountRange(_)
2876                | GenerationFilter::PerturbativeOrders(_) => {}
2877            }
2878        }
2879        Ok(true)
2880    }
2881
2882    fn veto_special_topologies(
2883        &self,
2884        graph: &Graph<NodeColor, EdgeColor>,
2885        veto_self_energy: Option<&SelfEnergyFilterOptions>,
2886        veto_tadpole: Option<&TadpoleFilterOptions>,
2887        veto_snails: Option<&SnailFilterOptions>,
2888        factorized_loop_topologies_count_range: Option<&(usize, usize)>,
2889    ) -> Result<bool, GenerationError> {
2890        if veto_self_energy.is_none()
2891            && veto_tadpole.is_none()
2892            && veto_snails.is_none()
2893            && factorized_loop_topologies_count_range.is_none()
2894        {
2895            return Ok(false);
2896        }
2897
2898        let external_nodes: Vec<_> = graph
2899            .nodes()
2900            .iter()
2901            .enumerate()
2902            .filter_map(|(index, node)| node.data.external.as_ref().map(|_| index))
2903            .collect();
2904        if graph.nodes().is_empty() {
2905            return Ok(factorized_loop_topologies_count_range
2906                .is_some_and(|range| !(range.0..=range.1).contains(&0)));
2907        }
2908        let roots: Vec<_> = if external_nodes.is_empty() {
2909            vec![0]
2910        } else {
2911            external_nodes
2912        };
2913        let mut external_particles = BTreeMap::new();
2914        for (node_index, node) in graph.nodes().iter().enumerate() {
2915            if let Some(external) = &node.data.external {
2916                let edge_id = node
2917                    .edges
2918                    .first()
2919                    .ok_or(GenerationError::MissingExternalEdge { node: node_index })?;
2920                let edge = &graph.edges()[*edge_id];
2921                external_particles.insert(
2922                    external.index,
2923                    self.model.particle_by_id(edge.data.particle)?,
2924                );
2925            }
2926        }
2927
2928        // Test vetoing from all external spanning-tree root positions to make
2929        // sure the result does not depend on spanning-tree directions.
2930        // TODO rewrite and improve the vetoing logic of special topologies.
2931        for root in roots {
2932            if !self.veto_special_topologies_with_spanning_tree_root(
2933                graph,
2934                veto_self_energy,
2935                veto_tadpole,
2936                veto_snails,
2937                factorized_loop_topologies_count_range,
2938                &external_particles,
2939                root,
2940            )? {
2941                return Ok(false);
2942            }
2943        }
2944        Ok(true)
2945    }
2946
2947    #[allow(clippy::too_many_arguments)]
2948    fn veto_special_topologies_with_spanning_tree_root(
2949        &self,
2950        graph: &Graph<NodeColor, EdgeColor>,
2951        veto_self_energy: Option<&SelfEnergyFilterOptions>,
2952        veto_tadpole: Option<&TadpoleFilterOptions>,
2953        veto_snails: Option<&SnailFilterOptions>,
2954        factorized_loop_topologies_count_range: Option<&(usize, usize)>,
2955        external_particles: &BTreeMap<usize, &Particle>,
2956        spanning_tree_root: usize,
2957    ) -> Result<bool, GenerationError> {
2958        let max_external = external_particles.len();
2959        let spanning_tree_node_external_index = graph.nodes()[spanning_tree_root]
2960            .data
2961            .external
2962            .as_ref()
2963            .map(|external| external.index);
2964        let mut spanning_tree = graph.get_spanning_tree(spanning_tree_root);
2965        spanning_tree.chain_decomposition();
2966
2967        let mut node_children = vec![vec![]; spanning_tree.nodes.len()];
2968        for (node_index, node) in spanning_tree.nodes.iter().enumerate() {
2969            node_children[node.parent].push(node_index);
2970        }
2971
2972        let mut external_momenta_routing = vec![vec![]; spanning_tree.nodes.len()];
2973        for (node_index, node) in graph.nodes().iter().enumerate() {
2974            let Some(external) = &node.data.external else {
2975                continue;
2976            };
2977            if node_index == spanning_tree_root {
2978                continue;
2979            }
2980            external_momenta_routing[node_index].push(external.index);
2981            let mut next_node = spanning_tree.nodes[node_index].parent;
2982            while next_node != spanning_tree_root {
2983                external_momenta_routing[next_node].push(external.index);
2984                next_node = spanning_tree.nodes[next_node].parent;
2985            }
2986        }
2987        if let Some(root_external_index) = spanning_tree_node_external_index {
2988            for route in &mut external_momenta_routing {
2989                if route.len() == max_external - 1 {
2990                    *route = vec![root_external_index];
2991                }
2992            }
2993        }
2994
2995        // See https://arxiv.org/pdf/1209.0700 for information on the logic of
2996        // this algorithm.
2997
2998        // Tuple format: (external leg id, back-edge start node position,
2999        // back-edge position in list, chain id).
3000        let mut self_energy_attachments: HashSet<(usize, usize, usize, usize)> = HashSet::new();
3001        // Tuple format: (back-edge start node position, back-edge position in
3002        // list, chain id).
3003        let mut vacuum_attachments: HashSet<(usize, usize, usize)> = HashSet::new();
3004        // Tuple format: (back-edge start node position, back-edge position in
3005        // list, chain id).
3006        let mut self_loops: HashSet<(usize, usize, usize)> = HashSet::new();
3007        let mut factorized_loop_count = 0;
3008
3009        let mut visited_nodes = vec![false; spanning_tree.nodes.len()];
3010        for &node_index in &spanning_tree.order {
3011            let node = &spanning_tree.nodes[node_index];
3012            for (back_edge_index, back_edge) in node.back_edges.iter().enumerate() {
3013                let chain_id = node_index;
3014                if back_edge.target == node_index {
3015                    factorized_loop_count += 1;
3016                    self_loops.insert((node_index, back_edge_index, chain_id));
3017                    continue;
3018                }
3019                let mut self_energy_external_leg_id = None;
3020                let mut current_chain_node = back_edge.target;
3021                let mut is_valid_chain = true;
3022                loop {
3023                    if current_chain_node == node_index {
3024                        factorized_loop_count += 1;
3025                        break;
3026                    }
3027                    let momenta = &external_momenta_routing[current_chain_node];
3028                    if momenta.len() == 1 {
3029                        if self_energy_external_leg_id.is_some_and(|leg_id| leg_id != momenta[0]) {
3030                            is_valid_chain = false;
3031                            break;
3032                        }
3033                        self_energy_external_leg_id = Some(momenta[0]);
3034                        for child in &node_children[current_chain_node] {
3035                            if !external_momenta_routing[*child].is_empty()
3036                                && external_momenta_routing[*child][0] != momenta[0]
3037                            {
3038                                is_valid_chain = false;
3039                                break;
3040                            }
3041                        }
3042                        if !is_valid_chain {
3043                            break;
3044                        }
3045                    } else if !momenta.is_empty() {
3046                        is_valid_chain = false;
3047                        break;
3048                    }
3049                    if spanning_tree.nodes[current_chain_node].chain_id.is_none()
3050                        || visited_nodes[current_chain_node]
3051                    {
3052                        is_valid_chain = false;
3053                        break;
3054                    }
3055                    visited_nodes[current_chain_node] = true;
3056                    current_chain_node = spanning_tree.nodes[current_chain_node].parent;
3057                }
3058
3059                if is_valid_chain {
3060                    if let Some(leg_id) = self_energy_external_leg_id {
3061                        // Make sure the self-energy attachment point does not
3062                        // receive any other external momenta. For 1 -> 1
3063                        // processes, also verify that it is not the whole graph.
3064                        if external_momenta_routing[node_index].as_slice() == [leg_id]
3065                            && (max_external > 2
3066                                || spanning_tree
3067                                    .nodes
3068                                    .iter()
3069                                    .filter(|node| !node.external && node.chain_id.is_none())
3070                                    .count()
3071                                    > 1)
3072                        {
3073                            self_energy_attachments.insert((
3074                                leg_id,
3075                                node_index,
3076                                back_edge_index,
3077                                chain_id,
3078                            ));
3079                        }
3080                    } else {
3081                        vacuum_attachments.insert((node_index, back_edge_index, chain_id));
3082                    }
3083                }
3084            }
3085        }
3086
3087        if factorized_loop_topologies_count_range.is_some_and(|(minimum, maximum)| {
3088            factorized_loop_count < *minimum || factorized_loop_count > *maximum
3089        }) {
3090            return Ok(true);
3091        }
3092
3093        let mut tree_bridge_node_indices = HashSet::new();
3094        for (node_index, node) in spanning_tree.nodes.iter().enumerate() {
3095            if node.chain_id.is_none()
3096                && !node.external
3097                && !external_momenta_routing[node_index].is_empty()
3098                && !spanning_tree.nodes[node.parent]
3099                    .back_edges
3100                    .iter()
3101                    .any(|end| node_index == end.target)
3102            {
3103                tree_bridge_node_indices.insert(node_index);
3104            }
3105        }
3106
3107        // Confirm self-energies by checking that the back-edge start node is a
3108        // bridge.
3109        for (leg_id, back_edge_start_node_index, _, _) in &self_energy_attachments {
3110            if tree_bridge_node_indices.contains(back_edge_start_node_index)
3111                && let Some(options) = veto_self_energy
3112            {
3113                let particle = external_particles
3114                    .get(leg_id)
3115                    .ok_or(GenerationError::MissingExternalParticle { index: *leg_id })?;
3116                let massless = self
3117                    .model
3118                    .particle_is_massless(self.model.particle_id(&particle.name)?);
3119                if (!massless && options.veto_massive) || (massless && options.veto_massless) {
3120                    return Ok(true);
3121                }
3122            }
3123        }
3124
3125        // For vacuum attachments, differentiate snails (the start node is a
3126        // tree bridge) from tadpoles (the start node is not a tree bridge).
3127        for (back_edge_start_node_index, _, _) in vacuum_attachments.iter().chain(self_loops.iter())
3128        {
3129            let attachment_particle_is_massive = if max_external > 0 {
3130                let mut first_tree_attachment_node_index = *back_edge_start_node_index;
3131                while external_momenta_routing[first_tree_attachment_node_index].is_empty()
3132                    && spanning_tree.nodes[first_tree_attachment_node_index]
3133                        .chain_id
3134                        .is_none()
3135                {
3136                    first_tree_attachment_node_index =
3137                        spanning_tree.nodes[first_tree_attachment_node_index].parent;
3138                }
3139                let parent = spanning_tree.nodes[first_tree_attachment_node_index].parent;
3140                let edge = graph
3141                    .edges()
3142                    .iter()
3143                    .find(|edge| {
3144                        edge.vertices == (first_tree_attachment_node_index, parent)
3145                            || edge.vertices == (parent, first_tree_attachment_node_index)
3146                    })
3147                    .ok_or(GenerationError::MissingSpanningTreeEdge {
3148                        node: first_tree_attachment_node_index,
3149                        parent,
3150                    })?;
3151                !self.model.particle_is_massless(edge.data.particle)
3152            } else {
3153                // Always consider the attachment particle massive for vacuum
3154                // graphs: without external legs there is no supported way to
3155                // differentiate massive and massless attachments.
3156                true
3157            };
3158
3159            if !tree_bridge_node_indices.contains(back_edge_start_node_index)
3160                && spanning_tree.nodes[*back_edge_start_node_index]
3161                    .chain_id
3162                    .is_none()
3163            {
3164                if let Some(options) = veto_tadpole
3165                    && ((attachment_particle_is_massive && options.veto_attached_to_massive)
3166                        || (!attachment_particle_is_massive && options.veto_attached_to_massless))
3167                {
3168                    return Ok(true);
3169                }
3170            } else if let Some(options) = veto_snails
3171                && ((attachment_particle_is_massive && options.veto_attached_to_massive)
3172                    || (!attachment_particle_is_massive && options.veto_attached_to_massless))
3173            {
3174                return Ok(true);
3175            }
3176        }
3177
3178        Ok(false)
3179    }
3180
3181    fn passes_interaction_filters(
3182        &self,
3183        graph: &Graph<ColoredNode, EdgeColor>,
3184        fermion_loop_count: usize,
3185        options: &GenerationOptions,
3186    ) -> Result<bool, GenerationError> {
3187        for filter in &options.graph_filters {
3188            match filter {
3189                GenerationFilter::CouplingOrders(required) => {
3190                    let actual = self.coupling_orders(graph)?;
3191                    if !required.iter().all(|(name, (minimum, maximum))| {
3192                        let value = actual.get(name).copied().unwrap_or(0);
3193                        value >= *minimum && maximum.is_none_or(|maximum| value <= maximum)
3194                    }) {
3195                        return Ok(false);
3196                    }
3197                }
3198                GenerationFilter::FermionLoopCountRange((minimum, maximum)) => {
3199                    if !(*minimum..=*maximum).contains(&fermion_loop_count) {
3200                        return Ok(false);
3201                    }
3202                }
3203                GenerationFilter::VertexAllow(selectors) => {
3204                    let allowed = selectors
3205                        .iter()
3206                        .map(|selector| match selector {
3207                            VertexSelector::Id { vertex, .. } => *vertex,
3208                            VertexSelector::Name(_) => {
3209                                unreachable!("generation selectors are resolved before use")
3210                            }
3211                        })
3212                        .collect::<BTreeSet<_>>();
3213                    if graph.nodes().iter().any(|node| {
3214                        matches!(
3215                            node.data,
3216                            ColoredNode::Interaction(rule) if !allowed.contains(&rule)
3217                        )
3218                    }) {
3219                        return Ok(false);
3220                    }
3221                }
3222                GenerationFilter::VertexVeto(selectors) => {
3223                    let vetoed = selectors
3224                        .iter()
3225                        .map(|selector| match selector {
3226                            VertexSelector::Id { vertex, .. } => *vertex,
3227                            VertexSelector::Name(_) => {
3228                                unreachable!("generation selectors are resolved before use")
3229                            }
3230                        })
3231                        .collect::<BTreeSet<_>>();
3232                    if graph.nodes().iter().any(|node| {
3233                        matches!(
3234                            node.data,
3235                            ColoredNode::Interaction(rule) if vetoed.contains(&rule)
3236                        )
3237                    }) {
3238                        return Ok(false);
3239                    }
3240                }
3241                GenerationFilter::ParticleVeto(_)
3242                | GenerationFilter::MaxNumberOfBridges(_)
3243                | GenerationFilter::LoopOneParticleIrreducible
3244                | GenerationFilter::LoopCountRange(_)
3245                | GenerationFilter::SelfEnergy(_)
3246                | GenerationFilter::Tadpoles(_)
3247                | GenerationFilter::ZeroSnails(_)
3248                | GenerationFilter::Sewn(_)
3249                | GenerationFilter::BlobRange(_)
3250                | GenerationFilter::SpectatorRange(_)
3251                | GenerationFilter::FactorizedLoopTopologiesCountRange(_)
3252                | GenerationFilter::PerturbativeOrders(_) => {}
3253            }
3254        }
3255        Ok(true)
3256    }
3257
3258    fn retain_cut_amplitude_cuts(
3259        cuts: &mut Vec<DiagramCut>,
3260        options: &GenerationOptions,
3261    ) -> Result<bool, GenerationError> {
3262        let mut retained = Vec::with_capacity(cuts.len());
3263        for partition in cuts.drain(..) {
3264            let mut passes = true;
3265            for filter in &options.cut_amplitude_filters {
3266                passes &= match filter {
3267                    GenerationFilter::CouplingOrders(required) => {
3268                        [&partition.left, &partition.right].iter().all(|side| {
3269                            required.iter().all(|(name, (minimum, maximum))| {
3270                                let value = side.coupling_orders.get(name).copied().unwrap_or(0);
3271                                value >= *minimum && maximum.is_none_or(|maximum| value <= maximum)
3272                            })
3273                        })
3274                    }
3275                    // The amplitude loop filter constrains the sum of the loop
3276                    // counts on both sides of the cut, matching GammaLoop's
3277                    // cross-section generation semantics.
3278                    GenerationFilter::LoopCountRange((minimum, maximum)) => (*minimum..=*maximum)
3279                        .contains(&(partition.left.loop_count + partition.right.loop_count)),
3280                    _ => {
3281                        return Err(GenerationError::InvalidFilterScope {
3282                            scope: FilterScope::CutAmplitude,
3283                            filter: filter.kind(),
3284                            generation_type: GenerationType::CrossSection,
3285                        });
3286                    }
3287                };
3288            }
3289            if passes {
3290                retained.push(partition);
3291            }
3292        }
3293        *cuts = retained;
3294        Ok(!cuts.is_empty())
3295    }
3296
3297    fn coupling_orders(
3298        &self,
3299        graph: &Graph<ColoredNode, EdgeColor>,
3300    ) -> Result<BTreeMap<String, usize>, GenerationError> {
3301        let mut result = BTreeMap::new();
3302        for node in graph.nodes() {
3303            let ColoredNode::Interaction(rule_id) = &node.data else {
3304                continue;
3305            };
3306            let rule = self.model.vertex_rule_by_id(*rule_id)?;
3307            for (name, order) in rule.coupling_orders(&self.model) {
3308                *result.entry(name).or_insert(0) += order;
3309            }
3310        }
3311        Ok(result)
3312    }
3313
3314    // Count closed, non-branching fermion components, optionally including ghosts
3315    // for the Grassmann sign. The fermion-loop filter excludes ghosts. Branching
3316    // components are rejected explicitly below.
3317    fn closed_fermion_loop_count(
3318        &self,
3319        graph: &Graph<ColoredNode, EdgeColor>,
3320        include_ghosts: bool,
3321    ) -> Result<usize, GenerationError> {
3322        let mut adjacency = vec![Vec::new(); graph.nodes().len()];
3323        let mut degrees = vec![0; graph.nodes().len()];
3324        // Build adjacency using only the selected Grassmann edges. A self-loop
3325        // contributes degree two.
3326        for edge in graph.edges() {
3327            let particle = self.model.particle_by_id(edge.data.particle)?;
3328            if !(particle.is_fermion() && !particle.is_ghost()
3329                || include_ghosts && particle.is_ghost())
3330            {
3331                continue;
3332            }
3333            let (left, right) = edge.vertices;
3334            if left == right {
3335                degrees[left] += 2;
3336                adjacency[left].push(right);
3337            } else {
3338                degrees[left] += 1;
3339                degrees[right] += 1;
3340                adjacency[left].push(right);
3341                adjacency[right].push(left);
3342            }
3343        }
3344
3345        for (vertex, degree) in degrees.iter().copied().enumerate() {
3346            if degree > 2 {
3347                return Err(GenerationError::UnsupportedFermionBranching { vertex, degree });
3348            }
3349        }
3350
3351        let mut visited = vec![false; graph.nodes().len()];
3352        let mut closed_loops = 0;
3353        for start in 0..graph.nodes().len() {
3354            if degrees[start] == 0 || visited[start] {
3355                continue;
3356            }
3357            let mut stack = vec![start];
3358            let mut closed = true;
3359            while let Some(vertex) = stack.pop() {
3360                if visited[vertex] {
3361                    continue;
3362                }
3363                visited[vertex] = true;
3364                closed &= degrees[vertex] == 2;
3365                stack.extend(
3366                    adjacency[vertex]
3367                        .iter()
3368                        .copied()
3369                        .filter(|neighbor| !visited[*neighbor]),
3370                );
3371            }
3372            closed_loops += usize::from(closed);
3373        }
3374        Ok(closed_loops)
3375    }
3376
3377    fn to_diagram(
3378        &self,
3379        name: String,
3380        generation_type: GenerationType,
3381        topology: ColoredTopology,
3382        external_permutations: u64,
3383        fermion_signs: FermionSigns,
3384        options: &GenerationOptions,
3385    ) -> Result<FeynmanDiagram, GenerationError> {
3386        // Symbolica's automorphism factor is a denominator in the overall
3387        // multiplier. It treats interchangeable external legs as identical,
3388        // so an orbit representative also carries the order of their
3389        // permutation group.
3390        let mut factors = vec![FACTOR_HEADS.aut_g.call(topology.symmetry).pow(-1)];
3391        if external_permutations != 1 {
3392            factors.push(
3393                FACTOR_HEADS
3394                    .numerator_independent_symmetry_grouping
3395                    .call(external_permutations),
3396            );
3397        }
3398        if topology.multiplicity != 1 {
3399            factors.push(
3400                FACTOR_HEADS
3401                    .couplings_multiplicity
3402                    .call(topology.multiplicity),
3403            );
3404        }
3405        if fermion_signs.internal_loop_negative {
3406            factors.push(FACTOR_HEADS.internal_fermion_loop_sign.call(-1));
3407        }
3408        if fermion_signs.include_external_ordering {
3409            let sign = if fermion_signs.external_ordering_negative {
3410                -1
3411            } else {
3412                1
3413            };
3414            factors.push(FACTOR_HEADS.external_fermion_ordering_sign.call(sign));
3415        }
3416        if fermion_signs.include_antifermion_spin_sum {
3417            let sign = if fermion_signs.antifermion_spin_sum_negative {
3418                -1
3419            } else {
3420                1
3421            };
3422            factors.push(FACTOR_HEADS.antifermion_spin_sum_sign.call(sign));
3423        }
3424        let overall_factor = Atom::mul_many(factors);
3425        let incoming_count = topology
3426            .graph
3427            .nodes()
3428            .iter()
3429            .filter(|node| {
3430                matches!(
3431                    node.data,
3432                    ColoredNode::External(ExternalNode {
3433                        state: ExternalState::Incoming,
3434                        ..
3435                    })
3436                )
3437            })
3438            .count();
3439        let projector = self.external_state_projector(
3440            &topology.graph,
3441            generation_type,
3442            options.projector.as_ref(),
3443        )?;
3444        let mut builder = FeynmanDiagram::builder(Arc::clone(&self.model), name)
3445            .canonical_loop_momentum_basis()
3446            .symmetry_factor(topology.symmetry)
3447            .overall_factor(overall_factor)
3448            .numerator_prefactor(NumeratorInterface::admit(
3449                options.numerator_prefactor.clone(),
3450                None,
3451            )?)
3452            .projector(projector)
3453            .cuts(topology.cut_partitions.clone())
3454            .topology_threshold_candidates(topology.topology_threshold_candidates.clone())
3455            .spectator_cuts(topology.spectator_cuts.clone());
3456        let mut endpoint_slots = BTreeMap::new();
3457        for (index, node) in topology.graph.nodes().iter().enumerate() {
3458            let vertex = match &node.data {
3459                ColoredNode::External(external) => {
3460                    let connection = match (generation_type, external.state) {
3461                        (GenerationType::Amplitude, _) | (_, ExternalState::Incoming) => {
3462                            external.index
3463                        }
3464                        (GenerationType::CrossSection, ExternalState::Outgoing) => external
3465                            .index
3466                            .checked_sub(incoming_count)
3467                            .ok_or(GenerationError::MissingExternalParticle {
3468                                index: external.index,
3469                            })?,
3470                    };
3471                    builder.add_generation_external(
3472                        format!("ext{}", external.index),
3473                        external.index,
3474                        external.state,
3475                        connection,
3476                    );
3477                    continue;
3478                }
3479                ColoredNode::Interaction(rule_id) => {
3480                    let rule = self.model.vertex_rule_by_id(*rule_id)?;
3481                    let legs = self.interaction_half_edges(&topology.graph, index, rule)?;
3482                    for (slot, leg) in legs.iter().enumerate() {
3483                        endpoint_slots.insert((leg.edge, leg.flow), VertexSlot(slot));
3484                    }
3485                    DiagramVertex::interaction(format!("v{index}"), *rule_id)
3486                }
3487            };
3488            builder.add_vertex(vertex);
3489        }
3490        for (edge_index, edge) in topology.graph.edges().iter().enumerate() {
3491            let diagram_edge = DiagramEdge::new(edge.data.particle, edge.directed);
3492            let source_slot = endpoint_slots
3493                .get(&(edge_index, Flow::Source))
3494                .copied()
3495                .unwrap_or(VertexSlot(0));
3496            let target_slot = endpoint_slots
3497                .get(&(edge_index, Flow::Sink))
3498                .copied()
3499                .unwrap_or(VertexSlot(0));
3500            builder.add_edge_with_slots(
3501                feynkit_graph::VertexId(edge.vertices.0),
3502                feynkit_graph::VertexId(edge.vertices.1),
3503                diagram_edge,
3504                source_slot,
3505                target_slot,
3506            )?;
3507        }
3508        let diagram = builder.build()?;
3509        self.construct_numerators(diagram)
3510    }
3511
3512    fn construct_numerators(
3513        &self,
3514        diagram: FeynmanDiagram,
3515    ) -> Result<FeynmanDiagram, GenerationError> {
3516        // Instantiate directly in the finalized frame. This avoids building
3517        // every factor in provisional indices and then translating it again.
3518        let mut vertices = Vec::new();
3519        for (vertex, data) in diagram.vertices() {
3520            let Some(rule_id) = data.interaction else {
3521                continue;
3522            };
3523            let rule = self.model.vertex_rule_by_id(rule_id)?;
3524            let mut legs = vec![None; rule.particles.len()];
3525            for (edge, endpoints, data) in diagram.edges() {
3526                for (attached, slot, endpoint, flow) in [
3527                    (
3528                        endpoints.source,
3529                        data.source_slot(),
3530                        DiagramEndpoint::Source,
3531                        Flow::Source,
3532                    ),
3533                    (
3534                        endpoints.target,
3535                        data.target_slot(),
3536                        DiagramEndpoint::Target,
3537                        Flow::Sink,
3538                    ),
3539                ] {
3540                    if attached != Some(vertex) {
3541                        continue;
3542                    }
3543                    let particle = self.model.particle_by_id(rule.particles[slot.0])?;
3544                    let hedge = diagram
3545                        .half_edge_id(DiagramHalfEdge { edge, endpoint })
3546                        .expect("finalized endpoint")
3547                        .0;
3548                    legs[slot.0] = Some(NumeratorHalfEdge {
3549                        edge: edge.0,
3550                        hedge,
3551                        flow,
3552                        spin: particle.spin,
3553                        color: particle.color,
3554                    });
3555                }
3556            }
3557            let legs = legs
3558                .into_iter()
3559                .map(|leg| leg.expect("assigned interaction slot"))
3560                .collect::<Vec<_>>();
3561            let instantiation = NumeratorInstantiation {
3562                owner: NumeratorOwner::Vertex(vertex.0),
3563                legs: &legs,
3564            };
3565            vertices.push((vertex, self.interaction_numerator(rule_id, &instantiation)?));
3566        }
3567        let mut edges = Vec::new();
3568        for (edge, _, data) in diagram
3569            .edges()
3570            .filter(|(_, _, data)| data.external.is_none())
3571        {
3572            let hedges = [DiagramEndpoint::Source, DiagramEndpoint::Target].map(|endpoint| {
3573                diagram
3574                    .half_edge_id(DiagramHalfEdge { edge, endpoint })
3575                    .expect("internal edge endpoint")
3576                    .0
3577            });
3578            edges.push((edge, self.edge_numerator(data.particle, edge.0, hedges)?));
3579        }
3580        Ok(diagram.with_numerator_fragments(vertices, edges)?)
3581    }
3582
3583    fn external_state_projector(
3584        &self,
3585        graph: &Graph<ColoredNode, EdgeColor>,
3586        generation_type: GenerationType,
3587        supplied: Option<&Atom>,
3588    ) -> Result<SymbolicTensor<PartialStructure>, GenerationError> {
3589        let mut projector = Atom::one();
3590        let mut external_indices = BTreeMap::new();
3591        for (vertex, node) in graph.nodes().iter().enumerate() {
3592            let ColoredNode::External(external) = &node.data else {
3593                continue;
3594            };
3595            let edge_id = *node
3596                .edges
3597                .first()
3598                .ok_or(GenerationError::MissingExternalEdge { node: vertex })?;
3599            let edge = &graph.edges()[edge_id];
3600            let flow = if edge.vertices.0 == vertex {
3601                Flow::Sink
3602            } else {
3603                Flow::Source
3604            };
3605            let hedge = edge_id
3606                .checked_mul(2)
3607                .and_then(|index| index.checked_add(usize::from(flow == Flow::Sink)))
3608                .ok_or(GenerationError::ArithmeticOverflow(
3609                    "an external half-edge identifier",
3610                ))?;
3611            // A supplied projector names each leg's momentum in its process
3612            // direction, into the diagram for an incoming leg and out of it
3613            // for an outgoing one, as the finalized external edge is oriented.
3614            // Finalization negates the momentum of a provisional edge oriented
3615            // the other way, so that edge's carriers are negated here first.
3616            let reversed = (flow == Flow::Sink) != (external.state == ExternalState::Incoming);
3617            if supplied.is_some() || generation_type == GenerationType::CrossSection {
3618                external_indices.insert(external.index, (edge_id, hedge, reversed));
3619            }
3620            if supplied.is_none() {
3621                projector *=
3622                    self.external_wavefunction(external.state, external.particle, edge_id, hedge)?;
3623            }
3624        }
3625        let Some(supplied) = supplied else {
3626            if generation_type == GenerationType::CrossSection {
3627                let incoming = graph
3628                    .nodes()
3629                    .iter()
3630                    .filter_map(|node| match &node.data {
3631                        ColoredNode::External(external)
3632                            if external.state == ExternalState::Incoming =>
3633                        {
3634                            Some(external)
3635                        }
3636                        _ => None,
3637                    })
3638                    .collect::<Vec<_>>();
3639                for external in &incoming {
3640                    let outgoing_index = external.index.checked_add(incoming.len()).ok_or(
3641                        GenerationError::ArithmeticOverflow("a paired external index"),
3642                    )?;
3643                    let outgoing = external_indices.get(&outgoing_index).ok_or(
3644                        GenerationError::MissingExternalParticle {
3645                            index: outgoing_index,
3646                        },
3647                    )?;
3648                    // Sewing maps outgoing/source and incoming/target ends to
3649                    // one carrier. Its color identity belongs to the projector,
3650                    // while external edge numerator fragments remain unit.
3651                    projector *= self.external_color_sum(
3652                        external.particle,
3653                        [outgoing.1, external_indices[&external.index].1],
3654                    )?;
3655                }
3656            }
3657            return Ok(NumeratorInterface::admit(projector, None)?);
3658        };
3659        // Process-level expressions cannot know a topology's provisional IDs.
3660        // Resolve their external-leg owners before the finalizer transports the
3661        // resulting edge/half-edge chart. Native local UFO slots are unchanged.
3662        let hedge_head = symbols::hedge_index();
3663        let edge_head = symbols::edge_index();
3664        let momenta = [momentum_symbol(), symbols::spatial_momentum()];
3665        let carriers = [
3666            momentum_symbol(),
3667            symbols::spatial_momentum(),
3668            symbols::u(),
3669            symbols::ubar(),
3670            symbols::v(),
3671            symbols::vbar(),
3672            symbols::epsilon(),
3673            symbols::epsilonbar(),
3674        ];
3675        projector = supplied.clone();
3676        for carrier_pass in [false, true] {
3677            let mut unknown = None;
3678            projector = projector.replace_map(|part, _, output| {
3679                let AtomView::Fun(function) = part else {
3680                    return;
3681                };
3682                let head = function.get_symbol();
3683                let is_index = head == hedge_head || head == edge_head;
3684                if (carrier_pass && !carriers.contains(&head)) || (!carrier_pass && !is_index) {
3685                    return;
3686                }
3687                let Some(index) = function
3688                    .iter()
3689                    .next()
3690                    .and_then(|arg| usize::try_from(arg).ok())
3691                else {
3692                    return;
3693                };
3694                let Some(&(edge, hedge, reversed)) = external_indices.get(&index) else {
3695                    unknown = Some(index);
3696                    return;
3697                };
3698                let resolved = FunctionBuilder::new(head)
3699                    .add_arg(if head == hedge_head { hedge } else { edge })
3700                    .add_args(function.iter().skip(1))
3701                    .finish();
3702                **output = if reversed && momenta.contains(&head) {
3703                    -resolved
3704                } else {
3705                    resolved
3706                };
3707            });
3708            if let Some(index) = unknown {
3709                return Err(GenerationError::UnknownProjectorExternalIndex { index });
3710            }
3711        }
3712        Ok(NumeratorInterface::admit(projector, None)?)
3713    }
3714
3715    fn external_color_sum(
3716        &self,
3717        particle: ParticleId,
3718        hedges: [usize; 2],
3719    ) -> Result<Atom, GenerationError> {
3720        let particle = self.model.particle_by_id(particle)?;
3721        let indices = hedges.map(|hedge| symbols::hedge_index().call((hedge, 1_i64)));
3722        Ok(ColorSum::new(particle)
3723            .map_err(AmplitudeError::from)
3724            .map_err(Box::new)?
3725            .expression(indices))
3726    }
3727
3728    fn external_wavefunction(
3729        &self,
3730        state: ExternalState,
3731        particle: ParticleId,
3732        edge: usize,
3733        hedge: usize,
3734    ) -> Result<Atom, GenerationError> {
3735        let index = symbols::hedge_index().call((hedge, 1_i64));
3736        let particle = self.model.particle_by_id(particle)?;
3737        let (head, index) = match particle.spin {
3738            2 => {
3739                let head = match (state, particle.is_antiparticle()) {
3740                    (ExternalState::Incoming, false) => symbols::u(),
3741                    (ExternalState::Incoming, true) => symbols::vbar(),
3742                    (ExternalState::Outgoing, false) => symbols::ubar(),
3743                    (ExternalState::Outgoing, true) => symbols::v(),
3744                };
3745                (head, Bispinor {}.new_rep(4).to_symbolic([index]))
3746            }
3747            3 => {
3748                let head = match state {
3749                    ExternalState::Incoming => symbols::epsilon(),
3750                    ExternalState::Outgoing => symbols::epsilonbar(),
3751                };
3752                (head, Minkowski {}.new_rep(4).to_symbolic([index]))
3753            }
3754            _ => return Ok(Atom::one()),
3755        };
3756        Ok(FunctionBuilder::new(head)
3757            .add_arg(edge)
3758            .add_arg(index)
3759            .finish())
3760    }
3761
3762    fn interaction_half_edges(
3763        &self,
3764        graph: &Graph<ColoredNode, EdgeColor>,
3765        vertex: usize,
3766        rule: &VertexRule,
3767    ) -> Result<Vec<NumeratorHalfEdge>, GenerationError> {
3768        // Reconstruct the UFO particle order discarded by topology
3769        // canonicalization. Direction distinguishes particle and antiparticle
3770        // slots, while a self-loop contributes both of its half-edges.
3771        let mut available = available_interaction_half_edges(graph, vertex, &self.model)?;
3772
3773        let mut ordered = Vec::with_capacity(rule.particles.len());
3774        for (leg, particle_id) in rule.particles.iter().enumerate() {
3775            let particle = self.model.particle_by_id(*particle_id)?;
3776            let expected = ResolvedProcess::vertex_half_edge(&self.model, particle)?;
3777            let Some(position) = available
3778                .iter()
3779                .position(|(_, signature)| *signature == expected)
3780            else {
3781                return Err(GenerationError::MissingInteractionLeg {
3782                    vertex,
3783                    interaction: rule.name.clone(),
3784                    leg: leg + 1,
3785                    particle: particle.name.clone(),
3786                });
3787            };
3788            let mut selected = available.remove(position).0;
3789            selected.spin = particle.spin;
3790            selected.color = particle.color;
3791            ordered.push(selected);
3792        }
3793        Ok(ordered)
3794    }
3795
3796    fn propagator_numerator(&self, particle: &Particle) -> Result<(Atom, bool), GenerationError> {
3797        match self.model.particle_propagator(particle)? {
3798            Some((id, reversed)) => {
3799                Ok((self.model.propagator_by_id(id)?.numerator.clone(), reversed))
3800            }
3801            None => Ok((Atom::one(), false)),
3802        }
3803    }
3804
3805    fn interaction_numerator(
3806        &self,
3807        rule_id: VertexRuleId,
3808        instantiation: &NumeratorInstantiation<'_>,
3809    ) -> Result<SymbolicTensor<PartialStructure>, GenerationError> {
3810        let key = InteractionNumeratorKey {
3811            rule: rule_id,
3812            owner: instantiation.owner,
3813            legs: instantiation.legs.to_vec(),
3814        };
3815        if let Some(numerator) = self
3816            .numerators
3817            .interactions
3818            .read()
3819            .expect("numerator cache was poisoned; its retained tensors cannot be reused")
3820            .get(&key)
3821        {
3822            return Ok(numerator.clone());
3823        }
3824        let legs = instantiation
3825            .legs
3826            .iter()
3827            .enumerate()
3828            .map(|(index, leg)| NumeratorHalfEdge {
3829                edge: instantiation.legs[..index]
3830                    .iter()
3831                    .position(|previous| previous.edge == leg.edge)
3832                    .unwrap_or(index),
3833                hedge: index,
3834                ..*leg
3835            })
3836            .collect::<Vec<_>>();
3837        let template = self.interaction_template(rule_id, legs)?;
3838        let numerator = match &*template {
3839            NumeratorTemplate::Dynamic => NumeratorInterface::admit(
3840                self.interaction_expression(rule_id, instantiation)?,
3841                None,
3842            )?,
3843            NumeratorTemplate::Admitted { .. } => template.instantiate(instantiation)?,
3844        }
3845        // Raw rules declare no axis order. Named interfaces use the same
3846        // canonical convention after actual-owner admission and template
3847        // transport; leaf argument order continues to specify the tensor.
3848        .canonicalize_named_interface();
3849        self.numerators
3850            .interactions
3851            .write()
3852            .expect("numerator cache was poisoned; its retained tensors cannot be reused")
3853            .insert(key, numerator.clone());
3854        Ok(numerator)
3855    }
3856
3857    fn interaction_template(
3858        &self,
3859        rule_id: VertexRuleId,
3860        legs: Vec<NumeratorHalfEdge>,
3861    ) -> Result<Arc<NumeratorTemplate>, GenerationError> {
3862        let key = InteractionNumeratorKey {
3863            rule: rule_id,
3864            owner: NumeratorOwner::Vertex(0),
3865            legs,
3866        };
3867        if let Some(template) = self
3868            .numerators
3869            .interaction_templates
3870            .read()
3871            .expect("numerator cache was poisoned; its retained tensors cannot be reused")
3872            .get(&key)
3873        {
3874            return Ok(template.clone());
3875        }
3876        let distinct = key
3877            .legs
3878            .iter()
3879            .enumerate()
3880            .map(|(index, leg)| NumeratorHalfEdge {
3881                edge: index,
3882                ..*leg
3883            })
3884            .collect::<Vec<_>>();
3885        // Establish the unspecialized rule first. Aliasing momenta can cancel a
3886        // tensor to zero, but must not hide malformed summands or erase its rank.
3887        let base = if distinct != key.legs {
3888            Some(self.interaction_template(rule_id, distinct)?)
3889        } else {
3890            None
3891        };
3892        let instantiation = NumeratorInstantiation {
3893            owner: key.owner,
3894            legs: &key.legs,
3895        };
3896        let template = if let Some(base) = base {
3897            match &*base {
3898                NumeratorTemplate::Dynamic => NumeratorTemplate::Dynamic,
3899                NumeratorTemplate::Admitted { tensor, labels } => {
3900                    let expression = instantiation.bind_template(tensor.expression())?;
3901                    let specialized = tensor
3902                        .with_renamed_indices(expression, &HashMap::new())
3903                        .map_err(DiagramError::from)?;
3904                    // Momentum aliases can erase the payload. Keep the admitted
3905                    // rule's complete label universe for its retained metadata.
3906                    NumeratorTemplate::Admitted {
3907                        tensor: Box::new(specialized),
3908                        labels: labels.clone(),
3909                    }
3910                }
3911            }
3912        } else {
3913            let rule = self.model.vertex_rule_by_id(rule_id)?;
3914            let mut supported = rule
3915                .color_structures
3916                .iter()
3917                .all(NumeratorTemplate::supports);
3918            for lorentz in &rule.lorentz_structures {
3919                supported &= NumeratorTemplate::supports(
3920                    &self.model.lorentz_structure_by_id(*lorentz)?.structure,
3921                );
3922            }
3923            if supported {
3924                let expression = self.interaction_expression(rule_id, &instantiation)?;
3925                NumeratorTemplate::admitted(NumeratorInterface::admit(expression, None)?)?
3926            } else {
3927                NumeratorTemplate::Dynamic
3928            }
3929        };
3930        // Build outside the lock: symbolic normalization may invoke callbacks.
3931        // Concurrent cold callers may compute the same immutable rule; only the
3932        // first completed template is retained and returned to all callers.
3933        let mut templates = self
3934            .numerators
3935            .interaction_templates
3936            .write()
3937            .expect("numerator template cache was poisoned while publishing a rule");
3938        Ok(Arc::clone(
3939            templates.entry(key).or_insert_with(|| Arc::new(template)),
3940        ))
3941    }
3942
3943    fn interaction_expression(
3944        &self,
3945        rule_id: VertexRuleId,
3946        instantiation: &NumeratorInstantiation<'_>,
3947    ) -> Result<Atom, GenerationError> {
3948        let rule = self.model.vertex_rule_by_id(rule_id)?;
3949        let mut terms = Vec::new();
3950        for (color_index, color) in rule.color_structures.iter().enumerate() {
3951            for (lorentz_index, lorentz_name) in rule.lorentz_structures.iter().enumerate() {
3952                if let Some(coupling) = rule
3953                    .couplings
3954                    .get(color_index)
3955                    .and_then(|row| row.get(lorentz_index))
3956                    .and_then(Option::as_ref)
3957                {
3958                    let coupling = self.model.coupling_by_id(*coupling)?;
3959                    let coupling = Atom::var(symbol!(&format!("UFO::{}", coupling.name)));
3960                    let lorentz = &self.model.lorentz_structure_by_id(*lorentz_name)?.structure;
3961                    let color = instantiation.instantiate(color, NumeratorSector::Color)?;
3962                    let lorentz = instantiation.instantiate(lorentz, NumeratorSector::Spin)?;
3963                    terms.push(coupling * color * lorentz);
3964                }
3965            }
3966        }
3967        Ok(if terms.is_empty() {
3968            Atom::one()
3969        } else {
3970            Atom::add_many(terms)
3971        })
3972    }
3973
3974    fn edge_numerator(
3975        &self,
3976        particle_id: ParticleId,
3977        edge: usize,
3978        hedges: [usize; 2],
3979    ) -> Result<SymbolicTensor<PartialStructure>, GenerationError> {
3980        let key = PropagatorNumeratorKey {
3981            particle: particle_id,
3982            edge,
3983            hedges,
3984        };
3985        if let Some(numerator) = self
3986            .numerators
3987            .propagators
3988            .read()
3989            .expect("numerator cache was poisoned; its retained tensors cannot be reused")
3990            .get(&key)
3991        {
3992            return Ok(numerator.clone());
3993        }
3994        let particle = self.model.particle_by_id(particle_id)?;
3995        let (propagator, reversed) = self.propagator_numerator(particle)?;
3996        let flows = if reversed {
3997            [Flow::Sink, Flow::Source]
3998        } else {
3999            [Flow::Source, Flow::Sink]
4000        };
4001        let legs = flows.map(|flow| NumeratorHalfEdge {
4002            edge,
4003            flow,
4004            hedge: hedges[usize::from(flow == Flow::Sink)],
4005            spin: particle.spin,
4006            color: particle.color,
4007        });
4008        let instantiation = NumeratorInstantiation {
4009            owner: NumeratorOwner::Edge(edge),
4010            legs: &legs,
4011        };
4012        let cached = self
4013            .numerators
4014            .propagator_templates
4015            .read()
4016            .expect("numerator cache was poisoned; its retained tensors cannot be reused")
4017            .get(&particle_id)
4018            .cloned();
4019        let template = if let Some(template) = cached {
4020            template
4021        } else {
4022            let template = if NumeratorTemplate::supports(&propagator) {
4023                let canonical = legs
4024                    .iter()
4025                    .enumerate()
4026                    .map(|(index, leg)| NumeratorHalfEdge {
4027                        edge: 0,
4028                        hedge: index,
4029                        ..*leg
4030                    })
4031                    .collect::<Vec<_>>();
4032                let instantiation = NumeratorInstantiation {
4033                    owner: NumeratorOwner::Edge(0),
4034                    legs: &canonical,
4035                };
4036                let expression =
4037                    instantiation.propagator_expression(&propagator, particle.color)?;
4038                NumeratorTemplate::admitted(NumeratorInterface::admit(expression, None)?)?
4039            } else {
4040                NumeratorTemplate::Dynamic
4041            };
4042            // Publish only after normalization, without holding a lock across
4043            // a callback. Reuse the winner if another cold caller raced us.
4044            let mut templates = self
4045                .numerators
4046                .propagator_templates
4047                .write()
4048                .expect("propagator template cache was poisoned while publishing a rule");
4049            Arc::clone(
4050                templates
4051                    .entry(particle_id)
4052                    .or_insert_with(|| Arc::new(template)),
4053            )
4054        };
4055        let numerator = match &*template {
4056            NumeratorTemplate::Dynamic => NumeratorInterface::admit(
4057                instantiation.propagator_expression(&propagator, particle.color)?,
4058                None,
4059            )?,
4060            NumeratorTemplate::Admitted { .. } => template.instantiate(&instantiation)?,
4061        }
4062        .canonicalize_named_interface();
4063        self.numerators
4064            .propagators
4065            .write()
4066            .expect("numerator cache was poisoned; its retained tensors cannot be reused")
4067            .insert(key, numerator.clone());
4068        Ok(numerator)
4069    }
4070}
4071
4072#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
4073pub struct EdgeColor {
4074    pub particle: ParticleId,
4075    pub direction: Option<bool>,
4076}
4077
4078impl fmt::Display for EdgeColor {
4079    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
4080        write!(formatter, "particle#{}", self.particle.index())
4081    }
4082}
4083
4084fn available_interaction_half_edges(
4085    graph: &Graph<ColoredNode, EdgeColor>,
4086    vertex: usize,
4087    model: &Model,
4088) -> Result<Vec<(NumeratorHalfEdge, HalfEdge<EdgeColor>)>, GenerationError> {
4089    let mut available = Vec::new();
4090    for edge_id in &graph.nodes()[vertex].edges {
4091        let edge = &graph.edges()[*edge_id];
4092        let particle = model.particle_by_id(edge.data.particle)?;
4093        let base = if particle.is_antiparticle() {
4094            particle.antiparticle
4095        } else {
4096            edge.data.particle
4097        };
4098        if edge.vertices.0 == vertex {
4099            available.push((
4100                NumeratorHalfEdge {
4101                    edge: *edge_id,
4102                    flow: Flow::Source,
4103                    hedge: 2 * *edge_id,
4104                    spin: 0,
4105                    color: 1,
4106                },
4107                HalfEdge {
4108                    data: EdgeColor {
4109                        particle: base,
4110                        direction: None,
4111                    },
4112                    direction: edge.directed.then_some(!particle.is_antiparticle()),
4113                },
4114            ));
4115        }
4116        if edge.vertices.1 == vertex {
4117            available.push((
4118                NumeratorHalfEdge {
4119                    edge: *edge_id,
4120                    flow: Flow::Sink,
4121                    hedge: 2 * *edge_id + 1,
4122                    spin: 0,
4123                    color: 1,
4124                },
4125                HalfEdge {
4126                    data: EdgeColor {
4127                        particle: base,
4128                        direction: None,
4129                    },
4130                    direction: edge.directed.then_some(particle.is_antiparticle()),
4131                },
4132            ));
4133        }
4134    }
4135    Ok(available)
4136}
4137
4138fn vertex_rule_signature(
4139    model: &Model,
4140    rule: &VertexRule,
4141) -> Result<Vec<HalfEdge<EdgeColor>>, GenerationError> {
4142    let mut signature = rule
4143        .particles
4144        .iter()
4145        .map(|particle| ResolvedProcess::vertex_half_edge(model, model.particle_by_id(*particle)?))
4146        .collect::<Result<Vec<_>, GenerationError>>()?;
4147    signature.sort();
4148    Ok(signature)
4149}
4150
4151/// The order of the group permuting external legs that Symbolica treats as
4152/// interchangeable: one symmetric group per interchangeable class (a
4153/// symmetrized state and species, or a crossed species under left/right
4154/// symmetrization of an amplitude).
4155///
4156/// The order is an exact `u64`. A larger order, such as one class of 21
4157/// legs, is refused with [`GenerationError::ArithmeticOverflow`] before
4158/// enumeration starts. FeynKit likewise converts each enumerated graph's
4159/// Symbolica automorphism factor to `u64` after enumeration and reports a
4160/// larger one as [`GenerationError::SymmetryFactor`].
4161fn interchangeable_external_permutations(
4162    external_edges: &[(NodeColor, HalfEdge<EdgeColor>)],
4163) -> Result<u64, GenerationError> {
4164    let mut classes = BTreeMap::<_, u64>::new();
4165    for external in external_edges {
4166        *classes.entry(external).or_default() += 1;
4167    }
4168    classes
4169        .into_values()
4170        .flat_map(|size| 1..=size)
4171        .try_fold(1_u64, |order, factor| order.checked_mul(factor))
4172        .ok_or(GenerationError::ArithmeticOverflow(
4173            "the external permutation order (at most 20 interchangeable legs per class)",
4174        ))
4175}
4176
4177#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
4178pub struct ExternalNode {
4179    pub index: usize,
4180    pub state: ExternalState,
4181    pub particle: ParticleId,
4182}
4183
4184#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
4185enum ExternalCanonicalClass {
4186    Exact { state: ExternalState, index: usize },
4187    Interchangeable(InterchangeableClass),
4188}
4189
4190/// A class of amplitude legs that Symbolica treats as interchangeable.
4191///
4192/// The derived order keeps the within-state classes in (state, species)
4193/// order, which fixes their canonical colors.
4194#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
4195enum InterchangeableClass {
4196    /// The legs of one species in one external state.
4197    WithinState(ExternalState, ParticleId),
4198    /// With left/right symmetrization, the legs of one crossed species in
4199    /// both states: an outgoing leg enters as its antiparticle, so an
4200    /// incoming particle is interchangeable with an outgoing antiparticle.
4201    AcrossStates(ParticleId),
4202}
4203
4204impl InterchangeableClass {
4205    /// The species that identifies the class: the incoming species of a
4206    /// crossed class.
4207    fn particle(self) -> ParticleId {
4208        match self {
4209            Self::WithinState(_, particle) | Self::AcrossStates(particle) => particle,
4210        }
4211    }
4212}
4213
4214#[derive(Debug, Clone, Default)]
4215pub struct NodeColor {
4216    pub external: Option<ExternalNode>,
4217    external_class: Option<ExternalCanonicalClass>,
4218}
4219
4220impl NodeColor {
4221    fn key(&self) -> Option<(ParticleId, ExternalCanonicalClass)> {
4222        self.external.as_ref().map(|external| {
4223            let class = self
4224                .external_class
4225                .expect("external nodes always have a canonical class");
4226            // Crossed legs of one class differ in state and declared species.
4227            let particle = match class {
4228                ExternalCanonicalClass::Exact { .. } => external.particle,
4229                ExternalCanonicalClass::Interchangeable(class) => class.particle(),
4230            };
4231            (particle, class)
4232        })
4233    }
4234}
4235
4236impl PartialEq for NodeColor {
4237    fn eq(&self, other: &Self) -> bool {
4238        self.key() == other.key()
4239    }
4240}
4241
4242impl Eq for NodeColor {}
4243
4244impl PartialOrd for NodeColor {
4245    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
4246        Some(self.cmp(other))
4247    }
4248}
4249
4250impl Ord for NodeColor {
4251    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
4252        self.key().cmp(&other.key())
4253    }
4254}
4255
4256impl Hash for NodeColor {
4257    fn hash<H: Hasher>(&self, state: &mut H) {
4258        self.key().hash(state);
4259    }
4260}
4261
4262impl fmt::Display for NodeColor {
4263    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
4264        match &self.external {
4265            Some(external) => write!(formatter, "ext{}", external.index),
4266            None => formatter.write_str("v"),
4267        }
4268    }
4269}
4270
4271#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
4272enum ColoredNode {
4273    External(ExternalNode),
4274    Interaction(VertexRuleId),
4275}
4276
4277/// Node color of the complete-color external frame: interchangeable
4278/// amplitude legs carry only their class.
4279#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
4280enum ExternalFrameNode {
4281    Retained(ColoredNode),
4282    Interchangeable(InterchangeableClass),
4283}
4284
4285#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
4286struct NumeratorCanonicalNode(i64);
4287
4288#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
4289struct NumeratorCanonicalEdge(String);
4290
4291type InteractionAssignment = (Graph<ColoredNode, EdgeColor>, usize);
4292
4293impl fmt::Display for ColoredNode {
4294    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
4295        match self {
4296            Self::External(external) => write!(formatter, "ext{}", external.index),
4297            Self::Interaction(rule) => write!(formatter, "vertex#{}", rule.index()),
4298        }
4299    }
4300}
4301
4302#[derive(Clone, PartialEq, Eq)]
4303struct ColoredTopology {
4304    graph: Graph<ColoredNode, EdgeColor>,
4305    symmetry: u64,
4306    multiplicity: usize,
4307    cut_partitions: Vec<DiagramCut>,
4308    topology_threshold_candidates: Vec<DiagramThresholdCandidate>,
4309    /// Spectator cuts of a selection-only topology, which then has no physical cuts.
4310    spectator_cuts: Vec<DiagramSpectatorCut>,
4311}
4312
4313struct DiagramPair {
4314    comparison: FeynmanDiagram,
4315    representative: FeynmanDiagram,
4316    reversed_edges: BTreeSet<EdgeId>,
4317}
4318
4319impl DiagramPair {
4320    fn same_payload(&self, other: &Self) -> bool {
4321        let same_diagram = |left: &FeynmanDiagram, right: &FeynmanDiagram| {
4322            left.model().fingerprint() == right.model().fingerprint()
4323                && left.numerator() == right.numerator()
4324                && left.numerator_prefactor() == right.numerator_prefactor()
4325                && left.projector() == right.projector()
4326                && left.loop_momentum_basis() == right.loop_momentum_basis()
4327                && left.cuts() == right.cuts()
4328                && left.topology_threshold_candidates() == right.topology_threshold_candidates()
4329                && left.spectator_cuts() == right.spectator_cuts()
4330                && left.half_edges().eq(right.half_edges())
4331                && left.vertices().count() == right.vertices().count()
4332                && left
4333                    .vertices()
4334                    .zip(right.vertices())
4335                    .all(|((a, x), (b, y))| {
4336                        a == b
4337                            && x.name == y.name
4338                            && x.interaction == y.interaction
4339                            && x.numerator == y.numerator
4340                    })
4341                && left.edges().count() == right.edges().count()
4342                && left
4343                    .edges()
4344                    .zip(right.edges())
4345                    .all(|((a, ax, x), (b, bx, y))| {
4346                        a == b
4347                            && ax == bx
4348                            && x.external == y.external
4349                            && x.particle == y.particle
4350                            && x.directed == y.directed
4351                            && x.is_dummy == y.is_dummy
4352                            && x.source_slot() == y.source_slot()
4353                            && x.target_slot() == y.target_slot()
4354                            && x.numerator == y.numerator
4355                    })
4356        };
4357        self.reversed_edges == other.reversed_edges
4358            && same_diagram(&self.comparison, &other.comparison)
4359            && same_diagram(&self.representative, &other.representative)
4360    }
4361
4362    fn add_weight(mut self, other: Self) -> Self {
4363        let combine = |left: &Atom, right: &Atom| {
4364            let weight =
4365                evaluate_overall_factor(left.as_view()) + evaluate_overall_factor(right.as_view());
4366            // Keep the first representative's bookkeeping, replacing only the
4367            // multiplier that records equivalent normalized source graphs.
4368            let base = left.replace_map(|atom, _, output| {
4369                if let AtomView::Fun(function) = atom
4370                    && function.get_symbol() == FACTOR_HEADS.numerator_independent_symmetry_grouping
4371                {
4372                    **output = Atom::one();
4373                }
4374            });
4375            let reference = evaluate_overall_factor(base.as_view());
4376            if reference.is_zero() {
4377                weight
4378            } else {
4379                let ratio = weight / reference;
4380                if ratio == Atom::one() {
4381                    base
4382                } else {
4383                    base * FACTOR_HEADS
4384                        .numerator_independent_symmetry_grouping
4385                        .call(ratio)
4386                }
4387            }
4388        };
4389        let comparison = combine(
4390            self.comparison.overall_factor(),
4391            other.comparison.overall_factor(),
4392        );
4393        let representative = combine(
4394            self.representative.overall_factor(),
4395            other.representative.overall_factor(),
4396        );
4397        self.comparison = self.comparison.with_overall_factor(comparison);
4398        self.representative = self.representative.with_overall_factor(representative);
4399        self
4400    }
4401
4402    fn combine_duplicates(
4403        pairs: Vec<Self>,
4404    ) -> Result<(Vec<(CanonicalDiagramKey, Self)>, usize), GenerationError> {
4405        let mut buckets = BTreeMap::<CanonicalDiagramKey, Vec<Self>>::new();
4406        for pair in pairs {
4407            let bucket = buckets.entry(pair.comparison.canonical_key()?).or_default();
4408            if let Some(index) = bucket
4409                .iter()
4410                .position(|existing| existing.same_payload(&pair))
4411            {
4412                let existing = bucket.remove(index);
4413                bucket.insert(index, existing.add_weight(pair));
4414            } else {
4415                bucket.push(pair);
4416            }
4417        }
4418        let mut retained = Vec::new();
4419        let mut canceled = 0;
4420        for (key, pairs) in buckets {
4421            for pair in pairs {
4422                if evaluate_overall_factor(pair.comparison.overall_factor().as_view()).is_zero()
4423                    && evaluate_overall_factor(pair.representative.overall_factor().as_view())
4424                        .is_zero()
4425                {
4426                    canceled += 1;
4427                } else {
4428                    retained.push((key.clone(), pair));
4429                }
4430            }
4431        }
4432        Ok((retained, canceled))
4433    }
4434}
4435
4436#[derive(Default)]
4437struct CutPartitionInventory {
4438    /// Spectator-free cuts between the sewn attachment nodes, serialized on the diagram.
4439    physical: Vec<DiagramCut>,
4440    /// Whether the spectator range admits zero spectators, so `physical` cuts select the graph.
4441    physical_satisfies_spectator_range: bool,
4442    /// Cuts through initial-state edges within the spectator range. As on main they
4443    /// only select the graph: they are never physical cuts or threshold candidates,
4444    /// and a graph that only they select becomes a selection-only diagram.
4445    spectator: Vec<DiagramCut>,
4446    topology_threshold_candidates: Vec<DiagramThresholdCandidate>,
4447}
4448
4449fn transport_cut_half_edge(
4450    mut half_edge: DiagramHalfEdge,
4451    reversed_edges: &BTreeSet<EdgeId>,
4452) -> DiagramHalfEdge {
4453    if reversed_edges.contains(&half_edge.edge) {
4454        half_edge.endpoint = match half_edge.endpoint {
4455            DiagramEndpoint::Source => DiagramEndpoint::Target,
4456            DiagramEndpoint::Target => DiagramEndpoint::Source,
4457        };
4458    }
4459    half_edge
4460}
4461
4462fn transport_cut_metadata(
4463    cuts: &[DiagramCut],
4464    reversed_edges: &BTreeSet<EdgeId>,
4465) -> Vec<DiagramCut> {
4466    cuts.iter()
4467        .map(|cut| DiagramCut {
4468            cut: cut
4469                .cut
4470                .iter()
4471                .copied()
4472                .map(|half_edge| transport_cut_half_edge(half_edge, reversed_edges))
4473                .collect(),
4474            left: DiagramCutSide {
4475                half_edges: cut
4476                    .left
4477                    .half_edges
4478                    .iter()
4479                    .copied()
4480                    .map(|half_edge| transport_cut_half_edge(half_edge, reversed_edges))
4481                    .collect(),
4482                coupling_orders: cut.left.coupling_orders.clone(),
4483                loop_count: cut.left.loop_count,
4484            },
4485            right: DiagramCutSide {
4486                half_edges: cut
4487                    .right
4488                    .half_edges
4489                    .iter()
4490                    .copied()
4491                    .map(|half_edge| transport_cut_half_edge(half_edge, reversed_edges))
4492                    .collect(),
4493                coupling_orders: cut.right.coupling_orders.clone(),
4494                loop_count: cut.right.loop_count,
4495            },
4496        })
4497        .collect()
4498}
4499
4500fn transport_threshold_candidate_metadata(
4501    candidates: &[DiagramThresholdCandidate],
4502    reversed_edges: &BTreeSet<EdgeId>,
4503) -> Vec<DiagramThresholdCandidate> {
4504    candidates
4505        .iter()
4506        .map(|candidate| DiagramThresholdCandidate {
4507            cut: candidate
4508                .cut
4509                .iter()
4510                .copied()
4511                .map(|half_edge| transport_cut_half_edge(half_edge, reversed_edges))
4512                .collect(),
4513            left: candidate
4514                .left
4515                .iter()
4516                .copied()
4517                .map(|half_edge| transport_cut_half_edge(half_edge, reversed_edges))
4518                .collect(),
4519            right: candidate
4520                .right
4521                .iter()
4522                .copied()
4523                .map(|half_edge| transport_cut_half_edge(half_edge, reversed_edges))
4524                .collect(),
4525        })
4526        .collect()
4527}
4528
4529fn transport_spectator_cut_metadata(
4530    cuts: &[DiagramSpectatorCut],
4531    reversed_edges: &BTreeSet<EdgeId>,
4532) -> Vec<DiagramSpectatorCut> {
4533    cuts.iter()
4534        .map(|cut| DiagramSpectatorCut {
4535            cut: cut
4536                .cut
4537                .iter()
4538                .copied()
4539                .map(|half_edge| transport_cut_half_edge(half_edge, reversed_edges))
4540                .collect(),
4541            left_spectators: cut.left_spectators.clone(),
4542            right_spectators: cut.right_spectators.clone(),
4543        })
4544        .collect()
4545}
4546
4547#[derive(Debug, Clone, Copy, Default)]
4548struct FermionSigns {
4549    internal_loop_negative: bool,
4550    include_external_ordering: bool,
4551    external_ordering_negative: bool,
4552    include_antifermion_spin_sum: bool,
4553    antifermion_spin_sum_negative: bool,
4554}
4555
4556/// The bookkeeping heads of the overall factors, created together in this
4557/// order on first use. Symbolica orders the factors of a product by symbol
4558/// creation, so a head first created by whichever generation worker needs it
4559/// first would make printed factors depend on the thread schedule.
4560pub(crate) struct FactorHeads {
4561    aut_g: Symbol,
4562    couplings_multiplicity: Symbol,
4563    internal_fermion_loop_sign: Symbol,
4564    external_fermion_ordering_sign: Symbol,
4565    antifermion_spin_sum_sign: Symbol,
4566    pub(crate) numerator_dependent_grouping: Symbol,
4567    numerator_independent_symmetry_grouping: Symbol,
4568}
4569
4570pub(crate) static FACTOR_HEADS: LazyLock<FactorHeads> = LazyLock::new(|| FactorHeads {
4571    aut_g: symbol!("feynkit_generator_factor::AutG"),
4572    couplings_multiplicity: symbol!("feynkit_generator_factor::CouplingsMultiplicity"),
4573    internal_fermion_loop_sign: symbol!("feynkit_generator_factor::InternalFermionLoopSign"),
4574    external_fermion_ordering_sign: symbol!(
4575        "feynkit_generator_factor::ExternalFermionOrderingSign"
4576    ),
4577    antifermion_spin_sum_sign: symbol!("feynkit_generator_factor::AntiFermionSpinSumSign"),
4578    numerator_dependent_grouping: symbol!("feynkit_generator_factor::NumeratorDependentGrouping"),
4579    numerator_independent_symmetry_grouping: symbol!(
4580        "feynkit_generator_factor::NumeratorIndependentSymmetryGrouping"
4581    ),
4582});
4583
4584struct NormalizedFermionFlow {
4585    #[cfg_attr(not(test), allow(dead_code))]
4586    graph: Graph<ColoredNode, EdgeColor>,
4587    reversed_edges: BTreeSet<EdgeId>,
4588    signs: FermionSigns,
4589}
4590
4591struct FermionNormalizationState<'a> {
4592    visited_edges: &'a mut [bool],
4593    vertices: &'a mut [Option<(usize, usize)>],
4594    particles: &'a mut [Option<ParticleId>],
4595}
4596
4597fn normalize_fermion_component(
4598    graph: &Graph<ColoredNode, EdgeColor>,
4599    starting_edge: usize,
4600    adjacency: &[Vec<(usize, usize)>],
4601    state: &mut FermionNormalizationState<'_>,
4602    model: &Model,
4603    canonicalize_virtual_start: bool,
4604) -> Result<BTreeSet<usize>, GenerationError> {
4605    let starting = &graph.edges()[starting_edge];
4606    let starting_particle = model.particle_by_id(starting.data.particle)?;
4607    let reverse_start = canonicalize_virtual_start && starting_particle.is_antiparticle();
4608    let (left, right) = if reverse_start {
4609        (starting.vertices.1, starting.vertices.0)
4610    } else {
4611        starting.vertices
4612    };
4613    let chain_is_antiparticle = starting_particle.is_antiparticle() && !reverse_start;
4614    state.visited_edges[starting_edge] = true;
4615    state.vertices[starting_edge] = Some((left, right));
4616    state.particles[starting_edge] = Some(if reverse_start {
4617        starting_particle.antiparticle
4618    } else {
4619        starting.data.particle
4620    });
4621    let mut external_legs = BTreeSet::new();
4622    let mut record_external = |node_id: usize| {
4623        if let ColoredNode::External(external) = &graph.nodes()[node_id].data {
4624            external_legs.insert(external.index);
4625        }
4626    };
4627    record_external(left);
4628    record_external(right);
4629
4630    // Read both ways from the first edge, flipping each subsequent edge when
4631    // needed so that the complete chain has one consistent orientation.
4632    for (mut current, read_forward) in [(right, true), (left, false)] {
4633        while let Some(&(edge_id, next)) = adjacency[current]
4634            .iter()
4635            .find(|(edge_id, _)| !state.visited_edges[*edge_id])
4636        {
4637            state.visited_edges[edge_id] = true;
4638            let vertices = if read_forward {
4639                (current, next)
4640            } else {
4641                (next, current)
4642            };
4643            state.vertices[edge_id] = Some(vertices);
4644            let edge = &graph.edges()[edge_id];
4645            let particle = model.particle_by_id(edge.data.particle)?;
4646            // Legacy GammaLoop represents a complete charged chain with the
4647            // same particle (or antiparticle) on every edge.  When a
4648            // canonical edge points against the chain, reversing only its
4649            // endpoints is not enough: choose the conjugate precisely when
4650            // needed to match the species selected by the starting edge.
4651            state.particles[edge_id] = Some(
4652                if vertices != edge.vertices && particle.is_antiparticle() != chain_is_antiparticle
4653                {
4654                    particle.antiparticle
4655                } else {
4656                    edge.data.particle
4657                },
4658            );
4659            record_external(next);
4660            current = next;
4661        }
4662    }
4663    Ok(external_legs)
4664}
4665
4666fn all_incoming_particle<'model>(
4667    external: &ExternalNode,
4668    model: &'model Model,
4669) -> Result<&'model Particle, GenerationError> {
4670    let particle = model.particle_by_id(external.particle)?;
4671    match external.state {
4672        ExternalState::Incoming => Ok(particle),
4673        ExternalState::Outgoing => Ok(model.antiparticle(particle)?),
4674    }
4675}
4676
4677fn permutation_is_odd(values: &[usize]) -> bool {
4678    values
4679        .iter()
4680        .enumerate()
4681        .map(|(index, value)| {
4682            values[index + 1..]
4683                .iter()
4684                .filter(|next| value > *next)
4685                .count()
4686        })
4687        .sum::<usize>()
4688        % 2
4689        == 1
4690}
4691
4692struct InteractionSignatures(BTreeMap<Vec<HalfEdge<EdgeColor>>, Vec<VertexRuleId>>);
4693
4694impl InteractionSignatures {
4695    fn new(model: &Model, options: &GenerationOptions) -> Result<Self, GenerationError> {
4696        let allowed = options
4697            .graph_filters
4698            .iter()
4699            .find_map(|filter| match filter {
4700                GenerationFilter::VertexAllow(selectors) => Some(
4701                    selectors
4702                        .iter()
4703                        .map(|selector| match selector {
4704                            VertexSelector::Id { vertex, .. } => *vertex,
4705                            VertexSelector::Name(_) => {
4706                                unreachable!("generation selectors are resolved before use")
4707                            }
4708                        })
4709                        .collect::<BTreeSet<_>>(),
4710                ),
4711                _ => None,
4712            });
4713        let vetoed = options
4714            .graph_filters
4715            .iter()
4716            .find_map(|filter| match filter {
4717                GenerationFilter::VertexVeto(selectors) => Some(
4718                    selectors
4719                        .iter()
4720                        .map(|selector| match selector {
4721                            VertexSelector::Id { vertex, .. } => *vertex,
4722                            VertexSelector::Name(_) => {
4723                                unreachable!("generation selectors are resolved before use")
4724                            }
4725                        })
4726                        .collect::<BTreeSet<_>>(),
4727                ),
4728                _ => None,
4729            });
4730        let particle_vetoes = options
4731            .graph_filters
4732            .iter()
4733            .find_map(|filter| match filter {
4734                GenerationFilter::ParticleVeto(selectors) => Some(
4735                    selectors
4736                        .iter()
4737                        .map(|selector| match selector {
4738                            ParticleSelector::Id { particle, .. } => *particle,
4739                            ParticleSelector::Name(_) | ParticleSelector::Pdg(_) => {
4740                                unreachable!("generation selectors are resolved before use")
4741                            }
4742                        })
4743                        .collect::<BTreeSet<_>>(),
4744                ),
4745                _ => None,
4746            });
4747        let mut signatures: BTreeMap<Vec<_>, Vec<_>> = BTreeMap::new();
4748        for (rule_index, rule) in model.vertex_rules().iter().enumerate() {
4749            let rule_id = model.vertex_rule_id_at(rule_index)?;
4750            if allowed
4751                .as_ref()
4752                .is_some_and(|allowed| !allowed.contains(&rule_id))
4753                || vetoed
4754                    .as_ref()
4755                    .is_some_and(|vetoed| vetoed.contains(&rule_id))
4756            {
4757                continue;
4758            }
4759            // Coupling powers are nonnegative. A vertex exceeding a graph-wide
4760            // upper bound cannot occur in an accepted graph, so exclude its
4761            // signature before enumerating topologies (especially QED=0).
4762            let orders = rule.coupling_orders(model);
4763            if options.graph_filters.iter().any(|filter| {
4764                matches!(filter, GenerationFilter::CouplingOrders(required)
4765                    if required.iter().any(|(name, (_, maximum))|
4766                        maximum.is_some_and(|maximum| orders.get(name).copied().unwrap_or(0) > maximum)))
4767            }) {
4768                continue;
4769            }
4770            let mut signature = Vec::new();
4771            let mut rejected = false;
4772            for particle_id in &rule.particles {
4773                let particle = model.particle_by_id(*particle_id)?;
4774                if particle_vetoes.as_ref().is_some_and(|vetoed| {
4775                    vetoed.contains(particle_id) || vetoed.contains(&particle.antiparticle)
4776                }) {
4777                    rejected = true;
4778                    break;
4779                }
4780                signature.push(ResolvedProcess::vertex_half_edge(model, particle)?);
4781            }
4782            if !rejected {
4783                signature.sort();
4784                signatures.entry(signature).or_default().push(rule_id);
4785            }
4786        }
4787        // Stable signature and rule ordering makes graph generation
4788        // reproducible.
4789        for rules in signatures.values_mut() {
4790            rules.sort();
4791        }
4792        Ok(Self(signatures))
4793    }
4794
4795    fn keys(&self) -> impl Iterator<Item = &Vec<HalfEdge<EdgeColor>>> {
4796        self.0.keys()
4797    }
4798
4799    fn rules(&self, signature: &[EdgeColor]) -> Option<&[VertexRuleId]> {
4800        let mut half_edges: Vec<_> = signature
4801            .iter()
4802            .map(|edge| HalfEdge {
4803                direction: edge.direction,
4804                data: EdgeColor {
4805                    particle: edge.particle,
4806                    direction: None,
4807                },
4808            })
4809            .collect();
4810        // `EdgeColor` and `HalfEdge<EdgeColor>` have different derived orderings:
4811        // the former orders by PDG first, while the latter orders by direction
4812        // first. Restore the key ordering used when interaction signatures were
4813        // built before performing the lookup.
4814        half_edges.sort();
4815        self.0.get(&half_edges).map(Vec::as_slice)
4816    }
4817}
4818
4819struct ResolvedProcess {
4820    generation_type: GenerationType,
4821    incoming: Vec<Particle>,
4822    outgoing: Vec<Vec<Particle>>,
4823    symmetrize_initial: bool,
4824    symmetrize_final: bool,
4825    symmetrize_left_right: bool,
4826    symmetrize_external_fermions: bool,
4827    /// The unresolved-cut policy of a cross section with initial states,
4828    /// resolved and validated once at the process boundary.
4829    unresolved: Option<UnresolvedCutContent>,
4830}
4831
4832impl ResolvedProcess {
4833    fn new(
4834        model: &Model,
4835        process: &Process,
4836        generation_type: GenerationType,
4837        options: &GenerationOptions,
4838    ) -> Result<Self, GenerationError> {
4839        let resolve = |selector: &ParticleSelector| -> Result<Particle, GenerationError> {
4840            Ok(model.particle_by_id(selector.resolve(model)?)?.clone())
4841        };
4842        Ok(Self {
4843            generation_type,
4844            incoming: process
4845                .incoming()
4846                .iter()
4847                .map(resolve)
4848                .collect::<Result<_, _>>()?,
4849            outgoing: process
4850                .outgoing_alternatives()
4851                .iter()
4852                .map(|alternative| alternative.iter().map(resolve).collect())
4853                .collect::<Result<_, _>>()?,
4854            symmetrize_initial: options.symmetrizes_initial(),
4855            symmetrize_final: options.symmetrizes_final(),
4856            symmetrize_left_right: options.symmetrizes_left_right(),
4857            symmetrize_external_fermions: options.symmetrizes_external_fermions(),
4858            unresolved: if generation_type == GenerationType::CrossSection
4859                && !process.incoming().is_empty()
4860            {
4861                unresolved_cut_content(model, options)?
4862            } else {
4863                None
4864            },
4865        })
4866    }
4867
4868    fn external_edges(
4869        &self,
4870        model: &Model,
4871    ) -> Result<Vec<(NodeColor, HalfEdge<EdgeColor>)>, GenerationError> {
4872        let mut result = Vec::new();
4873        for (index, particle) in self.incoming.iter().enumerate() {
4874            result.push(self.external_edge(model, particle, index, ExternalState::Incoming)?);
4875        }
4876        match self.generation_type {
4877            GenerationType::Amplitude => {
4878                for (offset, particle) in self.outgoing[0].iter().enumerate() {
4879                    result.push(self.external_edge(
4880                        model,
4881                        particle,
4882                        self.incoming.len() + offset,
4883                        ExternalState::Outgoing,
4884                    )?);
4885                }
4886            }
4887            GenerationType::CrossSection => {
4888                for (offset, particle) in self.incoming.iter().enumerate() {
4889                    result.push(self.external_edge(
4890                        model,
4891                        particle,
4892                        self.incoming.len() + offset,
4893                        ExternalState::Outgoing,
4894                    )?);
4895                }
4896            }
4897        }
4898        Ok(result)
4899    }
4900
4901    fn external_edge(
4902        &self,
4903        model: &Model,
4904        particle: &Particle,
4905        index: usize,
4906        state: ExternalState,
4907    ) -> Result<(NodeColor, HalfEdge<EdgeColor>), GenerationError> {
4908        // Symbolica represents every non-self-conjugate species by its particle
4909        // entry; particle versus antiparticle is encoded by edge direction.
4910        let base = if particle.is_antiparticle() {
4911            particle.antiparticle
4912        } else {
4913            model.particle_id(&particle.name)?
4914        };
4915        let particle_id = model.particle_id(&particle.name)?;
4916        let direction = if model.particle_is_self_conjugate(particle_id) {
4917            None
4918        } else {
4919            Some(match (state, particle.is_antiparticle()) {
4920                (ExternalState::Incoming, false) | (ExternalState::Outgoing, true) => true,
4921                (ExternalState::Incoming, true) | (ExternalState::Outgoing, false) => false,
4922            })
4923        };
4924        let external = ExternalNode {
4925            index,
4926            state,
4927            particle: particle_id,
4928        };
4929        // Both sides of a forward graph are labelled copies of the incoming
4930        // state. Neither independent permutations nor final-state symmetry may
4931        // enter its raw automorphism denominator. Paired incoming permutations
4932        // and the optional global side exchange are compared after generation.
4933        let external_class = match self.interchangeable_class(model, &external)? {
4934            Some(class) => ExternalCanonicalClass::Interchangeable(class),
4935            None => ExternalCanonicalClass::Exact { state, index },
4936        };
4937        Ok((
4938            NodeColor {
4939                external: Some(external),
4940                external_class: Some(external_class),
4941            },
4942            HalfEdge {
4943                direction,
4944                data: EdgeColor {
4945                    particle: base,
4946                    direction: None,
4947                },
4948            },
4949        ))
4950    }
4951
4952    /// Whether this amplitude leg is symmetrized with the other legs of its
4953    /// species in its state (and, with left/right symmetrization, across
4954    /// states).
4955    ///
4956    /// Commuting legs are eligible when their side is symmetrized. As on
4957    /// `main` (`diagram_generator.rs`, `is_anticommutating()`), every
4958    /// anticommuting field, Faddeev–Popov ghosts included, also needs the
4959    /// external-fermion opt-in: exchanging Grassmann legs would otherwise merge
4960    /// oppositely signed attachments into one orbit while their external
4961    /// ordering sign is kept.
4962    fn symmetrizes_within_state(&self, particle: &Particle, state: ExternalState) -> bool {
4963        self.generation_type == GenerationType::Amplitude
4964            && match state {
4965                ExternalState::Incoming => self.symmetrize_initial,
4966                ExternalState::Outgoing => self.symmetrize_final,
4967            }
4968            && (!particle.is_anticommutating() || self.symmetrize_external_fermions)
4969    }
4970
4971    /// The interchangeable class of an amplitude leg, if it has one.
4972    ///
4973    /// Left/right symmetrization of an amplitude, valid only with both
4974    /// states symmetrized, merges the two states: every leg that would be
4975    /// symmetrized within its state is interchangeable with the crossed legs
4976    /// of its species on either side, as on `main`. This exchanges incoming
4977    /// and outgoing momenta, so it is a user-requested crossing
4978    /// identification, not a symmetry of the amplitude at fixed kinematics:
4979    /// it preserves the sum of combinatorial graph weights, while each
4980    /// representative is evaluated at its own labels.
4981    fn interchangeable_class(
4982        &self,
4983        model: &Model,
4984        external: &ExternalNode,
4985    ) -> Result<Option<InterchangeableClass>, GenerationError> {
4986        let particle = model.particle_by_id(external.particle)?;
4987        if !self.symmetrizes_within_state(particle, external.state) {
4988            return Ok(None);
4989        }
4990        Ok(Some(if self.symmetrize_left_right {
4991            InterchangeableClass::AcrossStates(match external.state {
4992                ExternalState::Incoming => external.particle,
4993                ExternalState::Outgoing => particle.antiparticle,
4994            })
4995        } else {
4996            InterchangeableClass::WithinState(external.state, external.particle)
4997        }))
4998    }
4999
5000    /// Classes of at least two amplitude legs that Symbolica treats as
5001    /// interchangeable, each with its legs sorted by external label.
5002    fn interchangeable_classes(
5003        &self,
5004        graph: &Graph<ColoredNode, EdgeColor>,
5005        model: &Model,
5006    ) -> Result<BTreeMap<InterchangeableClass, Vec<ExternalNode>>, GenerationError> {
5007        let mut classes = BTreeMap::<_, Vec<ExternalNode>>::new();
5008        for node in graph.nodes() {
5009            if let ColoredNode::External(external) = &node.data
5010                && let Some(class) = self.interchangeable_class(model, external)?
5011            {
5012                classes.entry(class).or_default().push(external.clone());
5013            }
5014        }
5015        classes.retain(|_, legs| legs.len() > 1);
5016        for legs in classes.values_mut() {
5017            legs.sort_unstable();
5018        }
5019        Ok(classes)
5020    }
5021
5022    /// The class of `external` among `classes`. Relabelling permutes the
5023    /// legs of a class, so a leg is found by its label in any frame.
5024    fn class_of(
5025        classes: &BTreeMap<InterchangeableClass, Vec<ExternalNode>>,
5026        external: &ExternalNode,
5027    ) -> Option<InterchangeableClass> {
5028        classes
5029            .iter()
5030            .find(|(_, legs)| legs.iter().any(|leg| leg.index == external.index))
5031            .map(|(class, _)| *class)
5032    }
5033
5034    /// Give the legs of each interchangeable class that class's sorted legs
5035    /// in node order. Applied to a canonically ordered graph, this labels the
5036    /// legs by canonical position. A crossed leg also takes the state and
5037    /// declared species of its new label.
5038    fn relabel_interchangeable_legs(
5039        graph: &Graph<ColoredNode, EdgeColor>,
5040        classes: &BTreeMap<InterchangeableClass, Vec<ExternalNode>>,
5041    ) -> Result<Graph<ColoredNode, EdgeColor>, GenerationError> {
5042        let mut labels = classes
5043            .iter()
5044            .map(|(class, legs)| (*class, legs.iter()))
5045            .collect::<BTreeMap<_, _>>();
5046        let mut relabelled = Graph::new();
5047        for node in graph.nodes() {
5048            let mut data = node.data.clone();
5049            if let ColoredNode::External(external) = &mut data
5050                && let Some(label) = Self::class_of(classes, external)
5051                    .and_then(|class| labels.get_mut(&class))
5052                    .and_then(|legs| legs.next())
5053            {
5054                *external = label.clone();
5055            }
5056            relabelled.add_node(data);
5057        }
5058        for edge in graph.edges() {
5059            relabelled
5060                .add_edge(edge.vertices.0, edge.vertices.1, edge.directed, edge.data)
5061                .map_err(|error| GenerationError::GraphConstruction(error.to_string()))?;
5062        }
5063        Ok(relabelled)
5064    }
5065
5066    /// Order the complete colored graph canonically while its interchangeable
5067    /// legs carry only their class, then label those legs by canonical
5068    /// position.
5069    ///
5070    /// Interaction rules, exact particles and arrows all enter this canonical
5071    /// form, so every labelling of one orbit yields the identical graph, also
5072    /// when the reduced skeleton cannot tell the legs apart.
5073    fn complete_color_external_frame(
5074        graph: &Graph<ColoredNode, EdgeColor>,
5075        model: &Model,
5076        classes: &BTreeMap<InterchangeableClass, Vec<ExternalNode>>,
5077    ) -> Result<Graph<ColoredNode, EdgeColor>, GenerationError> {
5078        let mut colored = Graph::new();
5079        for node in graph.nodes() {
5080            let class = match &node.data {
5081                ColoredNode::External(external) => Self::class_of(classes, external),
5082                ColoredNode::Interaction(_) => None,
5083            };
5084            colored.add_node(match class {
5085                Some(class) => ExternalFrameNode::Interchangeable(class),
5086                None => ExternalFrameNode::Retained(node.data.clone()),
5087            });
5088        }
5089        for edge in graph.edges() {
5090            // A reversed stored arrow with its conjugate particle describes
5091            // the same physical endpoint species. Normalize only this
5092            // comparison key; real edges retain their original owners below.
5093            let mut vertices = edge.vertices;
5094            let mut data = edge.data;
5095            let particle = model.particle_by_id(data.particle)?;
5096            if edge.directed && particle.is_antiparticle() {
5097                vertices = (vertices.1, vertices.0);
5098                data.particle = particle.antiparticle;
5099            }
5100            colored
5101                .add_edge(vertices.0, vertices.1, edge.directed, data)
5102                .map_err(|error| GenerationError::GraphConstruction(error.to_string()))?;
5103        }
5104        let vertex_map = colored.canonize().vertex_map;
5105        let mut canonical_to_input = vec![0; vertex_map.len()];
5106        for (input, position) in vertex_map.iter().copied().enumerate() {
5107            canonical_to_input[position] = input;
5108        }
5109        let mut ordered = Graph::new();
5110        for input in canonical_to_input {
5111            ordered.add_node(graph.nodes()[input].data.clone());
5112        }
5113        let mut edges = graph
5114            .edges()
5115            .iter()
5116            .map(|edge| {
5117                let mut vertices = (vertex_map[edge.vertices.0], vertex_map[edge.vertices.1]);
5118                let internal = [edge.vertices.0, edge.vertices.1].iter().all(|vertex| {
5119                    matches!(graph.nodes()[*vertex].data, ColoredNode::Interaction(_))
5120                });
5121                // External edges keep their state orientation; an undirected
5122                // internal edge has none, so store it in canonical order.
5123                if internal && !edge.directed && vertices.0 > vertices.1 {
5124                    vertices = (vertices.1, vertices.0);
5125                }
5126                (vertices, edge.directed, edge.data)
5127            })
5128            .collect::<Vec<_>>();
5129        edges.sort();
5130        for (vertices, directed, data) in edges {
5131            ordered
5132                .add_edge(vertices.0, vertices.1, directed, data)
5133                .map_err(|error| GenerationError::GraphConstruction(error.to_string()))?;
5134        }
5135        Self::relabel_interchangeable_legs(&ordered, classes)
5136    }
5137
5138    /// Choose the reduced-skeleton representative before any numerator
5139    /// indices are instantiated.
5140    ///
5141    /// For left/right symmetry the extra orbit operation is global: either
5142    /// every sewn incoming leg is exchanged with its outgoing partner, or none
5143    /// is. Keeping the exact external colors in each skeleton prevents graph
5144    /// automorphisms from swapping only a subset of the pairs. Once the
5145    /// smallest skeleton is selected, the complete colored graph is rebuilt in
5146    /// that canonical vertex/edge order so UFO slot matching and propagator
5147    /// momenta are instantiated identically for isomorphic diagrams.
5148    ///
5149    /// Symbolica labels the interchangeable legs of an amplitude orbit
5150    /// representative arbitrarily. When numerators are grouped, two passes
5151    /// first fix those labels: the canonical order of the complete colored
5152    /// graph makes the input identical for every labelling of the orbit, and
5153    /// the reduced skeleton with class-colored legs then assigns the labels by
5154    /// canonical position. Orbits that share a reduced skeleton therefore
5155    /// share one external frame.
5156    fn canonicalize_numerator_graph(
5157        &self,
5158        graph: &Graph<ColoredNode, EdgeColor>,
5159        model: &Model,
5160        grouping: &NumeratorGrouping,
5161    ) -> Result<Graph<ColoredNode, EdgeColor>, GenerationError> {
5162        let grouping_options = match grouping {
5163            NumeratorGrouping::Identical(options)
5164            | NumeratorGrouping::UpToSign(options)
5165            | NumeratorGrouping::UpToScalar(options) => Some(options),
5166            NumeratorGrouping::None => None,
5167        };
5168        let include_external = self.generation_type == GenerationType::CrossSection
5169            && (self.symmetrize_initial || self.symmetrize_left_right);
5170        let exact_internal_particles =
5171            grouping_options.is_some_and(|options| !options.differentiate_particle_masses_only);
5172        let classes = if grouping_options.is_some() {
5173            self.interchangeable_classes(graph, model)?
5174        } else {
5175            BTreeMap::new()
5176        };
5177        let framed;
5178        let graph = if classes.is_empty() {
5179            graph
5180        } else {
5181            let complete = Self::complete_color_external_frame(graph, model, &classes)?;
5182            let reduced = self.canonicalize_numerator_graph_pass(
5183                &complete,
5184                model,
5185                exact_internal_particles,
5186                false,
5187                false,
5188                &classes,
5189            )?;
5190            framed = Self::relabel_interchangeable_legs(&reduced, &classes)?;
5191            &framed
5192        };
5193
5194        let selected = self.canonicalize_numerator_graph_pass(
5195            graph,
5196            model,
5197            exact_internal_particles,
5198            include_external,
5199            include_external,
5200            &BTreeMap::new(),
5201        )?;
5202        let canonical = if include_external {
5203            self.canonicalize_numerator_graph_pass(
5204                &selected,
5205                model,
5206                exact_internal_particles,
5207                false,
5208                true,
5209                &BTreeMap::new(),
5210            )?
5211        } else {
5212            selected
5213        };
5214        Ok(canonical)
5215    }
5216
5217    fn canonicalize_numerator_graph_pass(
5218        &self,
5219        graph: &Graph<ColoredNode, EdgeColor>,
5220        model: &Model,
5221        exact_internal_particles: bool,
5222        include_external_remapping: bool,
5223        use_sewn_external_colors: bool,
5224        interchangeable: &BTreeMap<InterchangeableClass, Vec<ExternalNode>>,
5225    ) -> Result<Graph<ColoredNode, EdgeColor>, GenerationError> {
5226        let mut candidates = Vec::new();
5227        let mut remappings = vec![(false, BTreeMap::new())];
5228        if include_external_remapping {
5229            let external_nodes = graph
5230                .nodes()
5231                .iter()
5232                .enumerate()
5233                .filter_map(|(node, value)| match &value.data {
5234                    ColoredNode::External(external) => Some((external.index, node)),
5235                    ColoredNode::Interaction(_) => None,
5236                })
5237                .collect::<BTreeMap<_, _>>();
5238            let incoming_count = self.incoming.len();
5239            if external_nodes.len() != 2 * incoming_count {
5240                return Err(GenerationError::GraphConstruction(format!(
5241                    "sewn canonicalization expected {} external nodes, found {}",
5242                    2 * incoming_count,
5243                    external_nodes.len()
5244                )));
5245            }
5246            let mut generators = vec![Permutation::id(incoming_count)];
5247            if self.symmetrize_initial {
5248                let mut species = BTreeMap::<i64, Vec<usize>>::new();
5249                for (index, particle) in self.incoming.iter().enumerate() {
5250                    species.entry(particle.pdg_code).or_default().push(index);
5251                }
5252                // Adjacent transpositions generate only permutations within
5253                // each identical-species class, without enumerating rejected
5254                // permutations of distinct incoming particles.
5255                for positions in species.values() {
5256                    for pair in positions.windows(2) {
5257                        let mut mapping = (0..incoming_count).collect::<Vec<_>>();
5258                        mapping.swap(pair[0], pair[1]);
5259                        generators.push(Permutation::from_map(mapping));
5260                    }
5261                }
5262            }
5263            let mut permutations = Permutation::generate_all(&generators)
5264                .map_err(|error| GenerationError::GraphConstruction(error.to_string()))?;
5265            permutations.sort_by(|left, right| left.map().cmp(right.map()));
5266            remappings.clear();
5267            for permutation in permutations {
5268                for swapped in [false, true] {
5269                    if swapped && !self.symmetrize_left_right {
5270                        continue;
5271                    }
5272                    let mapping = (0..incoming_count)
5273                        .flat_map(|index| {
5274                            let target = permutation.map()[index];
5275                            let (left, right) = if swapped {
5276                                (target + incoming_count, target)
5277                            } else {
5278                                (target, target + incoming_count)
5279                            };
5280                            [
5281                                (external_nodes[&index], external_nodes[&left]),
5282                                (
5283                                    external_nodes[&(index + incoming_count)],
5284                                    external_nodes[&right],
5285                                ),
5286                            ]
5287                        })
5288                        .collect();
5289                    remappings.push((swapped, mapping));
5290                }
5291            }
5292        }
5293        for (swapped, remapping) in remappings {
5294            let mut skeleton = Graph::new();
5295            for node in graph.nodes() {
5296                let class = match &node.data {
5297                    ColoredNode::External(external) => Self::class_of(interchangeable, external),
5298                    ColoredNode::Interaction(_) => None,
5299                };
5300                let color = match (&node.data, class) {
5301                    (ColoredNode::External(_), Some(class)) => {
5302                        // Interchangeable legs are told apart only by class.
5303                        let class = interchangeable.range(..class).count();
5304                        -4001
5305                            - i64::try_from(class).map_err(|_| {
5306                                GenerationError::ArithmeticOverflow("an external canonical color")
5307                            })?
5308                    }
5309                    (ColoredNode::External(external), None) => {
5310                        let index = i64::try_from(external.index).map_err(|_| {
5311                            GenerationError::ArithmeticOverflow("an external canonical color")
5312                        })?;
5313                        let incoming_count = i64::try_from(self.incoming.len()).map_err(|_| {
5314                            GenerationError::ArithmeticOverflow("an external canonical color")
5315                        })?;
5316                        if use_sewn_external_colors {
5317                            if index < incoming_count {
5318                                -2001 - index
5319                            } else {
5320                                -3001 - (index - incoming_count)
5321                            }
5322                        } else {
5323                            index + 1
5324                        }
5325                    }
5326                    (ColoredNode::Interaction(_), _) => 0,
5327                };
5328                skeleton.add_node(NumeratorCanonicalNode(color));
5329            }
5330            for edge in graph.edges() {
5331                let external = matches!(
5332                    graph.nodes()[edge.vertices.0].data,
5333                    ColoredNode::External(_)
5334                ) || matches!(
5335                    graph.nodes()[edge.vertices.1].data,
5336                    ColoredNode::External(_)
5337                );
5338                let mut vertices = (
5339                    remapping
5340                        .get(&edge.vertices.0)
5341                        .copied()
5342                        .unwrap_or(edge.vertices.0),
5343                    remapping
5344                        .get(&edge.vertices.1)
5345                        .copied()
5346                        .unwrap_or(edge.vertices.1),
5347                );
5348                // As in the legacy comparison graph, all external edges point
5349                // into the interaction graph. Internal fermion direction is
5350                // omitted from the reduced skeleton but restored below.
5351                let external_outgoing = matches!(
5352                    graph.nodes()[edge.vertices.1].data,
5353                    ColoredNode::External(_)
5354                );
5355                if external_outgoing {
5356                    vertices = (vertices.1, vertices.0);
5357                }
5358                let particle = model.particle_by_id(if external_outgoing {
5359                    model.particle_by_id(edge.data.particle)?.antiparticle
5360                } else {
5361                    edge.data.particle
5362                })?;
5363                // Ghost vertices differentiate one propagator end. Preserve its
5364                // physical arrow in the momentum chart: reversing storage while
5365                // conjugating the ghost must describe the same directed edge.
5366                if particle.is_ghost() && particle.is_antiparticle() {
5367                    vertices = (vertices.1, vertices.0);
5368                }
5369                let keep_direction = external || particle.is_ghost();
5370                let color = if external || exact_internal_particles {
5371                    particle.name.clone()
5372                } else {
5373                    format!(
5374                        "{} | {}",
5375                        model.parameter_by_id(particle.mass)?.name,
5376                        particle.spin
5377                    )
5378                };
5379                skeleton
5380                    .add_edge(
5381                        vertices.0,
5382                        vertices.1,
5383                        keep_direction,
5384                        NumeratorCanonicalEdge(color),
5385                    )
5386                    .map_err(|error| GenerationError::GraphConstruction(error.to_string()))?;
5387            }
5388            candidates.push((swapped, remapping, skeleton.canonize()));
5389        }
5390        candidates.sort_by(|left, right| {
5391            (left.2.graph.nodes(), left.2.graph.edges())
5392                .cmp(&(right.2.graph.nodes(), right.2.graph.edges()))
5393        });
5394        let (left_right_swapped, remapping, canonical) = candidates
5395            .into_iter()
5396            .next()
5397            .ok_or_else(|| GenerationError::GraphConstruction("no canonical graph".to_owned()))?;
5398        let inverse_remapping = remapping
5399            .iter()
5400            .map(|(source, target)| (*target, *source))
5401            .collect::<BTreeMap<_, _>>();
5402        let mut canonical_to_input = vec![0; graph.nodes().len()];
5403        for (input, canonical_position) in canonical.vertex_map.iter().copied().enumerate() {
5404            canonical_to_input[canonical_position] =
5405                inverse_remapping.get(&input).copied().unwrap_or(input);
5406        }
5407        let mut input_to_canonical = vec![0; graph.nodes().len()];
5408        for (canonical_position, input) in canonical_to_input.iter().copied().enumerate() {
5409            input_to_canonical[input] = canonical_position;
5410        }
5411
5412        let mut result = Graph::new();
5413        for input in canonical_to_input.iter().copied() {
5414            // Source edges retain their input owners; external labels belong
5415            // to the selected paired remapping. General incoming cycles need
5416            // the inverse above, unlike the involutive global side exchange.
5417            let data = remapping.get(&input).copied().unwrap_or(input);
5418            result.add_node(graph.nodes()[data].data.clone());
5419        }
5420
5421        let mut edges = graph
5422            .edges()
5423            .iter()
5424            .map(|edge| {
5425                let external = matches!(
5426                    graph.nodes()[edge.vertices.0].data,
5427                    ColoredNode::External(_)
5428                ) || matches!(
5429                    graph.nodes()[edge.vertices.1].data,
5430                    ColoredNode::External(_)
5431                );
5432                let external_outgoing = matches!(
5433                    graph.nodes()[edge.vertices.1].data,
5434                    ColoredNode::External(_)
5435                );
5436                let flipped = external_outgoing
5437                    || (!external
5438                        && input_to_canonical[edge.vertices.0]
5439                            > input_to_canonical[edge.vertices.1]);
5440                let vertices = if flipped {
5441                    (
5442                        input_to_canonical[edge.vertices.1],
5443                        input_to_canonical[edge.vertices.0],
5444                    )
5445                } else {
5446                    (
5447                        input_to_canonical[edge.vertices.0],
5448                        input_to_canonical[edge.vertices.1],
5449                    )
5450                };
5451                let mut data = edge.data;
5452                if edge.directed && flipped {
5453                    data.particle = model.particle_by_id(data.particle)?.antiparticle;
5454                }
5455                let particle = model.particle_by_id(data.particle)?;
5456                // CP acts on neutral adjoint Faddeev-Popov ghosts through
5457                // color, without exchanging ghost and antighost fields. Their
5458                // derivative momentum must keep its ghost-number orientation.
5459                if edge.directed
5460                    && left_right_swapped
5461                    && !(particle.is_ghost() && particle.color == 8 && particle.charge.is_zero())
5462                {
5463                    data.particle = particle.antiparticle;
5464                }
5465                let pdg_code = model.particle_by_id(data.particle)?.pdg_code;
5466                Ok((vertices, edge.directed, data, pdg_code))
5467            })
5468            .collect::<Result<Vec<_>, GenerationError>>()?;
5469        // Match the UFO/GammaLoop canonical momentum convention. Signed PDG
5470        // order is deliberately used here rather than model insertion order:
5471        // CP-conjugate charged lines can otherwise acquire the same edge/LMB
5472        // order even when their legacy canonical representatives differ.
5473        edges.sort_by_key(|(vertices, _, _, pdg_code)| (vertices.0, vertices.1, *pdg_code));
5474        for (vertices, directed, data, _) in edges {
5475            result
5476                .add_edge(vertices.0, vertices.1, directed, data)
5477                .map_err(|error| GenerationError::GraphConstruction(error.to_string()))?;
5478        }
5479        Ok(result)
5480    }
5481
5482    fn repair_cp_interaction_rules(
5483        graph: Graph<ColoredNode, EdgeColor>,
5484        model: &Model,
5485    ) -> Result<Graph<ColoredNode, EdgeColor>, GenerationError> {
5486        let mut replacements = BTreeMap::new();
5487        for (vertex, node) in graph.nodes().iter().enumerate() {
5488            let ColoredNode::Interaction(rule_id) = &node.data else {
5489                continue;
5490            };
5491            let rule = model.vertex_rule_by_id(*rule_id)?;
5492            let expected = vertex_rule_signature(model, rule)?;
5493            let mut actual = available_interaction_half_edges(&graph, vertex, model)?
5494                .into_iter()
5495                .map(|(_, signature)| signature)
5496                .collect::<Vec<_>>();
5497            actual.sort();
5498            if actual == expected {
5499                continue;
5500            }
5501
5502            let mut cp_expected = expected
5503                .iter()
5504                .map(|half_edge| HalfEdge {
5505                    direction: half_edge.direction.map(|direction| !direction),
5506                    data: half_edge.data,
5507                })
5508                .collect::<Vec<_>>();
5509            cp_expected.sort();
5510            let coupling_orders = rule.coupling_orders(model);
5511            let mut candidates = Vec::new();
5512            if actual == cp_expected {
5513                for (candidate_index, candidate) in model.vertex_rules().iter().enumerate() {
5514                    if candidate.coupling_orders(model) == coupling_orders
5515                        && vertex_rule_signature(model, candidate)? == actual
5516                    {
5517                        candidates.push((
5518                            model.vertex_rule_id_at(candidate_index)?,
5519                            candidate.name.clone(),
5520                        ));
5521                    }
5522                }
5523            }
5524            if candidates.len() != 1 {
5525                return Err(GenerationError::InvalidCpInteractionRule {
5526                    vertex,
5527                    interaction: rule.name.clone(),
5528                    candidates: candidates.into_iter().map(|(_, name)| name).collect(),
5529                });
5530            }
5531            replacements.insert(vertex, candidates[0].0);
5532        }
5533
5534        if replacements.is_empty() {
5535            return Ok(graph);
5536        }
5537        let mut repaired = Graph::new();
5538        for (vertex, node) in graph.nodes().iter().enumerate() {
5539            let data = replacements
5540                .get(&vertex)
5541                .map_or_else(|| node.data.clone(), |rule| ColoredNode::Interaction(*rule));
5542            repaired.add_node(data);
5543        }
5544        for edge in graph.edges() {
5545            repaired
5546                .add_edge(edge.vertices.0, edge.vertices.1, edge.directed, edge.data)
5547                .map_err(|error| GenerationError::GraphConstruction(error.to_string()))?;
5548        }
5549        Ok(repaired)
5550    }
5551
5552    // Normalize every fermion chain before exposing the diagram. A chain keeps
5553    // the orientation of its first external edge and all following edges are
5554    // oriented consistently with it. Purely virtual loops start from their
5555    // first edge in canonical edge order.
5556    fn normalize_fermion_flows(
5557        &self,
5558        graph: &Graph<ColoredNode, EdgeColor>,
5559        model: &Model,
5560    ) -> Result<NormalizedFermionFlow, GenerationError> {
5561        let mut adjacency = vec![Vec::new(); graph.nodes().len()];
5562        let mut degrees = vec![0; graph.nodes().len()];
5563        for (edge_id, edge) in graph.edges().iter().enumerate() {
5564            let particle = model.particle_by_id(edge.data.particle)?;
5565            if !(particle.is_fermion() || particle.is_ghost()) {
5566                continue;
5567            }
5568            let (left, right) = edge.vertices;
5569            adjacency[left].push((edge_id, right));
5570            if left == right {
5571                degrees[left] += 2;
5572            } else {
5573                adjacency[right].push((edge_id, left));
5574                degrees[left] += 1;
5575                degrees[right] += 1;
5576            }
5577        }
5578        for (vertex, degree) in degrees.iter().copied().enumerate() {
5579            if degree > 2 {
5580                return Err(GenerationError::UnsupportedFermionBranching { vertex, degree });
5581            }
5582        }
5583
5584        let external_nodes: BTreeMap<_, _> = graph
5585            .nodes()
5586            .iter()
5587            .enumerate()
5588            .filter_map(|(node_id, node)| match &node.data {
5589                ColoredNode::External(external) => {
5590                    Some((external.index, (node_id, external.clone())))
5591                }
5592                ColoredNode::Interaction(_) => None,
5593            })
5594            .collect();
5595        let mut visited_edges = vec![false; graph.edges().len()];
5596        let mut normalized_vertices = vec![None; graph.edges().len()];
5597        let mut normalized_particles = vec![None; graph.edges().len()];
5598        let mut normalization = FermionNormalizationState {
5599            visited_edges: &mut visited_edges,
5600            vertices: &mut normalized_vertices,
5601            particles: &mut normalized_particles,
5602        };
5603        // Pairing of the external fermion flows. The keys are sorted pairs of
5604        // all-incoming PDGs, and values are connected external leg IDs in the
5605        // order of that key.
5606        let mut pairings: BTreeMap<(i64, i64), Vec<(usize, usize)>> = BTreeMap::new();
5607        let mut line_pairings = Vec::new();
5608
5609        // First fix flows connected to external legs, then all internal flows.
5610        for (node_id, external) in external_nodes.values() {
5611            let Some((edge_id, _)) = adjacency[*node_id]
5612                .iter()
5613                .find(|(edge_id, _)| !normalization.visited_edges[*edge_id])
5614            else {
5615                continue;
5616            };
5617            let legs = normalize_fermion_component(
5618                graph,
5619                *edge_id,
5620                &adjacency,
5621                &mut normalization,
5622                model,
5623                false,
5624            )?;
5625            let legs = legs.into_iter().collect::<Vec<_>>();
5626            // Both spinor and ghost chains anticommute. Ghosts therefore
5627            // enter external permutation signs even though their scalar
5628            // propagators do not contribute antifermion spin sums.
5629            if !model
5630                .particle_by_id(external.particle)?
5631                .is_anticommutating()
5632            {
5633                continue;
5634            }
5635            let [first_leg, second_leg] = legs.as_slice() else {
5636                return Err(GenerationError::InvalidExternalFermionLegCount { legs });
5637            };
5638            let first = external_nodes
5639                .get(first_leg)
5640                .ok_or(GenerationError::MissingExternalParticle { index: *first_leg })?;
5641            let second = external_nodes
5642                .get(second_leg)
5643                .ok_or(GenerationError::MissingExternalParticle { index: *second_leg })?;
5644            let first_particle = all_incoming_particle(&first.1, model)?;
5645            let second_particle = all_incoming_particle(&second.1, model)?;
5646            let (anti_leg, anti, particle_leg, particle) = match (
5647                first_particle.is_anticommutating(),
5648                first_particle.is_antiparticle(),
5649                second_particle.is_anticommutating(),
5650                second_particle.is_antiparticle(),
5651            ) {
5652                (true, true, true, false) => {
5653                    (*first_leg, first_particle, *second_leg, second_particle)
5654                }
5655                (true, false, true, true) => {
5656                    (*second_leg, second_particle, *first_leg, first_particle)
5657                }
5658                _ => {
5659                    return Err(GenerationError::InvalidExternalFermionPair {
5660                        legs: [*first_leg, *second_leg],
5661                        particles: [first_particle.pdg_code, second_particle.pdg_code],
5662                    });
5663                }
5664            };
5665            pairings
5666                .entry((anti.pdg_code, particle.pdg_code))
5667                .or_default()
5668                .push((anti_leg, particle_leg));
5669            line_pairings.push((*first_leg, *second_leg));
5670        }
5671        for edge_id in 0..graph.edges().len() {
5672            let particle = model.particle_by_id(graph.edges()[edge_id].data.particle)?;
5673            if (particle.is_fermion() || particle.is_ghost())
5674                && !normalization.visited_edges[edge_id]
5675            {
5676                normalize_fermion_component(
5677                    graph,
5678                    edge_id,
5679                    &adjacency,
5680                    &mut normalization,
5681                    model,
5682                    true,
5683                )?;
5684            }
5685        }
5686
5687        let mut normalized_graph = Graph::new();
5688        for node in graph.nodes() {
5689            normalized_graph.add_node(node.data.clone());
5690        }
5691        let mut reversed_edges = BTreeSet::new();
5692        for (edge_id, edge) in graph.edges().iter().enumerate() {
5693            let particle = model.particle_by_id(edge.data.particle)?;
5694            let canonicalize_virtual_antiparticle = normalized_vertices[edge_id].is_none()
5695                && matches!(
5696                    (
5697                        &graph.nodes()[edge.vertices.0].data,
5698                        &graph.nodes()[edge.vertices.1].data
5699                    ),
5700                    (ColoredNode::Interaction(_), ColoredNode::Interaction(_))
5701                )
5702                && particle.is_antiparticle()
5703                && !(particle.is_fermion() || particle.is_ghost());
5704            let (left, right) = normalized_vertices[edge_id].unwrap_or({
5705                if canonicalize_virtual_antiparticle {
5706                    (edge.vertices.1, edge.vertices.0)
5707                } else {
5708                    edge.vertices
5709                }
5710            });
5711            let mut data = edge.data;
5712            data.particle = normalized_particles[edge_id].unwrap_or({
5713                if canonicalize_virtual_antiparticle {
5714                    particle.antiparticle
5715                } else {
5716                    edge.data.particle
5717                }
5718            });
5719            if (left, right) != edge.vertices {
5720                reversed_edges.insert(EdgeId(edge_id));
5721            }
5722            normalized_graph
5723                .add_edge(left, right, edge.directed, data)
5724                .map_err(|error| GenerationError::GraphConstruction(error.to_string()))?;
5725        }
5726
5727        let concatenated_lines = pairings
5728            .values()
5729            .flat_map(|lines| lines.iter().flat_map(|(anti, particle)| [*anti, *particle]))
5730            .collect::<Vec<_>>();
5731        let external_ordering_negative = match self.generation_type {
5732            GenerationType::Amplitude
5733                if self.symmetrize_external_fermions
5734                    && (self.symmetrize_initial || self.symmetrize_final) =>
5735            {
5736                false
5737            }
5738            GenerationType::Amplitude => permutation_is_odd(&concatenated_lines),
5739            GenerationType::CrossSection => {
5740                // Sewing permutes n external fermion chains into c cycles, with
5741                // parity (-1)^(n-c) = (-1)^(n+c). This is not the separate
5742                // virtual-loop sign: closing a single chain is an even
5743                // permutation. Internal cycles, cut antifermion propagators,
5744                // and sewn antifermion spin sums carry their own signs.
5745                // The crossed-decay regression compares the full covariant
5746                // sector to positive physical Dirac spin sums for both charges.
5747                (line_pairings.len() + self.external_fermion_loop_count(&line_pairings)?) % 2 == 1
5748            }
5749        };
5750        let antifermion_spin_sum_negative = self.generation_type == GenerationType::CrossSection
5751            && self
5752                .incoming
5753                .iter()
5754                .filter(|particle| particle.is_fermion() && particle.is_antiparticle())
5755                .count()
5756                % 2
5757                == 1;
5758
5759        Ok(NormalizedFermionFlow {
5760            graph: normalized_graph,
5761            reversed_edges,
5762            signs: FermionSigns {
5763                internal_loop_negative: false,
5764                include_external_ordering: self.generation_type == GenerationType::CrossSection
5765                    || !(self.symmetrize_external_fermions
5766                        && (self.symmetrize_initial || self.symmetrize_final)),
5767                external_ordering_negative,
5768                include_antifermion_spin_sum: self.generation_type == GenerationType::CrossSection,
5769                antifermion_spin_sum_negative,
5770            },
5771        })
5772    }
5773
5774    fn external_fermion_loop_count(
5775        &self,
5776        line_pairings: &[(usize, usize)],
5777    ) -> Result<usize, GenerationError> {
5778        let mut adjacency: BTreeMap<usize, Vec<usize>> = BTreeMap::new();
5779        let mut connect = |left: usize, right: usize| {
5780            adjacency.entry(left).or_default().push(right);
5781            adjacency.entry(right).or_default().push(left);
5782        };
5783        for &(left, right) in line_pairings {
5784            connect(left, right);
5785        }
5786        for (index, particle) in self.incoming.iter().enumerate() {
5787            if particle.is_anticommutating() {
5788                connect(index, self.incoming.len() + index);
5789            }
5790        }
5791        for (&leg, neighbors) in &adjacency {
5792            if neighbors.len() != 2 {
5793                return Err(GenerationError::InvalidExternalFermionLoopDegree {
5794                    leg,
5795                    degree: neighbors.len(),
5796                });
5797            }
5798        }
5799
5800        let mut visited = BTreeSet::new();
5801        let mut loops = 0;
5802        for &start in adjacency.keys() {
5803            if !visited.insert(start) {
5804                continue;
5805            }
5806            loops += 1;
5807            let mut stack = vec![start];
5808            while let Some(leg) = stack.pop() {
5809                if let Some(neighbors) = adjacency.get(&leg) {
5810                    for &neighbor in neighbors {
5811                        if visited.insert(neighbor) {
5812                            stack.push(neighbor);
5813                        }
5814                    }
5815                }
5816            }
5817        }
5818        Ok(loops)
5819    }
5820
5821    fn vertex_half_edge(
5822        model: &Model,
5823        particle: &Particle,
5824    ) -> Result<HalfEdge<EdgeColor>, GenerationError> {
5825        let base = if particle.is_antiparticle() {
5826            particle.antiparticle
5827        } else {
5828            model.particle_id(&particle.name)?
5829        };
5830        Ok(HalfEdge {
5831            direction: if model.particle_is_self_conjugate(model.particle_id(&particle.name)?) {
5832                None
5833            } else {
5834                Some(particle.is_antiparticle())
5835            },
5836            data: EdgeColor {
5837                particle: base,
5838                direction: None,
5839            },
5840        })
5841    }
5842
5843    // Enumerate exact s-channel cuts for cross-section generation. The caller
5844    // applies amplitude-level constraints to the returned partitions.
5845    fn cut_partitions(
5846        &self,
5847        graph: &Graph<ColoredNode, EdgeColor>,
5848        model: &Model,
5849        options: &GenerationOptions,
5850    ) -> Result<CutPartitionInventory, GenerationError> {
5851        let targets: Vec<Vec<ParticleId>> = self
5852            .outgoing
5853            .iter()
5854            .map(|particles| {
5855                let mut particle_ids = particles
5856                    .iter()
5857                    .map(|particle| model.particle_id(&particle.name))
5858                    .collect::<Result<Vec<_>, _>>()?;
5859                particle_ids.sort();
5860                Ok(particle_ids)
5861            })
5862            .collect::<Result<_, ModelError>>()?;
5863        let he_graph: HedgeGraph<EdgeColor, ColoredNode, ()> = graph.clone().into();
5864        // Legacy cross-section cuts were enumerated after sewing each incoming
5865        // external leg to its outgoing partner.  The resulting source/target
5866        // nodes are the internal attachment nodes, and an initial-state edge
5867        // can therefore never itself be part of an s-channel cut.  On the
5868        // canonical pre-sewn FeynKit graph, force every degree-one external
5869        // vertex and its internal attachment onto the same side to reproduce
5870        // that topology exactly.
5871        let mut source = BTreeSet::new();
5872        let mut target = BTreeSet::new();
5873        let mut external_source = Vec::new();
5874        let mut external_target = Vec::new();
5875        for (node_id, neighbours, node) in he_graph.iter_nodes() {
5876            if let ColoredNode::External(external) = node {
5877                let incident = neighbours.collect::<Vec<_>>();
5878                if incident.len() != 1 {
5879                    return Err(GenerationError::GraphConstruction(format!(
5880                        "cross-section external vertex {node_id:?} has degree {}, expected one",
5881                        incident.len(),
5882                    )));
5883                }
5884                let attachment = he_graph.node_id(he_graph.inv(incident[0]));
5885                match external.state {
5886                    ExternalState::Incoming => {
5887                        source.insert(node_id);
5888                        source.insert(attachment);
5889                        external_source.push(node_id);
5890                    }
5891                    ExternalState::Outgoing => {
5892                        target.insert(node_id);
5893                        target.insert(attachment);
5894                        external_target.push(node_id);
5895                    }
5896                }
5897            }
5898        }
5899        if source.is_empty() || target.is_empty() {
5900            // Vacuum or degenerate graphs have no physical s-channel cut.
5901            return Ok(CutPartitionInventory::default());
5902        }
5903        let default_blob_range = 1..=1;
5904        let blob_range = options
5905            .graph_filters
5906            .iter()
5907            .find_map(|filter| match filter {
5908                GenerationFilter::BlobRange(range) => Some(range),
5909                _ => None,
5910            })
5911            .unwrap_or(&default_blob_range);
5912
5913        let default_spectator_range = 0..=0;
5914        let spectator_range = options
5915            .graph_filters
5916            .iter()
5917            .find_map(|filter| match filter {
5918                GenerationFilter::SpectatorRange(range) => Some(range),
5919                _ => None,
5920            })
5921            .unwrap_or(&default_spectator_range);
5922
5923        // Count the blobs and spectators of one cut side. A component with more
5924        // than one included half-edge is a blob; a singleton is the external
5925        // half-edge of an initial-state edge crossed by the cut, a spectator.
5926        let side_shape = |subgraph: &SuBitGraph| {
5927            let mut blobs = 0;
5928            let mut spectators = 0;
5929            for component in he_graph.connected_components(subgraph) {
5930                if component.n_included() > 1 {
5931                    blobs += 1;
5932                } else {
5933                    spectators += 1;
5934                }
5935            }
5936            (blobs, spectators)
5937        };
5938        let physical_side =
5939            |(blobs, spectators): (usize, usize)| spectators == 0 && blob_range.contains(&blobs);
5940        let spectator_side = |subgraph: &SuBitGraph| {
5941            let (blobs, spectators) = side_shape(subgraph);
5942            blob_range.contains(&blobs) && spectator_range.contains(&spectators)
5943        };
5944        // Convert sink-oriented cut half-edges to antiparticles so the content
5945        // describes the physical state crossing left to right.
5946        let matches_final_state = |cut_left: &SuBitGraph| -> Result<bool, GenerationError> {
5947            let mut cut_content = cut_left
5948                .included_iter()
5949                .map(|hedge| {
5950                    let particle = he_graph[[&hedge]].particle;
5951                    if matches!(he_graph.flow(hedge), Flow::Sink) {
5952                        Ok(model.particle_by_id(particle)?.antiparticle)
5953                    } else {
5954                        Ok(particle)
5955                    }
5956                })
5957                .collect::<Result<Vec<_>, ModelError>>()?;
5958            cut_content.sort();
5959            Ok(targets.iter().any(|target| {
5960                Self::matches_cut_content(&cut_content, target, self.unresolved.as_ref())
5961            }))
5962        };
5963
5964        let stable_half_edges = |subgraph: &SuBitGraph| {
5965            let mut half_edges = subgraph
5966                .included_iter()
5967                .map(|hedge| DiagramHalfEdge {
5968                    edge: EdgeId(he_graph[&hedge].0),
5969                    endpoint: match he_graph.flow(hedge) {
5970                        Flow::Source => DiagramEndpoint::Source,
5971                        Flow::Sink => DiagramEndpoint::Target,
5972                    },
5973                })
5974                .collect::<Vec<_>>();
5975            half_edges.sort();
5976            half_edges.dedup();
5977            half_edges
5978        };
5979        let summarize_side = |subgraph: &SuBitGraph| -> Result<DiagramCutSide, GenerationError> {
5980            let mut coupling_orders = BTreeMap::new();
5981            for (_, _, node) in he_graph.iter_nodes_of(subgraph) {
5982                let ColoredNode::Interaction(rule_id) = node else {
5983                    continue;
5984                };
5985                for (name, order) in model.vertex_rule_by_id(*rule_id)?.coupling_orders(model) {
5986                    *coupling_orders.entry(name).or_insert(0) += order;
5987                }
5988            }
5989            let internal = InternalSubGraph::cleaned_filter_pessimist(subgraph.clone(), &he_graph);
5990            Ok(DiagramCutSide {
5991                half_edges: stable_half_edges(subgraph),
5992                coupling_orders,
5993                loop_count: he_graph.cyclotomatic_number(&internal),
5994            })
5995        };
5996
5997        let forward = ForwardGraph::new(&he_graph, &external_source, &external_target)
5998            .map_err(|error| GenerationError::GraphConstruction(error.to_string()))?;
5999        let mut inventory = CutPartitionInventory {
6000            physical_satisfies_spectator_range: spectator_range.contains(&0),
6001            ..CutPartitionInventory::default()
6002        };
6003        let source = source.into_iter().collect::<Vec<_>>();
6004        let target = target.into_iter().collect::<Vec<_>>();
6005        let mut enumerated = BTreeSet::new();
6006        for (_, cut, _) in he_graph.all_cuts_from_ids(&source, &target) {
6007            // Keep this guard even though the seeded attachment nodes make
6008            // such a cut impossible: serialized threshold candidates must
6009            // never rely on the runtime bridge stripping a crossing edge.
6010            if forward.crosses_leg(&cut.left) {
6011                continue;
6012            }
6013            // The search keeps the far half of a bridge it skips on the source
6014            // side. Rebuild whole vertex sides from the boundary, so that a
6015            // vertex behind such a bridge stays with its neighbours.
6016            let Some(partition) = forward.partition(&cut.left) else {
6017                continue;
6018            };
6019            enumerated.insert(cut.left);
6020            let cut_half_edges = stable_half_edges(partition.cut());
6021            let left_shape = side_shape(partition.left());
6022            let right_shape = side_shape(partition.right());
6023            if cut_half_edges.len() > 1 {
6024                inventory
6025                    .topology_threshold_candidates
6026                    .push(DiagramThresholdCandidate {
6027                        cut: cut_half_edges.clone(),
6028                        left: stable_half_edges(partition.left()),
6029                        right: stable_half_edges(partition.right()),
6030                    });
6031            }
6032            if physical_side(left_shape)
6033                && physical_side(right_shape)
6034                && matches_final_state(partition.cut())?
6035            {
6036                inventory.physical.push(DiagramCut {
6037                    cut: cut_half_edges,
6038                    left: summarize_side(partition.left())?,
6039                    right: summarize_side(partition.right())?,
6040                });
6041            }
6042        }
6043
6044        // As on main, also enumerate with only the degree-one external vertices
6045        // fixed. The search above grows the source side one vertex at a time
6046        // and drops every step whose target side has more components than the
6047        // fixed target nodes. With adjacent outgoing attachments, a subgraph
6048        // attached only to incoming attachments (such as a self-energy on the
6049        // internal line between them) is a second target component from the
6050        // start, so it never reaches a cut that places it on the incoming side.
6051        // This search has one fixed component per leg. It supplies the
6052        // partitions the first one missed: a physical cut when the sides
6053        // satisfy the requested blob range and final state, and a threshold
6054        // candidate only when both sides are connected, independently of the
6055        // process, so that it adds no disconnected threshold candidates.
6056        for found in forward.leg_seeded_cuts(|boundary| enumerated.contains(boundary)) {
6057            match found {
6058                LegSeededCut::Partition(partition) => {
6059                    let cut_half_edges = stable_half_edges(partition.cut());
6060                    let left_shape = side_shape(partition.left());
6061                    let right_shape = side_shape(partition.right());
6062                    if cut_half_edges.len() > 1 && left_shape == (1, 0) && right_shape == (1, 0) {
6063                        inventory
6064                            .topology_threshold_candidates
6065                            .push(DiagramThresholdCandidate {
6066                                cut: cut_half_edges.clone(),
6067                                left: stable_half_edges(partition.left()),
6068                                right: stable_half_edges(partition.right()),
6069                            });
6070                    }
6071                    if physical_side(left_shape)
6072                        && physical_side(right_shape)
6073                        && matches_final_state(partition.cut())?
6074                    {
6075                        inventory.physical.push(DiagramCut {
6076                            cut: cut_half_edges,
6077                            left: summarize_side(partition.left())?,
6078                            right: summarize_side(partition.right())?,
6079                        });
6080                    }
6081                }
6082                // Main counted a spectator when a cut crossed an initial-state
6083                // edge. It separates that edge's attachment node from its
6084                // external vertex, so it is not an s-t cut of the sewn graph
6085                // and is kept only to select the graph, never as a physical
6086                // cut or threshold candidate.
6087                LegSeededCut::CrossesLeg { left, cut, right } => {
6088                    if *spectator_range.end() > 0
6089                        && spectator_side(&left)
6090                        && spectator_side(&right)
6091                        && matches_final_state(&cut.left)?
6092                    {
6093                        inventory.spectator.push(DiagramCut {
6094                            cut: stable_half_edges(&cut.left),
6095                            left: summarize_side(&left)?,
6096                            right: summarize_side(&right)?,
6097                        });
6098                    }
6099                }
6100            }
6101        }
6102        Ok(inventory)
6103    }
6104
6105    /// Record a spectator cut found by [`Self::cut_partitions`] for a
6106    /// selection-only diagram. Crossed initial-state legs become spectators
6107    /// named by their external connection, as the diagram builder assigns it;
6108    /// every other crossed edge keeps its left half-edge.
6109    fn spectator_cut(
6110        &self,
6111        graph: &Graph<ColoredNode, EdgeColor>,
6112        cut: &DiagramCut,
6113    ) -> DiagramSpectatorCut {
6114        let mut record = DiagramSpectatorCut {
6115            cut: Vec::new(),
6116            left_spectators: Vec::new(),
6117            right_spectators: Vec::new(),
6118        };
6119        for half_edge in &cut.cut {
6120            let (source, target) = graph.edges()[half_edge.edge.0].vertices;
6121            let external =
6122                [source, target]
6123                    .into_iter()
6124                    .find_map(|node| match &graph.nodes()[node].data {
6125                        ColoredNode::External(external) => Some(external),
6126                        ColoredNode::Interaction(_) => None,
6127                    });
6128            match external {
6129                Some(ExternalNode {
6130                    index,
6131                    state: ExternalState::Incoming,
6132                    ..
6133                }) => record.left_spectators.push(*index),
6134                Some(ExternalNode {
6135                    index,
6136                    state: ExternalState::Outgoing,
6137                    ..
6138                }) => record.right_spectators.push(*index - self.incoming.len()),
6139                None => record.cut.push(*half_edge),
6140            }
6141        }
6142        record
6143    }
6144
6145    fn matches_cut_content(
6146        cut_content: &[ParticleId],
6147        target: &[ParticleId],
6148        unresolved: Option<&UnresolvedCutContent>,
6149    ) -> bool {
6150        let mut remainder = cut_content.to_vec();
6151        for particle in target {
6152            let Some(position) = remainder.iter().position(|candidate| candidate == particle)
6153            else {
6154                return false;
6155            };
6156            remainder.remove(position);
6157        }
6158        remainder.is_empty()
6159            || unresolved.is_some_and(|unresolved| {
6160                remainder.len() <= unresolved.maximum_multiplicity
6161                    && remainder
6162                        .iter()
6163                        .all(|particle| unresolved.particles.contains(particle))
6164            })
6165    }
6166
6167    fn passes_sewn_filter(
6168        &self,
6169        graph: &Graph<ColoredNode, EdgeColor>,
6170        options: &GenerationOptions,
6171    ) -> bool {
6172        let Some(SewnFilterOptions {
6173            filter_tadpoles: true,
6174        }) = options
6175            .graph_filters
6176            .iter()
6177            .find_map(|filter| match filter {
6178                GenerationFilter::Sewn(options) => Some(*options),
6179                _ => None,
6180            })
6181        else {
6182            return true;
6183        };
6184
6185        let mut graph: HedgeGraph<EdgeColor, ColoredNode, ()> = graph.clone().into();
6186        let external_nodes: Vec<_> = graph
6187            .iter_nodes()
6188            .filter_map(|(node, _, color)| match color {
6189                ColoredNode::External(external) => Some((external.index, node, color.clone())),
6190                ColoredNode::Interaction(_) => None,
6191            })
6192            .collect();
6193        let externals: Vec<_> = external_nodes.iter().map(|(_, node, _)| *node).collect();
6194        if externals.is_empty() {
6195            return true;
6196        }
6197        let connected_components_before = graph
6198            .tadpoles(&externals)
6199            .expect("external nodes are distinct graph terminals with incident edges")
6200            .len()
6201            + 1;
6202        let by_index: BTreeMap<usize, (NodeIndex, ColoredNode)> = external_nodes
6203            .into_iter()
6204            .map(|(index, node, color)| (index, (node, color)))
6205            .collect();
6206        for incoming in 0..self.incoming.len() {
6207            let outgoing = self.incoming.len() + incoming;
6208            if let (Some((left, color)), Some((right, _))) =
6209                (by_index.get(&incoming), by_index.get(&outgoing))
6210            {
6211                graph.identify_nodes(&[*left, *right], color.clone());
6212            }
6213        }
6214        // NodeStorageVec retains the crowns of nodes that were identified so
6215        // callers can inspect the identification history. Cycle detection must
6216        // run on the sewn quotient graph, without those historical crowns.
6217        graph.forget_identification_history();
6218        let non_bridges = graph.non_bridges();
6219        graph.count_connected_components(&non_bridges) == connected_components_before
6220    }
6221}
6222
6223#[cfg(test)]
6224mod tests {
6225    use crate::{CancellationToken, GraphGroupingOptions, NumeratorGrouping};
6226    use feynkit_model::Model;
6227    use symbolica::parser::ParseSettings;
6228
6229    use super::*;
6230    use feynkit_graph::VertexId;
6231    use idenso::tensor::composition::TensorCompositionError;
6232    use idenso::tensor::inference::TensorInferenceError;
6233    use serde_json::json;
6234    use spenso::tensor_symbol;
6235    use std::array;
6236    #[cfg(not(target_arch = "wasm32"))]
6237    use std::env;
6238    #[cfg(not(target_arch = "wasm32"))]
6239    use std::process::Command;
6240    use symbolica::function;
6241
6242    fn test_atom(expression: &str) -> Atom {
6243        Atom::parse(expression, "UFO", ParseSettings::default()).unwrap()
6244    }
6245
6246    fn factor_atom(expression: &str) -> Atom {
6247        Atom::parse(
6248            expression,
6249            "feynkit_generator_factor",
6250            ParseSettings::default(),
6251        )
6252        .unwrap()
6253    }
6254
6255    fn function_count(expression: &Atom, head: symbolica::atom::Symbol) -> usize {
6256        let mut count = 0;
6257        let _ = expression.replace_map(|term, _, _| {
6258            if matches!(term, AtomView::Fun(function) if function.get_symbol() == head) {
6259                count += 1;
6260            }
6261        });
6262        count
6263    }
6264
6265    fn tensor_test_legs() -> [NumeratorHalfEdge; 4] {
6266        [
6267            NumeratorHalfEdge {
6268                edge: 10,
6269                flow: Flow::Source,
6270                hedge: 20,
6271                spin: 2,
6272                color: -3,
6273            },
6274            NumeratorHalfEdge {
6275                edge: 20,
6276                flow: Flow::Sink,
6277                hedge: 41,
6278                spin: 2,
6279                color: 3,
6280            },
6281            NumeratorHalfEdge {
6282                edge: 30,
6283                flow: Flow::Source,
6284                hedge: 60,
6285                spin: 3,
6286                color: 8,
6287            },
6288            NumeratorHalfEdge {
6289                edge: 40,
6290                flow: Flow::Sink,
6291                hedge: 81,
6292                spin: 3,
6293                color: 8,
6294            },
6295        ]
6296    }
6297
6298    fn scalar_model() -> Model {
6299        Model::from_json(
6300            r#"{
6301                "name":"phi3",
6302                "restriction":null,
6303                "orders":[{"name":"QED","expansion_order":99,"hierarchy":1}],
6304                "parameters":[
6305                    {"name":"ZERO","lhablock":null,"lhacode":null,"nature":"internal","parameter_type":"real","value":[0.0,0.0],"expression":null},
6306                    {"name":"M","lhablock":"MASS","lhacode":[25],"nature":"external","parameter_type":"real","value":[1.0,0.0],"expression":null}
6307                ],
6308                "particles":[
6309                    {"pdg_code":25,"name":"phi","antiname":"phi","spin":1,"color":1,"mass":"M","width":"ZERO","texname":"phi","antitexname":"phi","charge":0.0,"ghost_number":0,"lepton_number":0,"y_charge":0}
6310                ],
6311                "propagators":[
6312                    {"name":"phi_prop","particle":"phi","numerator":"1","denominator":"P^2-M^2"}
6313                ],
6314                "lorentz_structures":[
6315                    {"name":"L1","spins":[1,1,1],"structure":"1"}
6316                ],
6317                "couplings":[
6318                    {"name":"GC1","expression":"g","orders":[["QED",1]],"value":null}
6319                ],
6320                "vertex_rules":[
6321                    {"name":"V1","particles":["phi","phi","phi"],"color_structures":["1"],"lorentz_structures":["L1"],"couplings":[["GC1"]]}
6322                ],
6323                "functions":[],
6324                "form_factors":[]
6325            }"#,
6326        )
6327        .unwrap()
6328    }
6329
6330    fn fermion_model() -> Model {
6331        Model::from_json(
6332            r#"{
6333                "name":"toy_qed",
6334                "restriction":null,
6335                "orders":[
6336                    {"name":"QED","expansion_order":99,"hierarchy":1},
6337                    {"name":"QCD","expansion_order":99,"hierarchy":1}
6338                ],
6339                "parameters":[
6340                    {"name":"ZERO","lhablock":null,"lhacode":null,"nature":"internal",
6341                     "parameter_type":"real","value":[0.0,0.0],"expression":null},
6342                    {"name":"M","lhablock":"MASS","lhacode":[25],"nature":"external",
6343                     "parameter_type":"real","value":[1.0,0.0],"expression":null}
6344                ],
6345                "particles":[
6346                    {"pdg_code":1,"name":"f","antiname":"f~","spin":2,"color":1,
6347                     "mass":"ZERO","width":"ZERO","texname":"f","antitexname":"f~",
6348                     "charge":-1.0,"ghost_number":0,"lepton_number":1,"y_charge":0},
6349                    {"pdg_code":-1,"name":"f~","antiname":"f","spin":2,"color":1,
6350                     "mass":"ZERO","width":"ZERO","texname":"f~","antitexname":"f",
6351                     "charge":1.0,"ghost_number":0,"lepton_number":-1,"y_charge":0},
6352                    {"pdg_code":22,"name":"a","antiname":"a","spin":3,"color":1,
6353                     "mass":"ZERO","width":"ZERO","texname":"a","antitexname":"a",
6354                     "charge":0.0,"ghost_number":0,"lepton_number":0,"y_charge":0},
6355                    {"pdg_code":25,"name":"phi","antiname":"phi","spin":1,"color":1,
6356                     "mass":"M","width":"ZERO","texname":"phi","antitexname":"phi",
6357                     "charge":0.0,"ghost_number":0,"lepton_number":0,"y_charge":0}
6358                ],
6359                "propagators":[
6360                    {"name":"f_prop","particle":"f","numerator":"PSlash(2,1)","denominator":"P^2"},
6361                    {"name":"a_prop","particle":"a","numerator":"1","denominator":"P^2"}
6362                ],
6363                "lorentz_structures":[{
6364                    "name":"FFV","spins":[2,2,3],"structure":"Gamma(3,2,1)"
6365                }],
6366                "couplings":[
6367                    {"name":"GC_LOW","expression":"g_low","orders":[["QED",1]],"value":null},
6368                    {"name":"GC_HIGH","expression":"g_high","orders":[["QED",3],["QCD",2]],"value":null}
6369                ],
6370                "vertex_rules":[{
6371                    "name":"V","particles":["f~","f","a"],
6372                    "color_structures":["1","1"],
6373                    "lorentz_structures":["FFV"],
6374                    "couplings":[["GC_LOW"],["GC_HIGH"]]
6375                }]
6376            }"#,
6377        )
6378        .unwrap()
6379    }
6380
6381    fn exact_cut_model() -> Model {
6382        Model::from_json(
6383            r#"{
6384                "name":"exact_cut_regression",
6385                "restriction":null,
6386                "orders":[
6387                    {"name":"QED","expansion_order":99,"hierarchy":2},
6388                    {"name":"QCD","expansion_order":99,"hierarchy":1}
6389                ],
6390                "parameters":[
6391                    {"name":"ZERO","lhablock":null,"lhacode":null,"nature":"internal",
6392                     "parameter_type":"real","value":[0.0,0.0],"expression":null},
6393                    {"name":"M","lhablock":"MASS","lhacode":[1],"nature":"external",
6394                     "parameter_type":"real","value":[1.0,0.0],"expression":null}
6395                ],
6396                "particles":[
6397                    {"pdg_code":22,"name":"a","antiname":"a","spin":3,"color":1,
6398                     "mass":"ZERO","width":"ZERO","texname":"a","antitexname":"a",
6399                     "charge":0.0,"ghost_number":0,"lepton_number":0,"y_charge":0},
6400                    {"pdg_code":21,"name":"g","antiname":"g","spin":3,"color":8,
6401                     "mass":"ZERO","width":"ZERO","texname":"g","antitexname":"g",
6402                     "charge":0.0,"ghost_number":0,"lepton_number":0,"y_charge":0},
6403                    {"pdg_code":5,"name":"b","antiname":"b~","spin":2,"color":3,
6404                     "mass":"M","width":"ZERO","texname":"b","antitexname":"b~",
6405                     "charge":"-1/3","ghost_number":0,"lepton_number":0,"y_charge":0},
6406                    {"pdg_code":-5,"name":"b~","antiname":"b","spin":2,"color":-3,
6407                     "mass":"M","width":"ZERO","texname":"b~","antitexname":"b",
6408                     "charge":"1/3","ghost_number":0,"lepton_number":0,"y_charge":0},
6409                    {"pdg_code":25,"name":"H","antiname":"H","spin":1,"color":1,
6410                     "mass":"M","width":"ZERO","texname":"H","antitexname":"H",
6411                     "charge":0.0,"ghost_number":0,"lepton_number":0,"y_charge":0},
6412                    {"pdg_code":11,"name":"e-","antiname":"e+","spin":2,"color":1,
6413                     "mass":"M","width":"ZERO","texname":"e-","antitexname":"e+",
6414                     "charge":-1.0,"ghost_number":0,"lepton_number":1,"y_charge":0},
6415                    {"pdg_code":-11,"name":"e+","antiname":"e-","spin":2,"color":1,
6416                     "mass":"M","width":"ZERO","texname":"e+","antitexname":"e-",
6417                     "charge":1.0,"ghost_number":0,"lepton_number":-1,"y_charge":0}
6418                ],
6419                "propagators":[],
6420                "lorentz_structures":[
6421                    {"name":"FFV","spins":[2,2,3],"structure":"Gamma(3,2,1)"},
6422                    {"name":"FFS","spins":[2,2,1],"structure":"1"}
6423                ],
6424                "couplings":[
6425                    {"name":"GC_QED","expression":"ee","orders":[["QED",1]],"value":null},
6426                    {"name":"GC_QCD","expression":"gs","orders":[["QCD",1]],"value":null}
6427                ],
6428                "vertex_rules":[
6429                    {"name":"V_73","particles":["b~","b","a"],"color_structures":["1"],
6430                     "lorentz_structures":["FFV"],"couplings":[["GC_QED"]]},
6431                    {"name":"V_76","particles":["b~","b","g"],"color_structures":["1"],
6432                     "lorentz_structures":["FFV"],"couplings":[["GC_QCD"]]},
6433                    {"name":"V_78","particles":["b~","b","H"],"color_structures":["1"],
6434                     "lorentz_structures":["FFS"],"couplings":[["GC_QED"]]},
6435                    {"name":"V_98","particles":["e+","e-","a"],"color_structures":["1"],
6436                     "lorentz_structures":["FFV"],"couplings":[["GC_QED"]]}
6437                ]
6438            }"#,
6439        )
6440        .unwrap()
6441    }
6442
6443    fn standard_model() -> Model {
6444        Model::from_json(include_str!("../../feynkit-model/tests/fixtures/sm.json")).unwrap()
6445    }
6446
6447    fn photon_process() -> Process {
6448        Process::new([22_i64], [22_i64])
6449    }
6450
6451    fn scalar_cross_section_process() -> Process {
6452        Process::new(["phi", "phi"], ["phi", "phi"])
6453    }
6454
6455    fn particle(model: &Model, pdg: i64) -> ParticleId {
6456        model.particle_id_by_pdg(pdg).unwrap()
6457    }
6458
6459    fn vertex(model: &Model, name: &str) -> VertexRuleId {
6460        model.vertex_rule_id(name).unwrap()
6461    }
6462
6463    fn edge(model: &Model, pdg: i64) -> EdgeColor {
6464        EdgeColor {
6465            particle: particle(model, pdg),
6466            direction: None,
6467        }
6468    }
6469
6470    #[test]
6471    fn loop_one_particle_irreducibility_preserves_trees_in_mixed_ranges() {
6472        let generator = Generator::new(scalar_model());
6473        let process = Process::new(["phi", "phi"], ["phi", "phi"]);
6474        let options = GenerationOptions::default()
6475            .with_loop_count(0, 1)
6476            .unwrap()
6477            .threads(1)
6478            .max_vertices(4);
6479        let automatic = options
6480            .clone()
6481            .with_graph_filter(GenerationFilter::LoopOneParticleIrreducible);
6482        assert_eq!(automatic.max_bridges(0), None);
6483        assert_eq!(automatic.max_bridges(1), Some(0));
6484
6485        let all = generator
6486            .generate(&process, &options, GenerationType::Amplitude)
6487            .unwrap();
6488        let filtered = generator
6489            .generate(&process, &automatic, GenerationType::Amplitude)
6490            .unwrap();
6491        let strict = generator
6492            .generate(
6493                &process,
6494                &options.with_graph_filter(GenerationFilter::MaxNumberOfBridges(0)),
6495                GenerationType::Amplitude,
6496            )
6497            .unwrap();
6498        let ids = |result: &GenerationResult, loops| {
6499            result
6500                .diagrams
6501                .iter()
6502                .filter(|diagram| diagram.loop_count() == loops)
6503                .map(FeynmanDiagram::id)
6504                .collect::<BTreeSet<_>>()
6505        };
6506        assert_eq!(
6507            ids(&filtered, 0).len(),
6508            3,
6509            "all tree exchange channels survive"
6510        );
6511        assert_eq!(ids(&filtered, 0), ids(&all, 0));
6512        assert!(
6513            ids(&strict, 0).is_empty(),
6514            "an explicit bridge limit remains literal"
6515        );
6516        assert!(!ids(&filtered, 1).is_empty());
6517        assert_eq!(ids(&filtered, 1), ids(&strict, 1));
6518        assert!(
6519            ids(&all, 1).len() > ids(&filtered, 1).len(),
6520            "1PR loop diagrams are removed"
6521        );
6522
6523        let loops_only = generator
6524            .generate(
6525                &process,
6526                &automatic.with_loop_count(1, 1).unwrap(),
6527                GenerationType::Amplitude,
6528            )
6529            .unwrap();
6530        assert_eq!(
6531            ids(&loops_only, 1),
6532            ids(&filtered, 1),
6533            "early pruning preserves the result"
6534        );
6535    }
6536
6537    #[test]
6538    fn generates_tree_and_one_loop_diagrams() {
6539        let generator = Generator::new(scalar_model());
6540        let process = Process::new(["phi"], ["phi", "phi"]);
6541        let generated = generator
6542            .generate(
6543                &process,
6544                &GenerationOptions::default()
6545                    .with_loop_count(0, 1)
6546                    .unwrap()
6547                    .allow_self_loops(true),
6548                GenerationType::Amplitude,
6549            )
6550            .unwrap();
6551        assert!(!generated.diagrams.is_empty());
6552        assert!(generated.report.completed);
6553        assert!(
6554            generated
6555                .diagrams
6556                .iter()
6557                .all(|diagram| !diagram.numerator().is_zero())
6558        );
6559    }
6560
6561    #[test]
6562    fn automatic_cross_section_projectors_close_initial_colors_without_averaging() {
6563        let model =
6564            Model::from_json(include_str!("../../feynkit-model/tests/fixtures/sm.json")).unwrap();
6565        let generator = Generator::new(model);
6566        for pdg in [1, -1, 21] {
6567            // Undirected edges sort their endpoints, so the incoming gluon uses hedge 0;
6568            // directed fermions use hedge 1. The outgoing endpoint is hedge 2.
6569            let mut graph = Graph::new();
6570            let owner = graph.add_node(ColoredNode::Interaction(vertex(&generator.model, "V_74")));
6571            let particle = particle(&generator.model, pdg);
6572            let incoming = graph.add_node(ColoredNode::External(ExternalNode {
6573                index: 0,
6574                state: ExternalState::Incoming,
6575                particle,
6576            }));
6577            let outgoing = graph.add_node(ColoredNode::External(ExternalNode {
6578                index: 1,
6579                state: ExternalState::Outgoing,
6580                particle,
6581            }));
6582            graph
6583                .add_edge(incoming, owner, pdg != 21, edge(&generator.model, pdg))
6584                .unwrap();
6585            graph
6586                .add_edge(owner, outgoing, pdg != 21, edge(&generator.model, pdg))
6587                .unwrap();
6588            let amplitude = generator
6589                .external_state_projector(&graph, GenerationType::Amplitude, None)
6590                .unwrap();
6591            let cross_section = generator
6592                .external_state_projector(&graph, GenerationType::CrossSection, None)
6593                .unwrap();
6594            let identity = ColorSum::new(generator.model.particle_by_id(particle).unwrap())
6595                .unwrap()
6596                .expression(
6597                    [2, if pdg == 21 { 0 } else { 1 }]
6598                        .map(|hedge| symbols::hedge_index().call((hedge, 1_i64))),
6599                );
6600            assert_eq!(
6601                cross_section.expression(),
6602                &(amplitude.expression() * identity)
6603            );
6604            assert_eq!(cross_section.rank(), amplitude.rank() + 2);
6605            let supplied = Atom::num(7);
6606            let explicit = generator
6607                .external_state_projector(&graph, GenerationType::CrossSection, Some(&supplied))
6608                .unwrap();
6609            assert_eq!(explicit.expression(), &supplied);
6610        }
6611    }
6612
6613    #[test]
6614    fn generated_and_imported_cross_section_color_projectors_agree() {
6615        let model =
6616            Model::from_json(include_str!("../../feynkit-model/tests/fixtures/sm.json")).unwrap();
6617        let generator = Generator::new(model);
6618        let process = Process::new([1_i64], [1_i64, 21]);
6619        let options = GenerationOptions::default()
6620            .with_loop_count(1, 1)
6621            .unwrap()
6622            .threads(1)
6623            .max_vertices(2)
6624            .with_graph_filter(GenerationFilter::VertexAllow(vec![VertexSelector::Name(
6625                "V_74".into(),
6626            )]));
6627        let generated = generator
6628            .generate(&process, &options, GenerationType::CrossSection)
6629            .unwrap();
6630        assert_eq!(generated.diagrams.len(), 1);
6631        let diagram = &generated.diagrams[0];
6632        assert_eq!(
6633            diagram.projector(),
6634            &diagram.external_state_projector().unwrap()
6635        );
6636        assert_eq!(
6637            diagram
6638                .numerator()
6639                .multiply(diagram.projector())
6640                .unwrap()
6641                .rank(),
6642            0
6643        );
6644        assert!(
6645            diagram
6646                .edges()
6647                .filter(|(_, _, edge)| edge.external.is_some())
6648                .all(|(_, _, edge)| edge.numerator.expression() == &Atom::one())
6649        );
6650        let imported =
6651            FeynmanDiagram::from_json(diagram.model_arc(), &diagram.to_json().unwrap()).unwrap();
6652        assert_eq!(
6653            imported.external_state_projector().unwrap(),
6654            *diagram.projector()
6655        );
6656        assert_eq!(
6657            imported.apply_feynman_rules().unwrap().projector(),
6658            diagram.projector()
6659        );
6660
6661        let explicit = generator
6662            .generate(
6663                &process,
6664                &options.clone().projector(Atom::num(7)),
6665                GenerationType::CrossSection,
6666            )
6667            .unwrap();
6668        assert_eq!(explicit.diagrams.len(), 1);
6669        assert_eq!(explicit.diagrams[0].projector().expression(), &Atom::num(7));
6670        assert_eq!(
6671            explicit.diagrams[0]
6672                .apply_feynman_rules()
6673                .unwrap()
6674                .projector()
6675                .expression(),
6676            &Atom::num(7)
6677        );
6678
6679        let amplitude = generator
6680            .generate(
6681                &process,
6682                &options.with_loop_count(0, 0).unwrap(),
6683                GenerationType::Amplitude,
6684            )
6685            .unwrap();
6686        assert_eq!(amplitude.diagrams.len(), 1);
6687        assert_eq!(
6688            amplitude.diagrams[0]
6689                .numerator()
6690                .multiply(amplitude.diagrams[0].projector())
6691                .unwrap()
6692                .rank(),
6693            3
6694        );
6695    }
6696
6697    #[test]
6698    fn normalized_duplicate_pairs_preserve_weights_and_distinct_payloads() {
6699        let generated = Generator::new(Model::phi4())
6700            .generate(
6701                &Process::new(["phi", "phi"], ["phi", "phi"]),
6702                &GenerationOptions::default()
6703                    .with_loop_count(0, 0)
6704                    .unwrap()
6705                    .threads(1)
6706                    .max_vertices(1),
6707                GenerationType::Amplitude,
6708            )
6709            .unwrap();
6710        assert_eq!(generated.diagrams.len(), 1);
6711        let diagram = &generated.diagrams[0];
6712        let pair = |diagram: FeynmanDiagram| DiagramPair {
6713            comparison: diagram.clone(),
6714            representative: diagram,
6715            reversed_edges: BTreeSet::new(),
6716        };
6717        let (merged, canceled) = DiagramPair::combine_duplicates(vec![
6718            pair(diagram.clone().with_overall_factor(Atom::num(3))),
6719            pair(
6720                diagram
6721                    .clone()
6722                    .with_name("duplicate")
6723                    .with_overall_factor(Atom::num(5)),
6724            ),
6725        ])
6726        .unwrap();
6727        assert_eq!((merged.len(), canceled), (1, 0));
6728        assert_eq!(
6729            evaluate_overall_factor(merged[0].1.representative.overall_factor().as_view()),
6730            Atom::num(8)
6731        );
6732        assert_eq!(merged[0].1.representative.numerator(), diagram.numerator());
6733        let (canceled_pairs, canceled) = DiagramPair::combine_duplicates(vec![
6734            pair(diagram.clone().with_overall_factor(Atom::num(3))),
6735            pair(diagram.clone().with_overall_factor(Atom::num(-3))),
6736        ])
6737        .unwrap();
6738        assert!(canceled_pairs.is_empty());
6739        assert_eq!(canceled, 1);
6740        let (restored, canceled) = DiagramPair::combine_duplicates(vec![
6741            pair(diagram.clone().with_overall_factor(Atom::num(3))),
6742            pair(diagram.clone().with_overall_factor(Atom::num(-3))),
6743            pair(diagram.clone().with_overall_factor(Atom::num(5))),
6744        ])
6745        .unwrap();
6746        assert_eq!((restored.len(), canceled), (1, 0));
6747        assert_eq!(
6748            evaluate_overall_factor(restored[0].1.representative.overall_factor().as_view()),
6749            Atom::num(5)
6750        );
6751
6752        let changed = [
6753            diagram
6754                .clone()
6755                .with_projector(SymbolicTensor::infer(Atom::num(7)).unwrap()),
6756            diagram
6757                .clone()
6758                .with_numerator_prefactor(SymbolicTensor::infer(Atom::num(2)).unwrap()),
6759            diagram
6760                .clone()
6761                .with_numerator(SymbolicTensor::infer(Atom::num(5)).unwrap())
6762                .unwrap(),
6763        ];
6764        for other in changed {
6765            assert_eq!(other.id(), diagram.id());
6766            let (kept, canceled) =
6767                DiagramPair::combine_duplicates(vec![pair(diagram.clone()), pair(other)]).unwrap();
6768            assert_eq!((kept.len(), canceled), (2, 0));
6769        }
6770    }
6771
6772    #[test]
6773    fn finalizes_external_fermion_projectors_unless_explicitly_overridden() {
6774        let generator = Generator::new(fermion_model());
6775        let process = Process::new([1_i64, -1], [1_i64, -1]);
6776        let options = GenerationOptions::default()
6777            .with_loop_count(0, 0)
6778            .unwrap()
6779            .threads(1)
6780            .max_vertices(2);
6781        let generated = generator
6782            .generate(&process, &options, GenerationType::Amplitude)
6783            .unwrap();
6784        assert!(!generated.diagrams.is_empty());
6785        for diagram in &generated.diagrams {
6786            for wavefunction in [
6787                feynkit_graph::symbols::u(),
6788                feynkit_graph::symbols::ubar(),
6789                feynkit_graph::symbols::v(),
6790                feynkit_graph::symbols::vbar(),
6791            ] {
6792                assert_eq!(
6793                    function_count(
6794                        &NumeratorInterface::export(diagram.projector()).0,
6795                        wavefunction
6796                    ),
6797                    1
6798                );
6799            }
6800            assert_eq!(
6801                function_count(
6802                    &NumeratorInterface::export(diagram.projector()).0,
6803                    feynkit_graph::symbols::hedge_index()
6804                ),
6805                4
6806            );
6807        }
6808
6809        let supplied = Atom::mul_many(
6810            [
6811                (1, ExternalState::Incoming),
6812                (-1, ExternalState::Incoming),
6813                (1, ExternalState::Outgoing),
6814                (-1, ExternalState::Outgoing),
6815            ]
6816            .into_iter()
6817            .enumerate()
6818            .map(|(index, (pdg, state))| {
6819                generator
6820                    .external_wavefunction(state, particle(&generator.model, pdg), index, index)
6821                    .unwrap()
6822            }),
6823        );
6824        let overridden = generator
6825            .generate(
6826                &process,
6827                &options.clone().projector(supplied),
6828                GenerationType::Amplitude,
6829            )
6830            .unwrap();
6831        assert_eq!(overridden.diagrams.len(), generated.diagrams.len());
6832        for (automatic, supplied) in generated.diagrams.iter().zip(&overridden.diagrams) {
6833            assert_eq!(automatic.id(), supplied.id());
6834            assert_eq!(automatic.projector(), supplied.projector());
6835            assert_eq!(automatic.numerator(), supplied.numerator());
6836        }
6837
6838        let explicit = generator
6839            .generate(
6840                &process,
6841                &options.projector(Atom::one()),
6842                GenerationType::Amplitude,
6843            )
6844            .unwrap();
6845        assert!(
6846            explicit
6847                .diagrams
6848                .iter()
6849                .all(|diagram| diagram.projector().expression() == &Atom::one())
6850        );
6851    }
6852
6853    #[test]
6854    fn compton_cuts_preserve_the_requested_particle_charge() {
6855        let generator = Generator::new(fermion_model());
6856        for pdg in [1_i64, -1] {
6857            let process = Process::new([pdg, 22], [pdg, 22]);
6858            let generated = generator
6859                .generate(
6860                    &process,
6861                    &GenerationOptions::default()
6862                        .with_loop_count(1, 1)
6863                        .unwrap()
6864                        .threads(1)
6865                        .max_vertices(4),
6866                    GenerationType::CrossSection,
6867                )
6868                .unwrap();
6869            assert!(!generated.diagrams.is_empty());
6870            for diagram in generated.diagrams {
6871                assert!(!diagram.cuts().is_empty());
6872                for cut in diagram.cuts() {
6873                    let mut particles = diagram
6874                        .cut_particles(cut)
6875                        .unwrap()
6876                        .into_iter()
6877                        .map(|id| diagram.model().particle_by_id(id).unwrap().pdg_code)
6878                        .collect::<Vec<_>>();
6879                    particles.sort();
6880                    assert_eq!(particles, vec![pdg, 22]);
6881                    // Reversing a stored edge conjugates its species and its
6882                    // cut endpoint together, preserving the physical state.
6883                    let reversed = diagram.reverse_edge(cut.cut[0].edge).unwrap();
6884                    let mut reversed_particles = reversed
6885                        .cut_particles(&reversed.cuts()[0])
6886                        .unwrap()
6887                        .into_iter()
6888                        .map(|id| reversed.model().particle_by_id(id).unwrap().pdg_code)
6889                        .collect::<Vec<_>>();
6890                    reversed_particles.sort();
6891                    assert_eq!(reversed_particles, particles);
6892                }
6893            }
6894        }
6895    }
6896
6897    #[test]
6898    fn sewing_a_single_external_fermion_chain_has_even_ordering() {
6899        let model = fermion_model();
6900        let generator = Generator::new(model);
6901        for pdg in [1_i64, -1] {
6902            let process = Process::new([pdg, 22], [pdg, 22]);
6903            let generated = generator
6904                .generate(
6905                    &process,
6906                    &GenerationOptions::default()
6907                        .with_loop_count(1, 1)
6908                        .unwrap()
6909                        .threads(1)
6910                        .max_vertices(4),
6911                    GenerationType::CrossSection,
6912                )
6913                .unwrap();
6914            assert!(!generated.diagrams.is_empty());
6915            for diagram in generated.diagrams {
6916                // One external chain closes into one cycle without exchanging
6917                // any external fermions. Its ordering sign must be positive.
6918                let positive = symbolica::function!(
6919                    symbol!("feynkit_generator_factor::ExternalFermionOrderingSign"),
6920                    Atom::num(1)
6921                );
6922                assert!(diagram.overall_factor().contains(positive.as_view()));
6923            }
6924        }
6925    }
6926
6927    #[test]
6928    fn normalized_cross_section_fermion_chains_keep_valid_cuts() {
6929        let generator = Generator::new(fermion_model());
6930        let process = Process::new([1_i64, -1], [22_i64]);
6931        let generated = generator
6932            .generate(
6933                &process,
6934                &GenerationOptions::default()
6935                    .with_loop_count(0, 1)
6936                    .unwrap()
6937                    .threads(1)
6938                    .max_vertices(4),
6939                GenerationType::CrossSection,
6940            )
6941            .unwrap();
6942        assert!(!generated.diagrams.is_empty());
6943
6944        for diagram in &generated.diagrams {
6945            diagram.validate().unwrap();
6946            assert!(!diagram.cuts().is_empty());
6947
6948            let external_edges = diagram
6949                .edges()
6950                .filter_map(|(edge, _, data)| data.external.is_some().then_some(edge))
6951                .collect::<BTreeSet<_>>();
6952            for candidate in diagram.topology_threshold_candidates() {
6953                assert!(
6954                    candidate
6955                        .cut
6956                        .iter()
6957                        .all(|half_edge| !external_edges.contains(&half_edge.edge)),
6958                    "topology thresholds must be cuts of the sewn internal attachment nodes"
6959                );
6960            }
6961
6962            let fermion_edges = diagram
6963                .edges()
6964                .filter(|(_, _, edge)| edge.external.is_none())
6965                .filter_map(|(edge_id, endpoints, edge)| {
6966                    diagram
6967                        .model()
6968                        .particle_by_id(edge.particle)
6969                        .unwrap()
6970                        .is_fermion()
6971                        .then_some((
6972                            edge_id,
6973                            endpoints.source.expect("sewn source").0,
6974                            endpoints.target.expect("sewn target").0,
6975                            edge.particle,
6976                        ))
6977                })
6978                .collect::<Vec<_>>();
6979            let mut remaining = fermion_edges
6980                .iter()
6981                .map(|(edge, _, _, _)| *edge)
6982                .collect::<BTreeSet<_>>();
6983            // Sewing preserves the ordinary particle flow at both attachment
6984            // vertices, including initial-state carriers.
6985            for (node, _, _) in diagram.underlying().iter_nodes() {
6986                let signed_pdgs = diagram
6987                    .underlying()
6988                    .iter_crown(node)
6989                    .map(|hedge| {
6990                        let edge = &diagram.underlying()[diagram.underlying()[&hedge]];
6991                        let particle = diagram.model().particle_by_id(edge.particle).unwrap();
6992                        let pdg = particle.pdg_code;
6993                        if !particle.is_fermion() {
6994                            0
6995                        } else if diagram.underlying().flow(hedge) == Flow::Source {
6996                            pdg
6997                        } else {
6998                            -pdg
6999                        }
7000                    })
7001                    .sum::<i64>();
7002                assert_eq!(
7003                    signed_pdgs, 0,
7004                    "fermion flow must be conserved at each interaction"
7005                );
7006            }
7007            while let Some(start) = remaining.iter().next().copied() {
7008                let (_, source, target, _) = fermion_edges
7009                    .iter()
7010                    .find(|(edge, _, _, _)| *edge == start)
7011                    .copied()
7012                    .unwrap();
7013                let mut stack = vec![source, target];
7014                let mut component_particles = BTreeSet::new();
7015                while let Some(vertex) = stack.pop() {
7016                    for (edge, source, target, particle) in &fermion_edges {
7017                        if remaining.contains(edge) && (*source == vertex || *target == vertex) {
7018                            remaining.remove(edge);
7019                            component_particles.insert(*particle);
7020                            stack.push(*source);
7021                            stack.push(*target);
7022                        }
7023                    }
7024                }
7025                assert_eq!(
7026                    component_particles.len(),
7027                    1,
7028                    "every finalized fermion chain must use one particle species"
7029                );
7030            }
7031        }
7032    }
7033
7034    #[test]
7035    fn cut_partitions_use_sewn_attachment_nodes() {
7036        let model = fermion_model();
7037        let resolved = ResolvedProcess::new(
7038            &model,
7039            &Process::new([22_i64, 22], [22_i64, 22]),
7040            GenerationType::CrossSection,
7041            &GenerationOptions::default(),
7042        )
7043        .unwrap();
7044        let mut graph = Graph::new();
7045        let external = |index, state| {
7046            ColoredNode::External(ExternalNode {
7047                index,
7048                state,
7049                particle: particle(&model, 22),
7050            })
7051        };
7052        let incoming_0 = graph.add_node(external(0, ExternalState::Incoming));
7053        let incoming_1 = graph.add_node(external(1, ExternalState::Incoming));
7054        let outgoing_0 = graph.add_node(external(2, ExternalState::Outgoing));
7055        let outgoing_1 = graph.add_node(external(3, ExternalState::Outgoing));
7056        let left_0 = graph.add_node(ColoredNode::Interaction(vertex(&model, "V")));
7057        let left_1 = graph.add_node(ColoredNode::Interaction(vertex(&model, "V")));
7058        let right_0 = graph.add_node(ColoredNode::Interaction(vertex(&model, "V")));
7059        let right_1 = graph.add_node(ColoredNode::Interaction(vertex(&model, "V")));
7060        let photon = edge(&model, 22);
7061        let external_edges = BTreeSet::from([
7062            EdgeId(graph.add_edge(incoming_0, left_0, false, photon).unwrap()),
7063            EdgeId(graph.add_edge(incoming_1, left_1, false, photon).unwrap()),
7064            EdgeId(graph.add_edge(right_0, outgoing_0, false, photon).unwrap()),
7065            EdgeId(graph.add_edge(right_1, outgoing_1, false, photon).unwrap()),
7066        ]);
7067        let bridge_0 = EdgeId(graph.add_edge(left_0, right_0, false, photon).unwrap());
7068        let bridge_1 = EdgeId(graph.add_edge(left_1, right_1, false, photon).unwrap());
7069        graph.add_edge(left_0, left_1, false, photon).unwrap();
7070        graph.add_edge(right_0, right_1, false, photon).unwrap();
7071
7072        // Fixing only the degree-one external vertices admits partitions which
7073        // cross an initial external edge and two or more internal edges;
7074        // stripping that edge in the runtime bridge would turn them into
7075        // non-s-t threshold candidates, so the inventory must skip them.
7076        let old_graph: HedgeGraph<EdgeColor, ColoredNode, ()> = graph.clone().into();
7077        let mut old_source = Vec::new();
7078        let mut old_target = Vec::new();
7079        for (node, _, color) in old_graph.iter_nodes() {
7080            let ColoredNode::External(external) = color else {
7081                continue;
7082            };
7083            match external.state {
7084                ExternalState::Incoming => old_source.push(node),
7085                ExternalState::Outgoing => old_target.push(node),
7086            }
7087        }
7088        assert!(
7089            old_graph
7090                .all_cuts_from_ids(&old_source, &old_target)
7091                .into_iter()
7092                .any(|(_, cut, _)| {
7093                    let crossing = cut
7094                        .left
7095                        .included_iter()
7096                        .map(|hedge| EdgeId(old_graph[&hedge].0))
7097                        .collect::<BTreeSet<_>>();
7098                    crossing.iter().any(|edge| external_edges.contains(edge))
7099                        && crossing
7100                            .iter()
7101                            .filter(|edge| !external_edges.contains(edge))
7102                            .count()
7103                            > 1
7104                })
7105        );
7106
7107        let inventory = resolved
7108            .cut_partitions(&graph, &model, &GenerationOptions::default())
7109            .unwrap();
7110        assert_eq!(inventory.topology_threshold_candidates.len(), 1);
7111        let crossing = inventory.topology_threshold_candidates[0]
7112            .cut
7113            .iter()
7114            .map(|half_edge| half_edge.edge)
7115            .collect::<BTreeSet<_>>();
7116        assert_eq!(crossing, BTreeSet::from([bridge_0, bridge_1]));
7117        assert!(crossing.is_disjoint(&external_edges));
7118    }
7119
7120    #[test]
7121    fn self_energies_between_attachments_keep_their_cut_on_either_side() {
7122        let model = scalar_model();
7123        let resolved = ResolvedProcess::new(
7124            &model,
7125            &scalar_cross_section_process(),
7126            GenerationType::CrossSection,
7127            &GenerationOptions::default(),
7128        )
7129        .unwrap();
7130        // Attachments a = 4, b = 5 (incoming) and c = 6, d = 7 (outgoing) on
7131        // one loop a - c - d - b, closed by a self-energy e = f (8, 9) on the
7132        // internal line between either the incoming or the outgoing pair. The
7133        // only two-phi cut separates the self-energy side from the other pair.
7134        let incoming_side = scalar_forward_graph(
7135            &model,
7136            &[
7137                (0, 4),
7138                (1, 5),
7139                (6, 2),
7140                (7, 3),
7141                (4, 6),
7142                (6, 7),
7143                (7, 5),
7144                (4, 8),
7145                (8, 9),
7146                (8, 9),
7147                (9, 5),
7148            ],
7149        );
7150        let outgoing_side = scalar_forward_graph(
7151            &model,
7152            &[
7153                (0, 4),
7154                (1, 5),
7155                (6, 2),
7156                (7, 3),
7157                (4, 6),
7158                (4, 5),
7159                (5, 7),
7160                (6, 8),
7161                (8, 9),
7162                (8, 9),
7163                (9, 7),
7164            ],
7165        );
7166        for (graph, name) in [(&incoming_side, "incoming"), (&outgoing_side, "outgoing")] {
7167            let inventory = resolved
7168                .cut_partitions(graph, &model, &GenerationOptions::default())
7169                .unwrap();
7170            assert_eq!(
7171                inventory.physical.len(),
7172                1,
7173                "self-energy on the {name} side"
7174            );
7175            let physical = &inventory.physical[0];
7176            assert_eq!(physical.cut.len(), 2, "self-energy on the {name} side");
7177            let loops = [physical.left.loop_count, physical.right.loop_count];
7178            let expected = if name == "incoming" { [1, 0] } else { [0, 1] };
7179            assert_eq!(loops, expected, "self-energy on the {name} side");
7180        }
7181    }
7182
7183    #[test]
7184    fn forward_graph_cuts_place_virtual_loops_on_both_sides_equally() {
7185        let generated = Generator::new(scalar_model())
7186            .generate(
7187                &scalar_cross_section_process(),
7188                &GenerationOptions::default()
7189                    .with_loop_count(2, 2)
7190                    .unwrap()
7191                    .threads(1),
7192                GenerationType::CrossSection,
7193            )
7194            .unwrap();
7195        // Every one-loop virtual correction of the amplitude has its
7196        // conjugate: the cuts of the labelled forward graphs are symmetric
7197        // under exchanging the two sides.
7198        let mut sides = BTreeMap::<_, usize>::new();
7199        for diagram in &generated.diagrams {
7200            for cut in diagram.cuts() {
7201                *sides
7202                    .entry((cut.left.loop_count, cut.right.loop_count))
7203                    .or_default() += 1;
7204            }
7205        }
7206        assert!(
7207            sides.get(&(1, 0)).is_some_and(|&count| count > 0),
7208            "{sides:?}"
7209        );
7210        assert_eq!(sides.get(&(1, 0)), sides.get(&(0, 1)), "{sides:?}");
7211    }
7212
7213    /// The crossing edge sets of the physical cuts and of the threshold
7214    /// candidates of `graph` for a phi phi -> `final_phis` cross section.
7215    fn cut_edge_set_inventory(
7216        graph: &Graph<ColoredNode, EdgeColor>,
7217        final_phis: usize,
7218        options: &GenerationOptions,
7219    ) -> (BTreeSet<BTreeSet<usize>>, BTreeSet<BTreeSet<usize>>) {
7220        let model = scalar_model();
7221        let inventory = ResolvedProcess::new(
7222            &model,
7223            &Process::new(["phi", "phi"], vec!["phi"; final_phis]),
7224            GenerationType::CrossSection,
7225            options,
7226        )
7227        .unwrap()
7228        .cut_partitions(graph, &model, options)
7229        .unwrap();
7230        let edges = |cut: &[DiagramHalfEdge]| cut.iter().map(|half| half.edge.0).collect();
7231        (
7232            inventory
7233                .physical
7234                .iter()
7235                .map(|cut| edges(&cut.cut))
7236                .collect(),
7237            inventory
7238                .topology_threshold_candidates
7239                .iter()
7240                .map(|candidate| edges(&candidate.cut))
7241                .collect(),
7242        )
7243    }
7244
7245    #[test]
7246    fn recovered_threshold_candidates_are_independent_of_the_process() {
7247        let model = scalar_model();
7248        // The incoming-side self-energy graph: a = 4, b = 5, c = 6, d = 7,
7249        // self-energy e = f (8, 9) between a and b. Edge 4 is a-c, 6 is d-b,
7250        // 7 is a-e and 10 is f-b.
7251        let graph = scalar_forward_graph(
7252            &model,
7253            &[
7254                (0, 4),
7255                (1, 5),
7256                (6, 2),
7257                (7, 3),
7258                (4, 6),
7259                (6, 7),
7260                (7, 5),
7261                (4, 8),
7262                (8, 9),
7263                (8, 9),
7264                (9, 5),
7265            ],
7266        );
7267        let set = |edges: &[usize]| edges.iter().copied().collect::<BTreeSet<_>>();
7268        let one_blob = GenerationOptions::default();
7269        let two_blobs = one_blob
7270            .clone()
7271            .with_graph_filter(GenerationFilter::BlobRange(1..=2));
7272        let connected = BTreeSet::from([set(&[4, 6])]);
7273        // The two-body cut, with the self-energy on the incoming side.
7274        assert_eq!(
7275            cut_edge_set_inventory(&graph, 2, &one_blob),
7276            (connected.clone(), connected.clone())
7277        );
7278        assert_eq!(
7279            cut_edge_set_inventory(&graph, 2, &two_blobs),
7280            (connected.clone(), connected.clone())
7281        );
7282        // Only a and b on the left: four lines, two blobs on each side. It is
7283        // a physical cut within two blobs but never a threshold candidate.
7284        assert_eq!(
7285            cut_edge_set_inventory(&graph, 4, &two_blobs),
7286            (BTreeSet::from([set(&[4, 6, 7, 10])]), connected.clone())
7287        );
7288        // A final state without a matching cut keeps the threshold.
7289        assert_eq!(
7290            cut_edge_set_inventory(&graph, 3, &one_blob),
7291            (BTreeSet::new(), connected)
7292        );
7293
7294        // An already selected graph: the cycle a-b-d-c-x-a (x = 8) with two
7295        // parallel x-c lines and a lobe at 9 attached to x only. The
7296        // attachment search finds the two-body cut {a-x, b-d} but stops when
7297        // x joins the left with the lobe on the right; the leg search adds
7298        // the connected three-line threshold {b-d, x-c, x-c}.
7299        let lobe = scalar_forward_graph(
7300            &model,
7301            &[
7302                (0, 4),
7303                (1, 5),
7304                (6, 2),
7305                (7, 3),
7306                (4, 5),
7307                (5, 7),
7308                (7, 6),
7309                (4, 8),
7310                (8, 6),
7311                (8, 6),
7312                (8, 9),
7313                (8, 9),
7314                (9, 9),
7315            ],
7316        );
7317        assert_eq!(
7318            cut_edge_set_inventory(&lobe, 2, &one_blob),
7319            (
7320                BTreeSet::from([set(&[5, 7])]),
7321                BTreeSet::from([set(&[5, 7]), set(&[5, 8, 9])])
7322            )
7323        );
7324    }
7325
7326    #[test]
7327    fn recovered_cuts_keep_whole_vertices_behind_bridges() {
7328        let model = scalar_model();
7329        // The incoming-side bubble e = f (8, 9) with one line replaced by
7330        // e - x - f (x = 10), and a self-loop vertex z = 11 attached to x by
7331        // the bridge x - z, which the cut search skips.
7332        let graph = scalar_forward_graph(
7333            &model,
7334            &[
7335                (0, 4),
7336                (1, 5),
7337                (6, 2),
7338                (7, 3),
7339                (4, 6),
7340                (6, 7),
7341                (7, 5),
7342                (4, 8),
7343                (8, 9),
7344                (8, 10),
7345                (10, 9),
7346                (9, 5),
7347                (10, 11),
7348                (11, 11),
7349            ],
7350        );
7351        let options = GenerationOptions::default()
7352            .allow_self_loops(true)
7353            .with_graph_filter(GenerationFilter::BlobRange(1..=2));
7354        let inventory = ResolvedProcess::new(
7355            &model,
7356            &scalar_cross_section_process(),
7357            GenerationType::CrossSection,
7358            &options,
7359        )
7360        .unwrap()
7361        .cut_partitions(&graph, &model, &options)
7362        .unwrap();
7363        assert_eq!(inventory.physical.len(), 1);
7364        let physical = &inventory.physical[0];
7365        // Both virtual loops, the bubble and the self-loop, are on the left.
7366        assert_eq!(
7367            [physical.left.loop_count, physical.right.loop_count],
7368            [2, 0]
7369        );
7370        let diagram = Generator::new(model)
7371            .to_diagram(
7372                "terminal_free_bridge".to_owned(),
7373                GenerationType::CrossSection,
7374                ColoredTopology {
7375                    graph,
7376                    symmetry: 1,
7377                    multiplicity: 1,
7378                    cut_partitions: inventory.physical,
7379                    topology_threshold_candidates: inventory.topology_threshold_candidates,
7380                    spectator_cuts: Vec::new(),
7381                },
7382                1,
7383                FermionSigns::default(),
7384                &options,
7385            )
7386            .unwrap();
7387        assert_eq!(diagram.cuts().len(), 1);
7388    }
7389
7390    #[test]
7391    fn unresolved_cut_policy_is_validated_before_any_graph_is_rejected() {
7392        let generator = Generator::new(fermion_model());
7393        let process = Process::new(["a", "a"], ["f", "f~"]);
7394        let options = GenerationOptions::default()
7395            .with_loop_count(1, 1)
7396            .unwrap()
7397            .threads(1);
7398        assert!(
7399            !generator
7400                .generate(&process, &options, GenerationType::CrossSection)
7401                .unwrap()
7402                .diagrams
7403                .is_empty()
7404        );
7405        // The unresolved-cut multiplicity overflows, whether or not a
7406        // graph-wide filter rejects every generated graph before its cuts are
7407        // searched.
7408        let overflow =
7409            options.with_graph_filter(GenerationFilter::PerturbativeOrders(BTreeMap::from([
7410                ("QED".to_owned(), usize::MAX),
7411                ("QCD".to_owned(), 1),
7412            ])));
7413        let rejecting = overflow
7414            .clone()
7415            .with_graph_filter(GenerationFilter::CouplingOrders(BTreeMap::from([(
7416                "QED".to_owned(),
7417                (100, None),
7418            )])));
7419        for options in [&overflow, &rejecting] {
7420            assert!(matches!(
7421                generator.generate(&process, options, GenerationType::CrossSection),
7422                Err(GenerationError::ArithmeticOverflow(
7423                    "the unresolved cut multiplicity"
7424                ))
7425            ));
7426        }
7427    }
7428
7429    #[test]
7430    fn attachment_seeded_cuts_keep_whole_vertices_behind_bridges() {
7431        let model = scalar_model();
7432        // a = 4, b = 5 (incoming), c = 6, d = 7 (outgoing), the line a - x - c
7433        // with x = 8, the line b - d, a self-energy 10 = 11 between c and d,
7434        // and a self-loop vertex z = 9 attached to x by the bridge x - z.
7435        // The attachment search finds both two-body cuts by itself.
7436        let graph = scalar_forward_graph(
7437            &model,
7438            &[
7439                (0, 4),
7440                (1, 5),
7441                (6, 2),
7442                (7, 3),
7443                (4, 5),
7444                (4, 8),
7445                (8, 6),
7446                (5, 7),
7447                (6, 10),
7448                (10, 11),
7449                (10, 11),
7450                (11, 7),
7451                (8, 9),
7452                (9, 9),
7453            ],
7454        );
7455        let options = GenerationOptions::default().allow_self_loops(true);
7456        let inventory = ResolvedProcess::new(
7457            &model,
7458            &scalar_cross_section_process(),
7459            GenerationType::CrossSection,
7460            &options,
7461        )
7462        .unwrap()
7463        .cut_partitions(&graph, &model, &options)
7464        .unwrap();
7465        // Edge 5 is a - x, 6 is x - c and 7 is b - d. Behind the cut {x-c,
7466        // b-d}, z and its self-loop stay with x on the left.
7467        let cuts = inventory
7468            .physical
7469            .iter()
7470            .map(|cut| {
7471                (
7472                    cut.cut
7473                        .iter()
7474                        .map(|half| half.edge.0)
7475                        .collect::<BTreeSet<_>>(),
7476                    [cut.left.loop_count, cut.right.loop_count],
7477                )
7478            })
7479            .collect::<BTreeSet<_>>();
7480        assert_eq!(
7481            cuts,
7482            BTreeSet::from([
7483                (BTreeSet::from([5, 7]), [0, 2]),
7484                (BTreeSet::from([6, 7]), [1, 1]),
7485            ])
7486        );
7487        let diagram = Generator::new(model)
7488            .to_diagram(
7489                "attachment_bridge".to_owned(),
7490                GenerationType::CrossSection,
7491                ColoredTopology {
7492                    graph,
7493                    symmetry: 1,
7494                    multiplicity: 1,
7495                    cut_partitions: inventory.physical,
7496                    topology_threshold_candidates: inventory.topology_threshold_candidates,
7497                    spectator_cuts: Vec::new(),
7498                },
7499                1,
7500                FermionSigns::default(),
7501                &options,
7502            )
7503            .unwrap();
7504        assert_eq!(diagram.cuts().len(), 2);
7505    }
7506
7507    /// Build a phi^3 forward graph on nodes `in0, in1, out0, out1` (0..4)
7508    /// followed by as many interaction vertices as `edges` references.
7509    fn scalar_forward_graph(
7510        model: &Model,
7511        edges: &[(usize, usize)],
7512    ) -> Graph<ColoredNode, EdgeColor> {
7513        let mut graph = Graph::new();
7514        let states = [
7515            ExternalState::Incoming,
7516            ExternalState::Incoming,
7517            ExternalState::Outgoing,
7518            ExternalState::Outgoing,
7519        ];
7520        let mut nodes = states
7521            .into_iter()
7522            .enumerate()
7523            .map(|(index, state)| {
7524                graph.add_node(ColoredNode::External(ExternalNode {
7525                    index,
7526                    state,
7527                    particle: particle(model, 25),
7528                }))
7529            })
7530            .collect::<Vec<_>>();
7531        let node_count = edges.iter().flat_map(|&(a, b)| [a, b]).max().unwrap() + 1;
7532        nodes.extend(
7533            (states.len()..node_count)
7534                .map(|_| graph.add_node(ColoredNode::Interaction(vertex(model, "V1")))),
7535        );
7536        for &(source, target) in edges {
7537            graph
7538                .add_edge(nodes[source], nodes[target], false, edge(model, 25))
7539                .unwrap();
7540        }
7541        graph
7542    }
7543
7544    #[test]
7545    fn spectator_cuts_count_crossed_initial_state_edges_as_on_main() {
7546        let model = scalar_model();
7547        // in0 -> a -> {c, d}, in1 -> c, c - d - e, e -> {out0, out1}: the cuts
7548        // {in1-c, a-c, a-d} and {in0-a, a-c, c-d} carry three phis with one
7549        // spectator on the left only. Their only spectator-free cuts carry one
7550        // or two phis.
7551        let one_sided = scalar_forward_graph(
7552            &model,
7553            &[
7554                (0, 4),
7555                (1, 5),
7556                (4, 5),
7557                (4, 6),
7558                (5, 6),
7559                (6, 7),
7560                (7, 2),
7561                (7, 3),
7562            ],
7563        );
7564        // in1 -> a, a - {b, c}, b - d, b -> out1, in0 -> c, c - d, d -> out0:
7565        // {in0-c, a-c, b-d, b-out1} and {in1-a, a-c, b-d, d-out0} carry four
7566        // phis with one spectator on each side; {a-b, c-d} is the only
7567        // spectator-free cut.
7568        let two_sided = scalar_forward_graph(
7569            &model,
7570            &[
7571                (1, 4),
7572                (4, 6),
7573                (4, 5),
7574                (5, 7),
7575                (5, 3),
7576                (0, 6),
7577                (6, 7),
7578                (7, 2),
7579            ],
7580        );
7581        // (graph, final-state phis, [(range, physical cuts, spectator cuts)]),
7582        // counted by hand with main's rule: only the external vertices are
7583        // fixed, a singleton cut side is a spectator, and the blob and
7584        // spectator ranges apply to each side.
7585        for (graph, final_phis, expected) in [
7586            (&one_sided, 3, [(0..=0, 0, 0), (0..=1, 0, 2), (1..=1, 0, 0)]),
7587            (&two_sided, 4, [(0..=0, 0, 0), (0..=1, 0, 2), (1..=1, 0, 2)]),
7588            (&two_sided, 2, [(0..=0, 1, 0), (0..=1, 1, 0), (1..=1, 1, 0)]),
7589        ] {
7590            let resolved = ResolvedProcess::new(
7591                &model,
7592                &Process::new(["phi", "phi"], vec!["phi"; final_phis]),
7593                GenerationType::CrossSection,
7594                &GenerationOptions::default(),
7595            )
7596            .unwrap();
7597            let default = resolved
7598                .cut_partitions(graph, &model, &GenerationOptions::default())
7599                .unwrap();
7600            for (range, physical, spectator) in expected {
7601                let inventory = resolved
7602                    .cut_partitions(
7603                        graph,
7604                        &model,
7605                        &GenerationOptions::default()
7606                            .with_graph_filter(GenerationFilter::SpectatorRange(range.clone())),
7607                    )
7608                    .unwrap();
7609                let case = format!("{final_phis} phis, spectators {range:?}");
7610                assert_eq!(inventory.physical.len(), physical, "{case}");
7611                assert_eq!(inventory.spectator.len(), spectator, "{case}");
7612                assert_eq!(
7613                    inventory.physical_satisfies_spectator_range,
7614                    range.contains(&0),
7615                    "{case}"
7616                );
7617                // Spectator counting never changes the serialized inventories.
7618                assert_eq!(inventory.physical, default.physical, "{case}");
7619                assert_eq!(
7620                    inventory.topology_threshold_candidates, default.topology_threshold_candidates,
7621                    "{case}"
7622                );
7623            }
7624        }
7625    }
7626
7627    #[test]
7628    fn spectator_ranges_list_selection_only_graphs_beside_physical_ones() {
7629        let generator = Generator::new(scalar_model());
7630        let generate = |final_phis, range| {
7631            let generated = generator
7632                .generate(
7633                    &Process::new(["phi", "phi"], vec!["phi"; final_phis]),
7634                    &GenerationOptions::default()
7635                        .with_loop_count(1, 1)
7636                        .unwrap()
7637                        .threads(1)
7638                        .max_vertices(4)
7639                        .with_graph_filter(GenerationFilter::SpectatorRange(range)),
7640                    GenerationType::CrossSection,
7641                )
7642                .unwrap();
7643            for diagram in &generated.diagrams {
7644                diagram.validate().unwrap();
7645            }
7646            generated
7647        };
7648        // Selection-only diagrams, and the IDs of those with physical cuts.
7649        let split = |diagrams: Vec<FeynmanDiagram>| {
7650            let (selection_only, physical): (Vec<_>, Vec<_>) = diagrams
7651                .into_iter()
7652                .partition(FeynmanDiagram::is_selection_only);
7653            let physical = physical
7654                .iter()
7655                .map(FeynmanDiagram::id)
7656                .collect::<BTreeSet<_>>();
7657            (selection_only, physical)
7658        };
7659
7660        // A spectator-free three-phi cut of a forward graph closes two loops, so
7661        // one-loop graphs are selected only through a spectator, such as the
7662        // one-sided graph of the test above; they are listed, marked.
7663        assert!(generate(3, 0..=0).diagrams.is_empty());
7664        let (up_to_one, physical) = split(generate(3, 0..=1).diagrams);
7665        assert!(physical.is_empty());
7666        assert!(!up_to_one.is_empty());
7667        assert!(up_to_one.iter().any(|diagram| {
7668            diagram
7669                .spectator_cuts()
7670                .iter()
7671                .any(|cut| cut.right_spectators.is_empty())
7672        }));
7673        let (exactly_one, physical) = split(generate(3, 1..=1).diagrams);
7674        assert!(physical.is_empty());
7675        assert!(!exactly_one.is_empty() && exactly_one.len() < up_to_one.len());
7676        assert!(
7677            exactly_one
7678                .iter()
7679                .flat_map(FeynmanDiagram::spectator_cuts)
7680                .all(|cut| cut.left_spectators.len() == 1 && cut.right_spectators.len() == 1)
7681        );
7682
7683        // With physical cuts available, the diagrams that carry them are the
7684        // same for every range containing zero, and 1..=1 narrows them.
7685        let (selection_only, no_spectator) = split(generate(2, 0..=0).diagrams);
7686        assert!(selection_only.is_empty());
7687        assert!(!no_spectator.is_empty());
7688        let (_, physical) = split(generate(2, 0..=1).diagrams);
7689        assert_eq!(physical, no_spectator);
7690        let (_, physical) = split(generate(2, 1..=1).diagrams);
7691        assert!(physical.is_subset(&no_spectator));
7692
7693        // Amplitude construction refuses a selection-only diagram.
7694        assert!(matches!(
7695            generate(3, 0..=1).into_amplitude(feynkit_amplitude::AmplitudeOptions::default()),
7696            Err(GenerationError::Amplitude(error))
7697                if matches!(*error, feynkit_amplitude::AmplitudeError::SelectionOnlyDiagram(_))
7698        ));
7699    }
7700
7701    #[test]
7702    fn vacuum_cross_sections_are_generated_without_cut_filtering() {
7703        let generator = Generator::new(scalar_model());
7704        let vacuum = Process::new(Vec::<i64>::new(), Vec::<i64>::new());
7705        // The graph-scope blob and spectator ranges the CLI always inserts
7706        // remain valid for a vacuum cross section.
7707        let options = GenerationOptions::default()
7708            .with_loop_count(2, 2)
7709            .unwrap()
7710            .threads(1)
7711            .max_vertices(2)
7712            .with_graph_filter(GenerationFilter::BlobRange(1..=1))
7713            .with_graph_filter(GenerationFilter::SpectatorRange(0..=0));
7714        let generated = generator
7715            .generate(&vacuum, &options, GenerationType::CrossSection)
7716            .unwrap();
7717        assert!(generated.report.completed);
7718        assert!(!generated.diagrams.is_empty());
7719        assert!(generated.diagrams.iter().all(|diagram| {
7720            diagram.cuts().is_empty() && diagram.topology_threshold_candidates().is_empty()
7721        }));
7722
7723        // Requests that no vacuum cut could satisfy are rejected, not ignored.
7724        assert!(matches!(
7725            generator.generate(
7726                &Process::new(Vec::<i64>::new(), [25_i64, 25]),
7727                &options,
7728                GenerationType::CrossSection
7729            ),
7730            Err(GenerationError::VacuumCrossSectionFinalState)
7731        ));
7732        assert!(matches!(
7733            generator.generate(
7734                &vacuum,
7735                &options.clone().with_scoped_filter(
7736                    FilterScope::CutAmplitude,
7737                    GenerationFilter::LoopCountRange((0, 2))
7738                ),
7739                GenerationType::CrossSection
7740            ),
7741            Err(GenerationError::VacuumCutAmplitudeFilters)
7742        ));
7743        let unknown = BTreeSet::from([EdgeId(0)]);
7744        assert!(matches!(
7745            generator.generate(
7746                &vacuum,
7747                &options.clone().forced_cuts([unknown]),
7748                GenerationType::CrossSection
7749            ),
7750            Err(GenerationError::UnknownForcedCut { .. })
7751        ));
7752    }
7753
7754    #[test]
7755    fn cross_sections_reject_empty_final_states_without_unresolved_content() {
7756        let generator = Generator::new(fermion_model());
7757        let process = Process::new(["a", "a"], Vec::<&str>::new());
7758        let options = GenerationOptions::default()
7759            .with_loop_count(1, 1)
7760            .unwrap()
7761            .threads(1)
7762            .max_vertices(4);
7763        let with_orders = |orders: &[(&str, usize)]| {
7764            options
7765                .clone()
7766                .with_graph_filter(GenerationFilter::PerturbativeOrders(
7767                    orders
7768                        .iter()
7769                        .map(|(name, order)| ((*name).to_owned(), *order))
7770                        .collect(),
7771                ))
7772        };
7773        // Without perturbative orders, with an empty order map, or with only
7774        // zero orders, an empty final state cannot match any cut.
7775        for (case, options) in [
7776            ("no perturbative orders", options.clone()),
7777            ("empty perturbative orders", with_orders(&[])),
7778            ("zero perturbative orders", with_orders(&[("QED", 0)])),
7779        ] {
7780            let result = generator.generate(&process, &options, GenerationType::CrossSection);
7781            assert!(
7782                matches!(result, Err(GenerationError::EmptyCrossSectionFinalStates)),
7783                "{case}: an unmatchable empty final state was not rejected: {:?}",
7784                result.map(|generated| generated.diagrams.len())
7785            );
7786        }
7787        // A non-zero order admits unresolved massless content.
7788        assert!(!matches!(
7789            generator.generate(
7790                &process,
7791                &with_orders(&[("QED", 2)]),
7792                GenerationType::CrossSection
7793            ),
7794            Err(GenerationError::EmptyCrossSectionFinalStates)
7795        ));
7796    }
7797
7798    #[test]
7799    fn default_loop_routing_uses_canonical_topology_order() {
7800        let model = Arc::new(scalar_model());
7801        let particle = model.particle_id("phi").unwrap();
7802        let interaction = model.vertex_rule_id("V1").unwrap();
7803        let mut builder = FeynmanDiagram::builder(Arc::clone(&model), "routing-order");
7804        let vertices = (0..4)
7805            .map(|vertex| {
7806                builder.add_vertex(DiagramVertex::interaction(
7807                    format!("v{vertex}"),
7808                    interaction,
7809                ))
7810            })
7811            .collect::<Vec<_>>();
7812        for (edge, source, target) in [(0, 2, 3), (1, 1, 3), (2, 1, 2), (3, 0, 3), (4, 0, 1)] {
7813            assert_eq!(
7814                builder
7815                    .add_edge(
7816                        vertices[source],
7817                        vertices[target],
7818                        DiagramEdge::new(particle, false),
7819                    )
7820                    .unwrap(),
7821                EdgeId(edge),
7822            );
7823        }
7824        let stable_id_default = builder.build().unwrap();
7825        assert_eq!(
7826            stable_id_default.loop_momentum_basis().loop_edges,
7827            vec![EdgeId(0), EdgeId(1)],
7828        );
7829
7830        let canonical = stable_id_default
7831            .with_canonical_loop_momentum_basis()
7832            .unwrap();
7833        assert_eq!(
7834            canonical.loop_momentum_basis().tree_edges,
7835            vec![EdgeId(0), EdgeId(2), EdgeId(3)],
7836        );
7837        assert_eq!(
7838            canonical.loop_momentum_basis().loop_edges,
7839            vec![EdgeId(1), EdgeId(4)],
7840        );
7841    }
7842
7843    #[test]
7844    fn default_loop_routing_matches_gl_multichannel_traversal() {
7845        let model = Arc::new(scalar_model());
7846        let particle = model.particle_id("phi").unwrap();
7847        let mut builder = FeynmanDiagram::builder(model, "gl-like-routing");
7848        let outgoing_0 = builder.add_generation_external("out0", 0, ExternalState::Outgoing, 0);
7849        let outgoing_1 = builder.add_generation_external("out1", 1, ExternalState::Outgoing, 1);
7850        let vertices = (0..8)
7851            .map(|vertex| {
7852                builder.add_vertex(DiagramVertex {
7853                    name: format!("v{vertex}"),
7854                    interaction: None,
7855
7856                    numerator: SymbolicTensor::infer(Atom::one()).unwrap(),
7857                })
7858            })
7859            .collect::<Vec<_>>();
7860        assert_eq!(
7861            builder
7862                .add_edge(outgoing_0, vertices[7], DiagramEdge::new(particle, false),)
7863                .unwrap(),
7864            EdgeId(0),
7865        );
7866        assert_eq!(
7867            builder
7868                .add_edge(outgoing_1, vertices[7], DiagramEdge::new(particle, false),)
7869                .unwrap(),
7870            EdgeId(1),
7871        );
7872        for (edge, source, target) in [
7873            (0, 0, 1),
7874            (1, 0, 3),
7875            (2, 5, 0),
7876            (3, 2, 1),
7877            (4, 1, 5),
7878            (5, 4, 2),
7879            (6, 2, 7),
7880            (7, 3, 4),
7881            (8, 3, 6),
7882            (9, 4, 5),
7883        ] {
7884            assert_eq!(
7885                builder
7886                    .add_edge(
7887                        vertices[source],
7888                        vertices[target],
7889                        DiagramEdge::new(particle, false),
7890                    )
7891                    .unwrap(),
7892                EdgeId(edge + 2),
7893            );
7894        }
7895
7896        let routed = builder.canonical_loop_momentum_basis().build().unwrap();
7897
7898        assert_eq!(
7899            routed.loop_momentum_basis().loop_edges,
7900            vec![EdgeId(4), EdgeId(5), EdgeId(9)],
7901        );
7902    }
7903
7904    #[test]
7905    fn supplied_vector_projector_uses_external_labels_before_topology_finalization() {
7906        let generator = Generator::new(fermion_model());
7907        for reversed in [false, true] {
7908            let mut graph = Graph::new();
7909            let left = graph.add_node(ColoredNode::Interaction(vertex(&generator.model, "V")));
7910            let right = graph.add_node(ColoredNode::Interaction(vertex(&generator.model, "V")));
7911            graph
7912                .add_edge(left, right, false, edge(&generator.model, 22))
7913                .unwrap();
7914            let mut supplied = Atom::one();
7915            for (index, state, attached) in [
7916                (7, ExternalState::Incoming, left),
7917                (3, ExternalState::Outgoing, right),
7918            ] {
7919                let external = graph.add_node(ColoredNode::External(ExternalNode {
7920                    index,
7921                    state,
7922                    particle: particle(&generator.model, 22),
7923                }));
7924                let (source, target) = if reversed {
7925                    (attached, external)
7926                } else {
7927                    (external, attached)
7928                };
7929                graph
7930                    .add_edge(source, target, false, edge(&generator.model, 22))
7931                    .unwrap();
7932                supplied *= generator
7933                    .external_wavefunction(state, particle(&generator.model, 22), index, index)
7934                    .unwrap();
7935            }
7936            assert_eq!(
7937                generator
7938                    .external_state_projector(&graph, GenerationType::Amplitude, Some(&supplied))
7939                    .unwrap(),
7940                generator
7941                    .external_state_projector(&graph, GenerationType::Amplitude, None)
7942                    .unwrap(),
7943            );
7944            let invalid = feynkit_graph::symbols::epsilon().call(999usize);
7945            assert!(matches!(
7946                generator.external_state_projector(
7947                    &graph,
7948                    GenerationType::Amplitude,
7949                    Some(&invalid)
7950                ),
7951                Err(GenerationError::UnknownProjectorExternalIndex { index: 999 })
7952            ));
7953        }
7954    }
7955
7956    /// `Q(leg)` and `Q3(leg)` in a supplied projector are the leg's momentum in its
7957    /// process direction and that momentum's spatial part.
7958    fn supplied_leg_momenta(legs: [usize; 2]) -> Atom {
7959        let [incoming, outgoing] = legs;
7960        let q = |edge: usize, index: Atom| momentum_symbol().call((edge, index));
7961        let q3 = |edge: usize, index: Atom| symbols::spatial_momentum().call((edge, index));
7962        let cind = |i: i64| function!(AIND_SYMBOLS.cind, i);
7963        let mink = || Minkowski {}.new_rep(4).to_symbolic([Atom::num(7)]);
7964        q(incoming, cind(0))
7965            + Atom::num(2) * q(outgoing, cind(0))
7966            + Atom::num(3) * q3(incoming, mink()) * q(outgoing, mink())
7967            + Atom::num(5) * q(incoming, mink()) * q3(outgoing, mink())
7968    }
7969
7970    #[test]
7971    fn supplied_projector_momenta_keep_their_process_direction_on_provisional_edges() {
7972        let generator = Generator::new(fermion_model());
7973        let q = |edge: usize, index: Atom| momentum_symbol().call((edge, index));
7974        let q3 = |edge: usize, index: Atom| symbols::spatial_momentum().call((edge, index));
7975        let cind = |i: i64| function!(AIND_SYMBOLS.cind, i);
7976        let mink = || Minkowski {}.new_rep(4).to_symbolic([Atom::num(7)]);
7977        for reversed in [false, true] {
7978            let mut graph = Graph::new();
7979            let left = graph.add_node(ColoredNode::Interaction(vertex(&generator.model, "V")));
7980            let right = graph.add_node(ColoredNode::Interaction(vertex(&generator.model, "V")));
7981            graph
7982                .add_edge(left, right, false, edge(&generator.model, 22))
7983                .unwrap();
7984            for (index, state, attached) in [
7985                (7, ExternalState::Incoming, left),
7986                (3, ExternalState::Outgoing, right),
7987            ] {
7988                let external = graph.add_node(ColoredNode::External(ExternalNode {
7989                    index,
7990                    state,
7991                    particle: particle(&generator.model, 22),
7992                }));
7993                let (source, target) = if reversed {
7994                    (attached, external)
7995                } else {
7996                    (external, attached)
7997                };
7998                // Directed, so that the provisional orientation is the one chosen here.
7999                graph
8000                    .add_edge(source, target, true, edge(&generator.model, 22))
8001                    .unwrap();
8002            }
8003            // Provisional edge 1 carries leg 7 and edge 2 leg 3. Unreversed, leg 7
8004            // flows into the diagram along its edge and leg 3 against its edge.
8005            let (incoming, outgoing) = if reversed {
8006                (-Atom::one(), Atom::one())
8007            } else {
8008                (Atom::one(), -Atom::one())
8009            };
8010            let expected = &incoming * q(1, cind(0))
8011                + Atom::num(2) * &outgoing * q(2, cind(0))
8012                + Atom::num(3) * &incoming * &outgoing * q3(1, mink()) * q(2, mink())
8013                + Atom::num(5) * &incoming * &outgoing * q(1, mink()) * q3(2, mink());
8014            assert_eq!(
8015                generator
8016                    .external_state_projector(
8017                        &graph,
8018                        GenerationType::Amplitude,
8019                        Some(&supplied_leg_momenta([7, 3]))
8020                    )
8021                    .unwrap(),
8022                NumeratorInterface::admit(expected, None).unwrap(),
8023                "reversed={reversed}"
8024            );
8025        }
8026    }
8027
8028    #[test]
8029    fn finalized_supplied_projector_momenta_are_the_external_edge_momenta() {
8030        let model =
8031            Model::from_json(include_str!("../../feynkit-model/tests/fixtures/sm.json")).unwrap();
8032        let generator = Generator::new(model);
8033        // Leg 1 is the outgoing photon of the amplitude, and the outgoing copy
8034        // of the initial quark of the cross section, sewn to leg 0.
8035        for (process, generation_type, connections) in [
8036            (
8037                Process::new([22_i64], [22_i64]),
8038                GenerationType::Amplitude,
8039                [0, 1],
8040            ),
8041            (
8042                Process::new([1_i64], [1_i64, 21]),
8043                GenerationType::CrossSection,
8044                [0, 0],
8045            ),
8046        ] {
8047            let options = GenerationOptions::default()
8048                .with_loop_count(1, 1)
8049                .unwrap()
8050                .threads(1)
8051                .max_vertices(2)
8052                .projector(supplied_leg_momenta([0, 1]));
8053            let generated = generator
8054                .generate(&process, &options, generation_type)
8055                .unwrap();
8056            assert!(!generated.diagrams.is_empty());
8057            for diagram in &generated.diagrams {
8058                // The finalized external edge of each leg is oriented along its
8059                // process direction, so its momentum is the leg's momentum.
8060                let leg_edge = |leg: usize| {
8061                    diagram
8062                        .edges()
8063                        .find_map(|(id, _, edge)| {
8064                            edge.external
8065                                .as_ref()
8066                                .is_some_and(|external| external.connection == connections[leg])
8067                                .then_some(id.0)
8068                        })
8069                        .unwrap()
8070                };
8071                assert_eq!(
8072                    diagram.projector(),
8073                    &NumeratorInterface::admit(
8074                        supplied_leg_momenta([leg_edge(0), leg_edge(1)]),
8075                        None
8076                    )
8077                    .unwrap(),
8078                    "{generation_type:?} {}",
8079                    diagram.name()
8080                );
8081            }
8082        }
8083    }
8084
8085    #[test]
8086    fn finalizes_vector_projectors_and_leaves_scalar_states_trivial() {
8087        let generator = Generator::new(fermion_model());
8088        let mut vector_graph = Graph::new();
8089        let incoming = vector_graph.add_node(ColoredNode::External(ExternalNode {
8090            index: 0,
8091            state: ExternalState::Incoming,
8092            particle: particle(&generator.model, 22),
8093        }));
8094        let left = vector_graph.add_node(ColoredNode::Interaction(vertex(&generator.model, "V")));
8095        let right = vector_graph.add_node(ColoredNode::Interaction(vertex(&generator.model, "V")));
8096        let outgoing = vector_graph.add_node(ColoredNode::External(ExternalNode {
8097            index: 1,
8098            state: ExternalState::Outgoing,
8099            particle: particle(&generator.model, 22),
8100        }));
8101        vector_graph
8102            .add_edge(incoming, left, false, edge(&generator.model, 22))
8103            .unwrap();
8104        vector_graph
8105            .add_edge(right, outgoing, false, edge(&generator.model, 22))
8106            .unwrap();
8107        let vector_projector = generator
8108            .external_state_projector(&vector_graph, GenerationType::Amplitude, None)
8109            .unwrap();
8110        let vector_projector = NumeratorInterface::export(&vector_projector).0;
8111        assert_eq!(
8112            function_count(&vector_projector, feynkit_graph::symbols::epsilon()),
8113            1
8114        );
8115        assert_eq!(
8116            function_count(&vector_projector, feynkit_graph::symbols::epsilonbar()),
8117            1
8118        );
8119        assert_eq!(
8120            function_count(&vector_projector, feynkit_graph::symbols::hedge_index()),
8121            2
8122        );
8123
8124        let mut scalar_graph = Graph::new();
8125        let scalar = scalar_graph.add_node(ColoredNode::External(ExternalNode {
8126            index: 0,
8127            state: ExternalState::Incoming,
8128            particle: particle(&generator.model, 25),
8129        }));
8130        let internal =
8131            scalar_graph.add_node(ColoredNode::Interaction(vertex(&generator.model, "V")));
8132        scalar_graph
8133            .add_edge(scalar, internal, false, edge(&generator.model, 25))
8134            .unwrap();
8135        assert_eq!(
8136            generator
8137                .external_state_projector(&scalar_graph, GenerationType::Amplitude, None)
8138                .unwrap()
8139                .expression(),
8140            &Atom::one()
8141        );
8142    }
8143
8144    #[test]
8145    fn forced_cuts_retain_only_the_requested_typed_edge_set() {
8146        let generator = Generator::new(scalar_model());
8147        let process = scalar_cross_section_process();
8148        let options = GenerationOptions::default()
8149            .with_loop_count(1, 1)
8150            .unwrap()
8151            .threads(1)
8152            .max_vertices(4);
8153        let generated = generator
8154            .generate(&process, &options, GenerationType::CrossSection)
8155            .unwrap();
8156        let requested: BTreeSet<EdgeId> = generated
8157            .diagrams
8158            .iter()
8159            .flat_map(|diagram| diagram.cuts())
8160            .next()
8161            .unwrap()
8162            .cut
8163            .iter()
8164            .map(|half_edge| half_edge.edge)
8165            .collect();
8166
8167        let forced = generator
8168            .generate(
8169                &process,
8170                &options.clone().forced_cuts([requested.clone()]),
8171                GenerationType::CrossSection,
8172            )
8173            .unwrap();
8174
8175        assert!(!forced.diagrams.is_empty());
8176        assert!(forced.diagrams.iter().all(|diagram| {
8177            !diagram.cuts().is_empty()
8178                && diagram.cuts().iter().all(|cut| {
8179                    cut.cut
8180                        .iter()
8181                        .map(|half_edge| half_edge.edge)
8182                        .collect::<BTreeSet<_>>()
8183                        == requested
8184                })
8185        }));
8186    }
8187
8188    #[test]
8189    fn unknown_forced_cut_reports_the_typed_edge_set() {
8190        let unknown = BTreeSet::from([EdgeId(usize::MAX)]);
8191        let result = Generator::new(scalar_model()).generate(
8192            &scalar_cross_section_process(),
8193            &GenerationOptions::default()
8194                .with_loop_count(1, 1)
8195                .unwrap()
8196                .threads(1)
8197                .max_vertices(4)
8198                .forced_cuts([unknown]),
8199            GenerationType::CrossSection,
8200        );
8201
8202        assert!(matches!(
8203            result,
8204            Err(GenerationError::UnknownForcedCut { edges })
8205                if edges == vec![usize::MAX]
8206        ));
8207    }
8208
8209    #[test]
8210    fn forced_cut_filtering_precedes_numerator_grouping() {
8211        let generator = Generator::new(scalar_model());
8212        let process = scalar_cross_section_process();
8213        let options = GenerationOptions::default()
8214            .with_loop_count(1, 1)
8215            .unwrap()
8216            .threads(1)
8217            .max_vertices(4);
8218        let generated = generator
8219            .generate(&process, &options, GenerationType::CrossSection)
8220            .unwrap();
8221        let cut_sets = generated
8222            .diagrams
8223            .iter()
8224            .flat_map(|diagram| diagram.cuts())
8225            .map(|cut| {
8226                cut.cut
8227                    .iter()
8228                    .map(|half_edge| half_edge.edge)
8229                    .collect::<BTreeSet<_>>()
8230            })
8231            .collect::<BTreeSet<_>>();
8232        assert!(
8233            cut_sets.len() > 1,
8234            "fixture must exercise actual cut filtering"
8235        );
8236        let requested = cut_sets.into_iter().next().unwrap();
8237
8238        let grouped = generator
8239            .generate(
8240                &process,
8241                &options.forced_cuts([requested.clone()]).numerator_grouping(
8242                    NumeratorGrouping::Identical(GraphGroupingOptions::default()),
8243                ),
8244                GenerationType::CrossSection,
8245            )
8246            .unwrap();
8247
8248        grouped.validate_groups().unwrap();
8249        assert!(!grouped.groups.is_empty());
8250        assert!(grouped.diagrams.iter().all(|diagram| {
8251            !diagram.cuts().is_empty()
8252                && diagram.cuts().iter().all(|cut| {
8253                    cut.cut
8254                        .iter()
8255                        .map(|half_edge| half_edge.edge)
8256                        .collect::<BTreeSet<_>>()
8257                        == requested
8258                })
8259        }));
8260    }
8261
8262    fn diagram_identities(result: &GenerationResult) -> BTreeMap<String, DiagramId> {
8263        result
8264            .diagrams
8265            .iter()
8266            .map(|diagram| (diagram.name().to_owned(), diagram.id()))
8267            .collect()
8268    }
8269
8270    fn cut_edge_sets(diagram: &FeynmanDiagram) -> BTreeSet<BTreeSet<EdgeId>> {
8271        diagram
8272            .cuts()
8273            .iter()
8274            .map(|cut| cut.cut.iter().map(|half_edge| half_edge.edge).collect())
8275            .collect()
8276    }
8277
8278    /// Diagram IDs cover the cuts, so a forced-cut survivor carries the ID of
8279    /// its unforced namesake restricted to the forced cut.
8280    fn id_restricted_to_cut(diagram: &FeynmanDiagram, requested: &BTreeSet<EdgeId>) -> DiagramId {
8281        let cuts = diagram
8282            .cuts()
8283            .iter()
8284            .filter(|cut| {
8285                cut.cut
8286                    .iter()
8287                    .map(|half_edge| half_edge.edge)
8288                    .collect::<BTreeSet<_>>()
8289                    == *requested
8290            })
8291            .cloned()
8292            .collect();
8293        diagram.clone().with_cuts(cuts).unwrap().id()
8294    }
8295
8296    /// The one-loop scenario of the original fix: at most four vertices.
8297    #[test]
8298    fn forced_cuts_preserve_unforced_one_loop_diagram_names_and_ids() {
8299        let generator = Generator::new(scalar_model());
8300        let process = scalar_cross_section_process();
8301        let options = GenerationOptions::default()
8302            .with_loop_count(1, 1)
8303            .unwrap()
8304            .threads(1)
8305            .max_vertices(4);
8306        let generate = |options: &GenerationOptions| {
8307            generator
8308                .generate(&process, options, GenerationType::CrossSection)
8309                .unwrap()
8310        };
8311        let unforced = generate(&options);
8312        // Force a cut of a diagram preceded by one lacking that cut-edge set,
8313        // so that renaming the surviving diagrams by position would shift it.
8314        let (target, requested) = unforced
8315            .diagrams
8316            .iter()
8317            .enumerate()
8318            .find_map(|(index, target)| {
8319                cut_edge_sets(target).into_iter().find_map(|requested| {
8320                    unforced.diagrams[..index]
8321                        .iter()
8322                        .any(|earlier| !cut_edge_sets(earlier).contains(&requested))
8323                        .then_some((target, requested))
8324                })
8325            })
8326            .expect("fixture must prune a diagram named before the forced-cut target");
8327        let survivors = unforced
8328            .diagrams
8329            .iter()
8330            .filter(|diagram| cut_edge_sets(diagram).contains(&requested))
8331            .map(|diagram| {
8332                (
8333                    diagram.name().to_owned(),
8334                    id_restricted_to_cut(diagram, &requested),
8335                )
8336            })
8337            .collect::<BTreeMap<_, _>>();
8338        let forced_options = options.clone().forced_cuts([requested.clone()]);
8339
8340        let forced = generate(&forced_options);
8341        assert!(forced.diagrams.len() < unforced.diagrams.len());
8342        assert_eq!(diagram_identities(&forced), survivors);
8343        let expected = BTreeMap::from([(
8344            target.name().to_owned(),
8345            id_restricted_to_cut(target, &requested),
8346        )]);
8347        for selected in [
8348            forced_options.clone().select_diagrams([target.name()]),
8349            forced_options.clone().select_diagram_ids([target.id()]),
8350        ] {
8351            assert_eq!(diagram_identities(&generate(&selected)), expected);
8352        }
8353        let mut remaining = survivors;
8354        remaining.remove(target.name());
8355        for vetoed in [
8356            forced_options.clone().veto_diagrams([target.name()]),
8357            forced_options.clone().veto_diagram_ids([target.id()]),
8358        ] {
8359            assert_eq!(diagram_identities(&generate(&vetoed)), remaining);
8360        }
8361    }
8362
8363    #[test]
8364    fn forced_cuts_preserve_unforced_diagram_names_ids_and_selections() {
8365        let generator = Generator::new(scalar_model());
8366        let process = scalar_cross_section_process();
8367        let options = GenerationOptions::default()
8368            .with_loop_count(2, 2)
8369            .unwrap()
8370            .threads(1)
8371            .max_vertices(6);
8372        let generate = |options: &GenerationOptions| {
8373            generator
8374                .generate(&process, options, GenerationType::CrossSection)
8375                .unwrap()
8376        };
8377        let unforced = generate(&options);
8378        // Force a cut of a diagram preceded by one lacking that cut-edge set,
8379        // so that renaming the surviving diagrams by position would shift it.
8380        let (target, requested) = unforced
8381            .diagrams
8382            .iter()
8383            .enumerate()
8384            .find_map(|(index, target)| {
8385                let cuts = cut_edge_sets(target);
8386                if cuts.len() < 2 {
8387                    return None;
8388                }
8389                cuts.into_iter().find_map(|requested| {
8390                    unforced.diagrams[..index]
8391                        .iter()
8392                        .any(|earlier| !cut_edge_sets(earlier).contains(&requested))
8393                        .then_some((target, requested))
8394                })
8395            })
8396            .expect("fixture must prune a diagram named before the forced-cut target");
8397        let survivors = unforced
8398            .diagrams
8399            .iter()
8400            .filter(|diagram| cut_edge_sets(diagram).contains(&requested))
8401            .map(|diagram| {
8402                (
8403                    diagram.name().to_owned(),
8404                    id_restricted_to_cut(diagram, &requested),
8405                )
8406            })
8407            .collect::<BTreeMap<_, _>>();
8408        let forced_options = options.clone().forced_cuts([requested.clone()]);
8409
8410        let forced = generate(&forced_options);
8411        assert!(forced.diagrams.len() < unforced.diagrams.len());
8412        assert_eq!(diagram_identities(&forced), survivors);
8413        let survivor = forced
8414            .diagrams
8415            .iter()
8416            .find(|diagram| diagram.name() == target.name())
8417            .unwrap();
8418        assert_ne!(survivor.id(), target.id());
8419        let expected = BTreeMap::from([(target.name().to_owned(), survivor.id())]);
8420        for selected in [
8421            forced_options.clone().select_diagrams([target.name()]),
8422            forced_options.clone().select_diagram_ids([target.id()]),
8423            forced_options.clone().select_diagram_ids([survivor.id()]),
8424        ] {
8425            assert_eq!(diagram_identities(&generate(&selected)), expected);
8426        }
8427        let mut remaining = survivors;
8428        remaining.remove(target.name());
8429        for vetoed in [
8430            forced_options.clone().veto_diagrams([target.name()]),
8431            forced_options.clone().veto_diagram_ids([target.id()]),
8432            forced_options.clone().veto_diagram_ids([survivor.id()]),
8433        ] {
8434            assert_eq!(diagram_identities(&generate(&vetoed)), remaining);
8435        }
8436
8437        let default_edges = &survivor.loop_momentum_basis().loop_edges;
8438        let alternate = default_edges.iter().rev().copied().collect::<Vec<_>>();
8439        assert_ne!(&alternate, default_edges);
8440        let selected = forced_options.clone().select_diagrams([target.name()]);
8441        for routed in [
8442            selected
8443                .clone()
8444                .with_loop_momentum_basis(target.id(), alternate.clone()),
8445            selected
8446                .clone()
8447                .with_loop_momentum_basis(survivor.id(), alternate.clone()),
8448            selected
8449                .clone()
8450                .with_named_loop_momentum_basis(target.name(), alternate.clone()),
8451            selected
8452                .with_loop_momentum_basis(target.id(), default_edges.clone())
8453                .with_loop_momentum_basis(survivor.id(), alternate.clone()),
8454        ] {
8455            let routed = generate(&routed);
8456            assert_eq!(diagram_identities(&routed), expected);
8457            assert_eq!(
8458                routed.diagrams[0].loop_momentum_basis().loop_edges,
8459                alternate
8460            );
8461        }
8462    }
8463
8464    /// Grouping compares numerators by loop-momentum basis position, so the
8465    /// group members and ratios must not depend on a basis requested for the
8466    /// master. The request reroutes only the master that is evaluated; a request
8467    /// for a member merged into another master cannot be honoured.
8468    #[test]
8469    fn requested_master_bases_preserve_numerator_groups() {
8470        let model = Model::qed();
8471        let veto = model
8472            .particles()
8473            .iter()
8474            .map(|particle| particle.pdg_code)
8475            .filter(|pdg| ![11, 22].contains(&pdg.abs()))
8476            .map(ParticleSelector::Pdg)
8477            .collect();
8478        let generator = Generator::new(model);
8479        let options = GenerationOptions::default()
8480            .with_loop_count(2, 2)
8481            .unwrap()
8482            .with_graph_filter(GenerationFilter::ParticleVeto(veto))
8483            .threads(1)
8484            .numerator_grouping(NumeratorGrouping::UpToScalar(
8485                GraphGroupingOptions::default(),
8486            ));
8487        let generate = |options: &GenerationOptions| {
8488            generator.generate(&photon_process(), options, GenerationType::Amplitude)
8489        };
8490        let groups = |result: &GenerationResult| {
8491            result
8492                .groups
8493                .iter()
8494                .map(|group| {
8495                    group
8496                        .members
8497                        .iter()
8498                        .map(|member| (member.source_name.clone(), member.ratio.clone()))
8499                        .collect::<Vec<_>>()
8500                })
8501                .collect::<Vec<_>>()
8502        };
8503        let default = generate(&options).unwrap();
8504        let (master, member) = default
8505            .groups
8506            .iter()
8507            .find_map(|group| match group.members.as_slice() {
8508                [_, member, ..] => Some((&default.diagrams[group.master], member)),
8509                _ => None,
8510            })
8511            .expect("fixture must group two diagrams");
8512        let default_edges = &master.loop_momentum_basis().loop_edges;
8513        // A request that matches no generated name or ID is an error, not a no-op.
8514        for (unknown, expected) in [
8515            (
8516                options
8517                    .clone()
8518                    .with_named_loop_momentum_basis("D999", default_edges.clone()),
8519                "\"D999\"".to_owned(),
8520            ),
8521            (
8522                options
8523                    .clone()
8524                    .with_loop_momentum_basis(DiagramId(u128::MAX), default_edges.clone()),
8525                DiagramId(u128::MAX).to_string(),
8526            ),
8527        ] {
8528            let error = generate(&unknown).unwrap_err();
8529            assert!(
8530                matches!(
8531                    &error,
8532                    GenerationError::UnknownLoopMomentumBasisTarget { target } if target == &expected
8533                ),
8534                "{error}"
8535            );
8536        }
8537        let mut requested = master
8538            .loop_momentum_bases()
8539            .unwrap()
8540            .into_iter()
8541            .map(|basis| basis.loop_edges)
8542            .filter(|edges| edges != default_edges)
8543            .collect::<Vec<_>>();
8544        // Reordering the default edges permutes the basis positions alone.
8545        requested.push(default_edges.iter().rev().copied().collect());
8546        assert!(requested.len() > 1);
8547        for edges in requested {
8548            let routed = generate(
8549                &options
8550                    .clone()
8551                    .with_named_loop_momentum_basis(master.name(), edges.clone()),
8552            )
8553            .unwrap();
8554            assert_eq!(groups(&routed), groups(&default), "basis {edges:?}");
8555            let routed_master = routed
8556                .diagrams
8557                .iter()
8558                .find(|diagram| diagram.name() == master.name())
8559                .unwrap();
8560            assert_eq!(routed_master.loop_momentum_basis().loop_edges, edges);
8561        }
8562
8563        // The member's own default basis is valid for it; only the grouping refuses it.
8564        let ungrouped =
8565            generate(&options.clone().numerator_grouping(NumeratorGrouping::None)).unwrap();
8566        let member_basis = ungrouped
8567            .diagrams
8568            .iter()
8569            .find(|diagram| diagram.name() == member.source_name)
8570            .unwrap()
8571            .loop_momentum_basis()
8572            .loop_edges
8573            .clone();
8574        let error = generate(
8575            &options
8576                .clone()
8577                .with_named_loop_momentum_basis(&member.source_name, member_basis),
8578        )
8579        .unwrap_err();
8580        assert!(
8581            matches!(
8582                &error,
8583                GenerationError::LoopMomentumBasisOfGroupedMember { member: requested, master: grouped }
8584                    if requested == &member.source_name && grouped == master.name()
8585            ),
8586            "{error}"
8587        );
8588    }
8589
8590    #[test]
8591    fn rejects_model_bound_process_and_filter_selectors_from_another_model() {
8592        let source = scalar_model();
8593        let mut target_json: serde_json::Value =
8594            serde_json::from_str(&source.to_json().unwrap()).unwrap();
8595        target_json["name"] = serde_json::Value::String("other_phi3".to_owned());
8596        let target = Model::from_json(&serde_json::to_string(&target_json).unwrap()).unwrap();
8597        assert_ne!(source.fingerprint(), target.fingerprint());
8598
8599        let foreign_particle =
8600            ParticleSelector::by_id(&source, source.particle_id("phi").unwrap()).unwrap();
8601        let process = Process::new([foreign_particle.clone()], ["phi"]);
8602        assert!(matches!(
8603            Generator::new(target.clone()).generate(
8604                &process,
8605                &GenerationOptions::default(),
8606                GenerationType::Amplitude
8607            ),
8608            Err(GenerationError::Selector(SelectorError::ModelMismatch {
8609                kind: "particle",
8610                ..
8611            }))
8612        ));
8613
8614        let foreign_vertex =
8615            VertexSelector::by_id(&source, source.vertex_rule_id("V1").unwrap()).unwrap();
8616        for filter in [
8617            GenerationFilter::ParticleVeto(vec![foreign_particle]),
8618            GenerationFilter::VertexAllow(vec![foreign_vertex]),
8619        ] {
8620            let options = GenerationOptions::default().with_graph_filter(filter);
8621            assert!(matches!(
8622                Generator::new(target.clone()).generate(
8623                    &Process::new(["phi"], ["phi", "phi"]),
8624                    &options,
8625                    GenerationType::Amplitude
8626                ),
8627                Err(GenerationError::Selector(
8628                    SelectorError::ModelMismatch { .. }
8629                ))
8630            ));
8631        }
8632    }
8633
8634    #[test]
8635    fn empty_generation_returns_a_completed_result() {
8636        let generator = Generator::new(scalar_model());
8637        let process = Process::new(["phi"], ["phi", "phi"]);
8638        for options in [
8639            GenerationOptions::default().max_vertices(0),
8640            GenerationOptions::default().with_graph_filter(GenerationFilter::ParticleVeto(vec![
8641                ParticleSelector::Name("phi".to_owned()),
8642            ])),
8643        ] {
8644            let result = generator
8645                .generate(&process, &options, GenerationType::Amplitude)
8646                .unwrap();
8647            assert!(result.report.completed);
8648            assert!(result.diagrams.is_empty());
8649            assert!(result.groups.is_empty());
8650            assert_eq!(result.report.topology_count, 0);
8651            assert_eq!(result.report.interaction_assignment_count, 0);
8652            assert_eq!(result.report.retained_count, 0);
8653        }
8654    }
8655
8656    #[test]
8657    fn cancelled_generation_returns_an_incomplete_result() {
8658        let cancellation = CancellationToken::new();
8659        cancellation.cancel();
8660        let generated = Generator::new(scalar_model())
8661            .generate(
8662                &Process::new(["phi"], ["phi", "phi"]),
8663                &GenerationOptions::default().cancellation_token(cancellation),
8664                GenerationType::Amplitude,
8665            )
8666            .unwrap();
8667
8668        assert!(!generated.report.completed);
8669        assert!(generated.diagrams.is_empty());
8670    }
8671
8672    #[test]
8673    fn thread_counts_preserve_diagrams_and_progress_order() {
8674        let generator = Generator::new(Model::qcd());
8675        let process = Process::new(["g"], ["g"])
8676            .with_particle_filters(
8677                Some(
8678                    ["u", "d", "c", "s", "t"]
8679                        .into_iter()
8680                        .map(Into::into)
8681                        .collect(),
8682                ),
8683                None,
8684                None,
8685                vec![],
8686            )
8687            .unwrap();
8688        let options = GenerationOptions::default()
8689            .with_loop_count(2, 2)
8690            .unwrap()
8691            .with_graph_filter(GenerationFilter::MaxNumberOfBridges(0));
8692        let serial = generator
8693            .generate(
8694                &process,
8695                &options.clone().threads(1),
8696                GenerationType::Amplitude,
8697            )
8698            .unwrap();
8699        let progress = Arc::new(Mutex::new(Vec::new()));
8700        let progress_sink = Arc::clone(&progress);
8701        let parallel = generator
8702            .generate(
8703                &process,
8704                &options.threads(4).progress(move |update| {
8705                    if update.stage == "numerators" {
8706                        progress_sink.lock().unwrap().push(update.completed);
8707                    }
8708                    crate::GenerationControl::Continue
8709                }),
8710                GenerationType::Amplitude,
8711            )
8712            .unwrap();
8713        assert!(!serial.diagrams.is_empty());
8714        assert_eq!(serial.report, parallel.report);
8715        assert_eq!(
8716            *progress.lock().unwrap(),
8717            (0..=parallel.diagrams.len()).collect::<Vec<_>>()
8718        );
8719        for (serial, parallel) in serial.diagrams.iter().zip(&parallel.diagrams) {
8720            assert_eq!(serial.to_json().unwrap(), parallel.to_json().unwrap());
8721        }
8722        assert_eq!(serial.groups.len(), parallel.groups.len());
8723        for (serial, parallel) in serial.groups.iter().zip(&parallel.groups) {
8724            assert_eq!(serial.master, parallel.master);
8725            assert_eq!(serial.members.len(), parallel.members.len());
8726            for (serial, parallel) in serial.members.iter().zip(&parallel.members) {
8727                assert_eq!(serial.source_id, parallel.source_id);
8728                assert_eq!(serial.source_diagram, parallel.source_diagram);
8729                assert_eq!(serial.ratio, parallel.ratio);
8730                assert_eq!(serial.overall_factor, parallel.overall_factor);
8731            }
8732        }
8733    }
8734
8735    #[test]
8736    fn zero_color_filter_is_opt_in_for_generated_qcd_tadpoles() {
8737        let model = Arc::new(Model::qcd());
8738        let process = Process::new([] as [&str; 0], ["g"]);
8739        let options = GenerationOptions::default()
8740            .with_loop_count(1, 1)
8741            .unwrap()
8742            .max_vertices(1)
8743            .allow_self_loops(true)
8744            .allow_zero_flow_edges(true)
8745            .threads(1);
8746        let unfiltered = process.generate_diagrams(model.clone(), &options).unwrap();
8747        assert!(unfiltered.report.completed);
8748        assert!(!unfiltered.diagrams.is_empty());
8749        assert_eq!(unfiltered.report.zero_numerator_count, 0);
8750        assert!(
8751            unfiltered
8752                .diagrams
8753                .iter()
8754                .any(|diagram| !diagram.numerator().is_zero())
8755        );
8756
8757        let updates = Arc::new(Mutex::new(Vec::new()));
8758        let captured = updates.clone();
8759        let filtered_options = options
8760            .clone()
8761            .filter_zero_color(true)
8762            .progress(move |update| {
8763                if update.stage == "filter_zero_color" {
8764                    captured.lock().unwrap().push(update);
8765                }
8766                crate::GenerationControl::Continue
8767            });
8768        let filtered = process
8769            .generate_diagrams(model.clone(), &filtered_options)
8770            .unwrap();
8771        assert!(filtered.report.completed);
8772        assert!(filtered.diagrams.is_empty());
8773        assert_eq!(
8774            filtered.report.zero_numerator_count,
8775            unfiltered.diagrams.len()
8776        );
8777        filtered.validate_groups().unwrap();
8778        let updates = updates.lock().unwrap();
8779        assert_eq!(
8780            updates
8781                .iter()
8782                .map(|update| (update.completed, update.zero_numerator_count))
8783                .collect::<Vec<_>>(),
8784            (0..=unfiltered.diagrams.len())
8785                .map(|count| (count, count))
8786                .collect::<Vec<_>>()
8787        );
8788        assert!(
8789            updates
8790                .iter()
8791                .all(|update| update.total == Some(unfiltered.diagrams.len()))
8792        );
8793
8794        let amplitude = process
8795            .generate_amplitude(model.clone(), &options, Default::default())
8796            .unwrap();
8797        assert_eq!(amplitude.diagrams().len(), unfiltered.diagrams.len());
8798        assert!(matches!(
8799            process.generate_amplitude(model, &options.filter_zero_color(true), Default::default()),
8800            Err(GenerationError::Amplitude(error)) if matches!(*error, feynkit_amplitude::AmplitudeError::Empty)
8801        ));
8802    }
8803
8804    #[test]
8805    fn zero_color_filter_progress_can_cancel_algebra() {
8806        let process = Process::new([] as [&str; 0], ["g"]);
8807        let result = process
8808            .generate_diagrams(
8809                Model::qcd(),
8810                &GenerationOptions::default()
8811                    .with_loop_count(1, 1)
8812                    .unwrap()
8813                    .max_vertices(1)
8814                    .allow_self_loops(true)
8815                    .allow_zero_flow_edges(true)
8816                    .threads(1)
8817                    .filter_zero_color(true)
8818                    .progress(|update| {
8819                        if update.stage == "filter_zero_color" && update.completed == 1 {
8820                            crate::GenerationControl::Cancel
8821                        } else {
8822                            crate::GenerationControl::Continue
8823                        }
8824                    }),
8825            )
8826            .unwrap();
8827        assert!(!result.report.completed);
8828        assert_eq!(result.report.zero_numerator_count, 1);
8829        assert!(!result.diagrams.is_empty());
8830        result.validate_groups().unwrap();
8831    }
8832
8833    #[test]
8834    fn single_thread_generation_stays_on_the_caller() {
8835        let caller = std::thread::current().id();
8836        let observed = Arc::new(Mutex::new(Vec::new()));
8837        let sink = observed.clone();
8838        let options = GenerationOptions::default()
8839            .with_loop_count(1, 1)
8840            .unwrap()
8841            .threads(1)
8842            .filter_zero_color(true)
8843            .progress(move |progress| {
8844                if progress.completed > 0 {
8845                    sink.lock()
8846                        .unwrap()
8847                        .push((progress.stage.to_owned(), std::thread::current().id()));
8848                }
8849                crate::GenerationControl::Continue
8850            });
8851        let generator = Generator::new(Model::yang_mills());
8852        let process = Process::new(["g"], ["g"]);
8853        let first = generator
8854            .generate(&process, &options, GenerationType::Amplitude)
8855            .unwrap();
8856        let second = generator
8857            .generate(&process, &options, GenerationType::Amplitude)
8858            .unwrap();
8859        assert!(first.report.completed && second.report.completed);
8860        first.validate_groups().unwrap();
8861        second.validate_groups().unwrap();
8862        assert!(!first.diagrams.is_empty());
8863        assert_eq!(first.diagrams.len(), second.diagrams.len());
8864        for (left, right) in first.diagrams.iter().zip(&second.diagrams) {
8865            assert_eq!(left.to_dot().unwrap(), right.to_dot().unwrap());
8866        }
8867        let observed = observed.lock().unwrap();
8868        for stage in ["interactions", "numerators", "filter_zero_color"] {
8869            assert!(
8870                observed.iter().any(|(actual, _)| actual == stage),
8871                "missing {stage}"
8872            );
8873        }
8874        assert!(observed.iter().all(|(_, thread)| *thread == caller));
8875    }
8876
8877    #[cfg(not(target_arch = "wasm32"))]
8878    #[test]
8879    fn color_filter_uses_the_requested_generation_pool() {
8880        for threads in [2, 4] {
8881            let observed = Arc::new(Mutex::new(Vec::new()));
8882            let sink = observed.clone();
8883            let options = GenerationOptions::default()
8884                .with_loop_count(1, 1)
8885                .unwrap()
8886                .threads(threads)
8887                .filter_zero_color(true)
8888                .progress(move |progress| {
8889                    if progress.stage == "filter_zero_color" && progress.completed > 0 {
8890                        sink.lock().unwrap().push(rayon::current_num_threads());
8891                    }
8892                    crate::GenerationControl::Continue
8893                });
8894            let generated = Generator::new(Model::yang_mills())
8895                .generate(
8896                    &Process::new(["g"], ["g"]),
8897                    &options,
8898                    GenerationType::Amplitude,
8899                )
8900                .unwrap();
8901            assert!(generated.report.completed);
8902            let observed = observed.lock().unwrap();
8903            assert!(!observed.is_empty());
8904            assert!(observed.iter().all(|&actual| actual == threads));
8905        }
8906    }
8907
8908    /// Symbolica orders the factors of a product by symbol creation, so the
8909    /// printed numerators and overall factors must not depend on which diagram
8910    /// first meets a coupling or a factor head. Each run is a fresh process of
8911    /// this test binary: one loop at 1 and at 32 threads, and at 1 thread after
8912    /// the Born diagrams, which meet the external-ordering sign and the tree
8913    /// couplings before any loop diagram does.
8914    #[cfg(not(target_arch = "wasm32"))]
8915    #[test]
8916    fn printed_numerators_and_overall_factors_do_not_depend_on_generation_order() {
8917        const RUN: &str = "FEYNKIT_GENERATOR_PRINT_TEST_RUN";
8918        if let Ok(run) = env::var(RUN) {
8919            let generator = Generator::new(standard_model());
8920            let generate = |loops, threads| {
8921                generator
8922                    .generate(
8923                        &Process::new(["e-", "e+"], ["mu-", "mu+"]),
8924                        &GenerationOptions::default()
8925                            .with_loop_count(loops, loops)
8926                            .unwrap()
8927                            .threads(threads),
8928                        GenerationType::Amplitude,
8929                    )
8930                    .unwrap()
8931            };
8932            let threads = match run.as_str() {
8933                "after-born" => {
8934                    generate(0, 1);
8935                    1
8936                }
8937                threads => threads.parse().unwrap(),
8938            };
8939            for diagram in generate(1, threads).diagrams {
8940                println!(
8941                    "{RUN} {} {} {}",
8942                    diagram.name(),
8943                    NumeratorInterface::export(diagram.numerator()).0,
8944                    diagram.overall_factor()
8945                );
8946            }
8947            return;
8948        }
8949        let child = |run: &str| {
8950            let output = Command::new(env::current_exe().unwrap())
8951                .args([
8952                    "--exact",
8953                    "generation::tests::printed_numerators_and_overall_factors_do_not_depend_on_generation_order",
8954                    "--nocapture",
8955                ])
8956                .env(RUN, run)
8957                .output()
8958                .unwrap();
8959            assert!(
8960                output.status.success(),
8961                "{run}: {}",
8962                String::from_utf8_lossy(&output.stderr)
8963            );
8964            String::from_utf8(output.stdout)
8965                .unwrap()
8966                .lines()
8967                .filter_map(|line| line.split_once(RUN).map(|(_, record)| record.to_owned()))
8968                .collect::<Vec<_>>()
8969        };
8970        let serial = child("1");
8971        assert_eq!(serial.len(), 464);
8972        for run in ["32", "after-born"] {
8973            let printed = child(run);
8974            assert_eq!(printed.len(), serial.len(), "{run}");
8975            for (serial, printed) in serial.iter().zip(&printed) {
8976                assert_eq!(printed, serial, "{run}");
8977            }
8978        }
8979    }
8980
8981    #[test]
8982    fn numerator_progress_can_cancel_construction() {
8983        let generated = Generator::new(Model::yang_mills())
8984            .generate(
8985                &Process::new(["g"], ["g"]),
8986                &GenerationOptions::default()
8987                    .with_loop_count(2, 2)
8988                    .unwrap()
8989                    .threads(4)
8990                    .progress(|update| {
8991                        if update.stage == "numerators" && update.completed == 2 {
8992                            crate::GenerationControl::Cancel
8993                        } else {
8994                            crate::GenerationControl::Continue
8995                        }
8996                    }),
8997                GenerationType::Amplitude,
8998            )
8999            .unwrap();
9000        assert!(!generated.report.completed);
9001        assert!(!generated.diagrams.is_empty());
9002        assert!(generated.report.retained_count < generated.report.interaction_assignment_count);
9003        generated.validate_groups().unwrap();
9004    }
9005
9006    #[test]
9007    fn cancellation_callback_returns_an_incomplete_result() {
9008        let generated = Generator::new(scalar_model())
9009            .generate(
9010                &Process::new(["phi"], ["phi", "phi"]),
9011                &GenerationOptions::default().cancellation_check(|| true),
9012                GenerationType::Amplitude,
9013            )
9014            .unwrap();
9015
9016        assert!(!generated.report.completed);
9017        assert!(generated.diagrams.is_empty());
9018    }
9019
9020    #[test]
9021    fn directed_and_undirected_half_edges_use_the_interaction_key_order() {
9022        let model = fermion_model();
9023        let options =
9024            GenerationOptions::default().with_graph_filter(GenerationFilter::VertexAllow(vec![
9025                VertexSelector::Name("V".to_owned()),
9026            ]));
9027        let options = options.resolve_selectors(&model).unwrap();
9028        let signatures = InteractionSignatures::new(&model, &options).unwrap();
9029        let mut signature = vec![
9030            EdgeColor {
9031                particle: particle(&model, 1),
9032                direction: Some(false),
9033            },
9034            EdgeColor {
9035                particle: particle(&model, 1),
9036                direction: Some(true),
9037            },
9038            EdgeColor {
9039                particle: particle(&model, 22),
9040                direction: None,
9041            },
9042        ];
9043        signature.sort();
9044
9045        assert_eq!(
9046            signatures.rules(&signature).unwrap(),
9047            &[vertex(&model, "V")]
9048        );
9049    }
9050
9051    #[test]
9052    fn external_fermion_chains_are_oriented_consistently() {
9053        let model = fermion_model();
9054        let process = ResolvedProcess::new(
9055            &model,
9056            &Process::new([1_i64, -1], Vec::<i64>::new()),
9057            GenerationType::Amplitude,
9058            &GenerationOptions::default(),
9059        )
9060        .unwrap();
9061        let mut graph = Graph::new();
9062        let particle_vertex = graph.add_node(ColoredNode::External(ExternalNode {
9063            index: 0,
9064            state: ExternalState::Incoming,
9065            particle: particle(&model, 1),
9066        }));
9067        let left = graph.add_node(ColoredNode::Interaction(vertex(&model, "V")));
9068        let right = graph.add_node(ColoredNode::Interaction(vertex(&model, "V")));
9069        let antiparticle = graph.add_node(ColoredNode::External(ExternalNode {
9070            index: 1,
9071            state: ExternalState::Incoming,
9072            particle: particle(&model, -1),
9073        }));
9074        let fermion = EdgeColor {
9075            particle: particle(&model, 1),
9076            direction: None,
9077        };
9078        graph
9079            .add_edge(particle_vertex, left, true, fermion)
9080            .unwrap();
9081        graph
9082            .add_edge(
9083                right,
9084                left,
9085                true,
9086                EdgeColor {
9087                    particle: particle(&model, -1),
9088                    direction: None,
9089                },
9090            )
9091            .unwrap();
9092        graph.add_edge(right, antiparticle, true, fermion).unwrap();
9093
9094        let normalized = process.normalize_fermion_flows(&graph, &model).unwrap();
9095        assert_eq!(
9096            normalized.graph.edges()[0].vertices,
9097            (particle_vertex, left)
9098        );
9099        assert_eq!(normalized.graph.edges()[1].vertices, (left, right));
9100        assert_eq!(normalized.graph.edges()[2].vertices, (right, antiparticle));
9101        assert_eq!(
9102            normalized
9103                .graph
9104                .edges()
9105                .iter()
9106                .map(|edge| edge.data.particle)
9107                .collect::<Vec<_>>(),
9108            vec![particle(&model, 1); 3],
9109        );
9110        assert_eq!(normalized.reversed_edges, BTreeSet::from([EdgeId(1)]));
9111        assert!(normalized.signs.external_ordering_negative);
9112        assert!(normalized.signs.include_external_ordering);
9113        assert!(!normalized.signs.include_antifermion_spin_sum);
9114        assert!(!normalized.signs.antifermion_spin_sum_negative);
9115
9116        let symmetrized = ResolvedProcess::new(
9117            &model,
9118            &Process::new([1_i64, -1], Vec::<i64>::new()),
9119            GenerationType::Amplitude,
9120            &GenerationOptions::default()
9121                .symmetrize_initial(true)
9122                .symmetrize_external_fermions(true),
9123        )
9124        .unwrap()
9125        .normalize_fermion_flows(&graph, &model)
9126        .unwrap();
9127        assert!(!symmetrized.signs.include_external_ordering);
9128        assert!(!symmetrized.signs.external_ordering_negative);
9129    }
9130
9131    #[test]
9132    fn ghost_chains_follow_external_anticommuting_order() {
9133        let source = fermion_model().to_json().unwrap();
9134        let mut definition = serde_json::from_str::<serde_json::Value>(&source).unwrap();
9135        for particle in definition["particles"].as_array_mut().unwrap() {
9136            match particle["name"].as_str() {
9137                Some("f") => {
9138                    particle["spin"] = serde_json::json!(-1);
9139                    particle["ghost_number"] = serde_json::json!(1);
9140                }
9141                Some("f~") => {
9142                    particle["spin"] = serde_json::json!(-1);
9143                    particle["ghost_number"] = serde_json::json!(-1);
9144                }
9145                _ => {}
9146            }
9147        }
9148        definition["lorentz_structures"][0]["spins"] = serde_json::json!([-1, -1, 3]);
9149        let model = Model::from_json(&definition.to_string()).unwrap();
9150        let process = ResolvedProcess::new(
9151            &model,
9152            &Process::new([1_i64, -1], Vec::<i64>::new()),
9153            GenerationType::Amplitude,
9154            &GenerationOptions::default(),
9155        )
9156        .unwrap();
9157        let mut graph = Graph::new();
9158        let ghost = graph.add_node(ColoredNode::External(ExternalNode {
9159            index: 0,
9160            state: ExternalState::Incoming,
9161            particle: particle(&model, 1),
9162        }));
9163        let left = graph.add_node(ColoredNode::Interaction(vertex(&model, "V")));
9164        let right = graph.add_node(ColoredNode::Interaction(vertex(&model, "V")));
9165        let antighost = graph.add_node(ColoredNode::External(ExternalNode {
9166            index: 1,
9167            state: ExternalState::Incoming,
9168            particle: particle(&model, -1),
9169        }));
9170        let flow = EdgeColor {
9171            particle: particle(&model, 1),
9172            direction: None,
9173        };
9174        graph.add_edge(ghost, left, true, flow).unwrap();
9175        graph.add_edge(right, left, true, flow).unwrap();
9176        graph.add_edge(right, antighost, true, flow).unwrap();
9177
9178        let normalized = process.normalize_fermion_flows(&graph, &model).unwrap();
9179        assert_eq!(normalized.graph.edges()[0].vertices, (ghost, left));
9180        assert_eq!(normalized.graph.edges()[1].vertices, (left, right));
9181        assert_eq!(normalized.graph.edges()[2].vertices, (right, antighost));
9182        // The all-incoming order [ghost, antighost] is one transposition
9183        // from the canonical [antighost, ghost] order, just as for spinors.
9184        assert!(normalized.signs.external_ordering_negative);
9185        assert!(!normalized.signs.antifermion_spin_sum_negative);
9186    }
9187
9188    #[test]
9189    fn cp_symmetrization_groups_mirrored_real_scalar_forward_graphs() {
9190        let model = Model::from_json(include_str!(
9191            "../../feynkit-model/tests/fixtures/scalars_2p_3p.json"
9192        ))
9193        .unwrap();
9194        let mut definition = serde_json::to_value(&model).unwrap();
9195        definition["lorentz_structures"]
9196            .as_array_mut()
9197            .unwrap()
9198            .push(serde_json::json!({
9199                "name":"SCALAR_4_LORENTZ_STRUCTURE", "spins":[1,1,1,1], "structure":"1"
9200            }));
9201        definition["vertex_rules"]
9202            .as_array_mut()
9203            .unwrap()
9204            .push(serde_json::json!({
9205                "name":"V_4_SCALAR_0000", "particles":["scalar_0","scalar_0","scalar_0","scalar_0"],
9206                "color_structures":["1"], "lorentz_structures":["SCALAR_4_LORENTZ_STRUCTURE"],
9207                "couplings":[["SCALAR_COUPLING"]]
9208            }));
9209        let model: Model = serde_json::from_value(definition).unwrap();
9210        let mut graphs = Vec::new();
9211        for mirrored in [false, true] {
9212            let mut graph = Graph::new();
9213            // Sew a cubic box to a quartic Born vertex. Its two external
9214            // neighbors have different valences, so only a global side swap
9215            // can identify the mirror.
9216            for node in 0..5 {
9217                graph.add_node(ColoredNode::Interaction(vertex(
9218                    &model,
9219                    if node == 4 {
9220                        "V_4_SCALAR_0000"
9221                    } else {
9222                        "V_3_SCALAR_000"
9223                    },
9224                )));
9225            }
9226            for index in 0..2 {
9227                let index = if mirrored { 1 - index } else { index };
9228                graph.add_node(ColoredNode::External(ExternalNode {
9229                    index,
9230                    state: if index == 0 {
9231                        ExternalState::Incoming
9232                    } else {
9233                        ExternalState::Outgoing
9234                    },
9235                    particle: particle(&model, 1000),
9236                }));
9237            }
9238            for (left, right) in [
9239                (5, 0),
9240                (0, 1),
9241                (1, 2),
9242                (2, 3),
9243                (3, 0),
9244                (1, 4),
9245                (2, 4),
9246                (3, 4),
9247                (4, 6),
9248            ] {
9249                let (left, right) = if mirrored {
9250                    (right, left)
9251                } else {
9252                    (left, right)
9253                };
9254                graph
9255                    .add_edge(left, right, true, edge(&model, 1000))
9256                    .unwrap();
9257            }
9258            graphs.push(graph);
9259        }
9260        for enabled in [false, true] {
9261            let process = ResolvedProcess::new(
9262                &model,
9263                &Process::new([1000_i64], [1000_i64, 1000, 1000]),
9264                GenerationType::CrossSection,
9265                &GenerationOptions::default()
9266                    .with_loop_count(3, 3)
9267                    .unwrap()
9268                    .symmetrize_left_right(enabled),
9269            )
9270            .unwrap();
9271            let canonical = graphs
9272                .iter()
9273                .map(|graph| {
9274                    process
9275                        .canonicalize_numerator_graph(graph, &model, &NumeratorGrouping::None)
9276                        .unwrap()
9277                })
9278                .collect::<Vec<_>>();
9279            assert_eq!(canonical[0] == canonical[1], enabled);
9280        }
9281    }
9282
9283    #[test]
9284    fn global_left_right_canonicalization_preserves_charged_slash_momenta() {
9285        let model = fermion_model();
9286        let process = ResolvedProcess::new(
9287            &model,
9288            &Process::new([1_i64, -1], [22_i64]),
9289            GenerationType::CrossSection,
9290            &GenerationOptions::default().symmetrize_left_right(true),
9291        )
9292        .unwrap();
9293        let mut graph = Graph::new();
9294        let external_particles = [1_i64, -1, 1, -1];
9295        let external_nodes = external_particles
9296            .into_iter()
9297            .enumerate()
9298            .map(|(index, pdg)| {
9299                graph.add_node(ColoredNode::External(ExternalNode {
9300                    index,
9301                    state: if index < 2 {
9302                        ExternalState::Incoming
9303                    } else {
9304                        ExternalState::Outgoing
9305                    },
9306                    particle: particle(&model, pdg),
9307                }))
9308            })
9309            .collect::<Vec<_>>();
9310        let left = graph.add_node(ColoredNode::Interaction(vertex(&model, "V")));
9311        let right = graph.add_node(ColoredNode::Interaction(vertex(&model, "V")));
9312        let charged = EdgeColor {
9313            particle: particle(&model, 1),
9314            direction: None,
9315        };
9316        graph
9317            .add_edge(external_nodes[0], left, true, charged)
9318            .unwrap();
9319        graph
9320            .add_edge(left, external_nodes[1], true, charged)
9321            .unwrap();
9322        graph
9323            .add_edge(right, external_nodes[2], true, charged)
9324            .unwrap();
9325        graph
9326            .add_edge(external_nodes[3], right, true, charged)
9327            .unwrap();
9328        graph.add_edge(left, right, true, charged).unwrap();
9329
9330        let external_swap = BTreeMap::from([
9331            (external_nodes[0], external_nodes[2]),
9332            (external_nodes[1], external_nodes[3]),
9333            (external_nodes[2], external_nodes[0]),
9334            (external_nodes[3], external_nodes[1]),
9335        ]);
9336        let mut mirror = Graph::new();
9337        for node in graph.nodes() {
9338            mirror.add_node(node.data.clone());
9339        }
9340        for edge in graph.edges() {
9341            let mut data = edge.data;
9342            data.particle = model.particle_by_id(data.particle).unwrap().antiparticle;
9343            mirror
9344                .add_edge(
9345                    external_swap
9346                        .get(&edge.vertices.0)
9347                        .copied()
9348                        .unwrap_or(edge.vertices.0),
9349                    external_swap
9350                        .get(&edge.vertices.1)
9351                        .copied()
9352                        .unwrap_or(edge.vertices.1),
9353                    edge.directed,
9354                    data,
9355                )
9356                .unwrap();
9357        }
9358
9359        let grouping = NumeratorGrouping::UpToScalar(GraphGroupingOptions::default());
9360        let canonical = process
9361            .canonicalize_numerator_graph(&graph, &model, &grouping)
9362            .unwrap();
9363        let canonical_mirror = process
9364            .canonicalize_numerator_graph(&mirror, &model, &grouping)
9365            .unwrap();
9366        assert_eq!(canonical, canonical_mirror);
9367
9368        let internal_edge = canonical
9369            .edges()
9370            .iter()
9371            .enumerate()
9372            .find(|(_, edge)| {
9373                matches!(
9374                    canonical.nodes()[edge.vertices.0].data,
9375                    ColoredNode::Interaction(_)
9376                ) && matches!(
9377                    canonical.nodes()[edge.vertices.1].data,
9378                    ColoredNode::Interaction(_)
9379                )
9380            })
9381            .map(|(edge, _)| edge)
9382            .unwrap();
9383        let generator = Generator::new(model.clone());
9384        let (particle_numerator, particle_fallback) = generator
9385            .propagator_numerator(model.particle_by_id(particle(&model, 1)).unwrap())
9386            .unwrap();
9387        let (antiparticle_numerator, antiparticle_fallback) = generator
9388            .propagator_numerator(model.particle_by_id(particle(&model, -1)).unwrap())
9389            .unwrap();
9390        assert_eq!(particle_numerator, antiparticle_numerator);
9391        assert!(!particle_fallback);
9392        assert!(antiparticle_fallback);
9393        let (propagator, used_antiparticle_fallback) = generator
9394            .propagator_numerator(
9395                model
9396                    .particle_by_id(canonical.edges()[internal_edge].data.particle)
9397                    .unwrap(),
9398            )
9399            .unwrap();
9400        let (first_flow, second_flow) = if used_antiparticle_fallback {
9401            (Flow::Sink, Flow::Source)
9402        } else {
9403            (Flow::Source, Flow::Sink)
9404        };
9405        let legs = [
9406            NumeratorHalfEdge {
9407                edge: internal_edge,
9408                flow: first_flow,
9409                hedge: 2 * internal_edge + usize::from(first_flow == Flow::Sink),
9410                spin: 2,
9411                color: 1,
9412            },
9413            NumeratorHalfEdge {
9414                edge: internal_edge,
9415                flow: second_flow,
9416                hedge: 2 * internal_edge + usize::from(second_flow == Flow::Sink),
9417                spin: 2,
9418                color: 1,
9419            },
9420        ];
9421        let localized = NumeratorInstantiation {
9422            owner: NumeratorOwner::Edge(internal_edge),
9423            legs: &legs,
9424        }
9425        .instantiate(&propagator, NumeratorSector::Spin)
9426        .unwrap();
9427        assert_eq!(function_count(&localized, symbol!("gammalooprs::Q")), 1);
9428    }
9429
9430    #[test]
9431    fn canonical_parallel_edges_are_ordered_by_signed_pdg() {
9432        let model = standard_model();
9433        let process = ResolvedProcess::new(
9434            &model,
9435            &photon_process(),
9436            GenerationType::Amplitude,
9437            &GenerationOptions::default(),
9438        )
9439        .unwrap();
9440        let grouping = NumeratorGrouping::UpToSign(GraphGroupingOptions::default());
9441
9442        for particles in [[-4_i64, 251_i64], [4_i64, -251_i64]] {
9443            let mut graph = Graph::new();
9444            let source = graph.add_node(ColoredNode::Interaction(vertex(&model, "V_71")));
9445            let sink = graph.add_node(ColoredNode::Interaction(vertex(&model, "V_71")));
9446            for pdg in particles {
9447                graph
9448                    .add_edge(source, sink, true, edge(&model, pdg))
9449                    .unwrap();
9450            }
9451
9452            let canonical = process
9453                .canonicalize_numerator_graph(&graph, &model, &grouping)
9454                .unwrap();
9455            let pdgs = canonical
9456                .edges()
9457                .iter()
9458                .map(|edge| model.particle_by_id(edge.data.particle).unwrap().pdg_code)
9459                .collect::<Vec<_>>();
9460            assert!(pdgs.windows(2).all(|pair| pair[0] <= pair[1]), "{pdgs:?}");
9461        }
9462    }
9463
9464    #[test]
9465    fn cp_transformed_edges_select_the_unique_conjugate_interaction_rule() {
9466        let model = standard_model();
9467        let mut graph = Graph::new();
9468        let interaction = graph.add_node(ColoredNode::Interaction(vertex(&model, "V_82")));
9469        for (index, pdg) in [-4_i64, 1, 251].into_iter().enumerate() {
9470            let external = graph.add_node(ColoredNode::External(ExternalNode {
9471                index,
9472                state: ExternalState::Incoming,
9473                particle: particle(&model, pdg),
9474            }));
9475            graph
9476                .add_edge(interaction, external, true, edge(&model, pdg))
9477                .unwrap();
9478        }
9479
9480        let repaired = ResolvedProcess::repair_cp_interaction_rules(graph, &model).unwrap();
9481        assert_eq!(
9482            repaired.nodes()[interaction].data,
9483            ColoredNode::Interaction(vertex(&model, "V_117"))
9484        );
9485        let rule = model.vertex_rule("V_117").unwrap();
9486        assert_eq!(
9487            Generator::new(model.clone())
9488                .interaction_half_edges(&repaired, interaction, rule)
9489                .unwrap()
9490                .len(),
9491            rule.particles.len()
9492        );
9493    }
9494
9495    #[test]
9496    fn cp_repaired_interaction_rules_obey_final_vertex_filters() {
9497        let model = standard_model();
9498        let mut graph = Graph::new();
9499        let interaction = graph.add_node(ColoredNode::Interaction(vertex(&model, "V_82")));
9500        for (index, pdg) in [-4_i64, 1, 251].into_iter().enumerate() {
9501            let external = graph.add_node(ColoredNode::External(ExternalNode {
9502                index,
9503                state: ExternalState::Incoming,
9504                particle: particle(&model, pdg),
9505            }));
9506            graph
9507                .add_edge(interaction, external, true, edge(&model, pdg))
9508                .unwrap();
9509        }
9510        let repaired = ResolvedProcess::repair_cp_interaction_rules(graph, &model).unwrap();
9511        assert_eq!(
9512            repaired.nodes()[interaction].data,
9513            ColoredNode::Interaction(vertex(&model, "V_117"))
9514        );
9515
9516        let resolved_options = |filter| {
9517            GenerationOptions::default()
9518                .with_graph_filter(filter)
9519                .resolve_selectors(&model)
9520                .unwrap()
9521        };
9522        let allow_original =
9523            resolved_options(GenerationFilter::VertexAllow(vec![VertexSelector::from(
9524                "V_82",
9525            )]));
9526        let veto_repaired =
9527            resolved_options(GenerationFilter::VertexVeto(vec![VertexSelector::from(
9528                "V_117",
9529            )]));
9530        let allow_repaired =
9531            resolved_options(GenerationFilter::VertexAllow(vec![VertexSelector::from(
9532                "V_117",
9533            )]));
9534        let generator = Generator::new(model);
9535
9536        assert!(
9537            !generator
9538                .passes_interaction_filters(&repaired, 0, &allow_original)
9539                .unwrap(),
9540            "a CP repair must not bypass an allow-list"
9541        );
9542        assert!(
9543            !generator
9544                .passes_interaction_filters(&repaired, 0, &veto_repaired)
9545                .unwrap(),
9546            "a CP repair must not bypass a veto-list"
9547        );
9548        assert!(
9549            generator
9550                .passes_interaction_filters(&repaired, 0, &allow_repaired)
9551                .unwrap(),
9552            "the finalized CP rule should pass when explicitly allowed"
9553        );
9554    }
9555
9556    #[test]
9557    fn antiparticle_edges_use_exact_propagator_ufo_slots() {
9558        let source = fermion_model().to_json().unwrap();
9559        let mut definition = serde_json::from_str::<serde_json::Value>(&source).unwrap();
9560        let propagators = definition["propagators"].as_array_mut().unwrap();
9561        propagators
9562            .iter_mut()
9563            .find(|propagator| propagator["name"] == "f_prop")
9564            .unwrap()["numerator"] = serde_json::json!("PSlash(2,1)");
9565        propagators.push(serde_json::json!({
9566            "name": "f~_prop",
9567            "particle": "f~",
9568            "numerator": "-PSlash(1,2)",
9569            "denominator": "P^2"
9570        }));
9571        let model = Model::from_json(&serde_json::to_string(&definition).unwrap()).unwrap();
9572        let generator = Generator::new(model.clone());
9573        let mut graph = Graph::new();
9574        let interaction = graph.add_node(ColoredNode::Interaction(vertex(&model, "V")));
9575        let external = graph.add_node(ColoredNode::External(ExternalNode {
9576            index: 0,
9577            state: ExternalState::Incoming,
9578            particle: particle(&model, 22),
9579        }));
9580        graph
9581            .add_edge(
9582                interaction,
9583                interaction,
9584                true,
9585                EdgeColor {
9586                    particle: particle(&model, -1),
9587                    direction: None,
9588                },
9589            )
9590            .unwrap();
9591        graph
9592            .add_edge(external, interaction, false, edge(&model, 22))
9593            .unwrap();
9594
9595        let diagram = generator
9596            .to_diagram(
9597                "antiparticle-propagator".to_owned(),
9598                GenerationType::Amplitude,
9599                ColoredTopology {
9600                    graph,
9601                    symmetry: 1,
9602                    multiplicity: 1,
9603                    cut_partitions: Vec::new(),
9604                    topology_threshold_candidates: Vec::new(),
9605                    spectator_cuts: Vec::new(),
9606                },
9607                1,
9608                FermionSigns {
9609                    internal_loop_negative: true,
9610                    ..FermionSigns::default()
9611                },
9612                &GenerationOptions::default(),
9613            )
9614            .unwrap();
9615        let (actual_edge, _, actual_data) = diagram
9616            .edges()
9617            .find(|(_, _, edge)| edge.external.is_none())
9618            .unwrap();
9619        let actual = &actual_data.numerator;
9620        let (antiparticle_propagator, antiparticle_fallback) = generator
9621            .propagator_numerator(model.particle_by_id(particle(&model, -1)).unwrap())
9622            .unwrap();
9623        let (particle_propagator, particle_fallback) = generator
9624            .propagator_numerator(model.particle_by_id(particle(&model, 1)).unwrap())
9625            .unwrap();
9626        assert!(!antiparticle_fallback);
9627        assert!(!particle_fallback);
9628        assert_ne!(particle_propagator, antiparticle_propagator);
9629        let instantiate = |propagator: &Atom, flows: [Flow; 2]| {
9630            let legs = flows.map(|flow| NumeratorHalfEdge {
9631                edge: 0,
9632                flow,
9633                hedge: usize::from(flow == Flow::Sink),
9634                spin: 2,
9635                color: 1,
9636            });
9637            NumeratorInstantiation {
9638                owner: NumeratorOwner::Edge(0),
9639                legs: &legs,
9640            }
9641            .instantiate(propagator, NumeratorSector::Spin)
9642            .unwrap()
9643        };
9644        let native = |expression: Atom| {
9645            let source = diagram
9646                .half_edge_id(DiagramHalfEdge {
9647                    edge: actual_edge,
9648                    endpoint: DiagramEndpoint::Source,
9649                })
9650                .unwrap();
9651            let sink = diagram
9652                .half_edge_id(DiagramHalfEdge {
9653                    edge: actual_edge,
9654                    endpoint: DiagramEndpoint::Target,
9655                })
9656                .unwrap();
9657            expression.replace_map_bottom_up(|term, _, output| {
9658                let AtomView::Fun(function) = term else {
9659                    return;
9660                };
9661                let head = function.get_symbol();
9662                let arguments = function.iter().collect::<Vec<_>>();
9663                let owner = usize::try_from(arguments[0]).ok();
9664                let index = if head == feynkit_graph::symbols::hedge_index() {
9665                    match owner {
9666                        Some(0) => Some(source.0),
9667                        Some(1) => Some(sink.0),
9668                        _ => None,
9669                    }
9670                } else if (head == feynkit_graph::symbols::edge_index()
9671                    || head == momentum_symbol())
9672                    && owner == Some(0)
9673                {
9674                    Some(actual_edge.0)
9675                } else {
9676                    None
9677                };
9678                if let Some(index) = index {
9679                    **output = FunctionBuilder::new(head)
9680                        .add_arg(index)
9681                        .add_args(arguments[1..].iter().copied())
9682                        .finish();
9683                }
9684            })
9685        };
9686        let exact = native(instantiate(
9687            &antiparticle_propagator,
9688            [Flow::Source, Flow::Sink],
9689        ));
9690        let blanket_reversal = native(instantiate(
9691            &antiparticle_propagator,
9692            [Flow::Sink, Flow::Source],
9693        ));
9694        let particle_fallback = native(instantiate(
9695            &particle_propagator,
9696            [Flow::Source, Flow::Sink],
9697        ));
9698
9699        let actual = NumeratorInterface::export(actual).0;
9700        assert_eq!(actual, exact);
9701        assert_ne!(actual, blanket_reversal);
9702        assert_ne!(actual, particle_fallback);
9703    }
9704
9705    #[test]
9706    fn implicit_momenta_reverse_only_for_the_conjugate_propagator() {
9707        let source = NumeratorHalfEdge {
9708            edge: 5,
9709            hedge: 10,
9710            flow: Flow::Source,
9711            spin: 2,
9712            color: 1,
9713        };
9714        let sink = NumeratorHalfEdge {
9715            hedge: 11,
9716            flow: Flow::Sink,
9717            ..source
9718        };
9719        let direct = [source, sink];
9720        let conjugate = [sink, source];
9721        let spin = |owner, legs: &[NumeratorHalfEdge], expression: &str| {
9722            NumeratorInstantiation { owner, legs }
9723                .instantiate(&test_atom(expression), NumeratorSector::Spin)
9724                .unwrap()
9725        };
9726        for (forward, reversed) in [
9727            ("P()", "P()"),
9728            ("P(dummy(1))", "P(dummy(1))"),
9729            ("PSlash(1,2)", "PSlash(2,1)"),
9730            ("Slash(P)", "Slash(P)"),
9731        ] {
9732            let edge = NumeratorOwner::Edge(5);
9733            let direct_term = spin(edge, &direct, forward);
9734            assert_ne!(direct_term, Atom::Zero, "{forward}");
9735            assert_eq!(spin(edge, &conjugate, reversed), -direct_term, "{forward}");
9736            let vertex = NumeratorOwner::Vertex(5);
9737            assert_eq!(
9738                spin(vertex, &conjugate, reversed),
9739                spin(vertex, &direct, forward),
9740                "{forward}"
9741            );
9742        }
9743        for owner in [NumeratorOwner::Edge(5), NumeratorOwner::Vertex(5)] {
9744            // Explicit P follows the flow of its specified leg.
9745            let implicit = spin(owner, &direct, "P(dummy(1))");
9746            assert_eq!(spin(owner, &direct, "P(dummy(1),1)"), -implicit.clone());
9747            assert_eq!(spin(owner, &conjugate, "P(dummy(1),1)"), implicit);
9748            // Choosing the same explicit slash momentum slot keeps its existing sign.
9749            assert_eq!(
9750                spin(owner, &direct, "PSlash(1,2,1)"),
9751                spin(owner, &conjugate, "PSlash(2,1,2)")
9752            );
9753        }
9754    }
9755
9756    #[test]
9757    fn antiparticle_propagator_falls_back_to_particle_definition() {
9758        let source = fermion_model().to_json().unwrap();
9759        let mut definition = serde_json::from_str::<serde_json::Value>(&source).unwrap();
9760        definition["propagators"]
9761            .as_array_mut()
9762            .unwrap()
9763            .iter_mut()
9764            .find(|propagator| propagator["name"] == "f_prop")
9765            .unwrap()["numerator"] = serde_json::json!("PSlash(2,1)");
9766        let model = Model::from_json(&serde_json::to_string(&definition).unwrap()).unwrap();
9767        let generator = Generator::new(model.clone());
9768
9769        let (antiparticle_numerator, antiparticle_fallback) = generator
9770            .propagator_numerator(model.particle_by_id(particle(&model, -1)).unwrap())
9771            .unwrap();
9772        let (particle_numerator, particle_fallback) = generator
9773            .propagator_numerator(model.particle_by_id(particle(&model, 1)).unwrap())
9774            .unwrap();
9775        assert_eq!(antiparticle_numerator, particle_numerator);
9776        assert!(antiparticle_fallback);
9777        assert!(!particle_fallback);
9778    }
9779
9780    #[test]
9781    fn conjugate_propagator_fallback_matches_explicit_standard_model_propagators() {
9782        let full = standard_model();
9783        let full_generator = Generator::new(full.clone());
9784        let definition = serde_json::to_value(&full).unwrap();
9785        let mut checked = Vec::new();
9786        for propagator in definition["propagators"].as_array().unwrap() {
9787            let name = propagator["name"].as_str().unwrap();
9788            let particle_id = full
9789                .particle_id(propagator["particle"].as_str().unwrap())
9790                .unwrap();
9791            let particle = full.particle_by_id(particle_id).unwrap();
9792            if full.antiparticle(particle).unwrap().name == particle.name {
9793                continue;
9794            }
9795            let mut stripped = definition.clone();
9796            stripped["propagators"]
9797                .as_array_mut()
9798                .unwrap()
9799                .retain(|candidate| candidate["name"] != name);
9800            // Quartet validation requires each member's own propagator, and
9801            // the quartets play no part in a propagator numerator.
9802            stripped["covariant_cut_multiplets"] = json!({});
9803            let stripped = Model::from_json(&stripped.to_string()).unwrap();
9804            let stripped_generator = Generator::new(stripped.clone());
9805            let (_, fallback) = stripped_generator
9806                .propagator_numerator(stripped.particle_by_id(particle_id).unwrap())
9807                .unwrap();
9808            assert!(fallback, "{name} must fall back to its conjugate");
9809            for (edge, hedges) in [(3, [6, 7]), (4, [9, 8])] {
9810                let expected = full_generator
9811                    .edge_numerator(particle_id, edge, hedges)
9812                    .unwrap();
9813                let actual = stripped_generator
9814                    .edge_numerator(particle_id, edge, hedges)
9815                    .unwrap();
9816                assert_eq!(
9817                    actual.expression(),
9818                    expected.expression(),
9819                    "the conjugate fallback for {name} differs from its explicit propagator"
9820                );
9821            }
9822            checked.push(name.to_owned());
9823        }
9824        for name in [
9825            "t_propFeynman",
9826            "t~_propFeynman",
9827            "ve~_propFeynman",
9828            "W-_propFeynman",
9829            "ghG~_propFeynman",
9830        ] {
9831            assert!(checked.iter().any(|checked| checked == name), "{name}");
9832        }
9833    }
9834
9835    #[test]
9836    fn vertex_orders_take_each_order_maximum_and_graph_orders_sum_vertices() {
9837        let model = fermion_model();
9838        let rule_orders = model.vertex_rule("V").unwrap().coupling_orders(&model);
9839        assert_eq!(
9840            rule_orders,
9841            BTreeMap::from([("QCD".to_owned(), 2), ("QED".to_owned(), 3)])
9842        );
9843
9844        let generator = Generator::new(model);
9845        let mut graph = Graph::new();
9846        graph.add_node(ColoredNode::Interaction(vertex(&generator.model, "V")));
9847        graph.add_node(ColoredNode::Interaction(vertex(&generator.model, "V")));
9848        assert_eq!(
9849            generator.coupling_orders(&graph).unwrap(),
9850            BTreeMap::from([("QCD".to_owned(), 4), ("QED".to_owned(), 6)])
9851        );
9852    }
9853
9854    #[test]
9855    fn interaction_numerator_keeps_named_couplings_and_lowers_tensors() {
9856        let mut definition = serde_json::to_value(fermion_model()).unwrap();
9857        for particle in definition["particles"].as_array_mut().unwrap() {
9858            particle["color"] = serde_json::json!(match particle["name"].as_str() {
9859                Some("f") => 3,
9860                Some("f~") => -3,
9861                Some("a") => 8,
9862                _ => 1,
9863            });
9864        }
9865        // Both couplings multiply the same open color interface. A scalar
9866        // color term cannot be added to a fundamental-adjoint tensor term.
9867        definition["vertex_rules"][0]["color_structures"] =
9868            serde_json::json!(["T(3,2,1)", "T(3,2,1)"]);
9869        let model = Model::from_json(&definition.to_string()).unwrap();
9870        let generator = Generator::new(model.clone());
9871        let legs = tensor_test_legs();
9872        let instantiation = NumeratorInstantiation {
9873            owner: NumeratorOwner::Vertex(7),
9874            legs: &legs[..3],
9875        };
9876        let numerator = generator
9877            .interaction_numerator(model.vertex_rule_id("V").unwrap(), &instantiation)
9878            .unwrap();
9879
9880        let numerator = NumeratorInterface::export(&numerator).0.to_plain_string();
9881        assert!(numerator.contains("UFO::GC_LOW"));
9882        assert!(numerator.contains("UFO::GC_HIGH"));
9883        assert!(!numerator.contains("g_low"));
9884        assert!(!numerator.contains("g_high"));
9885        assert!(numerator.contains("spenso::gamma"));
9886        assert!(numerator.contains("spenso::t"));
9887        assert!(!numerator.contains("Gamma("));
9888        assert!(!numerator.contains("UFO::T("));
9889    }
9890
9891    #[test]
9892    fn interaction_numerator_rejects_incompatible_color_summands() {
9893        let mut definition = serde_json::to_value(fermion_model()).unwrap();
9894        definition["vertex_rules"][0]["color_structures"] = json!(["1", "T(3,2,1)"]);
9895        let model = Model::from_json(&definition.to_string()).unwrap();
9896        let generator = Generator::new(model.clone());
9897        let legs = tensor_test_legs();
9898        let instantiation = NumeratorInstantiation {
9899            owner: NumeratorOwner::Vertex(7),
9900            legs: &legs[..3],
9901        };
9902        let error = generator
9903            .interaction_numerator(model.vertex_rule_id("V").unwrap(), &instantiation)
9904            .unwrap_err();
9905
9906        assert!(matches!(
9907            &error,
9908            GenerationError::Diagram(DiagramError::Tensor(_))
9909        ));
9910        assert!(
9911            error
9912                .to_string()
9913                .contains("tensor summands do not have compatible tensor interfaces")
9914        );
9915        assert!(generator.numerators.interactions.read().unwrap().is_empty());
9916        assert!(
9917            generator
9918                .numerators
9919                .interaction_templates
9920                .read()
9921                .unwrap()
9922                .is_empty()
9923        );
9924    }
9925
9926    #[test]
9927    fn interaction_templates_reuse_admission_and_localize_shifted_bound_indices() {
9928        let mut definition = serde_json::to_value(scalar_model()).unwrap();
9929        definition["lorentz_structures"][0]["structure"] =
9930            json!("Metric(idx(2,1),dummy(1))*P(dummy(1),2)");
9931        let model = Model::from_json(&definition.to_string()).unwrap();
9932        let rule = model.vertex_rule_id("V1").unwrap();
9933        let generator = Generator::new(model);
9934        let mut legs = tensor_test_legs()[..3].to_vec();
9935        let mut previous = None;
9936        for owner in [7, 12] {
9937            for leg in &mut legs {
9938                leg.edge += 13;
9939                leg.hedge += 19;
9940                leg.color = 1;
9941            }
9942            let instantiation = NumeratorInstantiation {
9943                owner: NumeratorOwner::Vertex(owner),
9944                legs: &legs,
9945            };
9946            let actual = generator
9947                .interaction_numerator(rule, &instantiation)
9948                .unwrap();
9949            let expected = NumeratorInterface::admit(
9950                generator
9951                    .interaction_expression(rule, &instantiation)
9952                    .unwrap(),
9953                None,
9954            )
9955            .unwrap();
9956            assert!(actual.same_value(&expected));
9957            assert_eq!(actual.rank(), 1);
9958            assert_eq!(
9959                actual.structure().logical_slots()[0].aind,
9960                PartialIndex::Explicit(AbstractIndex::Named(
9961                    symbols::hedge_index().into(),
9962                    legs[0].hedge,
9963                    2,
9964                ))
9965            );
9966            let templates = generator.numerators.interaction_templates.read().unwrap();
9967            assert_eq!(templates.len(), 1);
9968            let template = templates.values().next().unwrap().clone();
9969            if let Some(previous) = previous {
9970                assert!(Arc::ptr_eq(&previous, &template));
9971            }
9972            previous = Some(template);
9973        }
9974        assert_eq!(generator.numerators.interactions.read().unwrap().len(), 2);
9975    }
9976
9977    #[test]
9978    fn interaction_template_cache_retains_dummy_metadata_across_owners() {
9979        let mut definition = serde_json::to_value(scalar_model()).unwrap();
9980        definition["lorentz_structures"][0]["structure"] = json!("P(dummy(1),1)*P(dummy(1),2)");
9981        let model = Model::from_json(&definition.to_string()).unwrap();
9982        let rule = model.vertex_rule_id("V1").unwrap();
9983        let generator = Generator::new(model);
9984        let mut legs = tensor_test_legs()[..3].to_vec();
9985        for leg in &mut legs {
9986            leg.color = 1;
9987        }
9988        let head = tensor_symbol!("generation_template_cache_probe");
9989        let mut numerators = Vec::new();
9990        for owner in [7, 12] {
9991            let instantiation = NumeratorInstantiation {
9992                owner: NumeratorOwner::Vertex(owner),
9993                legs: &legs,
9994            };
9995            let numerator = generator
9996                .interaction_numerator(rule, &instantiation)
9997                .unwrap();
9998            let index = AbstractIndex::Named(symbols::vertex_index().into(), owner, 1);
9999            let probe = SymbolicTensor::infer(
10000                FunctionBuilder::new(head)
10001                    .add_arg(Minkowski {}.new_rep(4).to_symbolic([index.to_atom()]))
10002                    .finish(),
10003            )
10004            .unwrap();
10005            assert!(matches!(
10006                numerator.multiply(&probe),
10007                Err(TensorCompositionError::InvalidExplicitMultiplicity {
10008                    index: collision,
10009                    occurrences: 3,
10010                }) if collision == index
10011            ));
10012            // Consuming a returned clone must not establish metadata which the
10013            // retained cache entry lacks and would have to rediscover later.
10014            let cached = generator
10015                .interaction_numerator(rule, &instantiation)
10016                .unwrap();
10017            assert!(numerator.same_reduction_state(&cached));
10018            assert!(matches!(
10019                cached.multiply(&probe),
10020                Err(TensorCompositionError::InvalidExplicitMultiplicity { occurrences: 3, .. })
10021            ));
10022            numerators.push(cached);
10023        }
10024        assert!(numerators[0].multiply(&numerators[1]).is_ok());
10025        assert!(numerators[0].multiply(&numerators[0]).is_err());
10026        assert_eq!(
10027            generator
10028                .numerators
10029                .interaction_templates
10030                .read()
10031                .unwrap()
10032                .len(),
10033            1
10034        );
10035    }
10036
10037    #[test]
10038    fn cancelled_alias_templates_keep_hidden_dummy_labels_and_cached_metadata() {
10039        let mut definition = serde_json::to_value(scalar_model()).unwrap();
10040        definition["lorentz_structures"][0]["structure"] =
10041            json!("Metric(idx(2,3),dummy(1))*(P(dummy(1),1)+P(dummy(1),2))");
10042        let model = Model::from_json(&definition.to_string()).unwrap();
10043        let rule = model.vertex_rule_id("V1").unwrap();
10044        let generator = Generator::new(model);
10045        let mut legs = tensor_test_legs()[..3].to_vec();
10046        for leg in &mut legs {
10047            leg.color = 1;
10048        }
10049        legs[1].edge = legs[0].edge;
10050        let head = tensor_symbol!("generation_cancelled_template_probe");
10051        for owner in [4, 9] {
10052            let instantiation = NumeratorInstantiation {
10053                owner: NumeratorOwner::Vertex(owner),
10054                legs: &legs,
10055            };
10056            let zero = generator
10057                .interaction_numerator(rule, &instantiation)
10058                .unwrap();
10059            let cached = generator
10060                .interaction_numerator(rule, &instantiation)
10061                .unwrap();
10062            assert!(zero.is_zero());
10063            assert_eq!(zero.rank(), 1);
10064            assert!(zero.same_reduction_state(&cached));
10065            let index = AbstractIndex::Named(symbols::vertex_index().into(), owner, 1);
10066            let probe = |index: AbstractIndex| {
10067                SymbolicTensor::infer(
10068                    FunctionBuilder::new(head)
10069                        .add_arg(Minkowski {}.new_rep(4).to_symbolic([index.to_atom()]))
10070                        .finish(),
10071                )
10072                .unwrap()
10073            };
10074            for numerator in [zero, cached] {
10075                assert!(matches!(
10076                    numerator.multiply(&probe(index)),
10077                    Err(TensorCompositionError::InvalidExplicitMultiplicity {
10078                        index: collision,
10079                        occurrences: 3,
10080                    }) if collision == index
10081                ));
10082                let other = AbstractIndex::Named(symbols::vertex_index().into(), owner + 1, 1);
10083                let product = numerator.multiply(&probe(other)).unwrap();
10084                assert!(product.is_zero());
10085                assert_eq!(product.rank(), 2);
10086            }
10087        }
10088        let templates = generator.numerators.interaction_templates.read().unwrap();
10089        assert_eq!(templates.len(), 2);
10090        let dummy = AbstractIndex::Named(symbols::vertex_index().into(), 0, 1);
10091        for template in templates.values() {
10092            let NumeratorTemplate::Admitted { labels, .. } = &**template else {
10093                panic!("explicit rule must retain its admitted template");
10094            };
10095            assert!(labels.iter().any(|(index, _)| *index == dummy));
10096        }
10097    }
10098
10099    #[test]
10100    fn interaction_templates_preserve_rank_when_incident_momenta_cancel() {
10101        let mut definition = serde_json::to_value(scalar_model()).unwrap();
10102        definition["lorentz_structures"][0]["structure"] = json!("P(idx(2,1),1)+P(idx(2,1),2)");
10103        let model = Model::from_json(&definition.to_string()).unwrap();
10104        let rule = model.vertex_rule_id("V1").unwrap();
10105        let generator = Generator::new(model);
10106        let mut legs = tensor_test_legs()[..3].to_vec();
10107        for leg in &mut legs {
10108            leg.color = 1;
10109        }
10110        legs[1].edge = legs[0].edge;
10111        for owner in [4, 9] {
10112            let instantiation = NumeratorInstantiation {
10113                owner: NumeratorOwner::Vertex(owner),
10114                legs: &legs,
10115            };
10116            let zero = generator
10117                .interaction_numerator(rule, &instantiation)
10118                .unwrap();
10119            assert!(zero.is_zero());
10120            assert_eq!(zero.rank(), 1);
10121            assert_eq!(
10122                zero.structure().logical_slots()[0].aind,
10123                PartialIndex::Explicit(AbstractIndex::Named(
10124                    symbols::hedge_index().into(),
10125                    legs[0].hedge,
10126                    2,
10127                ))
10128            );
10129            legs[0].edge += 6;
10130            legs[1].edge = legs[0].edge;
10131            for leg in &mut legs {
10132                leg.hedge += 7;
10133            }
10134        }
10135        assert_eq!(
10136            generator
10137                .numerators
10138                .interaction_templates
10139                .read()
10140                .unwrap()
10141                .len(),
10142            2
10143        );
10144    }
10145
10146    #[test]
10147    fn propagator_templates_reuse_reversed_spin_and_color_interfaces() {
10148        let mut definition = serde_json::to_value(fermion_model()).unwrap();
10149        for particle in definition["particles"].as_array_mut().unwrap() {
10150            particle["color"] = json!(match particle["name"].as_str() {
10151                Some("f") => 3,
10152                Some("f~") => -3,
10153                _ => 1,
10154            });
10155        }
10156        let model = Model::from_json(&definition.to_string()).unwrap();
10157        let generator = Generator::new(model.clone());
10158        for pdg in [1, -1] {
10159            let particle_id = particle(&model, pdg);
10160            let particle = model.particle_by_id(particle_id).unwrap();
10161            let (propagator, reversed) = generator.propagator_numerator(particle).unwrap();
10162            for (edge, hedges) in [(5, [11, 17]), (8, [27, 21])] {
10163                let actual = generator.edge_numerator(particle_id, edge, hedges).unwrap();
10164                let flows = if reversed {
10165                    [Flow::Sink, Flow::Source]
10166                } else {
10167                    [Flow::Source, Flow::Sink]
10168                };
10169                let legs = flows.map(|flow| NumeratorHalfEdge {
10170                    edge,
10171                    hedge: hedges[usize::from(flow == Flow::Sink)],
10172                    flow,
10173                    spin: particle.spin,
10174                    color: particle.color,
10175                });
10176                let instantiation = NumeratorInstantiation {
10177                    owner: NumeratorOwner::Edge(edge),
10178                    legs: &legs,
10179                };
10180                let expected = NumeratorInterface::admit(
10181                    instantiation
10182                        .propagator_expression(&propagator, particle.color)
10183                        .unwrap(),
10184                    None,
10185                )
10186                .unwrap()
10187                .canonicalize_named_interface();
10188                assert_eq!(actual.expression(), expected.expression());
10189                assert_eq!(
10190                    actual.structure().logical_slots(),
10191                    expected.structure().logical_slots(),
10192                );
10193            }
10194        }
10195        assert_eq!(
10196            generator
10197                .numerators
10198                .propagator_templates
10199                .read()
10200                .unwrap()
10201                .len(),
10202            2
10203        );
10204    }
10205
10206    #[test]
10207    fn interaction_templates_use_canonical_named_interfaces_and_actual_owner_values() {
10208        for expression in [
10209            "Metric(1,2)",
10210            "P(idx(1,1),1)*P(idx(1,2),2)",
10211            "Metric(1,2)*(P(3,1)-P(3,2))",
10212        ] {
10213            let mut definition = serde_json::to_value(scalar_model()).unwrap();
10214            definition["lorentz_structures"][0]["structure"] = json!(expression);
10215            let model = Model::from_json(&definition.to_string()).unwrap();
10216            let rule = model.vertex_rule_id("V1").unwrap();
10217            let generator = Generator::new(model);
10218            for (owner, permutation) in [[0, 1, 2], [1, 0, 2], [2, 0, 1], [2, 1, 0]]
10219                .into_iter()
10220                .enumerate()
10221            {
10222                let legs = permutation.map(|index| NumeratorHalfEdge {
10223                    edge: [17, 3, 23][index],
10224                    hedge: [41, 11, 29][index],
10225                    flow: Flow::Sink,
10226                    spin: 1,
10227                    color: 1,
10228                });
10229                let instantiation = NumeratorInstantiation {
10230                    owner: NumeratorOwner::Vertex(owner),
10231                    legs: &legs,
10232                };
10233                let actual = generator
10234                    .interaction_numerator(rule, &instantiation)
10235                    .unwrap();
10236                let expected = NumeratorInterface::admit(
10237                    generator
10238                        .interaction_expression(rule, &instantiation)
10239                        .unwrap(),
10240                    None,
10241                )
10242                .unwrap()
10243                .canonicalize_named_interface();
10244                assert_eq!(
10245                    actual.expression().as_view().get_data(),
10246                    expected.expression().as_view().get_data(),
10247                    "{expression}: {permutation:?}"
10248                );
10249                assert_eq!(actual.presentation_atom(), *actual.expression());
10250                assert_eq!(
10251                    actual.structure().logical_slots(),
10252                    expected.structure().logical_slots(),
10253                    "{expression}: {permutation:?}"
10254                );
10255            }
10256            let templates = generator.numerators.interaction_templates.read().unwrap();
10257            assert_eq!(templates.len(), 1);
10258            assert!(matches!(
10259                &**templates.values().next().unwrap(),
10260                NumeratorTemplate::Admitted { .. }
10261            ));
10262        }
10263    }
10264
10265    #[test]
10266    fn propagator_templates_use_canonical_named_interfaces_and_actual_owner_values() {
10267        for expression in ["Metric(1,2)", "P(idx(1,1))*P(idx(1,2))"] {
10268            let mut definition = serde_json::to_value(scalar_model()).unwrap();
10269            definition["propagators"][0]["numerator"] = json!(expression);
10270            let model = Model::from_json(&definition.to_string()).unwrap();
10271            let particle_id = particle(&model, 25);
10272            let generator = Generator::new(model);
10273            let particle = generator.model.particle_by_id(particle_id).unwrap();
10274            let (propagator, reversed) = generator.propagator_numerator(particle).unwrap();
10275            assert!(!reversed);
10276            for (edge, hedges) in [(5, [11, 17]), (8, [27, 21])] {
10277                let actual = generator.edge_numerator(particle_id, edge, hedges).unwrap();
10278                let legs = [Flow::Source, Flow::Sink].map(|flow| NumeratorHalfEdge {
10279                    edge,
10280                    hedge: hedges[usize::from(flow == Flow::Sink)],
10281                    flow,
10282                    spin: particle.spin,
10283                    color: particle.color,
10284                });
10285                let instantiation = NumeratorInstantiation {
10286                    owner: NumeratorOwner::Edge(edge),
10287                    legs: &legs,
10288                };
10289                let expected = NumeratorInterface::admit(
10290                    instantiation
10291                        .propagator_expression(&propagator, particle.color)
10292                        .unwrap(),
10293                    None,
10294                )
10295                .unwrap()
10296                .canonicalize_named_interface();
10297                assert_eq!(
10298                    actual.expression().as_view().get_data(),
10299                    expected.expression().as_view().get_data(),
10300                    "{expression}: {hedges:?}"
10301                );
10302                assert_eq!(actual.presentation_atom(), *actual.expression());
10303                assert_eq!(
10304                    actual.structure().logical_slots(),
10305                    expected.structure().logical_slots(),
10306                    "{expression}: {hedges:?}"
10307                );
10308            }
10309            let templates = generator.numerators.propagator_templates.read().unwrap();
10310            assert_eq!(templates.len(), 1);
10311            assert!(matches!(
10312                &**templates.values().next().unwrap(),
10313                NumeratorTemplate::Admitted { .. }
10314            ));
10315        }
10316    }
10317
10318    #[test]
10319    fn interaction_scoped_pairs_preserve_leaf_arguments_with_canonical_free_interfaces() {
10320        let _ = tensor_symbol!("UFO::generation_scoped_order_tensor");
10321        let _ = Minkowski {}.new_rep(4).to_symbolic([]);
10322        for scalar in [
10323            "(P(1,1)*P(1,2)+P(1,2)*P(1,3))",
10324            "spenso::bracket(P(1,1),P(1,2))^2",
10325        ] {
10326            let expression = format!(
10327                "{scalar}*generation_scoped_order_tensor(spenso::mink(4,idx(1,2)),spenso::mink(4,idx(1,1)))"
10328            );
10329            let mut definition = serde_json::to_value(scalar_model()).unwrap();
10330            definition["lorentz_structures"][0]["structure"] = json!(expression);
10331            let model = Model::from_json(&definition.to_string()).unwrap();
10332            let rule = model.vertex_rule_id("V1").unwrap();
10333            let generator = Generator::new(model);
10334            for hedges in [[0, 1, 2], [27, 11, 19]] {
10335                let legs = array::from_fn::<_, 3, _>(|index| NumeratorHalfEdge {
10336                    edge: index + 3,
10337                    hedge: hedges[index],
10338                    flow: Flow::Sink,
10339                    spin: 1,
10340                    color: 1,
10341                });
10342                let instantiation = NumeratorInstantiation {
10343                    owner: NumeratorOwner::Vertex(7),
10344                    legs: &legs,
10345                };
10346                let expected = NumeratorInterface::admit(
10347                    generator
10348                        .interaction_expression(rule, &instantiation)
10349                        .unwrap(),
10350                    None,
10351                )
10352                .unwrap();
10353                let actual = generator
10354                    .interaction_numerator(rule, &instantiation)
10355                    .unwrap();
10356                let expected_indices = expected
10357                    .structure()
10358                    .logical_slots()
10359                    .into_iter()
10360                    .map(|slot| slot.aind)
10361                    .collect::<Vec<_>>();
10362                assert_eq!(
10363                    expected_indices,
10364                    [hedges[0].min(hedges[1]), hedges[0].max(hedges[1])].map(|hedge| {
10365                        PartialIndex::Explicit(AbstractIndex::Named(
10366                            symbols::hedge_index().into(),
10367                            hedge,
10368                            1,
10369                        ))
10370                    })
10371                );
10372                // Composite axes are canonical; exact payload comparisons
10373                // below retain the authored leaf argument order.
10374                let expected = expected.canonicalize_named_interface();
10375                assert_eq!(
10376                    actual.expression().as_view().get_data(),
10377                    expected.expression().as_view().get_data(),
10378                    "{scalar}"
10379                );
10380                assert_eq!(actual.presentation_atom(), *actual.expression());
10381                assert_eq!(
10382                    actual.structure().logical_slots(),
10383                    expected.structure().logical_slots(),
10384                    "{scalar}"
10385                );
10386            }
10387            let templates = generator.numerators.interaction_templates.read().unwrap();
10388            assert_eq!(templates.len(), 1);
10389            assert!(matches!(
10390                &**templates.values().next().unwrap(),
10391                NumeratorTemplate::Dynamic
10392            ));
10393        }
10394    }
10395
10396    #[test]
10397    fn propagator_scoped_pairs_preserve_leaf_arguments_with_canonical_free_interfaces() {
10398        let _ = tensor_symbol!("UFO::generation_scoped_prop_tensor");
10399        let _ = Minkowski {}.new_rep(4).to_symbolic([]);
10400        for scalar in ["(P(1,1)*P(1,2)+1)", "spenso::bracket(P(1,1),P(1,2))^2"] {
10401            let expression = format!(
10402                "{scalar}*generation_scoped_prop_tensor(spenso::mink(4,idx(1,2)),spenso::mink(4,idx(1,1)))"
10403            );
10404            let mut definition = serde_json::to_value(scalar_model()).unwrap();
10405            definition["propagators"][0]["numerator"] = json!(expression);
10406            let model = Model::from_json(&definition.to_string()).unwrap();
10407            let particle_id = particle(&model, 25);
10408            let generator = Generator::new(model);
10409            let particle = generator.model.particle_by_id(particle_id).unwrap();
10410            let (propagator, reversed) = generator.propagator_numerator(particle).unwrap();
10411            assert!(!reversed);
10412            for (edge, hedges) in [(3, [0, 1]), (5, [27, 11])] {
10413                let legs = [Flow::Source, Flow::Sink].map(|flow| NumeratorHalfEdge {
10414                    edge,
10415                    hedge: hedges[usize::from(flow == Flow::Sink)],
10416                    flow,
10417                    spin: particle.spin,
10418                    color: particle.color,
10419                });
10420                let instantiation = NumeratorInstantiation {
10421                    owner: NumeratorOwner::Edge(edge),
10422                    legs: &legs,
10423                };
10424                let expected = NumeratorInterface::admit(
10425                    instantiation
10426                        .propagator_expression(&propagator, particle.color)
10427                        .unwrap(),
10428                    None,
10429                )
10430                .unwrap();
10431                let actual = generator.edge_numerator(particle_id, edge, hedges).unwrap();
10432                let expected_indices = expected
10433                    .structure()
10434                    .logical_slots()
10435                    .into_iter()
10436                    .map(|slot| slot.aind)
10437                    .collect::<Vec<_>>();
10438                assert_eq!(
10439                    expected_indices,
10440                    [hedges[0].min(hedges[1]), hedges[0].max(hedges[1])].map(|hedge| {
10441                        PartialIndex::Explicit(AbstractIndex::Named(
10442                            symbols::hedge_index().into(),
10443                            hedge,
10444                            1,
10445                        ))
10446                    })
10447                );
10448                let expected = expected.canonicalize_named_interface();
10449                assert_eq!(
10450                    actual.expression().as_view().get_data(),
10451                    expected.expression().as_view().get_data(),
10452                    "{scalar}"
10453                );
10454                assert_eq!(actual.presentation_atom(), *actual.expression());
10455                assert_eq!(
10456                    actual.structure().logical_slots(),
10457                    expected.structure().logical_slots(),
10458                    "{scalar}"
10459                );
10460            }
10461            let templates = generator.numerators.propagator_templates.read().unwrap();
10462            assert_eq!(templates.len(), 1);
10463            assert!(matches!(
10464                &**templates.values().next().unwrap(),
10465                NumeratorTemplate::Dynamic
10466            ));
10467        }
10468    }
10469
10470    #[test]
10471    fn callback_rules_are_constructed_in_the_actual_owner_frame() {
10472        let callback = symbol!(
10473            "UFO::generation_owner_callback",
10474            norm = |node, out| {
10475                if let AtomView::Fun(function) = node
10476                    && let Some(AtomView::Fun(index)) = function.iter().next()
10477                    && index.get_symbol() == symbols::hedge_index()
10478                {
10479                    **out = index.iter().next().expect("owner ID").to_owned();
10480                }
10481            }
10482        );
10483        let mut definition = serde_json::to_value(scalar_model()).unwrap();
10484        definition["lorentz_structures"][0]["structure"] =
10485            json!("generation_owner_callback(idx(1,1))");
10486        let model = Model::from_json(&definition.to_string()).unwrap();
10487        let rule = model.vertex_rule_id("V1").unwrap();
10488        let generator = Generator::new(model);
10489        let mut legs = tensor_test_legs()[..3].to_vec();
10490        for owner in [3, 6] {
10491            let instantiation = NumeratorInstantiation {
10492                owner: NumeratorOwner::Vertex(owner),
10493                legs: &legs,
10494            };
10495            let actual = generator
10496                .interaction_numerator(rule, &instantiation)
10497                .unwrap();
10498            assert_eq!(
10499                actual.expression(),
10500                &(Atom::num(legs[0].hedge) * Atom::var(symbol!("UFO::GC1")))
10501            );
10502            assert_eq!(function_count(actual.expression(), callback), 0);
10503            legs[0].hedge += 5;
10504        }
10505        assert!(
10506            generator
10507                .numerators
10508                .interaction_templates
10509                .read()
10510                .unwrap()
10511                .values()
10512                .all(|template| matches!(&**template, NumeratorTemplate::Dynamic))
10513        );
10514    }
10515
10516    #[test]
10517    fn compact_rule_powers_allocate_independent_dummies_for_each_owner() {
10518        let _ = Minkowski {}.new_rep(4).to_symbolic([]);
10519        let _ = tensor_symbol!("UFO::generation_template_auto_tensor");
10520        for expression in [
10521            "generation_template_auto_tensor(spenso::mink(4))^2",
10522            "P(spenso::mink(4))^4",
10523        ] {
10524            let mut definition = serde_json::to_value(scalar_model()).unwrap();
10525            definition["lorentz_structures"][0]["structure"] = json!(expression);
10526            let model = Model::from_json(&definition.to_string()).unwrap();
10527            let rule = model.vertex_rule_id("V1").unwrap();
10528            let generator = Generator::new(model);
10529            let mut legs = tensor_test_legs()[..3].to_vec();
10530            let mut numerators = Vec::new();
10531            let mut owner_indices = Vec::new();
10532            for owner in [7, 12] {
10533                let instantiation = NumeratorInstantiation {
10534                    owner: NumeratorOwner::Vertex(owner),
10535                    legs: &legs,
10536                };
10537                let numerator = generator
10538                    .interaction_numerator(rule, &instantiation)
10539                    .unwrap();
10540                assert_eq!(numerator.rank(), 0);
10541                assert!(
10542                    numerator.same_value(
10543                        &generator
10544                            .interaction_numerator(rule, &instantiation)
10545                            .unwrap(),
10546                    )
10547                );
10548                let mut slots = SlotMatcher::default();
10549                let mut indices = HashSet::new();
10550                numerator.expression().visitor(&mut |node| {
10551                    if let SlotMatch::Explicit(slot) = slots.classify(node) {
10552                        indices.insert(AbstractIndex::try_from(slot.index()).unwrap());
10553                    }
10554                    true
10555                });
10556                assert!(
10557                    !indices.is_empty(),
10558                    "{expression} must materialize a dummy pair"
10559                );
10560                owner_indices.push(indices);
10561                numerators.push(numerator);
10562                for leg in &mut legs {
10563                    leg.edge += 13;
10564                    leg.hedge += 19;
10565                }
10566            }
10567            assert!(
10568                owner_indices[0].is_disjoint(&owner_indices[1]),
10569                "{expression}"
10570            );
10571            let product = numerators[0].multiply(&numerators[1]).unwrap();
10572            assert_eq!(product.rank(), 0);
10573            SymbolicTensor::validate_interface(product.expression(), product.structure()).unwrap();
10574            assert!(
10575                generator
10576                    .numerators
10577                    .interaction_templates
10578                    .read()
10579                    .unwrap()
10580                    .values()
10581                    .all(|template| matches!(&**template, NumeratorTemplate::Dynamic))
10582            );
10583        }
10584    }
10585
10586    #[test]
10587    fn template_eligibility_rejects_scoped_and_encoded_open_indices() {
10588        let scope = symbol!("generation_template_open_scope");
10589        let open = AbstractIndex::Open { owner: 3, axis: 0 };
10590        let scoped = open.scoped(scope).to_atom();
10591        let encoded = CookSettings::reversible()
10592            .cook_function(scoped.as_fun_view().unwrap())
10593            .unwrap();
10594        let head = tensor_symbol!("generation_template_open_tensor");
10595        for index in [open.to_atom(), scoped, encoded] {
10596            let expression = FunctionBuilder::new(head)
10597                .add_arg(Minkowski {}.new_rep(4).to_symbolic([index]))
10598                .finish();
10599            assert!(!NumeratorTemplate::supports(&expression));
10600        }
10601    }
10602
10603    #[test]
10604    fn bundled_rule_ports_preserve_actual_owner_rejection() {
10605        let head = tensor_symbol!("UFO::generation_template_bundle_tensor");
10606        let slot = Minkowski {}.new_rep(4).to_symbolic([test_atom("idx(1,1)")]);
10607        let expression = head.call((AIND_SYMBOLS.aind.call((slot,)),));
10608        let mut definition = serde_json::to_value(scalar_model()).unwrap();
10609        definition["lorentz_structures"][0]["structure"] = json!(expression.to_canonical_string());
10610        let model = Model::from_json(&definition.to_string()).unwrap();
10611        let rule = model.vertex_rule_id("V1").unwrap();
10612        let generator = Generator::new(model);
10613        let legs = tensor_test_legs();
10614        let instantiation = NumeratorInstantiation {
10615            owner: NumeratorOwner::Vertex(7),
10616            legs: &legs[..3],
10617        };
10618        let expected = NumeratorInterface::admit(
10619            generator
10620                .interaction_expression(rule, &instantiation)
10621                .unwrap(),
10622            None,
10623        )
10624        .unwrap_err();
10625        let actual = generator
10626            .interaction_numerator(rule, &instantiation)
10627            .unwrap_err();
10628        // Spenso's structural parser can read bundles, but typed admission
10629        // rejects the untagged aind head. Template selection must preserve
10630        // that actual-owner rejection rather than publish a trusted carrier.
10631        assert!(matches!(
10632            &expected,
10633            DiagramError::Tensor(TensorInferenceError::Invalid(message))
10634                if message.contains("carries structural ports but is not tagged as a tensor")
10635        ));
10636        let GenerationError::Diagram(actual) = actual else {
10637            panic!("expected the existing typed-admission rejection");
10638        };
10639        assert_eq!(actual.to_string(), expected.to_string());
10640        assert!(generator.numerators.interactions.read().unwrap().is_empty());
10641        let templates = generator.numerators.interaction_templates.read().unwrap();
10642        assert_eq!(templates.len(), 1);
10643        assert!(
10644            templates
10645                .values()
10646                .all(|template| matches!(&**template, NumeratorTemplate::Dynamic))
10647        );
10648    }
10649
10650    #[test]
10651    fn opaque_scalar_metadata_with_nonindex_slot_payload_keeps_checked_construction() {
10652        let _ = symbol!("UFO::generation_opaque_metadata"; Scalar);
10653        let _ = Minkowski {}.new_rep(4).to_symbolic([]);
10654        let mut definition = serde_json::to_value(scalar_model()).unwrap();
10655        definition["lorentz_structures"][0]["structure"] =
10656            json!("generation_opaque_metadata(spenso::mink(4,x+y))");
10657        let model = Model::from_json(&definition.to_string()).unwrap();
10658        let rule = model.vertex_rule_id("V1").unwrap();
10659        let generator = Generator::new(model);
10660        let legs = tensor_test_legs();
10661        for owner in [3, 6] {
10662            let instantiation = NumeratorInstantiation {
10663                owner: NumeratorOwner::Vertex(owner),
10664                legs: &legs[..3],
10665            };
10666            let expected = NumeratorInterface::admit(
10667                generator
10668                    .interaction_expression(rule, &instantiation)
10669                    .unwrap(),
10670                None,
10671            )
10672            .unwrap();
10673            let actual = generator
10674                .interaction_numerator(rule, &instantiation)
10675                .unwrap();
10676            assert!(actual.same_value(&expected));
10677            assert_eq!(actual.rank(), 0);
10678        }
10679        assert!(
10680            generator
10681                .numerators
10682                .interaction_templates
10683                .read()
10684                .unwrap()
10685                .values()
10686                .all(|template| matches!(&**template, NumeratorTemplate::Dynamic))
10687        );
10688    }
10689
10690    #[test]
10691    fn template_transport_retains_declared_order_scoped_labels_and_zero_ports() {
10692        let cooking = CookSettings::indices().with_mode(CookMode::ReversibleEncoding);
10693        let scope = symbol!("generation_template_scope");
10694        let labels = |hedges: [usize; 2]| {
10695            let plain = AbstractIndex::Named(symbols::hedge_index().into(), hedges[0], 2);
10696            let payload = symbol!("generation_template_label")
10697                .call((symbols::hedge_index().call((hedges[1], 3)),));
10698            let encoded = cooking
10699                .cook_function(payload.as_fun_view().unwrap())
10700                .unwrap();
10701            let scoped = AbstractIndex::try_from(encoded.as_view())
10702                .unwrap()
10703                .scoped(scope);
10704            [plain, scoped].map(|index| {
10705                Minkowski {}
10706                    .new_rep(4)
10707                    .cast::<LibraryRep>()
10708                    .slot::<PartialIndex<AbstractIndex>, _>(PartialIndex::Explicit(index))
10709            })
10710        };
10711        let original = labels([0, 1]);
10712        let head = tensor_symbol!("generation_template_order");
10713        let expression = FunctionBuilder::new(head)
10714            .add_args(original.map(|slot| match slot.aind {
10715                PartialIndex::Explicit(index) => {
10716                    slot.rep().slot::<AbstractIndex, _>(index).to_atom()
10717                }
10718                _ => unreachable!(),
10719            }))
10720            .finish();
10721        let source = SymbolicTensor::from_declared_parts(
10722            expression,
10723            PartialStructure::from_logical_slots([original[1], original[0]]),
10724        )
10725        .unwrap();
10726        let zero = source.with_checked_expression(Atom::Zero).unwrap();
10727        let legs = tensor_test_legs();
10728        let instantiation = NumeratorInstantiation {
10729            owner: NumeratorOwner::Vertex(7),
10730            legs: &legs[..2],
10731        };
10732        let target = labels([legs[0].hedge, legs[1].hedge]);
10733        for source in [source, zero] {
10734            let was_zero = source.is_zero();
10735            let direct =
10736                NumeratorInterface::translate(&source, |atom| instantiation.bind_template(atom))
10737                    .unwrap();
10738            let template = NumeratorTemplate::admitted(source).unwrap();
10739            let mapped = template.instantiate(&instantiation).unwrap();
10740            assert_eq!(
10741                mapped.explicit_indices().unwrap().collect::<Vec<_>>(),
10742                direct.explicit_indices().unwrap().collect::<Vec<_>>(),
10743                "template and direct translation must retain identical index history",
10744            );
10745            assert_eq!(
10746                mapped.structure().logical_slots(),
10747                vec![target[1], target[0]]
10748            );
10749            assert_eq!(mapped.is_zero(), was_zero);
10750            SymbolicTensor::validate_interface(mapped.expression(), mapped.structure()).unwrap();
10751        }
10752    }
10753
10754    #[test]
10755    fn zero_template_and_direct_transport_retain_hidden_index_history() {
10756        let index = AbstractIndex::Named(symbols::hedge_index().into(), 0, 2);
10757        let port = Minkowski {}
10758            .new_rep(4)
10759            .cast::<LibraryRep>()
10760            .slot::<AbstractIndex, _>(index)
10761            .to_atom();
10762        let source = NumeratorInterface::admit(
10763            FunctionBuilder::new(tensor_symbol!("generation_template_hidden_pair"))
10764                .add_arg(&port)
10765                .add_arg(&port)
10766                .finish(),
10767            None,
10768        )
10769        .unwrap()
10770        .with_algebra_result(Atom::Zero)
10771        .unwrap();
10772        assert_eq!(source.rank(), 0);
10773        let legs = tensor_test_legs();
10774        let instantiation = NumeratorInstantiation {
10775            owner: NumeratorOwner::Vertex(7),
10776            legs: &legs[..2],
10777        };
10778        let direct =
10779            NumeratorInterface::translate(&source, |atom| instantiation.bind_template(atom))
10780                .unwrap();
10781        let mapped = NumeratorTemplate::admitted(source)
10782            .unwrap()
10783            .instantiate(&instantiation)
10784            .unwrap();
10785        let expected = vec![AbstractIndex::Named(
10786            symbols::hedge_index().into(),
10787            legs[0].hedge,
10788            2,
10789        )];
10790        assert_eq!(
10791            direct.explicit_indices().unwrap().collect::<Vec<_>>(),
10792            expected
10793        );
10794        assert_eq!(
10795            mapped.explicit_indices().unwrap().collect::<Vec<_>>(),
10796            expected
10797        );
10798        assert!(mapped.is_zero());
10799    }
10800
10801    #[test]
10802    fn lowers_ufo_lorentz_tensors_to_spenso_structures() {
10803        let legs = tensor_test_legs();
10804        let instantiation = NumeratorInstantiation {
10805            owner: NumeratorOwner::Vertex(7),
10806            legs: &legs,
10807        };
10808        let gamma = instantiation
10809            .instantiate(&test_atom("Gamma(3,2,1)"), NumeratorSector::Spin)
10810            .unwrap();
10811        assert_eq!(
10812            gamma,
10813            test_atom(
10814                "spenso::gamma(spenso::bis(4,gammalooprs::hedge(41,1)),spenso::bis(4,gammalooprs::hedge(20,1)),spenso::mink(4,gammalooprs::hedge(60,1)))"
10815            )
10816        );
10817
10818        let metric = instantiation
10819            .instantiate(&test_atom("Metric(3,4)"), NumeratorSector::Spin)
10820            .unwrap();
10821        assert_eq!(
10822            metric,
10823            test_atom(
10824                "spenso::g(spenso::mink(4,gammalooprs::hedge(60,1)),spenso::mink(4,gammalooprs::hedge(81,1)))"
10825            )
10826        );
10827
10828        let identity = instantiation
10829            .instantiate(&test_atom("Identity(1,2)"), NumeratorSector::Spin)
10830            .unwrap();
10831        assert_eq!(
10832            identity,
10833            test_atom(
10834                "spenso::g(spenso::bis(4,gammalooprs::hedge(20,1)),spenso::bis(4,gammalooprs::hedge(41,1)))"
10835            )
10836        );
10837    }
10838
10839    #[test]
10840    fn lowers_covariant_propagator_with_compact_momentum_slots() {
10841        use idenso::{CookMode, CookSettings, IndexTooling, tensor::SymbolicTensor};
10842        use spenso::structure::abstract_index::AbstractIndex;
10843
10844        let legs = tensor_test_legs();
10845        let instantiation = NumeratorInstantiation {
10846            owner: NumeratorOwner::Edge(30),
10847            legs: &legs[2..],
10848        };
10849        let numerator = instantiation
10850            .instantiate(
10851                &test_atom(
10852                    "-1i*(Metric(idx(1,1),idx(1,2))-(1-xi)*P(idx(1,1))*P(idx(1,2))/spenso::dot(P(spenso::mink(4)),P(spenso::mink(4))))",
10853                ),
10854                NumeratorSector::Spin,
10855            )
10856            .unwrap();
10857        assert_eq!(
10858            numerator,
10859            test_atom(
10860                "-1i*(spenso::g(spenso::mink(4,gammalooprs::hedge(60,1)),spenso::mink(4,gammalooprs::hedge(81,1)))-(1-xi)*gammalooprs::Q(30,spenso::mink(4,gammalooprs::hedge(60,1)))*gammalooprs::Q(30,spenso::mink(4,gammalooprs::hedge(81,1)))/spenso::dot(gammalooprs::Q(30,spenso::mink(4)),gammalooprs::Q(30,spenso::mink(4))))"
10861            )
10862        );
10863        assert_eq!(
10864            instantiation.lower_spin(numerator.clone()).unwrap(),
10865            numerator
10866        );
10867        assert_eq!(numerator.list_dangling::<AbstractIndex>().unwrap().len(), 2);
10868        let metric = instantiation
10869            .instantiate(&test_atom("Metric(1,2)"), NumeratorSector::Spin)
10870            .unwrap();
10871        let cooking = CookSettings::indices().with_mode(CookMode::ReversibleEncoding);
10872        let source = SymbolicTensor::infer(cooking.cook((numerator * metric).as_view())).unwrap();
10873        let result = source.contract(Default::default()).unwrap();
10874        let result = result.to_dots().unwrap();
10875        let scalar = cooking.uncook(result.expression().as_view());
10876        assert_eq!(
10877            (scalar - test_atom("-1i*(3+xi)")).together().cancel(),
10878            Atom::Zero
10879        );
10880    }
10881
10882    #[test]
10883    fn ufo_lorentz_epsilon_matches_aloha_and_native_gamma5() {
10884        use idenso::{CookMode, CookSettings, tensor::SymbolicTensor};
10885        use spenso::{
10886            network::{
10887                ExecutionResult, Sequential, SmallestDegree,
10888                library::symbolic::ExplicitKey,
10889                parsing::{ParseSettings as TensorParseSettings, StrictTensorFilter},
10890            },
10891            structure::abstract_index::{AIND_SYMBOLS, AbstractIndex},
10892            tensors::parametric::MixedTensor,
10893        };
10894        use spenso_hep_lib::{FUN_LIB, HepNet, hep_lib_atom};
10895        use symbolica::function;
10896
10897        let mut legs = tensor_test_legs();
10898        for leg in &mut legs {
10899            leg.spin = 3;
10900        }
10901        let instantiation = NumeratorInstantiation {
10902            owner: NumeratorOwner::Vertex(7),
10903            legs: &legs,
10904        };
10905        let lowered = instantiation
10906            .instantiate(&test_atom("Epsilon(1,2,3,4)"), NumeratorSector::Spin)
10907            .unwrap();
10908        let native_epsilon = test_atom(
10909            "spenso::epsilon(spenso::mink(4,gammalooprs::hedge(20,1)),spenso::mink(4,gammalooprs::hedge(41,1)),spenso::mink(4,gammalooprs::hedge(60,1)),spenso::mink(4,gammalooprs::hedge(81,1)))",
10910        );
10911        assert_eq!(lowered, -Atom::i() * &native_epsilon);
10912        assert_eq!(instantiation.lower_spin(lowered.clone()).unwrap(), lowered);
10913        assert_eq!(
10914            instantiation
10915                .instantiate(&test_atom("Epsilon(2,1,3,4)"), NumeratorSector::Spin)
10916                .unwrap(),
10917            -&lowered,
10918        );
10919
10920        // Use the unchanged gamma5/gamma library as an exact component oracle,
10921        // not a second epsilon table. Idenso defines Tr(g5*g^a*g^b*g^c*g^d)
10922        // = 4*epsilon(a,b,c,d), with epsilon(0,1,2,3) = -i.
10923        let trace = instantiation
10924            .instantiate(
10925                &test_atom(
10926                    "Gamma5(-1,-2)*Gamma(1,-2,-3)*Gamma(2,-3,-4)*Gamma(3,-4,-5)*Gamma(4,-5,-1)",
10927                ),
10928                NumeratorSector::Spin,
10929            )
10930            .unwrap();
10931        let cooking = CookSettings::indices().with_mode(CookMode::ReversibleEncoding);
10932        let simplified = SymbolicTensor::infer(cooking.cook(trace.as_view()))
10933            .unwrap()
10934            .simplify_algebra(&idenso::tensor::AlgebraSettings {
10935                gamma: Some(idenso::dirac::GammaSimplifySettings::default()),
10936                ..Default::default()
10937            })
10938            .unwrap();
10939        assert_eq!(
10940            cooking.uncook(simplified.expression().as_view()),
10941            Atom::num(4) * &native_epsilon,
10942        );
10943        let component_expression = lowered
10944            .replace(native_epsilon.to_pattern())
10945            .with(&trace / Atom::num(4));
10946        let library = hep_lib_atom::<AbstractIndex, MixedTensor<f64, ExplicitKey<AbstractIndex>>>();
10947        let settings = TensorParseSettings::default()
10948            .with_strict_tensor_filter(StrictTensorFilter::ContainsReps);
10949        // MadGraph/ALOHA L_Epsilon.give_parity gives (0,1,2,3) -> -1.
10950        // Include an odd permutation and a repeated index. Four Minkowski
10951        // selectors add a minus sign for the three spatial directions.
10952        for (coordinates, aloha_component) in [
10953            ([0, 1, 2, 3], -1),
10954            ([1, 0, 2, 3], 1),
10955            ([0, 2, 3, 1], -1),
10956            ([0, 1, 2, 2], 0),
10957        ] {
10958            let mut selected = component_expression.clone();
10959            for (coordinate, hedge) in coordinates.into_iter().zip([20, 41, 60, 81]) {
10960                selected *= function!(
10961                    ETS.delta,
10962                    function!(AIND_SYMBOLS.cind, coordinate),
10963                    test_atom(&format!("spenso::mink(4,gammalooprs::hedge({hedge},1))"))
10964                );
10965            }
10966            let selected = cooking.cook(selected.as_view());
10967            let mut network =
10968                HepNet::<AbstractIndex>::try_from_view(selected.as_view(), &library, &settings)
10969                    .unwrap();
10970            network
10971                .execute::<Sequential, SmallestDegree, _, _, _>(&library, &*FUN_LIB)
10972                .unwrap();
10973            let actual = match network.result_scalar().unwrap() {
10974                ExecutionResult::One => Atom::one(),
10975                ExecutionResult::Zero => Atom::Zero,
10976                ExecutionResult::Val(value) => value.into_owned(),
10977            };
10978            assert_eq!(actual, Atom::num(-aloha_component), "{coordinates:?}");
10979        }
10980    }
10981
10982    #[test]
10983    fn lowers_ufo_epsilon_with_the_ufo_normalization() {
10984        use idenso::{
10985            CookMode, CookSettings,
10986            tensor::{AlgebraSettings, SymbolicTensor},
10987        };
10988
10989        let legs: [NumeratorHalfEdge; 4] = std::array::from_fn(|i| NumeratorHalfEdge {
10990            edge: 10 * (i + 1),
10991            flow: Flow::Sink,
10992            hedge: 20 * (i + 1),
10993            spin: 3,
10994            color: 1,
10995        });
10996        let instantiation = NumeratorInstantiation {
10997            owner: NumeratorOwner::Vertex(7),
10998            legs: &legs,
10999        };
11000        let lower = |structure: &str| {
11001            instantiation
11002                .instantiate(&test_atom(structure), NumeratorSector::Spin)
11003                .unwrap()
11004        };
11005        assert_eq!(
11006            lower("Epsilon(1,2,3,4)"),
11007            test_atom(
11008                "-1i*spenso::epsilon(spenso::mink(4,gammalooprs::hedge(20,1)),spenso::mink(4,gammalooprs::hedge(40,1)),spenso::mink(4,gammalooprs::hedge(60,1)),spenso::mink(4,gammalooprs::hedge(80,1)))"
11009            )
11010        );
11011        // ALOHA's explicit matrices satisfy
11012        // Tr[γ5 γ^μ γ^ν γ^ρ γ^σ] = 4i ε^{μνρσ} with its ε^{0123} = −1; the
11013        // lowered structures must agree after Idenso's trace simplification.
11014        let cooking = CookSettings::indices().with_mode(CookMode::ReversibleEncoding);
11015        let simplify = |structure: &str| {
11016            let tensor = SymbolicTensor::infer(cooking.cook(lower(structure).as_view())).unwrap();
11017            let simplified = tensor
11018                .simplify_algebra(&AlgebraSettings::hep())
11019                .unwrap()
11020                .into_expression();
11021            cooking.uncook(simplified.as_view())
11022        };
11023        let trace =
11024            simplify("Gamma5(-1,-2)*Gamma(1,-2,-3)*Gamma(2,-3,-4)*Gamma(3,-4,-5)*Gamma(4,-5,-1)");
11025        assert!(!trace.is_zero());
11026        assert_eq!(trace, simplify("4*1i*Epsilon(1,2,3,4)"));
11027        for malformed in ["Epsilon()", "Epsilon(1,2,3)", "Epsilon(1,2,3,4,-1)"] {
11028            assert!(matches!(
11029                instantiation.instantiate(&test_atom(malformed), NumeratorSector::Spin),
11030                Err(GenerationError::InvalidNumeratorTensor { .. })
11031            ));
11032        }
11033    }
11034
11035    #[test]
11036    fn lowers_ufo_charge_conjugation_and_rejects_invalid_arity() {
11037        let legs = tensor_test_legs();
11038        let instantiation = NumeratorInstantiation {
11039            owner: NumeratorOwner::Vertex(7),
11040            legs: &legs,
11041        };
11042        let charge_conjugation = instantiation
11043            .instantiate(&test_atom("C(1,2)"), NumeratorSector::Spin)
11044            .unwrap();
11045        assert_eq!(
11046            charge_conjugation,
11047            test_atom(
11048                "spenso::charge_conjugation(spenso::bis(4,gammalooprs::hedge(20,1)),spenso::bis(4,gammalooprs::hedge(41,1)))"
11049            )
11050        );
11051        assert_eq!(
11052            instantiation
11053                .instantiate(&test_atom("C(2,1)"), NumeratorSector::Spin)
11054                .unwrap(),
11055            -charge_conjugation,
11056        );
11057        for malformed in ["C()", "C(1)", "C(1,2,3)"] {
11058            assert!(matches!(
11059                instantiation.instantiate(&test_atom(malformed), NumeratorSector::Spin),
11060                Err(GenerationError::InvalidNumeratorTensor { .. })
11061            ));
11062        }
11063        assert!(
11064            instantiation
11065                .instantiate(&test_atom("C(1,2)"), NumeratorSector::Color)
11066                .is_err()
11067        );
11068    }
11069
11070    #[test]
11071    fn lowers_ufo_color_tensors_with_dual_representations() {
11072        let legs = tensor_test_legs();
11073        let instantiation = NumeratorInstantiation {
11074            owner: NumeratorOwner::Vertex(7),
11075            legs: &legs,
11076        };
11077        let tensors = instantiation
11078            .instantiate(
11079                &test_atom("Identity(1,2)*T(3,2,1)*f(3,-1,-2)"),
11080                NumeratorSector::Color,
11081            )
11082            .unwrap();
11083        let expected = test_atom(
11084            "spenso::g(spenso::dind(spenso::cof(3,gammalooprs::hedge(20,1))),spenso::cof(3,gammalooprs::hedge(41,1)))*spenso::t(spenso::coad(8,gammalooprs::hedge(60,1)),spenso::cof(3,gammalooprs::hedge(41,1)),spenso::dind(spenso::cof(3,gammalooprs::hedge(20,1))))*spenso::f(spenso::coad(8,gammalooprs::hedge(60,1)),spenso::coad(8,gammalooprs::vertex(7,1)),spenso::coad(8,gammalooprs::vertex(7,2)))",
11085        );
11086        assert_eq!(tensors, expected);
11087    }
11088
11089    #[test]
11090    fn expands_pslash_with_one_shared_collision_free_lorentz_index() {
11091        let legs = [
11092            NumeratorHalfEdge {
11093                edge: 5,
11094                flow: Flow::Source,
11095                hedge: 10,
11096                spin: 2,
11097                color: 3,
11098            },
11099            NumeratorHalfEdge {
11100                edge: 5,
11101                flow: Flow::Sink,
11102                hedge: 11,
11103                spin: 2,
11104                color: 3,
11105            },
11106        ];
11107        let instantiation = NumeratorInstantiation {
11108            owner: NumeratorOwner::Edge(5),
11109            legs: &legs,
11110        };
11111        let slash = instantiation
11112            .instantiate(
11113                &test_atom("PSlash(2,1)*Metric(dummy(4),dummy(4))"),
11114                NumeratorSector::Spin,
11115            )
11116            .unwrap();
11117        assert_eq!(
11118            slash,
11119            test_atom(
11120                "spenso::gamma(spenso::bis(4,gammalooprs::hedge(11,1)),spenso::bis(4,gammalooprs::hedge(10,1)),spenso::mink(4,gammalooprs::edge(5,5)))*gammalooprs::Q(5,spenso::mink(4,gammalooprs::edge(5,5)))*spenso::g(spenso::mink(4,gammalooprs::edge(5,4)),spenso::mink(4,gammalooprs::edge(5,4)))"
11121            )
11122        );
11123    }
11124
11125    #[test]
11126    fn explicit_leg_pslash_matches_gamma_times_momentum() {
11127        // ALOHA defines PSlash(i, j, N) as Gamma(mu, i, j) P(mu, N) with the
11128        // same all-incoming momentum, so a source leg reverses both alike.
11129        for flow in [Flow::Source, Flow::Sink] {
11130            let legs = [(Flow::Sink, 2), (Flow::Source, 2), (flow, 3)]
11131                .into_iter()
11132                .enumerate()
11133                .map(|(edge, (flow, spin))| NumeratorHalfEdge {
11134                    edge,
11135                    flow,
11136                    hedge: 2 * edge + usize::from(flow == Flow::Sink),
11137                    spin,
11138                    color: 1,
11139                })
11140                .collect::<Vec<_>>();
11141            let instantiation = NumeratorInstantiation {
11142                owner: NumeratorOwner::Vertex(0),
11143                legs: &legs,
11144            };
11145            let instantiate = |structure: &str| {
11146                instantiation
11147                    .instantiate(&test_atom(structure), NumeratorSector::Spin)
11148                    .unwrap()
11149            };
11150            assert_eq!(
11151                instantiate("PSlash(2,1,3)"),
11152                instantiate("Gamma(-1,2,1)*P(-1,3)"),
11153                "PSlash and Gamma*P disagree on a {flow:?} momentum leg"
11154            );
11155        }
11156    }
11157
11158    #[test]
11159    fn lowers_ufo_symmetric_color_tensor_with_standard_normalization() {
11160        use idenso::{
11161            CookMode, CookSettings, IndexTooling, color::ColorSimplifySettings,
11162            tensor::SymbolicTensor,
11163        };
11164        let cooking = CookSettings::indices().with_mode(CookMode::ReversibleEncoding);
11165        let simplify = |expression: Atom| {
11166            let source = SymbolicTensor::infer(cooking.cook(expression.as_view())).unwrap();
11167            let result = source
11168                .simplify_algebra(&idenso::tensor::AlgebraSettings {
11169                    color: Some(ColorSimplifySettings::default().with_cof_dimension_invariants()),
11170                    ..Default::default()
11171                })
11172                .unwrap()
11173                .contract(idenso::tensor::ContractSettings {
11174                    collect_chains: false,
11175                    collect_traces: false,
11176                    ..Default::default()
11177                })
11178                .unwrap();
11179            cooking.uncook(result.expression().as_view())
11180        };
11181
11182        let mut legs = [0, 1, 2].map(|edge| NumeratorHalfEdge {
11183            edge,
11184            flow: Flow::Source,
11185            hedge: 2 * edge,
11186            spin: 1,
11187            color: 8,
11188        });
11189        let instantiation = NumeratorInstantiation {
11190            owner: NumeratorOwner::Vertex(0),
11191            legs: &legs,
11192        };
11193        let tensor = instantiation
11194            .instantiate(&test_atom("d(1,2,3)"), NumeratorSector::Color)
11195            .unwrap();
11196        assert_eq!(tensor, tensor.spenso_conj());
11197        assert_eq!(
11198            tensor,
11199            instantiation
11200                .instantiate(&test_atom("d(3,1,2)"), NumeratorSector::Color)
11201                .unwrap()
11202        );
11203        assert_eq!(simplify(tensor.clone() * &tensor), test_atom("40/3"));
11204        let third = instantiation.index(legs[2], 1).unwrap();
11205        let other = test_atom("other_color_index");
11206        let right = tensor.replace(third.to_pattern()).with(other.clone());
11207        assert_eq!(
11208            simplify(tensor * right),
11209            test_atom("5/3")
11210                * ETS.metric(
11211                    ColorRepresentation::Adjoint
11212                        .representation()
11213                        .to_symbolic([third]),
11214                    ColorRepresentation::Adjoint
11215                        .representation()
11216                        .to_symbolic([other]),
11217                )
11218        );
11219        assert_eq!(
11220            simplify(
11221                instantiation
11222                    .instantiate(&test_atom("d(-1,-1,3)"), NumeratorSector::Color)
11223                    .unwrap()
11224            ),
11225            Atom::Zero
11226        );
11227        legs[0].color = 3;
11228        let incompatible = NumeratorInstantiation {
11229            owner: NumeratorOwner::Vertex(0),
11230            legs: &legs,
11231        };
11232        assert!(
11233            incompatible
11234                .instantiate(&test_atom("d(1,2,3)"), NumeratorSector::Color)
11235                .is_err()
11236        );
11237    }
11238
11239    #[test]
11240    fn lowers_ufo_color_epsilon_and_dual_contractions() {
11241        use idenso::{CookMode, CookSettings, IndexTooling, tensor::SymbolicTensor};
11242        let cooking = CookSettings::indices().with_mode(CookMode::ReversibleEncoding);
11243        let simplify = |expression: Atom| {
11244            let source = SymbolicTensor::infer(cooking.cook(expression.as_view())).unwrap();
11245            let result = source
11246                .simplify_algebra(&idenso::tensor::AlgebraSettings {
11247                    epsilon: true,
11248                    ..Default::default()
11249                })
11250                .unwrap();
11251            cooking.uncook(result.expression().as_view())
11252        };
11253
11254        for (color, name, conjugate_name) in
11255            [(3, "Epsilon", "EpsilonBar"), (-3, "EpsilonBar", "Epsilon")]
11256        {
11257            let legs = [0, 1, 2].map(|edge| NumeratorHalfEdge {
11258                edge,
11259                flow: Flow::Source,
11260                hedge: 2 * edge,
11261                spin: 1,
11262                color,
11263            });
11264            let instantiation = NumeratorInstantiation {
11265                owner: NumeratorOwner::Vertex(0),
11266                legs: &legs,
11267            };
11268            let tensor = instantiation
11269                .instantiate(
11270                    &test_atom(&format!("{name}(1,2,3)")),
11271                    NumeratorSector::Color,
11272                )
11273                .unwrap();
11274            let exchanged = instantiation
11275                .instantiate(
11276                    &test_atom(&format!("{name}(2,1,3)")),
11277                    NumeratorSector::Color,
11278                )
11279                .unwrap();
11280            assert_eq!(tensor, -exchanged);
11281            assert_eq!(tensor.spenso_conj().spenso_conj(), tensor);
11282            assert_eq!(
11283                simplify(tensor.clone() * tensor.spenso_conj()),
11284                Atom::num(6)
11285            );
11286            assert!(
11287                instantiation
11288                    .instantiate(
11289                        &test_atom(&format!("{conjugate_name}(1,2,3)")),
11290                        NumeratorSector::Color
11291                    )
11292                    .is_err()
11293            );
11294            assert!(
11295                instantiation
11296                    .instantiate(&test_atom(&format!("{name}(1,2)")), NumeratorSector::Color)
11297                    .is_err()
11298            );
11299            // Identity chains must transmit orientation to the external port,
11300            // without treating the two ends of a summed index as the same slot.
11301            let relayed = instantiation
11302                .instantiate(
11303                    &test_atom(&format!("Identity(1,-1)*Identity(-1,-2)*{name}(-2,2,3)")),
11304                    NumeratorSector::Color,
11305                )
11306                .unwrap();
11307            assert_eq!(relayed, tensor);
11308            let sum = instantiation
11309                .instantiate(
11310                    &test_atom(&format!("{name}(1,2,3)+{name}(1,2,-1)*Identity(-1,3)")),
11311                    NumeratorSector::Color,
11312                )
11313                .unwrap();
11314            assert_eq!(sum, Atom::num(2) * tensor);
11315        }
11316        let closed = NumeratorInstantiation {
11317            owner: NumeratorOwner::Vertex(3),
11318            legs: &[],
11319        };
11320        assert_eq!(
11321            simplify(
11322                closed
11323                    .instantiate(
11324                        &test_atom("Epsilon(-1,-2,-3)*EpsilonBar(-1,-2,-3)"),
11325                        NumeratorSector::Color,
11326                    )
11327                    .unwrap()
11328            ),
11329            Atom::num(6)
11330        );
11331        assert!(
11332            closed
11333                .instantiate(
11334                    &test_atom("Epsilon(-1,-2,-3)*f(-1,-2,-3)"),
11335                    NumeratorSector::Color
11336                )
11337                .is_err()
11338        );
11339    }
11340
11341    #[test]
11342    fn lowers_summed_fundamental_color_indices() {
11343        use idenso::{
11344            CookMode, CookSettings, color::ColorSimplifySettings, tensor::SymbolicTensor,
11345        };
11346
11347        let legs = [0, 1].map(|edge| NumeratorHalfEdge {
11348            edge,
11349            flow: Flow::Source,
11350            hedge: 2 * edge,
11351            spin: 1,
11352            color: 8,
11353        });
11354        let instantiation = NumeratorInstantiation {
11355            owner: NumeratorOwner::Vertex(2),
11356            legs: &legs,
11357        };
11358        let trace = instantiation
11359            .instantiate(&test_atom("T(1,-1,-2)*T(2,-2,-1)"), NumeratorSector::Color)
11360            .unwrap();
11361        let expected = instantiation
11362            .instantiate(&test_atom("Identity(1,2)/2"), NumeratorSector::Color)
11363            .unwrap();
11364        let cooking = CookSettings::indices().with_mode(CookMode::ReversibleEncoding);
11365        let source = SymbolicTensor::infer(cooking.cook(trace.as_view())).unwrap();
11366        let result = source
11367            .simplify_algebra(&idenso::tensor::AlgebraSettings {
11368                color: Some(ColorSimplifySettings::default().with_cof_dimension_invariants()),
11369                ..Default::default()
11370            })
11371            .unwrap()
11372            .contract(idenso::tensor::ContractSettings {
11373                collect_chains: false,
11374                collect_traces: false,
11375                ..Default::default()
11376            })
11377            .unwrap();
11378        assert_eq!(cooking.uncook(result.expression().as_view()), expected);
11379    }
11380
11381    #[test]
11382    fn keeps_color_and_spin_identity_sectors_distinct() {
11383        let model = standard_model();
11384        let generator = Generator::new(model.clone());
11385        let legs = [
11386            NumeratorHalfEdge {
11387                edge: 1,
11388                flow: Flow::Source,
11389                hedge: 2,
11390                spin: 2,
11391                color: -3,
11392            },
11393            NumeratorHalfEdge {
11394                edge: 2,
11395                flow: Flow::Sink,
11396                hedge: 5,
11397                spin: 2,
11398                color: 3,
11399            },
11400            NumeratorHalfEdge {
11401                edge: 3,
11402                flow: Flow::Source,
11403                hedge: 6,
11404                spin: 1,
11405                color: 1,
11406            },
11407        ];
11408        let instantiation = NumeratorInstantiation {
11409            owner: NumeratorOwner::Vertex(9),
11410            legs: &legs,
11411        };
11412        let numerator = generator
11413            .interaction_numerator(model.vertex_rule_id("V_78").unwrap(), &instantiation)
11414            .unwrap();
11415
11416        let numerator = NumeratorInterface::export(&numerator).0.to_plain_string();
11417        assert!(numerator.contains("spenso::bis(4"));
11418        assert!(numerator.contains("spenso::cof(3"));
11419        assert!(numerator.contains("spenso::dind"));
11420        assert_eq!(numerator.matches("spenso::g(").count(), 2);
11421        assert!(!numerator.contains("UFO::Identity("));
11422    }
11423
11424    #[test]
11425    fn coupling_upper_bounds_prune_vertex_signatures_without_applying_lower_bounds() {
11426        let model = standard_model();
11427        let options = GenerationOptions::default().with_graph_filter(
11428            GenerationFilter::CouplingOrders(BTreeMap::from([
11429                ("QCD".to_owned(), (6, Some(6))),
11430                ("QED".to_owned(), (0, Some(0))),
11431            ])),
11432        );
11433        let signatures = InteractionSignatures::new(&model, &options).unwrap();
11434        let rules: BTreeSet<_> = signatures.0.values().flatten().copied().collect();
11435        assert!(!rules.is_empty());
11436        for (index, rule) in model.vertex_rules().iter().enumerate() {
11437            let orders = rule.coupling_orders(&model);
11438            assert_eq!(
11439                rules.contains(&model.vertex_rule_id_at(index).unwrap()),
11440                orders.get("QED").copied().unwrap_or(0) == 0
11441                    && orders.get("QCD").copied().unwrap_or(0) <= 6
11442            );
11443        }
11444    }
11445
11446    #[test]
11447    fn generated_qcd_loop_numerators_are_spenso_ready() {
11448        let model = standard_model();
11449        let options = GenerationOptions::default()
11450            .with_loop_count(1, 1)
11451            .unwrap()
11452            .threads(1)
11453            .max_vertices(2)
11454            .with_graph_filter(GenerationFilter::CouplingOrders(BTreeMap::from([
11455                ("QCD".to_owned(), (2, Some(2))),
11456                ("QED".to_owned(), (0, Some(0))),
11457            ])))
11458            .with_graph_filter(GenerationFilter::ParticleVeto(
11459                vec![-6, -4, -3, -2, -1, 1, 2, 3, 4, 6]
11460                    .into_iter()
11461                    .map(ParticleSelector::Pdg)
11462                    .collect(),
11463            ));
11464        let generated = Generator::new(model)
11465            .generate(
11466                &Process::new(["g"], ["g"]),
11467                &options,
11468                GenerationType::Amplitude,
11469            )
11470            .unwrap();
11471        assert_eq!(generated.diagrams.len(), 3);
11472        assert_eq!(generated.report.retained_count, 3);
11473        assert_eq!(
11474            generated
11475                .diagrams
11476                .iter()
11477                .map(FeynmanDiagram::canonical_key)
11478                .collect::<Result<BTreeSet<_>, _>>()
11479                .unwrap()
11480                .len(),
11481            3,
11482            "normalized runtime representatives must remain unique after canonical comparison grouping",
11483        );
11484
11485        let residual_heads = [
11486            "UFO::Gamma(",
11487            "UFO::Metric(",
11488            "UFO::PSlash(",
11489            "UFO::Identity(",
11490            "UFO::T(",
11491            "UFO::f(",
11492        ];
11493        let mut combined = String::new();
11494        for diagram in &generated.diagrams {
11495            combined.push_str(
11496                &NumeratorInterface::export(diagram.numerator())
11497                    .0
11498                    .to_plain_string(),
11499            );
11500            for (_, vertex) in diagram.vertices() {
11501                combined.push_str(
11502                    &NumeratorInterface::export(&vertex.numerator)
11503                        .0
11504                        .to_plain_string(),
11505                );
11506            }
11507            for (_, _, edge) in diagram.edges() {
11508                combined.push_str(
11509                    &NumeratorInterface::export(&edge.numerator)
11510                        .0
11511                        .to_plain_string(),
11512                );
11513            }
11514        }
11515        for head in residual_heads {
11516            assert!(!combined.contains(head), "residual tensor head {head}");
11517        }
11518        assert!(combined.contains("spenso::gamma("));
11519        assert!(combined.contains("spenso::t("));
11520        assert!(combined.contains("spenso::f("));
11521        assert!(combined.contains("spenso::g("));
11522    }
11523
11524    #[test]
11525    fn apply_feynman_rules_to_compact_dot() {
11526        let generator = Generator::new(scalar_model());
11527        let diagram = FeynmanDiagram::from_dot(
11528            Arc::clone(&generator.model),
11529            r#"digraph bubble {
11530                ext [style=invis];
11531                ext -> a [particle="phi"];
11532                a -> b [particle="phi", lmb_id=0];
11533                a -> b [particle="phi"];
11534                b -> ext [particle="phi"];
11535            }"#,
11536        )
11537        .unwrap();
11538        assert_eq!(diagram.numerator().expression(), &Atom::one());
11539        let routed = diagram.loop_momentum_basis().clone();
11540        let id = diagram.id();
11541        let diagram = diagram.apply_feynman_rules().unwrap();
11542        assert_eq!(diagram.numerator().expression(), &test_atom("GC1^2"));
11543        assert_eq!(diagram.loop_momentum_basis(), &routed);
11544        assert_eq!(diagram.id(), id);
11545        diagram.validate().unwrap();
11546    }
11547
11548    #[test]
11549    fn apply_feynman_rules_matches_generated_local_factors() {
11550        let generator = Generator::new(standard_model());
11551        let generated = generator
11552            .generate(
11553                &Process::new(["g"], ["g"]),
11554                &GenerationOptions::default()
11555                    .with_loop_count(1, 1)
11556                    .unwrap()
11557                    .threads(1)
11558                    .max_vertices(2)
11559                    .with_graph_filter(GenerationFilter::CouplingOrders(BTreeMap::from([
11560                        ("QCD".to_owned(), (2, Some(2))),
11561                        ("QED".to_owned(), (0, Some(0))),
11562                    ]))),
11563                GenerationType::Amplitude,
11564            )
11565            .unwrap();
11566        assert!(!generated.diagrams.is_empty());
11567        for diagram in generated.diagrams {
11568            let topology = diagram
11569                .clone()
11570                .with_numerator(SymbolicTensor::infer(Atom::one()).unwrap())
11571                .unwrap();
11572            let restored = topology.apply_feynman_rules().unwrap();
11573            assert_eq!(restored.to_json().unwrap(), diagram.to_json().unwrap());
11574            let reapplied = restored.apply_feynman_rules().unwrap();
11575            assert_eq!(reapplied.to_json().unwrap(), restored.to_json().unwrap());
11576        }
11577    }
11578
11579    #[test]
11580    fn closed_fermion_loops_always_contribute_their_sign() {
11581        let generator = Generator::new(fermion_model());
11582        let mut graph = Graph::new();
11583        let interaction = graph.add_node(ColoredNode::Interaction(vertex(&generator.model, "V")));
11584        let external = graph.add_node(ColoredNode::External(ExternalNode {
11585            index: 0,
11586            state: ExternalState::Outgoing,
11587            particle: particle(&generator.model, 22),
11588        }));
11589        graph
11590            .add_edge(
11591                interaction,
11592                interaction,
11593                true,
11594                EdgeColor {
11595                    particle: particle(&generator.model, 1),
11596                    direction: None,
11597                },
11598            )
11599            .unwrap();
11600        graph
11601            .add_edge(
11602                interaction,
11603                external,
11604                false,
11605                EdgeColor {
11606                    particle: particle(&generator.model, 22),
11607                    direction: None,
11608                },
11609            )
11610            .unwrap();
11611
11612        let loop_count = generator.closed_fermion_loop_count(&graph, false).unwrap();
11613        assert_eq!(loop_count, 1);
11614        let diagram = generator
11615            .to_diagram(
11616                "loop".to_owned(),
11617                GenerationType::Amplitude,
11618                ColoredTopology {
11619                    graph,
11620                    symmetry: 3,
11621                    multiplicity: 2,
11622                    cut_partitions: Vec::new(),
11623                    topology_threshold_candidates: Vec::new(),
11624                    spectator_cuts: Vec::new(),
11625                },
11626                1,
11627                FermionSigns {
11628                    internal_loop_negative: loop_count % 2 == 1,
11629                    ..FermionSigns::default()
11630                },
11631                &GenerationOptions::default(),
11632            )
11633            .unwrap();
11634        assert_eq!(
11635            diagram.overall_factor(),
11636            &factor_atom("InternalFermionLoopSign(-1)*CouplingsMultiplicity(2)/AutG(3)")
11637        );
11638    }
11639
11640    #[test]
11641    fn open_ghost_chain_exchange_has_grassmann_sign() {
11642        let model = standard_model();
11643        let process = ResolvedProcess::new(
11644            &model,
11645            &Process::new([9000005_i64, 9000005], [9000005_i64, 9000005]),
11646            GenerationType::Amplitude,
11647            &GenerationOptions::default(),
11648        )
11649        .unwrap();
11650        let mut signs = Vec::new();
11651        for outgoing in [[2, 3], [3, 2]] {
11652            let mut graph = Graph::new();
11653            for index in 0..4 {
11654                graph.add_node(ColoredNode::External(ExternalNode {
11655                    index,
11656                    state: if index < 2 {
11657                        ExternalState::Incoming
11658                    } else {
11659                        ExternalState::Outgoing
11660                    },
11661                    particle: particle(&model, 9000005),
11662                }));
11663            }
11664            for _ in 0..2 {
11665                graph.add_node(ColoredNode::Interaction(vertex(&model, "V_35")));
11666            }
11667            for (left, right, pdg) in [
11668                (0, 4, 9000005),
11669                (4, outgoing[0], 9000005),
11670                (1, 5, 9000005),
11671                (5, outgoing[1], 9000005),
11672                (4, 5, 21),
11673            ] {
11674                graph
11675                    .add_edge(
11676                        left,
11677                        right,
11678                        true,
11679                        EdgeColor {
11680                            particle: particle(&model, pdg),
11681                            direction: None,
11682                        },
11683                    )
11684                    .unwrap();
11685            }
11686            signs.push(
11687                process
11688                    .normalize_fermion_flows(&graph, &model)
11689                    .unwrap()
11690                    .signs
11691                    .external_ordering_negative,
11692            );
11693        }
11694        assert_ne!(
11695            signs[0], signs[1],
11696            "exchanging two identical external ghosts must reverse the sign"
11697        );
11698    }
11699
11700    #[test]
11701    fn closed_ghost_loops_contribute_a_grassmann_minus_sign() {
11702        let generator = Generator::new(standard_model());
11703        let generated = generator
11704            .generate(
11705                &Process::new(["g"], ["g"]),
11706                &GenerationOptions::default()
11707                    .with_loop_count(1, 1)
11708                    .unwrap()
11709                    .threads(1)
11710                    .max_vertices(2)
11711                    .with_graph_filter(GenerationFilter::VertexAllow(vec![VertexSelector::Name(
11712                        "V_35".to_owned(),
11713                    )])),
11714                GenerationType::Amplitude,
11715            )
11716            .unwrap();
11717        assert_eq!(generated.diagrams.len(), 1);
11718        let diagram = &generated.diagrams[0];
11719        assert_eq!(
11720            diagram
11721                .edges()
11722                .filter(|(_, _, edge)| {
11723                    generator.model.particle_by_id(edge.particle).unwrap().spin == -1
11724                })
11725                .count(),
11726            2,
11727        );
11728
11729        // The ghost-gluon vertex and propagator supply no closed-loop sign.
11730        let factor = diagram.overall_factor();
11731        let without_loop_sign = factor
11732            .replace(factor_atom("InternalFermionLoopSign(-1)").to_pattern())
11733            .with(Atom::one().to_pattern());
11734        assert_ne!(
11735            factor, &without_loop_sign,
11736            "a closed ghost loop must carry its Grassmann minus sign in the overall factor",
11737        );
11738    }
11739
11740    #[test]
11741    fn closed_anticommutating_loop_counts() {
11742        let model = standard_model();
11743        let mut definition = serde_json::to_value(&model).unwrap();
11744        for particle in definition["particles"].as_array_mut().unwrap() {
11745            if particle["ghost_number"].as_i64().unwrap_or(0) != 0 {
11746                particle["spin"] = serde_json::json!(2);
11747            }
11748        }
11749        for lorentz in definition["lorentz_structures"].as_array_mut().unwrap() {
11750            for spin in lorentz["spins"].as_array_mut().unwrap() {
11751                if spin.as_i64() == Some(-1) {
11752                    *spin = serde_json::json!(2);
11753                }
11754            }
11755        }
11756        // This artificial spin/statistics model no longer describes the SM's
11757        // physical vector/Goldstone/ghost quartets used for covariant cuts.
11758        definition["covariant_cut_multiplets"] = serde_json::json!({});
11759        let half_integer_ghost_model: Model = serde_json::from_value(definition).unwrap();
11760        let generators = [
11761            Generator::new(model),
11762            Generator::new(half_integer_ghost_model),
11763        ];
11764        for (name, edges, expected, expected_fermions) in [
11765            ("ghost", vec![(0, 1, 9000005), (1, 0, 9000005)], 1, 0),
11766            ("antighost", vec![(0, 1, -9000005), (1, 0, -9000005)], 1, 0),
11767            ("ghost self-loop", vec![(0, 0, 9000005)], 1, 0),
11768            ("Dirac", vec![(0, 1, 5), (1, 0, 5)], 1, 1),
11769            ("anti-Dirac", vec![(0, 1, -5), (1, 0, -5)], 1, 1),
11770            ("Dirac self-loop", vec![(0, 0, 5)], 1, 1),
11771            ("open Dirac chain", vec![(0, 1, 5), (1, 2, 5)], 0, 0),
11772            (
11773                "open ghost chain",
11774                vec![(0, 1, 9000005), (1, 2, 9000005)],
11775                0,
11776                0,
11777            ),
11778            ("gluon cycle", vec![(0, 1, 21), (1, 0, 21)], 0, 0),
11779            (
11780                "ghost and Dirac loops joined by a gluon",
11781                vec![
11782                    (0, 1, 9000005),
11783                    (1, 0, 9000005),
11784                    (1, 2, 21),
11785                    (2, 3, 5),
11786                    (3, 2, 5),
11787                ],
11788                2,
11789                1,
11790            ),
11791            (
11792                "two ghost loops joined by a gluon",
11793                vec![
11794                    (0, 1, 9000005),
11795                    (1, 0, 9000005),
11796                    (1, 2, 21),
11797                    (2, 3, 9000005),
11798                    (3, 2, 9000005),
11799                ],
11800                2,
11801                0,
11802            ),
11803            (
11804                "two Dirac loops joined by a gluon",
11805                vec![(0, 1, 5), (1, 0, 5), (1, 2, 21), (2, 3, 5), (3, 2, 5)],
11806                2,
11807                2,
11808            ),
11809        ] {
11810            for generator in &generators {
11811                let model = &generator.model;
11812                let mut graph = Graph::new();
11813                let last_node = edges.iter().flat_map(|(a, b, _)| [*a, *b]).max().unwrap();
11814                for _ in 0..=last_node {
11815                    graph.add_node(ColoredNode::Interaction(vertex(model, "V_35")));
11816                }
11817                for &(a, b, pdg) in &edges {
11818                    graph.add_edge(a, b, true, edge(model, pdg)).unwrap();
11819                }
11820                assert_eq!(
11821                    generator.closed_fermion_loop_count(&graph, true).unwrap(),
11822                    expected,
11823                    "{name}"
11824                );
11825                assert_eq!(
11826                    generator.closed_fermion_loop_count(&graph, false).unwrap(),
11827                    expected_fermions,
11828                    "fermion filter: {name}"
11829                );
11830            }
11831        }
11832    }
11833
11834    #[test]
11835    fn ghost_loop_count_excludes_open_chains_and_counts_each_closed_component() {
11836        let generator = Generator::new(standard_model());
11837        let mut graph = Graph::new();
11838        let incoming = graph.add_node(ColoredNode::External(ExternalNode {
11839            index: 0,
11840            state: ExternalState::Incoming,
11841            particle: particle(&generator.model, 9000005),
11842        }));
11843        let outgoing = graph.add_node(ColoredNode::External(ExternalNode {
11844            index: 1,
11845            state: ExternalState::Outgoing,
11846            particle: particle(&generator.model, 9000005),
11847        }));
11848        graph
11849            .add_edge(incoming, outgoing, true, edge(&generator.model, 9000005))
11850            .unwrap();
11851        assert_eq!(
11852            generator.closed_fermion_loop_count(&graph, true).unwrap(),
11853            0
11854        );
11855
11856        for loop_count in 1..=2 {
11857            let interaction =
11858                graph.add_node(ColoredNode::Interaction(vertex(&generator.model, "V_35")));
11859            graph
11860                .add_edge(
11861                    interaction,
11862                    interaction,
11863                    true,
11864                    edge(&generator.model, 9000005),
11865                )
11866                .unwrap();
11867            assert_eq!(
11868                generator.closed_fermion_loop_count(&graph, true).unwrap(),
11869                loop_count,
11870            );
11871            assert_eq!(
11872                generator.closed_fermion_loop_count(&graph, false).unwrap(),
11873                0
11874            );
11875        }
11876    }
11877
11878    #[test]
11879    fn fermion_loop_filter_excludes_ghost_loops() {
11880        let generator = Generator::new(standard_model());
11881        for (fermion_loops, expected_diagrams) in [(0, 1), (1, 0)] {
11882            let generated = generator
11883                .generate(
11884                    &Process::new(["g"], ["g"]),
11885                    &GenerationOptions::default()
11886                        .with_loop_count(1, 1)
11887                        .unwrap()
11888                        .threads(1)
11889                        .max_vertices(2)
11890                        .with_graph_filter(GenerationFilter::VertexAllow(vec![
11891                            VertexSelector::Name("V_35".to_owned()),
11892                        ]))
11893                        .with_graph_filter(GenerationFilter::FermionLoopCountRange((
11894                            fermion_loops,
11895                            fermion_loops,
11896                        ))),
11897                    GenerationType::Amplitude,
11898                )
11899                .unwrap();
11900            assert_eq!(generated.diagrams.len(), expected_diagrams);
11901        }
11902    }
11903
11904    #[test]
11905    fn positive_external_fermion_signs_keep_symbolic_provenance() {
11906        let generator = Generator::new(fermion_model());
11907        let diagram = generator
11908            .to_diagram(
11909                "positive".to_owned(),
11910                GenerationType::Amplitude,
11911                ColoredTopology {
11912                    graph: Graph::new(),
11913                    symmetry: 1,
11914                    multiplicity: 1,
11915                    cut_partitions: Vec::new(),
11916                    topology_threshold_candidates: Vec::new(),
11917                    spectator_cuts: Vec::new(),
11918                },
11919                1,
11920                FermionSigns {
11921                    internal_loop_negative: false,
11922                    include_external_ordering: true,
11923                    external_ordering_negative: false,
11924                    include_antifermion_spin_sum: true,
11925                    antifermion_spin_sum_negative: false,
11926                },
11927                &GenerationOptions::default(),
11928            )
11929            .unwrap();
11930        assert_eq!(
11931            diagram.overall_factor(),
11932            &factor_atom("AntiFermionSpinSumSign(1)*ExternalFermionOrderingSign(1)*1/AutG(1)")
11933        );
11934    }
11935
11936    #[test]
11937    fn branching_fermion_chains_are_rejected() {
11938        let generator = Generator::new(fermion_model());
11939        let mut graph = Graph::new();
11940        let center = graph.add_node(ColoredNode::Interaction(vertex(&generator.model, "V")));
11941        for _ in 0..3 {
11942            let endpoint = graph.add_node(ColoredNode::Interaction(vertex(&generator.model, "V")));
11943            graph
11944                .add_edge(
11945                    center,
11946                    endpoint,
11947                    true,
11948                    EdgeColor {
11949                        particle: particle(&generator.model, 1),
11950                        direction: None,
11951                    },
11952                )
11953                .unwrap();
11954        }
11955
11956        assert!(matches!(
11957            generator.closed_fermion_loop_count(&graph, false),
11958            Err(GenerationError::UnsupportedFermionBranching {
11959                vertex,
11960                degree: 3
11961            }) if vertex == center
11962        ));
11963    }
11964
11965    #[test]
11966    fn filters_are_scoped_and_validated_before_generation() {
11967        let generator = Generator::new(fermion_model());
11968        let process = photon_process();
11969
11970        let unsupported = GenerationOptions::default().with_graph_filter(
11971            GenerationFilter::SelfEnergy(crate::SelfEnergyFilterOptions {
11972                only_scaleless: true,
11973                ..crate::SelfEnergyFilterOptions::default()
11974            }),
11975        );
11976        assert!(matches!(
11977            generator.generate(&process, &unsupported, GenerationType::Amplitude),
11978            Err(GenerationError::UnsupportedFilterOption {
11979                scope: FilterScope::Graph,
11980                filter: GenerationFilterKind::SelfEnergy,
11981                option: "only_scaleless"
11982            })
11983        ));
11984
11985        let perturbative_filter =
11986            GenerationFilter::PerturbativeOrders(BTreeMap::from([("QED".to_owned(), 1)]));
11987        generator
11988            .validate_filters(
11989                FilterScope::Graph,
11990                GenerationType::CrossSection,
11991                std::slice::from_ref(&perturbative_filter),
11992            )
11993            .unwrap();
11994        let perturbative = GenerationOptions::default().with_graph_filter(perturbative_filter);
11995        assert!(matches!(
11996            generator.generate(&process, &perturbative, GenerationType::Amplitude),
11997            Err(GenerationError::InvalidFilterScope {
11998                scope: FilterScope::Graph,
11999                filter: GenerationFilterKind::PerturbativeOrders,
12000                generation_type: GenerationType::Amplitude
12001            })
12002        ));
12003
12004        let sewn_filter = GenerationFilter::Sewn(SewnFilterOptions::default());
12005        generator
12006            .validate_filters(
12007                FilterScope::Graph,
12008                GenerationType::CrossSection,
12009                std::slice::from_ref(&sewn_filter),
12010            )
12011            .unwrap();
12012        assert!(matches!(
12013            generator.generate(
12014                &process,
12015                &GenerationOptions::default().with_graph_filter(sewn_filter),
12016                GenerationType::Amplitude
12017            ),
12018            Err(GenerationError::InvalidFilterScope {
12019                scope: FilterScope::Graph,
12020                filter: GenerationFilterKind::Sewn,
12021                generation_type: GenerationType::Amplitude
12022            })
12023        ));
12024
12025        let duplicate = GenerationOptions::default()
12026            .with_graph_filter(GenerationFilter::LoopCountRange((0, 0)))
12027            .with_graph_filter(GenerationFilter::LoopCountRange((0, 1)));
12028        assert!(matches!(
12029            generator.generate(&process, &duplicate, GenerationType::Amplitude),
12030            Err(GenerationError::DuplicateFilter {
12031                scope: FilterScope::Graph,
12032                filter: GenerationFilterKind::LoopCountRange
12033            })
12034        ));
12035
12036        let invalid = GenerationOptions::default()
12037            .with_graph_filter(GenerationFilter::LoopCountRange((2, 1)));
12038        assert!(matches!(
12039            generator.generate(&process, &invalid, GenerationType::Amplitude),
12040            Err(GenerationError::InvalidFilterRange {
12041                scope: FilterScope::Graph,
12042                filter: GenerationFilterKind::LoopCountRange,
12043                minimum: 2,
12044                maximum: 1
12045            })
12046        ));
12047
12048        let invalid_scope = GenerationOptions::default().with_cut_amplitude_filter(
12049            GenerationFilter::ParticleVeto(vec![ParticleSelector::Pdg(1)]),
12050        );
12051        assert!(matches!(
12052            generator.generate(&process, &invalid_scope, GenerationType::Amplitude),
12053            Err(GenerationError::InvalidFilterScope {
12054                scope: FilterScope::CutAmplitude,
12055                filter: GenerationFilterKind::ParticleVeto,
12056                generation_type: GenerationType::Amplitude
12057            })
12058        ));
12059    }
12060
12061    #[test]
12062    fn scalar_rescaling_refuses_a_single_sample() {
12063        let generator = Generator::new(fermion_model());
12064        let options = |samples, canonical| GraphGroupingOptions {
12065            number_of_numerical_samples: samples,
12066            check_canonical_numerator: canonical,
12067            ..GraphGroupingOptions::default()
12068        };
12069        let validate = |grouping: &NumeratorGrouping| {
12070            generator.validate_options(
12071                GenerationType::Amplitude,
12072                &GenerationOptions::default().numerator_grouping(grouping.clone()),
12073            )
12074        };
12075        // Canonical comparison falls back to the samples for the pairs it does not match,
12076        // so it does not lift the two-sample requirement.
12077        for canonical in [false, true] {
12078            let single = NumeratorGrouping::UpToScalar(options(1, canonical));
12079            assert!(single.single_sample_warning().is_none());
12080            assert!(matches!(
12081                validate(&single),
12082                Err(GenerationError::SingleSampleScalarRescaling)
12083            ));
12084        }
12085        for accepted in [options(2, false), options(0, true)] {
12086            validate(&NumeratorGrouping::UpToScalar(accepted)).unwrap();
12087        }
12088        // Identical and sign grouping accept one sample with a warning for the caller.
12089        for single in [
12090            NumeratorGrouping::Identical(options(1, false)),
12091            NumeratorGrouping::UpToSign(options(1, true)),
12092        ] {
12093            assert!(single.single_sample_warning().is_some());
12094            validate(&single).unwrap();
12095        }
12096        assert!(
12097            NumeratorGrouping::UpToSign(options(2, false))
12098                .single_sample_warning()
12099                .is_none()
12100        );
12101    }
12102
12103    #[test]
12104    fn grouping_options_are_validated() {
12105        let generator = Generator::new(fermion_model());
12106
12107        let grouping = GenerationOptions::default().filter_zero_color(true);
12108        generator
12109            .validate_options(GenerationType::Amplitude, &grouping)
12110            .unwrap();
12111
12112        let invalid = GenerationOptions::default().numerator_grouping(
12113            NumeratorGrouping::Identical(GraphGroupingOptions {
12114                number_of_numerical_samples: 0,
12115                ..GraphGroupingOptions::default()
12116            }),
12117        );
12118        assert!(matches!(
12119            generator.validate_options(GenerationType::Amplitude, &invalid),
12120            Err(GenerationError::InvalidNumericalSampleCount)
12121        ));
12122        let canonical_only = GenerationOptions::default().numerator_grouping(
12123            NumeratorGrouping::Identical(GraphGroupingOptions {
12124                number_of_numerical_samples: 0,
12125                check_canonical_numerator: true,
12126                ..GraphGroupingOptions::default()
12127            }),
12128        );
12129        generator
12130            .validate_options(GenerationType::Amplitude, &canonical_only)
12131            .unwrap();
12132    }
12133
12134    #[test]
12135    fn public_limits_report_arithmetic_overflow() {
12136        let model = fermion_model();
12137        let generator = Generator::new(model.clone());
12138        assert!(matches!(
12139            generator.generate(
12140                &photon_process(),
12141                &GenerationOptions::default().max_vertices(usize::MAX),
12142                GenerationType::Amplitude
12143            ),
12144            Err(GenerationError::ArithmeticOverflow(
12145                "the Symbolica vertex limit"
12146            ))
12147        ));
12148
12149        let options =
12150            GenerationOptions::default().with_graph_filter(GenerationFilter::PerturbativeOrders(
12151                BTreeMap::from([("QED".to_owned(), usize::MAX), ("QCD".to_owned(), 1)]),
12152            ));
12153        assert!(matches!(
12154            unresolved_cut_content(&model, &options),
12155            Err(GenerationError::ArithmeticOverflow(
12156                "the unresolved cut multiplicity"
12157            ))
12158        ));
12159    }
12160
12161    #[test]
12162    fn perturbative_orders_allow_only_derived_massless_cut_content() {
12163        let model = fermion_model();
12164        let options = GenerationOptions::default().with_graph_filter(
12165            GenerationFilter::PerturbativeOrders(BTreeMap::from([("QED".to_owned(), 1)])),
12166        );
12167        let unresolved = unresolved_cut_content(&model, &options).unwrap().unwrap();
12168        assert_eq!(unresolved.maximum_multiplicity, 1);
12169        assert_eq!(
12170            unresolved.particles,
12171            BTreeSet::from([
12172                particle(&model, -1),
12173                particle(&model, 1),
12174                particle(&model, 22),
12175            ])
12176        );
12177        assert!(ResolvedProcess::matches_cut_content(
12178            &[particle(&model, 1), particle(&model, 22)],
12179            &[particle(&model, 1)],
12180            Some(&unresolved)
12181        ));
12182        assert!(!ResolvedProcess::matches_cut_content(
12183            &[
12184                particle(&model, 1),
12185                particle(&model, 22),
12186                particle(&model, 22),
12187            ],
12188            &[particle(&model, 1)],
12189            Some(&unresolved)
12190        ));
12191        assert!(!ResolvedProcess::matches_cut_content(
12192            &[particle(&model, 1), particle(&model, 25)],
12193            &[particle(&model, 1)],
12194            Some(&unresolved)
12195        ));
12196    }
12197
12198    #[test]
12199    fn exact_cut_rejects_species_only_false_positives() {
12200        let model = exact_cut_model();
12201        let interaction = |name: &str| ColoredNode::Interaction(vertex(&model, name));
12202        let external = |index, state, pdg| {
12203            ColoredNode::External(ExternalNode {
12204                index,
12205                state,
12206                particle: particle(&model, pdg),
12207            })
12208        };
12209        let edge = |pdg| edge(&model, pdg);
12210
12211        let mut three_loop = Graph::new();
12212        let h0 = three_loop.add_node(interaction("V_78"));
12213        let h1 = three_loop.add_node(interaction("V_78"));
12214        let g0 = three_loop.add_node(interaction("V_76"));
12215        let p0 = three_loop.add_node(interaction("V_73"));
12216        let g1 = three_loop.add_node(interaction("V_76"));
12217        let p1 = three_loop.add_node(interaction("V_73"));
12218        let q0 = three_loop.add_node(interaction("V_98"));
12219        let q1 = three_loop.add_node(interaction("V_98"));
12220        let x0 = three_loop.add_node(external(0, ExternalState::Incoming, -11));
12221        let x1 = three_loop.add_node(external(1, ExternalState::Incoming, 11));
12222        let x2 = three_loop.add_node(external(2, ExternalState::Outgoing, -11));
12223        let x3 = three_loop.add_node(external(3, ExternalState::Outgoing, 11));
12224        three_loop.add_edge(h0, h1, false, edge(25)).unwrap();
12225        three_loop.add_edge(h0, p1, true, edge(5)).unwrap();
12226        three_loop.add_edge(h1, p0, true, edge(5)).unwrap();
12227        three_loop.add_edge(g0, g1, false, edge(21)).unwrap();
12228        three_loop.add_edge(g0, g1, true, edge(5)).unwrap();
12229        three_loop.add_edge(p0, g0, true, edge(5)).unwrap();
12230        three_loop.add_edge(p0, q1, false, edge(22)).unwrap();
12231        three_loop.add_edge(g1, h1, true, edge(5)).unwrap();
12232        three_loop.add_edge(p1, h0, true, edge(5)).unwrap();
12233        three_loop.add_edge(p1, q0, false, edge(22)).unwrap();
12234        three_loop.add_edge(q1, x0, true, edge(11)).unwrap();
12235        three_loop.add_edge(x1, q1, true, edge(11)).unwrap();
12236        three_loop.add_edge(q0, x2, true, edge(11)).unwrap();
12237        three_loop.add_edge(x3, q0, true, edge(11)).unwrap();
12238
12239        let mut four_loop = Graph::new();
12240        let x0 = four_loop.add_node(external(0, ExternalState::Incoming, -11));
12241        let x1 = four_loop.add_node(external(1, ExternalState::Incoming, 11));
12242        let x2 = four_loop.add_node(external(2, ExternalState::Outgoing, -11));
12243        let x3 = four_loop.add_node(external(3, ExternalState::Outgoing, 11));
12244        let p0 = four_loop.add_node(interaction("V_73"));
12245        let p1 = four_loop.add_node(interaction("V_73"));
12246        let h0 = four_loop.add_node(interaction("V_78"));
12247        let h1 = four_loop.add_node(interaction("V_78"));
12248        let g0 = four_loop.add_node(interaction("V_76"));
12249        let g1 = four_loop.add_node(interaction("V_76"));
12250        let g2 = four_loop.add_node(interaction("V_76"));
12251        let g3 = four_loop.add_node(interaction("V_76"));
12252        let q0 = four_loop.add_node(interaction("V_98"));
12253        let q1 = four_loop.add_node(interaction("V_98"));
12254        four_loop.add_edge(q1, x0, true, edge(11)).unwrap();
12255        four_loop.add_edge(x1, q1, true, edge(11)).unwrap();
12256        four_loop.add_edge(p0, q1, false, edge(22)).unwrap();
12257        four_loop.add_edge(g3, p0, true, edge(5)).unwrap();
12258        four_loop.add_edge(p0, g2, true, edge(5)).unwrap();
12259        four_loop.add_edge(g2, g3, false, edge(21)).unwrap();
12260        four_loop.add_edge(h0, g3, true, edge(5)).unwrap();
12261        four_loop.add_edge(g2, h0, true, edge(5)).unwrap();
12262        four_loop.add_edge(h0, h1, false, edge(25)).unwrap();
12263        four_loop.add_edge(g0, h1, true, edge(5)).unwrap();
12264        four_loop.add_edge(h1, g1, true, edge(5)).unwrap();
12265        four_loop.add_edge(p1, g0, true, edge(5)).unwrap();
12266        four_loop.add_edge(g1, p1, true, edge(5)).unwrap();
12267        four_loop.add_edge(g0, g1, false, edge(21)).unwrap();
12268        four_loop.add_edge(p1, q0, false, edge(22)).unwrap();
12269        four_loop.add_edge(q0, x2, true, edge(11)).unwrap();
12270        four_loop.add_edge(x3, q0, true, edge(11)).unwrap();
12271
12272        // These graphs contain the requested species, but neither has an
12273        // s-channel cut with the exact final-state multiset after allowing only
12274        // the configured unresolved QCD content.
12275        for (graph, qcd_order) in [(three_loop, 1), (four_loop, 2)] {
12276            let options = GenerationOptions::default()
12277                .with_graph_filter(GenerationFilter::PerturbativeOrders(BTreeMap::from([(
12278                    "QCD".to_owned(),
12279                    qcd_order,
12280                )])))
12281                .with_graph_filter(GenerationFilter::BlobRange(1..=1))
12282                .with_graph_filter(GenerationFilter::SpectatorRange(0..=0));
12283            let resolved = ResolvedProcess::new(
12284                &model,
12285                &Process::new([-11_i64, 11], [5_i64, -5, 25]),
12286                GenerationType::CrossSection,
12287                &options,
12288            )
12289            .unwrap();
12290            assert!(
12291                resolved
12292                    .cut_partitions(&graph, &model, &options)
12293                    .unwrap()
12294                    .physical
12295                    .is_empty()
12296            );
12297        }
12298    }
12299
12300    #[test]
12301    fn sewn_filter_vetoes_factorization_created_by_pairwise_sewing() {
12302        let model = fermion_model();
12303        let process = ResolvedProcess::new(
12304            &model,
12305            &Process::new([22_i64, 22], [22_i64]),
12306            GenerationType::CrossSection,
12307            &GenerationOptions::default(),
12308        )
12309        .unwrap();
12310        let mut graph = Graph::new();
12311        let externals: Vec<_> = (0..4)
12312            .map(|index| {
12313                graph.add_node(ColoredNode::External(ExternalNode {
12314                    index,
12315                    state: if index < 2 {
12316                        ExternalState::Incoming
12317                    } else {
12318                        ExternalState::Outgoing
12319                    },
12320                    particle: particle(&model, 22),
12321                }))
12322            })
12323            .collect();
12324        let center = graph.add_node(ColoredNode::Interaction(vertex(&model, "V")));
12325        let photon = edge(&model, 22);
12326        for external in &externals {
12327            graph.add_edge(*external, center, false, photon).unwrap();
12328        }
12329
12330        let options = GenerationOptions::default()
12331            .with_graph_filter(GenerationFilter::Sewn(SewnFilterOptions::default()));
12332        assert!(process.passes_sewn_filter(&graph, &options));
12333
12334        let mut factorized = Graph::new();
12335        let externals: Vec<_> = (0..4)
12336            .map(|index| {
12337                factorized.add_node(ColoredNode::External(ExternalNode {
12338                    index,
12339                    state: if index < 2 {
12340                        ExternalState::Incoming
12341                    } else {
12342                        ExternalState::Outgoing
12343                    },
12344                    particle: particle(&model, 22),
12345                }))
12346            })
12347            .collect();
12348        let left = factorized.add_node(ColoredNode::Interaction(vertex(&model, "V")));
12349        let right = factorized.add_node(ColoredNode::Interaction(vertex(&model, "V")));
12350        for external in [externals[0], externals[2]] {
12351            factorized.add_edge(external, left, false, photon).unwrap();
12352        }
12353        for external in [externals[1], externals[3]] {
12354            factorized.add_edge(external, right, false, photon).unwrap();
12355        }
12356        factorized.add_edge(left, right, false, photon).unwrap();
12357        assert!(!process.passes_sewn_filter(&factorized, &options));
12358        assert!(process.passes_sewn_filter(
12359            &factorized,
12360            &GenerationOptions::default().with_graph_filter(GenerationFilter::Sewn(
12361                SewnFilterOptions {
12362                    filter_tadpoles: false,
12363                }
12364            ))
12365        ));
12366    }
12367
12368    #[test]
12369    fn external_canonical_classes_keep_global_left_right_symmetry_out_of_raw_generation() {
12370        let model = fermion_model();
12371        let within = |name: &str| {
12372            ExternalCanonicalClass::Interchangeable(InterchangeableClass::WithinState(
12373                ExternalState::Incoming,
12374                model.particle_id(name).unwrap(),
12375            ))
12376        };
12377        let classes = |process: Process, generation_type, options: GenerationOptions| {
12378            ResolvedProcess::new(&model, &process, generation_type, &options)
12379                .unwrap()
12380                .external_edges(&model)
12381                .unwrap()
12382                .into_iter()
12383                .map(|(node, _)| node.external_class.unwrap())
12384                .collect::<Vec<_>>()
12385        };
12386        let process = Process::new([1_i64, -1, 22], Vec::<i64>::new());
12387        assert_eq!(
12388            classes(
12389                process.clone(),
12390                GenerationType::Amplitude,
12391                GenerationOptions::default().symmetrize_initial(true)
12392            ),
12393            vec![
12394                ExternalCanonicalClass::Exact {
12395                    state: ExternalState::Incoming,
12396                    index: 0,
12397                },
12398                ExternalCanonicalClass::Exact {
12399                    state: ExternalState::Incoming,
12400                    index: 1,
12401                },
12402                within("a"),
12403            ]
12404        );
12405        assert_eq!(
12406            classes(
12407                process,
12408                GenerationType::Amplitude,
12409                GenerationOptions::default()
12410                    .symmetrize_initial(true)
12411                    .symmetrize_external_fermions(true)
12412            ),
12413            vec![within("f"), within("f~"), within("a")]
12414        );
12415
12416        let cross_section = Process::new([1_i64, -1], [22_i64]);
12417        assert_eq!(
12418            classes(
12419                cross_section,
12420                GenerationType::CrossSection,
12421                GenerationOptions::default().symmetrize_initial(true)
12422            ),
12423            vec![
12424                ExternalCanonicalClass::Exact {
12425                    state: ExternalState::Incoming,
12426                    index: 0
12427                },
12428                ExternalCanonicalClass::Exact {
12429                    state: ExternalState::Incoming,
12430                    index: 1
12431                },
12432                ExternalCanonicalClass::Exact {
12433                    state: ExternalState::Outgoing,
12434                    index: 2,
12435                },
12436                ExternalCanonicalClass::Exact {
12437                    state: ExternalState::Outgoing,
12438                    index: 3,
12439                },
12440            ]
12441        );
12442
12443        let left_right = Process::new([1_i64, -1], [22_i64]);
12444        assert_eq!(
12445            classes(
12446                left_right,
12447                GenerationType::CrossSection,
12448                GenerationOptions::default().symmetrize_left_right(true)
12449            ),
12450            vec![
12451                ExternalCanonicalClass::Exact {
12452                    state: ExternalState::Incoming,
12453                    index: 0,
12454                },
12455                ExternalCanonicalClass::Exact {
12456                    state: ExternalState::Incoming,
12457                    index: 1,
12458                },
12459                ExternalCanonicalClass::Exact {
12460                    state: ExternalState::Outgoing,
12461                    index: 2,
12462                },
12463                ExternalCanonicalClass::Exact {
12464                    state: ExternalState::Outgoing,
12465                    index: 3,
12466                },
12467            ]
12468        );
12469    }
12470
12471    #[test]
12472    fn left_right_amplitude_classes_cross_symmetrized_legs_between_states() {
12473        let model = fermion_model();
12474        let classes = |options: GenerationOptions| {
12475            ResolvedProcess::new(
12476                &model,
12477                &Process::new([1_i64, 22], [1_i64, 22]),
12478                GenerationType::Amplitude,
12479                &options
12480                    .symmetrize_initial(true)
12481                    .symmetrize_final(true)
12482                    .symmetrize_left_right(true),
12483            )
12484            .unwrap()
12485            .external_edges(&model)
12486            .unwrap()
12487            .into_iter()
12488            .map(|(node, _)| node.external_class.unwrap())
12489            .collect::<Vec<_>>()
12490        };
12491        let crossed = |name: &str| {
12492            ExternalCanonicalClass::Interchangeable(InterchangeableClass::AcrossStates(
12493                model.particle_id(name).unwrap(),
12494            ))
12495        };
12496        let exact = |state, index| ExternalCanonicalClass::Exact { state, index };
12497        // Fermions stay labelled unless external fermion symmetrization is on.
12498        assert_eq!(
12499            classes(GenerationOptions::default()),
12500            vec![
12501                exact(ExternalState::Incoming, 0),
12502                crossed("a"),
12503                exact(ExternalState::Outgoing, 2),
12504                crossed("a"),
12505            ]
12506        );
12507        // An outgoing fermion crosses into an incoming antifermion, so it is
12508        // not interchangeable with the incoming fermion.
12509        assert_eq!(
12510            classes(GenerationOptions::default().symmetrize_external_fermions(true)),
12511            vec![crossed("f"), crossed("a"), crossed("f~"), crossed("a")]
12512        );
12513    }
12514
12515    #[test]
12516    fn amplitude_ghosts_need_the_external_fermion_opt_in() {
12517        let model = standard_model();
12518        let classes = |options: GenerationOptions| {
12519            ResolvedProcess::new(
12520                &model,
12521                &Process::new(["ghG", "ghG~"], ["ghG", "ghG~"]),
12522                GenerationType::Amplitude,
12523                &options.symmetrize_initial(true).symmetrize_final(true),
12524            )
12525            .unwrap()
12526            .external_edges(&model)
12527            .unwrap()
12528            .into_iter()
12529            .map(|(node, _)| node.external_class.unwrap())
12530            .collect::<Vec<_>>()
12531        };
12532        let crossed = |name: &str| {
12533            ExternalCanonicalClass::Interchangeable(InterchangeableClass::AcrossStates(
12534                model.particle_id(name).unwrap(),
12535            ))
12536        };
12537        let within = |state, name: &str| {
12538            ExternalCanonicalClass::Interchangeable(InterchangeableClass::WithinState(
12539                state,
12540                model.particle_id(name).unwrap(),
12541            ))
12542        };
12543        // As on main, left/right symmetrization keeps Grassmann ghost labels
12544        // fixed unless the external-fermion opt-in is given.
12545        assert!(
12546            classes(GenerationOptions::default().symmetrize_left_right(true))
12547                .iter()
12548                .all(|class| matches!(class, ExternalCanonicalClass::Exact { .. }))
12549        );
12550        assert_eq!(
12551            classes(
12552                GenerationOptions::default()
12553                    .symmetrize_left_right(true)
12554                    .symmetrize_external_fermions(true)
12555            ),
12556            vec![
12557                crossed("ghG"),
12558                crossed("ghG~"),
12559                crossed("ghG~"),
12560                crossed("ghG")
12561            ]
12562        );
12563        // So does separate side symmetrization, as on main.
12564        assert!(
12565            classes(GenerationOptions::default())
12566                .iter()
12567                .all(|class| matches!(class, ExternalCanonicalClass::Exact { .. }))
12568        );
12569        assert_eq!(
12570            classes(GenerationOptions::default().symmetrize_external_fermions(true)),
12571            vec![
12572                within(ExternalState::Incoming, "ghG"),
12573                within(ExternalState::Incoming, "ghG~"),
12574                within(ExternalState::Outgoing, "ghG"),
12575                within(ExternalState::Outgoing, "ghG~"),
12576            ]
12577        );
12578    }
12579
12580    /// One finalized external leg as attached to its interaction vertex.
12581    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
12582    struct ExternalAttachment {
12583        label: usize,
12584        state: ExternalState,
12585        pdg: i64,
12586        /// Whether the leg's momentum flows into the diagram.
12587        incoming_flow: bool,
12588        edge: EdgeId,
12589        vertex: VertexId,
12590        slot: VertexSlot,
12591        /// The all-incoming field that the interaction expects at `slot`.
12592        slot_pdg: i64,
12593    }
12594
12595    fn external_attachments(model: &Model, diagram: &FeynmanDiagram) -> Vec<ExternalAttachment> {
12596        let mut attachments = diagram
12597            .edges()
12598            .filter_map(|(edge_id, endpoints, edge)| {
12599                let leg = edge.external.as_ref()?;
12600                let (vertex, slot, incoming_flow) = match (endpoints.source, endpoints.target) {
12601                    (None, Some(vertex)) => (vertex, edge.target_slot(), true),
12602                    (Some(vertex), None) => (vertex, edge.source_slot(), false),
12603                    _ => panic!("an external edge has exactly one vertex"),
12604                };
12605                let rule = diagram.vertex(vertex).unwrap().interaction.unwrap();
12606                let slot_particle = model.vertex_rule_by_id(rule).unwrap().particles[slot.0];
12607                Some(ExternalAttachment {
12608                    label: leg.index,
12609                    state: leg.state,
12610                    pdg: model.particle_by_id(edge.particle).unwrap().pdg_code,
12611                    incoming_flow,
12612                    edge: edge_id,
12613                    vertex,
12614                    slot,
12615                    slot_pdg: model.particle_by_id(slot_particle).unwrap().pdg_code,
12616                })
12617            })
12618            .collect::<Vec<_>>();
12619        attachments.sort();
12620        attachments
12621    }
12622
12623    /// The DOT export with the attachment slots of two external legs that
12624    /// occupy slots of the same field at one vertex exchanged, if there are
12625    /// such legs.
12626    fn swap_same_field_external_slots(
12627        dot: &str,
12628        attachments: &[ExternalAttachment],
12629    ) -> Option<String> {
12630        let (first, second) = attachments
12631            .iter()
12632            .enumerate()
12633            .find_map(|(position, first)| {
12634                attachments[position + 1..]
12635                    .iter()
12636                    .find(|second| {
12637                        second.vertex == first.vertex && second.slot_pdg == first.slot_pdg
12638                    })
12639                    .map(|second| (first, second))
12640            })?;
12641        let retarget = |line: &str, attachment: &ExternalAttachment, slot: VertexSlot| {
12642            let attribute = if attachment.incoming_flow {
12643                "target_slot"
12644            } else {
12645                "source_slot"
12646            };
12647            line.replacen(
12648                &format!("{attribute}={}", attachment.slot.0),
12649                &format!("{attribute}={}", slot.0),
12650                1,
12651            )
12652        };
12653        let swapped = dot
12654            .lines()
12655            .map(|line| {
12656                if line.contains(&format!("[id={}, ", first.edge.0)) {
12657                    retarget(line, first, second.slot)
12658                } else if line.contains(&format!("[id={}, ", second.edge.0)) {
12659                    retarget(line, second, first.slot)
12660                } else {
12661                    line.to_owned()
12662                }
12663            })
12664            .collect::<Vec<_>>()
12665            .join("\n");
12666        Some(swapped)
12667    }
12668
12669    #[test]
12670    fn crossed_charged_amplitude_legs_keep_their_labels_through_finalization_and_dot() {
12671        let model = Arc::new(standard_model());
12672        let process = Process::new([24_i64, -24], [24_i64, -24]);
12673        let declared = [24_i64, -24, 24, -24];
12674        let generate = |left_right: bool| {
12675            Generator::new(Arc::clone(&model))
12676                .generate(
12677                    &process,
12678                    &GenerationOptions::default()
12679                        .symmetrize_initial(true)
12680                        .symmetrize_final(true)
12681                        .symmetrize_left_right(left_right)
12682                        .numerator_grouping(NumeratorGrouping::UpToSign(
12683                            GraphGroupingOptions::default(),
12684                        ))
12685                        .threads(1),
12686                    GenerationType::Amplitude,
12687                )
12688                .unwrap()
12689        };
12690        let result = generate(true);
12691        // Fewer representatives than without crossing: some stand for orbits
12692        // whose members attach an incoming W+ where another has the outgoing W-.
12693        assert!(result.diagrams.len() < generate(false).diagrams.len());
12694        let mut same_field_pairs = 0;
12695        for diagram in &result.diagrams {
12696            let finalized = external_attachments(&model, diagram);
12697            assert_eq!(finalized.len(), 4);
12698            for (position, attachment) in finalized.iter().enumerate() {
12699                let expected_incoming = position < 2;
12700                assert_eq!(attachment.label, position);
12701                assert_eq!(
12702                    attachment.state == ExternalState::Incoming,
12703                    expected_incoming
12704                );
12705                assert_eq!(attachment.pdg, declared[position]);
12706                // Momentum direction follows the declared state; the UFO slot
12707                // holds the all-incoming field of the attached leg.
12708                assert_eq!(attachment.incoming_flow, expected_incoming);
12709                let field = if expected_incoming {
12710                    attachment.pdg
12711                } else {
12712                    -attachment.pdg
12713                };
12714                assert_eq!(attachment.slot_pdg, field);
12715            }
12716            // The exact attached slot, not only its field, survives DOT.
12717            let dot = diagram.to_dot().unwrap();
12718            let reloaded = FeynmanDiagram::from_dot(Arc::clone(&model), &dot).unwrap();
12719            assert_eq!(external_attachments(&model, &reloaded), finalized);
12720            // A W+ W+ W- W- contact vertex has two slots per charge. Exchanging
12721            // the slots of two same-field legs is a different attachment.
12722            if let Some(swapped) = swap_same_field_external_slots(&dot, &finalized) {
12723                same_field_pairs += 1;
12724                let corrupted = FeynmanDiagram::from_dot(Arc::clone(&model), &swapped).unwrap();
12725                assert_ne!(external_attachments(&model, &corrupted), finalized);
12726            }
12727        }
12728        assert!(same_field_pairs > 0, "no vertex with two same-field legs");
12729    }
12730
12731    #[test]
12732    fn external_permutation_order_overflow_is_an_error() {
12733        // One crossed class of 21 legs: 21! exceeds u64 and is refused before
12734        // enumeration, while 11! * 10! for separate sides would still fit.
12735        let error = Generator::new(scalar_model())
12736            .generate(
12737                &Process::new(vec!["phi"; 11], vec!["phi"; 10]),
12738                &GenerationOptions::default()
12739                    .symmetrize_initial(true)
12740                    .symmetrize_final(true)
12741                    .symmetrize_left_right(true),
12742                GenerationType::Amplitude,
12743            )
12744            .unwrap_err();
12745        assert!(
12746            matches!(error, GenerationError::ArithmeticOverflow(_)),
12747            "{error}"
12748        );
12749    }
12750
12751    #[test]
12752    fn left_right_amplitude_symmetrization_permutes_identical_legs_across_states() {
12753        // Tree-level phi phi > phi phi in phi^3 theory: s, t and u channels.
12754        let process = Process::new(["phi", "phi"], ["phi", "phi"]);
12755        let weights = |options: GenerationOptions| {
12756            let result = Generator::new(scalar_model())
12757                .generate(&process, &options.threads(1), GenerationType::Amplitude)
12758                .unwrap();
12759            result.validate_groups().unwrap();
12760            let mut weights = result
12761                .diagrams
12762                .iter()
12763                .map(|diagram| evaluate_overall_factor(diagram.overall_factor().as_view()))
12764                .collect::<Vec<_>>();
12765            weights.sort();
12766            weights
12767        };
12768        let one = Atom::num(1);
12769        for grouping in [
12770            NumeratorGrouping::None,
12771            NumeratorGrouping::UpToSign(GraphGroupingOptions::default()),
12772        ] {
12773            let options = GenerationOptions::default().numerator_grouping(grouping);
12774            assert_eq!(
12775                weights(options.clone()),
12776                vec![one.clone(), one.clone(), one.clone()]
12777            );
12778            let within_states = options.symmetrize_initial(true).symmetrize_final(true);
12779            // S2 x S2 merges the t and u channels only.
12780            assert_eq!(
12781                weights(within_states.clone()),
12782                vec![one.clone(), Atom::num(2)]
12783            );
12784            // S4 also exchanges incoming and outgoing legs, merging all three
12785            // channels into one orbit; the total weight is unchanged.
12786            assert_eq!(
12787                weights(within_states.symmetrize_left_right(true)),
12788                vec![Atom::num(3)]
12789            );
12790        }
12791    }
12792
12793    #[test]
12794    fn left_right_amplitude_symmetrization_requires_both_states() {
12795        let process = Process::new(["phi", "phi"], ["phi", "phi"]);
12796        for (initial, final_state) in [(false, false), (true, false), (false, true)] {
12797            let error = Generator::new(scalar_model())
12798                .generate(
12799                    &process,
12800                    &GenerationOptions::default()
12801                        .symmetrize_initial(initial)
12802                        .symmetrize_final(final_state)
12803                        .symmetrize_left_right(true),
12804                    GenerationType::Amplitude,
12805                )
12806                .unwrap_err();
12807            assert!(
12808                matches!(
12809                    error,
12810                    GenerationError::OneSidedLeftRightAmplitudeSymmetrization { initial: i, final_state: f }
12811                        if i == initial && f == final_state
12812                ),
12813                "{error}"
12814            );
12815        }
12816    }
12817
12818    #[test]
12819    fn numerator_construction_localizes_internal_ufo_data() {
12820        let source = fermion_model().to_json().unwrap();
12821        let mut definition = serde_json::from_str::<serde_json::Value>(&source).unwrap();
12822        let fermion = definition["particles"]
12823            .as_array_mut()
12824            .unwrap()
12825            .iter_mut()
12826            .find(|particle| particle["name"] == "f")
12827            .unwrap();
12828        fermion["propagator"] = serde_json::json!("custom_f_prop");
12829        definition["propagators"]
12830            .as_array_mut()
12831            .unwrap()
12832            .push(serde_json::json!({
12833                "name": "custom_f_prop",
12834                "particle": "f",
12835                "numerator": "UFO::{}::P(UFO::{}::idx(1,1))*UFO::{}::P(UFO::{}::idx(1,2))*UFO::{}::Metric(UFO::{}::idx(1,1),UFO::{}::dummy(1))*UFO::{}::Metric(UFO::{}::dummy(1),UFO::{}::idx(1,2))",
12836                "denominator": "P^2"
12837            }));
12838        let definition = serde_json::to_string(&definition).unwrap();
12839        let generator = Generator::new(Model::from_json(&definition).unwrap());
12840
12841        let mut graph = Graph::new();
12842        let interaction = graph.add_node(ColoredNode::Interaction(vertex(&generator.model, "V")));
12843        let external = graph.add_node(ColoredNode::External(ExternalNode {
12844            index: 0,
12845            state: ExternalState::Outgoing,
12846            particle: particle(&generator.model, 22),
12847        }));
12848        graph
12849            .add_edge(
12850                interaction,
12851                interaction,
12852                true,
12853                EdgeColor {
12854                    particle: particle(&generator.model, 1),
12855                    direction: None,
12856                },
12857            )
12858            .unwrap();
12859        graph
12860            .add_edge(
12861                interaction,
12862                external,
12863                false,
12864                EdgeColor {
12865                    particle: particle(&generator.model, 22),
12866                    direction: None,
12867                },
12868            )
12869            .unwrap();
12870
12871        let diagram = generator
12872            .to_diagram(
12873                "localized".to_owned(),
12874                GenerationType::Amplitude,
12875                ColoredTopology {
12876                    graph,
12877                    symmetry: 1,
12878                    multiplicity: 1,
12879                    cut_partitions: Vec::new(),
12880                    topology_threshold_candidates: Vec::new(),
12881                    spectator_cuts: Vec::new(),
12882                },
12883                1,
12884                FermionSigns {
12885                    internal_loop_negative: true,
12886                    ..FermionSigns::default()
12887                },
12888                &GenerationOptions::default(),
12889            )
12890            .unwrap();
12891        let internal_numerator = &diagram
12892            .edges()
12893            .find(|(_, _, edge)| edge.external.is_none())
12894            .unwrap()
12895            .2
12896            .numerator;
12897        let internal_numerator = NumeratorInterface::export(internal_numerator)
12898            .0
12899            .to_plain_string();
12900        assert!(internal_numerator.contains("gammalooprs::Q"));
12901        assert!(internal_numerator.contains("gammalooprs::hedge"));
12902        assert!(internal_numerator.contains("gammalooprs::hedge"));
12903        assert!(internal_numerator.contains("gammalooprs::edge"));
12904        assert!(!internal_numerator.contains("idx("));
12905        assert!(!internal_numerator.contains("Slash(P)"));
12906
12907        let momentum = symbol!("gammalooprs::Q");
12908        assert!(momentum.has_tag("spenso::tensor"));
12909        assert!(momentum.has_tag("spenso::rank1"));
12910
12911        let external_numerator = &diagram
12912            .edges()
12913            .find(|(_, _, edge)| edge.external.is_some())
12914            .unwrap()
12915            .2
12916            .numerator;
12917        assert_eq!(external_numerator.expression(), &Atom::one());
12918
12919        let vertex_numerator = &diagram
12920            .vertex(feynkit_graph::VertexId(interaction))
12921            .unwrap()
12922            .numerator;
12923        let vertex_numerator = NumeratorInterface::export(vertex_numerator)
12924            .0
12925            .to_plain_string();
12926        assert!(vertex_numerator.contains("gammalooprs::hedge"));
12927        assert!(vertex_numerator.contains("gammalooprs::hedge"));
12928    }
12929}