1use feynkit_amplitude::{AxialReference, ColorRepresentation, SpinSum};
2use feynkit_graph::DOD;
3use std::{
4 collections::{BTreeMap, BTreeSet, HashMap},
5 fmt::{Display, Formatter},
6 ops::{Deref, DerefMut},
7 path::Path,
8};
9
10use color_eyre::Report;
11use eyre::eyre;
12use idenso::{dirac::AGS, representations::Bispinor};
13use itertools::Itertools;
14use linnet::half_edge::involution::{EdgeIndex, Flow};
15use rand::{Rng, SeedableRng, rngs::SmallRng};
16use serde::{Deserialize, Serialize, de::DeserializeOwned};
17use spenso::algebra::complex::Complex;
18use spenso::structure::{
19 Canonicalized, IndexLess, OrderedStructure, TensorDataLayout,
20 abstract_index::AbstractIndex,
21 representation::{Euclidean, LibraryRep, Minkowski, RepName},
22 slot::{DummyAind, IsAbstractSlot, Slot},
23};
24use spenso::tensors::{
25 data::{DataTensor, DenseTensor, SetTensorData, SparseTensor},
26 parametric::ParamTensor,
27};
28use symbolica::domains::rational::Fraction;
29use symbolica::prelude::*;
30
31use crate::{
32 momentum::Helicity,
33 numerator::aind::Aind,
34 settings::global::VectorPolarizationSumGauge,
35 utils::{F, GS, W_, serde_utils::SmartSerde},
36};
37
38pub use feynkit_model::{
39 Coupling, CouplingId, LorentzStructure, LorentzStructureId, Model, ModelFingerprint,
40 ModelFormFactor, ModelFormFactorId, ModelFunction, ModelFunctionId, Order, OrderId, Parameter,
41 ParameterId, ParameterNature, ParameterType, Particle, ParticleId, Propagator, PropagatorId,
42 VertexRule, VertexRuleId,
43};
44
45#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
47pub struct SerializableInputParamCard<T> {
48 pub data: BTreeMap<String, (T, T)>,
49}
50
51impl<T> SerializableInputParamCard<T>
52where
53 T: From<f64> + Clone + Serialize + DeserializeOwned,
54{
55 pub(crate) fn from_file(file_path: impl AsRef<Path>) -> Result<Self, Report> {
56 let data = SmartSerde::from_file(file_path, "model")?;
57 Ok(Self { data })
58 }
59
60 pub fn from_str(source: String, format: &str) -> Result<Self, Report> {
61 let data = SmartSerde::from_str(source, format, "model_parameters")?;
62 Ok(Self { data })
63 }
64
65 pub fn from_input_param_card(card: &InputParamCard<T>) -> Self {
66 Self {
67 data: card
68 .data
69 .iter()
70 .map(|(name, value)| {
71 (
72 name.namespaceless_string().to_owned(),
73 (value.re.clone(), value.im.clone()),
74 )
75 })
76 .collect(),
77 }
78 }
79
80 pub fn to_file<P: AsRef<Path>>(&self, path: P, overwrite: bool) -> Result<(), Report> {
81 SmartSerde::to_file(&self.data, path, overwrite)
82 }
83}
84
85#[derive(Debug, Clone)]
86pub struct InputParamCard<T>
87where
88 T: From<f64> + Clone + Serialize + DeserializeOwned,
89{
90 data: HashMap<UFOSymbol, Complex<T>>,
91}
92
93impl<T> Default for InputParamCard<T>
94where
95 T: From<f64> + Clone + Serialize + DeserializeOwned,
96{
97 fn default() -> Self {
98 Self::new()
99 }
100}
101
102impl<T> InputParamCard<T>
103where
104 T: From<f64> + Clone + Serialize + DeserializeOwned,
105{
106 pub fn new() -> Self {
107 Self {
108 data: HashMap::new(),
109 }
110 }
111
112 pub fn insert(&mut self, symbol: UFOSymbol, value: Complex<T>) -> Option<Complex<T>> {
113 self.data.insert(symbol, value)
114 }
115
116 pub fn get(&self, symbol: &UFOSymbol) -> Option<&Complex<T>> {
117 self.data.get(symbol)
118 }
119
120 pub fn get_mut(&mut self, symbol: &UFOSymbol) -> Option<&mut Complex<T>> {
121 self.data.get_mut(symbol)
122 }
123
124 pub fn remove(&mut self, symbol: &UFOSymbol) -> Option<Complex<T>> {
125 self.data.remove(symbol)
126 }
127
128 pub fn iter(&self) -> impl Iterator<Item = (&UFOSymbol, &Complex<T>)> {
129 self.data.iter()
130 }
131
132 pub fn to_serializable(&self) -> SerializableInputParamCard<T> {
133 SerializableInputParamCard::from_input_param_card(self)
134 }
135
136 pub fn from_serializable(card: &SerializableInputParamCard<T>) -> Self {
137 Self {
138 data: card
139 .data
140 .iter()
141 .map(|(name, (re, im))| {
142 (UFOSymbol::from(name), Complex::new(re.clone(), im.clone()))
143 })
144 .collect(),
145 }
146 }
147
148 pub fn from_file(file_path: impl AsRef<Path>) -> Result<Self, Report> {
149 Ok(Self::from_serializable(
150 &SerializableInputParamCard::from_file(file_path)?,
151 ))
152 }
153
154 pub fn from_str(source: String, format: &str) -> Result<Self, Report> {
155 Ok(Self::from_serializable(
156 &SerializableInputParamCard::from_str(source, format)?,
157 ))
158 }
159
160 pub fn to_file<P: AsRef<Path>>(&self, path: P, overwrite: bool) -> Result<(), Report> {
161 self.to_serializable().to_file(path, overwrite)
162 }
163}
164
165impl<T> Deref for InputParamCard<T>
166where
167 T: From<f64> + Clone + Serialize + DeserializeOwned,
168{
169 type Target = HashMap<UFOSymbol, Complex<T>>;
170
171 fn deref(&self) -> &Self::Target {
172 &self.data
173 }
174}
175
176impl<T> DerefMut for InputParamCard<T>
177where
178 T: From<f64> + Clone + Serialize + DeserializeOwned,
179{
180 fn deref_mut(&mut self) -> &mut Self::Target {
181 &mut self.data
182 }
183}
184
185impl From<feynkit_model::ParameterCard> for InputParamCard<F<f64>> {
186 fn from(card: feynkit_model::ParameterCard) -> Self {
187 Self {
188 data: card
189 .into_iter()
190 .map(|(name, value)| {
191 (
192 UFOSymbol::from(name),
193 Complex::new(F(value.re), F(value.im)),
194 )
195 })
196 .collect(),
197 }
198 }
199}
200
201impl From<&InputParamCard<F<f64>>> for feynkit_model::ParameterCard {
202 fn from(card: &InputParamCard<F<f64>>) -> Self {
203 card.iter()
204 .map(|(name, value)| {
205 (
206 name.namespaceless_string().to_owned(),
207 feynkit_model::ComplexValue::new(value.re.0, value.im.0),
208 )
209 })
210 .collect()
211 }
212}
213
214#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
216pub struct UFOSymbol(pub Symbol);
217
218impl UFOSymbol {
219 pub fn zero() -> Self {
220 Self(symbol!("UFO::ZERO"))
221 }
222
223 pub fn is_zero(self) -> bool {
224 self.0 == Self::zero().0
225 }
226
227 pub fn namespaceless_string(&self) -> &str {
228 self.0.get_stripped_name()
229 }
230}
231
232impl Display for UFOSymbol {
233 fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
234 Display::fmt(&self.0, formatter)
235 }
236}
237
238impl From<UFOSymbol> for Atom {
239 fn from(value: UFOSymbol) -> Self {
240 Atom::var(value.0)
241 }
242}
243
244impl<T: AsRef<str>> From<T> for UFOSymbol {
245 fn from(name: T) -> Self {
246 if name.as_ref() == "ZERO" {
247 Self::zero()
248 } else {
249 let qualified_name = format!("UFO::{}", name.as_ref());
250 if symbolica::get_symbol!(&qualified_name).is_none() {
251 Model::register_parameter_symbol(name.as_ref(), Some(name.as_ref()), None)
254 .expect("valid UFO symbol name");
255 }
256 Self(symbol!(&qualified_name))
257 }
258 }
259}
260
261pub trait ModelGammaLoopExt {
263 fn apply_param_card(&mut self, card: &InputParamCard<F<f64>>) -> Result<(), Report>;
264 fn recompute_dependents(&mut self) -> Result<(), Report>;
265 fn simplify(&mut self, card: &mut InputParamCard<F<f64>>) -> Result<(), Report>;
266 fn default_param_card(&self) -> InputParamCard<F<f64>>;
267 fn get_particle(&self, name: impl AsRef<str>) -> ParticleId;
268 fn try_get_particle(&self, name: impl AsRef<str>) -> Result<ParticleId, Report>;
269 fn get_particle_from_pdg(&self, pdg: isize) -> ParticleId;
270 fn try_get_particle_from_pdg(&self, pdg: isize) -> Result<ParticleId, Report>;
271 fn get_propagator(&self, name: impl AsRef<str>) -> PropagatorId;
272 fn get_parameter_opt(&self, name: impl AsRef<str>) -> Option<&Parameter>;
273 fn get_parameter(&self, name: impl AsRef<str>) -> &Parameter;
274 fn get_coupling(&self, name: impl AsRef<str>) -> &Coupling;
275 fn vertex_rules_for_particles(&self, particles: &[ParticleId]) -> Vec<VertexRuleId>;
276 fn unresolved_particles(&self) -> HashMap<String, BTreeSet<ParticleId>>;
277 fn contains_symbol(&self, symbol: &UFOSymbol) -> bool;
278 fn get_symbol_value(&self, symbol: UFOSymbol) -> Option<Complex<F<f64>>>;
279 fn generate_params(&self) -> Vec<Atom>;
280 fn apply_parameter_replacement_rules(&self, atom: &Atom) -> Atom;
281 fn get_description(
282 &self,
283 show_particles: bool,
284 show_parameters: bool,
285 show_vertices: bool,
286 show_couplings: bool,
287 ) -> String;
288 fn generate_edge_style_template(
289 &self,
290 template_path: impl AsRef<std::path::Path>,
291 ) -> Result<(), std::io::Error>;
292 fn is_empty(&self) -> bool;
293}
294
295impl ModelGammaLoopExt for Model {
296 fn apply_param_card(&mut self, card: &InputParamCard<F<f64>>) -> Result<(), Report> {
297 self.apply_parameter_card(&card.into())?;
298 self.recompute_dependents()
299 }
300
301 fn recompute_dependents(&mut self) -> Result<(), Report> {
302 let replacements = self
303 .couplings()
304 .iter()
305 .map(|coupling| {
306 let symbol = UFOSymbol::from(&coupling.name).0;
307 Replacement::new(Atom::var(symbol).to_pattern(), function!(symbol))
308 })
309 .chain(self.parameters().iter().map(|parameter| {
310 let symbol = UFOSymbol::from(¶meter.name).0;
311 Replacement::new(Atom::var(symbol).to_pattern(), function!(symbol))
312 }))
313 .collect_vec();
314 let mut function_map = FunctionMap::new();
315 let mut expressions = Vec::new();
316 for coupling in self.couplings() {
317 let symbol = UFOSymbol::from(&coupling.name).0;
318 expressions.push(function!(symbol));
319 function_map
320 .add_function::<Symbol, Symbol>(
321 symbol,
322 Vec::new(),
323 coupling.expression.replace_multiple(&replacements),
324 )
325 .map_err(|error| eyre!("{error}"))?;
326 }
327
328 let mut parameters = Vec::new();
329 let mut parameter_values = Vec::new();
330 let mut dependent_parameters = Vec::new();
331 for (index, parameter) in self.parameters().iter().enumerate() {
332 let symbol = UFOSymbol::from(¶meter.name).0;
333 let key = function!(symbol);
334 match parameter.nature {
335 ParameterNature::External => {
336 parameters.push(key);
337 let value = parameter.value.ok_or_else(|| {
338 eyre!("External parameter '{}' has no value", parameter.name)
339 })?;
340 parameter_values.push(Complex::new(F(value.re), F(value.im)));
341 }
342 ParameterNature::Internal if parameter.name == "ZERO" => {}
343 ParameterNature::Internal => {
344 if let Some(body) = ¶meter.expression {
345 expressions.push(key.clone());
346 dependent_parameters.push(ParameterId::from_index(index));
347 function_map
348 .add_function::<Symbol, Symbol>(
349 symbol,
350 Vec::new(),
351 body.replace_multiple(&replacements),
352 )
353 .map_err(|error| eyre!("{error}"))?;
354 } else {
355 let value = parameter.value.ok_or_else(|| {
356 eyre!(
357 "Internal parameter '{}' has neither expression nor value",
358 parameter.name
359 )
360 })?;
361 let value = symbolica::domains::float::Complex::new(
362 Fraction::<IntegerRing>::try_from(value.re).unwrap(),
363 Fraction::<IntegerRing>::try_from(value.im).unwrap(),
364 );
365 function_map
366 .add_aliases([(key, Atom::num(value))])
367 .map_err(|error| eyre!("{error}"))?;
368 }
369 }
370 }
371 }
372 function_map
373 .add_aliases([(
374 Atom::var(Symbol::PI),
375 Atom::num(symbolica::domains::float::Complex::new(
376 Rational::try_from(std::f64::consts::PI).unwrap(),
377 Rational::zero(),
378 )),
379 )])
380 .map_err(|error| eyre!("{error}"))?;
381
382 let evaluator = AtomView::to_eval_tree_multiple(&expressions, &function_map, ¶meters)?
383 .linearize(
384 &OptimizationSettings::new()
385 .cpe_iterations(Some(1))
386 .verbose(false),
387 );
388 let mut evaluator =
389 evaluator.map_coeff(&|value| Complex::new(F(value.re.to_f64()), F(value.im.to_f64())));
390 let mut values = vec![Complex::new(F(0.0), F(0.0)); expressions.len()];
391 evaluator.evaluate(¶meter_values, &mut values);
392 let coupling_count = self.couplings().len();
393 let evaluated = feynkit_model::EvaluatedValues {
394 couplings: self
395 .couplings()
396 .iter()
397 .zip(&values[..coupling_count])
398 .map(|(coupling, value)| {
399 (
400 coupling.name.clone(),
401 feynkit_model::ComplexValue::new(value.re.0, value.im.0),
402 )
403 })
404 .collect(),
405 internal_parameters: dependent_parameters
406 .into_iter()
407 .zip(&values[coupling_count..])
408 .map(|(parameter, value)| {
409 (
410 self.parameter_by_id(parameter).unwrap().name.clone(),
411 feynkit_model::ComplexValue::new(value.re.0, value.im.0),
412 )
413 })
414 .collect(),
415 };
416 self.recompute_with(&mut |_| Ok::<_, std::convert::Infallible>(evaluated.clone()))
417 .map_err(|error| eyre!(error))?;
418 Ok(())
419 }
420
421 fn simplify(&mut self, card: &mut InputParamCard<F<f64>>) -> Result<(), Report> {
422 self.apply_param_card(card)?;
423 card.data
424 .retain(|_, value| value.re != F(0.0) || value.im != F(0.0));
425
426 self.simplify_zero_values()?;
427 Ok(())
428 }
429
430 fn default_param_card(&self) -> InputParamCard<F<f64>> {
431 self.default_parameter_card()
432 .expect("validated models have complete external parameter cards")
433 .into()
434 }
435
436 fn get_particle(&self, name: impl AsRef<str>) -> ParticleId {
437 self.try_get_particle(name).unwrap()
438 }
439
440 fn try_get_particle(&self, name: impl AsRef<str>) -> Result<ParticleId, Report> {
441 self.particle_id(name.as_ref()).map_err(Into::into)
442 }
443
444 fn get_particle_from_pdg(&self, pdg: isize) -> ParticleId {
445 self.try_get_particle_from_pdg(pdg).unwrap()
446 }
447
448 fn try_get_particle_from_pdg(&self, pdg: isize) -> Result<ParticleId, Report> {
449 let pdg = i64::try_from(pdg).map_err(|_| eyre!("PDG code {pdg} is out of range"))?;
450 self.particle_id_by_pdg(pdg).map_err(Into::into)
451 }
452
453 fn get_propagator(&self, name: impl AsRef<str>) -> PropagatorId {
454 self.propagator_id(name.as_ref()).unwrap()
455 }
456
457 fn get_parameter_opt(&self, name: impl AsRef<str>) -> Option<&Parameter> {
458 self.parameter(name.as_ref()).ok()
459 }
460
461 fn get_parameter(&self, name: impl AsRef<str>) -> &Parameter {
462 self.parameter(name.as_ref()).unwrap()
463 }
464
465 fn get_coupling(&self, name: impl AsRef<str>) -> &Coupling {
466 self.coupling(name.as_ref()).unwrap()
467 }
468
469 fn vertex_rules_for_particles(&self, particles: &[ParticleId]) -> Vec<VertexRuleId> {
470 let mut requested = particles.to_vec();
471 requested.sort_unstable();
472
473 self.vertex_rules()
474 .iter()
475 .filter(|rule| {
476 let mut rule_particles = rule.particles.clone();
477 rule_particles.sort_unstable();
478 rule_particles == requested
479 })
480 .map(|rule| self.vertex_rule_id(&rule.name).unwrap())
481 .collect()
482 }
483
484 fn unresolved_particles(&self) -> HashMap<String, BTreeSet<ParticleId>> {
485 let mut unresolved = HashMap::<String, BTreeSet<ParticleId>>::new();
486 for vertex_rule in self.vertex_rules() {
487 let massless = vertex_rule
488 .particles
489 .iter()
490 .copied()
491 .filter(|particle| particle.resolve(self).is_massless(self))
492 .collect::<BTreeSet<_>>();
493 for order in vertex_rule.coupling_orders(self).into_keys() {
494 unresolved.entry(order).or_default().extend(&massless);
495 }
496 }
497 unresolved
498 }
499
500 fn contains_symbol(&self, symbol: &UFOSymbol) -> bool {
501 self.parameter(symbol.namespaceless_string()).is_ok()
502 || self.coupling(symbol.namespaceless_string()).is_ok()
503 }
504
505 fn get_symbol_value(&self, symbol: UFOSymbol) -> Option<Complex<F<f64>>> {
506 self.coupling(symbol.namespaceless_string())
507 .ok()
508 .and_then(|coupling| coupling.value)
509 .or_else(|| {
510 self.parameter(symbol.namespaceless_string())
511 .ok()
512 .and_then(|parameter| parameter.value)
513 })
514 .map(|value| Complex::new(F(value.re), F(value.im)))
515 }
516
517 fn generate_params(&self) -> Vec<Atom> {
518 self.couplings()
519 .iter()
520 .filter(|coupling| coupling.value.is_some())
521 .map(|coupling| Atom::from(UFOSymbol::from(&coupling.name)))
522 .chain(
523 self.parameters()
524 .iter()
525 .filter(|parameter| parameter.value.is_some())
526 .map(|parameter| Atom::from(UFOSymbol::from(¶meter.name))),
527 )
528 .collect()
529 }
530
531 fn apply_parameter_replacement_rules(&self, atom: &Atom) -> Atom {
532 let replacements = self
533 .parameters()
534 .iter()
535 .filter_map(|parameter| {
536 parameter.expression.as_ref().map(|expression| {
537 Replacement::new(
538 Atom::from(UFOSymbol::from(¶meter.name)).to_pattern(),
539 expression.clone(),
540 )
541 })
542 })
543 .collect::<Vec<_>>();
544 atom.replace_multiple(&replacements)
545 }
546
547 fn get_description(
548 &self,
549 show_particles: bool,
550 show_parameters: bool,
551 show_vertices: bool,
552 show_couplings: bool,
553 ) -> String {
554 use std::fmt::Write as _;
555
556 let restriction = self.restriction().unwrap_or("None");
557 let orders = if self.orders().is_empty() {
558 "None".to_owned()
559 } else {
560 self.orders()
561 .iter()
562 .map(|order| {
563 format!(
564 "{} (expansion order: {}, hierarchy: {})",
565 order.name, order.expansion_order, order.hierarchy
566 )
567 })
568 .join(", ")
569 };
570 let mut output = format!(
571 "\nModel name : {}\nRestriction : {}\nCoupling orders : {}\n\n{} particles",
572 self.name(),
573 restriction,
574 orders,
575 self.particles().len()
576 );
577
578 if show_particles {
579 for particle in self.particles() {
580 let mass = self
581 .parameter_by_id(particle.mass)
582 .expect("validated particle mass references resolve");
583 let width = self
584 .parameter_by_id(particle.width)
585 .expect("validated particle width references resolve");
586 let mass_value = mass
587 .value
588 .map_or_else(|| "None".to_owned(), |value| format!("{:.6}", value.re));
589 let width_value = width
590 .value
591 .map_or_else(|| "None".to_owned(), |value| format!("{:.6}", value.re));
592 let _ = write!(
593 output,
594 "\n {:<16} PDG {:+8} mass {}={} width {}={}",
595 particle.name,
596 particle.pdg_code,
597 mass.name,
598 mass_value,
599 width.name,
600 width_value
601 );
602 }
603 } else {
604 output.push_str(" [hidden]");
605 }
606
607 let _ = write!(output, "\n\n{} parameters", self.parameters().len());
608 if show_parameters {
609 let mut parameters = self.parameters().iter().collect_vec();
610 parameters.sort_by_key(|parameter| {
611 (
612 !matches!(parameter.nature, ParameterNature::External),
613 parameter.name.as_str(),
614 )
615 });
616 for parameter in parameters {
617 let value = parameter.value.map_or_else(String::new, |value| {
618 if value.im == 0.0 {
619 format!("{:.6}", value.re)
620 } else {
621 format!("{:.6}{:+.6}i", value.re, value.im)
622 }
623 });
624 let expression = parameter
625 .expression
626 .as_ref()
627 .map(ToString::to_string)
628 .unwrap_or_default();
629 let _ = write!(
630 output,
631 "\n {:<20} {:?} {:?} {}{}{}",
632 parameter.name,
633 parameter.nature,
634 parameter.parameter_type,
635 value,
636 if !value.is_empty() && !expression.is_empty() {
637 " = "
638 } else {
639 ""
640 },
641 expression
642 );
643 }
644 } else {
645 output.push_str(" [hidden]");
646 }
647
648 let _ = write!(output, "\n\n{} vertices", self.vertex_rules().len());
649 if show_vertices {
650 for rule in self.vertex_rules() {
651 let particles = rule
652 .particles
653 .iter()
654 .map(|particle| {
655 self.particle_by_id(*particle)
656 .expect("validated vertex particle references resolve")
657 .name
658 .as_str()
659 })
660 .join(", ");
661 let _ = write!(output, "\n {:<20} {}", rule.name, particles);
662 }
663 } else {
664 output.push_str(" [hidden]");
665 }
666
667 let _ = write!(output, "\n\n{} couplings", self.couplings().len());
668 if show_couplings {
669 for coupling in self.couplings() {
670 let orders = coupling
671 .orders
672 .iter()
673 .map(|(name, power)| format!("{name}={power}"))
674 .join(" ");
675 let _ = write!(
676 output,
677 "\n {:<20} {:<16} {}",
678 coupling.name, coupling.expression, orders
679 );
680 }
681 } else {
682 output.push_str(" [hidden]");
683 }
684 output.push('\n');
685 output
686 }
687
688 fn generate_edge_style_template(
689 &self,
690 template_path: impl AsRef<std::path::Path>,
691 ) -> Result<(), std::io::Error> {
692 use std::fs;
693
694 if let Some(parent) = template_path.as_ref().parent() {
695 fs::create_dir_all(parent)?;
696 }
697
698 let mut content = String::from(
699 r#"#import "physics-edge-style.typ": mi, palette, massive, massless, dashed, dotted, stroke-style, source-stroke, sink-stroke, fermion-flow, wave, coil, zigzag, default-edge, default-map, style as physics-style
700
701// Auto-generated particle styles from the canonical model. The reusable
702// drawing callbacks live in physics-edge-style.typ.
703#let generated-map = (
704"#,
705 );
706 for particle in self.particles() {
707 content.push_str(&format!(
708 " \"{}\": {},\n",
709 particle.name,
710 particle.generate_edge_typst_dict(self)
711 ));
712 }
713 content.push_str(
714 r#")
715
716#let map = generated-map
717
718// Merge model-specific particles with neutral aliases and caller overrides.
719#let style(map: (:), typst-fields: "plain", ..options) = physics-style(
720 map: default-map + generated-map + map,
721 typst-fields: typst-fields,
722 ..options.named(),
723)
724
725#let source-style(edge, typst-fields: "plain", ..options) = {
726 let callbacks = style(typst-fields: typst-fields, ..options.named())
727 (callbacks.source-style)(edge)
728}
729
730#let sink-style(edge, typst-fields: "plain", ..options) = {
731 let callbacks = style(typst-fields: typst-fields, ..options.named())
732 (callbacks.sink-style)(edge)
733}
734
735#let edge-label(edge, typst-fields: "plain", ..options) = {
736 let callbacks = style(typst-fields: typst-fields, ..options.named())
737 (callbacks.edge-label)(edge)
738}
739"#,
740 );
741 fs::write(template_path, content)
742 }
743
744 fn is_empty(&self) -> bool {
745 self.name() == "ModelNotLoaded" || self.particles().is_empty()
746 }
747}
748
749pub trait ParticleIdGammaLoopExt {
751 fn resolve(self, model: &Model) -> &Particle;
752 fn antiparticle(self, model: &Model) -> ParticleId;
753 fn is_self_antiparticle(&self, model: &Model) -> bool;
754 fn is_massless(&self, model: &Model) -> bool;
755}
756
757impl ParticleIdGammaLoopExt for ParticleId {
758 fn resolve(self, model: &Model) -> &Particle {
759 model
760 .particle_by_id(self)
761 .expect("particle IDs stored with a model must resolve in that model")
762 }
763
764 fn antiparticle(self, model: &Model) -> ParticleId {
765 self.resolve(model).antiparticle
766 }
767
768 fn is_self_antiparticle(&self, model: &Model) -> bool {
769 model.particle_is_self_conjugate(*self)
770 }
771
772 fn is_massless(&self, model: &Model) -> bool {
773 model.particle_is_massless(*self)
774 }
775}
776
777pub trait VertexRuleIdGammaLoopExt {
779 fn resolve(self, model: &Model) -> &VertexRule;
780}
781
782impl VertexRuleIdGammaLoopExt for VertexRuleId {
783 fn resolve(self, model: &Model) -> &VertexRule {
784 model
785 .vertex_rule_by_id(self)
786 .expect("vertex-rule IDs stored with a model must resolve in that model")
787 }
788}
789
790pub trait PropagatorIdGammaLoopExt {
792 fn resolve(self, model: &Model) -> &Propagator;
793}
794
795impl PropagatorIdGammaLoopExt for PropagatorId {
796 fn resolve(self, model: &Model) -> &Propagator {
797 model
798 .propagator_by_id(self)
799 .expect("propagator IDs stored with a model must resolve in that model")
800 }
801}
802
803pub trait ParticleGammaLoopExt {
805 fn resolved_mass_value(&self, model: &Model) -> Result<Complex<F<f64>>, Report>;
806 fn has_zero_resolved_mass(&self, model: &Model) -> Result<bool, Report>;
807 fn random_helicity(&self, seed: u64) -> Helicity;
808 fn spin_reps(&self) -> IndexLess<LibraryRep, Aind>;
809 fn color_reps(&self, flow: Flow) -> IndexLess;
810 fn polarization_sum(
811 &self,
812 model: &Model,
813 edge: EdgeIndex,
814 average: bool,
815 gauge: VectorPolarizationSumGauge,
816 ) -> Result<Option<Replacement>, Report>;
817}
818
819impl ParticleGammaLoopExt for Particle {
820 fn resolved_mass_value(&self, model: &Model) -> Result<Complex<F<f64>>, Report> {
821 model
822 .parameter_by_id(self.mass)
823 .ok()
824 .and_then(|parameter| parameter.value)
825 .map(|mass| Complex::new(F(mass.re), F(mass.im)))
826 .ok_or_else(|| {
827 eyre!(
828 "Particle '{}' (PDG {}) requires a resolved value for mass parameter '{}' in model '{}'.",
829 self.name,
830 self.pdg_code,
831 model.parameter_by_id(self.mass).unwrap().name,
832 model.name()
833 )
834 })
835 }
836
837 fn has_zero_resolved_mass(&self, model: &Model) -> Result<bool, Report> {
838 let mass = self.resolved_mass_value(model)?;
839 Ok(mass.re == F(0.0) && mass.im == F(0.0))
840 }
841
842 fn random_helicity(&self, seed: u64) -> Helicity {
843 let mut rng = SmallRng::seed_from_u64(seed);
844 if self.is_spinor() {
845 if rng.random_bool(0.5) {
846 Helicity::PLUS
847 } else {
848 Helicity::MINUS
849 }
850 } else if self.is_vector() {
851 Helicity::try_from(rng.random_range(1..=1)).unwrap()
852 } else {
853 Helicity::ZERO
854 }
855 }
856
857 fn spin_reps(&self) -> IndexLess<LibraryRep, Aind> {
858 Canonicalized::<IndexLess<LibraryRep, Aind>>::from_iter(match self.spin {
859 -1..=1 => vec![],
860 spin if spin > 0 && spin % 2 == 0 => {
861 vec![Bispinor {}.new_rep(4).cast(); spin.div_euclid(2) as usize]
862 }
863 spin if spin > 0 => {
864 vec![Minkowski {}.new_rep(4).cast(); spin.div_euclid(2) as usize]
865 }
866 _ => vec![],
867 })
868 .into_canonical()
869 }
870
871 fn color_reps(&self, flow: Flow) -> IndexLess {
872 let reps = ColorRepresentation::from_ufo(self.color).map(|representation| {
873 match flow {
874 Flow::Source => representation,
875 Flow::Sink => representation.dual(),
876 }
877 .representation()
878 });
879 Canonicalized::<IndexLess>::from_iter(reps).into_canonical()
880 }
881
882 fn polarization_sum(
883 &self,
884 model: &Model,
885 edge: EdgeIndex,
886 average: bool,
887 gauge: VectorPolarizationSumGauge,
888 ) -> Result<Option<Replacement>, Report> {
889 let sum = SpinSum::new(self, model)?
890 .averaged(average)
891 .covariant(gauge == VectorPolarizationSumGauge::Feynman);
892
893 Ok(match self.spin {
894 1 => None,
895 2 => {
896 let mu: Slot<Minkowski, AbstractIndex> =
897 Minkowski {}.new_rep(4).slot(AbstractIndex::new_dummy());
898 let slash = GS.emr_mom(edge, mu.to_atom())
899 * function!(AGS.gamma, W_.a_, W_.b_, mu.to_atom());
900 let rhs = sum.fermion(slash, &W_.a_.into(), &W_.b_.into())?;
901 sum.replacement(edge.0, [W_.a_.into(), W_.b_.into()], rhs)
902 }
903 3 => {
904 let reference = match gauge {
905 VectorPolarizationSumGauge::Feynman => None,
906 VectorPolarizationSumGauge::LightLikeAxial if !self.is_massless(model) => None,
907 VectorPolarizationSumGauge::LightLikeAxial => {
908 let temporal_component = GS.emr_mom(edge, GS.cind(0));
909 let n_a = temporal_component.clone() * GS.energy_delta(W_.a_)
910 - GS.emr_vec(edge, W_.a_);
911 let n_b = temporal_component.clone() * GS.energy_delta(W_.b_)
912 - GS.emr_vec(edge, W_.b_);
913 let minkowski = Minkowski {}.new_rep(4).to_symbolic([]);
916 let q_dot_n = temporal_component.pow(2)
917 - function!(
918 spenso::network::tags::SPENSO_TAG.dot,
919 GS.emr_vec(edge, &minkowski),
920 GS.emr_vec(edge, &minkowski)
921 );
922 Some(AxialReference {
923 left: n_a,
924 right: n_b,
925 momentum_dot_reference: q_dot_n,
926 norm_squared: Atom::Zero,
927 })
928 }
929 };
930 let rhs = sum.vector(
931 [&GS.emr_mom(edge, W_.a_), &GS.emr_mom(edge, W_.b_)],
932 &W_.a_.into(),
933 &W_.b_.into(),
934 reference.as_ref(),
935 )?;
936 sum.replacement(edge.0, [W_.a_.into(), W_.b_.into()], rhs)
937 }
938 spin => {
939 return Err(eyre!(
940 "Polarization sum replacement for particle '{}' (PDG {}, spin {}) is not implemented yet.",
941 self.name,
942 self.pdg_code,
943 spin
944 ));
945 }
946 })
947 }
948}
949
950pub trait VertexRuleGammaLoopExt {
952 fn tensors(
953 &self,
954 model: &Model,
955 i: Aind,
956 j: Aind,
957 ) -> [ParamTensor<OrderedStructure<Euclidean, Aind>>; 3];
958 fn degree_of_divergence(&self, model: &Model) -> i32;
959}
960
961impl VertexRuleGammaLoopExt for VertexRule {
962 fn tensors(
963 &self,
964 model: &Model,
965 i: Aind,
966 j: Aind,
967 ) -> [ParamTensor<OrderedStructure<Euclidean, Aind>>; 3] {
968 let spin_structure = self
969 .lorentz_structures
970 .iter()
971 .map(|id| {
972 model
973 .lorentz_structure_by_id(*id)
974 .unwrap()
975 .structure
976 .clone()
977 })
978 .collect_vec();
979 let color_structure = self.color_structures.clone();
980
981 let color_slot = Euclidean {}.new_slot(color_structure.len(), i);
982 let spin_slot = Euclidean {}.new_slot(spin_structure.len(), j);
983 let color_structure = ParamTensor::composite(DataTensor::Dense(
984 DenseTensor::from_storage_data(
985 color_structure,
986 Canonicalized::from_iter([color_slot]).into_canonical(),
987 )
988 .unwrap(),
989 ));
990 let spin_structure = ParamTensor::composite(DataTensor::Dense(
991 DenseTensor::from_storage_data(
992 spin_structure,
993 Canonicalized::from_iter([spin_slot]).into_canonical(),
994 )
995 .unwrap(),
996 ));
997 let coupling_structure = Canonicalized::from_iter([color_slot, spin_slot]);
998 let coupling_layout = TensorDataLayout::from_canonicalized(&coupling_structure)
999 .expect("vertex coupling dimensions are concrete");
1000 let mut couplings = ParamTensor::composite(DataTensor::Sparse(SparseTensor::empty(
1001 coupling_structure.into_canonical(),
1002 Atom::Zero,
1003 )));
1004 for (color, row) in self.couplings.iter().enumerate() {
1005 for (spin, coupling) in row.iter().enumerate() {
1006 if let Some(coupling) = coupling {
1007 couplings
1008 .set(
1009 &coupling_layout
1010 .logical_expanded_to_storage_expanded(&[color, spin])
1011 .expect("vertex coupling coordinates match their dimensions"),
1012 Atom::from(UFOSymbol::from(
1013 &model.coupling_by_id(*coupling).unwrap().name,
1014 )),
1015 )
1016 .unwrap();
1017 }
1018 }
1019 }
1020 [color_structure, couplings, spin_structure]
1021 }
1022
1023 fn degree_of_divergence(&self, model: &Model) -> i32 {
1024 self.lorentz_structures
1025 .iter()
1026 .map(|id| {
1027 model
1028 .lorentz_structure_by_id(*id)
1029 .unwrap()
1030 .structure
1031 .all_dod(GS.emr_mom)
1032 .expect("model momentum power counting failed")
1033 })
1034 .max()
1035 .unwrap_or_default()
1036 }
1037}
1038
1039pub trait PropagatorGammaLoopExt {
1041 fn numerator_atom(&self) -> Atom;
1042 fn denominator_atom(&self) -> Atom;
1043 fn degree_of_divergence(&self) -> i32;
1044}
1045
1046impl PropagatorGammaLoopExt for Propagator {
1047 fn numerator_atom(&self) -> Atom {
1048 self.numerator.clone()
1049 }
1050
1051 fn denominator_atom(&self) -> Atom {
1052 self.denominator.clone()
1053 }
1054
1055 fn degree_of_divergence(&self) -> i32 {
1056 (self.numerator_atom() / self.denominator_atom())
1057 .all_dod(GS.emr_mom)
1058 .expect("model momentum power counting failed")
1059 }
1060}
1061
1062#[cfg(test)]
1063mod tests {
1064 use super::*;
1065 use feynkit_amplitude::ColorSum;
1066 use idenso::tensor::{ContractSettings, SymbolicTensor};
1067 use spenso::{network::library::symbolic::ETS, structure::TensorStructure};
1068
1069 #[test]
1070 fn runtime_color_ports_match_shared_completeness_for_both_flows() {
1071 let model = Model::from_json(include_str!(
1072 "../../../feynkit-model/tests/fixtures/sm.json"
1073 ))
1074 .unwrap();
1075 let mut particle = model
1076 .particle_by_id(model.particle_id_by_pdg(5).unwrap())
1077 .unwrap()
1078 .clone();
1079 let left = parse!("color_left");
1080 let right = parse!("color_right");
1081 for color in [1, 3, -3, 6, -6, 8] {
1082 particle.color = color;
1083 let source = particle.color_reps(Flow::Source);
1084 let sink = particle.color_reps(Flow::Sink);
1085 let source_reps = source.external_reps_iter().collect::<Vec<_>>();
1086 let sink_reps = sink.external_reps_iter().collect::<Vec<_>>();
1087 assert_eq!(source_reps.len(), sink_reps.len());
1088 let completeness = source_reps.into_iter().zip(sink_reps).fold(
1089 Atom::one(),
1090 |product, (source, sink)| {
1091 product
1092 * ETS.metric(
1093 source.to_symbolic([left.clone()]),
1094 sink.to_symbolic([right.clone()]),
1095 )
1096 },
1097 );
1098 assert_eq!(
1099 completeness,
1100 ColorSum::new(&particle)
1101 .unwrap()
1102 .expression([left.clone(), right.clone()]),
1103 "runtime ports for UFO color {color}"
1104 );
1105 let contracted = SymbolicTensor::infer(
1106 completeness
1107 .replace(right.to_pattern())
1108 .with(left.to_pattern()),
1109 )
1110 .unwrap()
1111 .contract(ContractSettings {
1112 rank_one: false,
1113 collect_chains: false,
1114 collect_traces: false,
1115 ..Default::default()
1116 })
1117 .unwrap();
1118 assert_eq!(
1119 contracted.expression(),
1120 &Atom::num(color.unsigned_abs()),
1121 "completeness trace for UFO color {color}"
1122 );
1123 }
1124 }
1125}