Skip to main content

feynkit_graph/
expressions.rs

1//! Symbolic graph traversal shared with runtime graph consumers.
2//!
3//! A selected paired edge contributes its local numerator and the numerators of
4//! both incident vertices. Remaining vertices contribute only when their whole
5//! crown is selected, allowing dummy half-edges to be absent. An excluded region
6//! removes its edges and all vertices incident to that region.
7
8use linnet::half_edge::{
9    HedgeGraph, NodeIndex,
10    involution::{EdgeIndex, HedgePair},
11    subgraph::{ModifySubSet, SubGraphLike, SubSetLike, SubSetOps, subset::SubSet},
12};
13use spenso::structure::{
14    dimension::Dimension,
15    representation::{Minkowski, RepName},
16};
17use symbolica::{
18    atom::{Atom, AtomCore, AtomView, Symbol},
19    function, symbol,
20};
21
22/// Evaluate bookkeeping heads without distributing the scalar payload.
23pub fn evaluate_overall_factor(factor: AtomView<'_>) -> Atom {
24    let mut result = factor.to_owned();
25    for head in [
26        "AutG",
27        "CouplingsMultiplicity",
28        "InternalFermionLoopSign",
29        "ExternalFermionOrderingSign",
30        "AntiFermionSpinSumSign",
31        "NumeratorIndependentSymmetryGrouping",
32    ] {
33        for symbol in [
34            symbol!(&format!("gammalooprs::{head}")),
35            symbol!(&format!("feynkit_generator_factor::{head}")),
36        ] {
37            result = result
38                .replace(function!(symbol, Atom::var(symbol!("x_"))).to_pattern())
39                .with(Atom::var(symbol!("x_")).to_pattern());
40        }
41    }
42    for head in [
43        symbol!("gammalooprs::NumeratorDependentGrouping"),
44        symbol!("feynkit_generator::NumeratorDependentGrouping"),
45        symbol!("feynkit_generator_factor::NumeratorDependentGrouping"),
46    ] {
47        result = result
48            .replace(
49                function!(
50                    head,
51                    Atom::var(symbol!("GraphId_")),
52                    Atom::var(symbol!("ratio_")),
53                    Atom::var(symbol!("GraphSymmetryFactor_"))
54                )
55                .to_pattern(),
56            )
57            .with(
58                (Atom::var(symbol!("ratio_")) * Atom::var(symbol!("GraphSymmetryFactor_")))
59                    .to_pattern(),
60            );
61    }
62    result
63}
64
65/// Application data access is supplied by callers; the selection rules are shared.
66pub trait GraphExpressions<E, V> {
67    fn numerator_of<S: SubGraphLike + SubSetOps>(
68        &self,
69        subgraph: &S,
70        without: &S,
71        vertex_numerator: impl Fn(NodeIndex, &V) -> Atom,
72        edge_numerator: impl Fn(&E) -> Atom,
73        is_dummy: impl Fn(&E) -> bool,
74    ) -> Atom {
75        match self.try_fold_numerator(
76            subgraph,
77            without,
78            Atom::one(),
79            vertex_numerator,
80            edge_numerator,
81            is_dummy,
82            |left, right| Ok::<_, std::convert::Infallible>(left * right),
83        ) {
84            Ok(numerator) => numerator,
85            Err(never) => match never {},
86        }
87    }
88
89    /// Compose selected local fragments without erasing their owning value type.
90    /// Selection and dummy-edge rules are identical for source atoms and retained tensors.
91    #[allow(clippy::too_many_arguments)]
92    fn try_fold_numerator<S: SubGraphLike + SubSetOps, N, Error>(
93        &self,
94        subgraph: &S,
95        without: &S,
96        unit: N,
97        vertex_numerator: impl Fn(NodeIndex, &V) -> N,
98        edge_numerator: impl Fn(&E) -> N,
99        is_dummy: impl Fn(&E) -> bool,
100        product: impl FnMut(N, N) -> Result<N, Error>,
101    ) -> Result<N, Error>;
102
103    /// Only edges paired inside the selection contribute a propagator. Powers
104    /// may be negative or zero, and the factor callback is not run for zero powers.
105    fn denominator_of<S: SubGraphLike, Error>(
106        &self,
107        subgraph: &S,
108        propagator: impl Fn(EdgeIndex, &E) -> Result<Atom, Error>,
109        edge_power: impl Fn(EdgeIndex, &E) -> isize,
110    ) -> Result<Atom, Error>;
111}
112
113impl<E, V, H> GraphExpressions<E, V> for HedgeGraph<E, V, H> {
114    #[allow(clippy::too_many_arguments)]
115    fn try_fold_numerator<S: SubGraphLike + SubSetOps, N, Error>(
116        &self,
117        subgraph: &S,
118        without: &S,
119        unit: N,
120        vertex_numerator: impl Fn(NodeIndex, &V) -> N,
121        edge_numerator: impl Fn(&E) -> N,
122        is_dummy: impl Fn(&E) -> bool,
123        mut product: impl FnMut(N, N) -> Result<N, Error>,
124    ) -> Result<N, Error> {
125        let mut numerator = unit;
126        let mut seen: SubSet<NodeIndex> = SubSet::empty(self.n_nodes());
127        for (node, _, _) in self.iter_nodes_of(without) {
128            seen.add(node);
129        }
130        let selected = subgraph.subtract(without);
131        for (pair, _, edge) in self.iter_edges_of(&selected) {
132            if let HedgePair::Paired { source, sink } = pair {
133                for node in [self.node_id(source), self.node_id(sink)] {
134                    if !seen[node] {
135                        seen.add(node);
136                        numerator = product(numerator, vertex_numerator(node, &self[node]))?;
137                    }
138                }
139                numerator = product(numerator, edge_numerator(edge.data))?;
140            }
141        }
142        let unseen = !seen;
143        // From all the nodes not yet covered by paired edges, include those
144        // included in the subgraph, ignoring dummies.
145        for node in unseen.included_iter() {
146            if self
147                .iter_crown(node)
148                .all(|hedge| subgraph.includes(&hedge) || is_dummy(&self[self[&hedge]]))
149            {
150                numerator = product(numerator, vertex_numerator(node, &self[node]))?;
151            }
152        }
153        Ok(numerator)
154    }
155
156    fn denominator_of<S: SubGraphLike, Error>(
157        &self,
158        subgraph: &S,
159        propagator: impl Fn(EdgeIndex, &E) -> Result<Atom, Error>,
160        edge_power: impl Fn(EdgeIndex, &E) -> isize,
161    ) -> Result<Atom, Error> {
162        let mut denominator = Atom::one();
163        for (pair, edge_id, edge) in self.iter_edges_of(subgraph) {
164            if pair.is_paired() {
165                let power = edge_power(edge_id, edge.data);
166                if power != 0 {
167                    denominator *= propagator(edge_id, edge.data)?.pow(power as i64);
168                }
169            }
170        }
171        Ok(denominator)
172    }
173}
174
175/// Symbol families used by the canonical tagged quadratic propagator.
176#[derive(Clone, Copy)]
177pub struct PropagatorSymbols {
178    pub momentum: Symbol,
179    pub denominator: Symbol,
180}
181
182impl PropagatorSymbols {
183    /// The scalar energy component of a physical edge before momentum routing.
184    pub fn energy(&self, edge: EdgeIndex) -> Atom {
185        use spenso::structure::abstract_index::AIND_SYMBOLS;
186        function!(self.momentum, edge.0, function!(AIND_SYMBOLS.cind, 0))
187    }
188
189    /// The uncontracted Minkowski vector carried by an edge.
190    pub fn momentum(&self, edge: EdgeIndex, dimension: Dimension) -> Atom {
191        let representation = Minkowski {}.new_rep(dimension).to_symbolic([]);
192        self.momentum.call_args([Atom::num(edge.0), representation])
193    }
194
195    /// Keep the identity, uncontracted momentum and mass alongside the explicit
196    /// quadratic expression so UV derivatives can act on the fourth argument.
197    pub fn denominator(
198        &self,
199        edge: EdgeIndex,
200        mass_squared: &Atom,
201        dimension: impl Into<Dimension>,
202    ) -> Atom {
203        let momentum = self.momentum.call(edge.0);
204        let quadratic = Minkowski {}
205            .new_rep(dimension)
206            .inner_product(&momentum, &momentum)
207            - mass_squared;
208        self.denominator
209            .call_args([Atom::num(edge.0), momentum, mass_squared.clone(), quadratic])
210    }
211}
212
213impl crate::FeynmanDiagram {
214    /// Construct the selected local numerator using the same boundary and
215    /// exclusion rules as GammaLoop. Diagram-wide factors remain separate.
216    pub fn numerator_of<S: SubGraphLike + SubSetOps>(
217        &self,
218        subgraph: &S,
219        without: &S,
220    ) -> Result<
221        idenso::tensor::SymbolicTensor<spenso::structure::partial::PartialStructure>,
222        crate::DiagramError,
223    > {
224        Ok(self.graph.try_fold_numerator(
225            subgraph,
226            without,
227            idenso::tensor::SymbolicTensor::infer(Atom::one())?,
228            |_, vertex| vertex.numerator.clone(),
229            |edge| edge.numerator.clone(),
230            |edge| edge.is_dummy,
231            |left, right| left.multiply(&right),
232        )?)
233    }
234
235    pub fn denominator_of<S: SubGraphLike>(
236        &self,
237        subgraph: &S,
238        edge_powers: &std::collections::BTreeMap<crate::EdgeId, isize>,
239    ) -> Result<Atom, crate::DiagramError> {
240        self.denominator_of_in_dimension(subgraph, edge_powers, crate::symbols::dimension().into())
241    }
242
243    /// Symbolic dimension and signed propagator powers follow the runtime UV
244    /// representation, retaining its four-argument `denom` wrapper.
245    pub fn denominator_of_in_dimension<S: SubGraphLike>(
246        &self,
247        subgraph: &S,
248        edge_powers: &std::collections::BTreeMap<crate::EdgeId, isize>,
249        dimension: Dimension,
250    ) -> Result<Atom, crate::DiagramError> {
251        let symbols = PropagatorSymbols {
252            momentum: crate::symbols::momentum(),
253            denominator: crate::symbols::denominator(),
254        };
255        self.graph.denominator_of(
256            subgraph,
257            |edge_id, edge| {
258                let particle = self.model.particle_by_id(edge.particle)?;
259                let mass = particle
260                    .symbolic_mass(&self.model)
261                    .replace(symbolica::symbol!("UFO::ZERO"))
262                    .with(Atom::Zero);
263                Ok(symbols.denominator(edge_id, &mass.pow(2), dimension))
264            },
265            |edge_id, _| {
266                edge_powers
267                    .get(&crate::EdgeId(edge_id.0))
268                    .copied()
269                    .unwrap_or(1)
270            },
271        )
272    }
273
274    /// Local superficial degree for a half-edge selection, including its
275    /// boundary vertices and excluding physical external momentum carriers.
276    pub fn superficial_degree_of_divergence_of(
277        &self,
278        subgraph: &linnet::half_edge::subgraph::SuBitGraph,
279        dimension: i32,
280    ) -> Result<i32, crate::DiagramError> {
281        use crate::DOD;
282        let loops = self.momentum_basis_of(subgraph)?.loop_edges.len();
283        let mut degree = i64::from(dimension) * loops as i64;
284        for (_, _, vertex) in self.graph.iter_nodes_of(subgraph) {
285            degree += i64::from(
286                vertex
287                    .numerator
288                    .expression()
289                    .all_dod(crate::symbols::momentum())?,
290            );
291        }
292        for (pair, edge_id, edge) in self.graph.iter_edges_of(subgraph) {
293            if pair.is_paired() && edge.data.external.is_none() && !edge.data.is_dummy {
294                degree += i64::from(
295                    edge.data
296                        .numerator
297                        .expression()
298                        .edge_dod(crate::symbols::momentum(), edge_id.0)?,
299                ) - 2;
300            }
301        }
302        i32::try_from(degree).map_err(|_| {
303            crate::DiagramError::UvPowerCounting("degree exceeds the integer range".into())
304        })
305    }
306}
307
308#[cfg(test)]
309mod tests {
310    #[test]
311    fn evaluates_factor_annotations_without_erasing_unknown_heads() {
312        for namespace in ["gammalooprs", "feynkit_generator_factor"] {
313            let factor = Atom::parse(
314                "InternalFermionLoopSign(-1)*CouplingsMultiplicity(2)/AutG(4) + NumeratorDependentGrouping(7,2,3) + unknown(5)",
315                namespace,
316                symbolica::parser::ParseSettings::default(),
317            ).unwrap();
318            let expected = Atom::parse(
319                "11/2+unknown(5)",
320                namespace,
321                symbolica::parser::ParseSettings::default(),
322            )
323            .unwrap();
324            let evaluated = super::evaluate_overall_factor(factor.as_view());
325            assert_eq!(evaluated, expected);
326            assert_eq!(
327                super::evaluate_overall_factor(evaluated.as_view()),
328                evaluated
329            );
330        }
331    }
332
333    #[test]
334    fn evaluating_factor_annotations_preserves_powered_payloads() {
335        let factor = Atom::parse(
336            "NumeratorDependentGrouping(7,(x+y)^11,InternalFermionLoopSign(-1))",
337            "feynkit_generator_factor",
338            Default::default(),
339        )
340        .unwrap();
341        let expected =
342            Atom::parse("-(x+y)^11", "feynkit_generator_factor", Default::default()).unwrap();
343        assert_eq!(super::evaluate_overall_factor(factor.as_view()), expected);
344    }
345
346    use super::*;
347    use linnet::half_edge::{
348        builder::HedgeGraphBuilder,
349        involution::{Flow, Hedge, Orientation},
350        subgraph::SuBitGraph,
351    };
352
353    fn graph() -> HedgeGraph<(i32, bool), i32> {
354        let mut builder = HedgeGraphBuilder::new();
355        let a = builder.add_node(2);
356        let b = builder.add_node(3);
357        let c = builder.add_node(5);
358        builder.add_edge(a, b, (7, false), Orientation::Default);
359        builder.add_edge(b, c, (11, false), Orientation::Default);
360        builder.add_external_edge(a, (13, false), Orientation::Default, Flow::Sink);
361        builder.add_external_edge(c, (17, true), Orientation::Default, Flow::Source);
362        builder.build()
363    }
364
365    fn numerator(
366        graph: &HedgeGraph<(i32, bool), i32>,
367        selected: &SuBitGraph,
368        without: &SuBitGraph,
369    ) -> Atom {
370        graph.numerator_of(
371            selected,
372            without,
373            |_, n| Atom::num(*n),
374            |e| Atom::num(e.0),
375            |e| e.1,
376        )
377    }
378
379    #[test]
380    fn numerator_preserves_paired_boundary_and_exclusion_rules() {
381        let graph = graph();
382        let empty = graph.empty_subgraph();
383        let full = graph.full_filter();
384        assert_eq!(
385            numerator(&graph, &full, &empty),
386            Atom::num(2 * 3 * 5 * 7 * 11)
387        );
388        assert_eq!(numerator(&graph, &empty, &empty), Atom::one());
389        assert_eq!(numerator(&graph, &full, &full), Atom::one());
390
391        let mut first: SuBitGraph = graph.empty_subgraph();
392        first.add(graph[&EdgeIndex(0)].1);
393        assert_eq!(numerator(&graph, &first, &empty), Atom::num(2 * 3 * 7));
394        assert_eq!(numerator(&graph, &full, &first), Atom::num(5 * 11));
395
396        // Both selected boundary half-edges together cover the middle vertex.
397        let mut middle: SuBitGraph = graph.empty_subgraph();
398        middle.add(Hedge(1));
399        middle.add(Hedge(2));
400        assert_eq!(numerator(&graph, &middle, &empty), Atom::num(3));
401
402        // A missing dummy does not prevent the remaining crown from contributing.
403        let mut last: SuBitGraph = graph.empty_subgraph();
404        last.add(Hedge(3));
405        assert_eq!(numerator(&graph, &last, &empty), Atom::num(5));
406    }
407
408    #[test]
409    fn indexed_vertex_callback_selects_isolated_factors_without_division() {
410        let mut builder = HedgeGraphBuilder::new();
411        let left = builder.add_node(2);
412        let right = builder.add_node(3);
413        let isolated = builder.add_node(5);
414        let zero = builder.add_node(0);
415        builder.add_edge(left, right, (7, false), Orientation::Default);
416        let graph: HedgeGraph<(i32, bool), i32> = builder.build();
417        let empty: SuBitGraph = graph.empty_subgraph();
418        let evaluate = |selected: &SuBitGraph, isolated_nodes: &[NodeIndex]| {
419            graph.numerator_of(
420                selected,
421                &empty,
422                |id, numerator| {
423                    if graph.iter_crown(id).next().is_some() || isolated_nodes.contains(&id) {
424                        Atom::num(*numerator)
425                    } else {
426                        Atom::one()
427                    }
428                },
429                |edge| Atom::num(edge.0),
430                |edge| edge.1,
431            )
432        };
433        assert_eq!(evaluate(&graph.full_filter(), &[]), Atom::num(2 * 3 * 7));
434        assert_eq!(
435            evaluate(&graph.full_filter(), &[isolated]),
436            Atom::num(2 * 3 * 5 * 7)
437        );
438        assert_eq!(evaluate(&empty, &[isolated]), Atom::num(5));
439        assert_eq!(evaluate(&empty, &[isolated, zero]), Atom::Zero);
440        assert_eq!(evaluate(&empty, &[]), Atom::one());
441    }
442
443    #[test]
444    fn denominator_preserves_signed_powers_and_ignores_boundaries() {
445        let graph = graph();
446        let factor = |_: EdgeIndex, edge: &(i32, bool)| Ok::<_, ()>(Atom::num(edge.0));
447        let denominator = graph
448            .denominator_of(&graph.full_filter(), factor, |edge, _| {
449                if edge == EdgeIndex(0) { -2 } else { 3 }
450            })
451            .unwrap();
452        assert_eq!(denominator, Atom::num(11).pow(3) / Atom::num(7).pow(2));
453        let mut split: SuBitGraph = graph.empty_subgraph();
454        split.add(Hedge(0));
455        assert_eq!(
456            graph.denominator_of(&split, factor, |_, _| 1).unwrap(),
457            Atom::one()
458        );
459        assert_eq!(
460            graph.denominator_of(&graph.full_filter(), |_, _| Err::<Atom, _>(()), |_, _| 0),
461            Ok(Atom::one())
462        );
463    }
464}