1#![forbid(unsafe_code)]
8
9mod color;
10mod spin;
11
12pub use color::{ColorRepresentation, ColorSum, ColorSumError};
13pub use spin::{AxialReference, SpinSum, SpinSumError};
14
15use feynkit_graph::{
16 DiagramError, ExternalState, FeynmanDiagram, expressions::evaluate_overall_factor, symbols,
17};
18use feynkit_model::{Model, ModelError, ParameterType, ParticleId};
19use idenso::{
20 CookMode, CookSettings,
21 dirac::GammaSimplifySettings,
22 representations::Bispinor,
23 tensor::{SymbolicTensor, inference::TensorInferenceError},
24};
25use linnet::half_edge::involution::HedgePair;
26use spenso::{
27 network::{library::symbolic::ETS, tags::SPENSO_TAG},
28 structure::{
29 abstract_index::AbstractIndex,
30 dimension::Dimension,
31 partial::{PartialIndex, PartialStructure, PartialStructureExt},
32 representation::{LibrarySlot, Minkowski},
33 slot::{DualSlotTo, IsAbstractSlot, ParseableAind},
34 },
35};
36use std::{
37 collections::{BTreeMap, BTreeSet},
38 sync::Arc,
39};
40use symbolica::atom::{Atom, AtomCore, Symbol};
41use symbolica::id::{Pattern, Replacement};
42use symbolica::{function, symbol};
43use thiserror::Error;
44
45#[derive(Debug, Error)]
47pub enum AmplitudeError {
48 #[error("an amplitude needs at least one diagram")]
49 Empty,
50 #[error("diagram '{0}' belongs to a different model")]
51 DifferentModel(String),
52 #[error("diagram '{0}' has incompatible external states or tensor ports")]
53 DifferentExternals(String),
54 #[error("diagram '{0}' is already sewn; construct an amplitude from unsewn diagrams")]
55 SewnDiagram(String),
56 #[error(
57 "diagram '{0}' is a selection-only cross-section diagram: a spectator cut selected it, and it has no physical cut to construct an amplitude from"
58 )]
59 SelectionOnlyDiagram(String),
60 #[error("cannot identify external tensor ports in diagram '{0}': {1}")]
61 ExternalPorts(String, String),
62 #[error("external leg {0} does not exist")]
63 UnknownLeg(usize),
64 #[error("{kind} states of external leg {index} have already been summed")]
65 AlreadySummed { kind: &'static str, index: usize },
66 #[error(
67 "covariant polarization sums on colored massless vector legs {0:?} keep unphysical states that cancel only against ghosts; give all but one of them a reference"
68 )]
69 CovariantColoredVectors(Vec<usize>),
70 #[error("invalid tensor expression: {0}")]
71 Tensor(String),
72 #[error(transparent)]
73 Diagram(#[from] DiagramError),
74 #[error(transparent)]
75 Model(#[from] ModelError),
76 #[error(transparent)]
77 Spin(#[from] SpinSumError),
78 #[error(transparent)]
79 Color(#[from] ColorSumError),
80}
81
82impl From<TensorInferenceError> for AmplitudeError {
83 fn from(error: TensorInferenceError) -> Self {
84 Self::Tensor(error.to_string())
85 }
86}
87
88impl From<idenso::tensor::composition::TensorCompositionError> for AmplitudeError {
89 fn from(error: idenso::tensor::composition::TensorCompositionError) -> Self {
90 Self::Tensor(error.to_string())
91 }
92}
93
94impl From<idenso::AdjointError> for AmplitudeError {
95 fn from(error: idenso::AdjointError) -> Self {
96 Self::Tensor(error.to_string())
97 }
98}
99
100#[derive(Clone, Debug)]
103pub struct AmplitudeOptions {
104 pub dimension: Dimension,
105 pub real: Vec<Atom>,
106}
107
108impl Default for AmplitudeOptions {
109 fn default() -> Self {
110 Self {
111 dimension: Dimension::Concrete(4),
112 real: Vec::new(),
113 }
114 }
115}
116
117#[derive(Clone, Debug, PartialEq, Eq)]
119pub struct AmplitudeLeg {
120 pub index: usize,
121 pub particle: ParticleId,
122 pub state: ExternalState,
123 pub slots: Vec<LibrarySlot<AbstractIndex>>,
124 pub tensor_index: AbstractIndex,
125}
126
127impl AmplitudeLeg {
128 pub fn momentum(&self) -> Atom {
130 symbols::external_momentum().call(self.index)
131 }
132
133 pub fn index_atom(&self) -> Atom {
135 self.tensor_index.to_atom()
136 }
137
138 fn color_slot(&self) -> Option<LibrarySlot<AbstractIndex>> {
139 self.slots
140 .iter()
141 .copied()
142 .find(|s| s.rep_name() != Bispinor {}.into() && s.rep_name() != Minkowski {}.into())
143 }
144}
145
146#[derive(Clone, Debug)]
151pub struct Amplitude {
152 diagrams: Vec<Arc<FeynmanDiagram>>,
153 terms: Vec<SymbolicTensor<PartialStructure>>,
154 legs: Vec<AmplitudeLeg>,
155 options: AmplitudeOptions,
156 conjugated: bool,
157}
158
159impl Amplitude {
160 pub fn from_diagram(diagram: impl Into<Arc<FeynmanDiagram>>) -> Result<Self, AmplitudeError> {
161 Self::from_diagrams([diagram.into()])
162 }
163
164 pub fn from_diagrams(
165 diagrams: impl IntoIterator<Item = Arc<FeynmanDiagram>>,
166 ) -> Result<Self, AmplitudeError> {
167 Self::new(diagrams, AmplitudeOptions::default())
168 }
169
170 pub fn new(
171 diagrams: impl IntoIterator<Item = Arc<FeynmanDiagram>>,
172 options: AmplitudeOptions,
173 ) -> Result<Self, AmplitudeError> {
174 let diagrams: Vec<_> = diagrams.into_iter().collect();
175 let first = diagrams.first().ok_or(AmplitudeError::Empty)?;
176 let fingerprint = first.model().fingerprint();
177 let mut terms = Vec::with_capacity(diagrams.len());
178 let mut legs = Vec::new();
179 for diagram in &diagrams {
180 diagram.validate()?;
181 if !Arc::ptr_eq(&first.model_arc(), &diagram.model_arc())
182 && diagram.model().fingerprint() != fingerprint
183 {
184 return Err(AmplitudeError::DifferentModel(diagram.name().to_owned()));
185 }
186 let (term, external) = Self::diagram_term(diagram, &options)?;
187 if terms.is_empty() {
188 legs = external;
189 } else if legs != external {
190 return Err(AmplitudeError::DifferentExternals(
191 diagram.name().to_owned(),
192 ));
193 }
194 terms.push(term);
195 }
196 Ok(Self {
197 diagrams,
198 terms,
199 legs,
200 options,
201 conjugated: false,
202 })
203 }
204
205 pub fn diagrams(&self) -> &[Arc<FeynmanDiagram>] {
206 &self.diagrams
207 }
208 pub fn terms(&self) -> &[SymbolicTensor<PartialStructure>] {
209 &self.terms
210 }
211 pub fn legs(&self) -> &[AmplitudeLeg] {
212 &self.legs
213 }
214 pub fn model(&self) -> &Model {
215 self.diagrams[0].model()
216 }
217 pub fn dimension(&self) -> Dimension {
218 self.options.dimension
219 }
220 pub fn is_conjugated(&self) -> bool {
221 self.conjugated
222 }
223
224 pub fn expression(&self) -> Result<SymbolicTensor<PartialStructure>, AmplitudeError> {
225 let (first, rest) = self.terms.split_first().ok_or(AmplitudeError::Empty)?;
226 rest.iter()
227 .try_fold(first.clone(), |sum, term| Ok(sum.try_add(term)?))
228 }
229
230 pub fn structure(&self) -> PartialStructure {
232 PartialStructure::from_logical_slots(
233 self.legs
234 .iter()
235 .flat_map(|leg| &leg.slots)
236 .map(|slot| slot.rep().slot(PartialIndex::Explicit(slot.aind))),
237 )
238 }
239
240 pub fn conjugate(&self) -> Result<Self, AmplitudeError> {
244 let mut result = self.clone();
245 for leg in &mut result.legs {
246 leg.slots = leg.slots.iter().map(|slot| slot.dual()).collect();
247 leg.slots.sort();
248 }
249 let interface = result.structure();
250 let settings = GammaSimplifySettings {
251 gamma0: true,
252 evaluate_traces: false,
253 ..GammaSimplifySettings::default()
254 };
255 result.terms = self
256 .terms
257 .iter()
258 .map(|term| {
259 let adjoint = term.dirac_adjoint(true)?;
260 let adjoint = self.apply_reality(&adjoint)?;
261 SymbolicTensor::from_declared_parts(adjoint.expression().clone(), interface.clone())
264 .and_then(|value| {
265 value.simplify_algebra(&idenso::tensor::AlgebraSettings {
266 gamma: Some(settings),
267 epsilon: settings.output == idenso::dirac::GammaOutput::Reduced,
268 ..Default::default()
269 })
270 })
271 .and_then(|value| {
272 value.contract(idenso::tensor::ContractSettings {
273 collect_chains: false,
274 collect_traces: false,
275 ..Default::default()
276 })
277 })
278 .map_err(|error| AmplitudeError::Tensor(error.to_string()))
279 })
280 .collect::<Result<_, AmplitudeError>>()?;
281 result.conjugated = !self.conjugated;
282 Ok(result)
283 }
284
285 pub fn squared(&self) -> Result<SquaredAmplitude, AmplitudeError> {
286 let amplitude = if self.conjugated {
288 self.conjugate()?
289 } else {
290 self.clone()
291 };
292 let adjoint = amplitude.conjugate()?;
293 let loop_index = symbol!("feynkit_amplitude::loop_");
295 let args = symbol!("feynkit_amplitude::loop_args___");
296 let bra = adjoint.expression()?.wrap_indices(Self::bra(), false)?;
297 let mapped = bra
298 .expression()
299 .replace(function!(symbols::loop_momentum(), loop_index, args))
300 .with(function!(
301 symbols::loop_momentum(),
302 Self::bra().call(loop_index),
303 args
304 ));
305 let bra = bra.with_checked_expression(mapped)?;
306 let expression = amplitude.expression()?.multiply(&bra)?;
307 Ok(SquaredAmplitude {
308 amplitude,
309 expression,
310 spin_summed: BTreeSet::new(),
311 covariant_colored: BTreeSet::new(),
312 color_summed: BTreeSet::new(),
313 })
314 }
315
316 fn bra() -> Symbol {
317 symbol!("feynkit_amplitude::bra")
318 }
319
320 fn apply_reality(
321 &self,
322 expression: &SymbolicTensor<PartialStructure>,
323 ) -> Result<SymbolicTensor<PartialStructure>, AmplitudeError> {
324 let conjugate = symbol!("spenso::conj");
325 let mut rules = Vec::new();
326 for parameter in self
327 .model()
328 .parameters()
329 .iter()
330 .filter(|p| p.parameter_type == ParameterType::Real)
331 {
332 let real = Atom::var(symbol!(&format!("UFO::{}", parameter.name)));
333 rules.push(Replacement::new(
336 Pattern::Literal(conjugate.call(&real)),
337 Pattern::Literal(real),
338 ));
339 }
340 for real in &self.options.real {
341 rules.push(Replacement::new(
342 Pattern::Literal(conjugate.call(real)),
343 Pattern::Literal(real.clone()),
344 ));
345 }
346 let args = symbol!("feynkit_amplitude::args___");
347 for head in [symbols::external_momentum(), symbols::loop_momentum()] {
348 let vector = head.call(args);
349 rules.push(Replacement::new(
350 conjugate.call(&vector).to_pattern(),
351 vector,
352 ));
353 }
354 let left = symbol!("feynkit_amplitude::left___");
357 let right = symbol!("feynkit_amplitude::right___");
358 for p in [symbols::external_momentum(), symbols::loop_momentum()] {
359 for q in [symbols::external_momentum(), symbols::loop_momentum()] {
360 let dot = function!(SPENSO_TAG.dot, p.call(left), q.call(right));
361 rules.push(Replacement::new(conjugate.call(&dot).to_pattern(), dot));
362 }
363 }
364 let dimension = self.options.dimension.to_symbolic();
365 rules.push(Replacement::new(
366 Pattern::Literal(conjugate.call(&dimension)),
367 Pattern::Literal(dimension),
368 ));
369 Ok(expression.with_checked_expression(expression.expression().replace_multiple(rules))?)
370 }
371
372 fn diagram_term(
373 diagram: &FeynmanDiagram,
374 options: &AmplitudeOptions,
375 ) -> Result<(SymbolicTensor<PartialStructure>, Vec<AmplitudeLeg>), AmplitudeError> {
376 if diagram.is_selection_only() {
377 return Err(AmplitudeError::SelectionOnlyDiagram(
378 diagram.name().to_owned(),
379 ));
380 }
381 if !diagram.cuts().is_empty() {
382 return Err(AmplitudeError::SewnDiagram(diagram.name().to_owned()));
383 }
384 let numerator = diagram
385 .numerator()
386 .multiply(diagram.numerator_prefactor())?
387 .with_lorentz_dimension(options.dimension)?;
388 let ports = numerator
389 .structure()
390 .logical_slots()
391 .into_iter()
392 .map(|slot| {
393 let PartialIndex::Explicit(index) = slot.aind else {
394 return Err(AmplitudeError::ExternalPorts(
395 diagram.name().to_owned(),
396 "physical external ports need explicit leg identities".into(),
397 ));
398 };
399 Ok(slot.rep().slot::<AbstractIndex, _>(index))
400 })
401 .collect::<Result<Vec<_>, _>>()?;
402 let cooking = CookSettings::indices()
403 .with_mode(CookMode::ReversibleEncoding)
404 .with_representation_payloads(true, true);
405 let mut legs = BTreeMap::new();
406 let mut identified = 0;
407 for (pair, _, edge) in diagram.underlying().iter_edges() {
408 let Some(external) = &edge.data.external else {
409 continue;
410 };
411 let HedgePair::Unpaired { hedge, .. } = pair else {
412 return Err(AmplitudeError::SewnDiagram(diagram.name().to_owned()));
413 };
414 let old_index = symbols::hedge_index().call((hedge.0, 1));
415 let mut leg = AmplitudeLeg {
416 index: external.index,
417 particle: edge.data.particle,
418 state: external.state,
419 slots: Vec::new(),
420 tensor_index: AbstractIndex::try_from(old_index.as_view())
421 .map_err(|e| AmplitudeError::Tensor(e.to_string()))?,
422 };
423 for slot in ports
424 .iter()
425 .filter(|s| cooking.uncook(s.aind.to_atom().as_view()) == old_index)
426 {
427 leg.tensor_index = slot.aind;
428 leg.slots.push(*slot);
429 identified += 1;
430 }
431 leg.slots.sort();
432 let particle = diagram.model().particle_by_id(leg.particle)?;
433 let expected = usize::from(particle.spin != 1) + usize::from(particle.color != 1);
434 if leg.slots.len() != expected || legs.insert(leg.index, leg).is_some() {
435 return Err(AmplitudeError::ExternalPorts(
436 diagram.name().to_owned(),
437 "missing, duplicate, or unsupported external slots".into(),
438 ));
439 }
440 }
441 if identified != ports.len() {
442 return Err(AmplitudeError::ExternalPorts(
443 diagram.name().to_owned(),
444 "unassigned open tensor slots".into(),
445 ));
446 }
447 let basis = diagram.loop_momentum_basis();
448 let mut momentum_rules = Vec::new();
449 let args = symbol!("feynkit_amplitude::momentum_args___");
450 for (position, edge) in basis.external_edges.iter().enumerate() {
451 let external = diagram
452 .edges()
453 .find(|(id, _, _)| id == edge)
454 .and_then(|(_, _, e)| e.external.as_ref())
455 .expect("validated external basis edge");
456 momentum_rules.push(Replacement::new(
457 function!(symbols::external_momentum(), position, args).to_pattern(),
458 function!(symbols::external_momentum(), external.index, args),
459 ));
460 }
461 let denominator = diagram.denominator_of_in_dimension(
462 &diagram.internal_subgraph(),
463 &BTreeMap::new(),
464 options.dimension,
465 )?;
466 let [a, b, c, d] = ["den_edge_", "den_momentum_", "den_mass_", "den_value_"]
467 .map(|s| symbol!(&format!("feynkit_amplitude::{s}")));
468 let denominator = denominator
469 .replace(function!(symbols::denominator(), a, b, c, d))
470 .with(d);
471 let factor = evaluate_overall_factor(diagram.overall_factor().as_view());
472 let expression = diagram
473 .model()
474 .expand_couplings(&(factor * numerator.expression() / denominator));
475 let expression = basis
476 .route_expression(&expression)
477 .replace_multiple(momentum_rules);
478 let numerator = numerator.with_checked_expression(expression)?;
479 let legs = legs.into_values().collect::<Vec<_>>();
480 let interface = PartialStructure::from_logical_slots(
481 legs.iter()
482 .flat_map(|leg| &leg.slots)
483 .map(|slot| slot.rep().slot(PartialIndex::Explicit(slot.aind))),
484 );
485 let numerator =
486 SymbolicTensor::from_declared_parts(numerator.expression().clone(), interface)?;
487 Ok((numerator, legs))
488 }
489}
490
491#[derive(Clone, Debug)]
493pub struct SquaredAmplitude {
494 amplitude: Amplitude,
495 expression: SymbolicTensor<PartialStructure>,
496 spin_summed: BTreeSet<usize>,
497 covariant_colored: BTreeSet<usize>,
499 color_summed: BTreeSet<usize>,
500}
501
502impl SquaredAmplitude {
503 pub fn from_diagram(diagram: impl Into<Arc<FeynmanDiagram>>) -> Result<Self, AmplitudeError> {
504 Amplitude::from_diagram(diagram)?.squared()
505 }
506 pub fn amplitude(&self) -> &Amplitude {
507 &self.amplitude
508 }
509 pub fn expression(&self) -> &SymbolicTensor<PartialStructure> {
510 &self.expression
511 }
512 pub fn spin_summed(&self) -> &BTreeSet<usize> {
513 &self.spin_summed
514 }
515 pub fn color_summed(&self) -> &BTreeSet<usize> {
516 &self.color_summed
517 }
518
519 pub fn sum_spins(
532 &self,
533 legs: &[usize],
534 average_initial: bool,
535 references: &BTreeMap<usize, Atom>,
536 spin_vectors: &BTreeMap<usize, Atom>,
537 ) -> Result<Self, AmplitudeError> {
538 let mut result = self.clone();
539 for &index in references.keys().chain(spin_vectors.keys()) {
540 if !legs.contains(&index) {
541 return Err(AmplitudeError::UnknownLeg(index));
542 }
543 }
544 for &index in legs {
545 let leg = self.leg(index)?;
546 if !result.spin_summed.insert(index) {
547 return Err(AmplitudeError::AlreadySummed {
548 kind: "spin",
549 index,
550 });
551 }
552 let particle = self.amplitude.model().particle_by_id(leg.particle)?;
553 if particle.spin == 3
554 && particle.color.unsigned_abs() != 1
555 && particle.is_massless(self.amplitude.model())
556 && !references.contains_key(&index)
557 {
558 result.covariant_colored.insert(index);
559 }
560 let sum = SpinSum::new(particle, self.amplitude.model())?
561 .with_dimension(&self.amplitude.dimension().to_symbolic())?
562 .averaged(average_initial && leg.state == ExternalState::Incoming);
563 let [ket, bra] = [
564 leg.index_atom(),
565 leg.tensor_index.scoped(Amplitude::bra()).to_atom(),
566 ];
567 let column = (leg.state == ExternalState::Incoming) != particle.is_antiparticle();
568 let indices = if column { [ket, bra] } else { [bra, ket] };
569 let completeness = SymbolicTensor::infer(sum.expression(
571 &leg.momentum(),
572 indices,
573 references.get(&index),
574 spin_vectors.get(&index),
575 )?)?;
576 result.expression = result.expression.multiply(&completeness)?;
577 }
578 if result.covariant_colored.len() > 1 {
579 return Err(AmplitudeError::CovariantColoredVectors(
580 result.covariant_colored.into_iter().collect(),
581 ));
582 }
583 Ok(result)
584 }
585
586 pub fn sum_colors(
588 &self,
589 legs: &[usize],
590 average_initial: bool,
591 ) -> Result<Self, AmplitudeError> {
592 let mut result = self.clone();
593 for &index in legs {
594 let leg = self.leg(index)?;
595 if !result.color_summed.insert(index) {
596 return Err(AmplitudeError::AlreadySummed {
597 kind: "color",
598 index,
599 });
600 }
601 let particle = self.amplitude.model().particle_by_id(leg.particle)?;
602 ColorSum::new(particle)?;
603 if let Some(slot) = leg.color_slot() {
604 let mut left = slot.dual();
605 left.aind = leg.tensor_index;
606 let mut right = slot;
607 right.aind = leg.tensor_index.scoped(Amplitude::bra());
608 let completeness =
609 SymbolicTensor::infer(ETS.metric(left.to_atom(), right.to_atom()))?;
610 result.expression = result.expression.multiply(&completeness)?;
611 if average_initial && leg.state == ExternalState::Incoming {
612 result.expression = result.expression.with_checked_expression(
613 result.expression.expression() / Atom::num(particle.color.unsigned_abs()),
614 )?;
615 }
616 }
617 }
618 Ok(result)
619 }
620
621 fn leg(&self, index: usize) -> Result<&AmplitudeLeg, AmplitudeError> {
622 self.amplitude
623 .legs
624 .iter()
625 .find(|l| l.index == index)
626 .ok_or(AmplitudeError::UnknownLeg(index))
627 }
628}