Skip to content

Commit

Permalink
add dict utility
Browse files Browse the repository at this point in the history
  • Loading branch information
baggepinnen committed Mar 1, 2023
1 parent 06e8130 commit 027b5f5
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
name = "MonteCarloMeasurements"
uuid = "0987c9cc-fe09-11e8-30f0-b96dd679fdca"
authors = ["baggepinnen <[email protected]>"]
version = "1.0.13"
version = "1.1.0"

[deps]
Distributed = "8ba89e20-285c-5b6f-9357-94700520ee1b"
Expand Down
26 changes: 26 additions & 0 deletions src/particles.jl
Original file line number Diff line number Diff line change
Expand Up @@ -692,3 +692,29 @@ function LinearAlgebra.mul!(
y
end


"""
particle_dict2dict_vec(dict)
Take a dict that vaps keys to uncertain values, and return a vector of dicts where each dict has a single sample (particle) of the uncertain values. The length of the returned vector is the number of samples (particles) for all uncertain parameters.
"""
function particle_dict2dict_vec(dict)
# check the validity of uncertain parameters
found_particle_numbers = Set{Int}()
uncertain_parameters = Set{Base.keytype(dict)}()
for (k, v) in dict
if v isa AbstractParticles
push!(found_particle_numbers, nparticles(v))
push!(uncertain_parameters, k)
end
end
if length(found_particle_numbers) > 1
error("The number of samples (particles) for all uncertain parameters must be the same, but I found $(found_particle_numbers)")
elseif isempty(found_particle_numbers)
return [dict] # not much to do here
end
N = only(found_particle_numbers)
map(1:N) do i
Dict(k => vecindex(v, i) for (k, v) in dict)
end
end
6 changes: 6 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -548,6 +548,12 @@ Random.seed!(0)
@test p1 == p2
@test nparticles(bootstrap(p, 10)) == 10
@test_nowarn bootstrap([p; p])

dict = Dict(:a => p, :b => q, :c => 1)
dictvec = MonteCarloMeasurements.particle_dict2dict_vec(dict)
@test length(dictvec) == nparticles(p)
@test dictvec[1] == Dict(:a => p.particles[1], :b => q.particles[1], :c => 1)
@test dictvec[2] == Dict(:a => p.particles[2], :b => q.particles[2], :c => 1)
end

@time @testset "mutation" begin
Expand Down

0 comments on commit 027b5f5

Please sign in to comment.