Skip to content

Commit 93300cb

Browse files
authored
Fix bug in QN where sectors sometimes aren't sorted (#1659)
1 parent 2b53ddf commit 93300cb

File tree

3 files changed

+30
-21
lines changed

3 files changed

+30
-21
lines changed

Project.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
name = "ITensors"
22
uuid = "9136182c-28ba-11e9-034c-db9fb085ebd5"
33
authors = ["Matthew Fishman <[email protected]>", "Miles Stoudenmire <[email protected]>"]
4-
version = "0.9.6"
4+
version = "0.9.7"
55

66
[deps]
77
Adapt = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"

src/lib/QuantumNumbers/src/qn.jl

Lines changed: 25 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -176,29 +176,34 @@ function Base.:(-)(qn::QN)
176176
end
177177

178178
function Base.:(+)(a::QN, b::QN)
179-
!isactive(b[1]) && return a
180-
ma = MQNStorage(data(a))
181-
@inbounds for nb in 1:maxQNs
182-
!isactive(b[nb]) && break
183-
bname = name(b[nb])
184-
for na in 1:maxQNs
185-
aname = name(a[na])
186-
if !isactive(ma[na])
187-
ma[na] = b[nb]
188-
break
189-
elseif name(ma[na]) == bname
190-
ma[na] = ma[na] + b[nb]
191-
break
192-
elseif (bname < aname) && (na == 1 || bname > name(ma[na - 1]))
193-
for j in maxQNs:-1:(na + 1)
194-
ma[j] = ma[j - 1]
195-
end
196-
ma[na] = b[nb]
197-
break
179+
na = nactive(a)
180+
iszero(na) && return b
181+
nb = nactive(b)
182+
iszero(nb) && return a
183+
sectors_a = data(a)
184+
sectors_b = data(b)
185+
msectors_c = MQNStorage(sectors_a)
186+
nc = na
187+
@inbounds for ib in 1:nb
188+
sector_b = sectors_b[ib]
189+
found = false
190+
for ia in 1:na
191+
sector_a = sectors_a[ia]
192+
if name(sector_b) == name(sector_a)
193+
msectors_c[ia] = sector_a + sector_b
194+
found = true
195+
continue
198196
end
199197
end
198+
if !found
199+
if nc >= length(msectors_c)
200+
error("Cannot add QN, maximum number of QNVals reached")
201+
end
202+
msectors_c[nc += 1] = sector_b
203+
end
200204
end
201-
return QN(QNStorage(ma))
205+
sort!(view(msectors_c, 1:nc); by=name)
206+
return QN(msectors_c)
202207
end
203208

204209
Base.:(-)(a::QN, b::QN) = (a + (-b))

test/base/test_qn.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,10 @@ import ITensors: nactive
103103
@test QN("Sz", 2) - QN() == QN("Sz", 2)
104104
@test QN() - QN(("Sz", 2), ("N", 1)) == QN(("Sz", -2), ("N", -1))
105105
@test QN("N", 1) - QN("Sz", 2) == QN(("N", 1), ("Sz", -2))
106+
107+
# Regression test for https://github.com/ITensor/ITensors.jl/issues/1658
108+
@test QN("S3", 3) + QN(("S1", 1), ("S2", 2)) == QN(("S1", 1), ("S2", 2), ("S3", 3))
109+
@test QN(("S1", 1), ("S2", 2)) + QN("S3", 3) == QN(("S1", 1), ("S2", 2), ("S3", 3))
106110
end
107111

108112
@testset "Ordering" begin

0 commit comments

Comments
 (0)