Skip to main content

sparse_ir_core/
freq.rs

1//! Matsubara frequency implementation for SparseIR
2//!
3//! This module provides Matsubara frequency types for both fermionic and
4//! bosonic statistics, matching the C++ implementation in freq.hpp.
5
6use num_complex::Complex64;
7use std::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd};
8use std::fmt;
9use std::ops::{Add, Neg, Sub};
10
11use crate::error::Error;
12use crate::traits::{Bosonic, Fermionic, Statistics, StatisticsType};
13
14/// Matsubara frequency for a specific statistics type
15///
16/// This represents the Matsubara frequency ν = nπ/β, where:
17/// - n is the stored integer (the *reduced* Matsubara frequency, returned by
18///   [`n`](Self::n)): odd for fermionic statistics (n = ±1, ±3, …) and even
19///   for bosonic statistics (n = 0, ±2, ±4, …)
20/// - β is the inverse temperature, passed to [`value`](Self::value) and
21///   [`value_imaginary`](Self::value_imaginary)
22///
23/// In terms of the conventional Matsubara index m of ν = (2m + ζ)π/β, with
24/// ζ = 1 for fermionic and ζ = 0 for bosonic statistics, the stored integer is
25/// n = 2m + ζ; it is *not* m itself. [`new`](Self::new) rejects an n whose
26/// parity does not match the statistics.
27///
28/// The statistics type S is checked at compile time to ensure type safety.
29///
30/// # Examples
31/// ```
32/// use sparse_ir::{BosonicFreq, FermionicFreq};
33/// use std::f64::consts::PI;
34///
35/// let beta = 10.0;
36///
37/// // n = 1 is the lowest positive fermionic frequency, ω = π/β (k = 0).
38/// let w = FermionicFreq::new(1).unwrap();
39/// assert_eq!(w.n(), 1);
40/// assert!((w.value(beta) - PI / beta).abs() < 1e-15);
41///
42/// // n = 2 is the lowest positive bosonic frequency, ω = 2π/β (k = 1).
43/// let nu = BosonicFreq::new(2).unwrap();
44/// assert!((nu.value(beta) - 2.0 * PI / beta).abs() < 1e-15);
45///
46/// // The parity of n must match the statistics.
47/// assert!(FermionicFreq::new(2).is_err());
48/// assert!(BosonicFreq::new(1).is_err());
49/// ```
50///
51/// Adding or subtracting frequencies gives the statistics of the result:
52/// `FermionicFreq ± FermionicFreq` is a [`BosonicFreq`], and a fermionic and
53/// a bosonic frequency (in either order) give a [`FermionicFreq`].
54#[derive(Debug, Clone, Copy)]
55pub struct MatsubaraFreq<S: StatisticsType> {
56    n: i64,
57    // `fn() -> S` keeps the type Send + Sync whatever `S` is (it holds no S)
58    _phantom: std::marker::PhantomData<fn() -> S>,
59}
60
61// Type aliases for convenience
62pub type FermionicFreq = MatsubaraFreq<Fermionic>;
63pub type BosonicFreq = MatsubaraFreq<Bosonic>;
64
65impl<S: StatisticsType> MatsubaraFreq<S> {
66    /// Get the reduced Matsubara frequency n, where ν = nπ/β
67    ///
68    /// n is odd for fermionic and even for bosonic statistics.
69    pub fn n(&self) -> i64 {
70        self.n
71    }
72
73    /// Create a new Matsubara frequency
74    ///
75    /// # Arguments
76    /// * `n` - The reduced Matsubara frequency n of ν = nπ/β: odd for
77    ///   fermionic statistics, even for bosonic statistics
78    ///
79    /// # Errors
80    /// [`Error::InvalidMatsubaraIndex`] if `n` is even for fermionic or odd
81    /// for bosonic statistics
82    ///
83    /// # Examples
84    /// ```
85    /// use sparse_ir::freq::{FermionicFreq, BosonicFreq};
86    ///
87    /// let fermionic = FermionicFreq::new(1).unwrap();  // OK: odd n for fermionic
88    /// let bosonic = BosonicFreq::new(0).unwrap();      // OK: even n for bosonic
89    /// ```
90    pub fn new(n: i64) -> Result<Self, Error> {
91        // Check if the frequency is allowed for this statistics type
92        let allowed = match S::STATISTICS {
93            Statistics::Fermionic => n % 2 != 0, // Fermionic: odd n only
94            Statistics::Bosonic => n % 2 == 0,   // Bosonic: even n only
95        };
96
97        if !allowed {
98            return Err(Error::InvalidMatsubaraIndex {
99                n,
100                statistics: S::STATISTICS,
101            });
102        }
103
104        Ok(Self {
105            n,
106            _phantom: std::marker::PhantomData,
107        })
108    }
109
110    /// Create a Matsubara frequency without validation
111    ///
112    /// # Safety
113    /// This function bypasses the validation in `new()`. Only use when you're
114    /// certain the frequency is valid for the statistics type.
115    pub unsafe fn new_unchecked(n: i64) -> Self {
116        Self::with_parity_checked_by_caller(n)
117    }
118
119    /// The frequency `n`, whose parity the caller has established
120    ///
121    /// Used inside this module instead of [`Self::new_unchecked`]: the parity
122    /// is not a memory-safety requirement (a wrong one gives a wrong
123    /// frequency, not undefined behaviour), so it needs no `unsafe`.
124    const fn with_parity_checked_by_caller(n: i64) -> Self {
125        Self {
126            n,
127            _phantom: std::marker::PhantomData,
128        }
129    }
130
131    /// Get the reduced Matsubara frequency n, where ν = nπ/β (same as [`n`](Self::n))
132    pub fn get_n(&self) -> i64 {
133        self.n
134    }
135
136    /// Compute the real frequency value: n * π / β
137    ///
138    /// # Arguments
139    /// * `beta` - Inverse temperature
140    ///
141    /// # Returns
142    /// The real frequency value
143    pub fn value(&self, beta: f64) -> f64 {
144        self.n as f64 * std::f64::consts::PI / beta
145    }
146
147    /// Compute the imaginary frequency value: i * n * π / β
148    ///
149    /// # Arguments
150    /// * `beta` - Inverse temperature
151    ///
152    /// # Returns
153    /// The imaginary frequency value as a complex number
154    pub fn value_imaginary(&self, beta: f64) -> Complex64 {
155        Complex64::new(0.0, self.value(beta))
156    }
157
158    /// Get the statistics type
159    pub fn statistics(&self) -> Statistics {
160        S::STATISTICS
161    }
162
163    /// Convert to i64 (for compatibility with C++ operator long long())
164    pub fn into_i64(self) -> i64 {
165        self.n
166    }
167}
168
169// Default implementations
170impl Default for FermionicFreq {
171    fn default() -> Self {
172        // Default fermionic frequency is n=1 (smallest positive odd frequency)
173        Self::with_parity_checked_by_caller(1)
174    }
175}
176
177impl Default for BosonicFreq {
178    fn default() -> Self {
179        // Default bosonic frequency is n=0 (zero frequency)
180        Self::with_parity_checked_by_caller(0)
181    }
182}
183
184// Conversion to i64
185impl<S: StatisticsType> From<MatsubaraFreq<S>> for i64 {
186    fn from(freq: MatsubaraFreq<S>) -> Self {
187        freq.n
188    }
189}
190
191// Operator overloading: addition and subtraction
192//
193// The parity of n + m and n - m follows from the parities of n and m, so the
194// output type carries the statistics of the result: fermionic ± fermionic is
195// bosonic, fermionic ± bosonic (either order) is fermionic, bosonic ±
196// bosonic is bosonic. The i64 arithmetic is the usual one (a panic on
197// overflow in debug builds, wrapping in release builds); wrapping keeps the
198// parity, so the output is always a valid frequency.
199macro_rules! impl_freq_arithmetic {
200    ($lhs:ty, $rhs:ty => $out:ty) => {
201        impl Add<$rhs> for $lhs {
202            type Output = $out;
203
204            fn add(self, other: $rhs) -> $out {
205                // The parity of the sum is that of $out (see above)
206                <$out>::with_parity_checked_by_caller(self.n + other.n)
207            }
208        }
209
210        impl Sub<$rhs> for $lhs {
211            type Output = $out;
212
213            fn sub(self, other: $rhs) -> $out {
214                // As for `add`
215                <$out>::with_parity_checked_by_caller(self.n - other.n)
216            }
217        }
218    };
219}
220
221impl_freq_arithmetic!(FermionicFreq, FermionicFreq => BosonicFreq);
222impl_freq_arithmetic!(FermionicFreq, BosonicFreq => FermionicFreq);
223impl_freq_arithmetic!(BosonicFreq, FermionicFreq => FermionicFreq);
224impl_freq_arithmetic!(BosonicFreq, BosonicFreq => BosonicFreq);
225
226// Operator overloading: Negation
227impl<S: StatisticsType> Neg for MatsubaraFreq<S> {
228    type Output = Self;
229
230    fn neg(self) -> Self {
231        // Negation preserves parity, so this is always valid
232        Self::with_parity_checked_by_caller(-self.n)
233    }
234}
235
236// Comparison operators
237impl<S: StatisticsType> PartialEq for MatsubaraFreq<S> {
238    fn eq(&self, other: &Self) -> bool {
239        self.n == other.n
240    }
241}
242
243impl<S: StatisticsType> Eq for MatsubaraFreq<S> {}
244
245impl<S: StatisticsType> PartialOrd for MatsubaraFreq<S> {
246    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
247        Some(self.cmp(other))
248    }
249}
250
251impl<S: StatisticsType> Ord for MatsubaraFreq<S> {
252    fn cmp(&self, other: &Self) -> Ordering {
253        self.n.cmp(&other.n)
254    }
255}
256
257// Hash implementation (needed for some collections)
258impl<S: StatisticsType> std::hash::Hash for MatsubaraFreq<S> {
259    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
260        self.n.hash(state);
261    }
262}
263
264// Display implementation
265impl<S: StatisticsType> fmt::Display for MatsubaraFreq<S> {
266    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267        match self.n {
268            0 => write!(f, "0"),
269            1 => write!(f, "π/β"),
270            -1 => write!(f, "-π/β"),
271            n => write!(f, "{}π/β", n),
272        }
273    }
274}
275
276// Utility functions
277/// Get the sign of a Matsubara frequency
278#[allow(dead_code)]
279pub(crate) fn sign<S: StatisticsType>(freq: &MatsubaraFreq<S>) -> i32 {
280    if freq.n > 0 {
281        1
282    } else if freq.n < 0 {
283        -1
284    } else {
285        0
286    }
287}
288
289/// Get the fermionic sign based on statistics type
290#[allow(dead_code)]
291pub(crate) fn fermionic_sign<S: StatisticsType>() -> i32 {
292    match S::STATISTICS {
293        Statistics::Fermionic => -1,
294        Statistics::Bosonic => 1,
295    }
296}
297
298/// Check if a frequency is zero
299#[allow(dead_code)]
300#[doc(hidden)]
301pub fn is_zero<S: StatisticsType>(freq: &MatsubaraFreq<S>) -> bool {
302    match S::STATISTICS {
303        Statistics::Fermionic => false, // Fermionic frequencies are never zero
304        Statistics::Bosonic => freq.n == 0,
305    }
306}
307
308/// Compare two Matsubara frequencies of potentially different statistics types
309#[allow(dead_code)]
310pub(crate) fn is_less<S1: StatisticsType, S2: StatisticsType>(
311    a: &MatsubaraFreq<S1>,
312    b: &MatsubaraFreq<S2>,
313) -> bool {
314    a.get_n() < b.get_n()
315}
316
317/// Factory function to create Statistics from zeta value
318#[allow(dead_code)]
319pub(crate) fn create_statistics(zeta: i64) -> Result<Statistics, String> {
320    match zeta {
321        1 => Ok(Statistics::Fermionic),
322        0 => Ok(Statistics::Bosonic),
323        _ => Err(format!("Unknown statistics type: zeta={}", zeta)),
324    }
325}
326
327#[cfg(test)]
328mod tests {
329    use super::*;
330
331    #[test]
332    fn test_fermionic_frequency_creation() {
333        // Valid fermionic frequencies (odd n)
334        let freq1 = FermionicFreq::new(1).unwrap();
335        assert_eq!(freq1.get_n(), 1);
336
337        let freq3 = FermionicFreq::new(3).unwrap();
338        assert_eq!(freq3.get_n(), 3);
339
340        let freq_neg1 = FermionicFreq::new(-1).unwrap();
341        assert_eq!(freq_neg1.get_n(), -1);
342
343        // Invalid fermionic frequencies (even n)
344        assert!(FermionicFreq::new(0).is_err());
345        assert!(FermionicFreq::new(2).is_err());
346        assert!(FermionicFreq::new(-2).is_err());
347    }
348
349    #[test]
350    fn test_bosonic_frequency_creation() {
351        // Valid bosonic frequencies (even n)
352        let freq0 = BosonicFreq::new(0).unwrap();
353        assert_eq!(freq0.get_n(), 0);
354
355        let freq2 = BosonicFreq::new(2).unwrap();
356        assert_eq!(freq2.get_n(), 2);
357
358        let freq_neg2 = BosonicFreq::new(-2).unwrap();
359        assert_eq!(freq_neg2.get_n(), -2);
360
361        // Invalid bosonic frequencies (odd n)
362        assert!(BosonicFreq::new(1).is_err());
363        assert!(BosonicFreq::new(3).is_err());
364        assert!(BosonicFreq::new(-1).is_err());
365    }
366
367    #[test]
368    fn test_frequency_values() {
369        let beta = 2.0;
370        let pi = std::f64::consts::PI;
371
372        let fermionic = FermionicFreq::new(1).unwrap();
373        assert!((fermionic.value(beta) - pi / 2.0).abs() < 1e-14);
374
375        let bosonic = BosonicFreq::new(0).unwrap();
376        assert_eq!(bosonic.value(beta), 0.0);
377
378        let bosonic2 = BosonicFreq::new(2).unwrap();
379        assert!((bosonic2.value(beta) - pi).abs() < 1e-14);
380    }
381
382    #[test]
383    fn test_imaginary_values() {
384        let beta = 2.0;
385        let pi = std::f64::consts::PI;
386
387        let fermionic = FermionicFreq::new(1).unwrap();
388        let imag = fermionic.value_imaginary(beta);
389        assert!((imag.re - 0.0).abs() < 1e-14);
390        assert!((imag.im - pi / 2.0).abs() < 1e-14);
391    }
392
393    #[test]
394    fn test_operator_overloading() {
395        // Bosonic: even + even = even (valid)
396        let bfreq2 = BosonicFreq::new(2).unwrap();
397        let bfreq4 = BosonicFreq::new(4).unwrap();
398
399        let sum = bfreq2 + bfreq4;
400        assert_eq!(sum.get_n(), 6);
401
402        let diff = bfreq4 - bfreq2;
403        assert_eq!(diff.get_n(), 2);
404
405        // Negation preserves parity (valid for both statistics)
406        let freq1 = FermionicFreq::new(1).unwrap();
407        let neg = -freq1;
408        assert_eq!(neg.get_n(), -1);
409
410        let neg_b = -bfreq2;
411        assert_eq!(neg_b.get_n(), -2);
412    }
413
414    /// Sums and differences have the statistics of their parity: fermionic ±
415    /// fermionic is bosonic, fermionic ± bosonic is fermionic. Before the
416    /// change the output had the type of the inputs, so FermionicFreq(1) +
417    /// FermionicFreq(1) was a FermionicFreq with the even n = 2 in release
418    /// builds (a debug_assert only).
419    #[test]
420    fn test_sum_and_difference_follow_the_statistics() {
421        let f1 = FermionicFreq::new(1).unwrap();
422        let f3 = FermionicFreq::new(3).unwrap();
423        let b2 = BosonicFreq::new(2).unwrap();
424
425        let sum: BosonicFreq = f1 + f3;
426        assert_eq!(sum, BosonicFreq::new(4).unwrap());
427        let diff: BosonicFreq = f1 - f3;
428        assert_eq!(diff, BosonicFreq::new(-2).unwrap());
429
430        let fb_sum: FermionicFreq = f1 + b2;
431        assert_eq!(fb_sum, FermionicFreq::new(3).unwrap());
432        let fb_diff: FermionicFreq = f3 - b2;
433        assert_eq!(fb_diff, FermionicFreq::new(1).unwrap());
434        let bf_sum: FermionicFreq = b2 + f1;
435        assert_eq!(bf_sum, FermionicFreq::new(3).unwrap());
436        let bf_diff: FermionicFreq = b2 - f3;
437        assert_eq!(bf_diff, FermionicFreq::new(-1).unwrap());
438
439        let bb: BosonicFreq = b2 + b2;
440        assert_eq!(bb, BosonicFreq::new(4).unwrap());
441    }
442
443    #[test]
444    fn test_comparison_operators() {
445        let freq1 = FermionicFreq::new(1).unwrap();
446        let freq3 = FermionicFreq::new(3).unwrap();
447        let freq1_copy = FermionicFreq::new(1).unwrap();
448
449        assert_eq!(freq1, freq1_copy);
450        assert_ne!(freq1, freq3);
451        assert!(freq1 < freq3);
452        assert!(freq3 > freq1);
453        assert!(freq1 <= freq1_copy);
454        assert!(freq1 >= freq1_copy);
455    }
456
457    #[test]
458    fn test_utility_functions() {
459        let fermionic = FermionicFreq::new(1).unwrap();
460        let bosonic = BosonicFreq::new(0).unwrap();
461        let bosonic2 = BosonicFreq::new(2).unwrap();
462
463        // Sign function
464        assert_eq!(sign(&fermionic), 1);
465        assert_eq!(sign(&bosonic), 0);
466        assert_eq!(sign(&-fermionic), -1);
467
468        // Fermionic sign
469        assert_eq!(fermionic_sign::<Fermionic>(), -1);
470        assert_eq!(fermionic_sign::<Bosonic>(), 1);
471
472        // Is zero
473        assert!(!is_zero(&fermionic));
474        assert!(is_zero(&bosonic));
475        assert!(!is_zero(&bosonic2));
476
477        // Is less
478        assert!(is_less(&fermionic, &bosonic2));
479        assert!(!is_less(&bosonic2, &fermionic));
480    }
481
482    #[test]
483    fn test_statistics_creation() {
484        assert_eq!(create_statistics(1).unwrap(), Statistics::Fermionic);
485        assert_eq!(create_statistics(0).unwrap(), Statistics::Bosonic);
486        assert!(create_statistics(2).is_err());
487    }
488
489    #[test]
490    fn test_display() {
491        let freq1 = FermionicFreq::new(1).unwrap();
492        let freq_neg1 = FermionicFreq::new(-1).unwrap();
493        let freq0 = BosonicFreq::new(0).unwrap();
494        let freq2 = BosonicFreq::new(2).unwrap();
495
496        assert_eq!(format!("{}", freq1), "π/β");
497        assert_eq!(format!("{}", freq_neg1), "-π/β");
498        assert_eq!(format!("{}", freq0), "0");
499        assert_eq!(format!("{}", freq2), "2π/β");
500    }
501
502    #[test]
503    fn test_default_implementations() {
504        let default_fermionic = FermionicFreq::default();
505        assert_eq!(default_fermionic.get_n(), 1);
506
507        let default_bosonic = BosonicFreq::default();
508        assert_eq!(default_bosonic.get_n(), 0);
509    }
510
511    #[test]
512    fn test_conversion_to_i64() {
513        let freq = FermionicFreq::new(3).unwrap();
514        let n: i64 = freq.into();
515        assert_eq!(n, 3);
516
517        let n_direct = freq.into_i64();
518        assert_eq!(n_direct, 3);
519    }
520
521    #[test]
522    fn test_sign() {
523        let fermionic_pos = FermionicFreq::new(3).unwrap();
524        assert_eq!(sign(&fermionic_pos), 1);
525
526        let fermionic_neg = FermionicFreq::new(-5).unwrap();
527        assert_eq!(sign(&fermionic_neg), -1);
528
529        let bosonic_zero = BosonicFreq::new(0).unwrap();
530        assert_eq!(sign(&bosonic_zero), 0);
531
532        let bosonic_pos = BosonicFreq::new(4).unwrap();
533        assert_eq!(sign(&bosonic_pos), 1);
534    }
535
536    #[test]
537    fn test_fermionic_sign() {
538        assert_eq!(fermionic_sign::<Fermionic>(), -1);
539        assert_eq!(fermionic_sign::<Bosonic>(), 1);
540    }
541
542    #[test]
543    fn test_is_zero() {
544        // Fermionic frequencies are never zero
545        let fermionic = FermionicFreq::new(1).unwrap();
546        assert!(!is_zero(&fermionic));
547
548        // Bosonic zero frequency
549        let bosonic_zero = BosonicFreq::new(0).unwrap();
550        assert!(is_zero(&bosonic_zero));
551
552        // Non-zero bosonic frequency
553        let bosonic_nonzero = BosonicFreq::new(2).unwrap();
554        assert!(!is_zero(&bosonic_nonzero));
555    }
556
557    #[test]
558    fn test_is_less() {
559        let freq1 = FermionicFreq::new(1).unwrap();
560        let freq3 = FermionicFreq::new(3).unwrap();
561        assert!(is_less(&freq1, &freq3));
562        assert!(!is_less(&freq3, &freq1));
563
564        // Compare different statistics types
565        let fermionic = FermionicFreq::new(1).unwrap();
566        let bosonic = BosonicFreq::new(2).unwrap();
567        assert!(is_less(&fermionic, &bosonic));
568
569        // Same frequency
570        assert!(!is_less(&freq1, &freq1));
571    }
572
573    #[test]
574    fn test_create_statistics() {
575        // Fermionic (zeta = 1)
576        let fermionic = create_statistics(1).unwrap();
577        assert_eq!(fermionic, Statistics::Fermionic);
578
579        // Bosonic (zeta = 0)
580        let bosonic = create_statistics(0).unwrap();
581        assert_eq!(bosonic, Statistics::Bosonic);
582
583        // Invalid zeta
584        assert!(create_statistics(2).is_err());
585        assert!(create_statistics(-1).is_err());
586    }
587
588    /// The parity check holds for negative n, whose remainder is negative.
589    #[test]
590    fn test_new_rejects_wrong_parity_with_typed_error() {
591        use crate::error::Error;
592
593        assert_eq!(
594            FermionicFreq::new(2).unwrap_err(),
595            Error::InvalidMatsubaraIndex {
596                n: 2,
597                statistics: Statistics::Fermionic,
598            }
599        );
600        assert_eq!(
601            BosonicFreq::new(-3).unwrap_err(),
602            Error::InvalidMatsubaraIndex {
603                n: -3,
604                statistics: Statistics::Bosonic,
605            }
606        );
607        assert_eq!(
608            BosonicFreq::new(-3).unwrap_err().to_string(),
609            "Matsubara frequency n = -3 is not allowed for bosonic statistics"
610        );
611        assert_eq!(FermionicFreq::new(-1).unwrap().n(), -1);
612        assert_eq!(BosonicFreq::new(-2).unwrap().n(), -2);
613    }
614}