Skip to content

STOFS-3D Coastal Boundary Integration

Inspect an archived NOAA STOFS-3D-Atlantic station file, extract two coastal water-level time series, and distinguish unit conversion from vertical datum transformation.

This notebook executes extraction, metadata inspection, arithmetic checks and plotting on the real preserved sample. It does not edit a HEC-RAS project or execute a hydraulic simulation. The experimental stage-authoring API is shown as an unexecuted recipe requiring independently verified model units, datum and timing.

Current product facts (checked September 26, 2026): STOFS-3D-Atlantic runs daily at 12 UTC, with 24 hours of nowcast and up to 96 hours of forecast. Station output is six-minute data. See NOAA's product description.

The NOAA v3.1 notice states that station NetCDF changed to LMSL at the August 17, 2026 12 UTC cycle; grids remain xGEOID20b and station SHEF remains MLLW. Archived data can differ. The sample below explicitly identifies NAVD88; never transfer that label automatically to current forecasts.

Install optional dependencies in a terminal using the repository environment, for example uv pip install -e ".[full]".

Python
# =============================================================================
# DEVELOPMENT MODE TOGGLE
# =============================================================================
# Set USE_LOCAL_SOURCE based on your setup:
#   True  = Use local source code (for developers editing ras-commander)
#   False = Use pip-installed package (for users)
# =============================================================================

USE_LOCAL_SOURCE = True  # <-- TOGGLE THIS

# -----------------------------------------------------------------------------
if USE_LOCAL_SOURCE:
    import sys
    from pathlib import Path
    local_path = str(Path.cwd().parent)  # Parent of examples/ = repo root
    if local_path not in sys.path:
        sys.path.insert(0, local_path)  # Insert at position 0 = highest priority
    print(f"LOCAL SOURCE MODE: Loading from {local_path}/ras_commander")
else:
    print("PIP PACKAGE MODE: Loading installed ras-commander")
Text Only
LOCAL SOURCE MODE: Loading from C:\Users\billk_clb\.codex\workspaces\ras-docs-priority-20260926/ras_commander
Python
from pathlib import Path
import hashlib
import inspect
import numpy as np
import pandas as pd
import xarray as xr
import matplotlib.pyplot as plt
from ras_commander.boundaries import CoastalBoundary

repo_root = Path.cwd().parent if Path.cwd().name == "examples" else Path.cwd()
sample = repo_root / "examples/data/stofs3d_gulf/stofs_3d_atl.t12z.points.cwl.temp.salt.vel.nc"
if not sample.is_file():
    raise FileNotFoundError(f"Preserved NOAA sample missing: {sample}")
source_hash = hashlib.sha256(sample.read_bytes()).hexdigest()
print(f"Source: {sample}")
print(f"Bytes: {sample.stat().st_size:,}")
print(f"SHA-256: {source_hash}")
Text Only
Source: C:\Users\billk_clb\.codex\workspaces\ras-docs-priority-20260926\examples\data\stofs3d_gulf\stofs_3d_atl.t12z.points.cwl.temp.salt.vel.nc
Bytes: 5,509,661
SHA-256: 54d41d56d462ee9b2b7279a6399cf4c8117d2f121fe8fa174c04a45ed5864b82

Inspect the source before assigning a datum

Read the actual variable attributes and time extent. The sample's filename only gives the cycle hour; it does not establish its date or vertical datum. Global history also identifies the archive's original conversion, but the extractor relies on datum-bearing attributes rather than guessing from processing-history text.

Python
with xr.open_dataset(sample) as ds:
    print("Water-level attributes:")
    print(dict(ds["zeta"].attrs))
    print("Processing history:")
    print(ds.attrs.get("history", "Not recorded"))
    print(f"Time extent: {ds.time.values[0]} to {ds.time.values[-1]} UTC")
    print(f"Dimensions: {dict(ds.sizes)}")

print("\nCurrent product metadata (not a relabeling of this archive):")
for key in ("forecast_horizon", "nowcast_horizon", "update_frequency", "current_datums", "datum_effective_from"):
    print(f"{key}: {CoastalBoundary.get_info()[key]}")
Text Only
Water-level attributes:
{'long_name': 'water surface elevation above navd88', 'standard_name': 'sea_surface_height_above_navd88', 'units': 'm'}
Processing history:
Tue Apr 21 18:06:46 2026: ncap2 -O -F -S /lfs/h1/ops/prod/packages/stofs.v2.1.18/fix/stofs_3d_atl/stofs_3d_atl_sta_cwl_xgeoid_to_navd.nco staout_timeseries_2026-04-20-12.nc staout_timeseries_2026-04-20-12_navd.nc
Time extent: 2026-04-20T12:06:00.000000000 to 2026-04-25T12:00:00.000000000 UTC
Dimensions: {'time': 1200, 'station': 108}

Current product metadata (not a relabeling of this archive):
forecast_horizon: 96 hours
nowcast_horizon: 24 hours
update_frequency: Daily at 12 UTC
current_datums: {'station_netcdf': 'LMSL', 'grids': 'xGEOID20b', 'station_shef': 'MLLW'}
datum_effective_from: 2026-08-17T12:00:00Z (STOFS v3.1)

Extract Galveston Bay and Charleston station series

The API selects the nearest station/node within its distance limit, which is not a shoreline or hydrodynamic connectivity test. Review the returned nearest coordinates for your application. Both unit columns remain available; units records the preferred display units. No datum transformation occurs.

Python
locations = {"Galveston Bay": (29.35, -94.77), "Charleston Harbor": (32.78, -79.93)}
series = {}
for name, (lat, lon) in locations.items():
    frame = CoastalBoundary.extract_wse_at_point(sample, lat=lat, lon=lon, units="feet")
    series[name] = frame
    print(f"\n{name}: {len(frame)} timestamps")
    print(f"Nearest coordinates: {frame.attrs['nearest_lat']:.5f}, {frame.attrs['nearest_lon']:.5f}")
    print(f"Source datum: {frame.attrs['source_datum']}")
    print(f"Datum evidence: {frame.attrs['datum_evidence']}")
    print(frame.head(5).to_string(index=False))

summary = pd.DataFrame([
    {"location": name, "datum": frame.attrs["source_datum"],
     "min_ft": frame.wse_ft.min(), "max_ft": frame.wse_ft.max(),
     "mean_ft": frame.wse_ft.mean()}
    for name, frame in series.items()
])
summary
Text Only
2026-09-26 09:15:08 - ras_commander.boundaries.coastal_boundary - INFO - Extracting WSE at (29.3500, -94.7700) from 1 file(s)


2026-09-26 09:15:08 - ras_commander.boundaries.coastal_boundary - INFO - Using swapped x/y orientation (NOAA data quirk)


2026-09-26 09:15:08 - ras_commander.boundaries.coastal_boundary - INFO - Nearest grid point: (29.3575, -94.7247), distance: 0.0459 degrees


2026-09-26 09:15:08 - ras_commander.boundaries.coastal_boundary - INFO - Extracted 1200 valid WSE values. Range: -0.19 to 2.19 ft (NAVD88)


2026-09-26 09:15:08 - ras_commander.boundaries.coastal_boundary - INFO - Extracting WSE at (32.7800, -79.9300) from 1 file(s)


2026-09-26 09:15:08 - ras_commander.boundaries.coastal_boundary - INFO - Using swapped x/y orientation (NOAA data quirk)


2026-09-26 09:15:08 - ras_commander.boundaries.coastal_boundary - INFO - Nearest grid point: (32.7808, -79.9236), distance: 0.0064 degrees


2026-09-26 09:15:08 - ras_commander.boundaries.coastal_boundary - INFO - Extracted 1200 valid WSE values. Range: -1.71 to 3.57 ft (NAVD88)



Galveston Bay: 1200 timestamps
Nearest coordinates: 29.35747, -94.72474
Source datum: NAVD88
Datum evidence: {'variable.long_name': 'water surface elevation above navd88', 'variable.standard_name': 'sea_surface_height_above_navd88'}
           datetime    wse_m   wse_ft
2026-04-20 12:06:00 0.588357 1.930306
2026-04-20 12:12:00 0.594263 1.949682
2026-04-20 12:18:00 0.599208 1.965906
2026-04-20 12:24:00 0.603136 1.978793
2026-04-20 12:30:00 0.606287 1.989131

Charleston Harbor: 1200 timestamps
Nearest coordinates: 32.78084, -79.92362
Source datum: NAVD88
Datum evidence: {'variable.long_name': 'water surface elevation above navd88', 'variable.standard_name': 'sea_surface_height_above_navd88'}
           datetime     wse_m    wse_ft
2026-04-20 12:06:00 -0.129853 -0.426028
2026-04-20 12:12:00 -0.100898 -0.331029
2026-04-20 12:18:00 -0.072634 -0.238301
2026-04-20 12:24:00 -0.045689 -0.149898
2026-04-20 12:30:00 -0.020513 -0.067300
location datum min_ft max_ft mean_ft
0 Galveston Bay NAVD88 -0.194913 2.193223 1.039534
1 Charleston Harbor NAVD88 -1.712146 3.572358 0.157816
Python
fig, axes = plt.subplots(2, 1, figsize=(11, 6), sharex=True, layout="constrained")
for ax, (name, frame) in zip(axes, series.items()):
    ax.plot(frame.datetime, frame.wse_ft, linewidth=1.3)
    ax.set_title(f"{name}: archived NOAA station water level")
    ax.set_ylabel(f"WSE (ft {frame.attrs['source_datum']})")
    ax.grid(alpha=0.25)
axes[-1].set_xlabel("Source timestamp (UTC)")
fig.suptitle("April 2026 archive — no HEC-RAS simulation")
plt.show()

png

Verify units and the offset convention

One international foot is exactly 0.3048 meters. datum_adjustment_ft is always an additive offset in feet, even when the output unit is meters. The +1 ft arithmetic below illustrates that API contract only; it is not a measured datum correction for either site. Neither this arithmetic nor the plot validates a forecast model.

Python
wse = series["Galveston Bay"]
np.testing.assert_allclose(wse.wse_ft * 0.3048, wse.wse_m)
demonstration_offset_ft = 1.0
adjusted_ft = wse.wse_ft + demonstration_offset_ft
adjusted_m = wse.wse_m + demonstration_offset_ft / CoastalBoundary.METERS_TO_FEET
np.testing.assert_allclose(adjusted_ft * 0.3048, adjusted_m)
print("All archived values agree between feet and meters.")
print("Illustrative +1 ft offset adds +0.3048 m; no datum transformation was established.")
print(pd.DataFrame({"source_m": wse.wse_m, "source_ft": wse.wse_ft,
                    "illustrative_offset_m": adjusted_m,
                    "illustrative_offset_ft": adjusted_ft}).head().to_string(index=False))
try:
    CoastalBoundary.extract_wse_at_point(sample, 29.35, -94.77, units="ft")
except ValueError as exc:
    print(f"Invalid-unit rejection: {exc}")
Text Only
All archived values agree between feet and meters.
Illustrative +1 ft offset adds +0.3048 m; no datum transformation was established.
 source_m  source_ft  illustrative_offset_m  illustrative_offset_ft
 0.588357   1.930306               0.893157                2.930306
 0.594263   1.949682               0.899063                2.949682
 0.599208   1.965906               0.904008                2.965906
 0.603136   1.978793               0.907936                2.978793
 0.606287   1.989131               0.911087                2.989131
Invalid-unit rejection: units must be 'feet' or 'meters'

Experimental stage authoring: recipe for a verified model copy

The following recipe is not executed here. generate_stage_bc() writes an existing inline stage table. It does not know your model's datum or unit system, align its simulation dates, perform geodetic transformations, or run HEC-RAS. Configure those with RasUnsteady/RasPlan and establish model suitability separately.

Python
# working_unsteady must be an isolated copy of your existing .u## file.
# verified_model_datum must come from the model's actual reference documentation.
# Here same-datum writing is allowed only after independently checking equality.
assert verified_model_datum == wse.attrs["source_datum"]
CoastalBoundary.generate_stage_bc(
    wse_timeseries=wse,
    unsteady_file=working_unsteady,
    bc_location=verified_boundary_name,
    units=verified_model_units,  # exactly "feet" or "meters"
    target_datum=verified_model_datum,
    datum_adjustment_ft=0.0,
)

For different known datums, supply a locally established additive correction and its evidence via datum_adjustment_source=. Even a verified zero correction needs provenance. The library checks that provenance is supplied; it cannot validate the correction. For missing source metadata, the extractor reports unknown; use source_datum= only after independently verifying the file/product/version. Legacy authoring calls without target_datum emit an unverified-target warning.

The writer rejects unsupported units, irregular timestamps, missing/nonfinite elevations, ambiguous boundary names, DSS-active targets and targets without an existing stage table. It updates interval/value serialization but does not set hydrograph start-date or plan time-window settings. These authoring contracts are covered by focused tests, not by a solver run in this notebook.

Python
print("Experimental authoring signature:")
print(inspect.signature(CoastalBoundary.generate_stage_bc))
print("HEC-RAS files modified: 0")
print("HEC-RAS computations performed: 0")
assert hashlib.sha256(sample.read_bytes()).hexdigest() == source_hash
print("Archived NOAA source hash unchanged.")
Text Only
Experimental authoring signature:
(wse_timeseries, unsteady_file: Union[str, pathlib.Path], bc_location: str, units: str = 'feet', datum_adjustment_ft: float = 0.0, *, source_datum: Optional[str] = None, target_datum: Optional[str] = None, datum_adjustment_source: Optional[str] = None) -> None
HEC-RAS files modified: 0
HEC-RAS computations performed: 0
Archived NOAA source hash unchanged.

Obtaining a current forecast

The saved execution above is intentionally reproducible against the archive. Run this separate recipe when current network data are needed; retain date-specific directories and inspect that file's metadata again.

Python
from datetime import datetime, timezone
run_folder = repo_root / "working" / "stofs" / datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
files = CoastalBoundary.download_stofs3d(run_folder, file_type="points")
current_wse = CoastalBoundary.extract_wse_at_point(files[0], 29.35, -94.77)
print(current_wse.attrs)

The downloader probes recent daily 12 UTC products. NOMADS retains recent products for a limited time; availability and latency vary. fields may download a peak-only maxele product, which cannot provide a stage hydrograph. Consult NOAA archives for older cycles.

For the broader forecast sequence, see notebook 915. For unit/datum and file-authoring contracts, see the coastal boundary guide. When publishing work that uses this library, consider the RAS Commander citation guidance.