Skip to main content

sparse_ir_minipole/minipole/
mini_pole.rs

1//! MPM: minimal poles from Matsubara data on a uniform grid (port of
2//! `mini_pole/mini_pole.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::quad::oscillatory;
9use super::{MiniPoleResult, assemble};
10use crate::error::{ArrayRole, Error, Result};
11use crate::esprit::{ErrType, Esprit, EspritParams, linspace};
12use crate::linalg::lstsq;
13use num_complex::Complex;
14use std::f64::consts::PI;
15use tenferro_tensor::TypedTensor;
16
17type C64 = Complex<f64>;
18
19/// Choice of `n0`, the number of low frequencies left out of the contour.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum N0 {
22    /// Chosen from the data, plus `shift`.
23    Auto {
24        /// Shift added to the automatic choice.
25        shift: usize,
26    },
27    /// Fixed.
28    Fixed(usize),
29}
30
31/// Plane in which the pole weights are computed.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum Plane {
34    /// Least squares on the Matsubara data.
35    Z,
36    /// From the ESPRIT weights in the mapped plane.
37    W,
38}
39
40/// Parameters of [`mini_pole`], with the defaults of the reference.
41#[derive(Debug, Clone, PartialEq)]
42pub struct MiniPoleParams {
43    /// Choice of `n0` (default automatic, shift 0).
44    pub n0: N0,
45    /// Error tolerance, at least the noise level. Required: the reference's
46    /// default (knee detection) is not ported.
47    pub err: f64,
48    /// Interpretation of `err` (default absolute).
49    pub err_type: ErrType,
50    /// Maximum number of poles; `None` uses the precision of the first
51    /// ESPRIT. The result can have fewer: the bound of
52    /// [`EspritParams::m`](crate::esprit::EspritParams::m) applies, and
53    /// nodes with |γ| ≥ 1 and poles whose weights do not exceed the error
54    /// are dropped.
55    pub m: Option<usize>,
56    /// Preserve up-down symmetry.
57    pub symmetry: bool,
58    /// Symmetrize the data as `G_ij(z) = G_ji(z)`.
59    pub g_symmetric: bool,
60    /// Fit a constant term of `G`.
61    pub compute_const: bool,
62    /// Plane for the pole weights; `None` uses `Z` without and `W` with
63    /// symmetry.
64    pub plane: Option<Plane>,
65    /// Include the first `n0` points in the weight fit in the z plane.
66    pub include_n0: bool,
67    /// Maximum number of contour integrals (default 999).
68    pub k_max: usize,
69    /// Maximum ratio of oscillation when choosing `n0` (default 10).
70    pub ratio_max: f64,
71}
72
73impl MiniPoleParams {
74    /// Parameters with tolerance `err` and defaults otherwise.
75    pub fn new(err: f64) -> Self {
76        Self {
77            n0: N0::Auto { shift: 0 },
78            err,
79            err_type: ErrType::Abs,
80            m: None,
81            symmetry: false,
82            g_symmetric: false,
83            compute_const: false,
84            plane: None,
85            include_n0: false,
86            k_max: 999,
87            ratio_max: 10.0,
88        }
89    }
90}
91
92/// Minimal pole representation of Matsubara data.
93///
94/// `g_w` has shape `[n_w]` or `[n_w, n_orb, n_orb]`, `w` the corresponding
95/// finite, increasing, uniformly spaced non-negative Matsubara frequencies
96/// `ω_n` (real).
97///
98/// # Errors
99/// [`Error::ShapeMismatch`] for inconsistent shapes,
100/// [`Error::InvalidParameter`] for a grid that is not finite, increasing,
101/// uniform and non-negative or invalid parameters, and ESPRIT errors.
102pub fn mini_pole(
103    g_w: &TypedTensor<C64>,
104    w: &[f64],
105    params: &MiniPoleParams,
106) -> Result<MiniPoleResult> {
107    let shape = g_w.shape().to_vec();
108    let nw = w.len();
109    let n_orb = match shape.len() {
110        1 => 1,
111        3 if shape[1] == shape[2] => shape[1],
112        _ => {
113            return Err(Error::ShapeMismatch {
114                which: ArrayRole::Input,
115                expected: vec![
116                    nw,
117                    shape.get(1).copied().unwrap_or(1),
118                    shape.get(1).copied().unwrap_or(1),
119                ],
120                actual: shape,
121            });
122        }
123    };
124    if shape[0] != nw {
125        let mut expected = shape.clone();
126        expected[0] = nw;
127        return Err(Error::ShapeMismatch {
128            which: ArrayRole::Input,
129            expected,
130            actual: shape,
131        });
132    }
133    if nw < 3
134        || w.iter().any(|x| !x.is_finite() || *x < 0.0)
135        || w.windows(2).any(|pair| pair[1] <= pair[0])
136    {
137        return Err(Error::InvalidParameter {
138            name: "w",
139            value: format!("of length {nw} starting at {:?}", w.first()),
140            reason: "must have at least 3 finite, non-negative, strictly increasing frequencies"
141                .to_string(),
142        });
143    }
144    let wabs = w.iter().map(|x| x.abs()).fold(0.0, f64::max);
145    let dd = (0..nw - 2)
146        .map(|i| ((w[i + 2] - 2.0 * w[i + 1] + w[i]) / wabs).abs())
147        .fold(0.0, f64::max);
148    if dd.is_nan() || dd >= 1e-6 {
149        return Err(Error::InvalidParameter {
150            name: "w",
151            value: format!("with second differences up to {dd:e}"),
152            reason: "must be uniformly spaced".to_string(),
153        });
154    }
155    if params.symmetry && params.compute_const {
156        return Err(Error::InvalidParameter {
157            name: "compute_const",
158            value: "true".to_string(),
159            reason: "set symmetry to false to calculate the overall constant".to_string(),
160        });
161    }
162    let d = n_orb * n_orb;
163    let tr = |c: usize| (c % n_orb) * n_orb + c / n_orb;
164    let raw = g_w.host_data()?;
165    let g: Vec<C64> = if params.g_symmetric {
166        (0..nw * d)
167            .map(|idx| {
168                let (i, c) = (idx % nw, idx / nw);
169                (raw[idx] + raw[i + nw * tr(c)]) * 0.5
170            })
171            .collect()
172    } else {
173        raw.to_vec()
174    };
175    let plane = params
176        .plane
177        .unwrap_or(if params.symmetry { Plane::W } else { Plane::Z });
178
179    // First ESPRIT on each component.
180    let first = |lfactor: f64| -> Result<Vec<Esprit>> {
181        (0..d)
182            .map(|c| {
183                Esprit::new(
184                    &g[nw * c..nw * (c + 1)],
185                    nw,
186                    1,
187                    &EspritParams {
188                        x_min: w[0],
189                        x_max: w[nw - 1],
190                        err: Some(params.err),
191                        err_type: params.err_type,
192                        lfactor,
193                        ..EspritParams::default()
194                    },
195                )
196            })
197            .collect()
198    };
199    let p_o = first(0.4)?;
200    let (n0, err_max) = match params.n0 {
201        N0::Auto { shift } => {
202            let p_o2 = first(0.5)?;
203            let w_cont = linspace(w[0], w[nw - 1], 10 * nw - 9);
204            let err_max = p_o
205                .iter()
206                .chain(&p_o2)
207                .map(|p| p.err_max)
208                .fold(f64::NEG_INFINITY, f64::max);
209            let mut n0 = 0;
210            for c in 0..d {
211                let l1 = p_o[c].get_value(&w_cont);
212                let l2 = p_o2[c].get_value(&w_cont);
213                let diff: Vec<f64> = (0..nw - 1)
214                    .map(|j| {
215                        (0..10)
216                            .map(|t| (l2[10 * j + t] - l1[10 * j + t]).norm())
217                            .fold(f64::NEG_INFINITY, f64::max)
218                    })
219                    .collect();
220                let first_ok = (0..nw - 2)
221                    .position(|j| diff[j] <= err_max && diff[j] / diff[j + 1] < params.ratio_max)
222                    .unwrap_or(0);
223                n0 = n0.max(first_ok);
224            }
225            (n0 + shift, err_max)
226        }
227        N0::Fixed(n0) => (
228            n0,
229            p_o.iter()
230                .map(|p| p.err_max)
231                .fold(f64::NEG_INFINITY, f64::max),
232        ),
233    };
234    if n0 + 1 >= nw {
235        return Err(Error::InvalidParameter {
236            name: "n0",
237            value: n0.to_string(),
238            reason: format!("must be less than len(w) - 1 = {}", nw - 1),
239        });
240    }
241    if params.symmetry && w[n0] <= 0.0 {
242        // ConMapGapless needs ω_min > 0 (e.g. n0 = 0 on a bosonic grid).
243        return Err(Error::InvalidParameter {
244            name: "n0",
245            value: n0.to_string(),
246            reason: format!("must give w[n0] > 0 with symmetry, got {:?}", w[n0]),
247        });
248    }
249    let head = |c: usize, x: f64| p_o[c].get_value_indiv(x, 0);
250    let cutoff = err_max;
251    let qerr = 0.01 * cutoff;
252
253    let generic;
254    let gapless;
255    let mut constant = vec![C64::new(0.0, 0.0); d];
256    let (map, h, nk): (&dyn ConMap, Vec<C64>, usize) = if !params.symmetry {
257        generic = ConMapGeneric {
258            w_m: 0.5 * (w[n0] + w[nw - 1]),
259            dw_h: 0.5 * (w[nw - 1] - w[n0]),
260        };
261        let (w_m, dw_h) = (generic.w_m, generic.dw_h);
262        let (h, nk) = moments(params.k_max, d, cutoff, |k, c| {
263            let f = |x: f64| head(c, w_m + dw_h * x.sin());
264            let v = oscillatory(&f, -0.5 * PI, 0.5 * PI, (k + 1) as f64, k & 1 == 0, qerr);
265            if k & 1 == 0 {
266                v * C64::new(0.0, 1.0 / PI)
267            } else {
268                v / PI
269            }
270        });
271        (&generic, h, nk)
272    } else {
273        // Complex poles for the data in [iω_max, i∞).
274        let sub = mini_pole(
275            g_w,
276            w,
277            &MiniPoleParams {
278                m: None,
279                symmetry: false,
280                plane: None,
281                include_n0: false,
282                ..params.clone()
283            },
284        )?;
285        constant = sub.constant.clone();
286        let sub_loc = sub.pole_location.clone();
287        let sub_w = sub.pole_weight.host_data()?.to_vec();
288        let r_sub = sub_loc.len();
289        let tail = move |c: usize, x: f64| -> C64 {
290            let z = C64::new(0.0, x);
291            (0..r_sub)
292                .map(|j| sub_w[j + r_sub * c] / (z - sub_loc[j]))
293                .sum()
294        };
295        gapless = ConMapGapless { w_min: w[n0] };
296        let w_min = gapless.w_min;
297        let theta0 = (w_min / w[nw - 1]).asin();
298        let (ha, hb) = (theta0 + 1e-12, 0.5 * PI);
299        let (ta, tb) = (1e-6, theta0 - 1e-12);
300        let integral = |f: &dyn Fn(f64) -> C64, a: f64, b: f64, k: usize| {
301            oscillatory(f, a, b, (k + 1) as f64, k & 1 == 0, qerr)
302        };
303        // cal_hk_gapless_symmetric_indiv on one function
304        let sym = |gf: &dyn Fn(f64) -> C64, k: usize, a: f64, b: f64| -> C64 {
305            if k & 1 == 0 {
306                let f = |x: f64| C64::new(gf(w_min / x.sin()).im, 0.0);
307                integral(&f, a, b, k) * (-2.0 / PI)
308            } else {
309                let f = |x: f64| C64::new(gf(w_min / x.sin()).re, 0.0);
310                integral(&f, a, b, k) * (2.0 / PI)
311            }
312        };
313        let raw_int = |gf: &dyn Fn(f64) -> C64, k: usize, a: f64, b: f64| -> C64 {
314            let f = |x: f64| gf(w_min / x.sin());
315            integral(&f, a, b, k)
316        };
317        let sym_hk = |c: usize, k: usize| -> C64 {
318            sym(&|x| head(c, x), k, ha, hb) + sym(&|x| tail(c, x), k, ta, tb)
319        };
320        let (h, nk) = if params.g_symmetric {
321            moments(params.k_max, d, cutoff, |k, c| sym_hk(c, k))
322        } else {
323            moments_rows(params.k_max, d, cutoff, |k| {
324                let mut row = vec![C64::new(0.0, 0.0); d];
325                for i in 0..n_orb {
326                    for j in i..n_orb {
327                        // Channel of G_ij in the column-major layout.
328                        let c1 = i + n_orb * j;
329                        let c2 = j + n_orb * i;
330                        if i == j {
331                            row[c1] = sym_hk(c1, k);
332                        } else {
333                            let h1 = raw_int(&|x| head(c1, x), k, ha, hb)
334                                + raw_int(&|x| tail(c1, x), k, ta, tb);
335                            let h2 = raw_int(&|x| head(c2, x), k, ha, hb)
336                                + raw_int(&|x| tail(c2, x), k, ta, tb);
337                            if k & 1 == 0 {
338                                let f = C64::new(0.0, 1.0 / PI);
339                                row[c1] = f * (h1 - h2.conj());
340                                row[c2] = f * (h2 - h1.conj());
341                            } else {
342                                row[c1] = (h1 + h2.conj()) / PI;
343                                row[c2] = (h2 + h1.conj()) / PI;
344                            }
345                        }
346                    }
347                }
348                row
349            })
350        };
351        (&gapless, h, nk)
352    };
353
354    // find_poles: second ESPRIT on the contour integrals.
355    let esprit = Esprit::new(
356        &h,
357        nk,
358        d,
359        &EspritParams {
360            err: if params.m.is_none() {
361                Some(0.5 * err_max)
362            } else {
363                None
364            },
365            m: params.m,
366            lfactor: 0.5,
367            ..EspritParams::default()
368        },
369    )?;
370    let keep: Vec<usize> = (0..esprit.gamma.len())
371        .filter(|&j| esprit.gamma[j].norm() < 1.0)
372        .collect();
373    let r = keep.len();
374    let location: Vec<C64> = keep.iter().map(|&j| map.z(esprit.gamma[j])).collect();
375    let mut weight = vec![C64::new(0.0, 0.0); r * d];
376    for (jn, &j) in keep.iter().enumerate() {
377        let f = map.dz(esprit.gamma[j]);
378        for c in 0..d {
379            weight[jn + r * c] = esprit.omega[j + esprit.m * c] * f;
380        }
381    }
382    if params.compute_const {
383        let nf = nw - n0;
384        let mut cst = vec![C64::new(0.0, 0.0); d];
385        for (c, v) in cst.iter_mut().enumerate() {
386            for i in n0..nw {
387                let z = C64::new(0.0, w[i]);
388                let approx: C64 = (0..r).map(|j| weight[j + r * c] / (z - location[j])).sum();
389                *v += g[i + nw * c] - approx;
390            }
391            *v /= nf as f64;
392        }
393        let big = cst.iter().map(|v| v.norm()).fold(0.0, f64::max) > 100.0 * err_max;
394        constant = if big {
395            cst
396        } else {
397            vec![C64::new(0.0, 0.0); d]
398        };
399    }
400    if plane == Plane::Z {
401        let start = if params.include_n0 { 0 } else { n0 };
402        let mut ws: Vec<f64> = Vec::new();
403        let mut rows: Vec<(usize, bool)> = Vec::new(); // (frequency index, mirrored)
404        if params.symmetry {
405            for i in (start..nw).rev() {
406                ws.push(-w[i]);
407                rows.push((i, true));
408            }
409        }
410        ws.extend_from_slice(&w[start..]);
411        rows.extend((start..nw).map(|i| (i, false)));
412        let nr = ws.len();
413        let mut a = vec![C64::new(0.0, 0.0); nr * r];
414        for (j, &loc) in location.iter().enumerate() {
415            for (i, &x) in ws.iter().enumerate() {
416                a[i + nr * j] = (C64::new(0.0, x) - loc).inv();
417            }
418        }
419        let mut b = vec![C64::new(0.0, 0.0); nr * d];
420        for c in 0..d {
421            for (i, &(fi, mirrored)) in rows.iter().enumerate() {
422                let v = if mirrored {
423                    g[fi + nw * tr(c)].conj()
424                } else {
425                    g[fi + nw * c]
426                };
427                b[i + nr * c] = v - constant[c];
428            }
429        }
430        weight = lstsq(&a, nr, r, &b, d)?;
431    }
432    // Discard poles with negligible weights.
433    let keep: Vec<usize> = (0..r)
434        .filter(|&j| (0..d).map(|c| weight[j + r * c].norm()).fold(0.0, f64::max) > err_max)
435        .collect();
436    let location_k: Vec<C64> = keep.iter().map(|&j| location[j]).collect();
437    let mut weight_k = vec![C64::new(0.0, 0.0); keep.len() * d];
438    for (jn, &j) in keep.iter().enumerate() {
439        for c in 0..d {
440            weight_k[jn + keep.len() * c] = weight[j + r * c];
441        }
442    }
443    let mut hshape = shape;
444    hshape[0] = nk;
445    assemble(
446        location_k,
447        weight_k,
448        constant,
449        h,
450        hshape,
451        esprit,
452        n0,
453        Some(err_max),
454    )
455}
456
457/// Rows `h_k` for `k = 0, 1, …` until two successive rows are below
458/// `cutoff` in every component, at most `k_max` rows; column-major `K x d`.
459fn moments(
460    k_max: usize,
461    d: usize,
462    cutoff: f64,
463    f: impl Fn(usize, usize) -> C64,
464) -> (Vec<C64>, usize) {
465    moments_rows(k_max, d, cutoff, |k| (0..d).map(|c| f(k, c)).collect())
466}
467
468fn moments_rows(
469    k_max: usize,
470    d: usize,
471    cutoff: f64,
472    f: impl Fn(usize) -> Vec<C64>,
473) -> (Vec<C64>, usize) {
474    let mut rows: Vec<Vec<C64>> = Vec::new();
475    for k in 0..k_max {
476        rows.push(f(k));
477        if k >= 1 && (0..d).all(|c| rows[k][c].norm() < cutoff && rows[k - 1][c].norm() < cutoff) {
478            break;
479        }
480    }
481    let nk = rows.len();
482    let mut h = vec![C64::new(0.0, 0.0); nk * d];
483    for (k, row) in rows.iter().enumerate() {
484        for c in 0..d {
485            h[k + nk * c] = row[c];
486        }
487    }
488    (h, nk)
489}