cubie.batchsolving.BatchGridBuilder
Batch Grid Builder Module.
This module provides utilities for building grids of state and parameter values. The BatchGridBuilder class converts user-supplied dictionaries or arrays into the 2D numpy arrays expected by the solver.
Notes
The user primarily interacts with this class through the Solver class, unless they have very specific needs. Interaction with the BatchConfigurator is primarily through the __call__ method, which accepts four arguments:
request: A dictionary of (potentially mixed) parameter and state names mapped to sequences of values. Says: “Integrate from combinations of these named variables”
‘params’: A dictionary of purely parameter variable names, a 1D sequence to set one set of values for every integration, or a 2D array of all combinations to integrate from.
‘states’: A dictionary of purely state variable names, a 1D sequence to set one set of values for every integration, or a 2D array of all combinations to integrate from.
‘kind’: A string indicating how to combine the parameters and states. - ‘combinatorial’ constructs a grid of all combinations of the values
provided
‘verbatim’ constructs a grid of [[all variables[0]],[all variables[1]],…] when the combinations have been intentionally constructed already.
There is a subtle difference between a ‘combinatorial’ combination of two input arrays the same values given as per-variable arrays in a dict, as demonstrated in the examples above. If the user provides arrays as an argument, it is assumed that all within-array combinations have already been constructed. When the user provides a dict, it is assumed that they want a combinatorial combination of the values. In the array case, the method will return arrays which contain all combinations of the rows of the arrays ( i.e. nrows x nrows combinations). The dictionary case first constructs combinations of values, resulting in an array of height nvals1 * nvals2 * … * nvalsk for k variables, then combines these in the same fashion as the array case.
For more fine-grained control, you can call the grid_arrays and combine_grids methods directly, or construct the full arrays outside of this method and let them pass through verbatim.
Examples
>>> import numpy as np
>>> from cubie.batchsolving.BatchGridBuilder import BatchGridBuilder
>>> from cubie.systemmodels.systems.decays import Decays
>>> system = Decays(coefficients=[1.0, 2.0])
>>> grid_builder = BatchGridBuilder.from_system(system)
>>> params = {"p0": [0.1, 0.2], "p1": [10, 20]}
>>> states = {"x0": [1.0, 2.0], "x1": [0.5, 1.5]}
>>> inits, params = grid_builder(
... params=params, states=states, kind="combinatorial"
... )
>>> print(inits.shape)
(16, 2)
>>> print(inits)
[[1. 0.5]
[1. 0.5]
[1. 0.5]
[1. 0.5]
[1. 1.5]
[1. 1.5]
[1. 1.5]
[1. 1.5]
[2. 0.5]
[2. 0.5]
[2. 0.5]
[2. 0.5]
[2. 1.5]
[2. 1.5]
[2. 1.5]
[2. 1.5]]
>>> print(params.shape)
(16, 2)
>>> print(params)
[[ 0.1 10. ]
[ 0.1 20. ]
[ 0.2 10. ]
[ 0.2 20. ]
[ 0.1 10. ]
[ 0.1 20. ]
[ 0.2 10. ]
[ 0.2 20. ]
[ 0.1 10. ]
[ 0.1 20. ]
[ 0.2 10. ]
[ 0.2 20. ]
[ 0.1 10. ]
[ 0.1 20. ]
[ 0.2 10. ]
[ 0.2 20. ]]
Example 2: verbatim arrays
>>> params = np.array([[0.1, 0.2], [10, 20]])
>>> states = np.array([[1.0, 2.0], [0.5, 1.5]])
>>> inits, params = grid_builder(params=params, states=states, kind="verbatim")
>>> print(inits.shape)
(2, 2)
>>> print(inits)
[[1. 2. ]
[0.5 1.5]]
>>> print(params.shape)
(2, 2)
>>> print(params)
[[ 0.1 0.2]
[10. 20. ]]
>>> inits, params = grid_builder(
... params=params, states=states, kind="combinatorial"
... )
>>> print(inits.shape)
(4, 2)
>>> print(inits)
[[1. 2. ]
[1. 2. ]
[0.5 1.5]
[0.5 1.5]]
>>> print(params.shape)
(4, 2)
>>> print(params)
[[ 0.1 0.2]
[10. 20. ]
[ 0.1 0.2]
[10. 20. ]]
Same as individual dictionaries
>>> request = {
... "p0": [0.1, 0.2],
... "p1": [10, 20],
... "x0": [1.0, 2.0],
... "x1": [0.5, 1.5],
... }
>>> inits, params = grid_builder(request=request, kind="combinatorial")
>>> print(inits.shape)
(16, 2)
>>> print(params.shape)
(16, 2)
>>> request = {"p0": [0.1, 0.2]}
>>> inits, params = grid_builder(request=request, kind="combinatorial")
>>> print(inits.shape)
(2, 2)
>>> print(inits) # unspecified variables are filled with defaults from system
[[1. 1.]
[1. 1.]]
>>> print(params.shape)
(2, 2)
>>> print(params)
[[0.1 2. ]
[0.2 2. ]]
Functions
|
Build a grid of all unique combinations of values from a request dictionary. |
|
Combine two grids into extended grids. |
|
Join a grid with default values to create complete parameter arrays. |
|
Create a complete 2D array from a request dictionary. |
|
Generate a parameter grid for batch runs from a request dictionary. |
|
Return unique combinations of elements from input arrays. |
|
Build a grid where parameters vary together, not combinatorially. |
Classes
|
Build grids of parameter and state values for batch runs. |
- class cubie.batchsolving.BatchGridBuilder.BatchGridBuilder(interface: SystemInterface)[source]
Bases:
object
Build grids of parameter and state values for batch runs.
This class converts user-supplied dictionaries or arrays into the 2D numpy arrays expected by the solver for batch integration runs.
- Parameters:
interface (SystemInterface) – System interface containing parameter and state information.
- parameters
Parameter values and metadata from the interface.
- Type:
- states
State values and metadata from the interface.
- Type:
- _sanitise_arraylike(arr, values_object: SystemValues)[source]
Convert to 2D array if needed and ensure correct dimensions.
- Parameters:
arr (array_like) – Input array-like object to be sanitized.
values_object (SystemValues) – System values object containing size and default information.
- Returns:
Properly sized 2D array, or None if input array is empty.
- Return type:
np.ndarray or None
- Raises:
ValueError – If input has more than 2 dimensions.
- Warns:
UserWarning – If provided input data has incorrect number of columns.
- _trim_or_extend(arr: ndarray[Any, dtype[_ScalarType_co]], values_object: SystemValues)[source]
Extend incomplete arrays with defaults or trim extra values.
- Parameters:
arr (NDArray) – Input array to be trimmed or extended.
values_object (SystemValues) – System values object containing default values and size information.
- Returns:
Array with correct dimensions, either trimmed or extended.
- Return type:
NDArray
- classmethod from_system(system: GenericODE)[source]
Create a BatchGridBuilder from a system model.
- Parameters:
system (GenericODE) – The system model to create the grid builder from.
- Returns:
A new BatchGridBuilder instance configured for the given system.
- Return type:
- grid_arrays(request: Dict[str | int, float | Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | ndarray], kind: str = 'combinatorial') tuple[ndarray, ndarray] [source]
Build parameter and state grids from a mixed request dictionary.
- Parameters:
- Returns:
initial_values_array (np.ndarray) – 2D state array for input into the integrator.
params_array (np.ndarray) – 2D parameter array for input into the integrator.
- cubie.batchsolving.BatchGridBuilder.combinatorial_grid(request: Dict[str | int, float | Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | ndarray], values_instance: SystemValues, silent: bool = False) tuple[ndarray, ndarray] [source]
Build a grid of all unique combinations of values from a request dictionary.
- Parameters:
request (Dict[Union[str, int], Union[float, ArrayLike, np.ndarray]]) – Dictionary where keys are parameter names or indices, and values are either a single value or an array of values for that parameter. For a combinatorial grid, the arrays of values need not be equal in length.
values_instance (SystemValues) – The SystemValues instance in which to find the indices for the keys in the request.
silent (bool, default=False) – If True, suppress warnings about unrecognized parameters in the request.
- Returns:
indices (np.ndarray) – A 1D array of indices corresponding to the gridded parameters.
grid (np.ndarray) – A 2D array of shape (n_runs, n_requested_parameters) where each row corresponds to a set of parameters for a run.
Notes
Unspecified parameters are filled with their default values from the system. n_runs is the combinatorial product of the lengths of all of the value arrays - for example, if the request contains two parameters with 3, 2, and 4 values, then n_runs would be 3 * 2 * 4 = 24.
Examples
>>> combinatorial_grid( ... {"param1": [0.1, 0.2, 0.3], "param2": [10, 20]}, system.parameters ... ) (array([0, 1]), array([[ 0.1, 10. ], [ 0.1, 20. ], [ 0.2, 10. ], [ 0.2, 20. ], [ 0.3, 10. ], [ 0.3, 20. ]]))
- cubie.batchsolving.BatchGridBuilder.combine_grids(grid1: ndarray, grid2: ndarray, kind: str = 'combinatorial') tuple[ndarray, ndarray] [source]
Combine two grids into extended grids.
- Parameters:
grid1 (np.ndarray) – First grid (e.g., parameter grid).
grid2 (np.ndarray) – Second grid (e.g., state grid).
kind (str, default='combinatorial') – ‘combinatorial’ for cartesian product, ‘verbatim’ for row-wise pairing.
- Returns:
grid1_extended (np.ndarray) – Extended first grid.
grid2_extended (np.ndarray) – Extended second grid.
- Raises:
ValueError – If kind is ‘verbatim’ and grids have different numbers of rows. If kind is not ‘combinatorial’ or ‘verbatim’.
- cubie.batchsolving.BatchGridBuilder.extend_grid_to_array(grid: ndarray, indices: ndarray, default_values: ndarray)[source]
Join a grid with default values to create complete parameter arrays.
Creates a 2D array where each row has a full set of parameters, and non-gridded parameters are set to their default values.
- Parameters:
grid (np.ndarray) – A 2D array of shape (n_runs, n_requested_parameters) where each row corresponds to a set of parameters for a run.
indices (np.ndarray) – A 1D array of indices corresponding to the gridded parameters.
default_values (np.ndarray) – A 1D array of default values for the parameters.
- Returns:
array – A 2D array of shape (n_runs, n_parameters) where each row corresponds to a set of parameters for a run. Parameters not specified in the grid are filled with their default values from the system.
- Return type:
np.ndarray
- Raises:
ValueError – If grid shape does not match indices shape.
- cubie.batchsolving.BatchGridBuilder.generate_array(request: Dict[str | int, float | Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | ndarray], values_instance: SystemValues, kind: str = 'combinatorial') ndarray [source]
Create a complete 2D array from a request dictionary.
- Parameters:
request (Dict[Union[str, int], Union[float, ArrayLike, np.ndarray]]) – Dictionary where keys are parameter names or indices, and values are either a single value or an array of values for that parameter.
values_instance (SystemValues) – The SystemValues instance in which to find the indices for the keys in the request.
kind (str, default='combinatorial') – The type of grid to generate. Can be ‘combinatorial’ or ‘verbatim’.
- Returns:
array – A 2D array of shape (n_runs, n_parameters) where each row corresponds to a set of parameters for a run. Parameters not specified in the request are filled with their default values from the system.
- Return type:
np.ndarray
- cubie.batchsolving.BatchGridBuilder.generate_grid(request: Dict[str | int, float | Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | ndarray], values_instance: SystemValues, kind: str = 'combinatorial', silent: bool = False) tuple[ndarray, ndarray] [source]
Generate a parameter grid for batch runs from a request dictionary.
- Parameters:
request (Dict[Union[str, int], Union[float, ArrayLike, np.ndarray]]) – Dictionary where keys are parameter names or indices, and values are either a single value or an array of values for that parameter.
values_instance (SystemValues) – The SystemValues instance in which to find the indices for the keys in the request.
kind (str, default='combinatorial') – The type of grid to generate. Can be ‘combinatorial’ or ‘verbatim’.
silent (bool, default=False) – If True, suppress warnings about unrecognized parameters in the request.
- Returns:
indices (np.ndarray) – A 1D array of indices corresponding to the gridded parameters.
grid (np.ndarray) – A 2D array of shape (n_runs, n_requested_parameters) where each row corresponds to a set of parameters for a run.
Notes
The kind parameter determines how the grid is constructed: - ‘combinatorial’: see combinatorial_grid function - ‘verbatim’: see verbatim_grid function
- cubie.batchsolving.BatchGridBuilder.unique_cartesian_product(arrays: List[ndarray])[source]
Return unique combinations of elements from input arrays.
Each input array can have duplicates, but the output will not contain any duplicate rows. The order of the input arrays is preserved, and the output will have the same order of elements as the input.
- Parameters:
arrays (List[np.ndarray]) – A list of 1D numpy arrays, each containing elements to be combined.
- Returns:
combos – A 2D numpy array where each row is a unique combination of elements from the inputs.
- Return type:
np.ndarray
Notes
This function removes duplicates by creating a dict with the elements of the input array as keys. It then casts that to a list, getting the de-duplicated values. It then uses itertools.product to generate the Cartesian product of the input arrays.
Examples
>>> unique_cartesian_product([np.array([1, 2, 2]), np.array([3, 4])]) array([[1, 3], [1, 4], [2, 3], [2, 4]])
- cubie.batchsolving.BatchGridBuilder.verbatim_grid(request: Dict[str | int, float | Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | ndarray], values_instance: SystemValues, silent: bool = False) tuple[ndarray, ndarray] [source]
Build a grid where parameters vary together, not combinatorially.
Parameters vary together, but not combinatorially. All value arrays must be of equal length.
- Parameters:
request (Dict[Union[str, int], Union[float, ArrayLike, NDArray]]) – Dictionary where keys are parameter names or indices, and values are either a single value or an array of values for that parameter.
values_instance (SystemValues) – The SystemValues instance in which to find the indices for the keys in the request.
silent (bool, default=False) – If True, suppress warnings about unrecognized parameters in the request.
- Returns:
indices (np.ndarray) – A 1D array of indices corresponding to the gridded parameters.
grid (np.ndarray) – A 2D array of shape (n_runs, n_requested_parameters) where each row corresponds to a set of parameters for a run.
Notes
Unspecified parameters are filled with their default values from the system. n_runs is the length of all value arrays, which must be equal.
Examples
>>> verbatim_grid( ... {"param1": [0.1, 0.2, 0.3], "param2": [10, 20, 30]}, ... system.parameters, ... ) (array([0, 1]), array([[ 0.1, 10. ], [ 0.2, 20. ], [ 0.3, 30. ]]))