bebi103.utils.array_to_dict

bebi103.utils.array_to_dict(input_array: ndarray[tuple[Any, ...], dtype[_ScalarT]], base_name: str, n_index_axes: int = 1, one_indexed: bool = True, dtype=None) → dict[str, Any]

Given a Numpy array, convert to a dictionary with each key being of the form ‘base_name[1]’, ‘base_name[1,2]’, etc. The last n_index_axes axes of input_array are the indices of the array itself and become the indices in the keys. The leading axes, typically those of the samples, are retained in the values. This is the inverse of dict_to_array().

Parameters:
  • input_array (Numpy array) – Numpy array to convert to dictionary.

  • base_name (str) – Name of array represented to be represented in the dictionary. The keys will be of the form f’{base_name}[1].

  • n_index_axes (int, default 1) – Number of trailing axes of input_array that index the array itself. These become the indices in the keys of the outputted dictionary, so the keys have n_index_axes indices each. The remaining leading axes, in typical applications in MCMC the chain ID and the draw, are retained in each value.

  • one_indexed (bool, default True) – True if indexing of the array in the dictionary starts at 1, as is the case with Stan, and False if indexing starts at 0.

  • dtype (int, float, or None) – If not None, each entry is outputted as the specified dtype.

Returns:

output – Dictionary with entries like ‘base_name[1]’, ‘base_name[2]’, etc. Each value is a Numpy array of shape input_array.shape[:-n_index_axes]. If n_index_axes is the dimensionality of input_array, no axes are left over and each value is instead a scalar.

Return type:

dict

Raises:

ValueError – If n_index_axes is less than one or exceeds the dimensionality of input_array.

Notes

This is the inverse of dict_to_array(). For an array a,

dict_to_array(
    array_to_dict(a, 'a', n_index_axes=k), 'a', squeeze=False
)

gives back a. With squeeze=True, dict_to_array() discards axes of length one, so it is not in general invertible.

The values of the outputted dictionary are copies; they are not views into input_array.

Examples

>>> array_to_dict(np.array([1, 2, 3]), 'a')
{'a[1]': 1, 'a[2]': 2, 'a[3]': 3}
>>> array_to_dict(np.array([[1, 2], [3, 4], [5, 6]]), 'a', n_index_axes=2)
{'a[1,1]': 1, 'a[1,2]': 2, 'a[2,1]': 3, 'a[2,2]': 4, 'a[3,1]': 5, 'a[3,2]': 6}
>>> array_to_dict(np.array([[1, 2], [3, 4], [5, 6]]), 'a')
{'a[1]': array([1, 3, 5]), 'a[2]': array([2, 4, 6])}
>>> array_to_dict(np.array([1, 2, 3]), 'a', one_indexed=False)
{'a[0]': 1, 'a[1]': 2, 'a[2]': 3}