• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

RimuQMC / Rimu.jl / 12369488912

17 Dec 2024 08:51AM UTC coverage: 94.306% (-0.3%) from 94.567%
12369488912

Pull #300

github

mtsch
fix doctests
Pull Request #300: Fix normalisation in `single_particle_density`

3 of 3 new or added lines in 1 file covered. (100.0%)

97 existing lines in 22 files now uncovered.

6907 of 7324 relevant lines covered (94.31%)

13567973.06 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

97.13
/src/BitStringAddresses/bitstring.jl
1
"""
2
    num_chunks(::Val{B})
3

4
Determine the number and type of chunks needed to store `B` bits.
5
"""
6
function num_chunks(::Val{B}) where {B}
32,571,526✔
7
    if B ≤ 0
32,571,527✔
8
        throw(ArgumentError("`B` must be positive!"))
2✔
9
    elseif B ≤ 8
32,571,525✔
10
        return 1, UInt8
1,425,957✔
11
    elseif B ≤ 16
31,145,568✔
12
        return 1, UInt16
27,350,628✔
13
    elseif B ≤ 32
3,794,940✔
14
        return 1, UInt32
1,370,154✔
15
    else
16
        return (B - 1) ÷ 64 + 1, UInt64
2,424,787✔
17
    end
18
end
19

20
"""
21
    check_bitstring_typeparams(::Val{B}, ::Val{N})
22

23
Check if number of bits `B` is consistent with number of chunks `N`. Throw an error if not.
24
"""
25
function check_bitstring_typeparams(::Val{B}, ::Val{N}, ::Type{UInt64}) where {B,N}
1,633,754✔
26
    if B > N * 64
1,633,754✔
27
        error("$B bits do not fit into $N 64-bit chunks")
×
28
    elseif B ≤ (N - 1) * 64
1,633,754✔
29
        error("$B bits fit into $(N - 1) 64-bit chunks, but $N chunks were provided")
×
30
    end
31
end
32
function check_bitstring_typeparams(::Val{B}, ::Val{1}, ::Type{T}) where {B,T}
775,355,173✔
33
    if B > sizeof(T) * 8
775,506,122✔
34
        error("$B bits do not fit into a $(sizeof(T) * 8)-bit chunk")
×
35
    end
36
end
37
function check_bitstring_typeparams(::Val{B}, ::Val{1}, ::Type{UInt64}) where {B}
4,675,153✔
38
    if B > 64
4,675,153✔
39
        error("$B bits do not fit into a 64-bit chunk")
×
40
    end
41
end
42
function check_bitstring_typeparams(::Val{B}, ::Val{N}, ::Type{T}) where {B,N,T}
×
43
    error("Only `UInt64` is supported for multi-bit chunks")
×
44
end
45

46
"""
47
    BitString{B,N,T<:Unsigned}
48

49
Type for storing bitstrings of static size. Holds `B` bits in `N` chunks, where each chunk is
50
of type `T`.
51

52
`N` is chosen automatically to accommodate `B` bits as efficiently as possible.
53

54
# Constructors
55

56
* `BitString{B,N,T}(::SVector{N,T})`: unsafe constructor. Does not check for ghost bits.
57

58
* `BitString{B,N,T}(i::T)`: as above, but sets `i` as the rightmost chunk.
59

60
* `BitString{B}(::Integer)`: Convert integer to `BitString`. Integer is truncated to the
61
  correct number of bits.
62

63
"""
64
struct BitString{B,N,T<:Unsigned}
65
    chunks::SVector{N,T}
66

67
    # This constructor is only to be used internally. It doesn't check for ghost bits.
68
    function BitString{B,N,T}(s::SVector{N,T}) where {B,N,T}
234,725,870✔
69
        check_bitstring_typeparams(Val(B), Val(N), T)
234,952,257✔
70
        return new{B,N,T}(s)
235,293,672✔
71
    end
72
    function BitString{B,N,T}(i::T) where {B,N,T<:Unsigned}
547,591,014✔
73
        check_bitstring_typeparams(Val(B), Val(N), T)
547,592,938✔
74
        return new{B,N,T}(setindex(zero(SVector{N,UInt64}), i, N))
547,655,068✔
75
    end
76
end
77

78
###
79
### Basic properties.
80
###
81
"""
82
    num_chunks(::Type{<:BitString})
83
    num_chunks(s::BitString)
84

85
Number of chunks in bitstring. Equivalent to `length(chunks(s))`.
86
"""
87
num_chunks(::Type{<:BitString{<:Any,N}}) where {N} = N
136,170,291✔
88

89
"""
90
    chunk_type(::Type{<:BitString})
91
    chunk_type(s::BitString)
92

93
Type of unsigned integer used to store the chunks.
94
"""
95
chunk_type(::Type{<:BitString{<:Any,<:Any,T}}) where {T} = T
114,187,331✔
96

97
"""
98
    num_bits(::Type{<:BitString})
99
    num_bits(s::BitString)
100

101
Total number of bits stored in bitstring.
102
"""
103
num_bits(::Type{<:BitString{B}}) where {B} = B
304,783✔
104

105
"""
106
    top_chunk_bits(::Type{<:BitString})
107
    top_chunk_bits(s::BitString)
108

109
Number of bits stored in top chunk. Equivalent to `chunk_bits(s, 1)`.
110
"""
111
function top_chunk_bits(::Type{<:BitString{B}}) where B
113,089,027✔
112
    return B % 64 == 0 ? 64 : B % 64
113,096,525✔
113
end
114

115
for f in (:num_chunks, :chunk_type, :num_bits, :top_chunk_bits)
116
    @eval $f(s::BitString) = $f(typeof(s))
156,481,759✔
117
end
118

119
"""
120
    chunks(s::BitString)
121

122
`SVector` that stores the chunks of `s`.
123
"""
124
chunks(s::BitString) = s.chunks
114,210,081✔
125

126
"""
127
    chunks_bits(::Type{<:BitString}, i)
128
    chunks_bits(s, i)
129

130
Number of bits in the `i`-th chunk of `s`.
131
"""
132
chunk_bits(s, i) = chunk_bits(typeof(s), i)
42,395,706✔
133
chunk_bits(::Type{<:BitString{B,1}}, _) where {B} = B
39,641,522✔
134
function chunk_bits(::Type{S}, i) where {S<:BitString}
48,709,116✔
135
    return ifelse(i == 1, top_chunk_bits(S), 64)
48,709,116✔
136
end
137

138
function ghost_bit_mask(::Type{S}) where S<:BitString
55,949,903✔
139
    T = chunk_type(S)
55,954,205✔
140
    unused_bits = sizeof(T) * 8 - top_chunk_bits(S)
55,934,128✔
141
    return ~zero(T) >>> unused_bits
55,947,529✔
142
end
143

144
"""
145
    remove_ghost_bits(s::BitString)
146

147
Remove set bits outside data field if any are present.
148

149
See also: [`has_ghost_bits`](@ref).
150
"""
151
function remove_ghost_bits(s::S) where {S<:BitString}
426,298✔
152
    mask = ghost_bit_mask(S)
426,298✔
153
    return S(setindex(s.chunks, s.chunks[1] & mask, 1))
426,298✔
154
end
155

156
@inline function remove_ghost_bits(s::S) where {S<:BitString{<:Any,1}}
55,483,846✔
157
    mask = ghost_bit_mask(S)
55,509,662✔
158
    return S(chunks(s) .& mask)
55,504,573✔
159
end
160

161
"""
162
    has_ghost_bits(s::BitString)
163

164
Check for bits outside data field.
165

166
See also: [`remove_ghost_bits`](@ref).
167
"""
168
function has_ghost_bits(s::S) where {S<:BitString}
40✔
169
    top = first(chunks(s))
40✔
170
    mask = ~zero(UInt64) << top_chunk_bits(S)
40✔
171
    return top & mask > 0
40✔
172
end
173

174
###
175
### Alternative/useful constructors. These are not super efficient, but they are safe.
176
###
177
function BitString{B}(i::Union{Int128,Int64,Int32,Int16,Int8}) where {B}
569,078✔
178
    return remove_ghost_bits(BitString{B}(unsigned(i)))
569,078✔
179
end
180
function BitString{B}(i::Union{UInt64,UInt32,UInt16,UInt8}) where {B}
569,093✔
181
    N, T = num_chunks(Val(B))
569,093✔
182
    s = setindex(zero(SVector{N,T}), T(i), N)
569,093✔
183
    return remove_ghost_bits(BitString{B,N,T}(s))
569,093✔
184
end
185
function BitString{B}(i::UInt128) where {B}
19✔
186
    N, T = num_chunks(Val(B))
19✔
187
    left = i >>> 0x40 % T # left will only be used if T == UInt64 and N > 1
19✔
188
    right = i  % T
19✔
189
    s = ntuple(Val(N)) do i
19✔
190
        i == N ? right : i == N - 1 ? left : zero(T)
39✔
191
    end
192
    return remove_ghost_bits(BitString{B,N,T}(SVector{N,T}(s)))
19✔
193
end
194
function BitString{B}(i::BigInt) where {B}
12✔
195
    N, T = num_chunks(Val(B))
12✔
196
    s = zero(SVector{N,T})
12✔
197
    j = N
12✔
198
    while i ≠ 0
35✔
199
        chunk = i & typemax(T) % T
46✔
200
        i >>>= 64 # Can use 64 here, as only 1-chunk addresses can be smaller
23✔
201
        s = setindex(s, chunk, j)
23✔
202
        j -= 1
23✔
203
    end
23✔
204
    return remove_ghost_bits(BitString{B,N,T}(s))
12✔
205
end
206

207
function Base.zero(S::Type{<:BitString{B}}) where {B}
32,002,370✔
208
    N, T = num_chunks(Val(B))
32,002,371✔
209
    BitString{B,N,T}(zero(SVector{N,T}))
32,002,377✔
210
end
211
Base.zero(s::BitString) = zero(typeof(s))
32,002,358✔
212

213
function Base.show(io::IO, s::BitString{B,N}) where {B,N}
6✔
214
    str = join(map(i -> repr(i)[3:end], s.chunks), '_')
20✔
215

216
    print(io, "BitString{$B}(big\"0x", str, "\")")
6✔
217
end
218
Base.bitstring(s::BitString{B}) where {B} = join(bitstring.(s.chunks))[(end - B + 1):end]
×
219

220
###
221
### Operations on BitStrings
222
###
223
for op in (:⊻, :&, :|)
224
    @eval (Base.$op)(l::S, r::S) where S<:BitString = S($op.(l.chunks, r.chunks))
55,235,537✔
225
end
226
Base.:~(s::S) where S<:BitString = remove_ghost_bits(S(.~(s.chunks)))
42✔
227

228
Base.count_ones(s::BitString) = sum(count_ones, s.chunks)
453,736✔
229
Base.count_zeros(s::BitString) = num_bits(s) - count_ones(s)
23✔
230

231
function _trailing(f, s::BitString)
39,641,412✔
232
    result = 0
39,641,437✔
233
    i = 0
39,641,858✔
234
    # Idea: if all whole chunk is the same digit, you have to look at the next one.
235
    # This gets compiled away if N=1
236
    for i in num_chunks(s):-1:1
39,641,832✔
237
        r = f(s.chunks[i])
39,641,344✔
238
        result += r
39,640,539✔
239
        r == chunk_bits(s, i) || break
39,640,223✔
UNCOV
240
    end
×
241
    # If top chunk occupies the whole integer, result will always be smaller or equal to B.
242
    if f ≢ trailing_ones && top_chunk_bits(s) ≠ 64
39,641,736✔
243
        return min(num_bits(s), result)
23✔
244
    else
245
        return result
39,641,461✔
246
    end
247
end
248

249
function _leading(f, s::BitString)
4,267,443✔
250
    N = sizeof(chunk_type(s)) * 8
4,267,431✔
251
    # First chunk is a special case - we have to ignore the empty space before the string.
252
    result = min(f(s.chunks[1] << (N - top_chunk_bits(s))), top_chunk_bits(s))
4,267,399✔
253

254
    # This gets compiled away if N=1
255
    if num_chunks(s) > 1 && result == top_chunk_bits(s)
4,267,290✔
256
        for i in 2:num_chunks(s)
14✔
257
            r = f(s.chunks[i])
14✔
258
            result += r
14✔
259
            r == 64 || break
14✔
260
        end
×
261
    end
262
    return result
4,267,326✔
263
end
264

265
Base.trailing_ones(s::BitString) = _trailing(trailing_ones, s)
39,641,011✔
266
Base.trailing_zeros(s::BitString) = _trailing(trailing_zeros, s)
23✔
267
Base.leading_ones(s::BitString) = _leading(leading_ones, s)
4,267,294✔
268
Base.leading_zeros(s::BitString) = _leading(leading_zeros, s)
23✔
269

270
@generated function _right_shift(s::S, k) where {S<:BitString}
150✔
271
    N = num_chunks(S)
28✔
272
    quote
28✔
273
        $(Expr(:meta, :inline))
142✔
274
        # equivalent to d, r = divrem(k, 64)
275
        d = k >>> 0x6
142✔
276
        r = k & 63
142✔
277
        ri = 64 - r
142✔
278
        mask = ~zero(UInt64) >>> ri # 2^r-1 # 0b0...01...1 with `r` 1s
142✔
279
        c = chunks(s)
142✔
280

281
        @nif $(N + 1) l -> (d < l) l -> (
150✔
282
            S(SVector((@ntuple l - 1 k -> zero(UInt64))... ,c[1] >>> r,
283
                      (@ntuple $N-l q -> (c[q + 1] >>> r | ((c[q] & mask) << ri)))...
284
                      ))
285
        ) l -> (
286
            return zero(S)
287
        )
288
    end
289
end
290

291
function _left_shift(s::S, k) where {S<:BitString}
3,725✔
292
    result = zeros(MVector{num_chunks(S),UInt64})
3,725✔
293
    # d, r = divrem(k, 64)
294
    d = k >>> 0x6
3,725✔
295
    r = k & 63
3,725✔
296

297
    shift = s.chunks .<< (r % UInt64)
3,725✔
298
    carry = s.chunks .>>> ((64 - r) % UInt64)
3,725✔
299

300
    for i in d + 1:length(result)
3,726✔
301
        @inbounds result[i - d] = shift[i] | get(carry, i + 1, zero(UInt64))
13,626✔
302
    end
23,528✔
303
    # This bit removes ghost bits.
304
    result[1] &= ghost_bit_mask(S)
3,725✔
305
    return S(SVector(result))
3,725✔
306
end
307

308
Base.:>>(s::BitString, k) = k ≥ 0 ? _right_shift(s, k) : _left_shift(s, -k)
131✔
309
Base.:<<(s::BitString, k) = k > 0 ? _left_shift(s, k) : _right_shift(s, -k)
3,745✔
310
Base.:>>>(s::BitString, k) = s >> k
36,267,876✔
311

312
# remove ghost bits must be applied to both because k might be negative.
313
Base.:>>(s::S, k) where S<:BitString{<:Any,1} = remove_ghost_bits(S(s.chunks .>> k))
28✔
314
Base.:>>(s::S, k::Unsigned) where S<:BitString{<:Any,1} = S(s.chunks .>> k)
36,268,170✔
315
Base.:<<(s::S, k) where S<:BitString{<:Any,1} = remove_ghost_bits(S(s.chunks .<< k))
54,733,781✔
316

317
function Base.isless(s1::B, s2::B) where {B<:BitString}
136,772✔
318
    for i in 1:num_chunks(B)
136,772✔
319
        if chunks(s1)[i] ≠ chunks(s2)[i]
136,772✔
320
            return chunks(s1)[i] < chunks(s2)[i]
135,584✔
321
        end
322
    end
1,188✔
323
    return false
1,188✔
324
end
325
Base.isodd(s::BitString) = isodd(chunks(s)[end])
7,162,254✔
326
Base.iseven(s::BitString) = iseven(chunks(s)[end])
×
327

328
# For compatibility. Changing any of the hashes will slightly change results and make the
329
# tests fail.
330
Base.hash(b::BitString{<:Any,1}, h::UInt) = hash(b.chunks[1], h)
930,414,307✔
331
Base.hash(b::BitString, h::UInt) = hash(b.chunks.data, h)
×
332

333
"""
334
    partial_left_shift(bs::BitString, i, j)
335

336
Shift a part of the bitstring left by one place with boundaries `i < j`.
337
In a `BoseFS` bitstring, it moves a particle at offset `i` to the position at
338
offset `j`.
339

340
See also: [`excitation`](@ref), [`partial_right_shift`](@ref).
341
"""
342
function partial_left_shift(chunk::T, i, j) where {T<:Unsigned}
230,104,698✔
343
    # Mask of one spanning from i to j
344
    mask = (T(1) << T(j - i + 1) - T(1)) << T(i)
230,104,697✔
345
    # Shift the part of the string that needs to be shifted, ensure a one is added at the end
346
    # swap shift to move in other direction
347
    #println(bitstring(mask))
348
    shifted_part = ((chunk & mask) << 0x1) & mask
230,104,704✔
349
    # Leave the rest intact
350
    intact_part = chunk & ~mask
230,104,711✔
351

352
    return shifted_part | intact_part | T(1) << T(i)
230,104,709✔
353
end
354

355
"""
356
    partial_right_shift(bs::BitString, i, j)
357

358
Shift a part of the bitstring right by one place with boundaries `i < j`.
359
In a `BoseFS` bitstring, it moves a particle at offset `j` to the position at
360
offset `i`.
361

362
See also: [`partial_left_shift`](@ref), [`excitation`](@ref).
363
"""
364
function partial_right_shift(chunk::T, i, j) where {T<:Unsigned}
230,564,743✔
365
    # Mask of one spanning from i to j
366
    mask = (T(1) << T(j - i + 1) - T(1)) << T(i)
230,564,731✔
367
    # Shift the part of the string that needs to be shifted, ensure a one is added at the end
368
    # swap shift to move in other direction
369
    shifted_part = ((chunk & mask) >> 0x1) & mask
230,564,743✔
370
    # Leave the rest intact
371
    intact_part = chunk & ~mask
230,564,741✔
372
    #println(lpad("↑" * " "^j, length(bitstring(chunk))))
373

374
    return shifted_part | intact_part | T(1) << T(j)
230,564,732✔
375
end
376

377
function partial_left_shift(bs::S, i, j) where {S<:BitString{<:Any,1}}
229,718,970✔
378
    return S(partial_left_shift(bs.chunks[1], i, j))
229,718,966✔
379
end
380

381
function partial_right_shift(bs::S, i, j) where {S<:BitString{<:Any,1}}
230,230,411✔
382
    return S(partial_right_shift(bs.chunks[1], i, j))
230,230,422✔
383
end
384

385
function partial_left_shift(bs::S, i, j) where {N,S<:BitString{<:Any,N}}
231,358✔
386
    result = MVector(bs.chunks)
231,358✔
387
    lo_idx = N - (i >>> 0x6)
231,358✔
388
    hi_idx = N - (j >>> 0x6)
231,358✔
389
    lo_off = i & 63
231,358✔
390
    hi_off = j & 63
231,358✔
391
    @inbounds if hi_idx == lo_idx
231,358✔
392
        result[hi_idx] = partial_left_shift(result[hi_idx], lo_off, hi_off)
76,989✔
393
    else
394
        # Top part first.
395
        chunk = result[hi_idx]
154,369✔
396
        chunk = partial_left_shift(chunk, 0, hi_off)
154,369✔
397
        # Carry bit.
398
        chunk &= -UInt(1) << 0x1
154,369✔
399
        chunk |= result[hi_idx + 1] >> 63
154,369✔
400
        result[hi_idx] = chunk
154,369✔
401

402
        idx = hi_idx + 1
154,369✔
403
        while idx < lo_idx
260,519✔
404
            chunk = result[idx]
106,150✔
405
            chunk <<= 0x1
106,150✔
406
            chunk |= result[idx + 1] >> 63
106,150✔
407
            result[idx] = chunk
106,150✔
408
            idx += 1
106,150✔
409
        end
106,150✔
410

411
        # Bottom part.
412
        chunk = result[lo_idx]
154,369✔
413
        chunk = partial_left_shift(chunk, lo_off, 64)
154,369✔
414
        result[lo_idx] = chunk
154,369✔
415
    end
416
    return S(SVector(result))
231,358✔
417
end
418

419
function partial_right_shift(bs::S, i, j) where {N,S<:BitString{<:Any,N}}
201,210✔
420
    result = MVector(bs.chunks)
201,210✔
421
    lo_idx = N - (i >>> 0x6)
201,210✔
422
    hi_idx = N - (j >>> 0x6)
201,210✔
423
    lo_off = i & 63
201,210✔
424
    hi_off = j & 63
201,210✔
425
    @inbounds if hi_idx == lo_idx
201,210✔
426
        result[hi_idx] = partial_right_shift(result[hi_idx], lo_off, hi_off)
68,110✔
427
    else
428
        # Bottom first
429
        chunk = result[lo_idx]
133,100✔
430
        chunk = partial_right_shift(chunk, lo_off, 64)
133,100✔
431
        # Carry bit.
432
        chunk &= -UInt(1) >> 0x1
133,100✔
433
        chunk |= result[lo_idx - 1] << 63
133,100✔
434
        result[lo_idx] = chunk
133,100✔
435

436
        idx = lo_idx - 1
133,100✔
437
        while idx > hi_idx
218,550✔
438
            chunk = result[idx]
85,450✔
439
            chunk >>= 0x1
85,450✔
440
            chunk |= result[idx - 1] << 63
85,450✔
441
            result[idx] = chunk
85,450✔
442
            idx -= 1
85,450✔
443
        end
85,450✔
444

445
        # Top part.
446
        chunk = result[hi_idx]
133,100✔
447
        chunk = partial_right_shift(chunk, 0, hi_off)
133,100✔
448
        result[hi_idx] = chunk
133,100✔
449
    end
450
    return S(SVector(result))
201,210✔
451
end
452

453
function Base.bitreverse(bs::BitString{B,1,T}) where {B,T}
3,115✔
454
    return typeof(bs)(SVector(bitreverse(bs.chunks[1]) >> T(sizeof(T) * 8 - B)))
3,115✔
455
end
456
function Base.bitreverse(bs::BitString{B,N}) where {B,N}
40✔
457
    return typeof(bs)(bitreverse.(reverse(bs.chunks))) >> (64 * N - B)
40✔
458
end
459
Base.reverse(bs::BitString) = bitreverse(bs)
3,155✔
460

461
###
462
### Bose interface
463
###
464
function from_bose_onr(::Type{S}, onr) where {T,S<:BitString{<:Any,1,T}}
336,089✔
465
    result = zero(T)
336,089✔
466
    for i in length(onr):-1:1
336,707✔
467
        curr_occnum = T(onr[i])
2,009,293✔
468
        result <<= curr_occnum + T(1)
2,009,293✔
469
        result |= one(T) << curr_occnum - T(1)
2,009,293✔
470
    end
3,682,497✔
471
    return S(SVector(result))
336,089✔
472
end
473
function from_bose_onr(::Type{S}, onr) where {K,S<:BitString{<:Any,K}}
208,961✔
474
    result = zeros(MVector{K,UInt64})
208,961✔
475
    offset = 0
208,961✔
476
    bits_left = chunk_bits(S, K)
208,961✔
477
    i = 1
208,961✔
478
    j = K
208,961✔
479
    while true
15,128,978✔
480
        # Write number to result
481
        curr_occnum = onr[i]
15,128,978✔
482
        while curr_occnum > 0
37,357,367✔
483
            x = min(curr_occnum, bits_left)
11,447,003✔
484
            mask = (one(UInt64) << x - 1) << offset
11,117,156✔
485
            @inbounds result[j] |= mask
11,117,156✔
486
            bits_left -= x
11,117,156✔
487
            offset += x
11,117,156✔
488
            curr_occnum -= x
11,447,003✔
489

490
            if bits_left == 0
11,117,156✔
491
                j -= 1
650,764✔
492
                offset = 0
650,764✔
493
                bits_left = chunk_bits(S, j)
650,764✔
494
            end
495
        end
11,117,156✔
496
        offset += 1
15,128,978✔
497
        bits_left -= 1
15,128,978✔
498

499
        if bits_left == 0
15,128,978✔
500
            j -= 1
221,960✔
501
            offset = 0
221,960✔
502
            bits_left = chunk_bits(S, j)
221,960✔
503
        end
504
        i += 1
15,128,978✔
505
        i > length(onr) && break
15,128,978✔
506
    end
14,920,017✔
507
    return S(SVector(result))
208,961✔
508
end
509

510
# Version specialized for single-chunk addresses.
511
@inline function to_bose_onr(bs::BitString{<:Any,1}, ::Val{M}) where {M}
7,051,017✔
512
    result = zeros(MVector{M,Int32})
7,051,017✔
513
    for mode in 1:M
7,051,017✔
514
        bosons = Int32(trailing_ones(bs))
32,002,307✔
515
        @inbounds result[mode] = bosons
32,002,311✔
516
        bs >>>= (bosons + 1) % UInt
32,002,310✔
517
        iszero(bs) && break
32,002,316✔
518
    end
24,951,310✔
519
    return SVector(result)
7,051,017✔
520
end
521
# Version specialized for multi-chunk addresses. This is quite a bit faster for large
522
# addresses.
523
@inline function to_bose_onr(bs::BitString{<:Any,K}, ::Val{M}) where {K,M}
304,734✔
524
    B = num_bits(bs)
304,734✔
525
    result = zeros(MVector{M,Int32})
304,734✔
526
    mode = 1
304,734✔
527
    i = K
304,734✔
528
    while true
1,409,921✔
529
        chunk = chunks(bs)[i]
1,409,921✔
530
        bits_left = chunk_bits(bs, i)
1,409,921✔
531
        while !iszero(chunk)
22,760,072✔
532
            bosons = trailing_ones(chunk)
21,350,151✔
533
            @inbounds result[mode] += unsafe_trunc(Int32, bosons)
21,350,151✔
534
            chunk >>>= bosons % UInt
21,350,151✔
535
            empty_modes = trailing_zeros(chunk)
21,350,151✔
536
            mode += empty_modes
21,350,151✔
537
            chunk >>>= empty_modes % UInt
21,350,151✔
538
            bits_left -= bosons + empty_modes
21,350,151✔
539
        end
21,350,151✔
540
        i == 1 && break
1,409,921✔
541
        i -= 1
1,105,187✔
542
        mode += bits_left
1,105,187✔
543
    end
1,105,187✔
544
    return SVector(result)
304,734✔
545
end
546

547
# Fix offsets that changed after performing a move.
548
@inline function _fix_offset(pair, index::BoseFSIndex)
458,290,993✔
549
    fst, snd = pair[1], pair[2]
458,291,022✔
550
    if fst.offset < snd.offset
458,291,063✔
551
        return @set index.offset += fst.offset < index.offset ≤ snd.offset
176,037,685✔
552
    else
553
        return @set index.offset -= fst.offset > index.offset > snd.offset
282,253,569✔
554
    end
555
end
556
_fix_offset(pair) = Base.Fix1(_fix_offset, pair)
229,059,095✔
557

558
# Move a single particle
559
function bose_move_particle(bs::BitString, from, to)
460,401,791✔
560
    if to == from
460,401,799✔
561
        return bs
20,199✔
562
    elseif to < from
460,381,704✔
563
        return partial_left_shift(bs, to, from)
229,950,325✔
564
    else
565
        return partial_right_shift(bs, from, to - 1)
230,431,629✔
566
    end
567
end
568

569
# Move multiple particles. This does not care about values, so it performs moves in an
570
# arbitrary order (from left to right in pairs).
571
@inline function bose_move_particles(bs::BitString, (c,)::NTuple{1}, (d,)::NTuple{1})
231,343,023✔
572
    return bose_move_particle(bs, d.offset, c.offset)
462,677,564✔
573
end
574
@inline function bose_move_particles(bs::BitString, (c, cs...), (d, ds...))
229,059,121✔
575
    bs = bose_move_particle(bs, d.offset, c.offset)
458,106,217✔
576
    fix = _fix_offset(c => d)
229,059,105✔
577
    bs = bose_move_particles(bs, map(fix, cs), map(fix, ds))
458,107,194✔
578
    return bs
229,059,148✔
579
end
580

581
function bose_excitation(
231,588,375✔
582
    bs::BitString, creations::NTuple{N}, destructions::NTuple{N}
583
) where N
584
    # We start by computing the value. This is where the check if the move is even legal
585
    # is done.
586
    creations_rev = reverse(creations)
231,588,364✔
587
    value = bose_excitation_value(creations_rev, reverse(destructions))
231,588,361✔
588
    if iszero(value)
231,588,451✔
589
        return bs, 0.0
245,461✔
590
    else
591
        # Now that we know the value and that the move is legal, we can apply the moves
592
        # without worrying about doing something weird.
593
        return bose_move_particles(bs, creations_rev, destructions), √value
231,342,989✔
594
    end
595
end
596

597
function bose_num_occupied_modes(bs::BitString{<:Any,1})
16,722,338✔
598
    chunk = bs.chunks[1]
16,722,672✔
599
    result = 0
16,721,457✔
600
    while true
68,246,171✔
601
        chunk >>= (trailing_zeros(chunk) % UInt)
68,251,618✔
602
        chunk >>= (trailing_ones(chunk) % UInt)
68,259,663✔
603
        result += 1
68,263,345✔
604
        iszero(chunk) && break
68,267,117✔
605
    end
51,565,833✔
606
    return result
16,729,326✔
607
end
608
function bose_num_occupied_modes(bs::BitString)
98✔
609
    # This version is faster than using the occupied_mode iterator
610
    result = 0
98✔
611
    K = num_chunks(bs)
98✔
612
    last_mask = UInt64(1) << 63 # = 0b100000...
98✔
613
    prev_top_bit = false
98✔
614
    for i in K:-1:1
98✔
615
        chunk = chunks(bs)[i]
412✔
616
        # This part handles modes that span across chunk boundaries.
617
        # If the previous top bit and the current bottom bit are both 1, we have to subtract
618
        # 1 from the result or the mode will be counted twice.
619
        result -= (chunk & prev_top_bit) % Int
412✔
620
        prev_top_bit = (chunk & last_mask) > 0
412✔
621
        while !iszero(chunk)
5,931✔
622
            chunk >>>= trailing_zeros(chunk)
5,519✔
623
            chunk >>>= trailing_ones(chunk)
5,519✔
624
            result += 1
5,519✔
625
        end
5,519✔
626
    end
726✔
627
    return result
98✔
628
end
629

630
# Iterator stuff. Alias for type added here to make the following code less verbose.
631
const DenseBoseOccupiedModes{K} = BoseOccupiedModes{N,M,BitString{B,K,T}} where {N,M,B,T}
632

633
Base.length(bom::DenseBoseOccupiedModes) = bose_num_occupied_modes(bom.storage)
35✔
634

635
# Single chunk versions are simpler.
636
@inline function Base.iterate(bom::DenseBoseOccupiedModes{1})
497,642,901✔
637
    chunk = bom.storage.chunks[1]
497,653,558✔
638
    empty_modes = trailing_zeros(chunk)
497,672,208✔
639
    return iterate(
995,185,688✔
640
        bom, (chunk >> (empty_modes % UInt), empty_modes, 1 + empty_modes)
641
    )
642
end
643
@inline function Base.iterate(bom::DenseBoseOccupiedModes{1}, (chunk, bit, mode))
1,854,298,516✔
644
    if iszero(chunk)
1,854,273,718✔
645
        return nothing
279,769,285✔
646
    else
647
        bosons = trailing_ones(chunk)
1,574,744,248✔
648
        chunk >>>= (bosons % UInt)
1,574,849,237✔
649
        empty_modes = trailing_zeros(chunk)
1,574,959,656✔
650
        chunk >>>= (empty_modes % UInt)
1,575,010,777✔
651
        next_bit = bit + bosons + empty_modes
1,575,077,064✔
652
        next_mode = mode + empty_modes
1,574,909,732✔
653
        return BoseFSIndex(bosons, mode, bit), (chunk, next_bit, next_mode)
1,574,943,568✔
654
    end
655
end
656

657
# Multi-chunk version
658
@inline function Base.iterate(bom::DenseBoseOccupiedModes)
1,344,680✔
659
    bitstring = bom.storage
1,344,680✔
660
    i = num_chunks(bitstring)
1,344,680✔
661
    chunk = chunks(bitstring)[i]
1,344,680✔
662
    bits_left = chunk_bits(bitstring, i)
1,344,680✔
663
    mode = 1
1,344,680✔
664
    return iterate(bom, (i, chunk, bits_left, mode))
1,344,680✔
665
end
666
@inline function Base.iterate(bom::DenseBoseOccupiedModes, (i, chunk, bits_left, mode))
42,857,188✔
667
    i < 1 && return nothing
42,857,188✔
668
    bitstring = bom.storage
42,857,112✔
669
    S = typeof(bitstring)
42,857,112✔
670
    bit_position = 0
42,857,112✔
671

672
    # Remove and count trailing zeros.
673
    empty_modes = min(trailing_zeros(chunk), bits_left)
42,857,112✔
674
    chunk >>>= empty_modes % UInt
42,857,112✔
675
    bits_left -= empty_modes
42,857,112✔
676
    mode += empty_modes
42,857,112✔
677
    while bits_left < 1
43,426,334✔
678
        i -= 1
572,455✔
679
        i < 1 && return nothing
572,455✔
680
        @inbounds chunk = chunks(bitstring)[i]
569,222✔
681
        bits_left = chunk_bits(S, i)
569,222✔
682
        empty_modes = min(bits_left, trailing_zeros(chunk))
569,222✔
683
        mode += empty_modes
569,222✔
684
        bits_left -= empty_modes
569,222✔
685
        chunk >>>= empty_modes % UInt
569,222✔
686
    end
569,222✔
687

688
    bit_position = chunk_bits(S, i) - bits_left + 64 * (num_chunks(bitstring) - i)
42,853,879✔
689

690
    # Remove and count trailing ones.
691
    result = 0
42,853,879✔
692
    bosons = trailing_ones(chunk)
42,853,879✔
693
    bits_left -= bosons
42,853,879✔
694
    chunk >>>= bosons % UInt
42,853,879✔
695
    result += bosons
42,853,879✔
696
    while bits_left < 1
44,303,521✔
697
        i -= 1
1,478,383✔
698
        i < 1 && break
1,478,383✔
699
        @inbounds chunk = chunks(bitstring)[i]
1,449,642✔
700
        bits_left = chunk_bits(S, i)
1,449,642✔
701

702
        bosons = trailing_ones(chunk)
1,449,642✔
703
        bits_left -= bosons
1,449,642✔
704
        result += bosons
1,449,642✔
705
        chunk >>>= bosons % UInt
1,449,642✔
706
    end
1,449,642✔
707
    return BoseFSIndex(result, mode, bit_position), (i, chunk, bits_left, mode)
42,853,879✔
708
end
709

710
###
711
### FermiFS interface
712
###
713
function from_fermi_onr(::Type{S}, onr) where {M,C,T,S<:BitString{M,C,T}}
24,026✔
714
    result = zero(SVector{C,T})
24,026✔
715
    for mode in 1:M
24,026✔
716
        iszero(onr[mode]) && continue
1,802,278✔
717
        minus_j, offset = fldmod(mode - 1, 64)
1,246,310✔
718
        j = C - minus_j
1,246,310✔
719
        new = result[j] | T(1) << T(offset)
1,246,310✔
720
        result = setindex(result, new, j)
1,246,310✔
721
    end
3,580,530✔
722
    return S(result)
24,026✔
723
end
724

725
function _is_occupied(bs::BitString{M,1,T}, mode) where {M,T}
18,022,335✔
726
    @boundscheck 1 ≤ mode ≤ M || throw(BoundsError(bs, mode))
18,022,340✔
727
    return bs.chunks[1] & (T(1) << (mode - 1) % T) > 0
18,022,348✔
728
end
729
function _is_occupied(bs::BitString{M}, mode) where {M}
491,520✔
730
    @boundscheck 1 ≤ mode ≤ M || throw(BoundsError(bs, mode))
491,520✔
731
    j, i = fldmod1(mode, 64)
491,520✔
732
    return bs.chunks[end + 1 - j] & (UInt(1) << UInt(i - 1)) > 0
491,520✔
733
end
734

735
fermi_find_mode(bs::BitString, i) = FermiFSIndex(Int(_is_occupied(bs, i)), i, i-1)
18,513,849✔
736
function fermi_find_mode(bs::BitString, is::Tuple)
1,874,389✔
737
    return map(i -> FermiFSIndex(fermi_find_mode(bs, i)), is)
5,623,126✔
738
end
739

740
"""
741
    _flip_and_count(bs::BitString, k)
742

743
Count the number of ones before the `k`-th mode, flip the `k`th bit. Return the new
744
bitstring, the count, and the value of the bit after the flip.
745
"""
746
@inline function _flip_and_count(bs::BitString{<:Any,1,T}, k::Unsigned) where {T}
32,980,680✔
747
    chunk = bs.chunks[1]
32,980,670✔
748
    # highlights the k-th bit
749
    kmask = one(T) << k
32,980,654✔
750

751
    count = count_ones((kmask - 0x1) & chunk)
32,980,668✔
752
    chunk = chunk ⊻ kmask
32,980,682✔
753
    val = chunk & kmask > 0
32,980,683✔
754
    return typeof(bs)(chunk), count, val
32,980,686✔
755
end
756
@inline function _flip_and_count(bs::BitString, k::Unsigned)
337,234✔
757
    j, i = fldmod(k % Int, UInt(64))
337,234✔
758
    j = length(bs.chunks) - j
337,234✔
759
    chunk = bs.chunks[j]
337,234✔
760

761
    kmask = one(UInt64) << i
337,234✔
762

763
    count = count_ones((kmask - 0x1) & chunk)
337,234✔
764
    chunk = chunk ⊻ kmask
337,234✔
765
    val = chunk & kmask > 0
337,234✔
766

767
    for k in j + 1:num_chunks(bs)
444,796✔
768
        count += count_ones(bs.chunks[k])
363,237✔
769
    end
496,802✔
770
    return typeof(bs)(setindex(bs.chunks, chunk, j)), count, val
337,234✔
771
end
772

773
function fermi_excitation(
14,784,931✔
774
    bs::BitString, creations::NTuple{N}, destructions::NTuple{N}
775
) where {N}
776
    orig_bs = bs
14,784,934✔
777
    count = 0
14,784,935✔
778
    for i in N:-1:1
14,784,932✔
779
        d = destructions[i].mode
16,967,842✔
780
        bs, x, val = _flip_and_count(bs, UInt(d - 0x1))
17,059,602✔
781
        val && return orig_bs, 0.0
16,967,871✔
782
        count += x
16,674,382✔
783
    end
18,857,334✔
784
    for i in N:-1:1
14,491,459✔
785
        c = creations[i].mode
16,350,159✔
786
        bs, x, val = _flip_and_count(bs, UInt(c - 0x1))
16,391,966✔
787
        !val && return orig_bs, 0.0
16,350,154✔
788
        count += x
13,196,659✔
789
    end
15,055,366✔
790

791
    return bs, ifelse(iseven(count), 1.0, -1.0)
11,337,961✔
792
end
793

794
function Base.iterate(o::FermiOccupiedModes{<:Any,<:BitString})
122,994✔
795
    c = 0
122,994✔
796
    chunk = o.storage.chunks[end]
122,994✔
797
    while iszero(chunk)
122,994✔
798
        c += 1
×
799
        chunk = o.storage.chunks[end - c]
×
800
    end
×
801
    zeros = trailing_zeros(chunk % Int)
122,994✔
802
    return iterate(o, (chunk >> (zeros % UInt64), c * 64 + zeros, c))
122,994✔
803
end
804
function Base.iterate(o::FermiOccupiedModes{<:Any,<:BitString}, st)
22,261,338✔
805
    chunk, index, c = st
22,261,338✔
806
    while iszero(chunk)
22,630,312✔
807
        c += 1
491,968✔
808
        c == num_chunks(o.storage) && return nothing
491,968✔
809
        chunk = o.storage.chunks[end - c]
368,974✔
810
        index = c * 64
368,974✔
811
    end
368,974✔
812
    zeros = trailing_zeros(chunk % Int)
22,138,344✔
813
    index += zeros
22,138,344✔
814
    chunk >>= zeros
22,138,344✔
815
    return FermiFSIndex(1, index + 1, index), (chunk >> 1, index + 1, c)
22,138,344✔
816
end
817

818
function Base.iterate(o::FermiOccupiedModes{<:Any,<:BitString{<:Any,1,T}}) where {T}
9,498,334✔
819
    chunk = o.storage.chunks[end]
9,498,334✔
820
    zeros = trailing_zeros(chunk % Int)
9,498,334✔
821
    return iterate(o, (chunk >> (zeros % T), zeros))
18,996,670✔
822
end
823
function Base.iterate(o::FermiOccupiedModes{<:Any,<:BitString{<:Any,1,T}}, st) where {T}
23,446,187✔
824
    chunk, index = st
23,446,187✔
825
    iszero(chunk) && return nothing
23,446,187✔
826
    chunk >>= 0x1
22,914,144✔
827
    index += 1
22,914,144✔
828
    zeros = trailing_zeros(chunk % Int)
22,914,144✔
829
    return FermiFSIndex(1, index, index - 1), (chunk >> (zeros % T), index + zeros)
22,914,144✔
830
end
831

832
# Default implementation uses iterating over occupied modes.
833
function LinearAlgebra.dot(
453,690✔
834
    occ_a::FermiOccupiedModes{<:Any,S}, occ_b::FermiOccupiedModes{<:Any,S}
835
) where {S<:BitString}
836
    return count_ones(occ_a.storage & occ_b.storage)
453,690✔
837
end
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc