Skip to main content

gammalooprs/uv/approx/
mod.rs

1use crate::{
2    cff::{
3        CffEnergyDegreeBoundReport,
4        esurface::Esurface,
5        expression::{
6            GammaLoopOrientationExpression, OrientationExpression, OrientationID,
7            OrientationSelector, energy_map_replacements_gs,
8        },
9        hsurface::Hsurface,
10        surface::{GammaLoopLinearEnergyExpr, LinearEnergyExpr},
11    },
12    debug_tags,
13    graph::{Graph, LoopMomentumBasis, cuts::CutSet},
14    model::Model,
15    momentum::Sign,
16    settings::global::OrientationPattern,
17    utils::GS,
18    uv::{
19        ApproximationType, Spinney, UVgenerationSettings,
20        approx::{
21            direct_3d::{Direct3dApproximation, Direct3dCts},
22            final_integrand::{FinalIntegrandBuilder, FinalIntegrands},
23            integrated::{Integrated, IntegratedCts},
24            local_3d::{Local3DCts, Localizer},
25            local_4d::{Full4dCts, Local4dCts},
26            projected_4d::{Local4dProjectionContext, Projected4dApproximation},
27        },
28        marker::UvMarker,
29        settings::FinalIntegrandDimension,
30    },
31};
32use color_eyre::Result;
33use eyre::eyre;
34use gammaloop_tracing_filter::{LogMessage, debug_instrument};
35
36use std::sync::Mutex;
37
38use symbolica::{
39    atom::{Atom, AtomCore},
40    function,
41};
42
43use linnet::half_edge::involution::EdgeIndex;
44#[cfg(test)]
45use linnet::half_edge::involution::{EdgeVec, Orientation};
46use linnet::half_edge::subgraph::{InternalSubGraph, SuBitGraph, SubSetLike, SubSetOps};
47#[cfg(test)]
48use three_dimensional_reps::CffGenerationContext;
49use three_dimensional_reps::{Generate3DExpressionOptions, GeneratedThreeDExpression};
50use typed_index_collections::TiVec;
51
52use vakint::Vakint;
53
54#[cfg(test)]
55use self::direct_3d::DirectResidueBranches;
56
57pub mod direct_3d;
58pub mod final_integrand;
59pub mod integrated;
60pub mod local_3d;
61pub mod local_4d;
62pub(crate) mod projected_4d;
63
64pub trait Rooted {
65    fn root() -> Self;
66}
67
68pub trait ForestNodeLike: LogMessage {
69    fn subgraph(&self) -> &SuBitGraph;
70    fn lmb(&self) -> &LoopMomentumBasis;
71    fn lmb_id(&self) -> EdgeIndex {
72        *self.lmb().loop_edges.first().unwrap()
73    }
74    // fn lmb_given(&self, subgraph: &SuBitGraph) -> &LoopMomentumBasis;
75    fn dod(&self) -> i32;
76    fn renormalization_scheme(&self) -> ApproximationType;
77    fn topo_order(&self) -> usize;
78    fn reduced_subgraph(&self, given: &Self) -> SuBitGraph;
79}
80
81pub struct UVCtx<'a> {
82    pub graph: &'a Graph,
83    pub model: &'a crate::model::Model,
84    pub settings: &'a UVgenerationSettings,
85}
86
87impl<'a> UVCtx<'a> {
88    pub fn new(
89        graph: &'a Graph,
90        model: &'a crate::model::Model,
91        settings: &'a UVgenerationSettings,
92    ) -> Self {
93        Self {
94            graph,
95            model,
96            settings,
97        }
98    }
99}
100
101#[derive(Clone)]
102pub struct SimpleApprox {
103    t_args: Vec<Atom>,
104    pub sign: Sign,
105    graph: InternalSubGraph,
106}
107
108impl SimpleApprox {
109    pub(crate) fn expr(&self, bigger_graph: &SuBitGraph) -> Atom {
110        let reduced = UvMarker::subgraph(bigger_graph, &self.graph.filter);
111        let mut mul = Atom::num(1);
112        for i in &self.t_args {
113            mul *= i;
114        }
115        reduced * mul
116    }
117
118    pub(crate) fn t_op(&self, bigger_graph: &SuBitGraph) -> Atom {
119        function!(GS.uv_approx, self.expr(bigger_graph))
120    }
121
122    pub(crate) fn root(subgraph: InternalSubGraph) -> Self {
123        if !subgraph.is_empty() {
124            panic!(
125                "Root approximation must be empty {} {:?}",
126                subgraph.string_label(),
127                subgraph
128            )
129        }
130        SimpleApprox {
131            t_args: vec![],
132            sign: Sign::Positive,
133            graph: subgraph,
134        }
135    }
136
137    pub(crate) fn dependent(&self, bigger_graph: InternalSubGraph) -> Self {
138        Self {
139            t_args: vec![self.t_op(&bigger_graph.filter)],
140            sign: -self.sign,
141            graph: bigger_graph,
142        }
143    }
144}
145
146#[derive(Clone)]
147pub struct Approximation {
148    pub spinney: Spinney,
149    local_3d: Option<Local3DCts>,
150    local: Option<Local4dCts>,
151    integrated: Option<IntegratedCts>,
152    final_integrand: Option<FinalIntegrands>,
153    pub topo_order: usize,
154    pub simple_approx: Option<SimpleApprox>,
155}
156
157impl Approximation {
158    pub(crate) fn integrated(&self, graph: &Graph) -> Result<&IntegratedCts> {
159        self.integrated
160            .as_ref()
161            .ok_or_else(|| eyre!("No integrated CT for {}", self.simple_display(graph)))
162    }
163
164    pub(crate) fn local(&self, graph: &Graph) -> Result<&Local4dCts> {
165        self.local
166            .as_ref()
167            .ok_or_else(|| eyre!("No local CT for {}", self.simple_display(graph)))
168    }
169
170    pub(crate) fn recursion_input_4d(&self, graph: &Graph) -> Result<Full4dCts> {
171        Full4dCts::recursion_input(
172            self.local(graph)?,
173            self.integrated(graph)?,
174            self.renormalization_scheme(),
175            self.spinney.subgraph.is_empty(),
176            self.lmb(),
177        )
178    }
179
180    pub(crate) fn local_3d(&self, graph: &Graph) -> Result<&Local3DCts> {
181        self.local_3d
182            .as_ref()
183            .ok_or_else(|| eyre!("No local 3D CT for {}", self.simple_display(graph)))
184    }
185
186    pub(crate) fn final_integrand(&self, graph: &Graph) -> Result<&FinalIntegrands> {
187        self.final_integrand
188            .as_ref()
189            .ok_or_else(|| eyre!("No final integrand for {}", self.simple_display(graph)))
190    }
191
192    pub fn simple_display(&self, graph: &Graph) -> String {
193        format!(
194            "{} of {}",
195            self.simple_approx
196                .as_ref()
197                .unwrap()
198                .expr(&graph.full_filter()),
199            graph.name
200        )
201    }
202}
203
204impl LogMessage for Approximation {
205    fn log_display(&self) -> String {
206        format!(
207            "subgraph={}, topo_order={}, dod={}",
208            self.spinney.filter().string_label(),
209            self.topo_order,
210            self.spinney.dod
211        )
212    }
213}
214
215impl ForestNodeLike for Approximation {
216    fn dod(&self) -> i32 {
217        self.spinney.dod
218    }
219
220    fn renormalization_scheme(&self) -> ApproximationType {
221        self.spinney.renormalization_scheme
222    }
223
224    fn lmb(&self) -> &LoopMomentumBasis {
225        &self.spinney.lmb
226    }
227
228    fn reduced_subgraph(&self, given: &Self) -> SuBitGraph {
229        self.spinney
230            .subgraph
231            .subtract(&given.spinney.subgraph)
232            .filter
233    }
234
235    fn subgraph(&self) -> &SuBitGraph {
236        self.spinney.filter()
237    }
238
239    fn topo_order(&self) -> usize {
240        self.topo_order
241    }
242}
243
244#[derive(Clone)]
245pub struct CutStructure {
246    pub cuts: Vec<CutSet>,
247}
248
249#[derive(Clone, Copy, Debug)]
250enum OrientationProjectionSource<'a> {
251    Exact {
252        orientations: &'a TiVec<OrientationID, OrientationExpression>,
253        root_expression: Option<&'a GeneratedThreeDExpression<Esurface, Hsurface>>,
254        options: &'a Generate3DExpressionOptions,
255    },
256    FourDOnly,
257}
258
259#[derive(Clone, Copy, Debug)]
260pub(crate) struct OrientationProjection<'a> {
261    source: OrientationProjectionSource<'a>,
262    energy_degree_bound_reports: Option<&'a Mutex<Vec<CffEnergyDegreeBoundReport>>>,
263    pub(crate) orientation_pattern: &'a OrientationPattern,
264    pub(crate) explicit_orientation_sum_only: bool,
265    pub(crate) vacuum_subtraction: bool,
266}
267
268impl<'a> OrientationProjection<'a> {
269    /// Four-dimensional renormalization has no energy projection. It needs
270    /// neither a production CFF nor coarse orientation metadata. Computed
271    /// exports and production 3D UV use the stored exact source below.
272    pub(crate) fn four_d(orientation_pattern: &'a OrientationPattern) -> Self {
273        Self {
274            source: OrientationProjectionSource::FourDOnly,
275            energy_degree_bound_reports: None,
276            orientation_pattern,
277            explicit_orientation_sum_only: false,
278            vacuum_subtraction: false,
279        }
280    }
281
282    #[cfg(test)]
283    pub(crate) fn exact(
284        orientations: &'a TiVec<OrientationID, OrientationExpression>,
285        options: &'a Generate3DExpressionOptions,
286        orientation_pattern: &'a OrientationPattern,
287        explicit_orientation_sum_only: bool,
288    ) -> Self {
289        Self {
290            source: OrientationProjectionSource::Exact {
291                orientations,
292                root_expression: None,
293                options,
294            },
295            energy_degree_bound_reports: None,
296            orientation_pattern,
297            explicit_orientation_sum_only,
298            vacuum_subtraction: false,
299        }
300    }
301
302    pub(crate) fn exact_expression(
303        expression: &'a GeneratedThreeDExpression<Esurface, Hsurface>,
304        options: &'a Generate3DExpressionOptions,
305        orientation_pattern: &'a OrientationPattern,
306        explicit_orientation_sum_only: bool,
307    ) -> Self {
308        Self {
309            source: OrientationProjectionSource::Exact {
310                orientations: &expression.expression.orientations,
311                root_expression: Some(expression),
312                options,
313            },
314            energy_degree_bound_reports: None,
315            orientation_pattern,
316            explicit_orientation_sum_only,
317            vacuum_subtraction: false,
318        }
319    }
320
321    pub(crate) fn with_vacuum_subtraction(mut self, enabled: bool) -> Self {
322        self.vacuum_subtraction = enabled;
323        self
324    }
325
326    pub(crate) fn with_energy_degree_bound_reports(
327        mut self,
328        reports: &'a Mutex<Vec<CffEnergyDegreeBoundReport>>,
329    ) -> Self {
330        self.energy_degree_bound_reports = Some(reports);
331        self
332    }
333
334    pub(crate) fn record_energy_degree_bound_report(self, report: &CffEnergyDegreeBoundReport) {
335        let Some(reports) = self.energy_degree_bound_reports else {
336            return;
337        };
338        let mut report = report.clone();
339        report.physical_parent_bounds.sort_unstable();
340        report.assigned_cff_source_bounds.sort_unstable();
341        let mut reports = reports
342            .lock()
343            .unwrap_or_else(|poisoned| poisoned.into_inner());
344        if !reports.contains(&report) {
345            reports.push(report);
346        }
347    }
348
349    pub(crate) fn cff_options(self) -> Result<&'a Generate3DExpressionOptions> {
350        match self.source {
351            OrientationProjectionSource::Exact { options, .. } => Ok(options),
352            OrientationProjectionSource::FourDOnly => Err(eyre!(
353                "four-dimensional-only renormalization has no 3D projection options"
354            )),
355        }
356    }
357
358    pub(crate) fn orientation_ids(self) -> Result<Vec<OrientationID>> {
359        Ok(self
360            .exact_orientations()?
361            .iter_enumerated()
362            .filter_map(|(id, orientation)| {
363                self.orientation_pattern
364                    .filter_orientation(&orientation.data.orientation)
365                    .then_some(id)
366            })
367            .collect())
368    }
369
370    pub(crate) fn exact_orientations(
371        self,
372    ) -> Result<&'a TiVec<OrientationID, OrientationExpression>> {
373        match self.source {
374            OrientationProjectionSource::Exact { orientations, .. } => Ok(orientations),
375            OrientationProjectionSource::FourDOnly => Err(eyre!(
376                "four-dimensional-only renormalization has no 3D residue maps"
377            )),
378        }
379    }
380
381    pub(crate) fn root_expression(
382        self,
383    ) -> Option<&'a GeneratedThreeDExpression<Esurface, Hsurface>> {
384        match self.source {
385            OrientationProjectionSource::Exact {
386                root_expression, ..
387            } => root_expression,
388            OrientationProjectionSource::FourDOnly => None,
389        }
390    }
391
392    /// Apply one branch-owned exact energy map only to the newly owned
393    /// numerator fragment. The source map, when present, is authoritative;
394    /// otherwise the production selector also owns the numerator map.
395    pub(crate) fn map_numerator(
396        self,
397        graph: &Graph,
398        selector_id: OrientationID,
399        source_edge_energy_map: Option<&[LinearEnergyExpr]>,
400        numerator: &Atom,
401    ) -> Result<Atom> {
402        let orientation = self.exact_orientations()?.get(selector_id).ok_or_else(|| {
403            eyre!(
404                "missing production energy map for orientation {}",
405                selector_id.0
406            )
407        })?;
408        let replacements = source_edge_energy_map.map_or_else(
409            || orientation.energy_replacements_gs(graph),
410            |edge_energy_map| {
411                energy_map_replacements_gs(
412                    edge_energy_map.iter().map(|energy| energy.to_atom_gs(&[])),
413                    graph,
414                )
415            },
416        );
417        Ok(numerator.replace_multiple(replacements))
418    }
419}
420
421impl CutStructure {
422    pub(crate) fn empty(graph: &Graph) -> Self {
423        Self {
424            cuts: vec![CutSet::empty(graph.n_hedges())],
425        }
426    }
427}
428
429impl Approximation {
430    pub(crate) fn root(
431        &mut self,
432        graph: &mut Graph,
433        localizer: Localizer<'_>,
434        settings: &UVgenerationSettings,
435    ) -> Result<()> {
436        self.simple_approx = Some(SimpleApprox::root(self.spinney.subgraph.clone()));
437        self.local = Some(Local4dCts::root());
438        let integrated = IntegratedCts::root();
439        if let FinalIntegrandDimension::ThreeD = settings.final_integrand {
440            // The root is the original factorized 3D integrand, not a local UV
441            // approximation. Expanded-4D projection applies only to proper UV
442            // nodes and therefore must not change this identity element.
443            let direct = Direct3dCts::root(graph, localizer)?;
444            self.final_integrand = Some(
445                FinalIntegrandBuilder::new(localizer, settings).build_direct(
446                    graph,
447                    self,
448                    &direct,
449                    &integrated,
450                )?,
451            );
452            self.local_3d = Some(Local3DCts::Direct(direct));
453        }
454        self.integrated = Some(integrated);
455
456        Ok(())
457    }
458
459    pub(crate) fn new(spinney: Spinney) -> Approximation {
460        Approximation {
461            spinney,
462            topo_order: 0,
463            final_integrand: None,
464            simple_approx: None,
465            local: None,
466            local_3d: None,
467            integrated: None,
468        }
469    }
470
471    #[debug_instrument(
472        graph = %graph.log_display(),
473        current = %self.log_display(),
474        given = %dependent.log_display(),
475        reduced = ?self.reduced_subgraph(dependent),
476    )]
477    pub(crate) fn compute_4d(
478        &mut self,
479        graph: &Graph,
480        model: &Model,
481        vakint: (&Vakint, &vakint::VakintSettings),
482        dependent: &Self,
483        settings: &UVgenerationSettings,
484    ) -> Result<()> {
485        let ctx = UVCtx {
486            graph,
487            model,
488            settings,
489        };
490        debug_tags!(#generation,#uv,#fourd;
491            simple = %self.simple_display(graph),
492            "Computing 4D",
493        );
494
495        let old_full = dependent.recursion_input_4d(graph)?;
496        let local = local_4d::uv_limit(&old_full, &ctx, self, dependent, self, dependent)?;
497        let integrated = if settings.generate_integrated {
498            Integrated::new(vakint.0, vakint.1)
499                .run(&local, &ctx, self, dependent, self, dependent)?
500        } else {
501            IntegratedCts::zero_like(local.atom())?
502        };
503
504        self.local = Some(local);
505        self.integrated = Some(integrated);
506
507        Ok(())
508    }
509
510    /// Computes the 3d approximation of the UV
511    #[allow(clippy::too_many_arguments)]
512    #[debug_instrument(
513        graph = %graph.log_display(),
514        current = %self.log_display(),
515        given = %dependent.log_display(),
516    )]
517    pub(crate) fn compute_3d(
518        &mut self,
519        dependent: &Self,
520        graph: &mut Graph,
521        localizer: Localizer<'_>,
522        settings: &UVgenerationSettings,
523        projection_context: &mut Local4dProjectionContext,
524    ) -> Result<()> {
525        let (local_3d, final_integrand) =
526            if settings.local_uv_cts_from_expanded_4d_integrands {
527                let local_4d = self.local(graph)?;
528                let projected = Projected4dApproximation::new(localizer, graph, settings)
529                    .project_local_4d(local_4d, projection_context)?;
530                let final_integrand = FinalIntegrandBuilder::new(localizer, settings)
531                    .build_projected(graph, self, &projected, self.integrated(graph)?)?;
532                (Local3DCts::Projected4d(projected), final_integrand)
533            } else {
534                let parent_local = dependent.local_3d(graph)?;
535                let parent_integrated = dependent.integrated(graph)?;
536                let direct = Direct3dApproximation::new(localizer, graph, settings).run(
537                    parent_local.direct()?,
538                    parent_integrated,
539                    self,
540                    dependent,
541                    self,
542                    dependent,
543                )?;
544                let final_integrand = FinalIntegrandBuilder::new(localizer, settings)
545                    .build_direct(graph, self, &direct, self.integrated(graph)?)?;
546                (Local3DCts::Direct(direct), final_integrand)
547            };
548
549        self.final_integrand = Some(final_integrand);
550        self.local_3d = Some(local_3d);
551        Ok(())
552    }
553}
554
555#[cfg(test)]
556mod tests {
557    use std::collections::{BTreeMap, BTreeSet};
558
559    use super::*;
560    use crate::{
561        cff::CutCFFIndex,
562        finalized_runtime_dot,
563        graph::{FeynmanGraph, cuts::LuCutSelection},
564        initialisation::test_initialise,
565        integrands::{
566            evaluation::EvaluationMetaData,
567            process::{
568                GenericEvaluatorFloat,
569                evaluators::{EvaluatorStack, SingleOrAllOrientations},
570            },
571        },
572        momentum::{
573            ThreeMomentum,
574            sample::{BareMomentumSample, ExternalFourMomenta, LoopMomenta, MomentumSample},
575        },
576        numerator::symbolica_ext::NumeratorAtomExt,
577        processes::{EvaluatorSettings, cross_section::build_derivative_structure},
578        settings::RuntimeSettings,
579        utils::{
580            ArbPrec, F, FUN_LIB, FloatLike, TENSORLIB, W_, cut_energy,
581            hyperdual_utils::{DualOrNot, extract_t_derivatives_complex, simple_n_deriv_shape},
582        },
583        uv::UltravioletGraph,
584    };
585    use idenso::{
586        CookMode, CookSettings,
587        tensor::{ContractSettings, SymbolicTensor},
588    };
589    use linnet::half_edge::subgraph::subset::SubSet;
590    use spenso::{
591        algebra::{algebraic_traits::IsZero, complex::Complex},
592        network::{ExecutionResult, Sequential, SmallestDegree},
593    };
594    use symbolica::domains::dual::HyperDual;
595    use symbolica::{
596        domains::{
597            float::{Complex as SymComplex, Real},
598            integer::IntegerRing,
599            rational::{Fraction, Rational},
600        },
601        evaluate::ExpressionEvaluator,
602        parse_lit,
603    };
604
605    #[test]
606    fn expanded_4d_setting_does_not_change_the_empty_forest_root() -> Result<()> {
607        test_initialise()?;
608        let mut graph: Graph = finalized_runtime_dot!(digraph root_identity { graph [projector=1]
609            edge [num=1 mass=1]
610            node [num=1]
611
612            a -> b [id=0 lmb_id=0 source="{ufo_order:0}" sink="{ufo_order:0}"]
613            a -> b [id=1 source="{ufo_order:1}" sink="{ufo_order:1}"]
614        })?;
615        let options = graph.denominator_only_cff_3d_expression_options();
616        let canonization = graph.get_esurface_canonization(&graph.loop_momentum_basis);
617        let production = graph.generate_3d_expression_for_integrand(
618            &[],
619            &canonization,
620            &options,
621            Some(&Atom::one()),
622        )?;
623        let mut direct_graph = graph.clone();
624        let mut projected_graph = graph;
625        let cutset = CutSet::empty(direct_graph.n_hedges());
626        let orientation_pattern = OrientationPattern::default();
627        let localizer = Localizer::new(
628            &cutset,
629            OrientationProjection::exact_expression(
630                &production,
631                &options,
632                &orientation_pattern,
633                false,
634            ),
635        );
636        let mut direct = Approximation::new(Spinney::empty(&direct_graph));
637        let mut projected = Approximation::new(Spinney::empty(&projected_graph));
638        let direct_settings = UVgenerationSettings::default();
639        let projected_settings = UVgenerationSettings {
640            local_uv_cts_from_expanded_4d_integrands: true,
641            ..direct_settings.clone()
642        };
643
644        direct.root(&mut direct_graph, localizer, &direct_settings)?;
645        projected.root(&mut projected_graph, localizer, &projected_settings)?;
646
647        assert_eq!(
648            projected
649                .final_integrand(&projected_graph)?
650                .iter()
651                .collect::<BTreeMap<_, _>>(),
652            direct
653                .final_integrand(&direct_graph)?
654                .iter()
655                .collect::<BTreeMap<_, _>>(),
656            "the empty forest must preserve every finalized residue value and selector"
657        );
658        Ok(())
659    }
660
661    #[test]
662    fn selected_raised_lu_projection_preserves_quadratic_contact_family() -> Result<()> {
663        test_initialise()?;
664        let mut graph: Graph = finalized_runtime_dot!(digraph raised_lu_contact_family { graph [projector=1]
665            num = 1
666            edge [particle="scalar_1" num=1]
667            node [num=1]
668
669            v2 -> v3 [id=0 is_cut=0 initial_state_connection=true source="{ufo_order:1}" sink="{ufo_order:0}"]
670            v0 -> v1 [id=1 lmb_id=0 source="{ufo_order:0}" sink="{ufo_order:0}"]
671            v0 -> v1 [id=2 source="{ufo_order:1}" sink="{ufo_order:1}"]
672            v3 -> v0 [id=3 lmb_id=1 sink="{ufo_order:2}" source="{ufo_order:2}"]
673            v1 -> v2 [id=4 source="{ufo_order:2}" sink="{ufo_order:0}"]
674            v2 -> v3 [id=5 source="{ufo_order:2}" sink="{ufo_order:1}"]
675        }, "scalars")?;
676        let options = graph.denominator_only_cff_3d_expression_options();
677        let production_numerator =
678            GS.emr_mom(EdgeIndex(1), GS.cind(0)) * GS.emr_mom(EdgeIndex(3), GS.cind(0));
679        let canonization = graph.get_esurface_canonization(&graph.loop_momentum_basis);
680        let production = graph.generate_3d_expression_for_integrand(
681            &[],
682            &canonization,
683            &options,
684            Some(&production_numerator),
685        )?;
686        let lu_cut = graph
687            .determine_raised_esurfaces_from_expression(&production.expression)
688            .raised_groups
689            .into_iter()
690            .find(|group| {
691                group.max_occurence == 2
692                    && group.esurface_ids.iter().any(|surface_id| {
693                        !production.expression.surfaces.esurface_cache[*surface_id]
694                            .external_shift
695                            .is_empty()
696                    })
697            })
698            .expect("the repeated outer channel supplies a raised LU surface");
699        let mut cutset = CutSet::empty(graph.n_hedges());
700        cutset.residue_selector.lu = Some(LuCutSelection {
701            cut_edge_alternatives: lu_cut
702                .esurface_ids
703                .iter()
704                .map(|surface_id| {
705                    production.expression.surfaces.esurface_cache[*surface_id]
706                        .energies
707                        .clone()
708                })
709                .collect(),
710            raised_group: lu_cut,
711        });
712        let contracted = graph
713            .get_edge_subgraph(EdgeIndex(1))
714            .union(&graph.get_edge_subgraph(EdgeIndex(2)));
715        // These distinct occurrences carry the same physical four-momentum.
716        // Keep the multilinear form as an ordinary-CFF reference, and exercise
717        // a genuinely quadratic occurrence in the generalized contact source.
718        assert_eq!(
719            graph.loop_momentum_basis.edge_signatures[EdgeIndex(3)],
720            graph.loop_momentum_basis.edge_signatures[EdgeIndex(4)],
721        );
722        let multilinear_numerator = GS.emr_mom(EdgeIndex(3), GS.cind(0))
723            * GS.emr_mom(EdgeIndex(4), GS.cind(0))
724            + Atom::num(Rational::from((7, 11)));
725        let analysis_numerator =
726            GS.emr_mom(EdgeIndex(3), GS.cind(0)).pow(2) + Atom::num(Rational::from((7, 11)));
727        let contract_subgraph = contracted
728            .union(&graph.tree_edges)
729            .subtract(&graph.initial_state_cut);
730        let mut raw_graph = graph.clone();
731        let raw = raw_graph.cff(
732            &contract_subgraph,
733            &cutset,
734            &OrientationPattern::default(),
735            &options,
736            Some(&analysis_numerator),
737        )?;
738        let orientation_pattern = OrientationPattern::default();
739        let localizer = Localizer::new(
740            &cutset,
741            OrientationProjection::exact_expression(
742                &production,
743                &options,
744                &orientation_pattern,
745                true,
746            ),
747        );
748        let projected = localizer.projected_cff(
749            &mut graph,
750            &contracted,
751            [&analysis_numerator],
752            CffGenerationContext::Standalone,
753        )?;
754        let raw_expressions = raw
755            .terms
756            .iter()
757            .map(|(index, term)| {
758                (
759                    *index,
760                    term.orientations
761                        .iter()
762                        .map(|orientation| {
763                            &orientation.expression
764                                * analysis_numerator.replace_multiple(
765                                    orientation.orientation.energy_replacements_gs(&raw_graph),
766                                )
767                        })
768                        .fold(Atom::Zero, |sum, term| sum + term)
769                        * Atom::num(raw.production_prefactor_factor()),
770                )
771            })
772            .collect::<BTreeMap<_, _>>();
773        let mut denominator_only_graph = graph.clone();
774        let denominator_only = denominator_only_graph.cff(
775            &contract_subgraph,
776            &cutset,
777            &OrientationPattern::default(),
778            &options,
779            Some(&Atom::one()),
780        )?;
781        let denominator_only_expressions = denominator_only
782            .terms
783            .iter()
784            .map(|(index, term)| {
785                (
786                    *index,
787                    term.orientations
788                        .iter()
789                        .map(|orientation| {
790                            &orientation.expression
791                                * multilinear_numerator.replace_multiple(
792                                    orientation
793                                        .orientation
794                                        .energy_replacements_gs(&denominator_only_graph),
795                                )
796                        })
797                        .fold(Atom::Zero, |sum, term| sum + term)
798                        * Atom::num(denominator_only.production_prefactor_factor()),
799                )
800            })
801            .collect::<BTreeMap<_, _>>();
802        let mut projected_expressions = BTreeMap::<CutCFFIndex, Atom>::new();
803        for (orientation_id, source_edge_energy_map, integrands) in projected.iter_orientations() {
804            let mapped_numerator = localizer.map_numerator(
805                &graph,
806                orientation_id,
807                source_edge_energy_map,
808                &analysis_numerator,
809            )?;
810            for (index, expression) in integrands.iter() {
811                *projected_expressions.entry(*index).or_default() += expression * &mapped_numerator;
812            }
813        }
814        let fixed_point = |mut expression: Atom| -> Result<Atom> {
815            expression = expression
816                .replace(GS.dim)
817                .with(4)
818                .replace(GS.dim_epsilon)
819                .with(0)
820                .replace(GS.numerator_sampling_scale)
821                .with(Atom::num(Rational::from((13, 10))))
822                .replace(function!(GS.tree_denom_wrapper, W_.x_))
823                .with(W_.x_)
824                .replace(GS.den(W_.a_, W_.b_, W_.c_, W_.d_))
825                .with(W_.d_);
826            for edge in 0..graph.underlying.n_edges() {
827                let edge = EdgeIndex(edge);
828                expression = expression
829                    .replace(graph.underlying[edge].particle.mass_atom(&graph.model))
830                    .with(Atom::one())
831                    .replace(GS.ose(edge))
832                    .with(Atom::num(Rational::from((5, 4))))
833                    .replace(cut_energy(edge))
834                    .with(Atom::num(Rational::from((5, 4))))
835                    .replace(GS.emr_mom(edge, GS.cind(0)))
836                    .with(Atom::num(Rational::from((17, 7))));
837            }
838            Ok(expression)
839        };
840        let evaluate_arb = |expression: Atom| -> Result<Complex<F<ArbPrec>>> {
841            let parameters = [Atom::var(GS.pi)];
842            let rational: ExpressionEvaluator<SymComplex<Fraction<IntegerRing>>> = expression
843                .evaluator(&parameters)
844                .build()
845                .map_err(|error| eyre!("failed to build raised-contact evaluator: {error}"))?;
846            let mut arb: ExpressionEvaluator<Complex<F<ArbPrec>>> =
847                rational.map_coeff(&|coefficient| {
848                    Complex::new(F::from(&coefficient.re), F::from(&coefficient.im))
849                });
850            let zero = F(ArbPrec::default());
851            Ok(arb.evaluate_single(&[Complex::new(zero.clone().pi(), zero)]))
852        };
853        let tolerance = F(ArbPrec::default().epsilon()).sqrt().sqrt().sqrt();
854        for order in [1, 2] {
855            let index = raw_expressions
856                .keys()
857                .find(|index| index.lu_cut_order == Some(order))
858                .copied()
859                .expect("both raised orders are present");
860            let raw_value = evaluate_arb(fixed_point(raw_expressions[&index].clone())?)?;
861            let denominator_only_value =
862                evaluate_arb(fixed_point(denominator_only_expressions[&index].clone())?)?;
863            let projected_value =
864                evaluate_arb(fixed_point(projected_expressions[&index].clone())?)?;
865            let scale = raw_value
866                .clone()
867                .norm()
868                .re
869                .max(denominator_only_value.clone().norm().re)
870                .max(projected_value.clone().norm().re);
871            assert!(
872                (raw_value.clone() - &denominator_only_value).norm().re <= &tolerance * &scale,
873                "the generalized and denominator-only selected LU{order} residues differ: generalized={raw_value}, denominator-only={denominator_only_value}"
874            );
875            assert!(
876                (raw_value - projected_value).norm().re <= &tolerance * scale,
877                "production hosting changed the complete selected LU{order} residue"
878            );
879        }
880        Ok(())
881    }
882
883    #[test]
884    fn gl24_direct_3d_modes_preserve_orientation_selector_contracts() -> Result<()> {
885        test_initialise()?;
886        let mut graph: Graph = finalized_runtime_dot!(digraph gl24_selector_contract { graph [projector=1]
887            edge [num=1 mass=1]
888            node [num=1]
889
890            v0 -> v1 [id=0 is_cut=0 initial_state_connection=true source="{ufo_order:0}" sink="{ufo_order:0}"]
891            v0 -> v3 [id=1 lmb_id=0 num="(Q(1,spenso::cind(0))^2-Q(1,spenso::cind(1))^2-Q(1,spenso::cind(2))^2-Q(1,spenso::cind(3))^2)^2" source="{ufo_order:1}" sink="{ufo_order:0}"]
892            v0 -> v5 [id=2 source="{ufo_order:2}" sink="{ufo_order:0}"]
893            v1 -> v2 [id=3 lmb_id=1 source="{ufo_order:1}" sink="{ufo_order:0}"]
894            v1 -> v3 [id=4 source="{ufo_order:2}" sink="{ufo_order:1}"]
895            v2 -> v4 [id=5 lmb_id=2 source="{ufo_order:1}" sink="{ufo_order:0}"]
896            v2 -> v4 [id=6 source="{ufo_order:2}" sink="{ufo_order:1}"]
897            v3 -> v5 [id=7 source="{ufo_order:2}" sink="{ufo_order:1}"]
898            v4 -> v5 [id=8 mass=2 source="{ufo_order:2}" sink="{ufo_order:2}"]
899        })?;
900        let options = graph.denominator_only_cff_3d_expression_options();
901        let numerator = graph.production_numerator_atom_for_full_3d_expression();
902        let canonization = graph.get_esurface_canonization(&graph.loop_momentum_basis);
903        let production = graph.generate_3d_expression_for_integrand(
904            &[],
905            &canonization,
906            &options,
907            Some(&numerator),
908        )?;
909        let uv_filter = graph
910            .get_edge_subgraph(EdgeIndex(5))
911            .union(&graph.get_edge_subgraph(EdgeIndex(6)));
912        let uv_subgraph = InternalSubGraph::cleaned_filter_optimist(uv_filter, graph.as_ref());
913        let child_spinney = Spinney::new(uv_subgraph, &graph, &graph.loop_momentum_basis)?
914            .expect("the GL24 e5/e6 bubble has a compatible nonempty UV sub-LMB");
915        assert!(!child_spinney.subgraph.is_empty());
916
917        let target_support = [EdgeIndex(3), EdgeIndex(4)]
918            .into_iter()
919            .collect::<BTreeSet<_>>();
920        let lu_surface = graph
921            .determine_raised_esurfaces_from_expression(&production.expression)
922            .raised_groups
923            .into_iter()
924            .find(|group| {
925                group.esurface_ids.iter().any(|surface_id| {
926                    production.expression.surfaces.esurface_cache[*surface_id]
927                        .energies
928                        .iter()
929                        .copied()
930                        .collect::<BTreeSet<_>>()
931                        == target_support
932                })
933            })
934            .ok_or_else(|| eyre!("GL24 q3/q4 LU surface was not generated"))?;
935        let mut cutset = CutSet::empty(graph.n_hedges());
936        cutset.residue_selector.lu = Some(LuCutSelection {
937            raised_group: lu_surface,
938            cut_edge_alternatives: vec![vec![EdgeIndex(3), EdgeIndex(4)]],
939        });
940        let expected_keys = cutset
941            .residue_selector
942            .generate_allowed_keys()
943            .into_iter()
944            .collect::<BTreeSet<_>>();
945        assert_eq!(
946            expected_keys
947                .iter()
948                .filter_map(|index| index.lu_cut_order)
949                .collect::<BTreeSet<_>>(),
950            BTreeSet::from([1]),
951        );
952
953        let orientation_pattern = OrientationPattern::default();
954        let settings = UVgenerationSettings {
955            generate_integrated: false,
956            local_uv_cts_from_expanded_4d_integrands: false,
957            add_marker: false,
958            ..Default::default()
959        };
960        let check = |explicit_orientation_sum_only| -> Result<Atom> {
961            let mut route_graph = graph.clone();
962            let localizer = Localizer::new(
963                &cutset,
964                OrientationProjection::exact_expression(
965                    &production,
966                    &options,
967                    &orientation_pattern,
968                    explicit_orientation_sum_only,
969                ),
970            );
971            let mut root = Approximation::new(Spinney::empty(&route_graph));
972            root.root(&mut route_graph, localizer, &settings)?;
973            let mut child = Approximation::new(child_spinney.clone());
974            child.simple_approx = Some(
975                root.simple_approx
976                    .as_ref()
977                    .expect("the root approximation is initialized")
978                    .dependent(child.spinney.subgraph.clone()),
979            );
980            let vakint_settings = vakint::VakintSettings::default();
981            child.compute_4d(
982                &route_graph,
983                &graph.model,
984                (crate::utils::vakint()?, &vakint_settings),
985                &root,
986                &settings,
987            )?;
988            child.compute_3d(
989                &root,
990                &mut route_graph,
991                localizer,
992                &settings,
993                &mut Local4dProjectionContext::default(),
994            )?;
995            // Both direct modes Taylor-expand the same complete CFF. Check
996            // their selector contract at final assembly, after the opaque
997            // residue-map keys have been materialized.
998            let final_integrand = child
999                .final_integrand(&route_graph)?
1000                .iter()
1001                .find(|(index, _)| expected_keys.contains(index))
1002                .ok_or_else(|| eyre!("the selected GL24 residue has no final integrand"))?
1003                .1;
1004            Ok(final_integrand)
1005        };
1006        let ordinary_integrand = check(false)?;
1007        let explicit_integrand = check(true)?;
1008        assert!(!ordinary_integrand.is_zero());
1009        assert!(!explicit_integrand.is_zero());
1010
1011        let selector_atoms = production
1012            .expression
1013            .orientations
1014            .iter_enumerated()
1015            .map(|(id, _)| id.atom())
1016            .collect::<Vec<_>>();
1017        // Prove that every nonzero selector monomial is one production key.
1018        // Then summing its one-hot selections is exactly sigma=1, without
1019        // expanding 240 separately selected rational representations.
1020        for (key, coefficient) in ordinary_integrand.coefficient_list::<u8>(&selector_atoms) {
1021            if !coefficient.is_zero() {
1022                assert!(
1023                    selector_atoms.contains(&key),
1024                    "the final integrand must be homogeneous of degree one in its production selectors"
1025                );
1026                assert!(
1027                    !coefficient.contains_symbol(OrientationID::symbol()),
1028                    "selector coefficients must not contain uncatalogued production keys"
1029                );
1030            }
1031        }
1032        let ordinary_sum = ordinary_integrand
1033            .replace(function!(
1034                OrientationID::symbol(),
1035                symbolica::symbol!("gl24_selector_")
1036            ))
1037            .with(Atom::one());
1038        assert!(
1039            (ordinary_sum.collect_factors() - explicit_integrand.collect_factors()).is_zero(),
1040            "summing the orientation-local final integrand must recover the explicit final integrand"
1041        );
1042
1043        Ok(())
1044    }
1045
1046    #[test]
1047    fn nested_scalar_bubble_direct_3d_modes_match_without_a_cut() -> Result<()> {
1048        test_initialise()?;
1049        let mut graph: Graph = finalized_runtime_dot!(
1050            digraph nested_scalar_bubble_selector_contract { graph [projector=1]
1051                edge [particle="scalar_1" num="1𝑖"];
1052                node [num=1];
1053
1054                v1 -> v2 [id=0 lmb_id=0 source="{ufo_order:0}" sink="{ufo_order:0}"];
1055                v1 -> v2 [id=1 source="{ufo_order:1}" sink="{ufo_order:1}"];
1056                v2 -> v3 [id=2 lmb_id=1 source="{ufo_order:2}" sink="{ufo_order:0}"];
1057                v3 -> v1 [id=3 sink="{ufo_order:2}" source="{ufo_order:1}"];
1058            },
1059            "scalars"
1060        )?;
1061        let options = graph.denominator_only_cff_3d_expression_options();
1062        let numerator = graph.production_numerator_atom_for_full_3d_expression();
1063        let canonization = graph.get_esurface_canonization(&graph.loop_momentum_basis);
1064        let production = graph.generate_3d_expression_for_integrand(
1065            &[],
1066            &canonization,
1067            &options,
1068            Some(&numerator),
1069        )?;
1070        let uv_filter = graph
1071            .get_edge_subgraph(EdgeIndex(0))
1072            .union(&graph.get_edge_subgraph(EdgeIndex(1)));
1073        let uv_subgraph = InternalSubGraph::cleaned_filter_optimist(uv_filter, graph.as_ref());
1074        let child_spinney = Spinney::new(uv_subgraph, &graph, &graph.loop_momentum_basis)?
1075            .expect("the doubled edge is a logarithmic one-loop UV subgraph");
1076        let orientation_pattern = OrientationPattern::default();
1077        let settings = UVgenerationSettings {
1078            generate_integrated: false,
1079            add_marker: false,
1080            ..Default::default()
1081        };
1082        let build = |mut route_graph: Graph, explicit_orientation_sum_only| -> Result<_> {
1083            let cutset = CutSet::empty(route_graph.n_hedges());
1084            let localizer = Localizer::new(
1085                &cutset,
1086                OrientationProjection::exact_expression(
1087                    &production,
1088                    &options,
1089                    &orientation_pattern,
1090                    explicit_orientation_sum_only,
1091                ),
1092            );
1093            let mut root = Approximation::new(Spinney::empty(&route_graph));
1094            root.root(&mut route_graph, localizer, &settings)?;
1095            let mut child = Approximation::new(child_spinney.clone());
1096            child.simple_approx = Some(
1097                root.simple_approx
1098                    .as_ref()
1099                    .expect("the root approximation is initialized")
1100                    .dependent(child.spinney.subgraph.clone()),
1101            );
1102            child.compute_4d(
1103                &route_graph,
1104                &graph.model,
1105                (crate::utils::vakint()?, &vakint::VakintSettings::default()),
1106                &root,
1107                &settings,
1108            )?;
1109            child.compute_3d(
1110                &root,
1111                &mut route_graph,
1112                localizer,
1113                &settings,
1114                &mut Local4dProjectionContext::default(),
1115            )?;
1116            let sectors = child.local_3d(&route_graph)?.direct()?.sectors()?;
1117            let mut hosts = sectors
1118                .iter()
1119                .flat_map(|sector| sector.active.iter_keys())
1120                .filter(|(_, integrands)| {
1121                    integrands
1122                        .resolved()
1123                        .expect("diagnostic branch numerator definitions must resolve")
1124                        .iter()
1125                        .any(|(_, atom)| !atom.is_zero())
1126                })
1127                .map(|(key, _)| key.selector_host)
1128                .collect::<Vec<_>>();
1129            hosts.sort_unstable();
1130            hosts.dedup();
1131            let summarize_direct = |integrands: &DirectResidueBranches| {
1132                let mut by_host = BTreeMap::<OrientationID, Atom>::new();
1133                for (key, branch) in integrands.iter_keys() {
1134                    *by_host.entry(key.selector_host).or_default() += branch
1135                        .resolved()
1136                        .expect("diagnostic branch numerator definitions must resolve")
1137                        .iter()
1138                        .fold(Atom::Zero, |sum, (_, atom)| sum + atom);
1139                }
1140                by_host.into_iter().collect::<Vec<_>>()
1141            };
1142            let summarize_projected = |integrands: &local_3d::OrientationIntegrands| {
1143                let mut by_host = BTreeMap::<OrientationID, Atom>::new();
1144                for (host, _, branch) in integrands.iter_orientations() {
1145                    *by_host.entry(host).or_default() += branch
1146                        .resolved()
1147                        .expect("diagnostic branch numerator definitions must resolve")
1148                        .iter()
1149                        .fold(Atom::Zero, |sum, (_, atom)| sum + atom);
1150                }
1151                by_host.into_iter().collect::<Vec<_>>()
1152            };
1153            let child_branches = sectors
1154                .iter()
1155                .flat_map(|sector| summarize_direct(&sector.active))
1156                .collect::<Vec<_>>();
1157            let mut outer_branches = Vec::new();
1158            if !explicit_orientation_sum_only {
1159                for sector in sectors {
1160                    let reduced = route_graph
1161                        .full_filter()
1162                        .subtract(child.subgraph())
1163                        .subtract(&route_graph.initial_state_cut);
1164                    let resnum = route_graph
1165                        .numerator(&reduced, child.subgraph())?
1166                        .state
1167                        .expr
1168                        .multiply(route_graph.global_numerator()?)?;
1169                    let resnum = feynkit_graph::NumeratorInterface::export(&resnum).0;
1170                    let analysis_branches = sector
1171                        .active
1172                        .iter_keys()
1173                        .map(|(_, integrands)| integrands.resolved())
1174                        .collect::<Result<Vec<_>>>()?;
1175                    let analysis_numerators = analysis_branches
1176                        .iter()
1177                        .flat_map(|integrands| integrands.iter())
1178                        .map(|(_, atom)| atom * &resnum);
1179                    let outer = localizer.projected_cff(
1180                        &mut route_graph,
1181                        child.subgraph(),
1182                        analysis_numerators,
1183                        CffGenerationContext::Standalone,
1184                    )?;
1185                    outer_branches.extend(summarize_projected(&outer));
1186                }
1187            }
1188            let final_integrand = child
1189                .final_integrand(&route_graph)?
1190                .iter()
1191                .find(|(index, _)| *index == CutCFFIndex::new_all_none())
1192                .ok_or_else(|| eyre!("the scalar-bubble child has no root residue"))?
1193                .1
1194                .clone();
1195            Ok((hosts, child_branches, outer_branches, final_integrand))
1196        };
1197        let build_full_cff_oracle = |mut route_graph: Graph| -> Result<Atom> {
1198            let cutset = CutSet::empty(route_graph.n_hedges());
1199            let localizer = Localizer::new(
1200                &cutset,
1201                OrientationProjection::exact_expression(
1202                    &production,
1203                    &options,
1204                    &orientation_pattern,
1205                    false,
1206                ),
1207            );
1208            let mut root = Approximation::new(Spinney::empty(&route_graph));
1209            root.root(&mut route_graph, localizer, &settings)?;
1210            let child = Approximation::new(child_spinney.clone());
1211            let root_local = root.local_3d(&route_graph)?.direct()?.clone();
1212            let local = Direct3dApproximation::new(localizer, &mut route_graph, &settings).run(
1213                &root_local,
1214                &IntegratedCts::root(),
1215                &child,
1216                &root,
1217                &child,
1218                &root,
1219            )?;
1220            Ok(FinalIntegrandBuilder::new(localizer, &settings)
1221                .build_direct(&mut route_graph, &child, &local, &IntegratedCts::root())?
1222                .iter()
1223                .find(|(index, _)| *index == CutCFFIndex::new_all_none())
1224                .ok_or_else(|| eyre!("the full-CFF selector oracle has no root residue"))?
1225                .1)
1226        };
1227        let (ordinary_hosts, child_branches, outer_branches, ordinary) =
1228            build(graph.clone(), false)?;
1229        let (_, _, _, explicit) = build(graph.clone(), true)?;
1230        let full_cff_oracle = build_full_cff_oracle(graph.clone())?;
1231
1232        let production_map_ids = production
1233            .expression
1234            .orientations
1235            .iter_enumerated()
1236            .map(|(id, _)| id)
1237            .collect::<Vec<_>>();
1238        let ordinary_sum = production_map_ids
1239            .iter()
1240            .map(|id| id.select(ordinary.as_view()))
1241            .fold(Atom::Zero, |sum, atom| sum + atom);
1242        let full_cff_sum = production_map_ids
1243            .iter()
1244            .map(|id| id.select(full_cff_oracle.as_view()))
1245            .fold(Atom::Zero, |sum, atom| sum + atom);
1246        assert!(
1247            (&full_cff_sum - &explicit).expand().is_zero(),
1248            "the established full-CFF selector oracle must recover the explicit child sum"
1249        );
1250        let mismatched_map_keys = production_map_ids
1251            .iter()
1252            .filter_map(|id| {
1253                let ordinary = id.select(ordinary.as_view());
1254                let oracle = id.select(full_cff_oracle.as_view());
1255                let difference = (&ordinary - &oracle).expand();
1256                (!difference.is_zero()).then_some((
1257                    *id,
1258                    production.expression.orientations[*id]
1259                        .data
1260                        .orientation
1261                        .clone(),
1262                    ordinary,
1263                    oracle,
1264                    difference,
1265                ))
1266            })
1267            .collect::<Vec<_>>();
1268        assert!(
1269            (ordinary_sum - explicit).expand().is_zero(),
1270            "the isolated scalar-bubble child differs between direct local-3D modes; ordinary hosts {ordinary_hosts:?}, child branches {child_branches:?}, outer branches {outer_branches:?}, mismatched production map keys {mismatched_map_keys:?}"
1271        );
1272
1273        Ok(())
1274    }
1275
1276    #[test]
1277    fn factorized_owned_dot_child_cff_matches_direct_3d_for_uncut_self_energy() -> Result<()> {
1278        test_initialise()?;
1279        let mut graph: Graph = finalized_runtime_dot!(digraph factorized_child_cff { graph [projector=1]
1280            edge [num=1 mass="UFO::mass_scalar_1"]
1281            node [num=1]
1282            incoming [style=invis]
1283            outgoing [style=invis]
1284
1285            incoming -> v0 [id=0 sink="{ufo_order:0}"]
1286            v0 -> v1 [id=1 lmb_id=0 source="{ufo_order:1}" sink="{ufo_order:0}"]
1287            v0 -> v1 [id=2 num="Q(2,spenso::cind(0))^2-Q(2,spenso::cind(1))^2-Q(2,spenso::cind(2))^2-Q(2,spenso::cind(3))^2-UFO::mass_scalar_1^2" source="{ufo_order:2}" sink="{ufo_order:1}"]
1288            v1 -> outgoing [id=3 source="{ufo_order:2}"]
1289        }, "scalars")?;
1290        // Keep physical mass ownership symbolic during Taylor construction.
1291        // A literal 1 is also a component label and carries no mass identity.
1292        // The numerical comparison still uses the original unit-mass point.
1293        let masses = graph.get_real_mass_vector::<f64>(&graph.model);
1294        for edge in [EdgeIndex(0), EdgeIndex(1), EdgeIndex(2), EdgeIndex(3)] {
1295            assert_eq!(masses[edge], F(1.0));
1296        }
1297        let options = graph.denominator_only_cff_3d_expression_options();
1298        let numerator = graph.production_numerator_atom_for_full_3d_expression();
1299        let canonization = graph.get_esurface_canonization(&graph.loop_momentum_basis);
1300        let production = graph.generate_3d_expression_for_integrand(
1301            &[],
1302            &canonization,
1303            &options,
1304            Some(&numerator),
1305        )?;
1306        let uv_filter = graph
1307            .get_edge_subgraph(EdgeIndex(1))
1308            .union(&graph.get_edge_subgraph(EdgeIndex(2)));
1309        let uv_subgraph = InternalSubGraph::cleaned_filter_optimist(uv_filter, graph.as_ref());
1310        let child_spinney = Spinney::with_scheme(
1311            uv_subgraph,
1312            &graph,
1313            &graph.loop_momentum_basis,
1314            ApproximationType::MUV,
1315            2,
1316        )?
1317        .expect("the self-energy bubble has a compatible sub-LMB");
1318        assert_eq!(child_spinney.dod, 2);
1319        let cutset = CutSet::empty(graph.n_hedges());
1320        let orientation_pattern = OrientationPattern::default();
1321        let build = |mut route_graph: Graph, from_expanded_4d| -> Result<_> {
1322            let settings = UVgenerationSettings {
1323                generate_integrated: false,
1324                local_uv_cts_from_expanded_4d_integrands: from_expanded_4d,
1325                ..Default::default()
1326            };
1327            let bound_reports = Mutex::new(Vec::new());
1328            let localizer = Localizer::new(
1329                &cutset,
1330                OrientationProjection::exact_expression(
1331                    &production,
1332                    &options,
1333                    &orientation_pattern,
1334                    true,
1335                )
1336                .with_energy_degree_bound_reports(&bound_reports),
1337            );
1338            let mut root = Approximation::new(Spinney::empty(&route_graph));
1339            root.root(&mut route_graph, localizer, &settings)?;
1340            let root_integrand = root
1341                .final_integrand(&route_graph)?
1342                .iter()
1343                .find(|(index, _)| *index == CutCFFIndex::new_all_none())
1344                .expect("the uncut root has one residue sector")
1345                .1;
1346            let mut child = Approximation::new(child_spinney.clone());
1347            child.simple_approx = Some(
1348                root.simple_approx
1349                    .as_ref()
1350                    .expect("the root approximation is initialized")
1351                    .dependent(child.spinney.subgraph.clone()),
1352            );
1353            let vakint_settings = vakint::VakintSettings::default();
1354            child.compute_4d(
1355                &route_graph,
1356                &graph.model,
1357                (crate::utils::vakint()?, &vakint_settings),
1358                &root,
1359                &settings,
1360            )?;
1361            let projected_denominator_owners: Vec<Vec<usize>> = if from_expanded_4d {
1362                child
1363                    .local(&route_graph)?
1364                    .active_sectors()
1365                    .iter()
1366                    .map(|sector| sector.physical_terms())
1367                    .collect::<Result<Vec<_>>>()?
1368                    .into_iter()
1369                    .flatten()
1370                    .map(|term| {
1371                        term.denominators
1372                            .into_iter()
1373                            .map(|denominator| usize::from(denominator.source_edge))
1374                            .collect()
1375                    })
1376                    .collect()
1377            } else {
1378                Vec::new()
1379            };
1380            child.compute_3d(
1381                &root,
1382                &mut route_graph,
1383                localizer,
1384                &settings,
1385                &mut Local4dProjectionContext::default(),
1386            )?;
1387            let integrand = child
1388                .final_integrand(&route_graph)?
1389                .iter()
1390                .find(|(index, _)| *index == CutCFFIndex::new_all_none())
1391                .expect("the uncut self-energy has one residue sector")
1392                .1;
1393            let reports = bound_reports
1394                .lock()
1395                .unwrap_or_else(|poisoned| poisoned.into_inner())
1396                .clone();
1397            Ok((
1398                integrand,
1399                root_integrand,
1400                reports,
1401                projected_denominator_owners,
1402            ))
1403        };
1404        let (direct_expression, direct_root, direct_reports, _) = build(graph.clone(), false)?;
1405        let (
1406            projected_expression,
1407            projected_root,
1408            projected_reports,
1409            mut projected_denominator_owners,
1410        ) = build(graph.clone(), true)?;
1411        // Numerator Taylor layers may share a topology. Compare propagator
1412        // multisets without regrouping their factorized production numerators.
1413        for owners in &mut projected_denominator_owners {
1414            owners.sort_unstable();
1415        }
1416        projected_denominator_owners.sort_unstable();
1417        projected_denominator_owners.dedup();
1418        assert_eq!(
1419            projected_denominator_owners,
1420            vec![vec![1, 1, 2], vec![1, 2], vec![1, 2, 2], vec![1, 2, 2, 2]],
1421        );
1422
1423        let direct_bound = direct_reports
1424            .iter()
1425            .find(|report| {
1426                report.source_kind == crate::cff::CffEnergyBoundSourceKind::PhysicalGraph
1427                    && report.physical_parent_bounds == vec![(2, 2)]
1428            })
1429            .expect("the direct child CFF must retain its owned-dot energy bounds");
1430        assert_eq!(direct_bound.assigned_cff_source_bounds, vec![(2, 2)]);
1431        let projected_bound = projected_reports
1432            .iter()
1433            .find(|report| {
1434                report.source_kind == crate::cff::CffEnergyBoundSourceKind::ExactFourD
1435                    && report.physical_parent_bounds == vec![(2, 4)]
1436            })
1437            .expect("the quadratic numerator and two denominator derivatives retain e2 rank four");
1438        assert_eq!(
1439            projected_bound
1440                .assigned_cff_source_bounds
1441                .iter()
1442                .map(|(_, degree)| degree)
1443                .sum::<usize>(),
1444            4,
1445        );
1446
1447        // Component expansion is confined to these test copies. Production
1448        // keeps the owned-dot numerator factorized throughout construction.
1449        let normalize = |expression: Atom| {
1450            let expression = expression
1451                .replace(GS.dim)
1452                .with(4)
1453                .replace(GS.dim_epsilon)
1454                .with(0)
1455                .replace(GS.m_uv_expansion)
1456                .with(Atom::num(Rational::from((7, 5))))
1457                .replace(GS.m_uv_vacuum)
1458                .with(Atom::num(Rational::from((7, 5))))
1459                .replace(function!(GS.tree_denom_wrapper, W_.x_))
1460                .with(W_.x_)
1461                .replace(GS.den(W_.a_, W_.b_, W_.c_, W_.d_))
1462                .with(W_.d_)
1463                .replace(function!(GS.ose, W_.mass_, W_.prop_))
1464                .with(W_.prop_)
1465                .replace(function!(GS.on_shell_energy, W_.a_, W_.prop_))
1466                .with(Atom::var(W_.prop_).pow((1, 2)));
1467            let cooking = CookSettings::indices()
1468                .with_mode(CookMode::ReversibleEncoding)
1469                .with_representation_payloads(true, true);
1470            let value = SymbolicTensor::infer_indexed(
1471                cooking
1472                    .try_cook(expression.as_view())
1473                    .expect("test-only index admission must succeed"),
1474            )
1475            .expect("test-only tensor admission must succeed")
1476            .contract(ContractSettings {
1477                collect_chains: false,
1478                collect_traces: false,
1479                ..Default::default()
1480            })
1481            .expect("test-only contraction must succeed")
1482            .expand_dots()
1483            .expect("test-only component expansion must succeed");
1484            cooking.uncook(value.expression().as_view())
1485        };
1486        let expressions = vec![
1487            normalize(direct_expression),
1488            normalize(projected_expression),
1489            normalize(direct_root),
1490            normalize(projected_root),
1491        ];
1492        assert_eq!(graph.loop_momentum_basis.loop_edges.len(), 1);
1493        assert_eq!(graph.loop_momentum_basis.ext_edges.len(), 2);
1494        let rational =
1495            |numerator, denominator| F::<ArbPrec>::from(&Rational::from((numerator, denominator)));
1496        let loop_moms: LoopMomenta<F<ArbPrec>> = [ThreeMomentum::new(
1497            rational(31, 100),
1498            rational(-47, 100),
1499            rational(83, 100),
1500        )]
1501        .into_iter()
1502        .collect();
1503        let external_moms: ExternalFourMomenta<F<ArbPrec>> = [
1504            [
1505                rational(12, 5),
1506                rational(0, 1),
1507                rational(0, 1),
1508                rational(0, 1),
1509            ]
1510            .into(),
1511            [
1512                rational(-12, 5),
1513                rational(0, 1),
1514                rational(0, 1),
1515                rational(0, 1),
1516            ]
1517            .into(),
1518        ]
1519        .into_iter()
1520        .collect();
1521        let sample = MomentumSample {
1522            sample: BareMomentumSample {
1523                loop_moms: loop_moms.clone(),
1524                dual_loop_moms: None,
1525                loop_mom_cache_id: 0,
1526                loop_mom_base_cache_id: 0,
1527                external_moms,
1528                external_mom_cache_id: 0,
1529                external_mom_base_cache_id: 0,
1530                external_rotations: Vec::new(),
1531                jacobian: rational(1, 1),
1532                orientation: None,
1533                parameterization_branch: None,
1534            },
1535        };
1536        let orientations = TiVec::<OrientationID, EdgeVec<Orientation>>::new();
1537        let orientation_filter = SubSet::full(orientations.len());
1538        let mut param_builder = graph.param_builder.clone();
1539        let (mut evaluator, _) = EvaluatorStack::new_explicit_sum_with_timings(
1540            &expressions,
1541            &param_builder,
1542            &[],
1543            None,
1544            &EvaluatorSettings::default(),
1545        )?;
1546        let input = <ArbPrec as GenericEvaluatorFloat>::get_parameters(
1547            &mut param_builder,
1548            (false, false),
1549            &graph,
1550            &sample,
1551            &[],
1552            &[],
1553            None,
1554            None,
1555            None,
1556        );
1557        let values = evaluator
1558            .evaluate(
1559                input,
1560                SingleOrAllOrientations::All {
1561                    all: &orientations,
1562                    filter: &orientation_filter,
1563                },
1564                &RuntimeSettings::default(),
1565                &mut EvaluationMetaData::new_empty(),
1566            )?
1567            .into_iter()
1568            .map(|value| value.unwrap_real())
1569            .collect::<Vec<_>>();
1570        let distance = (values[0].clone() - values[1].clone()).norm().re;
1571        let direct_norm = values[0].clone().norm().re;
1572        let projected_norm = values[1].clone().norm().re;
1573        let scale = if direct_norm > projected_norm {
1574            direct_norm
1575        } else {
1576            projected_norm
1577        };
1578        let relative_distance = if scale.is_zero() {
1579            distance
1580        } else {
1581            distance / scale
1582        };
1583        let tolerance = F(ArbPrec::default().epsilon()).sqrt().sqrt().sqrt();
1584        assert!(
1585            relative_distance <= tolerance,
1586            "kinematically consistent owned-dot self-energy mismatch: direct={:e}, projected={:e}, relative delta={relative_distance:e}, tolerance={tolerance:e}",
1587            values[0],
1588            values[1],
1589        );
1590        Ok(())
1591    }
1592
1593    #[test]
1594    fn direct_nested_scalar_banana_replays_complete_cff_at_depth_three() -> Result<()> {
1595        test_initialise()?;
1596        for depth in [2, 3] {
1597            let mut graph: Graph = if depth == 2 {
1598                finalized_runtime_dot!(digraph nested_scalar_banana { graph [projector=1]
1599                    edge [num=1 mass=1]
1600                    node [num=1]
1601                    incoming [style=invis]
1602                    outgoing [style=invis]
1603
1604                    incoming -> a [id=0 sink="{ufo_order:3}"]
1605                    a -> b [id=1 lmb_id=0 source="{ufo_order:0}" sink="{ufo_order:0}"]
1606                    a -> b [id=2 lmb_id=1 source="{ufo_order:1}" sink="{ufo_order:1}"]
1607                    a -> b [id=3 source="{ufo_order:2}" sink="{ufo_order:2}"]
1608                    b -> outgoing [id=4 source="{ufo_order:3}"]
1609                })?
1610            } else {
1611                finalized_runtime_dot!(digraph depth_three_scalar_banana { graph [projector=1]
1612                    edge [num=1 mass=1]
1613                    node [num=1]
1614                    incoming [style=invis]
1615                    outgoing [style=invis]
1616
1617                    incoming -> a [id=0 sink="{ufo_order:4}"]
1618                    a -> b [id=1 lmb_id=0 source="{ufo_order:0}" sink="{ufo_order:0}"]
1619                    a -> b [id=2 lmb_id=1 source="{ufo_order:1}" sink="{ufo_order:1}"]
1620                    a -> b [id=3 lmb_id=2 source="{ufo_order:2}" sink="{ufo_order:2}"]
1621                    a -> b [id=4 source="{ufo_order:3}" sink="{ufo_order:3}"]
1622                    b -> outgoing [id=5 source="{ufo_order:4}"]
1623                })?
1624            };
1625            let global_marker = symbolica::symbol!("nested_scalar_banana::global");
1626            graph.global_prefactor.num =
1627                crate::numerator::AppliedFeynmanRule::new(Atom::var(global_marker))?.expr;
1628
1629            let mut filter = graph.get_edge_subgraph(EdgeIndex(1));
1630            let mut spinneys = Vec::new();
1631            for edge in 2..=depth + 1 {
1632                filter = filter.union(&graph.get_edge_subgraph(EdgeIndex(edge)));
1633                let subgraph =
1634                    InternalSubGraph::cleaned_filter_optimist(filter.clone(), graph.as_ref());
1635                spinneys.push(
1636                    Spinney::new(subgraph, &graph, &graph.loop_momentum_basis)?
1637                        .expect("each nested banana has a compatible sub-LMB"),
1638                );
1639            }
1640
1641            let options = graph.denominator_only_cff_3d_expression_options();
1642            let numerator = graph.production_numerator_atom_for_full_3d_expression();
1643            let canonization = graph.get_esurface_canonization(&graph.loop_momentum_basis);
1644            let production = graph.generate_3d_expression_for_integrand(
1645                &[],
1646                &canonization,
1647                &options,
1648                Some(&numerator),
1649            )?;
1650            let cutset = CutSet::empty(graph.n_hedges());
1651            let orientation_pattern = OrientationPattern::default();
1652
1653            let build = |mut route_graph: Graph, from_expanded_4d| -> Result<Vec<Atom>> {
1654                let settings = UVgenerationSettings {
1655                    generate_integrated: false,
1656                    local_uv_cts_from_expanded_4d_integrands: from_expanded_4d,
1657                    ..Default::default()
1658                };
1659                let localizer = Localizer::new(
1660                    &cutset,
1661                    OrientationProjection::exact_expression(
1662                        &production,
1663                        &options,
1664                        &orientation_pattern,
1665                        true,
1666                    ),
1667                );
1668                let vakint_settings = vakint::VakintSettings::default();
1669                let mut root = Approximation::new(Spinney::empty(&route_graph));
1670                root.root(&mut route_graph, localizer, &settings)?;
1671
1672                let mut parent = root;
1673                let mut finals = Vec::new();
1674                for spinney in &spinneys {
1675                    let mut current = Approximation::new(spinney.clone());
1676                    current.simple_approx = Some(
1677                        parent
1678                            .simple_approx
1679                            .as_ref()
1680                            .expect("the parent approximation is initialized")
1681                            .dependent(current.spinney.subgraph.clone()),
1682                    );
1683                    current.compute_4d(
1684                        &route_graph,
1685                        &graph.model,
1686                        (crate::utils::vakint()?, &vakint_settings),
1687                        &parent,
1688                        &settings,
1689                    )?;
1690                    current.compute_3d(
1691                        &parent,
1692                        &mut route_graph,
1693                        localizer,
1694                        &settings,
1695                        &mut Local4dProjectionContext::default(),
1696                    )?;
1697                    let local = current.local_3d(&route_graph)?;
1698                    if let Local3DCts::Direct(direct) = local {
1699                        let value = direct.branches()?.factorized_sum();
1700                        assert!(
1701                            !value.contains_symbol(global_marker),
1702                            "the untouched global numerator stays outside every local Taylor operation"
1703                        );
1704                        let negated = (-local.clone()).map(|atom| Ok(atom.clone()))?;
1705                        assert!(
1706                            (negated.direct()?.branches()?.factorized_sum() + value)
1707                                .expand()
1708                                .is_zero(),
1709                            "mapping a negated forest must negate its complete materialized value"
1710                        );
1711                    }
1712                    let final_integrand = current
1713                        .final_integrand(&route_graph)?
1714                        .iter()
1715                        .find(|(index, _)| *index == CutCFFIndex::new_all_none())
1716                        .ok_or_else(|| eyre!("the nested banana has no uncut final integrand"))?
1717                        .1
1718                        .clone();
1719                    assert!(
1720                        !final_integrand.contains_symbol(OrientationID::symbol()),
1721                        "explicit final assembly must have summed all selectors"
1722                    );
1723                    let without_global = final_integrand.replace(global_marker).with(1);
1724                    assert!(
1725                        !without_global.is_zero(),
1726                        "the subtraction fixture must be nonzero"
1727                    );
1728                    assert!(
1729                        (&final_integrand - Atom::var(global_marker) * without_global)
1730                            .expand()
1731                            .is_zero(),
1732                        "final assembly restores the outside global numerator exactly once"
1733                    );
1734                    finals.push(final_integrand);
1735                    parent = current;
1736                }
1737                Ok(finals)
1738            };
1739
1740            let direct = build(graph.clone(), false)?;
1741            let projected = build(graph.clone(), true)?;
1742            // Test-only component expansion makes the independently constructed
1743            // expressions evaluable by one Arb stack. Production keeps all
1744            // numerator factors intact throughout CFF and UV construction.
1745            let normalize = |expression: Atom| {
1746                let expression = expression
1747                    .replace(global_marker)
1748                    .with(1)
1749                    .replace(GS.dim)
1750                    .with(4)
1751                    .replace(GS.dim_epsilon)
1752                    .with(0)
1753                    .replace(GS.m_uv_expansion)
1754                    .with(Atom::num(Rational::from((7, 5))))
1755                    .replace(GS.m_uv_vacuum)
1756                    .with(Atom::num(Rational::from((7, 5))))
1757                    .replace(function!(GS.tree_denom_wrapper, W_.x_))
1758                    .with(W_.x_)
1759                    .replace(GS.den(W_.a_, W_.b_, W_.c_, W_.d_))
1760                    .with(W_.d_)
1761                    .replace(function!(GS.ose, W_.mass_, W_.prop_))
1762                    .with(W_.prop_)
1763                    .replace(function!(GS.on_shell_energy, W_.a_, W_.prop_))
1764                    .with(Atom::var(W_.prop_).pow((1, 2)));
1765                let cooking = CookSettings::indices()
1766                    .with_mode(CookMode::ReversibleEncoding)
1767                    .with_representation_payloads(true, true);
1768                let value = SymbolicTensor::infer_indexed(
1769                    cooking
1770                        .try_cook(expression.as_view())
1771                        .expect("test-only index admission must succeed"),
1772                )
1773                .expect("test-only tensor admission must succeed")
1774                .contract(ContractSettings {
1775                    collect_chains: false,
1776                    collect_traces: false,
1777                    ..Default::default()
1778                })
1779                .expect("test-only contraction must succeed")
1780                .expand_dots()
1781                .expect("test-only component expansion must succeed");
1782                cooking.uncook(value.expression().as_view())
1783            };
1784            let expressions = direct
1785                .into_iter()
1786                .zip(projected)
1787                .flat_map(|(direct, projected)| [normalize(direct), normalize(projected)])
1788                .collect::<Vec<_>>();
1789
1790            let rational = |numerator, denominator| {
1791                F::<ArbPrec>::from(&Rational::from((numerator, denominator)))
1792            };
1793            let loop_moms: LoopMomenta<F<ArbPrec>> = [
1794                ThreeMomentum::new(rational(31, 100), rational(-47, 100), rational(83, 100)),
1795                ThreeMomentum::new(rational(-19, 100), rational(37, 100), rational(61, 100)),
1796                ThreeMomentum::new(rational(43, 100), rational(29, 100), rational(-53, 100)),
1797            ]
1798            .into_iter()
1799            .take(depth)
1800            .collect();
1801            let external_moms: ExternalFourMomenta<F<ArbPrec>> = [
1802                [
1803                    rational(12, 5),
1804                    rational(11, 100),
1805                    rational(-8, 100),
1806                    rational(5, 100),
1807                ]
1808                .into(),
1809                [
1810                    rational(-12, 5),
1811                    rational(-11, 100),
1812                    rational(8, 100),
1813                    rational(-5, 100),
1814                ]
1815                .into(),
1816            ]
1817            .into_iter()
1818            .collect();
1819            let sample = MomentumSample {
1820                sample: BareMomentumSample {
1821                    loop_moms,
1822                    dual_loop_moms: None,
1823                    loop_mom_cache_id: 0,
1824                    loop_mom_base_cache_id: 0,
1825                    external_moms,
1826                    external_mom_cache_id: 0,
1827                    external_mom_base_cache_id: 0,
1828                    external_rotations: Vec::new(),
1829                    jacobian: rational(1, 1),
1830                    orientation: None,
1831                    parameterization_branch: None,
1832                },
1833            };
1834            let orientations = TiVec::<OrientationID, EdgeVec<Orientation>>::new();
1835            let orientation_filter = SubSet::full(orientations.len());
1836            let mut param_builder = graph.param_builder.clone();
1837            let (mut evaluator, _) = EvaluatorStack::new_explicit_sum_with_timings(
1838                &expressions,
1839                &param_builder,
1840                &[],
1841                None,
1842                &EvaluatorSettings::default(),
1843            )?;
1844            let input = <ArbPrec as GenericEvaluatorFloat>::get_parameters(
1845                &mut param_builder,
1846                (false, false),
1847                &graph,
1848                &sample,
1849                &[],
1850                &[],
1851                None,
1852                None,
1853                None,
1854            );
1855            let values = evaluator
1856                .evaluate(
1857                    input,
1858                    SingleOrAllOrientations::All {
1859                        all: &orientations,
1860                        filter: &orientation_filter,
1861                    },
1862                    &RuntimeSettings::default(),
1863                    &mut EvaluationMetaData::new_empty(),
1864                )?
1865                .into_iter()
1866                .map(|value| value.unwrap_real())
1867                .collect::<Vec<_>>();
1868            let tolerance = F(ArbPrec::default().epsilon()).sqrt().sqrt().sqrt();
1869            for (stage, [direct, projected]) in values.as_chunks::<2>().0.iter().enumerate() {
1870                let label = format!("depth {depth}, stage {}", stage + 1);
1871                assert!(
1872                    [&direct.re, &direct.im, &projected.re, &projected.im]
1873                        .into_iter()
1874                        .all(symbolica::domains::float::SingleFloat::is_finite),
1875                    "{label} must produce finite values: direct={direct:e}, projected={projected:e}"
1876                );
1877                let distance = (direct.clone() - projected.clone()).norm().re;
1878                let direct_norm = direct.clone().norm().re;
1879                let projected_norm = projected.clone().norm().re;
1880                let scale = if direct_norm > projected_norm {
1881                    direct_norm
1882                } else {
1883                    projected_norm
1884                };
1885                let relative_distance = if scale.is_zero() {
1886                    distance
1887                } else {
1888                    distance / scale
1889                };
1890                assert!(
1891                    relative_distance <= tolerance,
1892                    "{label} direct complete-CFF vs projected local-4D mismatch: direct={direct:e}, projected={projected:e}, relative delta={relative_distance:e}, tolerance={tolerance:e}"
1893                );
1894            }
1895        }
1896        Ok(())
1897    }
1898
1899    #[test]
1900    fn complete_self_energy_taylor_sum_matches_direct_3d_for_raised_lu_jets() -> Result<()> {
1901        test_initialise()?;
1902        let base_graph: Graph = finalized_runtime_dot!(
1903            digraph complete_self_energy_taylor_sum { graph [projector=1]
1904                num = 1
1905                edge [particle="scalar_1" num=1]
1906                node [num=1]
1907
1908                v2 -> v3 [id=0 is_cut=0 initial_state_connection=true source="{ufo_order:1}" sink="{ufo_order:0}"]
1909                v0 -> v1 [id=1 lmb_id=0 num="Q(1,spenso::mink(4,1))" source="{ufo_order:0}" sink="{ufo_order:0}"]
1910                v0 -> v1 [id=2 source="{ufo_order:1}" sink="{ufo_order:1}"]
1911                v3 -> v0 [id=3 lmb_id=1 num="Q(3,spenso::mink(4,1))" sink="{ufo_order:2}" source="{ufo_order:2}"]
1912                v1 -> v2 [id=4 source="{ufo_order:2}" sink="{ufo_order:0}"]
1913                v2 -> v3 [id=5 source="{ufo_order:2}" sink="{ufo_order:1}"]
1914            },
1915            "scalars"
1916        )?;
1917        assert_eq!(
1918            base_graph.loop_momentum_basis.edge_signatures[EdgeIndex(3)],
1919            base_graph.loop_momentum_basis.edge_signatures[EdgeIndex(4)],
1920            "the GL0-like cograph must expose a genuinely repeated outer channel"
1921        );
1922
1923        let outer_factors = [
1924            "unit outer numerator",
1925            "factorized cubic outer numerator",
1926            "factorized affine cubic outer numerator",
1927        ];
1928        for outer_label in outer_factors {
1929            let mut graph = base_graph.clone();
1930            graph.underlying = graph.underlying.map_data_ref(
1931                |_, _, vertex| {
1932                    let mut vertex = vertex.clone();
1933                    if outer_label == "factorized affine cubic outer numerator"
1934                        && vertex.name.value == "v2"
1935                    {
1936                        let factor = GS.emr_mom(EdgeIndex(5), GS.cind(0))
1937                            + GS.emr_mom(EdgeIndex(0), GS.cind(0));
1938                        vertex.num.value = vertex
1939                            .num
1940                            .value
1941                            .with_checked_expression(vertex.num.value.expression() * factor)
1942                            .expect("scalar vertex factors preserve the source tensor interface");
1943                    }
1944                    vertex
1945                },
1946                |_, edge, _, data| {
1947                    data.map(|data| {
1948                        let mut data = data.clone();
1949                        let factor = match (outer_label, edge) {
1950                            ("factorized cubic outer numerator", EdgeIndex(3..=5)) => {
1951                                GS.emr_mom(edge, GS.cind(0))
1952                            }
1953                            ("factorized affine cubic outer numerator", EdgeIndex(3 | 5)) => {
1954                                GS.emr_mom(edge, GS.cind(0))
1955                            }
1956                            _ => Atom::one(),
1957                        };
1958                        data.num.value = data
1959                            .num
1960                            .value
1961                            .with_checked_expression(data.num.value.expression() * factor)
1962                            .expect("scalar edge factors preserve the source tensor interface");
1963                        data
1964                    })
1965                },
1966                |_, data| data.clone(),
1967            );
1968            let options = graph.denominator_only_cff_3d_expression_options();
1969            let numerator = graph.production_numerator_atom_for_full_3d_expression();
1970            let canonization = graph.get_esurface_canonization(&graph.loop_momentum_basis);
1971            let production = graph.generate_3d_expression_for_integrand(
1972                &[],
1973                &canonization,
1974                &options,
1975                Some(&numerator),
1976            )?;
1977            let lu_cut = graph
1978                .determine_raised_esurfaces_from_expression(&production.expression)
1979                .raised_groups
1980                .into_iter()
1981                .find(|group| {
1982                    group.max_occurence > 1
1983                        && group.esurface_ids.iter().any(|surface_id| {
1984                            !production.expression.surfaces.esurface_cache[*surface_id]
1985                                .external_shift
1986                                .is_empty()
1987                        })
1988                })
1989                .expect("the repeated outer channel must supply a physical raised LU surface");
1990            assert_eq!(
1991                lu_cut.max_occurence, 2,
1992                "the GL0-like cograph must expose LU orders one and two"
1993            );
1994            let mut cutset = CutSet::empty(graph.n_hedges());
1995            cutset.residue_selector.lu = Some(LuCutSelection {
1996                raised_group: lu_cut.clone(),
1997                cut_edge_alternatives: lu_cut
1998                    .esurface_ids
1999                    .iter()
2000                    .map(|surface_id| {
2001                        production.expression.surfaces.esurface_cache[*surface_id]
2002                            .energies
2003                            .clone()
2004                    })
2005                    .collect(),
2006            });
2007            let uv_filter = graph
2008                .get_edge_subgraph(EdgeIndex(1))
2009                .union(&graph.get_edge_subgraph(EdgeIndex(2)));
2010            let uv_subgraph = InternalSubGraph::cleaned_filter_optimist(uv_filter, graph.as_ref());
2011            let child_spinney = Spinney::with_scheme(
2012                uv_subgraph,
2013                &graph,
2014                &graph.loop_momentum_basis,
2015                ApproximationType::MUV,
2016                1,
2017            )?
2018            .expect("the self-energy bubble has a compatible sub-LMB");
2019            let orientation_pattern = OrientationPattern::default();
2020
2021            let build_child = |mut route_graph: Graph,
2022                               route_cutset: &CutSet,
2023                               local_uv_cts_from_expanded_4d_integrands|
2024             -> Result<BTreeMap<CutCFFIndex, Atom>> {
2025                let settings = UVgenerationSettings {
2026                    generate_integrated: false,
2027                    local_uv_cts_from_expanded_4d_integrands,
2028                    ..Default::default()
2029                };
2030                let localizer = Localizer::new(
2031                    route_cutset,
2032                    OrientationProjection::exact_expression(
2033                        &production,
2034                        &options,
2035                        &orientation_pattern,
2036                        true,
2037                    ),
2038                );
2039                let mut root = Approximation::new(Spinney::empty(&route_graph));
2040                root.root(&mut route_graph, localizer, &settings)?;
2041                let mut child = Approximation::new(child_spinney.clone());
2042                child.simple_approx = Some(
2043                    root.simple_approx
2044                        .as_ref()
2045                        .expect("the root approximation is initialized")
2046                        .dependent(child.spinney.subgraph.clone()),
2047                );
2048                let vakint_settings = vakint::VakintSettings::default();
2049                child.compute_4d(
2050                    &route_graph,
2051                    &graph.model,
2052                    (crate::utils::vakint()?, &vakint_settings),
2053                    &root,
2054                    &settings,
2055                )?;
2056                // The complete Taylor value keeps the natural propagator
2057                // powers, factorized numerator, and physical edge owners.
2058                let reduced = child.reduced_subgraph(&root);
2059                let t_arg = route_graph
2060                    .numerator(&reduced, root.subgraph())?
2061                    .to_d_dim(GS.dim)?
2062                    .get_single_atom()
2063                    .expect("the scalar child numerator is available")
2064                    / route_graph.denominator(&reduced, &graph.model, |_| 1);
2065                let explicit_taylor_sum = route_graph
2066                    .uv_rescaled(
2067                        &reduced,
2068                        route_graph.n_loops(child.subgraph()),
2069                        child.lmb(),
2070                        child.lmb(),
2071                        &t_arg,
2072                    )
2073                    .series(GS.rescale, Atom::Zero, 0)
2074                    .expect("the scalar child Taylor series exists")
2075                    .to_atom()
2076                    .replace(GS.rescale)
2077                    .with(Atom::one());
2078                let cooking = CookSettings::indices()
2079                    .with_mode(CookMode::ReversibleEncoding)
2080                    .with_representation_payloads(true, true);
2081                let explicit_taylor_sum = SymbolicTensor::infer_indexed(
2082                    cooking.try_cook(explicit_taylor_sum.as_view())?,
2083                )?
2084                .contract(ContractSettings {
2085                    collect_chains: false,
2086                    collect_traces: false,
2087                    ..Default::default()
2088                })?
2089                .to_dots()?;
2090                let explicit_taylor_sum =
2091                    cooking.uncook(explicit_taylor_sum.expression().as_view());
2092                let local_atom =
2093                    cooking.uncook(child.local(&route_graph)?.atom().expression().as_view());
2094                assert!(
2095                    (local_atom.collect_factors() + explicit_taylor_sum.collect_factors())
2096                        .is_zero(),
2097                    "the local counterterm must equal the negative independently reconstructed Taylor sum"
2098                );
2099                child.compute_3d(
2100                    &root,
2101                    &mut route_graph,
2102                    localizer,
2103                    &settings,
2104                    &mut Local4dProjectionContext::default(),
2105                )?;
2106                Ok(child.final_integrand(&route_graph)?.iter().collect())
2107            };
2108            let direct = build_child(graph.clone(), &cutset, false)?;
2109            let expanded = build_child(graph.clone(), &cutset, true)?;
2110            let expected_orders = BTreeSet::from([1, 2]);
2111            assert_eq!(
2112                direct
2113                    .keys()
2114                    .filter_map(|index| index.lu_cut_order)
2115                    .collect::<BTreeSet<_>>(),
2116                expected_orders,
2117                "the direct child must retain both raised LU orders"
2118            );
2119            assert_eq!(
2120                direct.keys().collect::<Vec<_>>(),
2121                expanded.keys().collect::<Vec<_>>(),
2122                "the two routes must finalize the same residue sectors"
2123            );
2124
2125            let mass_squared = Atom::num(Rational::from((4, 9)));
2126            let m_uv = Atom::num(Rational::from((7, 5)));
2127            let base_spatial_momentum = |edge: EdgeIndex| match usize::from(edge) {
2128                1 => Atom::num(Rational::from((4, 3))),
2129                2 => Atom::num(Rational::from((-7, 12))),
2130                3..=5 => Atom::num(Rational::from((3, 4))),
2131                _ => Atom::Zero,
2132            };
2133            let scaled_on_shell_energy = |edge: EdgeIndex, rescale: Atom| {
2134                (mass_squared.clone() + (base_spatial_momentum(edge) * rescale).pow(2)).sqrt()
2135            };
2136            let representative =
2137                &production.expression.surfaces.esurface_cache[lu_cut.esurface_ids[0]];
2138            let root_energy_sum = representative
2139                .energies
2140                .iter()
2141                .map(|edge| scaled_on_shell_energy(*edge, Atom::one()))
2142                .fold(Atom::Zero, |sum, energy| sum + energy);
2143            let external_shift_coefficient = representative
2144                .external_shift
2145                .iter()
2146                .map(|(_, coefficient)| *coefficient)
2147                .sum::<i64>();
2148            assert_ne!(
2149                external_shift_coefficient, 0,
2150                "the selected raised LU surface must have a nonzero external shift"
2151            );
2152            let external_energy = -root_energy_sum / Atom::num(external_shift_coefficient);
2153            let external_edges = graph
2154                .external_momentum_edge_order()
2155                .into_iter()
2156                .collect::<BTreeSet<_>>();
2157            let scalarize = |expression: Atom| -> Result<Atom> {
2158                // Contract finite tensor components, including products of indexed
2159                // sums, without distributing the numerator. The independent oracle
2160                // below supplies its own coordinates and Arb jets; it shares tensor
2161                // contraction, but not EvaluatorStack lowering or parameter layout.
2162                let mut network = expression.parse_into_net()?;
2163                network.execute::<Sequential, SmallestDegree, _, _, _>(
2164                    &*TENSORLIB.read().unwrap(),
2165                    &*FUN_LIB,
2166                )?;
2167                Ok(match network.result_scalar()? {
2168                    ExecutionResult::One => Atom::one(),
2169                    ExecutionResult::Zero => Atom::Zero,
2170                    ExecutionResult::Val(value) => value.into_owned(),
2171                })
2172            };
2173            let rescale_expression = |mut expression: Atom| -> Result<Atom> {
2174                expression = expression.replace(GS.dim).with(4);
2175                let cooking = CookSettings::indices()
2176                    .with_mode(CookMode::ReversibleEncoding)
2177                    .with_representation_payloads(true, true);
2178                let value = SymbolicTensor::infer_indexed(cooking.try_cook(expression.as_view())?)?
2179                    .contract(ContractSettings {
2180                        collect_chains: false,
2181                        collect_traces: false,
2182                        ..Default::default()
2183                    })?
2184                    .expand_dots()?;
2185                expression = cooking.uncook(value.expression().as_view());
2186                let rescale = Atom::var(GS.rescale);
2187                let compact_minkowski = parse_lit!(spenso::mink(4));
2188                let time_direction =
2189                    function!(GS.delta_vec, GS.cind(0), compact_minkowski.as_view());
2190                expression = expression
2191                    .replace(function!(
2192                        GS.dot,
2193                        time_direction.as_view(),
2194                        time_direction.as_view()
2195                    ))
2196                    .with(Atom::one());
2197                for left in 0..graph.underlying.n_edges() {
2198                    let left = EdgeIndex(left);
2199                    let left_spatial = if !external_edges.contains(&left) {
2200                        base_spatial_momentum(left) * &rescale
2201                    } else {
2202                        Atom::Zero
2203                    };
2204                    for right in left.0..graph.underlying.n_edges() {
2205                        let right = EdgeIndex(right);
2206                        let right_spatial = if !external_edges.contains(&right) {
2207                            base_spatial_momentum(right) * &rescale
2208                        } else {
2209                            Atom::Zero
2210                        };
2211                        expression = expression
2212                            .replace(function!(
2213                                GS.dot,
2214                                GS.emr_vec(left, compact_minkowski.as_view()),
2215                                GS.emr_vec(right, compact_minkowski.as_view())
2216                            ))
2217                            .with(-&left_spatial * right_spatial);
2218                    }
2219                    expression = expression
2220                        .replace(function!(
2221                            GS.dot,
2222                            time_direction.as_view(),
2223                            GS.emr_vec(left, compact_minkowski.as_view())
2224                        ))
2225                        .with(Atom::Zero);
2226                }
2227                expression = expression
2228                    .replace(Atom::var(GS.m_uv_expansion))
2229                    .with(m_uv.clone())
2230                    .replace(Atom::var(GS.m_uv_vacuum))
2231                    .with(m_uv.clone())
2232                    .replace(Atom::var(GS.integrated_loop_scale))
2233                    .with(Atom::one())
2234                    .replace(function!(GS.tree_denom_wrapper, W_.x_))
2235                    .with(W_.x_)
2236                    .replace(GS.den(W_.a_, W_.b_, W_.c_, W_.d_))
2237                    .with(W_.d_);
2238                expression = scalarize(expression)?;
2239                for edge in 0..graph.underlying.n_edges() {
2240                    let edge = EdgeIndex(edge);
2241                    expression = expression
2242                        .replace(graph.underlying[edge].particle.mass_atom(&graph.model))
2243                        .with(mass_squared.clone().sqrt());
2244                    if external_edges.contains(&edge) {
2245                        expression = expression
2246                            .replace(GS.emr_mom(edge, GS.cind(0)))
2247                            .with(external_energy.clone());
2248                        for spatial_index in 1..=3 {
2249                            expression = expression
2250                                .replace(GS.emr_mom(edge, GS.cind(spatial_index)))
2251                                .with(Atom::Zero)
2252                                .replace(GS.emr_vec(edge, GS.cind(spatial_index)))
2253                                .with(Atom::Zero);
2254                        }
2255                    } else {
2256                        let on_shell_energy = scaled_on_shell_energy(edge, rescale.clone());
2257                        expression = expression
2258                            .replace(GS.emr_mom(edge, GS.cind(1)))
2259                            .with(base_spatial_momentum(edge) * &rescale)
2260                            .replace(GS.emr_vec(edge, GS.cind(1)))
2261                            .with(base_spatial_momentum(edge) * &rescale)
2262                            .replace(GS.ose(edge))
2263                            .with(on_shell_energy.clone())
2264                            .replace(cut_energy(edge))
2265                            .with(on_shell_energy);
2266                        for spatial_index in 2..=3 {
2267                            expression = expression
2268                                .replace(GS.emr_mom(edge, GS.cind(spatial_index)))
2269                                .with(Atom::Zero)
2270                                .replace(GS.emr_vec(edge, GS.cind(spatial_index)))
2271                                .with(Atom::Zero);
2272                        }
2273                    }
2274                }
2275                Ok(expression)
2276            };
2277            let eta = rescale_expression(representative.to_atom(&[]))?;
2278            assert!(
2279                eta.replace(GS.rescale).with(Atom::one()).expand().is_zero(),
2280                "the comparison point must lie on the selected raised LU surface"
2281            );
2282            let value_and_t_derivative = |expression: Atom| -> Result<[Atom; 2]> {
2283                let series = rescale_expression(expression)?
2284                    .series(GS.rescale, Atom::one(), 1)
2285                    .map_err(|error| eyre!("failed to build raised-LU child t jet: {error}"))?;
2286                Ok([
2287                    series
2288                        .coefficient(Rational::from(0))
2289                        .expect("requested coefficient is within series precision"),
2290                    series
2291                        .coefficient(Rational::from(1))
2292                        .expect("requested coefficient is within series precision"),
2293                ])
2294            };
2295            let evaluate_arb = |expression: Atom| -> Result<Complex<F<ArbPrec>>> {
2296                let expression = expression
2297                    .replace(function!(GS.on_shell_energy, W_.a_, W_.prop_))
2298                    .with(Atom::var(W_.prop_).pow((1, 2)));
2299                let parameters = [Atom::var(GS.pi)];
2300                let rational: ExpressionEvaluator<SymComplex<Fraction<IntegerRing>>> = expression
2301                    .evaluator(&parameters)
2302                    .build()
2303                    .map_err(|error| eyre!("failed to build complete-child evaluator: {error}"))?;
2304                let mut arb: ExpressionEvaluator<Complex<F<ArbPrec>>> =
2305                    rational.map_coeff(&|coefficient| {
2306                        Complex::new(F::from(&coefficient.re), F::from(&coefficient.im))
2307                    });
2308                Ok(arb.evaluate_single(&[Complex::new(
2309                    F::<ArbPrec>::from_f64(0.0).pi(),
2310                    F::<ArbPrec>::from_f64(0.0),
2311                )]))
2312            };
2313            // One eighth of ArbPrec's requested precision permits substantial,
2314            // route-dependent loss while preserving a precision-scaled oracle.
2315            let tolerance = F(ArbPrec::default().epsilon()).sqrt().sqrt().sqrt();
2316            let eta_series = eta
2317                .series(GS.rescale, Atom::one(), 2)
2318                .map_err(|error| eyre!("failed to build raised-LU eta jet: {error}"))?;
2319            let eta_prime = evaluate_arb(
2320                eta_series
2321                    .coefficient(Rational::from(1))
2322                    .expect("requested coefficient is within series precision"),
2323            )?;
2324            let eta_second = evaluate_arb(
2325                eta_series
2326                    .coefficient(Rational::from(2))
2327                    .expect("requested coefficient is within series precision")
2328                    * Atom::num(2),
2329            )?;
2330            let combined_raised_residue =
2331                |route: &BTreeMap<CutCFFIndex, Atom>| -> Result<Complex<F<ArbPrec>>> {
2332                    let sum_order = |order| {
2333                        route
2334                            .iter()
2335                            .filter(|(index, _)| index.lu_cut_order == Some(order))
2336                            .map(|(_, expression)| expression)
2337                            .fold(Atom::Zero, |sum, expression| sum + expression)
2338                    };
2339                    let order_one = sum_order(1);
2340                    let order_two = sum_order(2);
2341                    assert!(
2342                        !order_one.is_zero() && !order_two.is_zero(),
2343                        "the fixed raised cut must retain nonzero order-one and order-two pieces"
2344                    );
2345                    let f_one = value_and_t_derivative(order_one)?;
2346                    let f_two = value_and_t_derivative(order_two)?;
2347                    Ok(evaluate_arb(f_one[0].clone())? / eta_prime.clone()
2348                        + evaluate_arb(f_two[1].clone())? / eta_prime.clone().pow(2)
2349                        - evaluate_arb(f_two[0].clone())? * eta_second.clone()
2350                            / eta_prime.clone().pow(3))
2351                };
2352
2353            // The individual LU orders are representatives, not observables: replacing
2354            // f2 by f2 + eta*h and f1 by f1 - h leaves the complete raised residue
2355            // f1/eta' + f2'/eta'^2 - f2*eta''/eta'^3 invariant at eta = 0.  Compare the
2356            // fixed-Cutkosky physical residue only after summing every piece of each order.
2357            let direct_residue = combined_raised_residue(&direct)?;
2358            let expanded_residue = combined_raised_residue(&expanded)?;
2359            let distance = (direct_residue.clone() - expanded_residue.clone())
2360                .norm()
2361                .re;
2362            let scale = direct_residue
2363                .clone()
2364                .norm()
2365                .re
2366                .max(expanded_residue.clone().norm().re);
2367            let relative_distance = if scale.is_zero() {
2368                distance
2369            } else {
2370                distance / scale
2371            };
2372            assert!(
2373                relative_distance <= tolerance,
2374                "{outer_label} complete raised-LU residue mismatch: direct={direct_residue:e}, expanded={expanded_residue:e}, relative delta={relative_distance:e}, tolerance={tolerance:e}"
2375            );
2376
2377            // Exercise the production boundary which the symbolic comparison below bypasses:
2378            // forest output is tensor-preprocessed, lowered into an EvaluatorStack, and fed the
2379            // same first-order HyperDual loop-momentum jet as raised-LU pass one.  Construct the
2380            // independent Arb oracle directly from the generation LMB, so this remains a
2381            // comparison of two evaluation routes rather than two uses of the compiled evaluator.
2382            let production_rational =
2383                |numerator, denominator| Atom::num(Rational::from((numerator, denominator)));
2384            let base_loop_atoms = [
2385                [
2386                    production_rational(31, 100),
2387                    production_rational(-47, 100),
2388                    production_rational(83, 100),
2389                ],
2390                [
2391                    production_rational(-19, 100),
2392                    production_rational(37, 100),
2393                    production_rational(61, 100),
2394                ],
2395            ];
2396            let external_atoms = [[
2397                production_rational(12, 5),
2398                production_rational(11, 100),
2399                production_rational(-8, 100),
2400                production_rational(5, 100),
2401            ]];
2402            assert_eq!(
2403                graph.loop_momentum_basis.loop_edges.len(),
2404                base_loop_atoms.len()
2405            );
2406            assert_eq!(
2407                graph.loop_momentum_basis.ext_edges.len(),
2408                external_atoms.len()
2409            );
2410
2411            let production_rescale = |mut expression: Atom| -> Result<Atom> {
2412                expression = expression
2413                    .replace(GS.dim)
2414                    .with(4)
2415                    .replace(GS.dim_epsilon)
2416                    .with(0)
2417                    .replace(GS.m_uv_expansion)
2418                    .with(production_rational(7, 5))
2419                    .replace(GS.m_uv_vacuum)
2420                    .with(production_rational(7, 5))
2421                    .replace(function!(GS.tree_denom_wrapper, W_.x_))
2422                    .with(W_.x_)
2423                    .replace(GS.den(W_.a_, W_.b_, W_.c_, W_.d_))
2424                    .with(W_.d_)
2425                    .replace(function!(GS.ose, W_.mass_, W_.prop_))
2426                    .with(W_.prop_)
2427                    .replace(function!(GS.on_shell_energy, W_.a_, W_.prop_))
2428                    .with(Atom::var(W_.prop_).pow((1, 2)));
2429                // Realize finite components without distributing the numerator.
2430                let cooking = CookSettings::indices()
2431                    .with_mode(CookMode::ReversibleEncoding)
2432                    .with_representation_payloads(true, true);
2433                let value = SymbolicTensor::infer_indexed(cooking.try_cook(expression.as_view())?)?
2434                    .contract(ContractSettings {
2435                        collect_chains: false,
2436                        collect_traces: false,
2437                        ..Default::default()
2438                    })?
2439                    .expand_dots()?;
2440                expression = cooking.uncook(value.expression().as_view());
2441                expression = scalarize(expression)?;
2442                let t = Atom::var(GS.rescale);
2443                let loop_components = (0..3)
2444                    .map(|component| {
2445                        base_loop_atoms
2446                            .iter()
2447                            .map(|momentum| &momentum[component] * &t)
2448                            .collect::<Vec<_>>()
2449                    })
2450                    .collect::<Vec<_>>();
2451                let external_components = (0..3)
2452                    .map(|component| {
2453                        external_atoms
2454                            .iter()
2455                            .map(|momentum| momentum[component + 1].clone())
2456                            .collect::<Vec<_>>()
2457                    })
2458                    .collect::<Vec<_>>();
2459                let external_temporal = external_atoms
2460                    .iter()
2461                    .map(|momentum| momentum[0].clone())
2462                    .collect::<Vec<_>>();
2463                for edge in 0..graph.underlying.n_edges() {
2464                    let edge = EdgeIndex(edge);
2465                    let signature = &graph.loop_momentum_basis.edge_signatures[edge];
2466                    let spatial = (0..3)
2467                        .map(|component| {
2468                            signature
2469                                .try_compute_momentum(
2470                                    &loop_components[component],
2471                                    &external_components[component],
2472                                )
2473                                .unwrap_or(Atom::Zero)
2474                        })
2475                        .collect::<Vec<_>>();
2476                    let on_shell_energy = spatial
2477                        .iter()
2478                        .fold(Atom::one(), |norm, component| norm + component.pow(2))
2479                        .sqrt();
2480                    let temporal = if signature.internal.iter().any(|sign| sign.is_sign()) {
2481                        on_shell_energy.clone()
2482                    } else {
2483                        signature
2484                            .external
2485                            .try_apply(&external_temporal)
2486                            .unwrap_or(Atom::Zero)
2487                    };
2488                    expression = expression
2489                        .replace(GS.ose(edge))
2490                        .with(on_shell_energy.clone())
2491                        .replace(cut_energy(edge))
2492                        .with(on_shell_energy)
2493                        .replace(GS.emr_mom(edge, GS.cind(0)))
2494                        .with(temporal);
2495                    for (component, spatial_component) in spatial.iter().enumerate() {
2496                        expression = expression
2497                            .replace(GS.emr_mom(edge, GS.cind(component + 1)))
2498                            .with(spatial_component.clone())
2499                            .replace(GS.emr_vec(edge, GS.cind(component + 1)))
2500                            .with(spatial_component.clone());
2501                    }
2502                }
2503                Ok(expression)
2504            };
2505            let production_jet = |expression: Atom| -> Result<[Complex<F<ArbPrec>>; 2]> {
2506                let series = production_rescale(expression)?
2507                    .series(GS.rescale, Atom::one(), 1)
2508                    .map_err(|error| {
2509                        eyre!("failed to build production-boundary Arb jet: {error}")
2510                    })?;
2511                Ok([
2512                    evaluate_arb(
2513                        series
2514                            .coefficient(Rational::from(0))
2515                            .expect("requested coefficient is within series precision"),
2516                    )?,
2517                    evaluate_arb(
2518                        series
2519                            .coefficient(Rational::from(1))
2520                            .expect("requested coefficient is within series precision"),
2521                    )?,
2522                ])
2523            };
2524            let production_expressions = [&direct, &expanded]
2525                .into_iter()
2526                .map(|route| {
2527                    route
2528                        .iter()
2529                        .find(|(index, _)| index.lu_cut_order == Some(2))
2530                        .expect("the production-boundary route has an order-two LU sector")
2531                        .1
2532                        .clone()
2533                        .replace(GS.dim)
2534                        .with(4)
2535                        .replace(GS.dim_epsilon)
2536                        .with(0)
2537                        .replace(GS.m_uv_expansion)
2538                        .with(production_rational(7, 5))
2539                        .replace(GS.m_uv_vacuum)
2540                        .with(production_rational(7, 5))
2541                        .replace(function!(GS.tree_denom_wrapper, W_.x_))
2542                        .with(W_.x_)
2543                        .replace(GS.den(W_.a_, W_.b_, W_.c_, W_.d_))
2544                        .with(W_.d_)
2545                        .replace(function!(GS.ose, W_.mass_, W_.prop_))
2546                        .with(W_.prop_)
2547                        .replace(function!(GS.on_shell_energy, W_.a_, W_.prop_))
2548                        .with(Atom::var(W_.prop_).pow((1, 2)))
2549                })
2550                .collect::<Vec<_>>();
2551            let expected_production_jets = production_expressions
2552                .iter()
2553                .cloned()
2554                .map(production_jet)
2555                .collect::<Result<Vec<_>>>()?;
2556            let arb_rational = |numerator, denominator| {
2557                F::<ArbPrec>::from(&Rational::from((numerator, denominator)))
2558            };
2559            let loop_moms: LoopMomenta<F<ArbPrec>> = [
2560                ThreeMomentum::new(
2561                    arb_rational(31, 100),
2562                    arb_rational(-47, 100),
2563                    arb_rational(83, 100),
2564                ),
2565                ThreeMomentum::new(
2566                    arb_rational(-19, 100),
2567                    arb_rational(37, 100),
2568                    arb_rational(61, 100),
2569                ),
2570            ]
2571            .into_iter()
2572            .collect();
2573            let external_moms: ExternalFourMomenta<F<ArbPrec>> = [[
2574                arb_rational(12, 5),
2575                arb_rational(11, 100),
2576                arb_rational(-8, 100),
2577                arb_rational(5, 100),
2578            ]
2579            .into()]
2580            .into_iter()
2581            .collect();
2582            let dual_t =
2583                HyperDual::new(simple_n_deriv_shape(1)).variable(0, F::<ArbPrec>::from_f64(1.0));
2584            let dual_loop_moms = loop_moms.rescale_with_hyper_dual(&dual_t, None);
2585            let sample = MomentumSample {
2586                sample: BareMomentumSample {
2587                    loop_moms,
2588                    dual_loop_moms: Some(dual_loop_moms),
2589                    loop_mom_cache_id: 0,
2590                    loop_mom_base_cache_id: 0,
2591                    external_moms,
2592                    external_mom_cache_id: 0,
2593                    external_mom_base_cache_id: 0,
2594                    external_rotations: Vec::new(),
2595                    jacobian: arb_rational(1, 1),
2596                    orientation: None,
2597                    parameterization_branch: None,
2598                },
2599            };
2600            // The complete factorized child is deliberately deeper than a normal unit-test
2601            // thread stack. Use the same 32 MiB worker size as UV profiling rather than flattening
2602            // the numerator before it reaches the production evaluator.
2603            let actual_production_jets = std::thread::scope(|scope| -> Result<_> {
2604                let worker = std::thread::Builder::new()
2605                    .name("raised-lu-production-boundary".to_owned())
2606                    .stack_size(32 * 1024 * 1024)
2607                    .spawn_scoped(scope, || -> Result<_> {
2608                        let orientations = TiVec::<OrientationID, EdgeVec<Orientation>>::new();
2609                        let orientation_filter = SubSet::full(orientations.len());
2610                        let mut param_builder = graph.param_builder.clone();
2611                        param_builder.initialize_duals(2);
2612                        let (mut production_evaluator, _) =
2613                            EvaluatorStack::new_explicit_sum_with_timings(
2614                                &production_expressions,
2615                                &param_builder,
2616                                &[],
2617                                Some(simple_n_deriv_shape(1)),
2618                                &EvaluatorSettings::default(),
2619                            )?;
2620                        let input = <ArbPrec as GenericEvaluatorFloat>::get_parameters(
2621                            &mut param_builder,
2622                            (false, false),
2623                            &graph,
2624                            &sample,
2625                            &[],
2626                            &[],
2627                            None,
2628                            None,
2629                            None,
2630                        );
2631                        production_evaluator.evaluate(
2632                            input,
2633                            SingleOrAllOrientations::All {
2634                                all: &orientations,
2635                                filter: &orientation_filter,
2636                            },
2637                            &RuntimeSettings::default(),
2638                            &mut EvaluationMetaData::new_empty(),
2639                        )
2640                    })?;
2641                worker
2642                    .join()
2643                    .map_err(|_| eyre!("raised-LU production-boundary worker panicked"))?
2644            })?;
2645            for (route, actual, expected) in ["direct 3D", "projected local 4D"]
2646                .into_iter()
2647                .zip(actual_production_jets)
2648                .zip(&expected_production_jets)
2649                .map(|((route, actual), expected)| (route, actual, expected))
2650            {
2651                let DualOrNot::Dual(actual) = actual else {
2652                    panic!("{route} order-two production evaluator did not return a HyperDual jet")
2653                };
2654                let actual = extract_t_derivatives_complex(actual);
2655                for (component, actual, expected) in ["f2", "f2 prime"]
2656                    .into_iter()
2657                    .zip(actual)
2658                    .zip(expected)
2659                    .map(|((component, actual), expected)| (component, actual, expected))
2660                {
2661                    let distance = (actual.clone() - expected.clone()).norm().re;
2662                    let scale = actual.clone().norm().re.max(expected.clone().norm().re);
2663                    let relative_distance = if scale.is_zero() {
2664                        distance
2665                    } else {
2666                        distance / scale
2667                    };
2668                    assert!(
2669                        relative_distance <= tolerance,
2670                        "{route} production-boundary {component} mismatch: actual={actual:e}, expected={expected:e}, relative delta={relative_distance:e}, tolerance={tolerance:e}"
2671                    );
2672                }
2673            }
2674
2675            let consistent_eta = production_rescale(representative.to_atom(&[]))?;
2676            let consistent_eta_series = consistent_eta
2677                .series(GS.rescale, Atom::one(), 2)
2678                .map_err(|error| eyre!("failed to build production-boundary eta jet: {error}"))?;
2679            let consistent_eta_prime = evaluate_arb(
2680                consistent_eta_series
2681                    .coefficient(Rational::from(1))
2682                    .expect("requested coefficient is within series precision"),
2683            )?;
2684            let consistent_eta_second = evaluate_arb(
2685                consistent_eta_series
2686                    .coefficient(Rational::from(2))
2687                    .expect("requested coefficient is within series precision")
2688                    * Atom::num(2),
2689            )?;
2690            let mut pass_two_evaluator =
2691                build_derivative_structure(2, -1, &EvaluatorSettings::default());
2692            for (route, jet) in ["direct 3D", "projected local 4D"]
2693                .into_iter()
2694                .zip(&expected_production_jets)
2695            {
2696                let actual = <ArbPrec as GenericEvaluatorFloat>::get_evaluator_single(
2697                    &mut pass_two_evaluator,
2698                )(&[
2699                    jet[0].clone(),
2700                    jet[1].clone(),
2701                    consistent_eta_prime.clone(),
2702                    consistent_eta_second.clone(),
2703                ]);
2704                let expected = jet[1].clone() / consistent_eta_prime.clone().pow(2)
2705                    - jet[0].clone() * &consistent_eta_second / consistent_eta_prime.clone().pow(3);
2706                let distance = (actual.clone() - expected.clone()).norm().re;
2707                let scale = actual.clone().norm().re.max(expected.clone().norm().re);
2708                let relative_distance = if scale.is_zero() {
2709                    distance
2710                } else {
2711                    distance / scale
2712                };
2713                assert!(
2714                    relative_distance <= tolerance,
2715                    "{route} production pass-two mismatch: actual={actual:e}, expected={expected:e}, relative delta={relative_distance:e}, tolerance={tolerance:e}"
2716                );
2717            }
2718        }
2719        Ok(())
2720    }
2721}