Skip to main content

feynkit_cff/
symbols.rs

1//! Canonical GammaLoop energy symbols, also used by standalone FeynKit.
2
3use spenso::network::tags::mathml;
4use std::sync::LazyLock;
5
6use spenso::shadowing::symbolica_utils::{SpensoPrintBackend, SpensoPrintSettings};
7use spenso::structure::abstract_index::AIND_SYMBOLS;
8use spenso::symbolica_init::SymbolicaInitLazy;
9use spenso::utils;
10use symbolica::atom::{Atom, AtomCore, AtomView, Symbol};
11use symbolica::printer::{PrintOptions, PrintState};
12use symbolica::{function, symbol};
13use symbolica_notation::Notation;
14
15use crate::EdgeId;
16
17// The symbol owns its notation in native text, tensor MathML and graph Typst.
18// Canonical/plain serialization deliberately keeps the original function name.
19fn print_energy(
20    atom: AtomView<'_>,
21    options: &PrintOptions,
22    state: &PrintState,
23    on_shell: bool,
24) -> Option<String> {
25    if options.mode.is_mathml() {
26        let AtomView::Fun(function) = atom else {
27            return None;
28        };
29        if function.get_nargs() != 1 {
30            return None;
31        }
32        let index = function.iter().next()?;
33        if index.get_byte_size() > 1024 {
34            return None;
35        }
36        let id = mathml::expression(index, options, &PrintState::new(), &|_, _| None).ok()?;
37        let value = if on_shell {
38            format!("<msubsup><mi>E</mi><mrow>{id}</mrow><mtext>os</mtext></msubsup>")
39        } else {
40            format!("<msub><mi>E</mi><mrow>{id}</mrow></msub>")
41        };
42        return mathml::fragment(if on_shell && state.in_exp_base {
43            format!("<mrow><mo>(</mo>{value}<mo>)</mo></mrow>")
44        } else {
45            value
46        });
47    }
48    let backend = if options.mode.is_latex() {
49        SpensoPrintBackend::Latex
50    } else {
51        SpensoPrintSettings::resolve(options)?.backend
52    };
53    let AtomView::Fun(function) = atom else {
54        return None;
55    };
56    if function.get_nargs() != 1 {
57        return None;
58    }
59    let index = function.iter().next()?;
60    let id = index.printer(options.clone()).to_string();
61    Some(match backend {
62        SpensoPrintBackend::Typst => {
63            let head = if on_shell { "E^(\"os\")" } else { "E" };
64            let value = format!("{head}_({id})");
65            if on_shell && state.in_exp_base {
66                format!("lr(({value}))")
67            } else {
68                value
69            }
70        }
71        SpensoPrintBackend::Latex => {
72            let head = if on_shell { r"E^{\mathrm{os}}" } else { "E" };
73            let value = format!("{head}_{{{id}}}");
74            if on_shell && state.in_exp_base {
75                format!(r"\left({value}\right)")
76            } else {
77                value
78            }
79        }
80        SpensoPrintBackend::Plain => {
81            let head = if on_shell { "Eᵒˢ" } else { "E" };
82            let index = usize::try_from(index).ok()?;
83            format!("{head}{}", utils::to_subscript(index as isize))
84        }
85    })
86}
87
88static ON_SHELL: LazyLock<Symbol> = LazyLock::new(|| {
89    let symbol = symbol!(
90        "gammalooprs::OSE"; Scalar;
91        print = |a, opt, state| print_energy(a, opt, state, true),
92        der = |_, arg, out| {
93            if arg == 1 { **out = Atom::num(1); }
94        }
95    );
96    Notation {
97        custom_print: true,
98        ..Notation::default()
99    }
100    .register(symbol)
101    .expect("the canonical energy symbol has one notation");
102    symbol
103});
104static ENERGY: LazyLock<Symbol> = LazyLock::new(|| {
105    let symbol = symbol!(
106        "gammalooprs::E",
107        print = |a, opt, state| print_energy(a, opt, state, false)
108    );
109    Notation {
110        custom_print: true,
111        ..Notation::default()
112    }
113    .register(symbol)
114    .expect("the canonical energy symbol has one notation");
115    symbol
116});
117
118pub fn on_shell() -> Symbol {
119    *SymbolicaInitLazy::new(&ON_SHELL)
120}
121pub fn energy() -> Symbol {
122    *SymbolicaInitLazy::new(&ENERGY)
123}
124pub fn on_shell_atom(edge: EdgeId) -> Atom {
125    function!(on_shell(), edge.index() as i64)
126}
127pub fn energy_atom(edge: EdgeId) -> Atom {
128    function!(energy(), edge.index() as i64)
129}
130pub fn external_energy_atom(edge: EdgeId) -> Atom {
131    function!(
132        feynkit_graph::momentum_symbol(),
133        edge.index() as i64,
134        function!(AIND_SYMBOLS.cind, 0)
135    )
136}
137
138// Register attributes before an expression parser can create bare energy heads.
139symbolica::initialize!(|| spenso::symbolica_init::in_symbolica_initializer(|| {
140    on_shell();
141    energy();
142}));
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147
148    #[test]
149    fn energy_notation_preserves_identity_and_handles_powers() {
150        let energy = on_shell_atom(EdgeId(3));
151        let canonical = energy.to_canonical_string();
152        assert_eq!(energy, symbolica::parse!("gammalooprs::OSE(3)"));
153        assert!(canonical.ends_with("::OSE(3)"));
154        assert!(Notation::has_custom_print(on_shell()).unwrap());
155        assert_eq!(
156            energy.printer(PrintOptions::typst()).to_string(),
157            "E^(\"os\")_(3)"
158        );
159        assert_eq!(
160            energy.printer(PrintOptions::latex()).to_string(),
161            r"E^{\mathrm{os}}_{3}"
162        );
163        let squared = energy
164            .clone()
165            .pow(2)
166            .printer(PrintOptions::typst())
167            .to_string();
168        assert!(squared.contains("lr((E^(\"os\")_(3)))"), "{squared}");
169        assert_eq!(energy.to_canonical_string(), canonical);
170        // Unsupported arities keep their ordinary spelling instead of panicking
171        // or silently discarding an argument.
172        for malformed in [on_shell().call(()), on_shell().call((3, 4))] {
173            assert!(
174                malformed
175                    .printer(PrintOptions::typst())
176                    .to_string()
177                    .contains("OSE")
178            );
179        }
180    }
181}