Diese Seite wurde maschinell aus dem Englischen übersetzt und kann Fehler enthalten. Englisches Original
Quellcode für axqua.solvers.telemac.unsteady
"""Unsteady (quasi-steady hydrograph) TELEMAC runs, built on the converged 2D case.
The steady initial run (``preprocessing.py`` + ``initial_run.py``) establishes a
well-converged flow field and writes it to ``r2d.slf``. This module turns that into
a **hydrograph-driven** run - a natural flood wave discretized as a sequence of
steady discharges (see ``telemac2d-unsteady.md``) - **hotstarted from that steady
result**, for 2D (``telemac2d``) or, with the same forcing, 3D (``telemac3d``).
Design decisions (deliberately different from the manual-Notepad tutorial):
* **Boundaries are NOT re-defined.** axqua's generated ``boundaries.cli`` is
already correct for the unsteady case - the inflow is ``4 5 5`` (prescribed Q,
depth free) and the outflow ``5 4 4`` (prescribed elevation). So there is no
``5 5 5 -> 4 5 5`` find-and-replace and no separate ``boundaries-unsteady.cli``:
the inflow discharge is driven by the ``LIQUID BOUNDARIES FILE`` (Q(t)) and the
downstream water level by its prescribed elevation (constant, or the rating stage
SL(t) at each Q when a stage-discharge rating exists). The tutorial's
``STAGE-DISCHARGE CURVES`` route is the alternative; we take the liquid-file route
because it needs no ``.cli`` edit and reuses the steady boundary numbering.
* **Hotstart from the steady result** (``PREVIOUS COMPUTATION FILE : r2d.slf``,
clock reset to zero) instead of re-seeding a dry/pre-wetted bed - the flood wave
then propagates from an already-converged field.
* **Quasi-steady numerics**: ``NUMBER OF CORRECTIONS OF DISTRIBUTIVE SCHEMES : 2``
(the developers' recommendation for predictor-corrector schemes on quasi-steady
flows), and optional ``CONTROL SECTIONS`` so the run reports the flux across each
open boundary (verifying Q_in(t) vs Q_out(t)).
* **GAIA** (bedload / suspended load) is coupled when ``morphodynamics.enabled``.
The routines recover the FRONT2 liquid-boundary numbering from the sidecar
``liquid-boundaries.json`` the build wrote (:func:`axqua.boundary.dump_liquid_boundaries`),
so no mesh rebuild is needed.
"""
from __future__ import annotations
import logging
from dataclasses import dataclass
from pathlib import Path
from axqua import hydraulics
from axqua.core.boundaries import outlet_level
from axqua.solvers.telemac import boundary, steering
from axqua.config import Config
log = logging.getLogger("axqua")
# quasi-steady predictor-corrector corrections per time step (TELEMAC2d manual 7.2.1)
QUASI_STEADY_CORRECTIONS = 2
#: Points of the outflow rating an unsteady build computes for the range of its hydrograph.
RATING_POINTS = 12
[Doku]
@dataclass
class UnsteadySetup:
cas: Path
liquid_boundaries: Path
control_sections: Path | None
gaia_cas: Path | None
duration: float
results: Path
previous_computation: str
turbulence_model: int
n_inflows: int
n_outflows: int
[Doku]
@dataclass
class Unsteady3DSetup:
cas: Path
liquid_boundaries: Path
gaia_cas: Path | None
duration: float
n_levels: int
dz: float
time_step: float
n_time_steps: int
results3d: Path
# --------------------------------------------------------------------------- #
# inputs
# --------------------------------------------------------------------------- #
[Doku]
def load_hydrograph(cfg: Config, liquids: list | None = None) -> hydraulics.Inflow:
"""Load the inflow hydrograph Q(t) from ``boundaries.inflow`` (the full series).
Raises with an actionable message when no series is configured or when it is a
single constant value (a genuine hydrograph is required for an unsteady run - a
constant discharge is the steady case). With *liquids*, a table with columns per inflow
line gives every line its own hydrograph, and in a heat run its water temperature; a
heat run may have a constant discharge, because its temperature varies.
"""
src = cfg.boundaries.inflow
if src is None or not Path(src).exists():
raise ValueError(
"no inflow hydrograph: set boundaries.inflow in case-config.yml to a "
"time series (LfU or a CSV with a time and a Q column). An unsteady run "
"needs a varying discharge; a constant Q is the steady case."
)
heat = cfg.heat.enabled
inflow = None
if liquids is not None:
# the clock of the table is a setting of the heat, which no other run reads
inflow = hydraulics.read_line_series(
Path(src), liquids, temperatures=heat,
utc_offset=float(cfg.heat.inflow_utc_offset) if heat else 0.0)
if inflow is None:
inflow = hydraulics.read_inflow(Path(src), steady=False)
import numpy as np
q = np.asarray(inflow.discharge, dtype=float)
if heat and inflow.times_s is not None and q.size >= 2:
return inflow
if inflow.times_s is None or q.size < 2 or not inflow.varies: # as the build asks
raise ValueError(
f"boundaries.inflow ({Path(src).name}) is a single/constant discharge (on "
"every inflow line); "
"supply a varying hydrograph (>=2 rows with changing Q) for an unsteady run."
)
return inflow
# Callable Q -> downstream WSE matching the outflow condition (None if free); one implementation for the build and the unsteady run.
_outflow_wse_fn = hydraulics.outflow_wse_fn
def _load_liquids(cfg: Config) -> list[boundary.LiquidBoundary]:
meta = cfg.model_path(cfg.liquid_boundaries_json)
if not meta.exists():
raise FileNotFoundError(
f"{meta.name} not found in {cfg.model_dir}. Re-run preprocessing.py so the "
"build serializes the liquid-boundary numbering the unsteady run needs."
)
return boundary.load_liquid_boundaries(meta)
def _turbulence_model(cfg: Config) -> int:
"""Turbulence model for the unsteady run, from the built geometry when readable."""
from types import SimpleNamespace
from axqua.core import selafin
geom = cfg.model_path(cfg.geometry_slf)
mesh = None
if geom.exists():
try:
data = selafin.read_slf(geom)
mesh = SimpleNamespace(x=data["x"], y=data["y"], triangles=data["ikle"])
except Exception: # noqa: BLE001 - fall back to the config-based estimate
mesh = None
return steering.select_turbulence_model(cfg, mesh)[0]
# --------------------------------------------------------------------------- #
# control sections
# --------------------------------------------------------------------------- #
[Doku]
def write_control_sections(cfg: Config) -> Path | None:
"""Write a CONTROL SECTIONS file: one cross-section per open-boundary segment.
Parses the generated ``boundaries.cli`` and, for each contiguous run of inflow /
outflow nodes (in file / IPOBO order), emits a section defined by that run's first
and last **global** node numbers (node-id mode, ``-1``). TELEMAC then reports the
cumulated flux across each section, so the unsteady run can be checked for mass
balance (Q_in(t) vs Q_out(t)). Returns ``None`` if the ``.cli`` has no liquid
nodes. A boundary that wraps the ``.cli`` start/end is one section. A run of a single
node is no section: TELEMAC stops on it ("FLUSEC_TELEMAC2D : ALGORITHM FAILED").
"""
cli = cfg.model_path(cfg.boundary_cli)
if not cli.exists():
raise FileNotFoundError(
f"{cli.name} not found; run preprocessing.py before the unsteady setup.")
# group CONSECUTIVE .cli rows (by rank, not by global node number - the latter is
# not consecutive along a real contour) of the same liquid tag into one section,
# keeping that run's first and last global node numbers as the section endpoints.
runs: list[list] = [] # [kind, first_node, last_node, last_rank]
first_rank = last_rank = 0
for line in cli.read_text().splitlines():
left, _, comment = line.partition("#")
tag = comment.strip().lower()
tokens = left.split()
if len(tokens) < 2:
continue
n_global, rank = int(tokens[-2]), int(tokens[-1])
last_rank = rank
if tag not in ("inflow", "outflow"):
continue
first_rank = first_rank or rank
if runs and runs[-1][0] == tag and runs[-1][3] == rank - 1:
runs[-1][2], runs[-1][3] = n_global, rank # extend the contiguous run
else:
runs.append([tag, n_global, n_global, rank])
# the walk along the contour starts somewhere: where it starts inside a liquid boundary,
# the boundary is the first and the last run of the file
if (len(runs) > 1 and first_rank == 1 and runs[-1][3] == last_rank
and runs[0][0] == runs[-1][0]):
runs[0][1] = runs.pop()[1]
runs = [run for run in runs if run[1] != run[2]]
if not runs:
return None
counts: dict[str, int] = {}
lines = ["# control sections generated by axqua (unsteady flux verification)",
f"{len(runs)} -1"]
for kind, first, last, _rank in runs:
counts[kind] = counts.get(kind, 0) + 1
lines.append(f"{kind}_{counts[kind]}")
lines.append(f"{first} {last}")
path = cfg.model_path(cfg.control_sections_file)
path.write_text("\n".join(lines) + "\n")
log.info(" control sections: %d cross-sections -> %s", len(runs), path.name)
return path
# --------------------------------------------------------------------------- #
# builders
# --------------------------------------------------------------------------- #
def _is_steady_rating(cfg: Config) -> bool:
"""Whether the outflow rating is the one-point curve the steady build computed itself.
The preprocessing has put it into ``boundaries.stage_discharge`` by the time it writes the unsteady case.
"""
own = cfg.preprocessing_path("rating-curve.csv")
if Path(cfg.boundaries.stage_discharge) != own or not own.is_file():
return False
rows = [line for line in own.read_text().splitlines()
if line.strip() and not line.lstrip().startswith("#")]
return len(rows) <= 2 # the header and one point
[Doku]
def check_steady_result(cfg: Config) -> Path:
"""The steady result an unsteady run continues from, or a ConfigError saying why it cannot.
Two states are refused besides a missing file. A result of another mesh, because the case was built again after the steady run. And a result an unsteady run wrote: up to aXqua 1.5.1 the unsteady job ran the steering file of the preprocessing, whose results file was the one of the steady run.
"""
from axqua.core import errors, selafin
again = "Run the steady simulation (axqua submit <case> --kind steady) and then submit the unsteady run again."
path = cfg.model_path(cfg.results_slf)
if not path.exists():
raise errors.ConfigError(
f"no steady result at {path}; the unsteady run continues from it",
subject="model_dir", remedy=again)
try:
result = selafin.SelafinFile(path)
except Exception as exc: # noqa: BLE001 - an unfinished or foreign file
raise errors.ConfigError(f"the steady result {path} cannot be read: {exc}",
subject="model_dir", remedy=again) from exc
if result.n_frames == 0:
raise errors.ConfigError(f"{path.name} holds no time step yet",
subject="model_dir", remedy=again)
if result.title.endswith(" unsteady"):
raise errors.ConfigError(
f"{path.name} holds the result of an unsteady run, not of the steady run",
subject="model_dir", remedy=again)
geometry = cfg.model_path(cfg.geometry_slf)
if geometry.exists():
nodes = selafin.SelafinFile(geometry).npoin
if nodes != result.npoin:
raise errors.ConfigError(
f"{path.name} has {result.npoin} nodes and the mesh of the case has {nodes}: "
"the case was built again after the steady run",
subject="model_dir", remedy=again)
return path
def _synthesize_rating(cfg: Config, inflow) -> None:
"""The outflow rating of a hydrograph, where the case has none of its own.
The one the steady build computes holds for its discharge alone, so the level would stay constant while the discharge varies. This one covers the discharges of the series with :data:`RATING_POINTS` points, in a file of its own.
"""
import numpy as np
if outlet_level(cfg.outflow_condition) != "rating":
return
if cfg.boundaries.stage_discharge is not None and not _is_steady_rating(cfg):
return
from axqua import rating
q = np.asarray(inflow.discharge, dtype=float)
low, high = max(float(q.min()), 0.01 * float(q.max()), 1e-3), float(q.max())
points = ([high] if high - low < 1e-6
else [float(v) for v in np.geomspace(low, high, RATING_POINTS)])
out = cfg.preprocessing_path("rating-curve-unsteady.csv")
section = cfg.boundaries.rating_method == "section"
build = (rating.synthesize_outflow_rating_from_section if section
else rating.synthesize_outflow_rating)
cfg.boundaries.stage_discharge = build(cfg, points, out=out)
log.info(" outflow rating of the hydrograph: %d point(s), %.2f to %.2f m3/s -> %s",
len(points), low, high, out.name)
def _warn_about_the_first_discharge(cfg: Config, inflow) -> None:
"""The steady flow the run starts from should be the one of the first discharge."""
import numpy as np
first = float(np.asarray(inflow.discharge, dtype=float)[0])
steady = cfg.boundaries.prescribed_flowrate
steady = float(inflow.steady_value if steady is None else steady)
if abs(steady - first) > 0.05 * max(abs(first), 1e-9):
log.warning("the hydrograph starts at %.3f m3/s and the steady run the unsteady run "
"continues from has %.3f m3/s; the first hours are an adjustment from one "
"to the other (set boundaries.prescribed_flowrate to the first discharge)",
first, steady)
def _prepare_forcing(cfg: Config, *, require_steady: bool = True, n_tracers: int = 1):
"""Shared unsteady preamble: verify the hotstart source, load boundaries + the
hydrograph, and write the liquid-boundaries (Q(t)/SL(t)) file. Returns
``(liquids, inflow, liq_path, duration, wse_fn)``. Without *require_steady* (the preprocessing, which runs before the steady run) the hotstart source is not checked."""
if getattr(cfg, "hydrology_mode", False):
from axqua.core import errors
raise errors.ConfigError(
"a hydrology case has no unsteady run: its inflow lines follow their "
"hydrograph in the hydrology run", subject="boundaries.inflow",
remedy="Submit the hydrology run (axqua submit <case> --kind hydrology).")
if require_steady:
check_steady_result(cfg)
liquids = _load_liquids(cfg)
inflow = load_hydrograph(cfg, liquids)
_warn_about_the_first_discharge(cfg, inflow)
_synthesize_rating(cfg, inflow)
wse_fn = _outflow_wse_fn(cfg)
liq = steering.write_liquid_boundaries(cfg, liquids, inflow, wse_fn, n_tracers=n_tracers)
import numpy as np
t = np.asarray(inflow.times_s, dtype=float)
duration = float(t[-1] - t[0]) or 3600.0
return liquids, inflow, liq, duration, wse_fn
[Doku]
def build_unsteady_case(cfg: Config, *, control_sections: bool = True,
require_steady: bool = True,
regions: list | None = None, out_name: str | None = None,
results_name: str | None = None,
printout_periods: tuple[int, int] | None = None,
ensemble=None) -> UnsteadySetup:
"""Write the unsteady **telemac2d** case, hotstarted from the steady ``r2d.slf``.
Reuses ``boundaries.cli`` unchanged, drives the inflow with the hydrograph liquid
file and the outflow with its prescribed elevation / rating, adds the quasi-steady
correction keyword and (optionally) control sections, and couples GAIA when
``morphodynamics.enabled``. Returns the :class:`UnsteadySetup`.
The preprocessing writes the same case before there is a steady result (*require_steady* false) and passes the internal source *regions* it has checked against the mesh. The unsteady job writes it again, so a hydrograph changed after the preprocessing needs no new mesh.
*out_name*, *results_name* and *printout_periods* (graphic and listing, in steps) are for runs beside the one of the case, such as those of a calibration. *ensemble* is a heat run with several parameter sets (:mod:`axqua.solvers.telemac.heat_ensemble`).
"""
liquids, inflow, liq, duration, wse_fn = _prepare_forcing(
cfg, require_steady=require_steady,
n_tracers=1 if ensemble is None else len(ensemble.sets))
import numpy as np
q0 = float(np.asarray(inflow.discharge, dtype=float)[0])
outflow_wse = wse_fn(q0) if wse_fn is not None else None
sections = write_control_sections(cfg) if control_sections else None
gaia = steering.write_gaia_cas(cfg)
turb = _turbulence_model(cfg)
# internal losing/gaining source regions (percolation) carry over to the
# unsteady run - without them the exchange (and the side channel it feeds)
# would silently vanish from the hydrograph run. No mesh here (no re-meshing
# in the standalone script), so node counts are not re-verified; the regions
# file is (re)written to match the region order in the .cas. The layer is only
# needed for its internal lines, so an unreadable/absent one warns (loudly -
# the exchange would be dropped) rather than aborting the unsteady build.
if regions is None:
regions = []
try:
regions = boundary.exchange_regions(cfg)
except Exception as exc: # noqa: BLE001 - degrade, but say so
log.warning("could not re-read %s for internal source regions (%s); the "
"unsteady case will carry NO internal losing/gaining exchange",
cfg.boundaries.liquid_boundaries, exc)
if regions and not (cfg.gain_lose.active
and cfg.gain_lose.implementation == "fortran"):
steering.write_source_regions(cfg, regions)
from axqua.solvers.telemac import heat
thermal = None
if cfg.heat.enabled:
fortran_mode = cfg.gain_lose.active and cfg.gain_lose.implementation == "fortran"
thermal = heat.prepare(cfg, inflow, duration,
n_sources=0 if fortran_mode else len(regions),
ensemble=ensemble)
else:
heat.remove_routine(cfg)
cas = steering.write_cas(
cfg, liquids, inflow_q=q0, outflow_wse=outflow_wse,
gaia_cas=gaia.name if gaia else None,
previous_computation=cfg.results_slf, turbulence_model=turb,
extra_block=thermal["block"] if thermal else None,
printouts=thermal["printouts"] if thermal else None,
needs_fortran=thermal is not None,
unsteady=True, liquid_boundaries_file=liq.name, duration=duration,
out_name=out_name or cfg.unsteady_cas_file,
results_name=results_name or cfg.results_unsteady_slf,
printout_periods=printout_periods,
n_distributive_corrections=QUASI_STEADY_CORRECTIONS,
sections_input=sections.name if sections else None,
sections_output=cfg.sections_output_file if sections else None,
hotstart_note="/ hotstart: continue from the converged steady result r2d.slf",
source_regions=regions,
)
n_in = sum(1 for lb in liquids if lb.kind == "inflow")
n_out = sum(1 for lb in liquids if lb.kind == "outflow")
log.info("unsteady2d case -> %s (hydrograph %s over %.0f s, hotstart from %s)",
cas.name, liq.name, duration, cfg.results_slf)
return UnsteadySetup(
cas=cas, liquid_boundaries=liq, control_sections=sections,
gaia_cas=gaia, duration=duration, results=cfg.model_path(results_name or cfg.results_unsteady_slf),
previous_computation=cfg.results_slf, turbulence_model=turb,
n_inflows=n_in, n_outflows=n_out,
)
[Doku]
def build_unsteady_3d_case(cfg: Config, *,
total_time_factor: float = 4.0,
out_name: str | None = None,
data: dict | None = None) -> Unsteady3DSetup:
"""Write the unsteady **telemac3d** case: the same hydrograph forcing on the 3D,
non-hydrostatic mesh, hotstarted from the 2D result.
Writes the hydrograph liquid file (as for 2D) and delegates to
:func:`axqua.threed.build_3d_cas` with the unsteady forcing (the 3D case has
no DURATION keyword, so the run spans the hydrograph via its step count). Couples
GAIA when enabled. The 3D horizontal mesh should already be validated (2D
mesh-convergence) before running this. *out_name* overrides the steering filename
(default ``<case-name>3d-unsteady.cas``); *data* is an optional pre-read 2D
result so several 3D variants share one read of a large results file.
"""
from axqua.solvers.telemac import threed
liquids, inflow, liq, duration, _ = _prepare_forcing(cfg)
gaia = steering.write_gaia_cas(cfg)
setup = threed.build_3d_cas(
cfg, unsteady=True, liquid_boundaries_file=liq.name, duration=duration,
total_time_factor=total_time_factor, gaia_cas=gaia.name if gaia else None,
out_name=out_name or threed.cas3d_name(cfg, "-unsteady"),
results3d_name=cfg.results3d_unsteady_slf,
results2d_name=cfg.results2d_from_3d_unsteady_slf,
data=data,
)
log.info("unsteady 3D case -> %s (hydrograph %s over %.0f s, %d sigma levels)",
setup.cas.name, liq.name, duration, setup.n_levels)
return Unsteady3DSetup(
cas=setup.cas, liquid_boundaries=liq, gaia_cas=gaia, duration=duration,
n_levels=setup.n_levels, dz=setup.dz, time_step=setup.time_step,
n_time_steps=setup.n_time_steps,
results3d=cfg.model_path(cfg.results3d_unsteady_slf),
)