Skip to main content

gammalooprs/numerator/
mod.rs

1#![allow(dead_code)]
2
3use aind::Aind;
4use idenso::tensor::{AlgebraContraction, AlgebraSettings, ContractSettings, SymbolicTensor};
5use idenso::{
6    CookMode, CookSettings, coad, cof, color::ColorSimplifySettings, color_cas, color_idx,
7    dirac::GammaSimplifySettings,
8};
9use linnet::half_edge::involution::EdgeIndex;
10use schemars::JsonSchema;
11use tracing::warn;
12
13use spenso::network::library::DummyLibrary;
14use spenso::network::parsing::{ParseSettings, ShadowedStructure};
15use spenso::network::store::NetworkStore;
16use spenso::network::{ContractScalars, MinResultRank, Sequential, SingleSmallestDegree, Steps};
17use symbolica_utils::SerializableSymbol;
18
19use spenso::tensors::data::DataTensor;
20use spenso::tensors::data::GetTensorData;
21use spenso::tensors::data::StorageTensor;
22use spenso::tensors::parametric::atomcore::TensorAtomMaps;
23
24use spenso::tensors::parametric::ParamTensor;
25use spenso::tensors::parametric::TensorSet;
26use std::fmt::Debug;
27use std::ops::Deref;
28use std::sync::{Arc, Mutex};
29use thiserror::Error;
30use tracing::{debug, instrument};
31// use crate::feyngen::dis::{DisEdge, DisVertex};
32
33use crate::graph::parse::string_utils::ToOrderedSimple;
34use crate::momentum::{PolDef, PolType};
35use crate::utils::{FUN_LIB, GS, TENSORLIB, W_};
36use crate::{model::Model, utils::serde_utils::IsDefault};
37
38use crate::{GammaLoopContextContainer, disable};
39use bincode::{Decode, Encode};
40use color_eyre::{Report, Result};
41use eyre::eyre;
42// use gxhash::GxBuildHasher;
43
44use serde::de::DeserializeOwned;
45use serde::ser::SerializeStruct;
46use serde::{Deserialize, Serialize};
47
48use spenso::contraction::Contract;
49
50use spenso::network::library::symbolic::{ETS, ExplicitKey};
51
52use spenso::structure::IndexedStructure;
53use spenso::structure::concrete_index::{ExpandedIndex, FlatIndex};
54use spenso::structure::dimension::Dimension;
55
56use spenso::structure::{CanonicalLayout, HasStructure, ScalarTensor, SmartShadowStructure};
57
58use spenso::{
59    shadowing::Shadowable,
60    structure::{
61        NamedStructure, TensorStructure,
62        representation::{Lorentz, RepName},
63    },
64};
65
66use symbolica::state::Workspace;
67
68use crate::numerator::ufo::UFO;
69use symbolica::prelude::*;
70
71pub mod symbolica_ext;
72
73#[cfg(test)]
74pub(crate) mod exact_soft_jet;
75#[cfg(test)]
76pub(crate) mod pole_certificate;
77#[cfg(test)]
78pub(crate) mod soft_energy_certificate;
79
80#[cfg(test)]
81mod spensotests;
82
83pub mod aind;
84pub mod energy_degree;
85pub mod ufo;
86#[derive(Debug, Clone, Serialize, Deserialize, Encode, Decode, PartialEq)]
87/// Settings for the numerator
88pub struct NumeratorSettings {
89    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
90    pub eval_settings: NumeratorEvaluatorOptions,
91    /// Parse mode for the numerator, once all processing is done. `Polynomial` turns it into a polynomial in the energies, while `Direct` keeps it as is
92    pub parse_mode: NumeratorParseMode,
93    /// If set, dump the expression the expression at each step in this format
94    pub dump_expression: Option<ExpressionFormat>,
95    /// If set, instead of deriving the numerator from feynman rules, use this as the numerator
96    /// Will be parsed to a symbolica expression
97    // pub global_numerator: Option<String>,
98    /// If set, multiply the numerator by this prefactor
99    // pub global_prefactor: GlobalPrefactor,
100    /// Type of Gamma algebra to use, either symbolic (replacement rules) or concrete (replace by value using spenso)
101    pub gamma_algebra: GammaAlgebraMode,
102}
103
104#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, Encode, Decode, PartialEq)]
105pub enum ExpressionFormat {
106    Mathematica,
107    #[default]
108    Symbolica,
109}
110
111impl From<ExpressionFormat> for PrintOptions {
112    fn from(value: ExpressionFormat) -> Self {
113        match value {
114            ExpressionFormat::Symbolica => PrintOptions::file(),
115            ExpressionFormat::Mathematica => PrintOptions::mathematica(),
116        }
117    }
118}
119
120impl Default for NumeratorSettings {
121    fn default() -> Self {
122        NumeratorSettings {
123            eval_settings: Default::default(),
124            // global_numerator: None,
125            // global_prefactor: GlobalPrefactor::default(),
126            dump_expression: None,
127            gamma_algebra: GammaAlgebraMode::Symbolic,
128            parse_mode: NumeratorParseMode::Polynomial,
129        }
130    }
131}
132
133#[derive(Debug, Clone, Serialize, Deserialize, Encode, Decode, PartialEq)]
134pub enum GammaAlgebraMode {
135    Symbolic,
136    Concrete,
137}
138
139pub type AtomStructure = SmartShadowStructure<SerializableSymbol, Vec<Atom>>;
140
141pub struct RepeatingIterator<T> {
142    elements: Vec<T>,
143    positions: std::vec::IntoIter<usize>,
144}
145
146pub enum RepeatingIteratorTensorOrScalar<T: HasStructure> {
147    Tensors(RepeatingIterator<T>),
148    Scalars(RepeatingIterator<T::Scalar>),
149}
150
151impl<T> RepeatingIterator<T> {
152    pub(crate) fn new(positions: Vec<usize>, elements: Vec<T>) -> Self {
153        RepeatingIterator {
154            elements,
155            positions: positions.into_iter(),
156        }
157    }
158
159    pub(crate) fn new_not_repeating(elements: Vec<T>) -> Self {
160        let positions: Vec<usize> = (0..elements.len()).collect();
161        RepeatingIterator {
162            elements,
163            positions: positions.into_iter(),
164        }
165    }
166}
167
168// #[test]
169// fn rep_iter(){
170//     let mut r= RepeatingIterator::new_not_repeating(vec![1,2,3,4,5]);
171//     while let Some(s) =r.next()  {
172//         println!("{}",s);
173//     }
174// }
175
176impl<T: HasStructure> From<(TensorSet<T>, Vec<usize>)> for RepeatingIteratorTensorOrScalar<T> {
177    fn from(value: (TensorSet<T>, Vec<usize>)) -> Self {
178        match value.0 {
179            TensorSet::Tensors(t) => {
180                RepeatingIteratorTensorOrScalar::Tensors(RepeatingIterator::new(value.1, t))
181            }
182            TensorSet::Scalars(s) => {
183                RepeatingIteratorTensorOrScalar::Scalars(RepeatingIterator::new(value.1, s))
184            }
185        }
186    }
187}
188
189impl<T: HasStructure> From<TensorSet<T>> for RepeatingIteratorTensorOrScalar<T> {
190    fn from(value: TensorSet<T>) -> Self {
191        match value {
192            TensorSet::Tensors(t) => {
193                RepeatingIteratorTensorOrScalar::Tensors(RepeatingIterator::new_not_repeating(t))
194            }
195            TensorSet::Scalars(s) => {
196                RepeatingIteratorTensorOrScalar::Scalars(RepeatingIterator::new_not_repeating(s))
197            }
198        }
199    }
200}
201
202#[derive(Debug, Clone, Serialize, Deserialize, Encode, Decode)]
203pub struct Numerator<State> {
204    pub state: State,
205}
206
207impl<S: NumeratorState> Numerator<S> {
208    pub(crate) fn export(&self) -> String {
209        self.state.export()
210    }
211
212    pub(crate) fn forget_type(self) -> Numerator<PythonState> {
213        Numerator {
214            state: self.state.forget_type(),
215        }
216    }
217
218    pub(crate) fn update_model(&mut self, model: &Model) -> Result<()> {
219        self.state.update_model(model)
220    }
221
222    fn add_consts_to_fn_map(fn_map: &mut FunctionMap) {
223        fn_map
224            .add_aliases([(parse!("Nc"), Atom::num(Rational::from(3)))])
225            .unwrap();
226
227        fn_map
228            .add_aliases([
229                (color_idx!(2, cof!(3)), Atom::num(Rational::from((1, 2)))),
230                (color_cas!(2, cof!(3)), Atom::num(Rational::from((4, 3)))),
231                (color_cas!(2, coad!(8)), Atom::num(3)),
232            ])
233            .unwrap();
234    }
235}
236
237impl<S: GetSingleAtom> Numerator<S> {
238    pub(crate) fn get_single_atom(&self) -> Result<Atom, NumeratorStateError> {
239        self.state.get_single_atom()
240    }
241}
242
243pub trait TypedNumeratorState:
244    NumeratorState + TryFrom<PythonState, Error: std::error::Error + Send + Sync + 'static>
245{
246    fn apply<F, S: TypedNumeratorState>(
247        state: &mut Numerator<PythonState>,
248        f: F,
249    ) -> Result<(), NumeratorStateError>
250    where
251        F: FnMut(Numerator<Self>) -> Numerator<S>;
252}
253
254impl Numerator<PythonState> {
255    pub(crate) fn try_from<S: TypedNumeratorState>(self) -> Result<Numerator<S>, Report> {
256        Ok(Numerator {
257            state: self.state.try_into()?,
258        })
259    }
260
261    pub(crate) fn apply<F, S: TypedNumeratorState, T: TypedNumeratorState>(
262        &mut self,
263        f: F,
264    ) -> Result<(), NumeratorStateError>
265    where
266        F: FnMut(Numerator<S>) -> Numerator<T>,
267    {
268        S::apply(self, f)
269    }
270}
271pub trait NumeratorState:
272    Clone + Debug + Encode + for<'a> Decode<GammaLoopContextContainer<'a>>
273{
274    fn export(&self) -> String;
275
276    fn forget_type(self) -> PythonState;
277
278    fn update_model(&mut self, model: &Model) -> Result<()>;
279    // fn try_from(state: PythonState) -> Result<Self>;
280}
281
282#[derive(Debug, Clone, Serialize, Deserialize, Encode, Decode)]
283pub struct UnInit;
284
285impl Default for UnInit {
286    fn default() -> Self {
287        let _ = *UFO;
288        let _ = *ETS;
289        UnInit
290    }
291}
292
293impl TryFrom<PythonState> for UnInit {
294    type Error = NumeratorStateError;
295
296    fn try_from(value: PythonState) -> std::result::Result<Self, Self::Error> {
297        match value {
298            PythonState::UnInit(s) => {
299                if let Some(s) = s {
300                    Ok(s)
301                } else {
302                    Err(NumeratorStateError::NoneVariant)
303                }
304            }
305            _ => Err(NumeratorStateError::NotUnit),
306        }
307    }
308}
309
310impl NumeratorState for UnInit {
311    fn export(&self) -> String {
312        "Uninitialized".to_string()
313    }
314
315    fn forget_type(self) -> PythonState {
316        PythonState::UnInit(Some(self))
317    }
318
319    fn update_model(&mut self, _model: &Model) -> Result<()> {
320        Err(eyre!("Uninitialized, nothing to update"))
321    }
322}
323
324impl TypedNumeratorState for UnInit {
325    fn apply<F, S: TypedNumeratorState>(
326        num: &mut Numerator<PythonState>,
327        mut f: F,
328    ) -> Result<(), NumeratorStateError>
329    where
330        F: FnMut(Numerator<Self>) -> Numerator<S>,
331    {
332        if let PythonState::UnInit(s) = &mut num.state {
333            if let Some(s) = s.take() {
334                *num = f(Numerator { state: s }).forget_type();
335                return Ok(());
336            } else {
337                return Err(NumeratorStateError::NoneVariant);
338            }
339        }
340        Err(NumeratorStateError::NotUnit)
341    }
342}
343
344#[allow(dead_code)]
345#[derive(JsonSchema)]
346struct _GlobalPrefactorAny {
347    projector: serde_json::Value,
348    num: serde_json::Value,
349    projector_interface: Option<serde_json::Value>,
350    num_interface: Option<serde_json::Value>,
351}
352
353#[derive(Debug, Clone, bincode_trait_derive::Encode, bincode_trait_derive::Decode, PartialEq)]
354#[trait_decode(trait = crate::GammaLoopContext)]
355pub struct GlobalPrefactor {
356    pub projector: SymbolicTensor<IndexedStructure>,
357    pub num: SymbolicTensor<IndexedStructure>,
358}
359
360impl JsonSchema for GlobalPrefactor {
361    fn json_schema(generated: &mut schemars::SchemaGenerator) -> schemars::Schema {
362        generated.subschema_for::<_GlobalPrefactorAny>()
363    }
364    fn schema_name() -> std::borrow::Cow<'static, str> {
365        "GlobalPrefactor".into()
366    }
367}
368
369impl GlobalPrefactor {
370    pub fn polarizations(&self) -> Vec<(PolDef, Atom)> {
371        let mut pols = Vec::new();
372        // Polarization parameters use the component parser's source index
373        // syntax. This observation does not replace either retained tensor.
374        let cooking = CookSettings::indices()
375            .with_mode(CookMode::ReversibleEncoding)
376            .with_representation_payloads(true, true);
377        let full_prefactor =
378            cooking.uncook((self.projector.expression() * self.num.expression()).as_view());
379        let pat = function!(GS.epsilon, W_.e_, W_.i_).to_pattern();
380        for m in full_prefactor.pattern_match(&pat, None, None) {
381            let Some(e) = m.get(&W_.e_) else {
382                continue;
383            };
384            let Ok(e) = i64::try_from(e) else {
385                continue;
386            };
387
388            pols.push((
389                PolDef {
390                    pol_type: PolType::Epsilon,
391                    eid: EdgeIndex(e as usize),
392                },
393                pat.replace_wildcards(&m).unwrap(),
394            ));
395        }
396
397        let pat = function!(GS.epsilonbar, W_.e_, W_.i_).to_pattern();
398        for m in full_prefactor.pattern_match(&pat, None, None) {
399            let Some(e) = m.get(&W_.e_) else {
400                continue;
401            };
402            let Ok(e) = i64::try_from(e) else {
403                continue;
404            };
405
406            pols.push((
407                PolDef {
408                    pol_type: PolType::EpsilonBar,
409                    eid: EdgeIndex(e as usize),
410                },
411                pat.replace_wildcards(&m).unwrap(),
412            ));
413        }
414
415        let pat = function!(GS.u, W_.e_, W_.i_).to_pattern();
416        for m in full_prefactor.pattern_match(&pat, None, None) {
417            let Some(e) = m.get(&W_.e_) else {
418                continue;
419            };
420            let Ok(e) = i64::try_from(e) else {
421                continue;
422            };
423
424            pols.push((
425                PolDef {
426                    pol_type: PolType::U,
427                    eid: EdgeIndex(e as usize),
428                },
429                pat.replace_wildcards(&m).unwrap(),
430            ));
431        }
432
433        let pat = function!(GS.v, W_.e_, W_.i_).to_pattern();
434        for m in full_prefactor.pattern_match(&pat, None, None) {
435            let Some(e) = m.get(&W_.e_) else {
436                continue;
437            };
438            let Ok(e) = i64::try_from(e) else {
439                continue;
440            };
441
442            pols.push((
443                PolDef {
444                    pol_type: PolType::V,
445                    eid: EdgeIndex(e as usize),
446                },
447                pat.replace_wildcards(&m).unwrap(),
448            ));
449        }
450
451        let pat = function!(GS.ubar, W_.e_, W_.i_).to_pattern();
452        for m in full_prefactor.pattern_match(&pat, None, None) {
453            let Some(e) = m.get(&W_.e_) else {
454                continue;
455            };
456            let Ok(e) = i64::try_from(e) else {
457                continue;
458            };
459
460            pols.push((
461                PolDef {
462                    pol_type: PolType::UBar,
463                    eid: EdgeIndex(e as usize),
464                },
465                pat.replace_wildcards(&m).unwrap(),
466            ));
467        }
468
469        let pat = function!(GS.vbar, W_.e_, W_.i_).to_pattern();
470        for m in full_prefactor.pattern_match(&pat, None, None) {
471            let Some(e) = m.get(&W_.e_) else {
472                continue;
473            };
474            let Ok(e) = i64::try_from(e) else {
475                continue;
476            };
477
478            pols.push((
479                PolDef {
480                    pol_type: PolType::VBar,
481                    eid: EdgeIndex(e as usize),
482                },
483                pat.replace_wildcards(&m).unwrap(),
484            ));
485        }
486
487        pols.sort_by_key(|a| a.0);
488
489        pols
490    }
491}
492
493impl Default for GlobalPrefactor {
494    fn default() -> Self {
495        GlobalPrefactor {
496            projector: SymbolicTensor::infer_indexed(Atom::one()).expect("one is a scalar tensor"),
497            num: SymbolicTensor::infer_indexed(Atom::one()).expect("one is a scalar tensor"),
498        }
499    }
500}
501
502impl Serialize for GlobalPrefactor {
503    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
504    where
505        S: serde::Serializer,
506    {
507        let (projector, projector_interface) =
508            feynkit_graph::NumeratorInterface::export(&self.projector);
509        let (num, num_interface) = feynkit_graph::NumeratorInterface::export(&self.num);
510        let mut state = serializer.serialize_struct(
511            "GlobalPrefactor",
512            2 + usize::from(projector_interface.is_some()) + usize::from(num_interface.is_some()),
513        )?;
514        // Source fields must not use the display printer, whose compact tensor
515        // notation can omit the slots retained by the interface declaration.
516        state.serialize_field("projector", &projector.to_canonical_string())?;
517        state.serialize_field("num", &num.to_canonical_string())?;
518        if let Some(interface) = projector_interface {
519            state.serialize_field("projector_interface", &interface.to_json())?;
520        }
521        if let Some(interface) = num_interface {
522            state.serialize_field("num_interface", &interface.to_json())?;
523        }
524
525        state.end()
526    }
527}
528
529impl<'de> Deserialize<'de> for GlobalPrefactor {
530    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
531    where
532        D: serde::Deserializer<'de>,
533    {
534        #[derive(Deserialize)]
535        struct GlobalPrefactorHelper {
536            num: String,
537            projector: String,
538            #[serde(default)]
539            num_interface: Option<String>,
540            #[serde(default)]
541            projector_interface: Option<String>,
542        }
543        let helper = GlobalPrefactorHelper::deserialize(deserializer)?;
544        let admit = |source: &str,
545                     interface: Option<String>|
546         -> std::result::Result<SymbolicTensor<IndexedStructure>, D::Error> {
547            let expression = try_parse!(source).map_err(serde::de::Error::custom)?;
548            let interface = interface
549                .map(|source| feynkit_graph::NumeratorInterface::parse(&source))
550                .transpose()
551                .map_err(serde::de::Error::custom)?;
552            feynkit_graph::NumeratorInterface::admit(expression, interface)
553                .map_err(serde::de::Error::custom)?
554                .try_into_indexed()
555                .map_err(serde::de::Error::custom)
556        };
557        Ok(GlobalPrefactor {
558            projector: admit(&helper.projector, helper.projector_interface)?,
559            num: admit(&helper.num, helper.num_interface)?,
560        })
561    }
562}
563
564pub trait NumeratorNode {}
565
566pub mod graph;
567pub mod uninit;
568#[allow(clippy::default_constructed_unit_structs)]
569impl Default for Numerator<UnInit> {
570    fn default() -> Self {
571        Numerator {
572            state: UnInit::default(),
573        }
574    }
575}
576
577#[derive(Debug, Clone, bincode_trait_derive::Encode, bincode_trait_derive::Decode)]
578#[trait_decode(trait = symbolica::state::HasStateMap)]
579pub struct SymbolicExpression<State> {
580    pub expr: SymbolicTensor<IndexedStructure>,
581    pub state: State,
582}
583
584pub trait GetSingleAtom {
585    fn get_single_atom(&self) -> Result<Atom, NumeratorStateError>;
586}
587
588pub trait UnexpandedNumerator: NumeratorState + GetSingleAtom {
589    // fn expr(&self) -> Result<Atom, NumeratorStateError>;
590
591    fn map_color(self, f: impl Fn(Atom) -> Atom) -> Self;
592
593    fn map_color_mut(&mut self, f: impl FnMut(&mut Atom));
594
595    fn map_colorless(self, f: impl Fn(Atom) -> Atom) -> Self;
596}
597
598impl<E: ExpressionState> GetSingleAtom for SymbolicExpression<E> {
599    fn get_single_atom(&self) -> Result<Atom, NumeratorStateError> {
600        let cooking = CookSettings::indices()
601            .with_mode(CookMode::ReversibleEncoding)
602            .with_representation_payloads(true, true);
603        Ok(cooking.uncook(self.expr.expression().as_view()))
604    }
605}
606
607impl<E: ExpressionState> SymbolicExpression<E> {
608    // // #[allow(dead_code)]
609    // fn map_color(self, f: impl Fn(Atom) -> Atom) -> Self {
610    //     SymbolicExpression {
611    //         colorless: self.colorless,
612    //         color: self.color.map_data_self(f),
613    //         state: self.state,
614    //     }
615    // }
616
617    // // #[allow(dead_code)]
618    // fn map_color_mut(&mut self, f: impl FnMut(&mut Atom)) {
619    //     self.color.map_data_mut(f);
620    // }
621    // // #[allow(dead_code)]
622    // fn map_colorless(self, f: impl Fn(Atom) -> Atom) -> Self {
623    //     SymbolicExpression {
624    //         colorless: self.colorless.map_data_self(f),
625    //         color: self.color,
626    //         state: self.state,
627    //     }
628    // }
629}
630
631impl<E: ExpressionState> SymbolicExpression<E> {
632    pub(crate) fn new(expression: Atom) -> Result<Self> {
633        E::new(expression)
634    }
635    pub(crate) fn new_color(expression: Atom) -> Result<Self> {
636        E::new_color(expression)
637    }
638
639    /// Keep the interface and established facts of an admitted numerator.
640    pub(crate) fn from_tensor(expression: SymbolicTensor<IndexedStructure>) -> Self {
641        Self {
642            expr: expression,
643            state: E::default(),
644        }
645    }
646}
647
648pub trait ExpressionState:
649    Serialize
650    + Clone
651    + DeserializeOwned
652    + Debug
653    + Encode
654    + for<'a> Decode<GammaLoopContextContainer<'a>>
655    + Default
656{
657    fn forget_type(data: SymbolicExpression<Self>) -> PythonState;
658
659    fn new(expression: Atom) -> Result<SymbolicExpression<Self>> {
660        let cooking = CookSettings::indices()
661            .with_mode(CookMode::ReversibleEncoding)
662            .with_representation_payloads(true, true);
663        Ok(SymbolicExpression::from_tensor(
664            SymbolicTensor::infer_indexed(cooking.try_cook(expression.as_view())?)?,
665        ))
666    }
667
668    fn new_color(expression: Atom) -> Result<SymbolicExpression<Self>> {
669        Self::new(expression)
670    }
671
672    fn get_expression(
673        num: &mut PythonState,
674    ) -> Result<SymbolicExpression<Self>, NumeratorStateError>;
675}
676
677impl<E: ExpressionState> TypedNumeratorState for SymbolicExpression<E> {
678    fn apply<F, S: TypedNumeratorState>(
679        num: &mut Numerator<PythonState>,
680        mut f: F,
681    ) -> Result<(), NumeratorStateError>
682    where
683        F: FnMut(Numerator<Self>) -> Numerator<S>,
684    {
685        let s = Self::try_from(&mut num.state)?;
686        *num = f(Numerator { state: s }).forget_type();
687        Ok(())
688    }
689}
690
691impl<E: ExpressionState> TryFrom<&mut PythonState> for SymbolicExpression<E> {
692    type Error = NumeratorStateError;
693
694    fn try_from(value: &mut PythonState) -> std::result::Result<Self, Self::Error> {
695        let a = E::get_expression(value)?;
696        Ok(a)
697    }
698}
699
700impl<E: ExpressionState> TryFrom<PythonState> for SymbolicExpression<E> {
701    type Error = NumeratorStateError;
702
703    fn try_from(mut value: PythonState) -> std::result::Result<Self, Self::Error> {
704        let a = E::get_expression(&mut value)?;
705        Ok(a)
706    }
707}
708
709#[derive(Debug, Clone, Copy, Serialize, Deserialize, Encode, Decode, Default)]
710pub struct Local {}
711pub type AppliedFeynmanRule = SymbolicExpression<Local>;
712
713impl ExpressionState for Local {
714    fn forget_type(data: SymbolicExpression<Self>) -> PythonState {
715        PythonState::AppliedFeynmanRule(Some(data))
716    }
717
718    fn get_expression(
719        num: &mut PythonState,
720    ) -> Result<SymbolicExpression<Self>, NumeratorStateError> {
721        if let PythonState::AppliedFeynmanRule(s) = num {
722            if let Some(s) = s.take() {
723                Ok(s)
724            } else {
725                Err(NumeratorStateError::NoneVariant)
726            }
727        } else {
728            Err(NumeratorStateError::NotAppliedFeynmanRule)
729        }
730    }
731}
732
733#[derive(Debug, Copy, Clone, Serialize, Deserialize, Encode, Decode, Default)]
734pub struct NonLocal {}
735pub type Global = SymbolicExpression<NonLocal>;
736
737impl ExpressionState for NonLocal {
738    fn forget_type(data: SymbolicExpression<Self>) -> PythonState {
739        PythonState::Global(Some(data))
740    }
741
742    fn get_expression(
743        num: &mut PythonState,
744    ) -> Result<SymbolicExpression<Self>, NumeratorStateError> {
745        if let PythonState::Global(s) = num {
746            if let Some(s) = s.take() {
747                Ok(s)
748            } else {
749                Err(NumeratorStateError::NoneVariant)
750            }
751        } else {
752            Err(NumeratorStateError::NotGlobal)
753        }
754    }
755}
756
757impl Numerator<Global> {
758    #[instrument(skip(self))]
759    pub(crate) fn color_simplify(self) -> Result<Numerator<ColorSimplified>> {
760        // debug!("Color simplifying global numerator");
761        // let mut fully_simplified = true;
762
763        let state = ColorSimplified {
764            expr: {
765                self.state
766                    .expr
767                    .simplify_algebra(&AlgebraSettings {
768                        color: Some(ColorSimplifySettings::default()),
769                        // Color prerequisites must not distribute fermion numerators
770                        // or collect Dirac chains before local Taylor operations.
771                        contract: AlgebraContraction::None,
772                        ..Default::default()
773                    })?
774                    .contract(ContractSettings {
775                        collect_chains: false,
776                        collect_traces: false,
777                        expand: false,
778                        ..Default::default()
779                    })?
780            },
781            state: Color::Fully,
782        };
783        // debug!("Color simplified numerator:{}", state.expr);
784        Ok(Numerator { state })
785    }
786}
787
788#[derive(Debug, Copy, Clone, Serialize, Deserialize, Encode, Decode, Default)]
789pub enum Color {
790    #[default]
791    Fully,
792    Partially,
793}
794pub type ColorSimplified = SymbolicExpression<Color>;
795
796impl ExpressionState for Color {
797    fn forget_type(data: SymbolicExpression<Self>) -> PythonState {
798        PythonState::ColorSimplified(Some(data))
799    }
800
801    fn get_expression(
802        num: &mut PythonState,
803    ) -> Result<SymbolicExpression<Self>, NumeratorStateError> {
804        if let PythonState::ColorSimplified(s) = num {
805            if let Some(s) = s.take() {
806                Ok(s)
807            } else {
808                Err(NumeratorStateError::NoneVariant)
809            }
810        } else {
811            Err(NumeratorStateError::NotColorSimplified)
812        }
813    }
814}
815
816// #[derive(Debug, Clone, Serialize, Deserialize, Encode, Decode, Default)]
817// pub struct Projected {}
818// pub type ColorProjected = SymbolicExpression<Projected>;
819
820// impl ExpressionState for Projected {
821//     fn forget_type(data: SymbolicExpression<Self>) -> PythonState {
822//         PythonState::ColorProjected(Some(data))
823//     }
824
825//     fn get_expression(
826//         num: &mut PythonState,
827//     ) -> Result<SymbolicExpression<Self>, NumeratorStateError> {
828//         if let PythonState::ColorProjected(s) = num {
829//             if let Some(s) = s.take() {
830//                 Ok(s)
831//             } else {
832//                 Err(NumeratorStateError::NoneVariant)
833//             }
834//         } else {
835//             Err(NumeratorStateError::NotColorProjected)
836//         }
837//     }
838// }
839
840#[derive(Debug, Copy, Clone, Serialize, Deserialize, Encode, Decode, Default)]
841pub struct Gamma {}
842pub type GammaSimplified = SymbolicExpression<Gamma>;
843
844impl ExpressionState for Gamma {
845    fn forget_type(data: SymbolicExpression<Self>) -> PythonState {
846        PythonState::GammaSimplified(Some(data))
847    }
848
849    fn get_expression(
850        num: &mut PythonState,
851    ) -> Result<SymbolicExpression<Self>, NumeratorStateError> {
852        if let PythonState::GammaSimplified(s) = num {
853            if let Some(s) = s.take() {
854                Ok(s)
855            } else {
856                Err(NumeratorStateError::NoneVariant)
857            }
858        } else {
859            Err(NumeratorStateError::NotGammaSymplified)
860        }
861    }
862}
863
864impl<State: ExpressionState> NumeratorState for SymbolicExpression<State> {
865    fn export(&self) -> String {
866        self.get_single_atom().unwrap().to_canonical_string()
867    }
868
869    fn forget_type(self) -> PythonState {
870        State::forget_type(self)
871    }
872
873    fn update_model(&mut self, _model: &Model) -> Result<()> {
874        Err(eyre!("Only an expression, nothing to update"))
875    }
876}
877
878impl Numerator<AppliedFeynmanRule> {
879    #[allow(clippy::wrong_self_convention)]
880    pub(crate) fn to_d_dim(mut self, dim: impl Into<Dimension>) -> Result<Self> {
881        self.state.expr = self.state.expr.with_lorentz_dimension(dim.into())?;
882        Ok(self)
883    }
884
885    #[instrument(skip(self), fields(expr=%self.state.expr.expression().to_ordered_simple()))]
886    pub(crate) fn color_simplify(self) -> Result<Numerator<ColorSimplified>> {
887        // debug!("Color simplifying global numerator");
888        // let mut fully_simplified = true;
889
890        let state = ColorSimplified {
891            expr: {
892                self.state
893                    .expr
894                    .simplify_algebra(&AlgebraSettings {
895                        color: Some(ColorSimplifySettings::default()),
896                        // Color prerequisites must not distribute fermion numerators
897                        // or collect Dirac chains before local Taylor operations.
898                        contract: AlgebraContraction::None,
899                        ..Default::default()
900                    })?
901                    .contract(ContractSettings {
902                        collect_chains: false,
903                        collect_traces: false,
904                        expand: false,
905                        ..Default::default()
906                    })?
907            },
908            state: Color::Fully,
909        };
910        debug!(
911            "Color simplified numerator:{}",
912            state.expr.expression().to_ordered_simple()
913        );
914        Ok(Numerator { state })
915    }
916}
917
918// #[derive(Debug, Error)]
919// pub enum ColorError {
920//     #[error("Not fully simplified: {0}")]
921//     NotFully(Atom),
922// }
923
924impl Numerator<ColorSimplified> {
925    pub(crate) fn gamma_simplify(self) -> Result<Numerator<GammaSimplified>> {
926        debug!("Gamma simplifying color symplified numerator");
927        let expr = self
928            .state
929            .expr
930            .simplify_algebra(&idenso::tensor::AlgebraSettings {
931                gamma: Some(GammaSimplifySettings::default()),
932                epsilon: true,
933                ..Default::default()
934            })?
935            .contract(idenso::tensor::ContractSettings {
936                collect_chains: false,
937                collect_traces: false,
938                ..Default::default()
939            })?;
940        crate::debug_tags!(#generation, #inspect, #dump;
941            stage = "numerator_after_simplify_gamma",
942            log.after_gamma = expr.expression(),
943            "Numerator after gamma simplification"
944        );
945
946        Ok(Numerator {
947            state: GammaSimplified {
948                expr,
949                state: Default::default(),
950            },
951        })
952    }
953}
954
955#[cfg(test)]
956mod typed_expression_tests {
957    use super::*;
958    use crate::initialisation::test_initialise;
959    use idenso::bis;
960    use idenso::dirac::AGS;
961    use spenso::network::tags::SPENSO_TAG;
962    use spenso::{g, mink, p, q};
963
964    #[test]
965    fn color_stage_preserves_factorized_fermion_numerators() {
966        test_initialise().unwrap();
967        let [i, j, k, l] = [91, 92, 93, 94].map(|index| bis!(4, Atom::num(index)));
968        let [mu, nu] = [95, 96].map(|index| mink!(4, Atom::num(index)));
969        let mass = Atom::var(symbol!("color_stage_fermion_mass"));
970        let expression = (&mass * g!(&i, &j) + function!(AGS.gamma, &j, &i, p!(mink!(4))))
971            * (&mass * g!(&k, &l) + function!(AGS.gamma, &l, &k, q!(mink!(4))))
972            * function!(AGS.gamma, &i, &l, &mu)
973            * function!(AGS.gamma, &k, &j, &nu);
974        let local = Numerator {
975            state: AppliedFeynmanRule::new(expression.clone()).unwrap(),
976        }
977        .color_simplify()
978        .unwrap();
979        let global = Numerator {
980            state: Global::new(expression).unwrap(),
981        }
982        .color_simplify()
983        .unwrap();
984        for result in [local, global] {
985            assert!(
986                !result
987                    .state
988                    .expr
989                    .expression()
990                    .contains_symbol(SPENSO_TAG.trace),
991                "the color stage must leave Dirac collection to the gamma stage",
992            );
993            let AtomView::Mul(product) = result.state.expr.expression().as_view() else {
994                panic!("the color stage must retain the fermion numerator product");
995            };
996            assert_eq!(
997                product
998                    .iter()
999                    .filter(|factor| matches!(factor, AtomView::Add(_)))
1000                    .count(),
1001                2,
1002                "the two propagator numerators must remain independent factors",
1003            );
1004        }
1005    }
1006
1007    #[test]
1008    fn admitted_numerator_keeps_its_interface_through_color_and_gamma_stages() {
1009        let input = function!(
1010            spenso::tensor_symbol!("gammalooprs::typed_numerator_vector"),
1011            spenso::mink!(4, 81)
1012        );
1013        let admitted = AppliedFeynmanRule::new(input.clone()).unwrap();
1014        assert_eq!(admitted.expr.rank(), 1);
1015        assert_eq!(admitted.get_single_atom().unwrap(), input);
1016        let expected = admitted.expr.clone();
1017        let simplified = Numerator { state: admitted }
1018            .color_simplify()
1019            .unwrap()
1020            .gamma_simplify()
1021            .unwrap();
1022        assert!(simplified.state.expr.same_value(&expected));
1023    }
1024
1025    #[test]
1026    fn numerator_admission_requires_indexed_external_ports_but_keeps_closed_compact_dots() {
1027        let head = spenso::vector_symbol!("gammalooprs::indexed_admission_vector");
1028        let compact = function!(head, spenso::mink!(4));
1029        assert!(AppliedFeynmanRule::new(compact.clone()).is_err());
1030        let closed = AppliedFeynmanRule::new(spenso::dot!(&compact, &compact)).unwrap();
1031        assert!(closed.expr.is_scalar());
1032        let explicit = AppliedFeynmanRule::new(function!(head, spenso::mink!(4, 87))).unwrap();
1033        assert_eq!(explicit.expr.rank(), 1);
1034        let zero = explicit.expr.with_checked_expression(Atom::Zero).unwrap();
1035        assert!(zero.is_zero());
1036        assert_eq!(zero.structure(), explicit.expr.structure());
1037    }
1038
1039    #[test]
1040    fn zero_numerator_retains_open_tensor_rank_across_symbolic_states() {
1041        let vector = AppliedFeynmanRule::new(function!(
1042            spenso::tensor_symbol!("gammalooprs::typed_zero_numerator_vector"),
1043            spenso::mink!(4, 83)
1044        ))
1045        .unwrap();
1046        let zero = vector.expr.with_algebra_result(Atom::Zero).unwrap();
1047        let expected = zero.structure().clone();
1048        let simplified = Numerator {
1049            state: AppliedFeynmanRule::from_tensor(zero),
1050        }
1051        .to_d_dim(GS.dim)
1052        .unwrap()
1053        .color_simplify()
1054        .unwrap()
1055        .gamma_simplify()
1056        .unwrap();
1057        assert!(simplified.state.expr.is_zero());
1058        assert_eq!(simplified.state.expr.rank(), 1);
1059        assert_ne!(simplified.state.expr.structure(), &expected);
1060        assert_eq!(simplified.state.expr.structure().canonical().order(), 1);
1061    }
1062}
1063
1064pub type Gloopoly =
1065    symbolica::poly::polynomial::MultivariatePolynomial<symbolica::domains::atom::AtomField, u8>;
1066
1067#[derive(Debug, Clone)]
1068// #[trait_decode(trait = symbolica::state::HasStateMap)]
1069pub struct PolySplit {
1070    pub colorless: DataTensor<Gloopoly, ShadowedStructure<Aind>>,
1071    pub var_map: Arc<Vec<PolyVariable>>,
1072    pub energies: Vec<usize>,
1073    pub color: ParamTensor<ShadowedStructure<Aind>>,
1074    pub colorsimplified: Color,
1075}
1076
1077impl Encode for PolySplit {
1078    fn encode<E: bincode::enc::Encoder>(
1079        &self,
1080        _encoder: &mut E,
1081    ) -> std::result::Result<(), bincode::error::EncodeError> {
1082        todo!()
1083    }
1084}
1085
1086impl PolySplit {
1087    pub(crate) fn from_color_out(
1088        _color_simplified: Numerator<ColorSimplified>,
1089    ) -> DataTensor<Atom> {
1090        disable!(
1091
1092        let colorless_parsed = color_simplified
1093            .state
1094            .colorless
1095            .map_data(|a| {
1096                let mut net =
1097                    TensorNetwork::<MixedTensor<f64, AtomStructure>, Atom>::try_from(
1098                        a.as_view(),
1099                    )
1100                    .unwrap();
1101                net.contract().unwrap();
1102                net.to_fully_parametric()
1103                    .result_tensor_smart()
1104                    .unwrap()
1105                    .tensor
1106                    .map_structure(OrderedStructure::from)
1107            })
1108            .flatten(&Atom::num(0))
1109            .unwrap();
1110
1111        colorless_parsed
1112        );
1113        todo!()
1114    }
1115
1116    fn to_shadowed_poly_impl(
1117        poly: &Gloopoly,
1118        workspace: &Workspace,
1119        reps: Arc<Mutex<Vec<Atom>>>,
1120    ) -> Atom {
1121        if poly.is_zero() {
1122            return Atom::num(0);
1123        }
1124
1125        let mut add = Atom::num(0);
1126        let coef = symbol!("coef");
1127        let shift = reps.as_ref().lock().unwrap().len();
1128
1129        let mut mul_h;
1130        let mut var_h = workspace.new_atom();
1131        let mut num_h = workspace.new_atom();
1132        let mut pow_h = workspace.new_atom();
1133
1134        for (i, monomial) in poly.into_iter().enumerate() {
1135            mul_h = Atom::num(1);
1136            for (var_id, &pow) in poly.variables().iter().zip(monomial.exponents) {
1137                if pow > 0 {
1138                    match var_id {
1139                        PolyVariable::Symbol(v) => {
1140                            var_h.to_var(*v);
1141                        }
1142                        PolyVariable::Temporary(_) => {
1143                            unreachable!("Temporary variable in expression")
1144                        }
1145                        PolyVariable::Function(_, a) | PolyVariable::Power(a) => {
1146                            var_h.set_from_view(&a.as_view());
1147                        }
1148                    }
1149
1150                    if pow > 0 {
1151                        num_h.to_num(pow as i64);
1152                        pow_h.to_pow(var_h.as_view(), num_h.as_view());
1153                        mul_h *= pow_h.as_view();
1154                    } else {
1155                        mul_h *= var_h.as_view();
1156                    }
1157                }
1158            }
1159
1160            reps.lock()
1161                .as_mut()
1162                .unwrap()
1163                .push(monomial.coefficient.clone());
1164
1165            mul_h *= function!(coef, Atom::num((i + shift) as i64));
1166            add += mul_h.as_view();
1167        }
1168
1169        add
1170    }
1171    fn shadow_poly(poly: Gloopoly, reps: Arc<Mutex<Vec<Atom>>>) -> Atom {
1172        Workspace::get_local().with(|ws| Self::to_shadowed_poly_impl(&poly, ws, reps))
1173    }
1174
1175    pub(crate) fn optimize(self) -> PolyContracted {
1176        let reps = Arc::new(Mutex::new(Vec::new()));
1177
1178        let colorless = self
1179            .colorless
1180            .map_data(|a| Self::shadow_poly(a, reps.clone()));
1181
1182        let out = match self.colorsimplified {
1183            Color::Fully => ParamTensor::composite(colorless)
1184                .contract(&self.color)
1185                .unwrap(),
1186            Color::Partially => {
1187                warn!(
1188                    "Not fully color-simplified, taking the colorless part associated to {}",
1189                    self.color.get_owned_linear(FlatIndex::from(0)).unwrap()
1190                );
1191                ParamTensor::new_scalar(colorless.get_owned_linear(FlatIndex::from(0)).unwrap())
1192            }
1193        };
1194
1195        let reps = Arc::try_unwrap(reps).unwrap().into_inner().unwrap();
1196
1197        PolyContracted {
1198            tensor: out,
1199            coef_map: reps,
1200        }
1201    }
1202}
1203
1204impl Numerator<PolySplit> {
1205    pub(crate) fn contract(self) -> Result<Numerator<PolyContracted>> {
1206        match self.validate_squared_energies_impl() {
1207            Err(_) => {
1208                debug!("Trying to contract polynomial");
1209                let state = self.state.optimize();
1210                debug!("PolyContracted: {}", state.tensor);
1211                Ok(Numerator { state })
1212            }
1213            Ok(r) => Err(eyre!("has higher powers here: {}", r)),
1214        }
1215    }
1216
1217    fn validate_squared_energies_impl(
1218        &self,
1219    ) -> Result<DataTensor<ExpandedIndex, ShadowedStructure<Aind>>, ()> {
1220        self.state.colorless.map_data_ref_result(|p| {
1221            let mut square: Result<Vec<usize>, ()> = Err(());
1222            for (i, &e) in p.exponents.iter().enumerate() {
1223                if e > 1 {
1224                    if let Ok(sq) = &mut square {
1225                        sq.push(i);
1226                    } else {
1227                        square = Ok(vec![i]);
1228                    }
1229                }
1230            }
1231            square.map(ExpandedIndex::from)
1232        })
1233    }
1234
1235    pub(crate) fn validate_squared_energies(&self) -> bool {
1236        self.validate_squared_energies_impl().is_err()
1237    }
1238}
1239
1240#[derive(Debug, Clone, bincode_trait_derive::Encode, bincode_trait_derive::Decode)]
1241#[trait_decode(trait = symbolica::state::HasStateMap)]
1242pub struct PolyContracted {
1243    pub tensor: ParamTensor<ShadowedStructure<Aind>>,
1244    pub coef_map: Vec<Atom>,
1245}
1246
1247impl Numerator<PolyContracted> {
1248    #[allow(clippy::wrong_self_convention)]
1249    pub(crate) fn to_contracted(self) -> Numerator<Contracted> {
1250        let coefs: Vec<_> = (0..self.state.coef_map.len())
1251            .map(|i| function!(GS.coeff, Atom::num(i as i64)).to_pattern())
1252            .collect();
1253
1254        let coefs_reps: Vec<_> = self.state.coef_map.iter().map(|a| a.to_pattern()).collect();
1255
1256        let reps: Vec<_> = coefs
1257            .into_iter()
1258            .zip(coefs_reps)
1259            .map(|(p, rhs)| Replacement::new(p, rhs))
1260            .collect();
1261
1262        Numerator {
1263            state: Contracted {
1264                tensor: self.state.tensor.replace_multiple(&reps),
1265            },
1266        }
1267    }
1268
1269    fn generate_fn_map(&self) -> FunctionMap {
1270        let mut fn_map = FunctionMap::new();
1271
1272        for (v, k) in self.state.coef_map.clone().iter().enumerate() {
1273            fn_map
1274                .add_tagged_function::<Symbol>(
1275                    GS.coeff,
1276                    vec![Atom::num(v as i64)],
1277                    vec![],
1278                    k.clone(),
1279                )
1280                .unwrap();
1281        }
1282
1283        Numerator::<Contracted>::add_consts_to_fn_map(&mut fn_map);
1284        fn_map
1285    }
1286}
1287
1288impl NumeratorState for PolyContracted {
1289    fn export(&self) -> String {
1290        self.tensor.to_string()
1291    }
1292    fn forget_type(self) -> PythonState {
1293        PythonState::PolyContracted(Some(self))
1294    }
1295
1296    fn update_model(&mut self, _model: &Model) -> Result<()> {
1297        Err(eyre!(
1298            "Only applied feynman rule, simplified color, gamma, parsed into network and contracted, nothing to update"
1299        ))
1300    }
1301}
1302
1303impl PolyContracted {}
1304
1305impl GammaSimplified {
1306    pub(crate) fn parse(self) -> Network {
1307        let lib = DummyLibrary::<ParamTensor<ShadowedStructure<Aind>>, _>::new();
1308        let cooking = CookSettings::indices().with_mode(CookMode::ReversibleEncoding);
1309        let (net, layout) = self
1310            .expr
1311            .into_network(
1312                &lib,
1313                &spenso::network::library::panicing::ErroringLibrary::<Symbol>::new(),
1314                &ParseSettings::default(),
1315                Some(&cooking),
1316            )
1317            .unwrap()
1318            .into_parts();
1319
1320        // println!("net scalar{}", net.scalar.as_ref().unwrap());
1321        Network { net, layout }
1322    }
1323
1324    // pub(crate) fn parse_only_colorless(self) -> Network {
1325    //     let lib = DummyLibrary::<(), _>::new();
1326    //     let net = ParsingNet::try_from_view(
1327    //         self.colorless
1328    //             .clone()
1329    //             .scalar()
1330    //             .ok_or(NumeratorStateError::Any(eyre!("not a scalar")))
1331    //             .unwrap()
1332    //             .as_view(),
1333    //         &lib,
1334    //     )
1335    //     .unwrap();
1336
1337    //     // println!("net scalar{}", net.scalar.as_ref().unwrap());
1338    //     Network { net }
1339    // }
1340}
1341
1342impl Numerator<GammaSimplified> {
1343    pub(crate) fn parse(self) -> Result<Numerator<Network>> {
1344        // debug!("GammaSymplified numerator: {}", self.export());
1345        debug!("Parsing gamma simplified numerator into tensor network");
1346        let cooking = CookSettings::indices().with_mode(CookMode::ReversibleEncoding);
1347        let (net, layout) = self
1348            .state
1349            .expr
1350            .into_network(
1351                TENSORLIB.read().unwrap().deref(),
1352                &spenso::network::library::panicing::ErroringLibrary::<Symbol>::new(),
1353                &ParseSettings::default(),
1354                Some(&cooking),
1355            )?
1356            .into_parts();
1357        Ok(Numerator {
1358            state: Network { net, layout },
1359        })
1360    }
1361
1362    // pub(crate) fn parse_only_colorless(self) -> Numerator<Network> {
1363    //     debug!("Parsing only colorless gamma simplified numerator into tensor network");
1364    //     Numerator {
1365    //         state: self.state.parse_only_colorless(),
1366    //     }
1367    // }
1368}
1369
1370pub type ParsingNet = spenso::network::Network<
1371    NetworkStore<ParamTensor<ShadowedStructure<Aind>>, Atom>,
1372    ExplicitKey<Aind>,
1373    Symbol,
1374    Aind,
1375>;
1376
1377#[derive(Debug, Clone, bincode_trait_derive::Encode, bincode_trait_derive::Decode)]
1378#[trait_decode(trait = symbolica::state::HasStateMap)]
1379pub struct Network {
1380    // #[bincode(with_serde
1381    pub net: ParsingNet,
1382    /// Map canonical component axes to the numerator's declared logical axes.
1383    pub layout: CanonicalLayout,
1384}
1385
1386impl TryFrom<PythonState> for Network {
1387    type Error = NumeratorStateError;
1388
1389    fn try_from(value: PythonState) -> std::result::Result<Self, Self::Error> {
1390        match value {
1391            PythonState::Network(s) => {
1392                if let Some(s) = s {
1393                    Ok(s)
1394                } else {
1395                    Err(NumeratorStateError::NoneVariant)
1396                }
1397            }
1398            _ => Err(NumeratorStateError::NotNetwork),
1399        }
1400    }
1401}
1402
1403#[derive(Clone, Copy, Debug)]
1404pub struct ContractionSettings {
1405    n_steps: Option<usize>,
1406    mode: ExecutionMode,
1407}
1408
1409impl From<()> for ContractionSettings {
1410    fn from(_: ()) -> Self {
1411        Self {
1412            n_steps: None,
1413            mode: ExecutionMode::All,
1414        }
1415    }
1416}
1417
1418impl Default for ContractionSettings {
1419    fn default() -> Self {
1420        Self {
1421            n_steps: None,
1422            mode: ExecutionMode::All,
1423        }
1424    }
1425}
1426
1427#[derive(Clone, Copy, Debug)]
1428pub enum ExecutionMode {
1429    Single,
1430    Scalar,
1431    All,
1432}
1433
1434impl Network {
1435    pub(crate) fn parse_impl(expr: AtomView) -> Self {
1436        let lib = DummyLibrary::<ParamTensor<ShadowedStructure<Aind>>, _>::new();
1437        let cooking = CookSettings::indices().with_mode(CookMode::ReversibleEncoding);
1438        let (net, layout) = AppliedFeynmanRule::new(expr.to_owned())
1439            .unwrap()
1440            .expr
1441            .into_network(
1442                &lib,
1443                &spenso::network::library::panicing::ErroringLibrary::<Symbol>::new(),
1444                &ParseSettings::default(),
1445                Some(&cooking),
1446            )
1447            .unwrap()
1448            .into_parts();
1449
1450        // println!("net scalar{}", net.scalar.as_ref().unwrap());
1451        Network { net, layout }
1452    }
1453
1454    pub(crate) fn contract(&mut self, settings: impl Into<ContractionSettings>) -> Result<()> {
1455        let lib = TENSORLIB.read().unwrap();
1456        let fnlib = FUN_LIB.deref();
1457        let settings = settings.into();
1458        debug!(
1459            "Contracting network:{} with settings: {:#?}",
1460            self.net.dot(),
1461            settings
1462        );
1463        if let Some(n) = settings.n_steps {
1464            for _ in 0..n {
1465                match settings.mode {
1466                    ExecutionMode::All => self
1467                        .net
1468                        .execute::<Steps<1>, MinResultRank, _, _, _>(lib.deref(), fnlib)?,
1469                    ExecutionMode::Scalar => self
1470                        .net
1471                        .execute::<Steps<1>, ContractScalars, _, _, _>(lib.deref(), fnlib)?,
1472                    ExecutionMode::Single => self
1473                        .net
1474                        .execute::<Steps<1>, SingleSmallestDegree<false>, _, _, _>(
1475                            lib.deref(),
1476                            fnlib,
1477                        )?,
1478                }
1479            }
1480        } else {
1481            match settings.mode {
1482                ExecutionMode::All => {
1483                    self.net
1484                        .execute::<Sequential, MinResultRank, _, _, _>(lib.deref(), fnlib)?;
1485                }
1486                ExecutionMode::Scalar => {
1487                    self.net
1488                        .execute::<Sequential, ContractScalars, _, _, _>(lib.deref(), fnlib)?;
1489                }
1490                ExecutionMode::Single => {
1491                    self.net
1492                        .execute::<Sequential, SingleSmallestDegree<false>, _, _, _>(
1493                            lib.deref(),
1494                            fnlib,
1495                        )?;
1496                }
1497            }
1498        }
1499        Ok(())
1500    }
1501}
1502
1503impl NumeratorState for Network {
1504    fn export(&self) -> String {
1505        " self.expression.to_string()".to_string()
1506    }
1507
1508    fn forget_type(self) -> PythonState {
1509        PythonState::Network(Some(self))
1510    }
1511
1512    fn update_model(&mut self, _model: &Model) -> Result<()> {
1513        Err(eyre!(
1514            "Only applied feynman rule, simplified color, gamma and parsed into network, nothing to update"
1515        ))
1516    }
1517}
1518
1519impl TypedNumeratorState for Network {
1520    fn apply<F, S: TypedNumeratorState>(
1521        num: &mut Numerator<PythonState>,
1522        mut f: F,
1523    ) -> Result<(), NumeratorStateError>
1524    where
1525        F: FnMut(Numerator<Self>) -> Numerator<S>,
1526    {
1527        if let PythonState::Network(s) = &mut num.state {
1528            if let Some(s) = s.take() {
1529                *num = f(Numerator { state: s }).forget_type();
1530                return Ok(());
1531            } else {
1532                return Err(NumeratorStateError::NoneVariant);
1533            }
1534        }
1535        Err(NumeratorStateError::NotNetwork)
1536    }
1537}
1538
1539#[derive(Debug, Clone, bincode_trait_derive::Encode, bincode_trait_derive::Decode)]
1540#[trait_decode(trait = symbolica::state::HasStateMap)]
1541pub struct Contracted {
1542    pub tensor: ParamTensor<ShadowedStructure<Aind>>,
1543}
1544
1545impl TryFrom<PythonState> for Contracted {
1546    type Error = NumeratorStateError;
1547
1548    fn try_from(value: PythonState) -> std::result::Result<Self, Self::Error> {
1549        match value {
1550            PythonState::Contracted(s) => {
1551                if let Some(s) = s {
1552                    Ok(s)
1553                } else {
1554                    Err(NumeratorStateError::NoneVariant)
1555                }
1556            }
1557            _ => Err(NumeratorStateError::NotContracted),
1558        }
1559    }
1560}
1561
1562impl Contracted {
1563    pub(crate) fn one() -> Self {
1564        Contracted {
1565            tensor: ParamTensor::new_scalar(Atom::one()),
1566        }
1567    }
1568
1569    pub(crate) fn zero() -> Self {
1570        Contracted {
1571            tensor: ParamTensor::new_scalar(Atom::Zero),
1572        }
1573    }
1574
1575    pub(crate) fn generate_kinematic_params_impl(
1576        n_edges: usize,
1577        pol_data: Vec<(String, i64, usize)>,
1578    ) -> Vec<Atom> {
1579        fn atoms_for_pol(name: String, num: i64, size: usize) -> Vec<Atom> {
1580            let mut data = vec![];
1581            for index in 0..size {
1582                let e = FunctionBuilder::new(symbol!(&name));
1583                data.push(
1584                    e.add_arg(Atom::num(num))
1585                        .add_arg(parse!(&format!("cind({})", index)))
1586                        .finish(),
1587                );
1588            }
1589            data
1590        }
1591        let mut params: Vec<Atom> = vec![];
1592
1593        let mut pols = Vec::new();
1594
1595        for i in 0..n_edges {
1596            let named_structure: NamedStructure<String> =
1597                NamedStructure::from_iter([Lorentz {}.new_slot(4, i)], "Q".into(), Some(i))
1598                    .into_canonical();
1599            params.extend(
1600                named_structure
1601                    .to_shell()
1602                    .expanded_shadow()
1603                    .unwrap()
1604                    .data
1605                    .clone(),
1606            );
1607        }
1608
1609        for (name, num, size) in pol_data {
1610            pols.extend(atoms_for_pol(name, num, size));
1611        }
1612
1613        params.extend(pols);
1614        params.push(Atom::i());
1615
1616        params
1617    }
1618}
1619
1620impl NumeratorState for Contracted {
1621    fn export(&self) -> String {
1622        self.tensor.to_string()
1623    }
1624    fn forget_type(self) -> PythonState {
1625        PythonState::Contracted(Some(self))
1626    }
1627
1628    fn update_model(&mut self, _model: &Model) -> Result<()> {
1629        Err(eyre!(
1630            "Only applied feynman rule, simplified color, gamma, parsed into network and contracted, nothing to update"
1631        ))
1632    }
1633}
1634
1635impl TypedNumeratorState for Contracted {
1636    fn apply<F, S: TypedNumeratorState>(
1637        num: &mut Numerator<PythonState>,
1638        mut f: F,
1639    ) -> Result<(), NumeratorStateError>
1640    where
1641        F: FnMut(Numerator<Self>) -> Numerator<S>,
1642    {
1643        if let PythonState::Contracted(s) = &mut num.state {
1644            if let Some(s) = s.take() {
1645                *num = f(Numerator { state: s }).forget_type();
1646                return Ok(());
1647            } else {
1648                return Err(NumeratorStateError::NoneVariant);
1649            }
1650        }
1651        Err(NumeratorStateError::NotContracted)
1652    }
1653}
1654
1655impl Numerator<Contracted> {
1656    fn generate_fn_map(&self) -> FunctionMap {
1657        let mut map = FunctionMap::new();
1658        Numerator::<Contracted>::add_consts_to_fn_map(&mut map);
1659        map
1660    }
1661    // #[allow(clippy::too_many_arguments)]
1662    // pub(crate) fn generate_evaluators_from_params(
1663    //     self,
1664    //     n_edges: usize,
1665    //     name: &str,
1666    //     model_params_start: usize,
1667    //     params: &[Atom],
1668    //     double_param_values: Vec<Complex<F<f64>>>,
1669    //     quad_param_values: Vec<Complex<F<f128>>>,
1670    //     extra_info: &ExtraInfo,
1671    //     export_settings: &GenerationSettings,
1672    // ) -> Numerator<Evaluators> {
1673    //     let o = &export_settings.numerator_settings.eval_settings;
1674    //     let owned_fn_map = self.generate_fn_map();
1675
1676    //     let inline_asm = export_settings.compile.inline_asm();
1677    //     let compile_options = export_settings
1678    //         .compile
1679    //         .to_symbolica_compile_options();
1680
1681    //     let eval_settings = NumeratorEvaluatorSettings {
1682    //         options: o,
1683    //         inline_asm,
1684    //         compile_options,
1685    //     };
1686
1687    //     let fn_map: FunctionMap = owned_fn_map;
1688    //     let single = self.state.evaluator(
1689    //         extra_info.path.clone(),
1690    //         name,
1691    //         &eval_settings,
1692    //         params,
1693    //         &fn_map,
1694    //     );
1695
1696    //     match o {
1697    //         NumeratorEvaluatorOptions::Joint(_) => Numerator {
1698    //             state: Evaluators {
1699    //                 orientated: Some(single.orientated_joint_impl(
1700    //                     n_edges,
1701    //                     name,
1702    //                     params,
1703    //                     extra_info,
1704    //                     &eval_settings,
1705    //                     &fn_map,
1706    //                 )),
1707    //                 single,
1708    //                 choice: SingleOrCombined::Combined,
1709    //                 orientations: extra_info.orientations.clone(),
1710    //                 quad_param_values,
1711    //                 double_param_values,
1712    //                 model_params_start,
1713    //                 emr_len: n_edges,
1714    //                 fn_map,
1715    //             },
1716    //         },
1717    //         NumeratorEvaluatorOptions::Iterative(IterativeOptions {
1718    //             iterations,
1719    //             n_cores,
1720    //             verbose,
1721    //             ..
1722    //         }) => Numerator {
1723    //             state: Evaluators {
1724    //                 orientated: Some(single.orientated_iterative_impl(
1725    //                     n_edges,
1726    //                     name,
1727    //                     params,
1728    //                     extra_info,
1729    //                     &eval_settings,
1730    //                     *iterations,
1731    //                     *n_cores,
1732    //                     *verbose,
1733    //                     &fn_map,
1734    //                 )),
1735    //                 single,
1736    //                 choice: SingleOrCombined::Combined,
1737    //                 orientations: extra_info.orientations.clone(),
1738    //                 quad_param_values,
1739    //                 double_param_values,
1740    //                 model_params_start,
1741    //                 emr_len: n_edges,
1742    //                 fn_map,
1743    //             },
1744    //         },
1745    //         _ => Numerator {
1746    //             state: Evaluators {
1747    //                 orientated: None,
1748    //                 single,
1749    //                 choice: SingleOrCombined::Single,
1750    //                 orientations: extra_info.orientations.clone(),
1751    //                 quad_param_values,
1752    //                 double_param_values,
1753    //                 model_params_start,
1754    //                 emr_len: n_edges,
1755    //                 fn_map,
1756    //             },
1757    //         },
1758    //     }
1759    // }
1760}
1761
1762#[derive(Debug, Clone, Serialize, Deserialize, Encode, Decode, PartialEq)]
1763pub struct IterativeOptions {
1764    pub eval_options: EvaluatorOptions,
1765    pub iterations: usize,
1766    pub n_cores: usize,
1767    pub verbose: bool,
1768}
1769
1770#[derive(Debug, Clone, Serialize, Deserialize, Encode, Decode, PartialEq)]
1771pub enum NumeratorParseMode {
1772    Polynomial,
1773    Direct,
1774}
1775
1776#[derive(Debug, Clone, Serialize, Deserialize, Encode, Decode, PartialEq)]
1777#[serde(tag = "type")]
1778pub enum NumeratorEvaluatorOptions {
1779    #[serde(rename = "Single")]
1780    Single(EvaluatorOptions),
1781    #[serde(rename = "Joint")]
1782    Joint(EvaluatorOptions),
1783    #[serde(rename = "Iterative")]
1784    Iterative(IterativeOptions),
1785}
1786
1787#[derive(Clone)]
1788pub struct NumeratorEvaluatorSettings<'a> {
1789    pub options: &'a NumeratorEvaluatorOptions,
1790    pub inline_asm: InlineASM,
1791    pub compile_options: CompileOptions,
1792}
1793
1794impl Default for NumeratorEvaluatorOptions {
1795    fn default() -> Self {
1796        NumeratorEvaluatorOptions::Single(EvaluatorOptions::default())
1797    }
1798}
1799
1800impl NumeratorEvaluatorOptions {
1801    pub(crate) fn compile_options(&self) -> NumeratorCompileOptions {
1802        match self {
1803            NumeratorEvaluatorOptions::Single(options) => options.compile_options,
1804            NumeratorEvaluatorOptions::Joint(options) => options.compile_options,
1805            NumeratorEvaluatorOptions::Iterative(options) => options.eval_options.compile_options,
1806        }
1807    }
1808
1809    pub(crate) fn cpe_rounds(&self) -> Option<usize> {
1810        match self {
1811            NumeratorEvaluatorOptions::Single(options) => options.cpe_rounds,
1812            NumeratorEvaluatorOptions::Joint(options) => options.cpe_rounds,
1813            NumeratorEvaluatorOptions::Iterative(options) => options.eval_options.cpe_rounds,
1814        }
1815    }
1816}
1817
1818#[derive(Debug, Clone, Serialize, Deserialize, Copy, PartialEq, Eq, Hash, Encode, Decode)]
1819pub struct EvaluatorOptions {
1820    pub cpe_rounds: Option<usize>,
1821    pub compile_options: NumeratorCompileOptions,
1822}
1823
1824impl Default for EvaluatorOptions {
1825    fn default() -> Self {
1826        EvaluatorOptions {
1827            cpe_rounds: Some(1),
1828            compile_options: NumeratorCompileOptions::Compiled,
1829        }
1830    }
1831}
1832
1833#[derive(Debug, Clone, Serialize, Deserialize, Copy, PartialEq, Eq, Hash, Encode, Decode)]
1834#[serde(tag = "subtype")]
1835pub enum NumeratorCompileOptions {
1836    #[serde(rename = "Compiled")]
1837    Compiled,
1838    #[serde(rename = "NotCompiled")]
1839    NotCompiled,
1840}
1841
1842impl NumeratorCompileOptions {
1843    pub(crate) fn compile(&self) -> bool {
1844        matches!(self, NumeratorCompileOptions::Compiled)
1845    }
1846}
1847
1848#[derive(Error, Debug)]
1849pub enum NumeratorStateError {
1850    #[error("Not UnInit")]
1851    NotUnit,
1852    #[error("Not AppliedFeynmanRule")]
1853    NotAppliedFeynmanRule,
1854    #[error("Not ColorProjected")]
1855    NotColorProjected,
1856    #[error("Not Global")]
1857    NotGlobal,
1858    #[error("Not ColorSimplified")]
1859    NotColorSimplified,
1860    #[error("Not GammaSymplified")]
1861    NotGammaSymplified,
1862    #[error("Not Network")]
1863    NotNetwork,
1864    #[error("Not Contracted")]
1865    NotContracted,
1866    #[error("Not Evaluators")]
1867    NotEvaluators,
1868    #[error("None variant")]
1869    NoneVariant,
1870    #[error("Expanded")]
1871    Expanded,
1872    #[error("Any")]
1873    Any(#[from] eyre::Report),
1874}
1875
1876#[derive(Debug, Clone, bincode_trait_derive::Encode, bincode_trait_derive::Decode)]
1877#[trait_decode(trait = symbolica::state::HasStateMap)]
1878#[allow(clippy::large_enum_variant)]
1879pub enum PythonState {
1880    UnInit(Option<UnInit>),
1881    Global(Option<Global>),
1882    AppliedFeynmanRule(Option<AppliedFeynmanRule>),
1883    ColorSimplified(Option<ColorSimplified>),
1884    // ColorProjected(Option<ColorProjected>),
1885    GammaSimplified(Option<GammaSimplified>),
1886    Network(Option<Network>),
1887    Contracted(Option<Contracted>),
1888    PolyContracted(Option<PolyContracted>),
1889}
1890
1891impl Default for PythonState {
1892    fn default() -> Self {
1893        PythonState::UnInit(Some(UnInit))
1894    }
1895}
1896
1897impl NumeratorState for PythonState {
1898    fn export(&self) -> String {
1899        match self {
1900            PythonState::UnInit(state) => {
1901                if let Some(s) = state {
1902                    s.export()
1903                } else {
1904                    "None".into()
1905                }
1906            }
1907            PythonState::Global(state) => {
1908                if let Some(s) = state {
1909                    s.export()
1910                } else {
1911                    "None".into()
1912                }
1913            }
1914            PythonState::AppliedFeynmanRule(state) => {
1915                if let Some(s) = state {
1916                    s.export()
1917                } else {
1918                    "None".into()
1919                }
1920            }
1921            PythonState::ColorSimplified(state) => {
1922                if let Some(s) = state {
1923                    s.export()
1924                } else {
1925                    "None".into()
1926                }
1927            }
1928
1929            // PythonState::ColorProjected(state) => {
1930            //     if let Some(s) = state {
1931            //         s.export()
1932            //     } else {
1933            //         "None".into()
1934            //     }
1935            // }
1936            PythonState::GammaSimplified(state) => {
1937                if let Some(s) = state {
1938                    s.export()
1939                } else {
1940                    "None".into()
1941                }
1942            }
1943            PythonState::Network(state) => {
1944                if let Some(s) = state {
1945                    s.export()
1946                } else {
1947                    "None".into()
1948                }
1949            }
1950            PythonState::Contracted(state) => {
1951                if let Some(s) = state {
1952                    s.export()
1953                } else {
1954                    "None".into()
1955                }
1956            }
1957            PythonState::PolyContracted(state) => {
1958                if let Some(s) = state {
1959                    s.export()
1960                } else {
1961                    "None".into()
1962                }
1963            }
1964        }
1965    }
1966
1967    fn forget_type(self) -> PythonState {
1968        self
1969    }
1970
1971    fn update_model(&mut self, model: &Model) -> Result<()> {
1972        match self {
1973            PythonState::Global(state) => {
1974                if let Some(s) = state {
1975                    s.update_model(model)
1976                } else {
1977                    Err(NumeratorStateError::NoneVariant.into())
1978                }
1979            }
1980            PythonState::AppliedFeynmanRule(state) => {
1981                if let Some(s) = state {
1982                    s.update_model(model)
1983                } else {
1984                    Err(NumeratorStateError::NoneVariant.into())
1985                }
1986            }
1987            PythonState::ColorSimplified(state) => {
1988                if let Some(s) = state {
1989                    s.update_model(model)
1990                } else {
1991                    Err(NumeratorStateError::NoneVariant.into())
1992                }
1993            }
1994            PythonState::GammaSimplified(state) => {
1995                if let Some(s) = state {
1996                    s.update_model(model)
1997                } else {
1998                    Err(NumeratorStateError::NoneVariant.into())
1999                }
2000            }
2001            PythonState::Network(state) => {
2002                if let Some(s) = state {
2003                    s.update_model(model)
2004                } else {
2005                    Err(NumeratorStateError::NoneVariant.into())
2006                }
2007            }
2008            PythonState::Contracted(state) => {
2009                if let Some(s) = state {
2010                    s.update_model(model)
2011                } else {
2012                    Err(NumeratorStateError::NoneVariant.into())
2013                }
2014            }
2015            PythonState::PolyContracted(state) => {
2016                if let Some(s) = state {
2017                    s.update_model(model)
2018                } else {
2019                    Err(NumeratorStateError::NoneVariant.into())
2020                }
2021            }
2022
2023            _ => Err(eyre!("No model to update")),
2024        }
2025    }
2026}
2027
2028impl GetSingleAtom for PythonState {
2029    fn get_single_atom(&self) -> Result<Atom, NumeratorStateError> {
2030        match self {
2031            PythonState::Global(state) => {
2032                if let Some(s) = state {
2033                    s.get_single_atom()
2034                } else {
2035                    Err(NumeratorStateError::NoneVariant)
2036                }
2037            }
2038            PythonState::AppliedFeynmanRule(state) => {
2039                if let Some(s) = state {
2040                    s.get_single_atom()
2041                } else {
2042                    Err(NumeratorStateError::NoneVariant)
2043                }
2044            }
2045            PythonState::ColorSimplified(state) => {
2046                if let Some(s) = state {
2047                    s.get_single_atom()
2048                } else {
2049                    Err(NumeratorStateError::NoneVariant)
2050                }
2051            }
2052            PythonState::GammaSimplified(state) => {
2053                if let Some(s) = state {
2054                    s.get_single_atom()
2055                } else {
2056                    Err(NumeratorStateError::NoneVariant)
2057                }
2058            }
2059            _ => Err(NumeratorStateError::Expanded),
2060        }
2061    }
2062}