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:
objectEasy-to-use interface for designing optimal sensor networks.
- Parameters:
streamflow_data (ndarray)
locations (GeoDataFrame)
- 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.).
- 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).
- classmethod from_nwm_download(streamflow_file, locations_geojson, id_col='comid')[source]¶
Convenience method for NWM downloads with auto-alignment.
- 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
weightsis a file path.weight_fill_value (float, default=0.0) – Fill for locations not covered by the weight file. The default
0.0removes 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_sensorsthe 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_fracof 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:
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_sensorsentry pointing at a dropped column raises aValueError.
- class hydrosensenet.designer.NetworkDesignResult(selected_indices, locations, location_labels, performance_metrics, n_sensors, weights)[source]¶
Bases:
objectResults 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
- performance_metrics¶
When designed with
evaluate=True: per-locationnseandnnsearrays plus the raweval_resultsdict fromreconstruction_evaluation().- Type:
dict or None
- weights¶
Weight vector used for the design, if any.
- Type:
np.ndarray or None
- get_dataframe()[source]¶
Get results as DataFrame.
- Returns:
pd.DataFrame – Selected sensors with coordinates and metrics.
- Return type:
- 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
Xare candidate locations; pivoting ranks them by how much independent information they contribute, and the firstn_sensorspivots 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. withsplit_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 allmin(m, n)elimination steps;"truncated"runs only then_sensorsgreedy steps (O(m*n*k)), selecting identical pivots ~10x faster on large problems."auto"picks"truncated"whenn >= 2000and5 * 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. Whenfixed_indicesis given, those indices appear first, in the given order.- Return type:
- 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_columnand acol_poscolumn giving each row’s column position inX_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_assignmentsfor the selected locations.selected_sensor_indices (list of int) – Selected column positions into
X_train.
- Return type:
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].NaNwhere 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:
- hydrosensenet.core.metrics.reconstruction_error(true_values, pred_values, metric='rmse')[source]¶
Calculate reconstruction error.
- 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:
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 tolocations_gdfrow order.For the FEMA flood-risk workflow set
fill_value=1e-10so uncovered locations stay selectable by QR pivoting (0.0removes them entirely).normalizeis off because min-max scaling would map the minimum to0and have the same effect.
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.).
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.
- hydrosensenet.data.preprocessors.prepare_matrix(data, variable=None, drop_na=True)[source]¶
Convert DataFrame or xarray Dataset to 2D matrix for optimization.
- Parameters:
- Returns:
matrix (np.ndarray) – 2D array of shape (n_timesteps, n_locations).
location_labels (list of str) – Labels for each location (column).
- Return type:
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")
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:
- 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:
- Return type:
- filter_by_shapefile(shapefile, comid_column='COMID')[source]¶
Filter by COMIDs from a shapefile.
- Parameters:
- Return type:
- filter_by_csv(csv_file, comid_column='COMID')[source]¶
Filter by COMIDs from a CSV file.
- Parameters:
- Return type:
- 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:
- 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:
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:
- Returns:
pd.DataFrame – Available HUCs with codes and names.
- Return type:
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:
- 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:
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:
- Returns:
tuple – (gauges_gdf, comid_linkage_df) - gauges_gdf: GeoDataFrame of gauge locations - comid_linkage_df: DataFrame with STAID-COMID pairs
- Return type:
- 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:
- Returns:
usgs_comids (list of int) – COMIDs aligned to
matched_usgs_gdfrows:usgs_comids[i]is the COMID ofmatched_usgs_gdf.iloc[i].matched_usgs_gdf (GeoDataFrame) – Matched USGS gauges with a
comidcolumn (one row per station; duplicate stations dropped with a warning).
- Return type:
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.scaleis"tract"or"county".columnsselects which hazard columns to keep (e.g.RFLD_RISKS,CFLD_RISKS,HRCN_RISKS); passNoneto keep all.- Parameters:
- Return type:
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.
- hydrosensenet.io.load_streamflow(path, format='auto', columns=None, **kwargs)[source]¶
Load streamflow data with automatic format detection.
- hydrosensenet.io.save_locations(gdf, path, format='auto', **kwargs)[source]¶
Save gauge/sensor location data.
- 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:
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:
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:
Examples
>>> # Migrate all CSVs in a directory >>> parquet_files = migrate_directory("data/")
>>> # Migrate with custom pattern >>> parquet_files = migrate_directory("data/", pattern="streamflow_*.csv")