stan-dev / posterior

The posterior R package
https://mc-stan.org/posterior/
Other
167 stars 24 forks source link

Add a function to extract single draw of multidimensional variable #340

Closed avehtari closed 9 months ago

avehtari commented 10 months ago

Currently extract_variable doesn't work for matrix/array variables

In the following p1 is a Pathfinder object from CmdStanR and z_1 is defined in Stan as matrix[M_1, N_1] z_1; It took me some time to figure out how to extract an R array with the dimensions M_1, N_1

drop(draws_of(subset_draws(as_draws_rvars(p1$draws()), variable='z_1', draw=1)[[1]]))

It would be nice to have a function for this. The above code works also for scalars, vectors, and 1D arrays.

mjskay commented 10 months ago

Thinking about how this relates to uses of variable names across the API, this seems related to the inconsistent handling of indices in variable names between draws_rvars and the other formats (see here: https://github.com/stan-dev/posterior/issues/208#issuecomment-1005713122)

One thought is to fix the above-referenced issue so that something like variables(x, with_indices = TRUE) (default) returns names like x[1,1], x[1,2], ... and variables(x, with_indices = FALSE) returns names like x. Then have clear indications in the API of which functions take variable names with or without indices.

For this issue specifically, following the pattern of extract_variable_matrix() we could have an extract_variable_array(x, variable) that takes a variable name without indices and returns its array form. Then the solution in the above example would be extract_variable_array(x, "z_1")[1,,].

If we also want a solution specifically for getting one draw regardless of shape, then there is helper code used by for_each_draw that could be extracted and adapted for that purpose.

avehtari commented 10 months ago

I did also notice the index-inconsistency, and like the idea of with_indices

extract_variable_array would work for me (the first use case is https://github.com/stan-dev/cmdstanr/issues/876)

paul-buerkner commented 10 months ago

I agree. Sounds like a good solution.

mjskay commented 10 months ago

Cool, happy to take a stab at it.