Skip to main content

feynkit_graph/
symbols.rs

1//! Canonical graph symbols shared with GammaLoop.
2//!
3//! Polarization heads and graph-owned index labels retain their meaning in MathML:
4//! ```
5//! use feynkit_graph::symbols;
6//! use spenso::structure::representation::{Minkowski, RepName};
7//! use symbolica::atom::AtomCore;
8//! use symbolica::printer::{PrintMode, PrintOptions};
9//! let index = symbols::hedge_index().call((3, 1));
10//! let slot = Minkowski {}.new_rep(4).to_symbolic([index]);
11//! for head in [symbols::epsilon(), symbols::epsilonbar()] {
12//!     let expression = head.call((7, slot.clone()));
13//!     let html = expression.printer(PrintOptions {
14//!         mode: PrintMode::MathML, ..PrintOptions::default()
15//!     }).to_string();
16//!     assert!(html.contains("<mmultiscripts>"));
17//! }
18//! ```
19mod input;
20
21pub use input::{ExpressionParseError, parse_expression, parse_expression_in_scope};
22
23use spenso::network::tags;
24use spenso::network::tags::{COMPONENT_LABELS_SUBSCRIPT_TAG, SPENSO_TAG};
25use spenso::shadowing::symbolica_utils::SpensoPrintSettings;
26use spenso::spenso_print_scripted_indexed;
27use spenso::structure::abstract_index::AIND_SYMBOLS;
28use symbolica_notation::{DisplayText, IndexDisplay, Notation, TextOverrides};
29
30use spenso::symbolica_init::SymbolicaInitLazy;
31use spenso::utils;
32use std::sync::LazyLock;
33use symbolica::atom::{Atom, AtomView, Symbol};
34use symbolica::printer::PrintUserData;
35use symbolica::symbol;
36
37pub fn momentum() -> Symbol {
38    static SYMBOL: LazyLock<Symbol> = LazyLock::new(|| {
39        let symbol = symbol!(
40            "gammalooprs::Q",
41            print = tags::tensor_print,
42            tags = [
43                SPENSO_TAG.rank1.clone(),
44                SPENSO_TAG.tensor.clone(),
45                COMPONENT_LABELS_SUBSCRIPT_TAG.to_owned()
46            ]
47        );
48        Notation {
49            head: Some(IndexDisplay::symbol("q").expect("the canonical label is valid")),
50            ..Notation::default()
51        }
52        .register(symbol)
53        .expect("the canonical graph symbol has one notation");
54        symbol
55    });
56    *SymbolicaInitLazy::new(&SYMBOL)
57}
58
59/// Spatial part `Q3(e, mink(4, mu)) = (0, q_e)` of the edge momentum `Q(e, mink(4, mu))`.
60///
61/// Both are momentum carriers: generated-diagram finalization transports and,
62/// on a reversed edge, negates `Q3` together with `Q`. A concrete component
63/// normalizes to the edge momentum's spatial component `Q(e, cind(i))` for
64/// `i = 1, 2, 3`, and to zero for `i = 0`, so components have one representation.
65///
66/// # Examples
67///
68/// ```
69/// use feynkit_graph::symbols;
70/// use spenso::structure::abstract_index::AIND_SYMBOLS;
71/// use symbolica::atom::AtomCore;
72///
73/// let time = symbols::spatial_momentum().call((0, AIND_SYMBOLS.cind.call(0)));
74/// assert!(time.is_zero());
75/// ```
76pub fn spatial_momentum() -> Symbol {
77    static SYMBOL: LazyLock<Symbol> = LazyLock::new(|| {
78        symbol!(
79            "gammalooprs::Q3",
80            norm = |f, out| {
81                if let AtomView::Fun(ff) = f
82                    && ff.get_nargs() == 2
83                {
84                    let mut iter = ff.iter();
85                    let eid = iter.next().unwrap();
86                    let structure = iter.next().unwrap();
87                    let component = if let AtomView::Fun(cind) = structure
88                        && cind.get_symbol() == AIND_SYMBOLS.cind
89                        && cind.get_nargs() == 1
90                    {
91                        cind.iter()
92                            .next()
93                            .and_then(|i| i64::try_from(i).ok())
94                            .and_then(|i| usize::try_from(i).ok())
95                    } else {
96                        None
97                    };
98                    if i64::try_from(eid).is_ok_and(|eid| eid >= 0)
99                        && let Some(i @ 0..=3) = component
100                    {
101                        if i == 0 {
102                            **out = Atom::Zero;
103                        } else {
104                            let cind = AIND_SYMBOLS.cind.call_args([i as i64]);
105                            **out = momentum().call_args([eid, cind.as_view()])
106                        }
107                    }
108                }
109            },
110            print = |a, opt, _state| { spenso_print_scripted_indexed!(a, opt, "q⃗", "arrow(q)") },
111            tags = [SPENSO_TAG.rank1.clone(), SPENSO_TAG.tensor.clone()]
112        )
113    });
114    *SymbolicaInitLazy::new(&SYMBOL)
115}
116
117pub fn edge_index() -> Symbol {
118    static SYMBOL: LazyLock<Symbol> = LazyLock::new(|| {
119        let symbol = symbol!(
120            "gammalooprs::edge",
121            print = tags::tensor_print,
122            tags = [SPENSO_TAG.index.clone()]
123        );
124        Notation {
125            index_label: Some(IndexDisplay::symbol("e").expect("the canonical label is valid")),
126            ..Notation::default()
127        }
128        .register(symbol)
129        .expect("the canonical graph symbol has one notation");
130        symbol
131    });
132    *SymbolicaInitLazy::new(&SYMBOL)
133}
134
135pub fn vertex_index() -> Symbol {
136    static SYMBOL: LazyLock<Symbol> = LazyLock::new(|| {
137        let symbol = symbol!(
138            "gammalooprs::vertex",
139            print = tags::tensor_print,
140            tags = [SPENSO_TAG.index.clone()]
141        );
142        Notation {
143            index_label: Some(IndexDisplay::symbol("v").expect("the canonical label is valid")),
144            ..Notation::default()
145        }
146        .register(symbol)
147        .expect("the canonical graph symbol has one notation");
148        symbol
149    });
150    *SymbolicaInitLazy::new(&SYMBOL)
151}
152
153/// Half-edge-owned abstract indices `hedge(owner, local_index)`, or `hedge(owner)`
154/// for local zero.
155/// See the polarization example in [`crate::symbols`].
156pub fn hedge_index() -> Symbol {
157    static SYMBOL: LazyLock<Symbol> = LazyLock::new(|| {
158        let symbol = symbol!(
159            "gammalooprs::hedge",
160            print = |a, opt, state| {
161                if opt.mode.is_mathml() {
162                    return tags::tensor_print(a, opt, state);
163                }
164                match opt.custom_print_mode.get("spenso") {
165                    Some(PrintUserData::Integer(i)) => {
166                        let AtomView::Fun(f) = a else {
167                            return None;
168                        };
169                        let SpensoPrintSettings {
170                            index_subscripts, ..
171                        } = SpensoPrintSettings::from(*i as usize);
172
173                        let mut out = "".to_string();
174                        let mut first = true;
175                        for arg in f.iter() {
176                            let Ok(i) = isize::try_from(arg) else {
177                                return None;
178                            };
179
180                            if !first {
181                                out.push('.');
182                            }
183                            first = false;
184                            if index_subscripts {
185                                out.push_str(&utils::to_superscript(i));
186                            } else {
187                                out.push_str(&utils::to_subscript(i));
188                            }
189                        }
190                        Some(out)
191                    }
192                    _ => None,
193                }
194            },
195            tags = [SPENSO_TAG.index.clone()]
196        );
197        Notation {
198            index_label: Some(IndexDisplay::symbol("h").expect("the canonical label is valid")),
199            ..Notation::default()
200        }
201        .register(symbol)
202        .expect("the canonical graph symbol has one notation");
203        symbol
204    });
205    *SymbolicaInitLazy::new(&SYMBOL)
206}
207
208pub fn denominator() -> Symbol {
209    static SYMBOL: LazyLock<Symbol> = LazyLock::new(|| {
210        symbol!(
211            "gammalooprs::denom"; Scalar;
212            der = |_, arg, out| {
213                if arg != 3 {
214                    **out = Atom::Zero;
215                } else {
216                    **out = Atom::num(1);
217                }
218            }
219        )
220    });
221    *SymbolicaInitLazy::new(&SYMBOL)
222}
223
224pub fn dimension() -> Symbol {
225    static SYMBOL: LazyLock<Symbol> = LazyLock::new(|| symbol!("gammalooprs::dim"));
226    *SymbolicaInitLazy::new(&SYMBOL)
227}
228
229pub fn loop_momentum() -> Symbol {
230    static SYMBOL: LazyLock<Symbol> = LazyLock::new(|| {
231        let symbol = symbol!(
232            "gammalooprs::K",
233            print = tags::tensor_print,
234            tags = [
235                SPENSO_TAG.rank1.clone(),
236                SPENSO_TAG.tensor.clone(),
237                COMPONENT_LABELS_SUBSCRIPT_TAG.to_owned()
238            ]
239        );
240        Notation {
241            head: Some(IndexDisplay::symbol("k").expect("the canonical label is valid")),
242            ..Notation::default()
243        }
244        .register(symbol)
245        .expect("the canonical graph symbol has one notation");
246        symbol
247    });
248    *SymbolicaInitLazy::new(&SYMBOL)
249}
250
251pub fn external_momentum() -> Symbol {
252    static SYMBOL: LazyLock<Symbol> = LazyLock::new(|| {
253        let symbol = symbol!(
254            "gammalooprs::P",
255            print = tags::tensor_print,
256            tags = [
257                SPENSO_TAG.rank1.clone(),
258                SPENSO_TAG.tensor.clone(),
259                COMPONENT_LABELS_SUBSCRIPT_TAG.to_owned()
260            ]
261        );
262        Notation {
263            head: Some(IndexDisplay::symbol("p").expect("the canonical label is valid")),
264            ..Notation::default()
265        }
266        .register(symbol)
267        .expect("the canonical graph symbol has one notation");
268        symbol
269    });
270    *SymbolicaInitLazy::new(&SYMBOL)
271}
272
273pub fn u() -> Symbol {
274    static SYMBOL: LazyLock<Symbol> = LazyLock::new(|| {
275        symbol!(
276            "gammalooprs::u",
277            print = |a, opt, _state| { spenso_print_scripted_indexed!(a, opt, "u") },
278            tags = [SPENSO_TAG.rank1.clone(), SPENSO_TAG.tensor.clone()]
279        )
280    });
281    *SymbolicaInitLazy::new(&SYMBOL)
282}
283
284pub fn ubar() -> Symbol {
285    static SYMBOL: LazyLock<Symbol> = LazyLock::new(|| {
286        symbol!(
287            "gammalooprs::ubar",
288            print =
289                |a, opt, _state| { spenso_print_scripted_indexed!(a, opt, "u̅", "overline(u)") },
290            tags = [SPENSO_TAG.rank1.clone(), SPENSO_TAG.tensor.clone()]
291        )
292    });
293    *SymbolicaInitLazy::new(&SYMBOL)
294}
295
296pub fn v() -> Symbol {
297    static SYMBOL: LazyLock<Symbol> = LazyLock::new(|| {
298        symbol!(
299            "gammalooprs::v",
300            print = |a, opt, _state| { spenso_print_scripted_indexed!(a, opt, "v") },
301            tags = [SPENSO_TAG.rank1.clone(), SPENSO_TAG.tensor.clone()]
302        )
303    });
304    *SymbolicaInitLazy::new(&SYMBOL)
305}
306
307pub fn vbar() -> Symbol {
308    static SYMBOL: LazyLock<Symbol> = LazyLock::new(|| {
309        symbol!(
310            "gammalooprs::vbar",
311            print =
312                |a, opt, _state| { spenso_print_scripted_indexed!(a, opt, "v̅", "overline(v)") },
313            tags = [SPENSO_TAG.rank1.clone(), SPENSO_TAG.tensor.clone()]
314        )
315    });
316    *SymbolicaInitLazy::new(&SYMBOL)
317}
318
319/// Rank-one polarization tensor with a physical momentum ID and Lorentz slot.
320/// See the MathML example in [`crate::symbols`].
321pub fn epsilon() -> Symbol {
322    static SYMBOL: LazyLock<Symbol> = LazyLock::new(|| {
323        symbol!(
324            "gammalooprs::ϵ",
325            print = |a, opt, state| {
326                if opt.mode.is_mathml() {
327                    return tags::tensor_print(a, opt, state);
328                }
329                spenso_print_scripted_indexed!(a, opt, "ϵ")
330            },
331            tags = [SPENSO_TAG.rank1.clone(), SPENSO_TAG.tensor.clone()]
332        )
333    });
334    *SymbolicaInitLazy::new(&SYMBOL)
335}
336
337/// Conjugate polarization tensor; the bar is presentation metadata on its head.
338/// Source serialization retains the canonical symbol. See [`crate::symbols`].
339pub fn epsilonbar() -> Symbol {
340    static SYMBOL: LazyLock<Symbol> = LazyLock::new(|| {
341        let symbol = symbol!(
342            "gammalooprs::ϵbar",
343            print = |a, opt, state| {
344                if opt.mode.is_mathml() {
345                    return tags::tensor_print(a, opt, state);
346                }
347                spenso_print_scripted_indexed!(
348                    a,
349                    opt,
350                    if opt.mode.is_latex() {
351                        r"\bar{\epsilon}"
352                    } else {
353                        "ϵ̅"
354                    },
355                    "overline(epsilon.alt)"
356                )
357            },
358            tags = [SPENSO_TAG.rank1.clone(), SPENSO_TAG.tensor.clone()]
359        );
360        Notation {
361            head: Some(
362                IndexDisplay::math(
363                    "overline",
364                    vec![IndexDisplay::symbol("ϵ").expect("epsilon is a valid symbol label")],
365                )
366                .expect("overline takes one argument"),
367            ),
368            text: TextOverrides {
369                plain: Some(DisplayText::new("ϵ̅").expect("epsilon bar is valid display text")),
370                latex: Some(
371                    DisplayText::new(r"\bar{\epsilon}").expect("epsilon bar is valid display text"),
372                ),
373                typst: Some(
374                    DisplayText::new("overline(epsilon.alt)")
375                        .expect("epsilon bar is valid display text"),
376                ),
377            },
378            ..Notation::default()
379        }
380        .register(symbol)
381        .expect("the canonical polarization symbol has one notation");
382        symbol
383    });
384    *SymbolicaInitLazy::new(&SYMBOL)
385}
386
387#[cfg(test)]
388mod tests {
389    use super::*;
390    use spenso::network::tags::mathml;
391    use spenso::structure::abstract_index::AIND_SYMBOLS;
392    use symbolica::atom::AtomCore;
393    use symbolica::parse;
394    use symbolica::printer::{PrintMode, PrintOptions, PrintState};
395
396    #[test]
397    fn epsilonbar_canonical_roundtrip_preserves_bar_and_open_axis() {
398        // Exercise the ordinary global initializer rather than registering a
399        // test-only replacement for the production symbol.
400        let original = parse!("gammalooprs::ϵbar(7,spenso::mink(4))");
401        assert_eq!(original.as_view().get_symbol(), Some(epsilonbar()));
402        let bytes = original.as_view().get_data().to_vec();
403        let source = original.to_canonical_string();
404        let reparsed = Atom::parse(&source, "gammalooprs", Default::default()).unwrap();
405        assert_eq!(reparsed, original);
406        assert_eq!(reparsed.to_canonical_string(), source);
407        assert!(epsilonbar().has_tag(&SPENSO_TAG.rank1));
408        assert!(epsilonbar().has_tag(&SPENSO_TAG.tensor));
409
410        let options = PrintOptions {
411            mode: PrintMode::MathML,
412            hide_all_namespaces: true,
413            ..PrintOptions::new()
414        };
415        let native = reparsed.printer(options.clone()).to_string();
416        let html = mathml::render(reparsed.as_view(), &options, &PrintState::new(), &|_, _| {
417            None
418        })
419        .unwrap();
420        let exported =
421            mathml::expression(reparsed.as_view(), &options, &PrintState::new(), &|_, _| {
422                None
423            })
424            .unwrap();
425        for rendered in [&native, &html, &exported] {
426            assert!(
427                rendered.contains("<mover accent=\"true\"><mi>ϵ</mi><mo>¯</mo></mover>"),
428                "{rendered}"
429            );
430            assert!(rendered.contains("<mmultiscripts>"), "{rendered}");
431            assert!(!rendered.contains("ϵbar"), "{rendered}");
432        }
433        for rendered in [&html, &exported] {
434            assert!(
435                rendered.contains("data-spenso-open-axis=\"0\""),
436                "{rendered}"
437            );
438            assert!(rendered.contains("Unresolved axis 0"), "{rendered}");
439        }
440        assert!(
441            tags::prepare_tensor_print(&reparsed)
442                .printer(PrintOptions::typst())
443                .to_string()
444                .contains("overline(epsilon.alt)")
445        );
446        let latex = PrintOptions {
447            custom_print_mode: SpensoPrintSettings::typst().into(),
448            ..PrintOptions::latex()
449        };
450        assert!(
451            reparsed
452                .printer(latex.clone())
453                .to_string()
454                .contains(r"\bar{\epsilon}")
455        );
456        assert!(
457            tags::prepare_tensor_print(&reparsed)
458                .printer(latex)
459                .to_string()
460                .contains(r"\bar{\epsilon}")
461        );
462        assert_eq!(original.as_view().get_data(), bytes);
463        assert_eq!(reparsed.as_view().get_data(), bytes);
464        assert_eq!(reparsed.to_canonical_string(), source);
465    }
466
467    #[test]
468    fn momentum_components_keep_object_indices() {
469        for (head, label) in [
470            (momentum(), "q"),
471            (loop_momentum(), "k"),
472            (external_momentum(), "p"),
473        ] {
474            assert_eq!(
475                head.call(27).printer(PrintOptions::typst()).to_string(),
476                format!("{label}_27")
477            );
478            let component = head.call_args([Atom::num(27), AIND_SYMBOLS.cind.call(0)]);
479            assert_eq!(
480                component.printer(PrintOptions::typst()).to_string(),
481                format!("attach(attach({label},b:(27)),t:0)")
482            );
483            let plain = PrintOptions {
484                custom_print_mode: SpensoPrintSettings::typst().into(),
485                ..Default::default()
486            };
487            assert_eq!(
488                component.printer(plain).to_string(),
489                format!("{label}₂₇^(0)")
490            );
491            let latex = PrintOptions {
492                custom_print_mode: SpensoPrintSettings::typst().into(),
493                ..PrintOptions::latex()
494            };
495            assert_eq!(
496                component.printer(latex).to_string(),
497                format!("{label}_{{27}}^{{0}}")
498            );
499            assert!(
500                component
501                    .pow(2)
502                    .printer(PrintOptions::typst())
503                    .to_string()
504                    .contains("lr((attach(")
505            );
506        }
507    }
508}