Skip to content

Commit ae029d4

Browse files
author
Adria Labay
committed
skip use of cartesianindex to reduce allocations
1 parent 9910a34 commit ae029d4

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 (:(+), :(-), :(*), :(/), :(^))
@@ -775,32 +777,25 @@ function mean_occupation(ψ::QuantumObject{T,KetQuantumObject}) where {T}
775777
if length.dims) == 1
776778
return mapreduce(k -> abs2(ψ[k]) * (k - 1), +, 1:ρ.dims[1])
777779
else
778-
R = CartesianIndices((ψ.dims...,))
779-
off = circshift.dims, 1)
780-
off[end] = 1
780+
t = Tuple.dims)
781781

782-
x = sum(R) do j
783-
j_tuple = Tuple(j) .- 1
784-
J = dot(j_tuple, off) + 1
785-
return abs2(ψ[J]) * prod(j_tuple)
782+
x = 0.0
783+
for J in eachindex.data)
784+
x += abs2(ψ[J]) * prod(Base._ind2sub(t, J) .- 1)
786785
end
787-
788-
return x
786+
return real(x)
789787
end
790788
end
791789

792790
function mean_occupation::QuantumObject{T,OperatorQuantumObject}) where {T}
793791
if length.dims) == 1
794792
return real(mapreduce(k -> ρ[k, k] * (k - 1), +, 1:ρ.dims[1]))
795793
else
796-
R = CartesianIndices((ρ.dims...,))
797-
off = circshift.dims, 1)
798-
off[end] = 1
794+
t = Tuple.dims)
799795

800-
x = sum(R) do j
801-
j_tuple = Tuple(j) .- 1
802-
J = dot(j_tuple, off) + 1
803-
return ρ[J, J] * prod(j_tuple)
796+
x = 0.0im
797+
for J in eachindex.data[:, 1])
798+
x += ρ[J, J] * prod(Base._ind2sub(t, J) .- 1)
804799
end
805800

806801
return real(x)

0 commit comments

Comments
 (0)