Skip to content

Commit d288385

Browse files
Add FiniteMPS getindex (#218)
* add `getindex(::FiniteMPS, ::Int)` * add `getindex(::FiniteMPS, ::AbstractUnitRange)` * format
1 parent 71b709b commit d288385

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

src/states/finitemps.jl

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,30 @@ end
282282

283283
Base.checkbounds(::Type{Bool}, ψ::FiniteMPS, i::Integer) = 1 <= i <= length(ψ)
284284

285+
Base.@propagate_inbounds function Base.getindex::FiniteMPS, i::Int)
286+
c = ψ.center
287+
288+
@boundscheck begin
289+
checkbounds(ψ, i)
290+
end
291+
292+
if ishalfodd(c)
293+
c -= 1 / 2
294+
end
295+
296+
return if i > Int(c)
297+
ψ.AR[i]
298+
elseif i == Int(c)
299+
ψ.AC[i]
300+
else
301+
ψ.AL[i]
302+
end
303+
end
304+
305+
@inline function Base.getindex::FiniteMPS, I::AbstractUnitRange)
306+
return Base.getindex.(Ref(ψ), I)
307+
end
308+
285309
function Base.convert(::Type{TensorMap}, ψ::FiniteMPS)
286310
T = foldl.AR[2:end]; init=first.AC)) do x, y
287311
return _transpose_front(x * _transpose_tail(y))

test/states.jl

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,30 @@ end
4646
@test dot(ψ_small, ψ_small2) dot(ψ_small, ψ_small)
4747
end
4848

49+
@testset "FiniteMPS center + (slice) indexing" begin
50+
L = 11
51+
ψ = FiniteMPS(L, ℂ^2, ℂ^16)
52+
53+
ψ.AC[6] # moving the center to site 6
54+
55+
@test ψ.center == 6
56+
57+
@test ψ[5] == ψ.ALs[5]
58+
@test ψ[6] == ψ.ACs[6]
59+
@test ψ[7] == ψ.ARs[7]
60+
61+
@test ψ[5:7] ==.ALs[5], ψ.ACs[6], ψ.ARs[7]]
62+
63+
@inferred ψ[5]
64+
65+
@test_throws BoundsError ψ[0]
66+
@test_throws BoundsError ψ[L + 1]
67+
68+
ψ.C[6] = randn(ComplexF64, space.C[6])) # setting the center between sites 6 and 7
69+
@test ψ.center == 13 / 2
70+
@test ψ[5:7] ==.ALs[5], ψ.ACs[6], ψ.ARs[7]]
71+
end
72+
4973
@testset "InfiniteMPS ($(sectortype(D)), $elt)" for (D, d, elt) in
5074
[(ℙ^10, ℙ^2, ComplexF64),
5175
(Rep[U₁](1 => 3), Rep[U₁](0 => 1),

0 commit comments

Comments
 (0)