Skip to content

Commit 32d082d

Browse files
author
Adria Labay
committed
skip use of cartesianindex to reduce allocations
1 parent 6b57615 commit 32d082d

File tree

1 file changed

+11
-16
lines changed

1 file changed

+11
-16
lines changed

src/qobj/arithmetic_and_attributes.jl

Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ export proj, ptrace, purity, permute
88
export tidyup, tidyup!
99
export get_data, get_coherence, remove_coherence, mean_occupation
1010

11+
import Base: _ind2sub
12+
1113
# Broadcasting
1214
Base.broadcastable(x::QuantumObject) = x.data
1315
for op in (:(+), :(-), :(*), :(/), :(^))
@@ -741,32 +743,25 @@ function mean_occupation(ψ::QuantumObject{T,KetQuantumObject}) where {T}
741743
if length.dims) == 1
742744
return mapreduce(k -> abs2(ψ[k]) * (k - 1), +, 1:ρ.dims[1])
743745
else
744-
R = CartesianIndices((ψ.dims...,))
745-
off = circshift.dims, 1)
746-
off[end] = 1
746+
t = Tuple.dims)
747747

748-
x = sum(R) do j
749-
j_tuple = Tuple(j) .- 1
750-
J = dot(j_tuple, off) + 1
751-
return abs2(ψ[J]) * prod(j_tuple)
748+
x = 0.0
749+
for J in eachindex.data)
750+
x += abs2(ψ[J]) * prod(Base._ind2sub(t, J) .- 1)
752751
end
753-
754-
return x
752+
return real(x)
755753
end
756754
end
757755

758756
function mean_occupation::QuantumObject{T,OperatorQuantumObject}) where {T}
759757
if length.dims) == 1
760758
return real(mapreduce(k -> ρ[k, k] * (k - 1), +, 1:ρ.dims[1]))
761759
else
762-
R = CartesianIndices((ρ.dims...,))
763-
off = circshift.dims, 1)
764-
off[end] = 1
760+
t = Tuple.dims)
765761

766-
x = sum(R) do j
767-
j_tuple = Tuple(j) .- 1
768-
J = dot(j_tuple, off) + 1
769-
return ρ[J, J] * prod(j_tuple)
762+
x = 0.0im
763+
for J in eachindex.data[:, 1])
764+
x += ρ[J, J] * prod(Base._ind2sub(t, J) .- 1)
770765
end
771766

772767
return real(x)

0 commit comments

Comments
 (0)