Skip to main content

feynkit_cff/
generation.rs

1use std::collections::{BTreeMap, BTreeSet};
2
3use feynkit_graph::FeynmanDiagram;
4use linnet::half_edge::{
5    HedgeGraph, NodeIndex,
6    involution::{EdgeIndex, Flow, HedgePair, Orientation},
7    nodestore::NodeStorageOps,
8    subgraph::SubGraphLike,
9};
10use serde::{Deserialize, Serialize};
11use three_dimensional_reps::cff_recursion::SurfaceChainError;
12
13use crate::{
14    CffEdge, CffError, CffExpression, CffGraph, EdgeFlow, EdgeId, EdgeKind, EdgeOrientation,
15    EnergySurface, ExpressionTree, ExternalShift, GraphOrientation, HSurface, OrientationData,
16    OrientationExpression, OrientationId, OrientationWeight, Surface, SurfaceCache, SurfaceId,
17    VertexId, VertexSet,
18};
19
20/// Replace one dependent external momentum by a canonical linear combination.
21#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, bincode::Encode, bincode::Decode)]
22pub struct ShiftRewrite {
23    pub dependent_momentum: EdgeId,
24    pub replacement: ExternalShift,
25}
26
27/// Explicit controls for topology-only CFF generation.
28#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, bincode::Encode, bincode::Decode)]
29pub struct CffOptions {
30    fixed_orientations: BTreeMap<EdgeId, EdgeOrientation>,
31    contracted_edges: BTreeSet<EdgeId>,
32    initial_state_edges: BTreeSet<EdgeId>,
33    shift_rewrite: Option<ShiftRewrite>,
34    max_orientations: usize,
35}
36
37impl Default for CffOptions {
38    fn default() -> Self {
39        Self {
40            fixed_orientations: BTreeMap::new(),
41            contracted_edges: BTreeSet::new(),
42            initial_state_edges: BTreeSet::new(),
43            shift_rewrite: None,
44            max_orientations: usize::MAX,
45        }
46    }
47}
48
49impl CffOptions {
50    pub fn with_fixed_orientation(mut self, edge: EdgeId, orientation: EdgeOrientation) -> Self {
51        self.fixed_orientations.insert(edge, orientation);
52        self
53    }
54
55    pub fn with_contracted_edge(mut self, edge: EdgeId) -> Self {
56        self.contracted_edges.insert(edge);
57        self
58    }
59
60    /// Treat an on-shell energy as an external shift after each surface is generated.
61    pub fn with_initial_state_edge(mut self, edge: EdgeId) -> Self {
62        self.initial_state_edges.insert(edge);
63        self
64    }
65
66    pub fn with_shift_rewrite(mut self, rewrite: ShiftRewrite) -> Self {
67        self.shift_rewrite = Some(rewrite);
68        self
69    }
70
71    pub fn with_max_orientations(mut self, maximum: usize) -> Self {
72        self.max_orientations = maximum;
73        self
74    }
75
76    pub fn fixed_orientations(&self) -> &BTreeMap<EdgeId, EdgeOrientation> {
77        &self.fixed_orientations
78    }
79
80    pub fn contracted_edges(&self) -> &BTreeSet<EdgeId> {
81        &self.contracted_edges
82    }
83
84    pub fn initial_state_edges(&self) -> &BTreeSet<EdgeId> {
85        &self.initial_state_edges
86    }
87
88    pub fn shift_rewrite(&self) -> Option<&ShiftRewrite> {
89        self.shift_rewrite.as_ref()
90    }
91
92    pub const fn max_orientations(&self) -> usize {
93        self.max_orientations
94    }
95}
96
97/// Summary of the finite combinatorial search performed by a generator call.
98#[derive(
99    Clone,
100    Copy,
101    Debug,
102    Default,
103    PartialEq,
104    Eq,
105    Serialize,
106    Deserialize,
107    bincode::Encode,
108    bincode::Decode,
109)]
110pub struct CffReport {
111    pub candidate_orientations: usize,
112    pub acyclic_orientations: usize,
113    pub unfolded_terms: usize,
114    pub interned_surfaces: usize,
115}
116
117/// Typed CFF expression together with its generation-local surfaces and report.
118#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, bincode::Encode, bincode::Decode)]
119pub struct CffResult {
120    pub expression: CffExpression,
121    pub surfaces: SurfaceCache,
122    pub report: CffReport,
123}
124
125impl std::ops::Deref for CffResult {
126    type Target = CffExpression;
127
128    fn deref(&self) -> &Self::Target {
129        &self.expression
130    }
131}
132
133impl std::ops::DerefMut for CffResult {
134    fn deref_mut(&mut self) -> &mut Self::Target {
135        &mut self.expression
136    }
137}
138
139impl CffResult {
140    /// Select every non-zero residue order while retaining this result's arena.
141    pub fn select_energy_surface_residue(
142        &self,
143        group: &crate::RaisedEnergySurfaceGroup,
144    ) -> Vec<Self> {
145        self.expression
146            .select_energy_surface_residue(group)
147            .into_iter()
148            .map(|expression| Self {
149                expression,
150                surfaces: self.surfaces.clone(),
151                report: self.report,
152            })
153            .collect()
154    }
155
156    pub fn normalize_raised_surfaces(&mut self, raised: &crate::RaisedEnergySurfaceData) {
157        self.expression.normalize_raised_surfaces(raised);
158    }
159}
160
161/// A generated expression whose IDs refer to a caller-owned [`SurfaceCache`].
162#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, bincode::Encode, bincode::Decode)]
163pub struct CffGeneration {
164    pub expression: CffExpression,
165    pub report: CffReport,
166}
167
168/// Reusable CFF generator configuration.
169///
170/// Surface caches are intentionally not stored here. [`Self::generate`] creates
171/// a fresh arena, while [`Self::generate_into`] makes reuse of a caller-owned
172/// arena explicit.
173#[derive(Clone, Debug, Default)]
174pub struct CffGenerator {
175    options: CffOptions,
176}
177
178/// CFF construction directly on FeynKit diagrams without wrapping the graph type.
179pub trait FeynmanDiagramCffExt {
180    fn build_cff(&self, options: CffOptions) -> Result<CffResult, CffError>;
181    fn build_cff_subgraph<S: SubGraphLike>(
182        &self,
183        subgraph: &S,
184        options: CffOptions,
185    ) -> Result<CffResult, CffError>;
186}
187
188impl FeynmanDiagramCffExt for FeynmanDiagram {
189    fn build_cff(&self, options: CffOptions) -> Result<CffResult, CffError> {
190        self.build_cff_subgraph(&self.underlying().full_filter(), options)
191    }
192
193    fn build_cff_subgraph<S: SubGraphLike>(
194        &self,
195        subgraph: &S,
196        options: CffOptions,
197    ) -> Result<CffResult, CffError> {
198        let roles = self
199            .underlying()
200            .iter_edges()
201            .map(|(pair, edge, data)| {
202                let role = if data.data.is_dummy {
203                    HedgeEdgeRole::Omitted
204                } else if pair.is_unpaired() {
205                    HedgeEdgeRole::UnorientedExternal
206                } else if data.data.external.is_some() {
207                    HedgeEdgeRole::InitialState
208                } else {
209                    HedgeEdgeRole::Standard
210                };
211                (edge, role)
212            })
213            .collect::<BTreeMap<_, _>>();
214        if let Some(edge) = options
215            .contracted_edges()
216            .iter()
217            .find(|edge| roles.get(edge) == Some(&HedgeEdgeRole::InitialState))
218        {
219            return Err(CffError::Invariant(format!(
220                "initial-state edge {edge} cannot be contracted during CFF generation"
221            )));
222        }
223        self.underlying().build_cff_from_subgraph_with_edge_roles(
224            subgraph,
225            options,
226            &[],
227            |edge| roles[&edge],
228            &mut SurfaceCache::default(),
229        )
230    }
231}
232
233/// CFF construction directly on a selected Linnet topology.
234///
235/// The selected vertices retain their original Linnet identities in every
236/// generated surface, and orientations remain indexed by the original edge
237/// IDs. `reversed_dangling` changes the flow of boundary edges produced by the
238/// selection. Initial-state edges and shift rewrites are supplied through
239/// [`CffOptions`]. The caller owns `cache`; the returned result contains a
240/// snapshot of that arena after generation.
241#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
242pub enum HedgeEdgeRole {
243    /// Include the edge with the role implied by its Linnet topology.
244    #[default]
245    Standard,
246    /// Leave the edge out of CFF topology and return it as undirected.
247    Omitted,
248    /// Include an unpaired external edge in CFF surfaces but leave its output
249    /// orientation undirected.
250    UnorientedExternal,
251    /// Treat a paired edge as a sewn initial-state connection.
252    InitialState,
253}
254
255pub trait HedgeGraphCffExt {
256    fn build_cff_from_subgraph<S: SubGraphLike>(
257        &self,
258        subgraph: &S,
259        options: CffOptions,
260        reversed_dangling: &[EdgeId],
261        cache: &mut SurfaceCache,
262    ) -> Result<CffResult, CffError>;
263
264    /// Build CFF while assigning application-specific roles to selected edges.
265    ///
266    /// The callback classifies original Linnet edge IDs without constructing an
267    /// intermediate graph wrapper. This is useful for finalized runtime graphs
268    /// that retain bookkeeping edges which must not participate in CFF, or sewn
269    /// initial-state edges which contribute shifts but no generated orientation.
270    fn build_cff_from_subgraph_with_edge_roles<S, F>(
271        &self,
272        subgraph: &S,
273        options: CffOptions,
274        reversed_dangling: &[EdgeId],
275        edge_role: F,
276        cache: &mut SurfaceCache,
277    ) -> Result<CffResult, CffError>
278    where
279        S: SubGraphLike,
280        F: FnMut(EdgeId) -> HedgeEdgeRole;
281}
282
283impl<E, V, H, N> HedgeGraphCffExt for HedgeGraph<E, V, H, N>
284where
285    N: NodeStorageOps<NodeData = V>,
286{
287    fn build_cff_from_subgraph<S: SubGraphLike>(
288        &self,
289        subgraph: &S,
290        options: CffOptions,
291        reversed_dangling: &[EdgeId],
292        cache: &mut SurfaceCache,
293    ) -> Result<CffResult, CffError> {
294        self.build_cff_from_subgraph_with_edge_roles(
295            subgraph,
296            options,
297            reversed_dangling,
298            |_| HedgeEdgeRole::Standard,
299            cache,
300        )
301    }
302
303    fn build_cff_from_subgraph_with_edge_roles<S, F>(
304        &self,
305        subgraph: &S,
306        options: CffOptions,
307        reversed_dangling: &[EdgeId],
308        edge_role: F,
309        cache: &mut SurfaceCache,
310    ) -> Result<CffResult, CffError>
311    where
312        S: SubGraphLike,
313        F: FnMut(EdgeId) -> HedgeEdgeRole,
314    {
315        let input = HedgeSubgraphCffInput::new(self, subgraph, reversed_dangling, edge_role)?;
316        let contracted_edges = options.contracted_edges().clone();
317        let generation = CffGenerator::new(options).generate_into(&input.graph, cache)?;
318        let mut expression = generation.expression;
319
320        for orientation in expression.orientations_mut() {
321            for edge in &input.internal_edges {
322                if contracted_edges.contains(edge) {
323                    continue;
324                }
325                match orientation.data.orientation.get(*edge) {
326                    Some(EdgeOrientation::Default | EdgeOrientation::Reversed) => {}
327                    Some(EdgeOrientation::Undirected) | None => {
328                        return Err(CffError::Invariant(format!(
329                            "generated orientation does not direct represented edge {edge}"
330                        )));
331                    }
332                }
333            }
334
335            orientation.data.orientation = self.new_edgevec(|_, edge, _| {
336                if !input.represented_edges.contains(&edge) {
337                    return Orientation::Undirected;
338                }
339                if contracted_edges.contains(&edge)
340                    || input.unoriented_external_edges.contains(&edge)
341                {
342                    return Orientation::Undirected;
343                }
344                if input.reversed_boundary_edges.contains(&edge) {
345                    return Orientation::Reversed;
346                }
347                match orientation.data.orientation.get(edge) {
348                    Some(EdgeOrientation::Reversed) if input.internal_edges.contains(&edge) => {
349                        Orientation::Reversed
350                    }
351                    _ => Orientation::Default,
352                }
353            });
354        }
355
356        Ok(CffResult {
357            expression,
358            surfaces: cache.clone(),
359            report: generation.report,
360        })
361    }
362}
363
364struct HedgeSubgraphCffInput {
365    graph: CffGraph,
366    represented_edges: BTreeSet<EdgeIndex>,
367    internal_edges: BTreeSet<EdgeIndex>,
368    reversed_boundary_edges: BTreeSet<EdgeIndex>,
369    unoriented_external_edges: BTreeSet<EdgeIndex>,
370}
371
372impl HedgeSubgraphCffInput {
373    fn new<E, V, H, N, S, F>(
374        graph: &HedgeGraph<E, V, H, N>,
375        subgraph: &S,
376        reversed_dangling: &[EdgeId],
377        mut edge_role: F,
378    ) -> Result<Self, CffError>
379    where
380        N: NodeStorageOps<NodeData = V>,
381        S: SubGraphLike,
382        F: FnMut(EdgeId) -> HedgeEdgeRole,
383    {
384        let mut original_vertices = graph
385            .iter_nodes_of(subgraph)
386            .map(|(vertex, _, _)| vertex)
387            .collect::<Vec<_>>();
388        original_vertices.sort_unstable();
389        if let Some(vertex) = original_vertices
390            .iter()
391            .find(|vertex| vertex.0 >= u64::BITS as usize)
392        {
393            return Err(CffError::VertexIdentityOutOfRange {
394                vertex: *vertex,
395                maximum: u64::BITS as usize - 1,
396            });
397        }
398
399        let dense_vertices = original_vertices
400            .iter()
401            .enumerate()
402            .map(|(dense, original)| (*original, VertexId::new(dense)))
403            .collect::<BTreeMap<_, _>>();
404        let dense_vertex = |vertex: NodeIndex, edge: EdgeIndex| {
405            dense_vertices
406                .get(&vertex)
407                .copied()
408                .ok_or(CffError::SubgraphEndpointOutsideSelection { edge, vertex })
409        };
410
411        let reversed_dangling = reversed_dangling.iter().copied().collect::<BTreeSet<_>>();
412        let mut edges = Vec::new();
413        let mut represented_edges = BTreeSet::new();
414        let mut internal_edges = BTreeSet::new();
415        let mut reversed_boundary_edges = BTreeSet::new();
416        let mut unoriented_external_edges = BTreeSet::new();
417        for (pair, edge, _) in graph.iter_edges_of(subgraph) {
418            let role = edge_role(edge);
419            if role == HedgeEdgeRole::Omitted {
420                continue;
421            }
422            represented_edges.insert(edge);
423            let cff_edge = match (role, pair) {
424                (HedgeEdgeRole::Standard, HedgePair::Unpaired { hedge, flow }) => {
425                    CffEdge::external(
426                        edge,
427                        dense_vertex(graph.node_id(hedge), edge)?,
428                        match flow {
429                            Flow::Sink => EdgeFlow::Incoming,
430                            Flow::Source => EdgeFlow::Outgoing,
431                        },
432                    )
433                }
434                (HedgeEdgeRole::UnorientedExternal, HedgePair::Unpaired { hedge, flow }) => {
435                    unoriented_external_edges.insert(edge);
436                    CffEdge::external(
437                        edge,
438                        dense_vertex(graph.node_id(hedge), edge)?,
439                        match flow {
440                            Flow::Sink => EdgeFlow::Incoming,
441                            Flow::Source => EdgeFlow::Outgoing,
442                        },
443                    )
444                }
445                (HedgeEdgeRole::Standard, HedgePair::Paired { source, sink }) => {
446                    internal_edges.insert(edge);
447                    CffEdge::internal(
448                        edge,
449                        dense_vertex(graph.node_id(source), edge)?,
450                        dense_vertex(graph.node_id(sink), edge)?,
451                    )
452                }
453                (
454                    HedgeEdgeRole::Standard,
455                    HedgePair::Split {
456                        source,
457                        sink,
458                        split,
459                    },
460                ) => {
461                    let reversed = reversed_dangling.contains(&edge);
462                    if reversed {
463                        reversed_boundary_edges.insert(edge);
464                    }
465                    let (vertex, flow) = match (split, reversed) {
466                        (Flow::Source, false) => (graph.node_id(source), EdgeFlow::Outgoing),
467                        (Flow::Source, true) => (graph.node_id(source), EdgeFlow::Incoming),
468                        (Flow::Sink, false) => (graph.node_id(sink), EdgeFlow::Incoming),
469                        (Flow::Sink, true) => (graph.node_id(sink), EdgeFlow::Outgoing),
470                    };
471                    CffEdge::boundary(edge, dense_vertex(vertex, edge)?, flow)
472                }
473                (HedgeEdgeRole::InitialState, HedgePair::Paired { source, sink }) => {
474                    CffEdge::initial_state(
475                        edge,
476                        dense_vertex(graph.node_id(source), edge)?,
477                        dense_vertex(graph.node_id(sink), edge)?,
478                    )
479                }
480                (
481                    HedgeEdgeRole::InitialState,
482                    HedgePair::Split {
483                        source,
484                        sink,
485                        split,
486                    },
487                ) => {
488                    // A selected side of a sewn external line still carries the
489                    // positive external momentum, never an on-shell loop energy.
490                    unoriented_external_edges.insert(edge);
491                    let (hedge, flow) = match split {
492                        Flow::Source => (source, EdgeFlow::Outgoing),
493                        Flow::Sink => (sink, EdgeFlow::Incoming),
494                    };
495                    CffEdge::external(edge, dense_vertex(graph.node_id(hedge), edge)?, flow)
496                }
497                (HedgeEdgeRole::InitialState, _) => {
498                    return Err(CffError::Invariant(format!(
499                        "initial-state edge {edge} is not paired"
500                    )));
501                }
502                (HedgeEdgeRole::UnorientedExternal, _) => {
503                    return Err(CffError::Invariant(format!(
504                        "unoriented external edge {edge} is not unpaired"
505                    )));
506                }
507                (HedgeEdgeRole::Omitted, _) => unreachable!("omitted edges are skipped"),
508            };
509            edges.push(cff_edge);
510        }
511
512        let vertex_sets = original_vertices
513            .iter()
514            .map(|vertex| VertexSet::from_usize(vertex.0));
515        Ok(Self {
516            graph: CffGraph::with_vertex_sets(vertex_sets, edges)?,
517            represented_edges,
518            internal_edges,
519            reversed_boundary_edges,
520            unoriented_external_edges,
521        })
522    }
523}
524
525impl CffGenerator {
526    pub const fn new(options: CffOptions) -> Self {
527        Self { options }
528    }
529
530    pub const fn options(&self) -> &CffOptions {
531        &self.options
532    }
533
534    pub fn generate(&self, graph: &CffGraph) -> Result<CffResult, CffError> {
535        let mut surfaces = SurfaceCache::default();
536        let generation = self.generate_into(graph, &mut surfaces)?;
537        Ok(CffResult {
538            expression: generation.expression,
539            surfaces,
540            report: generation.report,
541        })
542    }
543
544    /// Generate into a caller-owned arena so related expressions can share surface IDs.
545    pub fn generate_into(
546        &self,
547        graph: &CffGraph,
548        cache: &mut SurfaceCache,
549    ) -> Result<CffGeneration, CffError> {
550        self.validate_options(graph)?;
551        let initial_surface_count = cache.len();
552
553        let mut seed_orientation = GraphOrientation::from_iter(std::iter::repeat_n(
554            EdgeOrientation::Undirected,
555            graph.edge_count(),
556        ));
557        for edge in graph.edges() {
558            seed_orientation[edge.id] = EdgeOrientation::Default;
559        }
560        let mut seed = WorkingGraph::from_graph(graph, seed_orientation.clone());
561        for edge in &self.options.contracted_edges {
562            seed.contract_edge(*edge)?;
563            seed_orientation[*edge] = EdgeOrientation::Undirected;
564        }
565        // A self-loop orders no vertices, so it leaves the denominator topology:
566        // it must not add an energy to a surface or block a source or sink.
567        // Both of its closures remain orientations, each with weight one half
568        // as in the shared recursion, whether enumerated or fixed by the caller;
569        // this includes parallel edges closed into self-loops by a contraction.
570        let self_loops = seed.self_loop_edge_ids();
571        for edge in &self_loops {
572            seed.remove_edge(*edge);
573        }
574        let weight = OrientationWeight::from_halvings(
575            u32::try_from(self_loops.len()).map_err(|_| CffError::OrientationCountOverflow)?,
576        );
577
578        let free_edges = seed
579            .internal_edge_ids()
580            .into_iter()
581            .chain(self_loops)
582            .filter(|edge| !self.options.fixed_orientations.contains_key(edge))
583            .collect::<BTreeSet<_>>()
584            .into_iter()
585            .collect::<Vec<_>>();
586        let free_edge_count =
587            u32::try_from(free_edges.len()).map_err(|_| CffError::OrientationCountOverflow)?;
588        let candidate_count = 1_usize
589            .checked_shl(free_edge_count)
590            .ok_or(CffError::OrientationCountOverflow)?;
591        if candidate_count > self.options.max_orientations {
592            return Err(CffError::TooManyOrientations {
593                candidate_count,
594                maximum: self.options.max_orientations,
595            });
596        }
597
598        let mut orientations = Vec::new();
599        for identifier in 0..candidate_count {
600            let mut orientation = seed_orientation.clone();
601            for (edge, fixed) in &self.options.fixed_orientations {
602                orientation[*edge] = *fixed;
603            }
604            for (bit, edge) in free_edges.iter().enumerate() {
605                let direction = if identifier & (1_usize << bit) == 0 {
606                    EdgeOrientation::Default
607                } else {
608                    EdgeOrientation::Reversed
609                };
610                orientation[*edge] = direction;
611            }
612
613            let mut oriented_graph = seed.clone();
614            oriented_graph.apply_orientation(orientation.clone());
615            if oriented_graph.has_directed_cycle() {
616                continue;
617            }
618
619            let id = OrientationId(orientations.len());
620            let expression = self.generate_tree(oriented_graph, cache, identifier)?;
621            orientations.push(OrientationExpression {
622                id,
623                data: OrientationData { orientation },
624                weight,
625                expression,
626            });
627        }
628
629        let expression = CffExpression::new(orientations);
630        let report = CffReport {
631            candidate_orientations: candidate_count,
632            acyclic_orientations: expression.orientations().len(),
633            unfolded_terms: expression.unfolded_term_count(),
634            interned_surfaces: cache.len() - initial_surface_count,
635        };
636        Ok(CffGeneration { expression, report })
637    }
638
639    fn validate_options(&self, graph: &CffGraph) -> Result<(), CffError> {
640        for edge in self
641            .options
642            .fixed_orientations
643            .keys()
644            .chain(&self.options.contracted_edges)
645        {
646            let graph_edge = graph.edge(*edge).ok_or(CffError::UnknownEdge(*edge))?;
647            if !graph_edge.is_internal() {
648                return Err(CffError::NotInternalEdge(*edge));
649            }
650        }
651        for edge in &self.options.contracted_edges {
652            if self.options.fixed_orientations.contains_key(edge) {
653                return Err(CffError::OrientedContractedEdge(*edge));
654            }
655        }
656        for (edge, orientation) in &self.options.fixed_orientations {
657            if *orientation == EdgeOrientation::Undirected {
658                return Err(CffError::UndirectedFixedEdge(*edge));
659            }
660        }
661        for edge in &self.options.initial_state_edges {
662            if graph.edge(*edge).is_none() {
663                return Err(CffError::UnknownEdge(*edge));
664            }
665        }
666        if let Some(rewrite) = &self.options.shift_rewrite {
667            if graph.edge(rewrite.dependent_momentum).is_none() {
668                return Err(CffError::UnknownEdge(rewrite.dependent_momentum));
669            }
670            for (edge, _) in rewrite.replacement.iter() {
671                if graph.edge(*edge).is_none() {
672                    return Err(CffError::UnknownEdge(*edge));
673                }
674            }
675        }
676        Ok(())
677    }
678
679    fn generate_tree(
680        &self,
681        graph: WorkingGraph,
682        cache: &mut SurfaceCache,
683        orientation: usize,
684    ) -> Result<ExpressionTree<SurfaceId>, CffError> {
685        use three_dimensional_reps::cff_recursion::{CffVertex, EdgeType};
686        let chains = graph
687            .shared_topology()
688            .try_surface_chains(&mut |vertex: &CffVertex| {
689                let convert = |edge: &three_dimensional_reps::cff_recursion::EdgeRef| WorkingEdge {
690                    id: EdgeId::new(edge.edge_id),
691                    kind: match edge.edge_type {
692                        EdgeType::Virtual => WorkingEdgeKind::Internal,
693                        EdgeType::Boundary => WorkingEdgeKind::Boundary,
694                        EdgeType::External | EdgeType::InitialStateCut => WorkingEdgeKind::External,
695                    },
696                };
697                let vertex = WorkingVertex {
698                    vertices: vertex.nodes.iter().fold(VertexSet::dummy(), |nodes, &id| {
699                        nodes.union(VertexSet::from_usize(id))
700                    }),
701                    incoming: vertex.incoming.iter().map(convert).collect(),
702                    outgoing: vertex.outgoing.iter().map(convert).collect(),
703                };
704                self.prepare_surface(graph.surface_for(&vertex)?)
705                    .map(|surface| cache.intern(surface))
706            })
707            .map_err(|error| match error {
708                SurfaceChainError::Surface(error) => error,
709                SurfaceChainError::NoContractionBranch => {
710                    CffError::NoContractionBranch { orientation }
711                }
712            })?;
713        let Some(first) = chains.first() else {
714            return Err(CffError::NoSourceOrSink { orientation });
715        };
716        let root = first.first().copied().unwrap_or(SurfaceId::Unit);
717        let mut tree = ExpressionTree::from_root(root);
718        for chain in chains {
719            let mut parent = crate::NodeId::ROOT;
720            for surface in chain.into_iter().skip(1) {
721                parent = tree
722                    .insert(parent, surface)
723                    .expect("newly inserted tree parent exists");
724            }
725        }
726        Ok(tree)
727    }
728
729    fn prepare_surface(&self, surface: Surface) -> Result<Surface, CffError> {
730        let surface = move_initial_state_energies(surface, &self.options.initial_state_edges)?;
731        match (surface, &self.options.shift_rewrite) {
732            (Surface::Energy(mut surface), Some(rewrite)) => {
733                surface
734                    .external_shift
735                    .rewrite(rewrite.dependent_momentum, &rewrite.replacement)?;
736                Ok(Surface::Energy(surface))
737            }
738            (surface, _) => Ok(surface),
739        }
740    }
741}
742
743#[derive(Clone, Copy, Debug, PartialEq, Eq)]
744enum WorkingEdgeKind {
745    External,
746    Internal,
747    Boundary,
748}
749
750#[derive(Clone, Copy, Debug, PartialEq, Eq)]
751struct WorkingEdge {
752    id: EdgeId,
753    kind: WorkingEdgeKind,
754}
755
756#[derive(Clone, Debug)]
757struct WorkingVertex {
758    vertices: VertexSet,
759    incoming: Vec<WorkingEdge>,
760    outgoing: Vec<WorkingEdge>,
761}
762
763#[derive(Clone, Copy, Debug, PartialEq, Eq)]
764enum VertexType {
765    Source,
766    Sink,
767    Neither,
768}
769
770impl WorkingVertex {
771    fn vertex_type(&self) -> VertexType {
772        let is_sink = self
773            .outgoing
774            .iter()
775            .all(|edge| edge.kind != WorkingEdgeKind::Internal);
776        let is_source = self
777            .incoming
778            .iter()
779            .all(|edge| edge.kind != WorkingEdgeKind::Internal);
780        if is_sink {
781            VertexType::Sink
782        } else if is_source {
783            VertexType::Source
784        } else {
785            VertexType::Neither
786        }
787    }
788
789    fn generates_energy_surface(&self) -> bool {
790        match self.vertex_type() {
791            VertexType::Sink => self
792                .outgoing
793                .iter()
794                .all(|edge| edge.kind == WorkingEdgeKind::External),
795            VertexType::Source => self
796                .incoming
797                .iter()
798                .all(|edge| edge.kind == WorkingEdgeKind::External),
799            VertexType::Neither => false,
800        }
801    }
802
803    fn edges(&self) -> impl Iterator<Item = WorkingEdge> + '_ {
804        self.incoming.iter().chain(&self.outgoing).copied()
805    }
806}
807
808#[derive(Clone, Debug)]
809struct WorkingGraph {
810    vertices: Vec<WorkingVertex>,
811    orientation: GraphOrientation,
812}
813
814impl WorkingGraph {
815    fn from_graph(graph: &CffGraph, orientation: GraphOrientation) -> Self {
816        let mut vertices = graph
817            .vertex_sets()
818            .iter()
819            .copied()
820            .map(|vertices| WorkingVertex {
821                vertices,
822                incoming: Vec::new(),
823                outgoing: Vec::new(),
824            })
825            .collect::<Vec<_>>();
826
827        for edge in graph.edges() {
828            match edge.kind {
829                EdgeKind::Internal { source, sink } => {
830                    let working = WorkingEdge {
831                        id: edge.id,
832                        kind: WorkingEdgeKind::Internal,
833                    };
834                    vertices[source.index()].outgoing.push(working);
835                    vertices[sink.index()].incoming.push(working);
836                }
837                EdgeKind::External { vertex, flow } => {
838                    Self::attach(
839                        &mut vertices[vertex.index()],
840                        WorkingEdge {
841                            id: edge.id,
842                            kind: WorkingEdgeKind::External,
843                        },
844                        flow,
845                    );
846                }
847                EdgeKind::Boundary { vertex, flow } => {
848                    Self::attach(
849                        &mut vertices[vertex.index()],
850                        WorkingEdge {
851                            id: edge.id,
852                            kind: WorkingEdgeKind::Boundary,
853                        },
854                        flow,
855                    );
856                }
857                EdgeKind::InitialState { source, sink } => {
858                    let edge = WorkingEdge {
859                        id: edge.id,
860                        kind: WorkingEdgeKind::External,
861                    };
862                    Self::attach(&mut vertices[source.index()], edge, EdgeFlow::Outgoing);
863                    Self::attach(&mut vertices[sink.index()], edge, EdgeFlow::Incoming);
864                }
865            }
866        }
867        Self {
868            vertices,
869            orientation,
870        }
871    }
872
873    fn attach(vertex: &mut WorkingVertex, edge: WorkingEdge, flow: EdgeFlow) {
874        match flow {
875            EdgeFlow::Incoming => vertex.incoming.push(edge),
876            EdgeFlow::Outgoing => vertex.outgoing.push(edge),
877        }
878    }
879
880    fn apply_orientation(&mut self, orientation: GraphOrientation) {
881        for (edge, direction) in orientation.iter() {
882            if *direction != EdgeOrientation::Reversed {
883                continue;
884            }
885            for vertex in &mut self.vertices {
886                if let Some(position) = vertex.outgoing.iter().position(|item| item.id == edge) {
887                    let edge = vertex.outgoing.remove(position);
888                    vertex.incoming.push(edge);
889                } else if let Some(position) =
890                    vertex.incoming.iter().position(|item| item.id == edge)
891                {
892                    let edge = vertex.incoming.remove(position);
893                    vertex.outgoing.push(edge);
894                }
895            }
896        }
897        self.orientation = orientation;
898    }
899
900    fn internal_edge_ids(&self) -> Vec<EdgeId> {
901        self.vertices
902            .iter()
903            .flat_map(WorkingVertex::edges)
904            .filter(|edge| edge.kind == WorkingEdgeKind::Internal)
905            .map(|edge| edge.id)
906            .collect::<BTreeSet<_>>()
907            .into_iter()
908            .collect()
909    }
910
911    /// Internal edges whose two ends attach to the same working vertex.
912    fn self_loop_edge_ids(&self) -> Vec<EdgeId> {
913        self.vertices
914            .iter()
915            .flat_map(|vertex| {
916                vertex
917                    .outgoing
918                    .iter()
919                    .filter(|edge| {
920                        edge.kind == WorkingEdgeKind::Internal && vertex.incoming.contains(edge)
921                    })
922                    .map(|edge| edge.id)
923            })
924            .collect()
925    }
926
927    fn vertex(&self, vertices: VertexSet) -> Option<&WorkingVertex> {
928        self.vertices
929            .iter()
930            .find(|vertex| vertex.vertices == vertices)
931    }
932
933    fn shared_topology(&self) -> three_dimensional_reps::cff_recursion::CffGenerationGraph {
934        use three_dimensional_reps::cff_recursion::{
935            CffGenerationGraph, CffVertex, EdgeRef, EdgeType,
936        };
937        let convert = |edge: &WorkingEdge| EdgeRef {
938            edge_id: edge.id.index(),
939            edge_type: match edge.kind {
940                WorkingEdgeKind::Internal => EdgeType::Virtual,
941                WorkingEdgeKind::External => EdgeType::External,
942                WorkingEdgeKind::Boundary => EdgeType::Boundary,
943            },
944        };
945        CffGenerationGraph::new(
946            self.vertices
947                .iter()
948                .map(|vertex| CffVertex {
949                    nodes: vertex.vertices.iter().map(|id| id.index()).collect(),
950                    incoming: vertex.incoming.iter().map(convert).collect(),
951                    outgoing: vertex.outgoing.iter().map(convert).collect(),
952                })
953                .collect(),
954        )
955    }
956
957    fn has_directed_cycle(&self) -> bool {
958        self.shared_topology().has_directed_cycle()
959    }
960
961    fn contract_edge(&mut self, edge: EdgeId) -> Result<(), CffError> {
962        let source = self
963            .vertices
964            .iter()
965            .find(|vertex| vertex.outgoing.iter().any(|item| item.id == edge))
966            .map(|vertex| vertex.vertices)
967            .ok_or(CffError::NotInternalEdge(edge))?;
968        let sink = self
969            .vertices
970            .iter()
971            .find(|vertex| vertex.incoming.iter().any(|item| item.id == edge))
972            .map(|vertex| vertex.vertices)
973            .ok_or(CffError::NotInternalEdge(edge))?;
974        if source == sink {
975            self.remove_edge(edge);
976        } else {
977            *self = self.contract_vertices(source, sink, Some(edge))?;
978        }
979        Ok(())
980    }
981
982    fn remove_edge(&mut self, edge: EdgeId) {
983        for vertex in &mut self.vertices {
984            vertex.incoming.retain(|item| item.id != edge);
985            vertex.outgoing.retain(|item| item.id != edge);
986        }
987    }
988
989    fn contract_vertices(
990        &self,
991        left: VertexSet,
992        right: VertexSet,
993        remove_single: Option<EdgeId>,
994    ) -> Result<Self, CffError> {
995        let left_vertex = self
996            .vertex(left)
997            .ok_or_else(|| CffError::Invariant("left contraction vertex is missing".to_owned()))?;
998        let right_vertex = self
999            .vertex(right)
1000            .ok_or_else(|| CffError::Invariant("right contraction vertex is missing".to_owned()))?;
1001        let shared_edges = left_vertex
1002            .edges()
1003            .filter(|left_edge| {
1004                right_vertex
1005                    .edges()
1006                    .any(|right_edge| left_edge == &right_edge)
1007            })
1008            .map(|edge| edge.id)
1009            .collect::<BTreeSet<_>>();
1010        let retain = |edge: &WorkingEdge| match remove_single {
1011            Some(remove) => edge.id != remove,
1012            None => !shared_edges.contains(&edge.id),
1013        };
1014        let mut incoming = left_vertex
1015            .incoming
1016            .iter()
1017            .chain(&right_vertex.incoming)
1018            .filter(|edge| retain(edge))
1019            .copied()
1020            .collect::<Vec<_>>();
1021        let mut outgoing = left_vertex
1022            .outgoing
1023            .iter()
1024            .chain(&right_vertex.outgoing)
1025            .filter(|edge| retain(edge))
1026            .copied()
1027            .collect::<Vec<_>>();
1028        incoming.sort_by_key(|edge| edge.id);
1029        outgoing.sort_by_key(|edge| edge.id);
1030
1031        let mut vertices = self
1032            .vertices
1033            .iter()
1034            .filter(|vertex| vertex.vertices != left && vertex.vertices != right)
1035            .cloned()
1036            .collect::<Vec<_>>();
1037        vertices.push(WorkingVertex {
1038            vertices: left.union(right),
1039            incoming,
1040            outgoing,
1041        });
1042        vertices.sort_by_key(|vertex| vertex.vertices);
1043        Ok(Self {
1044            vertices,
1045            orientation: self.orientation.clone(),
1046        })
1047    }
1048
1049    fn surface_for(&self, vertex: &WorkingVertex) -> Result<Surface, CffError> {
1050        let vertex_type = vertex.vertex_type();
1051        if vertex_type == VertexType::Neither {
1052            return Err(CffError::Invariant(
1053                "only a source or sink may generate a surface".to_owned(),
1054            ));
1055        }
1056        let mut external_shift = ExternalShift::default();
1057        for edge in vertex
1058            .incoming
1059            .iter()
1060            .filter(|edge| edge.kind == WorkingEdgeKind::External)
1061        {
1062            external_shift.add(
1063                edge.id,
1064                match vertex_type {
1065                    VertexType::Source => -1,
1066                    VertexType::Sink => 1,
1067                    VertexType::Neither => 0,
1068                },
1069            )?;
1070        }
1071        for edge in vertex
1072            .outgoing
1073            .iter()
1074            .filter(|edge| edge.kind == WorkingEdgeKind::External)
1075        {
1076            external_shift.add(
1077                edge.id,
1078                match vertex_type {
1079                    VertexType::Source => 1,
1080                    VertexType::Sink => -1,
1081                    VertexType::Neither => 0,
1082                },
1083            )?;
1084        }
1085
1086        let mut positive_energies = vertex
1087            .edges()
1088            .filter(|edge| edge.kind == WorkingEdgeKind::Internal)
1089            .map(|edge| edge.id)
1090            .collect::<Vec<_>>();
1091        if vertex.generates_energy_surface() {
1092            positive_energies.extend(
1093                vertex
1094                    .edges()
1095                    .filter(|edge| edge.kind == WorkingEdgeKind::Boundary)
1096                    .map(|edge| edge.id),
1097            );
1098            positive_energies.sort();
1099            return Ok(Surface::Energy(EnergySurface {
1100                energies: positive_energies,
1101                external_shift,
1102                vertex_set: vertex.vertices,
1103            }));
1104        }
1105
1106        let (positive_boundary, negative_energies): (Vec<_>, Vec<_>) = match vertex_type {
1107            VertexType::Sink => (
1108                vertex
1109                    .incoming
1110                    .iter()
1111                    .filter(|edge| edge.kind == WorkingEdgeKind::Boundary)
1112                    .map(|edge| edge.id)
1113                    .collect(),
1114                vertex
1115                    .outgoing
1116                    .iter()
1117                    .filter(|edge| edge.kind == WorkingEdgeKind::Boundary)
1118                    .map(|edge| edge.id)
1119                    .collect(),
1120            ),
1121            VertexType::Source => (
1122                vertex
1123                    .outgoing
1124                    .iter()
1125                    .filter(|edge| edge.kind == WorkingEdgeKind::Boundary)
1126                    .map(|edge| edge.id)
1127                    .collect(),
1128                vertex
1129                    .incoming
1130                    .iter()
1131                    .filter(|edge| edge.kind == WorkingEdgeKind::Boundary)
1132                    .map(|edge| edge.id)
1133                    .collect(),
1134            ),
1135            VertexType::Neither => {
1136                return Err(CffError::Invariant(
1137                    "only a source or sink may generate a surface".to_owned(),
1138                ));
1139            }
1140        };
1141        positive_energies.extend(positive_boundary);
1142        positive_energies.sort();
1143        let mut negative_energies = negative_energies;
1144        negative_energies.sort();
1145        Ok(Surface::H(HSurface {
1146            positive_energies,
1147            negative_energies,
1148            external_shift,
1149            vertex_set: vertex.vertices,
1150        }))
1151    }
1152}
1153
1154fn move_initial_state_energies(
1155    surface: Surface,
1156    initial: &BTreeSet<EdgeId>,
1157) -> Result<Surface, CffError> {
1158    match surface {
1159        Surface::Energy(mut surface) => {
1160            let moved = surface
1161                .energies
1162                .iter()
1163                .filter(|edge| initial.contains(edge))
1164                .copied()
1165                .collect::<Vec<_>>();
1166            surface.energies.retain(|edge| !initial.contains(edge));
1167            for edge in moved {
1168                surface.external_shift.add(edge, 1)?;
1169            }
1170            Ok(Surface::Energy(surface))
1171        }
1172        Surface::H(mut surface) => {
1173            let moved_positive = surface
1174                .positive_energies
1175                .iter()
1176                .filter(|edge| initial.contains(edge))
1177                .copied()
1178                .collect::<Vec<_>>();
1179            let moved_negative = surface
1180                .negative_energies
1181                .iter()
1182                .filter(|edge| initial.contains(edge))
1183                .copied()
1184                .collect::<Vec<_>>();
1185            surface
1186                .positive_energies
1187                .retain(|edge| !initial.contains(edge));
1188            surface
1189                .negative_energies
1190                .retain(|edge| !initial.contains(edge));
1191            for edge in moved_positive {
1192                surface.external_shift.add(edge, 1)?;
1193            }
1194            for edge in moved_negative {
1195                surface.external_shift.add(edge, -1)?;
1196            }
1197            if surface.negative_energies.is_empty() {
1198                Ok(Surface::Energy(EnergySurface {
1199                    energies: surface.positive_energies,
1200                    external_shift: surface.external_shift,
1201                    vertex_set: surface.vertex_set,
1202                }))
1203            } else {
1204                Ok(Surface::H(surface))
1205            }
1206        }
1207        surface => Ok(surface),
1208    }
1209}
1210
1211#[cfg(test)]
1212mod tests {
1213    use std::sync::Arc;
1214
1215    use bincode::config;
1216
1217    use super::*;
1218    use crate::{CffEdge, VertexId};
1219    use feynkit_graph::{DiagramEdge, DiagramVertex, ExternalState, FeynmanDiagram};
1220    use feynkit_model::Model;
1221    use linnet::{
1222        half_edge::subgraph::{ModifySubSet, SuBitGraph},
1223        parser::DotGraph,
1224    };
1225    use symbolica::atom::Atom;
1226
1227    fn edge(index: usize) -> EdgeId {
1228        EdgeId::new(index)
1229    }
1230
1231    fn vertex(index: usize) -> VertexId {
1232        VertexId::new(index)
1233    }
1234
1235    fn bubble() -> CffGraph {
1236        CffGraph::new(
1237            2,
1238            [
1239                CffEdge::external(edge(0), vertex(0), EdgeFlow::Incoming),
1240                CffEdge::external(edge(1), vertex(1), EdgeFlow::Outgoing),
1241                CffEdge::internal(edge(2), vertex(0), vertex(1)),
1242                CffEdge::internal(edge(3), vertex(0), vertex(1)),
1243            ],
1244        )
1245        .unwrap()
1246    }
1247
1248    #[test]
1249    fn generates_only_acyclic_bubble_orientations() {
1250        let result = CffGenerator::default().generate(&bubble()).unwrap();
1251
1252        assert_eq!(result.report.candidate_orientations, 4);
1253        assert_eq!(result.report.acyclic_orientations, 2);
1254        assert_eq!(result.report.unfolded_terms, 2);
1255        assert_eq!(result.surfaces.energy_surfaces().len(), 2);
1256        assert!(result.surfaces.h_surfaces().is_empty());
1257        assert!(
1258            result
1259                .expression
1260                .orientations()
1261                .iter()
1262                .all(|orientation| orientation.denominator_products().len() == 1)
1263        );
1264    }
1265
1266    #[test]
1267    fn triangle_preserves_the_source_sink_contraction_tree() {
1268        let graph = CffGraph::new(
1269            3,
1270            [
1271                CffEdge::internal(edge(0), vertex(0), vertex(1)),
1272                CffEdge::internal(edge(1), vertex(1), vertex(2)),
1273                CffEdge::internal(edge(2), vertex(0), vertex(2)),
1274            ],
1275        )
1276        .unwrap();
1277        let result = CffGenerator::default().generate(&graph).unwrap();
1278
1279        assert_eq!(result.report.candidate_orientations, 8);
1280        assert_eq!(result.report.acyclic_orientations, 6);
1281        // Of the two apparent contractions from a triangle source/sink, one
1282        // would orient the remaining parallel edges into a directed cycle.
1283        assert_eq!(result.report.unfolded_terms, 6);
1284        assert!(
1285            result
1286                .expression
1287                .orientations()
1288                .iter()
1289                .all(|orientation| orientation.denominator_products().len() == 1)
1290        );
1291    }
1292
1293    #[test]
1294    fn fixed_orientation_prunes_the_search_before_generation() {
1295        let options = CffOptions::default()
1296            .with_fixed_orientation(edge(2), EdgeOrientation::Default)
1297            .with_fixed_orientation(edge(3), EdgeOrientation::Default);
1298        let result = CffGenerator::new(options).generate(&bubble()).unwrap();
1299
1300        assert_eq!(result.report.candidate_orientations, 1);
1301        assert_eq!(result.report.acyclic_orientations, 1);
1302    }
1303
1304    #[test]
1305    fn cache_is_local_to_each_generation() {
1306        let generator = CffGenerator::default();
1307        let first = generator.generate(&bubble()).unwrap();
1308        let second = generator.generate(&bubble()).unwrap();
1309
1310        assert_eq!(first.surfaces, second.surfaces);
1311        assert_eq!(first.expression, second.expression);
1312    }
1313
1314    #[test]
1315    fn shared_arena_preserves_existing_expression_ids_and_raised_data() {
1316        let generator = CffGenerator::default();
1317        let mut surfaces = SurfaceCache::default();
1318        let first = generator.generate_into(&bubble(), &mut surfaces).unwrap();
1319        let first_expression = first.expression.clone();
1320        let first_ids = first_expression
1321            .orientations()
1322            .iter()
1323            .flat_map(|orientation| orientation.expression.nodes())
1324            .map(|node| node.data)
1325            .collect::<BTreeSet<_>>();
1326        let first_resolved = first_ids
1327            .iter()
1328            .map(|id| (*id, surfaces.get(*id).unwrap()))
1329            .collect::<Vec<_>>();
1330        let representative = |edge| {
1331            if edge == EdgeId::new(3) {
1332                EdgeId::new(2)
1333            } else {
1334                edge
1335            }
1336        };
1337        let raised_before = first_expression
1338            .raised_energy_surfaces(&surfaces, representative)
1339            .unwrap();
1340        let first_surface_count = surfaces.len();
1341
1342        let triangle = CffGraph::new(
1343            3,
1344            [
1345                CffEdge::internal(edge(4), vertex(0), vertex(1)),
1346                CffEdge::internal(edge(5), vertex(1), vertex(2)),
1347                CffEdge::internal(edge(6), vertex(0), vertex(2)),
1348            ],
1349        )
1350        .unwrap();
1351        generator.generate_into(&triangle, &mut surfaces).unwrap();
1352
1353        assert!(surfaces.len() > first_surface_count);
1354        assert_eq!(first.expression, first_expression);
1355        assert_eq!(
1356            first_expression
1357                .raised_energy_surfaces(&surfaces, representative)
1358                .unwrap(),
1359            raised_before
1360        );
1361        for (id, surface) in first_resolved {
1362            assert_eq!(surfaces.get(id), Some(surface));
1363        }
1364    }
1365
1366    #[test]
1367    fn boundary_edges_generate_h_surfaces() {
1368        let graph = CffGraph::new(
1369            2,
1370            [
1371                CffEdge::boundary(edge(0), vertex(0), EdgeFlow::Incoming),
1372                CffEdge::external(edge(1), vertex(1), EdgeFlow::Outgoing),
1373                CffEdge::internal(edge(2), vertex(0), vertex(1)),
1374            ],
1375        )
1376        .unwrap();
1377        let result = CffGenerator::default().generate(&graph).unwrap();
1378
1379        assert!(!result.surfaces.h_surfaces().is_empty());
1380        assert!(result.surfaces.h_surfaces().iter().any(|surface| {
1381            surface.negative_energies == vec![edge(0)]
1382                || surface.positive_energies.contains(&edge(0))
1383        }));
1384    }
1385
1386    #[test]
1387    fn initial_state_energy_and_dependent_shift_are_canonicalized() {
1388        let graph = CffGraph::new(
1389            2,
1390            [
1391                CffEdge::external(edge(0), vertex(0), EdgeFlow::Incoming),
1392                CffEdge::external(edge(1), vertex(1), EdgeFlow::Outgoing),
1393                CffEdge::internal(edge(2), vertex(0), vertex(1)),
1394            ],
1395        )
1396        .unwrap();
1397        let options = CffOptions::default()
1398            .with_initial_state_edge(edge(2))
1399            .with_shift_rewrite(ShiftRewrite {
1400                dependent_momentum: edge(2),
1401                replacement: ExternalShift::new([(edge(0), -1), (edge(1), 1)]).unwrap(),
1402            });
1403        let result = CffGenerator::new(options).generate(&graph).unwrap();
1404
1405        assert!(result.surfaces.energy_surfaces().iter().all(|surface| {
1406            !surface.energies.contains(&edge(2)) && surface.external_shift.get(edge(2)) == 0
1407        }));
1408    }
1409
1410    #[test]
1411    fn reports_orientation_budget_before_searching() {
1412        let error = CffGenerator::new(CffOptions::default().with_max_orientations(3))
1413            .generate(&bubble())
1414            .unwrap_err();
1415
1416        assert_eq!(
1417            error,
1418            CffError::TooManyOrientations {
1419                candidate_count: 4,
1420                maximum: 3,
1421            }
1422        );
1423    }
1424
1425    #[test]
1426    fn rejects_undirected_fixed_orientation() {
1427        let error = CffGenerator::new(
1428            CffOptions::default().with_fixed_orientation(edge(2), EdgeOrientation::Undirected),
1429        )
1430        .generate(&bubble())
1431        .unwrap_err();
1432
1433        assert_eq!(error, CffError::UndirectedFixedEdge(edge(2)));
1434    }
1435
1436    fn half_weights(count: u32) -> OrientationWeight {
1437        OrientationWeight::from_halvings(count)
1438    }
1439
1440    fn bubble_with_self_loops(count: usize) -> CffGraph {
1441        CffGraph::new(
1442            2,
1443            [
1444                CffEdge::internal(edge(0), vertex(0), vertex(1)),
1445                CffEdge::internal(edge(1), vertex(0), vertex(1)),
1446                CffEdge::internal(edge(2), vertex(0), vertex(0)),
1447                CffEdge::internal(edge(3), vertex(1), vertex(1)),
1448            ]
1449            .into_iter()
1450            .take(2 + count),
1451        )
1452        .unwrap()
1453    }
1454
1455    // The shared recursion in `three-dimensional-reps` weights each of the two
1456    // closures of a vacuum self-loop by one half, and both closures carry the
1457    // same denominators, so their sum equals one closure at unit weight.
1458    #[test]
1459    fn a_self_loop_keeps_both_closures_with_half_weights() {
1460        let graph = CffGraph::new(1, [CffEdge::internal(edge(0), vertex(0), vertex(0))]).unwrap();
1461        let result = CffGenerator::default().generate(&graph).unwrap();
1462
1463        assert_eq!(result.report.acyclic_orientations, 2);
1464        let directions = result
1465            .expression
1466            .orientations()
1467            .iter()
1468            .map(|orientation| orientation.data.orientation[edge(0)])
1469            .collect::<Vec<_>>();
1470        assert_eq!(
1471            directions,
1472            vec![EdgeOrientation::Default, EdgeOrientation::Reversed]
1473        );
1474        for orientation in result.expression.orientations() {
1475            assert_eq!(orientation.weight, half_weights(1));
1476            assert_eq!(
1477                orientation.denominator_products(),
1478                vec![vec![SurfaceId::Unit]]
1479            );
1480        }
1481        assert_eq!(result.expression.to_atom(), Atom::num(1));
1482    }
1483
1484    // Fixing a direction selects one closure without reweighting it, exactly as
1485    // fixing an ordinary edge selects orientations: the weight stays one half.
1486    #[test]
1487    fn a_fixed_self_loop_keeps_its_half_weight() {
1488        let graph = CffGraph::new(1, [CffEdge::internal(edge(0), vertex(0), vertex(0))]).unwrap();
1489        let result = CffGenerator::new(
1490            CffOptions::default().with_fixed_orientation(edge(0), EdgeOrientation::Reversed),
1491        )
1492        .generate(&graph)
1493        .unwrap();
1494
1495        assert_eq!(result.report.acyclic_orientations, 1);
1496        let orientation = &result.expression.orientations()[0];
1497        assert_eq!(
1498            orientation.data.orientation[edge(0)],
1499            EdgeOrientation::Reversed
1500        );
1501        assert_eq!(orientation.weight, half_weights(1));
1502        assert_eq!(result.expression.to_atom(), Atom::num(1) / Atom::num(2));
1503    }
1504
1505    #[test]
1506    fn filtering_self_loop_closures_matches_fixing_them() {
1507        for count in [1, 2] {
1508            let self_loops = [edge(2), edge(3)]
1509                .into_iter()
1510                .take(count)
1511                .collect::<Vec<_>>();
1512            let graph = bubble_with_self_loops(count);
1513            let mut filtered = CffGenerator::default().generate(&graph).unwrap();
1514            filtered.expression.retain_orientations(|orientation| {
1515                self_loops
1516                    .iter()
1517                    .all(|edge| orientation[*edge] == EdgeOrientation::Reversed)
1518            });
1519            let options = self_loops
1520                .iter()
1521                .fold(CffOptions::default(), |options, edge| {
1522                    options.with_fixed_orientation(*edge, EdgeOrientation::Reversed)
1523                });
1524            let fixed = CffGenerator::new(options).generate(&graph).unwrap();
1525
1526            assert_eq!(filtered.expression, fixed.expression, "{count} self-loops");
1527            assert_eq!(filtered.surfaces, fixed.surfaces, "{count} self-loops");
1528            assert!(
1529                fixed
1530                    .expression
1531                    .orientations()
1532                    .iter()
1533                    .all(|orientation| orientation.weight == half_weights(count as u32))
1534            );
1535        }
1536    }
1537
1538    #[test]
1539    fn a_self_loop_attached_to_a_bubble_leaves_its_surfaces_unchanged() {
1540        let reference = CffGenerator::default()
1541            .generate(&bubble_with_self_loops(0))
1542            .unwrap();
1543        let result = CffGenerator::default()
1544            .generate(&bubble_with_self_loops(1))
1545            .unwrap();
1546
1547        let products = |result: &CffResult| {
1548            result
1549                .expression
1550                .orientations()
1551                .iter()
1552                .map(OrientationExpression::denominator_products)
1553                .collect::<Vec<_>>()
1554        };
1555        // Edge 2 is the most significant enumeration bit, so each bubble
1556        // orientation appears once per closure of the self-loop.
1557        let reference_products = products(&reference);
1558        assert_eq!(
1559            products(&result),
1560            [reference_products.as_slice(); 2].concat()
1561        );
1562        assert_eq!(
1563            result.surfaces.energy_surfaces(),
1564            reference.surfaces.energy_surfaces()
1565        );
1566        assert!(
1567            result
1568                .surfaces
1569                .energy_surfaces()
1570                .iter()
1571                .all(|surface| surface.energies == vec![edge(0), edge(1)])
1572        );
1573        assert_eq!(result.expression.to_atom(), reference.expression.to_atom());
1574    }
1575
1576    #[test]
1577    fn contracting_one_bubble_edge_leaves_two_half_weight_tadpole_closures() {
1578        let result = CffGenerator::new(CffOptions::default().with_contracted_edge(edge(2)))
1579            .generate(&bubble())
1580            .unwrap();
1581
1582        assert_eq!(result.report.acyclic_orientations, 2);
1583        for orientation in result.expression.orientations() {
1584            assert_eq!(orientation.weight, half_weights(1));
1585            assert_eq!(
1586                orientation.data.orientation[edge(2)],
1587                EdgeOrientation::Undirected
1588            );
1589            assert_eq!(
1590                orientation.denominator_products(),
1591                vec![vec![SurfaceId::Unit]]
1592            );
1593        }
1594        assert_eq!(result.expression.to_atom(), Atom::num(1));
1595    }
1596
1597    /// Unit-weight, half-weight and partly emptied generated results.
1598    fn result_controls() -> Vec<CffResult> {
1599        let unit = CffGenerator::default().generate(&bubble()).unwrap();
1600        let weighted = CffGenerator::default()
1601            .generate(&bubble_with_self_loops(1))
1602            .unwrap();
1603        let mut emptied = weighted.clone();
1604        emptied.expression.orientations_mut()[0]
1605            .expression
1606            .retain_branches_with_value_count(&SurfaceId::Unit, 1);
1607        assert!(emptied.expression.orientations()[0].expression.is_empty());
1608        vec![unit, weighted, emptied]
1609    }
1610
1611    #[test]
1612    fn results_round_trip_through_bincode_and_json() {
1613        for result in result_controls() {
1614            let bytes = bincode::encode_to_vec(&result, config::standard()).unwrap();
1615            let (decoded, read): (CffResult, usize) =
1616                bincode::decode_from_slice(&bytes, config::standard()).unwrap();
1617            assert_eq!((&decoded, read), (&result, bytes.len()));
1618
1619            let json = serde_json::to_string(&result).unwrap();
1620            assert_eq!(serde_json::from_str::<CffResult>(&json).unwrap(), result);
1621        }
1622    }
1623
1624    #[test]
1625    fn result_round_trips_through_json() {
1626        let result = CffGenerator::default().generate(&bubble()).unwrap();
1627        let json = serde_json::to_string(&result).unwrap();
1628        let decoded: CffResult = serde_json::from_str(&json).unwrap();
1629
1630        assert_eq!(decoded, result);
1631    }
1632
1633    #[test]
1634    fn generates_from_a_feynman_diagram_conversion() {
1635        let model = Arc::new(
1636            Model::from_json(include_str!(
1637                "../../feynkit-model/tests/fixtures/scalars_2p_3p.json"
1638            ))
1639            .unwrap(),
1640        );
1641        let mut builder = FeynmanDiagram::builder(Arc::clone(&model), "bubble");
1642        let rule = model.vertex_rule_id("V_3_SCALAR_000").unwrap();
1643        let left = builder.add_vertex(DiagramVertex::interaction("left", rule));
1644        let right = builder.add_vertex(DiagramVertex::interaction("right", rule));
1645        let scalar = || DiagramEdge::new(model.particle_id("scalar_0").unwrap(), false);
1646        let external = |index, state| {
1647            let mut edge = scalar();
1648            edge.external = Some(feynkit_graph::ExternalLeg {
1649                name: format!("p{index}"),
1650                index,
1651                state,
1652                connection: index,
1653            });
1654            edge
1655        };
1656        builder
1657            .add_edge(None, left, external(0, ExternalState::Incoming))
1658            .unwrap();
1659        builder
1660            .add_edge(right, None, external(1, ExternalState::Outgoing))
1661            .unwrap();
1662        builder.add_edge(left, right, scalar()).unwrap();
1663        builder.add_edge(left, right, scalar()).unwrap();
1664        let diagram = builder.build().unwrap();
1665
1666        let result = diagram.build_cff(CffOptions::default()).unwrap();
1667
1668        assert_eq!(result.report.candidate_orientations, 4);
1669        assert_eq!(result.report.acyclic_orientations, 2);
1670        assert_eq!(result.report.unfolded_terms, 2);
1671    }
1672
1673    #[test]
1674    fn linnet_subgraph_keeps_original_ids_boundary_flow_and_caller_cache() {
1675        let graph: DotGraph = DotGraph::from_string(
1676            r#"
1677            digraph triangle {
1678                ext_in [style=invis]
1679                ext_out [style=invis]
1680                A [id=0]
1681                B [id=1]
1682                C [id=2]
1683                A -> C [id=0]
1684                B -> C [id=1]
1685                A -> B [id=2]
1686                C -> ext_out [id=3]
1687                ext_in -> A [id=4]
1688            }
1689            "#,
1690        )
1691        .unwrap();
1692        let mut selected: SuBitGraph = graph.empty_subgraph();
1693        for (_, neighbours, vertex) in graph.iter_nodes() {
1694            if matches!(vertex.name(), Some("B" | "C")) {
1695                neighbours.for_each(|hedge| selected.add(hedge));
1696            }
1697        }
1698
1699        let mut cache = SurfaceCache::default();
1700        cache.intern(Surface::Energy(EnergySurface {
1701            energies: vec![edge(99)],
1702            external_shift: ExternalShift::default(),
1703            vertex_set: VertexSet::dummy(),
1704        }));
1705        let result = graph
1706            .build_cff_from_subgraph(
1707                &selected,
1708                CffOptions::default().with_initial_state_edge(edge(1)),
1709                &[edge(2)],
1710                &mut cache,
1711            )
1712            .unwrap();
1713
1714        assert_eq!(result.surfaces, cache);
1715        assert!(cache.len() > 1);
1716        for orientation in result.orientations() {
1717            assert_eq!(orientation.data.orientation[edge(2)], Orientation::Reversed);
1718            assert_eq!(
1719                orientation.data.orientation[edge(4)],
1720                Orientation::Undirected
1721            );
1722            assert_ne!(
1723                orientation.data.orientation[edge(1)],
1724                Orientation::Undirected
1725            );
1726        }
1727        assert!(cache.energy_surfaces().iter().skip(1).all(|surface| {
1728            !surface.energies.contains(&edge(1))
1729                && surface
1730                    .vertex_set
1731                    .iter()
1732                    .all(|vertex| [1, 2].contains(&vertex.0))
1733        }));
1734        assert!(cache.h_surfaces().iter().all(|surface| {
1735            !surface.positive_energies.contains(&edge(1))
1736                && !surface.negative_energies.contains(&edge(1))
1737                && surface
1738                    .vertex_set
1739                    .iter()
1740                    .all(|vertex| [1, 2].contains(&vertex.0))
1741        }));
1742        assert!(
1743            cache
1744                .energy_surfaces()
1745                .iter()
1746                .skip(1)
1747                .any(|surface| surface.external_shift.get(edge(1)) != 0)
1748                || cache
1749                    .h_surfaces()
1750                    .iter()
1751                    .any(|surface| surface.external_shift.get(edge(1)) != 0)
1752        );
1753    }
1754
1755    #[test]
1756    fn selected_sewn_boundary_retains_positive_external_energy() {
1757        let graph: DotGraph = DotGraph::from_string(
1758            r#"digraph sewn {
1759                ext_in [style=invis]
1760                A [id=0]
1761                B [id=1]
1762                C [id=2]
1763                A -> B [id=0]
1764                A -> B [id=1]
1765                B -> C [id=2]
1766                ext_in -> A [id=3]
1767            }"#,
1768        )
1769        .unwrap();
1770        let mut selected: SuBitGraph = graph.empty_subgraph();
1771        for (_, neighbours, vertex) in graph.iter_nodes() {
1772            if matches!(vertex.name(), Some("A" | "B")) {
1773                neighbours.for_each(|hedge| selected.add(hedge));
1774            }
1775        }
1776        let actual = graph
1777            .build_cff_from_subgraph_with_edge_roles(
1778                &selected,
1779                CffOptions::default(),
1780                &[],
1781                |id| match id.index() {
1782                    2 => HedgeEdgeRole::InitialState,
1783                    3 => HedgeEdgeRole::UnorientedExternal,
1784                    _ => HedgeEdgeRole::Standard,
1785                },
1786                &mut SurfaceCache::default(),
1787            )
1788            .unwrap();
1789        let expected = CffGenerator::default()
1790            .generate(
1791                &CffGraph::new(
1792                    2,
1793                    [
1794                        CffEdge::internal(edge(0), vertex(0), vertex(1)),
1795                        CffEdge::internal(edge(1), vertex(0), vertex(1)),
1796                        CffEdge::external(edge(2), vertex(1), EdgeFlow::Outgoing),
1797                        CffEdge::external(edge(3), vertex(0), EdgeFlow::Incoming),
1798                    ],
1799                )
1800                .unwrap(),
1801            )
1802            .unwrap();
1803        assert_eq!(actual.surfaces, expected.surfaces);
1804        assert_eq!(actual.expression.to_atom(), expected.expression.to_atom());
1805        assert!(actual.orientations().iter().all(|orientation| {
1806            orientation.data.orientation[edge(2)] == Orientation::Undirected
1807        }));
1808        assert!(
1809            actual
1810                .surfaces
1811                .energy_surfaces()
1812                .iter()
1813                .all(|surface| { !surface.energies.contains(&edge(2)) })
1814        );
1815    }
1816
1817    #[test]
1818    fn linnet_edge_roles_cover_runtime_bookkeeping_without_an_adapter_graph() {
1819        let graph: DotGraph = DotGraph::from_string(
1820            r#"
1821            digraph bubble {
1822                ext_in [style=invis]
1823                ext_out [style=invis]
1824                ext_in -> A [id=2]
1825                B -> ext_out [id=3]
1826                A -> B [id=0]
1827                A -> B [id=1]
1828                A -> B [id=4]
1829            }
1830            "#,
1831        )
1832        .unwrap();
1833        let mut cache = SurfaceCache::default();
1834        let result = graph
1835            .build_cff_from_subgraph_with_edge_roles(
1836                &graph.full_filter(),
1837                CffOptions::default().with_contracted_edge(edge(0)),
1838                &[],
1839                |id| match id.index() {
1840                    1 => HedgeEdgeRole::InitialState,
1841                    2 | 3 => HedgeEdgeRole::UnorientedExternal,
1842                    4 => HedgeEdgeRole::Omitted,
1843                    _ => HedgeEdgeRole::Standard,
1844                },
1845                &mut cache,
1846            )
1847            .unwrap();
1848
1849        assert_eq!(result.report.candidate_orientations, 1);
1850        assert_eq!(result.orientations().len(), 1);
1851        let orientation = &result.orientations()[0].data.orientation;
1852        assert_eq!(orientation[edge(0)], Orientation::Undirected);
1853        assert_eq!(orientation[edge(1)], Orientation::Default);
1854        assert_eq!(orientation[edge(2)], Orientation::Undirected);
1855        assert_eq!(orientation[edge(3)], Orientation::Undirected);
1856        assert_eq!(orientation[edge(4)], Orientation::Undirected);
1857    }
1858}