State I/O
The state I/O module provides functions to save and load MOBIDIC simulation state variables in NetCDF format, enabling simulation restart and state analysis.
Overview
State files store:
- Grid variables: Capillary water (Wc), gravitational water (Wg), plant water (Wp), surface water (Ws)
- Network variables: Discharge, lateral inflow for each reach
- Metadata: Simulation time, grid coordinates, CRS, global attributes
- CF-1.12 compliance: NetCDF Climate and Forecast metadata conventions
State files enable:
- Warm start: Resume simulations from saved state
- State analysis: Examine spatial patterns of soil moisture, discharge
- Model evaluation: Compare simulated states against observations
- Ensemble runs: Initialize multiple simulations from different states
- Large simulations: Automatic file chunking for simulations exceeding size limits
Classes and functions
Incremental NetCDF state writer with buffering, flushing, and automatic chunking.
This class manages writing simulation states to NetCDF files across multiple timesteps, with configurable memory buffering, periodic flushing to disk, and automatic file chunking when size limits are reached.
File chunking occurs when the current file reaches max_file_size before a new flush. For effective chunking, flushing must be set to a positive integer (e.g., flush every N timesteps). If flushing=-1 (flush only at end), all data is written in one operation and chunking may not work as expected.
Note: Files may slightly exceed max_file_size by up to one flush worth of data, since the size check occurs before writing each flush batch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_path
|
str | Path
|
Path to output NetCDF file (will be created/overwritten) |
required |
grid_metadata
|
dict
|
Dictionary with grid metadata (shape, resolution, crs, etc.) |
required |
network_size
|
int
|
Number of reaches in network |
required |
output_states
|
OutputStates
|
Configuration object specifying which state variables to save |
required |
flushing
|
int
|
Flush interval (positive int = every N steps, -1 = only at end) |
-1
|
max_file_size
|
float
|
Maximum file size in MB before creating a new chunk (default: 500) |
500.0
|
add_metadata
|
dict | None
|
Additional global attributes (optional) |
None
|
Examples:
>>> # With automatic chunking at 500 MB
>>> writer = StateWriter("states.nc", metadata, 1235, config.output_states,
... flushing=10, max_file_size=500)
>>> for step in range(num_steps):
... writer.append_state(state, current_time)
>>> writer.close()
>>> # This may create: states_001.nc, states_002.nc, states_003.nc, etc.
Source code in mobidic/io/state.py
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 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 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 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 | |
__enter__()
__exit__(exc_type, exc_val, exc_tb)
__init__(output_path, grid_metadata, network_size, output_states, flushing=-1, max_file_size=500.0, add_metadata=None, reservoir_size=0)
Initialize the state writer and create the NetCDF file.
Source code in mobidic/io/state.py
append_state(state, time)
Add a state to the buffer and flush if necessary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
SimulationState
|
SimulationState object containing state variables |
required |
time
|
datetime
|
Current simulation time |
required |
Source code in mobidic/io/state.py
close()
Flush any remaining buffered states and close the writer.
Source code in mobidic/io/state.py
flush()
Write buffered states to disk using efficient append mode.
Source code in mobidic/io/state.py
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 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 | |
Load simulation state from NetCDF file.
Supports both single-timestep and multi-timestep state files. For multi-timestep files, loads the specified time index (default: last timestep). Automatically detects chunk files (e.g., states_001.nc) when the base path doesn’t exist.
If a state variable is missing from the file, it will be initialized using the initial conditions from the configuration file (if config and gisdata are provided), otherwise grid variables will be initialized with zeros and network variables will be initialized with zeros.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_path
|
str | Path
|
Path to output NetCDF file (may be chunked as _001.nc, _002.nc, etc.) |
required |
network_size
|
int
|
Expected number of reaches in network. Validates consistency between the saved state and current model setup. |
required |
time_index
|
int
|
Index of timestep to load (default: -1 = last timestep) |
-1
|
config
|
MOBIDICConfig | None
|
Optional MOBIDIC configuration for initializing missing variables |
None
|
gisdata
|
GISData | None
|
Optional GIS data for initializing missing variables |
None
|
Returns:
| Type | Description |
|---|---|
tuple[SimulationState, datetime, dict]
|
Tuple of (state, time, metadata) where: - state: SimulationState object - time: Simulation time from file - metadata: Grid metadata dictionary |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If input file does not exist |
ValueError
|
If file format is invalid |
Examples:
>>> from mobidic.io import load_state
>>> # Load last timestep
>>> state, time, metadata = load_state("states.nc", 1235)
>>> # Load first timestep with config (for missing variables)
>>> state, time, metadata = load_state("states.nc", 1235, time_index=0,
... config=config, gisdata=gisdata)
>>> # Works with chunked files too
>>> state, time, metadata = load_state("states.nc", 1235) # Auto-loads states_001.nc
Source code in mobidic/io/state.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 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 | |
Examples
Saving states incrementally with StateWriter
from mobidic.io import StateWriter
from mobidic import load_config, load_gisdata
from datetime import datetime, timedelta
# Load configuration and data
config = load_config("config.yaml")
gisdata = load_gisdata("gisdata.nc", "network.parquet")
# Create StateWriter with flushing every 10 timesteps
with StateWriter(
output_path="output/states.nc",
grid_metadata=gisdata.metadata,
network_size=len(gisdata.network),
output_states=config.output_states,
flushing=10, # Flush every 10 timesteps (-1 = only at end)
max_file_size=500.0, # Create new chunk file when reaching 500 MB
add_metadata={
"simulation_version": "v1.0",
"calibration_run": "baseline",
"notes": "Calibration run with default parameters"
}
) as writer:
# Simulation loop
current_time = datetime(2020, 1, 1)
dt = timedelta(seconds=900) # 15-minute timesteps
for step in range(num_steps):
# ... run simulation step ...
# state = perform_simulation_step(...)
# Append state to file (buffered)
writer.append_state(state, current_time)
current_time += dt
# States are automatically flushed and file closed when exiting context
# May create: states_001.nc, states_002.nc, states_003.nc, etc.
# Alternatively, manually manage the writer
writer = StateWriter(
output_path="output/states.nc",
grid_metadata=gisdata.metadata,
network_size=len(gisdata.network),
output_states=config.output_states,
flushing=-1, # Only flush at end
max_file_size=500.0,
)
for step in range(num_steps):
# ... simulation ...
writer.append_state(state, current_time)
current_time += dt
writer.close()
Saving only final state
from mobidic.io import StateWriter
from datetime import datetime
# Create writer with flushing=-1 (only flush at end)
writer = StateWriter(
output_path="output/state_final.nc",
grid_metadata=gisdata.metadata,
network_size=len(gisdata.network),
output_states=config.output_states,
flushing=-1,
add_metadata={"run_type": "final_state"}
)
# Only save the final state
writer.append_state(final_state, datetime(2020, 12, 31, 23, 45))
writer.close()
Loading state for warm start
from mobidic.io import load_state
from mobidic import Simulation, load_config, load_gisdata
# Load last timestep from multi-timestep file (default)
state, time, metadata = load_state(
input_path="output/states.nc",
network_size=1235 # Number of reaches in network
)
print(f"Loaded state at {time}")
print(f"Grid shape: {metadata['shape']}")
print(f"Mean capillary water: {state.wc.mean():.3f} m")
print(f"Mean discharge: {state.discharge.mean():.3f} m³/s")
# Load specific timestep (e.g., first timestep)
state_first, time_first, _ = load_state(
input_path="output/states.nc",
network_size=1235,
time_index=0 # 0 = first, -1 = last (default)
)
# Load from single-timestep file
state_final, time_final, _ = load_state(
input_path="output/state_final.nc",
network_size=1235
)
# Load from chunked files (automatically detects chunk files)
# Even if you specify "states.nc", it will find and load "states_001.nc"
state_chunk, time_chunk, _ = load_state(
input_path="output/states.nc", # Auto-detects states_001.nc
network_size=1235
)
# Load with config and gisdata for proper missing variable initialization
# If the state file is missing some variables, they will be initialized
# using the initial conditions from the config file. If config/gisdata are not
# provided, missing variables are set to zero.
config = load_config("config.yaml")
gisdata = load_gisdata("gisdata.nc", "network.parquet")
state_with_init, time, metadata = load_state(
input_path="output/states.nc",
network_size=1235,
config=config, # Optional: for missing variable initialization
gisdata=gisdata # Optional: for missing variable initialization
)
# Use state to initialize simulation
sim = Simulation(gisdata, forcing, config)
sim.state = state # Override initial state
# Resume simulation from this state
results = sim.run("2020-06-15", "2020-12-31")
Handling missing variables
When loading a state file, some variables may be missing (e.g., if the file was saved with selective output). The load_state() function handles this automatically:
Without config/gisdata (default behavior):
# Missing variables are initialized with zeros
state, time, metadata = load_state("output/states.nc", network_size=1235)
# Grid variables (Wc, Wg, Ws, Wp) → initialized with zeros
# Network variables (discharge, lateral_inflow) → initialized with zeros
With config/gisdata (recommended for warm start):
from mobidic import load_config, load_gisdata
config = load_config("config.yaml")
gisdata = load_gisdata("gisdata.nc", "network.parquet")
# Missing variables are initialized using config initial conditions
state, time, metadata = load_state(
"output/states.nc",
network_size=1235,
config=config,
gisdata=gisdata
)
# Grid variables (Wc, Wg, Ws, Wp) → initialized from config.initial_conditions
# - Wc: Wc0 × Wcsat (with capacity factors and Wg_Wc_tr transition)
# - Wg: Wg0 × Wgsat (with capacity factors and Wg_Wc_tr transition)
# - Ws: config.initial_conditions.Ws
# - Wp: zeros (with NaN outside domain)
# - All grid variables: NaN outside domain (where flow_acc is NaN)
# Network variables (discharge, lateral_inflow) → initialized with zeros
Example: Loading a partial state file
# Suppose a state file was saved with only Wc and Wg enabled
# (soil_surface=false in config), but you need Ws for the new simulation
config = load_config("config.yaml")
gisdata = load_gisdata("gisdata.nc", "network.parquet")
# Load state with config - Ws will be initialized from config.initial_conditions.Ws
state, time, metadata = load_state(
"output/partial_state.nc",
network_size=1235,
config=config,
gisdata=gisdata
)
# Now state.ws is properly initialized (not zeros) and ready for simulation
print(f"Ws initialized from config: {state.ws.mean():.6f} m")
# The Simulation class automatically uses config-based initialization
sim = Simulation(gisdata, forcing, config)
sim.set_initial_state(state_file="output/partial_state.nc")
# Missing variables are automatically initialized using config
This ensures that warm-start simulations always have properly initialized state variables, even when loading from files that don’t contain all variables.
Inspecting state files
import xarray as xr
import matplotlib.pyplot as plt
# Open multi-timestep state file
ds = xr.open_dataset("output/states.nc")
# Examine contents
print(ds)
print(f"\nVariables: {list(ds.data_vars)}")
print(f"Coordinates: {list(ds.coords)}")
print(f"Number of timesteps: {len(ds.time)}")
print(f"Time range: {ds.time.values[0]} to {ds.time.values[-1]}")
# Plot capillary water content at last timestep
if "Wc" in ds:
fig, ax = plt.subplots(figsize=(10, 8))
ds["Wc"].isel(time=-1).plot(ax=ax, cmap="Blues", cbar_kwargs={"label": "Wc [m]"})
ax.set_title(f"Capillary Water Content at {ds.time.values[-1]}")
plt.savefig("output/Wc_map.png")
# Plot time series of mean soil moisture
if "Wc" in ds:
mean_wc = ds["Wc"].mean(dim=["x", "y"])
plt.figure(figsize=(12, 4))
mean_wc.plot()
plt.ylabel("Mean Wc [m]")
plt.title("Mean Capillary Water Content Over Time")
plt.grid(True)
plt.savefig("output/Wc_timeseries.png")
# Plot discharge along network at last timestep
if "discharge" in ds:
plt.figure(figsize=(12, 4))
plt.plot(ds["reach"], ds["discharge"].isel(time=-1), 'b-', linewidth=0.5)
plt.xlabel("Reach ID")
plt.ylabel("Discharge [m³/s]")
plt.title(f"River Discharge at {ds.time.values[-1]}")
plt.grid(True)
plt.savefig("output/discharge_profile.png")
# Plot discharge time series for a specific reach
if "discharge" in ds:
reach_id = 500 # Example reach
plt.figure(figsize=(12, 4))
ds["discharge"].isel(reach=reach_id).plot()
plt.ylabel("Discharge [m³/s]")
plt.title(f"Discharge Time Series for Reach {reach_id}")
plt.grid(True)
plt.savefig("output/discharge_ts.png")
ds.close()
Comparing states
import xarray as xr
import numpy as np
import matplotlib.pyplot as plt
# Load two state files to compare
ds1 = xr.open_dataset("output/states_run1.nc")
ds2 = xr.open_dataset("output/states_run2.nc")
# Compare capillary water at last timestep
if "Wc" in ds1 and "Wc" in ds2:
wc1_final = ds1["Wc"].isel(time=-1)
wc2_final = ds2["Wc"].isel(time=-1)
diff = wc1_final - wc2_final
print(f"Wc difference statistics (final timestep):")
print(f" Mean: {float(diff.mean()):.6f} m")
print(f" Std: {float(diff.std()):.6f} m")
print(f" Max abs diff: {float(np.abs(diff).max()):.6f} m")
# Plot difference
fig, ax = plt.subplots(figsize=(10, 8))
diff.plot(ax=ax, cmap="RdBu_r", center=0)
ax.set_title("Capillary Water Difference (Run1 - Run2)")
plt.savefig("output/Wc_diff.png")
# Compare time series
if "Wc" in ds1 and "Wc" in ds2:
mean_wc1 = ds1["Wc"].mean(dim=["x", "y"])
mean_wc2 = ds2["Wc"].mean(dim=["x", "y"])
plt.figure(figsize=(12, 4))
mean_wc1.plot(label="Run 1")
mean_wc2.plot(label="Run 2")
plt.ylabel("Mean Wc [m]")
plt.title("Mean Capillary Water Content Comparison")
plt.legend()
plt.grid(True)
plt.savefig("output/Wc_comparison.png")
ds1.close()
ds2.close()
Working with chunked state files
When saving very large simulations, StateWriter automatically splits the output into multiple chunk files when the size limit is reached:
from mobidic.io import StateWriter, load_state
from datetime import datetime, timedelta
# Create writer with 500 MB chunk size and regular flushing
# NOTE: For chunking to work effectively, flushing must be > 0
writer = StateWriter(
output_path="output/states.nc",
grid_metadata=gisdata.metadata,
network_size=len(gisdata.network),
output_states=config.output_states,
flushing=100, # Flush every 100 steps (required for chunking)
max_file_size=500.0, # 500 MB per chunk
)
# Run long simulation that generates > 500 MB of data
for step in range(10000):
writer.append_state(state, current_time)
current_time += dt
writer.close()
# This creates multiple files:
# - states_001.nc (500 MB)
# - states_002.nc (500 MB)
# - states_003.nc (200 MB)
# Loading automatically detects and uses the first chunk
state, time, metadata = load_state(
input_path="output/states.nc", # Automatically finds states_001.nc
network_size=1235
)
# Or load from a specific chunk directly
state_chunk2, time_chunk2, _ = load_state(
input_path="output/states_002.nc", # Load from second chunk
network_size=1235,
time_index=-1 # Last timestep in this chunk
)
Important notes about chunking:
- Files may slightly exceed
max_file_sizeby up to one flush worth of data - Size check occurs before writing each flush batch
- For effective chunking, set
flushing > 0(e.g., 10, 50, 100) - If
flushing=-1(flush only at end), all data writes in one operation and chunking won’t work as expected - Chunk files are numbered sequentially:
_001.nc,_002.nc,_003.nc, etc. - Existing chunk files are automatically removed when creating a new StateWriter with the same base path
Configuration control
State saving is controlled by the configuration file:
output_states:
discharge: true # Save river discharge
soil_capillary: true # Save capillary water (Wc)
soil_gravitational: true # Save gravitational water (Wg)
soil_plant: true # Save plant/canopy water (Wp)
soil_surface: true # Save surface water (Ws)
# Other state outputs (not yet implemented):
reservoir_states: false
surface_temperature: false
ground_temperature: false
aquifer_head: false
et_prec: false
output_states_settings:
output_format: "netCDF" # Format (currently only netCDF)
output_states: "final" # "all", "final", or "list"
output_interval: 3600 # Interval in seconds (for "all")
output_list: [0, 100, 200] # Timestep indices (for "list")
File structure
NetCDF state files contain:
Dimensions
time: Unlimited dimension for multiple timestepsx: Grid columnsy: Grid rowsreach: Number of reaches (if discharge enabled)
Coordinates
time(time): Simulation time [datetime64]x(x): X coordinates [m]y(y): Y coordinates [m]reach(reach): Reach indices [dimensionless]
Data variables
Wc(time, y, x): Capillary water content [m] (if enabled)Wg(time, y, x): Gravitational water content [m] (if enabled)Wp(time, y, x): Plant/canopy water content [m] (optional, if enabled)Ws(time, y, x): Surface water content [m] (if enabled)discharge(time, reach): River discharge [m³/s] (if enabled)lateral_inflow(time, reach): Lateral inflow to reaches [m³/s] (if enabled)crs(): Grid mapping (CRS metadata, scalar)
Global attributes
title: “MOBIDIC simulation states”source: “MOBIDICpy simulation”Conventions: “CF-1.12”history: Creation timestamp with MOBIDICpy version- Custom metadata from
add_metadataparameter
Chunked files
When a simulation produces very large state files, StateWriter automatically creates multiple chunk files:
- Naming convention:
states_001.nc,states_002.nc,states_003.nc, etc. - Size limit: Each chunk is limited to
max_file_sizeMB (default: 500 MB) - Independent files: Each chunk is a complete, self-contained NetCDF file with its own timesteps
- Sequential ordering: Chunks are created in temporal order as the simulation progresses
- Automatic detection:
load_state()automatically findsstates_001.ncwhen you specifystates.nc
Design features
- CF-1.12 compliant: Follows Climate and Forecast metadata conventions
- Incremental writing: StateWriter appends states to a single file with unlimited time dimension
- Automatic chunking: Splits large outputs into multiple files when size limit is reached (configurable via
max_file_size) - Memory efficient: Configurable buffering with periodic flushing to disk
- Fast append mode: Uses netCDF4 library for efficient appending (avoids read-concatenate-write)
- Compression: zlib compression (level 4) for efficient storage
- Selective saving: Only configured state variables are saved
- Context manager support: Automatic resource cleanup with
withstatement - Multi-timestep support: Can load any timestep from multi-timestep files
- Chunk file detection:
load_state()automatically finds chunk files (e.g.,_001.nc) when base path doesn’t exist - CRS preservation: Coordinate Reference System stored as WKT
- Robust error handling: Clear warnings for missing data or size mismatches
Error handling
The module provides clear error messages for common issues:
from mobidic.io import load_state
try:
state, time, metadata = load_state("missing_file.nc", 1235)
except FileNotFoundError as e:
print(f"Error: {e}")
try:
state, time, metadata = load_state("state.nc", 5000) # Wrong network size
except ValueError as e:
print(f"Warning: {e}") # Warning about size mismatch, but loads anyway
References
File format:
- NetCDF4 with CF-1.12 conventions
- Uses xarray for reading/writing
- Compatible with standard NetCDF tools (ncdump, ncview, Panoply)
Related modules:
- Simulation - Uses state I/O for warm start and final states
- Report I/O - Time series output (Parquet format)