Skip to main content

sparse_ir_minipole/minipole/
mini_pole_dlr.rs

1//! MPM-DLR: minimal poles from DLR coefficients (port of
2//! `mini_pole/mini_pole_dlr.py`).
3//!
4//! Ported from Green-Phys/MiniPole (commit 15e4a54, MIT License,
5//! Copyright (c) 2024 lzphy); see `LICENSE-THIRD-PARTY`.
6
7use super::con_map::{ConMap, ConMapGapless, ConMapGeneric};
8use super::{MiniPoleResult, assemble};
9use crate::basis_trait::Basis;
10use crate::dlr::DiscreteLehmannRepresentation;
11use crate::error::{ArrayRole, Error, Result};
12use crate::esprit::{ErrType, Esprit, EspritParams};
13use crate::traits::StatisticsType;
14use num_complex::Complex;
15use tenferro_tensor::{TensorScalar, TypedTensor};
16
17type C64 = Complex<f64>;
18
19/// Parameters of [`mini_pole_dlr`], with the defaults of the reference.
20#[derive(Debug, Clone, PartialEq)]
21pub struct MiniPoleDlrParams {
22    /// Index of the lowest Matsubara frequency `ω_{n0} = (2 n0 + 1)π/β` of
23    /// the contour, typically in `0..10`.
24    pub n0: usize,
25    /// Cutoff `nmax` of the upper end `(2 nmax + 1)π/β` of the contour when
26    /// `symmetry` is false; `None` uses `β`.
27    pub nmax: Option<f64>,
28    /// Error tolerance of ESPRIT. One of `err` and `m` is required.
29    pub err: Option<f64>,
30    /// Interpretation of `err` (default absolute).
31    pub err_type: ErrType,
32    /// Maximum number of poles: the bound of
33    /// [`EspritParams::m`](crate::esprit::EspritParams::m) applies, and nodes
34    /// with |γ| ≥ 1 are dropped, so the result can have fewer.
35    pub m: Option<usize>,
36    /// Impose up-down symmetry (the gapless map).
37    pub symmetry: bool,
38    /// Maximum number of moments (default 200).
39    pub k_max: usize,
40    /// Ratio `L/N` of ESPRIT (default 0.4).
41    pub lfactor: f64,
42}
43
44impl MiniPoleDlrParams {
45    /// Parameters with contour start `n0`, tolerance `err` and defaults
46    /// otherwise.
47    pub fn new(n0: usize, err: f64) -> Self {
48        Self {
49            n0,
50            nmax: None,
51            err: Some(err),
52            err_type: ErrType::Abs,
53            m: None,
54            symmetry: false,
55            k_max: 200,
56            lfactor: 0.4,
57        }
58    }
59}
60
61/// Minimal pole representation of `G(z) = Σ_l A_l / (z - x_l)`.
62///
63/// `al` has shape `[r, ...]` (residues along axis 0, trailing channel axes),
64/// `xl` the `r` real pole locations.
65///
66/// # Errors
67/// [`Error::ShapeMismatch`] if `al` does not have `len(xl)` rows,
68/// [`Error::InvalidParameter`] for invalid parameters, and ESPRIT errors.
69pub fn mini_pole_dlr<T>(
70    al: &TypedTensor<T>,
71    xl: &[f64],
72    beta: f64,
73    params: &MiniPoleDlrParams,
74) -> Result<MiniPoleResult>
75where
76    T: TensorScalar + Copy + Into<C64>,
77{
78    let shape = al.shape().to_vec();
79    let r = xl.len();
80    if shape.first() != Some(&r) {
81        let mut expected = shape.clone();
82        match expected.first_mut() {
83            Some(n) => *n = r,
84            None => expected.push(r),
85        }
86        return Err(Error::ShapeMismatch {
87            which: ArrayRole::Input,
88            expected,
89            actual: shape,
90        });
91    }
92    if !(beta.is_finite() && beta > 0.0) {
93        return Err(Error::InvalidParameter {
94            name: "beta",
95            value: format!("{beta:?}"),
96            reason: "must be finite and positive".to_string(),
97        });
98    }
99    let d: usize = shape[1..].iter().product();
100    let al: Vec<C64> = al.host_data()?.iter().map(|&v| v.into()).collect();
101
102    let pi = std::f64::consts::PI;
103    let w_n0 = (2.0 * params.n0 as f64 + 1.0) * pi / beta;
104    let generic;
105    let gapless;
106    let map: &dyn ConMap = if !params.symmetry {
107        let nmax = params.nmax.unwrap_or(beta);
108        let w_nmax = (2.0 * nmax + 1.0) * pi / beta;
109        generic = ConMapGeneric {
110            w_m: 0.5 * (w_n0 + w_nmax),
111            dw_h: 0.5 * (w_nmax - w_n0),
112        };
113        if generic.dw_h.is_nan() || generic.dw_h <= 0.0 {
114            return Err(Error::InvalidParameter {
115                name: "nmax",
116                value: format!("{nmax:?}"),
117                reason: format!("must exceed n0 = {}", params.n0),
118            });
119        }
120        &generic
121    } else {
122        gapless = ConMapGapless { w_min: w_n0 };
123        &gapless
124    };
125
126    // h_k = Σ_l xl_p^k A_l / z'(xl_p), k < min(int((r + 1) / Lfactor), k_max).
127    let xl_p: Vec<C64> = xl.iter().map(|&x| map.w(C64::new(x, 0.0))).collect();
128    let n = (((r + 1) as f64 / params.lfactor) as usize).min(params.k_max);
129    let mut h = vec![C64::new(0.0, 0.0); n * d];
130    for (l, &q) in xl_p.iter().enumerate() {
131        let f = map.dz(q).inv();
132        let mut p = C64::new(1.0, 0.0);
133        for k in 0..n {
134            for c in 0..d {
135                h[k + n * c] += p * (al[l + r * c] * f);
136            }
137            p *= q;
138        }
139    }
140
141    let esprit = Esprit::new(
142        &h,
143        n,
144        d,
145        &EspritParams {
146            err: params.err,
147            err_type: params.err_type,
148            m: params.m,
149            lfactor: params.lfactor,
150            ..EspritParams::default()
151        },
152    )?;
153    let keep: Vec<usize> = (0..esprit.gamma.len())
154        .filter(|&j| esprit.gamma[j].norm() < 1.0)
155        .collect();
156    let location: Vec<C64> = keep.iter().map(|&j| map.z(esprit.gamma[j])).collect();
157    let mut weight = vec![C64::new(0.0, 0.0); keep.len() * d];
158    for (jn, &j) in keep.iter().enumerate() {
159        let f = map.dz(esprit.gamma[j]);
160        for c in 0..d {
161            weight[jn + keep.len() * c] = esprit.omega[j + esprit.m * c] * f;
162        }
163    }
164    let mut hshape = shape;
165    hshape[0] = n;
166    assemble(
167        location,
168        weight,
169        vec![C64::new(0.0, 0.0); d],
170        h,
171        hshape,
172        esprit,
173        params.n0,
174        None,
175    )
176}
177
178/// [`mini_pole_dlr`] of DLR coefficients: `A_l = g_l w_l` at the DLR poles
179/// `x_l`, with `w_l` the pole weights of the DLR.
180///
181/// # Errors
182/// See [`mini_pole_dlr`].
183pub fn mini_pole_dlr_from<S, T>(
184    dlr: &DiscreteLehmannRepresentation<S>,
185    g_dlr: &TypedTensor<T>,
186    params: &MiniPoleDlrParams,
187) -> Result<MiniPoleResult>
188where
189    S: StatisticsType + 'static,
190    T: TensorScalar + Copy + Into<C64>,
191{
192    let shape = g_dlr.shape().to_vec();
193    let r = dlr.poles().len();
194    if shape.first() != Some(&r) {
195        let mut expected = shape.clone();
196        match expected.first_mut() {
197            Some(n) => *n = r,
198            None => expected.push(r),
199        }
200        return Err(Error::ShapeMismatch {
201            which: ArrayRole::Input,
202            expected,
203            actual: shape,
204        });
205    }
206    let weights = dlr.pole_weights();
207    let g = g_dlr.host_data()?;
208    let al: Vec<C64> = g
209        .iter()
210        .enumerate()
211        .map(|(i, &v)| v.into() * weights[i % r])
212        .collect();
213    let al = TypedTensor::from_vec_col_major(shape, al)?;
214    mini_pole_dlr(&al, dlr.poles(), dlr.beta(), params)
215}