Skip to main content

spenso_hep_lib/
lib.rs

1use std::{ops::Neg, sync::LazyLock};
2
3use idenso::{
4    IndexTooling,
5    color::CS,
6    dirac::{AGS, spinor_matrix_structure},
7    representations::initialize,
8};
9
10use spenso::{
11    algebra::complex::Complex,
12    network::{
13        Network,
14        library::{
15            LibraryTensor, TensorLibraryData,
16            function_lib::{INBUILTS, PanicMissingConcrete, SymbolLib},
17            symbolic::{ExplicitKey, TensorLibrary},
18        },
19        parsing::ShadowedStructure,
20        store::NetworkStore,
21    },
22    structure::{
23        Canonicalized, TensorDataLayout, TensorStructure, abstract_index::AbstractIndex,
24        slot::AbsInd,
25    },
26    tensors::{
27        complex::RealOrComplexTensor,
28        data::{SetTensorData, SparseTensor, StorageTensor},
29        parametric::{MixedTensor, ParamTensor},
30    },
31};
32use symbolica::{
33    atom::{Atom, Symbol},
34    parse_lit,
35};
36
37/// Nonzero Weyl-basis entries of the UFO charge-conjugation matrix C = -i γ² γ⁰.
38pub const CHARGE_CONJUGATION_WEYL_COMPONENTS: [([usize; 2], i8); 4] =
39    [([0, 1], -1), ([1, 0], 1), ([2, 3], 1), ([3, 2], -1)];
40
41struct LogicalSparseInput<T, N> {
42    layout: TensorDataLayout,
43    storage: SparseTensor<T, N>,
44}
45
46impl<T, N: TensorStructure> LogicalSparseInput<T, N> {
47    fn set(&mut self, indices: &[usize], value: T) -> Result<(), &'static str> {
48        let storage_indices = self
49            .layout
50            .logical_expanded_to_storage_expanded(indices)
51            .map_err(|_| "hard-coded logical coordinate must be in bounds")?;
52        self.storage
53            .set(&storage_indices, value)
54            .map_err(|_| "translated storage coordinate must be in bounds")
55    }
56}
57
58fn sparse_from_logical<T, N>(
59    structure: Canonicalized<N>,
60    zero: T,
61    build: impl FnOnce(&mut LogicalSparseInput<T, N>),
62) -> Canonicalized<SparseTensor<T, N>>
63where
64    N: TensorStructure,
65{
66    let layout = TensorDataLayout::from_canonicalized(&structure)
67        .expect("hard-coded tensor data requires concrete dimensions");
68    structure.map_canonical(|structure| {
69        let mut input = LogicalSparseInput {
70            layout,
71            storage: SparseTensor::empty(structure, zero),
72        };
73        build(&mut input);
74        input.storage
75    })
76}
77
78#[allow(clippy::similar_names)]
79pub fn gamma_data_dirac<T, N>(
80    structure: Canonicalized<N>,
81    one: T,
82    zero: T,
83) -> Canonicalized<SparseTensor<Complex<T>, N>>
84where
85    T: Clone + Neg<Output = T>,
86    N: TensorStructure,
87{
88    let c1 = Complex::<T>::new(one.clone(), zero.clone());
89    let z = Complex::<T>::new(zero.clone(), zero.clone());
90    let cn1 = Complex::<T>::new(-one.clone(), zero.clone());
91    let ci = Complex::<T>::new(zero.clone(), one.clone());
92    let cni = Complex::<T>::new(zero.clone(), -one.clone());
93    sparse_from_logical(structure, z, |gamma| {
94        // Coordinates follow the public logical order: bispinor row, bispinor
95        // column, Minkowski. The layout maps them into canonical storage.
96
97        // dirac gamma matrices
98
99        gamma.set(&[0, 0, 0], c1.clone()).unwrap();
100        gamma.set(&[1, 1, 0], c1.clone()).unwrap();
101        gamma.set(&[2, 2, 0], cn1.clone()).unwrap();
102        gamma.set(&[3, 3, 0], cn1.clone()).unwrap();
103
104        gamma.set(&[0, 3, 1], c1.clone()).unwrap();
105        gamma.set(&[1, 2, 1], c1.clone()).unwrap();
106        gamma.set(&[2, 1, 1], cn1.clone()).unwrap();
107        gamma.set(&[3, 0, 1], cn1.clone()).unwrap();
108
109        gamma.set(&[0, 3, 2], cni.clone()).unwrap();
110        gamma.set(&[1, 2, 2], ci.clone()).unwrap();
111        gamma.set(&[2, 1, 2], ci.clone()).unwrap();
112        gamma.set(&[3, 0, 2], cni.clone()).unwrap();
113
114        gamma.set(&[0, 2, 3], c1.clone()).unwrap();
115        gamma.set(&[1, 3, 3], cn1.clone()).unwrap();
116        gamma.set(&[2, 0, 3], cn1.clone()).unwrap();
117        gamma.set(&[3, 1, 3], c1.clone()).unwrap();
118
119        // gamma.to_dense()
120    })
121}
122
123#[allow(clippy::similar_names)]
124pub fn gamma_data_weyl<T, N>(
125    structure: Canonicalized<N>,
126    one: T,
127    zero: T,
128) -> Canonicalized<SparseTensor<Complex<T>, N>>
129where
130    T: Neg<Output = T> + Clone,
131    N: TensorStructure,
132{
133    let z = Complex::<T>::new(zero.clone(), zero.clone());
134    let c1 = Complex::<T>::new(one.clone(), zero.clone());
135    let cn1 = Complex::<T>::new(-one.clone(), zero.clone());
136    let ci = Complex::<T>::new(zero.clone(), one.clone());
137    let cni = Complex::<T>::new(zero.clone(), -one.clone());
138    sparse_from_logical(structure, z, |gamma| {
139        // Coordinates follow the public logical order: bispinor row, bispinor
140        // column, Minkowski. The layout maps them into canonical storage.
141
142        // dirac gamma matrices
143
144        gamma.set(&[0, 2, 0], c1.clone()).unwrap();
145        gamma.set(&[1, 3, 0], c1.clone()).unwrap();
146        gamma.set(&[2, 0, 0], c1.clone()).unwrap();
147        gamma.set(&[3, 1, 0], c1.clone()).unwrap();
148
149        gamma.set(&[0, 3, 1], c1.clone()).unwrap();
150        gamma.set(&[1, 2, 1], c1.clone()).unwrap();
151        gamma.set(&[2, 1, 1], cn1.clone()).unwrap();
152        gamma.set(&[3, 0, 1], cn1.clone()).unwrap();
153
154        gamma.set(&[0, 3, 2], cni.clone()).unwrap();
155        gamma.set(&[1, 2, 2], ci.clone()).unwrap();
156        gamma.set(&[2, 1, 2], ci.clone()).unwrap();
157        gamma.set(&[3, 0, 2], cni.clone()).unwrap();
158
159        gamma.set(&[0, 2, 3], c1.clone()).unwrap();
160        gamma.set(&[1, 3, 3], cn1.clone()).unwrap();
161        gamma.set(&[2, 0, 3], cn1.clone()).unwrap();
162        gamma.set(&[3, 1, 3], c1.clone()).unwrap();
163
164        // gamma.to_dense()
165    })
166}
167
168#[allow(clippy::similar_names)]
169pub fn gamma_transpose_weyl<T, N>(
170    structure: Canonicalized<N>,
171    one: T,
172    zero: T,
173) -> Canonicalized<SparseTensor<Complex<T>, N>>
174where
175    T: Neg<Output = T> + Clone,
176    N: TensorStructure,
177{
178    let z = Complex::<T>::new(zero.clone(), zero.clone());
179    let c1 = Complex::<T>::new(one.clone(), zero.clone());
180    let cn1 = Complex::<T>::new(-one.clone(), zero.clone());
181    let ci = Complex::<T>::new(zero.clone(), one.clone());
182    let cni = Complex::<T>::new(zero.clone(), -one.clone());
183    sparse_from_logical(structure, z, |gamma| {
184        // Coordinates follow the public logical order: bispinor row, bispinor
185        // column, Minkowski. The layout maps them into canonical storage.
186
187        // dirac gamma matrices
188
189        gamma.set(&[2, 0, 0], c1.clone()).unwrap();
190        gamma.set(&[3, 1, 0], c1.clone()).unwrap();
191        gamma.set(&[0, 2, 0], c1.clone()).unwrap();
192        gamma.set(&[1, 3, 0], c1.clone()).unwrap();
193
194        gamma.set(&[3, 0, 1], c1.clone()).unwrap();
195        gamma.set(&[2, 1, 1], c1.clone()).unwrap();
196        gamma.set(&[1, 2, 1], cn1.clone()).unwrap();
197        gamma.set(&[0, 3, 1], cn1.clone()).unwrap();
198
199        gamma.set(&[3, 0, 2], cni.clone()).unwrap();
200        gamma.set(&[2, 1, 2], ci.clone()).unwrap();
201        gamma.set(&[1, 2, 2], ci.clone()).unwrap();
202        gamma.set(&[0, 3, 2], cni.clone()).unwrap();
203
204        gamma.set(&[2, 0, 3], c1.clone()).unwrap();
205        gamma.set(&[3, 1, 3], cn1.clone()).unwrap();
206        gamma.set(&[0, 2, 3], cn1.clone()).unwrap();
207        gamma.set(&[1, 3, 3], c1.clone()).unwrap();
208
209        // gamma.to_dense()
210    })
211}
212
213#[allow(clippy::similar_names)]
214pub fn gamma_conj_data_weyl<T, N>(
215    structure: Canonicalized<N>,
216    one: T,
217    zero: T,
218) -> Canonicalized<SparseTensor<Complex<T>, N>>
219where
220    T: Neg<Output = T> + Clone,
221    N: TensorStructure,
222{
223    gamma_data_weyl(structure, one, zero).map_canonical(|tensor| {
224        tensor.map_data(|a| {
225            let Complex { re, im } = a;
226            Complex { re, im: -im }
227        })
228    })
229}
230
231#[allow(clippy::similar_names)]
232pub fn gamma_adj_data_weyl<T, N>(
233    structure: Canonicalized<N>,
234    one: T,
235    zero: T,
236) -> Canonicalized<SparseTensor<Complex<T>, N>>
237where
238    T: Neg<Output = T> + Clone,
239    N: TensorStructure,
240{
241    gamma_transpose_weyl(structure, one, zero).map_canonical(|tensor| {
242        tensor.map_data(|a| {
243            let Complex { re, im } = a;
244            Complex { re, im: -im }
245        })
246    })
247}
248
249pub fn gamma0_weyl<T, N>(
250    structure: Canonicalized<N>,
251    one: T,
252    zero: T,
253) -> Canonicalized<SparseTensor<Complex<T>, N>>
254where
255    T: Clone,
256    N: TensorStructure,
257{
258    let c1 = Complex::<T>::new(one, zero.clone());
259    let z = Complex::<T>::new(zero.clone(), zero.clone());
260    sparse_from_logical(structure, z, |gamma0| {
261        // ! No check on actual structure, should expext bis,bis,lor
262
263        // dirac gamma0 matrices
264
265        gamma0.set(&[0, 2], c1.clone()).unwrap();
266        gamma0.set(&[1, 3], c1.clone()).unwrap();
267        gamma0.set(&[2, 0], c1.clone()).unwrap();
268        gamma0.set(&[3, 1], c1.clone()).unwrap();
269    })
270}
271
272pub fn gamma5_dirac_data<T, N>(
273    structure: Canonicalized<N>,
274    one: T,
275    zero: T,
276) -> Canonicalized<SparseTensor<Complex<T>, N>>
277where
278    T: Clone,
279    N: TensorStructure,
280{
281    let c1 = Complex::<T>::new(one, zero.clone());
282
283    let z = Complex::<T>::new(zero.clone(), zero.clone());
284    sparse_from_logical(structure, z, |gamma5| {
285        gamma5.set(&[0, 2], c1.clone()).unwrap();
286        gamma5.set(&[1, 3], c1.clone()).unwrap();
287        gamma5.set(&[2, 0], c1.clone()).unwrap();
288        gamma5.set(&[3, 1], c1.clone()).unwrap();
289    })
290}
291
292pub fn gamma5_weyl_data<T, N>(
293    structure: Canonicalized<N>,
294    one: T,
295    zero: T,
296) -> Canonicalized<SparseTensor<Complex<T>, N>>
297where
298    T: Clone + Neg<Output = T>,
299    N: TensorStructure,
300{
301    let z = Complex::<T>::new(zero.clone(), zero.clone());
302    let c1 = Complex::<T>::new(one, zero);
303
304    sparse_from_logical(structure, z, |gamma5| {
305        gamma5.set(&[0, 0], -c1.clone()).unwrap();
306        gamma5.set(&[1, 1], -c1.clone()).unwrap();
307        gamma5.set(&[2, 2], c1.clone()).unwrap();
308        gamma5.set(&[3, 3], c1.clone()).unwrap();
309    })
310}
311
312#[allow(clippy::similar_names)]
313pub fn proj_m_data_dirac<T, N>(
314    structure: Canonicalized<N>,
315    half: T,
316    zero: T,
317) -> Canonicalized<SparseTensor<Complex<T>, N>>
318where
319    T: Clone + Neg<Output = T>,
320    N: TensorStructure,
321{
322    let z = Complex::<T>::new(zero.clone(), zero.clone());
323    // ProjM(1,2) Left chirality projector (( 1−γ5)/ 2 )_s1_s2
324
325    let chalf = Complex::<T>::new(half.clone(), zero.clone());
326    let cnhalf = Complex::<T>::new(-half, zero);
327
328    sparse_from_logical(structure, z, |proj_m| {
329        proj_m.set(&[0, 0], chalf.clone()).unwrap();
330        proj_m.set(&[1, 1], chalf.clone()).unwrap();
331        proj_m.set(&[2, 2], chalf.clone()).unwrap();
332        proj_m.set(&[3, 3], chalf.clone()).unwrap();
333
334        proj_m.set(&[0, 2], cnhalf.clone()).unwrap();
335        proj_m.set(&[1, 3], cnhalf.clone()).unwrap();
336        proj_m.set(&[2, 0], cnhalf.clone()).unwrap();
337        proj_m.set(&[3, 1], cnhalf.clone()).unwrap();
338    })
339}
340
341#[allow(clippy::similar_names)]
342pub fn proj_m_data_weyl<T, N>(
343    structure: Canonicalized<N>,
344    one: T,
345    zero: T,
346) -> Canonicalized<SparseTensor<Complex<T>, N>>
347where
348    T: Clone,
349    N: TensorStructure,
350{
351    let z = Complex::<T>::new(zero.clone(), zero.clone());
352    // ProjM(1,2) Left chirality projector (( 1−γ5)/ 2 )_s1_s2
353    let c1 = Complex::<T>::new(one, zero);
354    sparse_from_logical(structure, z, |proj_m| {
355        proj_m.set(&[0, 0], c1.clone()).unwrap();
356        proj_m.set(&[1, 1], c1.clone()).unwrap();
357    })
358}
359
360pub fn proj_p_data_dirac<T, N>(
361    structure: Canonicalized<N>,
362    half: T,
363    zero: T,
364) -> Canonicalized<SparseTensor<Complex<T>, N>>
365where
366    T: Clone,
367    N: TensorStructure,
368{
369    let z = Complex::<T>::new(zero.clone(), zero.clone());
370    // ProjP(1,2) Right chirality projector (( 1+γ5)/ 2 )_s1_s2
371    let chalf = Complex::<T>::new(half, zero);
372
373    sparse_from_logical(structure, z, |proj_p| {
374        proj_p
375            .set(&[0, 0], chalf.clone())
376            .unwrap_or_else(|_| unreachable!());
377        proj_p
378            .set(&[1, 1], chalf.clone())
379            .unwrap_or_else(|_| unreachable!());
380        proj_p
381            .set(&[2, 2], chalf.clone())
382            .unwrap_or_else(|_| unreachable!());
383        proj_p
384            .set(&[3, 3], chalf.clone())
385            .unwrap_or_else(|_| unreachable!());
386
387        proj_p
388            .set(&[0, 2], chalf.clone())
389            .unwrap_or_else(|_| unreachable!());
390        proj_p
391            .set(&[1, 3], chalf.clone())
392            .unwrap_or_else(|_| unreachable!());
393        proj_p
394            .set(&[2, 0], chalf.clone())
395            .unwrap_or_else(|_| unreachable!());
396        proj_p
397            .set(&[3, 1], chalf.clone())
398            .unwrap_or_else(|_| unreachable!());
399    })
400}
401
402#[allow(clippy::similar_names)]
403pub fn proj_p_data_weyl<T, N>(
404    structure: Canonicalized<N>,
405    one: T,
406    zero: T,
407) -> Canonicalized<SparseTensor<Complex<T>, N>>
408where
409    T: Clone,
410    N: TensorStructure,
411{
412    let z = Complex::<T>::new(zero.clone(), zero.clone());
413    // ProjM(1,2) Left chirality projector (( 1−γ5)/ 2 )_s1_s2
414    let c1 = Complex::<T>::new(one, zero);
415    sparse_from_logical(structure, z, |proj_p| {
416        proj_p.set(&[2, 2], c1.clone()).unwrap();
417        proj_p.set(&[3, 3], c1.clone()).unwrap();
418    })
419}
420
421/// Fundamental SU(3) generators in the normalization `Tr(T^a T^b)=1/2 delta^{ab}`.
422///
423/// The index order follows `CS.t_strct`: adjoint, fundamental, anti-fundamental.
424pub fn su3_generator_data<N>(
425    structure: Canonicalized<N>,
426) -> Canonicalized<SparseTensor<Complex<f64>, N>>
427where
428    N: TensorStructure,
429{
430    let z = Complex::new(0., 0.);
431    let h = 0.5;
432    let s = 1. / (2. * 3_f64.sqrt());
433    sparse_from_logical(structure, z, |t| {
434        t.set(&[0, 0, 1], Complex::new(h, 0.)).unwrap();
435        t.set(&[0, 1, 0], Complex::new(h, 0.)).unwrap();
436
437        t.set(&[1, 0, 1], Complex::new(0., -h)).unwrap();
438        t.set(&[1, 1, 0], Complex::new(0., h)).unwrap();
439
440        t.set(&[2, 0, 0], Complex::new(h, 0.)).unwrap();
441        t.set(&[2, 1, 1], Complex::new(-h, 0.)).unwrap();
442
443        t.set(&[3, 0, 2], Complex::new(h, 0.)).unwrap();
444        t.set(&[3, 2, 0], Complex::new(h, 0.)).unwrap();
445
446        t.set(&[4, 0, 2], Complex::new(0., -h)).unwrap();
447        t.set(&[4, 2, 0], Complex::new(0., h)).unwrap();
448
449        t.set(&[5, 1, 2], Complex::new(h, 0.)).unwrap();
450        t.set(&[5, 2, 1], Complex::new(h, 0.)).unwrap();
451
452        t.set(&[6, 1, 2], Complex::new(0., -h)).unwrap();
453        t.set(&[6, 2, 1], Complex::new(0., h)).unwrap();
454
455        t.set(&[7, 0, 0], Complex::new(s, 0.)).unwrap();
456        t.set(&[7, 1, 1], Complex::new(s, 0.)).unwrap();
457        t.set(&[7, 2, 2], Complex::new(-2. * s, 0.)).unwrap();
458    })
459}
460
461/// SU(3) structure constants for `[T^a,T^b]=i f^{abc} T^c`.
462pub fn su3_structure_f_data<N>(structure: Canonicalized<N>) -> Canonicalized<SparseTensor<f64, N>>
463where
464    N: TensorStructure,
465{
466    fn set_antisymmetric<N>(
467        f: &mut LogicalSparseInput<f64, N>,
468        a: usize,
469        b: usize,
470        c: usize,
471        value: f64,
472    ) where
473        N: TensorStructure,
474    {
475        f.set(&[a, b, c], value).unwrap();
476        f.set(&[b, c, a], value).unwrap();
477        f.set(&[c, a, b], value).unwrap();
478        f.set(&[b, a, c], -value).unwrap();
479        f.set(&[a, c, b], -value).unwrap();
480        f.set(&[c, b, a], -value).unwrap();
481    }
482
483    sparse_from_logical(structure, 0., |f| {
484        set_antisymmetric(f, 0, 1, 2, 1.);
485        set_antisymmetric(f, 0, 3, 6, 0.5);
486        set_antisymmetric(f, 0, 4, 5, -0.5);
487        set_antisymmetric(f, 1, 3, 5, 0.5);
488        set_antisymmetric(f, 1, 4, 6, 0.5);
489        set_antisymmetric(f, 2, 3, 4, 0.5);
490        set_antisymmetric(f, 2, 5, 6, -0.5);
491        set_antisymmetric(f, 3, 4, 7, 3_f64.sqrt() / 2.);
492        set_antisymmetric(f, 5, 6, 7, 3_f64.sqrt() / 2.);
493    })
494}
495
496/// Exact Atom-backed SU(3) generators, useful for symbolic tensor libraries.
497pub fn su3_generator_data_atom<N>(
498    structure: Canonicalized<N>,
499) -> Canonicalized<SparseTensor<Atom, N>>
500where
501    N: TensorStructure,
502{
503    let half = Atom::num(1) / Atom::num(2);
504    let sqrt3 = parse_lit!(sqrt(3));
505    let t8 = sqrt3.clone() / Atom::num(6);
506    sparse_from_logical(structure, Atom::Zero, |t| {
507        t.set(&[0, 0, 1], half.clone()).unwrap();
508        t.set(&[0, 1, 0], half.clone()).unwrap();
509
510        t.set(&[1, 0, 1], -Atom::i() * half.clone()).unwrap();
511        t.set(&[1, 1, 0], Atom::i() * half.clone()).unwrap();
512
513        t.set(&[2, 0, 0], half.clone()).unwrap();
514        t.set(&[2, 1, 1], -half.clone()).unwrap();
515
516        t.set(&[3, 0, 2], half.clone()).unwrap();
517        t.set(&[3, 2, 0], half.clone()).unwrap();
518
519        t.set(&[4, 0, 2], -Atom::i() * half.clone()).unwrap();
520        t.set(&[4, 2, 0], Atom::i() * half.clone()).unwrap();
521
522        t.set(&[5, 1, 2], half.clone()).unwrap();
523        t.set(&[5, 2, 1], half.clone()).unwrap();
524
525        t.set(&[6, 1, 2], -Atom::i() * half).unwrap();
526        t.set(&[6, 2, 1], Atom::i() / Atom::num(2)).unwrap();
527
528        t.set(&[7, 0, 0], t8.clone()).unwrap();
529        t.set(&[7, 1, 1], t8.clone()).unwrap();
530        t.set(&[7, 2, 2], -sqrt3 / Atom::num(3)).unwrap();
531    })
532}
533
534/// Exact Atom-backed SU(3) structure constants.
535pub fn su3_structure_f_data_atom<N>(
536    structure: Canonicalized<N>,
537) -> Canonicalized<SparseTensor<Atom, N>>
538where
539    N: TensorStructure,
540{
541    fn set_antisymmetric<N>(
542        f: &mut LogicalSparseInput<Atom, N>,
543        a: usize,
544        b: usize,
545        c: usize,
546        value: Atom,
547    ) where
548        N: TensorStructure,
549    {
550        f.set(&[a, b, c], value.clone()).unwrap();
551        f.set(&[b, c, a], value.clone()).unwrap();
552        f.set(&[c, a, b], value.clone()).unwrap();
553        f.set(&[b, a, c], -value.clone()).unwrap();
554        f.set(&[a, c, b], -value.clone()).unwrap();
555        f.set(&[c, b, a], -value).unwrap();
556    }
557
558    let half = Atom::num(1) / Atom::num(2);
559    let sqrt3_half = parse_lit!(sqrt(3)) / Atom::num(2);
560
561    sparse_from_logical(structure, Atom::Zero, |f| {
562        set_antisymmetric(f, 0, 1, 2, Atom::num(1));
563        set_antisymmetric(f, 0, 3, 6, half.clone());
564        set_antisymmetric(f, 0, 4, 5, -half.clone());
565        set_antisymmetric(f, 1, 3, 5, half.clone());
566        set_antisymmetric(f, 1, 4, 6, half.clone());
567        set_antisymmetric(f, 2, 3, 4, half.clone());
568        set_antisymmetric(f, 2, 5, 6, -half);
569        set_antisymmetric(f, 3, 4, 7, sqrt3_half.clone());
570        set_antisymmetric(f, 5, 6, 7, sqrt3_half);
571    })
572}
573
574#[allow(clippy::similar_names)]
575pub fn sigma_data<T, N>(
576    structure: Canonicalized<N>,
577    one: T,
578    zero: T,
579) -> Canonicalized<SparseTensor<Complex<T>, N>>
580where
581    T: Clone + Neg<Output = T>,
582    N: TensorStructure,
583{
584    let z = Complex::<T>::new(zero.clone(), zero.clone());
585    let c1 = Complex::<T>::new(one.clone(), zero.clone());
586    let cn1 = Complex::<T>::new(-one.clone(), zero.clone());
587    let ci = Complex::<T>::new(zero.clone(), one.clone());
588    let cni = Complex::<T>::new(zero.clone(), -one.clone());
589
590    sparse_from_logical(structure, z, |sigma| {
591        sigma.set(&[0, 2, 0, 1], c1.clone()).unwrap();
592        sigma.set(&[0, 2, 3, 0], c1.clone()).unwrap();
593        sigma.set(&[0, 3, 1, 2], c1.clone()).unwrap();
594        sigma.set(&[1, 0, 2, 2], c1.clone()).unwrap();
595        sigma.set(&[1, 1, 1, 2], c1.clone()).unwrap();
596        sigma.set(&[1, 3, 0, 2], c1.clone()).unwrap();
597        sigma.set(&[2, 2, 1, 0], c1.clone()).unwrap();
598        sigma.set(&[2, 2, 2, 1], c1.clone()).unwrap();
599        sigma.set(&[2, 3, 3, 2], c1.clone()).unwrap();
600        sigma.set(&[3, 0, 0, 2], c1.clone()).unwrap();
601        sigma.set(&[3, 3, 2, 2], c1.clone()).unwrap();
602        sigma.set(&[3, 1, 3, 2], c1.clone()).unwrap();
603        sigma.set(&[0, 1, 3, 0], ci.clone()).unwrap();
604        sigma.set(&[0, 3, 1, 1], ci.clone()).unwrap();
605        sigma.set(&[0, 3, 2, 0], ci.clone()).unwrap();
606        sigma.set(&[1, 0, 3, 3], ci.clone()).unwrap();
607        sigma.set(&[1, 1, 0, 3], ci.clone()).unwrap();
608        sigma.set(&[1, 1, 2, 0], ci.clone()).unwrap();
609        sigma.set(&[2, 1, 1, 0], ci.clone()).unwrap();
610        sigma.set(&[2, 3, 0, 0], ci.clone()).unwrap();
611        sigma.set(&[2, 3, 3, 1], ci.clone()).unwrap();
612        sigma.set(&[3, 0, 1, 3], ci.clone()).unwrap();
613        sigma.set(&[3, 1, 0, 0], ci.clone()).unwrap();
614        sigma.set(&[3, 1, 2, 3], ci.clone()).unwrap();
615        sigma.set(&[0, 0, 3, 2], cn1.clone()).unwrap();
616        sigma.set(&[0, 1, 0, 2], cn1.clone()).unwrap();
617        sigma.set(&[0, 2, 1, 3], cn1.clone()).unwrap();
618        sigma.set(&[1, 2, 0, 3], cn1.clone()).unwrap();
619        sigma.set(&[1, 2, 1, 1], cn1.clone()).unwrap();
620        sigma.set(&[1, 2, 2, 0], cn1.clone()).unwrap();
621        sigma.set(&[2, 0, 1, 2], cn1.clone()).unwrap();
622        sigma.set(&[2, 1, 2, 2], cn1.clone()).unwrap();
623        sigma.set(&[2, 2, 3, 3], cn1.clone()).unwrap();
624        sigma.set(&[3, 2, 0, 0], cn1.clone()).unwrap();
625        sigma.set(&[3, 2, 2, 3], cn1.clone()).unwrap();
626        sigma.set(&[3, 2, 3, 1], cn1.clone()).unwrap();
627        sigma.set(&[0, 0, 2, 3], cni.clone()).unwrap();
628        sigma.set(&[0, 0, 3, 1], cni.clone()).unwrap();
629        sigma.set(&[0, 1, 1, 3], cni.clone()).unwrap();
630        sigma.set(&[1, 0, 2, 1], cni.clone()).unwrap();
631        sigma.set(&[1, 3, 0, 1], cni.clone()).unwrap();
632        sigma.set(&[1, 3, 3, 0], cni.clone()).unwrap();
633        sigma.set(&[2, 0, 0, 3], cni.clone()).unwrap();
634        sigma.set(&[2, 0, 1, 1], cni.clone()).unwrap();
635        sigma.set(&[2, 1, 3, 3], cni.clone()).unwrap();
636        sigma.set(&[3, 0, 0, 1], cni.clone()).unwrap();
637        sigma.set(&[3, 3, 1, 0], cni.clone()).unwrap();
638        sigma.set(&[3, 3, 2, 1], cni.clone()).unwrap();
639    })
640}
641
642pub fn hep_lib<Aind: AbsInd, T: TensorLibraryData + Clone + Default>(
643    one: T,
644    zero: T,
645) -> TensorLibrary<MixedTensor<T, ExplicitKey<Aind>>, Aind>
646where
647{
648    let mut weyl = TensorLibrary::new();
649    initialize();
650    weyl.update_ids();
651
652    let gamma_key = gamma_data_weyl(AGS.gamma_strct::<Aind>(4), one.clone(), zero.clone())
653        .map_canonical(Into::into);
654    // println!("layout{:?}", gamma_key.layout());
655    weyl.insert_explicit(gamma_key);
656    let gamma_conj_key =
657        gamma_conj_data_weyl(AGS.gamma_conj_strct::<Aind>(4), one.clone(), zero.clone())
658            .map_canonical(Into::into);
659    // println!("layout{:?}", gamma_key.layout());
660    weyl.insert_explicit(gamma_conj_key);
661    let gamma_adj_key =
662        gamma_adj_data_weyl(AGS.gamma_adj_strct::<Aind>(4), one.clone(), zero.clone())
663            .map_canonical(Into::into);
664    // println!("layout{:?}", gamma_key.layout());
665    weyl.insert_explicit(gamma_adj_key);
666    let gamma0_key = gamma0_weyl(AGS.gamma0_strct::<Aind>(4), one.clone(), zero.clone())
667        .map_canonical(Into::into);
668    // println!("layout{:?}", gamma_key.layout());
669    weyl.insert_explicit(gamma0_key);
670
671    let gamma5_key = gamma5_weyl_data(AGS.gamma5_strct::<Aind>(4), one.clone(), zero.clone())
672        .map_canonical(Into::into);
673    weyl.insert_explicit(gamma5_key);
674
675    let projm_key = proj_m_data_weyl(AGS.projm_strct::<Aind>(4), one.clone(), zero.clone())
676        .map_canonical(Into::into);
677    weyl.insert_explicit(projm_key);
678
679    let projp_key = proj_p_data_weyl(AGS.projp_strct::<Aind>(4), one.clone(), zero.clone())
680        .map_canonical(Into::into);
681    weyl.insert_explicit(projp_key);
682
683    let charge_conjugation = sparse_from_logical(
684        spinor_matrix_structure::<Aind>(AGS.charge_conjugation, 4),
685        Complex::new(zero.clone(), zero.clone()),
686        |tensor| {
687            for (indices, sign) in CHARGE_CONJUGATION_WEYL_COMPONENTS {
688                let value = if sign < 0 { -one.clone() } else { one.clone() };
689                tensor
690                    .set(&indices, Complex::new(value, zero.clone()))
691                    .unwrap();
692            }
693        },
694    )
695    .map_canonical(Into::into);
696    weyl.insert_explicit(charge_conjugation);
697
698    weyl
699}
700
701pub fn insert_su3_color_tensors<Aind: AbsInd>(
702    lib: &mut TensorLibrary<MixedTensor<f64, ExplicitKey<Aind>>, Aind>,
703) {
704    initialize();
705
706    let t_key = su3_generator_data(CS.t_strct::<Aind>(3, 8)).map_canonical(Into::into);
707    lib.insert_explicit(t_key);
708
709    let f_key = su3_structure_f_data(CS.f_strct::<Aind>(8)).map_canonical(Into::into);
710    lib.insert_explicit(f_key);
711}
712
713pub fn hep_lib_su3<Aind: AbsInd>() -> TensorLibrary<MixedTensor<f64, ExplicitKey<Aind>>, Aind> {
714    let mut lib = hep_lib(1., 0.);
715    insert_su3_color_tensors(&mut lib);
716    lib
717}
718
719pub fn hep_lib_atom<Aind: AbsInd, T>() -> TensorLibrary<T, Aind>
720where
721    T: LibraryTensor<Structure = ExplicitKey<Aind>>
722        + SetTensorData<SetData = <T as LibraryTensor>::Data>
723        + Clone
724        + From<ParamTensor<ExplicitKey<Aind>>>,
725    <T as LibraryTensor>::Data: TensorLibraryData,
726{
727    let mut weyl = TensorLibrary::new();
728    initialize();
729    weyl.update_ids_from::<ParamTensor<ExplicitKey<Aind>>>();
730
731    let one = Atom::one();
732    let zero = Atom::Zero;
733
734    let gamma_key = gamma_data_weyl(AGS.gamma_strct::<Aind>(4), one.clone(), zero.clone())
735        .map_canonical(|tensor| {
736            ParamTensor::param(tensor.map_data(|a| a.re + a.im * Atom::i()).into()).into()
737        });
738    // println!("layout{:?}", gamma_key.layout());
739    weyl.insert_explicit(gamma_key);
740    let gamma_conj_key =
741        gamma_conj_data_weyl(AGS.gamma_conj_strct::<Aind>(4), one.clone(), zero.clone())
742            .map_canonical(|tensor| {
743                ParamTensor::param(tensor.map_data(|a| a.re + a.im * Atom::i()).into()).into()
744            });
745    // println!("layout{:?}", gamma_key.layout());
746    weyl.insert_explicit(gamma_conj_key);
747    let gamma_adj_key =
748        gamma_adj_data_weyl(AGS.gamma_adj_strct::<Aind>(4), one.clone(), zero.clone())
749            .map_canonical(|tensor| {
750                ParamTensor::param(tensor.map_data(|a| a.re + a.im * Atom::i()).into()).into()
751            });
752    // println!("layout{:?}", gamma_key.layout());
753    weyl.insert_explicit(gamma_adj_key);
754    let gamma0_key = gamma0_weyl(AGS.gamma0_strct::<Aind>(4), one.clone(), zero.clone())
755        .map_canonical(|tensor| {
756            ParamTensor::param(tensor.map_data(|a| a.re + a.im * Atom::i()).into()).into()
757        });
758    // println!("layout{:?}", gamma_key.layout());
759    weyl.insert_explicit(gamma0_key);
760
761    let gamma5_key = gamma5_weyl_data(AGS.gamma5_strct::<Aind>(4), one.clone(), zero.clone())
762        .map_canonical(|tensor| {
763            ParamTensor::param(tensor.map_data(|a| a.re + a.im * Atom::i()).into()).into()
764        });
765    weyl.insert_explicit(gamma5_key);
766
767    let projm_key = proj_m_data_weyl(AGS.projm_strct::<Aind>(4), one.clone(), zero.clone())
768        .map_canonical(|tensor| {
769            ParamTensor::param(tensor.map_data(|a| a.re + a.im * Atom::i()).into()).into()
770        });
771    weyl.insert_explicit(projm_key);
772
773    let projp_key = proj_p_data_weyl(AGS.projp_strct::<Aind>(4), one.clone(), zero.clone())
774        .map_canonical(|tensor| {
775            ParamTensor::param(tensor.map_data(|a| a.re + a.im * Atom::i()).into()).into()
776        });
777    weyl.insert_explicit(projp_key);
778
779    let charge_conjugation = sparse_from_logical(
780        spinor_matrix_structure::<Aind>(AGS.charge_conjugation, 4),
781        Atom::Zero,
782        |tensor| {
783            for (indices, sign) in CHARGE_CONJUGATION_WEYL_COMPONENTS {
784                tensor.set(&indices, Atom::num(sign)).unwrap();
785            }
786        },
787    )
788    .map_canonical(|tensor| ParamTensor::param(tensor.into()).into());
789    weyl.insert_explicit(charge_conjugation);
790
791    let color_t_key = su3_generator_data_atom(CS.t_strct::<Aind>(3, 8))
792        .map_canonical(|tensor| ParamTensor::param(tensor.into()).into());
793    weyl.insert_explicit(color_t_key);
794
795    let color_f_key = su3_structure_f_data_atom(CS.f_strct::<Aind>(8))
796        .map_canonical(|tensor| ParamTensor::param(tensor.into()).into());
797    weyl.insert_explicit(color_f_key);
798
799    weyl
800}
801
802pub type HepTensor<Aind> = MixedTensor<f64, ShadowedStructure<Aind>>;
803
804pub type HepNet<Aind> =
805    Network<NetworkStore<HepTensor<Aind>, Atom>, ExplicitKey<Aind>, Symbol, Aind>;
806
807pub static HEP_LIB: LazyLock<
808    TensorLibrary<MixedTensor<f64, ExplicitKey<AbstractIndex>>, AbstractIndex>,
809> = LazyLock::new(hep_lib_atom);
810
811pub static FUN_LIB: LazyLock<
812    SymbolLib<RealOrComplexTensor<f64, ShadowedStructure<AbstractIndex>>, PanicMissingConcrete>,
813> = LazyLock::new(|| {
814    let mut lib = PanicMissingConcrete::new_lib();
815    lib.insert(INBUILTS.conj, |a| match a {
816        RealOrComplexTensor::Complex(c) => RealOrComplexTensor::Complex(c.map_data(|x| x.conj())),
817        RealOrComplexTensor::Real(r) => RealOrComplexTensor::Real(r),
818    });
819    lib.insert_scalar_fallible(INBUILTS.conj, |scalar| Ok(scalar.spenso_conj()));
820    lib
821});
822
823#[cfg(test)]
824mod tests {
825
826    use idenso::representations::{Bispinor, ColorAdjoint, ColorFundamental};
827    use spenso::network::MinResultRank;
828    use spenso::network::library::function_lib::Wrap;
829    use spenso::{
830        network::{
831            ExecutionResult, MinIntermediateCost, Network, Sequential, SingleSmallestDegree,
832            SmallestDegree, SmallestDegreeIter, Steps,
833            library::symbolic::ETS,
834            parsing::{ParseSettings, ShadowedStructure, StrictTensorFilter},
835            store::NetworkStore,
836            tags::SPENSO_TAG,
837        },
838        structure::{
839            HasStructure,
840            abstract_index::AbstractIndex,
841            representation::{Minkowski, RepName},
842        },
843        tensors::data::{DenseTensor, GetTensorData, SparseOrDense},
844    };
845    use symbolica::{
846        atom::{Atom, Symbol},
847        parse, parse_lit,
848    };
849
850    use super::*;
851
852    fn exact_default_scalar(expression: Atom) -> Atom {
853        let mut network = HepNet::<AbstractIndex>::try_from_view(
854            expression.as_view(),
855            &*HEP_LIB,
856            &ParseSettings::default().with_strict_tensor_filter(StrictTensorFilter::ContainsReps),
857        )
858        .unwrap();
859        network
860            .execute::<Sequential, MinIntermediateCost, _, _, _>(&*HEP_LIB, &*FUN_LIB)
861            .unwrap();
862        match network.result_tensor(&*HEP_LIB).unwrap() {
863            ExecutionResult::One => Atom::one(),
864            ExecutionResult::Zero => Atom::zero(),
865            ExecutionResult::Val(value) => value.into_owned().scalar().unwrap().into(),
866        }
867    }
868
869    #[test]
870    fn default_library_keeps_generic_metrics_exact() {
871        // Dimensions deliberately differ from the explicit four-dimensional HEP
872        // entries: exactness belongs to the generic metric factories.
873        let mink = Minkowski {}.new_rep(7);
874        let bis = Bispinor {}.new_rep(6);
875        let coad = ColorAdjoint {}.new_rep(11);
876        let cof = ColorFundamental {}.new_rep(5);
877        for (representations, dimension, lorentzian) in [
878            ([mink.to_lib(); 2], 7, true),
879            ([bis.to_lib(); 2], 6, false),
880            ([coad.to_lib(); 2], 11, false),
881            ([cof.to_lib(), cof.dual().to_lib()], 5, false),
882        ] {
883            let key = ExplicitKey::from_iter(representations, ETS.metric, None);
884            let metric = HEP_LIB
885                .get_storage(key.canonical())
886                .unwrap()
887                .into_owned()
888                .try_into_parametric()
889                .expect("exact default metric components")
890                .to_dense();
891            for row in 0..dimension {
892                for column in 0..dimension {
893                    let expected = if row != column {
894                        0
895                    } else if lorentzian && row > 0 {
896                        -1
897                    } else {
898                        1
899                    };
900                    assert_eq!(
901                        metric.get_owned([row, column]).unwrap(),
902                        Atom::num(expected)
903                    );
904                }
905            }
906        }
907        let numeric = hep_lib_su3::<AbstractIndex>();
908        let key = ExplicitKey::from_iter([mink.to_lib(); 2], ETS.metric, None);
909        assert!(
910            numeric
911                .get_storage(key.canonical())
912                .unwrap()
913                .into_owned()
914                .try_into_concrete()
915                .is_ok()
916        );
917    }
918
919    #[test]
920    fn default_component_contractions_preserve_exact_symbolic_coefficients() {
921        initialize();
922        let color = parse!(
923            "x/7*f(coad(8,a),coad(8,b),coad(8,c))^2",
924            default_namespace = "spenso"
925        );
926        assert_eq!(
927            exact_default_scalar(color),
928            parse!("24*x/7", default_namespace = "spenso")
929        );
930        let trace = parse!(
931            "x/7*spenso::gamma(bis(4,i),bis(4,j),mink(4,mu))*spenso::gamma(bis(4,j),bis(4,i),mink(4,mu))",
932            default_namespace = "spenso"
933        );
934        assert_eq!(
935            exact_default_scalar(trace),
936            parse!("16*x/7", default_namespace = "spenso")
937        );
938
939        let mut library =
940            hep_lib_atom::<AbstractIndex, MixedTensor<f64, ExplicitKey<AbstractIndex>>>();
941        let vector = SPENSO_TAG.rank_one_tensor_symbol("exact_default_momentum");
942        let key = ExplicitKey::from_iter([Minkowski {}.new_rep(4).to_lib()], vector, None);
943        library.insert_explicit(key.map_canonical(|structure| {
944            MixedTensor::Param(ParamTensor::param(
945                DenseTensor::from_storage_data(
946                    vec![
947                        parse!("x/3", default_namespace = "spenso"),
948                        parse!("1/5"),
949                        parse!("-2/7"),
950                        parse!("3/11"),
951                    ],
952                    structure,
953                )
954                .unwrap()
955                .into(),
956            ))
957        }));
958        let source = parse!(
959            "g(mink(4,a),mink(4,b))*exact_default_momentum(mink(4,a))*exact_default_momentum(mink(4,b))",
960            default_namespace = "spenso"
961        );
962        let mut network =
963            HepNet::try_from_view(source.as_view(), &library, &ParseSettings::default()).unwrap();
964        network
965            .execute::<Sequential, MinIntermediateCost, _, _, _>(&library, &*FUN_LIB)
966            .unwrap();
967        let ExecutionResult::Val(value) = network.result_tensor(&library).unwrap() else {
968            panic!("nonzero momentum norm")
969        };
970        let value: Atom = value.into_owned().scalar().unwrap().into();
971        assert_eq!(
972            value,
973            parse!("x^2/9-1/25-4/49-9/121", default_namespace = "spenso")
974        );
975    }
976
977    #[test]
978    fn default_components_annihilate_an_odd_color_network_exactly() {
979        initialize();
980        // K3,3 is odd under exchanging its first two left vertices: the three
981        // right f tensors each exchange two ports. This proves zero without
982        // using color-reduction formulas or the component contraction itself.
983        let source = parse!(
984            "g(coad(8,a),coad(8,j))*f(coad(8,j),coad(8,b),coad(8,c))*f(coad(8,d),coad(8,e),coad(8,f))*f(coad(8,g),coad(8,h),coad(8,i))*f(coad(8,a),coad(8,d),coad(8,g))*f(coad(8,b),coad(8,e),coad(8,h))*f(coad(8,c),coad(8,f),coad(8,i))",
985            default_namespace = "spenso"
986        );
987        assert!(!source.is_zero());
988        assert_eq!(exact_default_scalar(source), Atom::zero());
989    }
990
991    #[test]
992    fn su3_color_traces_are_independent_of_contraction_order() {
993        use spenso::network::{MinIntermediateCost, MinResultRank, library::function_lib::Wrap};
994
995        initialize();
996        type Net = Network<
997            NetworkStore<ParamTensor<ShadowedStructure<AbstractIndex>>, Atom>,
998            ExplicitKey<AbstractIndex>,
999            Symbol,
1000        >;
1001        let lib: TensorLibrary<ParamTensor<ExplicitKey<AbstractIndex>>, AbstractIndex> =
1002            hep_lib_atom();
1003        let functions: SymbolLib<ParamTensor<ShadowedStructure<AbstractIndex>>, Wrap> =
1004            Wrap::new_lib();
1005        for (expression, expected) in [
1006            // The two crossed cyclic orderings used to give -1/6 rather than -2/3.
1007            (
1008                "g(coad(8,a),coad(8,b))*g(coad(8,c),coad(8,d))*trace(cof(3),t(coad(8,a),in,out),t(coad(8,c),in,out),t(coad(8,b),in,out),t(coad(8,d),in,out))",
1009                parse!("-2/3"),
1010            ),
1011            (
1012                "1/8*(2+g(coad(8,a),coad(8,b))*g(coad(8,c),coad(8,d))*trace(cof(3),sym(t(coad(8,a),in,out),t(coad(8,b),in,out),t(coad(8,c),in,out),t(coad(8,d),in,out))))",
1013                parse!("2/3"),
1014            ),
1015            // sum_d T_d X T_d = Tr(X) I/2 - X/6 and
1016            // f_abc Tr(T_a T_b T_c) = 6i independently give -i.
1017            (
1018                "f(coad(8,a),coad(8,b),coad(8,c))*t(coad(8,a),cof(3,i0),dind(cof(3,i1)))*t(coad(8,d),cof(3,i1),dind(cof(3,i2)))*t(coad(8,b),cof(3,i2),dind(cof(3,i3)))*t(coad(8,c),cof(3,i3),dind(cof(3,i4)))*t(coad(8,d),cof(3,i4),dind(cof(3,i0)))",
1019                parse!("-1i"),
1020            ),
1021        ] {
1022            let expression = parse!(expression, default_namespace = "spenso");
1023            let original =
1024                Net::try_from_view(expression.as_view(), &lib, &ParseSettings::default()).unwrap();
1025            for prepare in [false, true] {
1026                let mut prepared = original.clone();
1027                if prepare {
1028                    prepared.graph.contract_ready_sum_boundaries();
1029                }
1030                macro_rules! check {
1031                    ($strategy:ty) => {{
1032                        let mut network = prepared.clone();
1033                        network
1034                            .execute::<Sequential, $strategy, _, _, _>(&lib, &functions)
1035                            .unwrap();
1036                        let ExecutionResult::Val(actual) = network.result_scalar().unwrap() else {
1037                            panic!("expected a scalar color trace");
1038                        };
1039                        assert_eq!(
1040                            actual.as_ref(),
1041                            &expected,
1042                            "strategy={}, prepare={prepare}",
1043                            stringify!($strategy)
1044                        );
1045                    }};
1046                }
1047                check!(SmallestDegree);
1048                check!(MinIntermediateCost);
1049                check!(MinResultRank);
1050            }
1051        }
1052    }
1053
1054    /// Two quark loops joined by gluons and a three-gluon vertex: with
1055    /// some contraction orders, one pairwise contraction matches three fundamental
1056    /// colour slots of mixed variance whose storage orders differ by a
1057    /// three-cycle. Every strategy must agree on the exact value.
1058    #[test]
1059    fn su3_two_loop_network_with_a_three_gluon_vertex_is_independent_of_contraction_order() {
1060        initialize();
1061        type Net = Network<
1062            NetworkStore<ParamTensor<ShadowedStructure<AbstractIndex>>, Atom>,
1063            ExplicitKey<AbstractIndex>,
1064            Symbol,
1065        >;
1066        let lib: TensorLibrary<ParamTensor<ExplicitKey<AbstractIndex>>, AbstractIndex> =
1067            hep_lib_atom();
1068        let functions: SymbolLib<ParamTensor<ShadowedStructure<AbstractIndex>>, Wrap> =
1069            Wrap::new_lib();
1070        // f(g4,g2,g3) Tr(T_g1 T_g3 T_g0 T_g2) Tr(T_g4 T_g1 T_g0), in shuffled factor order.
1071        let expression = parse!(
1072            "t(coad(8,g0),cof(3,q2),dind(cof(3,q3)))*t(coad(8,g1),cof(3,q0),dind(cof(3,q1)))*t(coad(8,g2),cof(3,q3),dind(cof(3,q0)))*t(coad(8,g0),cof(3,q6),dind(cof(3,q4)))*t(coad(8,g1),cof(3,q5),dind(cof(3,q6)))*f(coad(8,g4),coad(8,g2),coad(8,g3))*t(coad(8,g3),cof(3,q1),dind(cof(3,q2)))*t(coad(8,g4),cof(3,q4),dind(cof(3,q5)))",
1073            default_namespace = "spenso"
1074        );
1075        let original =
1076            Net::try_from_view(expression.as_view(), &lib, &ParseSettings::default()).unwrap();
1077        macro_rules! value {
1078            ($strategy:ty) => {{
1079                let mut network = original.clone();
1080                network
1081                    .execute::<Sequential, $strategy, _, _, _>(&lib, &functions)
1082                    .unwrap();
1083                match network.result_scalar().unwrap() {
1084                    ExecutionResult::Val(value) => value.into_owned(),
1085                    ExecutionResult::One => Atom::one(),
1086                    ExecutionResult::Zero => Atom::zero(),
1087                }
1088            }};
1089        }
1090        let reference = value!(SmallestDegree);
1091        assert_eq!(value!(MinIntermediateCost), reference);
1092        assert_eq!(value!(MinResultRank), reference);
1093    }
1094
1095    #[test]
1096    fn scalar_conjugation_execution_preserves_exact_coefficients() {
1097        initialize();
1098        let mut network =
1099            HepNet::<AbstractIndex>::from_scalar(parse!("1/3 + 2i/7")).fun(INBUILTS.conj);
1100        network
1101            .execute::<Sequential, SmallestDegree, _, _, _>(&*HEP_LIB, &*FUN_LIB)
1102            .unwrap();
1103        let ExecutionResult::Val(conjugated) = network.result_scalar().unwrap() else {
1104            panic!("conjugation should produce a scalar value")
1105        };
1106
1107        assert_eq!(conjugated.into_owned(), parse!("1/3 - 2i/7"));
1108    }
1109
1110    #[test]
1111    fn dirac_gamma_data_uses_storage_order() {
1112        initialize();
1113        let gamma =
1114            gamma_data_dirac(AGS.gamma_strct::<AbstractIndex>(4), 1_i32, 0_i32).into_canonical();
1115
1116        // The final coordinate is the Minkowski component. These are the
1117        // diagonal entries of gamma^0 in the Dirac basis.
1118        assert_eq!(*gamma.get_ref([0, 0, 0]).unwrap(), Complex::new(1, 0));
1119        assert_eq!(*gamma.get_ref([1, 1, 0]).unwrap(), Complex::new(1, 0));
1120        assert_eq!(*gamma.get_ref([2, 2, 0]).unwrap(), Complex::new(-1, 0));
1121        assert_eq!(*gamma.get_ref([3, 3, 0]).unwrap(), Complex::new(-1, 0));
1122    }
1123
1124    #[test]
1125    fn charge_conjugation_weyl_components_and_clifford_identities() {
1126        initialize();
1127        let key = spinor_matrix_structure::<AbstractIndex>(AGS.charge_conjugation, 4);
1128        let concrete_library = hep_lib::<AbstractIndex, i32>(1, 0);
1129        let concrete = concrete_library
1130            .get_storage(key.canonical())
1131            .unwrap()
1132            .into_owned()
1133            .try_into_concrete()
1134            .unwrap();
1135        let RealOrComplexTensor::Complex(charge_conjugation) = concrete else {
1136            panic!("the Weyl library stores complex matrix components");
1137        };
1138        let charge_conjugation = charge_conjugation.to_dense();
1139        let atom_library =
1140            hep_lib_atom::<AbstractIndex, MixedTensor<i32, ExplicitKey<AbstractIndex>>>();
1141        let atom_matrix = atom_library
1142            .get_storage(key.canonical())
1143            .unwrap()
1144            .into_owned()
1145            .try_into_parametric()
1146            .unwrap()
1147            .to_dense();
1148        let gamma = gamma_data_weyl(AGS.gamma_strct::<AbstractIndex>(4), 1, 0)
1149            .into_canonical()
1150            .to_dense();
1151
1152        for row in 0..4 {
1153            for column in 0..4 {
1154                let value = charge_conjugation.get_owned([row, column]).unwrap();
1155                // Derive the matrix independently from the shared Weyl gammas.
1156                let definition = (0..4).fold(Complex::new(0, 0), |sum, inner| {
1157                    sum + Complex::new(0, -1)
1158                        * gamma.get_owned([row, inner, 2]).unwrap()
1159                        * gamma.get_owned([inner, column, 0]).unwrap()
1160                });
1161                assert_eq!(value, definition);
1162                assert_eq!(value.conj(), value);
1163                assert_eq!(value, -charge_conjugation.get_owned([column, row]).unwrap());
1164                assert_eq!(
1165                    atom_matrix.get_owned([row, column]).unwrap(),
1166                    Atom::num(value.re)
1167                );
1168
1169                let square = (0..4).fold(Complex::new(0, 0), |sum, inner| {
1170                    sum + charge_conjugation.get_owned([row, inner]).unwrap()
1171                        * charge_conjugation.get_owned([inner, column]).unwrap()
1172                });
1173                assert_eq!(square, Complex::new(-i32::from(row == column), 0));
1174                for mu in 0..4 {
1175                    let mut sandwich = Complex::new(0, 0);
1176                    let mut transposed_sandwich = Complex::new(0, 0);
1177                    for first in 0..4 {
1178                        for second in 0..4 {
1179                            let left = charge_conjugation.get_owned([row, first]).unwrap();
1180                            let right = charge_conjugation.get_owned([second, column]).unwrap();
1181                            sandwich +=
1182                                left * gamma.get_owned([first, second, mu]).unwrap() * right;
1183                            transposed_sandwich +=
1184                                left * gamma.get_owned([second, first, mu]).unwrap() * right;
1185                        }
1186                    }
1187                    assert_eq!(sandwich, gamma.get_owned([column, row, mu]).unwrap());
1188                    assert_eq!(
1189                        transposed_sandwich,
1190                        gamma.get_owned([row, column, mu]).unwrap()
1191                    );
1192                }
1193            }
1194        }
1195    }
1196
1197    #[test]
1198    fn simple_scalar() {
1199        initialize();
1200        let gamma = AGS.gamma_strct(4);
1201        let _a = HEP_LIB.get(gamma.canonical()).unwrap();
1202
1203        let expr = parse!("gamma(bis(4,l_5),bis(4,l_4),mink(4,l_4))*gamma(bis(4,l_6),bis(4,l_5),mink(4,l_4))*gamma(bis(4,l_4),bis(4,l_6),mink(4,l_5))*p(mink(4,l_5))
1204            ",default_namespace="spenso");
1205        // let expr = parse!(
1206        // "gamma(bis(4,l_4),bis(4,l_6),mink(4,l_5))*p(mink(4,l_5))
1207        // ",
1208        // "spenso"
1209        // );
1210        // println!("{}", expr);
1211
1212        let mut net = Network::<
1213            NetworkStore<MixedTensor<f64, ShadowedStructure<AbstractIndex>>, Atom>,
1214            _,
1215            Symbol,
1216        >::try_from_view(
1217            expr.as_view(),
1218            &*HEP_LIB,
1219            &ParseSettings::default().with_strict_tensor_filter(StrictTensorFilter::ContainsReps),
1220        )
1221        .unwrap();
1222
1223        println!(
1224            "{}",
1225            net.dot_display_impl(
1226                |a| a.to_string(),
1227                |a| Some(format!("{}", a.global_name.unwrap())),
1228                |a| a.structure().global_name.unwrap().to_string(),
1229                |a| a.to_string()
1230            )
1231        );
1232
1233        net.execute::<Steps<1>, SmallestDegreeIter<1>, _, _, _>(&*HEP_LIB, &*FUN_LIB)
1234            .unwrap();
1235        println!(
1236            "{}",
1237            net.dot_display_impl(
1238                |a| a.to_string(),
1239                |a| Some(format!("{}", a.global_name?)),
1240                |a| a
1241                    .structure()
1242                    .global_name
1243                    .map(|a| a.to_string())
1244                    .unwrap_or("".to_string()),
1245                |a| a.to_string()
1246            )
1247        );
1248        net.execute::<Steps<1>, SmallestDegreeIter<2>, _, _, _>(&*HEP_LIB, &*FUN_LIB)
1249            .unwrap();
1250        println!(
1251            "{}",
1252            net.dot_display_impl(
1253                |a| a.to_string(),
1254                |a| Some(format!("{}", a.global_name?)),
1255                |a| a
1256                    .structure()
1257                    .global_name
1258                    .map(|a| a.to_string())
1259                    .unwrap_or("".to_string()),
1260                |a| a.to_string()
1261            )
1262        );
1263
1264        println!(
1265            "{}",
1266            net.dot_display_impl(
1267                |a| a.to_string(),
1268                |_| None,
1269                |a| a.to_string(),
1270                |a| a.to_string()
1271            )
1272        );
1273        // if let ExecutionResult::Val(TensorOrScalarOrKey::Tensor { tensor, .. }) =
1274        //     net.result().unwrap()
1275        // {
1276        //     // println!("YaY:{}", (&expr - &tensor.expression).expand());
1277        //     // assert_eq!(expr, tensor.expression);
1278        // } else {
1279        //     panic!("Not tensor")
1280        // }
1281    }
1282
1283    #[test]
1284    // #[should_panic]
1285    fn parse_problem() {
1286        initialize();
1287        let gamma = AGS.gamma_strct(4);
1288        let _a = HEP_LIB.get(gamma.canonical()).unwrap();
1289
1290        let expr = parse_lit!(
1291            (-1 * G
1292                ^ 3 * P(0, mink(4, 0))
1293                    * P(2, mink(4, 26))
1294                    * gamma(bis(4, 3), bis(4, 7), mink(4, 4))
1295                    * gamma(bis(4, 7), bis(4, 6), mink(4, 1))
1296                    * gamma(bis(4, 6), bis(4, 2), mink(4, 26))
1297                    + -1 * G
1298                ^ 3 * P(0, mink(4, 26))
1299                    * P(1, mink(4, 1))
1300                    * gamma(bis(4, 3), bis(4, 7), mink(4, 4))
1301                    * gamma(bis(4, 7), bis(4, 6), mink(4, 0))
1302                    * gamma(bis(4, 6), bis(4, 2), mink(4, 26))
1303                    + -1 * G
1304                ^ 3 * P(0, mink(4, 26))
1305                    * P(1, mink(4, 5))
1306                    * g(mink(4, 0), mink(4, 1))
1307                    * gamma(bis(4, 3), bis(4, 7), mink(4, 4))
1308                    * gamma(bis(4, 7), bis(4, 6), mink(4, 5))
1309                    * gamma(bis(4, 6), bis(4, 2), mink(4, 26))
1310                    + -1 * G
1311                ^ 3 * P(0, mink(4, 5))
1312                    * P(2, mink(4, 26))
1313                    * g(mink(4, 0), mink(4, 1))
1314                    * gamma(bis(4, 3), bis(4, 7), mink(4, 4))
1315                    * gamma(bis(4, 6), bis(4, 2), mink(4, 26))
1316                    * gamma(bis(4, 7), bis(4, 6), mink(4, 5))
1317                    + -1 * G
1318                ^ 3 * P(1, mink(4, 1))
1319                    * P(1, mink(4, 26))
1320                    * gamma(bis(4, 3), bis(4, 7), mink(4, 4))
1321                    * gamma(bis(4, 6), bis(4, 2), mink(4, 26))
1322                    * gamma(bis(4, 7), bis(4, 6), mink(4, 0))
1323                    + -1 * G
1324                ^ 3 * P(1, mink(4, 26))
1325                    * P(1, mink(4, 5))
1326                    * g(mink(4, 0), mink(4, 1))
1327                    * gamma(bis(4, 3), bis(4, 7), mink(4, 4))
1328                    * gamma(bis(4, 6), bis(4, 2), mink(4, 26))
1329                    * gamma(bis(4, 7), bis(4, 6), mink(4, 5))
1330                    + -2 * G
1331                ^ 3 * P(0, mink(4, 1))
1332                    * P(0, mink(4, 26))
1333                    * gamma(bis(4, 3), bis(4, 7), mink(4, 4))
1334                    * gamma(bis(4, 6), bis(4, 2), mink(4, 26))
1335                    * gamma(bis(4, 7), bis(4, 6), mink(4, 0))
1336                    + -2 * G
1337                ^ 3 * P(0, mink(4, 1))
1338                    * P(1, mink(4, 26))
1339                    * gamma(bis(4, 3), bis(4, 7), mink(4, 4))
1340                    * gamma(bis(4, 6), bis(4, 2), mink(4, 26))
1341                    * gamma(bis(4, 7), bis(4, 6), mink(4, 0))
1342                    + -2 * G
1343                ^ 3 * P(0, mink(4, 5))
1344                    * Q(0, mink(4, 5))
1345                    * g(mink(4, 0), mink(4, 1))
1346                    * gamma(bis(4, 3), bis(4, 2), mink(4, 4))
1347                    + -2 * G
1348                ^ 3 * P(1, mink(4, 0))
1349                    * P(1, mink(4, 1))
1350                    * gamma(bis(4, 3), bis(4, 2), mink(4, 4))
1351                    + -2 * G
1352                ^ 3 * P(1, mink(4, 0))
1353                    * P(2, mink(4, 26))
1354                    * gamma(bis(4, 3), bis(4, 7), mink(4, 4))
1355                    * gamma(bis(4, 6), bis(4, 2), mink(4, 26))
1356                    * gamma(bis(4, 7), bis(4, 6), mink(4, 1))
1357                    + -2 * G
1358                ^ 3 * P(1, mink(4, 1))
1359                    * P(2, mink(4, 0))
1360                    * gamma(bis(4, 3), bis(4, 2), mink(4, 4))
1361                    + -2 * G
1362                ^ 3 * P(1, mink(4, 5))
1363                    * P(2, mink(4, 5))
1364                    * g(mink(4, 0), mink(4, 1))
1365                    * gamma(bis(4, 3), bis(4, 2), mink(4, 4))
1366                    + -4 * G
1367                ^ 3 * P(0, mink(4, 1))
1368                    * P(2, mink(4, 0))
1369                    * gamma(bis(4, 3), bis(4, 2), mink(4, 4))
1370                    + 2 * G
1371                ^ 3 * P(0, mink(4, 0))
1372                    * P(0, mink(4, 1))
1373                    * gamma(bis(4, 3), bis(4, 2), mink(4, 4))
1374                    + 2 * G
1375                ^ 3 * P(0, mink(4, 0))
1376                    * P(2, mink(4, 1))
1377                    * gamma(bis(4, 3), bis(4, 2), mink(4, 4))
1378                    + 2 * G
1379                ^ 3 * P(0, mink(4, 1))
1380                    * P(2, mink(4, 26))
1381                    * gamma(bis(4, 3), bis(4, 7), mink(4, 4))
1382                    * gamma(bis(4, 6), bis(4, 2), mink(4, 26))
1383                    * gamma(bis(4, 7), bis(4, 6), mink(4, 0))
1384                    + 2 * G
1385                ^ 3 * P(0, mink(4, 26))
1386                    * P(1, mink(4, 0))
1387                    * gamma(bis(4, 3), bis(4, 7), mink(4, 4))
1388                    * gamma(bis(4, 6), bis(4, 2), mink(4, 26))
1389                    * gamma(bis(4, 7), bis(4, 6), mink(4, 1))
1390                    + 2 * G
1391                ^ 3 * P(0, mink(4, 5))
1392                    * P(2, mink(4, 5))
1393                    * g(mink(4, 0), mink(4, 1))
1394                    * gamma(bis(4, 3), bis(4, 2), mink(4, 4))
1395                    + 2 * G
1396                ^ 3 * P(1, mink(4, 0))
1397                    * P(1, mink(4, 26))
1398                    * gamma(bis(4, 3), bis(4, 7), mink(4, 4))
1399                    * gamma(bis(4, 6), bis(4, 2), mink(4, 26))
1400                    * gamma(bis(4, 7), bis(4, 6), mink(4, 1))
1401                    + 2 * G
1402                ^ 3 * P(1, mink(4, i))
1403                ^ 2 * g(mink(4, 0), mink(4, 1)) * gamma(bis(4, 3), bis(4, 2), mink(4, 4)) + G
1404                ^ 3 * P(1, mink(4, 1))
1405                    * P(2, mink(4, 26))
1406                    * gamma(bis(4, 3), bis(4, 7), mink(4, 4))
1407                    * gamma(bis(4, 6), bis(4, 2), mink(4, 26))
1408                    * gamma(bis(4, 7), bis(4, 6), mink(4, 0))),
1409            default_namespace = "spenso"
1410        );
1411        // println!("{}", expr);
1412
1413        let mut net = Network::<
1414            NetworkStore<MixedTensor<f64, ShadowedStructure<AbstractIndex>>, Atom>,
1415            _,
1416            Symbol,
1417        >::try_from_view(
1418            expr.as_view(),
1419            &*HEP_LIB,
1420            &ParseSettings::default().with_strict_tensor_filter(StrictTensorFilter::ContainsReps),
1421        )
1422        .unwrap();
1423
1424        net.merge_ops();
1425        println!(
1426            "{}",
1427            net.dot_display_impl(
1428                |a| a.to_string(),
1429                |a| Some(format!("{}", a.global_name.unwrap())),
1430                |a| a.structure().global_name.unwrap().to_string(),
1431                |a| a.to_string()
1432            )
1433        );
1434
1435        // net.validate();
1436        net.execute::<Steps<1>, SingleSmallestDegree<true>, _, _, _>(&*HEP_LIB, &(*FUN_LIB))
1437            .unwrap();
1438        // net.validate();
1439        // net.execute::<Steps<1>, SmallestDegree, _, _>(&*HEP_LIB);
1440        // net.validate();
1441        // net.execute::<Steps<1>, SmallestDegree, _, _>(&*HEP_LIB);
1442        // net.validate();
1443        // net.execute::<Steps<1>, SmallestDegree, _, _>(&*HEP_LIB);
1444        // net.validate();
1445        // net.execute::<Steps<1>, SmallestDegree, _, _>(&*HEP_LIB);
1446        // net.validate();
1447        // net.execute::<Steps<1>, SmallestDegree, _, _>(&*HEP_LIB);
1448        // net.validate();
1449        // net.execute::<Steps<1>, SmallestDegree, _, _>(&*HEP_LIB);
1450        // net.validate();
1451        // net.execute::<Steps<1>, SmallestDegree, _, _>(&*HEP_LIB);
1452        // net.validate();
1453        // net.execute::<Steps<1>, SmallestDegree, _, _>(&*HEP_LIB);
1454        // net.validate();
1455        // net.execute::<Steps<1>, SmallestDegree, _, _>(&*HEP_LIB);
1456        // net.validate();
1457        // net.execute::<Steps<1>, ContractScalars, _, _>(&*HEP_LIB);
1458        // net.execute::<Steps<1>, SmallestDegree, _, _>(&*HEP_LIB);
1459        // net.execute::<StepsDebug<1>, SingleSmallestDegree<true>, _, _>(&*HEP_LIB);
1460        // net.execute::<Steps<1>, ContractScalars, _, _>(&*HEP_LIB);
1461
1462        //     .unwrap();
1463        // net.execute::<Steps<14>, SingleSmallestDegree<false>, _, _>(&*HEP_LIB)
1464        //     .unwrap();
1465        // net.execute::<Steps<1>, SingleSmallestDegree<true>, _, _>(&*HEP_LIB)
1466        //     .unwrap();
1467        // // net.execute::<Sequential, SmallestDegree, _, _>(&*HEP_LIB)
1468        //     .unwrap();
1469        // println!(
1470        //     "{}",
1471        //     net.dot_display_impl(|a| a.to_string(), |_| None, |a| a.to_string())
1472        // );
1473
1474        println!(
1475            "{}",
1476            net.dot_display_impl(
1477                |a| a.to_string(),
1478                |_| None,
1479                |a| a.structure().to_string().replace('\n', "\\n"),
1480                |a| a.to_string()
1481            )
1482        );
1483        // if let ExecutionResult::Val(TensorOrScalarOrKey::Tensor { tensor, .. }) =
1484        //     net.result().unwrap()
1485        // {
1486        //     // println!("YaY:{}", (&expr - &tensor.expression).expand());
1487        //     // assert_eq!(expr, tensor.expression);
1488        // } else {
1489        //     panic!("Not tensor")
1490        // }
1491    }
1492
1493    #[test]
1494    fn transpose_test() {}
1495}