Skip to main content

feynkit_cff/
expression.rs

1use std::collections::{BTreeMap, BTreeSet};
2
3use serde::ser::SerializeStruct;
4use serde::{Deserialize, Deserializer, Serialize, Serializer};
5use symbolica::atom::Atom;
6use typed_index_collections::TiVec;
7
8use crate::{
9    CffError, EdgeId, EnergySurfaceId, ExpressionTree, GraphOrientation, OrientationId,
10    OrientationWeight, RaisedEnergySurfaceData, RaisedEnergySurfaceGroup, SurfaceCache, SurfaceId,
11    SurfaceIdMap,
12};
13
14/// One CFF denominator tree and its acyclic graph orientation.
15#[derive(
16    Clone,
17    Debug,
18    PartialEq,
19    Eq,
20    PartialOrd,
21    Ord,
22    Serialize,
23    Deserialize,
24    bincode::Encode,
25    bincode::Decode,
26)]
27pub struct OrientationData {
28    pub orientation: GraphOrientation,
29}
30
31/// One CFF denominator tree and its acyclic graph orientation.
32///
33/// Serde writes `weight` in every compact format, including the
34/// `bincode(with_serde)` path used by [`CffExpression`], because such formats
35/// decode every field by position. Human-readable formats omit a unit weight,
36/// and a missing weight reads as the unit weight.
37#[derive(Clone, Debug, PartialEq, Eq, bincode::Encode, bincode::Decode)]
38pub struct OrientationExpression {
39    pub id: OrientationId,
40    pub data: OrientationData,
41    /// Exact factor multiplying `expression`: unit unless the orientation
42    /// directs self-loops.
43    pub weight: OrientationWeight,
44    pub expression: ExpressionTree<SurfaceId>,
45}
46
47/// Field order shared by the serializer and every positional decoder.
48#[derive(Deserialize)]
49#[serde(rename = "OrientationExpression")]
50struct OrientationExpressionFields {
51    id: OrientationId,
52    data: OrientationData,
53    #[serde(default)]
54    weight: OrientationWeight,
55    expression: ExpressionTree<SurfaceId>,
56}
57
58impl Serialize for OrientationExpression {
59    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
60    where
61        S: Serializer,
62    {
63        let omit_weight = serializer.is_human_readable() && self.weight.is_unit();
64        let mut fields = serializer
65            .serialize_struct("OrientationExpression", if omit_weight { 3 } else { 4 })?;
66        fields.serialize_field("id", &self.id)?;
67        fields.serialize_field("data", &self.data)?;
68        if omit_weight {
69            fields.skip_field("weight")?;
70        } else {
71            fields.serialize_field("weight", &self.weight)?;
72        }
73        fields.serialize_field("expression", &self.expression)?;
74        fields.end()
75    }
76}
77
78impl<'de> Deserialize<'de> for OrientationExpression {
79    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
80    where
81        D: Deserializer<'de>,
82    {
83        let fields = OrientationExpressionFields::deserialize(deserializer)?;
84        Ok(Self {
85            id: fields.id,
86            data: fields.data,
87            weight: fields.weight,
88            expression: fields.expression,
89        })
90    }
91}
92
93impl OrientationExpression {
94    /// Unfold the tree into denominator products, one vector per additive term.
95    ///
96    /// The products exclude [`Self::weight`], which multiplies each of them.
97    pub fn denominator_products(&self) -> Vec<Vec<SurfaceId>> {
98        self.expression
99            .root_to_leaf_paths()
100            .into_iter()
101            .map(|path| path.into_iter().copied().collect())
102            .collect()
103    }
104
105    /// Lower this weighted tree to a sum of products of inverse surfaces.
106    pub fn to_atom(&self) -> Atom {
107        self.weight.to_atom() * self.expression.to_atom_inverse()
108    }
109}
110
111/// Sum of the expressions associated with all accepted acyclic orientations.
112#[derive(
113    Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, bincode::Encode, bincode::Decode,
114)]
115pub struct CffExpression {
116    #[bincode(with_serde)]
117    pub orientations: TiVec<OrientationId, OrientationExpression>,
118}
119
120impl CffExpression {
121    pub(crate) fn new(orientations: Vec<OrientationExpression>) -> Self {
122        Self {
123            orientations: orientations.into(),
124        }
125    }
126
127    pub fn orientations(&self) -> &[OrientationExpression] {
128        &self.orientations.raw
129    }
130
131    pub fn orientations_mut(&mut self) -> &mut [OrientationExpression] {
132        &mut self.orientations.raw
133    }
134
135    pub fn orientation(&self, id: OrientationId) -> Option<&OrientationExpression> {
136        self.orientations.get(id)
137    }
138
139    pub fn unfolded_term_count(&self) -> usize {
140        self.orientations
141            .iter()
142            .map(|orientation| orientation.expression.leaves().count())
143            .sum()
144    }
145
146    pub fn is_empty(&self) -> bool {
147        self.orientations.is_empty()
148    }
149
150    pub fn retain_orientations(&mut self, mut predicate: impl FnMut(&GraphOrientation) -> bool) {
151        self.orientations
152            .retain(|orientation| predicate(&orientation.data.orientation));
153        for (id, orientation) in self.orientations.iter_mut().enumerate() {
154            orientation.id = OrientationId(id);
155        }
156    }
157
158    pub fn remap_surfaces(&mut self, remap: &SurfaceIdMap) -> Result<(), CffError> {
159        let mut missing = None;
160        for orientation in &mut self.orientations {
161            orientation.expression.map_mut(|surface| {
162                if let Some(remapped) = remap.remap(*surface) {
163                    *surface = remapped;
164                } else {
165                    missing = Some(*surface);
166                }
167            });
168        }
169        match missing {
170            Some(surface) => Err(CffError::Invariant(format!(
171                "surface remap does not contain {surface:?}"
172            ))),
173            None => Ok(()),
174        }
175    }
176
177    /// Energy-surface IDs actually referenced by this expression.
178    pub fn energy_surface_ids(&self) -> BTreeSet<EnergySurfaceId> {
179        self.orientations
180            .iter()
181            .flat_map(|orientation| orientation.expression.nodes())
182            .filter_map(|node| match node.data {
183                SurfaceId::Energy(id) => Some(id),
184                _ => None,
185            })
186            .collect()
187    }
188
189    pub fn normalize_raised_surfaces(&mut self, raised: &RaisedEnergySurfaceData) {
190        let representatives = raised
191            .groups
192            .iter()
193            .flat_map(|group| {
194                group
195                    .surface_ids
196                    .first()
197                    .into_iter()
198                    .flat_map(move |representative| {
199                        group
200                            .surface_ids
201                            .iter()
202                            .map(move |surface| (*surface, *representative))
203                    })
204            })
205            .collect::<BTreeMap<_, _>>();
206        for orientation in &mut self.orientations {
207            orientation.expression.map_mut(|surface| {
208                if let SurfaceId::Energy(id) = surface
209                    && let Some(representative) = representatives.get(id)
210                {
211                    *id = *representative;
212                }
213            });
214        }
215    }
216
217    /// Select every non-zero residue order for a raised energy-surface group.
218    pub fn select_energy_surface_residue(&self, group: &RaisedEnergySurfaceGroup) -> Vec<Self> {
219        let Some(representative) = group.surface_ids.first().copied() else {
220            return Vec::new();
221        };
222        let mut normalized = self.clone();
223        normalized.normalize_raised_surfaces(&RaisedEnergySurfaceData {
224            groups: vec![group.clone()].into(),
225        });
226
227        (1..=group.max_occurrence)
228            .map(|occurrence| {
229                let mut residue = normalized.clone();
230                for orientation in &mut residue.orientations {
231                    orientation.expression.retain_branches_with_value_count(
232                        &SurfaceId::Energy(representative),
233                        occurrence,
234                    );
235                    orientation.expression.map_mut(|surface| {
236                        if *surface == SurfaceId::Energy(representative) {
237                            *surface = SurfaceId::Unit;
238                        }
239                    });
240                }
241                residue
242            })
243            .collect()
244    }
245
246    pub fn max_surface_occurrence(&self, surface: SurfaceId) -> usize {
247        self.orientations
248            .iter()
249            .map(|orientation| orientation.expression.max_value_count_on_branch(&surface))
250            .max()
251            .unwrap_or(0)
252    }
253
254    /// Discover equivalence classes induced by replacing raised parallel edges.
255    ///
256    /// `representative` maps every energy-carrying edge to the canonical edge of
257    /// its raised-propagator class. Only surfaces referenced by this expression
258    /// participate, even when the arena is shared with another expression.
259    pub fn raised_energy_surfaces(
260        &self,
261        surfaces: &SurfaceCache,
262        mut representative: impl FnMut(EdgeId) -> EdgeId,
263    ) -> Result<RaisedEnergySurfaceData, CffError> {
264        let mut normalized = Vec::new();
265        for id in self.energy_surface_ids() {
266            let surface = surfaces.energy_surfaces().get(id).ok_or_else(|| {
267                CffError::Invariant(format!(
268                    "expression references missing energy surface {id:?}"
269                ))
270            })?;
271            let mut energies = surface
272                .energies
273                .iter()
274                .copied()
275                .map(&mut representative)
276                .collect::<Vec<_>>();
277            energies.sort_unstable();
278            normalized.push((id, energies, surface.external_shift.clone()));
279        }
280
281        let mut groups: Vec<RaisedEnergySurfaceGroup> = Vec::new();
282        for (id, energies, shift) in &normalized {
283            if let Some(group) = groups.iter_mut().find(|group| {
284                let representative = group.surface_ids[0];
285                normalized
286                    .iter()
287                    .any(|(candidate, candidate_energies, candidate_shift)| {
288                        *candidate == representative
289                            && candidate_energies == energies
290                            && candidate_shift == shift
291                    })
292            }) {
293                group.surface_ids.push(*id);
294            } else {
295                groups.push(RaisedEnergySurfaceGroup {
296                    surface_ids: vec![*id],
297                    max_occurrence: 0,
298                });
299            }
300        }
301
302        let mut normalized_expression = self.clone();
303        normalized_expression.normalize_raised_surfaces(&RaisedEnergySurfaceData {
304            groups: groups.clone().into(),
305        });
306        for group in &mut groups {
307            group.max_occurrence = normalized_expression
308                .max_surface_occurrence(SurfaceId::Energy(group.surface_ids[0]));
309        }
310        Ok(RaisedEnergySurfaceData {
311            groups: groups.into(),
312        })
313    }
314}
315
316#[cfg(test)]
317mod tests {
318    use bincode::config;
319    use bincode::serde as bincode_serde;
320
321    use super::*;
322    use crate::{EdgeOrientation, GraphOrientation, NodeId};
323
324    fn expression_with_raised_surfaces() -> CffExpression {
325        let first = SurfaceId::Energy(EnergySurfaceId(0));
326        let equivalent = SurfaceId::Energy(EnergySurfaceId(1));
327        let mut tree = ExpressionTree::from_root(first);
328        tree.insert(NodeId::ROOT, equivalent).unwrap();
329        CffExpression::new(vec![OrientationExpression {
330            id: OrientationId(0),
331            data: OrientationData {
332                orientation: GraphOrientation::new(),
333            },
334            weight: OrientationWeight::UNIT,
335            expression: tree,
336        }])
337    }
338
339    #[test]
340    fn raised_surface_residue_selects_each_pole_order() {
341        let expression = expression_with_raised_surfaces();
342        let group = RaisedEnergySurfaceGroup {
343            surface_ids: vec![EnergySurfaceId(0), EnergySurfaceId(1)],
344            max_occurrence: 2,
345        };
346
347        let residues = expression.select_energy_surface_residue(&group);
348
349        assert_eq!(residues.len(), 2);
350        assert!(residues[0].orientations()[0].expression.is_empty());
351        assert_eq!(
352            residues[1].orientations()[0]
353                .expression
354                .root_to_leaf_paths(),
355            vec![vec![&SurfaceId::Unit, &SurfaceId::Unit]]
356        );
357    }
358
359    /// Unit-weight, weighted and emptied expressions, each followed by a
360    /// second weighted orientation so a misread field shifts later bytes.
361    fn binary_controls() -> Vec<CffExpression> {
362        let unit = expression_with_raised_surfaces();
363        let mut weighted = unit.clone();
364        weighted.orientations_mut()[0].weight = OrientationWeight::from_halvings(1);
365        let mut emptied = weighted.clone();
366        emptied.orientations_mut()[0]
367            .expression
368            .retain_branches_with_value_count(&SurfaceId::Unit, 1);
369        assert!(emptied.orientations()[0].expression.is_empty());
370        [unit, weighted, emptied]
371            .into_iter()
372            .map(|mut expression| {
373                let mut trailing = expression.orientations()[0].clone();
374                trailing.id = OrientationId(1);
375                trailing.weight = OrientationWeight::from_halvings(2);
376                expression.orientations.push(trailing);
377                expression
378            })
379            .collect()
380    }
381
382    #[test]
383    fn orientations_round_trip_through_derived_and_serde_bincode() {
384        for expression in binary_controls() {
385            for orientation in expression.orientations() {
386                let bytes = bincode::encode_to_vec(orientation, config::standard()).unwrap();
387                let (decoded, read): (OrientationExpression, usize) =
388                    bincode::decode_from_slice(&bytes, config::standard()).unwrap();
389                assert_eq!((&decoded, read), (orientation, bytes.len()));
390
391                let bytes = bincode_serde::encode_to_vec(orientation, config::standard()).unwrap();
392                let (decoded, read): (OrientationExpression, usize) =
393                    bincode_serde::decode_from_slice(&bytes, config::standard()).unwrap();
394                assert_eq!((&decoded, read), (orientation, bytes.len()));
395            }
396        }
397    }
398
399    #[test]
400    fn expressions_round_trip_through_bincode() {
401        for expression in binary_controls() {
402            let bytes = bincode::encode_to_vec(&expression, config::standard()).unwrap();
403            let (decoded, read): (CffExpression, usize) =
404                bincode::decode_from_slice(&bytes, config::standard()).unwrap();
405            assert_eq!((decoded, read), (expression, bytes.len()));
406        }
407    }
408
409    #[test]
410    fn json_omits_only_unit_weights() {
411        for expression in binary_controls() {
412            let json = serde_json::to_value(&expression).unwrap();
413            for (orientation, encoded) in expression
414                .orientations()
415                .iter()
416                .zip(json["orientations"].as_array().unwrap())
417            {
418                assert_eq!(
419                    encoded.get("weight").is_none(),
420                    orientation.weight.is_unit()
421                );
422            }
423            assert_eq!(
424                serde_json::from_value::<CffExpression>(json).unwrap(),
425                expression
426            );
427        }
428    }
429
430    #[test]
431    fn serialized_orientations_without_a_weight_keep_unit_weight() {
432        let mut expression = expression_with_raised_surfaces();
433        let legacy = serde_json::to_value(&expression).unwrap();
434        assert!(legacy["orientations"][0].get("weight").is_none());
435        assert_eq!(
436            serde_json::from_value::<CffExpression>(legacy).unwrap(),
437            expression
438        );
439
440        expression.orientations_mut()[0].weight = OrientationWeight::from_halvings(1);
441        let weighted = serde_json::to_value(&expression).unwrap();
442        assert_eq!(
443            serde_json::from_value::<CffExpression>(weighted).unwrap(),
444            expression
445        );
446    }
447
448    #[test]
449    fn retaining_orientations_renumbers_the_survivors() {
450        let mut expression = expression_with_raised_surfaces();
451        let mut second = expression.orientations()[0].clone();
452        second.id = OrientationId(1);
453        second.data.orientation = GraphOrientation::from_iter([EdgeOrientation::Reversed]);
454        expression.orientations.push(second);
455
456        expression.retain_orientations(|orientation| {
457            orientation.get(crate::EdgeId::new(0)) == Some(&EdgeOrientation::Reversed)
458        });
459
460        assert_eq!(expression.orientations().len(), 1);
461        assert_eq!(expression.orientations()[0].id, OrientationId(0));
462    }
463}