Source code for axqua.hydraulics

"""Readers for hydraulic inputs: inflow, stage-discharge, and measurements.

Handles the Bavarian LfU (gkd.bayern.de) CSV export format (UTF-8 BOM,
``;``-separated, comma decimals, ~10 metadata lines, then a ``Datum;...`` header)
as well as plain 2-column CSVs, so the workflow ingests both the raw gauge files
in ``stage-discharge/`` and tidy user-prepared tables.
"""

from __future__ import annotations

import logging
from dataclasses import dataclass
from pathlib import Path

import numpy as np
import pandas as pd

log = logging.getLogger("axqua")


def _is_lfu(path: Path) -> bool:
    with open(path, encoding="utf-8-sig", errors="ignore") as fh:
        head = fh.read(400)
    return "gkd.bayern" in head or "Messstellen-Nr" in head or "Datum;" in head


def _has_metadata(path: Path) -> bool:
    """True for an LfU export with its metadata lines above the header, which no plain table reader can parse. Told by the metadata itself: a German table whose header merely holds ``Datum`` is no export."""
    with open(path, encoding="utf-8-sig", errors="ignore") as fh:
        first = fh.readline()
        head = first + fh.read(400)
    return (not first.startswith("Datum;")
            and ("gkd.bayern" in head or "Messstellen-Nr" in head))


def _read_lfu(path: Path) -> pd.DataFrame:
    """Read an LfU time series -> DataFrame[datetime, value]."""
    with open(path, encoding="utf-8-sig", errors="ignore") as fh:
        lines = fh.readlines()
    header_idx = next(i for i, ln in enumerate(lines) if ln.startswith("Datum;"))
    df = pd.read_csv(
        path, sep=";", decimal=",", skiprows=header_idx,
        encoding="utf-8-sig", engine="python",
    )
    df = df.iloc[:, :2]
    df.columns = ["datetime", "value"]
    df["datetime"] = pd.to_datetime(df["datetime"], errors="coerce")
    df["value"] = pd.to_numeric(df["value"], errors="coerce")
    return df.dropna()


def _read_generic(path: Path) -> pd.DataFrame:
    df = pd.read_csv(path)
    if df.shape[1] < 2:
        df = pd.read_csv(path, sep=";", decimal=",")
    return df


[docs] @dataclass class Inflow: times_s: np.ndarray | None # seconds from start (unsteady), else None discharge: np.ndarray # m3/s series, or single-element array steady_value: float # representative steady discharge (mean) # per liquid boundary index, where the table has columns per inflow line lines: "dict[int, np.ndarray] | None" = None # m3/s temperatures: "dict[int, np.ndarray] | None" = None # deg C origin: "pd.Timestamp | None" = None # the first time stamp, in the clock of the table @property def varies(self) -> bool: """A hydrograph: a time series whose total or the discharge of one of its lines changes. The build (``pipeline._has_hydrograph``) and the unsteady run (``unsteady.load_hydrograph``) ask the same.""" if self.times_s is None: return False return any(np.asarray(q, dtype=float).size > 1 and float(np.ptp(q)) > 1e-6 for q in [self.discharge, *(self.lines or {}).values()])
[docs] def read_inflow(path: Path, steady: bool = True) -> Inflow: """Read an inflow discharge series (LfU or generic) into an :class:`Inflow`.""" path = Path(path) if _is_lfu(path): df = _read_lfu(path) q = df["value"].to_numpy(dtype=float) t = (df["datetime"] - df["datetime"].iloc[0]).dt.total_seconds().to_numpy() else: df = _read_generic(path) cols = {c.lower(): c for c in df.columns} qcol = next((cols[c] for c in cols if "q" in c or "disch" in c or "abfluss" in c), df.columns[-1]) # the time axis: use an explicit time column (numeric seconds or datetime # strings) when present - the row index is only the last resort (it would # silently compress e.g. an hourly hydrograph to 1-second spacing) tcol = next((cols[c] for c in cols if cols[c] != qcol and ("time" in c or "zeit" in c or "date" in c or "datum" in c or c.strip() == "t")), None) q_all = pd.to_numeric(df[qcol], errors="coerce") keys = {c: _line_key(c) for c in df.columns} per_line = [c for c, key in keys.items() if key and key[0] == "q" and key[1]] if per_line and ("q", "") not in keys.values(): # a column per inflow line: the discharge of the reach is their sum q_all = df[per_line].apply(pd.to_numeric, errors="coerce").sum( axis=1, min_count=len(per_line)) t_all = None if tcol is not None: t_all = pd.to_numeric(df[tcol], errors="coerce") if t_all.isna().any(): # datetime strings, not seconds stamps = pd.to_datetime(df[tcol], errors="coerce") valid = stamps.dropna() t_all = ((stamps - valid.iloc[0]).dt.total_seconds() if not valid.empty else None) if t_all is not None: keep = q_all.notna() & t_all.notna() q = q_all[keep].to_numpy(dtype=float) t = t_all[keep].to_numpy(dtype=float) if len(q) > 1 else None else: q = q_all.dropna().to_numpy(dtype=float) t = np.arange(len(q), dtype=float) if len(q) > 1 else None steady_value = float(np.mean(q)) return Inflow(times_s=(None if steady else t), discharge=q, steady_value=steady_value)
def _line_key(column) -> tuple[str, str] | None: """``("q" | "t", line)`` of a column of a hydrograph table, with an empty line for a column of the whole reach; None for any other column. ``Q``, ``Discharge [m3/s]`` and ``T`` are of the whole reach, ``Q Hauterive``, ``Q_Hauterive (m3/s)`` and ``T(2)`` of one line, by its name or its number. """ import re text = str(column).strip() index = re.search(r"\((\d+)\)", text) text = re.sub(r"\[.*?\]", "", text) text = re.sub(r"\(.*?\)", "", text) + (f" {index.group(1)}" if index else "") words = re.split(r"[\s_]+", text.strip().lower()) kind = {"q": "q", "discharge": "q", "abfluss": "q", "flow": "q", "t": "t", "temp": "t", "temperature": "t", "watertemperature": "t", "tw": "t"}.get(words[0] if words else "") if kind is None: return None rest = [w for w in words[1:] if w not in ("m3/s", "m3s", "degc", "c", "water")] return kind, " ".join(rest)
[docs] def read_line_series(path: Path, liquids, *, temperatures: bool = False, utc_offset: float = 0.0) -> Inflow | None: """The hydrograph table with columns per inflow line, or None where it has none. A line is named by the column ``Name`` of the liquid-boundary layer or by its number in TELEMAC (``liquid-boundaries.json``). Either every inflow line has a discharge column or the table holds the discharge of the reach; with *temperatures*, every inflow line needs a temperature, its own or one for all lines. The one column of a kind that names no inflow line (``Q_Oberaudorf``) is of the reach where there is one inflow line or the lines have no names; elsewhere it may be a misspelled name and is an error. Missing values are interpolated in time. *utc_offset* is the offset of the table's clock from UTC in hours (``heat.inflow_utc_offset``), the clock of ``origin``; it moves stamps with a zone of their own into that clock (:func:`axqua.heat.forcing.parse_times`). None, and :func:`read_inflow` reads the table, where no inflow line has a discharge column of its own and *temperatures* is False: a plain hydrograph (``Q``, or one column such as ``Q_Oberaudorf``), an LfU gauge export or a table that the reader of this function cannot parse. Two or more discharge columns of lines that match no line are an error, not a sum. """ from axqua.heat.forcing import parse_times, read_table, time_column, warn_unread path = Path(path) if _has_metadata(path): # an LfU export holds the discharge of one gauge, and read_inflow reads it if temperatures: raise ValueError(f"{path.name} is an LfU gauge export with the discharge only; " "the water temperature needs a table with a time, Q and T") return None try: frame = read_table(path) except (pd.errors.ParserError, UnicodeDecodeError) as exc: if not temperatures: return None # read_inflow reads it, or says why not raise ValueError(f"{path.name}: {exc}") from exc inflows = [lb for lb in liquids if lb.kind == "inflow"] columns: dict[tuple[str, str], str] = {} for column in frame.columns: key = _line_key(column) if key is not None: columns.setdefault(key, column) def series(kind: str, lb): names = ([lb.name.strip().lower().replace("_", " ")] if lb.name else []) + [str(lb.index)] for name in names: column = columns.get((kind, name)) if column is not None: return column return None def unmatched(kind: str) -> list[str]: """The columns of a kind that name a line, and no inflow line.""" own = {series(kind, lb) for lb in inflows} return [column for key, column in columns.items() if key[0] == kind and key[1] and column not in own] if (not temperatures and not any(series("q", lb) for lb in inflows) and len(unmatched("q")) < 2): # a plain hydrograph (Q, or one column such as Q_Oberaudorf): read_inflow's table; # two or more columns of lines that match none are an error below, not a sum return None tcol = time_column(frame) origin = None if tcol is None: tcol = next((c for c in frame.columns if str(c).strip().lower() in ("t", "t_s", "seconds") and ("t", "") != _line_key(c)), None) if tcol is None and not temperatures and ("t", "") in columns: tcol = columns.pop(("t", "")) # a bare "t" of a plain table is the time if tcol is None: raise ValueError(f"{path.name}: no time column") numeric = pd.to_numeric(frame[tcol], errors="coerce") if numeric.notna().all() and float(numeric.max()) < 1.0e8: seconds = numeric.to_numpy(dtype=float) else: stamps = parse_times(frame[tcol], utc_offset) keep = np.asarray(~stamps.isna()) warn_unread(path, tcol, keep) frame, stamps = frame[keep], stamps[keep] origin = stamps[0] seconds = (stamps - origin).total_seconds().to_numpy(dtype=float) if seconds.size < 2 or np.any(np.diff(seconds) <= 0): raise ValueError(f"{path.name}: the times do not increase") def values(column, what): data = pd.to_numeric(frame[column], errors="coerce").to_numpy(dtype=float) ok = np.isfinite(data) if not ok.any(): raise ValueError(f"{path.name}: the column {column!r} holds no number") if not ok.all(): marks = np.concatenate([[seconds[0]], seconds[ok], [seconds[-1]]]) log.warning("%s: %d of %d values of %s are missing and interpolated (longest " "gap %.1f h)", path.name, int((~ok).sum()), ok.size, what, float(np.diff(marks).max()) / 3600.0) data = np.interp(seconds, seconds[ok], data[ok]) return data def label(lb): return lb.name or f"inflow {lb.index}" # the one column of a kind that names no inflow line (Q_Oberaudorf) is of the reach, where # no misspelled name can be the cause: one inflow line, or lines without names if len(inflows) == 1 or not any(lb.name for lb in inflows): for kind in ("q", "t") if temperatures else ("q",): named = [key for key in columns if key[0] == kind and key[1]] if ((kind, "") not in columns and len(named) == 1 and not any(series(kind, lb) for lb in inflows)): log.info("%s: the column %r names no inflow line and is taken for the reach", path.name, columns[named[0]]) columns[(kind, "")] = columns.pop(named[0]) def stray(kind: str) -> str: names = unmatched(kind) return f"; the column(s) {', '.join(map(repr, names))} name no inflow line" if names else "" found = {lb.index: series("q", lb) for lb in inflows} lines = None if any(found.values()): missing = [label(lb) for lb in inflows if found[lb.index] is None] if missing: raise ValueError(f"{path.name}: no discharge column for {', '.join(missing)}; " "either every inflow line has one (Q <name of the line>) or " f"the table holds the discharge of the reach (Q){stray('q')}") lines = {lb.index: values(found[lb.index], f"the discharge of {label(lb)}") for lb in inflows} total = np.sum(list(lines.values()), axis=0) else: column = columns.get(("q", "")) if column is None: raise ValueError(f"{path.name}: no discharge column (Q, or Q <name of the line> " f"for {', '.join(label(lb) for lb in inflows)}){stray('q')}") total = values(column, "the discharge") temps = None if temperatures: own = {lb.index: series("t", lb) or columns.get(("t", "")) for lb in inflows} missing = [label(lb) for lb in inflows if own[lb.index] is None] if missing: raise ValueError(f"{path.name}: no water temperature for {', '.join(missing)}; " "add a column T <name of the line>, or one column T for all" f"{stray('t')}") temps = {lb.index: values(own[lb.index], f"the temperature of {label(lb)}") for lb in inflows} return Inflow(times_s=seconds - seconds[0], discharge=total, steady_value=float(np.mean(total)), lines=lines, temperatures=temps, origin=origin)
[docs] def read_rating_pairs(path: Path): """The pairs of a rating curve: ``(Q, WSE)`` as two arrays sorted by Q.""" df = _read_generic(Path(path)) num = df.select_dtypes("number") if num.shape[1] < 2: num = df.apply(pd.to_numeric, errors="coerce").dropna(axis=1, how="all") cols = {c.lower(): c for c in df.columns} qcol = next((cols[c] for c in cols if "q" in c or "disch" in c or "abfluss" in c), None) hcol = next((cols[c] for c in cols if "stage" in c or "wse" in c or "elev" in c or "wasserstand" in c or "h" == c.lower()), None) if qcol is None or hcol is None: qcol, hcol = num.columns[0], num.columns[1] q = pd.to_numeric(df[qcol], errors="coerce").to_numpy(dtype=float) h = pd.to_numeric(df[hcol], errors="coerce").to_numpy(dtype=float) keep = ~(np.isnan(q) | np.isnan(h)) q, h = q[keep], h[keep] if q.size == 0: raise ValueError(f"stage-discharge file {Path(path).name!r} has no Q-h pairs") order = np.argsort(q) return q[order], h[order]
[docs] def read_stage_discharge(path: Path): """Read a rating curve -> callable mapping discharge (m3/s) to WSE (m). Accepts a ``Q,WSE`` (or ``Q,stage``) CSV with one or more rows. A single Q-h pair is enough for a steady run (the WSE is then constant); with several rows the WSE is linearly interpolated in Q. Querying a Q outside the tabulated range clamps to the nearest endpoint and logs a warning (the curve does not extrapolate), so for steady runs supply the pair at the simulated discharge. """ q, h = read_rating_pairs(path) def wse_at(discharge: float) -> float: if discharge < q[0] - 1e-9 or discharge > q[-1] + 1e-9: log.warning( "outflow Q=%.3f m3/s is outside the rating curve range " "[%.3f, %.3f] m3/s; clamping the WSE. Add a Q-h pair at the " "simulated discharge to %s.", discharge, q[0], q[-1], Path(path).name) return float(np.interp(discharge, q, h)) return wse_at
[docs] def read_measurements(path: Path, crs_epsg: int) -> pd.DataFrame: """Read hydraulic measurement points into a tidy DataFrame. Returns columns: id, x, y, z (vertical offset, default 0), and any of ``water_depth`` / ``scalar_velocity`` that are present. Accepts a point shapefile/gpkg or a CSV with x/y columns. """ path = Path(path) if path.suffix.lower() in (".shp", ".gpkg", ".geojson"): import geopandas as gpd gdf = gpd.read_file(path) if gdf.crs and gdf.crs.to_epsg() != crs_epsg: gdf = gdf.to_crs(epsg=crs_epsg) df = pd.DataFrame(gdf.drop(columns="geometry")) df["x"] = gdf.geometry.x.to_numpy() df["y"] = gdf.geometry.y.to_numpy() else: df = _read_generic(path) lower = {c.lower(): c for c in df.columns} def pick(*names, default=None): for n in names: if n in lower: return df[lower[n]] return default out = pd.DataFrame() pid = pick("id", "name", "point") out["id"] = pid if pid is not None else np.arange(1, len(df) + 1) out["x"] = pd.to_numeric(pick("x", "easting", "ostwert"), errors="coerce") out["y"] = pd.to_numeric(pick("y", "northing", "nordwert"), errors="coerce") zoff = pick("z", "z_offset", "depth_below_surface") out["z"] = pd.to_numeric(zoff, errors="coerce") if zoff is not None else 0.0 depth = pick("water_depth", "water depth", "depth", "h", "wd") if depth is not None: out["water_depth"] = pd.to_numeric(depth, errors="coerce") vel = pick("scalar_velocity", "scalar velocity", "velocity", "v", "speed") if vel is not None: out["scalar_velocity"] = pd.to_numeric(vel, errors="coerce") return out.dropna(subset=["x", "y"]).reset_index(drop=True)
[docs] def resolve_outflow_wse(cfg, inflow_q: float) -> float: """Downstream water-surface elevation for a prescribed-elevation outflow. Shared by both backends: TELEMAC writes it as ``PRESCRIBED ELEVATIONS`` and OpenFOAM as a ``prghPressure`` profile on the outlet patch, and they must agree or the two models are not driven the same way. Where the level comes from is :data:`axqua.core.boundaries.OUTLET_LEVELS`: ``stage_discharge`` reads the rating curve and interpolates the WSE at the simulated discharge, ``elevation`` uses the fixed prescribed value, ``normal_depth`` the level of TELEMAC's Z(Q) curve at the discharge (the starting value TELEMAC then updates), and ``overfall`` the level below the lowest node of the built mesh. A free outflow has no level and raises. """ from axqua.core.boundaries import outlet_level level = outlet_level(cfg.outflow_condition) if level == "fixed": if cfg.boundaries.prescribed_elevation is None: raise ValueError( "outflow_condition: elevation needs boundaries.prescribed_elevation" ) return float(cfg.boundaries.prescribed_elevation) if level == "curve": from axqua.solvers.telemac.hydrology import outlet_rating_csv return read_stage_discharge(outlet_rating_csv(cfg))(inflow_q) if level == "mesh": from axqua.solvers.telemac.hydrology import overfall_level from axqua.workflow import mesh_from_geometry return overfall_level(mesh_from_geometry(cfg)) if level is None: raise ValueError(f"a {cfg.outflow_condition} outflow prescribes no water level") return _rating(cfg)(inflow_q)
[docs] def outflow_wse_fn(cfg, level: float | None = None): """Callable Q -> level of the outflow lines for a liquid-boundaries file, or None where the file gives no level: a free outflow prescribes none, and a ``normal_depth`` outlet takes its level from TELEMAC's own Z(Q) curve as the discharge changes. A rating curve gives the level of each discharge, every other outlet one level: *level* where the caller has it already (the hydrology build, from its mesh), else :func:`resolve_outflow_wse`.""" from axqua.core.boundaries import outlet_level kind = outlet_level(cfg.outflow_condition) if kind in (None, "curve"): return None if kind == "rating": return _rating(cfg) wse = float(level) if level is not None else resolve_outflow_wse(cfg, 0.0) return lambda _q: wse
def _rating(cfg): """The rating curve of the outflow, Q -> WSE, from ``boundaries.stage_discharge``.""" if cfg.boundaries.stage_discharge is None: raise ValueError( "outflow_condition: stage_discharge needs boundaries.stage_discharge (a Q-h " "rating CSV). Generate one with `axqua rating` from a Manning/" "Strickler value and the channel geometry (normal-flow conditions)." ) return read_stage_discharge(Path(cfg.boundaries.stage_discharge))