Skip to content

Commit

Permalink
Fix truncate function and add small test
Browse files Browse the repository at this point in the history
  • Loading branch information
jofrevalles committed Nov 19, 2024
1 parent 1a9540d commit da68655
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 6 deletions.
14 changes: 8 additions & 6 deletions src/Ansatz.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)'))
Expand Down
4 changes: 4 additions & 0 deletions test/MPS_test.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit da68655

Please sign in to comment.