diff --git a/src/Ansatz.jl b/src/Ansatz.jl index c7a96904d..e936a5d9e 100644 --- a/src/Ansatz.jl +++ b/src/Ansatz.jl @@ -290,14 +290,18 @@ function truncate!(::NonCanonical, tn::AbstractAnsatz, bond; threshold, maxdim, spectrum = parent(tensors(tn; bond)) - maxdim = isnothing(maxdim) ? size(tn, virtualind) : maxdim + maxdim = isnothing(maxdim) ? size(tn, virtualind) : min(maxdim, length(spectrum)) extent = if isnothing(threshold) 1:maxdim else - 1:something(findfirst(1:maxdim) do i + # Find the first index where the condition is met + found_index = findfirst(1:maxdim) do i abs(spectrum[i]) < threshold - end - 1, maxdim) + end + + # If no index is found, return 1:length(spectrum), otherwise calculate the range + 1:(isnothing(found_index) ? maxdim : found_index - 1) end slice!(tn, virtualind, extent) @@ -312,9 +316,7 @@ function truncate!(::MixedCanonical, tn::AbstractAnsatz, bond; threshold, maxdim end function truncate!(::Canonical, tn::AbstractAnsatz, bond; threshold, maxdim) - truncate!(NonCanonical(), tn, bond; threshold, maxdim, compute_local_svd=false) - # requires a sweep to recanonize the TN - return canonize!(tn) + return truncate!(NonCanonical(), tn, bond; threshold, maxdim, compute_local_svd=false) end overlap(a::AbstractAnsatz, b::AbstractAnsatz) = contract(merge(a, copy(b)')) diff --git a/test/MPS_test.jl b/test/MPS_test.jl index 86db308c7..a7c6c3a11 100644 --- a/test/MPS_test.jl +++ b/test/MPS_test.jl @@ -104,6 +104,10 @@ using LinearAlgebra singular_values = tensors(ψ; between=(site"2", site"3")) truncated = truncate(ψ, [site"2", site"3"]; threshold=singular_values[2] + 0.1) @test size(truncated, inds(truncated; bond=[site"2", site"3"])) == 1 + + # If maxdim > size(spectrum), the bond dimension is not truncated + truncated = truncate(ψ, [site"2", site"3"]; maxdim=4) + @test size(truncated, inds(truncated; bond=[site"2", site"3"])) == 2 end @testset "norm" begin