rom.rom_utils
Purpose: Provides the core utility infrastructure for data-driven reduced-order modeling workflows in scikit-rom, covering parameter sampling, snapshot management, basis construction and enrichment, full-to-reduced-order transformations, nonlinear solving, residual collection for hyperreduction training, and simulation data persistence.
Summary: Consolidates eighteen utility functions spanning the complete ROM lifecycle: parameter space sampling (Latin hypercube, Sobol, Gaussian), train/test splitting, POD basis update via SVD deflation, full-field reconstruction, Newton solvers for reduced and hyperreduced systems, residual collection for ECSW/ECM/DEIM offline training, ECM Gauss-point weight dictionary construction, and standardized data saving and loading. These utilities are designed to interoperate with all assembler classes and hyperreduction modules in the skrom package.
Authors: Suparno Bhattacharyya, Ali Hamza Abidi Syed
Functions
| Name | Description |
|---|---|
| collect_residuals | Evaluate and collect residuals for each training snapshot for ECSW/DEIM hyperreduction training. |
| collect_residuals_ecm | Collect per-element, per-Gauss-point residuals for ECM offline training. |
| collect_residuals_t | Collect residuals across groups of snapshots with optional downsampling. |
| compute_nonlinear_snapshots | Apply a nonlinear function to each full-order solution and parameter pair and stack results. |
| generate_gaussian_samples | Generate parameter samples from a centered, bounded multivariate normal distribution. |
| generate_lhs | Generate Latin hypercube samples for efficient parameter space coverage. |
| generate_sobol | Generate Sobol’ quasi-random samples for parameter studies and uncertainty quantification. |
| latin_hypercube_train_test_split | Split snapshot indices into train/test sets using ranked Latin hypercube ordering. |
| load_rom_data | Load saved ROM simulation data from a standard folder. |
| newton_hyper_rom_solver | Newton solver for nonlinear hyperreduced systems with user-supplied assembly function. |
| newton_hyper_rom_solver2 | Advanced Newton solver for hyperreduced systems with configurable linear backend and damping. |
| newton_solver_rom | General Newton solver for reduced-order systems with configurable linear backend. |
| reconstruct_solution | Reconstruct the full-order field from ROM coordinates, adding back the mean if required. |
| rom_data_gen | Save ROM simulation results and metadata to a standardized folder structure. |
| select_elements_and_gauss_weights | Build an element-to-Gauss-weight dictionary from flat ECM/DEIM index-weight pairs. |
| sobol_train_test_split | Split snapshot indices into train/test sets using Sobol-based ordering. |
| solve_linear | Solve a linear system ( A = ) with configurable backend and method. |
| train_test_split | Generate boolean train/test masks for a snapshot index set. |
| update_basis | Enrich the current reduced basis with new POD modes via SVD deflation and QR orthonormalization. |
collect_residuals
rom.rom_utils.collect_residuals(
NLS_train_ms,
NLS_train_mean,
V_sel,
reconstruct_solution,
Residual,
training_params,
assemble_kwargs,
extra_kwargs=None,
hyper_basis=None,
)Purpose: Evaluates the residual of the full-order model for each training snapshot and stacks the results into a matrix for use in ECSW- or DEIM-type hyperreduction offline training. For each snapshot, the procedure projects the snapshot to reduced coordinates, reconstructs the full field, evaluates the model residual, and accumulates the result.
collect_residuals_ecm
rom.rom_utils.collect_residuals_ecm(
NLS_train_ms,
NLS_train_mean,
V_sel,
reconstruct_solution,
Residual,
training_params,
assemble_kwargs,
extra_kwargs=None,
hyper_basis=None,
)Purpose: Computes and collects residuals at the element–Gauss-point level for ECM offline training. Returns a matrix with one block per snapshot, where each column corresponds to one (element, Gauss-point) pair in the linearized layout expected by ECM and ECM_from_skrom. This is the primary residual collection routine for the ECM training pipeline.
collect_residuals_t
rom.rom_utils.collect_residuals_t(
NLS_train_ms,
NLS_train_mean,
V_sel,
reconstruct_solution,
Residual,
training_params,
assemble_kwargs,
snapshot_downsampling=1,
extra_kwargs=None,
hyper_basis=None,
)Purpose: Extends collect_residuals to operate over groups of snapshots (e.g., collected in temporal segments or parameter windows), with optional downsampling via snapshot_downsampling to skip every (k)-th snapshot. Useful for time-dependent problems where the full snapshot set is too large for direct hyperreduction training.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| snapshot_downsampling | int | Stride for downsampling snapshots within each group; 1 retains all snapshots. |
1 |
compute_nonlinear_snapshots
rom.rom_utils.compute_nonlinear_snapshots(
non_linear_func,
fos_solutions,
param_list,
)Purpose: Applies a user-supplied nonlinear function to each (full-order solution, parameter) pair in the training set and stacks the outputs into a snapshot matrix for subsequent POD or hyperreduction analysis. Useful for computing derived quantities (e.g., nonlinear stress, flux) from stored solution fields.
generate_gaussian_samples
rom.rom_utils.generate_gaussian_samples(dimensions, bounds, num_points)Purpose: Generates random parameter samples from a multivariate normal distribution centered and scaled within the provided bounds. The mean is set to the midpoint of each dimension’s bounds and the standard deviation to (upper − lower) / 5. Note that samples are not clipped and may fall slightly outside the specified bounds.
generate_lhs
rom.rom_utils.generate_lhs(dimensions, num_points, bounds)Purpose: Generates Latin hypercube samples for efficient, space-filling coverage of the parameter domain. Avoids clustering by ensuring each subdivision of each parameter dimension contains exactly one sample, making it well-suited for training set design in moderate-to-high-dimensional parameter spaces.
generate_sobol
rom.rom_utils.generate_sobol(dimensions, num_points, bounds)Purpose: Generates Sobol’ quasi-random samples for parameter studies and uncertainty quantification. Sobol’ sequences provide superior uniformity compared to pseudo-random sampling, particularly in higher dimensions. num_points must be a power of two (e.g., 16, 32, 64).
latin_hypercube_train_test_split
rom.rom_utils.latin_hypercube_train_test_split(N_snap, train_percentage=0.8)Purpose: Splits snapshot indices into training and test sets using Latin hypercube ranked ordering, producing boolean masks for both sets. The Latin hypercube ordering ensures that the selected training indices are uniformly distributed across the index range rather than clustered.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| N_snap | int | Total number of snapshots. | required |
| train_percentage | float | Fraction of snapshots assigned to the training set. | 0.8 |
load_rom_data
rom.rom_utils.load_rom_data(self, rom_data_dir=None)Purpose: Loads ROM simulation data from a standardized folder produced by rom_data_gen. If self is not None, loaded data is set as attributes on the calling object; otherwise the data dictionary is returned directly.
newton_hyper_rom_solver
rom.rom_utils.newton_hyper_rom_solver(
assemble_func,
u,
tol=0.03,
maxit=200,
param=None,
)Purpose: Solves a nonlinear hyperreduced system using Newton’s method. The user supplies an assemble_func that accepts the current reduced state and returns the pair (system matrix, residual). Iterates until the residual norm falls below tol or maxit iterations are reached.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| assemble_func | callable | Function returning (K_r, f_r) given the current reduced state. |
required |
| u | ndarray | Initial reduced state vector. | required |
| tol | float | Convergence tolerance on the residual norm. | 0.03 |
| maxit | int | Maximum number of Newton iterations. | 200 |
| param | any or None | Optional parameter value forwarded to assemble_func. |
None |
newton_hyper_rom_solver2
rom.rom_utils.newton_hyper_rom_solver2(
J_rom_fn,
rhs_rom_fn,
u0,
*J_args,
tol=0.01,
maxit=50,
alpha=1.0,
damp_freq=40,
rhs_args=(),
linear_backend='numpy',
linear_method='cg',
linear_rtol=1e-08,
linear_atol=0.0,
linear_maxit=500,
petsc_pc='ilu',
petsc_options=None,
verbose=True,
)Purpose: An advanced Newton solver for hyperreduced systems offering full configurability of the linear solve backend, iterative method, damping schedule, and convergence criteria. Separates the Jacobian and right-hand side assembly into distinct callable arguments J_rom_fn and rhs_rom_fn for maximum flexibility. Suitable for large or specialized hyperreduced systems requiring preconditioned iterative linear solvers.
Key Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| J_rom_fn | callable | Function returning the reduced Jacobian matrix. | required |
| rhs_rom_fn | callable | Function returning the reduced right-hand side vector. | required |
| u0 | ndarray | Initial reduced state vector. | required |
| tol | float | Newton convergence tolerance. | 0.01 |
| maxit | int | Maximum Newton iterations. | 50 |
| alpha | float | Initial step size (damping factor). | 1.0 |
| damp_freq | int | Frequency (in iterations) at which damping is applied. | 40 |
| linear_backend | str | Linear solver backend: 'numpy' or 'petsc'. |
'numpy' |
| linear_method | str | Iterative method: 'cg', 'minres', or 'gmres'. |
'cg' |
| petsc_pc | str | PETSc preconditioner type when using PETSc backend. | 'ilu' |
| verbose | bool | If True, prints convergence information at each iteration. |
True |
newton_solver_rom
rom.rom_utils.newton_solver_rom(
assemble_func,
u0,
*args,
tol=0.01,
maxit=100,
alpha=1.0,
damp_freq=40,
linear_backend='numpy',
linear_method='cg',
linear_rtol=1e-08,
linear_atol=0.0,
linear_maxit=500,
petsc_pc='jacobi',
petsc_options=None,
verbose=True,
**kwargs,
)Purpose: General-purpose Newton solver for reduced-order systems, both linear and nonlinear. At each iteration, solves the linear system ( A = - ) using the configured backend and method, then updates the reduced state. Supports the same configurable linear backend, iterative method, and damping schedule as newton_hyper_rom_solver2.
reconstruct_solution
rom.rom_utils.reconstruct_solution(u_reduced, V_sel, mean)Purpose: Converts ROM coordinates (typically a low-dimensional vector of length ( r )) back to the full-order field by computing ( = V_{} _r + ), where ( ) is the mean snapshot. If mean is None, the mean term is omitted.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| u_reduced | ndarray | Reduced coordinate vector of length ( r ). | required |
| V_sel | ndarray, shape (N, r) | Selected reduced basis columns. | required |
| mean | ndarray or None | Mean snapshot vector; added back to the reconstructed field if provided. | required |
rom_data_gen
rom.rom_utils.rom_data_gen(save_kw, problem_path)Purpose: Saves ROM simulation results—including full-order solution snapshots and associated metadata—to a standardized folder structure at problem_path for reproducibility and downstream analysis. Requires a fos_solutions key to be present in the save_kw dictionary.
select_elements_and_gauss_weights
rom.rom_utils.select_elements_and_gauss_weights(
n_gauss_points,
element_indices,
weights,
)Purpose: Constructs an element-to-Gauss-weight dictionary from flat ECM or DEIM index-weight pairs. The returned dictionary maps each active element index to an array of per-Gauss-point weights, with unselected Gauss points assigned a weight of 0.0. Serves as a convenience wrapper when preparing ECM weights for downstream hyperreduced assembly.
Returns
| Name | Type | Description |
|---|---|---|
| element_gauss_weights | dict[int, list[float]] | Mapping {element_index: [weight_q0, weight_q1, ..., weight_qn]} for all elements containing at least one selected Gauss point. |
sobol_train_test_split
rom.rom_utils.sobol_train_test_split(N_snap, train_percentage=0.8)Purpose: Splits snapshot indices into training and test boolean masks using Sobol-based ordering. Analogous to latin_hypercube_train_test_split but uses Sobol’ sequence ranking for the index partitioning, providing an alternative space-filling split strategy.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| N_snap | int | Total number of snapshots. | required |
| train_percentage | float | Fraction of snapshots assigned to the training set. | 0.8 |
solve_linear
rom.rom_utils.solve_linear(
A,
b,
*,
backend='numpy',
method='cg',
rtol=1e-08,
atol=0.0,
maxit=500,
petsc_pc='jacobi',
petsc_options=None,
)Purpose: Solves the linear system ( A = ) with a configurable solver backend and iterative method. Method selection guidance:
- CG (
'cg'): For symmetric positive definite (SPD) matrices. - MINRES (
'minres'): For general symmetric matrices. - GMRES (
'gmres'): For non-symmetric or indefinite matrices.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| A | array_like or sparse matrix | System matrix. | required |
| b | ndarray | Right-hand side vector. | required |
| backend | str | Solver backend: 'numpy' or 'petsc'. |
'numpy' |
| method | str | Iterative method: 'cg', 'minres', or 'gmres'. |
'cg' |
| rtol | float | Relative convergence tolerance. | 1e-08 |
| atol | float | Absolute convergence tolerance. | 0.0 |
| maxit | int | Maximum number of iterations. | 500 |
| petsc_pc | str | PETSc preconditioner when using PETSc backend. | 'jacobi' |
train_test_split
rom.rom_utils.train_test_split(N_snap, N_sel=None, train_percentage=0.8)Purpose: Generates boolean train and test masks for a snapshot index set using simple sequential ordering without space-filling ranking. Optionally restricts to the first N_sel snapshots before splitting, enabling subselection of a smaller working set.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| N_snap | int | Total number of snapshots. | required |
| N_sel | int or None | If provided, restricts the index set to the first N_sel snapshots before splitting. |
None |
| train_percentage | float | Fraction of selected snapshots assigned to the training set. | 0.8 |
update_basis
rom.rom_utils.update_basis(V, W_mu, max_modes=5)Purpose: Enriches the current reduced basis V by incorporating new information from the data matrix W_mu. The procedure deflates out existing basis directions from W_mu, performs SVD on the deflated residual to extract new modes, appends up to max_modes new directions to V, and re-orthonormalizes the augmented basis via QR decomposition to maintain orthonormality. This incremental enrichment strategy avoids full recomputation of the basis when new snapshots become available.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| V | ndarray, shape (N, r) | Current orthonormal reduced basis. | required |
| W_mu | ndarray, shape (N, k) | New snapshot or residual data from which additional modes are extracted. | required |
| max_modes | int | Maximum number of new basis vectors to append from the SVD of the deflated residual. | 5 |