Skip to content

Commit 97ed363

Browse files
committed
Simplify set_namedtuple!
1 parent ed17b7e commit 97ed363

File tree

1 file changed

+11
-34
lines changed

1 file changed

+11
-34
lines changed

src/mcmc/mh.jl

Lines changed: 11 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -212,43 +212,20 @@ end
212212
Places the values of a `NamedTuple` into the relevant places of a `VarInfo`.
213213
"""
214214
function set_namedtuple!(vi::DynamicPPL.VarInfoOrThreadSafeVarInfo, nt::NamedTuple)
215-
# TODO: Replace this with something like
216-
# for vn in keys(vi)
217-
# vi = DynamicPPL.setindex!!(vi, get(nt, vn))
218-
# end
219215
for (n, vals) in pairs(nt)
220216
vns = vi.metadata[n].vns
221-
nvns = length(vns)
222-
223-
# if there is a single variable only
224-
if nvns == 1
225-
# assign the unpacked values
226-
if length(vals) == 1
227-
vi[vns[1]] = [vals[1];]
228-
# otherwise just assign the values
229-
else
230-
vi[vns[1]] = [vals;]
231-
end
232-
# if there are multiple variables
233-
elseif vals isa AbstractArray
234-
nvals = length(vals)
235-
# if values are provided as an array with a single element
236-
if nvals == 1
237-
# iterate over variables and unpacked values
238-
for (vn, val) in zip(vns, vals[1])
239-
vi[vn] = [val;]
240-
end
241-
# otherwise number of variables and number of values have to be equal
242-
elseif nvals == nvns
243-
# iterate over variables and values
244-
for (vn, val) in zip(vns, vals)
245-
vi[vn] = [val;]
246-
end
247-
else
248-
error("Cannot assign `NamedTuple` to `VarInfo`")
249-
end
217+
if vals isa AbstractVector
218+
vals = unvectorize(vals)
219+
end
220+
if length(vns) == 1
221+
# Only one variable, assign the values to it
222+
DynamicPPL.setindex!(vi, vals, vns[1])
250223
else
251-
error("Cannot assign `NamedTuple` to `VarInfo`")
224+
# Spread the values across the variables
225+
length(vns) == length(vals) || error("Unequal number of variables and values")
226+
for (vn, val) in zip(vns, vals)
227+
DynamicPPL.setindex!(vi, val, vn)
228+
end
252229
end
253230
end
254231
end

0 commit comments

Comments
 (0)