Skip to content
ml-rustPublic

About

Rust hydraulic simulation library for river and floodplain flow, built on numr and solvr.

Resources

Contributing

Stars

2 stars

Watchers

1 watching

Forks

Latest commit

 

History

297 Commits

Folders and files

Repository files navigation

hydr

Hydrology and hydraulic simulation in Rust. Conservative. Reproducible. Multi-backend.

2D shallow-water surface flow, Modified Green-Ampt infiltration, subcatchment runoff, 1D river channels, storage pools, hydraulic structures and HDS-5 culverts, piped drainage (pinned EPA SWMM v5.2.4), and conservative coupled advancement on numr and solvr.

Docs · Crate · Components · Backends · Install · Quick Start · Examples · Contributing

Join the Discord

CI status crates.io docs.rs License GitHub stars

hydr is a pure-Rust (#![forbid(unsafe_code)]) numerical engine for building flood, river, urban drainage, and water-resources applications. Every component operates in canonical SI units (m, m³, m³/s, s) with f64 precision, atomic accepted steps, explicit capability declarations, and bitwise-reproducible checkpoints.

  • No GUI or proprietary solver lock-in: Native Rust workers call hydr directly as a library.
  • Built on the ml-rust stack: numr provides tensor storage and CPU/CUDA kernels; solvr provides certified root-finding, quadrature, and interpolation; hydr owns hydraulic equations, admission rules, and conservation.
  • Conservative by construction: Negative water rejects without silent clipping. Coupled coordinators reserve native outflow before interface withdrawals and commit shared signed transfer volumes atomically.
  • Explicit scope: Every component exports <component>_capabilities() -> &'static ComponentCapabilities declaring precision, arithmetic contracts, runtimes, regimes, unsupported cases, and limits.

Installation

Requires Rust 1.95 or newer. Add hydr and numr:

cargo add hydr numr                  # CPU F64 reference + F32 opt-in profile
cargo add hydr --features cuda       # NVIDIA GPUs (F64 + F32, CUDA 12.8+ or 13.x)
cargo add hydr --features wgpu       # WebGPU (F32 native on Vulkan, Metal, DX12)

For piped urban drainage (hydr::drainage and SurfaceDrainageBatch), build the isolated pinned EPA SWMM v5.2.4 worker binary once on the host:

python3 tools/reference/swmm_drainage_build.py --help

See docs/drainage-reference.md for the pinned commit, build steps, and rollback verification.

Backends

hydr defaults to certified IEEE-754 f64 (Solver<R>, channels, pools, structures, and coupling) and offers an explicit opt-in f32 profile (SurfaceSolverF32<R>) for high-throughput CPU, CUDA, and WebGPU execution.

Runtime Feature F64 (default) F32 (opt-in SurfaceSolverF32) Notes
CpuRuntime default Checked reference Executed Deterministic reference profile; required for SwmmDrainage and SurfaceDrainageBatch
CudaRuntime cuda Executed parity Executed parity Verified on NVIDIA L4 (sm_89, CUDA 13.0)
WgpuRuntime wgpu Rejected cleanly Executed Native WebGPU (Vulkan, Metal, DX12) in F32; F64 rejects without silent fallback

Quick Start

Advance a 2D closed basin under constant rainfall and inspect the accepted water depth and conservation residual:

use hydr::grid::CartesianGrid;
use hydr::model::{CellState, Domain, FlowState, SpatialReference};
use hydr::soil::{LandCell, LandModel, SoilState};
use hydr::solver::{
    AdvanceStatus, BoundaryConditions, ForcingInterval, ForcingSchedule, InitialState, Solver,
    SolverConfig, SolverSetup,
};
use numr::runtime::cpu::{CpuClient, CpuDevice, ParallelismConfig};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = CpuClient::new(CpuDevice::new())
        .with_parallelism(ParallelismConfig::new(Some(1), None));

    let grid = CartesianGrid::new(5, 5, 10.0, 10.0)?;
    let n = grid.cell_count();
    let reference = SpatialReference::new(
        "projected metres".into(),
        "NAVD88".into(),
        [0.0, 0.0],
    )?;
    let domain = Domain::new(grid, vec![0.0; n], vec![0.03; n], vec![true; n], reference)?;
    let land = LandModel::new(&domain, vec![LandCell::Impervious; n])?;
    let soil = SoilState::initialized(&land)?;
    let flow = FlowState::new(&domain, vec![CellState { h: 0.0, qx: 0.0, qy: 0.0 }; n])?;

    let boundaries = BoundaryConditions::impermeable_walls();
    let forcing = ForcingSchedule::new(
        &domain,
        &boundaries,
        vec![ForcingInterval {
            start: 0.0,
            end: 60.0,
            rain: vec![1e-4; n],
            potential_evaporation: vec![0.0; n],
            withdrawal: vec![0.0; n],
            boundaries: Vec::new(),
        }],
    )?;

    let mut solver = Solver::new(
        client,
        SolverSetup {
            domain,
            land,
            boundaries,
            forcing,
            config: SolverConfig::default(),
        },
        InitialState { time: 0.0, flow, soil },
    )?;

    let report = solver.advance_to(60.0, 10_000)?;
    assert_eq!(report.status, AdvanceStatus::ReachedTarget);

    let depth = solver.state()?.cells()[12].h;
    let residual = solver.ledger().residual;
    println!("t={} s, center depth={depth:.6} m, mass residual={residual:e} m³", solver.time());
    Ok(())
}

Component Catalog

Applications depend only on the hydr facade crate. Every module re-exports its types and capability declarations:

Module What it computes Guide
hydr::solver 2D shallow-water finite-volume flow (hydrostatic bed reconstruction, HLL fluxes, Manning friction, 5 physical open boundary kinds, forecast splicing, checkpoints) Integration, Numerics, Boundaries
hydr::soil Pinned Modified Green-Ampt infiltration, capped evaporation, and prescribed withdrawals with complete soil memory Soil, Land sources
hydr::runoff Nonlinear reservoir and three-subarea subcatchment runoff with explicit rainfall ownership and contributing-support checks Subcatchment, Reservoir, Support
hydr::channel 1D rectangular, triangular, and certified surveyed river reaches with 6 endpoint policies, lateral momentum, and section epoch schedules Channels, Cross-sections, Prismatic bounds
hydr::storage Closed level-pool storage with piecewise-linear stage-volume curves, local rain/losses, and curve epoch schedules Level pools
hydr::structures Weir, orifice, hydrostatic gate, pump, and full HDS-5 inlet/outlet culvert laws (6 barrel shapes, blockage, sediment, closure), sampled controls, gate actuators, and geometry schedules Structures, Controls, Actuators
hydr::drainage Safe Rust wrapper over the isolated pinned EPA SWMM v5.2.4 piped drainage worker (EXTRAN/SLOT surcharge, live external link actuation, complete hidden-state rollback and restart) Piped drainage, Reference worker
hydr::coupling Conservative coordinators (CoupledLevelPoolBatch, ChannelPoolBatch, RunoffPoolBatch, SurfaceChannelBatch, SurfaceDrainageBatch) with exclusive parameter/control authority and certified crossing localization Surface/channels, Surface/drainage, Channel/pools
hydr::capability Stable machine-readable ComponentCapabilities declarations backed by admission and runtime evidence tests Read capabilities

Numerical Guarantees and Scope Limits

  • Atomic steps and rollback: Every engine advances via trial steps that shorten on CFL, donor-depletion, or convergence limits. Unaccepted or failed trials leave accepted state unchanged.
  • Complete portable checkpoints: Every component exports typed *SnapshotData packages with explicit schema and contract headers for exact bitwise restart and forecast splicing.
  • Exclusive parameter and control authority: Coordinators reject duplicate writers across structure operations, static blockage/closure conditions, geometry schedules, native SWMM [CONTROLS], and external hydr link commands.
  • Declared limits: First-order finite volumes solve the 2D shallow-water equations; scalar stage/discharge boundaries require wet-subcritical flow; synthetic and analytical benchmarks establish numerical contracts rather than site-specific field calibration. See docs/acceptance.md.

Examples

Run any example from a checkout:

cargo run --example grid
cargo run --example rain_basin
cargo run --example surface_runoff
cargo run --example native_worker    # capability check, cancellation, checkpoint/restore, forecast splice

Run the full test suite:

cargo test --workspace --all-targets

Documentation

Task Guide
Integrate hydr into a native Rust worker docs/integration.md
Review equations, step limits, and conservation docs/numerics.md
Inspect analytical and composite acceptance coverage docs/acceptance.md
Contribute code, tests, or docs CONTRIBUTING.md

References

  • Hydroflux: Rust shallow-water implementation reference.
  • GeoClaw: Independent depth-averaged flow reference.
  • EPA SWMM 5.2: Dynamic-wave piped drainage and Modified Green-Ampt reference.
  • FHWA HDS-5 / HEC-RAS: Culvert hydraulics and channel flow methods.

License

Apache-2.0. See LICENSE.

About

Rust hydraulic simulation library for river and floodplain flow, built on numr and solvr.

Resources

Contributing

Stars

2 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages