1use std::{
2 fmt::Display,
3 ops::{Add, Neg},
4};
5
6use linnet::num_traits::SignOrZero;
7use serde::{Deserialize, Serialize};
8use thiserror::Error;
9
10#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
12#[serde(transparent)]
13pub struct Signature {
14 coefficients: Vec<SignOrZero>,
15}
16
17#[derive(Debug, Clone, PartialEq, Eq, Error)]
19pub enum SignatureError {
20 #[error("invalid signature coefficient {value}; expected -1, 0, or 1")]
22 InvalidCoefficient {
23 value: i8,
25 },
26 #[error("signature expects {expected} basis vectors, received {actual}")]
28 BasisLength {
29 expected: usize,
31 actual: usize,
33 },
34 #[error("signature coefficient at index {index} would be outside -1, 0, or 1")]
36 CoefficientOverflow {
37 index: usize,
39 },
40}
41
42impl Signature {
43 pub fn new(coefficients: impl IntoIterator<Item = SignOrZero>) -> Self {
45 Self {
46 coefficients: coefficients.into_iter().collect(),
47 }
48 }
49
50 pub fn try_from_integers(
52 coefficients: impl IntoIterator<Item = i8>,
53 ) -> Result<Self, SignatureError> {
54 coefficients
55 .into_iter()
56 .map(|value| {
57 SignOrZero::try_from(value)
58 .map_err(|_| SignatureError::InvalidCoefficient { value })
59 })
60 .collect()
61 }
62
63 pub fn len(&self) -> usize {
65 self.coefficients.len()
66 }
67
68 pub fn is_empty(&self) -> bool {
70 self.coefficients.is_empty()
71 }
72
73 pub fn get(&self, index: usize) -> Option<SignOrZero> {
75 self.coefficients.get(index).copied()
76 }
77
78 pub fn iter(&self) -> impl ExactSizeIterator<Item = SignOrZero> + '_ {
80 self.coefficients.iter().copied()
81 }
82
83 pub fn integer_coefficients(&self) -> Vec<isize> {
85 self.iter().map(sign_value).collect()
86 }
87
88 pub fn canonicalized(&self) -> Self {
90 match self.iter().find(|coefficient| coefficient.is_sign()) {
91 Some(SignOrZero::Minus) => Self::new(self.iter().map(Neg::neg)),
92 _ => self.clone(),
93 }
94 }
95
96 pub fn checked_add(&self, rhs: &Self) -> Result<Self, SignatureError> {
98 if self.len() != rhs.len() {
99 return Err(SignatureError::BasisLength {
100 expected: self.len(),
101 actual: rhs.len(),
102 });
103 }
104
105 self.iter()
106 .zip(rhs.iter())
107 .enumerate()
108 .map(|(index, (left, right))| match (left, right) {
109 (SignOrZero::Zero, sign) | (sign, SignOrZero::Zero) => Ok(sign),
110 (SignOrZero::Plus, SignOrZero::Minus) | (SignOrZero::Minus, SignOrZero::Plus) => {
111 Ok(SignOrZero::Zero)
112 }
113 _ => Err(SignatureError::CoefficientOverflow { index }),
114 })
115 .collect()
116 }
117
118 pub fn apply<B>(&self, basis: &[B]) -> Result<Option<B>, SignatureError>
123 where
124 B: Clone + Neg<Output = B> + Add<Output = B>,
125 {
126 if self.len() != basis.len() {
127 return Err(SignatureError::BasisLength {
128 expected: self.len(),
129 actual: basis.len(),
130 });
131 }
132
133 Ok(self
134 .iter()
135 .zip(basis.iter())
136 .filter_map(|(coefficient, value)| match coefficient {
137 SignOrZero::Zero => None,
138 SignOrZero::Plus => Some(value.clone()),
139 SignOrZero::Minus => Some(-value.clone()),
140 })
141 .reduce(Add::add))
142 }
143}
144
145impl FromIterator<SignOrZero> for Signature {
146 fn from_iter<I: IntoIterator<Item = SignOrZero>>(iter: I) -> Self {
147 Self::new(iter)
148 }
149}
150
151impl IntoIterator for Signature {
152 type Item = SignOrZero;
153 type IntoIter = std::vec::IntoIter<SignOrZero>;
154
155 fn into_iter(self) -> Self::IntoIter {
156 self.coefficients.into_iter()
157 }
158}
159
160impl<'a> IntoIterator for &'a Signature {
161 type Item = SignOrZero;
162 type IntoIter = std::iter::Copied<std::slice::Iter<'a, SignOrZero>>;
163
164 fn into_iter(self) -> Self::IntoIter {
165 self.coefficients.iter().copied()
166 }
167}
168
169impl Display for Signature {
170 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171 for coefficient in &self.coefficients {
172 write!(formatter, "{coefficient}")?;
173 }
174 Ok(())
175 }
176}
177
178#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
180pub struct MomentumSignature {
181 pub loops: Signature,
183 pub external: Signature,
185}
186
187impl MomentumSignature {
188 pub const fn new(loops: Signature, external: Signature) -> Self {
190 Self { loops, external }
191 }
192
193 pub fn apply<B>(
195 &self,
196 loop_momenta: &[B],
197 external_momenta: &[B],
198 ) -> Result<Option<B>, SignatureError>
199 where
200 B: Clone + Neg<Output = B> + Add<Output = B>,
201 {
202 let loop_part = self.loops.apply(loop_momenta)?;
203 let external_part = self.external.apply(external_momenta)?;
204 Ok(match (loop_part, external_part) {
205 (Some(loop_part), Some(external_part)) => Some(loop_part + external_part),
206 (Some(loop_part), None) => Some(loop_part),
207 (None, Some(external_part)) => Some(external_part),
208 (None, None) => None,
209 })
210 }
211
212 pub fn integer_coefficients(&self) -> (Vec<isize>, Vec<isize>) {
214 (
215 self.loops.integer_coefficients(),
216 self.external.integer_coefficients(),
217 )
218 }
219
220 pub fn canonicalized(&self) -> Self {
222 let first = self
223 .loops
224 .iter()
225 .chain(self.external.iter())
226 .find(|coefficient| coefficient.is_sign());
227 if first == Some(SignOrZero::Minus) {
228 Self {
229 loops: Signature::new(self.loops.iter().map(Neg::neg)),
230 external: Signature::new(self.external.iter().map(Neg::neg)),
231 }
232 } else {
233 self.clone()
234 }
235 }
236
237 pub fn format_momentum(&self) -> String {
239 let terms = self
240 .loops
241 .iter()
242 .enumerate()
243 .map(|(index, sign)| (sign, format!("k_{index}")))
244 .chain(
245 self.external
246 .iter()
247 .enumerate()
248 .map(|(index, sign)| (sign, format!("p_{index}"))),
249 );
250
251 let mut result = String::new();
252 for (sign, label) in terms.filter(|(sign, _)| sign.is_sign()) {
253 if result.is_empty() {
254 if sign == SignOrZero::Minus {
255 result.push('-');
256 }
257 } else if sign == SignOrZero::Plus {
258 result.push('+');
259 } else {
260 result.push('-');
261 }
262 result.push_str(&label);
263 }
264 if result.is_empty() {
265 result.push('0');
266 }
267 result
268 }
269}
270
271fn sign_value(sign: SignOrZero) -> isize {
272 match sign {
273 SignOrZero::Zero => 0,
274 SignOrZero::Plus => 1,
275 SignOrZero::Minus => -1,
276 }
277}
278
279#[cfg(test)]
280mod tests {
281 use crate::FourMomentum;
282
283 use super::*;
284
285 #[test]
286 fn applies_to_scalar_and_momentum_bases() {
287 let signature = Signature::new([
288 SignOrZero::Plus,
289 SignOrZero::Minus,
290 SignOrZero::Zero,
291 SignOrZero::Plus,
292 ]);
293 assert_eq!(signature.apply(&[1, 2, 3, 4]).unwrap(), Some(3));
294
295 let basis = [
296 FourMomentum::from_args(1, 1, 0, 0),
297 FourMomentum::from_args(1, 0, 1, 0),
298 FourMomentum::from_args(1, 0, 0, 1),
299 FourMomentum::from_args(1, 1, 1, 1),
300 ];
301 assert_eq!(
302 signature.apply(&basis).unwrap(),
303 Some(FourMomentum::from_args(1, 2, 0, 1))
304 );
305 }
306
307 #[test]
308 fn all_zero_signature_has_no_value() {
309 let signature = Signature::new([SignOrZero::Zero; 3]);
310 assert_eq!(signature.apply(&[1, 2, 3]).unwrap(), None);
311 }
312
313 #[test]
314 fn checked_add_rejects_non_sign_coefficients() {
315 let plus = Signature::new([SignOrZero::Plus]);
316 assert_eq!(
317 plus.checked_add(&plus),
318 Err(SignatureError::CoefficientOverflow { index: 0 })
319 );
320 }
321
322 #[test]
323 fn combined_canonicalization_uses_one_overall_sign() {
324 let signature = MomentumSignature::new(
325 Signature::new([SignOrZero::Zero, SignOrZero::Minus]),
326 Signature::new([SignOrZero::Plus]),
327 );
328 let canonical = signature.canonicalized();
329 assert_eq!(canonical.format_momentum(), "k_1-p_0");
330 }
331}