Skip to content

scirex.data

Dataset loaders, containers and normalisers.

from scirex.data import load_darcy_flow_small
Group Names
Loaders load_darcy_flow_small, load_darcy_pt, load_navier_stokes_pt, load_cavity_kepsilon, load_airfrans, load_shapenet_car
Containers TensorDataset, DictDataset
Processing DefaultDataProcessor, UnitGaussianNormalizer

load_airfrans and load_shapenet_car read .vtk meshes and need the benchmark extra. The data of each benchmark is described in the dataset guides.

Dataset loaders

load_darcy_flow_small, load_darcy_pt and load_navier_stokes_pt return a training loader, a dict of test loaders keyed by resolution and a data processor. The other loaders return a dict of arrays; see each docstring. load_airfrans and load_shapenet_car need the benchmark extra (they read .vtk meshes).

load_darcy_flow_small

load_darcy_flow_small(
    n_train: int,
    n_tests: list[int],
    batch_size: int,
    test_batch_sizes: list[int],
    data_root: Path | str = example_data_root,
    test_resolutions: Sequence[int] = (16, 32),
    encode_input: bool = False,
    encode_output: bool = True,
    encoding: str = "channel-wise",
    channel_dim: int = 1,
) -> tuple[
    DataLoader, dict[int, DataLoader], DefaultDataProcessor
]

Load the small 2D Darcy flow dataset (16x16 training resolution).

Args:

Name Type Description Default
n_train int

Number of training samples.

n_tests list of int

Number of test samples for each test resolution.

batch_size int

Batch size of the training loader.

test_batch_sizes list of int

Batch size of the test loader for each test resolution.

data_root Path or str

Directory holding (or receiving) the data files; missing files are downloaded from Zenodo.

example_data_root
test_resolutions sequence of int

Resolutions of the test sets, by default [16, 32].

(16, 32)
encode_input bool

Whether the returned data processor normalizes inputs, by default False.

False
encode_output bool

Whether the returned data processor normalizes outputs, by default True.

True
encoding str

"channel-wise" or "pixel-wise" normalization, by default channel-wise.

'channel-wise'
channel_dim int

Axis that holds data channels, by default 1.

1

Returns:

Name Type Description
train_loader DataLoader

Batches of the training set.

test_loaders dict of int to DataLoader

Test loaders keyed by test resolution.

data_processor DefaultDataProcessor

Processor holding the fitted normalizers.

load_darcy_pt

load_darcy_pt(
    n_train: int,
    n_tests: list[int],
    batch_size: int,
    test_batch_sizes: list[int],
    data_root: Path | str = "./neuralop/data/datasets/data",
    train_resolution: int = 16,
    test_resolutions: Sequence[int] = (16, 32),
    encode_input: bool = False,
    encode_output: bool = True,
    encoding: str = "channel-wise",
    channel_dim: int = 1,
    num_workers: int = 1,
) -> tuple[
    DataLoader, dict[int, DataLoader], DefaultDataProcessor
]

Load the 2D Darcy flow dataset from local .pt files (no download).

Args:

Name Type Description Default
n_train int

Number of training samples.

n_tests list of int

Number of test samples for each test resolution.

batch_size int

Batch size of the training loader.

test_batch_sizes list of int

Batch size of the test loader for each test resolution.

data_root Path or str

Directory that already contains the darcy_train_<res>.pt and darcy_test_<res>.pt files.

'./neuralop/data/datasets/data'
train_resolution int

Resolution of the training set, by default 16.

16
test_resolutions sequence of int

Resolutions of the test sets, by default [16, 32].

(16, 32)
encode_input bool

Whether the returned data processor normalizes inputs, by default False.

False
encode_output bool

Whether the returned data processor normalizes outputs, by default True.

True
encoding str

"channel-wise" or "pixel-wise" normalization, by default channel-wise.

'channel-wise'
channel_dim int

Axis that holds data channels, by default 1.

1
num_workers int

Accepted for API compatibility; the loader batches in-process. By default 1.

1

Returns:

Name Type Description
train_loader DataLoader

Batches of the training set.

test_loaders dict of int to DataLoader

Test loaders keyed by test resolution.

data_processor DefaultDataProcessor

Processor holding the fitted normalizers.

load_navier_stokes_pt

load_navier_stokes_pt(
    n_train: int,
    n_tests: list[int],
    batch_size: int,
    test_batch_sizes: list[int],
    data_root: Path | str = example_data_root,
    train_resolution: int = 128,
    test_resolutions: Sequence[int] = (128,),
    encode_input: bool = False,
    encode_output: bool = True,
    encoding: str = "channel-wise",
    channel_dim: int = 1,
    subsampling_rate: int | list[int] | None = None,
    num_workers: int = 1,
) -> tuple[
    DataLoader, dict[int, DataLoader], DefaultDataProcessor
]

Load the 2D Navier-Stokes dataset (nsforcing files from Zenodo).

Args:

Name Type Description Default
n_train int

Number of training samples.

n_tests list of int

Number of test samples for each test resolution.

batch_size int

Batch size of the training loader.

test_batch_sizes list of int

Batch size of the test loader for each test resolution.

data_root Path or str

Directory holding (or receiving) the data files; missing files are downloaded from Zenodo.

example_data_root
train_resolution int

Resolution of the training set, by default 128.

128
test_resolutions sequence of int

Resolutions of the test sets, by default [128].

(128,)
subsampling_rate int or list of int

Rate at which each input dimension is subsampled, by default None.

None
encode_input bool

Whether the returned data processor normalizes inputs, by default False.

False
encode_output bool

Whether the returned data processor normalizes outputs, by default True.

True
encoding str

"channel-wise" or "pixel-wise" normalization, by default channel-wise.

'channel-wise'
channel_dim int

Axis that holds data channels, by default 1.

1
num_workers int

Accepted for API compatibility; the loader batches in-process. By default 1.

1

Returns:

Name Type Description
train_loader DataLoader

Batches of the training set.

test_loaders dict of int to DataLoader

Test loaders keyed by test resolution.

data_processor DefaultDataProcessor

Processor holding the fitted normalizers.

load_cavity_kepsilon

load_cavity_kepsilon(
    data_dir: str | Path,
    cache_dir: str | Path | None = None,
    use_cache: bool = True,
    n_test_frac: float = 0.1,
    seed: int = 0,
    verbose: bool = True,
    cases: tuple[str, ...] | None = None,
) -> dict

Loads the full Transient k-epsilon cavity dataset into two dense arrays (train/test), normalized.

Args:

Name Type Description Default
data_dir path

Root Transient_k-e directory (holds 01k/, 02k/, ...).

cache_dir path

If given, each case's raw (steps, P, U, pos) is cached to <cache_dir>/<case>.npz after the first CSV read (CSV parsing of ~900 33k-row files is the dominant one-time cost; cached loads are near-instant).

None
n_test_frac float

Fraction of ALL (case, step) snapshots held out as test, via a global random shuffle (so the split spans all selected lid speeds, testing interpolation across time within each case rather than extrapolation to an unseen lid speed).

0.1
seed int

Seed for the train/test shuffle.

0
cases tuple[str, ...]

Which case folders to load, e.g. ("01k", "02k", "04k") for a subset. Defaults to the module-level CASES (the full 5-case set) when not given, so existing callers are unaffected.

None

Returns:

Type Description
dict with keys:

pos : (16641, 2) shared mesh coordinates, UN-normalized (metres). X_train, Y_train, X_test, Y_test : dense (n, 16641, 4) / (n, 16641, 3) float32 arrays, normalized. meta_train, meta_test : (n, 2) int arrays of (case_index, step) per sample, for bookkeeping/plotting (cases[case_index] -- the cases key below, NOT necessarily the module-level CASES -- recovers the case string). cases : the resolved case tuple actually used (either the cases argument, or module-level CASES if omitted). coef_norm : (mean_in, std_in, mean_out, std_out), computed over the train split only and already applied to both splits. model_kwargs : dict(space_dim=4, fun_dim=0, out_dim=3, unified_pos=False, geometry="irregular").

load_airfrans

load_airfrans(
    data_dir: str | Path,
    n_test: int = 100,
    seed: int = 0,
    cache_dir: str | Path | None = None,
    use_cache: bool = True,
    max_cases: int | None = None,
    task: str | None = None,
    manifest_path: str | Path | None = None,
) -> dict

Loads the AirfRANS dataset with a fixed train/test split.

Args:

Name Type Description Default
data_dir path

Root directory holding one sub-folder per simulation case (see this module's docstring).

n_test int

Number of cases held out as the "unseen" test split. Ignored when task is given.

100
seed int

Seed for the train/test shuffle -- deterministic and reproducible across training/inference runs (both must pass the same seed). Ignored when task is given.

0
cache_dir path

If given, each case's computed (x, y, pos, surf) arrays are cached to <cache_dir>/<case_id>.npz after the first VTK read.

None
use_cache bool

Whether to read from cache_dir if a cached .npz already exists there.

True
max_cases int

If given, only the first max_cases case ids (after sorting, before the shuffle) are used in total -- for fast smoke tests. Ignored when task is given.

None
task str or None

One of "full", "scarce", "reynolds" or "aoa"; by default None (a random split). If given, use the AirfRANS paper's own official train/test case-id split for that benchmark task, read from manifest_path (the <task>_train/<task>_test keys of Dataset/manifest.json, e.g. "full" -> 800 train / 200 test) instead of a random split -- makes results directly comparable to the paper's Table 2/3 baselines. Overrides n_test, seed, and max_cases.

None
manifest_path path

Path to the official split manifest (JSON with {task}_train/{task}_test keys of case-id lists). Only used when task is given. Defaults to <data_dir>/manifest.json.

None

Returns:

Type Description
dict with keys:

train : list of per-sample dicts (x, y, pos, surf, case_id), normalized, NOT stacked (point count varies). test : same structure, for the held-out split. coef_norm : (mean_in, std_in, mean_out, std_out) -- per-channel population mean/std (ddof=0, eps=1e-8) over the training split's points only, already applied to both splits. model_kwargs : dict(space_dim=7, fun_dim=0, out_dim=4, unified_pos=False, geometry="irregular"), ready to pass into scirex.models.transolver.Transolver.

load_shapenet_car

load_shapenet_car(
    data_dir: str | Path,
    fold_id: int = 0,
    cache_dir: str | Path | None = None,
    use_cache: bool = True,
) -> dict

Loads the Car-Design-ShapeNetCar dataset for one train/val fold split.

Args:

Name Type Description Default
data_dir path

Root directory of the raw dataset (param0/ .. param8/, each a folder of per-sample subdirectories -- see this module's docstring).

fold_id int

Which of the 9 folds to hold out as the validation split; the other 8 folds become the training split. Matches main.py's --fold_id (default 0).

0
cache_dir path

If given, each sample's computed (x, y, pos, surf) arrays are cached to <cache_dir>/<fold>_<sample_id>.npz after the first VTK read, and reloaded from there on subsequent calls (use_cache=True) -- mirrors the reference's --save_dir/--preprocessed workflow, skipping the expensive VTK/SDF/normal computation on reruns.

None
use_cache bool

Whether to read from cache_dir if a cached .npz already exists there. Set False to force recomputation (e.g. after changing the raw data) while still writing fresh caches.

True

Returns:

Type Description
dict with keys:

train : list of per-sample dicts (x: (N_i, 7), y: (N_i, 4), pos: (N_i, 3), surf: (N_i,) bool, sample_rel_path: str e.g. "param3/1a0bc9ab...") -- NOT stacked, since N_i (point count) varies per car mesh. sample_rel_path is only used by drag-coefficient evaluation (shapenet_car_drag.py) to locate the sample's raw quadpress_smpl.vtk for cell/normal geometry; ignore it for training. val : same structure, for the held-out fold. coef_norm : (mean_in, std_in, mean_out, std_out), each a (7,) or (4,) numpy array -- per-channel population mean/std (ddof=0, eps=1e-8) computed over the training split only, already applied to both train and val's x/y (matching dataset.py::get_datalist's normalization, which fits on train and applies the same stats to val -- no leakage). model_kwargs : dict(space_dim=7, fun_dim=0, out_dim=4, unified_pos=False, geometry="irregular"), ready to pass into scirex.models.transolver.Transolver.

Containers

TensorDataset

TensorDataset(
    x: Array,
    y: Array,
    transform_x: Callable[[Array], Array] | None = None,
    transform_y: Callable[[Array], Array] | None = None,
)

In-memory dataset pairing an input array x with a target array y.

Indexing returns a dictionary {"x": ..., "y": ...} so samples can be passed to a data processor and the trainer directly.

Args:

Name Type Description Default
x Array

Input samples; the first axis indexes samples.

y Array

Target samples; must have the same size along the first axis as x.

transform_x callable

Applied to each selected x when it is accessed.

None
transform_y callable

Applied to each selected y when it is accessed.

None

DictDataset

DictDataset(
    data_list: list[dict], constant: dict | None = None
)

DictDataset is a basic dataset form that stores each batch as a dictionary of tensors or other data structures

Create the dataset.

Args:

Name Type Description Default
data_list List[dict]

list of individual batch dictionaries

constant dict

if each data batch shares some constant valued key/val pairs, they can be stored in constant for simplicity

None

Processors and normalisers

DefaultDataProcessor

DefaultDataProcessor(
    in_normalizer: Any | None = None,
    out_normalizer: Any | None = None,
)

DefaultDataProcessor is a simple processor to pre/post process data before training/inferencing a model.

Plain Python class (not a Flax nn.Module) so that training mode can be tracked as ordinary mutable state via train() / eval() calls.

Args:

Name Type Description Default
in_normalizer Transform

normalizer (e.g. UnitGaussianNormalizer) for the input samples

is None
out_normalizer Transform

normalizer (e.g. UnitGaussianNormalizer) for the target and predicted samples

is None

train

train() -> None

Switch to training mode (targets are normalized in preprocessing).

eval

eval() -> None

Switch to evaluation mode (outputs are denormalized in postprocessing).

to

to(device: str) -> DefaultDataProcessor

Record the target device name and return self.

wrap

wrap(model: Module) -> DefaultDataProcessor

Attach a model so the processor can run a full forward pass via call.

preprocess

preprocess(data_dict: dict, batched: bool = True) -> dict

Pre-process a batch: convert to JAX arrays and apply input normalization.

During training also normalizes the target y so the loss is computed in normalized space.

Args:

Name Type Description Default
data_dict dict

Must contain keys 'x' and 'y'.

batched bool

Unused; kept for API compatibility, by default True

True

Returns:

Type Description
dict

Preprocessed data_dict with JAX arrays.

postprocess

postprocess(
    output: ndarray,
    data_dict: dict,
    training: bool | None = None,
) -> tuple[jnp.ndarray, dict]

Post-process model output: denormalize during evaluation.

Args:

Name Type Description Default
output ndarray
data_dict dict
training bool or None

If None (default), uses self.training set by train()/eval() calls.

None

Returns:

Type Description
(output, data_dict)

UnitGaussianNormalizer

Normalizes data to zero mean and unit std. Implemented as a Flax PyTreeNode for functional purity and JAX compatibility.

Every method that updates statistics returns a new instance; the original is never modified. Create one with create, fit it with fit or partial_fit, then use transform and inverse_transform.

create classmethod

create(
    eps: float = 1e-07,
    axis: int | Sequence[int] | None = None,
    mask: ndarray | None = None,
) -> UnitGaussianNormalizer

Initialize the normalizer.

fit

fit(data_batch: ndarray) -> UnitGaussianNormalizer

Returns a NEW instance of the normalizer with updated stats.

partial_fit

partial_fit(
    data_batch: ndarray, batch_size: int = 1
) -> UnitGaussianNormalizer

Incrementally fits the normalizer and returns the updated instance.

update_mean_std

update_mean_std(
    data_batch: ndarray,
) -> UnitGaussianNormalizer

Compute the statistics of data_batch from scratch.

Args:

Name Type Description
data_batch ndarray

Data to take the mean and standard deviation of, reduced over axis.

Returns:

Type Description
UnitGaussianNormalizer

A new normalizer holding the mean, std, squared mean and element count of data_batch. Previously accumulated statistics are discarded.

incremental_update_mean_std

incremental_update_mean_std(
    data_batch: ndarray,
) -> UnitGaussianNormalizer

Merge the statistics of data_batch into the existing ones.

Requires statistics from an earlier update_mean_std call (as in partial_fit).

Args:

Name Type Description
data_batch ndarray

New samples to fold into the running mean and standard deviation.

Returns:

Type Description
UnitGaussianNormalizer

A new normalizer with the combined statistics and element count.

transform

transform(x: ndarray) -> jnp.ndarray

Normalize x to (x - mean) / (std + eps).

inverse_transform

inverse_transform(x: ndarray) -> jnp.ndarray

Undo transform: return x * (std + eps) + mean.

from_dataset classmethod

from_dataset(
    dataset: Iterable[dict],
    axis: int | Sequence[int] | None = None,
    keys: Iterable[str] | None = None,
    mask: ndarray | None = None,
) -> dict[str, UnitGaussianNormalizer]

Fit one normalizer per dictionary key by streaming over dataset.

Args:

Name Type Description Default
dataset iterable of dict

Samples, each a dict of arrays (a sample is fit as a batch of one).

axis int or sequence of int

Axes to reduce over, see create.

None
keys iterable of str

Entries to normalize. Defaults to all keys of the first sample.

None
mask ndarray

Mask passed to every normalizer, see create.

None

Returns:

Type Description
dict of str to UnitGaussianNormalizer

One fitted normalizer per key.