sparse-ir-dlr 0.16.0

Discrete Lehmann representation (DLR) of imaginary-time Green's functions, part of sparse-ir
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! Interpolative-decomposition (ID) construction of the DLR.
//!
//! Implements the construction of Kaye, Chen and Parcollet,
//! "Discrete Lehmann representation of imaginary time Green's functions",
//! Phys. Rev. B 105, 235115 (2022):
//!
//! 1. discretize the dimensionless logistic kernel
//!    `K(τ, ω) = e^{-τω} / (1 + e^{-ω})`, `τ ∈ [0, 1]`, `ω ∈ [-Λ, Λ]`, on
//!    composite Chebyshev grids refined dyadically towards `τ ∈ {0, 1}` and
//!    `ω = 0`;
//! 2. select real-frequency poles by a column-pivoted Gram–Schmidt (rank
//!    revealing) factorization of the discretized kernel;
//! 3. select imaginary-time and Matsubara nodes by the same procedure on the
//!    rows of the kernel restricted to the selected poles.
//!
//! The grids follow the parameter choices described in the paper (24-point
//! Chebyshev panels, `⌈log2 Λ⌉ - 2` dyadic levels in τ and `⌈log2 Λ⌉` in ω).
//! Everything here is statistics independent except the Matsubara candidates.

use num_complex::Complex;

/// Chebyshev nodes (first kind) per panel.
const PANEL_ORDER: usize = 24;

/// Matsubara indices `|k| <= DENSE_K` are all candidates; beyond that the
/// candidates are geometrically spaced.
const DENSE_K: i64 = 128;

/// Geometric candidates per octave beyond `DENSE_K`.
const POINTS_PER_OCTAVE: f64 = 32.0;

/// Imaginary-time candidate `τ/β`, stored as the distance `t` to the nearer
/// endpoint so that the kernel keeps full relative accuracy near `τ = β`.
#[derive(Clone, Copy, Debug)]
pub(crate) struct TauCandidate {
    /// Distance to the nearer endpoint, `t ∈ (0, 1/2]`.
    pub t: f64,
    /// `true` when `τ/β = 1 - t`, `false` when `τ/β = t`.
    pub from_end: bool,
}

impl TauCandidate {
    /// Dimensionless `τ/β`.
    pub fn value(self) -> f64 {
        if self.from_end { 1.0 - self.t } else { self.t }
    }
}

fn dyadic_levels(lambda: f64, offset: i64) -> usize {
    let l = lambda.max(1.0).log2().ceil() as i64 - offset;
    l.max(1) as usize
}

/// Chebyshev nodes of the first kind on each panel `[breaks[i], breaks[i+1]]`.
fn composite_chebyshev(breaks: &[f64]) -> Vec<f64> {
    let p = PANEL_ORDER;
    let mut x = Vec::with_capacity(p * (breaks.len() - 1));
    for w in breaks.windows(2) {
        let (a, b) = (w[0], w[1]);
        for k in (0..p).rev() {
            let c = (std::f64::consts::PI * (2 * k + 1) as f64 / (2 * p) as f64).cos();
            x.push(0.5 * (a + b) + 0.5 * (b - a) * c);
        }
    }
    x
}

/// Imaginary-time candidates on `[0, 1]`: dyadic panels towards both ends.
pub(crate) fn tau_candidates(lambda: f64) -> Vec<TauCandidate> {
    let npt = dyadic_levels(lambda, 2);
    // Breaks 0, 2^-npt, ..., 1/4, 1/2 on the half interval [0, 1/2].
    let mut breaks = vec![0.0];
    breaks.extend((0..npt).map(|i| 0.5 * 2f64.powi(i as i32 - npt as i32 + 1)));
    let half = composite_chebyshev(&breaks);
    let mut out: Vec<TauCandidate> = half
        .iter()
        .map(|&t| TauCandidate { t, from_end: false })
        .collect();
    out.extend(
        half.iter()
            .rev()
            .map(|&t| TauCandidate { t, from_end: true }),
    );
    out
}

/// Real-frequency candidates on `[-Λ, Λ]`: dyadic panels towards `ω = 0`.
pub(crate) fn omega_candidates(lambda: f64) -> Vec<f64> {
    let npo = dyadic_levels(lambda, 0);
    let mut breaks = vec![0.0];
    breaks.extend((0..npo).map(|i| lambda * 2f64.powi(i as i32 - npo as i32 + 1)));
    let pos = composite_chebyshev(&breaks);
    let mut out: Vec<f64> = pos.iter().rev().map(|&w| -w).collect();
    out.extend(pos);
    out
}

/// Dimensionless logistic kernel `e^{-τω} / (1 + e^{-ω})`, evaluated in the
/// branch that avoids overflow and cancellation.
pub(crate) fn logistic_kernel(tau: TauCandidate, omega: f64) -> f64 {
    let (t, from_end) = (tau.t, tau.from_end);
    if omega >= 0.0 {
        // e^{-τω} / (1 + e^{-ω}), with τ = t or 1 - t.
        let expo = if from_end {
            t * omega - omega
        } else {
            -t * omega
        };
        expo.exp() / (1.0 + (-omega).exp())
    } else {
        // e^{(1-τ)ω} / (1 + e^{ω}), with 1 - τ = 1 - t or t.
        let expo = if from_end {
            t * omega
        } else {
            omega - t * omega
        };
        expo.exp() / (1.0 + omega.exp())
    }
}

/// Matsubara index candidates `n` (with `ν = nπ/β`) of parity `zeta`.
///
/// Every allowed index with `|n| <= 2 DENSE_K + zeta` is included; above that
/// indices are geometrically spaced up to `n_max`. With `positive_only`, only
/// `n >= 0` is returned.
pub(crate) fn matsubara_candidates(lambda: f64, zeta: i64, positive_only: bool) -> Vec<i64> {
    let to_parity = |x: f64| -> i64 {
        let k = ((x - zeta as f64) / 2.0).round() as i64;
        2 * k + zeta
    };
    let n_dense = 2 * DENSE_K + zeta;
    let n_max = to_parity((8.0 * lambda).max(n_dense as f64));
    let mut pos: Vec<i64> = (0..=DENSE_K).map(|k| 2 * k + zeta).collect();
    let ratio = 2f64.powf(1.0 / POINTS_PER_OCTAVE);
    let mut x = n_dense as f64;
    while (x as i64) < n_max {
        x *= ratio;
        let n = to_parity(x.min(n_max as f64));
        if n > *pos.last().unwrap() {
            pos.push(n);
        }
    }
    if positive_only {
        return pos;
    }
    let mut all: Vec<i64> = pos.iter().rev().filter(|&&n| n > 0).map(|&n| -n).collect();
    all.extend(pos);
    all
}

/// Scalars accepted by [`pivoted_gram_schmidt`].
pub(crate) trait GsScalar:
    Copy
    + std::ops::Add<Output = Self>
    + std::ops::Sub<Output = Self>
    + std::ops::Mul<Output = Self>
    + num_traits::Zero
{
    fn conj(self) -> Self;
    fn norm_sqr(self) -> f64;
    fn scale(self, s: f64) -> Self;
}

impl GsScalar for f64 {
    fn conj(self) -> Self {
        self
    }
    fn norm_sqr(self) -> f64 {
        self * self
    }
    fn scale(self, s: f64) -> Self {
        self * s
    }
}

impl GsScalar for Complex<f64> {
    fn conj(self) -> Self {
        Complex::conj(&self)
    }
    fn norm_sqr(self) -> f64 {
        Complex::norm_sqr(&self)
    }
    fn scale(self, s: f64) -> Self {
        self * s
    }
}

fn dot<T: GsScalar>(q: &[T], v: &[T]) -> T {
    q.iter()
        .zip(v)
        .fold(T::zero(), |acc, (&qi, &vi)| acc + qi.conj() * vi)
}

fn axpy_neg<T: GsScalar>(c: T, q: &[T], v: &mut [T]) {
    for (vi, &qi) in v.iter_mut().zip(q) {
        *vi = *vi - c * qi;
    }
}

/// Column-pivoted Gram–Schmidt on the `n` columns (each of length `m`) of the
/// column-major matrix `a`, which is overwritten.
///
/// At each step the column with the largest residual norm is selected and
/// the remaining columns are orthogonalized against it (with one step of
/// re-orthogonalization). Selection stops when the largest residual norm
/// drops to `rtol` times the largest initial column norm, or after
/// `max_rank` columns.
///
/// Returns the selected column indices in selection order.
pub(crate) fn pivoted_gram_schmidt<T: GsScalar>(
    a: &mut [T],
    m: usize,
    n: usize,
    rtol: f64,
    max_rank: usize,
) -> Vec<usize> {
    let mut gs = BlockGramSchmidt::new(a, m, n);
    let max_rank = max_rank.min(m).min(n);
    let mut piv = Vec::new();
    while piv.len() < max_rank {
        let Some((jstar, best)) = gs.best(|j| gs.norms2[j]) else {
            break;
        };
        if gs.nrm0 == 0.0 || best.sqrt() <= rtol * gs.nrm0 {
            break;
        }
        if !gs.take(jstar) {
            break;
        }
        piv.push(jstar);
    }
    piv
}

/// Residuals of the columns of a column-major `m × n` matrix after
/// orthogonalizing them against a growing set of taken columns, the state of
/// the pivoted Gram–Schmidt of [`pivoted_gram_schmidt`] and
/// [`pivoted_pair_gram_schmidt`]
struct BlockGramSchmidt<'a, T> {
    a: &'a mut [T],
    m: usize,
    n: usize,
    /// Squared residual norm of each column
    norms2: Vec<f64>,
    /// Largest initial column norm
    nrm0: f64,
    active: Vec<bool>,
    q: Vec<Vec<T>>,
}

impl<'a, T: GsScalar> BlockGramSchmidt<'a, T> {
    fn new(a: &'a mut [T], m: usize, n: usize) -> Self {
        assert_eq!(a.len(), m * n);
        let norms2: Vec<f64> = (0..n)
            .map(|j| a[j * m..(j + 1) * m].iter().map(|v| v.norm_sqr()).sum())
            .collect();
        let nrm0 = norms2.iter().cloned().fold(0.0, f64::max).sqrt();
        Self {
            a,
            m,
            n,
            norms2,
            nrm0,
            active: vec![true; n],
            q: Vec::new(),
        }
    }

    fn col(&self, j: usize) -> &[T] {
        &self.a[j * self.m..(j + 1) * self.m]
    }

    /// The active column with the largest `score`, and the score
    fn best(&self, score: impl Fn(usize) -> f64) -> Option<(usize, f64)> {
        (0..self.n)
            .filter(|&j| self.active[j])
            .map(|j| (j, score(j)))
            .max_by(|x, y| x.1.total_cmp(&y.1))
    }

    /// Take column `j`: orthogonalize it against the taken columns,
    /// normalize it and orthogonalize the active columns against it. `false`
    /// (and nothing taken) if its residual vanishes.
    fn take(&mut self, j: usize) -> bool {
        self.active[j] = false;
        let mut v = self.col(j).to_vec();
        for qk in &self.q {
            let c = dot(qk, &v);
            axpy_neg(c, qk, &mut v);
        }
        let nv = v.iter().map(|x| x.norm_sqr()).sum::<f64>().sqrt();
        if nv == 0.0 {
            return false;
        }
        v.iter_mut().for_each(|x| *x = x.scale(1.0 / nv));
        let m = self.m;
        for k in (0..self.n).filter(|&k| self.active[k]) {
            let col = &mut self.a[k * m..(k + 1) * m];
            let c = dot(&v, col);
            axpy_neg(c, &v, col);
            self.norms2[k] = col.iter().map(|x| x.norm_sqr()).sum();
        }
        self.q.push(v);
        true
    }
}

/// The pivoted Gram–Schmidt of the DLR construction, taking the columns in
/// pairs `(2p, 2p + 1)` of the `n_pairs` pairs that follow `n_fixed` leading
/// columns, which are taken first: each step takes the pair whose residual
/// columns span the largest area (determinant of their Gram matrix), the
/// pivoted QR in blocks of two. When a single vector is still needed, it
/// takes the pair with the longest residual combination (largest eigenvalue
/// of the Gram matrix) instead. Used for the Matsubara points of bases
/// without parity (pairs `(Re û(n), Im û(n))`, i.e. `±n`).
///
/// Taking stops after `max_rank` vectors (the fixed columns and two per
/// pair), or once a pair's residual columns are both below `rtol` times the
/// largest initial column norm (rank exhausted). A pair column whose residual
/// vanishes is skipped. Returns the taken pairs (0-based, after the fixed
/// columns) in order.
pub fn pivoted_pair_gram_schmidt(
    a: &mut [f64],
    m: usize,
    n_fixed: usize,
    n_pairs: usize,
    rtol: f64,
    max_rank: usize,
) -> Vec<usize> {
    let mut gs = BlockGramSchmidt::new(a, m, n_fixed + 2 * n_pairs);
    for j in 0..n_fixed {
        gs.take(j);
    }
    let mut taken = n_fixed;
    let mut pairs = Vec::new();
    while taken < max_rank {
        let one_vector = taken + 1 == max_rank;
        let gram = |gs: &BlockGramSchmidt<f64>, p: usize| {
            let (i, j) = (n_fixed + 2 * p, n_fixed + 2 * p + 1);
            let g01 = dot(gs.col(i), gs.col(j));
            (gs.norms2[i], g01, gs.norms2[j])
        };
        let score = |p: usize| {
            let (g00, g01, g11) = gram(&gs, p);
            let det = g00 * g11 - g01 * g01;
            if one_vector {
                let half = (g00 + g11) / 2.0;
                half + (half * half - det).max(0.0).sqrt()
            } else {
                det
            }
        };
        // Pairs are tracked by their first column
        let Some((first, _)) = gs.best(|j| {
            if j >= n_fixed && (j - n_fixed).is_multiple_of(2) {
                score((j - n_fixed) / 2)
            } else {
                f64::NEG_INFINITY
            }
        }) else {
            break;
        };
        if first < n_fixed || !(first - n_fixed).is_multiple_of(2) {
            break; // no pair left
        }
        let p = (first - n_fixed) / 2;
        let (g00, _, g11) = gram(&gs, p);
        if gs.nrm0 == 0.0 || g00.max(g11).sqrt() <= rtol * gs.nrm0 {
            break; // rank exhausted
        }
        gs.take(first);
        gs.take(first + 1);
        taken += 2;
        pairs.push(p);
    }
    pairs
}

/// Select dimensionless DLR poles `ω ∈ [-Λ, Λ]` for accuracy `eps`
/// (sorted ascending), optionally capped at `max_rank`.
pub(crate) fn select_poles(lambda: f64, eps: f64, max_rank: Option<usize>) -> Vec<f64> {
    let taus = tau_candidates(lambda);
    let omegas = omega_candidates(lambda);
    let m = taus.len();
    let n = omegas.len();
    let mut a = Vec::with_capacity(m * n);
    for &w in &omegas {
        a.extend(taus.iter().map(|&t| logistic_kernel(t, w)));
    }
    let piv = pivoted_gram_schmidt(&mut a, m, n, eps, max_rank.unwrap_or(usize::MAX));
    let mut poles: Vec<f64> = piv.iter().map(|&j| omegas[j]).collect();
    poles.sort_by(f64::total_cmp);
    poles
}

/// Select `rank` rows of the column-major `rows x cols` matrix `mat` (rows
/// are treated as vectors) and return their indices sorted ascending.
pub(crate) fn select_rows<T: GsScalar>(
    mat: &[T],
    rows: usize,
    cols: usize,
    rank: usize,
) -> Vec<usize> {
    assert_eq!(mat.len(), rows * cols);
    // Transpose so that each row becomes a contiguous vector.
    let mut t = vec![T::zero(); rows * cols];
    for j in 0..cols {
        for i in 0..rows {
            t[i * cols + j] = mat[i + rows * j];
        }
    }
    let mut piv = pivoted_gram_schmidt(&mut t, cols, rows, 0.0, rank);
    piv.sort_unstable();
    piv
}

#[cfg(test)]
#[path = "dlr_id_tests.rs"]
mod tests;