Skip to content

HmsGaugeStudy

Gauge-first study packaging, USGS context retrieval, and TauDEM input-pack helpers.

hms_commander.HmsGaugeStudy

Gauge-first hydrology study and TauDEM input-pack helpers.

This module restores the lightweight TauDEM preprocessing surface used by the Illinois-first ras-agent work. The scope is intentionally narrow:

  • fetch gauge-first hydrology context from USGS NLDI/NWIS services
  • package a durable study workspace with manifest/report/data-gap artifacts
  • build a TauDEM handoff pack with pour point, basin boundary, HUC references, and a recommended DEM clip extent

The implementation stays within the repository's static-class pattern and uses plain GeoJSON dictionaries so the core workflow does not require optional GIS dependencies.

HmsHydrologyContext

Primitive-first USGS/NLDI gauge and geometry helpers.

The methods in this class intentionally return plain dictionaries so they can be used in lightweight preprocessing steps without optional GIS dependencies.

Source code in hms_commander/HmsGaugeStudy.py
class HmsHydrologyContext:
    """
    Primitive-first USGS/NLDI gauge and geometry helpers.

    The methods in this class intentionally return plain dictionaries so they
    can be used in lightweight preprocessing steps without optional GIS
    dependencies.
    """

    @staticmethod
    def normalize_site_id(site_id: Any) -> str:
        """Normalize a USGS site id."""
        return _normalize_site_id(site_id)

    @staticmethod
    def get_nldi_feature_id(site_id: Any) -> str:
        """Return the NLDI feature id for a site."""
        return _nldi_feature_id(site_id)

    @staticmethod
    def get_usgs_gauge_metadata(site_id: Any, session: Optional[Any] = None) -> Dict[str, Any]:
        """Fetch combined NLDI and NWIS metadata for a gauge."""
        metadata, _ = _fetch_gauge_metadata_payload(site_id, session=session)
        return metadata

    @staticmethod
    def get_usgs_gauge_point_feature(
        site_id: Optional[Any] = None,
        gauge_metadata: Optional[Mapping[str, Any]] = None,
        session: Optional[Any] = None,
    ) -> Dict[str, Any]:
        """Build a point FeatureCollection for a gauge site."""
        metadata = dict(gauge_metadata or {})
        if not metadata:
            if site_id is None:
                raise ValueError("Either site_id or gauge_metadata is required")
            metadata = HmsHydrologyContext.get_usgs_gauge_metadata(site_id, session=session)

        coordinates = metadata.get("coordinates") or {}
        longitude = coordinates.get("longitude")
        latitude = coordinates.get("latitude")
        if longitude is None or latitude is None:
            raise ValueError("Gauge metadata is missing longitude/latitude values")

        return {
            "type": "FeatureCollection",
            "features": [
                {
                    "type": "Feature",
                    "geometry": {
                        "type": "Point",
                        "coordinates": [float(longitude), float(latitude)],
                    },
                    "properties": {
                        "site_id": metadata.get("site_id") or _normalize_site_id(site_id),
                        "nldi_feature_id": metadata.get("nldi_feature_id") or _nldi_feature_id(site_id),
                        "name": metadata.get("name"),
                    },
                }
            ],
        }

    @staticmethod
    def get_nldi_basin_from_gauge(site_id: Any, session: Optional[Any] = None) -> Dict[str, Any]:
        """Fetch the NLDI basin for a gauge."""
        basin, _ = _fetch_nldi_basin_payload(site_id, session=session)
        return basin

    @staticmethod
    def get_nhdplus_upstream_flowlines_from_gauge(
        site_id: Any,
        distance_km: float = 25.0,
        session: Optional[Any] = None,
    ) -> Dict[str, Any]:
        """Fetch upstream NHDPlus flowlines for a gauge."""
        flowlines, _ = _fetch_upstream_flowlines_payload(
            site_id,
            session=session,
            distance_km=distance_km,
        )
        return flowlines

    @staticmethod
    def get_nhd_huc_context_for_bounds(
        bounds: Sequence[float],
        huc_levels: Optional[Sequence[str]] = None,
        session: Optional[Any] = None,
    ) -> Dict[str, Dict[str, Any]]:
        """Fetch HUC context for a bounding box."""
        context, _ = _fetch_huc_context_payload(bounds, huc_levels=huc_levels, session=session)
        return context

    @staticmethod
    def get_nhd_huc_context_for_geometry(
        feature_or_geometry: Any,
        huc_levels: Optional[Sequence[str]] = None,
        session: Optional[Any] = None,
    ) -> Dict[str, Dict[str, Any]]:
        """Fetch HUC context for a geometry by first deriving its bounds."""
        bounds = HmsHydrologyContext.geometry_bounds(feature_or_geometry)
        return HmsHydrologyContext.get_nhd_huc_context_for_bounds(
            bounds,
            huc_levels=huc_levels,
            session=session,
        )

    @staticmethod
    def get_nhd_huc_boundary_from_gauge(
        site_id: Any,
        huc_level: str = "huc12",
        session: Optional[Any] = None,
    ) -> Dict[str, Any]:
        """Fetch the containing HUC boundary for a gauge location."""
        point_feature = HmsHydrologyContext.get_usgs_gauge_point_feature(site_id=site_id, session=session)
        context = HmsHydrologyContext.get_nhd_huc_context_for_geometry(
            point_feature,
            huc_levels=[huc_level],
            session=session,
        )
        artifact_id, _, _ = _normalize_huc_level(huc_level)
        return context[artifact_id]

    @staticmethod
    def get_nhd_huc8_boundary_from_gauge(site_id: Any, session: Optional[Any] = None) -> Dict[str, Any]:
        """Convenience wrapper for HUC8 context."""
        return HmsHydrologyContext.get_nhd_huc_boundary_from_gauge(
            site_id,
            huc_level="huc8",
            session=session,
        )

    @staticmethod
    def get_nhd_huc12_boundary_from_gauge(site_id: Any, session: Optional[Any] = None) -> Dict[str, Any]:
        """Convenience wrapper for HUC12 context."""
        return HmsHydrologyContext.get_nhd_huc_boundary_from_gauge(
            site_id,
            huc_level="huc12",
            session=session,
        )

    @staticmethod
    def get_gauge_metadata(site_id: Any, session: Optional[Any] = None) -> Dict[str, Any]:
        """Compatibility alias for get_usgs_gauge_metadata."""
        return HmsHydrologyContext.get_usgs_gauge_metadata(site_id, session=session)

    @staticmethod
    def get_gauge_point_feature(
        site_id: Optional[Any] = None,
        gauge_metadata: Optional[Mapping[str, Any]] = None,
        session: Optional[Any] = None,
    ) -> Dict[str, Any]:
        """Compatibility alias for get_usgs_gauge_point_feature."""
        return HmsHydrologyContext.get_usgs_gauge_point_feature(
            site_id=site_id,
            gauge_metadata=gauge_metadata,
            session=session,
        )

    @staticmethod
    def get_huc_context_for_bounds(
        bounds: Sequence[float],
        huc_levels: Optional[Sequence[str]] = None,
        session: Optional[Any] = None,
    ) -> Dict[str, Dict[str, Any]]:
        """Compatibility alias for get_nhd_huc_context_for_bounds."""
        return HmsHydrologyContext.get_nhd_huc_context_for_bounds(
            bounds,
            huc_levels=huc_levels,
            session=session,
        )

    @staticmethod
    def get_huc_context_for_geometry(
        feature_or_geometry: Any,
        huc_levels: Optional[Sequence[str]] = None,
        session: Optional[Any] = None,
    ) -> Dict[str, Dict[str, Any]]:
        """Compatibility alias for get_nhd_huc_context_for_geometry."""
        return HmsHydrologyContext.get_nhd_huc_context_for_geometry(
            feature_or_geometry,
            huc_levels=huc_levels,
            session=session,
        )

    @staticmethod
    def get_upstream_flowlines_from_gauge(
        site_id: Any,
        distance_km: float = 25.0,
        session: Optional[Any] = None,
    ) -> Dict[str, Any]:
        """Compatibility alias for get_nhdplus_upstream_flowlines_from_gauge."""
        return HmsHydrologyContext.get_nhdplus_upstream_flowlines_from_gauge(
            site_id,
            distance_km=distance_km,
            session=session,
        )

    @staticmethod
    def get_watershed_boundary_from_gauge(site_id: Any, session: Optional[Any] = None) -> Dict[str, Any]:
        """Compatibility alias for the NLDI watershed boundary."""
        return HmsHydrologyContext.get_nldi_basin_from_gauge(site_id, session=session)

    @staticmethod
    def geometry_bounds(feature_or_geometry: Any) -> Tuple[float, float, float, float]:
        """Return GeoJSON bounds as (west, south, east, north)."""
        return _geometry_bounds(feature_or_geometry)

    @staticmethod
    def recommend_dem_clip_extent(
        feature_or_geometry: Any,
        buffer_fraction: float = 0.05,
        min_buffer_degrees: float = 0.01,
    ) -> Dict[str, Any]:
        """Recommend a padded DEM clipping extent around a reference geometry."""
        return _recommend_dem_clip_extent(
            feature_or_geometry,
            buffer_fraction=buffer_fraction,
            min_buffer_degrees=min_buffer_degrees,
        )

    @staticmethod
    def build_pour_point_feature(
        coordinates: Optional[Sequence[float]] = None,
        gauge_metadata: Optional[Mapping[str, Any]] = None,
        properties: Optional[Mapping[str, Any]] = None,
    ) -> Dict[str, Any]:
        """Build a TauDEM-style pour point FeatureCollection."""
        metadata = dict(gauge_metadata or {})
        if coordinates is None:
            metadata_coordinates = metadata.get("coordinates") or {}
            longitude = metadata_coordinates.get("longitude")
            latitude = metadata_coordinates.get("latitude")
            if longitude is None or latitude is None:
                raise ValueError("coordinates or gauge_metadata with longitude/latitude is required")
            coordinates = [float(longitude), float(latitude)]
        point_properties = {
            "site_id": metadata.get("site_id"),
            "nldi_feature_id": metadata.get("nldi_feature_id"),
            "name": metadata.get("name"),
        }
        if properties:
            point_properties.update(dict(properties))
        point_properties = {key: value for key, value in point_properties.items() if value is not None}
        return {
            "type": "FeatureCollection",
            "features": [
                {
                    "type": "Feature",
                    "geometry": {"type": "Point", "coordinates": [float(coordinates[0]), float(coordinates[1])]},
                    "properties": point_properties,
                }
            ],
        }

    @staticmethod
    def build_taudem_handoff(
        gauge_metadata: Optional[Mapping[str, Any]] = None,
        basin_boundary: Optional[Mapping[str, Any]] = None,
        huc_context: Optional[Mapping[str, Any]] = None,
        clip_geometry: Optional[Any] = None,
        buffer_fraction: float = 0.05,
        min_buffer_degrees: float = 0.01,
    ) -> Dict[str, Any]:
        """Build an in-memory TauDEM handoff bundle."""
        pour_point = None
        if gauge_metadata:
            try:
                pour_point = HmsHydrologyContext.build_pour_point_feature(gauge_metadata=gauge_metadata)
            except ValueError:
                pour_point = None

        clip_source = clip_geometry or basin_boundary
        recommended_extent = None
        if clip_source is not None:
            recommended_extent = HmsHydrologyContext.recommend_dem_clip_extent(
                clip_source,
                buffer_fraction=buffer_fraction,
                min_buffer_degrees=min_buffer_degrees,
            )

        return {
            "pour_point": pour_point,
            "basin_boundary": basin_boundary,
            "huc_context": dict(huc_context or {}),
            "recommended_dem_clip_extent": recommended_extent,
        }

normalize_site_id(site_id) staticmethod

Normalize a USGS site id.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def normalize_site_id(site_id: Any) -> str:
    """Normalize a USGS site id."""
    return _normalize_site_id(site_id)

get_nldi_feature_id(site_id) staticmethod

Return the NLDI feature id for a site.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_nldi_feature_id(site_id: Any) -> str:
    """Return the NLDI feature id for a site."""
    return _nldi_feature_id(site_id)

get_usgs_gauge_metadata(site_id, session=None) staticmethod

Fetch combined NLDI and NWIS metadata for a gauge.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_usgs_gauge_metadata(site_id: Any, session: Optional[Any] = None) -> Dict[str, Any]:
    """Fetch combined NLDI and NWIS metadata for a gauge."""
    metadata, _ = _fetch_gauge_metadata_payload(site_id, session=session)
    return metadata

get_usgs_gauge_point_feature(site_id=None, gauge_metadata=None, session=None) staticmethod

Build a point FeatureCollection for a gauge site.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_usgs_gauge_point_feature(
    site_id: Optional[Any] = None,
    gauge_metadata: Optional[Mapping[str, Any]] = None,
    session: Optional[Any] = None,
) -> Dict[str, Any]:
    """Build a point FeatureCollection for a gauge site."""
    metadata = dict(gauge_metadata or {})
    if not metadata:
        if site_id is None:
            raise ValueError("Either site_id or gauge_metadata is required")
        metadata = HmsHydrologyContext.get_usgs_gauge_metadata(site_id, session=session)

    coordinates = metadata.get("coordinates") or {}
    longitude = coordinates.get("longitude")
    latitude = coordinates.get("latitude")
    if longitude is None or latitude is None:
        raise ValueError("Gauge metadata is missing longitude/latitude values")

    return {
        "type": "FeatureCollection",
        "features": [
            {
                "type": "Feature",
                "geometry": {
                    "type": "Point",
                    "coordinates": [float(longitude), float(latitude)],
                },
                "properties": {
                    "site_id": metadata.get("site_id") or _normalize_site_id(site_id),
                    "nldi_feature_id": metadata.get("nldi_feature_id") or _nldi_feature_id(site_id),
                    "name": metadata.get("name"),
                },
            }
        ],
    }

get_nldi_basin_from_gauge(site_id, session=None) staticmethod

Fetch the NLDI basin for a gauge.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_nldi_basin_from_gauge(site_id: Any, session: Optional[Any] = None) -> Dict[str, Any]:
    """Fetch the NLDI basin for a gauge."""
    basin, _ = _fetch_nldi_basin_payload(site_id, session=session)
    return basin

get_nhdplus_upstream_flowlines_from_gauge(site_id, distance_km=25.0, session=None) staticmethod

Fetch upstream NHDPlus flowlines for a gauge.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_nhdplus_upstream_flowlines_from_gauge(
    site_id: Any,
    distance_km: float = 25.0,
    session: Optional[Any] = None,
) -> Dict[str, Any]:
    """Fetch upstream NHDPlus flowlines for a gauge."""
    flowlines, _ = _fetch_upstream_flowlines_payload(
        site_id,
        session=session,
        distance_km=distance_km,
    )
    return flowlines

get_nhd_huc_context_for_bounds(bounds, huc_levels=None, session=None) staticmethod

Fetch HUC context for a bounding box.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_nhd_huc_context_for_bounds(
    bounds: Sequence[float],
    huc_levels: Optional[Sequence[str]] = None,
    session: Optional[Any] = None,
) -> Dict[str, Dict[str, Any]]:
    """Fetch HUC context for a bounding box."""
    context, _ = _fetch_huc_context_payload(bounds, huc_levels=huc_levels, session=session)
    return context

get_nhd_huc_context_for_geometry(feature_or_geometry, huc_levels=None, session=None) staticmethod

Fetch HUC context for a geometry by first deriving its bounds.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_nhd_huc_context_for_geometry(
    feature_or_geometry: Any,
    huc_levels: Optional[Sequence[str]] = None,
    session: Optional[Any] = None,
) -> Dict[str, Dict[str, Any]]:
    """Fetch HUC context for a geometry by first deriving its bounds."""
    bounds = HmsHydrologyContext.geometry_bounds(feature_or_geometry)
    return HmsHydrologyContext.get_nhd_huc_context_for_bounds(
        bounds,
        huc_levels=huc_levels,
        session=session,
    )

get_nhd_huc_boundary_from_gauge(site_id, huc_level='huc12', session=None) staticmethod

Fetch the containing HUC boundary for a gauge location.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_nhd_huc_boundary_from_gauge(
    site_id: Any,
    huc_level: str = "huc12",
    session: Optional[Any] = None,
) -> Dict[str, Any]:
    """Fetch the containing HUC boundary for a gauge location."""
    point_feature = HmsHydrologyContext.get_usgs_gauge_point_feature(site_id=site_id, session=session)
    context = HmsHydrologyContext.get_nhd_huc_context_for_geometry(
        point_feature,
        huc_levels=[huc_level],
        session=session,
    )
    artifact_id, _, _ = _normalize_huc_level(huc_level)
    return context[artifact_id]

get_nhd_huc8_boundary_from_gauge(site_id, session=None) staticmethod

Convenience wrapper for HUC8 context.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_nhd_huc8_boundary_from_gauge(site_id: Any, session: Optional[Any] = None) -> Dict[str, Any]:
    """Convenience wrapper for HUC8 context."""
    return HmsHydrologyContext.get_nhd_huc_boundary_from_gauge(
        site_id,
        huc_level="huc8",
        session=session,
    )

get_nhd_huc12_boundary_from_gauge(site_id, session=None) staticmethod

Convenience wrapper for HUC12 context.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_nhd_huc12_boundary_from_gauge(site_id: Any, session: Optional[Any] = None) -> Dict[str, Any]:
    """Convenience wrapper for HUC12 context."""
    return HmsHydrologyContext.get_nhd_huc_boundary_from_gauge(
        site_id,
        huc_level="huc12",
        session=session,
    )

get_gauge_metadata(site_id, session=None) staticmethod

Compatibility alias for get_usgs_gauge_metadata.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_gauge_metadata(site_id: Any, session: Optional[Any] = None) -> Dict[str, Any]:
    """Compatibility alias for get_usgs_gauge_metadata."""
    return HmsHydrologyContext.get_usgs_gauge_metadata(site_id, session=session)

get_gauge_point_feature(site_id=None, gauge_metadata=None, session=None) staticmethod

Compatibility alias for get_usgs_gauge_point_feature.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_gauge_point_feature(
    site_id: Optional[Any] = None,
    gauge_metadata: Optional[Mapping[str, Any]] = None,
    session: Optional[Any] = None,
) -> Dict[str, Any]:
    """Compatibility alias for get_usgs_gauge_point_feature."""
    return HmsHydrologyContext.get_usgs_gauge_point_feature(
        site_id=site_id,
        gauge_metadata=gauge_metadata,
        session=session,
    )

get_huc_context_for_bounds(bounds, huc_levels=None, session=None) staticmethod

Compatibility alias for get_nhd_huc_context_for_bounds.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_huc_context_for_bounds(
    bounds: Sequence[float],
    huc_levels: Optional[Sequence[str]] = None,
    session: Optional[Any] = None,
) -> Dict[str, Dict[str, Any]]:
    """Compatibility alias for get_nhd_huc_context_for_bounds."""
    return HmsHydrologyContext.get_nhd_huc_context_for_bounds(
        bounds,
        huc_levels=huc_levels,
        session=session,
    )

get_huc_context_for_geometry(feature_or_geometry, huc_levels=None, session=None) staticmethod

Compatibility alias for get_nhd_huc_context_for_geometry.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_huc_context_for_geometry(
    feature_or_geometry: Any,
    huc_levels: Optional[Sequence[str]] = None,
    session: Optional[Any] = None,
) -> Dict[str, Dict[str, Any]]:
    """Compatibility alias for get_nhd_huc_context_for_geometry."""
    return HmsHydrologyContext.get_nhd_huc_context_for_geometry(
        feature_or_geometry,
        huc_levels=huc_levels,
        session=session,
    )

get_upstream_flowlines_from_gauge(site_id, distance_km=25.0, session=None) staticmethod

Compatibility alias for get_nhdplus_upstream_flowlines_from_gauge.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_upstream_flowlines_from_gauge(
    site_id: Any,
    distance_km: float = 25.0,
    session: Optional[Any] = None,
) -> Dict[str, Any]:
    """Compatibility alias for get_nhdplus_upstream_flowlines_from_gauge."""
    return HmsHydrologyContext.get_nhdplus_upstream_flowlines_from_gauge(
        site_id,
        distance_km=distance_km,
        session=session,
    )

get_watershed_boundary_from_gauge(site_id, session=None) staticmethod

Compatibility alias for the NLDI watershed boundary.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_watershed_boundary_from_gauge(site_id: Any, session: Optional[Any] = None) -> Dict[str, Any]:
    """Compatibility alias for the NLDI watershed boundary."""
    return HmsHydrologyContext.get_nldi_basin_from_gauge(site_id, session=session)

geometry_bounds(feature_or_geometry) staticmethod

Return GeoJSON bounds as (west, south, east, north).

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def geometry_bounds(feature_or_geometry: Any) -> Tuple[float, float, float, float]:
    """Return GeoJSON bounds as (west, south, east, north)."""
    return _geometry_bounds(feature_or_geometry)

recommend_dem_clip_extent(feature_or_geometry, buffer_fraction=0.05, min_buffer_degrees=0.01) staticmethod

Recommend a padded DEM clipping extent around a reference geometry.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def recommend_dem_clip_extent(
    feature_or_geometry: Any,
    buffer_fraction: float = 0.05,
    min_buffer_degrees: float = 0.01,
) -> Dict[str, Any]:
    """Recommend a padded DEM clipping extent around a reference geometry."""
    return _recommend_dem_clip_extent(
        feature_or_geometry,
        buffer_fraction=buffer_fraction,
        min_buffer_degrees=min_buffer_degrees,
    )

build_pour_point_feature(coordinates=None, gauge_metadata=None, properties=None) staticmethod

Build a TauDEM-style pour point FeatureCollection.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def build_pour_point_feature(
    coordinates: Optional[Sequence[float]] = None,
    gauge_metadata: Optional[Mapping[str, Any]] = None,
    properties: Optional[Mapping[str, Any]] = None,
) -> Dict[str, Any]:
    """Build a TauDEM-style pour point FeatureCollection."""
    metadata = dict(gauge_metadata or {})
    if coordinates is None:
        metadata_coordinates = metadata.get("coordinates") or {}
        longitude = metadata_coordinates.get("longitude")
        latitude = metadata_coordinates.get("latitude")
        if longitude is None or latitude is None:
            raise ValueError("coordinates or gauge_metadata with longitude/latitude is required")
        coordinates = [float(longitude), float(latitude)]
    point_properties = {
        "site_id": metadata.get("site_id"),
        "nldi_feature_id": metadata.get("nldi_feature_id"),
        "name": metadata.get("name"),
    }
    if properties:
        point_properties.update(dict(properties))
    point_properties = {key: value for key, value in point_properties.items() if value is not None}
    return {
        "type": "FeatureCollection",
        "features": [
            {
                "type": "Feature",
                "geometry": {"type": "Point", "coordinates": [float(coordinates[0]), float(coordinates[1])]},
                "properties": point_properties,
            }
        ],
    }

build_taudem_handoff(gauge_metadata=None, basin_boundary=None, huc_context=None, clip_geometry=None, buffer_fraction=0.05, min_buffer_degrees=0.01) staticmethod

Build an in-memory TauDEM handoff bundle.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def build_taudem_handoff(
    gauge_metadata: Optional[Mapping[str, Any]] = None,
    basin_boundary: Optional[Mapping[str, Any]] = None,
    huc_context: Optional[Mapping[str, Any]] = None,
    clip_geometry: Optional[Any] = None,
    buffer_fraction: float = 0.05,
    min_buffer_degrees: float = 0.01,
) -> Dict[str, Any]:
    """Build an in-memory TauDEM handoff bundle."""
    pour_point = None
    if gauge_metadata:
        try:
            pour_point = HmsHydrologyContext.build_pour_point_feature(gauge_metadata=gauge_metadata)
        except ValueError:
            pour_point = None

    clip_source = clip_geometry or basin_boundary
    recommended_extent = None
    if clip_source is not None:
        recommended_extent = HmsHydrologyContext.recommend_dem_clip_extent(
            clip_source,
            buffer_fraction=buffer_fraction,
            min_buffer_degrees=min_buffer_degrees,
        )

    return {
        "pour_point": pour_point,
        "basin_boundary": basin_boundary,
        "huc_context": dict(huc_context or {}),
        "recommended_dem_clip_extent": recommended_extent,
    }

HmsGaugeStudy

Static class for gauge-first study packaging and TauDEM handoff artifacts.

Source code in hms_commander/HmsGaugeStudy.py
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
class HmsGaugeStudy:
    """Static class for gauge-first study packaging and TauDEM handoff artifacts."""

    @staticmethod
    def normalize_site_id(site_id: Any) -> str:
        """Normalize a USGS site id."""
        return HmsHydrologyContext.normalize_site_id(site_id)

    @staticmethod
    def get_nldi_feature_id(site_id: Any) -> str:
        """Return the NLDI feature id for a site."""
        return HmsHydrologyContext.get_nldi_feature_id(site_id)

    @staticmethod
    def create_workspace(workspace_root: Union[str, Path]) -> Dict[str, Path]:
        """Create the standard gauge-study workspace layout."""
        root = Path(workspace_root)
        workspace = {
            "root": root,
            "metadata": root / "metadata",
            "context": root / "context",
            "reports": root / "reports",
            "raw": root / "raw",
        }
        for path in workspace.values():
            path.mkdir(parents=True, exist_ok=True)
        return workspace

    @staticmethod
    def fetch_gauge_metadata(site_id: Any, session: Optional[Any] = None) -> Dict[str, Any]:
        """Fetch combined gauge metadata."""
        return HmsHydrologyContext.get_usgs_gauge_metadata(site_id, session=session)

    @staticmethod
    def fetch_nldi_basin(site_id: Any, session: Optional[Any] = None) -> Dict[str, Any]:
        """Fetch the NLDI basin for a site."""
        return HmsHydrologyContext.get_nldi_basin_from_gauge(site_id, session=session)

    @staticmethod
    def fetch_upstream_hydrography(
        site_id: Any,
        distance_km: float = 25.0,
        session: Optional[Any] = None,
    ) -> Dict[str, Any]:
        """Fetch upstream hydrography for a site."""
        return HmsHydrologyContext.get_nhdplus_upstream_flowlines_from_gauge(
            site_id,
            distance_km=distance_km,
            session=session,
        )

    @staticmethod
    def fetch_huc_context(
        bounds: Sequence[float],
        huc_levels: Optional[Sequence[str]] = None,
        session: Optional[Any] = None,
    ) -> Dict[str, Dict[str, Any]]:
        """Fetch HUC context for bounds."""
        return HmsHydrologyContext.get_nhd_huc_context_for_bounds(
            bounds,
            huc_levels=huc_levels,
            session=session,
        )

    @staticmethod
    @log_call
    def build_from_usgs_site(
        site_id: Any,
        workspace_root: Union[str, Path],
        upstream_distance_km: float = 25.0,
        huc_levels: Optional[Sequence[str]] = None,
        session: Optional[Any] = None,
    ) -> Dict[str, Any]:
        """Build a gauge-first study workspace from USGS services."""
        normalized_site_id = HmsGaugeStudy.normalize_site_id(site_id)
        workspace = HmsGaugeStudy.create_workspace(workspace_root)
        artifact_state: Dict[str, Dict[str, Any]] = {}

        gauge_metadata, gauge_records = _fetch_gauge_metadata_payload(normalized_site_id, session=session)
        basin_boundary, basin_record = _fetch_nldi_basin_payload(normalized_site_id, session=session)
        provenance_records: List[Dict[str, Any]] = [*gauge_records, basin_record]

        context_payloads: Dict[str, Optional[Dict[str, Any]]] = {
            "nldi_basin": basin_boundary,
            "upstream_hydrography": None,
            "huc8_context": None,
            "huc12_context": None,
        }

        basin_bounds = HmsHydrologyContext.geometry_bounds(basin_boundary)

        try:
            huc_context, huc_records = _fetch_huc_context_payload(
                basin_bounds,
                huc_levels=huc_levels,
                session=session,
            )
            provenance_records.extend(huc_records)
            for artifact_id, payload in huc_context.items():
                context_payloads[artifact_id] = payload
        except Exception as exc:
            logger.warning("HUC context lookup failed for %s: %s", normalized_site_id, exc)

        try:
            flowlines_payload, flowlines_record = _fetch_upstream_flowlines_payload(
                normalized_site_id,
                session=session,
                distance_km=upstream_distance_km,
            )
            provenance_records.append(flowlines_record)
            context_payloads["upstream_hydrography"] = flowlines_payload
        except Exception as exc:
            logger.warning("Upstream hydrography lookup failed for %s: %s", normalized_site_id, exc)

        artifact_state["gauge_metadata"] = _write_json(
            workspace["metadata"] / "gauge_metadata.json",
            gauge_metadata,
        )
        artifact_state["nldi_basin"] = _write_json(
            workspace["context"] / "nldi_basin.geojson",
            basin_boundary,
        )
        if context_payloads["upstream_hydrography"] is not None:
            artifact_state["upstream_hydrography"] = _write_json(
                workspace["context"] / "upstream_hydrography.geojson",
                context_payloads["upstream_hydrography"],
            )
        for artifact_id in ("huc8_context", "huc12_context"):
            payload = context_payloads.get(artifact_id)
            if payload is not None:
                artifact_state[artifact_id] = _write_json(
                    workspace["context"] / Path(f"{artifact_id}.geojson"),
                    payload,
                )

        provenance = {
            "study_type": "gauge_first_watershed",
            "site_id": normalized_site_id,
            "generated_at": _utc_now(),
            "records": provenance_records,
        }
        artifact_state["provenance"] = _write_json(
            workspace["metadata"] / "provenance.json",
            provenance,
        )

        gaps: List[Dict[str, Any]] = []
        if context_payloads["huc8_context"] is None:
            gaps.append(
                {
                    "id": "missing_huc8_context",
                    "category": "hydrology_context",
                    "severity": "warning",
                    "status": "open",
                    "description": "HUC8 context could not be generated.",
                    "affected_artifact": "huc8_context",
                    "owner_repo": "hms-commander",
                    "issue_url": None,
                    "blocking_for": ["regional_context"],
                    "recommended_action": (
                        "Retry the HUC lookup with GIS dependencies installed or validate public Fabric API availability."
                    ),
                }
            )
        if context_payloads["huc12_context"] is None:
            gaps.append(
                {
                    "id": "missing_huc12_context",
                    "category": "hydrology_context",
                    "severity": "warning",
                    "status": "open",
                    "description": "HUC12 context could not be generated.",
                    "affected_artifact": "huc12_context",
                    "owner_repo": "hms-commander",
                    "issue_url": None,
                    "blocking_for": [],
                    "recommended_action": (
                        "Retry the HUC lookup with GIS dependencies installed or validate public Fabric API availability."
                    ),
                }
            )
        if context_payloads["upstream_hydrography"] is None:
            gaps.append(
                {
                    "id": "missing_upstream_hydrography",
                    "category": "hydrology_context",
                    "severity": "warning",
                    "status": "open",
                    "description": "Upstream hydrography context could not be generated.",
                    "affected_artifact": "upstream_hydrography",
                    "owner_repo": "hms-commander",
                    "issue_url": None,
                    "blocking_for": [],
                    "recommended_action": (
                        "Retry the NLDI navigation request or capture upstream flowlines from an alternate hydrography source."
                    ),
                }
            )

        data_gap_analysis = {
            "study_type": "gauge_first_watershed",
            "site_id": normalized_site_id,
            "generated_at": _utc_now(),
            "gap_count": len(gaps),
            "gaps": gaps,
        }
        artifact_state["data_gap_analysis"] = _write_json(
            workspace["reports"] / "data_gap_analysis.json",
            data_gap_analysis,
        )

        study_catalog_for_report = _artifact_catalog(_STUDY_ARTIFACT_SPECS, workspace["root"], artifact_state)
        available_context = sorted(
            artifact_id
            for artifact_id in ("nldi_basin", "huc8_context", "huc12_context", "upstream_hydrography")
            if context_payloads.get(artifact_id) is not None
        )
        missing_context = sorted(
            artifact_id
            for artifact_id in ("nldi_basin", "huc8_context", "huc12_context", "upstream_hydrography")
            if context_payloads.get(artifact_id) is None
        )
        study_report = {
            "study_type": "gauge_first_watershed",
            "site_id": normalized_site_id,
            "generated_at": _utc_now(),
            "gauge_name": gauge_metadata.get("name"),
            "coordinates": gauge_metadata.get("coordinates"),
            "available_context": available_context,
            "missing_context": missing_context,
            "artifact_count": len(_STUDY_ARTIFACT_SPECS),
            "data_gap_count": len(gaps),
            "blocking_gap_count": sum(1 for gap in gaps if gap.get("blocking_for")),
            "gap_affected_artifacts": sorted({gap["affected_artifact"] for gap in gaps}),
            "artifacts": _artifact_rows(
                study_catalog_for_report,
                status_overrides={"manifest": "planned", "study_report": "planned"},
            ),
        }
        artifact_state["study_report"] = _write_json(
            workspace["reports"] / "study_report.json",
            study_report,
        )

        study_catalog_for_manifest = _artifact_catalog(
            _STUDY_ARTIFACT_SPECS,
            workspace["root"],
            artifact_state,
            status_overrides={"manifest": "created"},
            omit_bytes_for={"manifest"},
        )
        manifest = {
            "schema_version": "1.0",
            "study_type": "gauge_first_watershed",
            "site_id": normalized_site_id,
            "nldi_feature_id": gauge_metadata.get("nldi_feature_id"),
            "generated_at": _utc_now(),
            "builder": {
                "package": "hms-commander",
                "class": "HmsGaugeStudy",
                "version": PACKAGE_VERSION,
            },
            "workspace": {
                "root": workspace["root"],
                "directories": {
                    "metadata": "metadata",
                    "context": "context",
                    "reports": "reports",
                    "raw": "raw",
                },
            },
            "artifacts": study_catalog_for_manifest,
        }
        artifact_state["manifest"] = _write_json(
            workspace["metadata"] / "study_manifest.json",
            manifest,
        )

        final_catalog = _artifact_catalog(_STUDY_ARTIFACT_SPECS, workspace["root"], artifact_state)
        final_manifest = dict(manifest)
        final_manifest["artifacts"] = _artifact_catalog(
            _STUDY_ARTIFACT_SPECS,
            workspace["root"],
            artifact_state,
            omit_bytes_for={"manifest"},
        )
        _write_json(workspace["metadata"] / "study_manifest.json", final_manifest)

        return {
            "site_id": normalized_site_id,
            "workspace_root": workspace["root"],
            "workspace": workspace,
            "gauge_metadata": gauge_metadata,
            "provenance": provenance,
            "manifest": final_manifest,
            "study_report": study_report,
            "data_gap_analysis": data_gap_analysis,
            "artifacts": final_catalog,
        }

    @staticmethod
    @log_call
    def build_taudem_input_pack(
        workspace_root: Union[str, Path],
        pack_name: str = "taudem_input_pack",
        dem_buffer_fraction: float = 0.05,
        min_dem_buffer_degrees: float = 0.01,
    ) -> Dict[str, Any]:
        """Build a TauDEM-ready input pack from a saved study workspace."""
        workspace_root = Path(workspace_root)
        HmsGaugeStudy.create_workspace(workspace_root)
        pack_root = workspace_root / "raw" / pack_name
        pack_root.mkdir(parents=True, exist_ok=True)

        artifact_state: Dict[str, Dict[str, Any]] = {}
        provenance_records: List[Dict[str, Any]] = []

        gauge_metadata_path = workspace_root / "metadata" / "gauge_metadata.json"
        basin_path = workspace_root / "context" / "nldi_basin.geojson"
        huc8_path = workspace_root / "context" / "huc8_context.geojson"
        huc12_path = workspace_root / "context" / "huc12_context.geojson"

        gauge_metadata = _load_json(gauge_metadata_path) if gauge_metadata_path.exists() else None
        basin_boundary = _load_json(basin_path) if basin_path.exists() else None
        site_id = (
            (gauge_metadata or {}).get("site_id")
            or (_load_json(workspace_root / "metadata" / "study_manifest.json").get("site_id")
                if (workspace_root / "metadata" / "study_manifest.json").exists() else None)
            or "unknown"
        )

        if gauge_metadata and (gauge_metadata.get("coordinates") or {}).get("longitude") is not None:
            pour_point = HmsHydrologyContext.build_pour_point_feature(
                gauge_metadata=gauge_metadata,
                properties={"source_artifact": "metadata/gauge_metadata.json"},
            )
            artifact_state["taudem_pour_point"] = _write_json(pack_root / "pour_point.geojson", pour_point)
            provenance_records.append(
                _provenance_record(
                    source_name="study_workspace",
                    method="DERIVED",
                    request_url=gauge_metadata_path,
                    artifact_id="taudem_pour_point",
                    notes="Derived from saved gauge metadata coordinates.",
                )
            )
        else:
            pour_point = None

        if basin_boundary is not None:
            artifact_state["taudem_basin_boundary"] = _write_json(pack_root / "basin_boundary.geojson", basin_boundary)
            provenance_records.append(
                _provenance_record(
                    source_name="study_workspace",
                    method="DERIVED",
                    request_url=basin_path,
                    artifact_id="taudem_basin_boundary",
                    notes="Copied from saved study basin boundary.",
                )
            )
        huc_reference_entries: List[Dict[str, Any]] = []
        for artifact_id, level, path in (
            ("huc8_context", "huc8", huc8_path),
            ("huc12_context", "huc12", huc12_path),
        ):
            if path.exists():
                payload = _load_json(path)
                huc_reference_entries.append(
                    {
                        "artifact_id": artifact_id,
                        "level": level,
                        "path": f"context/{path.name}",
                        "feature_count": len(payload.get("features") or []),
                        "bounds": list(HmsHydrologyContext.geometry_bounds(payload)),
                    }
                )

        huc_context_reference = {
            "study_type": "taudem_input_pack",
            "site_id": site_id,
            "generated_at": _utc_now(),
            "primary_reference": huc_reference_entries[0]["artifact_id"] if huc_reference_entries else None,
            "references": huc_reference_entries,
        }
        artifact_state["taudem_huc_context_reference"] = _write_json(
            pack_root / "huc_context_reference.json",
            huc_context_reference,
        )
        provenance_records.append(
            _provenance_record(
                source_name="study_workspace",
                method="DERIVED",
                request_url=workspace_root / "context",
                artifact_id="taudem_huc_context_reference",
                notes="References existing HUC context artifacts from the workspace.",
            )
        )

        recommended_extent = None
        if basin_boundary is not None:
            dem_extent_core = HmsHydrologyContext.recommend_dem_clip_extent(
                basin_boundary,
                buffer_fraction=dem_buffer_fraction,
                min_buffer_degrees=min_dem_buffer_degrees,
            )
            recommended_extent = {
                "study_type": "taudem_input_pack",
                "site_id": site_id,
                "generated_at": _utc_now(),
                "source_artifact": "taudem_basin_boundary",
                "source_bounds": dem_extent_core["source_bounds"],
                "recommended_bounds": dem_extent_core["recommended_bounds"],
                "buffer_fraction": dem_extent_core["buffer_fraction"],
                "min_buffer_degrees": dem_extent_core["minimum_buffer_degrees"],
                "applied_buffer_degrees": dem_extent_core["applied_buffer_degrees"],
                "recommended_clip_geometry": _bounds_polygon(dem_extent_core["recommended_bounds"]),
            }
            artifact_state["taudem_dem_clip_extent"] = _write_json(
                pack_root / "recommended_dem_clip_extent.json",
                recommended_extent,
            )
            provenance_records.append(
                _provenance_record(
                    source_name="study_workspace",
                    method="DERIVED",
                    request_url=pack_root,
                    artifact_id="taudem_dem_clip_extent",
                    notes="Derived from taudem_basin_boundary bounds with configured padding.",
                )
            )

        provenance = {
            "study_type": "taudem_input_pack",
            "site_id": site_id,
            "generated_at": _utc_now(),
            "records": provenance_records,
        }
        artifact_state["taudem_pack_provenance"] = _write_json(pack_root / "provenance.json", provenance)

        gaps: List[Dict[str, Any]] = []
        if pour_point is None:
            gaps.append(
                {
                    "id": "missing_gauge_metadata_for_taudem_pack",
                    "category": "taudem_pack",
                    "severity": "error",
                    "status": "open",
                    "description": "Gauge metadata is missing, so a TauDEM pour point cannot be derived.",
                    "affected_artifact": "taudem_pour_point",
                    "owner_repo": "hms-commander",
                    "issue_url": None,
                    "blocking_for": ["taudem_pour_point", "taudem_watershed_delineation"],
                    "recommended_action": (
                        "Build the gauge-first workspace first or provide a compatible gauge_metadata.json source file."
                    ),
                }
            )
        if not huc_reference_entries:
            gaps.append(
                {
                    "id": "missing_huc_context_for_taudem_pack",
                    "category": "taudem_pack",
                    "severity": "warning",
                    "status": "open",
                    "description": "No HUC context artifacts were available to reference in the TauDEM pack.",
                    "affected_artifact": "taudem_huc_context_reference",
                    "owner_repo": "hms-commander",
                    "issue_url": None,
                    "blocking_for": [],
                    "recommended_action": (
                        "Add at least one HUC context layer to improve review and DEM clipping context."
                    ),
                }
            )

        data_gap_analysis = {
            "study_type": "taudem_input_pack",
            "site_id": site_id,
            "generated_at": _utc_now(),
            "gap_count": len(gaps),
            "gaps": gaps,
        }
        artifact_state["taudem_pack_data_gap_analysis"] = _write_json(
            pack_root / "data_gap_analysis.json",
            data_gap_analysis,
        )

        available_components = sorted(
            artifact_id
            for artifact_id, is_available in (
                ("taudem_pour_point", pour_point is not None),
                ("taudem_basin_boundary", basin_boundary is not None),
                ("taudem_huc_context_reference", bool(huc_reference_entries)),
                ("taudem_dem_clip_extent", recommended_extent is not None),
            )
            if is_available
        )
        missing_components = sorted(
            artifact_id
            for artifact_id, is_available in (
                ("taudem_pour_point", pour_point is not None),
                ("taudem_basin_boundary", basin_boundary is not None),
                ("taudem_huc_context_reference", bool(huc_reference_entries)),
                ("taudem_dem_clip_extent", recommended_extent is not None),
            )
            if not is_available
        )
        pack_catalog_for_report = _artifact_catalog(_PACK_ARTIFACT_SPECS, workspace_root, artifact_state)
        study_report = {
            "study_type": "taudem_input_pack",
            "site_id": site_id,
            "generated_at": _utc_now(),
            "available_components": available_components,
            "missing_components": missing_components,
            "artifact_count": len(_PACK_ARTIFACT_SPECS),
            "data_gap_count": len(gaps),
            "blocking_gap_count": sum(1 for gap in gaps if gap.get("blocking_for")),
            "artifacts": _artifact_rows(
                pack_catalog_for_report,
                status_overrides={
                    "taudem_pack_manifest": "planned",
                    "taudem_pack_report": "planned",
                },
            ),
        }
        artifact_state["taudem_pack_report"] = _write_json(pack_root / "report.json", study_report)

        pack_catalog_for_manifest = _artifact_catalog(
            _PACK_ARTIFACT_SPECS,
            workspace_root,
            artifact_state,
            status_overrides={"taudem_pack_manifest": "created"},
            omit_bytes_for={"taudem_pack_manifest"},
        )
        manifest = {
            "schema_version": "1.0",
            "study_type": "taudem_input_pack",
            "site_id": site_id,
            "generated_at": _utc_now(),
            "builder": {
                "package": "hms-commander",
                "class": "HmsGaugeStudy",
                "method": "build_taudem_input_pack",
                "version": PACKAGE_VERSION,
            },
            "workspace_root": workspace_root,
            "pack_root": f"raw/{pack_name}",
            "artifacts": pack_catalog_for_manifest,
        }
        artifact_state["taudem_pack_manifest"] = _write_json(
            pack_root / "taudem_input_pack_manifest.json",
            manifest,
        )

        final_catalog = _artifact_catalog(_PACK_ARTIFACT_SPECS, workspace_root, artifact_state)
        final_manifest = dict(manifest)
        final_manifest["artifacts"] = _artifact_catalog(
            _PACK_ARTIFACT_SPECS,
            workspace_root,
            artifact_state,
            omit_bytes_for={"taudem_pack_manifest"},
        )
        _write_json(pack_root / "taudem_input_pack_manifest.json", final_manifest)

        return {
            "site_id": site_id,
            "workspace_root": workspace_root,
            "pack_root": pack_root,
            "artifacts": final_catalog,
            "provenance": provenance,
            "manifest": final_manifest,
            "study_report": study_report,
            "data_gap_analysis": data_gap_analysis,
        }

normalize_site_id(site_id) staticmethod

Normalize a USGS site id.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def normalize_site_id(site_id: Any) -> str:
    """Normalize a USGS site id."""
    return HmsHydrologyContext.normalize_site_id(site_id)

get_nldi_feature_id(site_id) staticmethod

Return the NLDI feature id for a site.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_nldi_feature_id(site_id: Any) -> str:
    """Return the NLDI feature id for a site."""
    return HmsHydrologyContext.get_nldi_feature_id(site_id)

create_workspace(workspace_root) staticmethod

Create the standard gauge-study workspace layout.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def create_workspace(workspace_root: Union[str, Path]) -> Dict[str, Path]:
    """Create the standard gauge-study workspace layout."""
    root = Path(workspace_root)
    workspace = {
        "root": root,
        "metadata": root / "metadata",
        "context": root / "context",
        "reports": root / "reports",
        "raw": root / "raw",
    }
    for path in workspace.values():
        path.mkdir(parents=True, exist_ok=True)
    return workspace

fetch_gauge_metadata(site_id, session=None) staticmethod

Fetch combined gauge metadata.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def fetch_gauge_metadata(site_id: Any, session: Optional[Any] = None) -> Dict[str, Any]:
    """Fetch combined gauge metadata."""
    return HmsHydrologyContext.get_usgs_gauge_metadata(site_id, session=session)

fetch_nldi_basin(site_id, session=None) staticmethod

Fetch the NLDI basin for a site.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def fetch_nldi_basin(site_id: Any, session: Optional[Any] = None) -> Dict[str, Any]:
    """Fetch the NLDI basin for a site."""
    return HmsHydrologyContext.get_nldi_basin_from_gauge(site_id, session=session)

fetch_upstream_hydrography(site_id, distance_km=25.0, session=None) staticmethod

Fetch upstream hydrography for a site.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def fetch_upstream_hydrography(
    site_id: Any,
    distance_km: float = 25.0,
    session: Optional[Any] = None,
) -> Dict[str, Any]:
    """Fetch upstream hydrography for a site."""
    return HmsHydrologyContext.get_nhdplus_upstream_flowlines_from_gauge(
        site_id,
        distance_km=distance_km,
        session=session,
    )

fetch_huc_context(bounds, huc_levels=None, session=None) staticmethod

Fetch HUC context for bounds.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def fetch_huc_context(
    bounds: Sequence[float],
    huc_levels: Optional[Sequence[str]] = None,
    session: Optional[Any] = None,
) -> Dict[str, Dict[str, Any]]:
    """Fetch HUC context for bounds."""
    return HmsHydrologyContext.get_nhd_huc_context_for_bounds(
        bounds,
        huc_levels=huc_levels,
        session=session,
    )

build_from_usgs_site(site_id, workspace_root, upstream_distance_km=25.0, huc_levels=None, session=None) staticmethod

Build a gauge-first study workspace from USGS services.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
@log_call
def build_from_usgs_site(
    site_id: Any,
    workspace_root: Union[str, Path],
    upstream_distance_km: float = 25.0,
    huc_levels: Optional[Sequence[str]] = None,
    session: Optional[Any] = None,
) -> Dict[str, Any]:
    """Build a gauge-first study workspace from USGS services."""
    normalized_site_id = HmsGaugeStudy.normalize_site_id(site_id)
    workspace = HmsGaugeStudy.create_workspace(workspace_root)
    artifact_state: Dict[str, Dict[str, Any]] = {}

    gauge_metadata, gauge_records = _fetch_gauge_metadata_payload(normalized_site_id, session=session)
    basin_boundary, basin_record = _fetch_nldi_basin_payload(normalized_site_id, session=session)
    provenance_records: List[Dict[str, Any]] = [*gauge_records, basin_record]

    context_payloads: Dict[str, Optional[Dict[str, Any]]] = {
        "nldi_basin": basin_boundary,
        "upstream_hydrography": None,
        "huc8_context": None,
        "huc12_context": None,
    }

    basin_bounds = HmsHydrologyContext.geometry_bounds(basin_boundary)

    try:
        huc_context, huc_records = _fetch_huc_context_payload(
            basin_bounds,
            huc_levels=huc_levels,
            session=session,
        )
        provenance_records.extend(huc_records)
        for artifact_id, payload in huc_context.items():
            context_payloads[artifact_id] = payload
    except Exception as exc:
        logger.warning("HUC context lookup failed for %s: %s", normalized_site_id, exc)

    try:
        flowlines_payload, flowlines_record = _fetch_upstream_flowlines_payload(
            normalized_site_id,
            session=session,
            distance_km=upstream_distance_km,
        )
        provenance_records.append(flowlines_record)
        context_payloads["upstream_hydrography"] = flowlines_payload
    except Exception as exc:
        logger.warning("Upstream hydrography lookup failed for %s: %s", normalized_site_id, exc)

    artifact_state["gauge_metadata"] = _write_json(
        workspace["metadata"] / "gauge_metadata.json",
        gauge_metadata,
    )
    artifact_state["nldi_basin"] = _write_json(
        workspace["context"] / "nldi_basin.geojson",
        basin_boundary,
    )
    if context_payloads["upstream_hydrography"] is not None:
        artifact_state["upstream_hydrography"] = _write_json(
            workspace["context"] / "upstream_hydrography.geojson",
            context_payloads["upstream_hydrography"],
        )
    for artifact_id in ("huc8_context", "huc12_context"):
        payload = context_payloads.get(artifact_id)
        if payload is not None:
            artifact_state[artifact_id] = _write_json(
                workspace["context"] / Path(f"{artifact_id}.geojson"),
                payload,
            )

    provenance = {
        "study_type": "gauge_first_watershed",
        "site_id": normalized_site_id,
        "generated_at": _utc_now(),
        "records": provenance_records,
    }
    artifact_state["provenance"] = _write_json(
        workspace["metadata"] / "provenance.json",
        provenance,
    )

    gaps: List[Dict[str, Any]] = []
    if context_payloads["huc8_context"] is None:
        gaps.append(
            {
                "id": "missing_huc8_context",
                "category": "hydrology_context",
                "severity": "warning",
                "status": "open",
                "description": "HUC8 context could not be generated.",
                "affected_artifact": "huc8_context",
                "owner_repo": "hms-commander",
                "issue_url": None,
                "blocking_for": ["regional_context"],
                "recommended_action": (
                    "Retry the HUC lookup with GIS dependencies installed or validate public Fabric API availability."
                ),
            }
        )
    if context_payloads["huc12_context"] is None:
        gaps.append(
            {
                "id": "missing_huc12_context",
                "category": "hydrology_context",
                "severity": "warning",
                "status": "open",
                "description": "HUC12 context could not be generated.",
                "affected_artifact": "huc12_context",
                "owner_repo": "hms-commander",
                "issue_url": None,
                "blocking_for": [],
                "recommended_action": (
                    "Retry the HUC lookup with GIS dependencies installed or validate public Fabric API availability."
                ),
            }
        )
    if context_payloads["upstream_hydrography"] is None:
        gaps.append(
            {
                "id": "missing_upstream_hydrography",
                "category": "hydrology_context",
                "severity": "warning",
                "status": "open",
                "description": "Upstream hydrography context could not be generated.",
                "affected_artifact": "upstream_hydrography",
                "owner_repo": "hms-commander",
                "issue_url": None,
                "blocking_for": [],
                "recommended_action": (
                    "Retry the NLDI navigation request or capture upstream flowlines from an alternate hydrography source."
                ),
            }
        )

    data_gap_analysis = {
        "study_type": "gauge_first_watershed",
        "site_id": normalized_site_id,
        "generated_at": _utc_now(),
        "gap_count": len(gaps),
        "gaps": gaps,
    }
    artifact_state["data_gap_analysis"] = _write_json(
        workspace["reports"] / "data_gap_analysis.json",
        data_gap_analysis,
    )

    study_catalog_for_report = _artifact_catalog(_STUDY_ARTIFACT_SPECS, workspace["root"], artifact_state)
    available_context = sorted(
        artifact_id
        for artifact_id in ("nldi_basin", "huc8_context", "huc12_context", "upstream_hydrography")
        if context_payloads.get(artifact_id) is not None
    )
    missing_context = sorted(
        artifact_id
        for artifact_id in ("nldi_basin", "huc8_context", "huc12_context", "upstream_hydrography")
        if context_payloads.get(artifact_id) is None
    )
    study_report = {
        "study_type": "gauge_first_watershed",
        "site_id": normalized_site_id,
        "generated_at": _utc_now(),
        "gauge_name": gauge_metadata.get("name"),
        "coordinates": gauge_metadata.get("coordinates"),
        "available_context": available_context,
        "missing_context": missing_context,
        "artifact_count": len(_STUDY_ARTIFACT_SPECS),
        "data_gap_count": len(gaps),
        "blocking_gap_count": sum(1 for gap in gaps if gap.get("blocking_for")),
        "gap_affected_artifacts": sorted({gap["affected_artifact"] for gap in gaps}),
        "artifacts": _artifact_rows(
            study_catalog_for_report,
            status_overrides={"manifest": "planned", "study_report": "planned"},
        ),
    }
    artifact_state["study_report"] = _write_json(
        workspace["reports"] / "study_report.json",
        study_report,
    )

    study_catalog_for_manifest = _artifact_catalog(
        _STUDY_ARTIFACT_SPECS,
        workspace["root"],
        artifact_state,
        status_overrides={"manifest": "created"},
        omit_bytes_for={"manifest"},
    )
    manifest = {
        "schema_version": "1.0",
        "study_type": "gauge_first_watershed",
        "site_id": normalized_site_id,
        "nldi_feature_id": gauge_metadata.get("nldi_feature_id"),
        "generated_at": _utc_now(),
        "builder": {
            "package": "hms-commander",
            "class": "HmsGaugeStudy",
            "version": PACKAGE_VERSION,
        },
        "workspace": {
            "root": workspace["root"],
            "directories": {
                "metadata": "metadata",
                "context": "context",
                "reports": "reports",
                "raw": "raw",
            },
        },
        "artifacts": study_catalog_for_manifest,
    }
    artifact_state["manifest"] = _write_json(
        workspace["metadata"] / "study_manifest.json",
        manifest,
    )

    final_catalog = _artifact_catalog(_STUDY_ARTIFACT_SPECS, workspace["root"], artifact_state)
    final_manifest = dict(manifest)
    final_manifest["artifacts"] = _artifact_catalog(
        _STUDY_ARTIFACT_SPECS,
        workspace["root"],
        artifact_state,
        omit_bytes_for={"manifest"},
    )
    _write_json(workspace["metadata"] / "study_manifest.json", final_manifest)

    return {
        "site_id": normalized_site_id,
        "workspace_root": workspace["root"],
        "workspace": workspace,
        "gauge_metadata": gauge_metadata,
        "provenance": provenance,
        "manifest": final_manifest,
        "study_report": study_report,
        "data_gap_analysis": data_gap_analysis,
        "artifacts": final_catalog,
    }

build_taudem_input_pack(workspace_root, pack_name='taudem_input_pack', dem_buffer_fraction=0.05, min_dem_buffer_degrees=0.01) staticmethod

Build a TauDEM-ready input pack from a saved study workspace.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
@log_call
def build_taudem_input_pack(
    workspace_root: Union[str, Path],
    pack_name: str = "taudem_input_pack",
    dem_buffer_fraction: float = 0.05,
    min_dem_buffer_degrees: float = 0.01,
) -> Dict[str, Any]:
    """Build a TauDEM-ready input pack from a saved study workspace."""
    workspace_root = Path(workspace_root)
    HmsGaugeStudy.create_workspace(workspace_root)
    pack_root = workspace_root / "raw" / pack_name
    pack_root.mkdir(parents=True, exist_ok=True)

    artifact_state: Dict[str, Dict[str, Any]] = {}
    provenance_records: List[Dict[str, Any]] = []

    gauge_metadata_path = workspace_root / "metadata" / "gauge_metadata.json"
    basin_path = workspace_root / "context" / "nldi_basin.geojson"
    huc8_path = workspace_root / "context" / "huc8_context.geojson"
    huc12_path = workspace_root / "context" / "huc12_context.geojson"

    gauge_metadata = _load_json(gauge_metadata_path) if gauge_metadata_path.exists() else None
    basin_boundary = _load_json(basin_path) if basin_path.exists() else None
    site_id = (
        (gauge_metadata or {}).get("site_id")
        or (_load_json(workspace_root / "metadata" / "study_manifest.json").get("site_id")
            if (workspace_root / "metadata" / "study_manifest.json").exists() else None)
        or "unknown"
    )

    if gauge_metadata and (gauge_metadata.get("coordinates") or {}).get("longitude") is not None:
        pour_point = HmsHydrologyContext.build_pour_point_feature(
            gauge_metadata=gauge_metadata,
            properties={"source_artifact": "metadata/gauge_metadata.json"},
        )
        artifact_state["taudem_pour_point"] = _write_json(pack_root / "pour_point.geojson", pour_point)
        provenance_records.append(
            _provenance_record(
                source_name="study_workspace",
                method="DERIVED",
                request_url=gauge_metadata_path,
                artifact_id="taudem_pour_point",
                notes="Derived from saved gauge metadata coordinates.",
            )
        )
    else:
        pour_point = None

    if basin_boundary is not None:
        artifact_state["taudem_basin_boundary"] = _write_json(pack_root / "basin_boundary.geojson", basin_boundary)
        provenance_records.append(
            _provenance_record(
                source_name="study_workspace",
                method="DERIVED",
                request_url=basin_path,
                artifact_id="taudem_basin_boundary",
                notes="Copied from saved study basin boundary.",
            )
        )
    huc_reference_entries: List[Dict[str, Any]] = []
    for artifact_id, level, path in (
        ("huc8_context", "huc8", huc8_path),
        ("huc12_context", "huc12", huc12_path),
    ):
        if path.exists():
            payload = _load_json(path)
            huc_reference_entries.append(
                {
                    "artifact_id": artifact_id,
                    "level": level,
                    "path": f"context/{path.name}",
                    "feature_count": len(payload.get("features") or []),
                    "bounds": list(HmsHydrologyContext.geometry_bounds(payload)),
                }
            )

    huc_context_reference = {
        "study_type": "taudem_input_pack",
        "site_id": site_id,
        "generated_at": _utc_now(),
        "primary_reference": huc_reference_entries[0]["artifact_id"] if huc_reference_entries else None,
        "references": huc_reference_entries,
    }
    artifact_state["taudem_huc_context_reference"] = _write_json(
        pack_root / "huc_context_reference.json",
        huc_context_reference,
    )
    provenance_records.append(
        _provenance_record(
            source_name="study_workspace",
            method="DERIVED",
            request_url=workspace_root / "context",
            artifact_id="taudem_huc_context_reference",
            notes="References existing HUC context artifacts from the workspace.",
        )
    )

    recommended_extent = None
    if basin_boundary is not None:
        dem_extent_core = HmsHydrologyContext.recommend_dem_clip_extent(
            basin_boundary,
            buffer_fraction=dem_buffer_fraction,
            min_buffer_degrees=min_dem_buffer_degrees,
        )
        recommended_extent = {
            "study_type": "taudem_input_pack",
            "site_id": site_id,
            "generated_at": _utc_now(),
            "source_artifact": "taudem_basin_boundary",
            "source_bounds": dem_extent_core["source_bounds"],
            "recommended_bounds": dem_extent_core["recommended_bounds"],
            "buffer_fraction": dem_extent_core["buffer_fraction"],
            "min_buffer_degrees": dem_extent_core["minimum_buffer_degrees"],
            "applied_buffer_degrees": dem_extent_core["applied_buffer_degrees"],
            "recommended_clip_geometry": _bounds_polygon(dem_extent_core["recommended_bounds"]),
        }
        artifact_state["taudem_dem_clip_extent"] = _write_json(
            pack_root / "recommended_dem_clip_extent.json",
            recommended_extent,
        )
        provenance_records.append(
            _provenance_record(
                source_name="study_workspace",
                method="DERIVED",
                request_url=pack_root,
                artifact_id="taudem_dem_clip_extent",
                notes="Derived from taudem_basin_boundary bounds with configured padding.",
            )
        )

    provenance = {
        "study_type": "taudem_input_pack",
        "site_id": site_id,
        "generated_at": _utc_now(),
        "records": provenance_records,
    }
    artifact_state["taudem_pack_provenance"] = _write_json(pack_root / "provenance.json", provenance)

    gaps: List[Dict[str, Any]] = []
    if pour_point is None:
        gaps.append(
            {
                "id": "missing_gauge_metadata_for_taudem_pack",
                "category": "taudem_pack",
                "severity": "error",
                "status": "open",
                "description": "Gauge metadata is missing, so a TauDEM pour point cannot be derived.",
                "affected_artifact": "taudem_pour_point",
                "owner_repo": "hms-commander",
                "issue_url": None,
                "blocking_for": ["taudem_pour_point", "taudem_watershed_delineation"],
                "recommended_action": (
                    "Build the gauge-first workspace first or provide a compatible gauge_metadata.json source file."
                ),
            }
        )
    if not huc_reference_entries:
        gaps.append(
            {
                "id": "missing_huc_context_for_taudem_pack",
                "category": "taudem_pack",
                "severity": "warning",
                "status": "open",
                "description": "No HUC context artifacts were available to reference in the TauDEM pack.",
                "affected_artifact": "taudem_huc_context_reference",
                "owner_repo": "hms-commander",
                "issue_url": None,
                "blocking_for": [],
                "recommended_action": (
                    "Add at least one HUC context layer to improve review and DEM clipping context."
                ),
            }
        )

    data_gap_analysis = {
        "study_type": "taudem_input_pack",
        "site_id": site_id,
        "generated_at": _utc_now(),
        "gap_count": len(gaps),
        "gaps": gaps,
    }
    artifact_state["taudem_pack_data_gap_analysis"] = _write_json(
        pack_root / "data_gap_analysis.json",
        data_gap_analysis,
    )

    available_components = sorted(
        artifact_id
        for artifact_id, is_available in (
            ("taudem_pour_point", pour_point is not None),
            ("taudem_basin_boundary", basin_boundary is not None),
            ("taudem_huc_context_reference", bool(huc_reference_entries)),
            ("taudem_dem_clip_extent", recommended_extent is not None),
        )
        if is_available
    )
    missing_components = sorted(
        artifact_id
        for artifact_id, is_available in (
            ("taudem_pour_point", pour_point is not None),
            ("taudem_basin_boundary", basin_boundary is not None),
            ("taudem_huc_context_reference", bool(huc_reference_entries)),
            ("taudem_dem_clip_extent", recommended_extent is not None),
        )
        if not is_available
    )
    pack_catalog_for_report = _artifact_catalog(_PACK_ARTIFACT_SPECS, workspace_root, artifact_state)
    study_report = {
        "study_type": "taudem_input_pack",
        "site_id": site_id,
        "generated_at": _utc_now(),
        "available_components": available_components,
        "missing_components": missing_components,
        "artifact_count": len(_PACK_ARTIFACT_SPECS),
        "data_gap_count": len(gaps),
        "blocking_gap_count": sum(1 for gap in gaps if gap.get("blocking_for")),
        "artifacts": _artifact_rows(
            pack_catalog_for_report,
            status_overrides={
                "taudem_pack_manifest": "planned",
                "taudem_pack_report": "planned",
            },
        ),
    }
    artifact_state["taudem_pack_report"] = _write_json(pack_root / "report.json", study_report)

    pack_catalog_for_manifest = _artifact_catalog(
        _PACK_ARTIFACT_SPECS,
        workspace_root,
        artifact_state,
        status_overrides={"taudem_pack_manifest": "created"},
        omit_bytes_for={"taudem_pack_manifest"},
    )
    manifest = {
        "schema_version": "1.0",
        "study_type": "taudem_input_pack",
        "site_id": site_id,
        "generated_at": _utc_now(),
        "builder": {
            "package": "hms-commander",
            "class": "HmsGaugeStudy",
            "method": "build_taudem_input_pack",
            "version": PACKAGE_VERSION,
        },
        "workspace_root": workspace_root,
        "pack_root": f"raw/{pack_name}",
        "artifacts": pack_catalog_for_manifest,
    }
    artifact_state["taudem_pack_manifest"] = _write_json(
        pack_root / "taudem_input_pack_manifest.json",
        manifest,
    )

    final_catalog = _artifact_catalog(_PACK_ARTIFACT_SPECS, workspace_root, artifact_state)
    final_manifest = dict(manifest)
    final_manifest["artifacts"] = _artifact_catalog(
        _PACK_ARTIFACT_SPECS,
        workspace_root,
        artifact_state,
        omit_bytes_for={"taudem_pack_manifest"},
    )
    _write_json(pack_root / "taudem_input_pack_manifest.json", final_manifest)

    return {
        "site_id": site_id,
        "workspace_root": workspace_root,
        "pack_root": pack_root,
        "artifacts": final_catalog,
        "provenance": provenance,
        "manifest": final_manifest,
        "study_report": study_report,
        "data_gap_analysis": data_gap_analysis,
    }

HmsHydrologyContext

Primitive-first gauge, geometry, and hydrology-context helpers used by the study workflow.

hms_commander.HmsHydrologyContext

Primitive-first USGS/NLDI gauge and geometry helpers.

The methods in this class intentionally return plain dictionaries so they can be used in lightweight preprocessing steps without optional GIS dependencies.

Source code in hms_commander/HmsGaugeStudy.py
class HmsHydrologyContext:
    """
    Primitive-first USGS/NLDI gauge and geometry helpers.

    The methods in this class intentionally return plain dictionaries so they
    can be used in lightweight preprocessing steps without optional GIS
    dependencies.
    """

    @staticmethod
    def normalize_site_id(site_id: Any) -> str:
        """Normalize a USGS site id."""
        return _normalize_site_id(site_id)

    @staticmethod
    def get_nldi_feature_id(site_id: Any) -> str:
        """Return the NLDI feature id for a site."""
        return _nldi_feature_id(site_id)

    @staticmethod
    def get_usgs_gauge_metadata(site_id: Any, session: Optional[Any] = None) -> Dict[str, Any]:
        """Fetch combined NLDI and NWIS metadata for a gauge."""
        metadata, _ = _fetch_gauge_metadata_payload(site_id, session=session)
        return metadata

    @staticmethod
    def get_usgs_gauge_point_feature(
        site_id: Optional[Any] = None,
        gauge_metadata: Optional[Mapping[str, Any]] = None,
        session: Optional[Any] = None,
    ) -> Dict[str, Any]:
        """Build a point FeatureCollection for a gauge site."""
        metadata = dict(gauge_metadata or {})
        if not metadata:
            if site_id is None:
                raise ValueError("Either site_id or gauge_metadata is required")
            metadata = HmsHydrologyContext.get_usgs_gauge_metadata(site_id, session=session)

        coordinates = metadata.get("coordinates") or {}
        longitude = coordinates.get("longitude")
        latitude = coordinates.get("latitude")
        if longitude is None or latitude is None:
            raise ValueError("Gauge metadata is missing longitude/latitude values")

        return {
            "type": "FeatureCollection",
            "features": [
                {
                    "type": "Feature",
                    "geometry": {
                        "type": "Point",
                        "coordinates": [float(longitude), float(latitude)],
                    },
                    "properties": {
                        "site_id": metadata.get("site_id") or _normalize_site_id(site_id),
                        "nldi_feature_id": metadata.get("nldi_feature_id") or _nldi_feature_id(site_id),
                        "name": metadata.get("name"),
                    },
                }
            ],
        }

    @staticmethod
    def get_nldi_basin_from_gauge(site_id: Any, session: Optional[Any] = None) -> Dict[str, Any]:
        """Fetch the NLDI basin for a gauge."""
        basin, _ = _fetch_nldi_basin_payload(site_id, session=session)
        return basin

    @staticmethod
    def get_nhdplus_upstream_flowlines_from_gauge(
        site_id: Any,
        distance_km: float = 25.0,
        session: Optional[Any] = None,
    ) -> Dict[str, Any]:
        """Fetch upstream NHDPlus flowlines for a gauge."""
        flowlines, _ = _fetch_upstream_flowlines_payload(
            site_id,
            session=session,
            distance_km=distance_km,
        )
        return flowlines

    @staticmethod
    def get_nhd_huc_context_for_bounds(
        bounds: Sequence[float],
        huc_levels: Optional[Sequence[str]] = None,
        session: Optional[Any] = None,
    ) -> Dict[str, Dict[str, Any]]:
        """Fetch HUC context for a bounding box."""
        context, _ = _fetch_huc_context_payload(bounds, huc_levels=huc_levels, session=session)
        return context

    @staticmethod
    def get_nhd_huc_context_for_geometry(
        feature_or_geometry: Any,
        huc_levels: Optional[Sequence[str]] = None,
        session: Optional[Any] = None,
    ) -> Dict[str, Dict[str, Any]]:
        """Fetch HUC context for a geometry by first deriving its bounds."""
        bounds = HmsHydrologyContext.geometry_bounds(feature_or_geometry)
        return HmsHydrologyContext.get_nhd_huc_context_for_bounds(
            bounds,
            huc_levels=huc_levels,
            session=session,
        )

    @staticmethod
    def get_nhd_huc_boundary_from_gauge(
        site_id: Any,
        huc_level: str = "huc12",
        session: Optional[Any] = None,
    ) -> Dict[str, Any]:
        """Fetch the containing HUC boundary for a gauge location."""
        point_feature = HmsHydrologyContext.get_usgs_gauge_point_feature(site_id=site_id, session=session)
        context = HmsHydrologyContext.get_nhd_huc_context_for_geometry(
            point_feature,
            huc_levels=[huc_level],
            session=session,
        )
        artifact_id, _, _ = _normalize_huc_level(huc_level)
        return context[artifact_id]

    @staticmethod
    def get_nhd_huc8_boundary_from_gauge(site_id: Any, session: Optional[Any] = None) -> Dict[str, Any]:
        """Convenience wrapper for HUC8 context."""
        return HmsHydrologyContext.get_nhd_huc_boundary_from_gauge(
            site_id,
            huc_level="huc8",
            session=session,
        )

    @staticmethod
    def get_nhd_huc12_boundary_from_gauge(site_id: Any, session: Optional[Any] = None) -> Dict[str, Any]:
        """Convenience wrapper for HUC12 context."""
        return HmsHydrologyContext.get_nhd_huc_boundary_from_gauge(
            site_id,
            huc_level="huc12",
            session=session,
        )

    @staticmethod
    def get_gauge_metadata(site_id: Any, session: Optional[Any] = None) -> Dict[str, Any]:
        """Compatibility alias for get_usgs_gauge_metadata."""
        return HmsHydrologyContext.get_usgs_gauge_metadata(site_id, session=session)

    @staticmethod
    def get_gauge_point_feature(
        site_id: Optional[Any] = None,
        gauge_metadata: Optional[Mapping[str, Any]] = None,
        session: Optional[Any] = None,
    ) -> Dict[str, Any]:
        """Compatibility alias for get_usgs_gauge_point_feature."""
        return HmsHydrologyContext.get_usgs_gauge_point_feature(
            site_id=site_id,
            gauge_metadata=gauge_metadata,
            session=session,
        )

    @staticmethod
    def get_huc_context_for_bounds(
        bounds: Sequence[float],
        huc_levels: Optional[Sequence[str]] = None,
        session: Optional[Any] = None,
    ) -> Dict[str, Dict[str, Any]]:
        """Compatibility alias for get_nhd_huc_context_for_bounds."""
        return HmsHydrologyContext.get_nhd_huc_context_for_bounds(
            bounds,
            huc_levels=huc_levels,
            session=session,
        )

    @staticmethod
    def get_huc_context_for_geometry(
        feature_or_geometry: Any,
        huc_levels: Optional[Sequence[str]] = None,
        session: Optional[Any] = None,
    ) -> Dict[str, Dict[str, Any]]:
        """Compatibility alias for get_nhd_huc_context_for_geometry."""
        return HmsHydrologyContext.get_nhd_huc_context_for_geometry(
            feature_or_geometry,
            huc_levels=huc_levels,
            session=session,
        )

    @staticmethod
    def get_upstream_flowlines_from_gauge(
        site_id: Any,
        distance_km: float = 25.0,
        session: Optional[Any] = None,
    ) -> Dict[str, Any]:
        """Compatibility alias for get_nhdplus_upstream_flowlines_from_gauge."""
        return HmsHydrologyContext.get_nhdplus_upstream_flowlines_from_gauge(
            site_id,
            distance_km=distance_km,
            session=session,
        )

    @staticmethod
    def get_watershed_boundary_from_gauge(site_id: Any, session: Optional[Any] = None) -> Dict[str, Any]:
        """Compatibility alias for the NLDI watershed boundary."""
        return HmsHydrologyContext.get_nldi_basin_from_gauge(site_id, session=session)

    @staticmethod
    def geometry_bounds(feature_or_geometry: Any) -> Tuple[float, float, float, float]:
        """Return GeoJSON bounds as (west, south, east, north)."""
        return _geometry_bounds(feature_or_geometry)

    @staticmethod
    def recommend_dem_clip_extent(
        feature_or_geometry: Any,
        buffer_fraction: float = 0.05,
        min_buffer_degrees: float = 0.01,
    ) -> Dict[str, Any]:
        """Recommend a padded DEM clipping extent around a reference geometry."""
        return _recommend_dem_clip_extent(
            feature_or_geometry,
            buffer_fraction=buffer_fraction,
            min_buffer_degrees=min_buffer_degrees,
        )

    @staticmethod
    def build_pour_point_feature(
        coordinates: Optional[Sequence[float]] = None,
        gauge_metadata: Optional[Mapping[str, Any]] = None,
        properties: Optional[Mapping[str, Any]] = None,
    ) -> Dict[str, Any]:
        """Build a TauDEM-style pour point FeatureCollection."""
        metadata = dict(gauge_metadata or {})
        if coordinates is None:
            metadata_coordinates = metadata.get("coordinates") or {}
            longitude = metadata_coordinates.get("longitude")
            latitude = metadata_coordinates.get("latitude")
            if longitude is None or latitude is None:
                raise ValueError("coordinates or gauge_metadata with longitude/latitude is required")
            coordinates = [float(longitude), float(latitude)]
        point_properties = {
            "site_id": metadata.get("site_id"),
            "nldi_feature_id": metadata.get("nldi_feature_id"),
            "name": metadata.get("name"),
        }
        if properties:
            point_properties.update(dict(properties))
        point_properties = {key: value for key, value in point_properties.items() if value is not None}
        return {
            "type": "FeatureCollection",
            "features": [
                {
                    "type": "Feature",
                    "geometry": {"type": "Point", "coordinates": [float(coordinates[0]), float(coordinates[1])]},
                    "properties": point_properties,
                }
            ],
        }

    @staticmethod
    def build_taudem_handoff(
        gauge_metadata: Optional[Mapping[str, Any]] = None,
        basin_boundary: Optional[Mapping[str, Any]] = None,
        huc_context: Optional[Mapping[str, Any]] = None,
        clip_geometry: Optional[Any] = None,
        buffer_fraction: float = 0.05,
        min_buffer_degrees: float = 0.01,
    ) -> Dict[str, Any]:
        """Build an in-memory TauDEM handoff bundle."""
        pour_point = None
        if gauge_metadata:
            try:
                pour_point = HmsHydrologyContext.build_pour_point_feature(gauge_metadata=gauge_metadata)
            except ValueError:
                pour_point = None

        clip_source = clip_geometry or basin_boundary
        recommended_extent = None
        if clip_source is not None:
            recommended_extent = HmsHydrologyContext.recommend_dem_clip_extent(
                clip_source,
                buffer_fraction=buffer_fraction,
                min_buffer_degrees=min_buffer_degrees,
            )

        return {
            "pour_point": pour_point,
            "basin_boundary": basin_boundary,
            "huc_context": dict(huc_context or {}),
            "recommended_dem_clip_extent": recommended_extent,
        }

normalize_site_id(site_id) staticmethod

Normalize a USGS site id.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def normalize_site_id(site_id: Any) -> str:
    """Normalize a USGS site id."""
    return _normalize_site_id(site_id)

get_nldi_feature_id(site_id) staticmethod

Return the NLDI feature id for a site.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_nldi_feature_id(site_id: Any) -> str:
    """Return the NLDI feature id for a site."""
    return _nldi_feature_id(site_id)

get_usgs_gauge_metadata(site_id, session=None) staticmethod

Fetch combined NLDI and NWIS metadata for a gauge.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_usgs_gauge_metadata(site_id: Any, session: Optional[Any] = None) -> Dict[str, Any]:
    """Fetch combined NLDI and NWIS metadata for a gauge."""
    metadata, _ = _fetch_gauge_metadata_payload(site_id, session=session)
    return metadata

get_usgs_gauge_point_feature(site_id=None, gauge_metadata=None, session=None) staticmethod

Build a point FeatureCollection for a gauge site.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_usgs_gauge_point_feature(
    site_id: Optional[Any] = None,
    gauge_metadata: Optional[Mapping[str, Any]] = None,
    session: Optional[Any] = None,
) -> Dict[str, Any]:
    """Build a point FeatureCollection for a gauge site."""
    metadata = dict(gauge_metadata or {})
    if not metadata:
        if site_id is None:
            raise ValueError("Either site_id or gauge_metadata is required")
        metadata = HmsHydrologyContext.get_usgs_gauge_metadata(site_id, session=session)

    coordinates = metadata.get("coordinates") or {}
    longitude = coordinates.get("longitude")
    latitude = coordinates.get("latitude")
    if longitude is None or latitude is None:
        raise ValueError("Gauge metadata is missing longitude/latitude values")

    return {
        "type": "FeatureCollection",
        "features": [
            {
                "type": "Feature",
                "geometry": {
                    "type": "Point",
                    "coordinates": [float(longitude), float(latitude)],
                },
                "properties": {
                    "site_id": metadata.get("site_id") or _normalize_site_id(site_id),
                    "nldi_feature_id": metadata.get("nldi_feature_id") or _nldi_feature_id(site_id),
                    "name": metadata.get("name"),
                },
            }
        ],
    }

get_nldi_basin_from_gauge(site_id, session=None) staticmethod

Fetch the NLDI basin for a gauge.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_nldi_basin_from_gauge(site_id: Any, session: Optional[Any] = None) -> Dict[str, Any]:
    """Fetch the NLDI basin for a gauge."""
    basin, _ = _fetch_nldi_basin_payload(site_id, session=session)
    return basin

get_nhdplus_upstream_flowlines_from_gauge(site_id, distance_km=25.0, session=None) staticmethod

Fetch upstream NHDPlus flowlines for a gauge.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_nhdplus_upstream_flowlines_from_gauge(
    site_id: Any,
    distance_km: float = 25.0,
    session: Optional[Any] = None,
) -> Dict[str, Any]:
    """Fetch upstream NHDPlus flowlines for a gauge."""
    flowlines, _ = _fetch_upstream_flowlines_payload(
        site_id,
        session=session,
        distance_km=distance_km,
    )
    return flowlines

get_nhd_huc_context_for_bounds(bounds, huc_levels=None, session=None) staticmethod

Fetch HUC context for a bounding box.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_nhd_huc_context_for_bounds(
    bounds: Sequence[float],
    huc_levels: Optional[Sequence[str]] = None,
    session: Optional[Any] = None,
) -> Dict[str, Dict[str, Any]]:
    """Fetch HUC context for a bounding box."""
    context, _ = _fetch_huc_context_payload(bounds, huc_levels=huc_levels, session=session)
    return context

get_nhd_huc_context_for_geometry(feature_or_geometry, huc_levels=None, session=None) staticmethod

Fetch HUC context for a geometry by first deriving its bounds.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_nhd_huc_context_for_geometry(
    feature_or_geometry: Any,
    huc_levels: Optional[Sequence[str]] = None,
    session: Optional[Any] = None,
) -> Dict[str, Dict[str, Any]]:
    """Fetch HUC context for a geometry by first deriving its bounds."""
    bounds = HmsHydrologyContext.geometry_bounds(feature_or_geometry)
    return HmsHydrologyContext.get_nhd_huc_context_for_bounds(
        bounds,
        huc_levels=huc_levels,
        session=session,
    )

get_nhd_huc_boundary_from_gauge(site_id, huc_level='huc12', session=None) staticmethod

Fetch the containing HUC boundary for a gauge location.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_nhd_huc_boundary_from_gauge(
    site_id: Any,
    huc_level: str = "huc12",
    session: Optional[Any] = None,
) -> Dict[str, Any]:
    """Fetch the containing HUC boundary for a gauge location."""
    point_feature = HmsHydrologyContext.get_usgs_gauge_point_feature(site_id=site_id, session=session)
    context = HmsHydrologyContext.get_nhd_huc_context_for_geometry(
        point_feature,
        huc_levels=[huc_level],
        session=session,
    )
    artifact_id, _, _ = _normalize_huc_level(huc_level)
    return context[artifact_id]

get_nhd_huc8_boundary_from_gauge(site_id, session=None) staticmethod

Convenience wrapper for HUC8 context.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_nhd_huc8_boundary_from_gauge(site_id: Any, session: Optional[Any] = None) -> Dict[str, Any]:
    """Convenience wrapper for HUC8 context."""
    return HmsHydrologyContext.get_nhd_huc_boundary_from_gauge(
        site_id,
        huc_level="huc8",
        session=session,
    )

get_nhd_huc12_boundary_from_gauge(site_id, session=None) staticmethod

Convenience wrapper for HUC12 context.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_nhd_huc12_boundary_from_gauge(site_id: Any, session: Optional[Any] = None) -> Dict[str, Any]:
    """Convenience wrapper for HUC12 context."""
    return HmsHydrologyContext.get_nhd_huc_boundary_from_gauge(
        site_id,
        huc_level="huc12",
        session=session,
    )

get_gauge_metadata(site_id, session=None) staticmethod

Compatibility alias for get_usgs_gauge_metadata.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_gauge_metadata(site_id: Any, session: Optional[Any] = None) -> Dict[str, Any]:
    """Compatibility alias for get_usgs_gauge_metadata."""
    return HmsHydrologyContext.get_usgs_gauge_metadata(site_id, session=session)

get_gauge_point_feature(site_id=None, gauge_metadata=None, session=None) staticmethod

Compatibility alias for get_usgs_gauge_point_feature.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_gauge_point_feature(
    site_id: Optional[Any] = None,
    gauge_metadata: Optional[Mapping[str, Any]] = None,
    session: Optional[Any] = None,
) -> Dict[str, Any]:
    """Compatibility alias for get_usgs_gauge_point_feature."""
    return HmsHydrologyContext.get_usgs_gauge_point_feature(
        site_id=site_id,
        gauge_metadata=gauge_metadata,
        session=session,
    )

get_huc_context_for_bounds(bounds, huc_levels=None, session=None) staticmethod

Compatibility alias for get_nhd_huc_context_for_bounds.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_huc_context_for_bounds(
    bounds: Sequence[float],
    huc_levels: Optional[Sequence[str]] = None,
    session: Optional[Any] = None,
) -> Dict[str, Dict[str, Any]]:
    """Compatibility alias for get_nhd_huc_context_for_bounds."""
    return HmsHydrologyContext.get_nhd_huc_context_for_bounds(
        bounds,
        huc_levels=huc_levels,
        session=session,
    )

get_huc_context_for_geometry(feature_or_geometry, huc_levels=None, session=None) staticmethod

Compatibility alias for get_nhd_huc_context_for_geometry.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_huc_context_for_geometry(
    feature_or_geometry: Any,
    huc_levels: Optional[Sequence[str]] = None,
    session: Optional[Any] = None,
) -> Dict[str, Dict[str, Any]]:
    """Compatibility alias for get_nhd_huc_context_for_geometry."""
    return HmsHydrologyContext.get_nhd_huc_context_for_geometry(
        feature_or_geometry,
        huc_levels=huc_levels,
        session=session,
    )

get_upstream_flowlines_from_gauge(site_id, distance_km=25.0, session=None) staticmethod

Compatibility alias for get_nhdplus_upstream_flowlines_from_gauge.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_upstream_flowlines_from_gauge(
    site_id: Any,
    distance_km: float = 25.0,
    session: Optional[Any] = None,
) -> Dict[str, Any]:
    """Compatibility alias for get_nhdplus_upstream_flowlines_from_gauge."""
    return HmsHydrologyContext.get_nhdplus_upstream_flowlines_from_gauge(
        site_id,
        distance_km=distance_km,
        session=session,
    )

get_watershed_boundary_from_gauge(site_id, session=None) staticmethod

Compatibility alias for the NLDI watershed boundary.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def get_watershed_boundary_from_gauge(site_id: Any, session: Optional[Any] = None) -> Dict[str, Any]:
    """Compatibility alias for the NLDI watershed boundary."""
    return HmsHydrologyContext.get_nldi_basin_from_gauge(site_id, session=session)

geometry_bounds(feature_or_geometry) staticmethod

Return GeoJSON bounds as (west, south, east, north).

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def geometry_bounds(feature_or_geometry: Any) -> Tuple[float, float, float, float]:
    """Return GeoJSON bounds as (west, south, east, north)."""
    return _geometry_bounds(feature_or_geometry)

recommend_dem_clip_extent(feature_or_geometry, buffer_fraction=0.05, min_buffer_degrees=0.01) staticmethod

Recommend a padded DEM clipping extent around a reference geometry.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def recommend_dem_clip_extent(
    feature_or_geometry: Any,
    buffer_fraction: float = 0.05,
    min_buffer_degrees: float = 0.01,
) -> Dict[str, Any]:
    """Recommend a padded DEM clipping extent around a reference geometry."""
    return _recommend_dem_clip_extent(
        feature_or_geometry,
        buffer_fraction=buffer_fraction,
        min_buffer_degrees=min_buffer_degrees,
    )

build_pour_point_feature(coordinates=None, gauge_metadata=None, properties=None) staticmethod

Build a TauDEM-style pour point FeatureCollection.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def build_pour_point_feature(
    coordinates: Optional[Sequence[float]] = None,
    gauge_metadata: Optional[Mapping[str, Any]] = None,
    properties: Optional[Mapping[str, Any]] = None,
) -> Dict[str, Any]:
    """Build a TauDEM-style pour point FeatureCollection."""
    metadata = dict(gauge_metadata or {})
    if coordinates is None:
        metadata_coordinates = metadata.get("coordinates") or {}
        longitude = metadata_coordinates.get("longitude")
        latitude = metadata_coordinates.get("latitude")
        if longitude is None or latitude is None:
            raise ValueError("coordinates or gauge_metadata with longitude/latitude is required")
        coordinates = [float(longitude), float(latitude)]
    point_properties = {
        "site_id": metadata.get("site_id"),
        "nldi_feature_id": metadata.get("nldi_feature_id"),
        "name": metadata.get("name"),
    }
    if properties:
        point_properties.update(dict(properties))
    point_properties = {key: value for key, value in point_properties.items() if value is not None}
    return {
        "type": "FeatureCollection",
        "features": [
            {
                "type": "Feature",
                "geometry": {"type": "Point", "coordinates": [float(coordinates[0]), float(coordinates[1])]},
                "properties": point_properties,
            }
        ],
    }

build_taudem_handoff(gauge_metadata=None, basin_boundary=None, huc_context=None, clip_geometry=None, buffer_fraction=0.05, min_buffer_degrees=0.01) staticmethod

Build an in-memory TauDEM handoff bundle.

Source code in hms_commander/HmsGaugeStudy.py
@staticmethod
def build_taudem_handoff(
    gauge_metadata: Optional[Mapping[str, Any]] = None,
    basin_boundary: Optional[Mapping[str, Any]] = None,
    huc_context: Optional[Mapping[str, Any]] = None,
    clip_geometry: Optional[Any] = None,
    buffer_fraction: float = 0.05,
    min_buffer_degrees: float = 0.01,
) -> Dict[str, Any]:
    """Build an in-memory TauDEM handoff bundle."""
    pour_point = None
    if gauge_metadata:
        try:
            pour_point = HmsHydrologyContext.build_pour_point_feature(gauge_metadata=gauge_metadata)
        except ValueError:
            pour_point = None

    clip_source = clip_geometry or basin_boundary
    recommended_extent = None
    if clip_source is not None:
        recommended_extent = HmsHydrologyContext.recommend_dem_clip_extent(
            clip_source,
            buffer_fraction=buffer_fraction,
            min_buffer_degrees=min_buffer_degrees,
        )

    return {
        "pour_point": pour_point,
        "basin_boundary": basin_boundary,
        "huc_context": dict(huc_context or {}),
        "recommended_dem_clip_extent": recommended_extent,
    }
CLB Engineering Corporation  ·  LLM Forward Engineering
HMS Commander is a free and open-source project maintained by CLB Engineering Corporation. For agencies and firms seeking to modernize H&H workflows with LLM Forward approaches, contact CLB to partner with the engineers who wrote the automation.