Skip to main content

gammalooprs/uv/
hedge_poset.rs

1use std::time::{Duration, Instant};
2use std::{
3    collections::{BTreeMap, BTreeSet},
4    fmt::Display,
5    sync::Arc,
6};
7
8#[cfg(test)]
9use crate::uv::Integrands;
10#[cfg(test)]
11use crate::{
12    cff::expression::OrientationID,
13    uv::approx::direct_3d::{DirectCoordinateFrame, DirectResidueBranches, DirectSector},
14};
15#[cfg(test)]
16use std::cmp::Reverse;
17
18use ahash::AHashMap;
19use eyre::{WrapErr, eyre};
20use gammaloop_tracing_filter::LogMessage;
21use idenso::{
22    CookMode, CookSettings,
23    color::ColorSimplifySettings,
24    representations::{ColorAdjoint, ColorFundamental, ColorSextet},
25    tensor::SymbolicTensor,
26};
27use itertools::Itertools;
28use linnet::half_edge::{
29    HedgeGraph, NoData, NodeIndex,
30    algorithms::{
31        DirectionBasis,
32        trace_unfold::{HiddenData, Independence, TraceKey, TraceUnfold, UnfoldedTraceGraph},
33    },
34    involution::{EdgeIndex, Flow, HedgePair},
35    nodestore::{NodeStorageOps, NodeStorageVec},
36    subgraph::{Inclusion, InternalSubGraph, ModifySubSet, SuBitGraph, SubSetLike, SubSetOps},
37};
38use spenso::shadowing::TensorCollectFilter;
39use spenso::structure::{IndexedStructure, OrderedStructure, ScalarStructure};
40use symbolica::{
41    atom::{Atom, AtomCore, FunctionBuilder},
42    function,
43};
44use tracing::debug;
45use vakint::Vakint;
46
47use crate::{
48    debug_tags,
49    graph::{
50        Graph, LMBext, LoopMomentumBasis,
51        cuts::CutSet,
52        parse::string_utils::{ToOrderedSimple, dot_attr_value},
53    },
54    model::Model,
55    settings::global::GenerationSettings,
56    utils::{GS, W_},
57    uv::{
58        ApproximationType, RenormalizationPart, Spinney, UVgenerationSettings, UltravioletGraph,
59        approx::{
60            CutStructure, ForestNodeLike, OrientationProjection, Rooted, UVCtx,
61            direct_3d::{Direct3dApproximation, Direct3dCts},
62            final_integrand::{FinalIntegrandBuilder, FinalIntegrands},
63            integrated::{Integrated, IntegratedCts},
64            local_3d::{Local3DCts, Localizer},
65            local_4d::{self, Full4dCts, Local4dCts},
66            projected_4d::{Local4dProjectionContext, Projected4dApproximation},
67        },
68        export::{
69            UVForestLocalProvenance, UVForestNodeExpression, UVForestNodeProvenance,
70            UVForestProvenance,
71        },
72        forest::ParametricIntegrands,
73        marker::UvMarker,
74    },
75};
76use color_eyre::Result;
77use spenso::shadowing::symbolica_utils::{LogPrint, SpensoPrintSettings};
78
79pub struct Wood {
80    pub graph: HedgeGraph<SuBitGraph, Spinney>,
81    pub root: NodeIndex,
82    pub vakint_settings: vakint::VakintSettings,
83    cuts: CutStructure,
84}
85
86impl Independence<HiddenData<SuBitGraph, EdgeIndex>> for Wood {
87    fn independent(
88        &self,
89        a: &HiddenData<SuBitGraph, EdgeIndex>,
90        b: &HiddenData<SuBitGraph, EdgeIndex>,
91    ) -> bool {
92        !a.order.intersects(&b.order)
93    }
94}
95
96impl TraceUnfold<SuBitGraph> for Wood {
97    type EdgeData = SuBitGraph;
98    type HedgeData = NoData;
99    type NodeData = Spinney;
100    type NodeStorage = NodeStorageVec<Spinney>;
101
102    fn graph(
103        &self,
104    ) -> &HedgeGraph<Self::EdgeData, Self::NodeData, Self::HedgeData, Self::NodeStorage> {
105        &self.graph
106    }
107
108    fn key(&self, e: EdgeIndex) -> SuBitGraph {
109        self.graph[e].clone()
110    }
111
112    /// Treats a wood node as a factorized join when its incoming sink edges are exactly the
113    /// disjoint connected components of the target spinney.
114    ///
115    /// The returned `SuBitGraph`s are the required branch factors for the generic trace unfold:
116    /// their union must be the target filter, they must be pairwise disjoint, and there must be
117    /// one factor per connected component.
118    fn join_factors(&self, target: NodeIndex) -> Option<BTreeSet<SuBitGraph>> {
119        if self.graph[target].n_components() < 2 {
120            return None;
121        }
122
123        let factors = self
124            .graph
125            .iter_crown(target)
126            .filter(|hedge| self.graph.flow(*hedge) == Flow::Sink)
127            .map(|hedge| self.graph[self.graph[&hedge]].clone())
128            .collect::<BTreeSet<_>>();
129        if factors.len() != self.graph[target].n_components() {
130            return None;
131        }
132        if factors.iter().any(|factor| {
133            !self
134                .graph
135                .iter_nodes()
136                .any(|(_, _, spinney)| spinney.n_components() == 1 && spinney.filter() == factor)
137        }) {
138            return None;
139        }
140
141        let mut cover: Option<SuBitGraph> = None;
142        for factor in &factors {
143            if let Some(acc) = &mut cover {
144                if acc.intersects(factor) {
145                    return None;
146                }
147                acc.union_with(factor);
148            } else {
149                cover = Some(factor.clone());
150            }
151        }
152
153        (cover.as_ref() == Some(self.graph[target].filter())).then_some(factors)
154    }
155}
156
157impl Wood {
158    pub fn current_given_pair<'a>(
159        &'a self,
160        edge_id: EdgeIndex,
161        order: usize,
162    ) -> (ForestNode<'a>, ForestNode<'a>) {
163        let HedgePair::Paired { source, sink } = self.graph[&edge_id].1 else {
164            panic!("edge in self is not paired");
165        };
166
167        // get this hedge's forest node from the self. This is the node that has already been computed (as it is a parent to this edge)
168        let given = ForestNode {
169            spinney: &self.graph[self.graph.node_id(source)],
170            topo_order: order,
171        };
172
173        // this is the current node, which should be the same for all union edges (since they all have the same sink)
174        let current_for_h = self.graph.node_id(sink);
175
176        // this is the current node, which we want to compute with
177        let current = ForestNode {
178            spinney: &self.graph[current_for_h],
179            topo_order: order,
180        };
181
182        (current, given)
183    }
184
185    pub(crate) fn new(
186        cuts: CutStructure,
187        graph: &Graph,
188        model: &Model,
189        settings: &GenerationSettings,
190    ) -> Result<Self> {
191        let mut subgraph = graph.full_filter();
192        subgraph.subtract_with(&graph.initial_state_cut.left);
193        let mut spinneys = Vec::new();
194
195        for (cut_index, cut) in cuts.cuts.iter().enumerate() {
196            let cut_sub = subgraph.subtract(&cut.union);
197            spinneys.extend(
198                graph
199                    .classified_spinneys(&cut_sub, model, &settings.uv, &graph.loop_momentum_basis)
200                    .wrap_err_with(|| {
201                        format!(
202                            "graph '{}' cut {cut_index}: failed to classify UV counterterm components",
203                            graph.name
204                        )
205                    })?,
206            );
207        }
208        graph.remove_full_observable_spinney(&mut spinneys, &settings.medium);
209
210        Ok(Self::from_spinneys(spinneys, graph, cuts, &settings.uv))
211    }
212
213    pub(crate) fn from_spinneys<I: IntoIterator<Item = Spinney>>(
214        s: I,
215        graph: &Graph,
216        cuts: CutStructure,
217        settings: &UVgenerationSettings,
218    ) -> Self {
219        let mut max_loops = 0;
220        let mut spinneys = BTreeMap::new();
221        for spinney in s {
222            max_loops = max_loops.max(graph.n_loops(spinney.filter()));
223            spinneys.entry(spinney.filter().clone()).or_insert(spinney);
224        }
225        let empty = Spinney::empty(graph);
226        spinneys.entry(empty.filter().clone()).or_insert(empty);
227        let mut vakint_settings = settings.vakint.true_settings();
228        vakint_settings.project_onto_tensor_integrals =
229            settings.project_integrated_uv_cts_onto_tensor_integrals;
230        // Retain enough positive epsilon powers for finite terms formed when disconnected
231        // integrated counterterms are multiplied.
232        vakint_settings.number_of_terms_in_epsilon_expansion = max_loops as i64 + 1;
233
234        let mut unions = BTreeSet::new();
235        let g: HedgeGraph<_, _> = HedgeGraph::poset(spinneys.into_values());
236        let mut poset = g.map(
237            |_, _, v| v,
238            |_, n, pair, _, e| {
239                let HedgePair::Paired { source, sink } = pair else {
240                    return e.map(|_| graph.as_ref().empty_subgraph());
241                };
242                let nsource = n.node_id_ref(source);
243                let nsink = n.node_id_ref(sink);
244
245                let source_subgraph = &n.get_node_data(nsource).subgraph;
246                let sink_subgraph = &n.get_node_data(nsink).subgraph;
247                let reduced_subgraph = sink_subgraph.subtract(source_subgraph).filter;
248                let hairy_source = graph.as_ref().full_crown(source_subgraph);
249
250                if graph.as_ref().bridges_of(&reduced_subgraph).is_empty()
251                    && !hairy_source.intersects(&reduced_subgraph)
252                {
253                    // if the reduced graph is bridgless,and has no node overlap with the source, then the source subgraph is cycle independent of reduced subgraph
254                    // if the source is not empty then this is a disjoint union
255                    if !source_subgraph.is_empty() {
256                        unions.insert(nsink);
257                    }
258                    e.map(|_| reduced_subgraph)
259                } else {
260                    e.map(|_| sink_subgraph.filter.clone())
261                }
262            },
263            |_, d| d,
264        );
265
266        let mut to_remove: SuBitGraph = poset.empty_subgraph();
267        let classified_filters = poset
268            .iter_nodes()
269            .map(|(_, _, spinney)| spinney.filter().clone())
270            .collect::<BTreeSet<_>>();
271
272        // Not quite transitive closure. A disconnected target factorizes only when every
273        // connected component is both an independently classified UV spinney and supplied by
274        // an incoming edge. In that case, keep only those component edges so trace unfolding
275        // builds the canonical product. If either condition fails, the target is a genuinely
276        // collective UV region whose atomic Taylor term and nested forest terms are both
277        // required. Label every retained transition by that full Taylor scope: the reduced
278        // complement remains available from the edge's source/sink nodes, while using it as
279        // the trace order would incorrectly make a collective operation commute with its
280        // nested prefix and could coalesce distinct forests into a false factorized join.
281        for u in unions {
282            let collective_scope = poset[u].subgraph.filter.clone();
283            let comps: BTreeSet<_> = graph
284                .as_ref()
285                .connected_components(&collective_scope)
286                .into_iter()
287                .collect();
288            let incoming = poset
289                .iter_crown(u)
290                .filter(|c| poset.flow(*c) == Flow::Sink)
291                .collect::<Vec<_>>();
292            let supplied = incoming
293                .iter()
294                .map(|c| &poset[poset[c]])
295                .filter(|factor| comps.contains(*factor))
296                .cloned()
297                .collect::<BTreeSet<_>>();
298            let independently_classified = comps
299                .iter()
300                .all(|component| classified_filters.contains(component));
301            if independently_classified && supplied == comps {
302                for c in incoming {
303                    if comps.contains(&poset[poset[&c]]) {
304                        continue;
305                    }
306                    to_remove.add(c);
307                    to_remove.add(poset.inv(c));
308                }
309            } else {
310                for c in incoming {
311                    let edge = poset[&c];
312                    poset[edge] = collective_scope.clone();
313                }
314            }
315        }
316
317        poset.delete_hedges(&to_remove);
318        let root = poset
319            .iter_nodes()
320            .find(|(_, _, s)| s.subgraph.is_empty())
321            .map(|(n, _, _)| n);
322
323        Wood {
324            graph: poset,
325            root: root.expect("no empty spinney found"),
326            cuts,
327            vakint_settings,
328        }
329    }
330
331    fn unfold_with_cached_node_label_atoms(self, cache_node_label_atoms: bool) -> Forests {
332        let unfolded = self.trace_unfold::<NodeStorageVec<_>>(self.root);
333        let graph = unfolded.map(|_, _, key| OperationNode { key });
334
335        let mut cuts: Vec<(SuBitGraph, CutSet)> = Vec::new();
336        for c in &self.cuts.cuts {
337            let mut compatible: SuBitGraph = graph.empty_subgraph();
338            for (_, crown, s) in graph.iter_nodes() {
339                if s.is_compatible_with(c) {
340                    for h in crown {
341                        compatible.add(h);
342                    }
343                }
344            }
345            cuts.push((compatible, c.clone()));
346        }
347        let root = graph
348            .iter_nodes()
349            .find(|(_, _, operation)| operation.key.is_empty())
350            .map(|(node, _, _)| node)
351            .expect("no empty trace key found in unfolded hedge-poset forest");
352
353        let forests = Forests {
354            graph,
355            cuts,
356            root,
357            cached_node_label_atoms: cache_node_label_atoms.then(AHashMap::new),
358            compute_store: ComputeStore::default(),
359            wood: self,
360        };
361
362        if cache_node_label_atoms {
363            forests.with_cached_node_label_atoms()
364        } else {
365            forests
366        }
367    }
368
369    pub fn unfold(self) -> Forests {
370        self.unfold_with_cached_node_label_atoms(true)
371    }
372
373    pub fn unfold_uncached(self) -> Forests {
374        self.unfold_with_cached_node_label_atoms(false)
375    }
376}
377
378impl Display for Wood {
379    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
380        self.graph.dot_impl_fmt(
381            f,
382            &self.graph.full_filter(),
383            "start=2;\n",
384            &|_| None,
385            &|a| Some(format!("label=\"{}\"", a.string_label())),
386            &|v| Some(format!("label=\"{}\"", v.subgraph.string_label())),
387        )
388    }
389}
390// pub type SpinneyGraph = HedgeGraph<SuBitGraph, Spinney>;
391
392// impl Key<&SuBitGraph> for SpinneyGraph {
393//     fn key(&self, e: linnet::half_edge::involution::EdgeIndex) -> K {
394//         &self[e]
395//     }
396// }
397
398#[derive(Default)]
399pub struct ComputeStore {
400    entries: AHashMap<OperationNode, ComputeNode>,
401}
402
403impl ComputeStore {
404    fn get(&self, key: &OperationNode) -> Option<&ComputeNode> {
405        self.entries.get(key)
406    }
407
408    fn require(&self, key: &OperationNode) -> Result<&ComputeNode> {
409        // Union operations, like individual Taylor steps, must be computed
410        // before their typed values are consumed by another forest node.
411        self.get(key)
412            .ok_or_else(|| eyre!("{key} not yet added to compute store"))
413    }
414
415    fn entry(
416        &mut self,
417        key: OperationNode,
418    ) -> std::collections::hash_map::Entry<'_, OperationNode, ComputeNode> {
419        self.entries.entry(key)
420    }
421}
422
423pub struct Forests {
424    pub graph: UnfoldedTraceGraph<Wood, OperationNode, NodeStorageVec<OperationNode>>,
425    pub root: NodeIndex,
426    /// Wood subgraph that has compatible
427    cuts: Vec<(SuBitGraph, CutSet)>,
428    cached_node_label_atoms: Option<AHashMap<NodeIndex, Atom>>,
429    pub compute_store: ComputeStore,
430    wood: Wood,
431}
432
433#[derive(Clone, Debug, Hash, PartialEq, Eq)]
434pub struct OperationNode {
435    pub key: TraceKey<SuBitGraph, EdgeIndex>,
436}
437
438pub struct ForestNode<'a> {
439    pub spinney: &'a Spinney,
440    pub topo_order: usize,
441}
442
443pub struct OwnedForestNode {
444    pub spinney: Spinney,
445    pub topo_order: usize,
446}
447
448#[cfg(test)]
449struct LocalLeafOperation {
450    op: HiddenData<SuBitGraph, EdgeIndex>,
451    frontier: NodeIndex,
452}
453
454struct UnionReplayState {
455    integrated: NodeIndex,
456    local_edges: Vec<EdgeIndex>,
457}
458
459#[cfg(test)]
460impl LocalLeafOperation {
461    fn new(op: &HiddenData<SuBitGraph, EdgeIndex>, frontier: NodeIndex) -> Self {
462        Self {
463            op: op.clone(),
464            frontier,
465        }
466    }
467}
468
469impl OperationNode {
470    pub fn is_compatible_with(&self, cut: &CutSet) -> bool {
471        self.covers().is_none_or(|c| !c.intersects(&cut.union))
472    }
473
474    pub fn current<'a>(&'a self, wood: &'a Wood, topo_order: usize) -> Option<Vec<ForestNode<'a>>> {
475        if self.key.is_empty() {
476            return None;
477        }
478
479        Some(
480            self.key
481                .iter_leaf_ops()
482                .map(|op| {
483                    let HedgePair::Paired { sink, .. } = wood.graph[&op.data].1 else {
484                        panic!("edge in trace key is not paired");
485                    };
486                    let spinney = &wood.graph[wood.graph.node_id(sink)];
487                    ForestNode {
488                        spinney,
489                        topo_order,
490                    }
491                })
492                .collect::<Vec<_>>(),
493        )
494    }
495}
496
497impl AsRef<TraceKey<SuBitGraph, EdgeIndex>> for OperationNode {
498    fn as_ref(&self) -> &TraceKey<SuBitGraph, EdgeIndex> {
499        &self.key
500    }
501}
502
503impl LogMessage for ForestNode<'_> {
504    fn log_display(&self) -> String {
505        format!(
506            "subgraph={}, topo_order={}, dod={}",
507            self.spinney.filter().string_label(),
508            self.topo_order,
509            self.spinney.dod
510        )
511    }
512}
513
514impl ForestNodeLike for ForestNode<'_> {
515    fn dod(&self) -> i32 {
516        self.spinney.dod
517    }
518    fn renormalization_scheme(&self) -> crate::uv::ApproximationType {
519        self.spinney.renormalization_scheme
520    }
521    fn lmb(&self) -> &LoopMomentumBasis {
522        &self.spinney.lmb
523    }
524    fn reduced_subgraph(&self, given: &Self) -> SuBitGraph {
525        self.spinney
526            .subgraph
527            .subtract(&given.spinney.subgraph)
528            .filter
529    }
530    fn subgraph(&self) -> &SuBitGraph {
531        self.spinney.filter()
532    }
533    fn topo_order(&self) -> usize {
534        self.topo_order
535    }
536}
537
538impl LogMessage for OwnedForestNode {
539    fn log_display(&self) -> String {
540        format!(
541            "subgraph={}, topo_order={}, dod={}",
542            self.spinney.filter().string_label(),
543            self.topo_order,
544            self.spinney.dod
545        )
546    }
547}
548
549impl ForestNodeLike for OwnedForestNode {
550    fn dod(&self) -> i32 {
551        self.spinney.dod
552    }
553
554    fn renormalization_scheme(&self) -> crate::uv::ApproximationType {
555        self.spinney.renormalization_scheme
556    }
557
558    fn lmb(&self) -> &LoopMomentumBasis {
559        &self.spinney.lmb
560    }
561
562    fn reduced_subgraph(&self, given: &Self) -> SuBitGraph {
563        self.spinney
564            .subgraph
565            .subtract(&given.spinney.subgraph)
566            .filter
567    }
568
569    fn subgraph(&self) -> &SuBitGraph {
570        self.spinney.filter()
571    }
572
573    fn topo_order(&self) -> usize {
574        self.topo_order
575    }
576}
577
578impl Display for OperationNode {
579    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
580        if self.key.is_empty() {
581            write!(f, "∅")
582        } else {
583            self.key.write_foata_like(f, |op| op.string_label())
584        }
585    }
586}
587
588impl OperationNode {
589    fn foata_level_labels(&self) -> String {
590        self.key
591            .iter_levels_top_down()
592            .map(|level| {
593                level
594                    .iter_leaf_ops()
595                    .map(|op| op.order.string_label())
596                    .join(",")
597            })
598            .join(";")
599    }
600
601    pub fn covers(&self) -> Option<SuBitGraph> {
602        let mut acc: Option<SuBitGraph> = None;
603
604        for level in self.key.iter_levels_top_down() {
605            for op in level.iter_leaf_ops() {
606                if let Some(a) = &mut acc {
607                    a.union_with(&op.order);
608                } else {
609                    acc = Some(op.order.clone());
610                }
611            }
612        }
613
614        acc
615    }
616
617    fn forest_node(&self, graph: &Graph, topo_order: usize) -> Result<OwnedForestNode> {
618        let spinney = match self.covers() {
619            Some(cover) if !cover.is_empty() => {
620                let subgraph = InternalSubGraph::cleaned_filter_optimist(cover, graph.as_ref());
621                Spinney::new(subgraph, graph, &graph.loop_momentum_basis)
622                    .wrap_err_with(|| {
623                        format!(
624                            "graph '{}': failed to construct forest node for operation {self}",
625                            graph.name
626                        )
627                    })?
628                    .ok_or_else(|| {
629                        eyre!(
630                            "graph '{}': operation {self} cover has negative degree of divergence",
631                            graph.name
632                        )
633                    })?
634            }
635            _ => Spinney::empty(graph),
636        };
637
638        Ok(OwnedForestNode {
639            spinney,
640            topo_order,
641        })
642    }
643
644    pub fn to_atom(&self) -> Atom {
645        let mut acc = Atom::one();
646
647        let approx = FunctionBuilder::new(GS.uv_approx);
648        let mut levels = self.key.iter_levels_top_down();
649        let Some(first_level) = levels.next() else {
650            return acc;
651        };
652
653        let Some(first_op) = first_level.iter_leaf_ops().next() else {
654            return acc;
655        };
656
657        let mut last = SuBitGraph::empty(first_op.order.size());
658        for l in std::iter::once(first_level).chain(levels) {
659            let last_sym = if last.is_empty() {
660                Atom::Zero
661            } else {
662                last.symbol().to_atom()
663            };
664
665            let mut mul = Atom::one();
666
667            for op in l.iter_leaf_ops() {
668                let new = function!(op.order.symbol(), usize::from(op.data));
669                mul *= approx.clone().add_arg((new - &last_sym) * &acc).finish();
670                last.union_with(&op.order);
671            }
672
673            acc = mul
674        }
675
676        acc
677    }
678
679    // Four-dimensional and per-cut local terms are composed by `Forests` from typed
680    // dependency-frontier values. Empty frontiers start from the typed roots, and
681    // `Direct3dApproximation::run` applies the direct-3D subtraction signs.
682}
683
684#[derive(Default)]
685pub struct ComputeNode {
686    local_4d: Option<Local4dCts>,
687    integrated: Option<IntegratedCts>,
688    cuts: AHashMap<CutSet, CutComputation>,
689}
690
691pub struct CutComputation {
692    local_3d: Local3DCts,
693    final_integrands: FinalIntegrands,
694}
695
696impl ComputeNode {
697    fn local_4d(&self, operation: &OperationNode) -> Result<&Local4dCts> {
698        self.local_4d
699            .as_ref()
700            .ok_or_else(|| eyre!("{operation} has no computed local 4D counterterm"))
701    }
702
703    fn integrated(&self, operation: &OperationNode) -> Result<&IntegratedCts> {
704        self.integrated
705            .as_ref()
706            .ok_or_else(|| eyre!("{operation} has no computed integrated counterterm"))
707    }
708
709    fn cut(&self, operation: &OperationNode, cutset: &CutSet) -> Result<&CutComputation> {
710        self.cuts.get(cutset).ok_or_else(|| {
711            eyre!("{operation} has no computed local counterterms for cut {cutset:?}")
712        })
713    }
714}
715
716impl Forests {
717    fn source_spinney(&self, node: NodeIndex) -> &Spinney {
718        &self.wood.graph[self.graph.source_node(node)]
719    }
720
721    fn recursion_input_4d(&self, node: NodeIndex) -> Result<Full4dCts> {
722        // The typed 4D value is the sequential accumulator. It already encodes that an empty
723        // dependency frontier starts at the typed root, that other prefixes enter through their
724        // reduced branch, and that both local subtraction signs are applied without a raw
725        // Foata-level product. Disconnected values likewise retain their factorized local and
726        // integrated-prefix cross terms, so no separate active/frozen root-path replay is needed.
727        let operation = &self.graph[node];
728        let computed = self.compute_store.require(operation)?;
729        if self.graph.is_disjoint_union(node) {
730            return Ok(Full4dCts::from_factorized_local(
731                computed.local_4d(operation)?,
732            ));
733        }
734        Full4dCts::recursion_input(
735            computed.local_4d(operation)?,
736            computed.integrated(operation)?,
737            self.source_spinney(node).renormalization_scheme,
738            node == self.root,
739            &self.source_spinney(node).lmb,
740        )
741    }
742
743    fn cached_node_label_atom(&self, node: NodeIndex) -> Option<Atom> {
744        self.cached_node_label_atoms
745            .as_ref()
746            .and_then(|labels| labels.get(&node))
747            .cloned()
748    }
749
750    fn node_label_atom_factor(
751        &self,
752        frontier: NodeIndex,
753        op: &HiddenData<SuBitGraph, EdgeIndex>,
754    ) -> Atom {
755        let approx = FunctionBuilder::new(GS.uv_approx);
756        let frontier_atom = self.node_label_atom(frontier);
757
758        let current = function!(op.order.symbol(), usize::from(op.data));
759        let argument = if self.graph[frontier].covers().is_none() {
760            current
761        } else {
762            let previous = self.graph[frontier]
763                .covers()
764                .expect("non-empty frontier cover must exist")
765                .symbol();
766            (current - previous) * frontier_atom
767        };
768        approx.add_arg(argument).finish()
769    }
770
771    fn node_label_atom(&self, node: NodeIndex) -> Atom {
772        if self.graph[node].key.is_empty() {
773            return Atom::one();
774        }
775
776        if let Some(cached) = self.cached_node_label_atom(node) {
777            return cached;
778        }
779
780        self.graph
781            .leaf_op_dependency_frontiers(node, &self.wood)
782            .fold(Atom::one(), |acc, (op, frontier)| {
783                acc * self.node_label_atom_factor(frontier, op)
784            })
785    }
786
787    fn with_cached_node_label_atoms(mut self) -> Self {
788        self.cache_node_label_atoms();
789        self
790    }
791
792    fn cache_node_label_atoms(&mut self) {
793        self.cached_node_label_atoms = Some(AHashMap::new());
794        for nidx in self
795            .graph
796            .topo_sort_kahn(DirectionBasis::Underlying)
797            .unwrap()
798        {
799            let atom = self.node_label_atom(nidx);
800            self.cached_node_label_atoms
801                .as_mut()
802                .expect("node-label cache was initialized")
803                .insert(nidx, atom);
804        }
805    }
806
807    fn node_label(&self, node: NodeIndex) -> String {
808        let key = &self.graph[node];
809        if key.key.is_empty() {
810            return "∅".to_string();
811        }
812
813        let mut foata = String::new();
814        key.key
815            .write_foata_like(&mut foata, |op| op.string_label())
816            .expect("writing a trace key into a string must succeed");
817        let atom = self.node_label_atom(node);
818        format!("{foata}: {}", atom.to_ordered_simple())
819    }
820
821    fn dot_serialize_expr_atom() -> Atom {
822        Atom::var(GS.expr)
823    }
824
825    fn dot_serialize_node_atom_factor(
826        &self,
827        frontier: NodeIndex,
828        op: &HiddenData<SuBitGraph, EdgeIndex>,
829    ) -> Atom {
830        let frontier_depth = self.graph[frontier].key.op_count();
831        let (current, given) = self.wood.current_given_pair(op.data, frontier_depth);
832        // Structured forest-DOT approximation records use the same operation and subgraph
833        // markers as the computed UV expressions.
834        function!(
835            GS.uv_approx,
836            UvMarker::subgraph(current.subgraph(), given.subgraph())
837                * self.dot_serialize_node_atom(frontier)
838        )
839    }
840
841    fn dot_serialize_node_atom(&self, node: NodeIndex) -> Atom {
842        if self.graph[node].key.is_empty() {
843            return Self::dot_serialize_expr_atom();
844        }
845
846        self.graph
847            .leaf_op_dependency_frontiers(node, &self.wood)
848            .fold(Atom::one(), |acc, (op, frontier)| {
849                acc * self.dot_serialize_node_atom_factor(frontier, op)
850            })
851    }
852
853    fn dot_serialize_node_attrs(&self, node: NodeIndex) -> String {
854        let key = &self.graph[node];
855        let label = self
856            .dot_serialize_node_atom(node)
857            .printer(SpensoPrintSettings::typst_options())
858            .to_string();
859        let cover = key
860            .covers()
861            .unwrap_or_else(|| self.graph.empty_subgraph())
862            .string_label();
863
864        format!(
865            "label={} foata={} cover={}",
866            dot_attr_value(&label),
867            dot_attr_value(&key.foata_level_labels()),
868            dot_attr_value(&cover),
869        )
870    }
871
872    pub fn dot_serialize(&self) -> String {
873        let mut output = String::new();
874        self.dot_serialize_fmt(&mut output)
875            .expect("writing hedge-poset forest DOT into a string must succeed");
876        output
877    }
878
879    pub fn dot_serialize_fmt(&self, writer: &mut impl std::fmt::Write) -> std::fmt::Result {
880        let attrs: AHashMap<_, _> = self
881            .graph
882            .iter_nodes()
883            .map(|(node, _, key)| (key.clone(), self.dot_serialize_node_attrs(node)))
884            .collect();
885
886        self.graph.dot_impl_fmt(
887            writer,
888            &self.graph.full_filter(),
889            "start=2;\n",
890            &|_| None,
891            &|_| None,
892            &|v| Some(attrs[v].clone()),
893        )
894    }
895
896    fn compatible_topological_order(&self, subset: &SuBitGraph) -> Result<Vec<NodeIndex>> {
897        let mut order = self
898            .graph
899            .topo_sort_kahn_of(subset, DirectionBasis::Underlying)?;
900
901        if let Some(root_position) = order.iter().position(|node| *node == self.root) {
902            if root_position != 0 {
903                let root = order.remove(root_position);
904                order.insert(0, root);
905            }
906        } else {
907            order.insert(0, self.root);
908        }
909
910        Ok(order)
911    }
912
913    #[cfg(test)]
914    fn local_leaf_operations(&self, node: NodeIndex) -> Vec<LocalLeafOperation> {
915        let mut leaves = self
916            .graph
917            .leaf_op_dependency_frontiers(node, &self.wood)
918            .map(|(op, frontier)| LocalLeafOperation::new(op, frontier))
919            .collect::<Vec<_>>();
920
921        leaves.sort_by_key(|leaf| {
922            (
923                Reverse(self.graph[leaf.frontier].key.op_count()),
924                leaf.op.order.clone(),
925                usize::from(leaf.op.data),
926            )
927        });
928        leaves
929    }
930
931    fn disconnected_component_nodes(&self, node: NodeIndex) -> Result<Vec<NodeIndex>> {
932        let operation = &self.graph[node];
933        let factors = self
934            .wood
935            .join_factors(self.graph.source_node(node))
936            .ok_or_else(|| eyre!("{operation} has no disconnected component factors"))?;
937        let target_ops = operation
938            .key
939            .iter_levels_top_down()
940            .flat_map(|level| level.iter_leaf_ops())
941            .cloned()
942            .collect::<Vec<_>>();
943
944        for op in &target_ops {
945            let owners = factors
946                .iter()
947                .filter(|factor| factor.includes(&op.order))
948                .count();
949            if owners != 1 {
950                return Err(eyre!(
951                    "operation {} in {operation} belongs to {owners} disconnected factors",
952                    op.order.string_label()
953                ));
954            }
955        }
956
957        factors
958            .into_iter()
959            .map(|factor| {
960                let key = target_ops
961                    .iter()
962                    .filter(|op| factor.includes(&op.order))
963                    .fold(TraceKey::empty(), |key, op| {
964                        key.push(&self.wood, op.clone())
965                    });
966                self.graph
967                    .iter_nodes()
968                    .find_map(|(component, _, candidate)| {
969                        (candidate.key == key && self.source_spinney(component).filter() == &factor)
970                            .then_some(component)
971                    })
972                    .ok_or_else(|| {
973                        eyre!(
974                            "component {} of {operation} is not in the unfolded forest",
975                            factor.string_label()
976                        )
977                    })
978            })
979            .collect()
980    }
981
982    fn operation_node_index(&self, operation: &OperationNode) -> Result<NodeIndex> {
983        let cover = operation.covers();
984        self.graph
985            .iter_nodes()
986            .find_map(|(node, _, candidate)| {
987                let source_matches = cover.as_ref().map_or_else(
988                    || self.source_spinney(node).filter().is_empty(),
989                    |cover| self.source_spinney(node).filter() == cover,
990                );
991                (candidate == operation && source_matches).then_some(node)
992            })
993            .ok_or_else(|| eyre!("{operation} is not in the unfolded forest"))
994    }
995
996    fn union_replay_states(&self, node: NodeIndex) -> Result<Vec<UnionReplayState>> {
997        let operation = &self.graph[node];
998        if operation.key.is_empty() {
999            return Ok(vec![UnionReplayState {
1000                integrated: node,
1001                local_edges: Vec::new(),
1002            }]);
1003        }
1004
1005        if !self.graph.is_disjoint_union(node) {
1006            let (parent, edge) = self
1007                .graph
1008                .unique_parent(node)
1009                .ok_or_else(|| eyre!("{operation} has no unique replay parent"))?;
1010            let mut states = self.union_replay_states(parent)?;
1011            for state in &mut states {
1012                state.local_edges.push(edge);
1013            }
1014            states.push(UnionReplayState {
1015                integrated: node,
1016                local_edges: Vec::new(),
1017            });
1018            return Ok(states);
1019        }
1020
1021        let component_states = self
1022            .disconnected_component_nodes(node)?
1023            .into_iter()
1024            .map(|component| self.union_replay_states(component))
1025            .collect::<Result<Vec<_>>>()?;
1026        let mut states = Vec::new();
1027        for components in component_states
1028            .iter()
1029            .map(|states| states.iter())
1030            .multi_cartesian_product()
1031        {
1032            let key = TraceKey::try_foata_join(
1033                components
1034                    .iter()
1035                    .map(|component| &self.graph[component.integrated].key),
1036                &self.wood,
1037            )
1038            .ok_or_else(|| eyre!("cannot join integrated prefixes for {operation}"))?;
1039            let mut local_edges = Vec::new();
1040            for component in components {
1041                local_edges.extend_from_slice(&component.local_edges);
1042            }
1043            let integrated = self.operation_node_index(&OperationNode { key })?;
1044            states.push(UnionReplayState {
1045                integrated,
1046                local_edges,
1047            });
1048        }
1049
1050        Ok(states)
1051    }
1052
1053    fn compute_4d_for_node(
1054        &self,
1055        node: NodeIndex,
1056        graph: &Graph,
1057        model: &Model,
1058        vakint: &Vakint,
1059        settings: &UVgenerationSettings,
1060    ) -> Result<(Local4dCts, IntegratedCts)> {
1061        let operation = &self.graph[node];
1062        if operation.key.is_empty() {
1063            return Ok((Local4dCts::root(), IntegratedCts::root()));
1064        }
1065
1066        if self.graph.is_disjoint_union(node) {
1067            let components = self.disconnected_component_nodes(node)?;
1068            let mut full_components = Vec::with_capacity(components.len());
1069            let mut integrated_components = Vec::with_capacity(components.len());
1070            for component in components {
1071                let component_operation = &self.graph[component];
1072                full_components.push(self.recursion_input_4d(component).wrap_err_with(|| {
1073                    format!("while loading 4D component {component_operation} for {operation}")
1074                })?);
1075                integrated_components.push(
1076                    self.compute_store
1077                        .require(component_operation)?
1078                        .integrated(component_operation)?,
1079                );
1080            }
1081
1082            let depth = graph.n_loops(
1083                &operation
1084                    .covers()
1085                    .expect("a non-root operation has a cover"),
1086            ) + 1;
1087            return Ok((
1088                Local4dCts::from_full_product(full_components)?,
1089                IntegratedCts::factorized_product(integrated_components, depth)?,
1090            ));
1091        }
1092
1093        let (parent, edge) = self
1094            .graph
1095            .unique_parent(node)
1096            .ok_or_else(|| eyre!("{operation} has no unique 4D parent"))?;
1097        let full = self
1098            .recursion_input_4d(parent)
1099            .wrap_err_with(|| format!("while loading the 4D parent for {operation}"))?;
1100        let step_order = self.graph[parent].key.op_count();
1101        let (current, given) = self.wood.current_given_pair(edge, step_order);
1102        let ctx = UVCtx::new(graph, model, settings);
1103        let integrated_approximation = Integrated::new(vakint, &self.wood.vakint_settings);
1104        let local = local_4d::uv_limit(&full, &ctx, &current, &given, &current, &given)?;
1105        let integrated = if settings.generate_integrated {
1106            integrated_approximation.run(&local, &ctx, &current, &given, &current, &given)?
1107        } else {
1108            IntegratedCts::zero_like(local.atom())?
1109        };
1110
1111        Ok((local, integrated))
1112    }
1113
1114    fn local_3d_for_node(
1115        &self,
1116        node: NodeIndex,
1117        graph: &mut Graph,
1118        cutset: &CutSet,
1119        localizer: Localizer<'_>,
1120        settings: &UVgenerationSettings,
1121        projection_context: &mut Local4dProjectionContext,
1122    ) -> Result<CutComputation> {
1123        let operation = &self.graph[node];
1124        let forest_node = ForestNode {
1125            spinney: self.source_spinney(node),
1126            topo_order: operation.key.op_count(),
1127        };
1128        let local_3d = if operation.key.is_empty() {
1129            Local3DCts::Direct(Direct3dCts::root(graph, localizer)?)
1130        } else if settings.local_uv_cts_from_expanded_4d_integrands {
1131            // This is the only route that may produce `Projected4d`: the 4D
1132            // Taylor coefficient is kept factorized and final assembly later
1133            // attaches its untouched outer CFF. It never enters any of the
1134            // `Direct3dApproximation` replay operations below.
1135            let local_4d = self.compute_store.require(operation)?.local_4d(operation)?;
1136            Local3DCts::Projected4d(
1137                Projected4dApproximation::new(localizer, graph, settings)
1138                    .project_local_4d(local_4d, projection_context)?,
1139            )
1140        } else if self.graph.is_disjoint_union(node) {
1141            // Both direct variants replay the Taylor operators on the complete
1142            // post-energy-integration CFF. `explicit_orientation_sum_only`
1143            // changes selector materialization only, not this construction.
1144            let mut active_sectors = Vec::new();
1145            for state in self
1146                .union_replay_states(node)?
1147                .into_iter()
1148                .filter(|state| !state.local_edges.is_empty())
1149            {
1150                let integrated_operation = &self.graph[state.integrated];
1151                let mut edges = state.local_edges.into_iter().enumerate();
1152                let (offset, first_edge) = edges
1153                    .next()
1154                    .expect("a proper integrated prefix has a local suffix");
1155                let step_order = integrated_operation.key.op_count() + offset;
1156                let (current, given) = self.wood.current_given_pair(first_edge, step_order);
1157
1158                // An empty integrated prefix starts from the per-cut root integrand. Every
1159                // other prefix enters through the reduced branch of its first local operation.
1160                let mut sector = if integrated_operation.key.is_empty() {
1161                    let root = Direct3dCts::root(graph, localizer)?;
1162                    Direct3dApproximation::new(localizer, graph, settings)
1163                        .run_local(&root, &current, &given, &current, &given)?
1164                } else {
1165                    // Retain each connected coefficient's owner before the
1166                    // product enters a local suffix. Equal physical masses in
1167                    // a disjoint sibling must not acquire the parent's grading.
1168                    // Keep disconnected vacuum masses owned as well; the
1169                    // complete union still determines the localization kernel.
1170                    let components = if self.graph.is_disjoint_union(state.integrated) {
1171                        self.disconnected_component_nodes(state.integrated)?
1172                    } else {
1173                        vec![state.integrated]
1174                    };
1175                    let finite_components = components
1176                        .into_iter()
1177                        .map(|component| {
1178                            let operation = &self.graph[component];
1179                            let integrated = self
1180                                .compute_store
1181                                .require(operation)?
1182                                .integrated(operation)?;
1183                            Ok((
1184                                integrated.physical_finite_counterterm()?,
1185                                ForestNode {
1186                                    spinney: self.source_spinney(component),
1187                                    topo_order: operation.key.op_count(),
1188                                },
1189                            ))
1190                        })
1191                        .collect::<Result<Vec<_>>>()?;
1192                    let finite_counterterms = finite_components
1193                        .iter()
1194                        .map(|(coefficient, owner)| (coefficient, owner))
1195                        .collect::<Vec<_>>();
1196                    // A disabled (or algebraically vanishing) integrated prefix
1197                    // still owns its typed component-path frame. Replay that
1198                    // zero coefficient through the local suffix; it remains
1199                    // algebraically zero without deleting the union sector.
1200                    let prefix_node = ForestNode {
1201                        spinney: self.source_spinney(state.integrated),
1202                        topo_order: integrated_operation.key.op_count(),
1203                    };
1204                    Direct3dApproximation::new(localizer, graph, settings).run_integrated(
1205                        &finite_counterterms,
1206                        &prefix_node,
1207                        &current,
1208                        &given,
1209                        &current,
1210                        &given,
1211                    )?
1212                };
1213
1214                for (offset, edge) in edges {
1215                    let step_order = integrated_operation.key.op_count() + offset;
1216                    let (current, given) = self.wood.current_given_pair(edge, step_order);
1217                    sector = Direct3dApproximation::new(localizer, graph, settings)
1218                        .run_local(&sector, &current, &given, &current, &given)?;
1219                }
1220
1221                // Keep each active/frozen split after its root-path replay so any connected
1222                // descendants rescale only the loop variables still active in that sector.
1223                active_sectors.extend(sector.sectors()?.iter().cloned());
1224            }
1225
1226            Local3DCts::Direct(
1227                Direct3dCts::from_sectors(active_sectors)
1228                    .wrap_err_with(|| format!("{operation} has no proper integrated prefixes"))?,
1229            )
1230        } else {
1231            let (parent, edge) = self
1232                .graph
1233                .unique_parent(node)
1234                .ok_or_else(|| eyre!("{operation} has no unique local parent"))?;
1235            let parent_operation = &self.graph[parent];
1236            // An empty dependency frontier starts from the per-cut root integrand;
1237            // otherwise its typed local result remains the sequential accumulator.
1238            let root;
1239            let parent_local = if parent_operation.key.is_empty() {
1240                root = Direct3dCts::root(graph, localizer)?;
1241                &root
1242            } else {
1243                self.compute_store
1244                    .require(parent_operation)?
1245                    .cut(parent_operation, cutset)?
1246                    .local_3d
1247                    .direct()?
1248            };
1249            let parent_integrated = self
1250                .compute_store
1251                .require(parent_operation)?
1252                .integrated(parent_operation)
1253                .wrap_err_with(|| {
1254                    format!("while loading integrated parent {parent_operation} for {operation}")
1255                })?;
1256            let step_order = parent_operation.key.op_count();
1257            let (current, given) = self.wood.current_given_pair(edge, step_order);
1258            // `run` applies the next Taylor operator to the complete CFF and
1259            // applies both subtraction signs; no projected 4D coefficient,
1260            // external sign, or raw Foata-level product enters this route.
1261            Local3DCts::Direct(Direct3dApproximation::new(localizer, graph, settings).run(
1262                parent_local,
1263                parent_integrated,
1264                &current,
1265                &given,
1266                &current,
1267                &given,
1268            )?)
1269        };
1270
1271        let integrated = self
1272            .compute_store
1273            .require(operation)?
1274            .integrated(operation)?;
1275        let final_builder = FinalIntegrandBuilder::new(localizer, settings);
1276        let final_integrands = match &local_3d {
1277            Local3DCts::Direct(direct) => {
1278                final_builder.build_direct(graph, &forest_node, direct, integrated)?
1279            }
1280            Local3DCts::Projected4d(projected) => {
1281                final_builder.build_projected(graph, &forest_node, projected, integrated)?
1282            }
1283        };
1284
1285        Ok(CutComputation {
1286            local_3d,
1287            final_integrands,
1288        })
1289    }
1290
1291    pub fn integrate(
1292        &mut self,
1293        graph: &Graph,
1294        model: &Model,
1295        vakint: &Vakint,
1296        settings: &UVgenerationSettings,
1297    ) -> Result<()> {
1298        for (order, nidx) in self
1299            .graph
1300            .topo_sort_kahn(DirectionBasis::Underlying)?
1301            .into_iter()
1302            .enumerate()
1303        {
1304            debug!(order, nidx=%nidx, key=%self.graph[nidx], "Computing hedge-poset 4D term");
1305            let operation = self.graph[nidx].clone();
1306            let node_started = std::time::Instant::now();
1307            let (local_4d, integrated) =
1308                self.compute_4d_for_node(nidx, graph, model, vakint, settings)?;
1309            let node_elapsed = node_started.elapsed();
1310            let cover = operation
1311                .covers()
1312                .unwrap_or_else(|| self.graph.empty_subgraph())
1313                .string_label();
1314            let source = self.source_spinney(nidx).filter().string_label();
1315            debug_tags!(#generation, #uv, #integrated, #graph, #term, #inspect, #profile, #summary;
1316                stage = "hedge_poset_4d_node_done",
1317                graph_name = %graph.name,
1318                empty_history = operation.key.is_empty(),
1319                elapsed_ms = node_elapsed.as_secs_f64() * 1000.0,
1320                finished_unix_milliseconds = u64::try_from(
1321                    std::time::SystemTime::now()
1322                        .duration_since(std::time::UNIX_EPOCH)?
1323                        .as_millis(),
1324                )?,
1325                order,
1326                node_index = %nidx,
1327                forest_term = %operation,
1328                cover = %cover,
1329                source = %source,
1330                is_union = self.graph.is_disjoint_union(nidx),
1331                log.local_4d = local_4d.atom().expression(),
1332                log.integrated_pole = integrated.physical_pole()?.expression(),
1333                log.integrated_finite = integrated.physical_finite_counterterm()?.expression(),
1334                "Computed hedge-poset 4D node"
1335            );
1336            let computed = self.compute_store.entry(operation).or_default();
1337            computed.local_4d = Some(local_4d);
1338            computed.integrated = Some(integrated);
1339        }
1340
1341        Ok(())
1342    }
1343
1344    /// Prepare the representation-independent 4D lane once, at the first
1345    /// selected orientation. The requested model remains the source of rules.
1346    pub(crate) fn prepare_four_d(
1347        &mut self,
1348        graph: &Graph,
1349        model: &Model,
1350        vakint: &Vakint,
1351        settings: &UVgenerationSettings,
1352        projection_context: &mut Local4dProjectionContext,
1353    ) -> Result<()> {
1354        let started = Instant::now();
1355        if settings.generate_integrated || settings.local_uv_cts_from_expanded_4d_integrands {
1356            // Local-4D projection also needs these coefficients when analytic addbacks are off.
1357            self.integrate(graph, model, vakint, settings)?;
1358        } else {
1359            // Direct local-3D consumes only the zero integrated lane. Seed every
1360            // operation because a disconnected replay can visit a prefix first.
1361            let mut zero_by_cover: BTreeMap<SuBitGraph, IntegratedCts> = BTreeMap::new();
1362            for (_, _, operation) in self.graph.iter_nodes() {
1363                let zero = match operation.covers() {
1364                    Some(cover) => {
1365                        if let Some(cached) = zero_by_cover.get(&cover) {
1366                            cached.clone()
1367                        } else {
1368                            let carrier = graph
1369                                .numerator(&cover, &graph.empty_subgraph())?
1370                                .to_d_dim(GS.dim)?
1371                                .state
1372                                .expr;
1373                            let zero = IntegratedCts::zero_like(&carrier)?;
1374                            zero_by_cover.insert(cover, zero.clone());
1375                            zero
1376                        }
1377                    }
1378                    None => IntegratedCts::root(),
1379                };
1380                self.compute_store
1381                    .entry(operation.clone())
1382                    .or_default()
1383                    .integrated = Some(zero);
1384            }
1385        }
1386        projection_context.shared_preparation_time += started.elapsed();
1387        Ok(())
1388    }
1389
1390    /// Return the measured representation-independent part of this computation.
1391    pub(crate) fn compute(
1392        &mut self,
1393        graph: &mut Graph,
1394        orientation: OrientationProjection<'_>,
1395        settings: &UVgenerationSettings,
1396        projection_context: &mut Local4dProjectionContext,
1397    ) -> Result<Duration> {
1398        let shared_before = projection_context.shared_preparation_time;
1399        for (compatible_subset, cutset) in self.cuts.clone() {
1400            let localizer = Localizer::new(&cutset, orientation);
1401            for (order, nidx) in self
1402                .compatible_topological_order(&compatible_subset)?
1403                .into_iter()
1404                .enumerate()
1405            {
1406                debug!(order, nidx=%nidx, key=%self.graph[nidx], "Computing hedge-poset per-cut term");
1407                let operation = self.graph[nidx].clone();
1408                // Direct local-3D nodes Taylor-expand the complete post-energy-integration CFF.
1409                // Expanded-4D nodes instead project their typed local coefficients and attach
1410                // the outer CFF only during final assembly.
1411                let cut_computation = self.local_3d_for_node(
1412                    nidx,
1413                    graph,
1414                    &cutset,
1415                    localizer,
1416                    settings,
1417                    projection_context,
1418                )?;
1419                self.compute_store
1420                    .entry(operation)
1421                    .or_default()
1422                    .cuts
1423                    .insert(cutset.clone(), cut_computation);
1424            }
1425        }
1426
1427        Ok(projection_context.shared_preparation_time - shared_before)
1428    }
1429
1430    pub(crate) fn orientation_parametric_exprs(
1431        &self,
1432        graph: &Graph,
1433        _settings: &UVgenerationSettings,
1434    ) -> Result<Vec<ParametricIntegrands>> {
1435        let split_momentum_replacements = graph
1436            .iter_edges_of(
1437                &graph
1438                    .full_filter()
1439                    .subtract(&graph.initial_state_cut)
1440                    .subtract(&graph.tree_edges),
1441            )
1442            .filter_map(|(pair, edge_index, _)| {
1443                (!matches!(pair, HedgePair::Unpaired { .. }))
1444                    .then(|| GS.split_mom_pattern_simple(edge_index))
1445            })
1446            .collect::<Vec<_>>();
1447        let mut expressions = Vec::with_capacity(self.cuts.len());
1448
1449        for (compatible_subset, cutset) in &self.cuts {
1450            let mut sum: Option<FinalIntegrands> = None;
1451            for nidx in self.compatible_topological_order(compatible_subset)? {
1452                let operation = &self.graph[nidx];
1453                let terms = self
1454                    .compute_store
1455                    .require(operation)?
1456                    .cut(operation, cutset)?
1457                    .final_integrands
1458                    .collect(TensorCollectFilter::Reps([
1459                        ColorAdjoint {}.into(),
1460                        ColorFundamental {}.into(),
1461                        ColorSextet {}.into(),
1462                    ]))?;
1463                sum = Some(match sum {
1464                    Some(sum) => sum.zip_add([terms]).wrap_err_with(|| {
1465                        format!("while aggregating hedge-poset term {operation} for cut {cutset:?}")
1466                    })?,
1467                    None => terms,
1468                });
1469            }
1470            // A per-node final integrand retains inspect/export provenance but
1471            // is not independently evaluator-ready.  In particular, temporal
1472            // components in localized integrated counterterms can cancel only
1473            // in the completed signed forest.  Preserve that exact cancellation
1474            // before the final orientation-local momentum split.
1475            let integrands = sum
1476                .ok_or_else(|| eyre!("No terms in hedge-poset forest for cut {cutset:?}"))?
1477                .map_expressions(|integrand| {
1478                    Ok(integrand
1479                        .replace_multiple(&split_momentum_replacements)
1480                        .replace(function!(GS.den, W_.a_, W_.b_, W_.c_, W_.d_))
1481                        .with(W_.d_))
1482                })?;
1483            expressions.push(ParametricIntegrands::from_final(integrands, cutset.clone()));
1484        }
1485
1486        Ok(expressions)
1487    }
1488
1489    pub(crate) fn export_node_expressions(
1490        &self,
1491        forest_index: usize,
1492        post_process: &mut impl FnMut(Atom) -> Atom,
1493    ) -> Result<Vec<UVForestNodeExpression>> {
1494        let (cut_compatible_forest_subset, cutset) = self
1495            .cuts
1496            .first()
1497            .ok_or_else(|| eyre!("No cuts in hedge-poset forest export"))?;
1498        let mut terms = Vec::new();
1499        for (node_index, nidx) in self
1500            .compatible_topological_order(cut_compatible_forest_subset)?
1501            .into_iter()
1502            .enumerate()
1503        {
1504            let operation = &self.graph[nidx];
1505            let computed = self.compute_store.require(operation)?;
1506            let cut_computation = computed.cut(operation, cutset)?;
1507            let final_integrands = cut_computation
1508                .final_integrands
1509                .clone()
1510                .into_integrands()
1511                .resolved()?
1512                .map(|numerator| post_process(numerator.clone()));
1513            let node_key = operation.to_string();
1514            let provenance = self.node_export_3d_provenance(nidx, &cut_computation.local_3d);
1515            for (term_index, (&residue_index, numerator)) in final_integrands.iter().enumerate() {
1516                terms.push(UVForestNodeExpression {
1517                    forest_index,
1518                    node_index,
1519                    node_key: node_key.clone(),
1520                    term_index,
1521                    residue_index,
1522                    numerator: numerator.clone(),
1523                    forest_provenance: Some(provenance.clone()),
1524                });
1525            }
1526        }
1527
1528        Ok(terms)
1529    }
1530
1531    pub(crate) fn export_4d_node_expressions(
1532        &self,
1533        forest_index: usize,
1534    ) -> Result<Vec<UVForestNodeExpression>> {
1535        let (cut_compatible_forest_subset, _) = self
1536            .cuts
1537            .first()
1538            .ok_or_else(|| eyre!("No cuts in hedge-poset forest export"))?;
1539        self.compatible_topological_order(cut_compatible_forest_subset)?
1540            .into_iter()
1541            .enumerate()
1542            .map(|(node_index, nidx)| {
1543                let operation = &self.graph[nidx];
1544                let local_4d = self.compute_store.require(operation)?.local_4d(operation)?;
1545                Ok(UVForestNodeExpression {
1546                    forest_index,
1547                    node_index,
1548                    node_key: operation.to_string(),
1549                    term_index: 0,
1550                    residue_index: crate::cff::CutCFFIndex::new_all_none(),
1551                    numerator: local_4d.atom().expression().clone(),
1552                    forest_provenance: Some(self.node_export_4d_provenance(nidx, local_4d)),
1553                })
1554            })
1555            .collect()
1556    }
1557
1558    fn node_parent_keys(&self, node: NodeIndex) -> Vec<String> {
1559        let mut parent_keys = self
1560            .graph
1561            .parents(node)
1562            .map(|(parent, _)| self.graph[parent].to_string())
1563            .collect::<Vec<_>>();
1564        parent_keys.sort();
1565        parent_keys.dedup();
1566        parent_keys
1567    }
1568
1569    fn node_export_4d_provenance(
1570        &self,
1571        node: NodeIndex,
1572        local_4d: &Local4dCts,
1573    ) -> Arc<UVForestProvenance> {
1574        Arc::new(UVForestProvenance {
1575            node: UVForestNodeProvenance {
1576                parent_keys: self.node_parent_keys(node),
1577                local: UVForestLocalProvenance::FourD {
1578                    components: local_4d.provenance_components().to_vec(),
1579                    branches: local_4d.provenance_branches().to_vec(),
1580                },
1581            },
1582        })
1583    }
1584
1585    fn node_export_3d_provenance(
1586        &self,
1587        node: NodeIndex,
1588        local_3d: &Local3DCts,
1589    ) -> Arc<UVForestProvenance> {
1590        Arc::new(UVForestProvenance {
1591            node: UVForestNodeProvenance {
1592                parent_keys: self.node_parent_keys(node),
1593                local: UVForestLocalProvenance::ThreeD {
1594                    projection_paths: local_3d.projection_paths(),
1595                },
1596            },
1597        })
1598    }
1599
1600    pub(crate) fn renormalization_part_of_ends(
1601        &self,
1602        graph: &Graph,
1603        settings: &UVgenerationSettings,
1604    ) -> Result<RenormalizationPart> {
1605        let mut sum: Option<SymbolicTensor<IndexedStructure>> = None;
1606        let marker = UvMarker::new(settings);
1607
1608        let wild = Atom::var(W_.x___);
1609
1610        let replacements =
1611            graph.integrand_replacement(&graph.full_filter(), &graph.loop_momentum_basis, &[wild]);
1612        let mut retained_prefactor = None;
1613        for (node, mut crown, key) in self.graph.iter_nodes() {
1614            if crown.any(|r| self.graph.flow(r).is_source()) {
1615                continue;
1616            }
1617
1618            let forest_node = key.forest_node(graph, key.key.op_count())?;
1619            // A disconnected terminal can combine components with different schemes. Select
1620            // each component's projection before multiplying; the aggregate integrated value
1621            // only represents the homogeneous all-finite and all-pole projections.
1622            let components = if self.graph.is_disjoint_union(node) {
1623                self.disconnected_component_nodes(node)?
1624            } else {
1625                vec![node]
1626            };
1627            let physical = components.into_iter().try_fold(
1628                SymbolicTensor::from_produced_indexed_parts(
1629                    Atom::one(),
1630                    IndexedStructure::identity(OrderedStructure::scalar_structure()),
1631                )?,
1632                |product, component| -> Result<_> {
1633                    let component_key = &self.graph[component];
1634                    let integrated = self
1635                        .compute_store
1636                        .require(component_key)?
1637                        .integrated(component_key)?;
1638                    let projection = match self.source_spinney(component).renormalization_scheme {
1639                        // The OS integral owns the vacuum scheme correction;
1640                        // its physical mass term stays in the local operator.
1641                        ApproximationType::MUV | ApproximationType::IR | ApproximationType::OS => {
1642                            integrated.physical_finite_counterterm()?
1643                        }
1644                        ApproximationType::PolePart => integrated.physical_pole()?,
1645                        scheme => {
1646                            return Err(eyre!("No terminal counterterm projection for {scheme}"));
1647                        }
1648                    };
1649                    Ok(product.multiply(projection)?)
1650                },
1651            )?;
1652            let marked = marker.prefix(
1653                &graph.full_filter(),
1654                forest_node.subgraph(),
1655                physical.expression(),
1656            );
1657            let physical = physical.with_produced_expression(marked)?;
1658            debug!(
1659                key=%key,
1660               expr = % physical.expression().log_print(None),"Term before simplification"
1661            );
1662            if retained_prefactor.is_none() {
1663                let overall = SymbolicTensor::infer_indexed(graph.overall_factor.clone())?;
1664                retained_prefactor = Some(
1665                    graph
1666                        .global_prefactor
1667                        .projector
1668                        .clone()
1669                        .multiply(graph.global_prefactor.num.clone())?
1670                        .multiply(overall)?,
1671                );
1672            }
1673            let prefactor = retained_prefactor
1674                .as_ref()
1675                .expect("initialized user prefactor")
1676                .clone();
1677            let cooking = CookSettings::indices()
1678                .with_mode(CookMode::ReversibleEncoding)
1679                .with_representation_payloads(true, true);
1680            let reduced = physical
1681                .multiply(prefactor)?
1682                .simplify_algebra(&idenso::tensor::AlgebraSettings {
1683                    color: Some(ColorSimplifySettings::default()),
1684                    ..Default::default()
1685                })?
1686                .contract(idenso::tensor::ContractSettings {
1687                    collect_chains: false,
1688                    collect_traces: false,
1689                    ..Default::default()
1690                })?
1691                .to_dots()?;
1692            let atom = cooking.uncook(reduced.expression().as_view());
1693
1694            debug!(
1695                key=%key,
1696               expr = % atom.log_print(None),"Term"
1697            );
1698            sum = Some(match sum {
1699                Some(sum) => sum.try_add(&reduced)?,
1700                None => reduced,
1701            });
1702        }
1703
1704        let sum = match sum {
1705            Some(sum) => sum,
1706            None => SymbolicTensor::from_produced_indexed_parts(
1707                Atom::Zero,
1708                IndexedStructure::identity(OrderedStructure::scalar_structure()),
1709            )?,
1710        };
1711        let cooking = CookSettings::indices()
1712            .with_mode(CookMode::ReversibleEncoding)
1713            .with_representation_payloads(true, true);
1714        Ok(RenormalizationPart::new(
1715            cooking
1716                .uncook(sum.expression().as_view())
1717                .replace_multiple(&replacements)
1718                .replace(GS.m_uv_expansion)
1719                .with(GS.m_uv_vacuum),
1720            sum.structure().clone(),
1721            self.graph.n_nodes(),
1722        ))
1723    }
1724
1725    pub fn debug_walk(&self) {
1726        let mut cover_groups: BTreeMap<SuBitGraph, Vec<NodeIndex>> = BTreeMap::new();
1727
1728        self.graph
1729            .topo_sort_kahn(DirectionBasis::Underlying)
1730            .unwrap()
1731            .iter()
1732            .for_each(|nidx| {
1733                let trace_key = &self.graph[*nidx];
1734                cover_groups
1735                    .entry(trace_key.covers().unwrap_or(self.graph.empty_subgraph()))
1736                    .and_modify(|e| e.push(*nidx))
1737                    .or_insert_with(|| vec![*nidx]);
1738
1739                println!("Node {}:{}", nidx, self.node_label(*nidx));
1740            });
1741
1742        println!("edge [constraint=true style=invis];");
1743        for (a, b) in cover_groups.values().tuple_windows() {
1744            println!("{}->{}", a.first().unwrap(), b.first().unwrap())
1745        }
1746        println!("edge [style=solid];");
1747
1748        for (s, g) in cover_groups.iter() {
1749            println!("subgraph group_{} {{rank=same; ", s.string_label());
1750            for n in g {
1751                println!("{};", n.0);
1752            }
1753            println!("}}");
1754        }
1755    }
1756}
1757
1758impl Display for Forests {
1759    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1760        let labels: AHashMap<_, _> = self
1761            .graph
1762            .iter_nodes()
1763            .map(|(node, _, key)| (key.clone(), self.node_label(node)))
1764            .collect();
1765        self.graph.dot_impl_fmt(
1766            f,
1767            &self.graph.full_filter(),
1768            "start=2;\n",
1769            &|_| None,
1770            &|_| None,
1771            &|v| Some(format!("label=\"{}\"", labels[v])),
1772        )
1773    }
1774}
1775
1776#[cfg(test)]
1777#[path = "native_mass_inventory_tests.rs"]
1778mod native_mass_inventory_tests;
1779
1780#[cfg(test)]
1781mod tests {
1782    use crate::initialisation;
1783    use crate::utils;
1784    use crate::uv::approx::integrated::native_mass_tests::QcdMassReference;
1785    use crate::uv::uv_graph::UVE;
1786    use crate::{
1787        finalized_runtime_dot,
1788        graph::{FeynmanGraph, Graph},
1789        initialisation::test_initialise,
1790        processes::DotExportSettings,
1791        uv::{
1792            UltravioletGraph, Wood as OldWood, approx::local_4d::Local4dBranch,
1793            settings::RenormalizationPrescriptionSettings,
1794        },
1795    };
1796    use idenso::color::ColorSimplifySettings;
1797    use idenso::tensor::{AlgebraContraction, AlgebraSettings, ContractSettings};
1798
1799    use super::*;
1800    use color_eyre::Result;
1801
1802    fn scalar_model() -> Model {
1803        crate::utils::load_generic_model("scalars")
1804    }
1805
1806    fn standard_model() -> Model {
1807        crate::utils::load_generic_model("sm")
1808    }
1809
1810    impl Forests {
1811        fn normalized_node_label(&self, node: NodeIndex) -> String {
1812            let label = self.node_label(node);
1813            let mut normalized = String::with_capacity(label.len());
1814            let mut chars = label.chars().peekable();
1815
1816            while let Some(ch) = chars.next() {
1817                normalized.push(ch);
1818                if ch != '(' {
1819                    continue;
1820                }
1821
1822                let mut digits = String::new();
1823                while chars.peek().is_some_and(|next| next.is_ascii_digit()) {
1824                    digits.push(chars.next().expect("peeked digit must exist"));
1825                }
1826
1827                if digits.is_empty() || !matches!(chars.peek(), Some(')')) {
1828                    normalized.push_str(&digits);
1829                } else {
1830                    normalized.push('_');
1831                }
1832            }
1833
1834            normalized
1835        }
1836
1837        fn normalized_node_labels_with_cover(&self, cover_label: &str) -> Vec<String> {
1838            let mut labels = self
1839                .graph
1840                .iter_nodes()
1841                .filter(|(_, _, operation)| {
1842                    operation
1843                        .covers()
1844                        .is_some_and(|cover| cover.string_label() == cover_label)
1845                })
1846                .map(|(node, _, _)| self.normalized_node_label(node))
1847                .collect::<Vec<_>>();
1848            labels.sort();
1849            labels
1850        }
1851    }
1852
1853    #[test]
1854    fn three_d_compute_skips_unused_four_d_atoms_when_integration_is_disabled() -> Result<()> {
1855        test_initialise().unwrap();
1856        for project_local_4d in [false, true] {
1857            let mut graph: Graph = Graph::import_dot(
1858                stringify!(digraph scalar_self_energy {
1859                    edge [particle="scalar_1"];
1860                    node [num=1];
1861                    ext [style=invis];
1862                    ext -> a;
1863                    b -> ext;
1864                    a -> b;
1865                    a -> b;
1866                }),
1867                &crate::utils::load_generic_model("scalars"),
1868            )
1869            .map(|mut graphs| {
1870                assert_eq!(graphs.len(), 1, "one fixture graph expected");
1871                graphs.remove(0)
1872            })?;
1873            let settings = GenerationSettings {
1874                uv: UVgenerationSettings {
1875                    generate_integrated: false,
1876                    local_uv_cts_from_expanded_4d_integrands: project_local_4d,
1877                    ..Default::default()
1878                },
1879                ..Default::default()
1880            };
1881            let orientation_pattern = crate::settings::global::OrientationPattern::default();
1882            let options = graph.denominator_only_cff_3d_expression_options();
1883            let production = graph.generate_3d_expression_for_integrand(
1884                &[],
1885                &graph.get_esurface_canonization(&graph.loop_momentum_basis),
1886                &options,
1887                Some(&Atom::one()),
1888            )?;
1889            let mut forests =
1890                Wood::new(CutStructure::empty(&graph), &graph, &graph.model, &settings)?.unfold();
1891
1892            let model = graph.model.clone();
1893            let mut context = Local4dProjectionContext::default();
1894            forests.prepare_four_d(
1895                &graph,
1896                &model,
1897                crate::utils::vakint()?,
1898                &settings.uv,
1899                &mut context,
1900            )?;
1901            forests.compute(
1902                &mut graph,
1903                OrientationProjection::exact_expression(
1904                    &production,
1905                    &options,
1906                    &orientation_pattern,
1907                    true,
1908                ),
1909                &settings.uv,
1910                &mut context,
1911            )?;
1912
1913            if project_local_4d {
1914                let mut legacy = crate::uv::wood::CutWoods::new(
1915                    CutStructure::empty(&graph),
1916                    &graph,
1917                    &model,
1918                    &settings,
1919                )?
1920                .unfold(&graph);
1921                let mut legacy_context = Local4dProjectionContext::default();
1922                legacy.compute(
1923                    &mut graph,
1924                    crate::utils::vakint()?,
1925                    OrientationProjection::exact_expression(
1926                        &production,
1927                        &options,
1928                        &orientation_pattern,
1929                        true,
1930                    ),
1931                    &settings.uv,
1932                    true,
1933                    &mut legacy_context,
1934                )?;
1935                let canonical_builds = [
1936                    context.canonical_preparation_builds,
1937                    legacy_context.canonical_preparation_builds,
1938                ];
1939                assert!(canonical_builds.iter().all(|count| *count > 0));
1940                for representation in [
1941                    three_dimensional_reps::RepresentationMode::Ltd,
1942                    three_dimensional_reps::RepresentationMode::Cff,
1943                ] {
1944                    let options = three_dimensional_reps::Generate3DExpressionOptions {
1945                        representation,
1946                        ..options.clone()
1947                    };
1948                    let production = graph.generate_3d_expression_for_integrand(
1949                        &[],
1950                        &graph.get_esurface_canonization(&graph.loop_momentum_basis),
1951                        &options,
1952                        Some(&Atom::one()),
1953                    )?;
1954                    assert_eq!(production.representation, representation);
1955                    let orientation = OrientationProjection::exact_expression(
1956                        &production,
1957                        &options,
1958                        &orientation_pattern,
1959                        true,
1960                    );
1961                    let before = [&context, &legacy_context].map(|context| {
1962                        (
1963                            context.shared_preparation_time,
1964                            context.preparations.hits,
1965                            context.source_preparation_builds,
1966                            context.generation_cache.native_generations,
1967                        )
1968                    });
1969                    let shared = [
1970                        forests.compute(&mut graph, orientation, &settings.uv, &mut context)?,
1971                        legacy.compute(
1972                            &mut graph,
1973                            crate::utils::vakint()?,
1974                            orientation,
1975                            &settings.uv,
1976                            false,
1977                            &mut legacy_context,
1978                        )?,
1979                    ];
1980                    for (index, context) in [&context, &legacy_context].into_iter().enumerate() {
1981                        assert_eq!(
1982                            context.canonical_preparation_builds,
1983                            canonical_builds[index]
1984                        );
1985                        assert!(context.preparations.hits > before[index].1);
1986                        assert_eq!(
1987                            shared[index],
1988                            context.shared_preparation_time - before[index].0
1989                        );
1990                        if representation == three_dimensional_reps::RepresentationMode::Ltd {
1991                            assert!(context.source_preparation_builds > before[index].2);
1992                            assert!(context.generation_cache.native_generations > before[index].3);
1993                        } else {
1994                            assert_eq!(context.source_preparation_builds, before[index].2);
1995                            assert_eq!(
1996                                context.generation_cache.native_generations,
1997                                before[index].3
1998                            );
1999                        }
2000                    }
2001                }
2002            }
2003
2004            assert_eq!(forests.compute_store.entries.len(), forests.graph.n_nodes());
2005            for (_, _, operation) in forests.graph.iter_nodes() {
2006                let computed = forests.compute_store.require(operation)?;
2007                assert_eq!(
2008                    computed.local_4d.is_some(),
2009                    project_local_4d,
2010                    "4D coefficients must be constructed exactly when the projected route needs them for {operation}"
2011                );
2012                let integrated = computed.integrated(operation)?;
2013                assert!(integrated.physical_pole()?.is_zero());
2014                assert!(integrated.physical_finite_counterterm()?.is_zero());
2015                assert!(
2016                    !computed.cuts.is_empty(),
2017                    "both routes must compute a cut for {operation}"
2018                );
2019                assert!(
2020                    computed
2021                        .cuts
2022                        .values()
2023                        .all(|cut| cut.final_integrands.iter().next().is_some()),
2024                    "every computed cut must retain a 3D final integrand for {operation}"
2025                );
2026            }
2027        }
2028
2029        Ok(())
2030    }
2031
2032    #[test]
2033    fn integrated_os_rainbow_retains_nonzero_owned_scheme_coefficients() -> Result<()> {
2034        use crate::numerator::symbolica_ext::NumeratorAtomExt;
2035        use crate::uv::{
2036            CTIdentifier, CTRenormalizationRule, orchestrator::validate_local_counterterm_schemes,
2037        };
2038
2039        test_initialise()?;
2040        // Exactly the public run-card graph, before external on-shell spinors
2041        // can annihilate its field-like finite scheme correction.
2042        let mut graphs = Graph::import_dot(
2043            include_str!(
2044                "../../../../tests/resources/graphs/local_nested_soft_top_self_energy.dot"
2045            ),
2046            &standard_model(),
2047        )?;
2048        assert_eq!(graphs.len(), 1);
2049        let graph = graphs.remove(0);
2050        let identifier = CTIdentifier::new(BTreeSet::from([-6, 6]), Some(BTreeSet::from([6, 21])));
2051        let settings = GenerationSettings {
2052            explicit_orientation_sum_only: true,
2053            uv: UVgenerationSettings {
2054                generate_integrated: true,
2055                local_uv_cts_from_expanded_4d_integrands: true,
2056                orchestrator: crate::uv::UVOrchestrator::HedgePoset,
2057                add_marker: false,
2058                renormalization_prescription: RenormalizationPrescriptionSettings {
2059                    overrides: vec![CTRenormalizationRule::new(
2060                        identifier.clone(),
2061                        ApproximationType::OS,
2062                    )],
2063                    ..Default::default()
2064                },
2065                ..Default::default()
2066            },
2067            ..Default::default()
2068        };
2069        let cuts = CutStructure::empty(&graph);
2070        assert!(validate_local_counterterm_schemes(
2071            &graph,
2072            &cuts,
2073            &settings.uv
2074        )?);
2075        let mut forests = Wood::new(cuts, &graph, &graph.model, &settings)?.unfold();
2076        assert_eq!(
2077            forests
2078                .wood
2079                .vakint_settings
2080                .number_of_terms_in_epsilon_expansion,
2081            3
2082        );
2083        // [], [child], [parent], [child,parent]; no disjoint or extra history.
2084        assert_eq!(forests.graph.n_nodes(), 4);
2085        let mut histories = BTreeSet::new();
2086        let mut child_node = None;
2087        let mut nested_parent_node = None;
2088        for (node, _, operation) in forests.graph.iter_nodes() {
2089            assert!(!forests.graph.is_disjoint_union(node));
2090            let source = forests.source_spinney(node);
2091            let edges = graph
2092                .paired_edges(source.filter())
2093                .into_iter()
2094                .map(|edge| edge.0)
2095                .collect::<Vec<_>>();
2096            histories.insert((edges.clone(), operation.key.op_count()));
2097            if edges == [3, 4] {
2098                child_node = Some(node);
2099            } else if edges == [2, 3, 4, 5, 6] && operation.key.op_count() == 2 {
2100                nested_parent_node = Some(node);
2101            }
2102            if !operation.key.is_empty() {
2103                assert_eq!(source.renormalization_scheme, ApproximationType::OS);
2104                assert_eq!(source.dod, 1);
2105                assert_eq!(
2106                    graph.ct_identifier(source.filter(), &graph.model),
2107                    identifier
2108                );
2109            }
2110        }
2111        assert_eq!(
2112            histories,
2113            BTreeSet::from([
2114                (vec![], 0),
2115                (vec![3, 4], 1),
2116                (vec![2, 3, 4, 5, 6], 1),
2117                (vec![2, 3, 4, 5, 6], 2),
2118            ])
2119        );
2120        forests.integrate(&graph, &graph.model, crate::utils::vakint()?, &settings.uv)?;
2121
2122        let scale_log = function!(
2123            symbolica::atom::Symbol::LOG,
2124            Atom::var(GS.m_uv_vacuum).pow(2) / Atom::var(GS.mu_r_sq)
2125        );
2126        let mut nonzero = BTreeSet::new();
2127        for (node, _, operation) in forests.graph.iter_nodes() {
2128            if operation.key.is_empty() {
2129                continue;
2130            }
2131            let computed = forests.compute_store.require(operation)?;
2132            let local = computed.local_4d(operation)?;
2133            let finite = computed
2134                .integrated(operation)?
2135                .physical_finite_counterterm()?;
2136            assert_eq!(
2137                finite.structure().logical_slots(),
2138                local.atom().structure().logical_slots()
2139            );
2140            assert!(
2141                !finite.is_zero(),
2142                "{operation}: integrated finite payload disappeared"
2143            );
2144            let source = forests.source_spinney(node);
2145            let loops = graph.n_loops(source.filter());
2146            // The source has already completed its actual operators and analytic
2147            // integration. Keep the original positive-epsilon payload unchanged;
2148            // inspect a separate constant-epsilon, generic-scale coefficient.
2149            let constant = finite.with_checked_expression(
2150                finite.expression().replace(GS.dim_epsilon).with(Atom::Zero),
2151            )?;
2152            let normalized = constant.simplify_algebra(&idenso::tensor::AlgebraSettings {
2153                color: Some(ColorSimplifySettings::default().with_cof_dimension_invariants()),
2154                ..Default::default()
2155            })?;
2156            let rows = normalized
2157                .expression()
2158                .coefficient_list_exact(std::slice::from_ref(&scale_log))
2159                .ok_or_else(|| eyre!("{operation}: finite scale-log polynomial was refused"))?;
2160            assert_eq!(
2161                rows.iter()
2162                    .map(|(monomial, _)| monomial.clone())
2163                    .collect::<BTreeSet<_>>(),
2164                (0..=loops)
2165                    .map(|power| scale_log.pow(power as i64))
2166                    .collect::<BTreeSet<_>>(),
2167                "{operation}: complete finite scale-log degree follows the source loop count",
2168            );
2169            let recomposed = Atom::add_many(
2170                rows.iter()
2171                    .map(|(monomial, coefficient)| monomial * coefficient),
2172            );
2173            let difference =
2174                normalized.with_checked_expression(normalized.expression() - &recomposed)?;
2175            // Check the complete finite tensor, including equivalent factored
2176            // scalar forms that generic coefficient collection cannot certify.
2177            let wrong = normalized
2178                .with_checked_expression(difference.expression() + normalized.expression())?;
2179            QcdMassReference::certify_finite_tagged_rows_zero(
2180                &format!(
2181                    "{operation}: scale-log rows exactly reconstruct the original finite tensor"
2182                ),
2183                difference,
2184            )?;
2185            assert!(
2186                QcdMassReference::certify_finite_tagged_rows_zero(
2187                    &format!(
2188                        "{operation}: nonzero finite tensor perturbation of scale-log recomposition"
2189                    ),
2190                    wrong,
2191                )
2192                .is_err()
2193            );
2194            let coefficient = rows
2195                .iter()
2196                .find(|(monomial, _)| *monomial == scale_log.pow(loops as i64))
2197                .expect("the independently bounded highest scale-log row exists")
2198                .1
2199                .clone();
2200            let mut exact = true;
2201            coefficient.visitor(&mut |view| {
2202                if let symbolica::atom::AtomView::Num(number) = view {
2203                    exact &= matches!(
2204                        number.get_coeff_view(),
2205                        symbolica::coefficient::CoefficientView::Natural(..)
2206                            | symbolica::coefficient::CoefficientView::Large(..)
2207                    );
2208                }
2209                true
2210            });
2211            assert!(
2212                exact,
2213                "{operation}: the nonzero witness must have exact rational coefficients"
2214            );
2215            // A nonzero retained coefficient at generic auxiliary scale, not
2216            // completeness of an independent open tensor basis. Numerical
2217            // master constants stay untouched in the unselected constant row.
2218            assert!(
2219                normalized
2220                    .with_checked_expression(coefficient)?
2221                    .coefficients_are_zero(TensorCollectFilter::<0>::Tensors)?
2222                    .is_false(),
2223                "{operation}: need an exactly nonzero highest scale-log coefficient",
2224            );
2225            nonzero.insert((loops, operation.key.op_count()));
2226        }
2227        assert_eq!(nonzero, BTreeSet::from([(1, 1), (2, 1), (2, 2)]));
2228
2229        let child = child_node.expect("the physical one-loop OS child exists");
2230        let operation = &forests.graph[child];
2231        let integrated = forests
2232            .compute_store
2233            .require(operation)?
2234            .integrated(operation)?;
2235        let expected = integrated.finite_counterterm()?;
2236        assert!(
2237            expected.expression().contains_symbol(GS.dim_epsilon),
2238            "the finite child retains positive epsilon orders for the parent pole"
2239        );
2240        let complete_child = forests.recursion_input_4d(child)?;
2241        let frozen = complete_child
2242            .sectors()
2243            .filter(|sector| !sector.frozen_lmbs().is_empty())
2244            .collect::<Vec<_>>();
2245        assert_eq!(frozen.len(), 1);
2246        assert!(frozen[0].active_components.is_empty());
2247        assert_eq!(
2248            frozen[0].frozen_lmbs(),
2249            std::slice::from_ref(&forests.source_spinney(child).lmb)
2250        );
2251        assert_eq!(
2252            frozen[0].atom, expected,
2253            "recursion carries the actual positive-epsilon coefficient exactly once"
2254        );
2255
2256        let parent = nested_parent_node.expect("the completed-child parent history exists");
2257        let operation = &forests.graph[parent];
2258        let local = forests
2259            .compute_store
2260            .require(operation)?
2261            .local_4d(operation)?;
2262        let sectors = local.active_sectors();
2263        assert_eq!(
2264            sectors.len(),
2265            2,
2266            "the parent acts on both local-child and finite-child sectors"
2267        );
2268        assert_eq!(
2269            sectors
2270                .iter()
2271                .filter(|sector| sector.frozen_lmbs().is_empty())
2272                .count(),
2273            1
2274        );
2275        let frozen_parent = sectors
2276            .iter()
2277            .filter(|sector| !sector.frozen_lmbs().is_empty())
2278            .collect::<Vec<_>>();
2279        assert_eq!(frozen_parent.len(), 1);
2280        assert_eq!(frozen_parent[0].active_components.len(), 1);
2281        assert_eq!(frozen_parent[0].frozen_lmbs(), frozen[0].frozen_lmbs());
2282        assert_ne!(
2283            frozen_parent[0].integration_atom().expression(),
2284            frozen_parent[0].atom.expression(),
2285            "the OS mass branch stays local while the vacuum remainder is integrated"
2286        );
2287        Ok(())
2288    }
2289
2290    #[test]
2291    fn vacuum_subtraction_prunes_only_full_observable_spinneys() -> Result<()> {
2292        use crate::settings::global::MediumMode;
2293
2294        test_initialise()?;
2295        let graphs: Vec<Graph> = Graph::unit_numerator_fixtures(
2296            stringify!(
2297            digraph sunrise {
2298                edge [particle="scalar_1"];
2299                v1 -> v2; v1 -> v2; v1 -> v2;
2300            }
2301            digraph dumbbell {
2302                edge [particle="scalar_1"];
2303                v1 -> v2;
2304                v2 -> v2;
2305                v1 -> v1; v1 -> v1;
2306            }
2307            digraph sunrise_with_bridge {
2308                edge [particle="scalar_1"];
2309                ext [style=invis];
2310                v1 -> v2; v1 -> v2; v1 -> v2;
2311                v2 -> v3;
2312                ext -> v3; v3 -> ext;
2313            }),
2314            &crate::utils::load_generic_model("scalars"),
2315        )?;
2316        for graph in graphs {
2317            // The counterterm covers the loop part, leaving any bridge untouched.
2318            let full = InternalSubGraph::cleaned_filter_pessimist(
2319                graph.full_filter().subtract(&graph.tree_edges),
2320                graph.as_ref(),
2321            );
2322            for subtract_uv in [false, true] {
2323                let mut settings = GenerationSettings::default();
2324                settings.uv.subtract_uv = subtract_uv;
2325                let ordinary =
2326                    Wood::new(CutStructure::empty(&graph), &graph, &graph.model, &settings)?;
2327                let all = ordinary
2328                    .graph
2329                    .iter_nodes()
2330                    .map(|(_, _, spinney)| spinney.filter().clone())
2331                    .collect::<BTreeSet<_>>();
2332                let proper = all
2333                    .iter()
2334                    .filter(|filter| **filter != full.filter)
2335                    .cloned()
2336                    .collect::<BTreeSet<_>>();
2337                assert!(proper.iter().any(|filter| filter.is_empty()));
2338                if subtract_uv {
2339                    assert!(all.contains(&full.filter), "{}", graph.name);
2340                    assert!(proper.len() > 1, "{}", graph.name);
2341                }
2342                for mode in [
2343                    MediumMode::Vacuum,
2344                    MediumMode::ThermodynamicEquilibrium,
2345                    MediumMode::ZeroTemperatureEquilibrium,
2346                ] {
2347                    settings.medium.mode = mode;
2348                    for vacuum_subtraction in [false, true] {
2349                        if mode == MediumMode::Vacuum && vacuum_subtraction {
2350                            continue; // Generation validation rejects this combination.
2351                        }
2352                        settings.medium.vacuum_subtraction = vacuum_subtraction;
2353                        let expected = if vacuum_subtraction { &proper } else { &all };
2354                        let wood = Wood::new(
2355                            CutStructure::empty(&graph),
2356                            &graph,
2357                            &graph.model,
2358                            &settings,
2359                        )?;
2360                        assert_eq!(
2361                            &wood
2362                                .graph
2363                                .iter_nodes()
2364                                .map(|(_, _, spinney)| spinney.filter().clone())
2365                                .collect::<BTreeSet<_>>(),
2366                            expected,
2367                            "{}: {mode:?}, subtract_uv={subtract_uv}, vacuum_subtraction={vacuum_subtraction}",
2368                            graph.name
2369                        );
2370                        // The shared filter also supplies the legacy executor.
2371                        let mut spinneys = graph.classified_spinneys(
2372                            &graph.full_filter(),
2373                            &graph.model,
2374                            &settings.uv,
2375                            &graph.loop_momentum_basis,
2376                        )?;
2377                        graph.remove_full_observable_spinney(&mut spinneys, &settings.medium);
2378                        assert_eq!(
2379                            &spinneys
2380                                .iter()
2381                                .map(|spinney| spinney.filter().clone())
2382                                .collect::<BTreeSet<_>>(),
2383                            expected,
2384                            "legacy {}: {mode:?}, subtract_uv={subtract_uv}, vacuum_subtraction={vacuum_subtraction}",
2385                            graph.name
2386                        );
2387                    }
2388                }
2389            }
2390        }
2391        Ok(())
2392    }
2393
2394    #[test]
2395    fn vacuum_subtraction_commutes_with_local_and_integrated_forests() -> Result<()> {
2396        use crate::{
2397            integrands::process::param_builder::ParamBuilderGraph,
2398            numerator::{
2399                soft_energy_certificate::{EnergyZeroOutcome, SoftEnergyAlgebra},
2400                symbolica_ext::NumeratorAtomExt,
2401            },
2402            settings::global::MediumMode,
2403        };
2404        use symbolica::atom::AtomView;
2405        use three_dimensional_reps::thermal::OCCUPATION_FORM;
2406        test_initialise()?;
2407        let graphs: Vec<Graph> = Graph::unit_numerator_fixtures(
2408            stringify!(
2409            digraph nested {
2410                edge [particle="scalar_1"]; node [num=1];
2411                v1 -> v2; v1 -> v2; v1 -> v2;
2412                v1 -> v1;
2413            }
2414            digraph disjoint {
2415                edge [particle="scalar_1"]; node [num=1];
2416                v1 -> v2; v1 -> v2;
2417                v3 -> v4; v3 -> v4;
2418                v2 -> v3; v1 -> v4;
2419            }),
2420            &crate::utils::load_generic_model("scalars"),
2421        )?;
2422        for graph in graphs {
2423            for medium in [
2424                MediumMode::ThermodynamicEquilibrium,
2425                MediumMode::ZeroTemperatureEquilibrium,
2426            ] {
2427                for generate_integrated in [false, true] {
2428                    let mut settings = GenerationSettings::default();
2429                    settings.medium.mode = medium;
2430                    settings.medium.vacuum_subtraction = true;
2431                    settings.uv.softct = false;
2432                    settings.uv.generate_integrated = generate_integrated;
2433                    let mut graph = graph.clone();
2434                    let options = graph.production_3d_expression_options(
2435                        &settings,
2436                        three_dimensional_reps::RepresentationMode::Cff,
2437                    )?;
2438                    let contract =
2439                        graph.paired_edges(&graph.tree_edges.subtract(&graph.initial_state_cut));
2440                    let production = graph
2441                        .generate_3d_expression_for_integrand(&contract, &None, &options, None)?;
2442                    let mut results = Vec::new();
2443                    for early_subtraction in [false, true] {
2444                        let projection = OrientationProjection::exact_expression(
2445                            &production,
2446                            &options,
2447                            &settings.orientation_pattern,
2448                            true,
2449                        )
2450                        .with_vacuum_subtraction(early_subtraction);
2451                        // Both routes use precisely the same proper forests. Only the
2452                        // boundary where the full vacuum projection acts is different.
2453                        let mut forests = Wood::new(
2454                            CutStructure::empty(&graph),
2455                            &graph,
2456                            &graph.model,
2457                            &settings,
2458                        )?
2459                        .unfold();
2460                        let model = graph.model.clone();
2461                        let mut context = Local4dProjectionContext::default();
2462                        forests.prepare_four_d(
2463                            &graph,
2464                            &model,
2465                            crate::utils::vakint()?,
2466                            &settings.uv,
2467                            &mut context,
2468                        )?;
2469                        forests.compute(&mut graph, projection, &settings.uv, &mut context)?;
2470                        drop(context);
2471                        results.push(forests.orientation_parametric_exprs(&graph, &settings.uv)?);
2472                    }
2473                    assert_eq!(results[0].len(), results[1].len());
2474                    for (late, early) in results[0].iter().zip(&results[1]) {
2475                        let late = late.integrands.resolved()?;
2476                        let early = early.integrands.resolved()?;
2477                        assert_eq!(late.iter().count(), early.iter().count());
2478                        for ((late_key, raw), (early_key, actual)) in late.iter().zip(early.iter())
2479                        {
2480                            assert_eq!(late_key, early_key);
2481                            let vacuum = graph.make_thermal_distributions_explicit(
2482                                &graph.model,
2483                                raw,
2484                                MediumMode::Vacuum,
2485                                graph.iter_edges().map(|(_, edge, _)| edge),
2486                            )?;
2487                            assert!(
2488                                raw.is_zero() || raw.contains_symbol(GS.thermal_weight_wrapper)
2489                            );
2490                            assert!(
2491                                actual.is_zero()
2492                                    || actual.contains_symbol(GS.thermal_weight_wrapper)
2493                            );
2494                            // Resolve only this scalar comparison. Final energy factors can
2495                            // group as E^-5 or E^-1/P^2, with E^2 = P, after the two routes.
2496                            let difference = (actual - (raw - vacuum))
2497                                .replace(function!(GS.thermal_weight_wrapper, W_.a_))
2498                                .with(W_.a_)
2499                                .replace_multiple(&*OCCUPATION_FORM)
2500                                .expand();
2501                            // Certify each occupation coefficient separately so unrelated
2502                            // energy denominators do not multiply the proof's term budget.
2503                            let mut occupations = BTreeSet::new();
2504                            difference.visitor(&mut |view| {
2505                                if let AtomView::Fun(call) = view
2506                                    && call.get_symbol() == GS.thermal_distribution
2507                                {
2508                                    occupations.insert(view.to_owned());
2509                                    return false;
2510                                }
2511                                true
2512                            });
2513                            let coefficients = difference
2514                                .coefficient_list_exact(&occupations.into_iter().collect_vec())
2515                                .expect("scalar difference must be polynomial in occupations");
2516                            for (occupation, coefficient) in coefficients {
2517                                let certificate =
2518                                    SoftEnergyAlgebra::default().scalar_zero(&coefficient)?;
2519                                assert!(
2520                                    matches!(certificate, EnergyZeroOutcome::Zero(_)),
2521                                    "{}: {medium:?}, integrated={generate_integrated}, residue={late_key:?}, occupation={occupation}: {certificate:?}: {coefficient}",
2522                                    graph.name
2523                                );
2524                            }
2525                        }
2526                    }
2527                }
2528            }
2529        }
2530        Ok(())
2531    }
2532
2533    #[test]
2534    fn local_leaf_operations_follow_dependency_frontiers() -> Result<()> {
2535        test_initialise().unwrap();
2536        let dumbell: Graph = finalized_runtime_dot!(
2537            digraph G{
2538                graph [projector=1]
2539                node [num=1]
2540                edge [particle="scalar_1" num=1];
2541                v1 -> v2 [source="{ufo_order:0}" sink="{ufo_order:0}"];
2542                v2 -> v2 [lmb_id=0 source="{ufo_order:1}" sink="{ufo_order:2}"];
2543                v1 -> v1 [lmb_id=1 source="{ufo_order:1}" sink="{ufo_order:2}"];
2544                v1 -> v1 [lmb_id=2 source="{ufo_order:3}" sink="{ufo_order:4}"];
2545            },"scalars"
2546        )?;
2547
2548        let forests = Wood::new(
2549            CutStructure::empty(&dumbell),
2550            &dumbell,
2551            &scalar_model(),
2552            &GenerationSettings::default(),
2553        )?
2554        .unfold();
2555
2556        let frontier_label = |operation: &OperationNode| {
2557            operation
2558                .covers()
2559                .map_or_else(|| "∅".to_string(), |cover| cover.string_label())
2560        };
2561        let leaf_labels = |node| {
2562            forests
2563                .local_leaf_operations(node)
2564                .iter()
2565                .map(|leaf| {
2566                    (
2567                        leaf.op.order.string_label(),
2568                        frontier_label(&forests.graph[leaf.frontier]),
2569                    )
2570                })
2571                .collect::<Vec<_>>()
2572        };
2573
2574        let root_disconnected = forests
2575            .graph
2576            .iter_nodes()
2577            .find_map(|(node, _, _)| {
2578                forests
2579                    .normalized_node_label(node)
2580                    .starts_with("{36,F}:")
2581                    .then_some(node)
2582            })
2583            .expect("lopsided dumbbell should contain a root disconnected frontier");
2584        assert_eq!(
2585            leaf_labels(root_disconnected),
2586            vec![
2587                ("36".to_string(), "∅".to_string()),
2588                ("F".to_string(), "∅".to_string())
2589            ]
2590        );
2591        let structured_dot = forests.dot_serialize();
2592        let mut join_markers = Vec::new();
2593        for (node, _, _) in forests.graph.iter_nodes() {
2594            for leaf in forests.local_leaf_operations(node) {
2595                let frontier_depth = forests.graph[leaf.frontier].key.op_count();
2596                let (current, given) = forests
2597                    .wood
2598                    .current_given_pair(leaf.op.data, frontier_depth);
2599                if current.subgraph() == &leaf.op.order {
2600                    continue;
2601                }
2602                join_markers.push(
2603                    UvMarker::subgraph(current.subgraph(), given.subgraph())
2604                        .printer(SpensoPrintSettings::typst_options())
2605                        .to_string(),
2606                );
2607            }
2608        }
2609        assert!(
2610            !join_markers.is_empty(),
2611            "lopsided dumbbell must contain a disconnected join"
2612        );
2613        for marker in join_markers {
2614            assert!(
2615                structured_dot.contains(&marker),
2616                "structured DOT must use the runtime current/given marker {marker}"
2617            );
2618        }
2619
2620        let dependent_disconnected = forests
2621            .graph
2622            .iter_nodes()
2623            .find_map(|(node, _, _)| {
2624                forests
2625                    .normalized_node_label(node)
2626                    .starts_with("{C} · {36,F}:")
2627                    .then_some(node)
2628            })
2629            .expect("lopsided dumbbell should contain a C-dependent disconnected frontier");
2630        assert_eq!(
2631            leaf_labels(dependent_disconnected),
2632            vec![
2633                ("F".to_string(), "C".to_string()),
2634                ("36".to_string(), "∅".to_string())
2635            ]
2636        );
2637        let replay_states = forests.union_replay_states(dependent_disconnected)?;
2638        assert_eq!(replay_states.len(), 6);
2639        assert_eq!(
2640            replay_states
2641                .iter()
2642                .filter(|state| !state.local_edges.is_empty())
2643                .count(),
2644            5
2645        );
2646        Ok(())
2647    }
2648
2649    #[test]
2650    fn union_terms_project_factorized_typed_4d_values() -> Result<()> {
2651        test_initialise().unwrap();
2652        let graph: Graph = finalized_runtime_dot!(digraph G {
2653          projector = "1";
2654          edge	 [
2655        num = "1𝑖", particle = "scalar_1"]
2656          node	 [
2657        num = "UFO::SCALAR_COUPLING"]
2658          v1;
2659          v2;
2660
2661          v1:0	-> v1:1	 [id=0 source="{ufo_order:0}" sink="{ufo_order:1}"  lmb_id="0"];
2662          v1:2	-> v1:3	 [id=1 source="{ufo_order:2}" sink="{ufo_order:3}"  lmb_id="1"];
2663          v1:4	-> v2:5	 [id=2 source="{ufo_order:4}" sink="{ufo_order:0}" ];
2664          v2:6	-> v2:7	 [id=3 source="{ufo_order:1}" sink="{ufo_order:2}"  lmb_id="2"];
2665        },"scalars"
2666                )?;
2667        // Disable integrated terms so each union equality isolates factorized
2668        // local 4D composition.
2669        let settings = GenerationSettings {
2670            uv: UVgenerationSettings {
2671                generate_integrated: false,
2672                local_uv_cts_from_expanded_4d_integrands: true,
2673                ..Default::default()
2674            },
2675            ..Default::default()
2676        };
2677        let cut_structure = CutStructure::empty(&graph);
2678        let mut forests = Wood::new(cut_structure, &graph, &graph.model, &settings)?.unfold();
2679        forests.integrate(&graph, &graph.model, crate::utils::vakint()?, &settings.uv)?;
2680
2681        let unions = forests
2682            .graph
2683            .iter_nodes()
2684            .filter_map(|(node, _, operation)| {
2685                (forests.graph.is_disjoint_union(node) && !operation.key.is_empty()).then_some(node)
2686            })
2687            .collect::<Vec<_>>();
2688        assert!(!unions.is_empty());
2689
2690        for union in unions {
2691            let components = forests.disconnected_component_nodes(union)?;
2692            let expected = Local4dCts::from_full_product(
2693                components
2694                    .into_iter()
2695                    .map(|component| forests.recursion_input_4d(component))
2696                    .collect::<Result<Vec<_>>>()?,
2697            )?;
2698            let operation = &forests.graph[union];
2699            let local = forests
2700                .compute_store
2701                .require(operation)?
2702                .local_4d(operation)?;
2703
2704            // Compare the complete typed union expression; no per-cut parent cache
2705            // or component-path replay participates.
2706            assert!(
2707                (local.atom().expression().collect_factors()
2708                    - expected.atom().expression().collect_factors())
2709                .is_zero()
2710            );
2711        }
2712        Ok(())
2713    }
2714
2715    #[test]
2716    fn union_terms_replay_component_paths_from_typed_roots() -> Result<()> {
2717        use crate::graph::feynman_graph::FeynmanGraph;
2718
2719        test_initialise().unwrap();
2720        let mut graph: Graph = finalized_runtime_dot!(
2721            digraph G{
2722                graph [projector=1]
2723                node [num=1]
2724                edge [particle="scalar_1" num=1];
2725                v1 -> v2 [source="{ufo_order:0}" sink="{ufo_order:0}"];
2726                v2 -> v2 [lmb_id=0 source="{ufo_order:1}" sink="{ufo_order:2}"];
2727                v1 -> v1 [lmb_id=1 source="{ufo_order:1}" sink="{ufo_order:2}"];
2728                v1 -> v1 [lmb_id=2 source="{ufo_order:3}" sink="{ufo_order:4}"];
2729            },"scalars"
2730        )?;
2731        let settings = GenerationSettings::default();
2732        let cut_structure = CutStructure::empty(&graph);
2733        let cutset = cut_structure
2734            .cuts
2735            .first()
2736            .expect("empty cut structure has one cut")
2737            .clone();
2738        let mut forests = Wood::new(cut_structure, &graph, &scalar_model(), &settings)?.unfold();
2739
2740        let root_disconnected = forests
2741            .graph
2742            .iter_nodes()
2743            .find_map(|(node, _, _)| {
2744                forests
2745                    .normalized_node_label(node)
2746                    .starts_with("{36,F}:")
2747                    .then_some(node)
2748            })
2749            .expect("lopsided dumbbell should contain a root disconnected frontier");
2750        let dependent_disconnected = forests
2751            .graph
2752            .iter_nodes()
2753            .find_map(|(node, _, _)| {
2754                forests
2755                    .normalized_node_label(node)
2756                    .starts_with("{C} · {36,F}:")
2757                    .then_some(node)
2758            })
2759            .expect("lopsided dumbbell should contain a C-dependent disconnected frontier");
2760        let non_root_frontier = forests
2761            .local_leaf_operations(dependent_disconnected)
2762            .first()
2763            .expect("dependent disconnected operation has a leaf")
2764            .frontier;
2765        assert_eq!(
2766            forests.graph[non_root_frontier]
2767                .covers()
2768                .expect("non-root frontier has a cover")
2769                .string_label(),
2770            "C"
2771        );
2772
2773        let operations = forests
2774            .graph
2775            .iter_nodes()
2776            .map(|(_, _, operation)| operation.clone())
2777            .collect::<Vec<_>>();
2778        // Zero integrated terms isolate component-path replay in the local accumulator.
2779        for operation in operations {
2780            forests
2781                .compute_store
2782                .entry(operation)
2783                .or_default()
2784                .integrated = Some(IntegratedCts::root());
2785        }
2786
2787        let orientation_pattern = crate::settings::global::OrientationPattern::default();
2788        let options = graph.denominator_only_cff_3d_expression_options();
2789        let canonization = graph.get_esurface_canonization(&graph.loop_momentum_basis);
2790        let contract_edges = graph
2791            .iter_edges_of(&graph.tree_edges)
2792            .map(|(_, edge, _)| edge)
2793            .collect_vec();
2794        let production = graph.generate_3d_expression_for_integrand(
2795            &contract_edges,
2796            &canonization,
2797            &options,
2798            Some(&Atom::one()),
2799        )?;
2800        let localizer = Localizer::new(
2801            &cutset,
2802            OrientationProjection::exact_expression(
2803                &production,
2804                &options,
2805                &orientation_pattern,
2806                false,
2807            ),
2808        );
2809        let seed = forests.local_3d_for_node(
2810            forests.root,
2811            &mut graph,
2812            &cutset,
2813            localizer,
2814            &settings.uv,
2815            &mut Local4dProjectionContext::default(),
2816        )?;
2817        let root_store_marker = symbolica::symbol!("root_store_marker");
2818        let frontier_store_marker = symbolica::symbol!("frontier_store_marker");
2819        // Mark cached local terms so the union result proves that replay starts from typed roots.
2820        let marked_computation = |marker| -> Result<CutComputation> {
2821            Ok(CutComputation {
2822                local_3d: seed.local_3d.map(|_| Ok(Atom::var(marker)))?,
2823                final_integrands: seed.final_integrands.clone(),
2824            })
2825        };
2826
2827        let root_operation = forests.graph[forests.root].clone();
2828        forests
2829            .compute_store
2830            .entry(root_operation)
2831            .or_default()
2832            .cuts
2833            .insert(cutset.clone(), marked_computation(root_store_marker)?);
2834        forests
2835            .compute_store
2836            .entry(forests.graph[non_root_frontier].clone())
2837            .or_default()
2838            .cuts
2839            .insert(cutset.clone(), marked_computation(frontier_store_marker)?);
2840
2841        let root_result = forests.local_3d_for_node(
2842            root_disconnected,
2843            &mut graph,
2844            &cutset,
2845            localizer,
2846            &settings.uv,
2847            &mut Local4dProjectionContext::default(),
2848        )?;
2849        assert!(
2850            root_result
2851                .local_3d
2852                .direct()?
2853                .branches()?
2854                .iter_keys()
2855                .all(|(_, integrands)| integrands
2856                    .iter()
2857                    .all(|(_, term)| !term.contains_symbol(root_store_marker))),
2858            "an empty dependency frontier must start from the typed root"
2859        );
2860
2861        let frontier_result = forests.local_3d_for_node(
2862            dependent_disconnected,
2863            &mut graph,
2864            &cutset,
2865            localizer,
2866            &settings.uv,
2867            &mut Local4dProjectionContext::default(),
2868        )?;
2869        let replay_states = forests.union_replay_states(dependent_disconnected)?;
2870        let state = replay_states
2871            .iter()
2872            .find(|state| {
2873                state.local_edges.len() == 2
2874                    && forests
2875                        .normalized_node_label(state.integrated)
2876                        .starts_with("{36}:")
2877            })
2878            .expect("the integrated 36 prefix has the two-step C-to-F suffix");
2879        let expected_active = state
2880            .local_edges
2881            .iter()
2882            .enumerate()
2883            .map(|(offset, edge)| {
2884                let step_order = forests.graph[state.integrated].key.op_count() + offset;
2885                let (current, given) = forests.wood.current_given_pair(*edge, step_order);
2886                current.reduced_subgraph(&given)
2887            })
2888            .reduce(|active, reduced| active.union(&reduced))
2889            .expect("the selected replay state has a local suffix");
2890        assert!(
2891            expected_active.empty_intersection(forests.source_spinney(state.integrated).filter())
2892        );
2893        let sector = frontier_result
2894            .local_3d
2895            .direct()?
2896            .sectors()?
2897            .iter()
2898            .find(|sector| sector.active_subgraph == expected_active)
2899            .expect("the replay frontier contains the expected active sector");
2900        assert!(
2901            !sector.projection_paths.is_empty()
2902                && sector.projection_paths.iter().all(|path| {
2903                    path.steps.len() == state.local_edges.len()
2904                        && path
2905                            .steps
2906                            .windows(2)
2907                            .all(|pair| pair[0].topo_order <= pair[1].topo_order)
2908                }),
2909            "each disconnected sector must retain its own ordered local replay path"
2910        );
2911        assert!(
2912            frontier_result
2913                .local_3d
2914                .direct()?
2915                .branches()?
2916                .iter_keys()
2917                .all(|(_, integrands)| integrands.iter().all(|(_, term)| {
2918                    !term.contains_symbol(root_store_marker)
2919                        && !term.contains_symbol(frontier_store_marker)
2920                })),
2921            "a union must replay every component path from its typed root"
2922        );
2923        Ok(())
2924    }
2925
2926    #[test]
2927    fn disconnected_soft_union_is_the_product_of_completed_component_atoms() -> Result<()> {
2928        test_initialise().unwrap();
2929        let mut graph: Graph = Graph::import_dot(
2930            include_str!("../../../../tests/resources/graphs/local_ir_dod2_scalar_spectacles.dot"),
2931            &crate::utils::load_generic_model("scalars"),
2932        )
2933        .map(|mut graphs| {
2934            assert_eq!(graphs.len(), 1, "one fixture graph expected");
2935            graphs.remove(0)
2936        })?;
2937        let settings = GenerationSettings {
2938            uv: UVgenerationSettings {
2939                generate_integrated: false,
2940                renormalization_prescription: RenormalizationPrescriptionSettings {
2941                    log_divergent: ApproximationType::IR,
2942                    massive_power_divergent: ApproximationType::IR,
2943                    massless_power_divergent: ApproximationType::IR,
2944                    ..Default::default()
2945                },
2946                ..Default::default()
2947            },
2948            ..Default::default()
2949        };
2950        let mut forests =
2951            Wood::new(CutStructure::empty(&graph), &graph, &graph.model, &settings)?.unfold();
2952        forests.integrate(&graph, &graph.model, crate::utils::vakint()?, &settings.uv)?;
2953
2954        let union = forests
2955            .graph
2956            .iter_nodes()
2957            .find_map(|(node, _, _)| forests.graph.is_disjoint_union(node).then_some(node))
2958            .expect("the spectacles fixture must contain a disconnected UV union");
2959        assert_eq!(
2960            forests.source_spinney(union).renormalization_scheme,
2961            ApproximationType::MUV,
2962            "a disconnected union carries only the neutral aggregate scheme"
2963        );
2964        let components = forests.disconnected_component_nodes(union)?;
2965        assert_eq!(components.len(), 2);
2966        assert!(components.iter().all(|component| {
2967            forests.source_spinney(*component).renormalization_scheme == ApproximationType::IR
2968        }));
2969
2970        let expected =
2971            components
2972                .iter()
2973                .try_fold(Atom::one(), |product, component| -> Result<Atom> {
2974                    let completed = forests.recursion_input_4d(*component)?;
2975                    assert!(
2976                        !completed.atom().is_zero(),
2977                        "each disconnected soft component must be completed before the join"
2978                    );
2979                    Ok(product * completed.atom().expression())
2980                })?;
2981        let operation = &forests.graph[union];
2982        let actual = forests
2983            .compute_store
2984            .require(operation)?
2985            .local_4d(operation)?;
2986        assert_eq!(actual.atom().expression(), &expected);
2987        let provenance = forests.node_export_4d_provenance(union, actual);
2988        assert_eq!(provenance.node.parent_keys.len(), 2);
2989        let UVForestLocalProvenance::FourD {
2990            components: provenance_components,
2991            branches,
2992        } = &provenance.node.local
2993        else {
2994            panic!("a computed 4D union must carry 4D provenance")
2995        };
2996        assert_eq!(provenance_components.len(), 2);
2997        assert!(provenance_components.iter().all(|component| {
2998            component.scheme == ApproximationType::IR
2999                && !component.route_loop_edges.is_empty()
3000                && !component.route_signatures.is_empty()
3001        }));
3002        assert_eq!(branches.len(), 1);
3003        assert_eq!(branches[0].branch, Local4dBranch::Combined);
3004        assert!(branches[0].byte_size > 0);
3005
3006        // Exercise the same factorization directly in one parent-CFF
3007        // orientation. With integrated generation disabled, only the replay
3008        // sector containing both local component operations may survive at
3009        // the disconnected-union node.
3010        let cutset = CutSet::empty(graph.n_hedges());
3011        let orientation_pattern = crate::settings::global::OrientationPattern::default();
3012        let options = graph.production_3d_expression_options(
3013            &Default::default(),
3014            three_dimensional_reps::RepresentationMode::Cff,
3015        )?;
3016        let canonization = graph.get_esurface_canonization(&graph.loop_momentum_basis);
3017        // Match the production root: its structural bridge remains a 4D
3018        // denominator outside the CFF and its loop-energy contour.
3019        let contract_edges = graph
3020            .iter_edges_of(
3021                &graph
3022                    .tree_edges
3023                    .subtract(&graph.initial_state_cut)
3024                    .subtract(&graph.external_filter::<SuBitGraph>()),
3025            )
3026            .map(|(_, edge, _)| edge)
3027            .collect::<Vec<_>>();
3028        let mut production = graph.generate_3d_expression_for_integrand(
3029            &contract_edges,
3030            &canonization,
3031            &options,
3032            None,
3033        )?;
3034        assert!(
3035            !production.expression.orientations.is_empty(),
3036            "the spectacles parent CFF has at least one orientation"
3037        );
3038        production.expression.orientations.truncate(1);
3039        let localizer = Localizer::new(
3040            &cutset,
3041            OrientationProjection::exact_expression(
3042                &production,
3043                &options,
3044                &orientation_pattern,
3045                false,
3046            ),
3047        );
3048        let union_3d = forests.local_3d_for_node(
3049            union,
3050            &mut graph,
3051            &cutset,
3052            localizer,
3053            &settings.uv,
3054            &mut Local4dProjectionContext::default(),
3055        )?;
3056        let sectors = union_3d
3057            .local_3d
3058            .direct()?
3059            .sectors()
3060            .expect("a disconnected local 3D union retains its replay sectors");
3061        assert_eq!(sectors.len(), 3);
3062        let combined_sectors = sectors
3063            .iter()
3064            .map(DirectSector::combine)
3065            .collect::<Result<Vec<_>>>()?;
3066        let nonzero_sectors = combined_sectors
3067            .iter()
3068            .filter(|branches| {
3069                branches
3070                    .iter_keys()
3071                    .any(|(_, integrands)| integrands.iter().any(|(_, atom)| !atom.is_zero()))
3072            })
3073            .collect::<Vec<_>>();
3074        assert_eq!(
3075            nonzero_sectors.len(),
3076            1,
3077            "zero integrated prefixes must leave only the two-local-component cross sector"
3078        );
3079        let cross = nonzero_sectors[0];
3080
3081        let assert_same_branches = |left: &DirectResidueBranches,
3082                                    right: &DirectResidueBranches,
3083                                    label: &str|
3084         -> Result<()> {
3085            let left = left.iter_keys().collect::<Vec<_>>();
3086            let right = right.iter_keys().collect::<Vec<_>>();
3087            assert_eq!(
3088                left.len(),
3089                right.len(),
3090                "{label} differs in residue-map count"
3091            );
3092            for ((left_key, left), (right_key, right)) in left.into_iter().zip(right) {
3093                assert_eq!(
3094                    left_key, right_key,
3095                    "{label} changed the complete residue map"
3096                );
3097                // Independently replayed forests have different numerator-family
3098                // scopes. Compare their values using the retained definitions.
3099                let left = left.resolved()?;
3100                let right = right.resolved()?;
3101                left.checked_zip(&right, |residue, left, right| {
3102                    // Compare the exact factorized forest values before selectors
3103                    // are materialized or any graph numerator is distributed.
3104                    let difference = (left - right).together().cancel();
3105                    assert!(
3106                        difference.is_zero(),
3107                        "{label} differs in residue {residue:?}: {difference}"
3108                    );
3109                    Ok(Atom::Zero)
3110                })?;
3111            }
3112            Ok(())
3113        };
3114        assert_same_branches(
3115            &union_3d.local_3d.direct()?.branches()?,
3116            cross,
3117            "the disconnected aggregate and its cross sector",
3118        )?;
3119
3120        let component_edges = components
3121            .iter()
3122            .map(|component| {
3123                let (parent, edge) = forests
3124                    .graph
3125                    .unique_parent(*component)
3126                    .expect("a primitive disconnected component has one root edge");
3127                assert!(
3128                    forests.graph[parent].key.is_empty(),
3129                    "the spectacles components must both be primitive"
3130                );
3131                edge
3132            })
3133            .collect::<Vec<_>>();
3134        let mut replay = |edges: &[EdgeIndex]| -> Result<Direct3dCts> {
3135            let mut local = Direct3dCts::root(&graph, localizer)?;
3136            for (order, edge) in edges.iter().enumerate() {
3137                let (current, given) = forests.wood.current_given_pair(*edge, order);
3138                local = Direct3dApproximation::new(localizer, &mut graph, &settings.uv)
3139                    .run_local(&local, &current, &given, &current, &given)?;
3140            }
3141            assert!(local.branches()?.iter_keys().all(|(_, integrands)| {
3142                integrands
3143                    .iter()
3144                    .all(|(_, atom)| !atom.contains_symbol(GS.rescale))
3145            }));
3146            Ok(local)
3147        };
3148        let forward = replay(&component_edges)?;
3149        let reverse = replay(&component_edges.iter().rev().copied().collect::<Vec<_>>())?;
3150        assert_same_branches(
3151            &forward.branches()?,
3152            cross,
3153            "forward component-local replay and the produced cross sector",
3154        )?;
3155        assert_same_branches(
3156            &reverse.branches()?,
3157            cross,
3158            "reverse component-local replay and the produced cross sector",
3159        )?;
3160        Ok(())
3161    }
3162
3163    #[test]
3164    fn nested_soft_top_self_energy_preserves_completed_parent_poles() -> Result<()> {
3165        initialisation::test_initialise()?;
3166        let model = utils::load_generic_model("sm");
3167        let graph = Graph::import_dot(
3168            include_str!(
3169                "../../../../tests/resources/graphs/local_nested_soft_top_self_energy.dot"
3170            ),
3171            &model,
3172        )?
3173        .remove(0);
3174        let external: SuBitGraph = graph.external_filter();
3175        let parent = graph.full_filter().subtract(&external);
3176        assert_eq!(graph.n_loops(&parent), 2);
3177        let physical_mass = graph[EdgeIndex::from(2)].mass_atom(&model);
3178        assert!(!physical_mass.is_zero());
3179        assert_ne!(physical_mass, Atom::var(GS.m_uv_vacuum));
3180
3181        let mut completed_poles = Vec::with_capacity(2);
3182        for scheme in [ApproximationType::MUV, ApproximationType::IR] {
3183            let settings = GenerationSettings {
3184                uv: UVgenerationSettings {
3185                    generate_integrated: true,
3186                    renormalization_prescription: RenormalizationPrescriptionSettings {
3187                        log_divergent: scheme,
3188                        massive_power_divergent: scheme,
3189                        massless_power_divergent: scheme,
3190                        ..Default::default()
3191                    },
3192                    ..Default::default()
3193                },
3194                ..Default::default()
3195            };
3196            let mut forests =
3197                Wood::new(CutStructure::empty(&graph), &graph, &model, &settings)?.unfold();
3198            forests.integrate(&graph, &model, utils::vakint()?, &settings.uv)?;
3199            let mut pole = Atom::Zero;
3200            let mut bare_parent_count = 0;
3201            let mut nested_parent_count = 0;
3202            let mut finite_prefix_retained = false;
3203            for (_, _, operation) in forests.graph.iter_nodes() {
3204                if operation.covers().as_ref() != Some(&parent) {
3205                    continue;
3206                }
3207                let computed = forests.compute_store.require(operation)?;
3208                pole += computed
3209                    .integrated(operation)?
3210                    .physical_pole()?
3211                    .into_expression();
3212                if operation.key.op_count() == 1 {
3213                    bare_parent_count += 1;
3214                } else {
3215                    nested_parent_count += 1;
3216                    finite_prefix_retained |=
3217                        computed.local_4d(operation)?.active_sectors().len() > 1;
3218                }
3219            }
3220            assert_eq!(bare_parent_count, 1);
3221            assert!(nested_parent_count > 0);
3222            assert!(
3223                finite_prefix_retained,
3224                "the nested {scheme} parent must include the integrated child's finite completion"
3225            );
3226            // Compare the complete parent forest, keeping its Feynman-rule numerator and
3227            // finite-prefix epsilon jets. Resolve the model's color representation
3228            // invariants before comparing; individual nested terms need not agree.
3229            let pole = SymbolicTensor::infer_indexed(
3230                pole.replace(GS.m_uv_expansion)
3231                    .with(GS.m_uv_vacuum)
3232                    .replace(GS.dim)
3233                    .with(4),
3234            )?
3235            .simplify_algebra(&AlgebraSettings {
3236                color: Some(ColorSimplifySettings::default().with_cof_dimension_invariants()),
3237                contract: AlgebraContraction::Minimal,
3238                ..Default::default()
3239            })?
3240            .to_dots()?
3241            .canonize()?
3242            .into_expression()
3243            .collect_factors();
3244            assert!(
3245                !pole.is_zero(),
3246                "the completed {scheme} parent pole must be nonzero"
3247            );
3248            completed_poles.push(pole);
3249        }
3250        let difference = (&completed_poles[0] - &completed_poles[1])
3251            .together()
3252            .cancel();
3253        assert!(
3254            difference.is_zero(),
3255            "MUV and H must give the same completed parent poles: {difference}"
3256        );
3257        Ok(())
3258    }
3259
3260    #[test]
3261    fn heterogeneous_terminal_projects_components_before_multiplying() -> Result<()> {
3262        // Symbolica's exact integrated projection is intentionally recursive and
3263        // needs more than libtest's 2 MiB worker stack. GammaLoop's runtime main
3264        // thread has the platform stack, so exercise the same operation here.
3265        std::thread::Builder::new()
3266            .name("heterogeneous-terminal-projection".to_string())
3267            .stack_size(8 * 1024 * 1024)
3268            .spawn(heterogeneous_terminal_projects_components_before_multiplying_impl)
3269            .expect("projection test thread should start")
3270            .join()
3271            .expect("projection test thread should not panic")
3272    }
3273
3274    fn heterogeneous_terminal_projects_components_before_multiplying_impl() -> Result<()> {
3275        test_initialise().unwrap();
3276        let graph: Graph = finalized_runtime_dot!(
3277            digraph G {
3278                num = "1";
3279                projector = "1";
3280                overall_factor = "1";
3281                edge [particle = "scalar_1" num=1];
3282                node [num = "1"];
3283                v1 -> v2 [source="{ufo_order:0}" sink="{ufo_order:0}"];
3284                v1 -> v1 [lmb_id=0 source="{ufo_order:1}" sink="{ufo_order:2}"];
3285                v2 -> v3 [source="{ufo_order:1}" sink="{ufo_order:0}"];
3286                v2 -> v3 [lmb_id=1 source="{ufo_order:2}" sink="{ufo_order:1}"];
3287            },
3288            "scalars"
3289        )?;
3290        let settings = GenerationSettings {
3291            uv: UVgenerationSettings {
3292                softct: false,
3293                renormalization_prescription: RenormalizationPrescriptionSettings {
3294                    log_divergent: ApproximationType::MUV,
3295                    massive_power_divergent: ApproximationType::PolePart,
3296                    massless_power_divergent: ApproximationType::PolePart,
3297                    ..Default::default()
3298                },
3299                ..Default::default()
3300            },
3301            ..Default::default()
3302        };
3303        let model = scalar_model();
3304        let mut forests =
3305            Wood::new(CutStructure::empty(&graph), &graph, &model, &settings)?.unfold();
3306        forests.integrate(&graph, &model, crate::utils::vakint()?, &settings.uv)?;
3307
3308        let terminals = forests
3309            .graph
3310            .iter_nodes()
3311            .filter_map(|(node, mut crown, _)| {
3312                (!crown.any(|hedge| forests.graph.flow(hedge).is_source())).then_some(node)
3313            })
3314            .collect::<Vec<_>>();
3315        assert_eq!(terminals.len(), 1);
3316        let terminal = terminals[0];
3317        assert!(forests.graph.is_disjoint_union(terminal));
3318
3319        let components = forests.disconnected_component_nodes(terminal)?;
3320        assert_eq!(components.len(), 2);
3321        let schemes = components
3322            .iter()
3323            .map(|component| forests.source_spinney(*component).renormalization_scheme)
3324            .collect::<Vec<_>>();
3325        assert!(schemes.contains(&ApproximationType::MUV));
3326        assert!(schemes.contains(&ApproximationType::PolePart));
3327
3328        let expected = components.iter().try_fold(
3329            SymbolicTensor::infer_indexed(Atom::one())?,
3330            |product, &component| -> Result<_> {
3331                let component_key = &forests.graph[component];
3332                let integrated = forests
3333                    .compute_store
3334                    .require(component_key)?
3335                    .integrated(component_key)?;
3336                let projection = match forests.source_spinney(component).renormalization_scheme {
3337                    ApproximationType::MUV => integrated.physical_finite_counterterm()?,
3338                    ApproximationType::PolePart => integrated.physical_pole()?,
3339                    scheme => panic!("unexpected component scheme {scheme}"),
3340                };
3341                Ok(product.multiply(projection)?)
3342            },
3343        )?;
3344        let terminal_key = &forests.graph[terminal];
3345        let aggregate = forests
3346            .compute_store
3347            .require(terminal_key)?
3348            .integrated(terminal_key)?;
3349        assert_ne!(
3350            expected.expression().expand(),
3351            aggregate
3352                .physical_finite_counterterm()?
3353                .expression()
3354                .expand()
3355        );
3356        assert_ne!(
3357            expected.expression().expand(),
3358            aggregate.physical_pole()?.expression().expand()
3359        );
3360
3361        let wild = Atom::var(W_.x___);
3362        let replacements =
3363            graph.integrand_replacement(&graph.full_filter(), &graph.loop_momentum_basis, &[wild]);
3364        let cooking = CookSettings::indices()
3365            .with_mode(CookMode::ReversibleEncoding)
3366            .with_representation_payloads(true, true);
3367        let expected = expected
3368            .simplify_algebra(&idenso::tensor::AlgebraSettings {
3369                color: Some(ColorSimplifySettings::default()),
3370                ..Default::default()
3371            })?
3372            .contract(idenso::tensor::ContractSettings {
3373                collect_chains: false,
3374                collect_traces: false,
3375                ..Default::default()
3376            })?
3377            .to_dots()?;
3378        let expected = cooking
3379            .uncook(expected.expression().as_view())
3380            .replace_multiple(&replacements)
3381            .replace(GS.m_uv_expansion)
3382            .with(GS.m_uv_vacuum);
3383        let actual = forests
3384            .renormalization_part_of_ends(&graph, &settings.uv)?
3385            .expression;
3386        assert_eq!(actual.expand(), expected.expand());
3387
3388        Ok(())
3389    }
3390
3391    #[test]
3392    fn triple_tadpole() -> Result<()> {
3393        test_initialise().unwrap();
3394        let dumbell: Graph = finalized_runtime_dot!(
3395            digraph G{
3396                graph [projector=1]
3397                node [num=1]
3398                edge [particle="scalar_1" num=1];
3399                v1 -> v2 [source="{ufo_order:0}" sink="{ufo_order:0}"];
3400                v2 -> v3 [source="{ufo_order:1}" sink="{ufo_order:0}"];
3401                v3 -> v3 [lmb_id=0 source="{ufo_order:1}" sink="{ufo_order:2}"];
3402                v2 -> v2 [lmb_id=1 source="{ufo_order:2}" sink="{ufo_order:3}"];
3403                v1 -> v1 [lmb_id=2 source="{ufo_order:1}" sink="{ufo_order:2}"];
3404            },"scalars"
3405        )?;
3406
3407        let spinneys: Vec<_> = dumbell
3408            .spinneys(&dumbell.full_filter())
3409            .into_iter()
3410            .filter_map(|a| Spinney::new(a, &dumbell, &dumbell.loop_momentum_basis).transpose())
3411            .collect::<Result<_>>()?;
3412        let f = Wood::new(
3413            CutStructure::empty(&dumbell),
3414            &dumbell,
3415            &scalar_model(),
3416            &GenerationSettings::default(),
3417        )?;
3418
3419        println!("{}", f);
3420
3421        insta::assert_snapshot!(
3422            f.graph.n_nodes(),
3423            @"8",
3424            // format!("Wood does not have correct number of spinneys: \n{}",f)
3425        );
3426
3427        let three_component_target = f
3428            .graph
3429            .iter_nodes()
3430            .find_map(|(node, _, spinney)| (spinney.n_components() == 3).then_some(node))
3431            .expect("triple tadpole should contain its fully factorized target");
3432        let target_filter = f.graph[three_component_target].filter().clone();
3433        let components = dumbell
3434            .as_ref()
3435            .connected_components(&target_filter)
3436            .into_iter()
3437            .collect::<BTreeSet<_>>();
3438        assert_eq!(components.len(), 3);
3439        let incoming = f
3440            .graph
3441            .iter_crown(three_component_target)
3442            .filter(|hedge| f.graph.flow(*hedge) == Flow::Sink)
3443            .map(|hedge| f.graph[f.graph[&hedge]].clone())
3444            .collect::<BTreeSet<_>>();
3445        assert_eq!(incoming, components);
3446        assert!(
3447            !incoming.contains(&target_filter),
3448            "a fully supplied product must not retain a duplicate atomic full-target transition"
3449        );
3450
3451        for (_, _, d) in f.graph.iter_nodes() {
3452            println!(
3453                "//Node {}: \n{}",
3454                d.subgraph.string_label(),
3455                dumbell.dot(&d.subgraph)
3456            );
3457        }
3458        let _ff = OldWood::from_spinneys(spinneys, &dumbell); //.unfold(&g, &g.loop_momentum_basis);
3459
3460        // println!("{}", ff.dot(&dumbell));
3461
3462        let f = f.unfold();
3463        println!("{}", f);
3464        insta::assert_snapshot!(
3465            f.graph.n_nodes(),
3466            @"8");
3467
3468        let three_component_union = f
3469            .graph
3470            .iter_nodes()
3471            .find_map(|(node, _, operation)| {
3472                (operation.key.op_count() == 3
3473                    && f.wood
3474                        .join_factors(f.graph.source_node(node))
3475                        .is_some_and(|factors| factors.len() == 3))
3476                .then_some(node)
3477            })
3478            .expect("triple tadpole should contain a three-component union");
3479        assert_eq!(
3480            f.disconnected_component_nodes(three_component_union)?.len(),
3481            3
3482        );
3483        let replay_states = f.union_replay_states(three_component_union)?;
3484        assert_eq!(replay_states.len(), 8);
3485        assert_eq!(
3486            replay_states
3487                .iter()
3488                .filter(|state| !state.local_edges.is_empty())
3489                .count(),
3490            7
3491        );
3492
3493        Ok(())
3494    }
3495
3496    #[test]
3497    fn saclay() -> Result<()> {
3498        test_initialise().unwrap();
3499        let dt: Graph = Graph::import_dot(
3500            stringify!(digraph GL16 {
3501                num = "spenso::g(spenso::coad(8,gammalooprs::hedge(0)),spenso::coad(8,gammalooprs::hedge(1)))"
3502                ext [style=invis];
3503                ext -> 0:0 [dir=none id=0 particle="g"];
3504                2:1 -> ext [dir=none id=1 particle="g"];
3505                0 -> 1 -> 2 -> 3 -> 0 [particle="d"];
3506                1 -> 3 [particle="g"];
3507            }),
3508            &standard_model(),
3509        )
3510        .map(|mut graphs| {
3511            assert_eq!(graphs.len(), 1, "one fixture graph expected");
3512            graphs.remove(0)
3513        })?;
3514
3515        let f = Wood::new(
3516            CutStructure::empty(&dt),
3517            &dt,
3518            &standard_model(),
3519            &GenerationSettings::default(),
3520        )?;
3521
3522        println!("{}", dt.dot_serialize(&DotExportSettings::default()));
3523
3524        insta::assert_snapshot!(
3525            f.graph.n_nodes(),
3526            @"5",
3527            // format!("Wood does not have correct number of spinneys: \n{}",f)
3528        );
3529
3530        // The two triangles, quark box and full two-loop graph are the
3531        // four UV subgraphs, independently of their half-edge numbering.
3532        let mut physical_spinneys = f
3533            .graph
3534            .iter_nodes()
3535            .map(|(_, _, spinney)| spinney.filter())
3536            .filter(|subgraph| !subgraph.is_empty())
3537            .map(|subgraph| {
3538                let mut quark_edges = 0;
3539                let mut gluon_edges = 0;
3540                for (_, _, edge) in dt.iter_edges_of(subgraph) {
3541                    match edge.data.particle_pdg_code(&dt.model).map(isize::abs) {
3542                        Some(1) => quark_edges += 1,
3543                        Some(21) => gluon_edges += 1,
3544                        other => panic!("unexpected Saclay fixture particle: {other:?}"),
3545                    }
3546                }
3547                (dt.cyclotomatic_number(subgraph), quark_edges, gluon_edges)
3548            })
3549            .collect::<Vec<_>>();
3550        physical_spinneys.sort_unstable();
3551        assert_eq!(
3552            physical_spinneys,
3553            [(1, 2, 1), (1, 2, 1), (1, 4, 0), (2, 4, 1)]
3554        );
3555
3556        // Subgraph labels encode hedge positions, which the model import fixes.
3557        let first_order_labels: Vec<_> = f
3558            .graph
3559            .iter_nodes()
3560            .map(|(_, _, spinney)| spinney.filter())
3561            .filter(|subgraph| !subgraph.is_empty())
3562            .map(|subgraph| format!(r#"label="K[#expr S_{}⊛0]""#, subgraph.string_label()))
3563            .collect();
3564        assert_eq!(first_order_labels.len(), 4);
3565
3566        let f = f.unfold();
3567        let structured_dot = f.dot_serialize();
3568        for label in &first_order_labels {
3569            assert!(structured_dot.contains(label), "{label}\n{structured_dot}");
3570        }
3571        assert!(!structured_dot.contains("#T("));
3572        println!("{structured_dot}");
3573        insta::assert_snapshot!(
3574            f.graph.n_nodes(),
3575            @"8");
3576
3577        Ok(())
3578    }
3579
3580    #[test]
3581    fn dumbells() -> Result<()> {
3582        test_initialise().unwrap();
3583        let dumbell: Graph = finalized_runtime_dot!(
3584            digraph G{
3585                graph [projector=1]
3586                node [num=1]
3587                edge [particle="scalar_1" num=1];
3588                v1 -> v2 [source="{ufo_order:0}" sink="{ufo_order:0}"];
3589                v2 -> v2 [lmb_id=0 source="{ufo_order:1}" sink="{ufo_order:2}"];
3590                v1 -> v1 [lmb_id=1 source="{ufo_order:1}" sink="{ufo_order:2}"];
3591            },"scalars"
3592        )?;
3593
3594        let spinneys: Vec<_> = dumbell
3595            .spinneys(&dumbell.full_filter())
3596            .into_iter()
3597            .filter_map(|a| Spinney::new(a, &dumbell, &dumbell.loop_momentum_basis).transpose())
3598            .collect::<Result<_>>()?;
3599        let f = Wood::new(
3600            CutStructure::empty(&dumbell),
3601            &dumbell,
3602            &scalar_model(),
3603            &GenerationSettings::default(),
3604        )?;
3605
3606        println!("{}", f);
3607
3608        insta::assert_snapshot!(
3609            f.graph.n_nodes(),
3610            @"4",
3611            // format!("Wood does not have correct number of spinneys: \n{}",f)
3612        );
3613
3614        for (_, _, d) in f.graph.iter_nodes() {
3615            println!(
3616                "//Node {}: \n{}",
3617                d.subgraph.string_label(),
3618                dumbell.dot(&d.subgraph)
3619            );
3620        }
3621        let _ff = OldWood::from_spinneys(spinneys, &dumbell); //.unfold(&g, &g.loop_momentum_basis);
3622
3623        // println!("{}", ff.dot(&dumbell));
3624
3625        let f = f.unfold();
3626        println!("{}", f);
3627        insta::assert_snapshot!(
3628            f.graph.n_nodes(),
3629            @"4");
3630
3631        Ok(())
3632    }
3633
3634    #[test]
3635    fn bugblatter() -> Result<()> {
3636        test_initialise().unwrap();
3637
3638        match Graph::import_dot(
3639            stringify!(digraph G {
3640                A1 -> A2 [particle="t"];
3641                A2 -> A3 [particle="t"];
3642                A3 -> A1 [particle="t"];
3643                B1 -> B2 [particle="t"];
3644                B2 -> B3 [particle="t"];
3645                B3 -> B1 [particle="t"];
3646                A1 -> B1 [particle="a"];
3647                A2 -> B2 [particle="a"];
3648                A3 -> B3 [particle="a"];
3649            }),
3650            &standard_model(),
3651        )
3652        .map(|mut graphs| {
3653            assert_eq!(graphs.len(), 1, "one fixture graph expected");
3654            graphs.remove(0)
3655        }) {
3656            Ok(g) => {
3657                let g: Graph = g;
3658                let spinneys: Vec<_> = g
3659                    .spinneys(&g.full_filter())
3660                    .into_iter()
3661                    .filter_map(|a| Spinney::new(a, &g, &g.loop_momentum_basis).transpose())
3662                    .collect::<Result<_>>()?;
3663                let f = Wood::new(
3664                    CutStructure::empty(&g),
3665                    &g,
3666                    &standard_model(),
3667                    &GenerationSettings::default(),
3668                )?;
3669
3670                println!("{}", f);
3671
3672                assert_eq!(
3673                    20,
3674                    f.graph.n_nodes(),
3675                    "Wood does not have correct number of spinneys: \n{}",
3676                    f
3677                );
3678
3679                for (_, _, d) in f.graph.iter_nodes() {
3680                    println!(
3681                        "//Node {}: \n{}",
3682                        d.subgraph.string_label(),
3683                        g.dot_lmb_of(&d.subgraph, &d.lmb)
3684                    );
3685                }
3686                let _ff = OldWood::from_spinneys(spinneys, &g); //.unfold(&g, &g.loop_momentum_basis);
3687
3688                // println!("{}", ff.dot(&g));
3689
3690                let f = f.unfold();
3691                f.debug_walk();
3692                println!("{}", f);
3693                assert_eq!(
3694                    152,
3695                    f.graph.n_nodes(),
3696                    "Forest unfolds into the wrong number of terms :\n{}",
3697                    f
3698                );
3699
3700                // println!("{}", f)
3701            }
3702            Err(e) => {
3703                eprintln!("{}", e);
3704            }
3705        }
3706
3707        // let f = SpinneyWood::from_spinneys(
3708        //     g.spinneys(&g.full_filter()).into_iter().map(|a| a.filter),
3709        //     &g,
3710        // )
3711        // .unfold();
3712
3713        // println!("{}", f.graph.base_dot());
3714        Ok(())
3715    }
3716
3717    #[test]
3718    fn mercedes() -> Result<()> {
3719        test_initialise().unwrap();
3720
3721        let mercedes: Graph = finalized_runtime_dot!(
3722            digraph G{
3723                graph [projector=1]
3724                node [num=1]
3725                edge [particle="scalar_1" num=1];
3726                v1 -> v2 [source="{ufo_order:0}" sink="{ufo_order:0}"];
3727                v2 -> v3 [source="{ufo_order:1}" sink="{ufo_order:0}"];
3728                v3 -> v1 [lmb_id=0 source="{ufo_order:1}" sink="{ufo_order:1}"];
3729                v1 -> v4 [source="{ufo_order:2}" sink="{ufo_order:0}"];
3730                v2 -> v4 [lmb_id=1 source="{ufo_order:2}" sink="{ufo_order:1}"];
3731                v3 -> v4 [lmb_id=2 source="{ufo_order:2}" sink="{ufo_order:2}"];
3732            },"scalars"
3733        )?;
3734
3735        let f = Wood::new(
3736            CutStructure::empty(&mercedes),
3737            &mercedes,
3738            &scalar_model(),
3739            &GenerationSettings::default(),
3740        )?;
3741        println!("{}", f);
3742        insta::assert_snapshot!(
3743        f.graph.n_nodes(),
3744        @"2",
3745        );
3746        let f = f.unfold();
3747        println!("{}", f);
3748        insta::assert_snapshot!(
3749        f.graph.n_nodes(),
3750        @"2",
3751         );
3752
3753        Ok(())
3754    }
3755
3756    #[test]
3757    fn sunrise() -> Result<()> {
3758        test_initialise().unwrap();
3759
3760        let sunrise: Graph = finalized_runtime_dot!( digraph sunrise{
3761            graph [projector=1]
3762            node [num = "1"]
3763            edge [particle=scalar_1 num=1]
3764            e        [style=invis]
3765            e -> A:0 [id=3 sink="{ufo_order:0}"]
3766            B:1 -> e [id=4 source="{ufo_order:0}"]
3767            A -> B [id=0 source="{ufo_order:1}" sink="{ufo_order:1}"]
3768            A -> B [id=1 lmb_id=0 source="{ufo_order:2}" sink="{ufo_order:2}"]
3769            A -> B [id=2 lmb_id=1 source="{ufo_order:3}" sink="{ufo_order:3}"]
3770        },"scalars")?;
3771        // let spinneys = spectacles.spinneys(&spectacles.full_filter());
3772        let f = Wood::new(
3773            CutStructure::empty(&sunrise),
3774            &sunrise,
3775            &scalar_model(),
3776            &GenerationSettings::default(),
3777        )?;
3778        println!("{}", f);
3779        insta::assert_snapshot!(
3780        f.graph.n_nodes(),
3781        @"5",
3782        );
3783        let f = f.unfold();
3784        println!("{}", f);
3785        insta::assert_snapshot!(
3786        f.graph.n_nodes(),
3787        @"8",
3788         );
3789
3790        Ok(())
3791    }
3792    #[test]
3793    fn dotted_sunrise() -> Result<()> {
3794        test_initialise().unwrap();
3795
3796        let sunrise: Graph = finalized_runtime_dot!( digraph sunrise{
3797            graph [projector=1]
3798            node [num=1]
3799            edge [particle=scalar_1 num=1]
3800            e        [style=invis]
3801            e -> A:0 [id=3 sink="{ufo_order:0}"]
3802            B:1 -> e [id=4 source="{ufo_order:0}"]
3803
3804            A -> C [id=0 source="{ufo_order:1}" sink="{ufo_order:0}"]
3805            C -> e [source="{ufo_order:1}"]
3806            C -> B [source="{ufo_order:2}" sink="{ufo_order:1}"]
3807            A -> B [id=1 lmb_id=0 source="{ufo_order:2}" sink="{ufo_order:2}"]
3808            A -> B [id=2 lmb_id=1 source="{ufo_order:3}" sink="{ufo_order:3}"]
3809        },"scalars")?;
3810        // let spinneys = spectacles.spinneys(&spectacles.full_filter());
3811        let f = Wood::new(
3812            CutStructure::empty(&sunrise),
3813            &sunrise,
3814            &scalar_model(),
3815            &GenerationSettings::default(),
3816        )?;
3817        println!("{}", f);
3818        insta::assert_snapshot!(
3819        f.graph.n_nodes(),
3820        @"3",
3821        );
3822        let f = f.unfold();
3823        println!("{}", f);
3824        insta::assert_snapshot!(
3825        f.graph.n_nodes(),
3826        @"4",
3827         );
3828
3829        Ok(())
3830    }
3831
3832    #[test]
3833    fn dotted() -> Result<()> {
3834        test_initialise().unwrap();
3835
3836        let sunrise: Graph = finalized_runtime_dot!( digraph sunrise{
3837            graph [projector=1]
3838            node [num=1]
3839            edge [particle=scalar_1 num=1]
3840            e        [style=invis]
3841            e -> A:0 [id=4 sink="{ufo_order:0}"]
3842            B:1 -> e [id=5 source="{ufo_order:0}"]
3843            C:2 -> e [id=6 source="{ufo_order:0}"]
3844
3845            A -> B [id=0 source="{ufo_order:1}" sink="{ufo_order:1}"]
3846            B -> C [id=1 source="{ufo_order:2}" sink="{ufo_order:1}"]
3847            C -> A [id=2 lmb_id=0 source="{ufo_order:2}" sink="{ufo_order:2}"]
3848            B -> C [id=3 lmb_id=1 source="{ufo_order:3}" sink="{ufo_order:3}"]
3849
3850        },"scalars")?;
3851        // let spinneys = spectacles.spinneys(&spectacles.full_filter());
3852        let f = Wood::new(
3853            CutStructure::empty(&sunrise),
3854            &sunrise,
3855            &scalar_model(),
3856            &GenerationSettings::default(),
3857        )?;
3858        println!("{}", f);
3859        insta::assert_snapshot!(
3860        f.graph.n_nodes(),
3861        @"3",
3862        );
3863        let f = f.unfold();
3864        println!("{}", f);
3865        insta::assert_snapshot!(
3866        f.graph.n_nodes(),
3867        @"4",
3868         );
3869
3870        Ok(())
3871    }
3872
3873    #[test]
3874    fn spectacles() -> Result<()> {
3875        use crate::graph::feynman_graph::FeynmanGraph;
3876
3877        test_initialise().unwrap();
3878
3879        let mut spectacles: Graph = finalized_runtime_dot!(
3880            digraph G{
3881                graph [projector=1]
3882                node [num=1]
3883                edge [particle="scalar_1" num=1];
3884                v1 -> v2 [source="{ufo_order:0}" sink="{ufo_order:0}"];
3885                v1 -> v2 [lmb_id=0 source="{ufo_order:1}" sink="{ufo_order:1}"];
3886
3887                v3 -> v4 [source="{ufo_order:0}" sink="{ufo_order:0}"];
3888                v3 -> v4 [lmb_id=1 source="{ufo_order:1}" sink="{ufo_order:1}"];
3889
3890                v2 -> v3 [source="{ufo_order:2}" sink="{ufo_order:2}"];
3891                v1 -> v4 [lmb_id=2 source="{ufo_order:2}" sink="{ufo_order:2}"];
3892            },"scalars"
3893        )?;
3894
3895        // let spinneys = spectacles.spinneys(&spectacles.full_filter());
3896        let settings = GenerationSettings::default();
3897        let cut_structure = CutStructure::empty(&spectacles);
3898        let cutset = cut_structure
3899            .cuts
3900            .first()
3901            .expect("empty cut structure has one cut")
3902            .clone();
3903        let f = Wood::new(cut_structure, &spectacles, &scalar_model(), &settings)?;
3904        println!("{}", f);
3905        let mut f = f.unfold();
3906        println!("{}", f);
3907
3908        let (union, edge) = f
3909            .graph
3910            .iter_nodes()
3911            .find_map(|(child, _, _)| {
3912                let (parent, edge) = f.graph.unique_parent(child)?;
3913                (!f.graph.is_disjoint_union(child) && f.graph.is_disjoint_union(parent))
3914                    .then_some((parent, edge))
3915            })
3916            .expect("spectacles has a connected child above its disconnected union");
3917        let operations = f
3918            .graph
3919            .iter_nodes()
3920            .map(|(_, _, operation)| operation.clone())
3921            .collect::<Vec<_>>();
3922        // Zero integrated terms isolate component-path replay in the local accumulator.
3923        for operation in operations {
3924            f.compute_store.entry(operation).or_default().integrated = Some(IntegratedCts::root());
3925        }
3926        let orientation_pattern = crate::settings::global::OrientationPattern::default();
3927        // The replay fixture keeps its synthetic unit branch, while the
3928        // existing exact source supplies a valid energy map for that key.
3929        let options = spectacles.denominator_only_cff_3d_expression_options();
3930        let canonization = spectacles.get_esurface_canonization(&spectacles.loop_momentum_basis);
3931        let contract_edges = spectacles.paired_edges(
3932            &spectacles
3933                .tree_edges
3934                .subtract(&spectacles.initial_state_cut),
3935        );
3936        let production = spectacles.generate_3d_expression_for_integrand(
3937            &contract_edges,
3938            &canonization,
3939            &options,
3940            None,
3941        )?;
3942        assert!(!production.expression.orientations.is_empty());
3943        let localizer = Localizer::new(
3944            &cutset,
3945            OrientationProjection::exact_expression(
3946                &production,
3947                &options,
3948                &orientation_pattern,
3949                false,
3950            ),
3951        );
3952        let replay_states = f
3953            .union_replay_states(union)?
3954            .into_iter()
3955            .filter(|state| !state.local_edges.is_empty())
3956            .collect::<Vec<_>>();
3957        let union_active = replay_states
3958            .iter()
3959            .map(|state| {
3960                state
3961                    .local_edges
3962                    .iter()
3963                    .enumerate()
3964                    .map(|(offset, edge)| {
3965                        let step_order = f.graph[state.integrated].key.op_count() + offset;
3966                        let (current, given) = f.wood.current_given_pair(*edge, step_order);
3967                        current.reduced_subgraph(&given)
3968                    })
3969                    .reduce(|active, reduced| active.union(&reduced))
3970                    .expect("a proper union replay state has a local suffix")
3971            })
3972            .collect::<Vec<_>>();
3973        let computed = f.local_3d_for_node(
3974            union,
3975            &mut spectacles,
3976            &cutset,
3977            localizer,
3978            &settings.uv,
3979            &mut Local4dProjectionContext::default(),
3980        )?;
3981        let sectors = computed.local_3d.direct()?.sectors()?;
3982        assert_eq!(
3983            sectors.len(),
3984            replay_states.len(),
3985            "every proper integrated prefix must produce one disconnected replay sector"
3986        );
3987        assert_eq!(
3988            sectors
3989                .iter()
3990                .map(|sector| sector.active_subgraph.clone())
3991                .collect::<Vec<_>>(),
3992            union_active,
3993            "the completed union must retain the active component support of every replay path"
3994        );
3995        assert!(
3996            computed.final_integrands.iter().next().is_some(),
3997            "the successfully replayed disconnected union must reach final-integrand construction"
3998        );
3999        let union_local = Direct3dCts::from_sectors(
4000            union_active
4001                .iter()
4002                .cloned()
4003                .map(|active_subgraph| {
4004                    let coordinate_frames = spectacles
4005                        .as_ref()
4006                        .connected_components(&active_subgraph)
4007                        .into_iter()
4008                        .filter(|component| spectacles.n_loops(component) != 0)
4009                        .map(|component| DirectCoordinateFrame {
4010                            lmb: spectacles.lmb_of(&component),
4011                            active_subgraph: component,
4012                        })
4013                        .collect();
4014                    Ok(DirectSector {
4015                        active_subgraph,
4016                        coordinate_frames,
4017                        active: DirectResidueBranches::production(
4018                            OrientationID(0),
4019                            Integrands::root(),
4020                        )?,
4021                        frozen_integrands: Integrands::root(),
4022                        projection_paths: Vec::new(),
4023                    })
4024                })
4025                .collect::<Result<_>>()?,
4026        )?;
4027
4028        let step_order = f.graph[union].key.op_count();
4029        let (current, given) = f.wood.current_given_pair(edge, step_order);
4030        let reduced = current.reduced_subgraph(&given);
4031        let numerator = spectacles
4032            .numerator(&reduced, given.subgraph())?
4033            .get_single_atom()
4034            .expect("the scalar reduced numerator is available");
4035        assert!(!numerator.contains_symbol(GS.emr_mom));
4036        // A Taylor projection leaves these momentum-independent source values
4037        // unchanged and supplies the subtraction sign. Compare the complete
4038        // result so retained and quotient coordinates can use any compatible
4039        // basis without fixing the number or storage of coordinate frames.
4040        let expected = union_local
4041            .branches()?
4042            .materialize(false)?
4043            .resolved()?
4044            .map(|atom| -(atom * &numerator));
4045        let given_internal =
4046            InternalSubGraph::try_new(given.subgraph().clone(), spectacles.as_ref())
4047                .expect("the connected child has an internal given prefix");
4048        let quotient_rank = spectacles
4049            .shrunken_sub_lmb(
4050                current.subgraph(),
4051                &given_internal,
4052                spectacles.dummy_stripped_external_flows_of(current.subgraph()),
4053                None,
4054            )?
4055            .loop_edges
4056            .len();
4057        let expected_frames = union_local
4058            .sectors()?
4059            .iter()
4060            .map(|sector| {
4061                let retained_region = sector.active_subgraph.intersection(given.subgraph());
4062                let mut retained = sector
4063                    .coordinate_frames
4064                    .iter()
4065                    .filter(|frame| retained_region.includes(&frame.active_subgraph))
4066                    .flat_map(|frame| frame.lmb.loop_edges.iter().copied())
4067                    .collect::<Vec<_>>();
4068                retained.sort();
4069                retained.dedup();
4070                let expected_rank = retained.len() + quotient_rank;
4071                (retained, expected_rank)
4072            })
4073            .collect::<Vec<_>>();
4074        let external: SuBitGraph = spectacles.external_filter();
4075        let full_internal = spectacles.full_filter().subtract(&external);
4076        let canonical_route = if current.subgraph() == &full_internal
4077            && spectacles.n_loops(&full_internal) == spectacles.loop_momentum_basis.loop_edges.len()
4078        {
4079            spectacles.loop_momentum_basis.clone()
4080        } else {
4081            spectacles.try_compatible_sub_lmb(
4082                current.subgraph(),
4083                spectacles.dummy_less_full_crown(current.subgraph()),
4084                &spectacles.loop_momentum_basis,
4085            )?
4086        };
4087        let expected_active = union_active
4088            .iter()
4089            .map(|active| active.union(&reduced))
4090            .collect::<Vec<_>>();
4091        let child_local = Direct3dApproximation::new(localizer, &mut spectacles, &settings.uv)
4092            .run(
4093                &union_local,
4094                &IntegratedCts::root(),
4095                &current,
4096                &given,
4097                &current,
4098                &given,
4099            )?;
4100        let actual = child_local.branches()?.materialize(false)?.resolved()?;
4101        assert_eq!(
4102            actual.map(|atom| atom.collect_factors()),
4103            expected.map(|atom| atom.collect_factors()),
4104            "the connected child must retain every complete source value across its enclosing Taylor operation",
4105        );
4106        let child_sectors = child_local.sectors()?;
4107        let child_active = child_sectors
4108            .iter()
4109            .map(|sector| sector.active_subgraph.clone())
4110            .collect::<Vec<_>>();
4111        assert_eq!(child_active.len(), 3);
4112        assert_eq!(child_active, expected_active);
4113        for (sector, (retained, expected_rank)) in child_sectors.iter().zip(expected_frames.iter())
4114        {
4115            assert_eq!(
4116                sector.coordinate_frames.len(),
4117                1,
4118                "one connected enclosing Taylor operation must merge every contained child frame"
4119            );
4120            let child_carriers = sector
4121                .coordinate_frames
4122                .iter()
4123                .flat_map(|frame| frame.lmb.loop_edges.iter())
4124                .copied()
4125                .collect::<BTreeSet<_>>();
4126            assert!(
4127                retained.iter().all(|edge| child_carriers.contains(edge)),
4128                "the connected child must retain every carrier from the contained union frames"
4129            );
4130            assert!(
4131                child_carriers.iter().all(|edge| {
4132                    spectacles.loop_momentum_basis.edge_signatures[*edge]
4133                        .external
4134                        .iter()
4135                        .all(|sign| sign.is_zero())
4136                }),
4137                "the connected child route must be homogeneous in graph-external momenta"
4138            );
4139            assert_eq!(
4140                sector
4141                    .coordinate_frames
4142                    .iter()
4143                    .map(|frame| frame.lmb.loop_edges.len())
4144                    .sum::<usize>(),
4145                *expected_rank,
4146                "the connected child rank is the retained prefix rank plus its quotient rank"
4147            );
4148            let canonical_carriers = canonical_route
4149                .loop_edges
4150                .iter()
4151                .copied()
4152                .collect::<BTreeSet<_>>();
4153            let canonical_is_admissible = retained
4154                .iter()
4155                .all(|edge| canonical_carriers.contains(edge))
4156                && canonical_carriers.len() == *expected_rank
4157                && canonical_carriers.iter().all(|edge| {
4158                    spectacles.loop_momentum_basis.edge_signatures[*edge]
4159                        .external
4160                        .iter()
4161                        .all(|sign| sign.is_zero())
4162                });
4163            if canonical_is_admissible {
4164                assert_eq!(
4165                    child_carriers, canonical_carriers,
4166                    "an admissible graph-canonical route must win before equivalent fallbacks"
4167                );
4168            }
4169        }
4170
4171        Ok(())
4172    }
4173
4174    #[test]
4175    fn collective_two_component_region_requires_independently_divergent_factors() -> Result<()> {
4176        test_initialise().unwrap();
4177
4178        // The two-line component has DOD two, while the scalar triangle has DOD
4179        // minus two. Their disconnected union has logarithmic simultaneous
4180        // power counting, but the triangle is not a UV region on its own.
4181        // Componentwise classification therefore retains only the bubble.
4182        let graph: Graph = finalized_runtime_dot!(
4183            digraph G { graph [projector=1]
4184                node [num = "1"];
4185                edge [particle = "scalar_1" num="1𝑖"];
4186                a0 -> a1 [id = 0, dod = "-1", num = "gammalooprs::Q(0,spenso::mink(4,0))" source="{ufo_order:0}" sink="{ufo_order:0}" lmb_id=0];
4187                a0 -> a1 [id = 1, dod = "-1", num = "gammalooprs::Q(1,spenso::mink(4,0))" source="{ufo_order:1}" sink="{ufo_order:1}"];
4188                a1 -> b0 [id = 2 source="{ufo_order:2}" sink="{ufo_order:0}"];
4189                b0 -> b1 [id = 3 source="{ufo_order:1}" sink="{ufo_order:0}" lmb_id=1];
4190                b1 -> b2 [id = 4 source="{ufo_order:1}" sink="{ufo_order:0}"];
4191                b2 -> b0 [id = 5 sink="{ufo_order:2}" source="{ufo_order:1}"];
4192            },
4193            "scalars"
4194        )?;
4195
4196        let settings = GenerationSettings {
4197            uv: UVgenerationSettings {
4198                generate_integrated: false,
4199                ..Default::default()
4200            },
4201            ..Default::default()
4202        };
4203        let wood = Wood::new(CutStructure::empty(&graph), &graph, &graph.model, &settings)?;
4204        let collective = graph
4205            .spinneys(&graph.full_filter())
4206            .into_iter()
4207            .find(|spinney| graph.as_ref().connected_components(spinney).len() == 2)
4208            .expect("the raw cycle inventory contains the collective region");
4209        let collective_filter = collective.filter;
4210        let components = graph
4211            .as_ref()
4212            .connected_components(&collective_filter)
4213            .into_iter()
4214            .collect::<BTreeSet<_>>();
4215        assert_eq!(components.len(), 2);
4216        assert_eq!(graph.compute_dod(&collective_filter), 0);
4217        assert_eq!(
4218            components
4219                .iter()
4220                .map(|component| graph.compute_dod(component))
4221                .sorted()
4222                .collect::<Vec<_>>(),
4223            vec![-2, 2]
4224        );
4225
4226        let root = OwnedForestNode {
4227            spinney: Spinney::empty(&graph),
4228            topo_order: 0,
4229        };
4230        let divergent_filter = components
4231            .iter()
4232            .find(|component| graph.compute_dod(*component) >= 0)
4233            .expect("the bubble is the independently divergent component")
4234            .clone();
4235        let divergent = OwnedForestNode {
4236            spinney: Spinney::new(
4237                InternalSubGraph::cleaned_filter_optimist(divergent_filter, graph.as_ref()),
4238                &graph,
4239                &graph.loop_momentum_basis,
4240            )?
4241            .expect("the divergent component has a compatible source chart"),
4242            topo_order: 0,
4243        };
4244        let collective_source = OwnedForestNode {
4245            spinney: Spinney::new(
4246                InternalSubGraph::cleaned_filter_optimist(
4247                    collective_filter.clone(),
4248                    graph.as_ref(),
4249                ),
4250                &graph,
4251                &graph.loop_momentum_basis,
4252            )?
4253            .expect("the collective region has a compatible source chart"),
4254            topo_order: 1,
4255        };
4256        let ctx = UVCtx::new(&graph, &graph.model, &settings.uv);
4257        let input = Full4dCts::from_factorized_local(&Local4dCts::root());
4258        let prefix = local_4d::uv_limit(&input, &ctx, &divergent, &root, &divergent, &root)?;
4259        // The two physical forests containing U are {U} and {A,U}:
4260        // (-T_U) I + (-T_U)(-T_A) I. Their full Taylor scope is U;
4261        // its convergent complement does not supply a separate counterterm.
4262        let atomic = local_4d::uv_limit(
4263            &input,
4264            &ctx,
4265            &collective_source,
4266            &root,
4267            &collective_source,
4268            &root,
4269        )?;
4270        let nested = local_4d::uv_limit(
4271            &Full4dCts::from_factorized_local(&prefix),
4272            &ctx,
4273            &collective_source,
4274            &divergent,
4275            &collective_source,
4276            &divergent,
4277        )?;
4278        let expected = atomic.atom().expression() + nested.atom().expression();
4279        let mut forests = wood.unfold();
4280        forests.integrate(&graph, &graph.model, crate::utils::vakint()?, &settings.uv)?;
4281        let actual = forests
4282            .graph
4283            .iter_nodes()
4284            .filter(|(_, _, operation)| operation.covers().as_ref() == Some(&collective_filter))
4285            .try_fold(Atom::Zero, |sum, (_, _, operation)| -> Result<_> {
4286                Ok(sum
4287                    + forests
4288                        .compute_store
4289                        .require(operation)?
4290                        .local_4d(operation)?
4291                        .atom()
4292                        .expression())
4293            })?;
4294        // These vacuum components have no nonzero crown shifts. Put both
4295        // complete coefficients into the same formal K coordinates, retaining
4296        // factorization and every denominator multiplicity before comparison.
4297        let replacements = graph.integrand_replacement(
4298            &graph.full_filter(),
4299            &graph.loop_momentum_basis,
4300            &[Atom::var(W_.x___)],
4301        );
4302        let [actual, expected] = [actual, expected].map(|expression| -> Result<Atom> {
4303            let expression = GS
4304                .erase_uv_momentum_provenance(&expression)
4305                .replace(GS.den(W_.a_, W_.mom_, W_.mass_, W_.prop_))
4306                .with(W_.prop_)
4307                .replace_multiple(&replacements);
4308            let cooking = CookSettings::indices()
4309                .with_mode(CookMode::ReversibleEncoding)
4310                .with_representation_payloads(true, true);
4311            let expression = SymbolicTensor::infer_indexed(
4312                cooking.try_cook(expression.as_view())?,
4313            )?
4314            .contract(ContractSettings {
4315                rank_one: false,
4316                collect_chains: false,
4317                collect_traces: false,
4318                ..Default::default()
4319            })?;
4320            Ok(cooking
4321                .uncook(expression.expression().as_view())
4322                .collect_factors())
4323        });
4324        let (actual, expected) = (actual?, expected?);
4325        assert!(
4326            !atomic.atom().is_zero(),
4327            "the atomic Taylor term must be nonzero"
4328        );
4329        assert!((actual - expected).collect_factors().is_zero());
4330
4331        assert!(
4332            forests
4333                .wood
4334                .graph
4335                .iter_nodes()
4336                .all(|(_, _, spinney)| { spinney.filter() != &collective_filter }),
4337            "a convergent connected factor cannot enter a disconnected UV spinney"
4338        );
4339        let convergent = components
4340            .iter()
4341            .find(|component| graph.compute_dod(*component) < 0)
4342            .expect("the collective region has one convergent component");
4343        let divergent = components
4344            .iter()
4345            .find(|component| graph.compute_dod(*component) >= 0)
4346            .expect("the collective region has one independently divergent component");
4347        assert!(
4348            forests
4349                .wood
4350                .graph
4351                .iter_nodes()
4352                .all(|(_, _, spinney)| spinney.filter() != convergent)
4353        );
4354        assert!(
4355            forests
4356                .wood
4357                .graph
4358                .iter_nodes()
4359                .any(|(_, _, spinney)| spinney.filter() == divergent)
4360        );
4361
4362        assert!(
4363            forests.graph.iter_nodes().all(|(_, _, operation)| {
4364                operation.covers().as_ref() != Some(&collective_filter)
4365            }),
4366            "neither atomic nor nested collective counterterms may bypass factor selection"
4367        );
4368        let mut cut = CutSet::empty(graph.n_hedges());
4369        cut.union = convergent.clone();
4370        assert!(
4371            forests.graph.iter_nodes().any(|(_, _, operation)| {
4372                operation.covers().as_ref() == Some(divergent) && operation.is_compatible_with(&cut)
4373            }),
4374            "a disjoint independently divergent prefix remains cut-compatible"
4375        );
4376        cut.union = divergent.clone();
4377        assert!(
4378            forests
4379                .graph
4380                .iter_nodes()
4381                .filter(|(_, _, operation)| { operation.covers().as_ref() == Some(divergent) })
4382                .all(|(_, _, operation)| !operation.is_compatible_with(&cut)),
4383            "cutting the retained divergent factor must exclude its counterterms"
4384        );
4385
4386        Ok(())
4387    }
4388
4389    #[test]
4390    fn collective_three_component_region_keeps_only_its_divergent_join() -> Result<()> {
4391        test_initialise().unwrap();
4392
4393        // The two bubbles have DOD two and the scalar triangle has DOD minus two.
4394        // Every component nevertheless has a divergent complement because the
4395        // other two components have non-negative combined DOD. The triangle itself
4396        // supplies no independent counterterm: this aggregate edge-label cover
4397        // cannot replace the collective Taylor operation by a factorized product.
4398        // Only the two independently divergent bubbles form a factorized join;
4399        // their complete Taylor cancellation permits omitting the collective
4400        // transition rather than classifying the triangle as a UV factor.
4401        let graph: Graph = finalized_runtime_dot!(
4402            digraph G { graph [projector=1]
4403                node [num = "1"];
4404                edge [particle = "scalar_1" num="1𝑖"];
4405                a0 -> a1 [id = 0, dod = "-1", num = "gammalooprs::Q(0,spenso::mink(4,0))" source="{ufo_order:0}" sink="{ufo_order:0}" lmb_id=0];
4406                a0 -> a1 [id = 1, dod = "-1", num = "gammalooprs::Q(1,spenso::mink(4,0))" source="{ufo_order:1}" sink="{ufo_order:1}"];
4407                a1 -> b0 [id = 2 source="{ufo_order:2}" sink="{ufo_order:0}"];
4408                b0 -> b1 [id = 3, dod = "-1", num = "gammalooprs::Q(3,spenso::mink(4,1))" source="{ufo_order:1}" sink="{ufo_order:0}" lmb_id=1];
4409                b0 -> b1 [id = 4, dod = "-1", num = "gammalooprs::Q(4,spenso::mink(4,1))" source="{ufo_order:2}" sink="{ufo_order:1}"];
4410                b1 -> c0 [id = 5 source="{ufo_order:2}" sink="{ufo_order:0}"];
4411                c0 -> c1 [id = 6 source="{ufo_order:1}" sink="{ufo_order:0}" lmb_id=2];
4412                c1 -> c2 [id = 7 source="{ufo_order:1}" sink="{ufo_order:0}"];
4413                c2 -> c0 [id = 8 sink="{ufo_order:2}" source="{ufo_order:1}"];
4414            },
4415            "scalars"
4416        )?;
4417
4418        let settings = GenerationSettings {
4419            uv: UVgenerationSettings {
4420                generate_integrated: false,
4421                ..Default::default()
4422            },
4423            ..Default::default()
4424        };
4425        let wood = Wood::new(CutStructure::empty(&graph), &graph, &graph.model, &settings)?;
4426        let collective = graph
4427            .spinneys(&graph.full_filter())
4428            .into_iter()
4429            .find(|spinney| graph.as_ref().connected_components(spinney).len() == 3)
4430            .expect("the raw cycle inventory contains the collective region");
4431        let collective_filter = collective.filter;
4432        let components = graph
4433            .as_ref()
4434            .connected_components(&collective_filter)
4435            .into_iter()
4436            .collect::<BTreeSet<_>>();
4437        assert_eq!(components.len(), 3);
4438        assert_eq!(graph.compute_dod(&collective_filter), 2);
4439        assert_eq!(
4440            components
4441                .iter()
4442                .map(|component| graph.compute_dod(component))
4443                .sorted()
4444                .collect::<Vec<_>>(),
4445            vec![-2, 2, 2]
4446        );
4447        assert!(
4448            wood.graph.iter_nodes().all(|(_, _, spinney)| {
4449                graph
4450                    .as_ref()
4451                    .connected_components(spinney.filter())
4452                    .iter()
4453                    .all(|component| graph.compute_dod(component) >= 0)
4454            }),
4455            "a convergent connected factor cannot enter a disconnected UV spinney"
4456        );
4457        assert!(
4458            components.iter().all(|component| {
4459                graph.compute_dod(&collective_filter.subtract(component)) >= 0
4460            })
4461        );
4462        let retained_components = components
4463            .iter()
4464            .filter(|component| {
4465                wood.graph
4466                    .iter_nodes()
4467                    .any(|(_, _, spinney)| spinney.filter() == *component)
4468            })
4469            .cloned()
4470            .collect::<BTreeSet<_>>();
4471        assert_eq!(
4472            retained_components.len(),
4473            2,
4474            "complete complement coverage must not stand in for independent component counterterms"
4475        );
4476        assert!(
4477            retained_components
4478                .iter()
4479                .all(|component| graph.compute_dod(component) >= 0)
4480        );
4481        let retained_union = retained_components
4482            .iter()
4483            .cloned()
4484            .reduce(|left, right| left.union(&right))
4485            .unwrap();
4486        let join = wood
4487            .graph
4488            .iter_nodes()
4489            .find_map(|(node, _, spinney)| (spinney.filter() == &retained_union).then_some(node))
4490            .expect("the two independently divergent bubbles retain their union");
4491        assert_eq!(wood.join_factors(join), Some(retained_components));
4492
4493        let root = OwnedForestNode {
4494            spinney: Spinney::empty(&graph),
4495            topo_order: 0,
4496        };
4497        let root_local = Local4dCts::root();
4498        let input = Full4dCts::from_factorized_local(&root_local);
4499        let ctx = UVCtx::new(&graph, &graph.model, &settings.uv);
4500        let convergent = components
4501            .iter()
4502            .find(|component| graph.compute_dod(*component) < 0)
4503            .expect("the triangle is the convergent component");
4504        // Use one common physical chart only because these vacuum components
4505        // have no nonzero crown shifts. This is not a general replacement for
4506        // the source reconstruction certificates used by projected CFF.
4507        let replacements = graph.integrand_replacement(
4508            &graph.full_filter(),
4509            &graph.loop_momentum_basis,
4510            &[Atom::var(W_.x___)],
4511        );
4512        let mut independent = Vec::<(OwnedForestNode, Local4dCts)>::new();
4513        for component in components
4514            .iter()
4515            .filter(|component| graph.compute_dod(*component) >= 0)
4516        {
4517            let source = OwnedForestNode {
4518                spinney: Spinney::new(
4519                    InternalSubGraph::cleaned_filter_optimist(component.clone(), graph.as_ref()),
4520                    &graph,
4521                    &graph.loop_momentum_basis,
4522                )?
4523                .expect("each divergent bubble has a compatible source chart"),
4524                topo_order: 0,
4525            };
4526            let local = local_4d::uv_limit(&input, &ctx, &source, &root, &source, &root)?;
4527            let mixed = OwnedForestNode {
4528                spinney: Spinney::new(
4529                    InternalSubGraph::cleaned_filter_optimist(
4530                        component.union(convergent),
4531                        graph.as_ref(),
4532                    ),
4533                    &graph,
4534                    &graph.loop_momentum_basis,
4535                )?
4536                .expect("the bubble-triangle collective region is logarithmic"),
4537                topo_order: 1,
4538            };
4539            let atomic = local_4d::uv_limit(&input, &ctx, &mixed, &root, &mixed, &root)?;
4540            let nested = local_4d::uv_limit(
4541                &Full4dCts::from_factorized_local(&local),
4542                &ctx,
4543                &mixed,
4544                &source,
4545                &mixed,
4546                &source,
4547            )?;
4548            assert!(
4549                !atomic.atom().is_zero(),
4550                "the mixed atomic Taylor term must be nonzero"
4551            );
4552            // T_AC(1-T_A)I and T_BC(1-T_B)I vanish: the degree-two
4553            // bubble subtraction leaves no divergent scaling with the triangle.
4554            // Their complete contributions therefore cancel even if a forest
4555            // representation includes or removes zero-quotient outer operations.
4556            let mixed_remainder = GS
4557                .erase_uv_momentum_provenance(
4558                    &(atomic.atom().expression() + nested.atom().expression()),
4559                )
4560                .replace(GS.den(W_.a_, W_.mom_, W_.mass_, W_.prop_))
4561                .with(W_.prop_)
4562                .replace_multiple(&replacements);
4563            let cooking = CookSettings::indices()
4564                .with_mode(CookMode::ReversibleEncoding)
4565                .with_representation_payloads(true, true);
4566            let mixed_remainder =
4567                SymbolicTensor::infer_indexed(cooking.try_cook(mixed_remainder.as_view())?)?
4568                    .contract(ContractSettings {
4569                        rank_one: false,
4570                        collect_chains: false,
4571                        collect_traces: false,
4572                        ..Default::default()
4573                    })?;
4574            let mixed_remainder = cooking
4575                .uncook(mixed_remainder.expression().as_view())
4576                .collect_factors();
4577            assert!(
4578                mixed_remainder.is_zero(),
4579                "mixed collective Taylor terms must cancel"
4580            );
4581            independent.push((source, local));
4582        }
4583        let joint_scope = independent.iter().fold(
4584            graph.empty_subgraph::<SuBitGraph>(),
4585            |scope, (source, _)| scope.union(source.subgraph()),
4586        );
4587        let joint = OwnedForestNode {
4588            spinney: Spinney::new(
4589                InternalSubGraph::cleaned_filter_optimist(joint_scope, graph.as_ref()),
4590                &graph,
4591                &graph.loop_momentum_basis,
4592            )?
4593            .expect("the disjoint divergent bubbles have a compatible joint source chart"),
4594            topo_order: 1,
4595        };
4596        let product = Local4dCts::from_full_product(
4597            independent
4598                .iter()
4599                .map(|(_, local)| Full4dCts::from_factorized_local(local)),
4600        )?;
4601        let collective_source = OwnedForestNode {
4602            spinney: Spinney::new(
4603                InternalSubGraph::cleaned_filter_optimist(
4604                    collective_filter.clone(),
4605                    graph.as_ref(),
4606                ),
4607                &graph,
4608                &graph.loop_momentum_basis,
4609            )?
4610            .expect("the collective region has a compatible source chart"),
4611            topo_order: 2,
4612        };
4613        // The surviving complete value is -T_U(1-T_A)(1-T_B)I.
4614        // AB supplies a product of independent counterterms, while the
4615        // convergent triangle supplies none; no incoming-edge or join catalogue
4616        // determines these four physical prefix values.
4617        let mut expected = Atom::Zero;
4618        for (given, local) in std::iter::once((&root, &root_local))
4619            .chain(independent.iter().map(|(source, local)| (source, local)))
4620            .chain(std::iter::once((&joint, &product)))
4621        {
4622            let term = local_4d::uv_limit(
4623                &Full4dCts::from_factorized_local(local),
4624                &ctx,
4625                &collective_source,
4626                given,
4627                &collective_source,
4628                given,
4629            )?;
4630            debug_tags!(#uv, #forest, #trace;
4631                stage = "collective_three_component_oracle_term",
4632                given = %given.subgraph().string_label(),
4633                file.prefix = %local.atom().expression().to_plain_string(),
4634                file.term = %term.atom().expression().to_plain_string(),
4635                "Independent collective Taylor contribution"
4636            );
4637            if given.subgraph().is_empty() {
4638                assert!(
4639                    !term.atom().is_zero(),
4640                    "the full atomic Taylor term must be nonzero"
4641                );
4642            }
4643            expected += term.atom().expression();
4644        }
4645        let mut forests = wood.unfold();
4646        forests.integrate(&graph, &graph.model, crate::utils::vakint()?, &settings.uv)?;
4647        let actual = forests
4648            .graph
4649            .iter_nodes()
4650            .filter(|(_, _, operation)| operation.covers().as_ref() == Some(&collective_filter))
4651            .try_fold(Atom::Zero, |sum, (_, _, operation)| -> Result<_> {
4652                let term = forests
4653                    .compute_store
4654                    .require(operation)?
4655                    .local_4d(operation)?;
4656                debug_tags!(#uv, #forest, #trace;
4657                    stage = "collective_three_component_forest_term",
4658                    operation = %operation,
4659                    file.term = %term.atom().expression().to_plain_string(),
4660                    "Scheduled collective Taylor contribution"
4661                );
4662                Ok(sum + term.atom().expression())
4663            })?;
4664        let [actual, expected] = [actual, expected].map(|expression| -> Result<Atom> {
4665            let expression = GS
4666                .erase_uv_momentum_provenance(&expression)
4667                .replace(GS.den(W_.a_, W_.mom_, W_.mass_, W_.prop_))
4668                .with(W_.prop_)
4669                .replace_multiple(&replacements);
4670            let cooking = CookSettings::indices()
4671                .with_mode(CookMode::ReversibleEncoding)
4672                .with_representation_payloads(true, true);
4673            let expression =
4674                SymbolicTensor::infer_indexed(cooking.try_cook(expression.as_view())?)?
4675                    .contract(ContractSettings {
4676                        rank_one: false,
4677                        collect_chains: false,
4678                        collect_traces: false,
4679                        ..Default::default()
4680                    })?
4681                    // Typed composition can spell a completed scalar contraction
4682                    // as g(p,q). Use the same dot notation before selecting the
4683                    // tensor basis; no indexed contraction or finite-D value is added.
4684                    .to_dots()?;
4685            Ok(cooking.uncook(expression.expression().as_view()))
4686        });
4687        let (actual, expected) = (actual?, expected?);
4688        let cooking = CookSettings::indices()
4689            .with_mode(CookMode::ReversibleEncoding)
4690            .with_representation_payloads(true, true);
4691        let actual = SymbolicTensor::infer_indexed(cooking.try_cook(actual.as_view())?)?;
4692        let expected = SymbolicTensor::infer_indexed(cooking.try_cook(expected.as_view())?)?;
4693        // This independent diagnostic selects tensor factors whose individual
4694        // interfaces may be unresolved; it does not store a runtime numerator.
4695        let difference = SymbolicTensor::infer(actual.expression() - expected.expression())?;
4696        // The fixture's numerator consists of its selected Q tensor factors.
4697        // Compare their complete scalar denominator weights in the same formal
4698        // dimension; finite-component specialization would narrow the identity.
4699        for (tensor, coefficient) in
4700            difference.coefficient_list(TensorCollectFilter::<0>::Tensors)?
4701        {
4702            assert!(coefficient.is_scalar());
4703            assert!(
4704                tensor.expression().is_zero() || coefficient.expression().together().is_zero(),
4705                "the complete collective Taylor value must equal -T_U(1-T_A)(1-T_B)I: {}",
4706                coefficient.expression()
4707            );
4708        }
4709
4710        assert!(
4711            forests.graph.iter_nodes().all(|(_, _, operation)| {
4712                operation.covers().is_none_or(|scope| {
4713                    graph
4714                        .as_ref()
4715                        .connected_components(&scope)
4716                        .iter()
4717                        .all(|component| graph.compute_dod(component) >= 0)
4718                })
4719            }),
4720            "no atomic or nested collective operation may include the convergent triangle"
4721        );
4722        assert!(
4723            forests.graph.iter_nodes().any(|(node, _, operation)| {
4724                operation.covers().as_ref() == Some(&retained_union)
4725                    && forests.graph.is_disjoint_union(node)
4726            }),
4727            "the complete independently divergent cover remains a factorized join"
4728        );
4729
4730        Ok(())
4731    }
4732
4733    #[test]
4734    fn spectacles_typed_4d_local_construction_matches_uv_limit() -> Result<()> {
4735        test_initialise().unwrap();
4736
4737        let spectacles: Graph = finalized_runtime_dot!(digraph G {
4738          projector = "1";
4739          edge	 [
4740        num = "1𝑖", particle = "scalar_1"]
4741          node	 [
4742        num = "UFO::SCALAR_COUPLING"]
4743          v1;
4744          v2;
4745          v3;
4746          v4;
4747
4748          v1:0	-> v2:1	 [id=0 source="{ufo_order:0}" sink="{ufo_order:0}"  lmb_id="0"];
4749          v1:2	-> v2:3	 [id=1 source="{ufo_order:1}" sink="{ufo_order:1}"  lmb_id="1"];
4750          v1:4	-> v4:5	 [id=2 source="{ufo_order:2}" sink="{ufo_order:0}" ];
4751          v2:6	-> v3:7	 [id=3 source="{ufo_order:2}" sink="{ufo_order:0}" ];
4752          v3:8	-> v4:9	 [id=4 source="{ufo_order:1}" sink="{ufo_order:1}"  lmb_id="2"];
4753          v3:10	-> v4:11	 [id=5 source="{ufo_order:2}" sink="{ufo_order:2}" ];
4754        },"scalars"
4755                )?;
4756
4757        // let spinneys = spectacles.spinneys(&spectacles.full_filter());
4758        let settings = GenerationSettings {
4759            uv: UVgenerationSettings {
4760                generate_integrated: false,
4761                local_uv_cts_from_expanded_4d_integrands: true,
4762                ..Default::default()
4763            },
4764            ..Default::default()
4765        };
4766        let cut_structure = CutStructure::empty(&spectacles);
4767        let f = Wood::new(cut_structure, &spectacles, &spectacles.model, &settings)?;
4768        println!("{}", f);
4769        let mut f = f.unfold();
4770        println!("{}", f);
4771
4772        let (union, child, edge) = f
4773            .graph
4774            .iter_nodes()
4775            .find_map(|(child, _, _)| {
4776                let (parent, edge) = f.graph.unique_parent(child)?;
4777                (!f.graph.is_disjoint_union(child) && f.graph.is_disjoint_union(parent))
4778                    .then_some((parent, child, edge))
4779            })
4780            .expect("spectacles has a connected child above its disconnected union");
4781        f.integrate(
4782            &spectacles,
4783            &spectacles.model,
4784            crate::utils::vakint()?,
4785            &settings.uv,
4786        )?;
4787
4788        let step_order = f.graph[union].key.op_count();
4789        let (current, given) = f.wood.current_given_pair(edge, step_order);
4790        let expected = local_4d::uv_limit(
4791            &f.recursion_input_4d(union)?,
4792            &UVCtx::new(&spectacles, &spectacles.model, &settings.uv),
4793            &current,
4794            &given,
4795            &current,
4796            &given,
4797        )?;
4798        let operation = &f.graph[child];
4799        let local = f.compute_store.require(operation)?.local_4d(operation)?;
4800        assert!(
4801            (local.atom().expression().collect_factors()
4802                - expected.atom().expression().collect_factors())
4803            .is_zero()
4804        );
4805
4806        Ok(())
4807    }
4808
4809    #[test]
4810    fn basketball() -> Result<()> {
4811        test_initialise().unwrap();
4812
4813        let basketball: Graph = finalized_runtime_dot!(
4814            digraph G{
4815                graph [projector=1]
4816                node [num=1]
4817                edge [particle="scalar_1" num=1];
4818                v1 -> v2 [source="{ufo_order:0}" sink="{ufo_order:0}"];
4819                v1 -> v2 [lmb_id=0 source="{ufo_order:1}" sink="{ufo_order:1}"];
4820                v1 -> v2 [lmb_id=1 source="{ufo_order:2}" sink="{ufo_order:2}"];
4821                v1 -> v2 [lmb_id=2 source="{ufo_order:3}" sink="{ufo_order:3}"];
4822            },"scalars"
4823        )?;
4824
4825        let f = Wood::new(
4826            CutStructure::empty(&basketball),
4827            &basketball,
4828            &scalar_model(),
4829            &GenerationSettings::default(),
4830        )?;
4831        println!("{}", f);
4832        insta::assert_snapshot!(
4833        f.graph.n_nodes(),
4834        @"12",
4835              );
4836        let f = f.unfold();
4837        println!("{}", f.dot_serialize());
4838        insta::assert_snapshot!(
4839        f.graph.n_nodes(),
4840        @"46");
4841        Ok(())
4842    }
4843
4844    #[test]
4845    fn fourloop_b() -> Result<()> {
4846        test_initialise().unwrap();
4847
4848        let fourloop_b: Graph = finalized_runtime_dot!(
4849            digraph G{
4850                graph [projector=1]
4851                node [num=1]
4852                edge [particle="scalar_1" num=1];
4853                v1 -> v2 [source="{ufo_order:0}" sink="{ufo_order:0}"];
4854                v1 -> v2 [lmb_id=0 source="{ufo_order:1}" sink="{ufo_order:1}"];
4855
4856                v3 -> v4 [source="{ufo_order:0}" sink="{ufo_order:0}"];
4857                v3 -> v4 [lmb_id=1 source="{ufo_order:1}" sink="{ufo_order:1}"];
4858
4859                v2 -> v3 [source="{ufo_order:2}" sink="{ufo_order:2}"];
4860                v1 -> v3 [lmb_id=2 source="{ufo_order:2}" sink="{ufo_order:3}"];
4861                v1 -> v4 [lmb_id=3 source="{ufo_order:3}" sink="{ufo_order:2}"];
4862            },"scalars"
4863        )?;
4864
4865        // let spinneys = fourloop_b.spinneys(&fourloop_b.full_filter());
4866        let f = Wood::new(
4867            CutStructure::empty(&fourloop_b),
4868            &fourloop_b,
4869            &scalar_model(),
4870            &GenerationSettings::default(),
4871        )?;
4872        println!("{}", f);
4873        insta::assert_snapshot!(
4874        f.graph.n_nodes(),
4875        @"14",
4876        );
4877        let f = f.unfold();
4878        println!("{}", f);
4879        insta::assert_snapshot!(
4880        f.graph.n_nodes(),
4881        @"80",
4882         );
4883
4884        Ok(())
4885    }
4886
4887    #[test]
4888    fn four_loop_a() -> Result<()> {
4889        test_initialise().unwrap();
4890
4891        let four_loop_a: Graph = finalized_runtime_dot!(
4892            digraph G{
4893                graph [projector=1]
4894                node [num=1]
4895                edge [particle="scalar_1" num=1];
4896                v1 -> v2 [source="{ufo_order:0}" sink="{ufo_order:0}"];
4897                v1 -> v2 [lmb_id=0 source="{ufo_order:1}" sink="{ufo_order:1}"];
4898                v2 -> v3 [source="{ufo_order:2}" sink="{ufo_order:0}"];
4899                v3 -> v1 [lmb_id=1 source="{ufo_order:1}" sink="{ufo_order:2}"];
4900                v1 -> v4 [source="{ufo_order:3}" sink="{ufo_order:0}"];
4901                v2 -> v4 [lmb_id=2 source="{ufo_order:3}" sink="{ufo_order:1}"];
4902                v3 -> v4 [lmb_id=3 source="{ufo_order:2}" sink="{ufo_order:2}"];
4903            },"scalars"
4904        )?;
4905
4906        let f = Wood::new(
4907            CutStructure::empty(&four_loop_a),
4908            &four_loop_a,
4909            &scalar_model(),
4910            &GenerationSettings::default(),
4911        )?;
4912        println!("{}", f);
4913        insta::assert_snapshot!(
4914        f.graph.n_nodes(),
4915        @"12",
4916        );
4917        let f = f.unfold();
4918        println!("{}", f);
4919        insta::assert_snapshot!(
4920        f.graph.n_nodes(),
4921        @"60",
4922         );
4923
4924        Ok(())
4925    }
4926
4927    #[test]
4928    fn triple_double_tadpole() -> Result<()> {
4929        test_initialise().unwrap();
4930        let dumbell: Graph = finalized_runtime_dot!(
4931            digraph G{
4932                graph [projector=1]
4933                node [num=1]
4934                edge [particle="scalar_1" num=1];
4935                v1 -> v2 [source="{ufo_order:0}" sink="{ufo_order:0}"];
4936                v2 -> v3 [source="{ufo_order:1}" sink="{ufo_order:0}"];
4937                v3 -> v3 [lmb_id=0 source="{ufo_order:1}" sink="{ufo_order:2}"];
4938                v3 -> v3 [lmb_id=1 source="{ufo_order:3}" sink="{ufo_order:4}"];
4939                v2 -> v2 [lmb_id=2 source="{ufo_order:2}" sink="{ufo_order:3}"];
4940                v2 -> v2 [lmb_id=3 source="{ufo_order:4}" sink="{ufo_order:5}"];
4941                v1 -> v1 [lmb_id=4 source="{ufo_order:1}" sink="{ufo_order:2}"];
4942                v1 -> v1 [lmb_id=5 source="{ufo_order:3}" sink="{ufo_order:4}"];
4943            },"scalars"
4944        )?;
4945
4946        let f = Wood::new(
4947            CutStructure::empty(&dumbell),
4948            &dumbell,
4949            &scalar_model(),
4950            &GenerationSettings::default(),
4951        )?;
4952
4953        insta::assert_snapshot!(
4954            f.graph.n_nodes(),
4955            @"64");
4956
4957        let f = f.unfold_uncached();
4958        insta::assert_snapshot!(
4959            f.graph.n_nodes(),
4960            @"307");
4961
4962        Ok(())
4963    }
4964
4965    mod failing {
4966        use super::*;
4967
4968        #[test]
4969        fn lobsided_double_dumbell() -> Result<()> {
4970            test_initialise().unwrap();
4971            let dumbell: Graph = finalized_runtime_dot!(
4972                digraph G{
4973                    graph [projector=1]
4974                    node [num=1]
4975                    edge [particle="scalar_1" num=1];
4976                    v1 -> v2 [source="{ufo_order:0}" sink="{ufo_order:0}"];
4977                    v2 -> v2 [lmb_id=0 source="{ufo_order:1}" sink="{ufo_order:2}"];
4978                    v1 -> v1 [lmb_id=1 source="{ufo_order:1}" sink="{ufo_order:2}"];
4979                    v1 -> v1 [lmb_id=2 source="{ufo_order:3}" sink="{ufo_order:4}"];
4980                },"scalars"
4981            )?;
4982
4983            let spinneys: Vec<_> = dumbell
4984                .spinneys(&dumbell.full_filter())
4985                .into_iter()
4986                .filter_map(|a| Spinney::new(a, &dumbell, &dumbell.loop_momentum_basis).transpose())
4987                .collect::<Result<_>>()?;
4988            let f = Wood::new(
4989                CutStructure::empty(&dumbell),
4990                &dumbell,
4991                &scalar_model(),
4992                &GenerationSettings::default(),
4993            )?;
4994
4995            println!("{}", f);
4996
4997            insta::assert_snapshot!(
4998                f.graph.n_nodes(),
4999                @"8",
5000                // format!("Wood does not have correct number of spinneys: \n{}",f)
5001            );
5002
5003            for (_, _, d) in f.graph.iter_nodes() {
5004                println!(
5005                    "//Node {}: \n{}",
5006                    d.subgraph.string_label(),
5007                    dumbell.dot(&d.subgraph)
5008                );
5009            }
5010            let _ff = OldWood::from_spinneys(spinneys, &dumbell); //.unfold(&g, &g.loop_momentum_basis);
5011
5012            // println!("{}", ff.dot(&dumbell));
5013
5014            let f = f.unfold();
5015            f.debug_walk();
5016            println!("{}", f);
5017            insta::assert_snapshot!(
5018                f.normalized_node_labels_with_cover("3L").join("\n"),
5019                @r###"
5020{36,F}: Approx(S_36(_))*Approx(S_F(_))
5021{3} · {36,F}: Approx((-1*S_3+S_F(_))*Approx(S_3(_)))*Approx(S_36(_))
5022{C} · {36,F}: Approx((-1*S_C+S_F(_))*Approx(S_C(_)))*Approx(S_36(_))
5023"###
5024            );
5025            insta::assert_snapshot!(
5026                f.graph.n_nodes(),
5027                @"12");
5028
5029            let f = Wood::new(
5030                CutStructure::empty(&dumbell),
5031                &dumbell,
5032                &scalar_model(),
5033                &GenerationSettings::default(),
5034            )?
5035            .unfold_uncached();
5036            assert!(f.compute_store.entries.is_empty());
5037            insta::assert_snapshot!(
5038                f.normalized_node_labels_with_cover("3L").join("\n"),
5039                @r###"
5040{36,F}: Approx(S_36(_))*Approx(S_F(_))
5041{3} · {36,F}: Approx((-1*S_3+S_F(_))*Approx(S_3(_)))*Approx(S_36(_))
5042{C} · {36,F}: Approx((-1*S_C+S_F(_))*Approx(S_C(_)))*Approx(S_36(_))
5043"###
5044            );
5045
5046            Ok(())
5047        }
5048
5049        #[test]
5050        fn double_double_dumbell() -> Result<()> {
5051            test_initialise().unwrap();
5052            let dumbell: Graph = finalized_runtime_dot!(
5053                digraph G{
5054                    graph [projector=1]
5055                    node [num=1]
5056                    edge [particle="scalar_1" num=1];
5057                    v1 -> v2 [source="{ufo_order:0}" sink="{ufo_order:0}"];
5058                    v2 -> v2 [lmb_id=0 source="{ufo_order:1}" sink="{ufo_order:2}"];
5059                    v2 -> v2 [lmb_id=1 source="{ufo_order:3}" sink="{ufo_order:4}"];
5060                    v1 -> v1 [lmb_id=2 source="{ufo_order:1}" sink="{ufo_order:2}"];
5061                    v1 -> v1 [lmb_id=3 source="{ufo_order:3}" sink="{ufo_order:4}"];
5062                },"scalars"
5063            )?;
5064
5065            let _spinneys: Vec<_> = dumbell
5066                .spinneys(&dumbell.full_filter())
5067                .into_iter()
5068                .filter_map(|a| Spinney::new(a, &dumbell, &dumbell.loop_momentum_basis).transpose())
5069                .collect::<Result<_>>()?;
5070            let f = Wood::new(
5071                CutStructure::empty(&dumbell),
5072                &dumbell,
5073                &scalar_model(),
5074                &GenerationSettings::default(),
5075            )?;
5076
5077            println!("{}", f);
5078
5079            insta::assert_snapshot!(
5080                f.graph.n_nodes(),
5081                @"16",
5082                // format!("Wood does not have correct number of spinneys: \n{}",f)
5083            );
5084
5085            let f = f.unfold();
5086
5087            insta::assert_snapshot!(
5088                f.graph.n_nodes(),
5089                @"36");
5090
5091            let f = Wood::new(
5092                CutStructure::empty(&dumbell),
5093                &dumbell,
5094                &scalar_model(),
5095                &GenerationSettings::default(),
5096            )?
5097            .unfold_uncached();
5098
5099            let foata_labels = f
5100                .graph
5101                .iter_nodes()
5102                .map(|(_, _, key)| key.foata_level_labels())
5103                .collect::<Vec<_>>();
5104            assert!(
5105                foata_labels
5106                    .iter()
5107                    .any(|label| label == "3,36;FU,F" || label == "36,3;FU,F"),
5108                "expected 3;F and 36;FU branch histories to combine, got:\n{}",
5109                foata_labels.join("\n")
5110            );
5111
5112            Ok(())
5113        }
5114    }
5115}
5116
5117#[cfg(test)]
5118#[path = "overlap_poles.rs"]
5119pub(crate) mod overlap_poles;