From a1b3e3c9606af9f2421a64288601dc7b727ab807 Mon Sep 17 00:00:00 2001 From: Anouar Moustaj Date: Thu, 12 Nov 2026 21:11:21 +0200 Subject: [PATCH 01/22] Document the spin factors, the qubit-operator naming and the shift direction The spin table of prepend_spin (and the comment above _SPIN_OPS) now says that :Sx, :Sy and :Sz are spin-1/2 operators (1/2 sigma) while :iSy and :miSy are the full +-i sigma_y, not i S_y. The qubit operators state their naming: sigma_plus = |0><1| lowers the bit value (spin naming with |0> = up), so the +1 shift in pairingNNN carries sigma_minus on the bit it raises; the companion paper (arXiv:2607.00991, App. A) names the operators by the bit value, so its tau^+ is sigma_minus. The shift-MPO section header claimed (Q f)(x) = f(x + q); build_shift_mpo maps |n> to |n + q>, so on amplitudes (Q psi)(x) = psi(x - q). Comments and docstrings only; no code changes. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 +++++++++ src/core/AuxDOF.jl | 6 ++++++ src/core/Utils.jl | 8 +++++++- 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b55f81..819dfb1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,15 @@ bugs without breaking the API. ## [Unreleased] +### Changed + +- **Documented conventions.** The spin table of `prepend_spin` states the factors: + `:Sx`, `:Sy` and `:Sz` are ½σ, but `:iSy` and `:miSy` are the full ±iσ_y, not i·S_y. + The qubit operators state their naming: `sigma_plus` = |0⟩⟨1| lowers the bit value + (spin naming with |0⟩ = ↑), the opposite of the bit naming in the companion paper, + whose τ̂⁺ is `sigma_minus`. The shift-MPO section of `core/Utils.jl` now says + `|n⟩ → |n + q⟩`, so `(Qψ)(x) = ψ(x − q)`; it said `(Q f)(x) = f(x + q)`. + ## [0.2.0] — 2026-10-05 The code reorganisation tracked in `docs/dev/REORGANISATION_TODO.md` (Tiers 1–3), the diff --git a/src/core/AuxDOF.jl b/src/core/AuxDOF.jl index f23cde8..b90ef86 100644 --- a/src/core/AuxDOF.jl +++ b/src/core/AuxDOF.jl @@ -70,6 +70,8 @@ spin_index() = Index(2, "Spin") # 2×2 spin-½ operator matrices, ComplexF64 throughout for uniformity. # Basis: |↑⟩ = 1, |↓⟩ = 2. +# Mind the factor: :Sx, :Sy, :Sz are spin-½ operators (½σ) and :Sp, :Sm the spin flips, +# but :iSy and :miSy are the full ±iσ_y (the singlet-pairing factor), not i·S_y = (i/2)σ_y. const _SPIN_OPS = Dict{Symbol, Matrix{ComplexF64}}( :Id => [1 0; 0 1], :Pup => [1 0; 0 0], # |↑⟩⟨↑| — spin-up projector @@ -146,6 +148,10 @@ Equivalent to `prepend_op(H, s, op)`. | `:miSy` | −i·σ_y | h.c. of singlet pairing | Basis: state 1 = ↑, state 2 = ↓. + +Mind the factor: `:Sx`, `:Sy` and `:Sz` are spin-½ operators (½σ), but `:iSy` and +`:miSy` are the full ±iσ_y, not i·S_y = (i/2)σ_y. The singlet pairing and the Rashba +term of `add_soc!` use them as such. """ prepend_spin(H::MPO, s::Index, op::Symbol) = prepend_op(H, s, op) prepend_spin(H::MPO, s::Index, mat::AbstractMatrix) = prepend_op(H, s, mat) diff --git a/src/core/Utils.jl b/src/core/Utils.jl index b7e2e31..30a13ae 100644 --- a/src/core/Utils.jl +++ b/src/core/Utils.jl @@ -21,6 +21,12 @@ # 1. Qubit operator extensions (defined once to avoid duplicate definitions) # ============================================================ +# Naming convention: spin flips with |0⟩ = ↑ (rows are outputs). sigma_plus = |0⟩⟨1| +# therefore LOWERS the bit value (1 → 0) and sigma_minus = |1⟩⟨0| raises it; sigma_u and +# sigma_d project on |0⟩ and |1⟩. The +1 shift is written with sigma_minus on the bit it +# raises and sigma_plus on the less significant bits it clears (pairingNNN, +# physics/Supercond.jl). The companion paper (arXiv:2607.00991, App. A) names the +# operators by the bit value instead (↓ = 0, ↑ = 1): its τ̂⁺ = |1⟩⟨0| is sigma_minus here. ITensors.op(::OpName"sigma_plus", ::SiteType"Qubit") = [0 1 0 0] @@ -33,7 +39,7 @@ ITensors.op(::OpName"sigma_d",::SiteType"Qubit") = [0 0; 0 1] # |1><1| ITensors.op(::OpName"sigma_u",::SiteType"Qubit") = [1 0; 0 0] # |0><0| # ============================================================ -# 2. Shift MPOs: (Q f)(x) = f(x + q) on a binary-encoded chain +# 2. Shift MPOs: |n⟩ → |n + q⟩ on a binary-encoded chain, so (Qψ)(x) = ψ(x − q) # ============================================================ """ From 69b6977b2ae1dc5367140e50a638f98c2ff636b3 Mon Sep 17 00:00:00 2001 From: Anouar Moustaj Date: Thu, 12 Nov 2026 21:20:48 +0200 Subject: [PATCH 02/22] Add a boundary keyword to add_soc!'s Rashba term; warn on 2D add_soc!(type=:rashba) built its term from the cyclic +-1 shifts, so on an open chain (the default of get_Hamiltonian("chain_1d")) it added a Rashba bond between the last and the first site that the kinetic term does not have. boundary=:open (or :obc) drops that bond. The default :periodic keeps the v0.2.0 term and code path, so the golden cases are unchanged. The keyword goes through the package's boundary parser, so an unsupported value is an error for every SOC type, before H is modified. On a 2D Hamiltonian (H.Lx < H.L) the term couples neighbours along the linear position index, across the row ends and with no y bonds; add_soc! now warns there. A 2D Rashba term is still missing. The docstring gave the term as lambda (S_y K_u - S_y K_d), which is not Hermitian; it now gives the lambda i sigma_y (K_u - K_d) that the code builds. bugfix_soc_boundary.jl checks both boundaries against dense references. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 15 +++++++++ src/core/AuxDOF.jl | 37 +++++++++++++++++----- test/bugfix_soc_boundary.jl | 61 +++++++++++++++++++++++++++++++++++++ test/runtests.jl | 1 + 4 files changed, 106 insertions(+), 8 deletions(-) create mode 100644 test/bugfix_soc_boundary.jl diff --git a/CHANGELOG.md b/CHANGELOG.md index 819dfb1..afb6c4e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,8 +7,18 @@ bugs without breaking the API. ## [Unreleased] +### Added + +- `add_soc!` keyword `boundary` for the Rashba term: `:periodic` (the default, as + before) or `:open`, which drops the bond between the last and the first site. The + default chain, `get_Hamiltonian("chain_1d", t; L)`, is open, so a Rashba term that + matches it needs `boundary=:open`. + ### Changed +- `add_soc!(type=:rashba)` warns on a 2D Hamiltonian (`H.Lx` set): the term couples + neighbours along the linear position index only, i.e. along x and across the row + ends, with no y bonds. Results are unchanged. - **Documented conventions.** The spin table of `prepend_spin` states the factors: `:Sx`, `:Sy` and `:Sz` are ½σ, but `:iSy` and `:miSy` are the full ±iσ_y, not i·S_y. The qubit operators state their naming: `sigma_plus` = |0⟩⟨1| lowers the bit value @@ -16,6 +26,11 @@ bugs without breaking the API. whose τ̂⁺ is `sigma_minus`. The shift-MPO section of `core/Utils.jl` now says `|n⟩ → |n + q⟩`, so `(Qψ)(x) = ψ(x − q)`; it said `(Q f)(x) = f(x + q)`. +### Fixed + +- The `add_soc!` docstring gave the Rashba term as `λ·(S_y ⊗ K_u − S_y ⊗ K_d)`, which + is not Hermitian; the code builds `λ·iσ_y ⊗ (K_u − K_d)`, as the docstring now says. + ## [0.2.0] — 2026-10-05 The code reorganisation tracked in `docs/dev/REORGANISATION_TODO.md` (Tiers 1–3), the diff --git a/src/core/AuxDOF.jl b/src/core/AuxDOF.jl index b90ef86..4f17175 100644 --- a/src/core/AuxDOF.jl +++ b/src/core/AuxDOF.jl @@ -488,17 +488,25 @@ end # ============================================================ """ - add_soc!(H, λ; type=:rashba, direction=:z, tol=1e-8, maxdim=200, - position=nothing, check=true) -> H + add_soc!(H, λ; type=:rashba, direction=:z, boundary=:periodic, tol=1e-8, + maxdim=200, position=nothing, check=true) -> H Add spin-orbit coupling to `H`. Calls `add_spin!` automatically if needed, placing the spin index at `position` (default `H.aux_side`). `type`: - `:rashba` — nearest-neighbour Rashba SOC on the position chain: - `λ · (S_y ⊗ K_u − S_y ⊗ K_d)` where `K_u/K_d` are the ±1 shift - operators. `λ` must be a scalar. Breaks SU(2) spin symmetry - while preserving time-reversal. + `λ · iσ_y ⊗ (K_u − K_d)`, where `K_u`/`K_d` are the ±1 shift + operators and `iσ_y = [0 1; −1 0]` is the spin factor `:iSy`; both + factors are anti-Hermitian, so the term is Hermitian for real `λ`. + `λ` must be a scalar. Breaks SU(2) spin symmetry while preserving + time-reversal. `boundary` sets the bond between the last and the + first site: `:periodic` (the default, as before) includes it, `:open` + drops it; pass `boundary=:open` on an open chain, such as the default + `get_Hamiltonian("chain_1d", t; L)`. 1D only: on a 2D Hamiltonian + (`H.Lx` set) the term couples neighbours along the linear position + index, i.e. along x and across the row ends, with no y bonds, and + `add_soc!` warns. - `:ising` — diagonal Ising SOC `λ(i) · S_z` (equivalent to a position-dependent Zeeman along z; useful for Kane–Mele type models). - `:custom` — arbitrary position-space MPO `λ_mpo` tensor-producted with the @@ -510,10 +518,14 @@ placing the spin index at `position` (default `H.aux_side`). itself be Hermitian: `λ(i,j) = conj(λ(j,i))`. Diagonal and real-symmetric inputs satisfy this automatically. +`boundary` (`:periodic` or `:open`; `:pbc`/`:obc` are accepted too) is read by `:rashba` +only and checked for every `type`. + Examples -------- ```julia -add_soc!(H, 0.05) # Rashba λ=0.05 +add_soc!(H, 0.05) # Rashba λ=0.05, periodic chain +add_soc!(H, 0.05; boundary=:open) # Rashba on an open chain add_soc!(H, i -> 0.1*cos(2π*i/H.N); type=:ising) add_soc!(H, (i,j)->...; type=:custom, direction=:y) ``` @@ -521,11 +533,13 @@ add_soc!(H, (i,j)->...; type=:custom, direction=:y) function add_soc!(H::TBHamiltonian, λ; type::Symbol = :rashba, direction::Symbol = :z, + boundary::Symbol = :periodic, tol::Real = 1e-8, maxdim::Int = 200, position::Union{Nothing,Symbol} = nothing, check::Bool = true) _require_binary_position_space(H, "add_soc!") + periodic = _tb_periodic_boundary(boundary) # errors on an unsupported boundary pos = something(position, H.aux_side) add_spin!(H; cutoff=tol, maxdim=maxdim, position=pos) pos_s = _pos_sites(H) @@ -545,8 +559,15 @@ function add_soc!(H::TBHamiltonian, λ; elseif type === :rashba λ isa Number || error("Rashba SOC requires a scalar λ; got $(typeof(λ)).") - K_u = generate_kin_u(pos_s, H.N) - K_d = generate_kin_d(pos_s, H.N) + H.Lx !== nothing && H.Lx < H.L && + @warn "add_soc!(type=:rashba) couples neighbours along the linear position " * + "index only: on this 2D Hamiltonian it hops along x and across the row " * + "ends, with no y bonds. A 2D Rashba term is not implemented yet." + # The default keeps the periodic shifts of generate_kin_u/d (results as in + # v0.2.0); boundary=:open drops the bond between the last and the first site. + K_u, K_d = periodic ? + (generate_kin_u(pos_s, H.N), generate_kin_d(pos_s, H.N)) : + (shift_mpo(pos_s, 1; cyclic=false), shift_mpo(pos_s, -1; cyclic=false)) # λ·(iσ_y) ⊗ (K_u − K_d): both factors anti-Hermitian → product Hermitian. # :Sy (Hermitian) ⊗ anti-Hermitian would give a non-Hermitian term. +(spin_prepend( λ * K_u, H.spin_s, :iSy), diff --git a/test/bugfix_soc_boundary.jl b/test/bugfix_soc_boundary.jl new file mode 100644 index 0000000..03acf9c --- /dev/null +++ b/test/bugfix_soc_boundary.jl @@ -0,0 +1,61 @@ +using TensorBinding, ITensors, ITensorMPS, LinearAlgebra, Logging, Test +using TensorBinding: get_Hamiltonian, add_soc!, get_matrix + +# add_soc!(type=:rashba) always built the periodic chain term (the cyclic ±1 shifts of +# generate_kin_u/d), so on an open chain, the default of get_Hamiltonian("chain_1d"), it +# added a Rashba bond between the last and the first site that the kinetic term does not +# have. boundary=:open drops that bond; the default :periodic keeps the v0.2.0 term. +# The dense references are λ·kron(iσ_y, K_u − K_u†): the spin is prepended +# (H.sites = [spin, pos…]) and get_matrix is big-endian, so kron(spin, position). + +@testset "add_soc! Rashba boundary" begin + L, λ = 3, 0.1 + N = 2^L + iσy = ComplexF64[0 1; -1 0] # the :iSy spin factor + Ku_open = zeros(ComplexF64, N, N) + for n in 1:N-1 + Ku_open[n + 1, n] = 1 # |n+1⟩⟨n| + end + Ku_per = copy(Ku_open) + Ku_per[1, N] = 1 # |1⟩⟨N|, the wrap bond + rashba(K) = λ * kron(iσy, K - K') + + chain() = get_Hamiltonian("chain_1d", 1.0; L=L) # open chain + dense(H) = get_matrix(H.mpo, H.sites) + Hc = chain() + K0 = kron(Matrix{ComplexF64}(I, 2, 2), dense(Hc)) # kinetic term on [spin, pos…] + + Ho = chain(); add_soc!(Ho, λ; boundary=:open) + Hp = chain(); add_soc!(Hp, λ; boundary=:periodic) + Hd = chain(); add_soc!(Hd, λ) # default + @test Ho.sites[1] == Ho.spin_s # the layout the references assume + + Mo, Mp, Md = dense(Ho), dense(Hp), dense(Hd) + @test Mo ≈ K0 + rashba(Ku_open) atol=1e-10 + @test Mp ≈ K0 + rashba(Ku_per) atol=1e-10 + @test Md == Mp # the default is the v0.2.0 term + @test Mo ≈ Mo' atol=1e-12 # Hermitian + # The two boundaries differ only on the wrap bond (positions N ↔ 1, every spin block); + # elsewhere only by round-off, as the two MPO sums are truncated differently. + wrap = falses(2N, 2N) + for σ in 0:1, σ′ in 0:1 + wrap[σ * N + 1, σ′ * N + N] = true + wrap[σ * N + N, σ′ * N + 1] = true + end + @test norm((Mp - Mo)[.!wrap]) < 1e-10 + @test norm((Mp - Mo)[wrap]) ≈ 2λ # λ on each of the 4 wrap entries + + # Aliases, and an unsupported boundary is an error for every type, before any change. + Hobc = chain(); add_soc!(Hobc, λ; boundary=:obc) + @test dense(Hobc) == Mo + Hbad = chain() + @test_throws ErrorException add_soc!(Hbad, λ; boundary=:twisted) + @test_throws ErrorException add_soc!(Hbad, λ; type=:ising, boundary=:twisted) + @test Hbad.spin_s === nothing + + # 2D: the term runs along the linear position index only, and says so. + H2 = get_Hamiltonian("square_2d", 1.0; L=2) + @test H2.Lx == 1 + @test_logs (:warn, r"2D Hamiltonian") add_soc!(H2, λ) + @test_logs min_level=Logging.Warn add_soc!(chain(), λ; boundary=:open) +end diff --git a/test/runtests.jl b/test/runtests.jl index b1a916f..3f23bd4 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -140,6 +140,7 @@ include("bugfix_exciton_nh4.jl") include("bugfix_lattice4.jl") include("bugfix_density_cache.jl") include("bugfix_cache_safety.jl") +include("bugfix_soc_boundary.jl") # The 0.1 names and keywords renamed in 0.2: deprecated aliases with a one-time warning. include("deprecations.jl") From bf538967414243aa687805db803431c23ca53a8d Mon Sep 17 00:00:00 2001 From: Anouar Moustaj Date: Thu, 12 Nov 2026 21:23:34 +0200 Subject: [PATCH 03/22] Document the KPM normalisation and the Jackson moment count With the convolution kernels every Hermitian KPM spectrum is divided by pi^2 Ncheb sqrt(1 - w^2): it is the spectral density per unit rescaled energy times 1/pi, so one state integrates to 1/pi and pi/H.scale converts to physical units. kernel=:hodc carries the delta normalisation (integral 1), so switching kernel rescales the output by pi. Only get_ldos_from_mun said so. A Conventions section on the Solvers page and a Normalisation note in the docstrings of the LDOS, DOS, band, exciton and QPI entry points (CPU and GPU) now say it, with a link to get_ldos_from_mun. The Conventions section and get_ldos_from_mun also say that kernel=:jackson with Ncheb moments is the textbook Jackson kernel for Ncheb - 1 moments (the last weight is zero), while the NH KPM and the cheb2d bubbles use all N. get_dos_stochastic called its normalize=false output Tr[delta(w - H)]; with the convolution kernels it is that divided by pi, per unit rescaled energy. Docstrings and docs only. A local makedocs run resolves every new cross-reference. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 12 ++++++++++++ docs/src/api/solvers.md | 17 +++++++++++++++++ src/gpu/bands.jl | 5 +++++ src/gpu/exciton.jl | 6 ++++++ src/gpu/kpm.jl | 16 ++++++++++++++++ src/physics/QPI.jl | 4 ++++ src/physics/qft/bands.jl | 5 +++++ src/physics/qft/exciton_spectra.jl | 12 ++++++++++++ src/solvers/kpm/cached.jl | 12 +++++++++++- src/solvers/kpm/dos.jl | 13 +++++++++++-- src/solvers/kpm/exciton.jl | 9 ++++++++- src/solvers/kpm/ldos.jl | 8 ++++++++ 12 files changed, 115 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index afb6c4e..56c8d55 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,11 +25,23 @@ bugs without breaking the API. (spin naming with |0⟩ = ↑), the opposite of the bit naming in the companion paper, whose τ̂⁺ is `sigma_minus`. The shift-MPO section of `core/Utils.jl` now says `|n⟩ → |n + q⟩`, so `(Qψ)(x) = ψ(x − q)`; it said `(Q f)(x) = f(x + q)`. +- **KPM normalisation documented.** With the convolution kernels every Hermitian KPM + spectrum is the spectral density per unit rescaled energy `(ω − H.center)/H.scale` + times `1/π`: one state integrates to `1/π`, and `π/H.scale` converts to physical + units. `kernel=:hodc` is normalised to 1, so switching kernel rescales the output by + `π`. Only `get_ldos_from_mun` said so; the docstrings of the LDOS, DOS, band, exciton + and QPI functions (CPU and GPU) and a new *Conventions* section on the Solvers page now + do, with the Jackson moment count: `kernel=:jackson` with `Ncheb` moments is the + textbook kernel for `Ncheb − 1` moments (the last weight is zero). Results are + unchanged. ### Fixed - The `add_soc!` docstring gave the Rashba term as `λ·(S_y ⊗ K_u − S_y ⊗ K_d)`, which is not Hermitian; the code builds `λ·iσ_y ⊗ (K_u − K_d)`, as the docstring now says. +- The `get_dos_stochastic` docstring called its `normalize=false` output the total + spectral weight `Tr[δ(ω − H)]`; with the convolution kernels it is + `Tr[δ(ω̃ − H̃)]/π` per unit rescaled energy (`:hodc`: without the `1/π`). ## [0.2.0] — 2026-10-05 diff --git a/docs/src/api/solvers.md b/docs/src/api/solvers.md index 9a8cbf2..8b4ab2f 100644 --- a/docs/src/api/solvers.md +++ b/docs/src/api/solvers.md @@ -6,6 +6,23 @@ CurrentModule = TensorBinding ## Kernel Polynomial Method (KPM) +### Conventions + +- **Rescaled energies.** The expansion runs on `H̃ = (H − H.center)/H.scale`, whose + spectrum lies in (−1, 1); a physical energy `ω` enters as `ω̃ = (ω − H.center)/H.scale`. +- **Normalisation.** With the convolution kernels (`:jackson`, `:lorentz`, `:fejer`, + `:dirichlet`) every Hermitian KPM spectrum (LDOS, DOS, `A(k, ω)`, exciton spectra, QPI) + is divided by `π²·Ncheb·√(1 − ω̃²)`. It is the spectral density per unit rescaled energy + times `1/π`: the LDOS of one state integrates to `1/π` over `ω̃`. Multiply by + `π/H.scale` for the density per unit physical energy. `kernel = :hodc`, where offered, + carries the δ-function normalisation itself (one state integrates to 1; multiply by + `1/H.scale`), so switching between `:hodc` and a convolution kernel rescales the output + by `π`. The reconstruction is spelled out in [`get_ldos_from_mun`](@ref). +- **Jackson moments.** `kernel = :jackson` with `Ncheb` moments uses the textbook Jackson + kernel for `Ncheb − 1` moments, whose weight on the last moment is zero, so its + resolution is that of `Ncheb − 1` moments. The non-Hermitian KPM and the low-rank + `cheb2d` bubbles use the kernel for all `N` moments. + ```@autodocs Modules = [TensorBinding] Pages = ["solvers/kpm/kernels.jl", "solvers/kpm/recursion.jl", "solvers/kpm/cached.jl", diff --git a/src/gpu/bands.jl b/src/gpu/bands.jl index d033843..b55903a 100644 --- a/src/gpu/bands.jl +++ b/src/gpu/bands.jl @@ -49,6 +49,11 @@ res = TensorBinding.get_bands_gpu(H, 500, omega; num_x=50, maxdim=200, type=ComplexF64, printinfo=true) heatmap(1:size(res.Ak,2), omega, res.Ak; xticks=(res.ticks, res.labels)) ``` + +**Normalisation:** the package's KPM convention (see [`get_ldos_from_mun`](@ref)): the +result is the spectral density per unit rescaled energy `(ω − H.center)/H.scale` times +`1/π`, so each momentum state integrates to `1/π`; multiply by `π/H.scale` for physical +units. """ function get_bands_gpu(H::TBHamiltonian, Ncheb::Int, ω_phys_vals; kpath = nothing, diff --git a/src/gpu/exciton.jl b/src/gpu/exciton.jl index c6ab8f9..992a06b 100644 --- a/src/gpu/exciton.jl +++ b/src/gpu/exciton.jl @@ -66,6 +66,12 @@ observable. from |X,X⟩, so block averaging would cost O(block_size) recursions per pixel — equivalent to computing every site. Use `reduce=:point` with `num_avg` for light spatial averaging (each output pixel averages `num_avg` nearby positions). + +**Normalisation:** the package's KPM convention (see [`get_ldos_from_mun`](@ref)): with +the convolution kernels the result is the spectral density per unit rescaled energy +`(ω − H.center)/H.scale` times `1/π`, so each state integrates to `1/π`; multiply by +`π/H.scale` for physical units. `kernel=:hodc` is normalised to 1 (multiply by +`1/H.scale`). """ function get_exciton_ldos_spatial_gpu(H::TBHamiltonian, Ncheb::Int, ω_phys_vals; Lx::Union{Nothing,Int} = nothing, diff --git a/src/gpu/kpm.jl b/src/gpu/kpm.jl index 44d1d3e..e9ce8be 100644 --- a/src/gpu/kpm.jl +++ b/src/gpu/kpm.jl @@ -152,6 +152,10 @@ ldos = TensorBinding.get_ldos_spatial_gpu(H, 200, ωlist; ldos = TensorBinding.get_ldos_spatial_gpu(H, 200, ωlist; reduce=:block, num_x=128, num_y=128, sublattice=:average, maxdim=200) ``` + +**Normalisation:** the package's KPM convention (see [`get_ldos_from_mun`](@ref)): the +result is the spectral density per unit rescaled energy `(ω − H.center)/H.scale` times +`1/π`, so each state integrates to `1/π`; multiply by `π/H.scale` for physical units. """ function get_ldos_spatial_gpu(H::TBHamiltonian, Ncheb::Int, ω_phys_vals; x_groups = nothing, @@ -396,6 +400,12 @@ explicit-group sampling. Grid/window/box/block sampling, non-physical ordering, and auxiliary degrees of freedom (on `H` or requested through the projection keywords) are rejected with targeted errors. For those features use the MPO GPU path or the CPU `get_ldos_spatial` implementation. + +**Normalisation:** the package's KPM convention (see [`get_ldos_from_mun`](@ref)): with +the convolution kernels the result is the spectral density per unit rescaled energy +`(ω − H.center)/H.scale` times `1/π`, so each state integrates to `1/π`; multiply by +`π/H.scale` for physical units. `kernel=:hodc` is normalised to 1 (multiply by +`1/H.scale`). """ function get_ldos_spatial_mps_gpu(H::TBHamiltonian, Ncheb::Int, ω_phys_vals; x_groups = nothing, @@ -575,6 +585,12 @@ product states with `x_e != x_h` for the `N_sample` branch. normalisation, so no `√(1−ω²)` denominator is applied. `eta=0` falls back to `1/(Ncheb+1)`. Otherwise `kernel` is a convolution kernel (`:jackson` default, `:lorentz` with `lambda`, `:fejer`, `:dirichlet`). + +**Normalisation:** the package's KPM convention (see [`get_ldos_from_mun`](@ref)): with +the convolution kernels the result is the spectral density per unit rescaled energy +`(ω − H.center)/H.scale` times `1/π`, so each state integrates to `1/π`; multiply by +`π/H.scale` for physical units. `kernel=:hodc` is normalised to 1 (multiply by +`1/H.scale`). """ function get_dos_stochastic_gpu(H::TBHamiltonian, Ncheb::Int, ω_phys_vals; N_sample::Int = 50, diff --git a/src/physics/QPI.jl b/src/physics/QPI.jl index 9ea7edd..205a633 100644 --- a/src/physics/QPI.jl +++ b/src/physics/QPI.jl @@ -112,6 +112,10 @@ H = get_Hamiltonian("square_2d", 1.0; L=8, Lx=4) qpi = get_qpi(H, 80, ωlist; V=2.0, window_fraction=0.8) # Reshape to 2D: reshape(qpi[1,:], 2^Lx, 2^Ly)' ``` + +**Normalisation:** built from LDOS in the package's KPM convention (see +[`get_ldos_from_mun`](@ref)): per unit rescaled energy `(ω − H.center)/H.scale` and +times `1/π`; multiply by `π/H.scale` for physical units. """ function get_qpi(H::TBHamiltonian, Ncheb::Int, ω_phys_vals; impurity_site::Union{Int,Nothing} = nothing, diff --git a/src/physics/qft/bands.jl b/src/physics/qft/bands.jl index 36dd9aa..0f243db 100644 --- a/src/physics/qft/bands.jl +++ b/src/physics/qft/bands.jl @@ -497,6 +497,11 @@ When `kpath` is set the return value is a `NamedTuple`: ``` Otherwise returns `Matrix{Float64}` as usual (backward-compatible). + +**Normalisation:** the package's KPM convention (see [`get_ldos_from_mun`](@ref)): the +result is the spectral density per unit rescaled energy `(ω − H.center)/H.scale` times +`1/π`, so each momentum state integrates to `1/π`; multiply by `π/H.scale` for physical +units. """ function get_bands(H::TBHamiltonian, Ncheb::Int, D::Int, ω_phys_vals; kpath = nothing, diff --git a/src/physics/qft/exciton_spectra.jl b/src/physics/qft/exciton_spectra.jl index 23c4fc9..f03c303 100644 --- a/src/physics/qft/exciton_spectra.jl +++ b/src/physics/qft/exciton_spectra.jl @@ -42,6 +42,12 @@ one output column. `K_list`, `K_groups`, `k_groups`, `num_k`, `k_start`, and coarse cells) and in `get_exciton_continuum` differ, e.g. `[1, 4, 7, 10, 13]` and `[1, 5, 8, 12, 16]` for `N = 16`, `num_q = 5`: pass `Q_list` to both to compare them at the same momenta. + +**Normalisation:** the package's KPM convention (see [`get_ldos_from_mun`](@ref)): with +the convolution kernels the result is the spectral density per unit rescaled energy +`(ω − H.center)/H.scale` times `1/π`, so each state integrates to `1/π`; multiply by +`π/H.scale` for physical units. `kernel=:hodc` is normalised to 1 (multiply by +`1/H.scale`). """ function get_exciton_bands(H_QFT::MPO, H::TBHamiltonian, Ncheb::Int, omega_phys_vals; Q_list = nothing, @@ -181,6 +187,12 @@ full KPM recursion for every explicit relative momentum. With `normalize=true` (default), the result estimates the per-relative-momentum average `(1/N) * Tr_Q`. With `normalize=false`, it is multiplied by `H.N` and estimates the total fixed-`Q` trace `Tr_Q`. + +**Normalisation:** the package's KPM convention (see [`get_ldos_from_mun`](@ref)): with +the convolution kernels the result is the spectral density per unit rescaled energy +`(ω − H.center)/H.scale` times `1/π`, so each state integrates to `1/π`; multiply by +`π/H.scale` for physical units. `kernel=:hodc` is normalised to 1 (multiply by +`1/H.scale`). """ function get_exciton_continuum(H_QFT::MPO, H::TBHamiltonian, Ncheb::Int, omega_phys_vals; Q_list::Union{Nothing,AbstractVector} = nothing, diff --git a/src/solvers/kpm/cached.jl b/src/solvers/kpm/cached.jl index b9b07ba..073344f 100644 --- a/src/solvers/kpm/cached.jl +++ b/src/solvers/kpm/cached.jl @@ -63,6 +63,11 @@ Chebyshev expansion cached in `H` by a prior `KPM_Tn` or `KPM_Tn_mps` call. - `maxdim`, `cutoff` — truncation of the MPO/MPS sums (modes `:diag`, `:mpo`). Physical energies are converted via `E = (ω_phys − H.center) / H.scale`. + +**Normalisation:** the package's KPM convention (see [`get_ldos_from_mun`](@ref)): with +the convolution kernels the result is the spectral density per unit rescaled energy `E` +times `1/π`, so each state integrates to `1/π`; multiply by `π/H.scale` for physical +units. `kernel=:hodc` is normalised to 1 (multiply by `1/H.scale`). """ function get_ldos(H::TBHamiltonian, ω_phys::Real; mode::Symbol = :diag, @@ -158,6 +163,10 @@ ldos_vec = get_ldos_spectrum(H, ωlist) # Evaluate LDOS at site x=16 (0-indexed position 15) for each energy: ldos_at_16 = [l === nothing ? 0.0 : eval_mps(l, 15) for l in ldos_vec] ``` + +**Normalisation:** the package's KPM convention (see [`get_ldos_from_mun`](@ref)): the +result is the spectral density per unit rescaled energy `(ω − H.center)/H.scale` times +`1/π`, so each state integrates to `1/π`; multiply by `π/H.scale` for physical units. """ function get_ldos_spectrum(H::TBHamiltonian, ω_phys_vals; kernel::Symbol = :jackson, @@ -191,7 +200,8 @@ Computes the KPM expansion of `⟨ψ₀|δ(E − H̃)|ψ₀⟩` with an extra fa where `gₙ` are the kernel damping weights normalised to `g₀ = 1` (Jackson by default), so `∫ A dE = 1/π` per state for these kernels. The `:hodc` weights -carry the δ-function normalisation itself (`∫ A dE = 1`). Supported +carry the δ-function normalisation itself (`∫ A dE = 1`). With `kernel=:jackson` the +last moment gets weight zero (the textbook Jackson kernel for `N − 1` moments). Supported `kernel` values: `:jackson`, `:lorentz` (requires `lambda`), `:fejer`, `:dirichlet`, and `:hodc`, which hands over to `get_ldos_hodc_from_mun` with the contour broadening `eta` (default `1/(N+1)`) and order `m_order` (default `4`); diff --git a/src/solvers/kpm/dos.jl b/src/solvers/kpm/dos.jl index 77cc5c1..1e33523 100644 --- a/src/solvers/kpm/dos.jl +++ b/src/solvers/kpm/dos.jl @@ -40,8 +40,11 @@ every 15 samples. **Normalization** - `dos_weighting=:trace` (default): returns the trace DOS. With - `normalize=false` this is the total spectral weight `Tr[δ(ω-H)]`; with - `normalize=true` it is divided by the traced Hilbert-space dimension. + `normalize=false` this is the total spectral weight per unit rescaled energy + `ω̃ = (ω − H.center)/H.scale`: `Tr[δ(ω̃ − H̃)]/π` with the convolution kernels (the + package's KPM convention, see [`get_ldos_from_mun`](@ref)) and `Tr[δ(ω̃ − H̃)]` with + `kernel=:hodc`; multiply by `π/H.scale` (`:hodc`: `1/H.scale`) for physical units. + With `normalize=true` it is divided by the traced Hilbert-space dimension. - `dos_weighting=:sample`: returns the unweighted sample signal. For exciton stratified runs this is `avg_full + avg_bound` (when `N_bound > 0`), with no phase-space factor multiplying the continuum. This is intended for @@ -311,6 +314,12 @@ converted to an MPS and contracted with the product MPS `|1,1,...>`, giving For projected position spaces, `T_0` is `physical_projector(H)` and the trace is therefore over physical states only. `normalize=true` divides by `Tr(T_0)`; otherwise the spectral weight corresponds to the total traced state count. + +**Normalisation:** the package's KPM convention (see [`get_ldos_from_mun`](@ref)): with +the convolution kernels the result is the spectral density per unit rescaled energy +`(ω − H.center)/H.scale` times `1/π`, so each state integrates to `1/π`; multiply by +`π/H.scale` for physical units. `kernel=:hodc` is normalised to 1 (multiply by +`1/H.scale`). """ function get_dos_trace(H::TBHamiltonian, Ncheb::Int, ω_phys_vals; normalize::Bool=false, diff --git a/src/solvers/kpm/exciton.jl b/src/solvers/kpm/exciton.jl index 27b1488..12bcdf0 100644 --- a/src/solvers/kpm/exciton.jl +++ b/src/solvers/kpm/exciton.jl @@ -48,6 +48,12 @@ each MPS recursion step; `verbose` or `printinfo` prints progress every 5 column column (the χ the Chebyshev recursion hit under the given `maxdim`/`cutoff`); up to v0.1.1 it was the tuple `(result, linkdims)`, which destructures the same way. Mirrors the GPU entry point; useful for cutoff/tolerance studies where χ is the observable. + +**Normalisation:** the package's KPM convention (see [`get_ldos_from_mun`](@ref)): with +the convolution kernels the result is the spectral density per unit rescaled energy +`(ω − H.center)/H.scale` times `1/π`, so each state integrates to `1/π`; multiply by +`π/H.scale` for physical units. `kernel=:hodc` is normalised to 1 (multiply by +`1/H.scale`). """ function get_exciton_ldos_spatial(H::TBHamiltonian, Ncheb::Int, omega_phys_vals; X_list = nothing, @@ -146,7 +152,8 @@ end Bound-pair exciton LDOS at the single position `X` (1-indexed in `1:H.N`): a one-column call of `get_exciton_ldos_spatial` with `X_list=[X]`. Note that the Chebyshev order is the keyword `Ncheb` here, and that `maxdim` defaults to `40` -(`get_exciton_ldos_spatial`: `100`). +(`get_exciton_ldos_spatial`: `100`). The normalisation is that of +`get_exciton_ldos_spatial` (the package's KPM convention, `1/π` per state). """ function get_exciton_ldos(H::TBHamiltonian, X::Int, omega_phys::Real; Ncheb::Int = 200, diff --git a/src/solvers/kpm/ldos.jl b/src/solvers/kpm/ldos.jl index dc95997..818b9f5 100644 --- a/src/solvers/kpm/ldos.jl +++ b/src/solvers/kpm/ldos.jl @@ -70,6 +70,10 @@ ldos_tot = get_ldos_online(H_spin, 200, 16, ωlist; spin_proj=true) # Spin-↑ LDOS only ldos_up = get_ldos_online(H_spin, 200, 16, ωlist; spin_proj=true, proj_s=1) ``` + +**Normalisation:** the package's KPM convention (see [`get_ldos_from_mun`](@ref)): the +result is the spectral density per unit rescaled energy `(ω − H.center)/H.scale` times +`1/π`, so each state integrates to `1/π`; multiply by `π/H.scale` for physical units. """ function get_ldos_online(H::TBHamiltonian, Ncheb::Int, X::Int, ω_phys_vals; kernel::Symbol = :jackson, @@ -258,6 +262,10 @@ ldos_blk = get_ldos_spatial(H_big, 200, ωlist; reduce=:block, num_x=128, num_y= # Kagome: sublattice A only — only A columns filled, B/C columns zero ldos_A = get_ldos_spatial(H_kg, 200, ωlist; proj_sl=1, num_x=H_kg.N) ``` + +**Normalisation:** the package's KPM convention (see [`get_ldos_from_mun`](@ref)): the +result is the spectral density per unit rescaled energy `(ω − H.center)/H.scale` times +`1/π`, so each state integrates to `1/π`; multiply by `π/H.scale` for physical units. """ function get_ldos_spatial(H::TBHamiltonian, Ncheb::Int, ω_phys_vals; num_x::Int = H.N, From 9e2834b8cc25b889701e2e0f16411782e6e96ed5 Mon Sep 17 00:00:00 2001 From: Anouar Moustaj Date: Thu, 12 Nov 2026 21:51:19 +0200 Subject: [PATCH 04/22] Import TensorCrossInterpolation instead of using it `using TensorCrossInterpolation` brought TCI's exports into the module, where `contract` and `evaluate` became ambiguous names. Nothing called them bare, but a future bare call would have thrown. `import TensorCrossInterpolation` keeps the module name for the four qualified calls (core/Hamiltonian.jl, core/Utils.jl) next to the TCI alias. The four call sites give the same matrices as v0.2.0. The full test suite passes apart from the golden mismatches that the v0.2.0 sources show on this machine too (scftopo 7, RPA 4, GPU 1, identical numbers), and the docs build. Ticks the item in docs/dev/REORGANISATION_TODO.md. Co-Authored-By: Claude Opus 5.5 --- docs/dev/REORGANISATION_TODO.md | 6 ++++-- src/TensorBinding.jl | 4 ++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/dev/REORGANISATION_TODO.md b/docs/dev/REORGANISATION_TODO.md index 5e78d72..cd27f4f 100644 --- a/docs/dev/REORGANISATION_TODO.md +++ b/docs/dev/REORGANISATION_TODO.md @@ -459,8 +459,10 @@ the affected golden cases in the same commit. `cutoff`/`maxdim`; NH `n` is half the expansion; the default exciton Q grids of bands and continuum differ; 2D `get_bands` without `kpath` samples the diagonal cut; `get_density_from_Tn`'s `fermi` is rescaled. *6130261.* -- [ ] `using TensorCrossInterpolation` in the module makes `contract` and `evaluate` - ambiguous there; nothing calls them bare today (a future bare call would throw). +- [x] `using TensorCrossInterpolation` in the module made `contract` and `evaluate` + ambiguous there; nothing called them bare (a future bare call would have thrown). + It is now `import TensorCrossInterpolation`, which keeps the module name for the + four qualified calls in `core/Hamiltonian.jl` and `core/Utils.jl` (2026-11-12). ### Found by the first CI run of the v0.2.0 release (2026-10-05) diff --git a/src/TensorBinding.jl b/src/TensorBinding.jl index 142ad84..0c3da12 100644 --- a/src/TensorBinding.jl +++ b/src/TensorBinding.jl @@ -18,8 +18,8 @@ using ITensorMPS using Quantics using QuanticsTCI using QuanticsGrids -using TensorCrossInterpolation -import TensorCrossInterpolation as TCI +import TensorCrossInterpolation # import, not using: its exports contract and +import TensorCrossInterpolation as TCI # evaluate would be ambiguous names in this module using FFTW using Base.Threads From daff2aa34a012dd912d52805d1eea06275ac8253 Mon Sep 17 00:00:00 2001 From: Anouar Moustaj Date: Fri, 13 Nov 2026 00:12:37 +0200 Subject: [PATCH 05/22] Run the golden suites with one BLAS thread; pin a near-zero GPU marker absolutely The 12 golden failures found at v0.2.0 were not code changes. The generators run with OPENBLAS_NUM_THREADS=1, but runtests.jl left OpenBLAS at its default (12 threads here), and threaded sums amplified through small-maxdim truncations moved 11 tests: bubble_kagome_kpm and rpa_charge_kagome by up to 6e-3 (relative 2-5), haydock_bubble_chain3_kpm by 2e-5, the scftopo Chern markers by 5e-8. With one BLAS thread all of them match the stored data exactly, at 0833629, 6d5eed0 (the last src commit before the release) and on this branch. runtests.jl now sets one BLAS thread around the characterization block and restores the count afterwards. The remaining GPU case, chern_honeycomb_nnn_sublattice_geometry_c64, is a near-zero marker (norm 9e-5) that McWeeny iterates GPU rounding into; it moved by 1e-7 since the data were generated (CUDA runtime 13.0 then, 13.4 now) and is pinned at atol = 1e-6. All 4127 golden tests pass with one thread; no data file changes. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 +++++++ test/golden_gpu.jl | 11 ++++++++--- test/runtests.jl | 30 +++++++++++++++++++++--------- 3 files changed, 36 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 56c8d55..2c91b45 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,13 @@ bugs without breaking the API. - The `get_dos_stochastic` docstring called its `normalize=false` output the total spectral weight `Tr[δ(ω − H)]`; with the convolution kernels it is `Tr[δ(ω̃ − H̃)]/π` per unit rescaled energy (`:hodc`: without the `1/π`). +- **Golden suites run with one BLAS thread.** `test/runtests.jl` sets + `BLAS.set_num_threads(1)` around the characterization suites (and restores the count), + as the generators prescribe. At OpenBLAS's default thread count 11 golden tests failed + on the reference machine (the kagome RPA bubble by 6e-3, Chern markers by 5e-8), with + no code change: every one passes with one thread, at v0.2.0 as now. The GPU case + `chern_honeycomb_nnn_sublattice_geometry_c64`, a near-zero marker that moved by 1e-7 + under a newer CUDA runtime, is pinned at `atol = 1e-6`. ## [0.2.0] — 2026-10-05 diff --git a/test/golden_gpu.jl b/test/golden_gpu.jl index fb462cd..ac9dd5d 100644 --- a/test/golden_gpu.jl +++ b/test/golden_gpu.jl @@ -784,12 +784,12 @@ const YF8 = (i, _) -> Float64(i ÷ 4) const CKW = (maxdim = 64, cutoff = 1e-10) -function chern_case!(name, setup, xy, kw, ucs; cpu_rtol = 1e-4, cpu_atol = 1e-5) +function chern_case!(name, setup, xy, kw, ucs; tol = TOL64, cpu_rtol = 1e-4, cpu_atol = 1e-5) case!(name, setup, H -> (C = ComplexF64[TB.chern_marker_gpu(H, xy...; kw...)(uc) for uc in ucs],), H -> (C = ComplexF64[TB.chern_marker(H, xy...; (k => v for (k, v) in pairs(kw) if k ∉ (:dtype,))...)(uc) for uc in ucs],); - cpu_rtol = cpu_rtol, cpu_atol = cpu_atol) + tol = tol, cpu_rtol = cpu_rtol, cpu_atol = cpu_atol) end chern_case!("chern_chern8_mcweeny_c64", chern8, (XF8, YF8), @@ -798,8 +798,13 @@ chern_case!("chern_chern8_sp2_flat_c64", chern8, (XF8, YF8), (; CKW..., method = :sp2, Nel = 7, quenched = false, dtype = ComplexF64), [2, 7]) chern_case!("chern_chern8_kpm_lambda_c64", chern8, (XF8, YF8), (; CKW..., method = :kpm, Ncheb = 30, Lambda = 5, dtype = ComplexF64), [3, 10]) +# A near-zero marker (‖C‖ = 9e-5 over its two unit cells at L = 2): McWeeny iterates GPU +# rounding into it. It moved by 1e-7 (relative 1e-3) since the data were generated, under +# the CUDA 13.0 runtime (13.4 since), so it is pinned in absolute terms, at about a +# hundredth of its size. chern_case!("chern_honeycomb_nnn_sublattice_geometry_c64", honeycomb_nnn, (), - (; CKW..., method = :mcweeny, dtype = ComplexF64), [1, 4]) + (; CKW..., method = :mcweeny, dtype = ComplexF64), [1, 4]; + tol = (rtol = 1e-8, atol = 1e-6)) case!("chern_unknown_method_throws", chern8, diff --git a/test/runtests.jl b/test/runtests.jl index 3f23bd4..bcbba4e 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -165,17 +165,29 @@ include("sampling_golden.jl") # DMRG cases by O(1), and `rand(rng, 1:N)` streams differ before Julia 1.11. They run # by default, are skipped on CI (ENV["CI"] == "true"), and TB_GOLDEN=1 / TB_GOLDEN=0 # forces them on / off. +# +# The data were generated with one BLAS thread (see each generator's header), and the +# suites run with one too: threaded BLAS sums in another order, and the same +# amplification fails 11 golden tests on this machine at OpenBLAS's default 12 threads +# (the kagome RPA bubble moves by 6e-3, the Chern markers by 5e-8). Run a golden file on +# its own with OPENBLAS_NUM_THREADS=1 for the same reason. const RUN_GOLDEN = get(ENV, "TB_GOLDEN", get(ENV, "CI", "false") == "true" ? "0" : "1") == "1" if RUN_GOLDEN - @testset "Characterization (golden)" begin - include("golden_kpm.jl") - include("golden_rpa.jl") - include("golden_qft.jl") - include("golden_nh.jl") - include("golden_lattice.jl") - include("golden_scftopo.jl") - include("golden_gpu.jl") - include("golden_dynamics.jl") + blas_threads = BLAS.get_num_threads() + BLAS.set_num_threads(1) + try + @testset "Characterization (golden)" begin + include("golden_kpm.jl") + include("golden_rpa.jl") + include("golden_qft.jl") + include("golden_nh.jl") + include("golden_lattice.jl") + include("golden_scftopo.jl") + include("golden_gpu.jl") + include("golden_dynamics.jl") + end + finally + BLAS.set_num_threads(blas_threads) end else @info "Characterization (golden) suites skipped: CI, or TB_GOLDEN=0 (set TB_GOLDEN=1 to run them)" From 8d4eb10cd2b50cf3ca1eb6c1136475ecc592b16b Mon Sep 17 00:00:00 2001 From: Anouar Moustaj Date: Fri, 13 Nov 2026 00:29:09 +0200 Subject: [PATCH 06/22] Default TDVP state evolution to reverse_step=true tdvp_evolve, evolve_with_tdvp, evolve_with_tdvp_timedep, get_state_amplitude_trajectory_gpu and check_tdvp_vs_U_mpo (tdvp_reverse_step) defaulted to reverse_step=false, which skips TDVP's backward evolution of the bond tensor and counts terms of H twice: every step is wrong at O(dt). On a full-rank state of a 3-site chain, one step of dt = 0.05 was off by 0.07 (0.21 after three); with the backward step TDVP matches exp(-iH dt) to 1e-15 (2-site and 1-site). build_tdvp_propagator_mpo has defaulted to true since 0.1.1, as ITensorMPS does. Passing false reproduces the old results and warns once per function. The heatmap example uses true as well. Changed results, golden data regenerated: - dynamics_golden.jl: the ten cases that run TDVP (tdvp_evolve_*, evolve_with_tdvp_*, basis_amplitude and phase_aligned_distance, whose states come from tdvp_evolve), moved by 0.04 to 0.26. The rerun also moved the three krylov_green cases by 5e-14 (rounding; Krylov.jl does not use TDVP), whose stored lines were kept. - gpu_golden.jl: the five state_traj cases, rerun with the generator's new --only option, which keeps the stored entries of every other case (a full rerun moves every GPU value by rounding). The generator now records the working-tree src/ tree, as the dynamics generator does; the header names 79984c1eef99, this commit's src/. New test: one TDVP step and three steps (fixed and time-dependent H) against a Taylor-series exp(-iHt) on a full-rank state, the warnings, and the size of the reverse_step=false error. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 19 ++++++ .../dynamics/propagator_vs_tdvp_heatmaps.jl | 2 +- src/gpu/timeev.jl | 7 ++- src/solvers/Timeev.jl | 47 +++++++++----- test/bugfix_tdvp.jl | 38 ++++++++++- test/data/dynamics_golden.jl | 22 +++---- test/data/generate_gpu_golden.jl | 63 ++++++++++++++++--- test/data/gpu_golden.jl | 22 ++++--- 8 files changed, 171 insertions(+), 49 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c91b45..d943d4b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,25 @@ bugs without breaking the API. textbook kernel for `Ncheb − 1` moments (the last weight is zero). Results are unchanged. +### Changed results + +- **TDVP state evolution defaults to `reverse_step=true`.** `tdvp_evolve`, + `evolve_with_tdvp`, `evolve_with_tdvp_timedep`, `get_state_amplitude_trajectory_gpu` + and the reference step of `check_tdvp_vs_U_mpo` (`tdvp_reverse_step`) defaulted to + `false`, which skips TDVP's backward evolution of the bond tensor and counts terms of + `H` twice: every step was wrong at O(dt). On a full-rank state of a 3-site chain one + step of `dt = 0.05` was off by 0.07 in norm (0.21 after three steps); with the backward + step TDVP matches `exp(-iH dt)` to 1e-15. `build_tdvp_propagator_mpo` already defaulted + to `true` (since v0.1.1), and ITensorMPS does. Passing `reverse_step=false` reproduces + the old results and warns once per function. The example + `examples/dynamics/propagator_vs_tdvp_heatmaps.jl` now uses `true` as well. + Regenerated golden cases: the ten TDVP cases of `test/data/dynamics_golden.jl` + (`tdvp_evolve_*`, `evolve_with_tdvp_*`, and `basis_amplitude` and + `phase_aligned_distance`, whose states come from `tdvp_evolve`), moved by 0.04 to 0.26, + and the five `state_traj_*` cases of `test/data/gpu_golden.jl` (with the new + `--only` option of its generator, which reruns the named cases and keeps every other + stored entry). + ### Fixed - The `add_soc!` docstring gave the Rashba term as `λ·(S_y ⊗ K_u − S_y ⊗ K_d)`, which diff --git a/examples/dynamics/propagator_vs_tdvp_heatmaps.jl b/examples/dynamics/propagator_vs_tdvp_heatmaps.jl index d3774f5..358b904 100644 --- a/examples/dynamics/propagator_vs_tdvp_heatmaps.jl +++ b/examples/dynamics/propagator_vs_tdvp_heatmaps.jl @@ -44,7 +44,7 @@ function compare_propagator_and_tdvp_heatmaps(U_mpo, H, psi0, L, sites, nsteps; mpo_maxdim = 10_000, tdvp_maxdim = 200, tdvp_cutoff = 1e-10, - tdvp_reverse_step = false, + tdvp_reverse_step = true, tdvp_outputlevel = 0, tdvp_nsite = 2, ) diff --git a/src/gpu/timeev.jl b/src/gpu/timeev.jl index d69e0ed..1f757c1 100644 --- a/src/gpu/timeev.jl +++ b/src/gpu/timeev.jl @@ -226,7 +226,7 @@ end component=:real, pointavg=:complex, normalize_each_step=false, maxdim=200, cutoff=1e-8, - reverse_step=false, outputlevel=0, nsite=2, + reverse_step=true, outputlevel=0, nsite=2, dtype=ComplexF32, printinfo=false, verbose=false) -> (amplitude, times, centers, groups, norms, maxlinkdims) @@ -242,6 +242,8 @@ and initial state are uploaded once, the TDVP loop stays on GPU, and only sampled scalar amplitudes are copied back to CPU. `nsteps` and `dt` are required; `nsite`, `reverse_step`, `outputlevel` and `normalize_each_step` are passed to `tdvp` (with the last, `tdvp` renormalizes the state after every step). +`reverse_step` is `true` by default, as in [`evolve_with_tdvp`](@ref); it was `false` +up to v0.2.0, which is wrong at O(dt) per step and now warns. The returned `amplitude` matrix has rows = sampled positions and columns = sampled times. By default it stores `real()`; `component` may be @@ -273,7 +275,7 @@ function get_state_amplitude_trajectory_gpu(H, psi0::MPS; normalize_each_step::Bool = false, maxdim::Int = 200, cutoff::Real = 1e-8, - reverse_step::Bool = false, + reverse_step::Bool = true, outputlevel::Int = 0, nsite::Int = 2, dtype::Type{<:Complex} = ComplexF32, @@ -286,6 +288,7 @@ function get_state_amplitude_trajectory_gpu(H, psi0::MPS; reduce in (:point, :block) || error("get_state_amplitude_trajectory_gpu: reduce must be :point or :block.") component in (:real, :imag, :abs, :abs2, :probability) || error("get_state_amplitude_trajectory_gpu: unsupported component :$component.") + _warn_no_reverse_step("get_state_amplitude_trajectory_gpu", reverse_step) H_mpo = H isa TBHamiltonian ? H.mpo : H Lbits = length(psi0) diff --git a/src/solvers/Timeev.jl b/src/solvers/Timeev.jl index ff0eb31..36d2122 100644 --- a/src/solvers/Timeev.jl +++ b/src/solvers/Timeev.jl @@ -53,6 +53,14 @@ function _tdvp_step(H, psi, dt; nsite, maxdim, cutoff, normalize, reverse_step, ) end +# reverse_step = false skips TDVP's backward evolution of the bond tensor, which the +# projector splitting needs: terms of H are then counted twice and every step is wrong +# at O(dt). It was the default of the state-evolution functions up to v0.2.0; passing it +# now warns once per function (build_tdvp_propagator_mpo has its own warning). +_warn_no_reverse_step(fname, reverse_step) = + reverse_step || @warn "$fname: reverse_step=false skips TDVP's backward bond evolution " * + "and counts terms of H twice; each step is wrong at O(dt)." maxlog=1 _id=Symbol(fname) + # The trajectory loop of every evolve_* function: returns [x0, x1, …, x_nsteps] # as a Vector{T}, with x_step = advance(step, x_{step-1}). `snapshot` makes the # stored copies and the working copy of x0: `copy` for the MPS loops, `deepcopy` @@ -255,7 +263,7 @@ end """ tdvp_evolve(H, psi, dt; maxdim=200, cutoff=1e-10, normalize=true, - reverse_step=false, outputlevel=0, nsite=2) -> MPS + reverse_step=true, outputlevel=0, nsite=2) -> MPS Apply one TDVP step to `psi` under Hamiltonian `H` for time `dt`. @@ -263,6 +271,11 @@ Apply one TDVP step to `psi` under Hamiltonian `H` for time `dt`. When `normalize=true` the output is normalised (`tdvp` normalises the state at the end of each half-sweep). +`reverse_step` evolves the bond tensor backwards between site updates, as the TDVP +projector splitting requires (the ITensorMPS default). `false` counts terms of `H` +twice, so the step is wrong at O(dt); it warns. The default was `false` up to v0.2.0 +(see the CHANGELOG); pass `reverse_step=false` to reproduce those results. + A `TBHamiltonian` overload applies `-im` internally: `tdvp_evolve(H::TBHamiltonian, psi, dt; ...)`. """ @@ -273,10 +286,11 @@ function tdvp_evolve( maxdim = 200, cutoff = 1e-10, normalize = true, - reverse_step = false, + reverse_step = true, outputlevel = 0, nsite = 2, ) + _warn_no_reverse_step("tdvp_evolve", reverse_step) return _tdvp_step( H, psi, @@ -337,13 +351,15 @@ end """ evolve_with_tdvp(H, psi0, nsteps, dt; normalize_each_step=true, maxdim=200, - cutoff=1e-10, reverse_step=false, outputlevel=0, nsite=2) + cutoff=1e-10, reverse_step=true, outputlevel=0, nsite=2) -> Vector{MPS} Run a TDVP loop for `nsteps` steps of size `dt` under a fixed Hamiltonian `H`, returning `[psi(0), psi(dt), ..., psi(nsteps*dt)]`. -`H` must carry the `-im` prefactor for Schrödinger evolution. +`H` must carry the `-im` prefactor for Schrödinger evolution. `reverse_step` is as in +[`tdvp_evolve`](@ref): `true` by default (it was `false` up to v0.2.0, which is wrong at +O(dt) per step and now warns). A `TBHamiltonian` overload applies `-im` internally: `evolve_with_tdvp(H::TBHamiltonian, psi0, nsteps, dt; ...)`. @@ -352,10 +368,11 @@ function evolve_with_tdvp(H, psi0, nsteps, dt; normalize_each_step = true, maxdim = 200, cutoff = 1e-10, - reverse_step = false, + reverse_step = true, outputlevel = 0, nsite = 2, ) + _warn_no_reverse_step("evolve_with_tdvp", reverse_step) return _trajectory(psi0, nsteps, MPS) do _, psi return _tdvp_step( H, @@ -374,7 +391,7 @@ end """ evolve_with_tdvp_timedep(Hoft, psi0, nsteps, dt; normalize_each_step=true, - maxdim=200, cutoff=1e-10, reverse_step=false, + maxdim=200, cutoff=1e-10, reverse_step=true, outputlevel=0, nsite=2, krylovdim=20, tol=1e-10) -> Vector{MPS} @@ -384,7 +401,8 @@ TDVP loop for a time-dependent Hamiltonian `H(t)`. Hamiltonian is frozen at the midpoint `t + dt/2` (midpoint rule). `Hoft` must return the physical Hamiltonian; the `-im` prefactor is applied internally. `krylovdim` and `tol` go to the TDVP exponentiation step (`updater_kwargs`); -the other keywords are as in `evolve_with_tdvp`. +the other keywords are as in `evolve_with_tdvp` (`reverse_step=true` by default; it was +`false` up to v0.2.0). Returns `[psi(0), psi(dt), ..., psi(nsteps*dt)]`. """ @@ -392,12 +410,13 @@ function evolve_with_tdvp_timedep(Hoft, psi0, nsteps, dt; normalize_each_step = true, maxdim = 200, cutoff = 1e-10, - reverse_step = false, + reverse_step = true, outputlevel = 0, nsite = 2, krylovdim = 20, tol = 1e-10, ) + _warn_no_reverse_step("evolve_with_tdvp_timedep", reverse_step) return _trajectory(psi0, nsteps, MPS) do step, psi t_mid = (step - 1) * dt + dt / 2 Hmid = Hoft(t_mid) @@ -500,7 +519,7 @@ end check_tdvp_vs_U_mpo(H, U_mpo, dt, L, sites; test_states=[0, 1, 3, 7, 13, 29, 57, 2^L - 1], tdvp_maxdim=200, tdvp_cutoff=1e-10, tdvp_normalize=true, - tdvp_reverse_step=false, tdvp_outputlevel=0, tdvp_nsite=2, + tdvp_reverse_step=true, tdvp_outputlevel=0, tdvp_nsite=2, apply_maxdim=500, apply_cutoff=1e-12, print_sample_amplitudes=true, sample_amplitudes=[0, 1, 2, 3]) -> (max_overlap_error, max_phase_error) @@ -520,10 +539,10 @@ Prints per-state overlap errors and phase-aligned distances, then returns the ma The reference is one TDVP step from the bare basis state, so it has the errors described in `build_tdvp_propagator_mpo`: it drops the hops that flip three or more qubits, and -with the default `tdvp_reverse_step=false` it also counts terms of `H` twice. An error -of order `dt` therefore does not mean `U_mpo` is wrong (chain_1d, L = 4, `dt = 0.05`: a -phase error of 0.056 for a `U_mpo` within 8e-5 of `exp(-iH dt)`). At small L, compare -with a dense `exp(-iH dt)` instead. +with `tdvp_reverse_step=false` (the default up to v0.2.0) it also counts terms of `H` +twice. An error of order `dt` therefore does not mean `U_mpo` is wrong (chain_1d, L = 4, +`dt = 0.05`, `tdvp_reverse_step=false`: a phase error of 0.056 for a `U_mpo` within 8e-5 +of `exp(-iH dt)`). At small L, compare with a dense `exp(-iH dt)` instead. The `TBHamiltonian` method applies `-im` internally and takes `L`, `sites` from `H`. """ @@ -537,7 +556,7 @@ function check_tdvp_vs_U_mpo( tdvp_maxdim = 200, tdvp_cutoff = 1e-10, tdvp_normalize = true, - tdvp_reverse_step = false, + tdvp_reverse_step = true, tdvp_outputlevel = 0, tdvp_nsite = 2, apply_maxdim = 500, diff --git a/test/bugfix_tdvp.jl b/test/bugfix_tdvp.jl index 1a63bbf..6745d88 100644 --- a/test/bugfix_tdvp.jl +++ b/test/bugfix_tdvp.jl @@ -1,5 +1,6 @@ -using TensorBinding, ITensors, ITensorMPS, LinearAlgebra, Test -using TensorBinding: get_Hamiltonian, get_matrix, build_tdvp_propagator_mpo +using TensorBinding, ITensors, ITensorMPS, LinearAlgebra, Test, Logging +using TensorBinding: get_Hamiltonian, get_matrix, build_tdvp_propagator_mpo, tdvp_evolve, + evolve_with_tdvp, evolve_with_tdvp_timedep using Random: seed! # Build under a fixed seed (QuanticsTCI draws random initial pivots) and count the TDVP @@ -63,3 +64,36 @@ end @test nnc > n4 @test get_matrix(Unc, H4.sites) == get_matrix(U4, H4.sites) end + +# e^{-iHt}|ψ⟩ by its Taylor series, without truncation (the reference below). +function _exact_evolve(Hm::MPO, ψ::MPS, t; K = 30) + term = acc = ψ + for k in 1:K + term = (-im * t / k) * apply(Hm, term; cutoff = 0.0) + acc = +(acc, term; cutoff = 0.0) + end + return acc +end + +@testset "TDVP state evolution: reverse_step defaults to true" begin + # A full-rank state, so TDVP's tangent space is the whole Hilbert space: with the + # backward bond step it is exact (|Δψ| ~ 1e-15); without it, it counted terms of H + # twice (|Δψ| = 0.07 per step at dt = 0.05, 0.21 after three). false was the default + # of these functions up to v0.2.0; it now warns. + dt = 0.05 + H = get_Hamiltonian("chain_1d", 1.0; L = 3) + seed!(7) + ψ0 = normalize!(MPS(randn(ComplexF64, 2, 2, 2), H.sites)) + ex1, ex3 = _exact_evolve(H.mpo, ψ0, dt), _exact_evolve(H.mpo, ψ0, 3dt) + + @test norm(tdvp_evolve(H, ψ0, dt; normalize = false) - ex1) < 1e-10 + @test norm(tdvp_evolve(H, ψ0, dt; normalize = false, nsite = 1) - ex1) < 1e-10 + @test norm(evolve_with_tdvp(H, ψ0, 3, dt; normalize_each_step = false)[end] - ex3) < 1e-10 + st = evolve_with_tdvp_timedep(_ -> H.mpo, ψ0, 3, dt; normalize_each_step = false) + @test norm(st[end] - ex3) < 1e-8 + + @test_logs min_level = Logging.Warn tdvp_evolve(H, ψ0, dt) + ψf = @test_logs (:warn, r"tdvp_evolve: reverse_step=false") tdvp_evolve(H, ψ0, dt; normalize = false, reverse_step = false) + @test norm(ψf - ex1) > 0.01 + @test_logs (:warn, r"evolve_with_tdvp: reverse_step=false") evolve_with_tdvp(H, ψ0, 1, dt; reverse_step = false) +end diff --git a/test/data/dynamics_golden.jl b/test/data/dynamics_golden.jl index 968316e..30bab21 100644 --- a/test/data/dynamics_golden.jl +++ b/test/data/dynamics_golden.jl @@ -1,7 +1,7 @@ # AUTO-GENERATED by test/data/generate_dynamics_golden.jl -- do not edit by hand. # # Pinned outputs of the dynamics area, checked by test/golden_dynamics.jl. -# Generated from src/ tree faf1e0126a2c +# Generated from src/ tree 79984c1eef99 # with Julia 1.12.3. Regenerate only for an intentional behaviour change; # see the generator's header. # @@ -173,16 +173,16 @@ push!(DYNAMICS_GOLDEN_CASES, (name = "haydock_single_step", group = "Haydock", s expected = (a = [5.1730133678233814e-18], b = [2.7386127875258306], norm0 = 2.7386127875258306, cf = 6.0 - 3.0im, resolve = ComplexF64[0.4 - 0.2im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im; 0.0 + 0.0im 0.8 - 0.4im 0.0 + 0.0im 0.0 + 0.0im; 0.0 + 0.0im 0.0 + 0.0im 1.2000000000000002 - 0.6000000000000001im 0.0 + 0.0im; 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 1.6 - 0.8im]))) push!(DYNAMICS_GOLDEN_CASES, (name = "tdvp_evolve_normalized", group = "Timeev", seed = 401, throws = nothing, - expected = (psi = ComplexF64[-0.011186845460023192 - 6.298616611108215e-18im, -5.248632856061593e-18 - 0.14831758390362504im, 0.9776075958321914 - 2.4933314224230485e-18im, -1.6184217914572027e-19 - 0.14873309293232542im, -0.006211552288699636 + 1.3246610628849734e-18im, 3.30820617875591e-20 + 0.00014506672668767806im, 2.3325302619611165e-6 - 4.431592130454866e-21im, -6.928878867263843e-23 - 2.851925761926611e-8im],))) + expected = (psi = ComplexF64[-0.004987511257590361 - 4.256244824910706e-18im, -4.8779394610017105e-18 - 0.09950068184912828im, 0.9900221149408974 - 1.758271761655908e-18im, -5.506220035155005e-20 - 0.09958393186897514im, -0.0037395947199759475 + 1.3323220194903071e-18im, 3.329188972963432e-20 + 8.315120651544959e-5im, 1.2996546806655269e-6 - 2.778993261489146e-21im, -4.170312417752371e-23 - 1.560021503269989e-8im],))) push!(DYNAMICS_GOLDEN_CASES, (name = "tdvp_evolve_nh_normalize_flag", group = "Timeev", seed = 402, throws = nothing, - expected = (normalized = ComplexF64[-0.044395201285566455 + 8.482251732889814e-19im, 9.340433502366598e-18 - 0.28795417327201933im, 0.9117077869912671 + 2.2995631664005813e-17im, 1.0316098517843696e-17 - 0.28863836152207223im, -0.024227735576569227 + 1.420181778022729e-17im, 4.2331177447507805e-18 + 0.0011327387592769693im, 3.641874712934168e-5 - 6.827925539641769e-18im, -7.023504260050665e-19 - 8.901425307242115e-7im], unnormalized = ComplexF64[-0.04282563463562926 - 9.790544289865937e-18im, 5.2733145617004546e-17 - 0.2777737201151399im, 0.8794748857877169 + 1.4921626770710904e-16im, 4.3909238483301495e-17 - 0.27843371928555205im, -0.023371178005856343 + 6.099337791542045e-18im, 3.528967740464522e-17 + 0.0010926914359589283im, 3.513118340007704e-5 + 9.262235725417984e-17im, 3.0854674547725016e-17 - 8.586720566709212e-7im], norm_unnormalized = 0.9646455787002522))) + expected = (normalized = ComplexF64[-0.019920162993775123 + 8.397243098236704e-19im, 3.4211858564850633e-18 - 0.1966108328915358im, 0.9603521328970197 + 1.3140109715845508e-17im, -4.230213297037297e-18 - 0.19609401178224165im, -0.014759931999047345 + 1.6069140557903678e-17im, 2.8107882033746024e-18 + 0.0006564038154412451im, 2.0505175467230007e-5 - 7.142096508460998e-18im, -5.728062214720125e-19 - 4.918876792868745e-7im], unnormalized = ComplexF64[-0.01956482497943339 - 5.7990419046574036e-18im, 4.561601250206888e-17 - 0.19310366766504927im, 0.9432212680502347 + 1.4441838329813577e-16im, 3.154478890842946e-17 - 0.19259606566640208im, -0.014496642741324083 + 1.0665685585195827e-17im, 2.4409277502230257e-17 + 0.0006446948134385892im, 2.0139401937293142e-5 + 9.938697870711178e-17im, 2.1236093123112708e-17 - 4.831133338391155e-7im], norm_unnormalized = 0.9821618922268568))) push!(DYNAMICS_GOLDEN_CASES, (name = "tdvp_evolve_tbhamiltonian", group = "Timeev", seed = 403, throws = nothing, - expected = (psi = ComplexF64[2.182199765832007e-22 - 2.85192607862128e-8im, 2.3325302606772615e-6 + 6.779174290855156e-21im, -2.9013097414966156e-19 + 0.000145066726682382im, -0.006211552288699764 + 2.415633906315482e-20im, -4.738429247128559e-19 - 0.14873309293232545im, 0.9776075958321915 + 3.843762790258654e-18im, -3.5633593303366556e-18 - 0.1483175839036248im, -0.011186845460023201 + 1.6821306983429548e-17im],))) + expected = (psi = ComplexF64[1.2158453522854604e-22 - 1.5600215111771384e-8im, 1.2996546815430964e-6 + 3.885628675702555e-21im, -1.7468084335288476e-19 + 8.315120652422862e-5im, -0.0037395947199757563 + 1.3680493596550602e-20im, -2.460767464239864e-19 - 0.09958393186897517im, 0.9900221149408975 + 3.621438010069551e-18im, -4.628194475677592e-18 - 0.09950068184912814im, -0.00498751125759044 + 1.6616361040202912e-17im],))) push!(DYNAMICS_GOLDEN_CASES, (name = "tdvp_evolve_nsite1", group = "Timeev", seed = 404, throws = nothing, - expected = (psi = ComplexF64[-0.00920276162744628 - 0.0024170841598647155im, -0.01637554442284315 - 0.16115067494666468im, 0.7696910929561378 - 0.14280497427087907im, 0.3847068235947162 - 0.1897707006300931im, -0.017726828121910013 + 0.0036191080773239244im, -0.4133873051773742 + 0.0026877630888292384im, 0.0049154337683140455 + 0.07234983376797594im, 0.010713283543799317 + 0.015646382672770916im],))) + expected = (psi = ComplexF64[-0.004072286897916106 + 6.79393844490242e-5im, -0.0020361428826548914 - 0.08124202172133772im, 0.8083520059990854 - 0.04068891628108989im, 0.4062104482469905 - 0.08124208966557822im, -0.0040688916275020415 + 8.092353176447631e-12im, -0.40621044881329343 + 0.00013574289660155114im, 3.395270414162637e-6 + 0.040688882300877346im, 0.0020378416504683227 - 6.794424049424985e-8im],))) push!(DYNAMICS_GOLDEN_CASES, (name = "apply_mpo_to_mps", group = "Timeev", seed = 405, throws = nothing, expected = (normalized = ComplexF64[-3.860460434409485e-17 - 2.3167305652416756e-18im, -3.386439716192975e-20 - 0.09901475429766764im, 0.9901475429766744 - 9.931034924197818e-19im, 2.0680926267789487e-21 - 0.09901475429766722im, 1.280512945972666e-35 + 8.013772651504016e-37im, -5.021684713522116e-23 + 3.342493350962204e-20im, -3.3424933509621976e-19 - 5.021684713522104e-22im, -5.0216847135220953e-23 + 3.34249335096219e-20im], unnormalized = ComplexF64[-3.8749021696585065e-17 - 2.339783178451268e-18im, -3.4201364637157006e-20 - 0.10000000000000026im, 1.0000000000000004 - 1.002985362599826e-18im, 2.088671169714006e-21 - 0.09999999999999984im, 1.3246250065770263e-35 + 8.100000165009719e-37im, -5.071652956311399e-23 + 3.375752810448521e-20im, -3.375752810448514e-19 - 5.071652956311387e-22im, -5.071652956311379e-23 + 3.375752810448506e-20im], norm_unnormalized = 1.0099504938362083))) @@ -191,25 +191,25 @@ push!(DYNAMICS_GOLDEN_CASES, (name = "evolve_with_propagator", group = "Timeev", expected = (normalized = ComplexF64[0.0 + 0.0im 0.0 + 0.0im 1.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im; -4.163336342344337e-17 - 1.6328224602610657e-18im 1.0388306928462953e-17 - 0.09901475429766758im 0.9901475429766743 + 1.0141504212207449e-16im 3.0031922513290032e-18 - 0.09901475429766722im 1.4294011305999016e-35 + 5.730534960258652e-37im -5.021684713522086e-23 + 3.3424933509622026e-20im -3.342493350962197e-19 - 5.021684713522071e-22im -5.021684713521819e-23 + 3.34249335096219e-20im; -0.009802979382130676 - 1.8705944963342314e-17im 4.0783339515249235e-17 - 0.1960595876426151im 0.9606919794488149 + 1.9975870024750033e-16im 3.6834881336005555e-17 - 0.19605958764261486im -0.00980297938213072 + 3.9189757260214785e-18im 1.0247732053383138e-19 - 1.8486149182358287e-15im -3.5947031642301997e-16 + 4.7095501640739e-21im 1.0143673990453503e-21 + 1.8778727277194854e-16im; -0.029113606554461303 - 5.898059818321144e-17im 6.938893903907228e-17 - 0.2882247048891685im 0.9122263387064593 + 2.662800535624399e-16im 7.025630077706069e-17 - 0.28822470488916796im -0.029113606554461532 + 4.445228907190568e-18im 3.0357660829594124e-18 + 0.0009704535518127483im -7.877401241376206e-16 - 4.117877623999526e-19im -2.4683140892599014e-19 + 3.5962496743479715e-16im], unnormalized = ComplexF64[0.0 + 0.0im 0.0 + 0.0im 1.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im; -4.336808689942018e-17 - 1.6490698500875163e-18im 1.0491675712523268e-17 - 0.10000000000000021im 1.0000000000000007 + 1.02424171873609e-16im 3.0330754973148008e-18 - 0.09999999999999987im 1.4294011305999016e-35 + 5.774615998414487e-37im -5.0716529563113703e-23 + 3.37575281044852e-20im -3.3757528104485145e-19 - 5.071652956311353e-22im -5.0716529563110994e-23 + 3.3757528104485073e-20im; -0.01000000000000006 - 2.7755575615628914e-17im 6.938893903907228e-17 - 0.20000000000000068im 0.9800000000000016 + 2.0404684886177193e-16im 2.3418766925686896e-17 - 0.19999999999999993im -0.00999999999999997 + 3.984442983884229e-18im 3.2526065174565133e-19 + 3.1320974459847495e-15im 6.223182759622941e-16 + 5.563063091184283e-20im 8.148289958272272e-21 + 5.12996633142156e-17im; -0.029999999999999888 - 6.9723092497118e-17im 9.786578547267268e-17 - 0.29700000000000043im 0.9400000000000017 + 2.277307610878724e-16im 5.3320186769396676e-17 - 0.29700000000000004im -0.02999999999999959 + 7.860991430341097e-18im 2.521762630645963e-18 + 0.0010000000000038173im 1.1618313384724398e-15 + 2.2747665951908703e-20im -1.1896537091744404e-19 + 6.851045528905009e-17im], norms_unnormalized = [1.0, 1.0099504938362085, 1.020098034504529, 1.0304460199350587], truncated = ComplexF64[0.0 + 0.0im 0.0 + 0.0im 0.7071067811865475 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.7071067811865475 + 0.0im 0.0 + 0.0im 0.0 + 0.0im; 0.016183143628432504 - 0.0005050768468250026im 0.004962314665086759 + 0.005192314613956749im 0.9078846593673016 - 0.028335132627037074im 0.2783890116052829 + 0.29129215514949885im 8.845380316321405e-5 - 0.0018029581917718433im 0.00062136038733793 - 0.0005050768468249957im 0.004962314665086842 - 0.10114710227958432im 0.0348587132732055 - 0.028335132627036876im; 0.0004528374794815198 - 0.020297793931012796im 0.004801655764467174 - 0.005608809060471993im 0.9321526294074961 - 0.05597557215379495im 0.2752570978215999 + 0.19890205967363717im -0.00223970046616855 - 0.00024315764131963165im -0.0005743994149798687 - 0.0005842007211631871im 0.002679301319112447 - 0.10358597894543947im 0.024608019884880112 - 0.028538684070391365im], nstates = 4))) push!(DYNAMICS_GOLDEN_CASES, (name = "evolve_with_tdvp_raw", group = "Timeev", seed = 407, throws = nothing, - expected = (states = ComplexF64[0.0 + 0.0im 0.0 + 0.0im 1.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im; -0.011186845460023196 - 6.298616611108218e-18im -5.248632856061594e-18 - 0.14831758390362507im 0.9776075958321918 - 2.4933314224230493e-18im -1.6184217914572034e-19 - 0.14873309293232548im -0.006211552288699638 + 1.3246610628849741e-18im 3.30820617875592e-20 + 0.00014506672668767811im 2.332530261961117e-6 - 4.431592130454869e-21im -6.928878867263853e-23 - 2.8519257619265872e-8im; -0.05939566282673919 - 3.4306979513644264e-18im -4.801255992659993e-17 - 0.328933936907805im 0.8810071526786496 - 1.1232561478361145e-18im 1.4278733237563712e-18 - 0.33035311560039154im -0.05419052282713331 + 6.477169246312338e-18im -4.5088577653193285e-20 + 0.0055724067443960095im 0.00041385071715082175 - 1.3246878153845069e-19im -8.239984028904836e-21 - 2.400536890757007e-5im; -0.14014090700692608 - 6.8154474299551196e-18im -5.658481112183792e-17 - 0.47041455375810826im 0.7191190553537727 + 6.714462026333761e-18im 4.595152032229356e-18 - 0.47304519941248707im -0.13267437170123583 + 9.924590931948863e-18im 8.644071657925445e-19 + 0.023554650833009394im 0.00304793096574568 - 6.846207106537829e-19im -6.994408477897236e-20 - 0.00031140067415395416im], nstates = 4))) + expected = (states = ComplexF64[0.0 + 0.0im 0.0 + 0.0im 1.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im; -0.004987511257590361 - 4.256244824910706e-18im -4.8779394610017105e-18 - 0.09950068184912828im 0.9900221149408974 - 1.758271761655908e-18im -5.506220035155005e-20 - 0.09958393186897514im -0.0037395947199759475 + 1.3323220194903071e-18im 3.329188972963432e-20 + 8.315120651544959e-5im 1.2996546806655269e-6 - 2.778993261489146e-21im -4.170312417752371e-23 - 1.560021503269989e-8im; -0.019800757011695487 - 5.885290700307777e-18im -2.596185115006721e-17 - 0.1960229572336232im 0.9603810388603901 - 2.181431582621343e-18im 2.2112597528739515e-19 - 0.19623190813175484im -0.018519818693988378 + 3.9619167282686535e-18im 1.4655513699454468e-19 + 0.00111472556738744im 4.885890317656899e-5 - 3.723287334633427e-20im -1.4614568170320214e-21 - 1.6782812305478658e-6im; -0.04399630386717385 - 3.894551703139737e-18im -4.9919305348653003e-17 - 0.28667713856252663im 0.9119624054804492 - 3.6684923624171546e-19im 1.3620241221455202e-18 - 0.2870224539985695im -0.042503060627599905 + 6.496172299960023e-18im 1.461653299867893e-19 + 0.004078233763764766im 0.0002880118236859822 - 1.2968732131990885e-19im -6.766319808171061e-21 - 1.6075621345392578e-5im], nstates = 4))) push!(DYNAMICS_GOLDEN_CASES, (name = "evolve_with_tdvp_nh_unnormalized", group = "Timeev", seed = 408, throws = nothing, - expected = (states = ComplexF64[0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 1.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im; 2.5185863793332767e-7 - 3.133246090027466e-18im 1.0770660761275833e-19 + 2.0124354544129934e-5im -0.0012058018242393435 + 1.816513980764623e-18im 1.0271400095713977e-18 - 0.04813564875797607im 0.9583805370608571 + 2.4261471340726103e-17im 7.23829256074296e-18 - 0.1441346949745543im -0.010807302793757757 + 2.5727740312238518e-17im 2.7411720051821824e-18 + 0.0005403748955406009im; 0.00015245730254686066 - 9.505455783165888e-18im 2.912961042969588e-18 + 0.0024144345226907405im -0.028653653368320254 + 1.1098041168128283e-17im -5.6711806278060074e-18 - 0.2250191466533221im 0.8569307683647844 + 4.258457588540048e-17im 2.7377444983996337e-17 - 0.31235430377097584im -0.05520610048520165 + 4.4534863619025824e-17im 8.895785963381632e-18 + 0.006496356950176086im; 0.001529504854564111 - 1.658196302513438e-17im 9.594390250959397e-18 + 0.013243485045048643im -0.08587033477355867 + 3.043260301451152e-17im -2.714337368917463e-17 - 0.36312423461347704im 0.6980861641392796 + 5.1612862638430043e-17im 5.699596733146827e-17 - 0.43734842117310896im -0.1245247553962922 + 5.218220923174905e-17im 1.3823947236309346e-17 + 0.02349001618979156im], norms = [1.0, 0.9704141636206739, 0.9415125968292468, 0.9132725677865249]))) + expected = (states = ComplexF64[0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 1.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im; 2.567537753088571e-7 - 3.1859896842252694e-18im 5.72537852056134e-20 + 2.051805903376956e-5im -0.0012296480518582372 + 1.85991093695779e-18im 4.252429963424243e-19 - 0.04910808942749657im 0.9789710707982199 + 1.2459633060943331e-17im 2.7324505609328044e-18 - 0.09801587906454175im -0.004898294272270104 + 1.3715111298880846e-17im 8.237272102442637e-19 + 0.00016320075919967883im; 2.052173998890074e-5 - 6.363781003935788e-18im 7.43377221554306e-19 + 0.0005447857622574906im -0.010844023501198782 + 4.0414044953454e-18im 1.8661793302840406e-19 - 0.14353924963461615im 0.940392362197431 + 2.3629196383994377e-17im 8.803901695663192e-18 - 0.19040347349617637im -0.019080563864080996 + 2.59166181255289e-17im 2.6285097881779194e-18 + 0.0012740571982997927im; 0.00015573123959473898 - 9.500080626236518e-18im 1.6744412054343565e-18 + 0.0024678387834416605im -0.029318325600582052 + 1.6475157968474265e-18im -1.7004478513181853e-18 - 0.23073085563146123im 0.8845713969798435 + 3.3110135514984334e-17im 1.7764165267179938e-17 - 0.274621567239137im -0.04153216597055702 + 3.580215754821976e-17im 5.1618344780121284e-18 + 0.004179735604485832im], norms = [1.0, 0.9851033483003095, 0.9704011412719077, 0.9558913949736177]))) push!(DYNAMICS_GOLDEN_CASES, (name = "evolve_with_tdvp_tbhamiltonian", group = "Timeev", seed = 409, throws = nothing, - expected = (states = ComplexF64[0.0 + 0.0im 0.7071067811865475 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 - 0.7071067811865475im 0.0 + 0.0im; -9.174762656251703e-17 - 0.042375518041909706im 0.7045631007419181 - 4.836439211269243e-17im 5.962969981537495e-18 - 0.04235046212911538im -0.0012458325551177307 + 2.455966422184375e-17im 9.32683903050589e-17 + 0.0012966984385507378im -0.04234969900347857 - 1.4023489520559867e-17im 8.468960886735421e-17 - 0.7045631099005252im -0.04237551813350933 + 1.9192592500453742e-16im; -1.8120078075499833e-16 - 0.08444624973411319im 0.6969548032527759 - 1.3321560441263254e-16im -6.577737560777005e-18 - 0.08424928353555482im -0.004863857603844601 + 1.067377411726475e-16im 1.4599165834137222e-16 + 0.005269686862545498im -0.08423709987984122 - 2.878869593702048e-17im 1.9660811425408665e-16 - 0.6969550958009804im -0.08444625558859076 + 4.389257558418702e-16im],))) + expected = (states = ComplexF64[0.0 + 0.0im 0.7071067811865475 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 - 0.7071067811865475im 0.0 + 0.0im; -1.6718761193372623e-16 - 0.02120684018975261im 0.7064705042545585 - 5.350870444371266e-17im 1.1100830675645562e-18 - 0.021203682643225086im -0.0003149213375100016 - 5.205877408081947e-17im 9.190254900773855e-17 + 0.0003212838667722099im -0.021203634922108274 - 1.101863829445276e-18im 1.501377078848448e-16 - 0.7064705045408939im -0.02120684019118434 + 1.3693199100791397e-16im; -3.111297149733956e-17 - 0.04237551804190931im 0.7045631007419183 - 1.4099703107814435e-16im -4.4064536142783134e-18 - 0.04235046212911519im -0.0012458325551176336 + 1.748286198429275e-17im 9.66107245555073e-18 + 0.0012966984385506598im -0.04234969900347918 - 1.5535647401470333e-17im 8.176257904352209e-17 - 0.7045631099005253im -0.042375518133509635 - 3.938326071442366e-17im],))) push!(DYNAMICS_GOLDEN_CASES, (name = "evolve_with_tdvp_timedep", group = "Timeev", seed = 410, throws = nothing, - expected = (normalized = ComplexF64[0.0 + 0.0im 0.0 + 0.0im 1.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im; -0.011186816737953336 + 2.5119001345576944e-5im -0.00038868466027668124 - 0.14831707121851204im 0.9776032123237354 - 0.002927921310731641im -0.0005013231219543594 - 0.14873224460770348im -0.006211513118417146 + 2.202002777181448e-5im 5.354471293571013e-7 + 0.00014506573518521953im 2.332513119221853e-6 - 8.927973079969787e-9im -1.1292590118343298e-10 - 2.8519048023356567e-8im; -0.05939400918189742 + 0.0004331247026457586im -0.0031543073635147607 - 0.3289186293439839im 0.8809453409736551 - 0.010448444052684894im -0.0046719914536121334 - 0.3303198881502035im -0.05418335141927872 + 0.000877993900783323im 0.00010122496587406914 + 0.0055714787094370034im 0.0004137664712611464 - 8.309124748579747e-6im -5.272602912144903e-7 - 2.3999518931421886e-5im; -0.14012349721296224 + 0.0021526201007521966im -0.009822351526687405 - 0.4703109664062515im 0.7188732480166135 - 0.01886602986495354im -0.014964232678659274 - 0.4728073553042303im -0.13258375279079693 + 0.00488267427136146im 0.000985706908260358 + 0.023533815833477592im 0.003044554444692907 - 0.00014269003860455996im -1.6121525978704344e-5 - 0.0003109786337795785im], unnormalized = ComplexF64[0.0 + 0.0im 0.0 + 0.0im 1.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im; -0.01103691132817287 + 4.963505400481112e-6im -7.664197553894716e-5 - 0.14599998178821746im 0.9601679436889661 - 0.0005761010387147744im -9.841004773815674e-5 - 0.14575053017868925im -0.006080614621870699 + 4.318045047393291e-6im 1.0490725021253388e-7 + 0.00014188418523892606im 2.2794861547987075e-6 - 1.747789578506272e-9im -2.2091057313207746e-11 - 2.7848530929689267e-8im; -0.05790444429442929 + 8.523688826765453e-5im -0.0006184147937381838 - 0.3189735777427292im 0.8498533687367171 - 0.0020396879395105988im -0.0009073366648056928 - 0.31699215679383375im -0.051761292188248445 + 0.0001697667242510921im 1.9492519483990037e-5 + 0.005299907270655853im 0.0003919973953360811 - 1.5937298500594265e-6im -1.0073760166444804e-7 - 2.2646396180089623e-5im], norms_unnormalized = [1.0, 0.9821613140079488, 0.9646474593560258]))) + expected = (normalized = ComplexF64[0.0 + 0.0im 0.0 + 0.0im 1.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im; -0.004987508669975323 + 4.977955815911505e-6im -0.0001241686371256542 - 0.09950060335034516im 0.990021005082587 - 0.0014825575802523481im -0.00017400999856131502 - 0.0995837788106844im -0.003739587827201953 + 7.1564336172979846e-6im 1.7122814985043176e-7 + 8.3151029087283e-5im 1.2996515259036912e-6 - 2.854579512996367e-9im -3.6337726688013575e-11 - 1.56001762150825e-8im; -0.019800631689661403 + 6.850934596925765e-5im -0.0009207813088570453 - 0.1960207621225673im 0.9603641650531627 - 0.005695292350301577im -0.0014059373115390226 - 0.1962268387940517im -0.018519172717466753 + 0.00015399238141099926im 1.0505124773411665e-5 + 0.001114675570822602im 4.885617677814247e-5 - 5.134733272786341e-7im -1.943591881165804e-8 - 1.6781675258983552e-6im; -0.04399500550836912 + 0.0003282306731510764im -0.0029533963158846002 - 0.2866617032849574im 0.9118840450943408 - 0.011965998341873103im -0.004576289042625271 - 0.28698574578828423im -0.04249557571318633 + 0.0007940261651013991im 8.714208699851e-5 + 0.004077293061359997im 0.0002879278380390095 - 6.917850543660634e-6im -4.2847220650634177e-7 - 1.6069848336060082e-5im], unnormalized = ComplexF64[0.0 + 0.0im 0.0 + 0.0im 1.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im; -0.004957686840533074 + 9.910417023586356e-7im -2.468687083707796e-5 - 0.09875725169843182im 0.981151847502961 - 0.00029434581455085467im -3.4493475572932383e-5 - 0.09854363206768935im -0.0036968321743424963 + 1.4171742537129257e-6im 3.3878205798152916e-8 + 8.212849771829617e-5im 1.2826114026720534e-6 - 5.643397290127712e-10im -7.1788794734716125e-12 - 1.5383312266761228e-8im; -0.01956485678598808 + 1.367028424165567e-5im -0.0001834132828565914 - 0.193104735199023im 0.9432481325917459 - 0.001131908542337971im -0.0002786407760086851 - 0.19215307144875385im -0.01808598828419767 + 3.044350493166107e-5im 2.0718865984378537e-6 + 0.0010858416959114272im 4.747581706462452e-5 - 1.0103654298724459e-7im -3.815732069596252e-9 - 1.6268436287963763e-6im], norms_unnormalized = [1.0, 0.9910404282661506, 0.9821617701679293]))) push!(DYNAMICS_GOLDEN_CASES, (name = "compute_basis_overlaps", group = "Timeev", seed = 411, throws = nothing, expected = (overlaps = ComplexF64[0.0 + 0.0im 0.0 + 0.0im 1.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im; -4.336808689942018e-17 - 1.6490698500875163e-18im 1.0491675712523268e-17 - 0.10000000000000021im 1.0000000000000007 + 1.02424171873609e-16im 3.0330754973148008e-18 - 0.09999999999999987im 1.4294011305999016e-35 + 5.774615998414487e-37im -5.0716529563113703e-23 + 3.37575281044852e-20im -3.3757528104485145e-19 - 5.071652956311353e-22im -5.0716529563110994e-23 + 3.3757528104485073e-20im; -0.01000000000000006 - 2.7755575615628914e-17im 6.938893903907228e-17 - 0.20000000000000068im 0.9800000000000016 + 2.0404684886177193e-16im 2.3418766925686896e-17 - 0.19999999999999993im -0.00999999999999997 + 3.984442983884229e-18im 3.2526065174565133e-19 + 3.1320974459847495e-15im 6.223182759622941e-16 + 5.563063091184283e-20im 8.148289958272272e-21 + 5.12996633142156e-17im], abs_overlaps = [0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0; 4.339942848340434e-17 0.10000000000000021 1.0000000000000007 0.09999999999999987 1.430567094250805e-35 3.3757566202134284e-20 3.3757566202134233e-19 3.375756620213416e-20; 0.01000000000000006 0.20000000000000068 0.9800000000000016 0.19999999999999993 0.00999999999999997 3.1320974628735105e-15 6.223182784487767e-16 5.1299663961340984e-17], probabilities = [0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0; 1.8835103926861277e-33 0.010000000000000044 1.0000000000000013 0.009999999999999974 2.0465222111531914e-70 1.139573275891479e-39 1.1395732758914753e-37 1.1395732758914704e-39; 0.00010000000000000118 0.04000000000000027 0.9604000000000033 0.03999999999999997 9.999999999999941e-5 9.810034516938682e-30 3.872800396914491e-31 2.631655522546507e-33], norms = [1.0, 1.0200000000000014, 1.0406000000000033]))) push!(DYNAMICS_GOLDEN_CASES, (name = "basis_amplitude", group = "Timeev", seed = 412, throws = nothing, - expected = (amplitudes = ComplexF64[-0.09621581007161992 - 2.331393520394121e-17im, 2.8403799357418994e-19 - 0.4056589151515193im, 0.8060762386451591 - 9.536769591192529e-18im, -1.9958383051746824e-18 - 0.4166299624633396im, -0.05319592260288309 + 3.748198897937057e-18im, 2.777648128304502e-19 + 0.0037543369833384407im, 0.00018178926822903332 - 1.1451860059147535e-19im, -5.397816681663427e-21 - 6.687975313222357e-6im],))) + expected = (amplitudes = ComplexF64[-0.043995675199517754 - 1.7089627067966986e-17im, 4.570985276460965e-18 - 0.28666483200872306im, 0.9117781020543121 - 6.605361657405849e-18im, -7.462933344970057e-19 - 0.2888946255113825im, -0.03291451257213042 + 3.912841432612483e-18im, 2.9194709265103003e-19 + 0.002206062222770084im, 0.0001037093164542626 - 7.373547736181594e-20im, -3.3304828604816472e-21 - 3.7429601752491264e-6im],))) push!(DYNAMICS_GOLDEN_CASES, (name = "phase_aligned_distance", group = "Timeev", seed = 413, throws = nothing, - expected = (d01 = 0.8164227268227637, d_scaled = 0.8164227268227637, d_zero = Inf))) + expected = (d01 = 0.555727576996291, d_scaled = 0.555727576996291, d_zero = Inf))) push!(DYNAMICS_GOLDEN_CASES, (name = "rk4_step_dm_timedep", group = "Timeev", seed = 414, throws = nothing, expected = (truncated = ComplexF64[7.812500001546395e-7 + 7.828663033771813e-19im 8.789062513261771e-10 - 3.255208333351538e-5im -0.0006652343740496785 - 3.37890625057409e-8im -5.292968751644172e-8 + 0.0006016927058446336im -3.098958333333776e-5 - 3.80859374382286e-9im 5.892408520376182e-17 - 7.812500001840115e-7im 8.985137226035288e-17 + 3.7730552092358375e-17im -3.608507228938031e-17 + 1.1941396375008241e-16im; 8.789062432952351e-10 + 3.255208333343369e-5im 0.0013101562498536415 - 2.7686623743118185e-18im 6.779296874072027e-7 - 0.026807291656854117im -0.024251041617815754 - 1.5236328116953764e-6im 1.0937499996247166e-7 - 0.0012460937450196295im 3.151041666660097e-5 + 3.808593670875125e-9im -4.9796461919960424e-18 + 5.20833333001248e-7im 5.7465408668161e-16 - 4.2982423426493997e-17im; -0.0006652343740491491 + 3.378906254570683e-8im 6.779296874280017e-7 + 0.026807291656854748im 0.5485640624942875 - 2.1537145565545178e-18im 1.864062499572192e-5 - 0.4962578121504889im 0.025498958282574643 + 1.5861328116873737e-6im -5.6445312554387505e-8 + 0.0006432291641779511im -1.0807291666728579e-5 - 1.2695311788067276e-9im 3.4068208699627984e-17 - 1.302083334709161e-7im; -5.292968753170732e-8 - 0.0006016927058453136im -0.024251041617814995 + 1.5236328116765189e-6im 1.864062499571872e-5 + 0.496257812150489im 0.4489390625060064 - 2.0552920284012612e-17im -5.68554687355567e-7 + 0.023067708325568495im -0.0005817708323828106 - 2.8710937487551183e-8im 8.789062972536364e-10 - 9.76562499995574e-6im 1.3020833346016022e-7 - 4.290233071760157e-17im; -3.098958333337169e-5 + 3.808593754318883e-9im 1.0937499998627083e-7 + 0.001246093745019287im 0.02549895828257476 - 1.5861328116696463e-6im -5.685546873657465e-7 - 0.023067708325568412im 0.0011851562498534126 + 3.1449156118893055e-18im -8.789062685652463e-10 + 2.9947916668884763e-5im -5.208333325878654e-7 + 3.157181943443593e-17im -2.2690149801382557e-17 + 7.01088101595345e-16im; 3.1120612521943634e-17 + 7.812499998212374e-7im 3.151041666654408e-5 - 3.808593732134098e-9im -5.644531248413814e-8 - 0.0006432291641786381im -0.0005817708323822479 + 2.8710937500230628e-8im -8.789063986768197e-10 - 2.994791666472071e-5im 7.812500003259077e-7 + 1.059582698198789e-15im 1.0855535322943259e-16 + 9.941394386792425e-15im -3.7725181629883064e-15 + 4.45046679785529e-16im; -4.725590952589523e-16 - 2.9476770988494356e-17im 5.559535364902561e-17 - 5.208333330150864e-7im -1.0807291667014608e-5 + 1.2695311807091001e-9im 8.789062592478671e-10 + 9.765624999733837e-6im -5.208333293033292e-7 + 3.859740532325664e-16im 1.283293169018773e-15 - 6.499275377567095e-15im 3.2292144445618815e-15 + 3.186403684246132e-16im -1.9546481582399423e-15 + 4.1910275373014925e-15im; -2.000076077492902e-17 + 4.564066570899162e-16im -5.80457687451473e-16 + 1.4761913269604708e-17im -6.178503266131759e-18 + 1.3020833357512826e-7im 1.3020833384544e-7 + 5.343440400179781e-17im 3.950316162383726e-16 - 3.961911810355959e-15im 5.291853465620903e-15 - 1.382132217493173e-16im -1.8105499900515692e-15 - 3.122793059504776e-15im -5.756535925965681e-15 - 4.215691744931907e-16im], untruncated = ComplexF64[7.812500001348455e-7 - 3.817762682220055e-18im 5.566406255968917e-9 - 3.2552083333513324e-5im -0.000665234329518352 - 2.369140624231081e-7im -4.1855468743509643e-7 + 0.0006016925523290584im -3.0989583333320766e-5 - 2.7246093750295486e-8im 2.9163238494847154e-17 - 7.812500001131047e-7im 8.633366063480177e-18 + 1.613208017026414e-17im -2.3302357869714034e-17 + 2.812879950801284e-17im; 5.566406266234249e-9 + 3.25520833333725e-5im 0.0013101562381348153 - 1.6875940372706733e-18im 4.793554641865628e-6 - 0.026807291076775305im -0.02425103831078383 - 1.2539257182503555e-5im 8.593749999831059e-7 - 0.0012460934379884005im 3.1510416666725355e-5 + 2.7246093753873277e-8im 1.575187059955461e-16 + 5.208333330108439e-7im 2.3045542830816585e-16 - 1.605702683382695e-16im; -0.0006652343295178544 + 2.3691406241891487e-7im 4.7935546418420145e-6 + 0.02680729107677576im 0.5485640616153802 - 7.48674548712753e-17im 0.00016789062179437016 - 0.49625778420127004im 0.025498954886481136 + 1.2976757183534797e-5im -4.4082031270817806e-7 + 0.0006432290106622354im -1.0807291666753276e-5 - 9.082030983846322e-9im -8.071841416300176e-18 - 1.3020833337031993e-7im; -4.1855468745546545e-7 - 0.0006016925523296256im -0.024251038310783245 + 1.2539257182542616e-5im 0.00016789062179430845 + 0.49625778420127054im 0.44893906340835105 - 1.7943959652397462e-17im -3.934179643001126e-6 + 0.023067707921271313im -0.0005817707878511916 - 2.0058593760120424e-7im 5.566406254734363e-9 - 9.765624999970437e-6im 1.3020833338597832e-7 - 2.7721999792807093e-16im; -3.098958333335061e-5 + 2.7246093738771083e-8im 8.593749999708287e-7 + 0.0012460934379876377im 0.025498954886481347 - 1.2976757183586541e-5im -3.934179642969821e-6 - 0.02306770792127104im 0.0011851562381346911 - 5.236769739731321e-18im -5.566406222168051e-9 + 2.994791667610757e-5im -5.208333384620471e-7 - 3.184022579559882e-17im 4.678296510099319e-17 - 5.142661547437696e-15im; 3.8137234933651246e-17 + 7.812499993310696e-7im 3.1510416666569596e-5 - 2.7246093745561535e-8im -4.4082031254334333e-7 - 0.0006432290106640603im -0.0005817707878494695 + 2.0058593770206893e-7im -5.566406225877245e-9 - 2.994791665729078e-5im 7.812500010315546e-7 + 2.6493095268584323e-16im 9.255173531772838e-17 + 2.5217376222039623e-14im -3.106064987221812e-14 - 2.0589963987560548e-16im; -5.295741869269865e-16 - 8.372974781295776e-18im 2.564079167849628e-16 - 5.208333332056605e-7im -1.0807291666604981e-5 + 9.082030995107412e-9im 5.5664061849885525e-9 + 9.765624999517586e-6im -5.208333273679067e-7 + 1.4554044189162603e-17im 6.297155758759884e-17 + 2.262980064088635e-16im -3.810151224961604e-15 - 7.666728973874657e-17im 2.848260725654927e-16 + 7.608525706010966e-15im; -3.216715804174629e-17 + 5.122327457588751e-16im -2.0472470475129194e-16 + 1.8242709303543758e-16im -8.302816589027492e-17 + 1.3020833383091527e-7im 1.3020833369678856e-7 + 2.6675882090693133e-16im 3.7291804018181406e-17 - 5.893804581012907e-15im 5.159673523485299e-15 - 3.954844793782288e-17im 3.0977169436090556e-16 - 7.29708707378671e-15im -3.321257943043266e-15 + 6.37614910389396e-17im], maxdim2 = ComplexF64[6.501940602090297e-5 + 5.843005848411471e-18im -3.935903113782434e-8 - 0.0002090851583797917im -0.0022647514604215886 - 1.2204144757401563e-5im -9.679366147059597e-7 + 0.014028950691627616im -2.1445035714081937e-8 + 2.583775943528358e-6im 1.0731107673247392e-6 + 3.997309506098958e-8im -0.012614453464996143 - 9.773561210066654e-5im -4.802931024582157e-5 + 0.005804250432094027im; -3.9359031126546175e-8 + 0.0002090851583802982im 0.0003355281367283294 + 8.312141579263691e-18im 7.447026015846931e-6 - 0.014028955326403678im -0.024355976865310436 + 2.8207200567031867e-6im -1.0731011068525308e-6 - 3.909286642885141e-8im -5.5400157671158494e-8 - 2.54780584374705e-7im 4.404496931192508e-5 - 0.005804280711712374im 0.0001825183196821959 - 5.881949638142732e-7im; -0.0022647514604213492 + 1.2204144756500136e-5im 7.447026016894716e-6 + 0.014028955326363697im 0.5489218288529895 + 1.7515899030508225e-16im 1.911199807838e-5 - 0.4965483987425975im 0.012615593014142433 + 4.8752408870669725e-6im 3.1864210663039036e-6 - 0.005809166278036842im -9.232730765974101e-5 - 5.563215190304687e-7im -3.5886310316602344e-7 + 8.351876498027784e-5im; -9.679366157084537e-7 - 0.014028950691668193im -0.024355976865311206 - 2.8207200578112943e-6im 1.91119980787689e-5 + 0.49654839874261686im 0.45022936907050826 + 1.625755127307084e-16im 7.958548085378505e-7 + 0.0058091683984297345im -0.00017431420413035822 - 2.0385455957875763e-6im 3.524342531429449e-7 - 8.351888548280547e-5im -7.572860487047444e-5 - 1.7912517515429852e-7im; -2.1445036531073597e-8 - 2.583775943525079e-6im -1.0731011068560896e-6 + 3.9092866622277395e-8im 0.012615593014143396 - 4.87524088747089e-6im 7.958548089595778e-7 - 0.00580916839844859im 3.555270048517865e-12 - 5.233424371845666e-22im -3.3422718817379146e-16 - 4.869600324780517e-12im -8.431806803468434e-11 + 1.1442447134144218e-8im 5.267057956696857e-9 + 2.83567924483408e-10im; 1.073110767319638e-6 - 3.997309525455074e-8im -5.5400157317144144e-8 + 2.547805843732661e-7im 3.1864210658612192e-6 + 0.005809166278018987im -0.00017431420413026533 + 2.0385455951991412e-6im -3.3422688545753955e-16 + 4.8696003247859755e-12im 6.0213339376135204e-12 + 1.7581653375120835e-22im -5.266949992510467e-9 - 2.79954882214093e-10im -4.550555245125071e-10 - 1.617829866423945e-10im; -0.01261445346499558 + 9.773561210106604e-5im 4.4044969311628766e-5 + 0.005804280711730431im -9.232730765994873e-5 + 5.563215190310261e-7im 3.524342531441862e-7 + 8.351888548302513e-5im -8.431806952830565e-11 - 1.1442447134138048e-8im -5.266949992524318e-9 + 2.799548829003644e-10im 1.0228441366631057e-8 - 1.7391174264821127e-23im 3.5609004072212776e-13 - 9.252664775472423e-9im; -4.802931024524765e-5 - 0.005804250432075349im 0.00018251831968229754 + 5.881949644023506e-7im -3.5886310316630857e-7 - 8.351876498050403e-5im -7.572860487071057e-5 + 1.7912517515501244e-7im 5.267057956676929e-9 - 2.835679251710625e-10im -4.550555244919356e-10 + 1.617829866426138e-10im 3.560900408159912e-13 + 9.252664775472784e-9im 8.389687689896142e-9 - 6.013369486057495e-23im]))) diff --git a/test/data/generate_gpu_golden.jl b/test/data/generate_gpu_golden.jl index f1988ee..9db6639 100644 --- a/test/data/generate_gpu_golden.jl +++ b/test/data/generate_gpu_golden.jl @@ -35,7 +35,13 @@ # JULIA_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 julia --project=. test/data/generate_gpu_golden.jl # # The output is deterministic up to GPU rounding: cases in a fixed order, no -# timestamps. +# timestamps. Because of that rounding (and CUDA runtime updates) a full rerun moves +# every stored value a little, so a change that moves a few cases should rerun only +# those, keeping the stored entries of all others: +# +# ... generate_gpu_golden.jl --only state_traj_real_point_all_c64,state_traj_abs_block_c64 +# +# The header then records the tree of the partial rerun and the cases it reran. using TensorBinding, ITensors, ITensorMPS, LinearAlgebra, Test, Random using CUDA @@ -48,6 +54,11 @@ const R = GPUGoldenRunner const OUTFILE = joinpath(@__DIR__, "gpu_golden.jl") +# `--only name1,name2,…`: rerun these cases, keep the stored entries of the others. +const ONLY = let i = findfirst(==("--only"), ARGS) + i === nothing ? nothing : Set(String.(split(ARGS[i + 1], ','))) +end + function evaluate(c) t0 = time() gpu = R.run_gpu(c) @@ -68,25 +79,41 @@ function evaluate(c) return (name = c.name, gpu = gpu, cpu = cpu) end +# The git tree hash of the working-tree src/ (through a throwaway index, as in +# generate_dynamics_golden.jl): the src/ of the commit that will hold the data. Up to +# v0.2.0 it was HEAD's src/ tree, marked "(plus uncommitted changes)" when src/ was dirty. function src_tree() repo = normpath(joinpath(@__DIR__, "..", "..")) + index = tempname() try - dirty = !isempty(readchomp(`git -C $repo status --porcelain -- src`)) - tree = readchomp(`git -C $repo rev-parse --short=12 HEAD:src`) - return dirty ? "$tree (plus uncommitted changes)" : tree + tree = withenv("GIT_INDEX_FILE" => index) do + run(`git -C $repo read-tree HEAD`) + run(`git -C $repo add -A -- src`) + readchomp(`git -C $repo write-tree --prefix=src/`) + end + return first(tree, 12) catch return "unknown" + finally + rm(index; force = true) end end -function write_golden(path, entries) +function write_golden(path, entries; header = nothing) dev = CUDA.name(CUDA.device()) open(path, "w") do io println(io, "# AUTO-GENERATED by test/data/generate_gpu_golden.jl -- do not edit by hand.") println(io, "#") println(io, "# Pinned outputs of the GPU entry points (src/gpu/*.jl), checked by") - println(io, "# test/golden_gpu.jl. Generated from src/ tree ", src_tree()) - println(io, "# with Julia ", VERSION, ", CUDA.jl ", pkgversion(CUDA), " on ", dev, ".") + if header === nothing + println(io, "# test/golden_gpu.jl. Generated from src/ tree ", src_tree()) + println(io, "# with Julia ", VERSION, ", CUDA.jl ", pkgversion(CUDA), " on ", dev, ".") + else + # a partial rerun (--only): the previous file's generation lines, then this rerun + foreach(l -> println(io, l), header) + println(io, "# Rerun with --only from src/ tree ", src_tree(), " with Julia ", VERSION, ",") + println(io, "# CUDA.jl ", pkgversion(CUDA), " on ", dev, ": ", join(sort!(collect(ONLY)), ", "), ".") + end println(io, "# Regenerate only for an intentional behaviour change; see the generator's header.") println(io, "#") println(io, "# Each entry is (name, gpu, cpu): `gpu` is the GPU output of the case of that") @@ -115,8 +142,26 @@ function same_exactly(a, b) end t_all = time() -entries = [evaluate(c) for c in R.CASES] -write_golden(OUTFILE, entries) +if ONLY === nothing + entries = [evaluate(c) for c in R.CASES] + write_golden(OUTFILE, entries) +else + names = [c.name for c in R.CASES] + unknown = setdiff(ONLY, names) + isempty(unknown) || error("--only: no such case(s): ", join(sort!(collect(unknown)), ", ")) + # the generation lines of the file being updated (lines 4 to the one before the + # "Regenerate only" line), so that the header keeps saying where the kept entries come from + lines = readlines(OUTFILE) + stop = findfirst(startswith("# Regenerate only"), lines) + header = lines[4:stop - 1] + stored = Dict(e.name => e for e in include(OUTFILE)) + missing_names = setdiff(setdiff(names, ONLY), keys(stored)) + isempty(missing_names) || error("--only: no stored entry for ", join(missing_names, ", "), + "; rerun those cases too, or run without --only") + entries = [c.name in ONLY ? evaluate(c) : (name = c.name, gpu = stored[c.name].gpu, cpu = stored[c.name].cpu) + for c in R.CASES] + write_golden(OUTFILE, entries; header = header) +end loaded = include(OUTFILE) length(loaded) == length(entries) || error("round trip: $(length(loaded)) entries read back, $(length(entries)) written") diff --git a/test/data/gpu_golden.jl b/test/data/gpu_golden.jl index 26dd8db..76714d8 100644 --- a/test/data/gpu_golden.jl +++ b/test/data/gpu_golden.jl @@ -3,6 +3,8 @@ # Pinned outputs of the GPU entry points (src/gpu/*.jl), checked by # test/golden_gpu.jl. Generated from src/ tree f88be17b7f31 (plus uncommitted changes) # with Julia 1.12.3, CUDA.jl 5.9.5 on NVIDIA GeForce RTX 4060 Laptop GPU. +# Rerun with --only from src/ tree 79984c1eef99 with Julia 1.12.3, +# CUDA.jl 5.9.5 on NVIDIA GeForce RTX 4060 Laptop GPU: state_traj_abs_block_c64, state_traj_abs_pointavg_abs_c64, state_traj_imag_xgroups_normalize_mpo_c64, state_traj_probability_pointavg_abs2_c64, state_traj_real_point_all_c64. # Regenerate only for an intentional behaviour change; see the generator's header. # # Each entry is (name, gpu, cpu): `gpu` is the GPU output of the case of that @@ -67,24 +69,24 @@ push!(GPU_GOLDEN_CASES, (name = "nh_density_traj_xgroups_c64", cpu = (density = [0.0 0.0047905729166667545; 1.0 0.9417233983333337; 0.0 6.213270103522349e-16], times = [0.0, 0.1]))) push!(GPU_GOLDEN_CASES, (name = "state_traj_real_point_all_c64", - gpu = (amplitude = [0.0 -0.05580450890501805 -0.12782145439551518; 0.0 5.369642314050414e-18 -7.018005760922292e-17; 1.0 0.8132723041446014 0.6378003016059953; 0.0 -7.063242776566961e-17 -5.846540347604278e-17; 0.0 -0.049209356271257915 -0.11456097140005932; 0.0 -5.155700764739601e-17 4.782242080525976e-17; 0.0 0.00037059688204394385 0.0025676777871032888; 0.0 -9.613053120885777e-19 1.0215032166937036e-17], times = [0.0, 0.2, 0.30000000000000004], centers = [1, 2, 3, 4, 5, 6, 7, 8], groups = [[1], [2], [3], [4], [5], [6], [7], [8]], norms = [1.0, 0.9231346655392004, 0.8870230313131474], maxlinkdims = [1, 2, 2]), - cpu = (amplitude = [0.0 -0.05580450890501752 -0.12782145439551473; 0.0 -4.025634661746592e-17 -6.135797698578847e-17; 1.0 0.8132723041446015 0.6378003016059955; 0.0 -1.193052230984447e-17 -2.507349247581188e-17; 0.0 -0.04920935627125796 -0.11456097140005948; 0.0 -1.777457354371954e-17 -7.996321603922599e-17; 0.0 0.0003705968820439737 0.002567677787103318; 0.0 9.158816035326546e-18 2.3187869854288752e-17], times = [0.0, 0.2, 0.30000000000000004], norms = [1.0, 0.9231346655392004, 0.8870230313131481]))) + gpu = (amplitude = [0.0 -0.01921610103543754 -0.04206399215009756; 0.0 -3.901529973046889e-17 -4.808785970974393e-17; 1.0 0.9227237989509299 0.8588529251664152; 0.0 -1.325621555426338e-16 -1.7592862427491296e-16; 0.0 -0.01762538132763919 -0.039446061189716344; 0.0 2.660380019386328e-18 1.8028456587286972e-17; 0.0 4.611252770965475e-5 0.00026366664599559867; 0.0 5.525265386312854e-18 9.228516706675508e-18], times = [0.0, 0.2, 0.30000000000000004], centers = [1, 2, 3, 4, 5, 6, 7, 8], groups = [[1], [2], [3], [4], [5], [6], [7], [8]], norms = [1.0, 0.960791409702533, 0.9417741664025726], maxlinkdims = [1, 2, 2]), + cpu = (amplitude = [0.0 -0.019216101035437718 -0.04206399215009761; 0.0 3.743781054945763e-18 -6.232415927956855e-18; 1.0 0.9227237989509307 0.8588529251664166; 0.0 -4.649015294629224e-17 -3.2435629560430705e-17; 0.0 -0.01762538132763918 -0.03944606118971637; 0.0 -3.789262070369216e-17 1.9888420610780686e-17; 0.0 4.611252770964527e-5 0.0002636666459955881; 0.0 3.790409076491257e-18 6.927028808284709e-18], times = [0.0, 0.2, 0.30000000000000004], norms = [1.0, 0.9607914097025333, 0.9417741664025739]))) push!(GPU_GOLDEN_CASES, (name = "state_traj_imag_xgroups_normalize_mpo_c64", - gpu = (amplitude = [0.0 -0.07443752554147598 -0.16591071177391867; 0.0 -2.912483128308583e-16 -2.6434807068189437e-16; 0.0 4.8010269669404526e-5 0.0018065061587984909], times = [0.0, 0.1, 0.2], centers = [1, 3, 6], groups = [[1, 2], [3], [6, 7, 8]], norms = [1.0, 1.0, 0.9999999999999996], maxlinkdims = [1, 2, 2]), - cpu = (amplitude = [0.0 -0.07443752554147588 -0.16591071177391883; 0.0 1.126090372528129e-16 1.167757083817526e-16; 0.0 4.8010269669380525e-5 0.0018065061587984842], times = [0.0, 0.1, 0.2], norms = [1.0, 1.0, 1.0]))) + gpu = (amplitude = [0.0 -0.049874917126394115 -0.0985029465442281; 0.0 -2.688990758272416e-16 -2.60967008323288e-16; 0.0 2.7556426553135622e-5 0.0003659536587201629], times = [0.0, 0.1, 0.2], centers = [1, 3, 6], groups = [[1, 2], [3], [6, 7, 8]], norms = [1.0, 1.0000000000000002, 1.0000000000000002], maxlinkdims = [1, 2, 2]), + cpu = (amplitude = [0.0 -0.04987491712639407 -0.09850294654422799; 0.0 6.151184077184959e-17 6.748749491222514e-17; 0.0 2.75564265531104e-5 0.0003659536587201418], times = [0.0, 0.1, 0.2], norms = [1.0, 1.0, 1.0]))) push!(GPU_GOLDEN_CASES, (name = "state_traj_abs_block_c64", - gpu = (amplitude = [0.0 0.07172351625361666 0.15567879479430713; 0.5 0.4750014203926977 0.4338165280424836; 0.0 0.002968415764654881 0.024732591435238625; 0.0 1.1113140620386017e-6 0.0001856057578687311], times = [0.0, 0.1, 0.2], centers = [2, 4, 6, 8], groups = [[2], [4], [6], [8]], norms = [1.0, 0.9607901407742484, 0.9231346655392004], maxlinkdims = [1, 2, 2]), - cpu = (amplitude = [0.0 0.0717235162536166 0.15567879479430718; 0.5 0.47500142039269755 0.4338165280424838; 0.0 0.0029684157646548753 0.024732591435238635; 0.0 1.111314062072125e-6 0.00018560575786875068], times = [0.0, 0.1, 0.2], norms = [1.0, 0.9607901407742481, 0.9231346655392004]))) + gpu = (amplitude = [0.0 0.04894901955060188 0.0951272452853345; 0.5 0.48764544951887107 0.47080027336810637; 0.0 0.0018256002389247876 0.008828505438164543; 0.0 6.325622258632611e-7 2.3069752963418967e-5], times = [0.0, 0.1, 0.2], centers = [2, 4, 6, 8], groups = [[2], [4], [6], [8]], norms = [1.0, 0.9801988038516668, 0.960791409702533], maxlinkdims = [1, 2, 2]), + cpu = (amplitude = [0.0 0.048949019550601824 0.09512724528533449; 0.5 0.48764544951887107 0.47080027336810676; 0.0 0.001825600238924786 0.008828505438164559; 0.0 6.325622258548236e-7 2.306975296341345e-5], times = [0.0, 0.1, 0.2], norms = [1.0, 0.9801988038516669, 0.9607914097025333]))) push!(GPU_GOLDEN_CASES, (name = "state_traj_probability_pointavg_abs2_c64", - gpu = (amplitude = [0.0 0.010288525567565635 0.04847177429721601; 0.5 0.45125269875016066 0.37639356000567004; 0.0 1.76229843037032e-5 0.0012234021582048756; 0.0 2.470037888973841e-12 6.889899470805224e-8], times = [0.0, 0.1, 0.2], centers = [1, 3, 5, 7], groups = [[1, 2], [3, 4], [5, 6], [7, 8]], norms = [1.0, 0.9607901407742484, 0.9231346655392004], maxlinkdims = [1, 2, 2]), - cpu = (amplitude = [0.0 0.010288525567565607 0.04847177429721602; 0.5 0.45125269875016033 0.3763935600056702; 0.0 1.762298430370317e-5 0.0012234021582048782; 0.0 2.4700378891128086e-12 6.889899470806351e-8], times = [0.0, 0.1, 0.2], norms = [1.0, 0.9607901407742481, 0.9231346655392004]))) + gpu = (amplitude = [0.0 0.004792013029930416 0.018098385591152403; 0.5 0.4755961688729237 0.44330579480696736; 0.0 6.665632464724479e-6 0.00015588501654340188; 0.0 8.002699391751239e-13 1.0644270035861395e-9], times = [0.0, 0.1, 0.2], centers = [1, 3, 5, 7], groups = [[1, 2], [3, 4], [5, 6], [7, 8]], norms = [1.0, 0.9801988038516668, 0.960791409702533], maxlinkdims = [1, 2, 2]), + cpu = (amplitude = [0.0 0.00479201302993041 0.018098385591152406; 0.5 0.4755961688729237 0.44330579480696813; 0.0 6.665632464724464e-6 0.00015588501654340172; 0.0 8.002699391548472e-13 1.0644270035856998e-9], times = [0.0, 0.1, 0.2], norms = [1.0, 0.9801988038516669, 0.9607914097025333]))) push!(GPU_GOLDEN_CASES, (name = "state_traj_abs_pointavg_abs_c64", - gpu = (amplitude = [0.5 0.5411563725839384; 0.0 2.2224624482887625e-6], times = [0.0, 0.1], centers = [2, 7], groups = [[2, 3], [7]], norms = [1.0, 0.9607901407742484], maxlinkdims = [1, 2]), - cpu = (amplitude = [0.5 0.5411563725839382; 0.0 2.2224624483511753e-6], times = [0.0, 0.1], norms = [1.0, 0.9607901407742481]))) + gpu = (amplitude = [0.5 0.5340965117309775; 0.0 1.2650335643099033e-6], times = [0.0, 0.1], centers = [2, 7], groups = [[2, 3], [7]], norms = [1.0, 0.9801988038516668], maxlinkdims = [1, 2]), + cpu = (amplitude = [0.5 0.5340965117309775; 0.0 1.265033564293894e-6], times = [0.0, 0.1], norms = [1.0, 0.9801988038516669]))) push!(GPU_GOLDEN_CASES, (name = "state_traj_bad_component_throws", gpu = (exception = :ErrorException, message_prefix = "get_state_amplitude_trajectory_gpu: unsupported component :p"), From a5f4f8bc0efbb74bdd25913de8af4a7603f59dfd Mon Sep 17 00:00:00 2001 From: Anouar Moustaj Date: Fri, 13 Nov 2026 00:43:34 +0200 Subject: [PATCH 07/22] Build the BdG hole block as -H*, not tau_z (x) H In the Nambu basis (c_up, c_dn, c+_up, c+_dn) of the package, the one in which the singlet pairing is i sigma_y (x) Delta, the hole block of a normal-state term H is -H*. add_superconductivity!, bdg_hamiltonian, bdg_spin_hamiltonian and the equal-spin triplet BdG of the SCF (_triplet_equalspin_bdg) built tau_z (x) H, whose hole block -H is wrong whenever H has imaginary entries (a Zeeman field along y, Peierls phases, complex hoppings); add_zeeman! and add_soc! on a Hamiltonian that already had a Nambu index lifted their terms the same way. An L = 2 spinful chain with h = 0.3 along y and Delta = 0.25 had a BdG spectrum off by 1.4e-2. Two helpers in core/AuxDOF.jl build Pp (x) M + Ph (x) (-M*) (dag conjugates each tensor and keeps the primes): _nambu_normal_block for the doubling, _lift_normal_term for a term added afterwards. A real M (every imaginary part exactly zero) still gets the one-term tau_z (x) M of v0.2.0, so every result with a real Hamiltonian is unchanged bit for bit: all 4127 golden tests pass against unchanged data. The bdg_spin_hamiltonian docstring named the basis (c_up, c_dn, c+_dn, -c+_up), in which its i sigma_y pairing would vanish; it now names the basis the code uses. New test (22 checks): dense BdG matrices against [H D; D' -conj(H)] for Zeeman fields along x, y, z, for bdg_hamiltonian and bdg_spin_hamiltonian with complex kinetic terms and for the triplet SCF builder with a complex H0; a Zeeman or y-SOC term added after the doubling gives the same matrix as before it; the real path is the tau_z build. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 13 ++++ src/core/AuxDOF.jl | 67 +++++++++++++++------ src/physics/SCF.jl | 6 +- src/physics/Supercond.jl | 37 ++++++++---- test/bugfix_bdg_hole_block.jl | 108 ++++++++++++++++++++++++++++++++++ test/runtests.jl | 1 + 6 files changed, 200 insertions(+), 32 deletions(-) create mode 100644 test/bugfix_bdg_hole_block.jl diff --git a/CHANGELOG.md b/CHANGELOG.md index d943d4b..eae6626 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,6 +53,19 @@ bugs without breaking the API. and the five `state_traj_*` cases of `test/data/gpu_golden.jl` (with the new `--only` option of its generator, which reruns the named cases and keeps every other stored entry). +- **BdG hole block is `−H*`.** In the Nambu basis `(c↑, c↓, c†↑, c†↓)` of the package + (singlet pairing `iσ_y ⊗ Δ`) the hole block of a normal-state term `H` is `−H*`, but + `add_superconductivity!`, `bdg_hamiltonian`, `bdg_spin_hamiltonian` and the + equal-spin triplet BdG of the SCF built `τ_z ⊗ H`, whose hole block `−H` is wrong + whenever `H` has imaginary entries: a Zeeman field along y, Peierls phases, complex + hoppings. `add_zeeman!` and `add_soc!` on a Hamiltonian that already has a Nambu index + lifted their term the same way, so a y-field added after the doubling was wrong too. + On an L = 2 spinful chain with `h = 0.3` along y and `Δ = 0.25`, the BdG spectrum was + off by 1.4e-2. They now build `P_p ⊗ H + P_h ⊗ (−H*)`; a real `H` still gets the + one-term `τ_z ⊗ H` it got before, so every result with a real Hamiltonian is unchanged + bit for bit (no golden case moves). The `bdg_spin_hamiltonian` docstring named the basis + `(c↑, c↓, c†↓, −c†↑)`, in which its `iσ_y` pairing would vanish; it now names the basis + the code uses. ### Fixed diff --git a/src/core/AuxDOF.jl b/src/core/AuxDOF.jl index 4f17175..5d0eb74 100644 --- a/src/core/AuxDOF.jl +++ b/src/core/AuxDOF.jl @@ -249,6 +249,37 @@ function _lift_to_aux_sites(H, M::MPO, ops::AbstractDict) return M end +# True when every tensor of M holds real numbers (imaginary parts exactly zero), so that +# M equals its entrywise complex conjugate. +_mpo_is_real(M::MPO) = all(T -> eltype(T) <: Real || all(isreal, Array(T, inds(T)...)), M) + +# The normal-state part of a BdG Hamiltonian, the Nambu index `s` attached on `side` +# (:pre or :post) of M. In the Nambu basis (c↑, c↓, c†↑, c†↓) (spinless: (c, c†)) of the +# BdG builders, whose singlet pairing is iσ_y ⊗ Δ, it is Pp ⊗ M + Ph ⊗ (−M*): the hole +# block is minus the complex conjugate. For a real M that is τz ⊗ M, which is built as +# one term as before, so real Hamiltonians give the same MPO bit for bit. Up to v0.2.0 +# every M got τz ⊗ M, whose hole block −M flips the sign of the imaginary entries (σ_y +# terms, Peierls phases, complex hoppings). `dag` conjugates each tensor and keeps the +# primes, so `-dag(M)` is −M*. +function _nambu_normal_block(M::MPO, s::Index, side::Symbol; cutoff::Real) + attach = side === :pre ? prepend_nambu : postpend_nambu + _mpo_is_real(M) && return attach(M, s, :tz) + return +(attach(M, s, :Pp), attach((-1) * dag(M), s, :Ph); cutoff = cutoff) +end + +# A normal-state term M (on the position sites) lifted to the sites of H for adding to +# H.mpo: `ops` on the auxiliary sites it names, the identity on the others, and on a +# Nambu site the particle-hole structure of _nambu_normal_block (τz for a real term, +# lifted as before). +function _lift_normal_term(H, M::MPO, ops::AbstractDict; cutoff::Real) + H.nambu_s === nothing && return _lift_to_aux_sites(H, M, ops) + T = _lift_to_aux_sites(H, M, merge(ops, Dict{Index,Any}(H.nambu_s => :tz))) + _mpo_is_real(T) && return T + Tp = _lift_to_aux_sites(H, M, merge(ops, Dict{Index,Any}(H.nambu_s => :Pp))) + Th = _lift_to_aux_sites(H, M, merge(ops, Dict{Index,Any}(H.nambu_s => :Ph))) + return +(Tp, (-1) * dag(Th); cutoff = cutoff) +end + # ============================================================ # 3. Spin extension @@ -301,8 +332,9 @@ Add a Zeeman coupling `h · Sα` to `H`. Calls `add_spin!` automatically if `direction`: `:x`, `:y`, or `:z` (default). -If `add_superconductivity!` was already called, the Zeeman term is wrapped in -`τ_z` so it enters with opposite sign in the hole sector, as required in BdG. +If `add_superconductivity!` was already called, the Zeeman term `Z` enters the hole +block as `−Z*`, as required in BdG: `τ_z ⊗ Z` along x and z, `+h·S_y` in the hole block +along y (up to v0.2.0 every direction got `τ_z ⊗ Z`, wrong along y). Examples -------- @@ -328,10 +360,9 @@ function add_zeeman!(H::TBHamiltonian, h; h_mpo = h isa Number ? h * MPO(pos_s, "Id") : get_diagonal_mpo(H.L, pos_s, h) - # h σ on the spin, τ_z on a Nambu site, the identity on any other aux site - ops = Dict{Index,Any}(H.spin_s => spin_op) - H.nambu_s === nothing || (ops[H.nambu_s] = :tz) - H_Z = _lift_to_aux_sites(H, h_mpo, ops) + # h σ on the spin, the particle-hole structure on a Nambu site (τ_z for a real term), + # the identity on any other aux site + H_Z = _lift_normal_term(H, h_mpo, Dict{Index,Any}(H.spin_s => spin_op); cutoff=tol) H.mpo = +(H.mpo, H_Z; maxdim=maxdim, cutoff=tol) ITensorMPS.truncate!(H.mpo; maxdim=maxdim, cutoff=tol) @@ -352,8 +383,12 @@ Extend `H` to a Bogoliubov–de Gennes (BdG) Hamiltonian by prepending (`position=:pre`) or postpending (`position=:post`) a Nambu (particle–hole) index; `position` defaults to `H.aux_side`. -The BdG structure is: - H_BdG = τ_z ⊗ H_kin + τ_+ ⊗ H_pair + τ_- ⊗ H_pair† +The BdG structure, in the Nambu basis `(c↑, c↓, c†↑, c†↓)` (spinless: `(c, c†)`), is: + H_BdG = P_p ⊗ H + P_h ⊗ (−H*) + τ_+ ⊗ H_pair + τ_- ⊗ H_pair† +with `P_p`, `P_h` the particle and hole projectors of the Nambu index. For a real `H` +the first two terms are `τ_z ⊗ H`, built as one term; up to v0.2.0 every `H` got +`τ_z ⊗ H`, which is wrong when `H` has imaginary entries (a Zeeman field along y, +Peierls phases, complex hoppings). - **Spinless + p-wave** (`type=:pwave`, or auto-selected when spinless + `:swave`): `H_pair = Δ·(K_forward − K_backward)`, the antisymmetric nearest-neighbour @@ -452,12 +487,12 @@ function add_superconductivity!(H::TBHamiltonian, Δ; # ── BdG assembly ───────────────────────────────────────────────────────── nambu_s = nambu_index() if pos === :pre - H_bdg = +(+(prepend_nambu(H.mpo, nambu_s, :tz), + H_bdg = +(+(_nambu_normal_block(H.mpo, nambu_s, :pre; cutoff=tol), prepend_nambu(H_pair, nambu_s, :tp); cutoff=tol), prepend_nambu(H_pair_adj, nambu_s, :tm); cutoff=tol) H.sites = [nambu_s; H.sites] else - H_bdg = +(+(postpend_nambu(H.mpo, nambu_s, :tz), + H_bdg = +(+(_nambu_normal_block(H.mpo, nambu_s, :post; cutoff=tol), postpend_nambu(H_pair, nambu_s, :tp); cutoff=tol), postpend_nambu(H_pair_adj, nambu_s, :tm); cutoff=tol) H.sites = [H.sites; nambu_s] @@ -469,7 +504,7 @@ function add_superconductivity!(H::TBHamiltonian, Δ; H.nambu_s = nambu_s H.aux_side = pos _invalidate_cache!(H) - # KPM scale of the BdG Hamiltonian (center 0): the normal part τ_z ⊗ H lies within + # KPM scale of the BdG Hamiltonian (center 0): the normal blocks H and −H* lie within # ±(|center| + scale) of H, the pairing adds at most its norm ‖Δ̂‖ (|Δ| on site, # 2|Δ| for the p-wave Δ K_f − Δ* K_b), padded by 10 %. Only when that bound is # known: a scale set on H (not the DMRG sentinel 0) and a number Δ; otherwise the @@ -544,13 +579,9 @@ function add_soc!(H::TBHamiltonian, λ; add_spin!(H; cutoff=tol, maxdim=maxdim, position=pos) pos_s = _pos_sites(H) - # The SOC term on the spin (op), τ_z on a Nambu site, the identity on any other - # aux site, each on the side H.sites puts it. - function spin_prepend(M, _, op) - ops = Dict{Index,Any}(H.spin_s => op) - H.nambu_s === nothing || (ops[H.nambu_s] = :tz) - return _lift_to_aux_sites(H, M, ops) - end + # The SOC term on the spin (op), the particle-hole structure on a Nambu site (τ_z for + # a real term), the identity on any other aux site, each on the side H.sites puts it. + spin_prepend(M, _, op) = _lift_normal_term(H, M, Dict{Index,Any}(H.spin_s => op); cutoff=tol) H_soc = if type === :ising λ_mpo = λ isa Number ? λ * MPO(pos_s, "Id") : diff --git a/src/physics/SCF.jl b/src/physics/SCF.jl index 2d4cd7c..8920ad9 100644 --- a/src/physics/SCF.jl +++ b/src/physics/SCF.jl @@ -459,8 +459,10 @@ function _triplet_equalspin_bdg(H0::TBHamiltonian, delta_up::MPS, delta_dn::MPS; spin_s = H0_work.spin_s nambu_s = nambu_index() - H = +(prepend_nambu(prepend_spin(Hkin_up, spin_s, :Pup), nambu_s, :tz), - prepend_nambu(prepend_spin(Hkin_dn, spin_s, :Pdn), nambu_s, :tz); + # particle block Hkin, hole block −Hkin* (τ_z ⊗ Hkin for a real Hkin, as up to v0.2.0 + # for every Hkin; see _nambu_normal_block) + H = +(_nambu_normal_block(prepend_spin(Hkin_up, spin_s, :Pup), nambu_s, :pre; cutoff=cutoff), + _nambu_normal_block(prepend_spin(Hkin_dn, spin_s, :Pdn), nambu_s, :pre; cutoff=cutoff); cutoff=cutoff) H_tp = +(prepend_spin(P_up, spin_s, :Pup), prepend_spin(P_dn, spin_s, :Pdn); cutoff=cutoff) diff --git a/src/physics/Supercond.jl b/src/physics/Supercond.jl index a88f757..b20f5aa 100644 --- a/src/physics/Supercond.jl +++ b/src/physics/Supercond.jl @@ -127,9 +127,14 @@ end """ bdg_hamiltonian(H_kin, H_pair, nambu_s; cutoff=1e-8) -> MPO -Build a **spinless** Bogoliubov–de Gennes Hamiltonian on `[nambu_s; pos_sites…]`: +Build a **spinless** Bogoliubov–de Gennes Hamiltonian on `[nambu_s; pos_sites…]`, in +the Nambu basis `(c, c†)`: - H_BdG = τ_z ⊗ H_kin + τ_+ ⊗ H_pair + τ_- ⊗ dag(H_pair) + H_BdG = P_p ⊗ H_kin + P_h ⊗ (−H_kin*) + τ_+ ⊗ H_pair + τ_- ⊗ H_pair† + +For a real `H_kin` the first two terms are `τ_z ⊗ H_kin`, built as one term; up to +v0.2.0 every `H_kin` got `τ_z ⊗ H_kin`, whose hole block `−H_kin` is wrong when `H_kin` +has imaginary entries (Peierls phases, complex hoppings). `H_kin` is the single-particle kinetic/hopping MPO measured from the chemical potential (`H_kin = H_tb − μ·I`). `H_pair` encodes the pairing amplitude @@ -151,7 +156,7 @@ The result is Hermitian for any `H_kin = H_kin†` and any complex `H_pair`. function bdg_hamiltonian(H_kin::MPO, H_pair::MPO, nambu_s::Index; cutoff::Real = 1e-8) H_pair_adj = swapprime(dag(H_pair), 0, 1) - return +(+(prepend_nambu(H_kin, nambu_s, :tz), + return +(+(_nambu_normal_block(H_kin, nambu_s, :pre; cutoff=cutoff), prepend_nambu(H_pair, nambu_s, :tp); cutoff=cutoff), prepend_nambu(H_pair_adj, nambu_s, :tm); cutoff=cutoff) end @@ -163,11 +168,17 @@ end Build a **spin-½ singlet** BdG Hamiltonian on `[nambu_s, spin_s; pos_sites…]`. -**Nambu–spin convention**: `Ψ = (c_↑, c_↓, c†_↓, −c†_↑)ᵀ` (standard BCS). +**Nambu–spin convention**: `Ψ = (c_↑, c_↓, c†_↑, c†_↓)ᵀ`, the basis in which the +singlet pairing is `i·σ_y ⊗ Δ` (up to v0.2.0 this docstring named the basis +`(c_↑, c_↓, c†_↓, −c†_↑)`, in which the singlet pairing would be `1 ⊗ Δ` instead). - H_BdG = τ_z⊗P_↑ ⊗ H_kin_up + τ_z⊗P_↓ ⊗ H_kin_down + H_BdG = N(P_↑ ⊗ H_kin_up) + N(P_↓ ⊗ H_kin_down) + τ_+⊗(i·σ_y) ⊗ H_pair + τ_-⊗(−i·σ_y) ⊗ H_pair† - [+ τ_z⊗S_z ⊗ H_soc] + [+ N(S_z ⊗ H_soc)] + +with `N(M) = P_p ⊗ M + P_h ⊗ (−M*)`, the particle and hole blocks. For a real `M`, +`N(M) = τ_z ⊗ M`, built as one term; up to v0.2.0 every `M` got `τ_z ⊗ M`, whose hole +block is wrong when `M` has imaginary entries. The first two lines are the kinetic energy (allowing spin-dependent fields, e.g. Zeeman: pass `H_kin_up = H_tb − (μ+h)·I`, `H_kin_down = H_tb − (μ−h)·I`). @@ -176,7 +187,7 @@ The pairing lines implement singlet Cooper-pair creation via the antisymmetric spin factor `i·σ_y = [[0,1],[−1,0]]`. For on-site s-wave pairing, build `H_pair` as a diagonal MPO with `Δ` on the diagonal. -`H_soc` (optional) adds an Ising-type spin-orbit coupling `τ_z⊗S_z⊗H_soc`. +`H_soc` (optional) adds an Ising-type spin-orbit coupling `N(S_z ⊗ H_soc)`. The result is Hermitian for real or complex `H_pair` and any `H_kin_up/dn`. """ @@ -186,9 +197,10 @@ function bdg_spin_hamiltonian( H_soc::Union{MPO, Nothing} = nothing, cutoff::Real = 1e-8, ) - # τ_z ⊗ P_↑ ⊗ H_kin_up and τ_z ⊗ P_↓ ⊗ H_kin_down - H = +(prepend_nambu(prepend_spin(H_kin_up, spin_s, :Pup), nambu_s, :tz), - prepend_nambu(prepend_spin(H_kin_down, spin_s, :Pdn), nambu_s, :tz); cutoff=cutoff) + # N(P_↑ ⊗ H_kin_up) and N(P_↓ ⊗ H_kin_down): τ_z ⊗ … for real terms + H = +(_nambu_normal_block(prepend_spin(H_kin_up, spin_s, :Pup), nambu_s, :pre; cutoff=cutoff), + _nambu_normal_block(prepend_spin(H_kin_down, spin_s, :Pdn), nambu_s, :pre; cutoff=cutoff); + cutoff=cutoff) # τ_+ ⊗ (i·σ_y) ⊗ Δ + τ_- ⊗ (−i·σ_y) ⊗ Δ† # i·σ_y = [[0,1],[-1,0]] (real matrix): P_↑ pairs with h-↓, P_↓ pairs with h-↑ (singlet) @@ -197,9 +209,10 @@ function bdg_spin_hamiltonian( H_tm = prepend_nambu(prepend_spin(H_pair_adj, spin_s, :miSy), nambu_s, :tm) H = +(+(H, H_tp; cutoff=cutoff), H_tm; cutoff=cutoff) - # Optional Ising SOC: τ_z ⊗ S_z ⊗ H_soc + # Optional Ising SOC: N(S_z ⊗ H_soc) if !isnothing(H_soc) - H = +(H, prepend_nambu(prepend_spin(H_soc, spin_s, :Sz), nambu_s, :tz); cutoff=cutoff) + H = +(H, _nambu_normal_block(prepend_spin(H_soc, spin_s, :Sz), nambu_s, :pre; cutoff=cutoff); + cutoff=cutoff) end return H end diff --git a/test/bugfix_bdg_hole_block.jl b/test/bugfix_bdg_hole_block.jl new file mode 100644 index 0000000..ff0fde2 --- /dev/null +++ b/test/bugfix_bdg_hole_block.jl @@ -0,0 +1,108 @@ +using TensorBinding, ITensors, ITensorMPS, LinearAlgebra, Test +using TensorBinding: get_Hamiltonian, add_spin!, add_zeeman!, add_soc!, add_superconductivity!, + bdg_hamiltonian, bdg_spin_hamiltonian, pairingNNN, shift_mpo, nambu_index, + spin_index, constant_mps + +# The BdG hole block in the Nambu basis (c↑, c↓, c†↑, c†↓) of the package (singlet pairing +# iσ_y ⊗ Δ) is −H*. Up to v0.2.0 every builder used τz ⊗ H, whose hole block −H is wrong +# whenever H has imaginary entries (a Zeeman field along y: the BdG spectrum was off by +# 1.4e-2 for h = 0.3, Δ = 0.25 on an L = 2 spinful chain). +# +# Dense matrices: rows on the primed indices, the first MPO site the most significant, so +# a prepended Nambu site gives the blocks [particle-particle pair; pair' hole-hole]. + +const _TB = TensorBinding +_dense(M::MPO) = _TB._mpo_dense_matrix(M) +const _iσy = ComplexF64[0 1; -1 0] + +# Hermitian, purely imaginary hopping: 0.3i (K_u − K_d), a Peierls-like phase term. +_imag_hop(sites) = 0.3im * +(shift_mpo(sites, 1; cyclic=false), -1 * shift_mpo(sites, -1; cyclic=false); cutoff=1e-14) + +@testset "BdG hole block is −H*" begin + Δ = 0.25 + + @testset "add_superconductivity! with a Zeeman field along $dir" for dir in (:x, :y, :z) + H = get_Hamiltonian("chain_1d", 1.0; L=2, scale=4.0) + add_spin!(H) + add_zeeman!(H, 0.3; direction=dir) + H0 = _dense(H.mpo) # normal state on [spin, pos…] + add_superconductivity!(H, Δ) + @test H.sites[1] == H.nambu_s + D = Δ * kron(_iσy, Matrix{ComplexF64}(I, size(H0, 1) ÷ 2, size(H0, 1) ÷ 2)) + B = _dense(H.mpo) + @test norm(B - [H0 D; D' -conj(H0)]) < 1e-10 + @test norm(B - B') < 1e-10 + if dir === :y # the v0.2.0 model, τz ⊗ H, is visibly different + @test norm(B - [H0 D; D' -H0]) > 0.1 + end + end + + # A term added after the BdG doubling enters as it would before it. + @testset "$what added before or after add_superconductivity!" for what in (:zeeman_y, :zeeman_z, :soc_custom_y) + add_term!(H) = what === :zeeman_y ? add_zeeman!(H, 0.3; direction=:y) : + what === :zeeman_z ? add_zeeman!(H, 0.3; direction=:z) : + add_soc!(H, 0.2; type=:custom, direction=:y) + Hb = get_Hamiltonian("chain_1d", 1.0; L=2, scale=4.0); add_spin!(Hb) + add_term!(Hb); add_superconductivity!(Hb, Δ) + Ha = get_Hamiltonian("chain_1d", 1.0; L=2, scale=4.0); add_spin!(Ha) + add_superconductivity!(Ha, Δ); add_term!(Ha) + @test norm(_dense(Ha.mpo) - _dense(Hb.mpo)) < 1e-10 + end + + @testset "bdg_hamiltonian with a complex H_kin" begin + Hc = get_Hamiltonian("chain_1d", 1.0; L=2) + s = Hc.sites + Hk = +(Hc.mpo, _imag_hop(s); cutoff=1e-14) + P = pairingNNN(2, s, Δ * MPO(s, "Id"), 1) + nb = nambu_index() + K, Pd = _dense(Hk), _dense(P) + @test norm(imag(K)) > 0.1 + @test norm(_dense(bdg_hamiltonian(Hk, P, nb)) - [K Pd; Pd' -conj(K)]) < 1e-10 + end + + @testset "bdg_spin_hamiltonian with complex H_kin" begin + s = siteinds("Qubit", 2) + Hu = +(0.2 * MPO(s, "Id"), _imag_hop(s); cutoff=1e-14) + Hd = +(-0.1 * MPO(s, "Id"), 2 * _imag_hop(s); cutoff=1e-14) + P = Δ * MPO(s, "Id") + sp, nb = spin_index(), nambu_index() + U, Dn, Pd = _dense(Hu), _dense(Hd), _dense(P) + Pup, Pdn = ComplexF64[1 0; 0 0], ComplexF64[0 0; 0 1] + Hn = kron(Pup, U) + kron(Pdn, Dn) + Dp = kron(_iσy, Pd) + @test norm(_dense(bdg_spin_hamiltonian(Hu, Hd, P, sp, nb)) - [Hn Dp; Dp' -conj(Hn)]) < 1e-10 + end + + @testset "equal-spin triplet BdG (SCF) with a complex H0" begin + H0 = get_Hamiltonian("chain_1d", 1.0; L=2, scale=3.0) + H0.mpo = +(H0.mpo, _imag_hop(H0.sites); cutoff=1e-14) + du = constant_mps(H0.sites, 0.1) + dd = constant_mps(H0.sites, 0.05) + Hb = _TB._triplet_equalspin_bdg(H0, du, dd; distance=1, mu=0.1, scale=3.0) + pos = Hb.sites[3:end] + @test pos == H0.sites # [nambu, spin, pos…] + K = _dense(+(H0.mpo, -0.1 * MPO(pos, "Id"); cutoff=1e-14)) + Pu = _dense(_TB._pwave_bond_mpo(du, pos, 1)) + Pd = _dense(_TB._pwave_bond_mpo(dd, pos, 1)) + Pup, Pdn = ComplexF64[1 0; 0 0], ComplexF64[0 0; 0 1] + Hn = kron(Pup, K) + kron(Pdn, K) + Dp = kron(Pup, Pu) + kron(Pdn, Pd) + @test norm(_dense(Hb.mpo) - [Hn Dp; Dp' -conj(Hn)]) < 1e-8 + end + + # Real Hamiltonians keep the one-term τz ⊗ H build, so their MPOs are unchanged + # (exactly equal dense matrices; the two-term build would differ by rounding). + @testset "real H: τz ⊗ H" begin + Hc = get_Hamiltonian("chain_1d", 1.0; L=2) + M = Hc.mpo + @test _TB._mpo_is_real(M) + @test !_TB._mpo_is_real(_imag_hop(Hc.sites)) + nb = nambu_index() + @test _dense(_TB._nambu_normal_block(M, nb, :pre; cutoff=1e-8)) == + _dense(_TB.prepend_nambu(M, nb, :tz)) + Mc = +(M, _imag_hop(Hc.sites); cutoff=1e-14) + N = _dense(_TB._nambu_normal_block(Mc, nb, :post; cutoff=1e-12)) # Nambu index last + K = _dense(Mc) + @test norm(N - kron(K, ComplexF64[1 0; 0 0]) - kron(-conj(K), ComplexF64[0 0; 0 1])) < 1e-10 + end +end diff --git a/test/runtests.jl b/test/runtests.jl index bcbba4e..0f594e7 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -141,6 +141,7 @@ include("bugfix_lattice4.jl") include("bugfix_density_cache.jl") include("bugfix_cache_safety.jl") include("bugfix_soc_boundary.jl") +include("bugfix_bdg_hole_block.jl") # The 0.1 names and keywords renamed in 0.2: deprecated aliases with a one-time warning. include("deprecations.jl") From f0bbcf4cc8e3286867ad5b5a0e765ef6448d61fa Mon Sep 17 00:00:00 2001 From: Anouar Moustaj Date: Fri, 13 Nov 2026 00:46:38 +0200 Subject: [PATCH 08/22] Default build_K's cutoff_K to min(1e-8, 1e-4 eta^4) cutoff_K is relative to the squared norm of each sum and product in build_K, and the eta^2 I term is the smallest part of K = (H - omega)^2 + eta^2: with the fixed default 1e-8 the truncation dropped most of it at small eta (a 5-qubit chain with a cos potential, omega = 0.05, eta = 1e-2: ||Delta K|| = 9.7e-5 against the dense K, i.e. about eta^2). Zero-mode work had to pass 1e-14 to 1e-20 by hand. build_K and dmrg_spectral now default to cutoff_K = nothing, resolved to min(1e-8, 1e-4 eta^4): exactly 1e-8 for eta >= 0.1, and 1e-8 for eta = 0, where K has no eta^2 term; results there are unchanged bit for bit (the dynamics golden cases, at eta = 0.1 and 0.2, pass unchanged). An explicit cutoff_K >= eta^4 is used as given and warns once. The default assumes eigenvalues of H - omega of order one, as the docstring says. New test: ||Delta K|| < 1e-3 eta^2 at eta = 1e-2 with the default, the old value and its warning, and identical K at eta = 0.1, 0.3 and 0. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 ++++++++ src/solvers/DMRG.jl | 30 ++++++++++++++++++++++++------ test/bugfix_build_K.jl | 27 +++++++++++++++++++++++++++ test/runtests.jl | 1 + 4 files changed, 60 insertions(+), 6 deletions(-) create mode 100644 test/bugfix_build_K.jl diff --git a/CHANGELOG.md b/CHANGELOG.md index eae6626..d9f4b8a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,6 +66,14 @@ bugs without breaking the API. bit for bit (no golden case moves). The `bdg_spin_hamiltonian` docstring named the basis `(c↑, c↓, c†↓, −c†↑)`, in which its `iσ_y` pairing would vanish; it now names the basis the code uses. +- **`build_K` and `dmrg_spectral`: `cutoff_K` defaults to `min(1e-8, 1e-4·η⁴)`.** The + cutoff is relative to the squared norm of each sum and product, and `η² I` is the + smallest part of `K = (H − ω)² + η²`, so the fixed default `1e-8` truncated most of it + at small η: on a 5-qubit chain at η = 1e-2, ‖ΔK‖ = 9.7e-5 ≈ η² (now below 1e-7). The + default stays `1e-8` for η ≥ 0.1 and for η = 0, so those results are unchanged bit for + bit; below η = 0.1, K and the DMRG results built on it move. An explicit + `cutoff_K ≥ η⁴` is used as given and warns once. The default assumes eigenvalues of + `H − ω` of order one; pass a smaller `cutoff_K` for a wider spectrum. ### Fixed diff --git a/src/solvers/DMRG.jl b/src/solvers/DMRG.jl index be4adcc..b5a33e7 100644 --- a/src/solvers/DMRG.jl +++ b/src/solvers/DMRG.jl @@ -62,7 +62,7 @@ end # ============================================================ """ - build_K(H_mpo::MPO, sites, ω, η; maxdim_K=200, cutoff_K=1e-8) -> MPO + build_K(H_mpo::MPO, sites, ω, η; maxdim_K=200, cutoff_K=min(1e-8, 1e-4η⁴)) -> MPO Build the resolvent-squared MPO @@ -74,24 +74,41 @@ eigenstate of H nearest to ω. `maxdim_K` and `cutoff_K` control truncation of the intermediate MPO product; larger `maxdim_K` gives a more accurate K at the cost of DMRG wall time. + +`cutoff_K` is relative (to the squared Frobenius norm of each sum and product), and +`η² I` is the smallest part of K: from `cutoff_K ≈ η⁴` on, the truncation can drop it +(a 5-qubit chain at η = 1e-2 kept almost none of it with the fixed default `1e-8` of +v0.2.0: ‖ΔK‖ = 9.7e-5 ≈ η²). The default is `1e-8` for η ≥ 0.1 (and η = 0), as before, +and `1e-4 η⁴` below, which assumes eigenvalues of H − ω of order one: for a wider +spectrum pass a smaller `cutoff_K`. A `cutoff_K` of η⁴ or more is used as given and +warns. """ function build_K(H_mpo::MPO, sites, ω::Real, η::Real; maxdim_K::Int = 200, - cutoff_K::Real = 1e-8) + cutoff_K::Union{Nothing,Real} = nothing) + cutoff_K = something(cutoff_K, _default_cutoff_K(η)) + η != 0 && cutoff_K >= η^4 && + @warn "build_K: cutoff_K = $cutoff_K is not below η⁴ = $(η^4); the truncation of " * + "K = (H − ω)² + η² can drop its η² term (the default is min(1e-8, 1e-4η⁴))." maxlog=1 I_mpo = MPO(sites, "Id") H_shift = +(H_mpo, (-ω) * I_mpo; cutoff = cutoff_K) H_sq = apply(H_shift, H_shift; cutoff = cutoff_K, maxdim = maxdim_K) return +(H_sq, (η^2) * I_mpo; cutoff = cutoff_K) end +# The default cutoff_K of build_K and dmrg_spectral: the fixed 1e-8 of v0.2.0 where it +# keeps the η² I term of K (η ≥ 0.1, or η = 0, where there is none), 1e-4 η⁴ below. +_default_cutoff_K(η::Real) = iszero(η) ? 1e-8 : min(1e-8, 1e-4 * Float64(η)^4) + # ============================================================ # 3. Spectral DMRG (minimise K) # ============================================================ """ - dmrg_spectral(H_mpo::MPO, sites, ω, η; ψ0=nothing, maxdim_K=200, cutoff_K=1e-8, - linkdim_init=10, nsweeps=10, maxdim=[10, 20, 50, 100, 200], + dmrg_spectral(H_mpo::MPO, sites, ω, η; ψ0=nothing, maxdim_K=200, + cutoff_K=min(1e-8, 1e-4η⁴), linkdim_init=10, nsweeps=10, + maxdim=[10, 20, 50, 100, 200], cutoff=1e-8, noise=[1e-6, 1e-7, 1e-8, 0.0], kwargs...) -> (E_K, ψ) Find the ground state of `K(ω,η) = (H−ωI)² + η²I` using DMRG. @@ -102,7 +119,8 @@ Use `local_weight(ψ, i, L, sites)` to read off the LDoS proxy `|⟨i|ψ(ω)⟩| # Keyword arguments - `ψ0` : warm-start MPS (random if `nothing`, the default) - `maxdim_K`, `cutoff_K` : truncation for building K (see `build_K`). Defaults - `200`, `1e-8`. + `200` and `min(1e-8, 1e-4η⁴)` (`1e-8` up to v0.2.0, which + drops most of the η² term at η = 1e-2). - `linkdim_init` : bond dimension of the random initial MPS (if ψ0=nothing). Default `10`. - `nsweeps`, `maxdim`, `cutoff`, `noise` : DMRG sweep parameters, with the same @@ -114,7 +132,7 @@ Returns `(E_K, ψ)` where `E_K ≈ η²` at spectral peaks. function dmrg_spectral(H_mpo::MPO, sites, ω::Real, η::Real; ψ0 = nothing, maxdim_K::Int = 200, - cutoff_K::Real = 1e-8, + cutoff_K::Union{Nothing,Real} = nothing, linkdim_init::Int = 10, nsweeps::Int = 10, maxdim = [10, 20, 50, 100, 200], diff --git a/test/bugfix_build_K.jl b/test/bugfix_build_K.jl new file mode 100644 index 0000000..5e87c1a --- /dev/null +++ b/test/bugfix_build_K.jl @@ -0,0 +1,27 @@ +using TensorBinding, ITensors, ITensorMPS, LinearAlgebra, Test, Logging, Random +using TensorBinding: get_Hamiltonian, add_onsite!, build_K, get_matrix + +# build_K's cutoff_K was a fixed 1e-8, relative to ‖K‖², so at small η the truncation +# dropped the η² I term of K = (H − ω)² + η² (η = 1e-2 on this chain: ‖ΔK‖ = 9.7e-5 ≈ η²). +# The default is now min(1e-8, 1e-4 η⁴): 1e-8 as before for η ≥ 0.1 (and η = 0), smaller +# below; an explicit cutoff_K ≥ η⁴ is used as given and warns. +@testset "build_K: cutoff_K default scales with η" begin + H = get_Hamiltonian("chain_1d", 1.0; L=5) + Random.seed!(11) + add_onsite!(H, n -> 0.3 * cos(2π * 0.618 * n)) + Hd = get_matrix(H.mpo, H.sites) + ω = 0.05 + Kex(η) = (Hd - ω * I)^2 + η^2 * I + Kd(η; kw...) = get_matrix(build_K(H.mpo, H.sites, ω, η; kw...), H.sites) + + η = 1e-2 + @test opnorm(Kd(η) - Kex(η)) < 1e-3 * η^2 + Kold = @test_logs (:warn, r"cutoff_K = 1.0e-8 is not below η⁴") Kd(η; cutoff_K=1e-8) + @test opnorm(Kold - Kex(η)) > 0.5 * η^2 # the v0.2.0 default lost most of η² + + # η ≥ 0.1 and η = 0: the default is 1e-8, as before, bit for bit and without warning. + for η in (0.1, 0.3, 0.0) + @test (@test_logs min_level=Logging.Warn Kd(η)) == Kd(η; cutoff_K=1e-8) + end + @test TensorBinding._default_cutoff_K(0.05) ≈ 1e-4 * 0.05^4 +end diff --git a/test/runtests.jl b/test/runtests.jl index 0f594e7..ac85b86 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -142,6 +142,7 @@ include("bugfix_density_cache.jl") include("bugfix_cache_safety.jl") include("bugfix_soc_boundary.jl") include("bugfix_bdg_hole_block.jl") +include("bugfix_build_K.jl") # The 0.1 names and keywords renamed in 0.2: deprecated aliases with a one-time warning. include("deprecations.jl") From f4bbc27f41711dca6ec2f4391cf3b4577f6a17f1 Mon Sep 17 00:00:00 2001 From: Anouar Moustaj Date: Fri, 13 Nov 2026 00:49:25 +0200 Subject: [PATCH 09/22] Accept vectors (TT-SVD) and an opt-in check for the QTCI diagonal profiles get_mps runs QTCI from the first point and five random pivots (global RNG) and checks nothing, so get_diagonal_mpo, add_onsite! and add_zeeman! could lose a narrow feature or throw on a profile that vanishes almost everywhere (L = 10: a 4-site box on a 0.1 background lost for 3 of 5 seeds; a single nonzero site threw "maxsamplevalue is zero!" for 5 of 5). Added, with no change to existing calls: - a vector of the 2^L values (v[n+1] at the 0-indexed n) for get_mps, get_mpo, get_diagonal_mpo, add_onsite! and add_zeeman!, compressed by TT-SVD (cutoff tol^2/2^L per bond, so every entry within about sqrt(L) tol max|v|): exact, no sampling, no RNG; - check (default false) for get_mps, the one-argument get_mpo, get_diagonal_mpo and add_onsite!: the QTCI build is kept when no checked entry is off by more than sqrt(tol) max|f|. Up to 2^20 points every point is checked and a wrong build (or a throw) is replaced by the TT-SVD of the values; above, a sample (ends, carry boundaries 2^k-2 .. 2^k+1, a golden-ratio stride of 4096 points) is checked and a wrong build is redone from the missed points as pivots without random ones, then checked again (an error if it still fails). A passing build is returned unchanged, as in hopping2MPO(...; check=true). get_mpo with a two-argument f rejects check=true and points to hopping2MPO. New test (31 checks): TT-SVD exactness for a box, a single site, a complex profile and L = 1; check=true at the five seeds that failed before, on the box and on the single site; a passing build unchanged; the zero profile; add_onsite! and add_zeeman! with vectors; the sampled path at L = 21 with a box at the carry boundary 2^20. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 15 +++ src/core/AuxDOF.jl | 4 +- src/core/TBSystem.jl | 24 +++-- src/core/Utils.jl | 176 ++++++++++++++++++++++++++++++++--- test/bugfix_qtci_profiles.jl | 85 +++++++++++++++++ test/runtests.jl | 1 + 6 files changed, 286 insertions(+), 19 deletions(-) create mode 100644 test/bugfix_qtci_profiles.jl diff --git a/CHANGELOG.md b/CHANGELOG.md index d9f4b8a..adfceb2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,21 @@ bugs without breaking the API. before) or `:open`, which drops the bond between the last and the first site. The default chain, `get_Hamiltonian("chain_1d", t; L)`, is open, so a Rashba term that matches it needs `boundary=:open`. +- **Diagonal profiles from vectors.** `get_mps`, `get_mpo`, `get_diagonal_mpo`, + `add_onsite!` and `add_zeeman!` accept the values themselves as a vector of length + `2^L` (`v[n+1]` at the 0-indexed point `n`), compressed by TT-SVD: exact up to `tol`, + with no sampling and no RNG. Functions keep the QTCI build, which can lose a narrow + feature depending on the RNG state (at L = 10 a 4-site box on a 0.1 background was lost + for 3 of 5 seeds) or throw "maxsamplevalue is zero!" on a profile that vanishes almost + everywhere. +- **`check` keyword for the QTCI profiles** (`get_mps`, the one-argument `get_mpo`, + `get_diagonal_mpo`, `add_onsite!`; default `false`, the build of v0.2.0). With + `check=true` the QTCI build is compared with `f` and kept when no entry is off by more + than `√tol · max|f|`; up to 2^20 points every point is compared and a wrong build (or a + throw) is replaced by the TT-SVD of the values, above that a sample is compared (ends, + carry boundaries, a golden-ratio stride) and a wrong build is redone from the missed + points as pivots, then checked again (an error if it still fails). As in + `hopping2MPO(...; check=true)`, a build that passes is returned unchanged. ### Changed diff --git a/src/core/AuxDOF.jl b/src/core/AuxDOF.jl index 5d0eb74..06da6ae 100644 --- a/src/core/AuxDOF.jl +++ b/src/core/AuxDOF.jl @@ -328,7 +328,9 @@ Add a Zeeman coupling `h · Sα` to `H`. Calls `add_spin!` automatically if `h` can be: - a `Number` — uniform field amplitude `h₀` -- a `Function` — spatially varying `h(i)`, `i ∈ {1, …, N}` (1-indexed) +- a `Function` — spatially varying `h(i)`, `i ∈ {1, …, N}` (1-indexed), compressed by + QTCI, which can lose narrow features (see [`get_diagonal_mpo`](@ref)) +- an `AbstractVector` — the values `h[i]` (length N), compressed exactly by TT-SVD `direction`: `:x`, `:y`, or `:z` (default). diff --git a/src/core/TBSystem.jl b/src/core/TBSystem.jl index 4c8f140..36bdc4b 100644 --- a/src/core/TBSystem.jl +++ b/src/core/TBSystem.jl @@ -899,7 +899,7 @@ end """ add_onsite!(H, f; layer=nothing, sublat=nothing, Lx=nothing, - tol=1e-8, maxdim=nothing) -> H + tol=1e-8, maxdim=nothing, check=false) -> H Add a diagonal (on-site) potential to `H`. @@ -910,6 +910,14 @@ Add a diagonal (on-site) potential to `H`. - `f(n)` — 1-arg function; `n ∈ {0, …, N-1}` is the 0-indexed unit-cell index. - `f(ix, iy)` — 2-arg function; `ix, iy` are 0-indexed 2D coordinates (`ix = n % Nx`, `iy = n ÷ Nx`). Requires `Lx=` keyword so that `Nx = 2^Lx`. +- `f::AbstractVector` — the values themselves, `f[n+1]` at unit cell `n` (length `N`; + a 2D map `V[ix+1, iy+1]` is `vec(V)`), compressed exactly by TT-SVD. + +The functions are compressed by QTCI, which can lose narrow features (a box of a few +cells, a single impurity) for some RNG states, or throw on a profile that vanishes +almost everywhere (see [`get_mps`](@ref)). Pass the values as a vector, or +`check=true` to check the QTCI build against `f` and replace it when it is wrong +(`false` by default, the build of v0.2.0). **`sublat` keyword** (`H.sublattice_s` must be set) @@ -938,7 +946,7 @@ projectors. Invalidates all caches. """ function add_onsite!(H::TBHamiltonian, f; layer=nothing, sublat=nothing, - Lx=nothing, tol=1e-8, maxdim=nothing) + Lx=nothing, tol=1e-8, maxdim=nothing, check::Bool=false) _require_binary_position_space(H, "add_onsite!") if H.layer_s !== nothing (H.spin_s === nothing && H.nambu_s === nothing) || @@ -960,7 +968,7 @@ function add_onsite!(H::TBHamiltonian, f; layer=nothing, sublat=nothing, spin_s=nothing, nambu_s=nothing, layer_s=nothing, sublattice_s=H.sublattice_s, aux_side=:post) add_onsite!(H_pos, f; layer=nothing, sublat=sublat, - Lx=Lx, tol=tol, maxdim=maxdim) + Lx=Lx, tol=tol, maxdim=maxdim, check=check) term = prepend_layer_projector(H_pos.mpo, H.layer_s, ell) H_layered_term = H_layered_term === nothing ? term : +(H_layered_term, term; cutoff=tol) @@ -981,13 +989,15 @@ function add_onsite!(H::TBHamiltonian, f; layer=nothing, sublat=nothing, fkind = if f isa Number :scalar + elseif f isa AbstractVector # f[n+1] — the values, compressed by TT-SVD + :vector elseif applicable(f, 0, 0) # f(ix, iy) — 0-indexed 2D :pos2d elseif applicable(f, 0) # f(n) — 0-indexed 1D :pos1d else error("add_onsite!: unsupported f signature.\n" * - "Supported: Number, f(n), f(ix, iy)") + "Supported: Number, f(n), f(ix, iy), a vector f[n+1]") end Nx = if fkind === :pos2d @@ -1002,10 +1012,12 @@ function add_onsite!(H::TBHamiltonian, f; layer=nothing, sublat=nothing, diag_mpo = if fkind === :scalar get_diagonal_mpo(L, pos_s, x -> f) + elseif fkind === :vector + get_diagonal_mpo(L, pos_s, f) elseif fkind === :pos1d - get_diagonal_mpo(L, pos_s, i -> f(round(Int, i) - 1)) + get_diagonal_mpo(L, pos_s, i -> f(round(Int, i) - 1); check=check) else # :pos2d - get_diagonal_mpo(L, pos_s, i -> (n = round(Int, i) - 1; f(n % Nx, n ÷ Nx))) + get_diagonal_mpo(L, pos_s, i -> (n = round(Int, i) - 1; f(n % Nx, n ÷ Nx)); check=check) end if H.sublattice_s !== nothing diff --git a/src/core/Utils.jl b/src/core/Utils.jl index 30a13ae..e5bd099 100644 --- a/src/core/Utils.jl +++ b/src/core/Utils.jl @@ -1176,11 +1176,42 @@ function constant_mps(sites::Vector{<:Index}, value::Number) end """ - get_mps(L, sites, f; type=Float64, tol=1e-8) -> MPS + get_mps(L, sites, f; type=Float64, tol=1e-8, check=false) -> MPS + get_mps(L, sites, v::AbstractVector; tol=1e-8) -> MPS + +Compress a scalar profile `f(n)` on `n = 0, ..., 2^L-1` into an MPS via QTCI (site 1 +the most significant bit). + +QTCI samples `f` from a few pivots (the first point and five random ones, from the +global RNG) and checks nothing afterwards, so a narrow feature on a flat background can +be lost, depending on the RNG state, and a profile that vanishes almost everywhere can +make it throw "maxsamplevalue is zero!" (L = 10: a 4-site box on a 0.1 background was +lost for 3 of 5 seeds; a single nonzero site threw for 5 of 5). Two ways round it: + +- a vector `v` (`v[n+1] = f(n)`, length `2^L`) is compressed by TT-SVD: sequential SVDs, + exact up to about `tol · max|v|` per entry, with no sampling and no RNG; +- `check=true` checks the QTCI build against `f` and returns it as it is when it passes; + an entry fails when it is off by more than `√tol · max|f|` (1e-4 of the largest value + at the default `tol`). Up to 2^20 points the check covers every point and a failed + build (or a throw) is replaced by the TT-SVD of those values. Above, it covers a + sample (both ends, the carry boundaries `2^k − 2 … 2^k + 1` and a golden-ratio stride of + 4096 points), and a failed build is rebuilt by QTCI from the sampled points it missed as + pivots, without random pivots, then checked again; a second failure is an error. + Features between the sampled points cannot be checked there: pass a vector instead. + +`check=false` (the default) keeps the plain QTCI build of v0.2.0. +""" +function get_mps(L::Int, sites, f; type=Float64, tol::Real=1e-8, check::Bool=false) + check && return _checked_qtci_mps(L, sites, f; type=type, tol=tol) + return _qtci_mps(L, sites, f; type=type, tol=tol) +end -Compress a scalar profile `f(n)` on `n = 0, ..., 2^L-1` into an MPS via QTCI. -""" -function get_mps(L::Int, sites, f; type=Float64, tol::Real=1e-8) +# A vector needs no check (TT-SVD samples nothing); `check` is accepted for generic callers. +get_mps(L::Int, sites, v::AbstractVector; type=nothing, tol::Real=1e-8, check::Bool=false) = + _ttsvd_mps(L, sites, type === nothing ? v : convert(Vector{type}, v); tol=tol) + +# The QTCI build of get_mps (what it runs without `check`). +function _qtci_mps(L::Int, sites, f; type, tol) if L == 1 s = first(sites) T = ITensor(type, s) @@ -1194,18 +1225,126 @@ function get_mps(L::Int, sites, f; type=Float64, tol::Real=1e-8) return MPS(tt; sites=collect(sites)) end +# TT-SVD of the 2^L values v (v[n+1] at n = 0 … 2^L-1, site 1 the most significant bit, +# as the QTCI builders): sequential SVDs with the relative cutoff tol²/2^L per bond, so +# that the discarded weight stays below (L-1)·tol²·max|v|² and every entry within about +# √L·tol·max|v|. +function _ttsvd_mps(L::Int, sites, v::AbstractVector; tol::Real) + N = 2^L + length(v) == N || + throw(DimensionMismatch("a profile on L = $L qubits needs 2^L = $N values, got $(length(v))")) + length(sites) == L || + throw(DimensionMismatch("$(length(sites)) sites for L = $L")) + T = float(eltype(v)) + iszero(maximum(abs, v)) && return constant_mps(collect(sites), zero(T)) + A = permutedims(reshape(collect(T, v), ntuple(_ -> 2, L)), L:-1:1) # dim 1 = site 1 (MSB) + return MPS(A, collect(sites); cutoff=tol^2 / N) +end + +# The entries of an MPS on qubit `sites` as a dense vector, v[n+1] at n = 0 … 2^L-1 (site +# 1 the most significant bit; eval_mps keeps only the real part). +function _mps_dense_vector(mps::MPS, sites) + T = mps[1] + for k in 2:length(mps) + T *= mps[k] + end + return vec(Array(T, reverse(collect(sites))...)) +end + +# The entry of an MPS on qubit `sites` at the 0-indexed n (site 1 the most significant bit). +function _mps_entry(mps::MPS, sites, n::Integer) + L = length(sites) + acc = ITensor(1.0) + for k in 1:L + acc *= mps[k] * onehot(sites[k] => ((n >> (L - k)) & 1) + 1) + end + return scalar(acc) +end + +# The first entry of `got` off `want` by more than √tol·max|want|, as (index, got, want), +# or nothing. +function _profile_mismatch(got, want, tol) + bound = sqrt(tol) * maximum(abs, want; init=0.0) + i = findfirst(k -> abs(got[k] - want[k]) > bound, eachindex(got, want)) + return i === nothing ? nothing : (i, got[i], want[i]) +end + +# The 0-indexed points get_mps(...; check=true) compares above the full-grid limit: both +# ends, the carry boundaries 2^k − 2 … 2^k + 1 (k = 1 … L-1), and an odd golden-ratio +# stride of `nbulk` points through the bulk. +function _profile_sample_points(L::Int; nbulk::Int=4096) + N = 2^L + s = 2 * round(Int, 0.30901699437494745 * N) + 1 + pts = [0; 1; 2; 3; [2^k + δ for k in 1:L-1 for δ in (-2, -1, 0, 1)]; N - 2; N - 1; + [mod(k * s, N) for k in 0:nbulk-1]] + return sort!(unique!(filter(n -> 0 <= n < N, pts))) +end + +# Up to 2^20 points get_mps(...; check=true) compares every point. +const _PROFILE_CHECK_FULL_MAXLEN = 2^20 + +# get_mps(...; check=true): the QTCI build when it reproduces f on the checked points, +# else a rebuild (see the get_mps docstring). +function _checked_qtci_mps(L::Int, sites, f; type, tol) + N = 2^L + qtci = try + _qtci_mps(L, sites, f; type=type, tol=tol) + catch err + (err isa ErrorException && occursin("maxsamplevalue is zero", err.msg)) || rethrow() + nothing + end + if N <= _PROFILE_CHECK_FULL_MAXLEN + vals = type[f(n) for n in 0:N-1] + qtci !== nothing && + _profile_mismatch(_mps_dense_vector(qtci, sites), vals, tol) === nothing && return qtci + return _ttsvd_mps(L, sites, vals; tol=tol) + end + pts = _profile_sample_points(L) + vals = type[f(n) for n in pts] + got = qtci === nothing ? nothing : [_mps_entry(qtci, sites, n) for n in pts] + got !== nothing && _profile_mismatch(got, vals, tol) === nothing && return qtci + all(iszero, vals) && + error("get_mps: f vanishes at all $(length(pts)) sampled points and QTCI found no " * + "nonzero value either. If f is identically zero, leave the term out; otherwise " * + "pass the profile as a vector (compressed by TT-SVD).") + # pivots: the largest sampled |f|, then the sampled points the build missed (at most 64) + bound = sqrt(tol) * maximum(abs, vals) + missed = got === nothing ? findall(!iszero, vals) : + findall(k -> abs(got[k] - vals[k]) > bound, eachindex(vals)) + piv = unique([argmax(abs.(vals)); missed]) + piv = piv[1:min(end, 64)] + xvals = range(1, N; length=N) + qtt, _, _ = quanticscrossinterpolate(type, x -> f(round(Int, x) - 1), [xvals], + [[pts[k] + 1] for k in piv]; + nrandominitpivot=0, tolerance=tol) + mps = MPS(TensorCrossInterpolation.tensortrain(qtt.tci); sites=collect(sites)) + bad = _profile_mismatch([_mps_entry(mps, sites, n) for n in pts], vals, tol) + bad === nothing && return mps + k, g, w = bad + error("get_mps: the QTCI-compressed profile is wrong at n = $(pts[k]): $g instead of $w, " * + "also when rebuilt from the sampled points it missed as pivots. Pass the profile " * + "as a vector (compressed by TT-SVD), or check=false to accept the approximate MPS.") +end + """ - get_mpo(L, sites, f; type=Float64, tol=1e-8, kwargs...) -> MPO + get_mpo(L, sites, f; type=Float64, tol=1e-8, check=false, kwargs...) -> MPO + get_mpo(L, sites, v::AbstractVector; tol=1e-8) -> MPO Compress a function into an MPO via QTCI using 0-indexed coordinates `n = 0, ..., 2^L-1`. Dispatches on arity: -- **1-argument** `f(n)`: builds a diagonal MPO (on-site potential). +- **1-argument** `f(n)`: builds a diagonal MPO (on-site potential), through + [`get_mps`](@ref) (`check=true` checks it, see there). - **2-argument** `f(i, j)`: builds a full interaction MPO by 2D QTCI, - pairing the interleaved quantics legs into bra/ket via `custom_mpo`. + pairing the interleaved quantics legs into bra/ket via `custom_mpo`. `check` is not + available here (`hopping2MPO(f, N, sites; check=true)` checks a hopping matrix). + +A vector `v` (`v[n+1] = f(n)`) gives the diagonal MPO by TT-SVD, exact up to `tol`. """ -function get_mpo(L::Int, sites, f; type=Float64, tol::Real=1e-8, kwargs...) +function get_mpo(L::Int, sites, f; type=Float64, tol::Real=1e-8, check::Bool=false, kwargs...) if applicable(f, 0, 0) + check && throw(ArgumentError("get_mpo: check=true is for a one-argument profile f(n); " * + "check a two-argument f with hopping2MPO(f, N, sites; check=true)")) N = 1 << L xvals = range(0, N - 1; length=N) kernel = (x, y) -> f(round(Int, x), round(Int, y)) @@ -1214,25 +1353,38 @@ function get_mpo(L::Int, sites, f; type=Float64, tol::Real=1e-8, kwargs...) tt = TensorCrossInterpolation.tensortrain(qtt.tci) return custom_mpo(MPS(tt), collect(sites)) else - return mps2mpo(L, sites, get_mps(L, sites, f; type=type, tol=tol)) + return mps2mpo(L, sites, get_mps(L, sites, f; type=type, tol=tol, check=check)) end end +get_mpo(L::Int, sites, v::AbstractVector; type=nothing, tol::Real=1e-8, check::Bool=false) = + mps2mpo(L, sites, get_mps(L, sites, v; type=type, tol=tol)) + """ - get_diagonal_mpo(L, sites, f; type=Float64, tol=1e-8) -> MPO + get_diagonal_mpo(L, sites, f; type=Float64, tol=1e-8, check=false) -> MPO + get_diagonal_mpo(L, sites, v::AbstractVector; tol=1e-8) -> MPO Build a diagonal MPO with entry `f(x)` at 1-indexed site `x ∈ {1, ..., 2^L}`. Wraps `get_mpo` with a 1→0 index shift for backward compatibility. +The QTCI build can lose narrow features (a box of a few sites, a single impurity) for +some RNG states, or throw on a profile that vanishes almost everywhere; see +[`get_mps`](@ref). A vector `v` (`v[x]` at site `x`, length `2^L`) is compressed exactly +by TT-SVD instead, and `check=true` checks a function's build (and replaces a wrong one). + # Example ```julia pot = get_diagonal_mpo(L, sites, x -> 0.01 * x) +imp = get_diagonal_mpo(L, sites, [x == 37 ? 1.0 : 0.0 for x in 1:2^L]) # TT-SVD ``` """ -function get_diagonal_mpo(L, sites, f; type=Float64, tol::Real=1e-8) - return get_mpo(L, sites, n -> f(n + 1); type=type, tol=tol) +function get_diagonal_mpo(L, sites, f; type=Float64, tol::Real=1e-8, check::Bool=false) + return get_mpo(L, sites, n -> f(n + 1); type=type, tol=tol, check=check) end +get_diagonal_mpo(L, sites, v::AbstractVector; type=nothing, tol::Real=1e-8, check::Bool=false) = + get_mpo(L, sites, v; type=type, tol=tol) + # ============================================================ # 8. Diagonal MPO <-> MPS conversion diff --git a/test/bugfix_qtci_profiles.jl b/test/bugfix_qtci_profiles.jl new file mode 100644 index 0000000..87c2484 --- /dev/null +++ b/test/bugfix_qtci_profiles.jl @@ -0,0 +1,85 @@ +using TensorBinding, ITensors, ITensorMPS, LinearAlgebra, Test, Random +using TensorBinding: get_mps, get_mpo, get_diagonal_mpo, extract_diagonal_to_mps, add_onsite!, + get_Hamiltonian + +# get_mps / get_mpo / get_diagonal_mpo run QTCI from a few random pivots and checked nothing: +# at L = 10 a 4-site box on a 0.1 background was lost in 3 of 5 seeds, and a profile that +# vanishes almost everywhere threw "maxsamplevalue is zero!". A vector is now compressed +# by TT-SVD (exact up to tol), and `check=true` verifies a function's QTCI build (on the +# whole grid up to 2^20 points) and replaces a wrong one. + +const _TBq = TensorBinding +_diag(M::MPO, sites) = _TBq._mps_dense_vector(extract_diagonal_to_mps(M), sites) + +@testset "QTCI profiles: vectors by TT-SVD, opt-in check for functions" begin + L = 10; N = 2^L; s = siteinds("Qubit", L) + c = round(Int, 0.68N) # an off-centre feature + box(x) = 0.1 + (c <= x <= c + 3 ? 1.0 : 0.0) # 1-indexed x, as get_diagonal_mpo + single(x) = x == c ? 1.0 : 0.0 + vbox = [box(x) for x in 1:N] + + @testset "vectors" begin + @test maximum(abs.(_diag(get_diagonal_mpo(L, s, vbox), s) .- vbox)) < 1e-10 + vs = [single(x) for x in 1:N] + @test maximum(abs.(_diag(get_diagonal_mpo(L, s, vs), s) .- vs)) < 1e-10 + vc = [cis(2π * 3x / N) + (x == c ? 0.5im : 0) for x in 1:N] # complex + @test maximum(abs.(_diag(get_diagonal_mpo(L, s, vc), s) .- vc)) < 1e-10 + @test maximum(abs.(_TBq._mps_dense_vector(get_mps(L, s, vbox), s) .- vbox)) < 1e-10 + @test maximum(abs.(_diag(get_mpo(L, s, vbox), s) .- vbox)) < 1e-10 # v[n+1] = f(n) + s1 = siteinds("Qubit", 1) + @test _TBq._mps_dense_vector(get_mps(1, s1, [2.0, -1.0]), s1) ≈ [2.0, -1.0] + @test_throws DimensionMismatch get_diagonal_mpo(L, s, vbox[1:end-1]) + @test maxlinkdim(get_mps(L, s, vbox)) <= 4 # a box is low rank + end + + @testset "check=true on a function" begin + # the seeds of the 2026-11-12 check, in which the unchecked build lost the box + # (3 of 5) or threw on the single site (5 of 5) + for seed in 1:5 + Random.seed!(seed) + checked = _diag(get_diagonal_mpo(L, s, box; check=true), s) + @test maximum(abs.(checked .- vbox)) < 1e-6 + Random.seed!(seed) + @test maximum(abs.(_diag(get_diagonal_mpo(L, s, single; check=true), s) .- + [single(x) for x in 1:N])) < 1e-6 + end + + # A build that passes the check is returned as it is. + sm(x) = cos(2π * x / N) + Random.seed!(3); a = _diag(get_diagonal_mpo(L, s, sm), s) + Random.seed!(3); b = _diag(get_diagonal_mpo(L, s, sm; check=true), s) + @test a == b + # An identically zero profile gives the zero MPS instead of throwing. + @test all(iszero, _diag(get_diagonal_mpo(L, s, x -> 0.0; check=true), s)) + @test_throws ArgumentError get_mpo(3, siteinds("Qubit", 3), (i, j) -> 1.0; check=true) + end + + @testset "add_onsite! with a vector or check=true" begin + H = get_Hamiltonian("chain_1d", 1.0; L=L) + d0 = _diag(H.mpo, H.sites) + Hv = deepcopy(H); add_onsite!(Hv, vbox) # v[n+1] at 0-indexed n + @test maximum(abs.(_diag(Hv.mpo, Hv.sites) .- d0 .- vbox)) < 1e-8 + Hc = deepcopy(H); Random.seed!(1) + add_onsite!(Hc, n -> box(n + 1); check=true) + @test maximum(abs.(_diag(Hc.mpo, Hc.sites) .- d0 .- vbox)) < 1e-6 + + # add_zeeman! takes a vector through get_diagonal_mpo: h[i]·S_z, S_z = σ_z/2 + Hz = get_Hamiltonian("chain_1d", 1.0; L=3); TensorBinding.add_spin!(Hz) + dz = real(diag(_TBq._mpo_dense_matrix(Hz.mpo))) + hv = [0.1x for x in 1:8] + TensorBinding.add_zeeman!(Hz, hv) # sites [spin, pos…]: ↑ block first + @test real(diag(_TBq._mpo_dense_matrix(Hz.mpo))) ≈ dz .+ [hv ./ 2; -hv ./ 2] atol=1e-10 + end + + # Above 2^20 points the check samples (ends, carry boundaries 2^k - 2 … 2^k + 1, a + # golden-ratio stride) and rebuilds QTCI with the missed points as pivots. + @testset "check=true above the full-grid limit" begin + Lb = 21; Nb = 2^Lb; sb = siteinds("Qubit", Lb) + fb(n) = 0.1 + (2^20 - 2 <= n <= 2^20 + 1 ? 1.0 : 0.0) # 0-indexed, at a carry boundary + Random.seed!(2) + m = get_mps(Lb, sb, fb; check=true) + for n in (0, 2^20 - 3, 2^20 - 2, 2^20, 2^20 + 1, 2^20 + 2, Nb - 1) + @test abs(_TBq._mps_entry(m, sb, n) - fb(n)) < 1e-6 + end + end +end diff --git a/test/runtests.jl b/test/runtests.jl index ac85b86..3a59670 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -143,6 +143,7 @@ include("bugfix_cache_safety.jl") include("bugfix_soc_boundary.jl") include("bugfix_bdg_hole_block.jl") include("bugfix_build_K.jl") +include("bugfix_qtci_profiles.jl") # The 0.1 names and keywords renamed in 0.2: deprecated aliases with a one-time warning. include("deprecations.jl") From 9795a20639a76ec1ecfce643f5daed28b6dfa27f Mon Sep 17 00:00:00 2001 From: Anouar Moustaj Date: Fri, 13 Nov 2026 00:52:30 +0200 Subject: [PATCH 10/22] Note that a dynamics golden rerun reproduces untouched cases only up to rounding The generator header said a rerun reproduces the data file byte for byte. The rerun for 8d4eb10 also moved the three krylov_green cases by up to 5e-14 although src/solvers/Krylov.jl had not changed; their stored lines were kept. The header now says so and asks for the same after every rerun, so that the data diff shows only the cases a change moves. Co-Authored-By: Claude Opus 5.5 --- test/data/generate_dynamics_golden.jl | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/test/data/generate_dynamics_golden.jl b/test/data/generate_dynamics_golden.jl index e858b78..78dbc95 100644 --- a/test/data/generate_dynamics_golden.jl +++ b/test/data/generate_dynamics_golden.jl @@ -16,7 +16,11 @@ # Line 4 of the data file records the git tree hash of the working-tree src/, # i.e. the src/ that the regenerating commit will contain. It does not move when # only tests or docs change, so such a rerun reproduces the file byte for byte -# (floating-point results are written with `repr`, which round-trips exactly). +# (floating-point results are written with `repr`, which round-trips exactly) up +# to rounding: the rerun for 8d4eb10 also moved the three krylov_green cases by up +# to 5e-14, although src/solvers/Krylov.jl had not changed. After a rerun, keep the +# stored lines of the cases whose code did not change, so that the data diff shows +# only the cases the change moves. # # Regenerate ONLY when a behaviour change is intentional. Do it in the same # commit as the change, review the diff of dynamics_golden.jl case by case, and From 48467e6ee4fa21801b51af19e442467b81ef7f1e Mon Sep 17 00:00:00 2001 From: Anouar Moustaj Date: Fri, 13 Nov 2026 01:46:37 +0200 Subject: [PATCH 11/22] Address the review of the fixes commits An independent review of daff2aa..9795a20 confirmed the BdG, TDVP and TT-SVD numerics (including a full Fock-space check of the BdG spectrum) and found the following, each reproduced here: - build_K: the norm of K grows like 2^L, and zip-up's apply(H - w, H - w) drops a term that lives on a few sites once cutoff_K exceeds about 0.3*4^-L. On a uniform open chain <0|K|0> = 2.01 instead of 1.01 (the end bond lost) at L = 16 with the old and current default 1e-8 (eta >= 0.1) and at L = 20 with the new default at eta = 0.01; fine at L = 12. A cutoff below the bound keeps K exact (1e-10 at L = 20 and 24 with the default divided by 2^L). The default is unchanged (a size-aware default moves eta >= 0.1 results, a decision for later); build_K now warns once when cutoff_K > 0.3/D^2 and the docstring states the limit. - The vector TT-SVD and the dense readout built an order-L ITensor, so ITensors printed a contraction warning with a backtrace from L = 14 and compiled per tensor order (14-45 s first calls). Both now work on plain arrays site by site (LinearAlgebra.svd, matrix products); L = 20 takes 0.3 s and prints nothing. _mps_entry reads many entries from precomputed site arrays. - Abstractly typed vectors (Vector{Any}) failed in float(eltype); the element type is now promoted from the entries. - check=true above 2^20 points cannot see a feature between its sampled points (as documented); an @info now says so once. - check_tdvp_vs_U_mpo(...; tdvp_reverse_step=false) warns under its own name and keyword. - The BdG helpers build -M*, the hole block of a Hermitian term; for a non-Hermitian term it would be -M^T, which neither build gives. Documented as a requirement. Tests: the size warning and the exact K below the bound at L = 16; check_tdvp's warning; Vector{Any}/Vector{Real} profiles; an L = 16 vector with nothing printed. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 12 +++- src/core/AuxDOF.jl | 8 ++- src/core/Utils.jl | 111 ++++++++++++++++++++++++++++------- src/solvers/DMRG.jl | 17 ++++++ src/solvers/Timeev.jl | 5 +- test/bugfix_build_K.jl | 10 ++++ test/bugfix_qtci_profiles.jl | 13 ++++ test/bugfix_tdvp.jl | 9 +++ 8 files changed, 158 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index adfceb2..ed1da0b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,7 +26,8 @@ bugs without breaking the API. than `√tol · max|f|`; up to 2^20 points every point is compared and a wrong build (or a throw) is replaced by the TT-SVD of the values, above that a sample is compared (ends, carry boundaries, a golden-ratio stride) and a wrong build is redone from the missed - points as pivots, then checked again (an error if it still fails). As in + points as pivots, then checked again (an error if it still fails); a feature between + the sampled points goes unchecked there, which an `@info` says once. As in `hopping2MPO(...; check=true)`, a build that passes is returned unchanged. ### Changed @@ -80,7 +81,8 @@ bugs without breaking the API. one-term `τ_z ⊗ H` it got before, so every result with a real Hamiltonian is unchanged bit for bit (no golden case moves). The `bdg_spin_hamiltonian` docstring named the basis `(c↑, c↓, c†↓, −c†↑)`, in which its `iσ_y` pairing would vanish; it now names the basis - the code uses. + the code uses. `H` must be Hermitian, as before: for a non-Hermitian `H` the hole block + would be `−Hᵀ`, which neither build gives (now documented). - **`build_K` and `dmrg_spectral`: `cutoff_K` defaults to `min(1e-8, 1e-4·η⁴)`.** The cutoff is relative to the squared norm of each sum and product, and `η² I` is the smallest part of `K = (H − ω)² + η²`, so the fixed default `1e-8` truncated most of it @@ -89,6 +91,12 @@ bugs without breaking the API. bit; below η = 0.1, K and the DMRG results built on it move. An explicit `cutoff_K ≥ η⁴` is used as given and warns once. The default assumes eigenvalues of `H − ω` of order one; pass a smaller `cutoff_K` for a wider spectrum. + It does not fix large systems: the norm of K grows like 2^L, and once `cutoff_K` + exceeds about `0.3·4^(−L)` the product drops terms that live on a few sites, such as the + end bond of an open chain (K wrong by t² there: from L ≈ 14 with the default at + η ≥ 0.1, the v0.2.0 behaviour, and at L = 20 with the default at η = 0.01). `build_K` + now warns once in that regime and uses the value as given; the docstring gives the + bound (a cutoff below it keeps K exact: errors of 1e-10 at L = 20 and 24). ### Fixed diff --git a/src/core/AuxDOF.jl b/src/core/AuxDOF.jl index 06da6ae..d95bb69 100644 --- a/src/core/AuxDOF.jl +++ b/src/core/AuxDOF.jl @@ -260,7 +260,10 @@ _mpo_is_real(M::MPO) = all(T -> eltype(T) <: Real || all(isreal, Array(T, inds(T # one term as before, so real Hamiltonians give the same MPO bit for bit. Up to v0.2.0 # every M got τz ⊗ M, whose hole block −M flips the sign of the imaginary entries (σ_y # terms, Peierls phases, complex hoppings). `dag` conjugates each tensor and keeps the -# primes, so `-dag(M)` is −M*. +# primes, so `-dag(M)` is −M*. The hole block of a general quadratic term is −Mᵀ, which is +# −M* only for a Hermitian M: a non-Hermitian term (loss, nonreciprocal hopping) would need +# −Mᵀ, which neither this nor the τz build gives, so BdG of non-Hermitian Hamiltonians is +# not supported. function _nambu_normal_block(M::MPO, s::Index, side::Symbol; cutoff::Real) attach = side === :pre ? prepend_nambu : postpend_nambu _mpo_is_real(M) && return attach(M, s, :tz) @@ -390,7 +393,8 @@ The BdG structure, in the Nambu basis `(c↑, c↓, c†↑, c†↓)` (spinless with `P_p`, `P_h` the particle and hole projectors of the Nambu index. For a real `H` the first two terms are `τ_z ⊗ H`, built as one term; up to v0.2.0 every `H` got `τ_z ⊗ H`, which is wrong when `H` has imaginary entries (a Zeeman field along y, -Peierls phases, complex hoppings). +Peierls phases, complex hoppings). `H` must be Hermitian: for a non-Hermitian `H` (loss, +nonreciprocal hopping) the hole block is `−Hᵀ`, which is not built. - **Spinless + p-wave** (`type=:pwave`, or auto-selected when spinless + `:swave`): `H_pair = Δ·(K_forward − K_backward)`, the antisymmetric nearest-neighbour diff --git a/src/core/Utils.jl b/src/core/Utils.jl index e5bd099..1800e5b 100644 --- a/src/core/Utils.jl +++ b/src/core/Utils.jl @@ -1208,7 +1208,7 @@ end # A vector needs no check (TT-SVD samples nothing); `check` is accepted for generic callers. get_mps(L::Int, sites, v::AbstractVector; type=nothing, tol::Real=1e-8, check::Bool=false) = - _ttsvd_mps(L, sites, type === nothing ? v : convert(Vector{type}, v); tol=tol) + _ttsvd_mps(L, sites, type === nothing ? v : convert(Vector{type}, collect(v)); tol=tol) # The QTCI build of get_mps (what it runs without `check`). function _qtci_mps(L::Int, sites, f; type, tol) @@ -1225,40 +1225,105 @@ function _qtci_mps(L::Int, sites, f; type, tol) return MPS(tt; sites=collect(sites)) end +# The helpers below (TT-SVD, dense readout, single entries) work on plain arrays, site by +# site: an order-L ITensor would make ITensors print a contraction warning from L = 14 on +# and compile code for every tensor order. + +# A concrete number type for the values of a profile vector (an abstractly typed vector, +# Vector{Any} or Vector{Real}, gets the promoted type of its entries). +_profile_eltype(v::AbstractVector) = + float(isconcretetype(eltype(v)) ? eltype(v) : mapreduce(typeof, promote_type, v)) + +# The number of singular values `S` (sorted, largest first) to keep so that the discarded +# weight Σ S² stays within `cutoff` times the total, as ITensors' relative cutoff. +function _svd_keep(S, cutoff) + total = sum(abs2, S) + χ = length(S) + iszero(total) && return 1 + discarded = zero(total) + while χ > 1 && discarded + abs2(S[χ]) <= cutoff * total + discarded += abs2(S[χ]) + χ -= 1 + end + return χ +end + # TT-SVD of the 2^L values v (v[n+1] at n = 0 … 2^L-1, site 1 the most significant bit, -# as the QTCI builders): sequential SVDs with the relative cutoff tol²/2^L per bond, so -# that the discarded weight stays below (L-1)·tol²·max|v|² and every entry within about -# √L·tol·max|v|. +# as the QTCI builders): sequential SVDs from site 1 with the relative cutoff tol²/2^L per +# bond, so that the discarded weight stays below (L-1)·tol²·max|v|² and every entry within +# about √L·tol·max|v|. function _ttsvd_mps(L::Int, sites, v::AbstractVector; tol::Real) N = 2^L length(v) == N || throw(DimensionMismatch("a profile on L = $L qubits needs 2^L = $N values, got $(length(v))")) length(sites) == L || throw(DimensionMismatch("$(length(sites)) sites for L = $L")) - T = float(eltype(v)) - iszero(maximum(abs, v)) && return constant_mps(collect(sites), zero(T)) - A = permutedims(reshape(collect(T, v), ntuple(_ -> 2, L)), L:-1:1) # dim 1 = site 1 (MSB) - return MPS(A, collect(sites); cutoff=tol^2 / N) + T = _profile_eltype(v) + vals = collect(T, v) + iszero(maximum(abs, vals)) && return constant_mps(collect(sites), zero(T)) + L == 1 && return MPS([ITensor(vals, sites[1])]) + # C[b_1, b_2, …, b_L]: dimension k is the bit of site k (v is stored with the least + # significant bit fastest), so each reshape below fuses (left link, bit k) with the + # link fastest, and the rest (b_{k+1}, …) with b_{k+1} fastest. + M = reshape(permutedims(reshape(vals, ntuple(_ -> 2, L)), L:-1:1), 2, :) + cutoff = tol^2 / N + tensors = ITensor[] + left = nothing + for k in 1:L-1 + F = svd(M) + χ = _svd_keep(F.S, cutoff) + right = Index(χ, "Link,l=$k") + U = F.U[:, 1:χ] + push!(tensors, left === nothing ? ITensor(U, sites[k], right) : + ITensor(reshape(U, dim(left), 2, χ), left, sites[k], right)) + R = Diagonal(F.S[1:χ]) * F.Vt[1:χ, :] # (χ, rest), rest = (b_{k+1}, …) + M = reshape(R, 2χ, :) + left = right + end + push!(tensors, ITensor(reshape(M, dim(left), 2), left, sites[L])) + return MPS(tensors) +end + +# The site tensors of an MPS on the qubit `sites` as arrays A[k][left, bit, right] (several +# link indices on a bond merged; dimension 1 at the ends). +function _mps_site_arrays(mps::MPS, sites) + n = length(mps) + links = [collect(commoninds(mps[k], mps[k + 1])) for k in 1:n - 1] + return map(1:n) do k + lk = k > 1 ? links[k - 1] : Index[] + rk = k < n ? links[k] : Index[] + reshape(Array(mps[k], lk..., sites[k], rk...), + prod(dim, lk; init=1), dim(sites[k]), prod(dim, rk; init=1)) + end end # The entries of an MPS on qubit `sites` as a dense vector, v[n+1] at n = 0 … 2^L-1 (site # 1 the most significant bit; eval_mps keeps only the real part). function _mps_dense_vector(mps::MPS, sites) - T = mps[1] - for k in 2:length(mps) - T *= mps[k] + A = _mps_site_arrays(mps, sites) + T = mapreduce(eltype, promote_type, A) + V = ones(T, 1, 1) # (prefixes n_k, link) + for Ak in A + P = size(V, 1) + W = Array{T}(undef, size(Ak, 2), P, size(Ak, 3)) + for b in axes(Ak, 2) + W[b, :, :] = V * Ak[:, b, :] + end + V = reshape(W, size(Ak, 2) * P, size(Ak, 3)) # row n_{k+1} = 2 n_k + bit end - return vec(Array(T, reverse(collect(sites))...)) + return vec(V) end -# The entry of an MPS on qubit `sites` at the 0-indexed n (site 1 the most significant bit). -function _mps_entry(mps::MPS, sites, n::Integer) - L = length(sites) - acc = ITensor(1.0) - for k in 1:L - acc *= mps[k] * onehot(sites[k] => ((n >> (L - k)) & 1) + 1) +# The entry at the 0-indexed n (site 1 the most significant bit) of an MPS, or of its site +# arrays from _mps_site_arrays (to read many entries). +_mps_entry(mps::MPS, sites, n::Integer) = _mps_entry(_mps_site_arrays(mps, sites), n) +function _mps_entry(A::AbstractVector{<:AbstractArray}, n::Integer) + L = length(A) + v = A[1][:, ((n >> (L - 1)) & 1) + 1, :] + for k in 2:L + v = v * A[k][:, ((n >> (L - k)) & 1) + 1, :] end - return scalar(acc) + return only(v) end # The first entry of `got` off `want` by more than √tol·max|want|, as (index, got, want), @@ -1300,8 +1365,11 @@ function _checked_qtci_mps(L::Int, sites, f; type, tol) return _ttsvd_mps(L, sites, vals; tol=tol) end pts = _profile_sample_points(L) + @info "get_mps(...; check=true): above 2^20 points the check compares $(length(pts)) " * + "sampled points only, so a feature between them goes unchecked; pass the values " * + "as a vector for an exact build." maxlog=1 vals = type[f(n) for n in pts] - got = qtci === nothing ? nothing : [_mps_entry(qtci, sites, n) for n in pts] + got = qtci === nothing ? nothing : (A = _mps_site_arrays(qtci, sites); [_mps_entry(A, n) for n in pts]) got !== nothing && _profile_mismatch(got, vals, tol) === nothing && return qtci all(iszero, vals) && error("get_mps: f vanishes at all $(length(pts)) sampled points and QTCI found no " * @@ -1318,7 +1386,8 @@ function _checked_qtci_mps(L::Int, sites, f; type, tol) [[pts[k] + 1] for k in piv]; nrandominitpivot=0, tolerance=tol) mps = MPS(TensorCrossInterpolation.tensortrain(qtt.tci); sites=collect(sites)) - bad = _profile_mismatch([_mps_entry(mps, sites, n) for n in pts], vals, tol) + A = _mps_site_arrays(mps, sites) + bad = _profile_mismatch([_mps_entry(A, n) for n in pts], vals, tol) bad === nothing && return mps k, g, w = bad error("get_mps: the QTCI-compressed profile is wrong at n = $(pts[k]): $g instead of $w, " * diff --git a/src/solvers/DMRG.jl b/src/solvers/DMRG.jl index b5a33e7..bf6e17f 100644 --- a/src/solvers/DMRG.jl +++ b/src/solvers/DMRG.jl @@ -82,6 +82,17 @@ v0.2.0: ‖ΔK‖ = 9.7e-5 ≈ η²). The default is `1e-8` for η ≥ 0.1 (and and `1e-4 η⁴` below, which assumes eigenvalues of H − ω of order one: for a wider spectrum pass a smaller `cutoff_K`. A `cutoff_K` of η⁴ or more is used as given and warns. + +!!! warning "Large systems" + The norm of K grows like 2^L, so a term that lives on a few sites, such as the + missing bond at the end of an open chain, falls below the cutoff in large systems: + the product `apply(H − ω, H − ω)` then drops it once `cutoff_K` exceeds about + `0.3·4^(−L)`. On a uniform chain (ω = 0.05) `⟨0|K|0⟩` comes out as 2.01 instead of + 1.01, K wrong by t² at both ends, from L ≈ 14 with the default at η ≥ 0.1 and at + L = 20 with the default at η = 0.01. A cutoff below that bound keeps K exact: the + default divided by 2^L, which stays below it up to L = 24 at η ≥ 0.1, gives errors of + 1e-10 at L = 20 and 24. `build_K` warns once when `cutoff_K` is above `0.3/D²`, D the + dimension of the site space (2^L for qubits), and uses the value as given. """ function build_K(H_mpo::MPO, sites, ω::Real, η::Real; maxdim_K::Int = 200, @@ -90,6 +101,12 @@ function build_K(H_mpo::MPO, sites, ω::Real, η::Real; η != 0 && cutoff_K >= η^4 && @warn "build_K: cutoff_K = $cutoff_K is not below η⁴ = $(η^4); the truncation of " * "K = (H − ω)² + η² can drop its η² term (the default is min(1e-8, 1e-4η⁴))." maxlog=1 + D = prod(Float64 ∘ dim, sites) + cutoff_K > 0.3 / D^2 && + @warn "build_K: cutoff_K = $cutoff_K on $(length(sites)) sites can drop the terms of K " * + "that live on a few sites, such as the end bond of an open chain (K wrong by t² " * + "there); keep it well below 0.3/D² = $(0.3 / D^2) (D the dimension of the " * + "site space)." maxlog=1 I_mpo = MPO(sites, "Id") H_shift = +(H_mpo, (-ω) * I_mpo; cutoff = cutoff_K) H_sq = apply(H_shift, H_shift; cutoff = cutoff_K, maxdim = maxdim_K) diff --git a/src/solvers/Timeev.jl b/src/solvers/Timeev.jl index 36d2122..02a09ec 100644 --- a/src/solvers/Timeev.jl +++ b/src/solvers/Timeev.jl @@ -57,8 +57,8 @@ end # projector splitting needs: terms of H are then counted twice and every step is wrong # at O(dt). It was the default of the state-evolution functions up to v0.2.0; passing it # now warns once per function (build_tdvp_propagator_mpo has its own warning). -_warn_no_reverse_step(fname, reverse_step) = - reverse_step || @warn "$fname: reverse_step=false skips TDVP's backward bond evolution " * +_warn_no_reverse_step(fname, reverse_step; keyword = "reverse_step") = + reverse_step || @warn "$fname: $keyword=false skips TDVP's backward bond evolution " * "and counts terms of H twice; each step is wrong at O(dt)." maxlog=1 _id=Symbol(fname) # The trajectory loop of every evolve_* function: returns [x0, x1, …, x_nsteps] @@ -564,6 +564,7 @@ function check_tdvp_vs_U_mpo( print_sample_amplitudes = true, sample_amplitudes = [0, 1, 2, 3], ) + _warn_no_reverse_step("check_tdvp_vs_U_mpo", tdvp_reverse_step; keyword = "tdvp_reverse_step") println("Checking TDVP evolution against applying U_mpo") println("L = $L, dt = $dt") println() diff --git a/test/bugfix_build_K.jl b/test/bugfix_build_K.jl index 5e87c1a..66036ff 100644 --- a/test/bugfix_build_K.jl +++ b/test/bugfix_build_K.jl @@ -24,4 +24,14 @@ using TensorBinding: get_Hamiltonian, add_onsite!, build_K, get_matrix @test (@test_logs min_level=Logging.Warn Kd(η)) == Kd(η; cutoff_K=1e-8) end @test TensorBinding._default_cutoff_K(0.05) ≈ 1e-4 * 0.05^4 + + # Large systems: a cutoff above about 0.3·4^(-L) drops the end bond of an open chain + # (<0|K|0> = 2.01 instead of 1.01 at L = 16 with 1e-8); build_K warns there, and a + # cutoff below the bound keeps K exact. + L16 = 16 + H16 = get_Hamiltonian("chain_1d", 1.0; L=L16) + ψ0 = TensorBinding.binary_to_MPS(0, L16, H16.sites) + @test_logs (:warn, r"live on a few sites") build_K(H16.mpo, H16.sites, ω, 0.1) + K16 = build_K(H16.mpo, H16.sites, ω, 0.1; cutoff_K = 1e-8 / 2^L16) + @test abs(real(inner(ψ0', K16, ψ0)) - (ω^2 + 1 + 0.1^2)) < 1e-8 end diff --git a/test/bugfix_qtci_profiles.jl b/test/bugfix_qtci_profiles.jl index 87c2484..e661dc4 100644 --- a/test/bugfix_qtci_profiles.jl +++ b/test/bugfix_qtci_profiles.jl @@ -30,6 +30,19 @@ _diag(M::MPO, sites) = _TBq._mps_dense_vector(extract_diagonal_to_mps(M), sites) @test _TBq._mps_dense_vector(get_mps(1, s1, [2.0, -1.0]), s1) ≈ [2.0, -1.0] @test_throws DimensionMismatch get_diagonal_mpo(L, s, vbox[1:end-1]) @test maxlinkdim(get_mps(L, s, vbox)) <= 4 # a box is low rank + # abstractly typed vectors + s3 = siteinds("Qubit", 3) + @test _TBq._mps_dense_vector(get_mps(3, s3, Any[1.0, 2, 3, 4, 5, 6, 7, 8]), s3) ≈ 1.0:8.0 + @test _TBq._mps_dense_vector(get_mps(3, s3, Real[1, 2.5, 3, 4, 5, 6, 7, 8]), s3) ≈ [1, 2.5, 3, 4, 5, 6, 7, 8] + # L = 16: plain-array TT-SVD and readout, so ITensors prints no order-16 contraction warning + L16 = 16; s16 = siteinds("Qubit", L16) + v16 = [x == 40_000 ? 1.0 : 0.0 for x in 1:2^L16] + path, io = mktemp() + m16 = redirect_stdout(() -> get_mps(L16, s16, v16), io) + d16 = redirect_stdout(() -> _TBq._mps_dense_vector(m16, s16), io) + close(io) + @test isempty(read(path, String)); rm(path) + @test maximum(abs.(d16 .- v16)) < 1e-10 end @testset "check=true on a function" begin diff --git a/test/bugfix_tdvp.jl b/test/bugfix_tdvp.jl index 6745d88..537246d 100644 --- a/test/bugfix_tdvp.jl +++ b/test/bugfix_tdvp.jl @@ -96,4 +96,13 @@ end ψf = @test_logs (:warn, r"tdvp_evolve: reverse_step=false") tdvp_evolve(H, ψ0, dt; normalize = false, reverse_step = false) @test norm(ψf - ex1) > 0.01 @test_logs (:warn, r"evolve_with_tdvp: reverse_step=false") evolve_with_tdvp(H, ψ0, 1, dt; reverse_step = false) + + # check_tdvp_vs_U_mpo names its own keyword + H2 = get_Hamiltonian("chain_1d", 1.0; L = 2) + seed!(3) + U2 = build_tdvp_propagator_mpo(H2, dt) + @test_logs (:warn, r"check_tdvp_vs_U_mpo: tdvp_reverse_step=false") match_mode=:any redirect_stdout(devnull) do + TensorBinding.check_tdvp_vs_U_mpo(H2, U2, dt; test_states = [0], tdvp_reverse_step = false, + print_sample_amplitudes = false) + end end From 722145cb92420edd0983a965fc58d7392526459b Mon Sep 17 00:00:00 2001 From: Anouar Moustaj Date: Fri, 13 Nov 2026 08:54:17 +0200 Subject: [PATCH 12/22] Make build_K's default cutoff_K size-aware: min(1e-8, 1e-4 eta^4, 0.1/D^2) cutoff_K is relative to the squared norm of each sum and product, and the norm of K = (H - omega)^2 + eta^2 grows with D, the dimension of the site space (2^L for qubits). The zip-up product apply(H - omega, H - omega) therefore drops a term that lives on a few sites once cutoff_K exceeds about 0.5/D^2: on an open chain (omega = 0.05, eta = 0.1) the end bond is kept at 0.3/D^2 and lost at 0.7/D^2 to 1/D^2 (L = 12-16), and the v0.2.0 default 1e-8 gave <0|K|0> = 2.01 instead of 1.01 from L = 13 on, K wrong by t^2 at both ends (the eta-only default min(1e-8, 1e-4 eta^4) from L = 20 at eta = 0.01). The default adds 0.1/D^2: 1e-8 for eta >= 0.1 (and eta = 0) up to L = 11, so those results are unchanged bit for bit (the golden DMRG cases are at L = 3 and pass unchanged); from L = 12 on it is smaller. On an open chain with an exact H it keeps five probed elements of K (both ends, bulk, <0|K|2>, the wrap) to 2e-7 up to L = 30 (2.2e-8 with the untruncated kinetic_1d_nn); the build costs the same (bond dimension 6, under 0.1 s). With H from get_Hamiltonian("chain_1d") K is wrong again from L = 26, because that MPO is truncated at a relative 1e-8 itself and loses the hop across the middle: a separate, pre-existing issue, not changed here. The size warning (cutoff_K > 0.3/D^2) stays; the docstring replaces the "Large systems" admonition by the three bounds of the default. Test: the default at L = 16 keeps the end bond without a warning; an explicit 1e-8 warns and loses it; _default_cutoff_K at L = 5, 11, 12, 16. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 29 +++++++++--------- src/solvers/DMRG.jl | 67 +++++++++++++++++++++++------------------- test/bugfix_build_K.jl | 32 +++++++++++++------- 3 files changed, 73 insertions(+), 55 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ed1da0b..e89b7a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -83,20 +83,21 @@ bugs without breaking the API. `(c↑, c↓, c†↓, −c†↑)`, in which its `iσ_y` pairing would vanish; it now names the basis the code uses. `H` must be Hermitian, as before: for a non-Hermitian `H` the hole block would be `−Hᵀ`, which neither build gives (now documented). -- **`build_K` and `dmrg_spectral`: `cutoff_K` defaults to `min(1e-8, 1e-4·η⁴)`.** The - cutoff is relative to the squared norm of each sum and product, and `η² I` is the - smallest part of `K = (H − ω)² + η²`, so the fixed default `1e-8` truncated most of it - at small η: on a 5-qubit chain at η = 1e-2, ‖ΔK‖ = 9.7e-5 ≈ η² (now below 1e-7). The - default stays `1e-8` for η ≥ 0.1 and for η = 0, so those results are unchanged bit for - bit; below η = 0.1, K and the DMRG results built on it move. An explicit - `cutoff_K ≥ η⁴` is used as given and warns once. The default assumes eigenvalues of - `H − ω` of order one; pass a smaller `cutoff_K` for a wider spectrum. - It does not fix large systems: the norm of K grows like 2^L, and once `cutoff_K` - exceeds about `0.3·4^(−L)` the product drops terms that live on a few sites, such as the - end bond of an open chain (K wrong by t² there: from L ≈ 14 with the default at - η ≥ 0.1, the v0.2.0 behaviour, and at L = 20 with the default at η = 0.01). `build_K` - now warns once in that regime and uses the value as given; the docstring gives the - bound (a cutoff below it keeps K exact: errors of 1e-10 at L = 20 and 24). +- **`build_K` and `dmrg_spectral`: `cutoff_K` defaults to `min(1e-8, 1e-4·η⁴, 0.1/D²)`**, + D the dimension of the site space (2^L for qubits). The cutoff is relative to the + squared norm of each sum and product, so the fixed default `1e-8` dropped the two + smallest parts of `K = (H − ω)² + η²`. At small η it truncated most of `η² I`: on a + 5-qubit chain at η = 1e-2, ‖ΔK‖ = 9.7e-5 ≈ η² (now below 1e-7); the `1e-4·η⁴` bound + assumes eigenvalues of `H − ω` of order one, so pass a smaller `cutoff_K` for a wider + spectrum. In large systems it dropped the terms that live on a few sites, such as the + end bond of an open chain: the norm of K grows with D, and the product drops such a + term once `cutoff_K` exceeds about `0.5/D²`, so on a uniform chain `⟨0|K|0⟩` was 2.01 + instead of 1.01 (K wrong by t² at both ends) from L = 13 on; with the new default K + stays within 2e-7 up to L = 30, the largest size tested, given an exact MPO of H. The + default stays `1e-8` for η ≥ 0.1 (and η = 0) up to L = 11, so those results are + unchanged bit for bit (no golden case moves); below η = 0.1, or from L = 12 on, K and + the DMRG results built on it move. An explicit `cutoff_K` is used as given and warns + once when it is not below `η⁴` or when it is above `0.3/D²`. ### Fixed diff --git a/src/solvers/DMRG.jl b/src/solvers/DMRG.jl index bf6e17f..dd40724 100644 --- a/src/solvers/DMRG.jl +++ b/src/solvers/DMRG.jl @@ -62,7 +62,7 @@ end # ============================================================ """ - build_K(H_mpo::MPO, sites, ω, η; maxdim_K=200, cutoff_K=min(1e-8, 1e-4η⁴)) -> MPO + build_K(H_mpo::MPO, sites, ω, η; maxdim_K=200, cutoff_K=min(1e-8, 1e-4η⁴, 0.1/D²)) -> MPO Build the resolvent-squared MPO @@ -75,47 +75,52 @@ eigenstate of H nearest to ω. `maxdim_K` and `cutoff_K` control truncation of the intermediate MPO product; larger `maxdim_K` gives a more accurate K at the cost of DMRG wall time. -`cutoff_K` is relative (to the squared Frobenius norm of each sum and product), and -`η² I` is the smallest part of K: from `cutoff_K ≈ η⁴` on, the truncation can drop it -(a 5-qubit chain at η = 1e-2 kept almost none of it with the fixed default `1e-8` of -v0.2.0: ‖ΔK‖ = 9.7e-5 ≈ η²). The default is `1e-8` for η ≥ 0.1 (and η = 0), as before, -and `1e-4 η⁴` below, which assumes eigenvalues of H − ω of order one: for a wider -spectrum pass a smaller `cutoff_K`. A `cutoff_K` of η⁴ or more is used as given and -warns. - -!!! warning "Large systems" - The norm of K grows like 2^L, so a term that lives on a few sites, such as the - missing bond at the end of an open chain, falls below the cutoff in large systems: - the product `apply(H − ω, H − ω)` then drops it once `cutoff_K` exceeds about - `0.3·4^(−L)`. On a uniform chain (ω = 0.05) `⟨0|K|0⟩` comes out as 2.01 instead of - 1.01, K wrong by t² at both ends, from L ≈ 14 with the default at η ≥ 0.1 and at - L = 20 with the default at η = 0.01. A cutoff below that bound keeps K exact: the - default divided by 2^L, which stays below it up to L = 24 at η ≥ 0.1, gives errors of - 1e-10 at L = 20 and 24. `build_K` warns once when `cutoff_K` is above `0.3/D²`, D the - dimension of the site space (2^L for qubits), and uses the value as given. +`cutoff_K` is relative (to the squared Frobenius norm of each sum and product). The +default is the smallest of `1e-8`, the fixed value of v0.2.0, and two bounds that keep +the two smallest parts of K: +- `1e-4 η⁴` (η ≠ 0) keeps `η² I`, which the truncation can drop from `cutoff_K ≈ η⁴` on + (a 5-qubit chain at η = 1e-2 kept almost none of it with `1e-8`: ‖ΔK‖ = 9.7e-5 ≈ η²). + It assumes eigenvalues of H − ω of order one: for a wider spectrum pass a smaller + `cutoff_K`. +- `0.1/D²`, D the dimension of the site space (2^L for qubits), keeps the terms that live + on a few sites, such as the missing bond at the end of an open chain. The norm of K + grows with D, and the product `apply(H − ω, H − ω)` drops such a term once `cutoff_K` + exceeds about `0.5/D²` (measured on a uniform chain, L = 12–16): with `1e-8`, + `⟨0|K|0⟩` came out as 2.01 instead of 1.01 from L = 13 on, K wrong by t² at both ends. + +The default is therefore `1e-8`, as in v0.2.0, for η ≥ 0.1 (and η = 0) up to L = 11. On +an open chain (ω = 0.05) it keeps K to within 2e-7 up to L = 30, the largest size tested, +provided `H_mpo` itself is exact: an MPO truncated with a relative cutoff of its own can +already lack such terms. An explicit `cutoff_K` is used as given; it warns once when it +is not below η⁴ or when it is above `0.3/D²`. """ function build_K(H_mpo::MPO, sites, ω::Real, η::Real; maxdim_K::Int = 200, cutoff_K::Union{Nothing,Real} = nothing) - cutoff_K = something(cutoff_K, _default_cutoff_K(η)) + D = prod(Float64 ∘ dim, sites) + cutoff_K = something(cutoff_K, _default_cutoff_K(η, D)) η != 0 && cutoff_K >= η^4 && @warn "build_K: cutoff_K = $cutoff_K is not below η⁴ = $(η^4); the truncation of " * - "K = (H − ω)² + η² can drop its η² term (the default is min(1e-8, 1e-4η⁴))." maxlog=1 - D = prod(Float64 ∘ dim, sites) + "K = (H − ω)² + η² can drop its η² term (the default is " * + "min(1e-8, 1e-4η⁴, 0.1/D²))." maxlog=1 cutoff_K > 0.3 / D^2 && @warn "build_K: cutoff_K = $cutoff_K on $(length(sites)) sites can drop the terms of K " * "that live on a few sites, such as the end bond of an open chain (K wrong by t² " * - "there); keep it well below 0.3/D² = $(0.3 / D^2) (D the dimension of the " * - "site space)." maxlog=1 + "there); keep it below 0.3/D² = $(0.3 / D^2), D the dimension of the site " * + "space (the default is at most 0.1/D²)." maxlog=1 I_mpo = MPO(sites, "Id") H_shift = +(H_mpo, (-ω) * I_mpo; cutoff = cutoff_K) H_sq = apply(H_shift, H_shift; cutoff = cutoff_K, maxdim = maxdim_K) return +(H_sq, (η^2) * I_mpo; cutoff = cutoff_K) end -# The default cutoff_K of build_K and dmrg_spectral: the fixed 1e-8 of v0.2.0 where it -# keeps the η² I term of K (η ≥ 0.1, or η = 0, where there is none), 1e-4 η⁴ below. -_default_cutoff_K(η::Real) = iszero(η) ? 1e-8 : min(1e-8, 1e-4 * Float64(η)^4) +# The default cutoff_K of build_K and dmrg_spectral: the fixed 1e-8 of v0.2.0, lowered to +# 1e-4 η⁴ to keep the η² I term of K (η < 0.1; η = 0 has none) and to 0.1/D² to keep the +# terms that live on a few sites (D the dimension of the site space: from L = 12 qubits). +function _default_cutoff_K(η::Real, D::Real) + c = min(1e-8, 0.1 / Float64(D)^2) + return iszero(η) ? c : min(c, 1e-4 * Float64(η)^4) +end # ============================================================ @@ -124,7 +129,7 @@ _default_cutoff_K(η::Real) = iszero(η) ? 1e-8 : min(1e-8, 1e-4 * Float64(η)^4 """ dmrg_spectral(H_mpo::MPO, sites, ω, η; ψ0=nothing, maxdim_K=200, - cutoff_K=min(1e-8, 1e-4η⁴), linkdim_init=10, nsweeps=10, + cutoff_K=min(1e-8, 1e-4η⁴, 0.1/D²), linkdim_init=10, nsweeps=10, maxdim=[10, 20, 50, 100, 200], cutoff=1e-8, noise=[1e-6, 1e-7, 1e-8, 0.0], kwargs...) -> (E_K, ψ) @@ -136,8 +141,10 @@ Use `local_weight(ψ, i, L, sites)` to read off the LDoS proxy `|⟨i|ψ(ω)⟩| # Keyword arguments - `ψ0` : warm-start MPS (random if `nothing`, the default) - `maxdim_K`, `cutoff_K` : truncation for building K (see `build_K`). Defaults - `200` and `min(1e-8, 1e-4η⁴)` (`1e-8` up to v0.2.0, which - drops most of the η² term at η = 1e-2). + `200` and `min(1e-8, 1e-4η⁴, 0.1/D²)`, D the dimension of + the site space (`1e-8` up to v0.2.0, which drops most of the + η² term at η = 1e-2 and the end bonds of an open chain from + L = 13). - `linkdim_init` : bond dimension of the random initial MPS (if ψ0=nothing). Default `10`. - `nsweeps`, `maxdim`, `cutoff`, `noise` : DMRG sweep parameters, with the same diff --git a/test/bugfix_build_K.jl b/test/bugfix_build_K.jl index 66036ff..9f803bb 100644 --- a/test/bugfix_build_K.jl +++ b/test/bugfix_build_K.jl @@ -2,10 +2,12 @@ using TensorBinding, ITensors, ITensorMPS, LinearAlgebra, Test, Logging, Random using TensorBinding: get_Hamiltonian, add_onsite!, build_K, get_matrix # build_K's cutoff_K was a fixed 1e-8, relative to ‖K‖², so at small η the truncation -# dropped the η² I term of K = (H − ω)² + η² (η = 1e-2 on this chain: ‖ΔK‖ = 9.7e-5 ≈ η²). -# The default is now min(1e-8, 1e-4 η⁴): 1e-8 as before for η ≥ 0.1 (and η = 0), smaller -# below; an explicit cutoff_K ≥ η⁴ is used as given and warns. -@testset "build_K: cutoff_K default scales with η" begin +# dropped the η² I term of K = (H − ω)² + η² (η = 1e-2 on this chain: ‖ΔK‖ = 9.7e-5 ≈ η²), +# and in large systems the terms that live on a few sites (the end bond of an open chain +# from L = 13). The default is now min(1e-8, 1e-4 η⁴, 0.1/D²): 1e-8 as before for η ≥ 0.1 +# (and η = 0) up to L = 11, smaller below; an explicit cutoff_K ≥ η⁴ or > 0.3/D² is used +# as given and warns. +@testset "build_K: cutoff_K default scales with η and system size" begin H = get_Hamiltonian("chain_1d", 1.0; L=5) Random.seed!(11) add_onsite!(H, n -> 0.3 * cos(2π * 0.618 * n)) @@ -23,15 +25,23 @@ using TensorBinding: get_Hamiltonian, add_onsite!, build_K, get_matrix for η in (0.1, 0.3, 0.0) @test (@test_logs min_level=Logging.Warn Kd(η)) == Kd(η; cutoff_K=1e-8) end - @test TensorBinding._default_cutoff_K(0.05) ≈ 1e-4 * 0.05^4 + dc = TensorBinding._default_cutoff_K + @test dc(0.05, 2.0^5) ≈ 1e-4 * 0.05^4 + @test dc(0.1, 2.0^11) == 1e-8 == dc(0.0, 2.0^11) # unchanged up to L = 11 + @test dc(0.1, 2.0^12) ≈ 0.1 / 4.0^12 + @test dc(0.0, 2.0^16) ≈ 0.1 / 4.0^16 + @test dc(0.01, 2.0^16) ≈ 1e-12 # η bound below the size bound - # Large systems: a cutoff above about 0.3·4^(-L) drops the end bond of an open chain - # (<0|K|0> = 2.01 instead of 1.01 at L = 16 with 1e-8); build_K warns there, and a - # cutoff below the bound keeps K exact. + # Large systems: a cutoff above about 0.5·4^(-L) drops the end bond of an open chain + # (<0|K|0> = 2.01 instead of 1.01 at L = 16 with 1e-8, the v0.2.0 default). The default + # (here 0.1·4^(-16)) keeps it without a warning; an explicit 1e-8 warns and loses it. L16 = 16 H16 = get_Hamiltonian("chain_1d", 1.0; L=L16) ψ0 = TensorBinding.binary_to_MPS(0, L16, H16.sites) - @test_logs (:warn, r"live on a few sites") build_K(H16.mpo, H16.sites, ω, 0.1) - K16 = build_K(H16.mpo, H16.sites, ω, 0.1; cutoff_K = 1e-8 / 2^L16) - @test abs(real(inner(ψ0', K16, ψ0)) - (ω^2 + 1 + 0.1^2)) < 1e-8 + K00(K) = real(inner(ψ0', K, ψ0)) + K16 = @test_logs min_level=Logging.Warn build_K(H16.mpo, H16.sites, ω, 0.1) + @test abs(K00(K16) - (ω^2 + 1 + 0.1^2)) < 1e-8 + Kold = @test_logs (:warn, r"live on a few sites") build_K(H16.mpo, H16.sites, ω, 0.1; + cutoff_K = 1e-8) + @test abs(K00(Kold) - (ω^2 + 1 + 0.1^2)) > 0.9 # the end bond is lost end From 37fa32efbb46d1b652fc3189817163b9454c1622 Mon Sep 17 00:00:00 2001 From: Anouar Moustaj Date: Fri, 13 Nov 2026 10:43:09 +0200 Subject: [PATCH 13/22] Make the Hamiltonian builders' truncation cutoff size-aware: min(1e-8, 0.1/D) The builders and term adders truncate with a cutoff relative to the squared norm of the MPO, ||H||^2 ~ z D t^2 for a site space of dimension D, so a fixed 1e-8 drops a term carried by a single matrix element once D is large. The bond across the middle of a 1D chain, 2^(L-1) - 1 -> 2^(L-1), whose carry flips every qubit, is such a term: - get_Hamiltonian("chain_1d") (truncate! at tol = 1e-8) lost it at L = 26, gained a wrap-around element of -0.036, and from L = 28 lost every hop flipping 27 bits or more, cutting the chain every 2^26 sites (N/2 included); - "uniform" and "aah" lost it at L = 26 through their own sum with the on-site term (cutoff = 1e-8 hard-coded in HUniform/HAAH) and hopping2MPO's final truncate! (also hard-coded); "ssh" at L = 28; "ssh_sublattice" lost two carry levels at L = 26; - get_Hamiltonian("custom") with nearest-neighbour hops threw at L = 26: the sampled check of hopping2MPO caught the missing bond and the rebuild lost it again; - add_onsite! (and every other term adder, which sum and truncate at tol = 1e-8) cut a correct chain again. The default is now _default_mpo_cutoff(D) = min(1e-8, 0.1/D), which keeps every term with at least one element of order the hopping (z <= 10) and equals 1e-8 up to D = 2^23, so smaller systems build the same MPOs bit for bit (no golden case moves). It applies to get_Hamiltonian and estimate_scale (tol), add_hopping!, add_hopping_2D!, add_onsite!, add_spin! (cutoff), add_zeeman!, add_soc!, add_superconductivity!, exciton_hamiltonian, Exciton_Hamiltonian (tol), spin_hamiltonian, bdg_hamiltonian, bdg_spin_hamiltonian, ssh_sublattice_hamiltonian, add_tjunction!, tjunction_hamiltonian (cutoff), and to the fixed truncations inside hopping2MPO, qtci_matrix_to_MPO, HUniform and HAAH. A given value is used as given and warns once (_mpo_cutoff) above 0.3/D; the middle bond of a chain is lost from about 0.5/D. Where tol was also a QTCI tolerance ("custom", "haldane", two-argument terms) a given tol still is, and the QTCI default stays 1e-8. The projected quasicrystal spaces keep 1e-8 (not checked at large L); the 2D-only builders and the solvers are not changed: in 2D a long carry repeats along a whole row or column, and 1e-8 kept every hop of square, hex, triangular, chern8, kagome and honeycomb lattices at L = 26-30. Audit (examples/nontracked/fixes_checks/builders_carry_audit*.jl): every 1D model keeps all its hops at L = 26, 28 and 30, and add_onsite! keeps them at L = 26 and 28. The chain MPO of kinetic_1d_nn itself loses the middle bond at L = 40 whatever the cutoff (documented, not investigated). Test: test/bugfix_large_L_cutoffs.jl (L = 26: chain with and without an explicit 1e-8, add_onsite!, "uniform", "aah", "custom"; the default and the warning threshold). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 26 ++++++++++ src/core/AuxDOF.jl | 71 +++++++++++++++++---------- src/core/Hamiltonian.jl | 10 +++- src/core/MPOTools.jl | 38 +++++++++++++- src/core/ModelRegistry.jl | 31 +++++++----- src/core/TBSystem.jl | 90 +++++++++++++++++++++++----------- src/lattice/NNNeighbor.jl | 24 +++++---- src/lattice/TJunction.jl | 17 ++++--- src/lattice/presets.jl | 6 ++- src/lattice/sublattice.jl | 9 +++- src/physics/Supercond.jl | 31 +++++++++--- src/physics/TwoParticle.jl | 31 +++++++----- test/bugfix_large_L_cutoffs.jl | 40 +++++++++++++++ test/runtests.jl | 1 + 14 files changed, 315 insertions(+), 110 deletions(-) create mode 100644 test/bugfix_large_L_cutoffs.jl diff --git a/CHANGELOG.md b/CHANGELOG.md index e89b7a1..5eaf5fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -98,6 +98,32 @@ bugs without breaking the API. unchanged bit for bit (no golden case moves); below η = 0.1, or from L = 12 on, K and the DMRG results built on it move. An explicit `cutoff_K` is used as given and warns once when it is not below `η⁴` or when it is above `0.3/D²`. +- **Size-aware truncation cutoff of the Hamiltonian builders.** Their cutoff (`1e-8` up + to v0.2.0) is relative to the squared norm of the MPO, which grows with the dimension D + of the site space, so in large systems it dropped terms carried by a single matrix + element. The bond across the middle of a 1D chain, `2^(L-1) - 1 → 2^(L-1)`, whose carry + flips every qubit, is such a term: `"chain_1d"`, `"uniform"`, `"aah"` and + `"ssh_sublattice"` lost it at L = 26 (`"ssh"` at L = 28), from L = 28 the chain was cut + every `2^26` sites, and `"custom"` with nearest-neighbour hops threw (its self-check + caught the missing bond). `add_onsite!` and the other term adders cut a correct chain + again. The default is now `min(1e-8, 0.1/D)`: in `get_Hamiltonian` and + `estimate_scale` (`tol`), `add_hopping!`, `add_hopping_2D!`, `add_onsite!`, + `add_spin!` (`cutoff`), `add_zeeman!`, `add_soc!`, `add_superconductivity!`, + `exciton_hamiltonian` and `Exciton_Hamiltonian` (`tol`), `spin_hamiltonian`, + `bdg_hamiltonian`, `bdg_spin_hamiltonian`, `ssh_sublattice_hamiltonian`, + `add_tjunction!` and `tjunction_hamiltonian` (`cutoff`), and in the fixed truncations + inside `hopping2MPO`, `qtci_matrix_to_MPO` and the `"uniform"` and `"aah"` presets. It + equals `1e-8` up to D = 2^23 (L = 23 for a spinless chain, 22 spinful, 21 for spinful + BdG or three atoms per cell), so smaller systems build the same MPOs bit for bit (no + golden case moves); larger ones move at the truncation level, and the 1D ones are + right again (checked up to L = 30). A given value is used as given and warns once when + it is above `0.3/D`; a given `tol` is still also the QTCI tolerance where it was + (`"custom"`, `"haldane"`, two-argument terms), whose default stays `1e-8`. Not changed: + the 2D-only builders, where a long carry repeats along a whole row or column and `1e-8` + keeps it until `Lx` or `Ly` reaches about 24 (estimated; checked at `Lx = Ly = 13`); + the projected quasicrystal spaces (still `1e-8`, not checked at large L); the solvers. + At L = 40 the chain MPO of `kinetic_1d_nn` itself loses the bond across the middle, + whatever the cutoff. ### Fixed diff --git a/src/core/AuxDOF.jl b/src/core/AuxDOF.jl index d95bb69..7f5e1aa 100644 --- a/src/core/AuxDOF.jl +++ b/src/core/AuxDOF.jl @@ -289,16 +289,20 @@ end # ============================================================ """ - add_spin!(H; cutoff=1e-8, maxdim=200, position=:pre) -> H + add_spin!(H; cutoff=nothing, maxdim=200, position=:pre) -> H Extend `H` to a spin-½ degenerate system by adding a spin-½ index in front of (`position=:pre`) or behind (`position=:post`) the existing sites. The resulting Hamiltonian is `I_spin ⊗ H` (both spin sectors identical). +`cutoff` is the relative cutoff of the final truncation, by default `min(1e-8, 0.1/D)`, D +the dimension of the new site space (`1e-8` up to D = 2^23; see "Large systems" in +[`get_Hamiltonian`](@ref)). + No-op if `H` is already spinful (`H.spin_s !== nothing`). Invalidates all caches. """ -function add_spin!(H::TBHamiltonian; cutoff::Real=1e-8, maxdim::Int=200, +function add_spin!(H::TBHamiltonian; cutoff::Union{Nothing,Real}=nothing, maxdim::Int=200, position::Symbol=:pre) _require_binary_position_space(H, "add_spin!") H.spin_s === nothing || return H @@ -310,7 +314,9 @@ function add_spin!(H::TBHamiltonian; cutoff::Real=1e-8, maxdim::Int=200, H.mpo = postpend_spin(H.mpo, spin_s, :Id) H.sites = [H.sites; spin_s] end - ITensorMPS.truncate!(H.mpo; maxdim=maxdim, cutoff=cutoff) + ITensorMPS.truncate!(H.mpo; maxdim=maxdim, + cutoff=_mpo_cutoff(cutoff, _site_space_dim(H.sites), "add_spin!"; + keyword="cutoff")) H.spin_s = spin_s H.aux_side = position _invalidate_cache!(H) @@ -323,7 +329,7 @@ end # ============================================================ """ - add_zeeman!(H, h; direction=:z, tol=1e-8, maxdim=200, position=nothing) -> H + add_zeeman!(H, h; direction=:z, tol=nothing, maxdim=200, position=nothing) -> H Add a Zeeman coupling `h · Sα` to `H`. Calls `add_spin!` automatically if `H` is not yet spinful, placing the spin index at `position` (default @@ -341,6 +347,9 @@ If `add_superconductivity!` was already called, the Zeeman term `Z` enters the h block as `−Z*`, as required in BdG: `τ_z ⊗ Z` along x and z, `+h·S_y` in the hole block along y (up to v0.2.0 every direction got `τ_z ⊗ Z`, wrong along y). +`tol` is the relative cutoff of the sums, by default `min(1e-8, 0.1/D)`, D the dimension of +the site space (`1e-8` up to D = 2^23; see "Large systems" in [`get_Hamiltonian`](@ref)). + Examples -------- ```julia @@ -351,7 +360,7 @@ add_zeeman!(H, 0.05; direction=:x) # in-plane """ function add_zeeman!(H::TBHamiltonian, h; direction::Symbol = :z, - tol::Real = 1e-8, + tol::Union{Nothing,Real} = nothing, maxdim::Int = 200, position::Union{Nothing,Symbol} = nothing) _require_binary_position_space(H, "add_zeeman!") @@ -359,6 +368,7 @@ function add_zeeman!(H::TBHamiltonian, h; error("direction must be :x, :y, or :z; got :$direction") pos = something(position, H.aux_side) add_spin!(H; cutoff=tol, maxdim=maxdim, position=pos) + cut = _mpo_cutoff(tol, _site_space_dim(H.sites), "add_zeeman!") spin_op = direction == :z ? :Sz : direction == :x ? :Sx : :Sy pos_s = _pos_sites(H) @@ -367,10 +377,10 @@ function add_zeeman!(H::TBHamiltonian, h; # h σ on the spin, the particle-hole structure on a Nambu site (τ_z for a real term), # the identity on any other aux site - H_Z = _lift_normal_term(H, h_mpo, Dict{Index,Any}(H.spin_s => spin_op); cutoff=tol) + H_Z = _lift_normal_term(H, h_mpo, Dict{Index,Any}(H.spin_s => spin_op); cutoff=cut) - H.mpo = +(H.mpo, H_Z; maxdim=maxdim, cutoff=tol) - ITensorMPS.truncate!(H.mpo; maxdim=maxdim, cutoff=tol) + H.mpo = +(H.mpo, H_Z; maxdim=maxdim, cutoff=cut) + ITensorMPS.truncate!(H.mpo; maxdim=maxdim, cutoff=cut) _invalidate_cache!(H) return H end @@ -381,7 +391,7 @@ end # ============================================================ """ - add_superconductivity!(H, Δ; type=:swave, tol=1e-8, maxdim=200, + add_superconductivity!(H, Δ; type=:swave, tol=nothing, maxdim=200, position=nothing, check=true) -> H Extend `H` to a Bogoliubov–de Gennes (BdG) Hamiltonian by prepending @@ -418,6 +428,11 @@ automatically redirects to `:pwave` (uniform `Δ`) or errors (spatially varying - `:pwave` — antisymmetric NN pairing `Δ·(K_f − K_b)` for spinless chains; `Δ` must be a `Number` - `:custom` — arbitrary `Δ(i,j)`; pass a 2-arg function +`tol` is the relative cutoff of the BdG assembly, by default `min(1e-8, 0.1/D)`, D the +dimension of the BdG site space (`1e-8` up to D = 2^23; see "Large systems" in +[`get_Hamiltonian`](@ref)); a given `tol` is also the QTCI tolerance of `type=:custom` +(default `1e-8`). + Errors if BdG has already been applied. Invalidates all caches. The KPM scale becomes `|H.center| + H.scale + 1.1‖Δ̂‖` (center 0), with ‖Δ̂‖ = `abs(Δ)` for s-wave and `2abs(Δ)` for p-wave, when `H.scale` is set and `Δ` is a `Number`; @@ -435,7 +450,7 @@ add_superconductivity!(H, (i,j) -> ...; type=:custom) # general pairing """ function add_superconductivity!(H::TBHamiltonian, Δ; type::Symbol = :swave, - tol::Real = 1e-8, + tol::Union{Nothing,Real} = nothing, maxdim::Int = 200, position::Union{Nothing,Symbol} = nothing, check::Bool = true) @@ -445,6 +460,7 @@ function add_superconductivity!(H::TBHamiltonian, Δ; pos = something(position, H.aux_side) pos_s = _pos_sites(H) + cut = _mpo_cutoff(tol, 2 * _site_space_dim(H.sites), "add_superconductivity!") # ── Spinless + :swave redirect ─────────────────────────────────────────── if H.spin_s === nothing && type === :swave @@ -477,7 +493,7 @@ function add_superconductivity!(H::TBHamiltonian, Δ; elseif type === :custom Δ isa Function || error("For type=:custom, Δ must be a 2-arg Function Δ(i,j).") - pairing2MPO(Δ, H.N, pos_s; tol=tol, type=ComplexF64, check=check) + pairing2MPO(Δ, H.N, pos_s; tol=something(tol, 1e-8), type=ComplexF64, check=check) else error("Unknown pairing type :$type. Use :swave, :pwave, or :custom.") end @@ -493,17 +509,17 @@ function add_superconductivity!(H::TBHamiltonian, Δ; # ── BdG assembly ───────────────────────────────────────────────────────── nambu_s = nambu_index() if pos === :pre - H_bdg = +(+(_nambu_normal_block(H.mpo, nambu_s, :pre; cutoff=tol), - prepend_nambu(H_pair, nambu_s, :tp); cutoff=tol), - prepend_nambu(H_pair_adj, nambu_s, :tm); cutoff=tol) + H_bdg = +(+(_nambu_normal_block(H.mpo, nambu_s, :pre; cutoff=cut), + prepend_nambu(H_pair, nambu_s, :tp); cutoff=cut), + prepend_nambu(H_pair_adj, nambu_s, :tm); cutoff=cut) H.sites = [nambu_s; H.sites] else - H_bdg = +(+(_nambu_normal_block(H.mpo, nambu_s, :post; cutoff=tol), - postpend_nambu(H_pair, nambu_s, :tp); cutoff=tol), - postpend_nambu(H_pair_adj, nambu_s, :tm); cutoff=tol) + H_bdg = +(+(_nambu_normal_block(H.mpo, nambu_s, :post; cutoff=cut), + postpend_nambu(H_pair, nambu_s, :tp); cutoff=cut), + postpend_nambu(H_pair_adj, nambu_s, :tm); cutoff=cut) H.sites = [H.sites; nambu_s] end - ITensorMPS.truncate!(H_bdg; maxdim=maxdim, cutoff=tol) + ITensorMPS.truncate!(H_bdg; maxdim=maxdim, cutoff=cut) old_scale, old_center = H.scale, H.center H.mpo = H_bdg @@ -529,7 +545,7 @@ end # ============================================================ """ - add_soc!(H, λ; type=:rashba, direction=:z, boundary=:periodic, tol=1e-8, + add_soc!(H, λ; type=:rashba, direction=:z, boundary=:periodic, tol=nothing, maxdim=200, position=nothing, check=true) -> H Add spin-orbit coupling to `H`. Calls `add_spin!` automatically if needed, @@ -562,6 +578,10 @@ placing the spin index at `position` (default `H.aux_side`). `boundary` (`:periodic` or `:open`; `:pbc`/`:obc` are accepted too) is read by `:rashba` only and checked for every `type`. +`tol` is the relative cutoff of the sums, by default `min(1e-8, 0.1/D)`, D the dimension of +the site space (`1e-8` up to D = 2^23; see "Large systems" in [`get_Hamiltonian`](@ref)); +a given `tol` is also the QTCI tolerance of a two-argument `λ` (default `1e-8`). + Examples -------- ```julia @@ -575,7 +595,7 @@ function add_soc!(H::TBHamiltonian, λ; type::Symbol = :rashba, direction::Symbol = :z, boundary::Symbol = :periodic, - tol::Real = 1e-8, + tol::Union{Nothing,Real} = nothing, maxdim::Int = 200, position::Union{Nothing,Symbol} = nothing, check::Bool = true) @@ -584,10 +604,11 @@ function add_soc!(H::TBHamiltonian, λ; pos = something(position, H.aux_side) add_spin!(H; cutoff=tol, maxdim=maxdim, position=pos) pos_s = _pos_sites(H) + cut = _mpo_cutoff(tol, _site_space_dim(H.sites), "add_soc!") # The SOC term on the spin (op), the particle-hole structure on a Nambu site (τ_z for # a real term), the identity on any other aux site, each on the side H.sites puts it. - spin_prepend(M, _, op) = _lift_normal_term(H, M, Dict{Index,Any}(H.spin_s => op); cutoff=tol) + spin_prepend(M, _, op) = _lift_normal_term(H, M, Dict{Index,Any}(H.spin_s => op); cutoff=cut) H_soc = if type === :ising λ_mpo = λ isa Number ? λ * MPO(pos_s, "Id") : @@ -608,7 +629,7 @@ function add_soc!(H::TBHamiltonian, λ; # λ·(iσ_y) ⊗ (K_u − K_d): both factors anti-Hermitian → product Hermitian. # :Sy (Hermitian) ⊗ anti-Hermitian would give a non-Hermitian term. +(spin_prepend( λ * K_u, H.spin_s, :iSy), - spin_prepend(-λ * K_d, H.spin_s, :iSy); cutoff=tol) + spin_prepend(-λ * K_d, H.spin_s, :iSy); cutoff=cut) elseif type === :custom direction in (:x, :y, :z) || @@ -619,7 +640,7 @@ function add_soc!(H::TBHamiltonian, λ; elseif λ isa Function && applicable(λ, 1) get_diagonal_mpo(H.L, pos_s, λ) elseif λ isa Function - hopping2MPO(λ, H.N, pos_s; tol=tol, type=ComplexF64, check=check) + hopping2MPO(λ, H.N, pos_s; tol=something(tol, 1e-8), type=ComplexF64, check=check) else error("λ must be a Number or a Function.") end @@ -629,8 +650,8 @@ function add_soc!(H::TBHamiltonian, λ; error("Unknown SOC type :$type. Use :rashba, :ising, or :custom.") end - H.mpo = +(H.mpo, H_soc; maxdim=maxdim, cutoff=tol) - ITensorMPS.truncate!(H.mpo; maxdim=maxdim, cutoff=tol) + H.mpo = +(H.mpo, H_soc; maxdim=maxdim, cutoff=cut) + ITensorMPS.truncate!(H.mpo; maxdim=maxdim, cutoff=cut) _invalidate_cache!(H) return H end diff --git a/src/core/Hamiltonian.jl b/src/core/Hamiltonian.jl index 7eaffd3..a44f0e2 100644 --- a/src/core/Hamiltonian.jl +++ b/src/core/Hamiltonian.jl @@ -80,6 +80,10 @@ from the RNG. `get_Hamiltonian("custom", f)`, `add_hopping!(H, f)` with a two-ar `f`, `add_superconductivity!(H, Δ; type=:custom)` (through `pairing2MPO`) and `add_soc!(H, λ; type=:custom)` with a two-argument `λ` turn the check on (their keyword `check`); the default here is `false`. + +The QTCI output is truncated at a relative cutoff of `min(1e-8, 0.1/N)`: the fixed `1e-8` +of v0.2.0 dropped bonds carried by a single matrix element from N = 2^26 on, such as the +bond across the middle of a chain (see "Large systems" in [`get_Hamiltonian`](@ref)). """ function hopping2MPO(f, N, sites; tol=1e-8, initial_positions=[], type=Float64, unfoldingscheme=:interleaved, nrandominitpivot::Int=5, @@ -136,7 +140,9 @@ function _hopping2MPO(f, N, sites; tol, initial_positions, type, unfoldingscheme @debug "hopping2MPO: QTCI tensor train converted to MPS" mpo = unfoldingscheme == :fused ? fused_mpo(mps, sites) : custom_mpo(mps, sites) @debug "hopping2MPO: MPS turned into MPO" - ITensorMPS.truncate!(mpo; cutoff=1e-8) + # 1e-8 up to N = 2^23, 0.1/N above: the fixed 1e-8 of v0.2.0 dropped the bond across + # the middle of a chain from L = 26 on (see _default_mpo_cutoff) + ITensorMPS.truncate!(mpo; cutoff=_default_mpo_cutoff(N)) return mpo end @@ -236,7 +242,7 @@ function qtci_matrix_to_MPO(A_fun, L, sites; @debug "qtci_matrix_to_MPO: MPS built" mpo = custom_mpo(mps, sites) @debug "qtci_matrix_to_MPO: MPO built" - ITensorMPS.truncate!(mpo; maxdim=20, cutoff=1e-8) + ITensorMPS.truncate!(mpo; maxdim=20, cutoff=_default_mpo_cutoff(Nc)) # see hopping2MPO return mpo end diff --git a/src/core/MPOTools.jl b/src/core/MPOTools.jl index 956e200..4a672d8 100644 --- a/src/core/MPOTools.jl +++ b/src/core/MPOTools.jl @@ -7,7 +7,8 @@ # rank-1 site projector (_site_projector_mpo) and the left-to-right compressed # sum of MPO terms (sum_mpos) that the lattice builders assemble with, with its # checked variant _checked_sum_mpos (the sublattice builders) and its Frobenius -# distance _mpo_distance. +# distance _mpo_distance; and the size-aware default truncation cutoff of the +# Hamiltonian builders and term adders (_default_mpo_cutoff, _mpo_cutoff). # # Main entry points: mpo_kron, interleave_mpo, interleave_mpo_tb, compose_power, # sum_mpos. @@ -312,3 +313,38 @@ function _mpo_distance(A::MPO, B::MPO) orthogonalize!(Δ, 1) return norm(Δ[1]) end + + +# ============================================================ +# 7. Size-aware truncation cutoff of the Hamiltonian builders +# ============================================================ +# +# ITensors' cutoffs are relative to the squared Frobenius norm, which grows with the +# dimension D of the site space: ‖H‖² ≈ z D t² for z hops of size t per row. A term +# carried by k matrix elements of size t weighs about k/(zD) of it, and a truncation drops +# it once the cutoff exceeds that. The bond across the middle of a 1D chain, +# n = 2^(L-1) - 1 → 2^(L-1), whose carry flips every qubit, is such a term with k = 2: the +# fixed cutoff 1e-8 of v0.2.0 lost it from L = 26 on (a single site-space dimension of +# 2^26), and from L = 28 every bond whose carry flips 27 qubits or more, which cut the +# chain every 2^26 sites. The builders and term adders therefore default to +# `_default_mpo_cutoff(D)`: 1e-8, as before, up to D = 2^23, and 0.1/D above, which +# keeps every term with k ≥ 1 for z ≤ 10. In 2D a long carry repeats along a whole row or +# column, so 1e-8 already kept it; the default changes nothing there below D = 2^23. + +_default_mpo_cutoff(D::Real) = min(1e-8, 0.1 / Float64(D)) + +# The dimension of the site space of `sites`, a collection of Index. +_site_space_dim(sites) = prod(s -> Float64(dim(s)), sites; init = 1.0) + +# The truncation cutoff of a builder or term adder on a site space of dimension D: the +# default above when `value` is `nothing`, otherwise `value` as given, with a warning +# (once per function) when it is above 0.3/D, where it can drop a term carried by a single +# matrix element (the middle bond of a chain is lost from about 0.5/D on). +function _mpo_cutoff(value, D::Real, fname::AbstractString; keyword::AbstractString = "tol") + value === nothing && return _default_mpo_cutoff(D) + value > 0.3 / D && + @warn "$fname: $keyword = $value can drop a term carried by a single matrix element " * + "on this site space of dimension $(Float64(D)), such as the bond across the " * + "middle of a 1D chain; the default is min(1e-8, 0.1/D)." maxlog=1 _id=Symbol(fname, :_, keyword, :_size) + return value +end diff --git a/src/core/ModelRegistry.jl b/src/core/ModelRegistry.jl index 3f86537..df6b810 100644 --- a/src/core/ModelRegistry.jl +++ b/src/core/ModelRegistry.jl @@ -175,7 +175,7 @@ function _preset_params(name::AbstractString, params, kwargs) end function _build_preset(geometry, params, L, N, sites; - scale=nothing, tol=1e-8, maxdim=15, + scale=nothing, tol=nothing, maxdim=15, ref_sites::Union{Nothing,Vector{<:Index}}=nothing, kwargs...) # Route through build_hamiltonian, which reads MODEL_REGISTRY; params (a scalar, @@ -191,7 +191,7 @@ function _build_preset(geometry, params, L, N, sites; kw_filtered = Dict(k => v for (k, v) in kwargs if k ∉ (:Lx, :Ly)) build_hamiltonian(geometry, Lx, Ly; mparam_dict, kw_filtered...) end - ITensorMPS.truncate!(mpo; maxdim=maxdim, cutoff=tol) + ITensorMPS.truncate!(mpo; maxdim=maxdim, cutoff=_mpo_cutoff(tol, 2.0^L, "get_Hamiltonian")) # The model builders (HAAH, HSSH, …) create their own site indices internally, # so we extract the actual sites from the MPO rather than using the ones # created by get_Hamiltonian (which would be a different set). @@ -212,12 +212,13 @@ end # The 2D multi-atom lattices: the builder `entry.builder(Lx, Ly, params...)` with the # parameters of `entry.defaults` in order, the geometry from `entry.positions`. function _build_sublattice(entry::ModelEntry, params, L; - scale=nothing, tol=1e-8, maxdim=200, ref_sites=nothing, kwargs...) + scale=nothing, tol=nothing, maxdim=200, ref_sites=nothing, kwargs...) Lx = get(kwargs, :Lx, L ÷ 2) Ly = get(kwargs, :Ly, L - Lx) args = Tuple(_param(params, k, v; scalar = k === :t) for (k, v) in pairs(entry.defaults)) + cut = _mpo_cutoff(tol, entry.n_sub * 2.0^L, "get_Hamiltonian") - H = getfield(@__MODULE__, entry.builder)(Lx, Ly, args...; cutoff=tol, maxdim=maxdim) + H = getfield(@__MODULE__, entry.builder)(Lx, Ly, args...; cutoff=cut, maxdim=maxdim) rs = getfield(@__MODULE__, entry.positions)(Lx, Ly) H.geometry = let m = rs; i -> m[i, :]; end @@ -237,11 +238,13 @@ function _build_sublattice(entry::ModelEntry, params, L; end # SSH chain with an explicit sublattice index: `t` (or the single number) and `d`. -function _build_ssh_sublattice(params, L; scale=nothing, tol=1e-8, maxdim=15, +function _build_ssh_sublattice(params, L; scale=nothing, tol=nothing, maxdim=15, ref_sites=nothing) t = _param(params, :t, 1.0; scalar=true) d = _param(params, :d, 0.0) - H = ssh_sublattice_hamiltonian(L, t, d; cutoff=tol, maxdim=maxdim) + H = ssh_sublattice_hamiltonian(L, t, d; + cutoff=_mpo_cutoff(tol, 2 * 2.0^L, "get_Hamiltonian"), + maxdim=maxdim) isnothing(scale) || (H.scale = Float64(scale)) ref_sites === nothing || _replace_pos_sites!(H, ref_sites, "ssh_sublattice") return H @@ -276,10 +279,12 @@ end # get_Hamiltonian build function of a projected position space: rejects ref_sites. _projected_build(f, space::AbstractString) = - function (params, L, N, sites; ref_sites=nothing, kwargs...) + function (params, L, N, sites; ref_sites=nothing, tol=nothing, kwargs...) ref_sites === nothing || throw(ArgumentError("ref_sites is not supported for $space")) - return f(params, L; kwargs...) + # get_Hamiltonian's default tol is size-aware (_default_mpo_cutoff); the projected + # spaces keep the 1e-8 it was up to v0.2.0, their large-L behaviour being unchecked + return f(params, L; tol=something(tol, 1e-8), kwargs...) end @@ -426,7 +431,7 @@ const _MODEL_ENTRIES = ModelEntry[ rowsum=(params, kwargs) -> _ssh_rowsum(_preset_params("ssh", params, kwargs))), ModelEntry("ssh_sublattice"; kind=:sublattice, dim=1, n_sub=2, params=[:t, :d], defaults=(; t=1.0, d=0.0), builder=:ssh_sublattice_hamiltonian, - build=(params, L, N, sites; ref_sites=nothing, scale=nothing, tol=1e-8, + build=(params, L, N, sites; ref_sites=nothing, scale=nothing, tol=nothing, maxdim=15, kwargs...) -> _build_ssh_sublattice(params, L; scale, tol, maxdim, ref_sites), auto=:small, @@ -653,8 +658,8 @@ function _small_scale(entry::ModelEntry, H, params, L; tol, maxdim, kwargs...) return _SCALE_PADDING * _preserving_rngs(() -> _dense_spectral_radius(H.mpo)) end cacheable = entry.resizable - key = (entry.name, _freeze(params), small, Float64(tol), maxdim, - _freeze_kwargs(kwargs, (:Lx, :Ly))) + key = (entry.name, _freeze(params), small, tol === nothing ? nothing : Float64(tol), + maxdim, _freeze_kwargs(kwargs, (:Lx, :Ly))) if cacheable cached = lock(() -> get(_SMALL_SCALE_CACHE, key, nothing), _SMALL_SCALE_LOCK) cached === nothing || return cached @@ -690,7 +695,7 @@ function _check_scale_method(entry::ModelEntry, method::Symbol, L, kwargs) end """ - estimate_scale(geometry, params; L, method=:auto, tol=1e-8, maxdim=15, kwargs...) -> Float64 + estimate_scale(geometry, params; L, method=:auto, tol=nothing, maxdim=15, kwargs...) -> Float64 KPM half-bandwidth estimate (spectral centre 0) for `get_Hamiltonian(geometry, params; L, tol, maxdim, kwargs...)`; `kwargs` are that call's @@ -729,7 +734,7 @@ estimate_scale("square_2d", 1.0; L=12, Lx=6, method=:geometry) # 4.4 ``` """ function estimate_scale(geometry::AbstractString, params; L::Integer, method::Symbol=:auto, - tol=1e-8, maxdim=15, ref_sites=nothing, kwargs...) + tol=nothing, maxdim=15, ref_sites=nothing, kwargs...) entry = _model_entry(geometry) m = _check_scale_method(entry, method, L, kwargs) m === :geometry && return _SCALE_PADDING * entry.rowsum(params, kwargs) diff --git a/src/core/TBSystem.jl b/src/core/TBSystem.jl index 36bdc4b..422d225 100644 --- a/src/core/TBSystem.jl +++ b/src/core/TBSystem.jl @@ -346,7 +346,7 @@ end # ============================================================ """ - get_Hamiltonian(geometry, params; L, scale=nothing, tol=1e-8, maxdim=15, + get_Hamiltonian(geometry, params; L, scale=nothing, tol=nothing, maxdim=15, ref_sites=nothing, kwargs...) -> TBHamiltonian Build a `TBHamiltonian` from a named geometry and model parameters. @@ -373,8 +373,8 @@ Projected position spaces (quasicrystals; `H.N` counts the admissible sites only | `"kbonacci"` | `(A, B, C, …[, t, onsite])` or `(values=(a_1, …, a_k)[, t, onsite])` | `k` (required; `k=3` Tribonacci), `model`, `boundary`, `padding` | These call [`fibonacci_hamiltonian`](@ref), [`metallic_mean_hamiltonian`](@ref) and -[`kbonacci_hamiltonian`](@ref) with `cutoff=tol` and `maxdim=maxdim`; they reject -`ref_sites`. +[`kbonacci_hamiltonian`](@ref) with `cutoff=tol` (`1e-8` by default, as up to v0.2.0) and +`maxdim=maxdim`; they reject `ref_sites`. Preset models (routed through [`build_hamiltonian`](@ref) and `MODEL_REGISTRY`) ------------------------------------------------------------------------------- @@ -428,8 +428,11 @@ Common keyword arguments (dense spectrum of the model at a small size), `:geometry` (row-sum bound) or `:dmrg` (DMRG spectral bounds of `H`, which also set `center`) -- `tol` : truncation cutoff of the built MPO (default `1e-8`); for `"custom"` - and `"haldane"` also the QTCI tolerance. The preset models take their +- `tol` : relative truncation cutoff of the built MPO; by default + `min(1e-8, 0.1/D)`, D the dimension of the site space, which is `1e-8` + (as up to v0.2.0) up to D = 2^23 (see "Large systems" below); the + projected spaces keep `1e-8`. For `"custom"` and `"haldane"` a given `tol` + is also the QTCI tolerance (default `1e-8`). The preset models take their QTCI tolerance from `MODEL_REGISTRY` (`tol_quantics`: `1e-8`, `1e-9` for `"qc2dsquare"`), which `params`/`mparams` override - `maxdim` : maximum MPO bond dimension after construction (default `15`). It can @@ -459,6 +462,25 @@ exceed it and is not computed. Every other geometry keeps its builder's default: the analytic bounds of `"haldane"`, `"chernhex"`, `"ssh_sublattice"` and the projected spaces. The centre is 0 except for the projected spaces. +Large systems +------------- +`tol` is relative to the squared norm of the MPO, which grows with the dimension D of the +site space, so a fixed cutoff drops a term carried by a single matrix element once the +system is large enough. In a 1D chain the bond across the middle, `2^(L-1) - 1 → 2^(L-1)`, +whose carry flips every qubit, is such a term. With the fixed `1e-8` of v0.2.0 the 1D +models lost such bonds at L = 26 (`"chain_1d"`, `"uniform"`, `"aah"`, `"ssh_sublattice"`; +`"ssh"` at L = 28), and from L = 28 the chain was cut every `2^26` sites; `"custom"` with +nearest-neighbour hops threw, its self-check catching the missing bond. The default +`min(1e-8, 0.1/D)` keeps such terms; it equals `1e-8` up to D = 2^23 (L = 23 for a spinless +chain), so smaller systems build the same MPO as before. An explicit `tol` above `0.3/D` is +used as given and warns once. [`add_hopping!`](@ref), [`add_onsite!`](@ref), +[`add_spin!`](@ref), [`add_zeeman!`](@ref), [`add_soc!`](@ref) and +[`add_superconductivity!`](@ref) have the same default; with `1e-8` each of them cut the +chain again. In 2D a long carry repeats along a whole row or column, so `1e-8` keeps it +until `Lx` or `Ly` reaches about 24 (estimated; checked at `Lx = Ly = 13`). The chain MPO +of [`kinetic_1d_nn`](@ref) is itself exact up to L = 38 and loses the bond across the +middle at L = 40, whatever `tol`. + Examples -------- ```julia @@ -482,7 +504,7 @@ After construction, add further interaction terms with function get_Hamiltonian(geometry::String, params; L::Int, scale=nothing, - tol=1e-8, + tol=nothing, maxdim=15, ref_sites::Union{Nothing,Vector{<:Index}}=nothing, kwargs...) @@ -510,13 +532,13 @@ end function _build_chain_1d(t, L, N, sites; scale=nothing, - tol=1e-8, + tol=nothing, maxdim=15, boundary::Symbol=:open, bc=nothing) bc === nothing || (boundary = Symbol(bc)) mpo = t * kinetic_1d_nn(L, sites; boundary=boundary) - ITensorMPS.truncate!(mpo; maxdim=maxdim, cutoff=tol) + ITensorMPS.truncate!(mpo; maxdim=maxdim, cutoff=_mpo_cutoff(tol, 2.0^L, "get_Hamiltonian")) sc = something(scale, _estimate_scale("chain_1d", t)) # 2.5|t| return TBHamiltonian(; L, N, sites, mpo, geometry=_chain_geometry(), scale=sc) end @@ -667,7 +689,9 @@ end _haldane_rowsum(t2, M) = 3.0 + 6.0 * abs(t2) + abs(M) function _build_haldane(params, L, N, sites; - rs=nothing, scale=nothing, tol=1e-8, maxdim=15) + rs=nothing, scale=nothing, tol=nothing, maxdim=15) + cut = _mpo_cutoff(tol, Float64(N), "get_Hamiltonian") + tol = something(tol, 1e-8) # the QTCI tolerance @assert !isnothing(rs) "Haldane model requires keyword `rs` (N×2 position matrix). " * "Generate it with `honeycomb_positions($L)`." _check_haldane_layout(rs, N) @@ -684,7 +708,7 @@ function _build_haldane(params, L, N, sites; mpo = hopping2MPO(f, N, sites; tol=tol, type=ComplexF64, initial_positions=piv, nrandominitpivot=0, nsearchglobalpivot=0) _check_haldane_mpo(mpo, sites, f, rsN, piv; tol=tol) - ITensorMPS.truncate!(mpo; maxdim=maxdim, cutoff=tol) + ITensorMPS.truncate!(mpo; maxdim=maxdim, cutoff=cut) # Gershgorin bound, padded by 10% (nearly reached at phi = 0, π). sc = something(scale, _SCALE_PADDING * _haldane_rowsum(t2, M)) rs_f = let m = Float64.(rs); i -> m[i, :]; end @@ -699,16 +723,17 @@ end function _build_custom(f, L, N, sites; geometry=nothing, scale=nothing, - tol=1e-8, + tol=nothing, maxdim=15, type=ComplexF64, check::Bool=true) @assert !isnothing(scale) "`scale` must be provided for geometry=\"custom\"." geom_f = geometry isa Matrix ? (let m = Float64.(geometry); i -> m[i, :]; end) : geometry + cut = _mpo_cutoff(tol, Float64(N), "get_Hamiltonian") # The sampled self-check of hopping2MPO: the default QTCI pivots miss bond classes of # a sparse f; a build that passes is returned unchanged (see hopping2MPO). - mpo = hopping2MPO(f, N, sites; tol=tol, type=type, check=check) - ITensorMPS.truncate!(mpo; maxdim=maxdim, cutoff=tol) + mpo = hopping2MPO(f, N, sites; tol=something(tol, 1e-8), type=type, check=check) + ITensorMPS.truncate!(mpo; maxdim=maxdim, cutoff=cut) return TBHamiltonian(; L, N, sites, mpo, geometry=geom_f, scale=Float64(scale)) end @@ -742,7 +767,7 @@ end # ============================================================ """ - add_hopping!(H, f; nn=1, boundary=:open, bc=nothing, maxdim=15, tol=1e-8, + add_hopping!(H, f; nn=1, boundary=:open, bc=nothing, maxdim=15, tol=nothing, type=ComplexF64, apply_kwargs=NamedTuple(), sublat=nothing, sublat_from=nothing, sublat_to=nothing, check=true) -> H @@ -778,8 +803,10 @@ Add a hopping term to `H`. - `boundary=:open` or `:periodic` (`bc` overrides it): boundary of the position shift for scalar and 1-arg `f` and for the inter-sublattice hops. -- `maxdim`, `tol`: truncation of the summed MPO (`tol` is also the QTCI - tolerance of a 2-arg `f`). +- `maxdim`, `tol`: truncation of the summed MPO; `tol` defaults to `min(1e-8, 0.1/D)`, D + the dimension of the site space (`1e-8` up to D = 2^23; see "Large systems" in + [`get_Hamiltonian`](@ref)). A given `tol` is also the QTCI tolerance of a 2-arg `f` + (default `1e-8`). - `type`: element type of the QTCI compression of a 2-arg `f`. - `check=true`: the sampled self-check of [`hopping2MPO`](@ref) for a 2-arg `f` (the default QTCI pivots miss bond classes of a sparse `f`; a build that passes it is kept). @@ -798,7 +825,7 @@ function add_hopping!(H::TBHamiltonian, f; boundary::Symbol = :open, bc = nothing, maxdim = 15, - tol = 1e-8, + tol = nothing, type = ComplexF64, apply_kwargs = NamedTuple(), sublat = nothing, @@ -836,7 +863,8 @@ function add_hopping!(H::TBHamiltonian, f; pos_s = _pos_sites(H) sl_s = H.sublattice_s - apkw = isempty(apply_kwargs) ? (; cutoff=tol, maxdim=maxdim) : apply_kwargs + cut = _mpo_cutoff(tol, _site_space_dim(H.sites), "add_hopping!") + apkw = isempty(apply_kwargs) ? (; cutoff=cut, maxdim=maxdim) : apply_kwargs bc === nothing || (boundary = Symbol(bc)) # ── Build position-space hopping MPO (shared for all cases) ─────────────── @@ -848,7 +876,7 @@ function add_hopping!(H::TBHamiltonian, f; kineticNNN(H.L, pos_s, get_diagonal_mpo(H.L, pos_s, f), nn; apply_kwargs=apply_kwargs, boundary=boundary) else - hopping2MPO(f, H.N, pos_s; tol=tol, type=type, check=check) + hopping2MPO(f, H.N, pos_s; tol=something(tol, 1e-8), type=type, check=check) end end @@ -886,12 +914,12 @@ function add_hopping!(H::TBHamiltonian, f; else ku_nn, kd_nn = shift_pair_mpos(pos_s, nn; cyclic=_tb_periodic_boundary(boundary)) +(extend_with_sublat(ku_nn, mat_fwd), - extend_with_sublat(kd_nn, mat_bwd); cutoff=tol) + extend_with_sublat(kd_nn, mat_bwd); cutoff=cut) end end - H.mpo = +(H.mpo, new_term; maxdim=maxdim, cutoff=tol) - ITensorMPS.truncate!(H.mpo; maxdim=maxdim, cutoff=tol) + H.mpo = +(H.mpo, new_term; maxdim=maxdim, cutoff=cut) + ITensorMPS.truncate!(H.mpo; maxdim=maxdim, cutoff=cut) _invalidate_cache!(H) return H end @@ -899,7 +927,7 @@ end """ add_onsite!(H, f; layer=nothing, sublat=nothing, Lx=nothing, - tol=1e-8, maxdim=nothing, check=false) -> H + tol=nothing, maxdim=nothing, check=false) -> H Add a diagonal (on-site) potential to `H`. @@ -943,11 +971,15 @@ For layered sublattice Hamiltonians, the onsite term is first built on the `position ⊗ sublattice` monolayer space, then wrapped with the selected layer projectors. +`tol` is the relative cutoff of the sum, by default `min(1e-8, 0.1/D)`, D the dimension +of the site space (`1e-8` up to D = 2^23; see "Large systems" in [`get_Hamiltonian`](@ref)). + Invalidates all caches. """ function add_onsite!(H::TBHamiltonian, f; layer=nothing, sublat=nothing, - Lx=nothing, tol=1e-8, maxdim=nothing, check::Bool=false) + Lx=nothing, tol=nothing, maxdim=nothing, check::Bool=false) _require_binary_position_space(H, "add_onsite!") + cut = _mpo_cutoff(tol, _site_space_dim(H.sites), "add_onsite!") if H.layer_s !== nothing (H.spin_s === nothing && H.nambu_s === nothing) || error("Layered add_onsite! currently supports layer/position/sublattice Hamiltonians only.") @@ -971,12 +1003,12 @@ function add_onsite!(H::TBHamiltonian, f; layer=nothing, sublat=nothing, Lx=Lx, tol=tol, maxdim=maxdim, check=check) term = prepend_layer_projector(H_pos.mpo, H.layer_s, ell) H_layered_term = H_layered_term === nothing ? term : - +(H_layered_term, term; cutoff=tol) + +(H_layered_term, term; cutoff=cut) end H.mpo = isnothing(maxdim) ? - +(H.mpo, H_layered_term; cutoff=tol) : - +(H.mpo, H_layered_term; cutoff=tol, maxdim=maxdim) + +(H.mpo, H_layered_term; cutoff=cut) : + +(H.mpo, H_layered_term; cutoff=cut, maxdim=maxdim) _invalidate_cache!(H) return H end @@ -1042,8 +1074,8 @@ function add_onsite!(H::TBHamiltonian, f; layer=nothing, sublat=nothing, end H.mpo = isnothing(maxdim) ? - +(H.mpo, new_term; cutoff=tol) : - +(H.mpo, new_term; cutoff=tol, maxdim=maxdim) + +(H.mpo, new_term; cutoff=cut) : + +(H.mpo, new_term; cutoff=cut, maxdim=maxdim) _invalidate_cache!(H) return H end diff --git a/src/lattice/NNNeighbor.jl b/src/lattice/NNNeighbor.jl index c30a4d9..28269c5 100644 --- a/src/lattice/NNNeighbor.jl +++ b/src/lattice/NNNeighbor.jl @@ -186,7 +186,7 @@ end """ add_hopping_2D!(H, f; Lx, Ly, nn=1, layer=nothing, lattice=nothing, geometry=nothing, - maxdim=50, tol=1e-8) -> H + maxdim=50, tol=nothing) -> H Add the `nn`-th nearest-neighbor hopping to a 2D `TBHamiltonian`. @@ -214,6 +214,9 @@ Add the `nn`-th nearest-neighbor hopping to a 2D `TBHamiltonian`. `:honeycomb`; `geometry` may be either a function `i -> r_i` or a coordinate matrix with one row per position site, or per atom when `H.sublattice_s` is set. - `nn`: neighbor shell index (1 = nearest, 2 = next-nearest, etc.). +- `maxdim`, `tol`: truncation of the summed MPO; `tol` defaults to `min(1e-8, 0.1/D)`, D the + dimension of the site space (`1e-8` up to D = 2^23; see "Large systems" in + [`get_Hamiltonian`](@ref)). **Compatibility** Works on the 2D geometries whose `H.geometry` is a Bravais lattice in the cell index @@ -251,7 +254,8 @@ function add_hopping_2D!(H::TBHamiltonian, f; lattice = nothing, geometry = nothing, maxdim::Int = 50, - tol::Real = 1e-8) + tol::Union{Nothing,Real} = nothing) + cut = _mpo_cutoff(tol, _site_space_dim(H.sites), "add_hopping_2D!") if H.layer_s !== nothing (H.spin_s === nothing && H.nambu_s === nothing) || error("Layered add_hopping_2D! currently supports layer/position/sublattice Hamiltonians only.") @@ -275,11 +279,11 @@ function add_hopping_2D!(H::TBHamiltonian, f; maxdim=maxdim, tol=tol) term = prepend_layer_projector(H_pos.mpo, H.layer_s, ell) H_layered_term = H_layered_term === nothing ? term : - +(H_layered_term, term; cutoff=tol) + +(H_layered_term, term; cutoff=cut) end - H.mpo = +(H.mpo, H_layered_term; cutoff=tol, maxdim=maxdim) - ITensorMPS.truncate!(H.mpo; cutoff=tol, maxdim=maxdim) + H.mpo = +(H.mpo, H_layered_term; cutoff=cut, maxdim=maxdim) + ITensorMPS.truncate!(H.mpo; cutoff=cut, maxdim=maxdim) _invalidate_cache!(H) return H end @@ -291,7 +295,7 @@ function add_hopping_2D!(H::TBHamiltonian, f; H.geometry = _resolve_2d_geometry(H, lattice, geometry, Lx, Ly) end - apkw = (; cutoff=tol, maxdim=maxdim) + apkw = (; cutoff=cut, maxdim=maxdim) n_sub = H.sublattice_s === nothing ? 1 : dim(H.sublattice_s) pos_s = _pos_sites(H) Nx = 2^Lx @@ -377,12 +381,12 @@ function add_hopping_2D!(H::TBHamiltonian, f; conj(amp) * postpend_op(K_bwd_m, H.sublattice_s, M_bwd) end - pair = +(fwd, bwd; cutoff=tol) - new_term = new_term === nothing ? pair : +(new_term, pair; cutoff=tol) + pair = +(fwd, bwd; cutoff=cut) + new_term = new_term === nothing ? pair : +(new_term, pair; cutoff=cut) end - H.mpo = +(H.mpo, new_term; cutoff=tol, maxdim=maxdim) - ITensorMPS.truncate!(H.mpo; cutoff=tol, maxdim=maxdim) + H.mpo = +(H.mpo, new_term; cutoff=cut, maxdim=maxdim) + ITensorMPS.truncate!(H.mpo; cutoff=cut, maxdim=maxdim) _invalidate_cache!(H) return H end diff --git a/src/lattice/TJunction.jl b/src/lattice/TJunction.jl index 88529d0..a97f6e1 100644 --- a/src/lattice/TJunction.jl +++ b/src/lattice/TJunction.jl @@ -56,7 +56,7 @@ _is_tjunction(H) = H.sublattice_s !== nothing && hastags(H.sublattice_s, "TJunct """ add_tjunction!(H, t_j; junction_site=0, coupling=nothing, - cutoff=1e-8, maxdim=200) -> H + cutoff=nothing, maxdim=200) -> H Extend a 1D `TBHamiltonian` to a T/Y-junction by postpending a dim-3 "TJunction" index. The three states |1⟩≡|-1⟩, |2⟩≡|0⟩, |3⟩≡|+1⟩ label @@ -103,8 +103,10 @@ add_tjunction!(H3, 0.5; coupling=[0 1 0; 1 0 1; 0 1 0]) function add_tjunction!(H::TBHamiltonian, t_j; junction_site::Int = 0, coupling = nothing, - cutoff::Real = 1e-8, + cutoff::Union{Nothing,Real} = nothing, maxdim::Int = 200) + # the default min(1e-8, 0.1/D), D the dimension of the 3-branch site space + cut = _mpo_cutoff(cutoff, 3 * _site_space_dim(H.sites), "add_tjunction!"; keyword="cutoff") isnothing(H.sublattice_s) && isnothing(H.layer_s) && isnothing(H.spin_s) && isnothing(H.nambu_s) || error("add_tjunction! requires H with no existing auxiliary indices " * @@ -134,8 +136,8 @@ function add_tjunction!(H::TBHamiltonian, t_j; H.geometry = let m = rs; i -> m[i, :]; end # --- Assemble and update struct ------------------------------------------- - H.mpo = +(H_intra, H_junc; cutoff=cutoff, maxdim=maxdim) - ITensorMPS.truncate!(H.mpo; maxdim=maxdim, cutoff=cutoff) + H.mpo = +(H_intra, H_junc; cutoff=cut, maxdim=maxdim) + ITensorMPS.truncate!(H.mpo; maxdim=maxdim, cutoff=cut) H.sites = [pos_s; tj_s] H.sublattice_s = tj_s H.aux_side = :post @@ -150,7 +152,7 @@ end """ tjunction_hamiltonian(L, t, t_j; junction_site=0, coupling=nothing, - boundary=:open, cutoff=1e-8, maxdim=200) + boundary=:open, cutoff=nothing, maxdim=200) -> TBHamiltonian Build a T/Y-junction Hamiltonian: three identical 1D nearest-neighbour chains @@ -176,7 +178,8 @@ from the junction site (placed at the origin). See `tjunction_positions`. - `coupling` : custom 3×3 coupling matrix (default: symmetric Y-junction `t_j * [0 1 1; 1 0 1; 1 1 0]`) - `boundary` : `:open` (default) or `:periodic` for the intra-chain hoppings -- `cutoff` : MPO truncation cutoff +- `cutoff` : MPO truncation cutoff, by default `min(1e-8, 0.1/D)`, D = 3·2^L (`1e-8` + up to L = 21; see "Large systems" in [`get_Hamiltonian`](@ref)) - `maxdim` : maximum MPO bond dimension Examples @@ -196,7 +199,7 @@ function tjunction_hamiltonian(L::Int, t::Number, t_j::Number; junction_site::Int = 0, coupling = nothing, boundary::Symbol = :open, - cutoff::Real = 1e-8, + cutoff::Union{Nothing,Real} = nothing, maxdim::Int = 200) H = get_Hamiltonian("chain_1d", t; L=L, boundary=boundary) add_tjunction!(H, t_j; diff --git a/src/lattice/presets.jl b/src/lattice/presets.jl index cae2a2a..3437c78 100644 --- a/src/lattice/presets.jl +++ b/src/lattice/presets.jl @@ -36,7 +36,9 @@ function HUniform(L::Integer, t; hops_MPO = qtt_mpo(L, xvals, sites, _ -> t; tol_quantics=tol_quantics, maxbonddim_quantics=maxbonddim_quantics) iszero(v) && return kineticNNN(L, sites, hops_MPO, nn) onsite_MPO = qtt_mpo(L, xvals, sites, _ -> v; tol_quantics=tol_quantics, maxbonddim_quantics=maxbonddim_quantics) - return +(kineticNNN(L, sites, hops_MPO, nn), onsite_MPO; cutoff=1e-8) + # 1e-8 up to 2^23 sites, 0.1/2^L above (the fixed 1e-8 of v0.2.0 dropped the bond + # across the middle of the chain from L = 26 on; see _default_mpo_cutoff) + return +(kineticNNN(L, sites, hops_MPO, nn), onsite_MPO; cutoff=_default_mpo_cutoff(2.0^L)) end @@ -77,7 +79,7 @@ function HAAH(L::Integer, V, phi, t; iszero(V) && return kineticNNN(L, sites, hops_MPO, 1) onsite_MPO = qtt_mpo(L, xvals, sites, x -> V * cos(2pi * b * x + phi); tol_quantics=tol_quantics, maxbonddim_quantics=maxbonddim_quantics) - return +(kineticNNN(L, sites, hops_MPO, 1), onsite_MPO; cutoff=1e-8) + return +(kineticNNN(L, sites, hops_MPO, 1), onsite_MPO; cutoff=_default_mpo_cutoff(2.0^L)) # as HUniform end diff --git a/src/lattice/sublattice.jl b/src/lattice/sublattice.jl index 41ea050..9b93a43 100644 --- a/src/lattice/sublattice.jl +++ b/src/lattice/sublattice.jl @@ -425,7 +425,7 @@ end # ============================================================ """ - ssh_sublattice_hamiltonian(L, t=1.0, d=0.0; cutoff=1e-8, maxdim=200) -> TBHamiltonian + ssh_sublattice_hamiltonian(L, t=1.0, d=0.0; cutoff=nothing, maxdim=200) -> TBHamiltonian Build an SSH (Su-Schrieffer-Heeger) tight-binding Hamiltonian with an explicit 2-component sublattice index, as a `TBHamiltonian`. @@ -446,10 +446,15 @@ Build an SSH (Su-Schrieffer-Heeger) tight-binding Hamiltonian with an explicit The chain has periodic boundary conditions (B(N-1) ↔ A(0) inter-cell bond from the binary-increment wrap-around), consistent with all other QTT Hamiltonians. + +`cutoff` defaults to `min(1e-8, 0.1/D)`, D = 2·2^L the number of atoms: with the fixed +`1e-8` of v0.2.0 the inter-cell bonds whose carry flips the top two qubits were lost at +L = 26 (see "Large systems" in [`get_Hamiltonian`](@ref)). """ function ssh_sublattice_hamiltonian(L::Integer, t::Number = 1.0, d::Number = 0.0; - cutoff::Real = 1e-8, + cutoff::Union{Nothing,Real} = nothing, maxdim::Int = 200) + cutoff = _mpo_cutoff(cutoff, 2 * 2.0^L, "ssh_sublattice_hamiltonian"; keyword="cutoff") # A 1D chain: the setup of a 2^L × 2^0 grid. S = _sublattice_setup(L, 0, 2, "SSH"; cutoff, maxdim) diff --git a/src/physics/Supercond.jl b/src/physics/Supercond.jl index b20f5aa..ac88bf2 100644 --- a/src/physics/Supercond.jl +++ b/src/physics/Supercond.jl @@ -103,7 +103,7 @@ end """ spin_hamiltonian(H_up, H_down, spin_s; - H_Zeeman=nothing, cutoff=1e-8) -> MPO + H_Zeeman=nothing, cutoff=nothing) -> MPO Build a spin-resolved Hamiltonian on `[spin_s; pos_sites…]`: @@ -113,10 +113,16 @@ Build a spin-resolved Hamiltonian on `[spin_s; pos_sites…]`: spin-orbit coupling or magnetic exchange). `H_Zeeman` is an optional position-MPO encoding a local magnetic field `h(x)`; it enters as `S_z ⊗ H_Zeeman` so spin-↑ gains `+½ h(x)` and spin-↓ gains `−½ h(x)`. + +`cutoff` is the relative cutoff of the sums, by default `min(1e-8, 0.1/D)`, D the dimension +of the spinful site space (`1e-8` up to D = 2^23; see "Large systems" in +[`get_Hamiltonian`](@ref)). """ function spin_hamiltonian(H_up::MPO, H_down::MPO, spin_s::Index; H_Zeeman::Union{MPO, Nothing} = nothing, - cutoff::Real = 1e-8) + cutoff::Union{Nothing,Real} = nothing) + cutoff = _mpo_cutoff(cutoff, dim(spin_s) * _site_space_dim(_mpo_ket_sites(H_up)), + "spin_hamiltonian"; keyword="cutoff") H = +(prepend_spin(H_up, spin_s, :Pup), prepend_spin(H_down, spin_s, :Pdn); cutoff=cutoff) isnothing(H_Zeeman) || (H = +(H, prepend_spin(H_Zeeman, spin_s, :Sz); cutoff=cutoff)) @@ -125,7 +131,7 @@ end """ - bdg_hamiltonian(H_kin, H_pair, nambu_s; cutoff=1e-8) -> MPO + bdg_hamiltonian(H_kin, H_pair, nambu_s; cutoff=nothing) -> MPO Build a **spinless** Bogoliubov–de Gennes Hamiltonian on `[nambu_s; pos_sites…]`, in the Nambu basis `(c, c†)`: @@ -152,9 +158,15 @@ H_pair = pairingNNN(L, sites, Δ * MPO(sites, "Id"), 1) # Δ(i,i+1) = +Δ, Δ( `τ_- ⊗ H_pair†` is built automatically. For a general `Δ(i,j)` use `pairing2MPO`. The result is Hermitian for any `H_kin = H_kin†` and any complex `H_pair`. + +`cutoff` is the relative cutoff of the sums, by default `min(1e-8, 0.1/D)`, D the dimension +of the BdG site space (`1e-8` up to D = 2^23; see "Large systems" in +[`get_Hamiltonian`](@ref)). """ function bdg_hamiltonian(H_kin::MPO, H_pair::MPO, nambu_s::Index; - cutoff::Real = 1e-8) + cutoff::Union{Nothing,Real} = nothing) + cutoff = _mpo_cutoff(cutoff, dim(nambu_s) * _site_space_dim(_mpo_ket_sites(H_kin)), + "bdg_hamiltonian"; keyword="cutoff") H_pair_adj = swapprime(dag(H_pair), 0, 1) return +(+(_nambu_normal_block(H_kin, nambu_s, :pre; cutoff=cutoff), prepend_nambu(H_pair, nambu_s, :tp); cutoff=cutoff), @@ -164,7 +176,7 @@ end """ bdg_spin_hamiltonian(H_kin_up, H_kin_down, H_pair, spin_s, nambu_s; - H_soc=nothing, cutoff=1e-8) -> MPO + H_soc=nothing, cutoff=nothing) -> MPO Build a **spin-½ singlet** BdG Hamiltonian on `[nambu_s, spin_s; pos_sites…]`. @@ -190,13 +202,20 @@ spin factor `i·σ_y = [[0,1],[−1,0]]`. For on-site s-wave pairing, build `H_soc` (optional) adds an Ising-type spin-orbit coupling `N(S_z ⊗ H_soc)`. The result is Hermitian for real or complex `H_pair` and any `H_kin_up/dn`. + +`cutoff` is the relative cutoff of the sums, by default `min(1e-8, 0.1/D)`, D the dimension +of the spinful BdG site space (`1e-8` up to D = 2^23; see "Large systems" in +[`get_Hamiltonian`](@ref)). """ function bdg_spin_hamiltonian( H_kin_up::MPO, H_kin_down::MPO, H_pair::MPO, spin_s::Index, nambu_s::Index; H_soc::Union{MPO, Nothing} = nothing, - cutoff::Real = 1e-8, + cutoff::Union{Nothing,Real} = nothing, ) + cutoff = _mpo_cutoff(cutoff, + dim(nambu_s) * dim(spin_s) * _site_space_dim(_mpo_ket_sites(H_kin_up)), + "bdg_spin_hamiltonian"; keyword="cutoff") # N(P_↑ ⊗ H_kin_up) and N(P_↓ ⊗ H_kin_down): τ_z ⊗ … for real terms H = +(_nambu_normal_block(prepend_spin(H_kin_up, spin_s, :Pup), nambu_s, :pre; cutoff=cutoff), _nambu_normal_block(prepend_spin(H_kin_down, spin_s, :Pdn), nambu_s, :pre; cutoff=cutoff); diff --git a/src/physics/TwoParticle.jl b/src/physics/TwoParticle.jl index b54a300..327f139 100644 --- a/src/physics/TwoParticle.jl +++ b/src/physics/TwoParticle.jl @@ -12,11 +12,11 @@ """ exciton_hamiltonian(geometry, params, Ufunc; L, on_site=nothing, scale=nothing, - tol_quantics=1e-8, maxbonddim_quantics=100, tol=1e-8, cutoff=1e-8, + tol_quantics=1e-8, maxbonddim_quantics=100, tol=nothing, cutoff=1e-8, maxdim=200, kwargs...) -> TBHamiltonian exciton_hamiltonian(H_c, H_v, Ufunc; on_site=nothing, scale=nothing, - tol_quantics=1e-8, maxbonddim_quantics=100, tol=1e-8, cutoff=1e-8, + tol_quantics=1e-8, maxbonddim_quantics=100, tol=nothing, cutoff=1e-8, maxdim=200) -> TBHamiltonian Build an exciton Hamiltonian and wrap it in a `TBHamiltonian` for use with @@ -57,9 +57,12 @@ TensorBinding's KPM, DMRG, and spectral tools. term from `Ufunc` is interpolated at a fixed `1e-8`, see `build_interaction_op_exciton`.) - `maxbonddim_quantics` : QTCI max bond dimension for `on_site`. Default `100`. -- `tol` : MPO assembly truncation tolerance. Default `1e-8`. The - geometry method also passes it to `get_Hamiltonian` for both - sectors. +- `tol` : MPO assembly truncation tolerance, by default + `min(1e-8, 0.1/2^L)` (`1e-8` up to L = 23). The geometry + method also passes it to `get_Hamiltonian` for both sectors, + whose default is the same: with the fixed `1e-8` of v0.2.0 a 1D + sector lost the bond across the middle of the chain from L = 26 + (see "Large systems" in [`get_Hamiltonian`](@ref)). - `maxdim` : the geometry method passes it to `get_Hamiltonian` for both sectors (default `200`, not `get_Hamiltonian`'s `15`); the assembled exciton MPO itself is not truncated, so with @@ -74,7 +77,7 @@ function exciton_hamiltonian(geometry::String, params, Ufunc; scale = nothing, tol_quantics = 1e-8, maxbonddim_quantics = 100, - tol = 1e-8, + tol = nothing, cutoff = 1e-8, maxdim = 200, kwargs...) @@ -93,7 +96,7 @@ function exciton_hamiltonian(H_c::TBHamiltonian, H_v::TBHamiltonian, Ufunc; scale = nothing, tol_quantics = 1e-8, maxbonddim_quantics = 100, - tol = 1e-8, + tol = nothing, cutoff = 1e-8, maxdim = 200) _require_binary_position_space(H_c, "exciton_hamiltonian") @@ -120,7 +123,7 @@ end """ Exciton_Hamiltonian(H_c, H_v, Ufunc; on_site=nothing, tol_quantics=1e-8, - maxbonddim_quantics=100, tol=1e-8, cutoff=1e-8, + maxbonddim_quantics=100, tol=nothing, cutoff=1e-8, maxdim=200) -> MPO Build the exciton Hamiltonian on the interleaved 2L-site electron-hole space: @@ -144,8 +147,9 @@ and `−V` to the valence sector, so that the hole also feels `+V` after the `H_c − H_v` subtraction (type-I semiconductor convention: both carriers confined). `tol_quantics` and `maxbonddim_quantics` control the QTCI compression of `V`. -`tol` is the cutoff of the sums that add `V`; the keywords `cutoff` and `maxdim` are -accepted but unused (the returned MPO is not truncated). +`tol` is the cutoff of the sums that add `V`, by default `min(1e-8, 0.1/D)` with D the +dimension of a sector's site space (`1e-8` up to D = 2^23); the keywords `cutoff` and +`maxdim` are accepted but unused (the returned MPO is not truncated). Examples -------- @@ -166,7 +170,7 @@ function Exciton_Hamiltonian(H_c::TBHamiltonian, H_v::TBHamiltonian, Ufunc; on_site = nothing, tol_quantics = 1e-8, maxbonddim_quantics = 100, - tol = 1e-8, + tol = nothing, cutoff = 1e-8, maxdim = 200) @assert H_c.L == H_v.L "Electron and hole sectors must have the same system size" @@ -184,8 +188,9 @@ function Exciton_Hamiltonian(H_c::TBHamiltonian, H_v::TBHamiltonian, Ufunc; tol_quantics=tol_quantics, maxbonddim_quantics=maxbonddim_quantics) V_v = qtt_mpo(L, xvals, H_v.sites, on_site; tol_quantics=tol_quantics, maxbonddim_quantics=maxbonddim_quantics) - mpo_c = +(mpo_c, V_c; cutoff=tol) - mpo_v = +(mpo_v, -1.0*V_v; cutoff=tol) + cut = _mpo_cutoff(tol, _site_space_dim(H_c.sites), "Exciton_Hamiltonian") + mpo_c = +(mpo_c, V_c; cutoff=cut) + mpo_v = +(mpo_v, -1.0*V_v; cutoff=cut) end # Electron (H_c.sites) on the odd sites of sites_eh (interleave_mpo n = 1), hole diff --git a/test/bugfix_large_L_cutoffs.jl b/test/bugfix_large_L_cutoffs.jl new file mode 100644 index 0000000..0739bfe --- /dev/null +++ b/test/bugfix_large_L_cutoffs.jl @@ -0,0 +1,40 @@ +using TensorBinding, ITensors, ITensorMPS, LinearAlgebra, Test, Logging +using TensorBinding: get_Hamiltonian, add_onsite!, binary_to_MPS + +# ITensors' cutoffs are relative to ‖H‖², which grows with the system: with the fixed 1e-8 +# of v0.2.0 the 1D builders and the term adders dropped the bond across the middle of a +# chain (n = 2^(L-1) - 1 → 2^(L-1), whose carry flips every qubit) from L = 26 on, and +# get_Hamiltonian("custom") with nearest-neighbour hops threw (its self-check caught the +# missing bond). The default cutoff is now min(1e-8, 0.1/D), D the dimension of the site +# space; an explicit value is used as given and warns above 0.3/D. + +const _TBc = TensorBinding +_el(H, a, b) = real(inner(binary_to_MPS(a, H.L, H.sites)', H.mpo, binary_to_MPS(b, H.L, H.sites))) +_middle(H) = _el(H, 2^(H.L - 1) - 1, 2^(H.L - 1)) # the bond across the middle +_wrap(H) = _el(H, 0, 2^H.L - 1) # zero on an open chain + +@testset "Size-aware truncation cutoff of the Hamiltonian builders" begin + dc = _TBc._default_mpo_cutoff + @test dc(2.0^23) == 1e-8 && dc(2.0^10) == 1e-8 # unchanged up to D = 2^23 + @test dc(2.0^24) ≈ 0.1 / 2.0^24 + @test _TBc._mpo_cutoff(nothing, 2.0^26, "f") ≈ 0.1 / 2.0^26 + @test (@test_logs min_level=Logging.Warn _TBc._mpo_cutoff(1e-8, 2.0^24, "f")) == 1e-8 + @test (@test_logs (:warn, r"single matrix element") _TBc._mpo_cutoff(1e-8, 2.0^26, "g")) == 1e-8 + + L = 26 + H = @test_logs min_level=Logging.Warn get_Hamiltonian("chain_1d", 1.0; L) + @test _middle(H) ≈ 1.0 atol=1e-8 + @test abs(_wrap(H)) < 1e-8 + Hold = @test_logs (:warn, r"single matrix element") get_Hamiltonian("chain_1d", 1.0; L, tol=1e-8) + @test abs(_middle(Hold) - 1.0) > 0.5 # what v0.2.0 built + + add_onsite!(H, n -> 0.1 * cos(0.3n)) # with 1e-8 it cut the chain again + @test _middle(H) ≈ 1.0 atol=1e-8 + + # the QTCI presets (hopping2MPO and their own sums) and "custom", which threw + for (geom, p, kw) in (("uniform", 1.0, (;)), + ("aah", (V=0.5, phi=0.0, t=1.0), (;)), + ("custom", (i, j) -> abs(i - j) == 1 ? 1.0 : 0.0, (; scale=2.5))) + @test abs(_middle(get_Hamiltonian(geom, p; L, kw...))) ≈ 1.0 atol=1e-6 + end +end diff --git a/test/runtests.jl b/test/runtests.jl index 3a59670..cd0d345 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -144,6 +144,7 @@ include("bugfix_soc_boundary.jl") include("bugfix_bdg_hole_block.jl") include("bugfix_build_K.jl") include("bugfix_qtci_profiles.jl") +include("bugfix_large_L_cutoffs.jl") # The 0.1 names and keywords renamed in 0.2: deprecated aliases with a one-time warning. include("deprecations.jl") From f49a6380d9f181ab9d8d26107ae2d1ee4c20d456 Mon Sep 17 00:00:00 2001 From: Anouar Moustaj Date: Fri, 13 Nov 2026 10:45:02 +0200 Subject: [PATCH 14/22] Let add_onsite! act on spinful and BdG Hamiltonians add_onsite! built the potential on the position (and sublattice) sites only and added it to H.mpo, which on a Hamiltonian with a spin or Nambu index threw "the input MPS or MPO do not have the same site indices" (a function and a vector alike): the potential had to come before add_spin! and add_superconductivity!. It now lifts the term with _lift_normal_term, as add_zeeman! and add_soc! do: the identity on the spin, tau_z (x) V on the Nambu index (the hole block -V* of _nambu_normal_block, i.e. -V for a real V), the sublattice projector on a sublattice index, each on the side H.sites puts it. That is the matrix the old order gave. A complex V on a BdG Hamiltonian is an error: it is not Hermitian, and the BdG hole block -H* is only right for a Hermitian H. The spinless and sublattice paths are unchanged; a layered Hamiltonian with spin or Nambu still errors, as before. Test: test/bugfix_onsite_aux.jl (L = 3 chain with the spin in front and behind, a spinful BdG with a Zeeman field along y, the Kitaev chain, SSH with sublat = 1 and a spin; each against adding the potential before; the complex-V error). On a BdG Hamiltonian a complex value is rejected with that error whatever its form: a complex number up front, function values as QTCI samples them (they used to reach the real-valued QTCI build and stop there with an InexactError), vectors after their TT-SVD build. The scftopo golden case tbsystem/add_onsite!/spinful pinned the v0.2.0 error; it now pins the value, kron(I2, H0 + 0.1 I) to 1.9e-15. The new entry was spliced into the stored file: a full rerun of generate_scftopo_golden.jl moved only this entry, the count of throwing cases (27 -> 26) and the two get_W KPM entries its header keeps at their old values (2.3e-11 and 3.2e-11). Scftopo goldens 199/199. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 +++++ src/core/TBSystem.jl | 38 ++++++++++++++++++-- test/bugfix_onsite_aux.jl | 52 ++++++++++++++++++++++++++++ test/data/generate_scftopo_golden.jl | 5 ++- test/data/scftopo_golden.jl | 8 +++-- test/runtests.jl | 1 + 6 files changed, 105 insertions(+), 7 deletions(-) create mode 100644 test/bugfix_onsite_aux.jl diff --git a/CHANGELOG.md b/CHANGELOG.md index 5eaf5fd..873485a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -127,6 +127,14 @@ bugs without breaking the API. ### Fixed +- **`add_onsite!` on a spinful or BdG Hamiltonian** threw ("the input MPS or MPO do not + have the same site indices"): the potential was built on the position (and sublattice) + sites only, so it had to come before `add_spin!` and `add_superconductivity!`. It is + now the identity on the spin and `τ_z ⊗ V` on the Nambu index, the same matrix as + adding it before; a complex `V` on a BdG Hamiltonian is an error, since it is not + Hermitian. A layered Hamiltonian with spin or Nambu is still not supported. The + golden case `tbsystem/add_onsite!/spinful` of `test/data/scftopo_golden.jl`, which + pinned the old error, now pins the value. - The `add_soc!` docstring gave the Rashba term as `λ·(S_y ⊗ K_u − S_y ⊗ K_d)`, which is not Hermitian; the code builds `λ·iσ_y ⊗ (K_u − K_d)`, as the docstring now says. - The `get_dos_stochastic` docstring called its `normalize=false` output the total diff --git a/src/core/TBSystem.jl b/src/core/TBSystem.jl index 422d225..d801979 100644 --- a/src/core/TBSystem.jl +++ b/src/core/TBSystem.jl @@ -971,6 +971,13 @@ For layered sublattice Hamiltonians, the onsite term is first built on the `position ⊗ sublattice` monolayer space, then wrapped with the selected layer projectors. +**Spin and Nambu indices** (not layered): on a spinful Hamiltonian the potential is the +identity on the spin (a spin-dependent one goes through [`add_zeeman!`](@ref)); on a BdG +Hamiltonian it enters as `τ_z ⊗ V`, `V` in the particle and `−V` in the hole block, so `f` +must be real there. Up to v0.2.0 `add_onsite!` threw on a Hamiltonian with a spin or +Nambu index; it had to come before [`add_spin!`](@ref) and +[`add_superconductivity!`](@ref), which give the same result. + `tol` is the relative cutoff of the sum, by default `min(1e-8, 0.1/D)`, D the dimension of the site space (`1e-8` up to D = 2^23; see "Large systems" in [`get_Hamiltonian`](@ref)). @@ -1042,17 +1049,38 @@ function add_onsite!(H::TBHamiltonian, f; layer=nothing, sublat=nothing, fkind === :scalar && iszero(f) && return _add_zero_onsite!(H, sublat) + # On a BdG Hamiltonian a complex value is rejected with the error of a complex vector + # (below), before the real-valued QTCI build would stop on it with an InexactError. + bdg = H.nambu_s !== nothing + bdg && fkind === :scalar && !isreal(f) && error(_BDG_COMPLEX_ONSITE_MSG) + val = bdg ? (v -> isreal(v) ? v : error(_BDG_COMPLEX_ONSITE_MSG)) : identity + diag_mpo = if fkind === :scalar get_diagonal_mpo(L, pos_s, x -> f) elseif fkind === :vector get_diagonal_mpo(L, pos_s, f) elseif fkind === :pos1d - get_diagonal_mpo(L, pos_s, i -> f(round(Int, i) - 1); check=check) + get_diagonal_mpo(L, pos_s, i -> val(f(round(Int, i) - 1)); check=check) else # :pos2d - get_diagonal_mpo(L, pos_s, i -> (n = round(Int, i) - 1; f(n % Nx, n ÷ Nx)); check=check) + get_diagonal_mpo(L, pos_s, i -> (n = round(Int, i) - 1; val(f(n % Nx, n ÷ Nx))); check=check) end - if H.sublattice_s !== nothing + if H.spin_s !== nothing || H.nambu_s !== nothing + # Spinful or BdG: the identity on the spin, τ_z ⊗ V on the Nambu index (the hole + # block −V* of _nambu_normal_block, −V for a real V), the sublattice matrix below on + # a sublattice index, each on the side H.sites puts it. Up to v0.2.0 the term was + # added on the position (and sublattice) sites only, which threw. + ops = Dict{Index,Any}() + if H.sublattice_s !== nothing + n = dim(H.sublattice_s) + ops[H.sublattice_s] = isnothing(sublat) ? Matrix{Float64}(I, n, n) : + (proj = zeros(Float64, n, n); proj[sublat, sublat] = 1.0; proj) + elseif !isnothing(sublat) + error("add_onsite! with sublat=$sublat requires H.sublattice_s to be set.") + end + (H.nambu_s === nothing || _mpo_is_real(diag_mpo)) || error(_BDG_COMPLEX_ONSITE_MSG) + new_term = _lift_normal_term(H, diag_mpo, ops; cutoff=cut) + elseif H.sublattice_s !== nothing sl_s = H.sublattice_s n = dim(sl_s) sl_pos = findfirst(==(sl_s), H.sites) @@ -1080,6 +1108,10 @@ function add_onsite!(H::TBHamiltonian, f; layer=nothing, sublat=nothing, return H end +const _BDG_COMPLEX_ONSITE_MSG = + "add_onsite!: a complex on-site term on a BdG Hamiltonian is not Hermitian, and the " * + "BdG hole block (−H*) is only right for a Hermitian H; pass real values." + # add_onsite! of the constant 0: nothing to add (its QTCI compression would throw # "maxsamplevalue is zero!"), so H.mpo is left as it is; the `sublat` check and the cache # invalidation are those of any other add_onsite! call. diff --git a/test/bugfix_onsite_aux.jl b/test/bugfix_onsite_aux.jl new file mode 100644 index 0000000..fedabb7 --- /dev/null +++ b/test/bugfix_onsite_aux.jl @@ -0,0 +1,52 @@ +using TensorBinding, ITensors, ITensorMPS, LinearAlgebra, Test +using TensorBinding: get_Hamiltonian, add_onsite!, add_spin!, add_superconductivity!, add_zeeman! + +# add_onsite! threw on a Hamiltonian with a spin or Nambu index (v0.2.0): the potential was +# built on the position (and sublattice) sites only. It now acts as the identity on the +# spin and as τ_z ⊗ V on the Nambu index, so adding it after add_spin! or +# add_superconductivity! gives what adding it before did. + +const _TBo = TensorBinding +_dense(H) = _TBo._mpo_dense_matrix(H.mpo) + +@testset "add_onsite! on spinful and BdG Hamiltonians" begin + L = 3; N = 2^L + f(n) = 0.1 * n - 0.3 + chain() = get_Hamiltonian("chain_1d", 1.0; L) + + # spinful, with the spin in front (the default) and behind + for pos in (:pre, :post) + Hb = chain(); add_onsite!(Hb, f); add_spin!(Hb; position=pos) + Ha = chain(); add_spin!(Ha; position=pos); add_onsite!(Ha, f) + @test _dense(Ha) ≈ _dense(Hb) atol=1e-10 + end + Hs = chain(); add_spin!(Hs); add_onsite!(Hs, f) # spin = most significant site + @test _dense(Hs) ≈ kron(Matrix(1.0I, 2, 2), _dense(chain()) + Diagonal(f.(0:N-1))) atol=1e-10 + + # spinful BdG with a Zeeman field along y (complex), the potential after the doubling + function bdg(onsite_first) + H = chain() + onsite_first && add_onsite!(H, f) + add_zeeman!(H, 0.3; direction=:y) + add_superconductivity!(H, 0.25) + onsite_first || add_onsite!(H, f) + return H + end + @test _dense(bdg(false)) ≈ _dense(bdg(true)) atol=1e-10 + + # spinless BdG (Kitaev chain) + Hk1 = chain(); add_onsite!(Hk1, f); add_superconductivity!(Hk1, 0.2; type=:pwave) + Hk2 = chain(); add_superconductivity!(Hk2, 0.2; type=:pwave); add_onsite!(Hk2, f) + @test _dense(Hk2) ≈ _dense(Hk1) atol=1e-10 + # a complex on-site term is not Hermitian, and the BdG hole block needs a Hermitian H + @test_throws ErrorException add_onsite!(Hk2, fill(0.1im, N)) + @test_throws ErrorException add_onsite!(Hk2, 0.1im) # not an InexactError + @test_throws ErrorException add_onsite!(Hk2, n -> 0.1im * (n + 1)) + + # sublattice and spin: SSH, the potential on sublattice 1 + Hs1 = get_Hamiltonian("ssh_sublattice", (t=1.0, d=0.2); L=2) + Hs2 = deepcopy(Hs1) + add_onsite!(Hs1, n -> 0.1 * n; sublat=1); add_spin!(Hs1) + add_spin!(Hs2); add_onsite!(Hs2, n -> 0.1 * n; sublat=1) + @test _dense(Hs2) ≈ _dense(Hs1) atol=1e-10 +end diff --git a/test/data/generate_scftopo_golden.jl b/test/data/generate_scftopo_golden.jl index 46b5e52..c16a46a 100644 --- a/test/data/generate_scftopo_golden.jl +++ b/test/data/generate_scftopo_golden.jl @@ -16,7 +16,10 @@ # runaway to NaN, half the states as the default Nel), the four add_superconductivity! # scale fields, and the two density-cache cases (the cache answers only its own method). # The get_W/KPM_flat and KPM_quenched entries move at the 1e-11 level from one -# regeneration to the next; they are kept at their old values. +# regeneration to the next; they are kept at their old values. The 0.2.1 fix of +# add_onsite! on spinful Hamiltonians regenerated tbsystem/add_onsite!/spinful, which +# had pinned the v0.2.0 error; its new entry was spliced into the stored file, every +# other entry kept, and the data header says so (this script has no --only). # # The cases themselves are defined in test/golden_scftopo.jl (module ScftopoGolden), # which this script includes with SCFTOPO_GOLDEN_GENERATOR defined so that only the diff --git a/test/data/scftopo_golden.jl b/test/data/scftopo_golden.jl index 3bd438c..854272d 100644 --- a/test/data/scftopo_golden.jl +++ b/test/data/scftopo_golden.jl @@ -4,6 +4,8 @@ # Generated from src/ tree bf2cb816172e # with Julia 1.12.3. Regenerate only for an intentional behaviour change; # see the generator's header. +# Entry tbsystem/add_onsite!/spinful regenerated for the 0.2.1 fix of add_onsite! on +# spinful Hamiltonians (it no longer throws); every other entry kept its values. # # Each entry is (name, throws, expected): `name` selects a case of # ScftopoGolden.CASES (test/golden_scftopo.jl); `throws` is the name of the @@ -11,7 +13,7 @@ # is the case's value, or for a throwing case the first 60 characters of # its message (`message_prefix`, `nothing` when the exception has no message). # -# 195 cases, 27 of them pinned as throwing. +# 195 cases, 26 of them pinned as throwing. SCFTOPO_GOLDEN_CASES = Any[] @@ -63,8 +65,8 @@ push!(SCFTOPO_GOLDEN_CASES, (name = "tbsystem/add_onsite!/layered_spinful", thro push!(SCFTOPO_GOLDEN_CASES, (name = "tbsystem/add_onsite!/unsupported_signature", throws = "ErrorException", expected = (message_prefix = "add_onsite!: unsupported f signature.",))) -push!(SCFTOPO_GOLDEN_CASES, (name = "tbsystem/add_onsite!/spinful", throws = "ErrorException", - expected = (message_prefix = "In `+(::MPS/MPO...)`, the input `MPS` or `MPO` do not have t",))) +push!(SCFTOPO_GOLDEN_CASES, (name = "tbsystem/add_onsite!/spinful", throws = nothing, + expected = (mpo = ComplexF64[0.09999999999999992 + 0.0im 0.999999999999999 + 0.0im 3.9252311466902396e-17 + 0.0im 6.960274364096636e-17 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im; 0.9999999999999981 + 0.0im 0.09999999999999996 + 0.0im 0.9999999999999992 + 0.0im 3.9252311466902415e-17 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im; 1.0188397731345939e-15 + 0.0im 0.999999999999999 + 0.0im 0.09999999999999999 + 0.0im 0.9999999999999994 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im; 2.496054612122747e-16 + 0.0im 1.0188397731345945e-15 + 0.0im 0.999999999999999 + 0.0im 0.10000000000000005 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im; 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.09999999999999995 + 0.0im 0.9999999999999997 + 0.0im 3.9252311466902415e-17 + 0.0im 1.6715578222594704e-16 + 0.0im; 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.9999999999999988 + 0.0im 0.1 + 0.0im 0.9999999999999998 + 0.0im 3.9252311466902433e-17 + 0.0im; 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 1.0188397731345945e-15 + 0.0im 0.9999999999999996 + 0.0im 0.10000000000000003 + 0.0im 0.9999999999999999 + 0.0im; 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 0.0 + 0.0im 2.3613619733473978e-16 + 0.0im 1.0188397731345949e-15 + 0.0im 0.9999999999999994 + 0.0im 0.10000000000000007 + 0.0im], sites_match = true, dims = [2, 2, 2], tags = ["\"Spin\"", "\"Qubit,Site,n=1\"", "\"Qubit,Site,n=2\""], L = 2, N = 4, Lx = nothing, scale = 0.0, center = 0.0, aux_side = :pre, spin_pos = 1, nambu_pos = nothing, layer_pos = nothing, sublattice_pos = nothing, geometry = [[1.0], [2.0], [3.0], [4.0]], geometry_uc = nothing, interaction = nothing, fock = nothing, tn_Ncheb = 0, has_tn_cache = false, has_density_cache = false, position_space = "BinaryPositionSpace"))) push!(SCFTOPO_GOLDEN_CASES, (name = "tbsystem/add_hopping!/scalar_nn1", throws = nothing, expected = (mpo = [-5.437529463627866e-32 1.2999999999999998 6.283740653744388e-17 4.0548251590268217e-16 8.597516641367433e-32 -6.062191664034892e-16 1.8392485043977414e-33 -3.4845587547023205e-17; 1.2999999999999985 0.0 1.2999999999999998 0.0 1.1724620761327671e-15 0.0 3.205363112315146e-18 0.0; -6.283740653744385e-17 1.2999999999999985 -4.406349473567261e-33 1.2999999999999992 6.283740653744403e-17 -1.4191722272344514e-15 -7.890874125174856e-49 2.3280351284580695e-16; -7.558769489431313e-17 0.0 1.2999999999999994 0.0 1.300000000000001 0.0 2.32803512845807e-16 0.0; -1.3306450577230843e-32 -1.7545622953232885e-16 -6.283740653744394e-17 1.3000000000000003 -5.437529463627865e-32 1.2999999999999992 6.283740653744385e-17 3.864341002518903e-16; -4.507442578517701e-16 0.0 6.006217499225155e-17 0.0 1.299999999999998 0.0 1.2999999999999992 0.0; 1.3498274005765498e-34 8.317440638835377e-16 8.126672739537083e-49 -2.3976025108252067e-16 -6.283740653744384e-17 1.299999999999998 -4.4063494735672596e-33 1.2999999999999987; 8.345366292000327e-16 0.0 -2.397602510825207e-16 0.0 -2.516453564134826e-16 0.0 1.299999999999999 0.0], sites_match = true, dims = [2, 2, 2], tags = ["\"Qubit,Site,n=1\"", "\"Qubit,Site,n=2\"", "\"Qubit,Site,n=3\""], L = 3, N = 8, Lx = nothing, scale = 0.0, center = 0.0, aux_side = :pre, spin_pos = nothing, nambu_pos = nothing, layer_pos = nothing, sublattice_pos = nothing, geometry = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0], [7.0], [8.0]], geometry_uc = nothing, interaction = nothing, fock = nothing, tn_Ncheb = 0, has_tn_cache = false, has_density_cache = false, position_space = "BinaryPositionSpace"))) diff --git a/test/runtests.jl b/test/runtests.jl index cd0d345..ed3b284 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -145,6 +145,7 @@ include("bugfix_bdg_hole_block.jl") include("bugfix_build_K.jl") include("bugfix_qtci_profiles.jl") include("bugfix_large_L_cutoffs.jl") +include("bugfix_onsite_aux.jl") # The 0.1 names and keywords renamed in 0.2: deprecated aliases with a one-time warning. include("deprecations.jl") From 8633167c8e346416f0a9898ab49b3827b56585b9 Mon Sep 17 00:00:00 2001 From: Anouar Moustaj Date: Fri, 13 Nov 2026 10:45:12 +0200 Subject: [PATCH 15/22] Add --only to the dynamics golden generator A full rerun of generate_dynamics_golden.jl moves untouched cases by rounding (the three krylov_green cases by up to 5e-14 in the rerun for 8d4eb10), so their stored lines had to be restored by hand. `--only name1,name2,...` now reruns the named cases and keeps the stored entries of all others, as generate_gpu_golden.jl does since 8d4eb10. The header keeps the previous generation lines and records the src/ tree and the cases of the partial rerun; generation_lines also reads the header written before this change, which had the "Regenerate only" note at the end of the Julia line (a full rerun now puts that note on its own line). Unknown names, or kept cases with no stored entry, are errors. As before, the script reloads the file, checks the round trip and replays every case. Checked: --only dmrg_build_K,tdvp_evolve_normalized changed only the header (both cases reproduced exactly) and the replay passed 118/118; the data file was restored. Co-Authored-By: Claude Opus 5.5 --- test/data/generate_dynamics_golden.jl | 65 ++++++++++++++++++++++----- 1 file changed, 55 insertions(+), 10 deletions(-) diff --git a/test/data/generate_dynamics_golden.jl b/test/data/generate_dynamics_golden.jl index 78dbc95..0f99404 100644 --- a/test/data/generate_dynamics_golden.jl +++ b/test/data/generate_dynamics_golden.jl @@ -18,9 +18,14 @@ # only tests or docs change, so such a rerun reproduces the file byte for byte # (floating-point results are written with `repr`, which round-trips exactly) up # to rounding: the rerun for 8d4eb10 also moved the three krylov_green cases by up -# to 5e-14, although src/solvers/Krylov.jl had not changed. After a rerun, keep the -# stored lines of the cases whose code did not change, so that the data diff shows -# only the cases the change moves. +# to 5e-14, although src/solvers/Krylov.jl had not changed. A change that moves a few +# cases should therefore rerun only those, keeping the stored entries of all others, +# so that the data diff shows only the cases the change moves: +# +# ... generate_dynamics_golden.jl --only tdvp_evolve_normalized,evolve_with_tdvp_raw +# +# The header of the data file then keeps the previous generation lines and records +# the tree of the partial rerun and the cases it reran (as generate_gpu_golden.jl). # # Regenerate ONLY when a behaviour change is intentional. Do it in the same # commit as the change, review the diff of dynamics_golden.jl case by case, and @@ -42,6 +47,11 @@ include(joinpath(@__DIR__, "..", "golden_dynamics.jl")) # loads DynamicsGolden const R = DynamicsGoldenRunner const OUTFILE = joinpath(@__DIR__, "dynamics_golden.jl") +# `--only name1,name2,…`: rerun these cases, keep the stored entries of the others. +const ONLY = let i = findfirst(==("--only"), ARGS) + i === nothing ? nothing : Set(String.(split(ARGS[i + 1], ','))) +end + # An exception of one of these types means the case itself is malformed (a # misspelt keyword, a wrong argument type), not a behaviour worth pinning. const GENERATOR_BUGS = (MethodError, UndefVarError, UndefKeywordError, TypeError) @@ -90,15 +100,34 @@ function src_info() end end -function write_golden(path, entries) +# The generation lines of the data file at `path` (line 4 up to the "Regenerate only" note), +# which a partial rerun keeps. Files written before --only existed carry the note at the end +# of their "with Julia" line, which is cut there. +function generation_lines(path) + lines = readlines(path) + stop = findfirst(l -> occursin("Regenerate only", l), lines) + stop === nothing && error("$path: no \"Regenerate only\" line in the header") + head = lines[4:stop] + tail = rstrip(first(split(head[end], " Regenerate only"))) + return tail == "#" ? head[1:end-1] : [head[1:end-1]; tail] +end + +function write_golden(path, entries; header = nothing) source = src_info() open(path, "w") do io println(io, "# AUTO-GENERATED by test/data/generate_dynamics_golden.jl -- do not edit by hand.") println(io, "#") println(io, "# Pinned outputs of the dynamics area, checked by test/golden_dynamics.jl.") - println(io, "# Generated from $source") - println(io, "# with Julia $VERSION. Regenerate only for an intentional behaviour change;") - println(io, "# see the generator's header.") + if header === nothing + println(io, "# Generated from $source") + println(io, "# with Julia $VERSION.") + else + # a partial rerun (--only): the previous generation lines, then this rerun + foreach(l -> println(io, l), header) + println(io, "# Rerun with --only from $source with Julia $VERSION:") + println(io, "# ", join(sort!(collect(ONLY)), ", "), ".") + end + println(io, "# Regenerate only for an intentional behaviour change; see the generator's header.") println(io, "#") println(io, "# Each entry is (name, group, seed, throws, expected): the case of that name in") println(io, "# DynamicsGoldenRunner.CASES is run after Random.seed!(seed); `throws` is the") @@ -130,9 +159,25 @@ function same(a, b) end t_start = time() -entries, notes = evaluate(R.CASES) -foreach(println, notes) -write_golden(OUTFILE, entries) +if ONLY === nothing + entries, notes = evaluate(R.CASES) + foreach(println, notes) + write_golden(OUTFILE, entries) +else + names = [c.name for c in R.CASES] + unknown = setdiff(ONLY, names) + isempty(unknown) || error("--only: no such case(s): ", join(sort!(collect(unknown)), ", ")) + header = generation_lines(OUTFILE) + stored = Dict(e.name => e for e in include(OUTFILE)) + missing_names = setdiff(setdiff(names, ONLY), keys(stored)) + isempty(missing_names) || error("--only: no stored entry for ", join(missing_names, ", "), + "; rerun those cases too, or run without --only") + fresh, notes = evaluate([c for c in R.CASES if c.name in ONLY]) + foreach(println, notes) + rerun = Dict(e.name => e for e in fresh) + entries = [c.name in ONLY ? rerun[c.name] : stored[c.name] for c in R.CASES] + write_golden(OUTFILE, entries; header = header) +end loaded = include(OUTFILE) length(loaded) == length(entries) || error("round trip: $(length(loaded)) entries read back, $(length(entries)) written") From 3c9de3afcb7892ecfb79bedddf85e35cb6fc2882 Mon Sep 17 00:00:00 2001 From: Anouar Moustaj Date: Fri, 13 Nov 2026 10:46:03 +0200 Subject: [PATCH 16/22] Warn in the docstrings that 2D get_bands is not a 2D Fourier transform conjugate_by_qft applies one QFT over all position qubits, i.e. over the linear index n = ix + iy 2^Lx (src/physics/qft/conjugation.jl), not QFT_x (x) QFT_y. In 2D the k-group label (ky << Lx) | kx is then misread: its low Ly bits are the true ky and its high bits the true kx, plus a shear of (label mod 2^Ly)/2^Ly grid steps (for Lx = Ly, ky comes from the x bits and kx from the y bits). Checked on 2026-09-29 against dense diagonalisation: along Gamma -> X an anisotropic 8x8 torus (tx = 1, ty = 0.3) follows the ty band, and on 4x4 to 8x8 tori the off-diagonal part of the conjugated Hamiltonian is 0.5-0.7 of its diagonal in Frobenius norm (that part decays with size; the relabelling and the shear do not). The kpath labels are therefore not the points they name. The low-level get_bands, the TBHamiltonian method and get_bands_gpu now carry a warning admonition; the code and every result are unchanged (1D is not affected). The fix, an opt-in separable 2D transform (or plane-wave probes) beside the current path, is left for a later release. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 ++++++ src/gpu/bands.jl | 5 +++++ src/physics/qft/bands.jl | 16 ++++++++++++++++ 3 files changed, 27 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 873485a..7659974 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,6 +50,12 @@ bugs without breaking the API. do, with the Jackson moment count: `kernel=:jackson` with `Ncheb` moments is the textbook kernel for `Ncheb − 1` moments (the last weight is zero). Results are unchanged. +- **2D bands documented as wrong.** In 2D, `get_bands` and `get_bands_gpu` take their + momenta from one QFT over the linear index `n = ix + iy·2^Lx`, not from a QFT along x + times one along y: ky is read from the x bits and kx from the y bits, with a shear, so + 2D bands are not resolved by `(kx, ky)` and the `kpath` labels are not the points they + name. Both docstrings now say so; results are unchanged, and a separable 2D transform + is left for a later release. 1D is not affected. ### Changed results diff --git a/src/gpu/bands.jl b/src/gpu/bands.jl index b55903a..dc36e69 100644 --- a/src/gpu/bands.jl +++ b/src/gpu/bands.jl @@ -54,6 +54,11 @@ heatmap(1:size(res.Ak,2), omega, res.Ak; xticks=(res.ticks, res.labels)) result is the spectral density per unit rescaled energy `(ω − H.center)/H.scale` times `1/π`, so each momentum state integrates to `1/π`; multiply by `π/H.scale` for physical units. + +!!! warning "2D bands" + As in [`get_bands`](@ref): in 2D one QFT runs over the linear index + `n = ix + iy·2^Lx`, which mixes kx and ky, so 2D bands are not resolved by `(kx, ky)` + and the `kpath` labels are not the points they name. 1D is not affected. """ function get_bands_gpu(H::TBHamiltonian, Ncheb::Int, ω_phys_vals; kpath = nothing, diff --git a/src/physics/qft/bands.jl b/src/physics/qft/bands.jl index 0f243db..3035ea7 100644 --- a/src/physics/qft/bands.jl +++ b/src/physics/qft/bands.jl @@ -248,6 +248,16 @@ an `ArgumentError` instead. # Returns `Matrix{Float64}` of shape `(Nω, num_x)`. + +!!! warning "2D: one QFT over the linear index" + In 2D the momenta come from one QFT over all position qubits (`conjugate_by_qft`), + i.e. over the linear index `n = ix + iy·2^Lx`, not from a QFT along x times one along + y. The label `(ky << Lx) | kx` of a k-group then reads ky from the x bits and kx from + the y bits, with a shear of `x/2^Ly` grid steps, so 2D bands are not resolved by + `(kx, ky)`: on a torus 50–72 % of the weight stays off the momentum diagonal, and along + Γ → X an anisotropic torus (`tx = 1`, `ty = 0.3`) follows the `ty` band (checked + against dense diagonalisation). 1D is not affected. Until a separable 2D transform is + added, use 1D cuts or a dense calculation for 2D bands. """ function get_bands(H_mpo::MPO, scale::Real, center::Real, sites, Ncheb::Int, D::Int, ω_vals; @@ -502,6 +512,12 @@ Otherwise returns `Matrix{Float64}` as usual (backward-compatible). result is the spectral density per unit rescaled energy `(ω − H.center)/H.scale` times `1/π`, so each momentum state integrates to `1/π`; multiply by `π/H.scale` for physical units. + +!!! warning "2D bands" + In 2D (`D = 2`) the momenta are not those of a 2D Fourier transform: one QFT runs over + the linear index `n = ix + iy·2^Lx`, which mixes kx and ky (see the low-level method). + The `kpath` labels are therefore not the high-symmetry points they name. 1D is not + affected. """ function get_bands(H::TBHamiltonian, Ncheb::Int, D::Int, ω_phys_vals; kpath = nothing, From d30b3f25d288e300d622097c69652b2e78e07c58 Mon Sep 17 00:00:00 2001 From: Anouar Moustaj Date: Fri, 13 Nov 2026 11:11:37 +0200 Subject: [PATCH 17/22] Run the TDVP exactness checks without truncation The test of 8d4eb10 compares TDVP on a full-rank 3-site state with the exact e^{-iHt}|psi>, which reverse_step=true reproduces to 1e-15. It called tdvp_evolve, evolve_with_tdvp and evolve_with_tdvp_timedep at their default cutoff = 1e-10, so the two-site SVD could drop a singular value near the threshold: with Julia 1.10's OpenBLAS (same package versions, same initial state) evolve_with_tdvp was off by 3.3e-9 after three steps and failed the 1e-10 bound, while 1.12 rounds the other way (3e-15). With cutoff = 0 both give 1.7e-15 to 3.9e-15. The checks now pass cutoff = 0.0; the bounds and the reverse_step=false comparison are unchanged. Found by running the CI matrix's Julia 1.10 locally (juliaup, beside 1.12). Co-Authored-By: Claude Opus 5.5 --- test/bugfix_tdvp.jl | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/test/bugfix_tdvp.jl b/test/bugfix_tdvp.jl index 537246d..aa41568 100644 --- a/test/bugfix_tdvp.jl +++ b/test/bugfix_tdvp.jl @@ -79,17 +79,20 @@ end # A full-rank state, so TDVP's tangent space is the whole Hilbert space: with the # backward bond step it is exact (|Δψ| ~ 1e-15); without it, it counted terms of H # twice (|Δψ| = 0.07 per step at dt = 0.05, 0.21 after three). false was the default - # of these functions up to v0.2.0; it now warns. + # of these functions up to v0.2.0; it now warns. The exactness checks run without + # truncation (cutoff = 0): at the default cutoff = 1e-10 the two-site SVD can drop a + # singular value near the threshold, which with Julia 1.10's OpenBLAS cost + # |Δψ| = 3e-9 after three steps (1e-15 without truncation). dt = 0.05 H = get_Hamiltonian("chain_1d", 1.0; L = 3) seed!(7) ψ0 = normalize!(MPS(randn(ComplexF64, 2, 2, 2), H.sites)) ex1, ex3 = _exact_evolve(H.mpo, ψ0, dt), _exact_evolve(H.mpo, ψ0, 3dt) - @test norm(tdvp_evolve(H, ψ0, dt; normalize = false) - ex1) < 1e-10 - @test norm(tdvp_evolve(H, ψ0, dt; normalize = false, nsite = 1) - ex1) < 1e-10 - @test norm(evolve_with_tdvp(H, ψ0, 3, dt; normalize_each_step = false)[end] - ex3) < 1e-10 - st = evolve_with_tdvp_timedep(_ -> H.mpo, ψ0, 3, dt; normalize_each_step = false) + @test norm(tdvp_evolve(H, ψ0, dt; normalize = false, cutoff = 0.0) - ex1) < 1e-10 + @test norm(tdvp_evolve(H, ψ0, dt; normalize = false, nsite = 1, cutoff = 0.0) - ex1) < 1e-10 + @test norm(evolve_with_tdvp(H, ψ0, 3, dt; normalize_each_step = false, cutoff = 0.0)[end] - ex3) < 1e-10 + st = evolve_with_tdvp_timedep(_ -> H.mpo, ψ0, 3, dt; normalize_each_step = false, cutoff = 0.0) @test norm(st[end] - ex3) < 1e-8 @test_logs min_level = Logging.Warn tdvp_evolve(H, ψ0, dt) From e5d2b2f779a7e216ded95b9d214f767cb266c075 Mon Sep 17 00:00:00 2001 From: Anouar Moustaj Date: Fri, 13 Nov 2026 13:08:34 +0200 Subject: [PATCH 18/22] Scale build_K's size term with |H|^2/|H - omega|^2 The norm of K = (H - omega)^2 + eta^2 grows with omega while the terms that live on a few sites (the end bond of an open chain) do not, so the 0.1/D^2 of 722145c still lost the end bond near the band edge: on a 14-qubit chain at omega = 1.7t and 2t, <0|K|0> was off by 1 (found by the review of the branch; the loss threshold fits 0.5/(1 + omega^2/2)^2/D^2 there). The size term is now 0.1 r^2/D^2 with r = min(1, |H|^2/|H - omega|^2), computed exactly from |H|^2, tr H and D (two MPO inner products). As r <= 1 the default never exceeds the previous one, and it is unchanged near the band centre: the golden DMRG cases (L = 3) pass unchanged. A clean chain now keeps K within 5e-7 for |omega| <= 5t at L = 14, 20 and 26. Not covered, and now documented: terms weak next to the rest of H. With an on-site potential V cos(.) part of K is lost from V ~ 2t (0.17 at V = 2t on 14 qubits), as with 1e-8; cutoff_K = 1e-2/D^2 (V <~ 3t) or 1e-3/D^2 (V <~ 5t) is needed there. The size warning compares with 0.3 r^2/D^2. Test: the end bond at omega = 2 on 14 qubits with the default; _default_cutoff_K with r. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 37 +++++++++++++--------- src/solvers/DMRG.jl | 70 ++++++++++++++++++++++++++---------------- test/bugfix_build_K.jl | 9 ++++++ 3 files changed, 74 insertions(+), 42 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7659974..9c8e7ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -89,21 +89,28 @@ bugs without breaking the API. `(c↑, c↓, c†↓, −c†↑)`, in which its `iσ_y` pairing would vanish; it now names the basis the code uses. `H` must be Hermitian, as before: for a non-Hermitian `H` the hole block would be `−Hᵀ`, which neither build gives (now documented). -- **`build_K` and `dmrg_spectral`: `cutoff_K` defaults to `min(1e-8, 1e-4·η⁴, 0.1/D²)`**, - D the dimension of the site space (2^L for qubits). The cutoff is relative to the - squared norm of each sum and product, so the fixed default `1e-8` dropped the two - smallest parts of `K = (H − ω)² + η²`. At small η it truncated most of `η² I`: on a - 5-qubit chain at η = 1e-2, ‖ΔK‖ = 9.7e-5 ≈ η² (now below 1e-7); the `1e-4·η⁴` bound - assumes eigenvalues of `H − ω` of order one, so pass a smaller `cutoff_K` for a wider - spectrum. In large systems it dropped the terms that live on a few sites, such as the - end bond of an open chain: the norm of K grows with D, and the product drops such a - term once `cutoff_K` exceeds about `0.5/D²`, so on a uniform chain `⟨0|K|0⟩` was 2.01 - instead of 1.01 (K wrong by t² at both ends) from L = 13 on; with the new default K - stays within 2e-7 up to L = 30, the largest size tested, given an exact MPO of H. The - default stays `1e-8` for η ≥ 0.1 (and η = 0) up to L = 11, so those results are - unchanged bit for bit (no golden case moves); below η = 0.1, or from L = 12 on, K and - the DMRG results built on it move. An explicit `cutoff_K` is used as given and warns - once when it is not below `η⁴` or when it is above `0.3/D²`. +- **`build_K` and `dmrg_spectral`: `cutoff_K` defaults to `min(1e-8, 1e-4·η⁴, 0.1·r²/D²)`**, + D the dimension of the site space (2^L for qubits) and `r = min(1, ‖H‖²/‖H − ω‖²)`. + The cutoff is relative to the squared norm of each sum and product, so the fixed + default `1e-8` dropped the two smallest parts of `K = (H − ω)² + η²`. + - **The `η² I` term at small η.** On a 5-qubit chain at η = 1e-2, ‖ΔK‖ = 9.7e-5 ≈ η² + (now below 1e-7). The `1e-4·η⁴` bound assumes eigenvalues of `H − ω` of order one, + so pass a smaller `cutoff_K` for a wider spectrum. + - **Terms that live on a few sites in large systems**, such as the end bond of an open + chain. The norm of K grows with D and with ω, and the product drops such a term once + `cutoff_K` exceeds about `0.5·r²/D²`. On a uniform chain `⟨0|K|0⟩` was 2.01 instead + of 1.01 (K wrong by t² at both ends) from L = 13 on at ω = 0.05, and from L = 12 at + ω = 1.7t. With the new default, and an exact MPO of H, K stays within 5e-7 for + |ω| ≤ 5t at L = 14–26 (2e-7 at ω = 0.05 up to L = 30). + - **Not protected: terms that are weak next to the rest of H.** With an on-site + potential of a few t, part of K is lost again (0.17 at V = 2t on a 14-qubit chain, as + with `1e-8`). There `cutoff_K = 1e-2/D²` (V ≲ 3t) or `1e-3/D²` (V ≲ 5t) is needed. + + The default stays `1e-8` while `D ≤ 3162·r` (L ≤ 11 near the band centre, η ≥ 0.1 or + η = 0), so those results are unchanged bit for bit and no golden case moves. Below + η = 0.1, or for larger systems, K and the DMRG results built on it move. An explicit + `cutoff_K` is used as given; it warns once when it is not below `η⁴` or when it is + above `0.3·r²/D²`. - **Size-aware truncation cutoff of the Hamiltonian builders.** Their cutoff (`1e-8` up to v0.2.0) is relative to the squared norm of the MPO, which grows with the dimension D of the site space, so in large systems it dropped terms carried by a single matrix diff --git a/src/solvers/DMRG.jl b/src/solvers/DMRG.jl index dd40724..b984236 100644 --- a/src/solvers/DMRG.jl +++ b/src/solvers/DMRG.jl @@ -62,7 +62,7 @@ end # ============================================================ """ - build_K(H_mpo::MPO, sites, ω, η; maxdim_K=200, cutoff_K=min(1e-8, 1e-4η⁴, 0.1/D²)) -> MPO + build_K(H_mpo::MPO, sites, ω, η; maxdim_K=200, cutoff_K=min(1e-8, 1e-4η⁴, 0.1r²/D²)) -> MPO Build the resolvent-squared MPO @@ -82,46 +82,62 @@ the two smallest parts of K: (a 5-qubit chain at η = 1e-2 kept almost none of it with `1e-8`: ‖ΔK‖ = 9.7e-5 ≈ η²). It assumes eigenvalues of H − ω of order one: for a wider spectrum pass a smaller `cutoff_K`. -- `0.1/D²`, D the dimension of the site space (2^L for qubits), keeps the terms that live - on a few sites, such as the missing bond at the end of an open chain. The norm of K - grows with D, and the product `apply(H − ω, H − ω)` drops such a term once `cutoff_K` - exceeds about `0.5/D²` (measured on a uniform chain, L = 12–16): with `1e-8`, - `⟨0|K|0⟩` came out as 2.01 instead of 1.01 from L = 13 on, K wrong by t² at both ends. - -The default is therefore `1e-8`, as in v0.2.0, for η ≥ 0.1 (and η = 0) up to L = 11. On -an open chain (ω = 0.05) it keeps K to within 2e-7 up to L = 30, the largest size tested, -provided `H_mpo` itself is exact: an MPO truncated with a relative cutoff of its own can -already lack such terms. An explicit `cutoff_K` is used as given; it warns once when it -is not below η⁴ or when it is above `0.3/D²`. +- `0.1 r²/D²`, D the dimension of the site space (2^L for qubits) and + `r = min(1, ‖H‖²/‖H − ω‖²)` (Frobenius norms), keeps the terms that live on a few + sites, such as the missing bond at the end of an open chain. The norm of K grows with D + and, through `‖H − ω‖`, with ω, and the product `apply(H − ω, H − ω)` drops such a term + once `cutoff_K` exceeds about `0.5 r²/D²` (uniform chain): with `1e-8`, `⟨0|K|0⟩` came + out as 2.01 instead of 1.01 from L = 13 on at ω = 0.05, and from L = 12 at ω = 1.7t, + K wrong by t² at both ends. + +The default is therefore `1e-8`, as in v0.2.0, as long as `D ≤ 3162 r` (L ≤ 11 near the +band centre, η ≥ 0.1 or η = 0). On an open chain it keeps K within 5e-7 for |ω| ≤ 5t at +L = 14–26 and within 2e-7 at ω = 0.05 up to L = 30, provided `H_mpo` itself is exact: an +MPO truncated with a relative cutoff of its own can already lack such terms. Terms that +are weak next to the rest of H are not protected: with an on-site potential of a few t +part of K is lost again (a 14-qubit chain with `V cos(2πbn)`: 0.17 at V = 2t), and +`cutoff_K = 1e-2/D²` (V ≲ 3t) or `1e-3/D²` (V ≲ 5t) is needed there. An explicit +`cutoff_K` is used as given; it warns once when it is not below η⁴ or when it is above +`0.3 r²/D²`. """ function build_K(H_mpo::MPO, sites, ω::Real, η::Real; maxdim_K::Int = 200, cutoff_K::Union{Nothing,Real} = nothing) D = prod(Float64 ∘ dim, sites) - cutoff_K = something(cutoff_K, _default_cutoff_K(η, D)) + I_mpo = MPO(sites, "Id") + r = _K_norm_ratio(H_mpo, I_mpo, ω, D) + cutoff_K = something(cutoff_K, _default_cutoff_K(η, D, r)) η != 0 && cutoff_K >= η^4 && @warn "build_K: cutoff_K = $cutoff_K is not below η⁴ = $(η^4); the truncation of " * "K = (H − ω)² + η² can drop its η² term (the default is " * - "min(1e-8, 1e-4η⁴, 0.1/D²))." maxlog=1 - cutoff_K > 0.3 / D^2 && + "min(1e-8, 1e-4η⁴, 0.1r²/D²))." maxlog=1 + cutoff_K > 0.3 * r^2 / D^2 && @warn "build_K: cutoff_K = $cutoff_K on $(length(sites)) sites can drop the terms of K " * "that live on a few sites, such as the end bond of an open chain (K wrong by t² " * - "there); keep it below 0.3/D² = $(0.3 / D^2), D the dimension of the site " * - "space (the default is at most 0.1/D²)." maxlog=1 - I_mpo = MPO(sites, "Id") + "there); keep it below 0.3r²/D² = $(0.3 * r^2 / D^2), D the dimension of the " * + "site space and r = min(1, ‖H‖²/‖H − ω‖²) (the default is at most 0.1r²/D²)." maxlog=1 H_shift = +(H_mpo, (-ω) * I_mpo; cutoff = cutoff_K) H_sq = apply(H_shift, H_shift; cutoff = cutoff_K, maxdim = maxdim_K) return +(H_sq, (η^2) * I_mpo; cutoff = cutoff_K) end # The default cutoff_K of build_K and dmrg_spectral: the fixed 1e-8 of v0.2.0, lowered to -# 1e-4 η⁴ to keep the η² I term of K (η < 0.1; η = 0 has none) and to 0.1/D² to keep the -# terms that live on a few sites (D the dimension of the site space: from L = 12 qubits). -function _default_cutoff_K(η::Real, D::Real) - c = min(1e-8, 0.1 / Float64(D)^2) +# 1e-4 η⁴ to keep the η² I term of K (η < 0.1; η = 0 has none) and to 0.1 r²/D² to keep +# the terms that live on a few sites (D the dimension of the site space: from L = 12 +# qubits; r = min(1, ‖H‖²/‖H − ω‖²), since ‖K‖ grows with ω while those terms do not). +function _default_cutoff_K(η::Real, D::Real, r::Real = 1.0) + c = min(1e-8, 0.1 * Float64(r)^2 / Float64(D)^2) return iszero(η) ? c : min(c, 1e-4 * Float64(η)^4) end +# r = min(1, ‖H‖²/‖H − ω‖²) for the default cutoff_K, with ‖H − ω‖² = ‖H‖² − 2ω tr H + ω² D +# (Frobenius norms; exact, from two MPO inner products). +function _K_norm_ratio(H_mpo::MPO, I_mpo::MPO, ω::Real, D::Real) + nH2 = real(inner(H_mpo, H_mpo)) + nS2 = nH2 - 2ω * real(inner(I_mpo, H_mpo)) + ω^2 * D + return nS2 > 0 ? min(1.0, nH2 / nS2) : 1.0 +end + # ============================================================ # 3. Spectral DMRG (minimise K) @@ -129,7 +145,7 @@ end """ dmrg_spectral(H_mpo::MPO, sites, ω, η; ψ0=nothing, maxdim_K=200, - cutoff_K=min(1e-8, 1e-4η⁴, 0.1/D²), linkdim_init=10, nsweeps=10, + cutoff_K=min(1e-8, 1e-4η⁴, 0.1r²/D²), linkdim_init=10, nsweeps=10, maxdim=[10, 20, 50, 100, 200], cutoff=1e-8, noise=[1e-6, 1e-7, 1e-8, 0.0], kwargs...) -> (E_K, ψ) @@ -141,10 +157,10 @@ Use `local_weight(ψ, i, L, sites)` to read off the LDoS proxy `|⟨i|ψ(ω)⟩| # Keyword arguments - `ψ0` : warm-start MPS (random if `nothing`, the default) - `maxdim_K`, `cutoff_K` : truncation for building K (see `build_K`). Defaults - `200` and `min(1e-8, 1e-4η⁴, 0.1/D²)`, D the dimension of - the site space (`1e-8` up to v0.2.0, which drops most of the - η² term at η = 1e-2 and the end bonds of an open chain from - L = 13). + `200` and `min(1e-8, 1e-4η⁴, 0.1r²/D²)`, D the dimension of + the site space and `r = min(1, ‖H‖²/‖H − ω‖²)` (`1e-8` up to + v0.2.0, which drops most of the η² term at η = 1e-2 and the + end bonds of an open chain from L = 13). - `linkdim_init` : bond dimension of the random initial MPS (if ψ0=nothing). Default `10`. - `nsweeps`, `maxdim`, `cutoff`, `noise` : DMRG sweep parameters, with the same diff --git a/test/bugfix_build_K.jl b/test/bugfix_build_K.jl index 9f803bb..f98633d 100644 --- a/test/bugfix_build_K.jl +++ b/test/bugfix_build_K.jl @@ -44,4 +44,13 @@ using TensorBinding: get_Hamiltonian, add_onsite!, build_K, get_matrix Kold = @test_logs (:warn, r"live on a few sites") build_K(H16.mpo, H16.sites, ω, 0.1; cutoff_K = 1e-8) @test abs(K00(Kold) - (ω^2 + 1 + 0.1^2)) > 0.9 # the end bond is lost + + # ‖K‖ grows with ω while the end bond does not: the default scales with + # r = min(1, ‖H‖²/‖H − ω‖²) (r ≈ 1/3 here). At ω = 2 a plain 0.1/D² lost the end bond + # from L = 12 (<0|K|0> off by 1). + @test dc(0.1, 2.0^14, 1/3) ≈ 0.1 / 9 / 4.0^14 + H14 = get_Hamiltonian("chain_1d", 1.0; L=14) + ψ14 = TensorBinding.binary_to_MPS(0, 14, H14.sites) + K14 = build_K(H14.mpo, H14.sites, 2.0, 0.1) + @test abs(real(inner(ψ14', K14, ψ14)) - (1 + 2.0^2 + 0.1^2)) < 1e-6 end From 3183ee21a81031fd4d4752d014a0dbc8247ee11e Mon Sep 17 00:00:00 2001 From: Anouar Moustaj Date: Fri, 13 Nov 2026 13:08:50 +0200 Subject: [PATCH 19/22] Size-aware cutoff: 2D dimension, non-Hermitian adders, kinetic sums, weak T-junctions Follow-up to 37fa32e after the review of the branch. - 2D: a long carry repeats along a whole row or column, so the term adders (through _cutoff_dim), the 2D presets and the multi-atom lattices take D along the longer side. 2D results keep 1e-8 at every usual size, and an explicit 1e-8 no longer warns there: get_valley_operator on a 12x12 honeycomb (D = 3.4e7) warned about "the bond across the middle of a 1D chain". The multi-atom and 2D preset builders take D from Lx and Ly, not from the keyword L (a mismatched L gave another size's cutoff). - The non-Hermitian adders (add_nh_onsite!, add_loss!, nh_nonreciprocal_hopping_mpo, add_nh_nonreciprocal_hopping!, add_nh_skin_hopping!) and the hermitization (hermitized_hamiltonian, hermitize) still summed at a fixed 1e-8 and cut an L = 26 chain again (middle bond 3e-31 after add_nh_onsite!); they now take the same default. - kinetic_1d_nn, kineticNNN and shift_hopping_mpo summed at a fixed 1e-12, which cut the middle bond at L = 39 (one direction: a non-Hermitian chain) and 40. They now use min(1e-12, 0.1/D), unchanged up to L = 36. This was the "loss at L = 40 whatever tol" that 37fa32e documented as not investigated. - add_tjunction!: the junction is a single-site term of weight ~(t_j/t)^2/2^L, and a relative cutoff above it left three decoupled chains (t_j = 0.02t at L = 16 with 1e-8, t_j <= 0.18t at L >= 22 with 0.1/D). Its default now stays a tenth below that weight. - One warning per call: add_zeeman! and add_soc! attach the spin through _attach_spin! with their own resolved cutoff, and get_Hamiltonian("ssh_sublattice") builds through _ssh_sublattice_hamiltonian, instead of resolving and warning twice. - The hermitization's default also scales with r = min(1, |H|^2/|zI - H|^2), as the block grows with |z|: with 0.1/D an L = 26 chain kept its middle bond as 0.92/0.08 at z = 3 and 1/1.7e-7 at z = 4 (now exact). The non-Hermitian KPM entry points pass their own cutoff to it, which is documented. - pairingNNN summed at a fixed 1e-12 like kineticNNN; it gets the same min(1e-12, 0.1/D). - add_tjunction!: the cap applies only when the junction has weight. With t_j = 0 a zero cap kept every noise vector (bond dimension 200 at L = 10). - Docs: the default keeps a bond with |t|^2 >= /10, = |H|^2/D. It does not keep a bond that is weak next to the rest of its rows (on-site terms beyond ~4t, a 3x stronger bond), and neither did 1e-8: "aah" with V = 6 at L = 26 and "ssh_sublattice" with d = 0.8 at L = 25 lose it. get_Hamiltonian's "Large systems" section, the MPOTools comment and the CHANGELOG say so. The source map and the file headers list the new calls into MPOTools and AuxDOF. Test: test/bugfix_large_L_cutoffs.jl adds the non-Hermitian adder at L = 26, a single warning from add_zeeman!, no warning for an explicit 1e-8 in 2D at L = 26, the chain at L = 40, a weak and a zero T-junction, the hermitized chain at z = 4 and pairingNNN at L = 40; the check on the explicit-1e-8 chain reads both directions of the middle bond, since which one survives is up to the SVD's rounding. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 77 ++++++++++++++++++---------- src/TensorBinding.jl | 18 ++++--- src/core/AuxDOF.jl | 28 +++++++---- src/core/Hamiltonian.jl | 9 ++-- src/core/MPOTools.jl | 14 ++++-- src/core/ModelRegistry.jl | 14 +++--- src/core/TBSystem.jl | 58 +++++++++++++++------- src/core/Utils.jl | 2 +- src/lattice/NNNeighbor.jl | 4 +- src/lattice/TJunction.jl | 24 +++++++-- src/lattice/sublattice.jl | 9 +++- src/physics/Supercond.jl | 3 +- src/physics/TwoParticle.jl | 2 +- src/physics/nh/model.jl | 91 ++++++++++++++++++++++------------ test/bugfix_large_L_cutoffs.jl | 46 ++++++++++++++++- 15 files changed, 282 insertions(+), 117 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c8e7ff..ed453ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -112,31 +112,58 @@ bugs without breaking the API. `cutoff_K` is used as given; it warns once when it is not below `η⁴` or when it is above `0.3·r²/D²`. - **Size-aware truncation cutoff of the Hamiltonian builders.** Their cutoff (`1e-8` up - to v0.2.0) is relative to the squared norm of the MPO, which grows with the dimension D - of the site space, so in large systems it dropped terms carried by a single matrix - element. The bond across the middle of a 1D chain, `2^(L-1) - 1 → 2^(L-1)`, whose carry - flips every qubit, is such a term: `"chain_1d"`, `"uniform"`, `"aah"` and - `"ssh_sublattice"` lost it at L = 26 (`"ssh"` at L = 28), from L = 28 the chain was cut - every `2^26` sites, and `"custom"` with nearest-neighbour hops threw (its self-check - caught the missing bond). `add_onsite!` and the other term adders cut a correct chain - again. The default is now `min(1e-8, 0.1/D)`: in `get_Hamiltonian` and - `estimate_scale` (`tol`), `add_hopping!`, `add_hopping_2D!`, `add_onsite!`, - `add_spin!` (`cutoff`), `add_zeeman!`, `add_soc!`, `add_superconductivity!`, - `exciton_hamiltonian` and `Exciton_Hamiltonian` (`tol`), `spin_hamiltonian`, - `bdg_hamiltonian`, `bdg_spin_hamiltonian`, `ssh_sublattice_hamiltonian`, - `add_tjunction!` and `tjunction_hamiltonian` (`cutoff`), and in the fixed truncations - inside `hopping2MPO`, `qtci_matrix_to_MPO` and the `"uniform"` and `"aah"` presets. It - equals `1e-8` up to D = 2^23 (L = 23 for a spinless chain, 22 spinful, 21 for spinful - BdG or three atoms per cell), so smaller systems build the same MPOs bit for bit (no - golden case moves); larger ones move at the truncation level, and the 1D ones are - right again (checked up to L = 30). A given value is used as given and warns once when - it is above `0.3/D`; a given `tol` is still also the QTCI tolerance where it was - (`"custom"`, `"haldane"`, two-argument terms), whose default stays `1e-8`. Not changed: - the 2D-only builders, where a long carry repeats along a whole row or column and `1e-8` - keeps it until `Lx` or `Ly` reaches about 24 (estimated; checked at `Lx = Ly = 13`); - the projected quasicrystal spaces (still `1e-8`, not checked at large L); the solvers. - At L = 40 the chain MPO of `kinetic_1d_nn` itself loses the bond across the middle, - whatever the cutoff. + to v0.2.0) is relative to the squared norm of the MPO, `‖H‖² = D⟨h²⟩`, with D the + dimension of the site space and `⟨h²⟩` the mean squared norm of a row. In large systems + it therefore dropped terms carried by a single matrix element, such as the bond across + the middle of a 1D chain, `2^(L-1) - 1 → 2^(L-1)`, whose carry flips every qubit: + - `"chain_1d"`, `"uniform"`, `"aah"` and `"ssh_sublattice"` lost it at L = 26 + (`"ssh"` at L = 28), and from L = 28 the chain was cut every `2^26` sites; + - `"custom"` with nearest-neighbour hops threw, its self-check catching the missing bond; + - `add_onsite!` and the other term adders, the non-Hermitian ones included, cut a + correct chain again; + - the chain MPO of `kinetic_1d_nn` lost the bond at L = 39–40 through its own `1e-12`. + + The default is now `min(1e-8, 0.1/D)` in: + - `get_Hamiltonian` and `estimate_scale` (`tol`); + - `add_hopping!`, `add_hopping_2D!`, `add_onsite!`, `add_spin!` (`cutoff`), + `add_zeeman!`, `add_soc!` and `add_superconductivity!`; + - `add_nh_onsite!`, `add_loss!`, `nh_nonreciprocal_hopping_mpo`, + `add_nh_nonreciprocal_hopping!` and `add_nh_skin_hopping!`; + - `exciton_hamiltonian` and `Exciton_Hamiltonian` (`tol`); + - `hermitized_hamiltonian` and `hermitize`, scaled by `r = min(1, ‖H‖²/‖zI − H‖²)` as + the block grows with `|z|` (the non-Hermitian KPM entry points pass their own + `cutoff` there; at large L pass a smaller one); + - `spin_hamiltonian`, `bdg_hamiltonian`, + `bdg_spin_hamiltonian`, `ssh_sublattice_hamiltonian`, `add_tjunction!` and + `tjunction_hamiltonian` (`cutoff`); + - the fixed truncations inside `hopping2MPO`, `qtci_matrix_to_MPO` and the `"uniform"` + and `"aah"` presets. + + The `1e-12` of the 1D kinetic and p-wave sums (`kinetic_1d_nn`, `kineticNNN`, + `shift_hopping_mpo`, `pairingNNN`) became `min(1e-12, 0.1/D)`. In 2D a long carry repeats along a + whole row or column, so D is taken along the longer side and 2D results keep `1e-8`, + with no warning at the usual sizes. The default equals `1e-8` up to D = 2^23 (L = 23 + for a spinless chain, 22 spinful, 21 for spinful BdG or three atoms per cell), so + smaller systems build the same MPOs bit for bit (apart from very weak T-junctions, see + below) and no golden case moves. Larger 1D + ones move at the truncation level and keep every bond with `|t|² ≥ ⟨h²⟩/10`, such as + the hops of a uniform chain (checked up to L = 30, the chain MPO at L = 40). + + A bond that is weak next to the rest of its rows is still not kept, as it was not with + `1e-8`. That happens beside on-site terms beyond about 4t (`"aah"` with V ≳ 4t, a large + potential added by `add_onsite!`) or beside a much stronger bond (`"ssh_sublattice"` + with `|t − d| < |t + d|/3`); pass a smaller `tol` there. `add_tjunction!` keeps its + default below a tenth of the junction's weight, so a weak junction is no longer + removed: `t_j = 0.02t` at L = 16 was lost at `1e-8`. For `t_j² < 1e-7·2^L·t²` that + lowers the default below `1e-8` at any size. + + A value you pass is used as given; it warns once when it is above `0.3/D`. A given + `tol` is still also the QTCI tolerance where it was (`"custom"`, `"haldane"`, + two-argument terms), and that default stays `1e-8`. Not changed: + - the 2D-only builders called directly (bilayer, twisted, flake, the 2D T-junction, the + multi-atom builders); + - the projected quasicrystal spaces (still `1e-8`, not checked at large L); + - the solvers. ### Fixed diff --git a/src/TensorBinding.jl b/src/TensorBinding.jl index 0c3da12..a70689f 100644 --- a/src/TensorBinding.jl +++ b/src/TensorBinding.jl @@ -90,17 +90,19 @@ export chern_marker_gpu, get_bands_gpu, get_dos_stochastic_gpu, # # core/Utils.jl qubit ops, basis MPS, eval_mps, diagonal/shift MPOs, sampling plans, # dense MPO matrices, deprecation helpers (_depwarn_once, _renamed_kw) -# → Fibonacci* +# → Fibonacci*, MPOTools* # core/MPOTools.jl mpo_kron, interleave_mpo & co., compose_power, _site_projector_mpo, -# sum_mpos, _checked_sum_mpos +# sum_mpos, _checked_sum_mpos, the size-aware default cutoff of the builders +# (_default_mpo_cutoff, _mpo_cutoff) # → Utils # core/Hamiltonian.jl 1D kinetic MPOs, the QTCI hopping builder hopping2MPO -# → Utils +# → Utils, MPOTools # core/TBSystem.jl TBHamiltonian, position spaces, get_Hamiltonian, add_hopping!/add_onsite! -# → Utils, Hamiltonian, geometry*, ModelRegistry*, NNNeighbor* +# → Utils, MPOTools, Hamiltonian, AuxDOF*, geometry*, ModelRegistry*, +# NNNeighbor* # core/AuxDOF.jl spin/Nambu indices, add_spin! & co., project_aux, sector projectors, # the aux projection AuxProjection/_project_aux_sectors, probe_state -# → Utils, Hamiltonian, TBSystem, hopping2d*, Supercond* +# → Utils, MPOTools, Hamiltonian, TBSystem, hopping2d*, Supercond* # lattice/geometry.jl i → position closures, *_positions tables, _resolve_2d_geometry # → TBSystem # position_spaces/Fibonacci.jl Zeckendorf space, Fib* ops, constructors, conumbering @@ -118,12 +120,12 @@ export chern_marker_gpu, get_bands_gpu, get_dos_stochastic_gpu, # → Utils, MPOTools, Hamiltonian, hopping2d # core/ModelRegistry.jl model registry MODELS (MODEL_REGISTRY), build_hamiltonian, the # per-kind builders, the KPM scale maker estimate_scale -# → Utils, TBSystem, geometry, Fibonacci, MetallicMean, KBonacci, +# → Utils, MPOTools, TBSystem, geometry, Fibonacci, MetallicMean, KBonacci, # presets, sublattice*, DMRG* # lattice/sublattice.jl kagome/Lieb/honeycomb/dice/SSH sublattice builders # → Utils, MPOTools, TBSystem, masks2d # lattice/NNNeighbor.jl nth-neighbour hopping add_hopping_2D!, get_shell_disps -# → Utils, TBSystem, geometry, masks2d, hopping2d +# → Utils, MPOTools, TBSystem, geometry, masks2d, hopping2d # lattice/Flake.jl signed-distance functions, QTCI flake masks # → Utils, TBSystem # lattice/Twisted.jl twisted multilayer builders @@ -184,7 +186,7 @@ export chern_marker_gpu, get_bands_gpu, get_dos_stochastic_gpu, # physics/Topology.jl Chern/winding markers, valley operators, Thouless pump # → Utils, TBSystem, NNNeighbor, kpm/recursion, Purification # physics/nh/model.jl NonHermitianHamiltonian, hermitize, add_loss!/add_nh_* -# → Utils, TBSystem +# → Utils, MPOTools, TBSystem # physics/nh/kpm.jl NH KPM, spectral function, nh_spectrum_grid # → Utils, TBSystem, AuxDOF, DMRG, kpm/kernels, kpm/recursion, # nh/model diff --git a/src/core/AuxDOF.jl b/src/core/AuxDOF.jl index 7f5e1aa..7d0bb24 100644 --- a/src/core/AuxDOF.jl +++ b/src/core/AuxDOF.jl @@ -43,7 +43,7 @@ # methods' eight aux keywords, in one value) # 10. _ldos_make_psi0 (← solvers/kpm/ldos.jl), probe_state # -# Depends on: Utils, Hamiltonian, TBSystem, hopping2d*, Supercond* (a * marks a +# Depends on: Utils, MPOTools (_mpo_cutoff), Hamiltonian, TBSystem, hopping2d*, Supercond* (a * marks a # file included later; see the source map in TensorBinding.jl). Included right # after core/TBSystem.jl, this file needs only the ITensors types and # TBHamiltonian at definition time. Its callees are resolved at run time: the @@ -305,6 +305,16 @@ Invalidates all caches. function add_spin!(H::TBHamiltonian; cutoff::Union{Nothing,Real}=nothing, maxdim::Int=200, position::Symbol=:pre) _require_binary_position_space(H, "add_spin!") + H.spin_s === nothing || return H + # the dimension once the spin index is added + cut = _mpo_cutoff(cutoff, 2 * _cutoff_dim(H), "add_spin!"; keyword="cutoff") + return _attach_spin!(H, cut; maxdim=maxdim, position=position) +end + +# add_spin! with a resolved cutoff `cut`: add_zeeman! and add_soc! resolve their own `tol` +# (and warn about it once, under their own name) and pass it here. No-op when H is +# already spinful. +function _attach_spin!(H::TBHamiltonian, cut::Real; maxdim::Int, position::Symbol) H.spin_s === nothing || return H spin_s = spin_index() if position === :pre @@ -314,9 +324,7 @@ function add_spin!(H::TBHamiltonian; cutoff::Union{Nothing,Real}=nothing, maxdim H.mpo = postpend_spin(H.mpo, spin_s, :Id) H.sites = [H.sites; spin_s] end - ITensorMPS.truncate!(H.mpo; maxdim=maxdim, - cutoff=_mpo_cutoff(cutoff, _site_space_dim(H.sites), "add_spin!"; - keyword="cutoff")) + ITensorMPS.truncate!(H.mpo; maxdim=maxdim, cutoff=cut) H.spin_s = spin_s H.aux_side = position _invalidate_cache!(H) @@ -367,8 +375,9 @@ function add_zeeman!(H::TBHamiltonian, h; direction in (:x, :y, :z) || error("direction must be :x, :y, or :z; got :$direction") pos = something(position, H.aux_side) - add_spin!(H; cutoff=tol, maxdim=maxdim, position=pos) - cut = _mpo_cutoff(tol, _site_space_dim(H.sites), "add_zeeman!") + # one resolution, and at most one warning, for the spin step and the Zeeman term + cut = _mpo_cutoff(tol, (H.spin_s === nothing ? 2 : 1) * _cutoff_dim(H), "add_zeeman!") + _attach_spin!(H, cut; maxdim=maxdim, position=pos) spin_op = direction == :z ? :Sz : direction == :x ? :Sx : :Sy pos_s = _pos_sites(H) @@ -460,7 +469,7 @@ function add_superconductivity!(H::TBHamiltonian, Δ; pos = something(position, H.aux_side) pos_s = _pos_sites(H) - cut = _mpo_cutoff(tol, 2 * _site_space_dim(H.sites), "add_superconductivity!") + cut = _mpo_cutoff(tol, 2 * _cutoff_dim(H), "add_superconductivity!") # ── Spinless + :swave redirect ─────────────────────────────────────────── if H.spin_s === nothing && type === :swave @@ -602,9 +611,10 @@ function add_soc!(H::TBHamiltonian, λ; _require_binary_position_space(H, "add_soc!") periodic = _tb_periodic_boundary(boundary) # errors on an unsupported boundary pos = something(position, H.aux_side) - add_spin!(H; cutoff=tol, maxdim=maxdim, position=pos) + # one resolution, and at most one warning, for the spin step and the SOC term + cut = _mpo_cutoff(tol, (H.spin_s === nothing ? 2 : 1) * _cutoff_dim(H), "add_soc!") + _attach_spin!(H, cut; maxdim=maxdim, position=pos) pos_s = _pos_sites(H) - cut = _mpo_cutoff(tol, _site_space_dim(H.sites), "add_soc!") # The SOC term on the spin (op), the particle-hole structure on a Nambu site (τ_z for # a real term), the identity on any other aux site, each on the side H.sites puts it. diff --git a/src/core/Hamiltonian.jl b/src/core/Hamiltonian.jl index a44f0e2..218e69e 100644 --- a/src/core/Hamiltonian.jl +++ b/src/core/Hamiltonian.jl @@ -9,7 +9,8 @@ # # Main entry points: hopping2MPO, kinetic_1d_nn, kineticNNN. # -# Depends on: Utils (shift_pair_mpos, shift_hopping_mpo, custom_mpo, fused_mpo). +# Depends on: Utils (shift_pair_mpos, shift_hopping_mpo, custom_mpo, fused_mpo), MPOTools +# (_default_mpo_cutoff). # The 2D kinetic builders are in lattice/hopping2d.jl. # ============================================================ @@ -35,7 +36,9 @@ function kinetic_1d_nn(L, sites; boundary::Symbol=:open, bc=nothing) @assert L == length(sites) "L must equal length(sites)" bc === nothing || (boundary = Symbol(bc)) K, Kdag = shift_pair_mpos(sites, 1; cyclic=_tb_periodic_boundary(boundary)) - return +(K, Kdag; cutoff=1e-12) + # 1e-12 up to L = 36, 0.1/2^L above: the fixed 1e-12 dropped the bond across the + # middle of the chain at L = 39 (one direction) and 40 (see _default_mpo_cutoff) + return +(K, Kdag; cutoff=min(1e-12, _default_mpo_cutoff(2.0^L))) end @@ -273,6 +276,6 @@ function kineticNNN(L, sites, hopping::MPO, nn::Integer; bc === nothing || (boundary = Symbol(bc)) return shift_hopping_mpo(hopping, sites, nn; cyclic=_tb_periodic_boundary(boundary), - cutoff=1e-12, + cutoff=min(1e-12, _default_mpo_cutoff(2.0^L)), # as kinetic_1d_nn apply_kwargs=apply_kwargs) end diff --git a/src/core/MPOTools.jl b/src/core/MPOTools.jl index 4a672d8..e16d992 100644 --- a/src/core/MPOTools.jl +++ b/src/core/MPOTools.jl @@ -327,9 +327,12 @@ end # fixed cutoff 1e-8 of v0.2.0 lost it from L = 26 on (a single site-space dimension of # 2^26), and from L = 28 every bond whose carry flips 27 qubits or more, which cut the # chain every 2^26 sites. The builders and term adders therefore default to -# `_default_mpo_cutoff(D)`: 1e-8, as before, up to D = 2^23, and 0.1/D above, which -# keeps every term with k ≥ 1 for z ≤ 10. In 2D a long carry repeats along a whole row or -# column, so 1e-8 already kept it; the default changes nothing there below D = 2^23. +# `_default_mpo_cutoff(D)`: 1e-8, as before, up to D = 2^23, and 0.1/D above, which keeps +# a single element a while |a|² ≥ ‖H‖²/(10D), i.e. every hop of a uniform chain, but not a +# bond that is weak next to the rest of its rows (on-site terms beyond ~4t, a 3x stronger +# bond): that needs a cutoff that knows |a|, which a relative default cannot. In 2D a long +# carry repeats along a whole row or column, so 2D callers pass D along the longer side +# (_cutoff_dim in core/TBSystem.jl), which keeps 1e-8 there at every usual size. _default_mpo_cutoff(D::Real) = min(1e-8, 0.1 / Float64(D)) @@ -344,7 +347,8 @@ function _mpo_cutoff(value, D::Real, fname::AbstractString; keyword::AbstractStr value === nothing && return _default_mpo_cutoff(D) value > 0.3 / D && @warn "$fname: $keyword = $value can drop a term carried by a single matrix element " * - "on this site space of dimension $(Float64(D)), such as the bond across the " * - "middle of a 1D chain; the default is min(1e-8, 0.1/D)." maxlog=1 _id=Symbol(fname, :_, keyword, :_size) + "at this size (D = $(Float64(D)), the site-space dimension, along the longer " * + "side in 2D), such as the bond across the middle of a 1D chain; the default is " * + "min(1e-8, 0.1/D)." maxlog=1 _id=Symbol(fname, :_, keyword, :_size) return value end diff --git a/src/core/ModelRegistry.jl b/src/core/ModelRegistry.jl index df6b810..5cde7c2 100644 --- a/src/core/ModelRegistry.jl +++ b/src/core/ModelRegistry.jl @@ -15,7 +15,7 @@ # Main entry points: build_hamiltonian, estimate_scale; get_Hamiltonian # (core/TBSystem.jl) looks every geometry up in MODELS. # -# Depends on: Utils (fix_sites, _mpo_ket_sites, _mpo_dense_matrix), TBSystem (TBHamiltonian, the chain, +# Depends on: Utils (fix_sites, _mpo_ket_sites, _mpo_dense_matrix), MPOTools (_mpo_cutoff), TBSystem (TBHamiltonian, the chain, # Haldane and custom builders), geometry (the i -> position closures), Fibonacci, # MetallicMean, KBonacci (their get_Hamiltonian wrappers), presets (the H* builders, # looked up by Symbol at call time), sublattice* (builders and position tables, looked @@ -182,16 +182,18 @@ function _build_preset(geometry, params, L, N, sites; # a NamedTuple or a Dict) becomes its mparam_dict. entry = MODELS[geometry] mparam_dict = _preset_param_dict(entry, params) + Dcut = 2.0^L # the dimension the size-aware cutoff scales with (2D: the longer side) mpo = if entry.dim == 1 build_hamiltonian(geometry, L; mparam_dict, kwargs...) else # 2D: expect Lx and Ly in kwargs, or factorise L equally Lx = get(kwargs, :Lx, L ÷ 2) Ly = get(kwargs, :Ly, L - Lx) + Dcut = 2.0^max(Lx, Ly) kw_filtered = Dict(k => v for (k, v) in kwargs if k ∉ (:Lx, :Ly)) build_hamiltonian(geometry, Lx, Ly; mparam_dict, kw_filtered...) end - ITensorMPS.truncate!(mpo; maxdim=maxdim, cutoff=_mpo_cutoff(tol, 2.0^L, "get_Hamiltonian")) + ITensorMPS.truncate!(mpo; maxdim=maxdim, cutoff=_mpo_cutoff(tol, Dcut, "get_Hamiltonian")) # The model builders (HAAH, HSSH, …) create their own site indices internally, # so we extract the actual sites from the MPO rather than using the ones # created by get_Hamiltonian (which would be a different set). @@ -216,7 +218,7 @@ function _build_sublattice(entry::ModelEntry, params, L; Lx = get(kwargs, :Lx, L ÷ 2) Ly = get(kwargs, :Ly, L - Lx) args = Tuple(_param(params, k, v; scalar = k === :t) for (k, v) in pairs(entry.defaults)) - cut = _mpo_cutoff(tol, entry.n_sub * 2.0^L, "get_Hamiltonian") + cut = _mpo_cutoff(tol, entry.n_sub * 2.0^max(Lx, Ly), "get_Hamiltonian") # 2D: the longer side (_cutoff_dim) H = getfield(@__MODULE__, entry.builder)(Lx, Ly, args...; cutoff=cut, maxdim=maxdim) rs = getfield(@__MODULE__, entry.positions)(Lx, Ly) @@ -242,9 +244,9 @@ function _build_ssh_sublattice(params, L; scale=nothing, tol=nothing, maxdim=15, ref_sites=nothing) t = _param(params, :t, 1.0; scalar=true) d = _param(params, :d, 0.0) - H = ssh_sublattice_hamiltonian(L, t, d; - cutoff=_mpo_cutoff(tol, 2 * 2.0^L, "get_Hamiltonian"), - maxdim=maxdim) + H = _ssh_sublattice_hamiltonian(L, t, d; + cutoff=_mpo_cutoff(tol, 2 * 2.0^L, "get_Hamiltonian"), + maxdim=maxdim) isnothing(scale) || (H.scale = Float64(scale)) ref_sites === nothing || _replace_pos_sites!(H, ref_sites, "ssh_sublattice") return H diff --git a/src/core/TBSystem.jl b/src/core/TBSystem.jl index d801979..6aece11 100644 --- a/src/core/TBSystem.jl +++ b/src/core/TBSystem.jl @@ -19,7 +19,7 @@ # Main entry points: get_Hamiltonian, TBHamiltonian, add_hopping!, add_onsite!, # add_interaction!, truncate!, central_index, haldane_hoppingf. # -# Depends on: Utils, Hamiltonian, geometry*, ModelRegistry*, NNNeighbor* (a * +# Depends on: Utils, MPOTools (_mpo_cutoff), Hamiltonian, AuxDOF* (_lift_normal_term), geometry*, ModelRegistry*, NNNeighbor* (a * # marks a file included later; see the source map in TensorBinding.jl). # ============================================================ @@ -464,22 +464,30 @@ spaces. The centre is 0 except for the projected spaces. Large systems ------------- -`tol` is relative to the squared norm of the MPO, which grows with the dimension D of the -site space, so a fixed cutoff drops a term carried by a single matrix element once the -system is large enough. In a 1D chain the bond across the middle, `2^(L-1) - 1 → 2^(L-1)`, -whose carry flips every qubit, is such a term. With the fixed `1e-8` of v0.2.0 the 1D -models lost such bonds at L = 26 (`"chain_1d"`, `"uniform"`, `"aah"`, `"ssh_sublattice"`; -`"ssh"` at L = 28), and from L = 28 the chain was cut every `2^26` sites; `"custom"` with -nearest-neighbour hops threw, its self-check catching the missing bond. The default -`min(1e-8, 0.1/D)` keeps such terms; it equals `1e-8` up to D = 2^23 (L = 23 for a spinless -chain), so smaller systems build the same MPO as before. An explicit `tol` above `0.3/D` is -used as given and warns once. [`add_hopping!`](@ref), [`add_onsite!`](@ref), -[`add_spin!`](@ref), [`add_zeeman!`](@ref), [`add_soc!`](@ref) and -[`add_superconductivity!`](@ref) have the same default; with `1e-8` each of them cut the -chain again. In 2D a long carry repeats along a whole row or column, so `1e-8` keeps it -until `Lx` or `Ly` reaches about 24 (estimated; checked at `Lx = Ly = 13`). The chain MPO -of [`kinetic_1d_nn`](@ref) is itself exact up to L = 38 and loses the bond across the -middle at L = 40, whatever `tol`. +`tol` is relative to the squared norm of the MPO, `‖H‖² = D⟨h²⟩` with D the dimension of +the site space and `⟨h²⟩` the mean squared norm of a row, so a fixed cutoff drops a term +carried by a single matrix element once the system is large enough: an element `a` +survives while the cutoff stays below about `|a|²/‖H‖²`. In a 1D chain the bond across the +middle, `2^(L-1) - 1 → 2^(L-1)`, whose carry flips every qubit, is such a term. With the +fixed `1e-8` of v0.2.0 the 1D models lost it at L = 26 (`"chain_1d"`, `"uniform"`, `"aah"`, +`"ssh_sublattice"`; `"ssh"` at L = 28), and from L = 28 the chain was cut every `2^26` +sites; `"custom"` with nearest-neighbour hops threw, its self-check catching the missing +bond. The default is now `min(1e-8, 0.1/D)`. It equals `1e-8` up to D = 2^23 (L = 23 for a +spinless chain), so smaller systems build the same MPO as before, and above it keeps every +bond with `|t|² ≥ ⟨h²⟩/10`, such as the hops of a uniform chain (checked up to L = 30). + +It does not keep a bond that is weak next to the rest of its rows: beside on-site terms +beyond about 4t (`"aah"` with V ≳ 4t, a large `add_onsite!` potential) or beside a much +stronger bond (`"ssh_sublattice"` with `|t − d| < |t + d|/3`). There pass a `tol` below +`|t|²/‖H‖²`; the fixed `1e-8` lost those bonds as well. An explicit `tol` above `0.3/D` is +used as given and warns once. In 2D a long carry repeats along a whole row or column, so D +is taken along the longer side: 2D models keep `1e-8` until that side has 2^23 sites. + +[`add_hopping!`](@ref), [`add_onsite!`](@ref), [`add_spin!`](@ref), [`add_zeeman!`](@ref), +[`add_soc!`](@ref), [`add_superconductivity!`](@ref) and the non-Hermitian adders have the +same default; with `1e-8` each of them cut the chain again. The 1D kinetic MPOs +([`kinetic_1d_nn`](@ref), `kineticNNN`) summed with a fixed `1e-12`, which cut the bond at +L = 39 (one direction) and 40; that sum is size-aware too. Examples -------- @@ -863,7 +871,7 @@ function add_hopping!(H::TBHamiltonian, f; pos_s = _pos_sites(H) sl_s = H.sublattice_s - cut = _mpo_cutoff(tol, _site_space_dim(H.sites), "add_hopping!") + cut = _mpo_cutoff(tol, _cutoff_dim(H), "add_hopping!") apkw = isempty(apply_kwargs) ? (; cutoff=cut, maxdim=maxdim) : apply_kwargs bc === nothing || (boundary = Symbol(bc)) @@ -986,7 +994,7 @@ Invalidates all caches. function add_onsite!(H::TBHamiltonian, f; layer=nothing, sublat=nothing, Lx=nothing, tol=nothing, maxdim=nothing, check::Bool=false) _require_binary_position_space(H, "add_onsite!") - cut = _mpo_cutoff(tol, _site_space_dim(H.sites), "add_onsite!") + cut = _mpo_cutoff(tol, _cutoff_dim(H), "add_onsite!") if H.layer_s !== nothing (H.spin_s === nothing && H.nambu_s === nothing) || error("Layered add_onsite! currently supports layer/position/sublattice Hamiltonians only.") @@ -1143,6 +1151,18 @@ function _pos_sites(H::TBHamiltonian) return filter(s -> s ∉ aux_set, H.sites) end +# The dimension that the size-aware cutoff of a term added to H scales with +# (_mpo_cutoff): the dimension of its site space in 1D; in 2D (H.Lx set, below H.L) that +# divided by the number of sites along the shorter side, because a carry along x repeats +# along every row and one along y along every column, so the weakest carry class weighs +# 1/max(Nx, Ny) of what a 1D carry would. 2D results then keep 1e-8 until the longer side +# reaches 2^23 sites, with no warning at the usual sizes. +function _cutoff_dim(H) + D = _site_space_dim(H.sites) + (H.Lx === nothing || H.Lx >= H.L) && return D + return D / 2.0^min(H.Lx, H.L - H.Lx) +end + # An exciton Hamiltonian (exciton_hamiltonian): the interleaved 2L-site electron-hole # register, with no auxiliary index. Counting sites alone is not enough: auxiliary # indices can also bring a one-particle model to 2L sites (a spinful L = 1 chain). diff --git a/src/core/Utils.jl b/src/core/Utils.jl index 1800e5b..829cf72 100644 --- a/src/core/Utils.jl +++ b/src/core/Utils.jl @@ -105,7 +105,7 @@ end function shift_hopping_mpo(hopping::MPO, sites, q::Integer; cyclic::Bool=false, maxdim::Int=typemax(Int), - cutoff::Real=1e-12, + cutoff::Real=min(1e-12, _default_mpo_cutoff(2.0^length(sites))), apply_kwargs=NamedTuple()) K, Kdag = shift_pair_mpos(sites, q; cyclic=cyclic) apkw = isempty(apply_kwargs) ? diff --git a/src/lattice/NNNeighbor.jl b/src/lattice/NNNeighbor.jl index 28269c5..5170c0b 100644 --- a/src/lattice/NNNeighbor.jl +++ b/src/lattice/NNNeighbor.jl @@ -14,7 +14,7 @@ # _check_bravais_layout - rejects geometries that are not Bravais in the cell index # _resolve_layer_selection - the `layer` keyword of add_hopping_2D! as a list of layers # -# Depends on: core/Utils.jl (build_shift_mpo, get_diagonal_mpo, postpend_op, +# Depends on: core/MPOTools.jl (_mpo_cutoff), core/Utils.jl (build_shift_mpo, get_diagonal_mpo, postpend_op, # prepend_layer_projector), core/TBSystem.jl (TBHamiltonian, _pos_sites, # _invalidate_cache!), lattice/geometry.jl (_resolve_2d_geometry), # lattice/masks2d.jl (_row_break_mpo) and lattice/hopping2d.jl (generate_kin_u/d). @@ -255,7 +255,7 @@ function add_hopping_2D!(H::TBHamiltonian, f; geometry = nothing, maxdim::Int = 50, tol::Union{Nothing,Real} = nothing) - cut = _mpo_cutoff(tol, _site_space_dim(H.sites), "add_hopping_2D!") + cut = _mpo_cutoff(tol, _site_space_dim(H.sites) / 2.0^min(Lx, Ly), "add_hopping_2D!") if H.layer_s !== nothing (H.spin_s === nothing && H.nambu_s === nothing) || error("Layered add_hopping_2D! currently supports layer/position/sublattice Hamiltonians only.") diff --git a/src/lattice/TJunction.jl b/src/lattice/TJunction.jl index a97f6e1..3afe978 100644 --- a/src/lattice/TJunction.jl +++ b/src/lattice/TJunction.jl @@ -83,6 +83,12 @@ See `tjunction_positions` for the atom index convention. After the call, `H.sublattice_s` stores the TJunction index and `H.aux_side = :post`. All caches are invalidated. +`cutoff` is the relative cutoff of the sum. The default is `min(1e-8, 0.1/D)`, D = 3·2^L +(see "Large systems" in [`get_Hamiltonian`](@ref)), and at most a tenth of the junction's +share of `‖H‖²`: the junction is a single-site term weighing `≈ (t_j/t)²/2^L`, and up to +v0.2.0 the fixed `1e-8` removed a weak one entirely (`t_j = 0.02 t` at L = 16), leaving +three decoupled chains. + Examples -------- ```julia @@ -105,8 +111,9 @@ function add_tjunction!(H::TBHamiltonian, t_j; coupling = nothing, cutoff::Union{Nothing,Real} = nothing, maxdim::Int = 200) - # the default min(1e-8, 0.1/D), D the dimension of the 3-branch site space - cut = _mpo_cutoff(cutoff, 3 * _site_space_dim(H.sites), "add_tjunction!"; keyword="cutoff") + # the default min(1e-8, 0.1/D), D the dimension of the 3-branch site space; capped + # below by the junction's weight once the term is built + cut = _mpo_cutoff(cutoff, 3 * _cutoff_dim(H), "add_tjunction!"; keyword="cutoff") isnothing(H.sublattice_s) && isnothing(H.layer_s) && isnothing(H.spin_s) && isnothing(H.nambu_s) || error("add_tjunction! requires H with no existing auxiliary indices " * @@ -127,6 +134,15 @@ function add_tjunction!(H::TBHamiltonian, t_j; t_j * [0.0 1.0 1.0; 1.0 0.0 1.0; 1.0 1.0 0.0] : coupling H_junc = postpend_op(P_junc, tj_s, J_mat) + # The junction P ⊗ J is a single-site term of weight ‖H_junc‖²/‖H‖² ≈ (t_j/t)²/2^L, + # its own singular vector: a relative cutoff above that removed it and left three + # decoupled chains (t_j = 0.02 at L = 16 with 1e-8, t_j ≤ 0.18 t at L ≥ 22 with + # 0.1/D). The default stays a tenth below it. + # (t_j = 0 or a zero coupling matrix: no junction to keep, so no cap) + if cutoff === nothing + wj, wi = real(inner(H_junc, H_junc)), real(inner(H_intra, H_intra)) + wj > 0 && (cut = min(cut, 0.1 * wj / (wi + wj))) + end # --- Geometry: 2D Y-junction, branches at 0°, 120°, 240° ----------------- # Atom index convention (branch-fast): @@ -178,8 +194,8 @@ from the junction site (placed at the origin). See `tjunction_positions`. - `coupling` : custom 3×3 coupling matrix (default: symmetric Y-junction `t_j * [0 1 1; 1 0 1; 1 1 0]`) - `boundary` : `:open` (default) or `:periodic` for the intra-chain hoppings -- `cutoff` : MPO truncation cutoff, by default `min(1e-8, 0.1/D)`, D = 3·2^L (`1e-8` - up to L = 21; see "Large systems" in [`get_Hamiltonian`](@ref)) +- `cutoff` : MPO truncation cutoff, by default that of [`add_tjunction!`](@ref) + (`min(1e-8, 0.1/D)`, D = 3·2^L, kept below the junction's weight) - `maxdim` : maximum MPO bond dimension Examples diff --git a/src/lattice/sublattice.jl b/src/lattice/sublattice.jl index 9b93a43..58dec69 100644 --- a/src/lattice/sublattice.jl +++ b/src/lattice/sublattice.jl @@ -454,7 +454,14 @@ L = 26 (see "Large systems" in [`get_Hamiltonian`](@ref)). function ssh_sublattice_hamiltonian(L::Integer, t::Number = 1.0, d::Number = 0.0; cutoff::Union{Nothing,Real} = nothing, maxdim::Int = 200) - cutoff = _mpo_cutoff(cutoff, 2 * 2.0^L, "ssh_sublattice_hamiltonian"; keyword="cutoff") + cut = _mpo_cutoff(cutoff, 2 * 2.0^L, "ssh_sublattice_hamiltonian"; keyword="cutoff") + return _ssh_sublattice_hamiltonian(L, t, d; cutoff=cut, maxdim=maxdim) +end + +# ssh_sublattice_hamiltonian with a resolved cutoff (get_Hamiltonian resolves and warns +# about its own tol, then builds through here). +function _ssh_sublattice_hamiltonian(L::Integer, t::Number, d::Number; + cutoff::Real, maxdim::Int) # A 1D chain: the setup of a 2^L × 2^0 grid. S = _sublattice_setup(L, 0, 2, "SSH"; cutoff, maxdim) diff --git a/src/physics/Supercond.jl b/src/physics/Supercond.jl index ac88bf2..e2ba156 100644 --- a/src/physics/Supercond.jl +++ b/src/physics/Supercond.jl @@ -68,7 +68,8 @@ function pairingNNN(L, sites, hopping::MPO, nn::Integer; apply_kwargs = NamedTup An = compose_power(k1, nn; side=:right, apply_kwargs) Am = compose_power(k2, nn; side=:left, apply_kwargs) return +(apply(hopping, An; apply_kwargs...), - -1.0 * apply(Am, dag(hopping); apply_kwargs...); cutoff=1e-12) + -1.0 * apply(Am, dag(hopping); apply_kwargs...); + cutoff=min(1e-12, _default_mpo_cutoff(2.0^L))) # as kineticNNN end diff --git a/src/physics/TwoParticle.jl b/src/physics/TwoParticle.jl index 327f139..cfa3d5f 100644 --- a/src/physics/TwoParticle.jl +++ b/src/physics/TwoParticle.jl @@ -188,7 +188,7 @@ function Exciton_Hamiltonian(H_c::TBHamiltonian, H_v::TBHamiltonian, Ufunc; tol_quantics=tol_quantics, maxbonddim_quantics=maxbonddim_quantics) V_v = qtt_mpo(L, xvals, H_v.sites, on_site; tol_quantics=tol_quantics, maxbonddim_quantics=maxbonddim_quantics) - cut = _mpo_cutoff(tol, _site_space_dim(H_c.sites), "Exciton_Hamiltonian") + cut = _mpo_cutoff(tol, _cutoff_dim(H_c), "Exciton_Hamiltonian") mpo_c = +(mpo_c, V_c; cutoff=cut) mpo_v = +(mpo_v, -1.0*V_v; cutoff=cut) end diff --git a/src/physics/nh/model.jl b/src/physics/nh/model.jl index e5a8c23..0f14ca0 100644 --- a/src/physics/nh/model.jl +++ b/src/physics/nh/model.jl @@ -7,7 +7,7 @@ # Entry points: hermitize, hermitized_hamiltonian, NonHermitianHamiltonian, # nh_block_index, add_nh_onsite!, loss_profile_mpo, add_loss!, # nh_nonreciprocal_hopping_mpo, add_nh_nonreciprocal_hopping!, add_nh_skin_hopping!. -# Depends on: core/Utils.jl, core/TBSystem.jl. +# Depends on: core/Utils.jl, core/MPOTools.jl (_mpo_cutoff), core/TBSystem.jl (_cutoff_dim). # # The core construction here hermitizes a non-Hermitian single-particle MPO by # adding one dim-2 auxiliary block index: @@ -79,7 +79,7 @@ with the existing KPM code paths. nh_block_index() = Index(2, "Qubit,NHBlock") """ - hermitized_hamiltonian(H; z=0.0, block_s=nh_block_index(), cutoff=1e-8, + hermitized_hamiltonian(H; z=0.0, block_s=nh_block_index(), cutoff=nothing, maxdim=200, scale=0.0, convention=:z_minus_H, block_placement=:post) -> TBHamiltonian @@ -96,7 +96,11 @@ block as written; `convention=:H_minus_z` uses `H - zI` instead. - `:post` (default) — site order `[H.sites...; block_s]`; position qubits occupy 1:L directly - `:pre` — site order `[block_s; H.sites...]`; original layout before postpend change -`scale=0.0` keeps the usual lazy KPM spectral-bound estimation. +`scale=0.0` keeps the usual lazy KPM spectral-bound estimation. `cutoff` defaults to +`min(1e-8, 0.1r/D)`, D the dimension of the block space and `r = min(1, ‖H‖²/‖zI − H‖²)` +(the block grows with `|z|`; see "Large systems" in [`get_Hamiltonian`](@ref)). The +non-Hermitian KPM entry points pass their own `cutoff` here; at large L pass a smaller one +(an explicit value above `0.3r/D` warns). The result is a copy of `H` with the block operator as `mpo`, the extra site in `sites` and `aux_side = block_placement` (the side of the block index, the @@ -108,7 +112,7 @@ do not know it. function hermitized_hamiltonian(H::TBHamiltonian; z::Number = 0.0, block_s::Index = nh_block_index(), - cutoff::Real = 1e-8, + cutoff::Union{Nothing,Real} = nothing, maxdim::Int = 200, scale::Real = 0.0, convention::Symbol = :z_minus_H, @@ -117,6 +121,10 @@ function hermitized_hamiltonian(H::TBHamiltonian; convention in (:H_minus_z, :z_minus_H) || error("convention must be :H_minus_z or :z_minus_H; got :$convention") I_H = MPO(H.sites, "Id") + # the size-aware default on the block space (dimension 2D, see _mpo_cutoff), scaled by + # r = min(1, |H|^2/|zI - H|^2) since the block grows with |z| (as build_K with omega) + r = _herm_norm_ratio(H.mpo, I_H, z, _site_space_dim(H.sites)) + cutoff = _mpo_cutoff(cutoff, 2 * _cutoff_dim(H) / r, "hermitized_hamiltonian"; keyword="cutoff") H_shift = convention === :H_minus_z ? +(H.mpo, -ComplexF64(z) * I_H; cutoff=cutoff) : +(ComplexF64(z) * I_H, -H.mpo; cutoff=cutoff) @@ -141,16 +149,24 @@ function hermitized_hamiltonian(H::TBHamiltonian; end """ - hermitize(H; z=0.0, cutoff=1e-8, maxdim=200, scale=0.0, convention=:z_minus_H, + hermitize(H; z=0.0, cutoff=nothing, maxdim=200, scale=0.0, convention=:z_minus_H, block_placement=:post) -> NonHermitianHamiltonian Build a `NonHermitianHamiltonian` wrapper without modifying `H`. It takes the keywords of `hermitized_hamiltonian` except `block_s` (a fresh `nh_block_index()` is used). """ +# r = min(1, ‖H‖²/‖zI − H‖²), ‖zI − H‖² = |z|²D − 2Re(z̄ tr H) + ‖H‖² (exact, from two MPO +# inner products), for the default cutoff of hermitized_hamiltonian. +function _herm_norm_ratio(Hm::MPO, I_H::MPO, z::Number, D::Real) + nH2 = real(inner(Hm, Hm)) + nS2 = abs2(z) * D - 2 * real(conj(z) * inner(I_H, Hm)) + nH2 + return nS2 > 0 ? min(1.0, nH2 / nS2) : 1.0 +end + function hermitize(H::TBHamiltonian; z::Number = 0.0, - cutoff::Real = 1e-8, + cutoff::Union{Nothing,Real} = nothing, maxdim::Int = 200, scale::Real = 0.0, convention::Symbol = :z_minus_H, @@ -169,7 +185,7 @@ function hermitize(H::TBHamiltonian; end """ - hermitize(NH; z=NH.z, cutoff=1e-8, maxdim=200, scale=NH.scale, + hermitize(NH; z=NH.z, cutoff=nothing, maxdim=200, scale=NH.scale, convention=NH.convention, block_placement=NH.block_placement) -> NonHermitianHamiltonian @@ -179,7 +195,7 @@ carry over unless passed; `cutoff` and `maxdim` take their defaults. """ function hermitize(NH::NonHermitianHamiltonian; z::Number = NH.z, - cutoff::Real = 1e-8, + cutoff::Union{Nothing,Real} = nothing, maxdim::Int = 200, scale::Real = NH.scale, convention::Symbol = NH.convention, @@ -250,7 +266,7 @@ function _nh_fullspace_diagonal_mpo(H::TBHamiltonian, f; Lx=nothing, type=Float6 end """ - add_nh_onsite!(H, v; Lx=nothing, tol=1e-8, maxdim=200, type=ComplexF64) + add_nh_onsite!(H, v; Lx=nothing, tol=nothing, maxdim=200, type=ComplexF64) Add a possibly complex onsite potential to a position-only `TBHamiltonian`. @@ -260,18 +276,20 @@ Add a possibly complex onsite potential to a position-only `TBHamiltonian`. - `v(ix, iy)` with 0-indexed coordinates, requiring `Lx=...` This is the non-Hermitian counterpart of `add_onsite!`; unlike the generic -version it preserves complex values by default. +version it preserves complex values by default. `tol` is the relative cutoff of the sum, by default +`min(1e-8, 0.1/D)` as for `add_onsite!` (see "Large systems" in [`get_Hamiltonian`](@ref)). """ function add_nh_onsite!(H::TBHamiltonian, v; Lx=nothing, - tol::Real = 1e-8, + tol::Union{Nothing,Real} = nothing, maxdim::Int = 200, type = ComplexF64) _require_binary_position_space(H, "add_nh_onsite!") pos_s = _nh_position_sites_only(H) term = _nh_diagonal_mpo(H.L, pos_s, v; Lx=Lx, type=type) - H.mpo = +(H.mpo, term; cutoff=tol, maxdim=maxdim) - ITensorMPS.truncate!(H.mpo; cutoff=tol, maxdim=maxdim) + cut = _mpo_cutoff(tol, _cutoff_dim(H), "add_nh_onsite!") + H.mpo = +(H.mpo, term; cutoff=cut, maxdim=maxdim) + ITensorMPS.truncate!(H.mpo; cutoff=cut, maxdim=maxdim) _invalidate_cache!(H) return H end @@ -302,23 +320,25 @@ function loss_profile_mpo(H::TBHamiltonian, f; end """ - add_loss!(H, f; coefficient=-1im, Lx=nothing, tol=1e-8, maxdim=200, + add_loss!(H, f; coefficient=-1im, Lx=nothing, tol=nothing, maxdim=200, type=Float64, space=:full) Add a loss/gain term `coefficient * diag(f)` to the original Hamiltonian MPO. -This only modifies `H.mpo`; it does not create the hermitized NH block. +This only modifies `H.mpo`; it does not create the hermitized NH block. `tol` is the +relative cutoff of the sum, by default `min(1e-8, 0.1/D)` as for `add_onsite!`. """ function add_loss!(H::TBHamiltonian, f; coefficient::Number = -1im, Lx=nothing, - tol::Real = 1e-8, + tol::Union{Nothing,Real} = nothing, maxdim::Int = 200, type = Float64, space::Symbol = :full) _require_binary_position_space(H, "add_loss!") term = ComplexF64(coefficient) * loss_profile_mpo(H, f; Lx=Lx, type=type, space=space) - H.mpo = +(H.mpo, term; cutoff=tol, maxdim=maxdim) - ITensorMPS.truncate!(H.mpo; cutoff=tol, maxdim=maxdim) + cut = _mpo_cutoff(tol, _cutoff_dim(H), "add_loss!") + H.mpo = +(H.mpo, term; cutoff=cut, maxdim=maxdim) + ITensorMPS.truncate!(H.mpo; cutoff=cut, maxdim=maxdim) _invalidate_cache!(H) return H end @@ -346,7 +366,7 @@ function _nh_directional_hop(pos_s, N::Int, amplitude, nn::Integer, direction::S end """ - nh_nonreciprocal_hopping_mpo(H, t_forward, t_backward; nn=1, tol=1e-8, + nh_nonreciprocal_hopping_mpo(H, t_forward, t_backward; nn=1, tol=nothing, maxdim=200, type=ComplexF64) Build the position-space MPO @@ -360,20 +380,27 @@ site-dependent one-argument functions `t(n)` with 0-indexed `n`. """ function nh_nonreciprocal_hopping_mpo(H::TBHamiltonian, t_forward, t_backward; nn::Integer = 1, - tol::Real = 1e-8, + tol::Union{Nothing,Real} = nothing, maxdim::Int = 200, type = ComplexF64) _require_binary_position_space(H, "nh_nonreciprocal_hopping_mpo") + cut = _mpo_cutoff(tol, _cutoff_dim(H), "nh_nonreciprocal_hopping_mpo") + return _nh_nonreciprocal_hopping_mpo(H, t_forward, t_backward; nn, cut, maxdim, type) +end + +# nh_nonreciprocal_hopping_mpo with a resolved cutoff `cut`. +function _nh_nonreciprocal_hopping_mpo(H::TBHamiltonian, t_forward, t_backward; + nn::Integer, cut::Real, maxdim::Int, type) pos_s = _nh_position_sites_only(H) Hf = _nh_directional_hop(pos_s, H.N, t_forward, nn, :forward; - L=H.L, tol=tol, maxdim=maxdim, type=type) + L=H.L, tol=cut, maxdim=maxdim, type=type) Hb = _nh_directional_hop(pos_s, H.N, t_backward, nn, :backward; - L=H.L, tol=tol, maxdim=maxdim, type=type) - return +(Hf, Hb; cutoff=tol, maxdim=maxdim) + L=H.L, tol=cut, maxdim=maxdim, type=type) + return +(Hf, Hb; cutoff=cut, maxdim=maxdim) end """ - add_nh_nonreciprocal_hopping!(H, t_forward, t_backward; nn=1, tol=1e-8, + add_nh_nonreciprocal_hopping!(H, t_forward, t_backward; nn=1, tol=nothing, maxdim=200, type=ComplexF64) Add asymmetric hopping directly to `H`. This is the skin-effect helper: @@ -381,19 +408,21 @@ choose, for example, `t_forward=t*exp(g)` and `t_backward=t*exp(-g)`. """ function add_nh_nonreciprocal_hopping!(H::TBHamiltonian, t_forward, t_backward; nn::Integer = 1, - tol::Real = 1e-8, + tol::Union{Nothing,Real} = nothing, maxdim::Int = 200, type = ComplexF64) - term = nh_nonreciprocal_hopping_mpo(H, t_forward, t_backward; - nn=nn, tol=tol, maxdim=maxdim, type=type) - H.mpo = +(H.mpo, term; cutoff=tol, maxdim=maxdim) - ITensorMPS.truncate!(H.mpo; cutoff=tol, maxdim=maxdim) + _require_binary_position_space(H, "add_nh_nonreciprocal_hopping!") + cut = _mpo_cutoff(tol, _cutoff_dim(H), "add_nh_nonreciprocal_hopping!") + term = _nh_nonreciprocal_hopping_mpo(H, t_forward, t_backward; + nn=nn, cut=cut, maxdim=maxdim, type=type) + H.mpo = +(H.mpo, term; cutoff=cut, maxdim=maxdim) + ITensorMPS.truncate!(H.mpo; cutoff=cut, maxdim=maxdim) _invalidate_cache!(H) return H end """ - add_nh_skin_hopping!(H, t, g; nn=1, convention=:exp, tol=1e-8, maxdim=200) + add_nh_skin_hopping!(H, t, g; nn=1, convention=:exp, tol=nothing, maxdim=200) Convenience wrapper for non-reciprocal skin hopping. @@ -403,7 +432,7 @@ Convenience wrapper for non-reciprocal skin hopping. function add_nh_skin_hopping!(H::TBHamiltonian, t, g; nn::Integer = 1, convention::Symbol = :exp, - tol::Real = 1e-8, + tol::Union{Nothing,Real} = nothing, maxdim::Int = 200) t_forward, t_backward = if convention === :exp (t * exp(g), t * exp(-g)) diff --git a/test/bugfix_large_L_cutoffs.jl b/test/bugfix_large_L_cutoffs.jl index 0739bfe..6996c24 100644 --- a/test/bugfix_large_L_cutoffs.jl +++ b/test/bugfix_large_L_cutoffs.jl @@ -26,7 +26,10 @@ _wrap(H) = _el(H, 0, 2^H.L - 1) # zero on an open chain @test _middle(H) ≈ 1.0 atol=1e-8 @test abs(_wrap(H)) < 1e-8 Hold = @test_logs (:warn, r"single matrix element") get_Hamiltonian("chain_1d", 1.0; L, tol=1e-8) - @test abs(_middle(Hold) - 1.0) > 0.5 # what v0.2.0 built + # what v0.2.0 built: at L = 26, 1e-8 removes one of the two (degenerate) directions of + # the bond, which one being up to the SVD's rounding, so check both + m = 2^(L - 1) + @test max(abs(_el(Hold, m - 1, m) - 1), abs(_el(Hold, m, m - 1) - 1)) > 0.5 add_onsite!(H, n -> 0.1 * cos(0.3n)) # with 1e-8 it cut the chain again @test _middle(H) ≈ 1.0 atol=1e-8 @@ -37,4 +40,45 @@ _wrap(H) = _el(H, 0, 2^H.L - 1) # zero on an open chain ("custom", (i, j) -> abs(i - j) == 1 ? 1.0 : 0.0, (; scale=2.5))) @test abs(_middle(get_Hamiltonian(geom, p; L, kw...))) ≈ 1.0 atol=1e-6 end + + # the non-Hermitian adders cut the chain again too + Hn = get_Hamiltonian("chain_1d", 1.0; L) + TensorBinding.add_nh_onsite!(Hn, 0.1im) + @test _el(Hn, m - 1, m) ≈ 1.0 atol=1e-8 + @test _el(Hn, m, m - 1) ≈ 1.0 atol=1e-8 + + # one explicit risky value, one warning (add_zeeman! used to warn under add_spin! too) + Hz = get_Hamiltonian("chain_1d", 1.0; L) + @test_logs (:warn, r"^add_zeeman!") TensorBinding.add_zeeman!(Hz, 0.1; tol=1e-8) + + # 2D: a long carry repeats along a whole row or column, so the cutoff scales with the + # longer side and an explicit 1e-8 neither warns nor changes at L = 26 + @test_logs min_level=Logging.Warn get_Hamiltonian("square_2d", 1.0; L, Lx=13, tol=1e-8) + @test TensorBinding._cutoff_dim(get_Hamiltonian("square_2d", 1.0; L=8, Lx=3)) == 2.0^5 + + # kinetic_1d_nn's own sum: 1e-12 cut one direction of the bond at L = 39, both at 40 + H40 = get_Hamiltonian("chain_1d", 1.0; L=40) + m40 = 2^39 + @test _el(H40, m40 - 1, m40) ≈ 1.0 atol=1e-8 + @test _el(H40, m40, m40 - 1) ≈ 1.0 atol=1e-8 + + # a weak T-junction, a single-site term, is no longer truncated away (t_j = 0.02 at L = 16) + Ht = TensorBinding.tjunction_hamiltonian(16, 1.0, 0.02) + st(n, b) = MPS(Ht.sites, [[((n >> (16 - k)) & 1) + 1 for k in 1:16]; b]) + @test real(inner(st(0, 1)', Ht.mpo, st(0, 2))) ≈ 0.02 atol=1e-10 + # ... and without a junction the cap does not apply (a zero cap kept every noise vector) + @test maxlinkdim(TensorBinding.tjunction_hamiltonian(10, 1.0, 0.0).mpo) <= 4 + + # the hermitized block grows with |z|: its default scales with ‖H‖²/‖zI − H‖², so the + # middle bond survives at z = 4 (0.92/0.08 at z = 3 and 1e-7 at z = 4 without it) + Hc = get_Hamiltonian("chain_1d", 1.0; L) + Hh = TensorBinding.hermitized_hamiltonian(Hc; z = 4.0) + sb(n, b) = MPS(Hh.sites, [[((n >> (L - k)) & 1) + 1 for k in 1:L]; b]) + @test real(inner(sb(m - 1, 1)', Hh.mpo, sb(m, 2))) ≈ -1.0 atol=1e-8 + @test real(inner(sb(m, 1)', Hh.mpo, sb(m - 1, 2))) ≈ -1.0 atol=1e-8 + + # pairingNNN summed at a fixed 1e-12, like kinetic_1d_nn + s40 = H40.sites + P40 = TensorBinding.pairingNNN(40, s40, 0.2 * MPO(s40, "Id"), 1) + @test _el(TensorBinding.TBHamiltonian(H40; mpo = P40), m40 - 1, m40) ≈ 0.2 atol=1e-8 end From 71114412426588d370efc54faf45d4b4c7df4684 Mon Sep 17 00:00:00 2001 From: Anouar Moustaj Date: Fri, 13 Nov 2026 13:09:01 +0200 Subject: [PATCH 20/22] Reject unknown arguments in the golden generators generate_dynamics_golden.jl and generate_gpu_golden.jl only looked for "--only" followed by a value. A mistyped option (--only=..., -only) fell back to a full regeneration, the outcome --only exists to prevent; "--only a b" reran a without a word; a trailing --only died with a BoundsError after the packages had loaded. Both now accept --only a,b and --only=a,b, and stop with an error on a missing value or any other argument (checked on seven argument lists). Co-Authored-By: Claude Opus 5.5 --- test/data/generate_dynamics_golden.jl | 16 ++++++++++++++-- test/data/generate_gpu_golden.jl | 16 ++++++++++++++-- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/test/data/generate_dynamics_golden.jl b/test/data/generate_dynamics_golden.jl index 0f99404..9c3ca28 100644 --- a/test/data/generate_dynamics_golden.jl +++ b/test/data/generate_dynamics_golden.jl @@ -48,8 +48,20 @@ const R = DynamicsGoldenRunner const OUTFILE = joinpath(@__DIR__, "dynamics_golden.jl") # `--only name1,name2,…`: rerun these cases, keep the stored entries of the others. -const ONLY = let i = findfirst(==("--only"), ARGS) - i === nothing ? nothing : Set(String.(split(ARGS[i + 1], ','))) +# (`--only=name1,…` works too.) Any other argument is an error, so that a mistyped option +# cannot fall back to a full regeneration. +const ONLY = let args = copy(ARGS), only = nothing + i = findfirst(a -> a == "--only" || startswith(a, "--only="), args) + if i !== nothing + bare = args[i] == "--only" + val = bare ? (i < length(args) ? args[i + 1] : "") : args[i][8:end] + isempty(val) && error("--only needs a comma-separated list of case names") + only = Set(String.(split(val, ','))) + deleteat!(args, bare ? (i:i + 1) : (i:i)) + end + isempty(args) || error("unknown argument(s): ", join(args, " "), + " (the only option is --only name1,name2,...)") + only end # An exception of one of these types means the case itself is malformed (a diff --git a/test/data/generate_gpu_golden.jl b/test/data/generate_gpu_golden.jl index 9db6639..2f2d13e 100644 --- a/test/data/generate_gpu_golden.jl +++ b/test/data/generate_gpu_golden.jl @@ -55,8 +55,20 @@ const R = GPUGoldenRunner const OUTFILE = joinpath(@__DIR__, "gpu_golden.jl") # `--only name1,name2,…`: rerun these cases, keep the stored entries of the others. -const ONLY = let i = findfirst(==("--only"), ARGS) - i === nothing ? nothing : Set(String.(split(ARGS[i + 1], ','))) +# (`--only=name1,…` works too.) Any other argument is an error, so that a mistyped option +# cannot fall back to a full regeneration. +const ONLY = let args = copy(ARGS), only = nothing + i = findfirst(a -> a == "--only" || startswith(a, "--only="), args) + if i !== nothing + bare = args[i] == "--only" + val = bare ? (i < length(args) ? args[i + 1] : "") : args[i][8:end] + isempty(val) && error("--only needs a comma-separated list of case names") + only = Set(String.(split(val, ','))) + deleteat!(args, bare ? (i:i + 1) : (i:i)) + end + isempty(args) || error("unknown argument(s): ", join(args, " "), + " (the only option is --only name1,name2,...)") + only end function evaluate(c) From 4c7ef304641ae9672e03350668a7adb99082e788 Mon Sep 17 00:00:00 2001 From: Anouar Moustaj Date: Fri, 13 Nov 2026 13:09:01 +0200 Subject: [PATCH 21/22] Extend the 2D QFT warning to get_qpi and the cheb2d k-diagonals; correct its figure get_qpi and get_bubble_diag_cheb2d(_svd, _tucker) take their momenta from the same single QFT over the linear index as get_bands (QPI.jl, and cheb2d.jl through conjugate_by_qft); get_qpi's docstring even told the user to reshape the output as a (kx, ky) map. Both docstrings now carry the warning, and the CHANGELOG entry names them. In get_bands, "50-72 % of the weight stays off the momentum diagonal" was the Frobenius ratio of the off-diagonal to the diagonal part of the conjugated Hamiltonian on 4x4 to 8x8 tori, which decays with size, and "ky from the x bits" holds only for Lx = Ly. The admonition now says what is misread at every size: the low Ly bits of the label are the true ky, the high bits the true kx plus a shear. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 ++++++--- src/physics/QPI.jl | 6 ++++++ src/physics/qft/bands.jl | 15 +++++++++------ src/physics/rpa/cheb2d.jl | 6 ++++++ 4 files changed, 27 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ed453ba..76e6d1e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,10 +52,13 @@ bugs without breaking the API. unchanged. - **2D bands documented as wrong.** In 2D, `get_bands` and `get_bands_gpu` take their momenta from one QFT over the linear index `n = ix + iy·2^Lx`, not from a QFT along x - times one along y: ky is read from the x bits and kx from the y bits, with a shear, so + times one along y: the low `Ly` bits of a momentum label are the true ky and the high + bits the true kx, plus a shear (for `Lx = Ly`, ky is read from the x bits), so 2D bands are not resolved by `(kx, ky)` and the `kpath` labels are not the points they - name. Both docstrings now say so; results are unchanged, and a separable 2D transform - is left for a later release. 1D is not affected. + name. Their docstrings now say so, as do those of `get_qpi` (whose 2D map has the same + mix-up) and of the k-space diagonals `get_bubble_diag_cheb2d(_svd, _tucker)`; results + are unchanged, and a separable 2D transform is left for a later release. 1D is not + affected. ### Changed results diff --git a/src/physics/QPI.jl b/src/physics/QPI.jl index 205a633..450b213 100644 --- a/src/physics/QPI.jl +++ b/src/physics/QPI.jl @@ -116,6 +116,12 @@ qpi = get_qpi(H, 80, ωlist; V=2.0, window_fraction=0.8) **Normalisation:** built from LDOS in the package's KPM convention (see [`get_ldos_from_mun`](@ref)): per unit rescaled energy `(ω − H.center)/H.scale` and times `1/π`; multiply by `π/H.scale` for physical units. + +!!! warning "2D maps" + As in [`get_bands`](@ref), the momenta come from one QFT over the linear index + `n = ix + iy·2^Lx`, not from a QFT along x times one along y, so the reshape above does + not give a `(kx, ky)` map: a modulation along x shows up along y, with a shear, and for + `Lx ≠ Ly` the map is scrambled. 1D is not affected. """ function get_qpi(H::TBHamiltonian, Ncheb::Int, ω_phys_vals; impurity_site::Union{Int,Nothing} = nothing, diff --git a/src/physics/qft/bands.jl b/src/physics/qft/bands.jl index 3035ea7..ae5709f 100644 --- a/src/physics/qft/bands.jl +++ b/src/physics/qft/bands.jl @@ -252,12 +252,15 @@ an `ArgumentError` instead. !!! warning "2D: one QFT over the linear index" In 2D the momenta come from one QFT over all position qubits (`conjugate_by_qft`), i.e. over the linear index `n = ix + iy·2^Lx`, not from a QFT along x times one along - y. The label `(ky << Lx) | kx` of a k-group then reads ky from the x bits and kx from - the y bits, with a shear of `x/2^Ly` grid steps, so 2D bands are not resolved by - `(kx, ky)`: on a torus 50–72 % of the weight stays off the momentum diagonal, and along - Γ → X an anisotropic torus (`tx = 1`, `ty = 0.3`) follows the `ty` band (checked - against dense diagonalisation). 1D is not affected. Until a separable 2D transform is - added, use 1D cuts or a dense calculation for 2D bands. + y. The label `(ky << Lx) | kx` of a k-group is then misread: its low `Ly` bits are the + true ky and its high bits the true kx, plus a shear of `(label mod 2^Ly)/2^Ly` (for + `Lx = Ly`, ky comes from the x bits and kx from the y bits), so 2D bands are not + resolved by `(kx, ky)`. Along Γ → X an anisotropic 8×8 torus (`tx = 1`, `ty = 0.3`) + follows the `ty` band, and on 4×4 to 8×8 tori the off-diagonal part of the conjugated + Hamiltonian is 0.5–0.7 of its diagonal in Frobenius norm; that part decays with size, + the relabelling and the shear do not (checked against dense diagonalisation). 1D is not + affected. Until a separable 2D transform is added, use 1D cuts or a dense calculation + for 2D bands. """ function get_bands(H_mpo::MPO, scale::Real, center::Real, sites, Ncheb::Int, D::Int, ω_vals; diff --git a/src/physics/rpa/cheb2d.jl b/src/physics/rpa/cheb2d.jl index 0462bf5..446a039 100644 --- a/src/physics/rpa/cheb2d.jl +++ b/src/physics/rpa/cheb2d.jl @@ -625,6 +625,12 @@ is the sum of the results for the two spin sectors **Keyword arguments** — identical to `get_bubble_mpo_cheb2d`, plus: - `qft_tol` : truncation tolerance inside `conjugate_by_qft`. Default `1e-9`. - `qft_maxdim` : max bond dimension inside `conjugate_by_qft`. Default `100`. + +!!! warning "2D momenta" + The diagonal is taken after one QFT over the linear index `n = ix + iy·2^Lx`, as in + [`get_bands`](@ref), so on a 2D lattice it is not `χ₀(kx, ky, ω)`: kx and ky are mixed, + with a shear. The same holds for `get_bubble_diag_cheb2d_svd` and + `get_bubble_diag_cheb2d_tucker`. 1D is not affected. """ function get_bubble_diag_cheb2d(H1::TBHamiltonian, H2::TBHamiltonian, ωlist::AbstractVector{<:Real}; From d73a837147845cbe7b26d4f11fcbf49f37362e2a Mon Sep 17 00:00:00 2001 From: Anouar Moustaj Date: Fri, 13 Nov 2026 13:09:01 +0200 Subject: [PATCH 22/22] Release 0.2.1 Bump the version to 0.2.1 and date the changelog section. 0.2.1 keeps the v0.2 API (fixes and additive keywords only); the Changed results entries are bug fixes that move numbers. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 +++++- Project.toml | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 76e6d1e..b6887fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,11 @@ reading of semantic versioning: before 1.0, a change in the minor number (0.1 is breaking, and a change in the last number (0.1.0 → 0.1.1) adds features or fixes bugs without breaking the API. -## [Unreleased] +## [0.2.1] — 2026-11-13 + +This release keeps the v0.2 API. Every entry under **Changed results** is a bug fix +that moves numbers; reproduce an old result by pinning v0.2.0 or, where the entry names +one, by passing its keyword. ### Added diff --git a/Project.toml b/Project.toml index 323f797..446ff81 100644 --- a/Project.toml +++ b/Project.toml @@ -1,6 +1,6 @@ name = "TensorBinding" uuid = "3b6805fc-d418-45a2-b1ea-024139a4a543" -version = "0.2.0" +version = "0.2.1" authors = ["Tiago Antao, Anouar Moustaj, Yitao Sun"] [deps]