API reference

High-level API

High-level API for sensor network design - Simple interface for water managers.

class hydrosensenet.designer.SensorNetworkDesigner(streamflow_data, locations, location_labels=None)[source]

Bases: object

Easy-to-use interface for designing optimal sensor networks.

Parameters:
classmethod from_files(streamflow_file, locations_file=None, time_col=None, lat_col='latitude', lon_col='longitude', **streamflow_kwargs)[source]

Create designer from data files (CSV, Parquet, Excel, NetCDF, etc.).

Parameters:
classmethod from_csv(streamflow_file, locations_file=None, time_col=None, lat_col='latitude', lon_col='longitude')[source]

Load data from files (works with all formats despite name).

Parameters:
classmethod from_nwm_download(streamflow_file, locations_geojson, id_col='comid')[source]

Convenience method for NWM downloads with auto-alignment.

Parameters:
design_network(n_sensors, weights=None, weight_column=None, weight_fill_value=0.0, existing_sensors=None, train_frac=0.7, evaluate=True, verbose=True)[source]

Design an optimal sensor network.

Splits the record in time (when evaluate=True), selects sensor locations by weighted pivoted QR on the training block, and scores reconstruction of the full field on the held-out block.

Parameters:
  • n_sensors (int) – Number of sensors to place (including existing_sensors).

  • weights (np.ndarray or str or Path, optional) – Per-location weights aligned to the data columns, or a path to a spatial weight file resolved via calculate_spatial_weights().

  • weight_column (str, optional) – Column to read when weights is a file path.

  • weight_fill_value (float, default=0.0) – Fill for locations not covered by the weight file. The default 0.0 removes uncovered locations from consideration; use a tiny positive value (e.g. 1e-10) to keep them selectable as a last resort.

  • existing_sensors (list of int, optional) – Column indices of gauges to keep (indices into the original column order). They appear first in the result; if len(existing_sensors) == n_sensors the QR step is skipped and the existing network is just evaluated.

  • train_frac (float, default=0.7) – Fraction of timesteps used for design when evaluating.

  • evaluate (bool, default=True) – Hold out 1 - train_frac of the record and compute reconstruction metrics (NSE, NNSE, relative error).

  • verbose (bool, default=True) – Print progress information.

Returns:

NetworkDesignResult – Selected indices, locations, labels, and (if evaluated) per-location performance metrics.

Return type:

NetworkDesignResult

Notes

Columns containing NaN/inf in the training block are dropped before selection (a warning reports how many). All indices in the returned result refer to the original column order, and per-location metric arrays have the original length with NaN at dropped locations. An existing_sensors entry pointing at a dropped column raises a ValueError.

class hydrosensenet.designer.NetworkDesignResult(selected_indices, locations, location_labels, performance_metrics, n_sensors, weights)[source]

Bases: object

Results from sensor network design.

Parameters:
selected_indices

Selected column indices in priority order (rank 1 first).

Type:

np.ndarray

locations

Rows of the input locations for the selected sensors.

Type:

gpd.GeoDataFrame

location_labels

Labels of the selected sensors, in the same order.

Type:

list of str

performance_metrics

When designed with evaluate=True: per-location nse and nnse arrays plus the raw eval_results dict from reconstruction_evaluation().

Type:

dict or None

n_sensors

Number of sensors requested.

Type:

int

weights

Weight vector used for the design, if any.

Type:

np.ndarray or None

print_summary()[source]

Print summary of results.

export(output_path, format='auto', include_metrics=True)[source]

Export results to file.

Parameters:
get_dataframe()[source]

Get results as DataFrame.

Returns:

pd.DataFrame – Selected sensors with coordinates and metrics.

Return type:

DataFrame

plot(figsize=(12, 8), show_rank=True, basemap=True, title='Optimal Sensor Network Design', save_path=None, flowlines_gdf=None, rank_column='Median Rank')[source]

Create map visualization of selected sensors.

plot_comparison(baseline_result, flowlines_gdf, location_labels, comparison_labels=None, metric='nnse', figsize=(7, 5), save_path=None, comid_column=None)[source]

Plot comparison of NNSE between this network and a baseline network.

Parameters:
  • baseline_result (NetworkDesignResult) – Baseline network to compare against (e.g., USGS network)

  • flowlines_gdf (GeoDataFrame) – GeoDataFrame containing flowline geometries with COMID column

  • location_labels (List[str]) – Labels for all locations (COMIDs) matching the order in performance metrics

  • comparison_labels (dict, optional) – Dictionary with keys ‘optimal’ and ‘baseline’ for scatter plot labels

  • metric (str) – Performance metric to compare (‘nnse’, ‘nse’, or ‘r2’)

  • figsize (tuple) – Figure size (width, height)

  • save_path (str, optional) – Path to save the figure

  • comid_column (str, optional) – Name of the COMID column in flowlines_gdf. If None, will auto-detect by trying ‘COMID’, ‘comid’, ‘feature_id’, ‘FEATUREID’

Returns:

tuple – (figure, axis)

Core algorithms

Core sensor placement algorithms using QR decomposition.

hydrosensenet.core.algorithms.sensor_placement_qr(X, n_sensors, weights=None, fixed_indices=None, method='auto', verbose=False)[source]

Select sensor locations by (weighted) QR decomposition with column pivoting.

Columns of X are candidate locations; pivoting ranks them by how much independent information they contribute, and the first n_sensors pivots are returned. Deterministic: the same input always yields the same selection.

Parameters:
  • X (np.ndarray or pd.DataFrame) – Data matrix of shape (n_timesteps, n_locations). Must not contain NaN/inf (filter beforehand, e.g. with split_timeseries()).

  • n_sensors (int) – Number of locations to select.

  • weights (array-like of shape (n_locations,), optional) – Per-location importance weights. Columns are scaled by these values before pivoting, biasing selection toward high-weight locations.

  • fixed_indices (list of int, optional) – Column indices of existing sensors to keep. They are placed first in the result; remaining sensors are chosen from the residual after orthogonalizing against them.

  • method ({"auto", "full", "truncated"}, default="auto") – Factorization path. "full" runs LAPACK pivoted QR over all min(m, n) elimination steps; "truncated" runs only the n_sensors greedy steps (O(m*n*k)), selecting identical pivots ~10x faster on large problems. "auto" picks "truncated" when n >= 2000 and 5 * n_sensors < min(m, n); float32 input is preserved on the truncated path, halving memory.

  • verbose (bool, default=False) – Print progress information.

Returns:

np.ndarray – Selected column indices, length n_sensors. When fixed_indices is given, those indices appear first, in the given order.

Return type:

ndarray

hydrosensenet.core.algorithms.qr_pivot_selection(X_train, region_assignments, sensors_per_region, region_column='region_name', verbose=False)[source]

Select sensors independently within each spatial region (per-region quotas).

Runs pivoted QR separately on each region’s columns, taking the region’s quota from sensors_per_region.

Parameters:
  • X_train (np.ndarray or pd.DataFrame) – Data matrix of shape (n_timesteps, n_locations).

  • region_assignments (pd.DataFrame or np.ndarray) – Region label per location. As a DataFrame it must contain region_column and a col_pos column giving each row’s column position in X_train; as an array, positions are assigned in order.

  • sensors_per_region (dict) – Mapping of region name to number of sensors. Regions not listed get zero sensors; quotas are capped at the region’s size.

  • region_column (str, default="region_name") – Name of the region label column.

  • verbose (bool, default=False) – Print a summary of the selection.

Returns:

  • selected_locations (pd.DataFrame) – Rows of region_assignments for the selected locations.

  • selected_sensor_indices (list of int) – Selected column positions into X_train.

Return type:

tuple

Metrics

Performance metrics for sensor network evaluation.

hydrosensenet.core.metrics.calculate_performance_metrics(true_values, pred_values)[source]

Calculate per-location NSE and normalized NSE (NNSE) skill scores.

Parameters:
  • true_values (np.ndarray) – Arrays of shape (n_timesteps, n_locations).

  • pred_values (np.ndarray) – Arrays of shape (n_timesteps, n_locations).

Returns:

  • r_squared (np.ndarray) – Coefficient of determination per location. Computed with the NSE formula (1 - SSE/SST against the observed mean), so it is numerically identical to nse.

  • nse (np.ndarray) – Nash-Sutcliffe efficiency per location, in (-inf, 1]. NaN where the true series is constant (zero variance).

  • nnse (np.ndarray) – Normalized NSE, 1 / (2 - NSE), mapping (-inf, 1] to (0, 1] — convenient for mapping and aggregation.

Return type:

Tuple[ndarray, ndarray, ndarray]

hydrosensenet.core.metrics.reconstruction_error(true_values, pred_values, metric='rmse')[source]

Calculate reconstruction error.

Parameters:
Return type:

float | ndarray

hydrosensenet.core.metrics.reconstruction_evaluation(X_train, X_test, sensor_locations, n_sensors, verbose=False)[source]

Evaluate reconstruction performance for given sensor locations.

Parameters:
  • X_train (np.ndarray) – Training data, shape (n_train_timesteps, n_locations).

  • X_test (np.ndarray) – Testing data, shape (n_test_timesteps, n_locations).

  • sensor_locations (np.ndarray) – Array of sensor location indices.

  • n_sensors (int) – Number of sensors to use for evaluation.

  • verbose (bool, default=False) – Print progress information.

Returns:

results (dict) – Dictionary containing: - ‘X_test_selected’: Selected sensor data - ‘X_test_reconstructed’: Reconstructed full field - ‘selected_sensors’: Indices of selected sensors - ‘non_selected_sensors’: Indices of non-selected sensors - ‘rmse’: RMSE per location - ‘relative_error’: Overall relative error

Return type:

Dict[str, ndarray]

Spatial weights

Spatial weighting for risk-informed sensor placement.

hydrosensenet.spatial.weights.calculate_spatial_weights(locations_gdf, weight_source, weight_column=None, id_column=None, align_to=None, fill_value=0.0, aggregation='mean', normalize=False)[source]

Compute a per-location weight vector for sensor_placement_qr.

Output is aligned to align_to (e.g. the streamflow matrix’s column order) when given, else to locations_gdf row order.

For the FEMA flood-risk workflow set fill_value=1e-10 so uncovered locations stay selectable by QR pivoting (0.0 removes them entirely). normalize is off because min-max scaling would map the minimum to 0 and have the same effect.

Parameters:
Return type:

ndarray

Data loading

Universal data loaders for streamflow and gauge data.

hydrosensenet.data.loaders.load_streamflow_data(data_source, format='auto', time_col=None, location_cols=None, **kwargs)[source]

Load streamflow data from any source (CSV, Parquet, Excel, NetCDF, etc.).

Parameters:
Return type:

DataFrame | Dataset

hydrosensenet.data.loaders.prepare_gauge_locations(gauge_data, lat_col='latitude', lon_col='longitude', id_col=None, crs='EPSG:4326')[source]

Prepare gauge location data as GeoDataFrame.

Parameters:
Return type:

GeoDataFrame

Preprocessing

Data preprocessing utilities for sensor network optimization.

hydrosensenet.data.preprocessors.split_timeseries(data, train_frac=0.7, filter_invalid=True, return_mapping=False)[source]

Split time series data into training and testing sets.

Parameters:
Return type:

Tuple | Tuple[any, any, Dict]

hydrosensenet.data.preprocessors.prepare_matrix(data, variable=None, drop_na=True)[source]

Convert DataFrame or xarray Dataset to 2D matrix for optimization.

Parameters:
  • data (DataFrame or Dataset) – Input data. - DataFrame: columns are locations, rows are time - Dataset: will stack spatial dimensions

  • variable (str, optional) – Variable name to extract from Dataset (required for Dataset input).

  • drop_na (bool, default=True) – Drop locations with any NaN values.

Returns:

  • matrix (np.ndarray) – 2D array of shape (n_timesteps, n_locations).

  • location_labels (list of str) – Labels for each location (column).

Return type:

Tuple[ndarray, List[str]]

Examples

>>> # DataFrame input
>>> df = pd.DataFrame(np.random.randn(365, 100))
>>> matrix, labels = prepare_matrix(df)
>>> # xarray Dataset input
>>> ds = xr.Dataset(...)
>>> matrix, labels = prepare_matrix(ds, variable="discharge")
hydrosensenet.data.preprocessors.filter_valid_data(data, min_valid_fraction=0.8, remove_zeros=False)[source]

Filter locations based on data quality.

Parameters:
  • data (np.ndarray) – Data matrix of shape (n_timesteps, n_locations).

  • min_valid_fraction (float, default=0.8) – Minimum fraction of valid (non-NaN) values required.

  • remove_zeros (bool, default=False) – Remove locations with all zeros (dry streams).

Returns:

  • filtered_data (np.ndarray) – Filtered data matrix.

  • valid_indices (np.ndarray) – Indices of kept locations.

Return type:

Tuple[ndarray, ndarray]

National Water Model (NWM)

National Water Model (NWM) data utilities.

This module provides functions to download, process, and filter NWM data for sensor network optimization workflows.

class hydrosensenet.data.nwm.NWMDataLoader(version='3.0', use_dask=True, n_workers=8, threads_per_worker=4, memory_limit='8GB')[source]

Load and process National Water Model retrospective data from AWS.

Examples

>>> # Filter by HUC and download data
>>> loader = NWMDataLoader(version="3.0")
>>> loader.filter_by_huc("1204")  # Texas-Gulf HUC4
>>> df = loader.download_streamflow(
...     start_date="2020-01-01",
...     end_date="2022-01-01",
...     resample="D"
... )
>>> df.to_csv("streamflow_daily.csv")
>>> # Or filter by COMID list
>>> comids = [1234567, 7654321, 9876543]
>>> loader = NWMDataLoader(version="3.0")
>>> loader.filter_by_comids(comids)
>>> df = loader.download_streamflow("2021-01-01", "2022-01-01")
Parameters:
  • version (str)

  • use_dask (bool)

  • n_workers (int)

  • threads_per_worker (int)

  • memory_limit (str)

close()[source]

Shut down the Dask client and cluster if they were started.

filter_by_huc(huc, huc_level=None)[source]

Filter COMIDs by Hydrologic Unit Code (HUC).

Only HUC levels up to 8 are supported: filtering matches NHDPlus reachcode prefixes, which identify hydrologic units down to HUC8 only.

Parameters:
  • huc (str)

  • huc_level (int | None)

Return type:

NWMDataLoader

filter_by_comids(comids)[source]

Filter by explicit list of COMIDs.

Parameters:

comids (List[str | int])

Return type:

NWMDataLoader

filter_by_shapefile(shapefile, comid_column='COMID')[source]

Filter by COMIDs from a shapefile.

Parameters:
Return type:

NWMDataLoader

filter_by_csv(csv_file, comid_column='COMID')[source]

Filter by COMIDs from a CSV file.

Parameters:
Return type:

NWMDataLoader

export_locations(output_file, format='csv', sample_size=None, use_full_geometries=False, random_state=None)[source]

Export COMID locations to file.

Parameters:
  • output_file (str or Path) – Destination file path.

  • format (str, default="csv") – Output format, “csv” or “geojson”.

  • sample_size (int, optional) – If given and smaller than the number of COMIDs, export a random sample of this size.

  • use_full_geometries (bool, default=False) – For GeoJSON output, keep full flowline geometries instead of centroids.

  • random_state (int, optional) – Seed for the random sampling, for reproducible exports.

Return type:

Path

download_streamflow(start_date, end_date, resample='D', resample_method='mean', batch_size=5000, output_file=None, format='auto')[source]

Download and process streamflow data.

Parameters:
  • start_date (str)

  • end_date (str)

  • resample (str)

  • resample_method (str)

  • batch_size (int)

  • output_file (str | Path | None)

  • format (str)

Return type:

DataFrame

download_multiple_years(years, output_dir='.', resample='D', format='parquet', **kwargs)[source]

Download multiple years of data, saving each year separately.

Parameters:
Return type:

List[Path]

hydrosensenet.data.nwm.get_huc_info(huc)[source]

Get information about a Hydrologic Unit Code.

Parameters:

huc (str) – HUC code (e.g., “12”, “1204”, “120401”).

Returns:

dict – HUC information including name, area, and parent HUC. The area (area_sqkm) is computed in EPSG:5070 (CONUS Albers equal-area), so it is only accurate for HUCs within the conterminous United States (CONUS).

Return type:

dict

Examples

>>> info = get_huc_info("1204")
>>> print(info['name'])
'Brazos-Colorado'
hydrosensenet.data.nwm.list_available_hucs(region=None, level=2)[source]

List available HUC regions.

Parameters:
  • region (str, optional) – Filter by region code (e.g., “12” for Texas-Gulf).

  • level (int, default=2) – HUC level to list (2, 4, 8, 10, 12).

Returns:

pd.DataFrame – Available HUCs with codes and names.

Return type:

DataFrame

Examples

>>> # List all HUC2 regions
>>> hucs = list_available_hucs(level=2)
>>>
>>> # List HUC4 subregions in Texas-Gulf
>>> hucs = list_available_hucs(region="12", level=4)

USGS gauge networks

USGS gauge network data utilities.

hydrosensenet.data.usgs.download_usgs_gauges(output_dir, huc2=None, force_download=False, verbose=True)[source]

Download USGS gauge network data with NHDPlus COMID linkage.

Parameters:
  • output_dir (str or Path) – Directory to save the downloaded data

  • huc2 (str, optional) – HUC2 region code to filter gauges (e.g., ‘12’ for Texas-Gulf)

  • force_download (bool, default=False) – If True, download even if file exists

  • verbose (bool, default=True) – Print progress messages

Returns:

tuple of Path – (shapefile_path, comid_linkage_path) - shapefile_path: Path to the gauge locations GeoJSON - comid_linkage_path: Path to the USGS-COMID linkage CSV

Return type:

Tuple[Path, Path]

Notes

Downloads USGS Streamgage NHDPlus Basins dataset from ScienceBase: - 12,422 streamgages across conterminous US - Pre-computed NHDPlusV2 COMID linkages - Station locations and attributes

Reference: Wieczorek, M.E., et al., 2018, USGS Streamgage NHDPlus Version 1 Basins 2011 https://www.sciencebase.gov/catalog/item/5ebe92af82ce476925e44b8f

hydrosensenet.data.usgs.load_usgs_gauges(shapefile_path, comid_linkage_path=None, huc2=None, comids=None)[source]

Load USGS gauge network data with COMID linkage.

Parameters:
  • shapefile_path (str or Path) – Path to USGS gauge GeoJSON/Shapefile

  • comid_linkage_path (str or Path, optional) – Path to USGS-COMID linkage CSV file

  • huc2 (str, optional) – Filter to specific HUC2 region

  • comids (list, optional) – Filter to specific NHDPlus COMIDs

Returns:

tuple – (gauges_gdf, comid_linkage_df) - gauges_gdf: GeoDataFrame of gauge locations - comid_linkage_df: DataFrame with STAID-COMID pairs

Return type:

Tuple[GeoDataFrame, DataFrame]

hydrosensenet.data.usgs.match_usgs_to_nwm(usgs_gdf, comid_linkage, available_comids, verbose=True)[source]

Match USGS gauges to NWM COMIDs and return indices.

Parameters:
  • usgs_gdf (GeoDataFrame) – USGS gauge locations

  • comid_linkage (DataFrame) – USGS-COMID linkage with columns [‘STAID’, ‘COMID’]

  • available_comids (list) – List of COMIDs available in NWM dataset

  • verbose (bool) – Print matching statistics

Returns:

  • usgs_comids (list of int) – COMIDs aligned to matched_usgs_gdf rows: usgs_comids[i] is the COMID of matched_usgs_gdf.iloc[i].

  • matched_usgs_gdf (GeoDataFrame) – Matched USGS gauges with a comid column (one row per station; duplicate stations dropped with a warning).

Return type:

Tuple[list, GeoDataFrame]

FEMA National Risk Index

FEMA National Risk Index (NRI) loader.

Download the GeoDatabase from https://www.fema.gov/about/openfema/data-sets/national-risk-index-data and pass the path to load_nri().

hydrosensenet.data.fema.load_nri(path, scale='tract', columns=('RFLD_RISKS',), mask=None)[source]

Load a FEMA NRI layer, optionally clipped to mask.

scale is "tract" or "county". columns selects which hazard columns to keep (e.g. RFLD_RISKS, CFLD_RISKS, HRCN_RISKS); pass None to keep all.

Parameters:
Return type:

GeoDataFrame

I/O utilities

Efficient I/O utilities for streamflow and sensor data.

This module provides optimized save/load functions with automatic format detection and intelligent defaults. Parquet format is recommended for better performance and smaller file sizes.

hydrosensenet.io.save_streamflow(df, path, format='auto', compression='snappy', **kwargs)[source]

Save streamflow data with optimal format and compression.

Parameters:
Return type:

Path

hydrosensenet.io.load_streamflow(path, format='auto', columns=None, **kwargs)[source]

Load streamflow data with automatic format detection.

Parameters:
Return type:

DataFrame

hydrosensenet.io.save_locations(gdf, path, format='auto', **kwargs)[source]

Save gauge/sensor location data.

Parameters:
Return type:

Path

hydrosensenet.io.load_locations(path, format='auto', **kwargs)[source]

Load gauge/sensor location data.

Parameters:
  • path (str or Path) – Input file path.

  • format ({"auto", "parquet", "csv", "geojson", "shapefile"}, default="auto") – Input format. “auto” detects from extension.

  • **kwargs – Additional arguments passed to read functions.

Returns:

DataFrame or GeoDataFrame – Location data.

Return type:

DataFrame | GeoDataFrame

Examples

>>> # Load parquet
>>> locations = load_locations("locations.parquet")
>>> # Load GeoJSON
>>> locations = load_locations("locations.geojson")
>>> # Load CSV
>>> locations = load_locations("locations.csv")
hydrosensenet.io.migrate_csv_to_parquet(csv_path, parquet_path=None, compression='snappy', remove_csv=False, **kwargs)[source]

Migrate CSV file to Parquet format.

Parameters:
  • csv_path (str or Path) – Path to input CSV file.

  • parquet_path (str or Path, optional) – Path to output parquet file. If None, replaces .csv with .parquet.

  • compression (str, default="snappy") – Compression algorithm: “snappy”, “gzip”, “brotli”, “zstd”.

  • remove_csv (bool, default=False) – If True, delete CSV file after successful migration.

  • **kwargs – Additional arguments passed to pd.read_csv.

Returns:

Path – Path to created parquet file.

Return type:

Path

Examples

>>> # Migrate single file
>>> migrate_csv_to_parquet("streamflow.csv")
>>> # Creates: streamflow.parquet
>>> # Migrate and remove original
>>> migrate_csv_to_parquet("streamflow.csv", remove_csv=True)
>>> # Custom output path
>>> migrate_csv_to_parquet("old/data.csv", "new/data.parquet")
hydrosensenet.io.migrate_directory(directory, pattern='*.csv', compression='snappy', remove_csv=False, **kwargs)[source]

Migrate all CSV files in a directory to Parquet.

Parameters:
  • directory (str or Path) – Directory containing CSV files.

  • pattern (str, default "*.csv") – Glob pattern for CSV files.

  • compression (str, default="snappy") – Compression algorithm.

  • remove_csv (bool, default=False) – If True, delete CSV files after migration.

  • **kwargs – Additional arguments passed to pd.read_csv.

Returns:

list of Path – Paths to created parquet files.

Return type:

list[Path]

Examples

>>> # Migrate all CSVs in a directory
>>> parquet_files = migrate_directory("data/")
>>> # Migrate with custom pattern
>>> parquet_files = migrate_directory("data/", pattern="streamflow_*.csv")