Metadata-Version: 2.4
Name: hydroforge-tools
Version: 1.0.1
Summary: Toolkit for applying uncertainties to water network models
Author: "Tomasz Janus"
Author-email: Tomasz Janus <tomasz.k.janus@gmail.com>
License-Expression: GPL-3.0
Keywords: hydrology,water-network,uncertainty-analysis,leak-detection
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Scientific/Engineering :: Hydrology
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: cloudpickle>=3.0.0
Requires-Dist: contourpy>=1.0.0
Requires-Dist: cycler>=0.10.0
Requires-Dist: fonttools>=4.0.0
Requires-Dist: kiwisolver>=1.0.0
Requires-Dist: matplotlib>=3.5.0
Requires-Dist: networkx>=3.0
Requires-Dist: numpy>=1.20.0
Requires-Dist: packaging>=20.0
Requires-Dist: pandas>=1.5.0
Requires-Dist: pillow>=8.0.0
Requires-Dist: pygad>=3.0.0
Requires-Dist: pydantic<3,>=2.0.0
Requires-Dist: pyparsing>=3.0.0
Requires-Dist: python-dateutil>=2.8.0
Requires-Dist: rich>=13.0.0
Requires-Dist: tzdata>=2021.1
Requires-Dist: PyYAML>=6.0.0
Requires-Dist: scipy>=1.8.0
Requires-Dist: setuptools>=60.0.0
Requires-Dist: six>=1.16.0
Requires-Dist: wntr
Requires-Dist: rich
Requires-Dist: SALib
Provides-Extra: ptsnet
Requires-Dist: ptsnet; extra == "ptsnet"
Provides-Extra: dev
Requires-Dist: black==26.10.1; extra == "dev"
Requires-Dist: flake8==7.5.0; extra == "dev"
Requires-Dist: mypy==2.4.1; extra == "dev"
Requires-Dist: pytest==8.3.4; extra == "dev"
Requires-Dist: pytest-cov==6.0.0; extra == "dev"
Dynamic: license-file

# HydroForge

<p align="center">
  <img src="assets/banner.png" alt="hydroforge-banner" width="100%">
</p>

[![License: GPL-3.0](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://opensource.org/licenses/GPL-3.0)
[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/)
[![Status: Alpha](https://img.shields.io/badge/status-Alpha-orange.svg)](https://github.com/tomjanus/HydroForge)

**HydroForge** is a toolkit for uncertainty injection and scenario generation in
water distribution network (WDN) simulations. It provides probability
distributions and uncertain parameters, sampling strategies, sensor-imperfection
models, network modifiers, EPANET file I/O, graph analysis, sensor placement, and
a common simulation-backend facade.

## Project status

HydroForge is alpha software. `hydroforge.wdn_modelling.backends` is the
supported simulation entry point and sole supported implementation.
The legacy `hydroforge.simulation`, `hydroforge.scenario_generation`,
`hydroforge.topology`, and `hydroforge.uncertainty_sampling` packages have been
retired in favour of `hydroforge.wdn_modelling.backends` and
`hydroforge.sampling`.

## Installation

HydroForge requires Python 3.10 or newer. After a release is available on
PyPI, install the distribution with:

```bash
pip install hydroforge-tools
```

For an editable development installation, use a source checkout:

```bash
git clone https://github.com/tomjanus/HydroForge.git
cd HydroForge

# Runtime installation
pip install -e .

# Development installation (black, flake8, mypy, pytest)
pip install -e ".[dev]"
```

The core dependencies are declared in `pyproject.toml` and include NumPy, SciPy,
pandas, NetworkX, Matplotlib, PyYAML, Rich, pygad, cloudpickle, SALib, and WNTR.

Transient solver backends are optional extras. Install only the backend you
need:

| Backend | Solver package |
| --- | --- |
| `wntr` | WNTR (core dependency) |
| `tsnet` | `pip install "git+https://github.com/glorialulu/TSNet.git"` |
| `tsnetplus` | `pip install "git+https://github.com/tomjanus/TSNetPlus.git"` |
| `ptsnet` | `pip install "hydroforge-tools[ptsnet]"` |

TSNet and TSNetPlus are installed directly from GitHub because PyPI does not
allow direct URL requirements in published package metadata. `ptsnet` installs
the package from PyPI. If code requests a transient backend whose package is
missing, HydroForge explains which package is required and asks whether to
install it. Installation happens only after an explicit `y` or `yes`; pressing
Enter (or answering `n`) leaves the environment unchanged.

## Quick start

```python
from hydroforge import __version__
from hydroforge.measurements import RandomNoiseSensor

print(f"HydroForge version {__version__}")

sensor = RandomNoiseSensor(sigma=0.05, seed=42)
measurement = sensor.measure(1.0)
```

The command-line interface is currently a placeholder. `hydroforge --version`
works, but `run-analysis`, `localize`, and `sensor-placement` report that they
are not implemented and exit with a non-zero status.

## Package layout

### Generic (domain-agnostic, importable without any WDN modelling package dependencies)

| Package | Purpose | Current state |
| --- | --- | --- |
| `hydroforge.uncertainty` | Distributions, uncertainty transforms, parameters, CDFs | Supported |
| `hydroforge.sampling` | Monte Carlo, LHS, Sobol, Halton, stratified, conditional, nested, scenario-tree and mixed sampling | Supported (SALib is a core dependency) |
| `hydroforge.measurements` | Imperfect-sensor models and window averaging (renamed from `sensors`) | Supported |
| `hydroforge.auxiliary` | Configuration I/O, logging, exceptions, utility helpers | Supported |

### WDN / EPANET-specific modelling

| Package | Purpose | Current state |
| --- | --- | --- |
| `hydroforge.wdn_modelling.backends` | Common backend facade for WNTR, EPANET, TSNet, TSNetPlus, and PTSNet | Supported; optional solvers required |
| `hydroforge.wdn_modelling.epanetfile_io` | Typed EPANET `.inp` parsing, editing, and writing without WNTR | Supported |
| `hydroforge.wdn_modelling.graphs` | EPANET network graph analysis and visualization | Supported |
| `hydroforge.wdn_modelling.networks` | Model/graph selectors and `JunctionLeaks` | Supported |
| `hydroforge.wdn_modelling.modifiers` | WNTR model and graph modifiers | Supported |
| `hydroforge.wdn_modelling.uncertainty` | Apply realized parameters and generic sensors to WNTR models/results | Supported |
| `hydroforge.wdn_modelling.measurement_placement` | Sensor placement and sensor-network graph (depends on `graphs`) | Supported |

## API overview

### Uncertainty distributions and parameters

```python
from hydroforge.uncertainty import (
    NormalDistribution,
    UniformDistribution,
    AdditiveUncertainty,
    Parameter,
    ParameterType,
)

diameter = Parameter(
    name="diameter",
    nominal_value=200.0,
    uncertainty=AdditiveUncertainty(NormalDistribution(mean=0.0, std_dev=2.5)),
    type=ParameterType.NUMERICAL,
)

value = diameter.sample()
controlled = diameter.sample_from_unit(0.5)
cdf_at_200 = diameter.cdf(200.0)
```

Available distributions include `NormalDistribution`, `UniformDistribution`,
`DiscreteNormalDistribution`, `DiscreteUniformDistribution`,
`DiscreteHistogramDistribution`, `DiracDeltaDistribution`, the categorical
variants, and `DistributionChecker`.

### Sampling

```python
from hydroforge.sampling import MonteCarloSampler, LatinHypercubeSampler

sampler = LatinHypercubeSampler([diameter], seed=42)
for scenario in sampler.generate(100):
    print(scenario.id, scenario.values)
```

The sampling package also exports `SobolSampler`, `HaltonSampler`,
`StratifiedSampler`, `ConditionalMonteCarloSampler`,
`NestedMonteCarloSampler`, `ScenarioTreeSampler`, `MixedStrategySampler`,
`GibbsSampler` (a legacy independent marginal resampler, not MCMC), and
supporting specification types. See
[`src/hydroforge/sampling/README.md`](src/hydroforge/sampling/README.md) for the
statistical assumptions and current limitations.

### Sensors and sensor placement

```python
from hydroforge.measurements import (
    FixedPrecisionSensor,
    RandomNoiseSensor,
    CompositeSensor,
    WindowAverager,
)

sensor = CompositeSensor(
    FixedPrecisionSensor(delta_y=0.01),
    RandomNoiseSensor(sigma=0.005, seed=42),
)
measured = sensor.measure(1.234)

averager = WindowAverager(window_size=3)
averaged = averager.average([1.0, 1.1, 0.9, 1.2, 1.0, 1.1])
```

Placement strategies are available through `hydroforge.wdn_modelling.measurement_placement`:
`GreedySensorPlacement`, `KCentreSensorPlacement`, `RandomSensorPlacement`,
`CentralityBasedSensorPlacement`, `CoverageBasedSensorPlacement`,
`DominatingSetBasedSensorPlacement`, and `FixedLocationSensorPlacement`, all
orchestrated by `SensorPlacer`.

### Applying realized parameters to a WNTR model

WDN parameter bindings connect a component property to a named value in a
caller-owned mapping. The adapter does not sample or run the simulator; it
preflights the complete binding set, updates the supplied model in place, and
returns an ordered audit report.

Supported properties are `diameter`, `diameter_multiplier`, and `roughness` on
pipes; `base_demand` on a junction with exactly one demand timeseries; and
`valve_setting`. PRV/PSV/FCV settings must be positive numbers, TCV settings
must be non-negative, GPV settings reference an existing `HEADLOSS` curve, and
PBV settings are `OPEN` or `CLOSED`. Multiple junction demand entries are
rejected rather than partially updated.

```python
from hydroforge.wdn_modelling.uncertainty import (
    WNTRParameterAdapter,
    WNTRParameterBinding,
)

adapter = WNTRParameterAdapter(
    [WNTRParameterBinding("P1", "diameter", "pipe_diameter")]
)
audit = adapter.apply(model, {"pipe_diameter": 0.25})
```

After running WNTR, bind generic sensor definitions to selected points and
variables. Only the bound result columns are measured; the raw results are left
unchanged. The example assumes `specification`, `model`, and `results` have
already been created by the caller.

```python
from hydroforge.wdn_modelling.uncertainty import (
    WNTRSensorAdapter,
    WNTRSensorBinding,
)

sensor_adapter = WNTRSensorAdapter(
    [WNTRSensorBinding("J1", "pressure_sensor", "pressure")],
    specification.sensors,
)
measured = sensor_adapter.apply(model, results)
```

### Simulation backends

```python
from hydroforge.wdn_modelling.backends import get_backend

backend = get_backend("wntr")
model = backend.load_model("tests/base_networks/Net1_shortened.inp")
results = backend.create_simulator().run(model)

pressure = results.get_node_variable(
    "pressure",
    list(model.junction_name_list)[:3],
    as_dataframe=True,
)
```

Backend configuration is split into persistent model options
(`backend.apply_config(...)`) and simulator runtime options
(`backend.create_simulator(...)`). WNTR uses `WNTRConfig`,
`WNTRSimulatorConfig`, and `EPANETSimulatorConfig`; the transient backends
currently use one configuration type for both scopes.

### EPANET file I/O

```python
from hydroforge.wdn_modelling.epanetfile_io import EPANETNetworkModelIO

network = EPANETNetworkModelIO.from_inp_file("network.inp")
network.junctions.modify_by_field("id", "J1", elevation=105.0)
EPANETNetworkModelIO.to_inp_file(network, "modified.inp")
```

### Graphs

```python
from hydroforge.wdn_modelling.graphs.graph import EPANETNetworkGraph
from hydroforge.wdn_modelling.graphs.visualization import EPANETGraphPlotter

network = EPANETNetworkGraph.from_epanet_file("network.inp")
print(network.find_total_length())
print(network.find_bridges())

EPANETGraphPlotter(network).plot(title="Water network")
```

## Examples

Examples are grouped under `examples/`. The following example is verified to run
with the core dependencies:

```bash
PYTHONPATH=src python examples/measurements/ex1_sensors.py
```

Other examples demonstrate the backend registry, EPANET file I/O, graph
analysis, sampling, uncertainty distributions, and sensor placement. Some
examples require optional solvers or `SALib`; those are only runnable when the
corresponding dependency is installed.

## Configuration

`hydroforge.auxiliary.load_config()` reads YAML with `yaml.safe_load`. The
repository contains legacy configuration files under `data/config/`; they
reference retired modules and are not working templates.

## Development

```bash
# Formatting
black --check .

# Linting
flake8 --config=.flake8 .

# Type checking
mypy .

# Tests
pytest
```

The CI workflow runs the same commands on Python 3.12 and builds the package.

Repository conventions and the development workflow are described in
[`WORKFLOW_GUIDELINES.md`](WORKFLOW_GUIDELINES.md). Domain terminology is in
[`GLOSSARY.md`](GLOSSARY.md).

## Citation

If you use HydroForge in research, cite the HydroForge repository and record the
version or commit used. A formal archived citation and DOI have not yet been
assigned for this project, so no DOI is provided here.

## License

HydroForge is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.

HydroForge is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with
HydroForge. If not, see <https://www.gnu.org/licenses/>.

## Contributing

Bug reports and feature requests can be opened on the GitHub issue tracker.
Contributions should follow the repository style checks (`black`, `flake8`,
`mypy`) and include tests for new behaviour. Do not open a pull request that
claims validation for a backend or optional dependency that was not actually
exercised.
