Skip to main content

feynkit_cff/
surface.rs

1use std::collections::BTreeMap;
2
3use linnet::half_edge::{
4    HedgeGraph,
5    involution::{Flow, HedgePair},
6    nodestore::NodeStorageOps,
7    subgraph::{OrientedCut, SubGraphLike},
8};
9use serde::{Deserialize, Serialize};
10use typed_index_collections::TiVec;
11
12use crate::{CffError, EdgeId, VertexId};
13
14pub(crate) const MAX_VERTEX_COUNT: usize = u64::BITS as usize;
15
16macro_rules! index_type {
17    ($name:ident) => {
18        #[derive(
19            Clone,
20            Copy,
21            Debug,
22            PartialEq,
23            Eq,
24            PartialOrd,
25            Ord,
26            Hash,
27            Serialize,
28            Deserialize,
29            bincode::Encode,
30            bincode::Decode,
31        )]
32        pub struct $name(pub usize);
33
34        impl $name {
35            pub const fn index(self) -> usize {
36                self.0
37            }
38        }
39
40        impl From<usize> for $name {
41            fn from(value: usize) -> Self {
42                Self(value)
43            }
44        }
45
46        impl From<$name> for usize {
47            fn from(value: $name) -> Self {
48                value.0
49            }
50        }
51    };
52}
53
54index_type!(EnergySurfaceId);
55index_type!(HSurfaceId);
56index_type!(RaisedEnergySurfaceId);
57
58/// One equivalence class of energy surfaces produced by raised propagators.
59#[derive(
60    Clone,
61    Debug,
62    PartialEq,
63    Eq,
64    PartialOrd,
65    Ord,
66    Hash,
67    Serialize,
68    Deserialize,
69    bincode::Encode,
70    bincode::Decode,
71)]
72pub struct RaisedEnergySurfaceGroup {
73    pub surface_ids: Vec<EnergySurfaceId>,
74    pub max_occurrence: usize,
75}
76
77/// Structural raised-surface information for one CFF expression.
78#[derive(
79    Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, bincode::Encode, bincode::Decode,
80)]
81pub struct RaisedEnergySurfaceData {
82    #[bincode(with_serde)]
83    pub groups: TiVec<RaisedEnergySurfaceId, RaisedEnergySurfaceGroup>,
84}
85
86/// A canonical linear combination of external edge energies.
87#[derive(
88    Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, bincode::Encode, bincode::Decode,
89)]
90pub struct ExternalShift(BTreeMap<EdgeId, i64>);
91
92impl ExternalShift {
93    pub fn new(terms: impl IntoIterator<Item = (EdgeId, i64)>) -> Result<Self, CffError> {
94        let mut shift = Self::default();
95        for (edge, coefficient) in terms {
96            shift.add(edge, coefficient)?;
97        }
98        Ok(shift)
99    }
100
101    pub fn get(&self, edge: EdgeId) -> i64 {
102        self.0.get(&edge).copied().unwrap_or(0)
103    }
104
105    pub fn iter(&self) -> impl Iterator<Item = (&EdgeId, &i64)> {
106        self.0.iter()
107    }
108
109    pub fn is_empty(&self) -> bool {
110        self.0.is_empty()
111    }
112
113    pub fn remove(&mut self, edge: EdgeId) -> Option<i64> {
114        self.0.remove(&edge)
115    }
116
117    pub(crate) fn add(&mut self, edge: EdgeId, coefficient: i64) -> Result<(), CffError> {
118        if coefficient == 0 {
119            return Ok(());
120        }
121        let new_coefficient = self
122            .get(edge)
123            .checked_add(coefficient)
124            .ok_or(CffError::ExternalShiftOverflow { edge })?;
125        if new_coefficient == 0 {
126            self.0.remove(&edge);
127        } else {
128            self.0.insert(edge, new_coefficient);
129        }
130        Ok(())
131    }
132
133    pub(crate) fn rewrite(
134        &mut self,
135        dependent: EdgeId,
136        replacement: &Self,
137    ) -> Result<(), CffError> {
138        let coefficient = self.get(dependent);
139        self.0.remove(&dependent);
140        for (edge, replacement_coefficient) in replacement.iter() {
141            let term = coefficient
142                .checked_mul(*replacement_coefficient)
143                .ok_or(CffError::ExternalShiftOverflow { edge: *edge })?;
144            self.add(*edge, term)?;
145        }
146        Ok(())
147    }
148}
149
150impl FromIterator<(EdgeId, i64)> for ExternalShift {
151    fn from_iter<T: IntoIterator<Item = (EdgeId, i64)>>(iter: T) -> Self {
152        Self::new(iter).expect("external-shift coefficients overflowed i64")
153    }
154}
155
156impl From<Vec<(EdgeId, i64)>> for ExternalShift {
157    fn from(value: Vec<(EdgeId, i64)>) -> Self {
158        value.into_iter().collect()
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use linnet::half_edge::{
165        HedgeGraph,
166        builder::HedgeGraphBuilder,
167        involution::{EdgeIndex, Flow, HedgePair, Orientation},
168        subgraph::{ModifySubSet, OrientedCut, SuBitGraph},
169    };
170
171    use super::*;
172
173    #[test]
174    fn duplicate_terms_report_coefficient_overflow() {
175        let edge = EdgeId::new(0);
176        assert_eq!(
177            ExternalShift::new([(edge, i64::MAX), (edge, 1)]),
178            Err(CffError::ExternalShiftOverflow { edge })
179        );
180    }
181
182    #[test]
183    fn rewrite_reports_multiplication_overflow() {
184        let dependent = EdgeId::new(0);
185        let replacement_edge = EdgeId::new(1);
186        let mut shift = ExternalShift::new([(dependent, i64::MAX)]).unwrap();
187        let replacement = ExternalShift::new([(replacement_edge, 2)]).unwrap();
188
189        assert_eq!(
190            shift.rewrite(dependent, &replacement),
191            Err(CffError::ExternalShiftOverflow {
192                edge: replacement_edge,
193            })
194        );
195    }
196
197    #[test]
198    fn cut_side_surface_preserves_original_edges_vertices_and_external_flow() {
199        let mut builder = HedgeGraphBuilder::<(), (), ()>::new();
200        let left = builder.add_node(());
201        let right = builder.add_node(());
202        builder.add_external_edge(left, (), Orientation::Undirected, Flow::Sink);
203        builder.add_edge(left, right, (), Orientation::Default);
204        builder.add_external_edge(right, (), Orientation::Undirected, Flow::Source);
205        let graph: HedgeGraph<(), (), ()> = builder.into();
206
207        let mut side: SuBitGraph = graph.empty_subgraph();
208        let (_, neighbours, _) = graph
209            .iter_nodes()
210            .find(|(vertex, _, _)| *vertex == left)
211            .unwrap();
212        neighbours.for_each(|hedge| side.add(hedge));
213
214        let HedgePair::Paired { source, .. } = graph[&EdgeIndex(1)].1 else {
215            panic!("the middle edge must be internal");
216        };
217        let mut crossing: SuBitGraph = graph.empty_subgraph();
218        crossing.add(source);
219        let crossing = OrientedCut::from_underlying_strict(crossing, &graph).unwrap();
220
221        let surface = EnergySurface::from_cut_side(&graph, &crossing, &side, None).unwrap();
222        assert_eq!(surface.energies, vec![EdgeIndex(1)]);
223        assert_eq!(surface.external_shift.get(EdgeIndex(0)), -1);
224        assert!(surface.vertex_set.contains(left));
225        assert!(!surface.vertex_set.contains(right));
226    }
227}
228
229/// Set of original vertices represented by a contracted CFF vertex.
230#[derive(
231    Clone,
232    Copy,
233    Debug,
234    Default,
235    PartialEq,
236    Eq,
237    PartialOrd,
238    Ord,
239    Hash,
240    Serialize,
241    Deserialize,
242    bincode::Encode,
243    bincode::Decode,
244)]
245pub struct VertexSet(u64);
246
247impl VertexSet {
248    pub fn singleton(vertex: VertexId) -> Self {
249        Self(1_u64 << vertex.index())
250    }
251
252    pub const fn union(self, other: Self) -> Self {
253        Self(self.0 | other.0)
254    }
255
256    pub fn from_usize(vertex: usize) -> Self {
257        Self::singleton(VertexId::new(vertex))
258    }
259
260    pub const fn dummy() -> Self {
261        Self(0)
262    }
263
264    pub const fn join(&self, other: &Self) -> Self {
265        self.union(*other)
266    }
267
268    pub fn contains(self, vertex: VertexId) -> bool {
269        vertex.index() < MAX_VERTEX_COUNT && self.0 & (1_u64 << vertex.index()) != 0
270    }
271
272    pub fn iter(self) -> impl Iterator<Item = VertexId> {
273        (0..MAX_VERTEX_COUNT)
274            .filter(move |index| self.0 & (1_u64 << index) != 0)
275            .map(VertexId::new)
276    }
277}
278
279/// An E-surface generated from an ordinary source or sink.
280#[derive(Clone, Debug, Serialize, Deserialize, bincode::Encode, bincode::Decode)]
281pub struct EnergySurface {
282    pub energies: Vec<EdgeId>,
283    pub external_shift: ExternalShift,
284    pub vertex_set: VertexSet,
285}
286
287impl EnergySurface {
288    /// Construct the energy surface associated with one side of an oriented cut.
289    ///
290    /// The crossing edges supply the positive on-shell energies. External shifts
291    /// are read either from an explicit initial-state cut or from the unpaired
292    /// edges incident on `side`. Original Linnet vertex identities are retained
293    /// in the resulting surface.
294    pub fn from_cut_side<E, V, H, N, C, S>(
295        graph: &HedgeGraph<E, V, H, N>,
296        crossing: &C,
297        side: &S,
298        initial_state_cut: Option<&OrientedCut>,
299    ) -> Result<Self, CffError>
300    where
301        N: NodeStorageOps<NodeData = V>,
302        C: SubGraphLike,
303        S: SubGraphLike,
304    {
305        let mut energies = graph
306            .iter_edges_of(crossing)
307            .map(|(_, edge, _)| edge)
308            .collect::<Vec<_>>();
309        energies.sort_unstable();
310
311        let mut external_shift = if let Some(initial_state_cut) = initial_state_cut {
312            graph
313                .iter_edges_of(initial_state_cut)
314                .map(|(_, edge, _)| (edge, -1))
315                .collect::<Vec<_>>()
316        } else {
317            graph
318                .iter_edges_of(side)
319                .filter_map(|(pair, edge, _)| match pair {
320                    HedgePair::Unpaired { flow, .. } => Some((
321                        edge,
322                        match flow {
323                            Flow::Sink => -1,
324                            Flow::Source => 1,
325                        },
326                    )),
327                    _ => None,
328                })
329                .collect::<Vec<_>>()
330        };
331        external_shift.sort_by_key(|(edge, _)| *edge);
332
333        let mut vertices = graph.iter_nodes_of(side).map(|(vertex, _, _)| vertex);
334        let first = vertices.next().ok_or(CffError::EmptyGraph)?;
335        if first.0 >= MAX_VERTEX_COUNT {
336            return Err(CffError::VertexIdentityOutOfRange {
337                vertex: first,
338                maximum: MAX_VERTEX_COUNT - 1,
339            });
340        }
341        let mut vertex_set = VertexSet::singleton(first);
342        for vertex in vertices {
343            if vertex.0 >= MAX_VERTEX_COUNT {
344                return Err(CffError::VertexIdentityOutOfRange {
345                    vertex,
346                    maximum: MAX_VERTEX_COUNT - 1,
347                });
348            }
349            vertex_set = vertex_set.union(VertexSet::singleton(vertex));
350        }
351
352        Ok(Self {
353            energies,
354            external_shift: ExternalShift::new(external_shift)?,
355            vertex_set,
356        })
357    }
358
359    pub(crate) fn cache_equivalent(&self, other: &Self) -> bool {
360        self.energies == other.energies && self.external_shift == other.external_shift
361    }
362}
363
364impl PartialEq for EnergySurface {
365    fn eq(&self, other: &Self) -> bool {
366        self.cache_equivalent(other)
367    }
368}
369
370impl Eq for EnergySurface {}
371
372/// An H-surface generated when a subgraph has severed internal edges.
373///
374/// This is the historical CFF “H-surface” name: in an amplitude subgraph it
375/// usually represents an E-surface of the containing graph.
376#[derive(Clone, Debug, Serialize, Deserialize, bincode::Encode, bincode::Decode)]
377pub struct HSurface {
378    pub positive_energies: Vec<EdgeId>,
379    pub negative_energies: Vec<EdgeId>,
380    pub external_shift: ExternalShift,
381    pub vertex_set: VertexSet,
382}
383
384impl PartialEq for HSurface {
385    fn eq(&self, other: &Self) -> bool {
386        self.cache_equivalent(other)
387    }
388}
389
390impl Eq for HSurface {}
391
392impl HSurface {
393    pub(crate) fn cache_equivalent(&self, other: &Self) -> bool {
394        // The signed on-shell energies and the external shift identify an
395        // H-surface; the originating vertices are metadata.
396        self.positive_energies == other.positive_energies
397            && self.negative_energies == other.negative_energies
398            && self.external_shift == other.external_shift
399    }
400}
401
402#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, bincode::Encode, bincode::Decode)]
403pub enum Surface {
404    Energy(EnergySurface),
405    H(HSurface),
406    Unit,
407    Infinite,
408}
409
410#[derive(
411    Clone,
412    Copy,
413    Debug,
414    PartialEq,
415    Eq,
416    PartialOrd,
417    Ord,
418    Hash,
419    Serialize,
420    Deserialize,
421    bincode::Encode,
422    bincode::Decode,
423)]
424pub enum SurfaceId {
425    Energy(EnergySurfaceId),
426    H(HSurfaceId),
427    Unit,
428    Infinite,
429}
430
431/// Surface interning owned by one [`crate::CffGenerator::generate`] call.
432#[derive(
433    Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, bincode::Encode, bincode::Decode,
434)]
435pub struct SurfaceCache {
436    #[bincode(with_serde)]
437    energy_surfaces: TiVec<EnergySurfaceId, EnergySurface>,
438    #[bincode(with_serde)]
439    h_surfaces: TiVec<HSurfaceId, HSurface>,
440}
441
442/// ID translation produced while merging one surface arena into another.
443#[derive(Clone, Debug, Default, PartialEq, Eq)]
444pub struct SurfaceIdMap {
445    energy: Vec<EnergySurfaceId>,
446    h: Vec<HSurfaceId>,
447}
448
449impl SurfaceIdMap {
450    pub fn remap(&self, id: SurfaceId) -> Option<SurfaceId> {
451        match id {
452            SurfaceId::Energy(id) => self.energy.get(id.index()).copied().map(SurfaceId::Energy),
453            SurfaceId::H(id) => self.h.get(id.index()).copied().map(SurfaceId::H),
454            SurfaceId::Unit => Some(SurfaceId::Unit),
455            SurfaceId::Infinite => Some(SurfaceId::Infinite),
456        }
457    }
458}
459
460impl SurfaceCache {
461    pub fn energy_surfaces(&self) -> &TiVec<EnergySurfaceId, EnergySurface> {
462        &self.energy_surfaces
463    }
464
465    pub fn h_surfaces(&self) -> &TiVec<HSurfaceId, HSurface> {
466        &self.h_surfaces
467    }
468
469    pub fn get(&self, id: SurfaceId) -> Option<Surface> {
470        match id {
471            SurfaceId::Energy(id) => self.energy_surfaces.get(id).cloned().map(Surface::Energy),
472            SurfaceId::H(id) => self.h_surfaces.get(id).cloned().map(Surface::H),
473            SurfaceId::Unit => Some(Surface::Unit),
474            SurfaceId::Infinite => Some(Surface::Infinite),
475        }
476    }
477
478    pub fn len(&self) -> usize {
479        self.energy_surfaces.len() + self.h_surfaces.len()
480    }
481
482    pub fn is_empty(&self) -> bool {
483        self.energy_surfaces.is_empty() && self.h_surfaces.is_empty()
484    }
485
486    pub fn intern(&mut self, surface: Surface) -> SurfaceId {
487        match surface {
488            Surface::Energy(surface) => {
489                if let Some(index) = self
490                    .energy_surfaces
491                    .iter()
492                    .position(|cached| cached.cache_equivalent(&surface))
493                {
494                    SurfaceId::Energy(EnergySurfaceId(index))
495                } else {
496                    let id = EnergySurfaceId(self.energy_surfaces.len());
497                    self.energy_surfaces.push(surface);
498                    SurfaceId::Energy(id)
499                }
500            }
501            Surface::H(surface) => {
502                if let Some(index) = self
503                    .h_surfaces
504                    .iter()
505                    .position(|cached| cached.cache_equivalent(&surface))
506                {
507                    SurfaceId::H(HSurfaceId(index))
508                } else {
509                    let id = HSurfaceId(self.h_surfaces.len());
510                    self.h_surfaces.push(surface);
511                    SurfaceId::H(id)
512                }
513            }
514            Surface::Unit => SurfaceId::Unit,
515            Surface::Infinite => SurfaceId::Infinite,
516        }
517    }
518
519    /// Merge `other` into this arena while preserving this arena's existing IDs.
520    pub fn merge(&mut self, other: &Self) -> SurfaceIdMap {
521        let energy = other
522            .energy_surfaces
523            .iter()
524            .cloned()
525            .map(|surface| match self.intern(Surface::Energy(surface)) {
526                SurfaceId::Energy(id) => id,
527                _ => unreachable!("interning an energy surface returned a different kind"),
528            })
529            .collect();
530        let h = other
531            .h_surfaces
532            .iter()
533            .cloned()
534            .map(|surface| match self.intern(Surface::H(surface)) {
535                SurfaceId::H(id) => id,
536                _ => unreachable!("interning an H-surface returned a different kind"),
537            })
538            .collect();
539        SurfaceIdMap { energy, h }
540    }
541}
542
543impl From<EnergySurfaceId> for symbolica::atom::Atom {
544    fn from(id: EnergySurfaceId) -> Self {
545        symbolica::parse!(&format!("η({})", id.index()))
546    }
547}
548
549impl From<HSurfaceId> for symbolica::atom::Atom {
550    fn from(id: HSurfaceId) -> Self {
551        symbolica::parse!(&format!("H({})", id.index()))
552    }
553}
554
555impl From<SurfaceId> for symbolica::atom::Atom {
556    fn from(id: SurfaceId) -> Self {
557        match id {
558            SurfaceId::Energy(id) => id.into(),
559            SurfaceId::H(id) => id.into(),
560            SurfaceId::Unit => Self::num(1),
561            SurfaceId::Infinite => symbolica::parse!("η_inf"),
562        }
563    }
564}
565
566#[cfg(test)]
567mod cache_tests {
568    use super::*;
569
570    fn energy(edge: usize) -> EnergySurface {
571        EnergySurface {
572            energies: vec![EdgeId::new(edge)],
573            external_shift: ExternalShift::default(),
574            vertex_set: VertexSet::default(),
575        }
576    }
577
578    #[test]
579    fn merge_deduplicates_surfaces_and_returns_a_total_remap() {
580        let mut target = SurfaceCache::default();
581        let existing = target.intern(Surface::Energy(energy(1)));
582        let mut source = SurfaceCache::default();
583        let duplicate = source.intern(Surface::Energy(energy(1)));
584        let distinct = source.intern(Surface::Energy(energy(2)));
585
586        let remap = target.merge(&source);
587
588        assert_eq!(remap.remap(duplicate), Some(existing));
589        assert_eq!(
590            remap.remap(distinct),
591            Some(SurfaceId::Energy(EnergySurfaceId(1)))
592        );
593        assert_eq!(target.energy_surfaces().len(), 2);
594    }
595
596    #[test]
597    fn h_surfaces_with_distinct_external_shifts_are_distinct() {
598        let h_surface = |coefficient| HSurface {
599            positive_energies: vec![EdgeId::new(1)],
600            negative_energies: vec![EdgeId::new(2)],
601            external_shift: ExternalShift::new([(EdgeId::new(0), coefficient)]).unwrap(),
602            vertex_set: VertexSet::default(),
603        };
604        let mut cache = SurfaceCache::default();
605        let incoming = cache.intern(Surface::H(h_surface(1)));
606        let outgoing = cache.intern(Surface::H(h_surface(-1)));
607
608        assert_ne!(incoming, outgoing);
609        assert_ne!(h_surface(1), h_surface(-1));
610        assert_eq!(cache.intern(Surface::H(h_surface(1))), incoming);
611    }
612}