From 027b5f5f488a5234701c5a13bb3696396df58aa9 Mon Sep 17 00:00:00 2001 From: Fredrik Bagge Carlson Date: Wed, 1 Mar 2023 10:55:14 +0100 Subject: [PATCH] add dict utility --- Project.toml | 2 +- src/particles.jl | 26 ++++++++++++++++++++++++++ test/runtests.jl | 6 ++++++ 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/Project.toml b/Project.toml index 6cdfda6..7bcff44 100644 --- a/Project.toml +++ b/Project.toml @@ -1,7 +1,7 @@ name = "MonteCarloMeasurements" uuid = "0987c9cc-fe09-11e8-30f0-b96dd679fdca" authors = ["baggepinnen "] -version = "1.0.13" +version = "1.1.0" [deps] Distributed = "8ba89e20-285c-5b6f-9357-94700520ee1b" diff --git a/src/particles.jl b/src/particles.jl index 7716a71..43b931e 100644 --- a/src/particles.jl +++ b/src/particles.jl @@ -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 \ No newline at end of file diff --git a/test/runtests.jl b/test/runtests.jl index dea4a30..9275a13 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -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