Solver
- class cubie.batchsolving.solver.Solver(system: BaseODE, algorithm: str | None = None, lineinfo: bool | None = None, step_control_settings: Dict[str, object] | None = None, algorithm_settings: Dict[str, object] | None = None, system_settings: Dict[str, object] | None = None, output_settings: Dict[str, object] | None = None, memory_settings: Dict[str, object] | None = None, loop_settings: Dict[str, object] | None = None, time_logging_level: str | None = None, cache: bool | str | Path | None = None, auto_performance: bool | None = None, **kwargs: Any)[source]
Bases:
objectUser-facing interface for solving batches of ODE systems.
- Parameters:
system – System model containing the ODEs to integrate.
algorithm – Integration algorithm to use. Defaults to
"euler".lineinfo – Compile all kernels and device functions with source-line correlation data for profilers such as Nsight Compute.
Nonedefers to theCUBIE_LINEINFOenvironment variable (default off). Changing it later viaupdate()triggers a rebuild.step_control_settings – Explicit controller configuration that overrides solver defaults.
algorithm_settings – Explicit algorithm configuration overriding solver defaults.
system_settings – Explicit system configuration; each key may also be a keyword argument.
output_settings – Explicit output configuration overriding solver defaults. Individual selectors such as
save_variablesor index-based parameters may also be supplied as keyword arguments.memory_settings – Memory configuration; each key may also be a keyword argument. Host result arrays above 80% of system RAM are disk-backed in the cache root. An idle solver’s completed device buffers are freed when another solver faces a genuine VRAM shortage; the evicted solver reallocates on its next solve.
loop_settings – Explicit loop configuration overriding solver defaults. Keys such as
save_everyandsummarise_everymay also be supplied as loose keyword arguments.time_logging_level (str or None, default='default') – Time logging verbosity level. Options are ‘silent’, ‘default’, ‘verbose’, ‘debug’, None, or ‘None’ to disable timing.
auto_performance (bool, default=True) – Set buffer locations, loop unrolling and launch residency from your hardware and CuBIE’s best guess. Never overrides explicit
unroll_*or*_locationarguments. Turning it off on a built solver keeps the last derived values.**kwargs – Any setting named in
SolverSettingsand any constant ofsystemby name.
- given
Settings that the user explicitly set, a
SolverSettings.
- effective
Settings that the solver is using, including
givenand the ones resolved from it, anEffectiveSettings.
Notes
Instances coordinate batch grid construction, kernel configuration, and driver interpolation so that
solve()orchestrates a complete GPU integration run.When specifying variables:
Nonemeans “use all” (default behavior for both states and observables)[](empty list) means “explicitly no variables”When both labels and indices are provided, their union is used
- _apply_performance_defaults() None[source]
Apply the auto-performance unroll and placement defaults.
- _child_defaults() Dict[str, Any][source]
Return the declared default of every child compile setting.
- _configure_drivers(drivers: Dict[str, Any]) None[source]
Update the kernel-owned driver interpolator as one unit.
- Parameters:
drivers – Driver samples plus interpolation settings, as accepted by
ArrayInterpolator.update_from_dict().
- property active_outputs: ActiveOutputs
Expose active outputs from the kernel.
- property algorithm
Return the configured algorithm name.
- build_grid(initial_values: ndarray | Dict[str, float | ndarray] = None, parameters: None | ndarray | Dict[str, float | ndarray] = None, grid_type: str = 'verbatim') Tuple[ndarray, ndarray][source]
Build parameter and state grids for external use.
- Parameters:
initial_values – Initial state values as dictionaries mapping state names to value sequences, or arrays in (n_states, n_runs) format.
parameters – Parameter values as dictionaries mapping parameter names to value sequences, or arrays in (n_params, n_runs) format.
grid_type – Strategy for constructing the grid.
"combinatorial"produces all combinations while"verbatim"preserves column-wise pairings. Default is"verbatim".
- Returns:
Tuple of (initial_values, parameters) arrays in (n_vars, n_runs) format with system precision dtype. These arrays can be passed directly to
solve()for fast-path execution.- Return type:
Tuple[ndarray, ndarray]
Examples
>>> inits, params = solver.build_grid( ... {"x": [1, 2, 3]}, {"p": [0.1, 0.2]}, grid_type="combinatorial" ... ) >>> result = solver.solve(inits, params) # Uses fast path
- calibrate(initial_values: ndarray | Dict[str, Any], parameters: ndarray | Dict[str, Any], drivers: Dict[str, Any] | None = None, duration: float = 1.0, settling_time: float = 0.0, t0: float = 0.0, grid_type: str = 'verbatim', apply: bool = True, verbose: bool = True) CalibrationResult[source]
Race solver configurations and pick the fastest.
Compare a range of integration algorithms and settings (preconditioners, solver types, smoothed error and prediction), returning a winner and a ranked list based on solve time and solver-failure count. Can run for up to an hour on large systems, but takes care of a lot of trial/error. Candidates inherit this solver’s tolerances and output configuration.
- Parameters:
initial_values – A typical initial-values grid that you’ll solve over; aim for at least 32768 combined initial-value/parameter sets to test the solver at full capacity. Accepts dictionaries mapping state names to values for grid construction, or pre-built arrays in (n_states, n_runs) format.
parameters – Parameter values for each run. Accepts dictionaries mapping parameter names to values, or pre-built arrays in (n_params, n_runs) format.
drivers – Driver samples or configuration matching
cubie.array_interpolator.ArrayInterpolator.duration – Total integration time. Default is
1.0.settling_time – Warm-up period before recording outputs. Default
0.0.t0 – Initial integration time. Default
0.0.grid_type – Strategy for constructing the integration grid from inputs. Only used when dict inputs trigger grid construction.
apply – Apply the winner’s configuration to this solver when
True(default). PassFalseto only report.verbose – Print per-candidate progress lines. Default
True.
- Returns:
Winner, ranking, and every candidate measurement. A candidate that fails to build or integrate is reported as dropped with its error message.
- Return type:
CalibrationResult
- Raises:
ValueError – If the system declares drivers but none are supplied.
- property chunks
Return the number of chunks used in the last run.
- close(shutdown_timeout: float | None = None) None[source]
Release GPU resources after pending transfers finish.
- Parameters:
shutdown_timeout – Maximum seconds to wait. None waits until transfers finish.
- compile(initial_values: ndarray | Dict[str, float | ndarray], parameters: ndarray | Dict[str, float | ndarray], drivers: Dict[str, Any] | None = None, duration: float = 1.0, settling_time: float = 0.0, t0: float = 0.0, grid_type: str = 'verbatim', **kwargs: Any) None[source]
Compile the batch kernel for these inputs without solving.
- property compile_flags: OutputCompileFlags
Expose output compile flags from the kernel.
- convert_output_labels(output_settings: Dict[str, Any]) None[source]
Convert variable labels to indices.
- Parameters:
output_settings – Output configuration kwargs. Entries used are
save_variables,summarise_variables,saved_state_indices,saved_observable_indices,summarised_state_indices, andsummarised_observable_indices.- Raises:
ValueError – If variable labels are not recognized by the system.
- copy(**overrides: Any) Solver[source]
Return a copy: same settings and drivers, current log level.
- Parameters:
**overrides – Settings applied over this solver’s;
Noneleaves one not given.
- property device_initial_values
Device initial values of the last run; raise if chunked.
- property device_iteration_counters
Expose the device buffer of iteration counters.
- property device_observable_summaries
Expose the device buffer of observable summaries.
- property device_observables
Expose the device buffer of observable outputs.
- property device_parameters
Device parameters of the last run; raise if chunked.
- property device_state
Expose the device buffer of state outputs.
- property device_state_summaries
Expose the device buffer of state summaries.
- property device_status_codes
Expose the device buffer of status codes.
- property driver_coefficients
Expose driver interpolation coefficients.
- property driver_interpolator: ArrayInterpolator
The kernel-owned driver interpolator.
- property duration
Return the requested integration duration.
- get_observable_indices(observable_labels: List[str] | None = None) ndarray[source]
Return indices for the specified observables.
- Parameters:
observable_labels – Labels of observables to query.
Nonereturns indices for all observables.- Returns:
Integer indices corresponding to the requested observables.
- Return type:
ndarray
- get_state_indices(state_labels: List[str] | None = None) ndarray[source]
Return indices for the specified state variables.
- Parameters:
state_labels – Labels of states to query.
Nonereturns indices for all states.- Returns:
Integer indices corresponding to the requested states.
- Return type:
ndarray
- property initial_values
Expose initial values array used in the last run.
- property iteration_counters
Expose iteration counters at each save point.
- property mem_proportion
Return the proportion of global memory allocated.
- property memory_manager
Return the associated memory manager instance.
- property num_runs
Expose the number of runs in the last solve.
- property observable_summaries
Expose observable summary outputs.
- property observables
Expose latest observable outputs.
- optimisation_candidates(force: bool = False) Tuple[Dict[str, Any], ...][source]
Return optimisation candidates;
forcefrees the given keys.
- optimize(initial_values: ndarray | Dict[str, Any], parameters: ndarray | Dict[str, Any], drivers: Dict[str, Any] | None = None, duration: float = 1.0, settling_time: float = 0.0, t0: float = 0.0, grid_type: str = 'verbatim', apply: bool = True, verbose: bool = True, force: bool = False, auto_size: bool = True, waves: int = 5, target_ms: float = 20.0) OptimizeResult[source]
Time placement, unrolling and launch options; keep the fastest.
Settings you gave, or an earlier
optimizeapplied, stay fixed unlessforce=True.- Parameters:
initial_values – Dict of state names to values, or an (n_states, n_runs) array.
parameters – Dict of parameter names to values, or an (n_params, n_runs) array.
drivers – Time-domain sampled driver values.
duration – Integration time of your solves. Default
1.0.settling_time – Warm-up period before outputs are recorded. Default
0.0.t0 – Initial integration time. Default
0.0.grid_type – Grid strategy when dict inputs build a grid.
apply – Apply the fastest settings to this solver. Default
True.verbose – Print per-launch progress lines. Default
True.force – Vary the settings you gave or applied earlier too.
auto_size –
Trueoptimizes at an automatically selected batch size and duration to reduce runtime;Falseoptimizes at your given batch size and duration. DefaultTrue.waves – How many waves the
auto_sizesetting sets your batch size to fill. Default5.target_ms – Target kernel runtime that
auto_sizesets your integration duration to. Default20.0.
- Returns:
Every launch, the best one, and the applied settings.
- Return type:
OptimizeResult
- Raises:
ValueError –
wavesunder 1, ortarget_msunder 10 or not finite.
- property output_array_heights
Expose output array heights from the kernel.
- property output_length
Expose the flattened output length.
- property parameters
Expose parameter array used in the last run.
- property precision: type[float16] | type[float32] | type[float64] | dtype[float16] | dtype[float32] | dtype[float64]
Expose the kernel precision.
- property saved_observable_indices
Expose saved observable indices.
- property saved_observables
List saved observable labels.
- property saved_state_indices
Expose saved state indices.
- property saved_states
List saved state labels.
- set_cache_dir(path: str | Path) None[source]
Set a custom cache directory for compiled kernels.
- Parameters:
path – New cache directory path. Can be absolute or relative.
Notes
Invalidates the current cache, causing a rebuild on next access.
- set_verbosity(verbosity: str | None) None[source]
Set the time logging verbosity level.
- Parameters:
verbosity (str or None) – New verbosity level. Options are ‘default’, ‘verbose’, ‘debug’, None, or ‘None’.
Notes
Updates the global time logger verbosity. This affects all timing events across the entire CuBIE package.
- property settings_dict: Dict[str, Any]
Return the given settings over the children’s retained values.
- solve(initial_values: ndarray | Dict[str, float | ndarray], parameters: ndarray | Dict[str, float | ndarray], drivers: Dict[str, Any] | None = None, duration: float = 1.0, settling_time: float = 0.0, t0: float = 0.0, blocksize: int | None = None, grid_type: str = 'verbatim', nan_error_trajectories: bool = True, on_device: bool = False, **kwargs: Any) SolveResult | DeviceSolveResult[source]
Solve a batch initial value problem.
- Parameters:
initial_values – Initial state values for each integration run. Accepts dictionaries mapping state names to values for grid construction, or pre-built arrays in (n_states, n_runs) format for fast-path execution. Device arrays (CuPy or Numba) are used in place with no host-to-device transfer; they must already match the system precision.
parameters – Parameter values for each run. Accepts dictionaries mapping parameter names to values, or pre-built arrays in (n_params, n_runs) format. Device arrays are accepted as for
initial_values.drivers – Driver samples or configuration matching
cubie.array_interpolator.ArrayInterpolator.duration – Total integration time. Default is
1.0.settling_time – Warm-up period before recording outputs. Default
0.0.t0 – Initial integration time. Default
0.0.blocksize – CUDA block size for this launch;
Nonelets the solver pick.grid_type – Strategy for constructing the integration grid from inputs. Only used when dict inputs trigger grid construction.
nan_error_trajectories – When
True(default), trajectories with nonzero status codes are automatically set to NaN, making failed runs easy to identify and exclude from analysis. WhenFalse, all trajectories are returned unchanged. Ignored whenon_deviceisTrue.on_device – When
True, skip the device-to-host copy of the output arrays and return aDeviceSolveResultholding the solver’s device output buffers plus the CUDA stream the solve ran on; see Notes. DefaultFalse.**kwargs – Additional options forwarded to
update(). See “Optional Arguments” in the docs for possibilities.
- Returns:
SolveResultowning the solve’s host output buffers — nothing is copied. Keep it alive while its data is needed: once it is garbage collected the solver reuses the buffers on its next run.as_numpy,as_numpy_per_summary, andas_pandasbuild RAM representations on demand; disk-backed results release their spill files onclose()or context exit.DeviceSolveResultwhenon_deviceisTrue.- Return type:
SolveResult or DeviceSolveResult
Notes
Input type detection determines the processing path:
Dictionary inputs trigger grid construction via
BatchInputHandlerPre-built numpy arrays with correct shapes skip grid construction for improved performance
Device arrays are used in place: no grid construction and no host-to-device transfer
device_initial_values/device_parametersre-run the previous solve’s inputs with nothing uploaded
When GPU memory is insufficient for the full batch, arrays are automatically chunked along the run axis.
on_device=Truereturns without synchronizing: buffer contents are valid once the returned stream is synchronized, and the nextsolve()on this solver overwrites them. A chunked run raisesValueError.
- property solve_info: SolveSpec
SolveSpec for the current settings, cached until they change.
- property state
Expose latest state outputs.
- property state_summaries
Expose state summary outputs.
- property status_codes
Expose integration status codes.
- property status_messages
Decode nonzero run status codes into named result flags.
- property stream
Return the CUDA stream used by this solver.
- property stream_group
Return the CUDA stream group assigned to this solver.
- property summaries_length
Expose the flattened summary length.
- property summarised_observable_indices
Expose summarised observable indices.
- property summarised_observables
List summarised observable labels.
- property summarised_state_indices
Expose summarised state indices.
- property summarised_states
List summarised state labels.
- property summary_legend_per_variable: dict[int, str]
Expose summary legends keyed by variable index.
- property summary_unit_modifications: dict[int, str]
Expose summary unit modifications keyed by variable index.
- property system_sizes
Expose cached system size metadata.
- update(updates_dict: Dict[str, Any] | None = None, silent: bool = False, **kwargs: Any) Set[str][source]
Record the given settings, resolve them and update the kernel.
Constants of the system are given by name;
Nonemakes a setting not given.
- update_memory_settings(updates_dict: Dict[str, Any] | None = None, silent: bool = False, **kwargs: Any) Set[str][source]
Update the memory settings.
- property warmup
Return the warm-up period length.