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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
#![doc = include_str!("../README.md")]
#![forbid(unsafe_code)]
#![warn(missing_docs)]

mod beta;
mod conv;
pub mod discrete;
pub mod interp;
pub mod models;
mod polynomial;
pub mod segment;
pub mod singularity;
mod util;

use std::f64::consts::PI;
use std::ops::{Add, Mul, Neg, Sub};
use std::sync::Arc;

use bilby::QuadratureError;
use bilby::result::QuadratureResult;
use num_complex::Complex64;

use crate::discrete::DiscreteSF;
use crate::interp::InterpolatedSF;
use crate::segment::Segment;
use crate::singularity::{Singularity, Strength};

//
// ContinuousSF
//

/// The mathematics underneath.
///
/// A prose account of the splitting of a spectral function into discrete, regular and
/// singular parts, of what [`SpectralFunction::integrate()`] does with it, and of how
/// [`SpectralFunction::conv()`] derives the singular structure of a convolution.
#[doc = include_str!("../doc/theory.md")]
pub mod theory {}

/// Continuous spectral function possibly containing integrable singularities.
///
/// It has the form $A(\omega) = R(\omega) + \sum_p S_p(\omega)$ for
/// $\omega \in [\omega_{min}, \omega_{max}]$ and zero otherwise, each $S_p(\omega)$
/// having one isolated integrable singularity at $\Omega_p$.
///
/// $S_p(\omega)$ is described in closed form by the corresponding [`Singularity`],
/// which fixes it over the whole support and not merely near $\Omega_p$. A support
/// with singularities must be bounded.
///
/// # Example
///
/// A band rising as $\frac{3}{2}\sqrt{\omega-\epsilon}$ out of its lower edge and cut
/// off a unit of frequency above it.
///
/// ```
/// use vanhove::segment::Segment;
/// use vanhove::singularity::{AsymptTerm, Singularity};
/// use vanhove::{ContinuousSF, SpectralFunction};
///
/// struct SqrtBand {
///     support: Segment,
///     edge: [Singularity; 1],
/// }
///
/// impl SqrtBand {
///     fn new(eps: f64) -> SqrtBand {
///         let terms = vec![AsymptTerm::power(0.5, 1.5)];
///         SqrtBand {
///             support: Segment::new(eps, eps + 1.0),
///             edge: [Singularity::new(eps, 1.0, terms)],
///         }
///     }
/// }
///
/// impl ContinuousSF for SqrtBand {
///     fn support(&self) -> Segment {
///         self.support
///     }
///     // The whole of A(ω) is the singular part, so nothing is left over
///     fn regular(&self, _omega: f64) -> f64 {
///         0.0
///     }
///     fn singularities(&self) -> &[Singularity] {
///         &self.edge
///     }
///     fn shifted(&self, by: f64) -> Box<dyn ContinuousSF> {
///         Box::new(SqrtBand {
///             support: self.support.shifted(by),
///             edge: [self.edge[0].shifted(by)],
///         })
///     }
///     fn mirrored(&self, omega: f64) -> Box<dyn ContinuousSF> {
///         Box::new(SqrtBand {
///             support: self.support.mirrored(omega),
///             edge: [self.edge[0].mirrored(omega)],
///         })
///     }
/// }
///
/// let dos = SpectralFunction::from_continuous(SqrtBand::new(0.0));
///
/// // The band is normalized, and its first moment is 3/5
/// assert!((dos.integrate(|_| 1.0, None).unwrap().value - 1.0).abs() < 1e-12);
/// assert!((dos.integrate(|omega| omega, None).unwrap().value - 0.6).abs() < 1e-12);
///
/// // Reflected about the origin, it falls into an upper edge at 0 instead
/// let image = dos.mirrored(0.0);
/// assert!((image.integrate(|omega| omega, None).unwrap().value + 0.6).abs() < 1e-12);
///
/// // It convolves like any model of the crate's own, the singular structure of the
/// // result derived from the band edge it was given
/// let twice = dos.conv(&dos, None);
/// assert!((twice.integrate(|_| 1.0, None).unwrap().value - 1.0).abs() < 1e-9);
/// assert!((twice.integrate(|omega| omega, None).unwrap().value - 1.2).abs() < 1e-9);
/// assert_eq!(twice.support().unwrap(), Segment::new(0.0, 2.0));
/// ```
pub trait ContinuousSF: Send + Sync {
    /// Support of the spectral function.
    fn support(&self) -> Segment;
    /// Regular part, $R(\omega) = A(\omega) - \sum_p S_p(\omega)$, at an `omega` within
    /// [`support()`](ContinuousSF::support), where it must be a finite number.
    ///
    /// Smooth between consecutive singular points, which is where it is integrated
    /// and interpolated. How smooth is a matter of how many terms each $S_p$ has,
    /// one more of them buying one more derivative.
    fn regular(&self, omega: f64) -> f64;
    /// Singular points $\Omega_p$ along with the closed form of $S_p$ at each.
    ///
    /// Every frequency where $R(\omega)$ stops being smooth belongs here, whether or
    /// not $A(\omega)$ diverges at it.
    fn singularities(&self) -> &[Singularity] {
        &[]
    }
    /// The same spectral function displaced in frequency by `by`.
    fn shifted(&self, by: f64) -> Box<dyn ContinuousSF>;
    /// The image of the spectral function under the reflection $\nu \mapsto \omega - \nu$,
    /// $A(\omega - \nu)$ as a function of $\nu$.
    fn mirrored(&self, omega: f64) -> Box<dyn ContinuousSF>;
}

/// Spectral function as a weighted sum of discrete resonances and continuous
/// contributions.
///
/// Weights may be negative, so that $A(\omega)$ is not assumed to be sign-definite.
#[derive(Clone)]
pub struct SpectralFunction {
    // Contributions of discrete resonances.
    discrete: DiscreteSF,
    // Continuous contributions with their weights.
    // Invariant: all weights are non-zero and no two entries share a contribution.
    continuous: Vec<(Arc<dyn ContinuousSF>, f64)>,
}

/// Integral computed by quadrature, with an estimate of its absolute error.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct Integral<T> {
    /// Value of the integral.
    pub value: T,
    /// Estimated absolute error of `value`. A complex integral has the errors of its real
    /// and imaginary parts estimated separately.
    pub error_estimate: T,
    /// Whether every quadrature the integral is made of has reached the requested
    /// tolerance.
    pub converged: bool,
}

impl Integral<f64> {
    /// An integral known exactly.
    pub(crate) fn exact(value: f64) -> Integral<f64> {
        Integral {
            value,
            error_estimate: 0.0,
            converged: true,
        }
    }

    /// What bilby reports for one quadrature.
    pub(crate) fn from_quadrature(result: QuadratureResult<f64>) -> Integral<f64> {
        Integral {
            value: result.value,
            error_estimate: result.error_estimate,
            converged: result.converged,
        }
    }

    /// Add `other` scaled by `weight`.
    pub(crate) fn add_scaled(&mut self, other: &Integral<f64>, weight: f64) {
        self.value += weight * other.value;
        self.error_estimate += weight.abs() * other.error_estimate;
        self.converged &= other.converged;
    }
}

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

    fn mul(self, a: f64) -> Self {
        // A weight can vanish upon scaling, either exactly for a == 0 or by underflow.
        // Such contributions are dropped by `from_discrete_continuous()`.
        Self::from_discrete_continuous(
            self.discrete * a,
            self.continuous
                .into_iter()
                .map(|(cd, w)| (cd, w * a))
                .collect(),
        )
    }
}
/// Multiply spectral function by a real number from the left.
impl Mul<SpectralFunction> for f64 {
    type Output = SpectralFunction;
    fn mul(self, sf: SpectralFunction) -> SpectralFunction {
        sf * self
    }
}
/// Negation of a spectral function.
impl Neg for SpectralFunction {
    type Output = Self;
    fn neg(self) -> SpectralFunction {
        self * (-1.0)
    }
}
/// Addition of two spectral functions.
impl Add for SpectralFunction {
    type Output = Self;
    fn add(self, rhs: SpectralFunction) -> SpectralFunction {
        // Concatenation can repeat a contribution the operands have in common, which
        // `from_discrete_continuous()` merges back into a single weight.
        let mut continuous = self.continuous;
        continuous.extend(rhs.continuous);
        SpectralFunction::from_discrete_continuous(self.discrete + rhs.discrete, continuous)
    }
}
/// Subtraction of two spectral functions.
impl Sub for SpectralFunction {
    type Output = Self;
    fn sub(self, rhs: SpectralFunction) -> SpectralFunction {
        self + (-rhs)
    }
}
/// Continuous contributions of the convolution of `discrete` with `continuous`.
fn conv_discrete_continuous(
    discrete: &DiscreteSF,
    continuous: &[(Arc<dyn ContinuousSF>, f64)],
) -> Vec<(Arc<dyn ContinuousSF>, f64)> {
    let mut contributions = Vec::with_capacity(discrete.len() * continuous.len());
    // A resonance displaces every band to its position and scales it by its weight
    for (csf, w) in continuous {
        for res in discrete.iter() {
            contributions.push((Arc::from(csf.shifted(res.eps)), w * res.weight));
        }
    }
    contributions
}

impl SpectralFunction {
    /// Build a `SpectralFunction` from a discrete spectral function and a list of
    /// continuous contributions with their weights.
    ///
    /// Repeated contributions are merged by summing their weights, keeping the order
    /// of first appearance. A contribution is dropped once its total weight is small
    /// enough against the total magnitude of the weights to be a cancellation
    /// artefact, by the same relative tolerance that governs the discrete weights.
    ///
    /// Two contributions count as one only when they share an allocation, so that
    /// separately built models of identical parameters stay apart.
    fn from_discrete_continuous(
        discrete: DiscreteSF,
        continuous: Vec<(Arc<dyn ContinuousSF>, f64)>,
    ) -> SpectralFunction {
        // Contributions grouped by identity: (contribution, ∑ w, ∑ |w|)
        let mut merged: Vec<(Arc<dyn ContinuousSF>, f64, f64)> =
            Vec::with_capacity(continuous.len());
        for (cd, w) in continuous {
            match merged
                .iter_mut()
                .find(|(other, _, _)| Arc::ptr_eq(other, &cd))
            {
                Some((_, sum, magnitude)) => {
                    *sum += w;
                    *magnitude += w.abs();
                }
                None => merged.push((cd, w, w.abs())),
            }
        }
        SpectralFunction {
            discrete,
            continuous: merged
                .into_iter()
                .filter(|(_, sum, magnitude)| sum.abs() > DiscreteSF::WEIGHT_TOL * magnitude)
                .map(|(cd, sum, _)| (cd, sum))
                .collect(),
        }
    }

    /// Build a `SpectralFunction` out of a single continuous contribution of unit weight.
    pub fn from_continuous<C: ContinuousSF + 'static>(continuous: C) -> SpectralFunction {
        SpectralFunction::from_discrete_continuous(
            DiscreteSF::new(),
            vec![(Arc::new(continuous), 1.0)],
        )
    }

    /// Discrete part of the spectral function.
    pub fn discrete(&self) -> &DiscreteSF {
        &self.discrete
    }

    /// Continuous contributions with their weights.
    ///
    /// A contribution added more than once is listed once, with its weights summed.
    /// Only additions of the same instance of [`ContinuousSF`] count as repeats, so
    /// separately built models of identical parameters are listed apart.
    pub fn continuous(&self) -> impl Iterator<Item = (&dyn ContinuousSF, f64)> {
        self.continuous.iter().map(|(csf, w)| (csf.as_ref(), *w))
    }

    /// Support of the spectral function.
    ///
    /// It is the smallest segment $[\omega_{min}, \omega_{max}]$ containing the supports
    /// of all contributions. The segment is not necessarily tight: the spectral function
    /// may vanish within the gaps between disjoint contributions. Returns [`None`] for an
    /// empty spectral function.
    pub fn support(&self) -> Option<Segment> {
        Segment::hull(
            self.continuous
                .iter()
                .map(|(cd, _)| cd.support())
                .chain(self.discrete.support()),
        )
    }

    /// The same spectral function displaced in frequency by `by`.
    pub fn shifted(&self, by: f64) -> SpectralFunction {
        let mut continuous = Vec::with_capacity(self.continuous.len());
        for (csf, w) in &self.continuous {
            continuous.push((Arc::from(csf.shifted(by)), *w));
        }
        SpectralFunction::from_discrete_continuous(self.discrete.shifted(by), continuous)
    }

    /// The image of the spectral function under the reflection $\nu \mapsto \omega - \nu$,
    /// $A(\omega - \nu)$ as a function of $\nu$.
    pub fn mirrored(&self, omega: f64) -> SpectralFunction {
        let mut continuous = Vec::with_capacity(self.continuous.len());
        for (csf, w) in &self.continuous {
            continuous.push((Arc::from(csf.mirrored(omega)), *w));
        }
        SpectralFunction::from_discrete_continuous(self.discrete.mirrored(omega), continuous)
    }

    /// Replace the regular part of every continuous contribution with a Chebyshev
    /// interpolation of it.
    ///
    /// The singular parts are kept exactly, so the result departs from the
    /// original in $R(\omega)$ alone, and only within the relative tolerance `tol` of
    /// the fit. It pays for itself when one spectral function is integrated many times
    /// over and its regular part is expensive, as for the lattice models built on an
    /// elliptic integral.
    ///
    /// Contributions of unbounded support are left as they are, there being no
    /// interval to expand them over.
    pub fn precomputed(&self, tol: Option<f64>) -> SpectralFunction {
        let continuous = self
            .continuous
            .iter()
            .map(|(csf, w)| {
                if csf.support().is_bounded() {
                    let interpolated = InterpolatedSF::new(csf.as_ref(), tol);
                    (Arc::new(interpolated) as Arc<dyn ContinuousSF>, *w)
                } else {
                    (Arc::clone(csf), *w)
                }
            })
            .collect();
        SpectralFunction::from_discrete_continuous(self.discrete.clone(), continuous)
    }

    /// Convolution with another spectral function,
    /// $\int A(\nu) B(\omega - \nu) d\nu$.
    ///
    /// The singular structure of the result is derived: its van Hove points are
    /// the pairwise sums of the frequencies where either operand stops being smooth.
    /// The asymptotics at each singular point follows from the asymptotic forms of
    /// $A$ and $B$. The regular part of the result is interpolated to the relative
    /// tolerance `tol`, which defaults to $10^{-12}$.
    ///
    /// Panics if both operands have continuous parts and any of them has an unbounded
    /// support. A discrete part convolves with a continuous part of any support.
    pub fn conv(&self, other: &SpectralFunction, tol: Option<f64>) -> SpectralFunction {
        // $A \ast B$ splits four ways across the discrete and continuous parts of the
        // two operands. These are the two cross terms: a resonance of one operand
        // displaces the whole continuous part of the other to its position and scales
        // it by its weight.
        let mut continuous = conv_discrete_continuous(&self.discrete, &other.continuous);
        continuous.extend(conv_discrete_continuous(&other.discrete, &self.continuous));

        // The third term, continuous against continuous, taken one pair at a time. Such
        // a convolution is a continuous contribution in its own right, so each pair
        // becomes one interpolated contribution, and $w_1 w_2$ stays its weight rather
        // than being scaled into the interpolant.
        let tol = tol.unwrap_or(InterpolatedSF::DEFAULT_TOL);
        for (c1, w1) in &self.continuous {
            for (c2, w2) in &other.continuous {
                let (c1, c2) = (c1.as_ref(), c2.as_ref());
                let support = conv::pair_support(c1, c2);
                let singularities = conv::pair_singularities(c1, c2);
                // Subtracting the derived structure from the pair's value leaves a
                // remainder smooth enough to fit. `from_parts()` puts the same
                // structure back, so whatever the derived terms come to away from
                // their own singular point cancels and never has to be right.
                let regular = |omega: f64| {
                    let singular: f64 = singularities.iter().map(|s| s.value(omega)).sum();
                    conv::pair_value(c1, c2, omega, tol) - singular
                };
                let interpolated =
                    InterpolatedSF::from_parts(support, singularities.clone(), regular, Some(tol));
                continuous.push((Arc::new(interpolated) as Arc<dyn ContinuousSF>, w1 * w2));
            }
        }

        // The fourth term is discrete against discrete, which is exact and needs no
        // interpolation
        SpectralFunction::from_discrete_continuous(self.discrete.conv(&other.discrete), continuous)
    }

    /// Total spectral weight.
    pub fn total_weight(&self) -> f64 {
        self.discrete.total_weight() + self.continuous.iter().map(|(_, w)| w).sum::<f64>()
    }

    /// Value of the continuous part of the spectral function at a frequency `omega`.
    ///
    /// Returns $\pm\infty$ where the spectral function diverges, and zero outside of
    /// the support of every continuous contribution.
    ///
    /// The discrete resonances are left out, a $\delta$-function having no value at a
    /// point. Use [`SpectralFunction::discrete()`] to inspect them.
    pub fn continuous_at(&self, omega: f64) -> f64 {
        // Divergent terms encountered at omega, grouped by strength:
        // (strength, ∑ w c, ∑ |w c|).
        let mut divergent: Vec<(Strength, f64, f64)> = Vec::new();
        // Everything that stays finite at omega
        let mut finite = 0.0f64;

        for (csf, w) in &self.continuous {
            // R(ω) is not defined outside of the support
            if !csf.support().contains(omega) {
                continue;
            }

            let mut value = csf.regular(omega);
            for sing in csf.singularities() {
                // Away from Ω_p the asymptotics is finite and needs no analysis
                if sing.position() != omega {
                    value += sing.value(omega);
                    continue;
                }
                value += sing.finite_limit();
                for (strength, c) in sing.divergences() {
                    let coeff = w * c;
                    match divergent.iter_mut().find(|(s, _, _)| *s == strength) {
                        Some((_, sum, magnitude)) => {
                            *sum += coeff;
                            *magnitude += coeff.abs();
                        }
                        None => divergent.push((strength, coeff, coeff.abs())),
                    }
                }
            }
            finite += w * value;
        }

        // The strongest divergence whose coefficients do not cancel fixes the value. The
        // same relative tolerance decides a cancellation here as for the discrete weights.
        match divergent
            .iter()
            .filter(|(_, sum, magnitude)| sum.abs() > DiscreteSF::WEIGHT_TOL * magnitude)
            .max_by(|x, y| x.0.order(&y.0))
        {
            Some((_, sum, _)) => sum.signum() * f64::INFINITY,
            // Every divergence has cancelled, leaving the finite limits behind
            None => finite,
        }
    }

    //
    // Spectral function integration
    //

    /// Integrate the spectral function $A(\omega)$ against a real-valued function
    /// $f(\omega)$.
    ///
    /// The integral $\int A(\omega)f(\omega)d\omega$ is assembled from several
    /// quadratures, each computed to the absolute tolerance `tol`, which defaults to
    /// $10^{-10}$. [`Integral::converged`] tells whether all of them have reached it.
    ///
    /// `f` must be finite everywhere on [`SpectralFunction::support()`]. The tolerance is
    /// otherwise reached only as far as `f` is smooth: a jump at a frequency where
    /// $A(\omega)$ diverges puts it out of reach.
    pub fn integrate<F: Fn(f64) -> f64>(
        &self,
        f: F,
        tol: Option<f64>,
    ) -> Result<Integral<f64>, QuadratureError> {
        // Discrete spectral contributions
        let mut discrete = 0.0f64;
        for r in self.discrete.iter() {
            discrete += r.weight * f(r.eps);
        }
        let mut result = Integral::exact(discrete);

        // Continuous spectral contributions
        // ∫A(ω)f(ω)dω = ∫R(ω)f(ω)dω + ∑_p ∫S_p(ω)[f(ω) - f(Ω_p)]dω + ∑_p f(Ω_p) ∫S_p(ω)dω
        let tol = tol.unwrap_or(1e-10);
        for (csf, w) in &self.continuous {
            let support = csf.support();

            // Integrate the regular part, ∫R(ω)f(ω)dω
            let mut res_contrib = Integral::from_quadrature(util::bilby_integrate(
                |omega| csf.regular(omega) * f(omega),
                support,
                tol,
            )?);

            // Add integrals of the asymptotics
            for sing in csf.singularities() {
                if sing.is_trivial() {
                    continue;
                }
                // ∫S_p(ω)[f(ω) - f(Ω_p)]dω + f(Ω_p)∫S_p(ω)dω
                let asympt = util::integrate_by_subtraction(
                    sing.position(),
                    |omega| sing.value(omega),
                    |stretch| sing.integral(stretch),
                    &f,
                    support,
                    tol,
                )?;
                res_contrib.add_scaled(&asympt, 1.0);
            }

            result.add_scaled(&res_contrib, *w);
        }
        Ok(result)
    }

    /// Integrate the spectral function $A(\omega)$ against a complex-valued function
    /// $f(\omega)$.
    ///
    /// The real and imaginary parts of $\int A(\omega)f(\omega)d\omega$ are computed
    /// separately, each to the absolute tolerance `tol` and under the conditions
    /// [`SpectralFunction::integrate()`] places on a real-valued integrand. The real and
    /// imaginary parts of [`Integral::error_estimate`] belong to the respective parts of
    /// the integral, and [`Integral::converged`] holds only if both parts have converged.
    pub fn integrate_complex<F: Fn(f64) -> Complex64>(
        &self,
        f: F,
        tol: Option<f64>,
    ) -> Result<Integral<Complex64>, QuadratureError> {
        let re = self.integrate(|omega| f(omega).re, tol)?;
        let im = self.integrate(|omega| f(omega).im, tol)?;
        Ok(Integral {
            value: Complex64::new(re.value, im.value),
            error_estimate: Complex64::new(re.error_estimate, im.error_estimate),
            converged: re.converged && im.converged,
        })
    }

    /// Value of the broadened spectral function at a frequency `omega`.
    ///
    /// The broadening is a convolution with the Lorentzian line shape function of the
    /// half-width at half-maximum `delta`,
    /// $$
    ///     \int \frac{1}{\pi} \frac{\delta}{\delta^2 + (\omega-\omega')^2}
    ///         A(\omega') d\omega'.
    /// $$
    /// The discrete part contributes a Lorentzian per resonance, so that the
    /// broadened spectral function is smooth in `omega` for any $\delta > 0$.
    ///
    /// The line shape function is sharply peaked for small `delta`, and its integral
    /// is of the order $1/(\pi\delta)$. It may, therefore, be necessary to relax the
    /// absolute quadrature tolerance `tol` from its default value of $10^{-10}$.
    pub fn broadened(
        &self,
        omega: f64,
        delta: f64,
        tol: Option<f64>,
    ) -> Result<Integral<f64>, QuadratureError> {
        assert!(delta > 0.0, "broadening must be positive");
        let (weight, delta_sq) = (delta / PI, delta.powi(2));
        let f = |omega_prime: f64| -> f64 { weight / (delta_sq + (omega_prime - omega).powi(2)) };
        self.integrate(f, tol)
    }
}

#[cfg(test)]
mod tests {
    use crate::SpectralFunction;
    use crate::models::*;
    use crate::segment::Segment;
    use crate::util;
    use approx::{assert_abs_diff_eq, assert_relative_eq};
    use num_complex::Complex64;
    use std::f64::consts::PI;

    #[test]
    fn send_sync() {
        // Spectral functions cross thread boundaries, so that frequency scans can be
        // run in parallel. `ContinuousSF` requires as much of every model.
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<SpectralFunction>();
    }

    #[test]
    fn total_weight() {
        let dos = 2.0 * discrete(&[-0.7, 1.2], &[0.25, 0.6]) + 5.0 * gaussian(1.4, 0.5);
        assert_relative_eq!(dos.total_weight(), 6.7, epsilon = 1e-12);
    }

    #[test]
    fn discrete_part() {
        let dos = 2.0 * discrete(&[-0.7, 1.2], &[0.25, 0.6]) + 5.0 * gaussian(1.4, 0.5);
        let d = dos.discrete();
        assert_eq!(d.len(), 2);
        assert_relative_eq!(d.total_weight(), 1.7, epsilon = 1e-12);
        assert_relative_eq!(d.find(1.2).unwrap().weight, 1.2, epsilon = 1e-12);

        // Continuous contributions leave no trace in the discrete part
        assert!(d.find(1.4).is_none());
        assert!(gaussian(1.4, 0.5).discrete().is_empty());
    }

    #[test]
    fn continuous_part() {
        let band = chain(0.5, 1.0);
        let dos = 2.0 * discrete(&[-0.7, 1.2], &[0.25, 0.6])
            + 5.0 * gaussian(1.4, 0.5)
            + band.clone()
            + 0.5 * band.clone();

        // A repeated contribution is listed once, with the weights summed
        let parts: Vec<_> = dos.continuous().collect();
        assert_eq!(parts.len(), 2);
        assert_eq!(parts[0].1, 5.0);
        assert_eq!(parts[1].1, 1.5);
        assert_eq!(
            parts[0].0.support(),
            Segment::new(f64::NEG_INFINITY, f64::INFINITY)
        );
        assert_eq!(parts[1].0.support(), Segment::new(-1.5, 2.5));

        // Discrete resonances leave no trace in the continuous part
        assert_eq!(discrete(&[-0.7], &[1.0]).continuous().count(), 0);
    }

    #[test]
    fn support() {
        // An empty spectral function has no support
        assert_eq!(discrete(&[], &[]).support(), None);
        assert_eq!((gaussian(1.4, 0.5) * 0.0).support(), None);

        // Discrete contributions alone: positions of the outermost resonances
        assert_eq!(
            discrete(&[-0.7, 1.2, 0.3], &[0.25, 0.6, 0.15]).support(),
            Some(Segment::new(-0.7, 1.2))
        );

        // A single continuous contribution: its band edges
        assert_eq!(chain(0.5, 1.0).support(), Some(Segment::new(-1.5, 2.5)));

        // Mixed contributions: the hull of all supports. Neither the resonance at 0.0
        // nor the narrower square lattice band widens the chain band, the resonance
        // at 5.0 does.
        let dos = discrete(&[0.0, 5.0], &[0.3, 0.3]) + chain(0.5, 1.0) + square(0.0, 0.25);
        assert_eq!(dos.support(), Some(Segment::new(-1.5, 5.0)));

        // An unbounded contribution makes the whole support unbounded
        let dos = discrete(&[-0.7], &[0.5]) + gaussian(1.4, 0.5);
        assert_eq!(
            dos.support(),
            Some(Segment::new(f64::NEG_INFINITY, f64::INFINITY))
        );
    }

    #[test]
    fn continuous_at() {
        // Away from the singularities the value is that of A(ω) itself
        let (eps, t) = (0.5f64, 1.0f64);
        let dos = chain(eps, t);
        for omega in [-1.0, 0.0, 0.8, 2.0] {
            let ref_value = 1.0 / (PI * ((2.0 * t).powi(2) - (omega - eps).powi(2)).sqrt());
            assert_relative_eq!(dos.continuous_at(omega), ref_value, max_relative = 1e-12);
        }

        // Outside of the support of every contribution
        assert_eq!(dos.continuous_at(10.0), 0.0);

        // Divergent singular points
        assert_eq!(dos.continuous_at(eps - 2.0 * t), f64::INFINITY);
        assert_eq!(dos.continuous_at(eps + 2.0 * t), f64::INFINITY);
        assert_eq!(square(eps, t).continuous_at(eps), f64::INFINITY);
        assert_eq!(
            (-1.0 * square(eps, t)).continuous_at(eps),
            f64::NEG_INFINITY
        );

        // A square-root band edge is a singular point where A(ω) stays finite
        assert_eq!(semicircle(eps, 2.0).continuous_at(eps - 2.0), 0.0);

        // Discrete resonances contribute nothing
        assert_eq!(discrete(&[-0.7, 1.2], &[0.25, 0.6]).continuous_at(1.2), 0.0);
    }

    #[test]
    fn continuous_at_cancelling_divergences() {
        // Two logarithmic singularities meet at ω = 0, and the weights are chosen to
        // cancel their coefficients c = 1/(2π^2 t) exactly. What is left of A(ω) there is
        // the difference of the scales the two logarithms are written with,
        // ln(16t_1)/(2π^2 t_1) - 2ln(16t_2)/(2π^2 t_2) = -ln(2)/(2π^2).
        let dos = square(0.0, 1.0) + (-2.0) * square(0.0, 2.0);
        assert_relative_eq!(
            dos.continuous_at(0.0),
            -2f64.ln() / (2.0 * PI.powi(2)),
            max_relative = 1e-12
        );

        // A power law outranks a logarithm: the chain band edge wins over the
        // logarithmic peak of the square lattice, both sitting at ω = 0.
        let dos = square(0.0, 1.0) + (-1.0) * chain(2.0, 1.0);
        assert_eq!(dos.continuous_at(0.0), f64::NEG_INFINITY);
    }

    #[test]
    fn continuous_at_cancelling_across_scales() {
        // Two |ω|^(-1/2) edges at the origin, one of unit width and one four times as wide.
        let (narrow, wide) = (powerlaw(0.0, -0.5, 1.0), powerlaw(0.0, -0.5, 4.0));

        // The true coefficients stand as 2 : 1, so this pair cancels and the divergence
        // is gone - not merely outweighed
        let cancelling = narrow.clone() + (-2.0) * wide.clone();
        assert!(cancelling.continuous_at(0.0).is_finite());
        for omega in [1e-6f64, 1e-10] {
            assert_abs_diff_eq!(cancelling.continuous_at(omega), 0.0, epsilon = 1e-12);
        }

        // Equal and opposite coefficients as stored do not cancel, the two being
        // written against different distances, and what is left of them diverges
        let surviving = narrow + (-1.0) * wide;
        assert_eq!(surviving.continuous_at(0.0), f64::INFINITY);
        assert!(surviving.continuous_at(1e-10) > 1e4);
    }

    #[test]
    fn mul() {
        let dos = 2.0 * discrete(&[-0.7, 1.2], &[0.25, 0.6]) + 5.0 * gaussian(1.4, 0.5);
        assert_eq!(dos.discrete.len(), 2);
        assert_eq!(dos.continuous.len(), 1);

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

        // Scaling by zero empties the spectral function
        let scaled = dos * 0.0;
        assert!(scaled.discrete.is_empty());
        assert!(scaled.continuous.is_empty());
        assert_eq!(scaled.total_weight(), 0.0);
    }

    #[test]
    fn add_merges_repeated_contributions() {
        let dos = chain(0.5, 1.0);
        let omega = 0.8;

        // A contribution repeated by addition is listed once, with the weights summed
        let tripled = dos.clone() + dos.clone() + dos.clone();
        assert_eq!(tripled.continuous.len(), 1);
        assert_relative_eq!(tripled.total_weight(), 3.0, epsilon = 1e-12);
        assert_relative_eq!(
            tripled.continuous_at(omega),
            3.0 * dos.continuous_at(omega),
            max_relative = 1e-12
        );

        // Weights cancelling each other out drop the contribution altogether
        let zero = 2.0 * dos.clone() - 2.0 * dos.clone();
        assert!(zero.continuous.is_empty());
        assert_eq!(zero.continuous_at(omega), 0.0);

        // Contributions are told apart by their allocation rather than by their
        // parameters, so separately built models of the same band stay apart
        let pair = chain(0.5, 1.0) + chain(0.5, 1.0);
        assert_eq!(pair.continuous.len(), 2);
        assert_relative_eq!(
            pair.continuous_at(omega),
            2.0 * dos.continuous_at(omega),
            max_relative = 1e-12
        );

        // Merging keeps the order of first appearance
        let mixed = dos.clone() + square(0.0, 1.0) + dos.clone();
        assert_eq!(mixed.continuous.len(), 2);
        assert_eq!(mixed.continuous[0].1, 2.0);
        assert_eq!(mixed.continuous[1].1, 1.0);
    }

    #[test]
    fn neg() {
        let dos = 2.0 * discrete(&[-0.7, 1.2], &[0.25, 0.6]) + 5.0 * gaussian(1.4, 0.5);
        let neg_dos = -dos.clone();

        // Negation flips the sign of every weight while preserving the structure
        assert_eq!(neg_dos.discrete.len(), 2);
        assert_eq!(neg_dos.continuous.len(), 1);
        assert_eq!(neg_dos.support(), dos.support());
        assert_relative_eq!(neg_dos.total_weight(), -dos.total_weight(), epsilon = 1e-12);
        assert_relative_eq!(
            neg_dos.discrete().find(1.2).unwrap().weight,
            -1.2,
            epsilon = 1e-12
        );
        for omega in [-1.0, 0.5, 1.4, 3.0] {
            assert_relative_eq!(
                neg_dos.continuous_at(omega),
                -dos.continuous_at(omega),
                max_relative = 1e-12
            );
        }

        // A divergence changes sign along with the spectral function
        let (eps, t) = (0.5f64, 1.0f64);
        assert_eq!((-square(eps, t)).continuous_at(eps), f64::NEG_INFINITY);

        // Negating twice is the identity
        let dos2 = -(-dos.clone());
        assert_relative_eq!(dos2.total_weight(), dos.total_weight(), epsilon = 1e-12);
        assert_relative_eq!(
            dos2.continuous_at(0.5),
            dos.continuous_at(0.5),
            epsilon = 1e-12
        );

        // A spectral function and its negation cancel each other out
        let zero = dos.clone() + (-dos);
        assert!(zero.discrete.is_empty());
        assert!(zero.continuous.is_empty());
        assert_relative_eq!(zero.total_weight(), 0.0, epsilon = 1e-12);
        assert_eq!(zero.continuous_at(1.4), 0.0);
    }

    #[test]
    fn sub() {
        let dos = 2.0 * discrete(&[-0.7, 1.2], &[0.25, 0.6]) + 5.0 * gaussian(1.4, 0.5);
        let rhs = discrete(&[1.2], &[1.0]) + 2.0 * gaussian(1.4, 0.5);
        let diff = dos.clone() - rhs.clone();

        // Subtraction acts on the discrete and the continuous parts alike
        assert_eq!(diff.discrete.len(), 2);
        assert_relative_eq!(
            diff.discrete().find(1.2).unwrap().weight,
            0.2,
            epsilon = 1e-12
        );
        assert_relative_eq!(
            diff.total_weight(),
            dos.total_weight() - rhs.total_weight(),
            epsilon = 1e-12
        );
        for omega in [-1.0, 0.5, 1.4, 3.0] {
            assert_relative_eq!(
                diff.continuous_at(omega),
                dos.continuous_at(omega) - rhs.continuous_at(omega),
                max_relative = 1e-12
            );
        }

        // Subtraction agrees with adding the negation
        let diff2 = dos.clone() + (-rhs);
        assert_relative_eq!(diff2.total_weight(), diff.total_weight(), epsilon = 1e-12);
        assert_relative_eq!(
            diff2.continuous_at(0.5),
            diff.continuous_at(0.5),
            max_relative = 1e-12
        );

        // A spectral function subtracted from itself cancels out
        let zero = dos.clone() - dos;
        assert!(zero.discrete.is_empty());
        assert_relative_eq!(zero.total_weight(), 0.0, epsilon = 1e-12);
        assert_eq!(zero.continuous_at(1.4), 0.0);
    }

    #[test]
    fn precomputed() {
        let dos = square(0.0, 1.0);
        let fast = dos.precomputed(None);

        assert_eq!(fast.support(), dos.support());
        assert_relative_eq!(fast.total_weight(), dos.total_weight(), epsilon = 1e-14);

        // The singular part is kept as it stands, divergence included
        assert_eq!(fast.continuous_at(0.0), f64::INFINITY);

        // Away from the singular point the expansion stands in for A(ω)
        for omega in [-3.5, -1.2, 0.3, 2.0, 3.9] {
            assert_relative_eq!(
                fast.continuous_at(omega),
                dos.continuous_at(omega),
                max_relative = 1e-10
            );
        }

        // Moments of even order survive the substitution, the odd ones vanishing
        for order in [0, 2, 4] {
            assert_relative_eq!(
                fast.integrate(|omega| omega.powi(order), None)
                    .unwrap()
                    .value,
                dos.integrate(|omega| omega.powi(order), None)
                    .unwrap()
                    .value,
                max_relative = 1e-10
            );
        }

        // An unbounded contribution has no interval to expand over and is left alone
        let g = gaussian(1.4, 0.5);
        let fast_g = g.precomputed(None);
        for omega in [0.0, 1.4, 3.0] {
            assert_eq!(fast_g.continuous_at(omega), g.continuous_at(omega));
        }

        // The band centre breaks a panel, without which the kink there would cap the
        // fit five orders short
        for dos in [honeycomb(0.0, 1.0), lieb(0.0, 1.0)] {
            let fast = dos.precomputed(None);
            let support = dos.support().unwrap();
            let (mut worst, mut peak) = (0.0f64, 0.0f64);
            for i in 1..500 {
                let omega = support.min() + support.length() * (i as f64) / 500.0;
                let (a, b) = (dos.continuous_at(omega), fast.continuous_at(omega));
                if a.is_finite() && b.is_finite() {
                    worst = worst.max((b - a).abs());
                    peak = peak.max(a.abs());
                }
            }
            assert!(worst < 1e-7 * peak, "fit stalled at {:.2e}", worst / peak);
        }

        // The discrete part passes through untouched
        let mixed = 0.5 * square(0.0, 1.0) + 0.5 * discrete(&[3.0], &[1.0]);
        let fast_mixed = mixed.precomputed(None);
        assert_eq!(fast_mixed.discrete().len(), 1);
        assert_relative_eq!(fast_mixed.total_weight(), 1.0, epsilon = 1e-14);
    }

    #[test]
    fn conv_discrete_continuous() {
        // A unit resonance displaces a band to its position
        let shifted = discrete(&[1.5], &[1.0]).conv(&semicircle(0.0, 2.0), None);
        let reference = semicircle(1.5, 2.0);
        assert_eq!(shifted.support(), reference.support());
        for omega in [-0.5, 0.4, 1.5, 2.6, 3.5] {
            assert_relative_eq!(
                shifted.continuous_at(omega),
                reference.continuous_at(omega),
                max_relative = 1e-14
            );
        }

        // Singular points travel with the band
        let shifted = discrete(&[2.0], &[1.0]).conv(&square(0.0, 1.0), None);
        assert_eq!(shifted.continuous_at(2.0), f64::INFINITY);
        assert_eq!(shifted.support(), Some(Segment::new(-2.0, 6.0)));

        // Weight is multiplicative, and the operands need not be normalized
        let a = 0.5 * discrete(&[-1.0, 2.0], &[0.25, 0.75]);
        let b = 3.0 * chain(0.0, 1.0);
        let c = a.conv(&b, None);
        assert_relative_eq!(
            c.total_weight(),
            a.total_weight() * b.total_weight(),
            max_relative = 1e-14
        );

        // One band per resonance, each displaced to its own position
        assert_eq!(c.continuous.len(), 2);
        assert_eq!(c.support(), Some(Segment::new(-3.0, 4.0)));

        // Convolution commutes
        for omega in [-2.5, 0.0, 1.3, 3.5] {
            assert_relative_eq!(
                c.continuous_at(omega),
                b.conv(&a, None).continuous_at(omega),
                max_relative = 1e-14
            );
        }

        // Moments obey M_n = Σ_k C(n,k) M_k^A M_{n-k}^B
        let moment =
            |sf: &SpectralFunction, n: i32| sf.integrate(|w| w.powi(n), None).unwrap().value;
        for n in 0..=4usize {
            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, max_relative = 1e-9);
        }
    }

    #[test]
    fn conv_shifts_every_model() {
        // Displacing a contribution must move its support, regular part and
        // singular points alike
        let by = 1.25f64;
        let unit = discrete(&[by], &[1.0]);
        let models = [
            chain(0.5, 1.0),
            semicircle(0.5, 2.0),
            bethe(4, 0.5, 1.0),
            powerlaw(0.5, -0.5, 2.0),
            powerlaw(0.5, 2.5, 2.0),
            pseudogap(0.5, 0.5, 2.0),
            pseudogap(0.5, 2.5, 2.0),
            square(0.5, 1.0),
            triangular(0.5, 1.0),
            honeycomb(0.5, 1.0),
            lieb(0.5, 1.0),
            kagome(0.5, 1.0),
            gaussian(0.5, 1.0),
            flat(0.5, 2.0, 0.0),
            flat(0.5, 2.0, 0.3),
            square(0.5, 1.0).precomputed(None),
        ];
        for dos in models {
            let moved = unit.conv(&dos, None);
            let support = dos.support().unwrap();
            let (lo, hi) = (support.min().max(-20.0), support.max().min(20.0));
            for i in 0..=40 {
                let omega = lo + (hi - lo) * (i as f64) / 40.0;
                let (before, after) = (dos.continuous_at(omega), moved.continuous_at(omega + by));
                assert_relative_eq!(after, before, max_relative = 1e-12, epsilon = 1e-300);
            }
            assert_relative_eq!(
                moved.total_weight(),
                dos.total_weight(),
                max_relative = 1e-14
            );
        }
    }

    #[test]
    fn mirrored_every_model() {
        // Reflecting must carry the support, regular part and singular points over to
        // A(ω - ν), whichever side of a singular point each term was given for. The
        // reflection rounds, so a vanishing value is met to an absolute floor.
        let omega = 0.3f64;
        let models = [
            chain(0.5, 1.0),
            semicircle(0.5, 2.0),
            bethe(4, 0.5, 1.0),
            powerlaw(0.5, -0.5, 2.0),
            powerlaw(0.5, 2.5, 2.0),
            pseudogap(0.5, 0.5, 2.0),
            pseudogap(0.5, 2.5, 2.0),
            square(0.5, 1.0),
            triangular(0.5, 1.0),
            triangular(0.5, -1.0),
            honeycomb(0.5, 1.0),
            lieb(0.5, 1.0),
            kagome(0.5, 1.0),
            gaussian(0.5, 1.0),
            flat(0.5, 2.0, 0.0),
            flat(0.5, 2.0, 0.3),
            triangular(0.5, 1.0).precomputed(None),
            powerlaw(0.5, -0.5, 2.0).conv(&chain(0.0, 1.0), None),
            2.0 * discrete(&[-0.7, 1.2], &[0.25, 0.6]) + 5.0 * gaussian(1.4, 0.5),
        ];
        for dos in models {
            let image = dos.mirrored(omega);
            let support = dos.support().unwrap();
            assert_eq!(image.support().unwrap(), support.mirrored(omega));
            let (lo, hi) = (support.min().max(-20.0), support.max().min(20.0));
            // The ends are left out: where A(ω) steps there, its value at the step is
            // read from above, and the reflection turns a lower end into an upper one
            for i in 1..40 {
                let nu = lo + (hi - lo) * (i as f64) / 40.0;
                assert_relative_eq!(
                    image.continuous_at(omega - nu),
                    dos.continuous_at(nu),
                    max_relative = 1e-12,
                    epsilon = 1e-14
                );
            }
            for (csf, _) in image.continuous() {
                let positions: Vec<f64> =
                    csf.singularities().iter().map(|s| s.position()).collect();
                assert!(positions.is_sorted(), "singular points out of order");
            }

            // The zeroth moment stays and the first one turns about omega
            let moment = |sf: &SpectralFunction, n: i32| {
                sf.integrate(|w: f64| w.powi(n), None).unwrap().value
            };
            assert_relative_eq!(moment(&image, 0), moment(&dos, 0), max_relative = 1e-10);
            assert_relative_eq!(
                moment(&image, 1),
                omega * moment(&dos, 0) - moment(&dos, 1),
                max_relative = 1e-9,
                epsilon = 1e-10
            );

            // Reflecting twice about the same point is the identity
            let back = image.mirrored(omega);
            for i in 1..40 {
                let nu = lo + (hi - lo) * (i as f64) / 40.0;
                assert_relative_eq!(
                    back.continuous_at(nu),
                    dos.continuous_at(nu),
                    max_relative = 1e-12,
                    epsilon = 1e-14
                );
            }
        }
    }

    #[test]
    fn shifted_spectral_function() {
        let by = 0.7f64;
        let dos = 0.5 * discrete(&[-0.7, 1.2], &[0.25, 0.6]) + triangular(0.5, 1.0);
        let moved = dos.shifted(by);
        assert_eq!(moved.support().unwrap(), dos.support().unwrap().shifted(by));
        assert_relative_eq!(moved.discrete().resonances()[0].eps, -0.7 + by);
        for nu in [-4.0, -1.1, 0.2, 2.4, 3.3] {
            assert_relative_eq!(
                moved.continuous_at(nu + by),
                dos.continuous_at(nu),
                max_relative = 1e-12
            );
        }
    }

    #[test]
    fn conv_of_mirrored_is_mirrored_conv() {
        // A(ω_a - ν) ⊛ B(ω_b - ν) is (A ⊛ B)(ω_a + ω_b - ν). A power law edge reflected
        // to the top of its support sends conv() down the side it is otherwise never
        // asked for.
        let (a, b) = (powerlaw(0.0, -0.5, 1.0), triangular(0.0, 1.0));
        let (omega_a, omega_b) = (0.4, -0.1);
        let direct = a.conv(&b, None).mirrored(omega_a + omega_b);
        let reflected = a.mirrored(omega_a).conv(&b.mirrored(omega_b), None);
        let support = direct.support().unwrap();
        let (got, want) = (reflected.support().unwrap(), support);
        assert_relative_eq!(got.min(), want.min(), max_relative = 1e-15);
        assert_relative_eq!(got.max(), want.max(), max_relative = 1e-15);
        for i in 1..60 {
            let nu = support.min() + support.length() * (i as f64) / 60.0;
            assert_relative_eq!(
                reflected.continuous_at(nu),
                direct.continuous_at(nu),
                max_relative = 1e-8
            );
        }
    }

    #[test]
    fn conv_two_continuous() {
        // Two continuous parts convolve into one interpolated contribution holding
        // the whole spectral weight between them
        let c = chain(0.0, 1.0).conv(&square(0.0, 1.0), None);
        assert_relative_eq!(c.total_weight(), 1.0, max_relative = 1e-9);
        assert!(c.discrete().is_empty());
        assert_relative_eq!(
            c.integrate(|_| 1.0, None).unwrap().value,
            1.0,
            max_relative = 1e-9
        );
    }

    /// A linear chain against itself is the square lattice, the two dispersions being
    /// independent one-dimensional bands. Nothing in the library is told so.
    #[test]
    fn conv_of_two_chains_is_the_square_lattice() {
        let t = 1.3f64;
        let derived = chain(0.0, t).conv(&chain(0.0, t), None);
        let known = square(0.0, t);
        for i in 0..=120 {
            let omega = -3.99 * t + 7.98 * t * f64::from(i) / 120.0;
            let want = known.continuous_at(omega);
            if want.abs() < 1e-9 {
                continue;
            }
            assert_relative_eq!(derived.continuous_at(omega), want, max_relative = 1e-9);
        }
    }

    /// Moments of a convolution follow the binomial rule whatever the operands are.
    #[test]
    fn conv_moments_follow_the_binomial_rule() {
        let (a, b) = (chain(0.0, 1.0), semicircle(0.5, 2.0));
        let c = a.conv(&b, None);
        let moment = |sf: &SpectralFunction, n: i32| {
            sf.integrate(|omega: f64| omega.powi(n), None)
                .unwrap()
                .value
        };
        for n in 0..=4i32 {
            let c_row = util::binomials(n as usize);
            let want: f64 = (0..=n)
                .map(|k| c_row[k as usize] * moment(&a, k) * moment(&b, n - k))
                .sum();
            assert_relative_eq!(moment(&c, n), want, max_relative = 1e-8, epsilon = 1e-10);
        }
    }

    /// Both operands holding both discrete and continuous parts: all four ways of
    /// pairing them must be accounted for.
    #[test]
    fn conv_of_mixed_spectral_functions() {
        let a = 0.4 * discrete(&[-1.0, 0.5], &[0.3, 0.7]) + 0.6 * chain(0.0, 1.0);
        let b = 0.25 * discrete(&[2.0], &[1.0]) + 0.75 * flat(0.0, 1.0, 0.0);
        let c = a.conv(&b, None);

        // Weight is multiplicative, and each of the four pairings takes its share
        assert_relative_eq!(
            c.total_weight(),
            a.total_weight() * b.total_weight(),
            max_relative = 1e-9
        );
        assert_relative_eq!(
            c.integrate(|_| 1.0, None).unwrap().value,
            a.total_weight() * b.total_weight(),
            max_relative = 1e-8
        );

        // The first moment adds, weighted
        let mean = |sf: &SpectralFunction| sf.integrate(|w: f64| w, None).unwrap().value;
        assert_relative_eq!(
            mean(&c),
            mean(&a) * b.total_weight() + a.total_weight() * mean(&b),
            max_relative = 1e-8,
            epsilon = 1e-10
        );
    }

    /// Two boxes convolve into a triangle, and the result is fitted exactly
    /// although nothing of it is derived: a kink at a panel boundary is a polynomial
    /// either side of it.
    #[test]
    fn conv_of_two_boxes_is_a_triangle() {
        let d = 1.5f64;
        let c = flat(0.0, d, 0.0).conv(&flat(0.0, d, 0.0), None);
        for i in 0..=60 {
            let omega = -2.0 * d + 4.0 * d * f64::from(i) / 60.0;
            let want = (2.0 * d - omega.abs()).max(0.0) / (4.0 * d * d);
            assert_relative_eq!(c.continuous_at(omega), want, epsilon = 1e-12);
        }
    }

    #[test]
    fn broadened_discrete() {
        // A discrete spectral function is broadened into a sum of Lorentzians,
        // which serves as an analytic reference value.
        let levels = [-0.7f64, 1.2];
        let weights = [0.25f64, 0.6];
        let dos = 2.0 * discrete(&levels, &weights);

        for delta in [1e-1, 1e-2, 1e-4] {
            for omega in [-0.7, 0.0, 0.5, 1.2, 50.0] {
                let ref_value: f64 = 2.0
                    * levels
                        .iter()
                        .zip(&weights)
                        .map(|(eps, w)| w * (delta / PI) / (delta.powi(2) + (omega - eps).powi(2)))
                        .sum::<f64>();
                assert_relative_eq!(
                    dos.broadened(omega, delta, None).unwrap().value,
                    ref_value,
                    max_relative = 1e-10
                );
            }
        }
    }

    #[test]
    fn broadened_narrow_limit() {
        // As delta -> 0 the broadened spectral function approaches A(omega) itself.
        // The error of the Lorentzian broadening is linear in delta.
        let (eps, t, omega) = (0.5f64, 1.0f64, 0.8f64);
        let dos = chain(eps, t);
        let ref_value = 1.0 / (PI * ((2.0 * t).powi(2) - (omega - eps).powi(2)).sqrt());
        for delta in [1e-4, 1e-6] {
            assert_relative_eq!(
                dos.broadened(omega, delta, None).unwrap().value,
                ref_value,
                max_relative = 10.0 * delta
            );
        }
    }

    #[test]
    fn broadened_log_singularity() {
        // Broadening forces the quadrature to sample the spectral function arbitrarily
        // close to the logarithmic van Hove singularity of the square lattice. At the
        // band center the broadened spectral function diverges as -ln(delta)/(2π^2 t)
        // for delta -> 0.
        let t = 2.0f64;
        let dos = square(0.0, t);
        let mut prev = dos.broadened(0.0, 1e-2, None).unwrap().value;
        for delta in [1e-3, 1e-4, 1e-5, 1e-6] {
            let value = dos.broadened(0.0, delta, None).unwrap().value;
            assert_relative_eq!(
                value - prev,
                10f64.ln() / (2.0 * PI.powi(2) * t),
                max_relative = 1e-3
            );
            prev = value;
        }
    }

    #[test]
    fn broadened_mixed() {
        let dos = 2.0 * discrete(&[-0.7, 1.2], &[0.25, 0.6]) + 5.0 * gaussian(1.4, 0.5);
        assert_relative_eq!(
            dos.broadened(0.5, 1e-2, None).unwrap().value,
            // Reference value computed independently with mpmath (40 decimal digits).
            0.8138402146,
            epsilon = 1e-9
        );
    }

    #[test]
    #[should_panic(expected = "broadening must be positive")]
    fn broadened_zero_delta() {
        let _ = gaussian(1.4, 0.5).broadened(0.5, 0.0, None);
    }

    #[test]
    fn integral_reports_convergence() {
        // A discrete part is summed exactly
        let d = discrete(&[-0.7, 1.2], &[0.25, 0.6]).integrate(|w| w * w, None);
        let d = d.unwrap();
        assert_relative_eq!(d.value, 0.25 * 0.49 + 0.6 * 1.44, max_relative = 1e-15);
        assert_eq!(d.error_estimate, 0.0);
        assert!(d.converged);

        // A tolerance out of reach of f64 still yields a value, but not convergence
        let g = gaussian(1.4, 0.5);
        let reached = g.integrate(|_| 1.0, None).unwrap();
        let missed = g.integrate(|_| 1.0, Some(1e-30)).unwrap();
        assert!(reached.converged);
        assert!(!missed.converged);
        assert_relative_eq!(missed.value, 1.0, max_relative = 1e-12);

        // A request the quadrature cannot make sense of is an error
        assert!(g.integrate(|_| 1.0, Some(f64::NAN)).is_err());
    }

    #[test]
    fn complex_integral_reports_its_parts_apart() {
        // A rapidly oscillating imaginary part fails to converge, the real part does not
        let dos = flat(0.3, 1.0, 0.0);
        let integral = dos
            .integrate_complex(|w| Complex64::new(1.0, (1e5 * w * w).cos()), None)
            .unwrap();
        assert!(!integral.converged);
        assert_relative_eq!(integral.value.re, 1.0, max_relative = 1e-12);
        assert!(integral.error_estimate.re < 1e-10);
        assert!(integral.error_estimate.im > 1e-10);
    }
}