1use std::{
2 collections::BTreeMap,
3 hash::Hash,
4 ops::{Mul, Neg},
5 sync::Arc,
6};
7
8use crate::{
9 GammaLoopContext,
10 cff::CutCFFIndex,
11 integrands::process::param_builder::{FnMapEntry, NumeratorDefinition},
12 uv::approx::Rooted,
13};
14#[cfg(test)]
15use crate::{numerator::aind::Aind, utils::GS};
16use bincode_trait_derive::{Decode, Encode};
17use color_eyre::Result;
18use eyre::eyre;
19use idenso::tensor::SymbolicTensor;
20use itertools::{EitherOrBoth, Itertools};
21use spenso::structure::IndexedStructure;
22#[cfg(test)]
23use spenso::{
24 network::parsing::ShadowedStructure,
25 structure::{
26 NamedStructure, ToSymbolic,
27 dimension::Dimension,
28 representation::{Minkowski, RepName},
29 },
30};
31use symbolica::{
32 atom::{Atom, AtomCore, AtomView, Symbol},
33 symbol,
34};
35
36use linnet::half_edge::involution::HedgePair;
37
38#[cfg(test)]
41pub(crate) fn spenso_lor(
42 tag: i32,
43 ind: impl Into<Aind>,
44 dim: impl Into<Dimension>,
45) -> ShadowedStructure<Aind> {
46 let mink = Minkowski {}.new_slot(dim, ind);
47 NamedStructure::from_iter([mink], GS.emr_mom, Some(vec![Atom::num(tag)])).into_canonical()
48}
49
50#[cfg(test)]
51pub(crate) fn spenso_lor_atom(tag: i32, ind: impl Into<Aind>, dim: impl Into<Dimension>) -> Atom {
52 spenso_lor(tag, ind, dim).to_symbolic(None).unwrap()
53}
54
55#[derive(Clone, Debug, PartialEq, Eq, Hash, Encode, Decode)]
59#[trait_decode(trait = GammaLoopContext)]
60pub struct Integrands {
61 atoms: BTreeMap<CutCFFIndex, Atom>,
62 numerators: Vec<Arc<NumeratorDefinition>>,
63 scalars: Vec<Arc<FnMapEntry>>,
64}
65
66impl Integrands {
67 pub fn map<F: FnMut(&Atom) -> Atom>(&self, mut f: F) -> Self {
68 Self {
69 atoms: self.iter().map(|(key, atom)| (*key, f(atom))).collect(),
70 numerators: self.numerators.clone(),
71 scalars: self.scalars.clone(),
72 }
73 }
74
75 pub fn fallible_map<F: FnMut(&Atom) -> Result<Atom>>(&self, mut f: F) -> Result<Self> {
76 Ok(Self {
77 atoms: self
78 .iter()
79 .map(|(key, atom)| Ok((*key, f(atom)?)))
80 .collect::<Result<_>>()?,
81 numerators: self.numerators.clone(),
82 scalars: self.scalars.clone(),
83 })
84 }
85
86 pub fn iter(&self) -> impl Iterator<Item = (&CutCFFIndex, &Atom)> {
88 self.atoms.iter()
89 }
90
91 pub fn expressions(&self) -> impl Iterator<Item = &Atom> {
103 self.atoms
104 .values()
105 .chain(self.definitions().map(|(_, body)| body))
106 }
107
108 pub fn definitions(&self) -> impl Iterator<Item = (&Atom, &Atom)> {
110 self.numerators
111 .iter()
112 .map(|entry| (&entry.lhs, entry.rhs.expression()))
113 .chain(self.scalars.iter().map(|entry| (&entry.lhs, &entry.rhs)))
114 }
115
116 pub(crate) fn numerators(&self) -> &[Arc<NumeratorDefinition>] {
117 &self.numerators
118 }
119
120 pub(crate) fn scalar_symbol() -> Symbol {
121 symbol!("gammalooprs::uv::scalar_coefficient"; Scalar)
122 }
123
124 pub(crate) fn scalar_definitions(&self) -> &[Arc<FnMapEntry>] {
125 &self.scalars
126 }
127
128 pub(crate) fn with_scalar_definitions(
132 mut self,
133 scalars: impl IntoIterator<Item = Arc<FnMapEntry>>,
134 ) -> Result<Self> {
135 let head = Self::scalar_symbol();
136 let mut definitions: BTreeMap<Vec<Atom>, Arc<FnMapEntry>> = BTreeMap::new();
137 for entry in scalars {
138 if let Some(existing) = definitions.get(&entry.tags) {
139 if Arc::ptr_eq(existing, &entry) || existing == &entry {
140 continue;
141 }
142 return Err(eyre!(
143 "conflicting retained scalar definition for {}",
144 entry.lhs
145 ));
146 }
147 let parameters = entry
148 .args
149 .iter()
150 .cloned()
151 .map(Atom::from)
152 .collect::<Vec<_>>();
153 if entry.tags.is_empty()
154 || entry.is_alias
155 || entry.tags.iter().any(|tag| tag.contains_symbol(head))
156 || entry.lhs != head.call_args(entry.tags.iter().chain(¶meters))
157 || parameters.iter().enumerate().any(|(index, parameter)| {
158 !matches!(parameter.as_view(), AtomView::Var(_))
159 || entry.tags.iter().any(|tag| tag.contains(parameter))
160 || parameters[..index].contains(parameter)
161 })
162 {
163 return Err(eyre!("invalid retained scalar binding {}", entry.lhs));
164 }
165 let mut invalid = false;
166 entry.rhs.visitor(&mut |view| {
167 let valid = match view {
168 AtomView::Num(_) | AtomView::Add(_) | AtomView::Mul(_) | AtomView::Pow(_) => {
169 true
170 }
171 AtomView::Var(_) => parameters
172 .iter()
173 .any(|parameter| parameter.as_view() == view),
174 _ => false,
175 };
176 invalid |= !valid;
177 valid
178 });
179 if invalid {
180 return Err(eyre!(
181 "retained scalar bodies must contain only arithmetic in their formals: {}",
182 entry.lhs
183 ));
184 }
185 definitions.insert(entry.tags.clone(), entry);
186 }
187 self.scalars = definitions.into_values().collect();
188 Ok(self)
189 }
190
191 pub(crate) fn scalar_resolver(
194 scalars: impl IntoIterator<Item = Arc<FnMapEntry>>,
195 ) -> Result<impl FnMut(&Atom) -> Result<Atom>> {
196 let validated = Self::from_iter([]).with_scalar_definitions(scalars)?;
197 let mut replacements = BTreeMap::new();
198 for entry in &validated.scalars {
199 replacements
200 .entry(entry.tags.len())
201 .or_insert_with(BTreeMap::new)
202 .insert(
203 entry.tags.clone(),
204 (entry.tags.len() + entry.args.len(), entry.replacement()),
205 );
206 }
207 let head = Self::scalar_symbol();
208 let mut cache = BTreeMap::<Atom, Atom>::new();
209 Ok(move |atom: &Atom| -> Result<Atom> {
210 if !atom.contains_symbol(head) {
211 return Ok(atom.clone());
212 }
213 let mut error = None;
214 let result = atom.replace_map_bottom_up(|view, _, out| {
215 let AtomView::Fun(call) = view else {
216 return;
217 };
218 if call.get_symbol() != head || error.is_some() {
219 return;
220 }
221 let original = view.to_owned();
222 if let Some(cached) = cache.get(&original) {
223 **out = cached.clone();
224 return;
225 }
226 let mut matched = None;
227 for (tag_count, definitions) in &replacements {
228 let tags = call
229 .iter()
230 .take(*tag_count)
231 .map(|arg| arg.to_owned())
232 .collect::<Vec<_>>();
233 if let Some((arity, replacement)) = definitions.get(&tags)
234 && *arity == call.get_nargs()
235 {
236 if matched.is_some() {
237 error = Some(eyre!("ambiguous retained scalar call {view}"));
238 return;
239 }
240 matched = Some(replacement);
241 }
242 }
243 let Some(replacement) = matched else {
244 error = Some(eyre!("unresolved retained scalar call {view}"));
245 return;
246 };
247 let resolved = view.replace_multiple([replacement]);
248 if resolved.contains_symbol(head) {
249 error = Some(eyre!("unresolved or cyclic retained scalar call {view}"));
250 return;
251 }
252 cache.insert(original, resolved.clone());
253 **out = resolved;
254 });
255 if let Some(error) = error {
256 Err(error)
257 } else {
258 Ok(result)
259 }
260 })
261 }
262
263 #[cfg(test)]
264 pub(crate) fn resolve_scalar(&self, atom: &Atom) -> Result<Atom> {
265 Self::scalar_resolver(self.scalars.iter().cloned())?(atom)
266 }
267
268 pub(crate) fn resolved_scalars(&self) -> Result<Self> {
272 let mut resolve = Self::scalar_resolver(self.scalars.iter().cloned())?;
273 let mut resolved = self.fallible_map(&mut resolve)?.map_numerators(|tensor| {
274 Ok(tensor.with_checked_expression(resolve(tensor.expression())?)?)
275 })?;
276 resolved.scalars.clear();
277 Ok(resolved)
278 }
279
280 pub(crate) fn with_numerators(
283 mut self,
284 numerators: impl IntoIterator<Item = Arc<NumeratorDefinition>>,
285 ) -> Result<Self> {
286 let family = symbol!("gammalooprs::uv::numerator_family");
287 let mut definitions: BTreeMap<Vec<Atom>, Arc<NumeratorDefinition>> = BTreeMap::new();
288 for numerator in numerators {
289 let parameters = numerator
290 .args
291 .iter()
292 .cloned()
293 .map(Atom::from)
294 .collect::<Vec<_>>();
295 if numerator.tags.is_empty()
296 || numerator.lhs
297 != family.call_args(
298 numerator
299 .tags
300 .iter()
301 .cloned()
302 .chain(parameters.iter().cloned()),
303 )
304 || parameters.iter().enumerate().any(|(index, parameter)| {
307 numerator.tags.iter().any(|tag| tag.contains(parameter))
308 || parameters[..index].iter().any(|other| {
309 other.contains(parameter) || parameter.contains(other)
310 })
311 })
312 {
313 return Err(eyre!(
314 "invalid retained numerator binding {}",
315 numerator.lhs
316 ));
317 }
318 if let Some(existing) = definitions.get(&numerator.tags) {
319 if existing != &numerator {
320 return Err(eyre!(
321 "conflicting retained numerator definition for {}",
322 numerator.lhs
323 ));
324 }
325 continue;
326 }
327 if numerator.rhs.expression().contains_symbol(family) {
328 return Err(eyre!(
329 "retained numerator definitions must be flat: {} contains a family call",
330 numerator.lhs
331 ));
332 }
333 definitions.insert(numerator.tags.clone(), numerator);
334 }
335 self.numerators = definitions.into_values().collect();
336 Ok(self)
337 }
338
339 pub(crate) fn map_numerators(
342 &self,
343 mut map: impl FnMut(
344 &SymbolicTensor<IndexedStructure>,
345 ) -> Result<SymbolicTensor<IndexedStructure>>,
346 ) -> Result<Self> {
347 let numerators = self
348 .numerators
349 .iter()
350 .map(|entry| {
351 let rhs = map(&entry.rhs)?;
352 Ok(
353 if rhs == entry.rhs && rhs.same_reduction_state(&entry.rhs) {
354 Arc::clone(entry)
355 } else {
356 Arc::new(FnMapEntry {
357 rhs,
358 ..entry.as_ref().clone()
359 })
360 },
361 )
362 })
363 .collect::<Result<Vec<_>>>()?;
364 self.clone().with_numerators(numerators)
365 }
366
367 pub(crate) fn resolved(&self) -> Result<Self> {
371 let validated = self.resolved_scalars()?;
372 let replacements = validated
373 .numerators
374 .iter()
375 .map(|entry| entry.replacement())
376 .collect::<Vec<_>>();
377 let mut resolved = validated.map(|atom| atom.replace_multiple(&replacements));
378 let family = symbol!("gammalooprs::uv::numerator_family");
379 if resolved
380 .iter()
381 .any(|(_, atom)| atom.contains_symbol(family))
382 {
383 return Err(eyre!("unresolved or cyclic retained numerator family call"));
384 }
385 resolved.numerators.clear();
386 Ok(resolved)
387 }
388
389 pub(crate) fn zero_like(&self) -> Self {
390 self.map(|_| Atom::Zero)
391 }
392
393 pub fn checked_zip(
394 &self,
395 other: &Integrands,
396 mut map: impl FnMut(&CutCFFIndex, &Atom, &Atom) -> Result<Atom>,
397 ) -> Result<Integrands> {
398 let atoms = self
399 .iter()
400 .merge_join_by(other.iter(), |(left_key, _), (right_key, _)| {
401 left_key.cmp(right_key)
402 })
403 .map(|pair| match pair {
404 EitherOrBoth::Both((key, left), (_, right)) => Ok((*key, map(key, left, right)?)),
405 EitherOrBoth::Left((key, _)) => {
406 Err(eyre!("right integrands are missing key {key:?}"))
407 }
408 EitherOrBoth::Right((key, _)) => {
409 Err(eyre!("left integrands are missing key {key:?}"))
410 }
411 })
412 .collect::<Result<_>>()?;
413 Self {
414 atoms,
415 numerators: Vec::new(),
416 scalars: Vec::new(),
417 }
418 .with_numerators(self.numerators.iter().chain(&other.numerators).cloned())?
419 .with_scalar_definitions(self.scalars.iter().chain(&other.scalars).cloned())
420 }
421
422 pub fn zip_mul(&self, other: &Integrands) -> Result<Integrands> {
423 self.checked_zip(other, |_, v1, v2| Ok(v1 * v2))
424 }
425
426 pub fn zip_add(self, others: impl IntoIterator<Item = Self>) -> Result<Self> {
429 let mut numerators = self.numerators;
430 let mut scalars = self.scalars;
431 let mut terms = self
432 .atoms
433 .into_iter()
434 .map(|(key, atom)| (key, vec![atom]))
435 .collect::<BTreeMap<_, _>>();
436 for other in others {
437 numerators.extend(other.numerators);
438 scalars.extend(other.scalars);
439 for pair in terms
440 .iter_mut()
441 .merge_join_by(other.atoms, |(left, _), (right, _)| (*left).cmp(right))
442 {
443 match pair {
444 EitherOrBoth::Both((_, terms), (_, atom)) => terms.push(atom),
445 EitherOrBoth::Left((key, _)) => {
446 return Err(eyre!("right integrands are missing key {key:?}"));
447 }
448 EitherOrBoth::Right((key, _)) => {
449 return Err(eyre!("left integrands are missing key {key:?}"));
450 }
451 }
452 }
453 }
454 Self {
455 atoms: terms
456 .into_iter()
457 .map(|(key, terms)| (key, Atom::add_many(terms)))
458 .collect(),
459 numerators: Vec::new(),
460 scalars: Vec::new(),
461 }
462 .with_numerators(numerators)?
463 .with_scalar_definitions(scalars)
464 }
465}
466
467impl FromIterator<(CutCFFIndex, Atom)> for Integrands {
468 fn from_iter<I: IntoIterator<Item = (CutCFFIndex, Atom)>>(iter: I) -> Self {
469 Self {
470 atoms: BTreeMap::from_iter(iter),
471 numerators: Vec::new(),
472 scalars: Vec::new(),
473 }
474 }
475}
476
477impl Mul<Atom> for Integrands {
478 type Output = Self;
479
480 fn mul(self, rhs: Atom) -> Self::Output {
481 self.map(|a| a * &rhs)
482 }
483}
484
485impl Neg for Integrands {
486 type Output = Self;
487
488 fn neg(self) -> Self::Output {
489 self.map(|a| a.neg())
490 }
491}
492
493impl Mul<&Atom> for Integrands {
494 type Output = Self;
495
496 fn mul(self, rhs: &Atom) -> Self::Output {
497 self.map(|a| a * rhs)
498 }
499}
500
501impl Rooted for Integrands {
502 fn root() -> Self {
503 [(CutCFFIndex::new_all_none(), Atom::num(1))]
504 .into_iter()
505 .collect()
506 }
507}
508
509#[allow(dead_code)]
510pub(crate) fn is_not_paired(pair: &HedgePair) -> bool {
511 !pair.is_paired()
512}
513
514pub mod hedge_poset;
515mod marker;
516mod orchestrator;
517#[cfg(test)]
518pub(crate) mod overlap_control;
519#[cfg(test)]
520pub(crate) mod overlap_numerators;
521pub mod renormalization;
522pub use renormalization::{RenormalizationPart, RenormalizationStats};
523pub mod settings;
524pub use settings::{
525 ApproximationType, CTIdentifier, CTRenormalizationRule, RenormalizationPrescriptionSettings,
526 UVOrchestrator, UVgenerationSettings,
527};
528pub mod uv_graph;
529pub use uv_graph::UltravioletGraph;
530
531pub mod spinney;
532pub use spinney::Spinney;
533
534pub mod poset;
535pub use poset::Poset;
536
537pub mod wood;
538pub use wood::Wood;
539
540pub mod approx;
541
542pub mod export;
543
544pub mod forest;
545pub use forest::Forest;
546
547pub mod profile;
548pub use profile::{UVProfile, UVProfileAnalysis, UVProfilePassFail};
549
550#[cfg(test)]
551mod tests;