diff --git a/src/tensors/tensoroperations.jl b/src/tensors/tensoroperations.jl index 91b5d6f..9e9a8ea 100644 --- a/src/tensors/tensoroperations.jl +++ b/src/tensors/tensoroperations.jl @@ -214,6 +214,37 @@ function TK.trace_permute!( return tdst end +# TensorKit's `planartrace!` only goes through `trace_permute!` for bosonic sectors, the others +# write into the subblocks of `tdst`, which loses what belongs to blocks a sparse `tdst` doesn't have +function TK.planartrace!( + tdst::AbstractBlockTensorMap, tsrc::AbstractBlockTensorMap, + (p₁, p₂)::Index2Tuple, (q₁, q₂)::Index2Tuple, + α::Number, β::Number, backend, allocator + ) + TK.check_spacetype(tdst, tsrc) + (N₃ = length(q₁)) == length(q₂) || + throw(IndexError("number of trace indices does not match")) + + @boundscheck begin + space(tdst) == TK.select(space(tsrc), (p₁, p₂)) || + throw(SpaceMismatch("trace: tsrc = $(codomain(tsrc))←$(domain(tsrc)), + tdst = $(codomain(tdst))←$(domain(tdst)), p₁ = $(p₁), p₂ = $(p₂)")) + all(i -> space(tsrc, q₁[i]) == dual(space(tsrc, q₂[i])), 1:N₃) || + throw(SpaceMismatch("trace: tsrc = $(codomain(tsrc))←$(domain(tsrc)), + q₁ = $(q₁), q₂ = $(q₂)")) + end + + isone(β) || (iszero(β) ? zerovector!(tdst) : scale!(tdst, β)) + @inbounds for (Isrc, vsrc) in nonzero_pairs(tsrc) + TT.getindices(Isrc.I, q₁) == TT.getindices(Isrc.I, q₂) || continue + Idst = CartesianIndex(TT.getindices(Isrc.I, (p₁..., p₂...))) + _addblock!(tdst, Idst, One(), allocator) do c, γ + TK.planartrace!(c, vsrc, (p₁, p₂), (q₁, q₂), α, γ, backend, allocator) + end + end + return tdst +end + # PlanarOperations # ---------------- diff --git a/test/linalg/tensoroperations.jl b/test/linalg/tensoroperations.jl index 681c748..2ddc003 100644 --- a/test/linalg/tensoroperations.jl +++ b/test/linalg/tensoroperations.jl @@ -107,6 +107,26 @@ end end end +# for non-bosonic sectors `planartrace!` doesn't go through `trace_permute!` +@testset "planartrace! (fermionic, B sparse = $Bsparse, C sparse = $Csparse)" for Bsparse in (false, true), + Csparse in (false, true) + F = Vect[FermionParity] + V1, V2, V3 = F(0 => 1, 1 => 1) ⊞ F(0 => 2), F(1 => 1) ⊞ F(0 => 1, 1 => 2), F(0 => 2, 1 => 1) ⊞ F(1 => 1) + T = ComplexF64 + B = Bsparse ? sprand(T, V1 ⊗ V2 ← V3 ⊗ V2, 0.6) : randn(T, V1 ⊗ V2 ← V3 ⊗ V2) + Bd = convert(TensorMap, B) + @planar C1[a; b] := B[a c; b c] + @planar C2[a; b] := Bd[a c; b c] + @test convert(TensorMap, C1) ≈ C2 + for β in (zero(T), one(T), randn(T)) + α = randn(T) + C = Csparse ? sprand(T, V1 ← V3, 0.5) : randn(T, V1 ← V3) + Cd = TensorKit.planartrace!(convert(TensorMap, C), Bd, ((1,), (3,)), ((2,), (4,)), α, β) + @test TensorKit.planartrace!(C, B, ((1,), (3,)), ((2,), (4,)), α, β) === C + @test convert(TensorMap, C) ≈ Cd + end +end + ## @testset "tensortrace" begin