sparse-ir 0.10.0

Rust implementation of SparseIR functionality
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
//! Discrete Lehmann Representation (DLR)
//!
//! This module provides the Discrete Lehmann Representation (DLR) basis,
//! which represents Green's functions as a linear combination of poles on the
//! real-frequency axis.

use crate::error::{Error, require_finite, require_positive_finite};
use crate::fitters::RealMatrixFitter;
use crate::freq::MatsubaraFreq;
use crate::gemm::GemmBackendHandle;
use crate::taufuncs::normalize_tau;
use crate::traits::{Statistics, StatisticsType};
use mdarray::DTensor;
use num_complex::Complex;
use std::marker::PhantomData;

/// Generic single-pole Green's function at imaginary time τ
///
/// Computes G(τ) for either fermionic or bosonic statistics based on the type parameter S.
/// Both use G(τ) = -exp(-ω×τ) / (1 ± exp(-β×ω)) (+ for fermions, - for bosons),
/// the imaginary-time counterpart of [`giwn_single_pole`]'s G(iν) = 1/(iν - ω).
///
/// # Type Parameters
/// * `S` - Statistics type (Fermionic or Bosonic)
///
/// # Arguments
/// * `tau` - Imaginary time τ ∈ [-β, β]; τ < 0 is mapped to [0, β] by
///   (anti-)periodicity (see [`fermionic_single_pole`] and [`bosonic_single_pole`])
/// * `omega` - Pole position (real frequency)
/// * `beta` - Inverse temperature
///
/// # Returns
/// Real-valued Green's function G(τ)
///
/// # Errors
///
/// * [`Error::InvalidParameter`] if `beta` is not positive and finite, or
///   `omega` is not finite
/// * [`Error::OutOfDomain`] if `tau` is outside [-β, β] or NaN
///
/// # Example
/// ```
/// use sparse_ir::traits::{Bosonic, Fermionic};
/// use sparse_ir::{bosonic_single_pole, fermionic_single_pole, gtau_single_pole};
///
/// let g_f = gtau_single_pole::<Fermionic>(0.5, 5.0, 1.0).unwrap();
/// assert_eq!(g_f, fermionic_single_pole(0.5, 5.0, 1.0).unwrap());
///
/// let g_b = gtau_single_pole::<Bosonic>(0.5, 5.0, 1.0).unwrap();
/// assert_eq!(g_b, bosonic_single_pole(0.5, 5.0, 1.0).unwrap());
/// ```
pub fn gtau_single_pole<S: StatisticsType>(tau: f64, omega: f64, beta: f64) -> Result<f64, Error> {
    match S::STATISTICS {
        Statistics::Fermionic => fermionic_single_pole(tau, omega, beta),
        Statistics::Bosonic => bosonic_single_pole(tau, omega, beta),
    }
}

/// Compute fermionic single-pole Green's function at imaginary time τ
///
/// Evaluates G(τ) = -exp(-ω×τ) / (1 + exp(-β×ω)) for a single pole at frequency ω.
///
/// Supports negative τ with anti-periodic boundary conditions:
/// - G(τ + β) = -G(τ) (fermionic anti-periodicity)
/// - Valid for τ ∈ [-β, β]; τ is normalized with
///   [`normalize_tau`]
///
/// # Arguments
/// * `tau` - Imaginary time τ ∈ [-β, β]
/// * `omega` - Pole position (real frequency)
/// * `beta` - Inverse temperature
///
/// # Returns
/// Real-valued Green's function G(τ)
///
/// # Errors
///
/// * [`Error::InvalidParameter`] if `beta` is not positive and finite, or
///   `omega` is not finite
/// * [`Error::OutOfDomain`] if `tau` is outside [-β, β] or NaN
///
/// # Example
/// ```
/// use sparse_ir::fermionic_single_pole;
///
/// let beta = 1.0;
/// let omega = 5.0;
/// let tau = 0.5 * beta;
/// let g = fermionic_single_pole(tau, omega, beta).unwrap();
///
/// let expected = -(-omega * tau).exp() / (1.0 + (-beta * omega).exp());
/// assert!((g - expected).abs() < 1e-15);
///
/// // Anti-periodicity: G(τ - β) = -G(τ)
/// assert!((fermionic_single_pole(tau - beta, omega, beta).unwrap() + g).abs() < 1e-15);
/// ```
pub fn fermionic_single_pole(tau: f64, omega: f64, beta: f64) -> Result<f64, Error> {
    use crate::traits::Fermionic;

    // Normalize τ to [0, β] and track sign from anti-periodicity
    // G(τ + β) = -G(τ) for fermions
    let (tau_normalized, sign) = normalize_tau::<Fermionic>(tau, beta)?;
    require_finite("omega", omega)?;
    Ok(sign * fermionic_single_pole_unchecked(tau_normalized, omega, beta))
}

/// Fermionic single-pole G(τ) for τ already in [0, β], without the sign of
/// the antiperiodic continuation
///
/// Checked callers only: β positive and finite, ω finite. The DLR checks its
/// poles in `with_poles` and they cannot be changed afterwards.
pub(crate) fn fermionic_single_pole_unchecked(tau_normalized: f64, omega: f64, beta: f64) -> f64 {
    // Avoid overflow for large negative ω by factoring out exp(βω).
    // Both branches keep the exponent non-positive.
    if omega >= 0.0 {
        -(-omega * tau_normalized).exp() / (1.0 + (-beta * omega).exp())
    } else {
        -(omega * (beta - tau_normalized)).exp() / (1.0 + (beta * omega).exp())
    }
}

/// Compute bosonic single-pole Green's function at imaginary time τ
///
/// Evaluates G(τ) = -exp(-ω×τ) / (1 - exp(-β×ω)) for a single pole at frequency ω.
///
/// This is the imaginary-time counterpart of [`giwn_single_pole`]:
/// G(iνn) = ∫₀^β dτ exp(iνn×τ) G(τ) = 1/(iνn - ω). G(τ) is negative for ω > 0
/// and positive for ω < 0, the same sign convention as [`fermionic_single_pole`]
/// and the bosonic τ functions of [`DiscreteLehmannRepresentation`].
///
/// Supports negative τ with periodic boundary conditions:
/// - G(τ + β) = G(τ) (bosonic periodicity)
/// - Valid for τ ∈ [-β, β]; τ is normalized with
///   [`normalize_tau`]
///
/// ω = 0 is a genuine pole of the Bose factor, so the result is infinite there:
/// `-inf` for `omega = +0.0` (the ω → 0⁺ limit) and `+inf` for `omega = -0.0`.
/// [`DiscreteLehmannRepresentation`] evaluates a zero pole through its finite,
/// regularized limit instead.
///
/// # Arguments
/// * `tau` - Imaginary time τ ∈ [-β, β]
/// * `omega` - Pole position (real frequency)
/// * `beta` - Inverse temperature
///
/// # Returns
/// Real-valued Green's function G(τ)
///
/// # Errors
///
/// * [`Error::InvalidParameter`] if `beta` is not positive and finite, or
///   `omega` is not finite
/// * [`Error::OutOfDomain`] if `tau` is outside [-β, β] or NaN
///
/// # Example
/// ```
/// use sparse_ir::bosonic_single_pole;
///
/// let beta = 1.0;
/// let omega = 5.0;
/// let tau = 0.5 * beta;
/// let g = bosonic_single_pole(tau, omega, beta).unwrap();
///
/// let expected = -(-omega * tau).exp() / (1.0 - (-beta * omega).exp());
/// assert!((g - expected).abs() <= 1e-14 * expected.abs());
/// assert!(g < 0.0);
///
/// // Periodicity: G(τ - β) = G(τ)
/// assert!((bosonic_single_pole(tau - beta, omega, beta).unwrap() - g).abs() < 1e-15);
/// ```
pub fn bosonic_single_pole(tau: f64, omega: f64, beta: f64) -> Result<f64, Error> {
    use crate::traits::Bosonic;

    // Normalize τ to [0, β] using periodicity
    // G(τ + β) = G(τ) for bosons
    let tau_normalized = normalize_tau::<Bosonic>(tau, beta)?.0;
    require_finite("omega", omega)?;

    // Avoid overflow for large negative ω by factoring out exp(βω): both
    // branches keep the exponents non-positive. expm1 keeps the Bose
    // denominator 1 - exp(-β|ω|) accurate for small β|ω|. This is the same
    // form as the bosonic arm of `DiscreteLehmannRepresentation::evaluate_tau`.
    // At ω = ±0 the denominator is a signed zero and the result is ∓inf.
    if omega >= 0.0 {
        // 1 - exp(-βω) = -expm1(-βω)
        let denominator = -(-beta * omega).exp_m1();
        Ok(-(-omega * tau_normalized).exp() / denominator)
    } else {
        // -exp(-ωτ) / (1 - exp(-βω)) = exp(ω(β - τ)) / (1 - exp(βω))
        let denominator = -(beta * omega).exp_m1();
        Ok((omega * (beta - tau_normalized)).exp() / denominator)
    }
}

/// Generic single-pole Green's function at Matsubara frequency
///
/// Computes G(iν) = 1/(iν - ω) for a single pole at frequency ω.
///
/// # Type Parameters
/// * `S` - Statistics type (Fermionic or Bosonic)
///
/// # Arguments
/// * `matsubara_freq` - Matsubara frequency
/// * `omega` - Pole position (real frequency)
/// * `beta` - Inverse temperature
///
/// # Returns
/// Complex-valued Green's function G(iν)
///
/// # Errors
///
/// [`Error::InvalidParameter`] if `beta` is not positive and finite, or
/// `omega` is not finite
pub fn giwn_single_pole<S: StatisticsType>(
    matsubara_freq: &MatsubaraFreq<S>,
    omega: f64,
    beta: f64,
) -> Result<Complex<f64>, Error> {
    require_positive_finite("beta", beta)?;
    require_finite("omega", omega)?;
    // G(iν) = 1/(iν - ω)
    let wn = matsubara_freq.value(beta);
    let denominator = Complex::new(0.0, 1.0) * wn - Complex::new(omega, 0.0);
    Ok(Complex::new(1.0, 0.0) / denominator)
}

// ============================================================================
// Discrete Lehmann Representation
// ============================================================================

/// Discrete Lehmann Representation (DLR)
///
/// The DLR is a variant of the IR basis based on a "sketching" of the analytic
/// continuation kernel K. Instead of using singular value expansion, it represents
/// Green's functions as a linear combination of poles on the real-frequency axis:
///
/// ```text
/// G(iν) = Σ_i a[i] * reg[i] / (iν - ω[i])
/// ```
///
/// where:
/// - `ω[i]` are pole positions on the real axis
/// - `a[i]` are expansion coefficients
/// - `reg[i]` are the kernel regularizers `w(β, ω_i)`
///
/// The public `regularizers` field stores `w(β, ω_i)`: 1 for fermions and
/// `tanh(βω_i/2)` for bosons with `LogisticKernel`, and `ω_i` for
/// `RegularizedBoseKernel`. The DLR functions are `-K(τ, ω_i)` and its Fourier
/// transform for the physical kernel `K(τ, ω) = Σ_l U_l(τ) S_l V_l(ω)` of the
/// source basis.
///
/// # Type Parameters
/// * `S` - Statistics type (Fermionic or Bosonic)
pub struct DiscreteLehmannRepresentation<S>
where
    S: StatisticsType,
{
    /// Pole positions on the real-frequency axis ω ∈ [-ωmax, ωmax]
    poles: Vec<f64>,

    /// Inverse temperature β
    beta: f64,

    /// Maximum frequency ωmax
    wmax: f64,

    /// LogisticKernel reference basis used for Basis trait compatibility
    kernel: crate::kernel::LogisticKernel,

    /// Power with which the source kernel scales the spectral variable.
    kernel_ypower: i32,

    /// Accuracy of the representation
    accuracy: f64,

    /// Regularizers for each pole: regularizer[i] = w(β, ω_i)
    /// These are computed from the source IR basis kernel.
    regularizers: Vec<f64>,

    /// Pole weights used in tau and Matsubara evaluations.
    ///
    /// They equal `regularizers`: the τ functions are
    /// `-w_i e^{-τω_i} / (1 ± e^{-βω_i})` and the Matsubara functions
    /// `w_i / (iν - ω_i)`, which is `-K(τ, ω_i)` and its Fourier transform for
    /// the physical kernel of the source basis.
    pole_weights: Vec<f64>,

    /// Fitting matrix from IR: fitmat = -s · V(poles)
    /// Used for to_IR transformation
    fitmat: DTensor<f64, 2>,

    /// Fitter for from_IR transformation (uses SVD of fitmat)
    fitter: RealMatrixFitter,

    /// Marker for statistics type
    _phantom: PhantomData<S>,
}

impl<S> DiscreteLehmannRepresentation<S>
where
    S: StatisticsType,
{
    pub fn kernel_ypower(&self) -> i32 {
        self.kernel_ypower
    }

    pub fn pole_weights(&self) -> &[f64] {
        &self.pole_weights
    }

    /// Pole positions on the real-frequency axis, in the order they were
    /// given to [`Self::with_poles`] or chosen by [`Self::new`]
    pub fn poles(&self) -> &[f64] {
        &self.poles
    }

    /// Regularizers of the poles: `regularizers[i] = w(β, poles[i])` of the
    /// kernel of the IR basis this DLR was built from
    pub fn regularizers(&self) -> &[f64] {
        &self.regularizers
    }

    /// Number of functions of the IR basis this DLR was built from: the
    /// extent of the IR axis of [`Self::from_ir_nd`] and [`Self::to_ir_nd`]
    pub fn ir_basis_size(&self) -> usize {
        self.fitmat.shape().0
    }

    /// Create DLR from IR basis with custom poles
    ///
    /// The tau-domain pole basis is built from the logistic representation, while
    /// kernel-specific regularizers are preserved for compatible kernels.
    ///
    /// # Arguments
    /// * `basis` - The IR basis to construct DLR from
    /// * `poles` - Pole positions on the real-frequency axis, in
    ///   [-ωmax, ωmax] of `basis`
    ///
    /// # Errors
    /// * [`Error::KernelStatisticsMismatch`] if the kernel does not support
    ///   the requested statistics (e.g. `RegularizedBoseKernel` with fermionic
    ///   statistics)
    /// * [`Error::EmptyInput`] if `poles` is empty
    /// * [`Error::NonFiniteInput`] if a pole is NaN or infinite, and
    ///   [`Error::OutOfDomain`] if a pole is outside [-ωmax, ωmax] of `basis`,
    ///   both named `poles`, for the first such pole
    /// * [`Error::NotSupported`] for a bosonic pole at 0 if the kernel has a
    ///   `ypower` other than 0 or 1 (the DLR knows the limit at 0 for those
    ///   only), or if `basis` is itself a DLR
    ///
    /// Duplicate poles are accepted. They make [`Self::from_ir_nd`]
    /// ill-conditioned: the coefficients of equal poles are not unique,
    /// although the round trip through [`Self::to_ir_nd`] still recovers the
    /// IR coefficients.
    pub fn with_poles<K>(
        basis: &impl crate::basis_trait::Basis<S, Kernel = K>,
        poles: Vec<f64>,
    ) -> Result<Self, Error>
    where
        S: 'static,
        K: crate::kernel::KernelProperties + Clone,
    {
        use crate::kernel::LogisticKernel;

        // RegularizedBoseKernel (ypower == 1) is meaningful only for bosonic
        // statistics; its regularizer panics for fermionic input. Reject the
        // combination before computing anything.
        if S::STATISTICS == Statistics::Fermionic && basis.kernel().ypower() == 1 {
            return Err(Error::KernelStatisticsMismatch);
        }
        // Without poles the fitting matrix has no columns, and its SVD would
        // transpose [n, 0] arrays, which mdarray 0.7.2 does out of bounds
        // (https://github.com/fre-hu/mdarray/issues/21).
        if poles.is_empty() {
            return Err(Error::EmptyInput { name: "poles" });
        }

        let beta = basis.beta();
        let wmax = basis.wmax();
        let accuracy = basis.accuracy();
        let kernel_ypower = basis.kernel().ypower();

        // Each pole must be finite and in [-ωmax, ωmax], the domain of V_l.
        // evaluate_omega below checks the domain of the basis again.
        for (i, &pole) in poles.iter().enumerate() {
            if !pole.is_finite() {
                return Err(Error::NonFiniteInput {
                    name: "poles",
                    index: vec![i],
                    value: pole,
                });
            }
            if !(-wmax..=wmax).contains(&pole) {
                return Err(Error::OutOfDomain {
                    name: "poles",
                    value: pole,
                    domain: (-wmax, wmax),
                });
            }
        }
        // A bosonic pole at 0 is evaluated through its finite limit, which is
        // known for ypower 0 (regularizer tanh(βω/2)) and 1 (regularizer ω)
        // only; see zero_pole_tau_limit.
        if S::STATISTICS == Statistics::Bosonic
            && !(0..=1).contains(&kernel_ypower)
            && poles.contains(&0.0)
        {
            return Err(Error::NotSupported {
                what: format!(
                    "a bosonic DLR pole at 0 for a kernel with ypower = {kernel_ypower}: \
                     its limit is known for ypower 0 and 1 only"
                ),
            });
        }

        // Compute fitting matrix: fitmat = -s · V(poles)
        // This transforms DLR coefficients to IR coefficients
        let v_at_poles = basis.evaluate_omega(&poles)?; // shape: [n_poles, basis_size]
        let s = basis.svals(); // Non-normalized singular values (same as C++)

        let basis_size = basis.size();
        let n_poles = poles.len();

        // fitmat[l, i] = -s[l] * V_l(pole[i])
        // C++: fitmat = (-A_array * s_array.replicate(1, A.cols())).matrix()
        let fitmat = DTensor::<f64, 2>::from_fn([basis_size, n_poles], |idx| {
            let l = idx[0];
            let i = idx[1];
            -s[l] * v_at_poles[[i, l]]
        });

        // Create fitter for from_IR (inverse operation)
        let fitter = RealMatrixFitter::new(fitmat.clone());

        let lambda = beta * wmax;
        let logistic_kernel = LogisticKernel::new(lambda)?;
        let regularizers: Vec<f64> = poles
            .iter()
            .map(|&pole| basis.kernel().regularizer::<S>(beta, pole))
            .collect();
        let pole_weights = regularizers.clone();

        Ok(Self {
            poles,
            beta,
            wmax,
            kernel: logistic_kernel,
            kernel_ypower,
            accuracy,
            regularizers,
            pole_weights,
            fitmat,
            fitter,
            _phantom: PhantomData,
        })
    }

    fn zero_pole_tau_limit(&self) -> f64 {
        match self.kernel_ypower {
            // -lim_{ω→0} w(β, ω) e^{-τω} / (1 - e^{-βω}) with w = tanh(βω/2) or ω
            0 => -0.5,
            1 => -1.0 / self.beta,
            // Unreachable: with_poles rejects a bosonic pole at 0 for any
            // other ypower, and neither the poles nor the kernel can be
            // changed afterwards.
            _ => panic!(
                "DLR tau evaluation does not support kernel ypower = {}",
                self.kernel_ypower
            ),
        }
    }

    fn zero_pole_matsubara_limit(&self) -> f64 {
        match self.kernel_ypower {
            // lim_{ω→0} w(β, ω) / (0 - ω) at n = 0 with w = tanh(βω/2) or ω
            0 => -0.5 * self.beta,
            1 => -1.0,
            // Unreachable: with_poles rejects a bosonic pole at 0 for any
            // other ypower, and neither the poles nor the kernel can be
            // changed afterwards.
            _ => panic!(
                "DLR Matsubara evaluation does not support kernel ypower = {}",
                self.kernel_ypower
            ),
        }
    }

    /// Create DLR from IR basis with default pole locations
    ///
    /// Uses the default omega sampling points from the basis.
    ///
    /// # Arguments
    /// * `basis` - The IR basis to construct DLR from
    ///
    /// # Errors
    /// * [`Error::InsufficientDefaultPoles`] if the basis has fewer default
    ///   poles than functions. This can happen with certain kernel types
    ///   (e.g. `RegularizedBoseKernel`) due to numerical precision limitations
    ///   in root finding.
    /// * [`Error::KernelStatisticsMismatch`] as in [`Self::with_poles`]
    /// * [`Error::NotSupported`] as in [`Self::with_poles`]: for a default
    ///   pole at 0 of a bosonic basis whose kernel has a `ypower` other than
    ///   0 or 1, or if `basis` is itself a DLR
    /// * The errors of
    ///   [`Basis::default_omega_sampling_points`](crate::basis_trait::Basis::default_omega_sampling_points)
    ///   (NotSupported for an SVE with too few singular functions)
    pub fn new<K>(basis: &impl crate::basis_trait::Basis<S, Kernel = K>) -> Result<Self, Error>
    where
        S: 'static,
        K: crate::kernel::KernelProperties + Clone,
    {
        let poles = basis.default_omega_sampling_points()?;
        let basis_size = basis.size();
        if basis_size > poles.len() {
            return Err(Error::InsufficientDefaultPoles {
                basis_size,
                n_poles: poles.len(),
            });
        }
        Self::with_poles(basis, poles)
    }

    // ========================================================================
    // Public API (generic, user-friendly)
    // ========================================================================

    /// Convert IR coefficients to DLR (N-dimensional, generic over real/complex)
    ///
    /// # Type Parameters
    /// * `T` - Element type (f64 or Complex<f64>)
    ///
    /// # Arguments
    /// * `gl` - IR coefficients as N-D tensor
    /// * `dim` - Dimension along which to transform
    ///
    /// # Returns
    /// DLR coefficients as N-D tensor, with [`Basis::size`](crate::basis_trait::Basis::size)
    /// (the number of poles) entries along `dim`. An empty batch (a zero
    /// extent on another axis) gives an empty result.
    ///
    /// # Errors
    ///
    /// * [`Error::AxisOutOfRange`] if `dim` is not an axis of `gl`
    /// * [`Error::ShapeMismatch`] of the input if `gl` does not have
    ///   [`Self::ir_basis_size`] entries along `dim`
    /// * [`Error::DecompositionFailed`] if the SVD of the fitting matrix fails
    ///   (its entries are finite, since the poles are)
    pub fn from_ir_nd<T>(
        &self,
        backend: Option<&GemmBackendHandle>,
        gl: &mdarray::Tensor<T, mdarray::DynRank>,
        dim: usize,
    ) -> Result<mdarray::Tensor<T, mdarray::DynRank>, Error>
    where
        T: num_complex::ComplexFloat
            + faer_traits::ComplexField
            + From<f64>
            + Copy
            + Default
            + 'static,
    {
        use mdarray::{DTensor, Shape};

        let mut gl_shape = vec![];
        gl.shape().with_dims(|dims| {
            gl_shape.extend_from_slice(dims);
        });

        let basis_size = self.ir_basis_size();
        // Check the axis and its extent before anything reads gl_shape[dim].
        crate::fitters::common::check_input_shape(&gl_shape, dim, basis_size)?;

        if gl.is_empty() {
            // Zero-extent guard: an empty batch has nothing to convert.
            // Returning early keeps it away from the permuted copies that
            // mdarray 0.7.2 does out of bounds for a zero extent
            // (https://github.com/fre-hu/mdarray/issues/21) and from
            // zero-size GEMMs.
            let out_shape = crate::sampling::build_output_shape(gl.shape(), dim, self.poles.len());
            return Ok(mdarray::Tensor::zeros(&out_shape[..]));
        }

        // Move target dimension to position 0
        let gl_dim0 = crate::sampling::movedim(gl, dim, 0);

        // Reshape to 2D
        let extra_size = gl_dim0.len() / basis_size;
        let gl_2d_dyn = gl_dim0.reshape(&[basis_size, extra_size][..]).to_tensor();

        let gl_2d = DTensor::<T, 2>::from_fn([basis_size, extra_size], |idx| {
            gl_2d_dyn[&[idx[0], idx[1]][..]]
        });

        // Fit using fitter's generic 2D method. It fails only if the SVD of
        // the fitting matrix does.
        let g_dlr_2d = self.fitter.fit_2d_generic::<T>(backend, &gl_2d)?;

        // Reshape back
        let n_poles = self.poles.len();
        let mut g_dlr_shape = vec![n_poles];
        gl_dim0.shape().with_dims(|dims| {
            for i in 1..dims.len() {
                g_dlr_shape.push(dims[i]);
            }
        });

        let g_dlr_dim0 = g_dlr_2d.into_dyn().reshape(&g_dlr_shape[..]).to_tensor();
        Ok(crate::sampling::movedim(&g_dlr_dim0, 0, dim))
    }

    /// Convert DLR coefficients to IR (N-dimensional, generic over real/complex)
    ///
    /// # Type Parameters
    /// * `T` - Element type (f64 or Complex<f64>)
    ///
    /// # Arguments
    /// * `g_dlr` - DLR coefficients as N-D tensor
    /// * `dim` - Dimension along which to transform
    ///
    /// # Returns
    /// IR coefficients as N-D tensor, with [`Self::ir_basis_size`] entries
    /// along `dim`. An empty batch gives an empty result.
    ///
    /// # Errors
    ///
    /// * [`Error::AxisOutOfRange`] if `dim` is not an axis of `g_dlr`
    /// * [`Error::ShapeMismatch`] of the input if `g_dlr` does not have
    ///   [`Basis::size`](crate::basis_trait::Basis::size) (the number of
    ///   poles) entries along `dim`
    pub fn to_ir_nd<T>(
        &self,
        backend: Option<&GemmBackendHandle>,
        g_dlr: &mdarray::Tensor<T, mdarray::DynRank>,
        dim: usize,
    ) -> Result<mdarray::Tensor<T, mdarray::DynRank>, Error>
    where
        T: num_complex::ComplexFloat
            + faer_traits::ComplexField
            + From<f64>
            + Copy
            + Default
            + 'static,
    {
        use mdarray::{DTensor, Shape};

        let mut g_dlr_shape = vec![];
        g_dlr.shape().with_dims(|dims| {
            g_dlr_shape.extend_from_slice(dims);
        });

        let n_poles = self.poles.len();
        // Check the axis and its extent before anything reads g_dlr_shape[dim].
        crate::fitters::common::check_input_shape(&g_dlr_shape, dim, n_poles)?;

        if g_dlr.is_empty() {
            // Zero-extent guard: an empty batch has nothing to convert.
            // Returning early keeps it away from the permuted copies that
            // mdarray 0.7.2 does out of bounds for a zero extent
            // (https://github.com/fre-hu/mdarray/issues/21) and from
            // zero-size GEMMs.
            let out_shape =
                crate::sampling::build_output_shape(g_dlr.shape(), dim, self.ir_basis_size());
            return Ok(mdarray::Tensor::zeros(&out_shape[..]));
        }

        // Move target dimension to position 0
        let g_dlr_dim0 = crate::sampling::movedim(g_dlr, dim, 0);

        // Reshape to 2D
        let extra_size = g_dlr_dim0.len() / n_poles;
        let g_dlr_2d_dyn = g_dlr_dim0.reshape(&[n_poles, extra_size][..]).to_tensor();

        let g_dlr_2d = DTensor::<T, 2>::from_fn([n_poles, extra_size], |idx| {
            g_dlr_2d_dyn[&[idx[0], idx[1]][..]]
        });

        // Evaluate using fitter's generic 2D method
        let gl_2d = self.fitter.evaluate_2d_generic::<T>(backend, &g_dlr_2d);

        // Reshape back
        let basis_size = self.ir_basis_size();
        let mut gl_shape = vec![basis_size];
        g_dlr_dim0.shape().with_dims(|dims| {
            for i in 1..dims.len() {
                gl_shape.push(dims[i]);
            }
        });

        let gl_dim0 = gl_2d.into_dyn().reshape(&gl_shape[..]).to_tensor();
        Ok(crate::sampling::movedim(&gl_dim0, 0, dim))
    }
}

// ============================================================================
// Basis trait implementation for DLR
// ============================================================================

impl<S> crate::basis_trait::Basis<S> for DiscreteLehmannRepresentation<S>
where
    S: StatisticsType + 'static,
{
    type Kernel = crate::kernel::LogisticKernel;

    fn kernel(&self) -> &Self::Kernel {
        // DLR always uses LogisticKernel for weight computations
        &self.kernel
    }

    fn beta(&self) -> f64 {
        self.beta
    }

    fn wmax(&self) -> f64 {
        self.wmax
    }

    fn lambda(&self) -> f64 {
        self.beta * self.wmax
    }

    fn size(&self) -> usize {
        self.poles.len()
    }

    fn accuracy(&self) -> f64 {
        self.accuracy
    }

    fn significance(&self) -> Vec<f64> {
        // All poles are equally significant in DLR
        vec![1.0; self.poles.len()]
    }

    fn svals(&self) -> Vec<f64> {
        // All poles are equally significant in DLR (no singular value concept)
        vec![1.0; self.poles.len()]
    }

    fn default_tau_sampling_points(&self) -> Result<Vec<f64>, Error> {
        // DLR does not own the underlying IR basis, so it cannot delegate.
        // Callers should obtain tau sampling points from the IR basis that
        // was used to construct this DLR, e.g. `ir_basis.default_tau_sampling_points()`.
        Err(Error::NotSupported {
            what: "default tau sampling points of a DLR, which does not own its IR basis; \
                   use those of the IR basis"
                .to_string(),
        })
    }

    fn default_matsubara_sampling_points(
        &self,
        _positive_only: bool,
    ) -> Result<Vec<crate::freq::MatsubaraFreq<S>>, Error> {
        // DLR does not own the underlying IR basis, so it cannot delegate.
        // Callers should obtain Matsubara sampling points from the IR basis
        // that was used to construct this DLR, e.g.
        // `ir_basis.default_matsubara_sampling_points(positive_only)`.
        Err(Error::NotSupported {
            what: "default Matsubara sampling points of a DLR, which does not own its IR \
                   basis; use those of the IR basis"
                .to_string(),
        })
    }

    fn evaluate_tau(&self, tau: &[f64]) -> Result<mdarray::DTensor<f64, 2>, Error> {
        use mdarray::DTensor;

        let n_poles = self.poles.len();
        // Normalize every τ first: this rejects a τ outside [-β, β] and NaN
        // for every pole, including the bosonic pole at 0, whose limit does
        // not depend on τ.
        let normalized = tau
            .iter()
            .map(|&t| normalize_tau::<S>(t, self.beta))
            .collect::<Result<Vec<(f64, f64)>, Error>>()?;
        if normalized.is_empty() {
            // mdarray 0.7.2 runs the closure of from_fn for a zero extent
            // (https://github.com/fre-hu/mdarray/issues/21).
            return Ok(DTensor::<f64, 2>::from_elem([0, n_poles], 0.0));
        }
        Ok(DTensor::<f64, 2>::from_fn(
            [normalized.len(), n_poles],
            |idx| {
                let (tau_norm, sign) = normalized[idx[0]];
                let pole = self.poles[idx[1]];
                let pole_weight = self.pole_weights[idx[1]];
                match S::STATISTICS {
                    Statistics::Fermionic => {
                        sign * fermionic_single_pole_unchecked(tau_norm, pole, self.beta)
                            * pole_weight
                    }
                    Statistics::Bosonic => {
                        // The bosonic sign of normalize_tau is always 1.
                        if pole == 0.0 {
                            self.zero_pole_tau_limit()
                        } else if pole > 0.0 {
                            let denominator = -(-self.beta * pole).exp_m1();
                            -(-tau_norm * pole).exp() * pole_weight / denominator
                        } else {
                            let denominator = -(self.beta * pole).exp_m1();
                            (pole * (self.beta - tau_norm)).exp() * pole_weight / denominator
                        }
                    }
                }
            },
        ))
    }

    fn evaluate_matsubara(
        &self,
        freqs: &[crate::freq::MatsubaraFreq<S>],
    ) -> Result<mdarray::DTensor<num_complex::Complex<f64>, 2>, Error> {
        use mdarray::DTensor;
        use num_complex::Complex;

        let n_points = freqs.len();
        let n_poles = self.poles.len();
        if n_points == 0 {
            // See evaluate_tau (mdarray#21).
            return Ok(DTensor::<Complex<f64>, 2>::from_elem(
                [0, n_poles],
                Complex::new(0.0, 0.0),
            ));
        }

        // Evaluate MatsubaraPoles basis functions
        Ok(DTensor::<Complex<f64>, 2>::from_fn(
            [n_points, n_poles],
            |idx| {
                let freq = &freqs[idx[0]];
                let pole = self.poles[idx[1]];
                let pole_weight = self.pole_weights[idx[1]];

                // iν = iπn/β, with n = freq.n() (odd for fermions, even for bosons)
                let iv = freq.value_imaginary(self.beta);

                // u_i(iν) = pole_weight / (iν - pole_i), where `pole_weight` is the
                // regularizer w(β, ω_i) of the source kernel.
                if S::STATISTICS == Statistics::Bosonic && pole == 0.0 {
                    if crate::freq::is_zero(freq) {
                        Complex::new(self.zero_pole_matsubara_limit(), 0.0)
                    } else {
                        Complex::new(0.0, 0.0)
                    }
                } else {
                    Complex::new(pole_weight, 0.0) / (iv - Complex::new(pole, 0.0))
                }
            },
        ))
    }

    fn evaluate_omega(&self, _omega: &[f64]) -> Result<mdarray::DTensor<f64, 2>, Error> {
        // TODO(#205): For the IR basis, evaluate_omega returns V_l(omega).
        // For DLR, the "basis functions" in omega-space are single-pole
        // functions (conceptually delta functions at the pole positions),
        // which do not have a well-defined continuous representation on the
        // real-frequency axis analogous to V_l(omega).  A proper
        // implementation would require either:
        //   (a) returning the IR basis's V_l(omega) (but DLR does not store
        //       the IR basis), or
        //   (b) defining an appropriate discretized representation for the
        //       pole basis in omega-space.
        // Until the semantics are clarified, this is NotSupported.
        Err(Error::NotSupported {
            what: "evaluate_omega of a DLR: its pole functions have no real-frequency \
                   representation (#205); use the IR basis"
                .to_string(),
        })
    }

    fn default_omega_sampling_points(&self) -> Result<Vec<f64>, Error> {
        // DLR poles ARE the omega sampling points
        Ok(self.poles.clone())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::traits::{Bosonic, Fermionic};

    /// Generic test for periodicity/anti-periodicity
    fn test_periodicity_generic<S: StatisticsType>(expected_sign: f64, stat_name: &str) {
        let beta = 1.0;
        let omega = 5.0;

        // Test periodicity by comparing G(τ) with G(τ-β)
        // Since normalize_tau is restricted to [-β, β], we test:
        // For τ ∈ (0, β]: compare G(τ) with G(τ-β)
        // For fermions: G(τ) should equal -G(τ-β)
        // For bosons: G(τ) should equal G(τ-β)
        for tau in [0.1, 0.3, 0.7] {
            let g_tau = gtau_single_pole::<S>(tau, omega, beta).unwrap();
            let g_tau_minus_beta = gtau_single_pole::<S>(tau - beta, omega, beta).unwrap();

            // For fermions: G(τ) = -G(τ-β) → G(τ-β) = -G(τ)
            // For bosons: G(τ) = G(τ-β)
            let expected = expected_sign * g_tau;

            assert!(
                (expected - g_tau_minus_beta).abs() < 1e-14,
                "{} periodicity violated at τ={}: G(τ)={}, G(τ-β)={}, expected={}",
                stat_name,
                tau,
                g_tau,
                g_tau_minus_beta,
                expected
            );
        }
    }

    #[test]
    fn test_fermionic_antiperiodicity() {
        // Fermions: G(τ+β) = -G(τ)
        test_periodicity_generic::<Fermionic>(-1.0, "Fermionic");
    }

    #[test]
    fn test_bosonic_periodicity() {
        // Bosons: G(τ+β) = G(τ)
        test_periodicity_generic::<Bosonic>(1.0, "Bosonic");
    }

    #[test]
    fn test_generic_function_matches_specific() {
        let beta = 1.0;
        let omega = 5.0;
        let tau = 0.5;

        // Test that generic function matches specific functions
        let g_f_specific = fermionic_single_pole(tau, omega, beta).unwrap();
        let g_f_generic = gtau_single_pole::<Fermionic>(tau, omega, beta).unwrap();

        let g_b_specific = bosonic_single_pole(tau, omega, beta).unwrap();
        let g_b_generic = gtau_single_pole::<Bosonic>(tau, omega, beta).unwrap();

        assert!(
            (g_f_specific - g_f_generic).abs() < 1e-14,
            "Fermionic: specific={}, generic={}",
            g_f_specific,
            g_f_generic
        );
        assert!(
            (g_b_specific - g_b_generic).abs() < 1e-14,
            "Bosonic: specific={}, generic={}",
            g_b_specific,
            g_b_generic
        );
    }
}

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