Data Preparation
bnode_core.data_generation.data_preperation
Dataset preparation module for BNODE raw data processing.
Module Description
This module processes raw FMU simulation data and creates prepared dataset files with train/validation/test splits. It applies transformations, filters trajectories, selects variables, and generates multiple dataset sizes from a single raw data source.
Command-line Usage
With uv (recommended):
uv run data_preperation [hydra_overrides]
In activated (uv) virtual environment:
data_preperation [hydra_overrides]
Direct Python execution:
python -m bnode_core.data_generation.data_preperation [hydra_overrides]
Example Commands
# Generate datasets with 128, 512, and 2048 samples
uv run data_preperation pModel.dataset_prep.n_samples=[128,512,2048]
# Apply temperature conversion transform
uv run data_preperation pModel.dataset_prep.transforms.temperature=temperature_k_to_degC
# Change validation/test fractions
uv run data_preperation pModel.dataset_prep.validation_fraction=0.15 pModel.dataset_prep.test_fraction=0.15
What This Module Does
1. Loads raw data HDF5 file and validates configuration
2. Removes failed simulation runs and filters trajectories by limits/expressions
3. Applies transformations (unit conversions, numerical derivatives, custom operations)
4. Selects requested variables (states, controls, outputs, parameters)
5. Extracts requested time window from trajectories
6. Creates train/validation/test splits with consistent common sets across dataset sizes
7. Generates multiple HDF5 dataset files (one per n_samples value)
8. Saves dataset-specific YAML configs alongside each HDF5 file
See main() function for entry point and run_data_preperation() for the complete pipeline.
Key Features
- Safely modifies data in temporary file before creating final datasets
- Common validation/test sets ensure fair comparison across dataset sizes
- Incremental dataset creation allows generating multiple sizes efficiently
- Comprehensive logging of filtering, transformation, and split statistics
- Supports external raw data sources (skip config validation)
Configuration
Uses Hydra for configuration management. Config loaded from 'data_generation.yaml'.
Key config sections: pModel.RawData (raw data metadata) and pModel.dataset_prep
(preparation settings).
load_and_validate_raw_data(cfg: data_gen_config) -> Tuple[h5py.File, Optional[RawDataClass]]
Load raw data HDF5 file and validate its configuration against current config.
Loads the raw data file and its companion YAML config, validates the config structure, and compares it to the current configuration. If differences are found (excluding creation_date), logs warnings and overwrites the current config with the loaded one to ensure consistency.
For external raw data sources (cfg.pModel.RawData.raw_data_from_external_source=True), skips config loading and validation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg
|
data_gen_config
|
Data generation configuration containing:
|
required |
Returns:
| Type | Description |
|---|---|
Tuple[File, Optional[RawDataClass]]
|
Tuple of (raw_data, raw_data_config) where:
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If raw data file or config file does not exist (unless external source). |
Notes
- Config comparison excludes creation_date field to avoid false mismatches.
- If config mismatch is detected, logs which keys differ and overwrites cfg.pModel.RawData.
- The raw data file is returned open; caller is responsible for closing it.
Source code in src/bnode_core/data_generation/data_preperation.py
get_position_in_raw_data_file(variable: str, temp_raw_data: h5py.File) -> list
Find the dataset and index position of a variable in the raw data HDF5 file.
Searches all '*_names' datasets in the HDF5 file to locate the specified variable. Returns the dataset name (without '_names' suffix) and the index within that dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
variable
|
str
|
Name of the variable to find (e.g., 'temperature', 'control_1'). |
required |
temp_raw_data
|
File
|
Open h5py.File handle to the raw data file. |
required |
Returns:
| Type | Description |
|---|---|
list
|
List [dataset_name, idx] where:
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If variable is not found in any dataset, or if found in multiple datasets. |
Source code in src/bnode_core/data_generation/data_preperation.py
transform_raw_data(cfg: data_gen_config, temp_raw_data: h5py.File, raw_data_config: RawDataClass) -> None
Apply configured transformations to variables in the raw data file.
Performs in-place transformations on raw data variables according to the transforms specified in cfg.pModel.dataset_prep.transforms. Each variable can have one transform applied. The function modifies the data directly in the temp_raw_data HDF5 file.
Supported transforms
- 'temperature_k_to_degC': Convert from Kelvin to Celsius (subtract 273.15)
- 'power_w_to_kw': Convert from Watts to kilowatts (divide by 1000)
- 'differentiate': Compute numerical derivative using Akima interpolation. Also updates states_der if present. Logs interpolation error statistics.
- 'evaluate_python_
': Evaluate arbitrary Python expression where '#' is replaced with the data array reference (e.g., 'evaluate_python_#/100' divides by 100)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg
|
data_gen_config
|
Data generation configuration. cfg.pModel.dataset_prep.transforms is a dict mapping variable names to transform names. |
required |
temp_raw_data
|
File
|
Open h5py.File handle to the temporary raw data file (modified in-place). |
required |
raw_data_config
|
RawDataClass
|
Raw data configuration (used for context, not directly modified). |
required |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If an unsupported transform name is specified. |
Notes
- For 'differentiate': Uses scipy.interpolate.Akima1DInterpolator with 'makima' method. Computes 0th, 1st, and optionally 2nd derivatives. Logs mean and max interpolation errors normalized by standard deviation.
- For 'evaluate_python_': The command is split on '#' and reconstructed with
temp_raw_data[dataset_name][:, idx]as the data reference. Use caution with arbitrary code execution. - Transform operations are logged for each variable.
Source code in src/bnode_core/data_generation/data_preperation.py
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 | |
replace_hdf5_dataset(dataset_name: str, raw_data: h5py.File, data: np.ndarray, remove: bool = False)
Replace or remove a dataset in an HDF5 file.
Updates an existing dataset in the HDF5 file with new data. If the new data has a different shape than the existing dataset, or if remove=True, deletes the old dataset. If remove=True, no new dataset is created.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
str
|
Name of the dataset to replace (e.g., 'states', 'controls'). |
required |
raw_data
|
File
|
Open h5py.File handle to the HDF5 file. |
required |
data
|
ndarray
|
New data array to write (ignored if remove=True). |
required |
remove
|
bool
|
If True, delete the dataset without creating a replacement. |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If dataset_name does not exist in the HDF5 file. |
Notes
- If shapes match and remove=False, overwrites data in-place using [...] assignment.
- If shapes differ, deletes old dataset and creates new one with the provided data.
- If remove=True, only deletes the dataset (used for cleanup).
Source code in src/bnode_core/data_generation/data_preperation.py
run_data_preperation(cfg: data_gen_config)
Main orchestration function for dataset preparation pipeline.
Complete dataset preparation workflow:
- Load and validate raw data HDF5 file and config
- Copy raw data to temporary file for safe manipulation
- Remove failed simulation runs
- Filter trajectories based on configured limits and expressions
- Apply transformations (unit conversions, derivatives, etc.)
- Select only requested variables (states, controls, outputs, parameters)
- Select requested time window
- Create common validation and test sets
- Generate multiple dataset files with different sample counts
- Save dataset-specific configs and clean up temporary files
The function creates one or more dataset HDF5 files (based on cfg.pModel.dataset_prep.n_samples list) with train/validation/test splits plus common_validation and common_test sets that are consistent across all dataset sizes.
This is the Hydra-decorated entry point called by main().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg
|
data_gen_config
|
Data generation configuration (automatically populated by Hydra from YAML + CLI args). Key settings include:
|
required |
Workflow details
- Failed runs (from 'failed_idx' or 'logs/completed') are removed.
- Filtering can exclude trajectories based on min/max limits or Python expressions.
- Transforms are applied in the order specified in the config.
- Variables not in the selection lists are removed to reduce file size.
- Time window selection adjusts sequence_length accordingly.
- Common test/validation sets are created from the full raw data and stored in each dataset file. Smaller datasets use proportionally fewer train samples but keep the same validation/test examples.
- Each dataset file gets a companion YAML config with the pModel settings and dataset-specific n_samples.
- Temporary HDF5 file is deleted after all datasets are created.
Notes
- The temporary file (temp_raw_data.hdf5) is created in the current directory.
- Dataset file paths determined by filepath_dataset(cfg, n_samples).
- Config paths determined by filepath_dataset_config(cfg, n_samples).
- Creation date is recorded in each dataset file's 'creation_date' attribute.
- If n_samples in the list exceeds raw data sample count, it's clamped and logged.
Source code in src/bnode_core/data_generation/data_preperation.py
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 | |
main()
CLI entry point for dataset preparation.
Sets up Hydra configuration management and launches run_data_preperation(). Displays help message if --help or -h is provided.
Hydra automatically:
- Loads the data_generation.yaml config from the auto-detected config directory
- Parses command-line overrides
- Creates a working directory for outputs
- Injects the composed config into run_data_preperation()
Usage
python data_preperation.py [overrides]
python data_preperation.py --help
python data_preperation.py --hydra-help
Examples:
python data_preperation.py pModel.dataset_prep.n_samples=[128,512,2048]
python data_preperation.py pModel=SHF pModel.dataset_prep.validation_fraction=0.15
python data_preperation.py pModel.dataset_prep.transforms.temperature=temperature_k_to_degC
Notes
- The standard config file used is 'data_generation.yaml' (same as raw_data_generation.py).
- Config directory is auto-detected using config_dir_auto_recognize().
- You can override config path and direcotory using Hydra CLI options "-cp"/"--config-path" and/or "-cd"/"--config-dir"
- Hydra overrides can modify any config field from the command line.