vanhove 0.2.0

Model densities of states with integrable van Hove singularities, their convolutions, and accurate integration of spectral functions
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//! Discrete spectral function.

use std::ops::{Add, Mul, Neg, Sub};

use crate::segment::Segment;
use crate::util;

/// Single discrete resonance $w \delta(\omega - \varepsilon)$.
#[derive(Debug, Clone, Copy)]
pub struct Resonance {
    /// Position of the resonance, $\varepsilon$.
    pub eps: f64,
    /// Weight of the resonance, $w$.
    pub weight: f64,
}

/// Discrete spectral function with a finite number of resonances,
/// $$
///     D(\omega) = \sum_p w_p \delta(\omega - \varepsilon_p).
/// $$
///
/// The list of resonances is sealed upon construction and is always kept in its
/// canonical form: sorted w.r.t. $\varepsilon_p$, free of duplicate positions and
/// free of negligible weights.
#[derive(Debug, Clone, Default)]
pub struct DiscreteSF {
    /// Resonances $(\varepsilon_p, w_p)$ in the canonical form.
    resonances: Vec<Resonance>,
}

/// Build a discrete spectral function out of resonances given in an arbitrary order.
///
/// Resonances sharing a position are merged, and groups whose total weight cancels
/// out are dropped.
impl FromIterator<Resonance> for DiscreteSF {
    fn from_iter<I: IntoIterator<Item = Resonance>>(resonances: I) -> Self {
        let mut resonances: Vec<Resonance> = resonances
            .into_iter()
            .inspect(|res| {
                assert!(
                    res.eps.is_finite(),
                    "a resonance must sit at a finite frequency"
                )
            })
            .filter(|res| res.weight != 0.0)
            .map(|res| Resonance {
                // canonicalize -0.0 so that it groups with 0.0 under total_cmp
                eps: if res.eps == 0.0 { 0.0 } else { res.eps },
                weight: res.weight,
            })
            .collect();
        resonances.sort_by(|r1, r2| r1.eps.total_cmp(&r2.eps));
        canonicalize(&mut resonances);
        DiscreteSF { resonances }
    }
}

/// Addition of two discrete spectral functions.
impl Add for DiscreteSF {
    type Output = Self;

    fn add(self, rhs: Self) -> Self {
        let (lhs, rhs) = (self.resonances, rhs.resonances);
        let mut resonances = Vec::with_capacity(lhs.len() + rhs.len());

        let (mut l, mut r) = (lhs.iter().peekable(), rhs.iter().peekable());
        loop {
            let ordering = match (l.peek(), r.peek()) {
                (Some(rl), Some(rr)) => rl.eps.total_cmp(&rr.eps),
                (Some(_), None) => std::cmp::Ordering::Less,
                (None, Some(_)) => std::cmp::Ordering::Greater,
                (None, None) => break,
            };
            match ordering {
                std::cmp::Ordering::Less => resonances.push(*l.next().unwrap()),
                std::cmp::Ordering::Greater => resonances.push(*r.next().unwrap()),
                std::cmp::Ordering::Equal => {
                    // Both operands are duplicate-free, so exactly two weights meet here
                    // and their sum needs no compensation to be correctly rounded.
                    let (rl, rr) = (l.next().unwrap(), r.next().unwrap());
                    let weight = rl.weight + rr.weight;
                    // Drop the resonance if the contributions cancel each other out
                    let tol = DiscreteSF::WEIGHT_TOL;
                    if weight.abs() > tol * (rl.weight.abs() + rr.weight.abs()) {
                        resonances.push(Resonance {
                            eps: rl.eps,
                            weight,
                        });
                    }
                }
            }
        }
        DiscreteSF { resonances }
    }
}

/// Multiply all spectral weights by a real number from the right.
impl Mul<f64> for DiscreteSF {
    type Output = Self;

    fn mul(mut self, a: f64) -> Self {
        if a == 0.0 {
            self.resonances.clear();
        } else {
            // Scaling preserves both the ordering w.r.t. ε and the absence of duplicates.
            // A weight can, however, underflow to zero and has to be dropped to keep the
            // list free of negligible weights.
            self.resonances.retain_mut(|res| {
                res.weight *= a;
                res.weight != 0.0
            });
        }
        self
    }
}

/// Multiply all spectral weights by a real number from the left.
impl Mul<DiscreteSF> for f64 {
    type Output = DiscreteSF;
    fn mul(self, sf: DiscreteSF) -> DiscreteSF {
        sf * self
    }
}

/// Negation of a discrete spectral function.
impl Neg for DiscreteSF {
    type Output = Self;
    fn neg(self) -> DiscreteSF {
        self * (-1.0)
    }
}

/// Subtraction of two discrete spectral functions.
impl Sub for DiscreteSF {
    type Output = Self;
    fn sub(self, rhs: Self) -> Self {
        self + (-rhs)
    }
}

/// Iterate over the resonances in the order of increasing $\varepsilon_p$.
impl<'a> IntoIterator for &'a DiscreteSF {
    type Item = &'a Resonance;
    type IntoIter = std::slice::Iter<'a, Resonance>;
    fn into_iter(self) -> Self::IntoIter {
        self.resonances.iter()
    }
}

/// Merge resonances sharing the same position within an $\varepsilon$-sorted list, and
/// remove the groups whose total weight is negligible. Called on a freshly sorted list,
/// this establishes the canonical form.
fn canonicalize(resonances: &mut Vec<Resonance>) {
    let (mut w, mut i) = (0, 0);
    while i < resonances.len() {
        // Find a slice of resonances sharing the same ε
        let start = i;
        let eps = resonances[i].eps;
        while i < resonances.len() && resonances[i].eps == eps {
            i += 1;
        }

        // A lone resonance needs no summation and can never be negligible
        if i == start + 1 {
            resonances[w] = resonances[start];
            w += 1;
            continue;
        }

        // Sum all weights within the slice, with Neumaier compensation
        let group = &mut resonances[start..i];
        group.sort_unstable_by(|r1, r2| r1.weight.abs().total_cmp(&r2.weight.abs()));
        let total = util::kahan_babushka_neumaier_sum(group.iter().map(|r| r.weight));

        // Keep the resonance if its total weight is not too small compared
        // to the total magnitude of the weights
        let mag: f64 = group.iter().map(|r| r.weight.abs()).sum();
        if total.abs() > DiscreteSF::WEIGHT_TOL * mag {
            resonances[w] = Resonance { eps, weight: total };
            w += 1;
        }
    }
    // Remove the unused elements
    resonances.truncate(w);
}

impl DiscreteSF {
    /// Relative tolerance below which the total weight of a group of resonances sharing
    /// the same position is considered a cancellation artefact and is discarded.
    pub const WEIGHT_TOL: f64 = f64::EPSILON;

    /// Make an empty discrete spectral function (zero resonances).
    pub fn new() -> Self {
        Self::default()
    }

    /// Make a discrete spectral function with one resonance.
    pub fn one_resonance(eps: f64, weight: f64) -> DiscreteSF {
        DiscreteSF::from_iter([Resonance { eps, weight }])
    }

    /// Access the resonance list in its canonical form (sorted w.r.t. $\varepsilon_p$,
    /// deduplicated, free of negligible weights).
    pub fn resonances(&self) -> &[Resonance] {
        &self.resonances
    }

    /// Number of resonances in the spectral function.
    pub fn len(&self) -> usize {
        self.resonances.len()
    }

    /// Is the spectral function free of resonances?
    pub fn is_empty(&self) -> bool {
        self.resonances.is_empty()
    }

    /// Iterate over the resonances in the order of increasing $\varepsilon_p$.
    pub fn iter(&self) -> std::slice::Iter<'_, Resonance> {
        self.resonances.iter()
    }

    /// Consume the spectral function and return its resonance list in the canonical form.
    pub fn into_resonances(self) -> Vec<Resonance> {
        self.resonances
    }

    /// Support of the spectral function.
    ///
    /// It is the segment between the positions of the lowest and the highest resonances.
    /// Returns [`None`] for an empty spectral function.
    pub fn support(&self) -> Option<Segment> {
        Some(Segment::new(
            self.resonances.first()?.eps,
            self.resonances.last()?.eps,
        ))
    }

    /// Total spectral weight.
    pub fn total_weight(&self) -> f64 {
        util::kahan_babushka_neumaier_sum(self.iter().map(|r| r.weight))
    }

    /// The same spectral function displaced in frequency by `by`.
    pub fn shifted(&self, by: f64) -> DiscreteSF {
        self.iter()
            .map(|r| Resonance {
                eps: r.eps + by,
                weight: r.weight,
            })
            .collect()
    }

    /// The image of the spectral function under the reflection $\nu \mapsto \omega - \nu$.
    pub fn mirrored(&self, omega: f64) -> DiscreteSF {
        self.iter()
            .map(|r| Resonance {
                eps: omega - r.eps,
                weight: r.weight,
            })
            .collect()
    }

    /// Convolution with another discrete spectral function,
    /// $\int D_A(\nu) D_B(\omega - \nu) d\nu$.
    pub fn conv(&self, other: &DiscreteSF) -> DiscreteSF {
        self.iter()
            .flat_map(|a| {
                other.iter().map(move |b| Resonance {
                    eps: a.eps + b.eps,
                    weight: a.weight * b.weight,
                })
            })
            .collect()
    }

    /// Find the resonance located at a given position $\varepsilon$, if any.
    pub fn find(&self, eps: f64) -> Option<&Resonance> {
        // -0.0 is stored as 0.0, so the same canonicalization applies to the needle
        let eps = if eps == 0.0 { 0.0 } else { eps };
        let index = self
            .resonances
            .binary_search_by(|res| res.eps.total_cmp(&eps))
            .ok()?;
        Some(&self.resonances[index])
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_relative_eq;

    #[test]
    #[should_panic(expected = "must sit at a finite frequency")]
    fn from_iter_nan() {
        let _ = DiscreteSF::one_resonance(f64::NAN, 1.0);
    }

    #[test]
    #[should_panic(expected = "must sit at a finite frequency")]
    fn from_iter_infinite() {
        // A resonance out at infinity would leave `support()` no segment to name
        let _ = DiscreteSF::one_resonance(f64::INFINITY, 1.0);
    }

    #[test]
    fn add() {
        let sf = DiscreteSF::new();
        assert!(sf.is_empty());
        assert_eq!(sf.resonances().len(), 0);
        assert_eq!(sf.total_weight(), 0.0);
        assert_eq!(sf.support(), None);

        let sf = DiscreteSF::one_resonance(2.0, 1.0);
        assert_eq!(sf.len(), 1);
        assert_eq!(sf.resonances()[0].eps, 2.0);
        assert_eq!(sf.resonances()[0].weight, 1.0);
        assert_eq!(sf.total_weight(), 1.0);
        assert_eq!(sf.support(), Some(Segment::new(2.0, 2.0)));

        // A resonance of zero weight is not a resonance
        assert!(DiscreteSF::one_resonance(2.0, 0.0).is_empty());

        let sf = sf + DiscreteSF::one_resonance(-1.5, 0.25);
        assert_eq!(sf.len(), 2);
        assert_eq!(sf.total_weight(), 1.25);
        assert_eq!(sf.support(), Some(Segment::new(-1.5, 2.0)));

        // Exactly cancelling contributions annihilate the resonance
        let sf = sf + DiscreteSF::one_resonance(2.0, -1.0);
        assert_eq!(sf.len(), 1);
        assert_eq!(sf.total_weight(), 0.25);
        assert_eq!(sf.support(), Some(Segment::new(-1.5, -1.5)));
    }

    #[test]
    fn from_iter() {
        let batch: Vec<Resonance> = (0..100)
            .map(|n| Resonance {
                eps: ((n * 37) % 20) as f64 - 10.0,
                weight: 0.01,
            })
            .collect();

        // Building in one go and accumulating pairwise give the same canonical form
        let bulk = DiscreteSF::from_iter(batch.iter().copied());
        let one_by_one = batch.iter().fold(DiscreteSF::new(), |sf, res| {
            sf + DiscreteSF::one_resonance(res.eps, res.weight)
        });

        // 20 distinct levels, each hit 5 times
        assert_eq!(bulk.len(), 20);
        assert_relative_eq!(bulk.total_weight(), 1.0, epsilon = 1e-15);
        assert_eq!(bulk.support(), Some(Segment::new(-10.0, 9.0)));
        for (r1, r2) in bulk.iter().zip(&one_by_one) {
            assert_eq!(r1.eps, r2.eps);
            assert_relative_eq!(r1.weight, r2.weight, epsilon = 1e-15);
        }
        // Sorted w.r.t. ε and free of duplicates
        assert!(bulk.resonances().windows(2).all(|w| w[0].eps < w[1].eps));

        // Exactly cancelling contributions are dropped, keeping the survivors
        let sf = bulk
            + DiscreteSF::from_iter(batch.iter().filter(|r| r.eps < 0.0).map(|r| Resonance {
                eps: r.eps,
                weight: -r.weight,
            }));
        assert_eq!(sf.len(), 10);
        assert!(sf.iter().all(|r| r.eps >= 0.0));
        assert_relative_eq!(sf.total_weight(), 0.5, epsilon = 1e-15);
    }

    /// $M_n = \sum_p w_p \varepsilon_p^n$.
    fn moment(sf: &DiscreteSF, n: i32) -> f64 {
        sf.iter().map(|r| r.weight * r.eps.powi(n)).sum()
    }

    #[test]
    fn conv() {
        let a = DiscreteSF::from_iter([
            Resonance {
                eps: -1.0,
                weight: 0.5,
            },
            Resonance {
                eps: 2.0,
                weight: 0.25,
            },
        ]);
        let b = DiscreteSF::from_iter([
            Resonance {
                eps: 0.5,
                weight: 2.0,
            },
            Resonance {
                eps: 1.5,
                weight: -1.0,
            },
        ]);
        let c = a.conv(&b);

        // Every pair meets at the sum of its positions, with the product of weights
        assert_eq!(c.len(), 4);
        let expected = [(-0.5, 1.0), (0.5, -0.5), (2.5, 0.5), (3.5, -0.25)];
        for (res, (eps, weight)) in c.iter().zip(expected) {
            assert_relative_eq!(res.eps, eps, epsilon = 1e-14);
            assert_relative_eq!(res.weight, weight, epsilon = 1e-14);
        }

        // Weight is multiplicative under convolution
        assert_relative_eq!(
            c.total_weight(),
            a.total_weight() * b.total_weight(),
            epsilon = 1e-14
        );

        // Convolution commutes
        for (l, r) in a.conv(&b).iter().zip(b.conv(&a).iter()) {
            assert_eq!(l.eps, r.eps);
            assert_eq!(l.weight, r.weight);
        }

        // Moments obey M_n = Σ_k C(n,k) M_k^A M_{n-k}^B
        for n in 0..=4 {
            let c_row = util::binomials(n);
            let reference: f64 = (0..=n)
                .map(|k| c_row[k] * moment(&a, k as i32) * moment(&b, (n - k) as i32))
                .sum();
            assert_relative_eq!(moment(&c, n as i32), reference, epsilon = 1e-12);
        }
    }

    #[test]
    fn conv_degenerate() {
        let unit = |eps| DiscreteSF::one_resonance(eps, 1.0);

        // A unit resonance at the origin is the identity, one elsewhere shifts
        let a = DiscreteSF::from_iter([
            Resonance {
                eps: -1.0,
                weight: 0.5,
            },
            Resonance {
                eps: 2.0,
                weight: 0.25,
            },
        ]);
        for (l, r) in a.conv(&unit(0.0)).iter().zip(a.iter()) {
            assert_eq!((l.eps, l.weight), (r.eps, r.weight));
        }
        for (l, r) in a.conv(&unit(3.0)).iter().zip(a.iter()) {
            assert_eq!((l.eps, l.weight), (r.eps + 3.0, r.weight));
        }

        // An empty spectral function annihilates whatever it meets
        assert!(a.conv(&DiscreteSF::new()).is_empty());
        assert!(DiscreteSF::new().conv(&a).is_empty());

        // Pairs landing on one position are merged, and cancel there if they sum to zero
        let ladder = |w| {
            DiscreteSF::from_iter([
                Resonance {
                    eps: 0.0,
                    weight: 1.0,
                },
                Resonance {
                    eps: 1.0,
                    weight: w,
                },
            ])
        };
        let binomial = ladder(1.0).conv(&ladder(1.0));
        assert_eq!(binomial.len(), 3);
        assert_relative_eq!(binomial.find(1.0).unwrap().weight, 2.0, epsilon = 1e-14);

        let cancelling = ladder(1.0).conv(&ladder(-1.0));
        assert_eq!(cancelling.len(), 2);
        assert!(cancelling.find(1.0).is_none());
    }

    #[test]
    fn find() {
        let sf = DiscreteSF::from_iter((0..64).map(|n| Resonance {
            eps: (n - 32) as f64 / 2.0,
            weight: 1.0 / 64.0,
        }));

        for n in 0..64 {
            let eps = (n - 32) as f64 / 2.0;
            assert_eq!(sf.find(eps).unwrap().eps, eps);
            assert_eq!(sf.find(eps).unwrap().weight, 1.0 / 64.0);
        }
        assert!(sf.find(0.25).is_none());
        assert!(sf.find(100.0).is_none());
        // -0.0 and 0.0 denote the same position
        assert_eq!(sf.find(-0.0).unwrap().eps, 0.0);
        assert_eq!(
            DiscreteSF::one_resonance(-0.0, 1.0).find(0.0).unwrap().eps,
            0.0
        );
    }

    #[test]
    fn neg() {
        let sf = DiscreteSF::one_resonance(2.0, 1.0) + DiscreteSF::one_resonance(-1.5, 0.25);
        let neg_sf = -sf.clone();

        // Negation flips the sign of every weight while preserving the positions
        assert_eq!(neg_sf.len(), 2);
        assert_eq!(neg_sf.support(), sf.support());
        assert_eq!(neg_sf.resonances()[0].weight, -0.25);
        assert_eq!(neg_sf.resonances()[1].weight, -1.0);
        assert_eq!(neg_sf.total_weight(), -sf.total_weight());

        // Negating twice is the identity
        assert_eq!((-neg_sf).total_weight(), sf.total_weight());

        // Negation of an empty spectral function is empty
        assert!((-DiscreteSF::new()).is_empty());
    }

    #[test]
    fn sub() {
        let sf = DiscreteSF::one_resonance(2.0, 1.0) + DiscreteSF::one_resonance(-1.5, 0.25);

        // Resonances sharing a position have their weights subtracted
        let diff = sf.clone() - DiscreteSF::one_resonance(2.0, 0.75);
        assert_eq!(diff.len(), 2);
        assert_relative_eq!(diff.find(2.0).unwrap().weight, 0.25, epsilon = 1e-15);
        assert_eq!(diff.find(-1.5).unwrap().weight, 0.25);

        // Resonances absent from the left operand enter with a negative weight
        let diff = sf.clone() - DiscreteSF::one_resonance(4.0, 0.5);
        assert_eq!(diff.len(), 3);
        assert_eq!(diff.find(4.0).unwrap().weight, -0.5);
        assert_relative_eq!(diff.total_weight(), 0.75, epsilon = 1e-15);

        // A spectral function subtracted from itself cancels out exactly
        let zero = sf.clone() - sf;
        assert!(zero.is_empty());
        assert_eq!(zero.total_weight(), 0.0);
    }

    #[test]
    fn mul() {
        let sf = DiscreteSF::one_resonance(2.0, 1.0) + DiscreteSF::one_resonance(-1.5, 0.25);

        let sf = sf * 4.0;
        assert_eq!(sf.len(), 2);
        assert_eq!(sf.resonances()[0].weight, 1.0);
        assert_eq!(sf.resonances()[1].weight, 4.0);
        assert_eq!(sf.total_weight(), 5.0);

        // Weights underflowing to zero are dropped
        let sf = f64::MIN_POSITIVE * (f64::MIN_POSITIVE * sf);
        assert!(sf.is_empty());
        assert_eq!(sf.total_weight(), 0.0);

        // Scaling by zero empties the spectral function
        let sf = DiscreteSF::one_resonance(2.0, 1.0) * 0.0;
        assert!(sf.is_empty());
        assert_eq!(sf.total_weight(), 0.0);
    }
}