Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
avehtari opened this issue Jan 25, 2024 · 4 comments · Fixed by #342
Closed

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

avehtari opened this issue Jan 25, 2024 · 4 comments · Fixed by #342
Labels
feature New feature or request

Comments

@avehtari
Copy link
Collaborator

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.

@paul-buerkner paul-buerkner added the feature New feature or request label Jan 25, 2024
@mjskay
Copy link
Collaborator

mjskay commented Jan 25, 2024

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: #208 (comment))

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
Copy link
Collaborator Author

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 stan-dev/cmdstanr#876)

@paul-buerkner
Copy link
Collaborator

I agree. Sounds like a good solution.

@mjskay
Copy link
Collaborator

mjskay commented Jan 27, 2024

Cool, happy to take a stab at it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature New feature or request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants