Imported from cmorett/tlaloc_repo (
AGENTS.md). Install upstream withnpx skills add cmorett/tlaloc_repo. Copyright stays with the author.
AGENTS Guide for tlaloc_repo
This repository implements a graph neural network (GNN) surrogate and gradient-based model predictive control (MPC)
for EPANET water distribution models. The main example network is CTown.inp.
Project Layout
README.md– high level usage instructions.AGENTS.md– repository guidelines for Codex.CTown.inp– EPANET input file for the C‑Town network.pytorchcheck.py– quick script verifying that PyTorch Geometric runs on the configured GPU.inspect_pump_alignment.py– diagnostic utility confirming that pump speed features align with the commands applied during data generation.models/loss_utils.py– physics-based loss helpers.losses.py– weighted multi-task loss utilities.gnn_surrogate.pth– trained weights saved here after running the training script.
scripts/data_generation.py– create randomized simulation scenarios and produce training datasets. It also stores the node order innode_names.npy.experiments_validation.py– validate the surrogate, compare baselines and aggregate results.metrics.py– report surrogate accuracy, MPC control and runtime metrics.diagnose_pump_cluster.py– dump per-node residuals, pump head rise and unit head loss diagnostics for trained checkpoints.mpc_control.py– run gradient-based MPC using the trained surrogate.feature_utils.py– shared feature construction and normalization helpers.ablation_study.py– run a small grid of model variants and report validation pressure MAE.train_gnn.py– train a graph neural network surrogate on generated data. Pass--checkpointto enable gradient checkpointing when GPU memory is limited. The script also writes predicted vs. actual pressures todata/pressures_<run>.csv(override with--pred-csv). The loader verifies that feature matrices follow the node order saved asnode_names.npyduring data generation.sweep_training.py– run hyperparameter sweeps over loss weights and architecture.plot_sweep.py– visualise pressure MAE across sweep configurations.reproducibility.py– helper utilities for seeding and config logging.
notebooks/– quickstart notebooks visualising common analyses.00_validate_surrogate_rollout.ipynb– compare 1-step and multi-step surrogate errors.01_mpc_cost_sensitivity.ipynb– explore pressure–energy trade-offs under different cost weights.
tests/– pytest suite containing:test_accuracy_export.pytest_amp.pytest_cli_args.pytest_clip.pytest_dataset_distributions.pytest_demand_scaling.pytest_early_stop.pytest_energy.pytest_extreme_events.pytest_flow_denorm.pytest_headloss_loss.pytest_pump_curve_loss.pytest_hydroconv.pytest_interrupt_dataloader.pytest_interrupt_handler.pytest_load_surrogate.pytest_mass_balance.pytest_metrics.pytest_mpc_input_check.pytest_mpc_normalization.pytest_nan_check.py
test_normalization.pytest_normalized_negative.pytest_output_clamp.pytest_physics_training.pytest_pump_controls.pytest_recurrent_forward.pytest_reservoir_feature.pytest_reservoir_mask.pytest_scatter.pytest_scatter_interrupt.pytest_sequence_nan_check.pytest_sequence_norm_stats.pytest_tank_dynamics.pytest_tank_initial_randomization.pytest_validate_surrogate.pytest_rollout_eval.pytest_visualizations.pytest_mpc_animation.pytest_workers.py
data/– ignored by git; used for generated datasets and temporary simulation outputs.plots/– ignored by git; stores figures generated during training, validation and MPC runs.logs/– ignored by git; JSON summaries such assurrogate_metrics.jsonandmpc_summary.json..vscode/– VS Code configuration (containssettings.json).
Architecture Overview
- Data Generation –
scripts/data_generation.pyexecutes multiple EPANET simulations with randomized demand profiles, jittered reservoir heads and tank thresholds, and paired pump overrides for boosters without explicit controls. Pump schedules default to the INP control rules (use--manual-pump-fraction/--paired-pump-fractionfor stress tests). The script writes node feature matrices, labels for the next hour pressure and chlorine, and the graphedge_indexto thedata/directory. - Surrogate Training –
scripts/train_gnn.pyloads the generated data and trains a configurable GNN encoder. The model supports heterogeneous node and edge types, optional attention and residual connections. NaNs in the features are replaced with zero to avoid invalid losses. Gradients are clipped to keep the training stable. Scatter plots comparing predictions to EPANET are saved underplots/. - MPC Controller –
scripts/mpc_control.pyloads the trained surrogate (GNNSurrogate) and repeatedly optimizes pump speeds via gradient descent. The controller can either propagate the network state entirely through the surrogate or periodically synchronize with EPANET for ground truth. Simulation history is written todata/mpc_history.csvand a summary JSON file tologs/. - Experiment Validation –
scripts/experiments_validation.pyevaluates the surrogate on prerecorded EPANET scenarios and compares the MPC controller against two baselines. Results are aggregated into CSV files underdata/and plots underplots/. Validation metrics are stored inlogs/surrogate_metrics.json. 5 Metric Reporting and Visualization – After each script is ran, several logs are created which summarize accuracy, control quality and computational overhead as well as visualizations: scatter plots, time‑series and convergence curves for reports.
The repository assumes a working Python environment. Create a virtual environment
and install the required packages listed in requirements.txt:
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
This installs PyTorch, PyTorch Geometric, numpy, scikit-learn, wntr,
pandas, matplotlib, networkx and epyt along with other dependencies.
Testing Protocols
Basic unit tests live in the tests/ directory. Run them with pytest. The recommended workflow is:
- Verify GPU and PyG installation using
python pytorchcheck.py. - Run the unit tests:
pytest - Generate a small dataset with
python scripts/data_generation.py --num-scenarios 10 --output-dir data/ - Train the surrogate:
python scripts/train_gnn.py --x-path data/X_train.npy --y-path data/Y_train.npy --edge-index-path data/edge_index.npy --inp-path CTown.inp [--checkpoint] - Run the experiment suite which includes a surrogate validation step:
python scripts/experiments_validation.py --model models/gnn_surrogate.pth --inp CTown.inp - Optionally launch MPC control directly using
scripts/mpc_control.py.
When adding new features or bug fixes, please create unit tests using pytest inside a tests/ directory and run pytest before committing.
Additional Notes for Codex
- NEVER assume that other scripts work exactly as intended. Always check that scripts you may need in fact do what they say they do as there may be errors.
- Negative pressures or
NaNvalues for energy are physically unrealistic and should be avoided. Ensure that simulated pressures remain non‑negative and that computed pump energy never becomesNaN. - Paths should be resolved relative to the repository root so scripts work when launched from any location.
- Generated data and results should remain inside the
data/folder, if they are plots they go toplots/. - Any changes that you do that influence the way the user is supposed to interact with the scripts should be accompanied with a corresponding change to the
README.mdfile in which you declare how the new change is supposed to be used. If the change involves the creation of new files those changes should be present in thisAGENTS.mdfile. - Also aim to consistently have the optimal example prompt in the
README.mdfile for optimal usage.