Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/weights.jl
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ end

Base.getindex(wv::W, ::Colon) where {W <: AbstractWeights} = W(copy(wv.values), sum(wv))

@propagate_inbounds function Base.view(wv::W, inds...) where {W <: AbstractWeights}
@boundscheck checkbounds(wv, inds...)
@inbounds v = view(wv.values, inds...)
W(v, sum(v))
end

@propagate_inbounds function Base.setindex!(wv::AbstractWeights, v::Real, i::Int)
s = v - wv[i]
wv.values[i] = v
Expand Down
13 changes: 12 additions & 1 deletion test/weights.jl
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ weight_funcs = (weights, aweights, fweights, pweights)
@test sum(sa, wv) === 7.0
end

@testset "$f, setindex!" for f in weight_funcs
@testset "$f, getindex, view, setindex!" for f in weight_funcs
w = [1., 2., 3.]
wv = f(w)

Expand All @@ -46,6 +46,17 @@ end
@test sum(wv) === 6.
@test wv == w

@test wv[[1, 3]] == w[[1, 3]]
@test typeof(wv[[1, 3]]) === typeof(wv)
@test sum( wv[[1, 3]]) === sum(w[[1, 3]])

# Check view
@test view(wv, [1, 3]) == view(wv, [true, false, true]) == w[[1, 3]]
@test typeof(view(wv, [1, 3])) === typeof(view(wv, [true, false, true])) === typeof(wv)
@test sum(view(wv, [1, 3])) === sum(view(wv, [true, false, true])) === sum(w[[1, 3]])
@test_throws BoundsError view(wv, [1, 5])
@test_throws BoundsError view(wv, [true, false, true, true])

# Test setindex! success
@test (wv[1] = 4) === 4 # setindex! returns original val
@test wv[1] === 4. # value correctly converted and set
Expand Down