|
| 1 | +"""Configuration dataclass for ERA5/GFS hindcast preprocessing.""" |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +import datetime as _dt |
| 5 | +import logging |
| 6 | +import os |
| 7 | +from dataclasses import dataclass |
| 8 | +from typing import List, Sequence, Union |
| 9 | + |
| 10 | +logger = logging.getLogger(__name__) |
| 11 | + |
| 12 | + |
| 13 | +@dataclass |
| 14 | +class HindcastConfig: |
| 15 | + """Configuration parsed from a hindcast input file. |
| 16 | +
|
| 17 | + The expected file format is a text file with ``key: value`` pairs:: |
| 18 | +
|
| 19 | + year: 2020 |
| 20 | + month: 08 |
| 21 | + day: 26 |
| 22 | + time: 00:00 |
| 23 | + area: 50,-130,10,-50 |
| 24 | +
|
| 25 | + The ``area`` field is ``lat_max, lon_min, lat_min, lon_max``. |
| 26 | + """ |
| 27 | + |
| 28 | + year: int |
| 29 | + month: int |
| 30 | + day: int |
| 31 | + time: str # "HH:MM" |
| 32 | + area: List[float] # [lat_max, lon_min, lat_min, lon_max] |
| 33 | + |
| 34 | + @classmethod |
| 35 | + def from_file(cls, filename: Union[str, os.PathLike]) -> "HindcastConfig": |
| 36 | + """Parse a key:value input file into a :class:`HindcastConfig`. |
| 37 | +
|
| 38 | + Parameters |
| 39 | + ---------- |
| 40 | + filename: |
| 41 | + Path to the input file. Accepts both ``str`` and |
| 42 | + :class:`os.PathLike` objects (e.g. :class:`pathlib.Path`). |
| 43 | +
|
| 44 | + Returns |
| 45 | + ------- |
| 46 | + HindcastConfig |
| 47 | + """ |
| 48 | + filename = os.fspath(filename) |
| 49 | + if not os.path.isfile(filename): |
| 50 | + raise FileNotFoundError(f"Input file not found: {filename}") |
| 51 | + data: dict = {} |
| 52 | + with open(filename, "r") as fh: |
| 53 | + for lineno, line in enumerate(fh, start=1): |
| 54 | + stripped = line.strip() |
| 55 | + if not stripped or stripped.startswith("#"): |
| 56 | + continue |
| 57 | + if ":" not in stripped: |
| 58 | + logger.warning( |
| 59 | + "%s line %d: skipping unrecognised line: %r", |
| 60 | + filename, |
| 61 | + lineno, |
| 62 | + stripped, |
| 63 | + ) |
| 64 | + continue |
| 65 | + key, _, value = stripped.partition(":") |
| 66 | + key = key.strip().lower() |
| 67 | + value = value.strip() |
| 68 | + if key == "area": |
| 69 | + data[key] = [float(x) for x in value.split(",")] |
| 70 | + elif key == "time": |
| 71 | + data[key] = value |
| 72 | + else: |
| 73 | + try: |
| 74 | + data[key] = int(value) |
| 75 | + except ValueError: |
| 76 | + data[key] = value |
| 77 | + return cls(**data) |
| 78 | + |
| 79 | + @classmethod |
| 80 | + def from_datetime( |
| 81 | + cls, |
| 82 | + dt: Union[str, _dt.datetime], |
| 83 | + area: Sequence[float], |
| 84 | + ) -> "HindcastConfig": |
| 85 | + """Construct a :class:`HindcastConfig` from a datetime-like object and area. |
| 86 | +
|
| 87 | + Parameters |
| 88 | + ---------- |
| 89 | + dt: |
| 90 | + The date/time of the hindcast snapshot. Accepted types are: |
| 91 | +
|
| 92 | + * ``str`` – ISO-format string (e.g. ``"2020-08-26"``, |
| 93 | + ``"2020-08-26 00:00"``). When :mod:`pandas` is available, |
| 94 | + any string parseable by :class:`pandas.Timestamp` is accepted; |
| 95 | + otherwise :func:`datetime.datetime.fromisoformat` is used. |
| 96 | + * :class:`datetime.datetime` or :class:`pandas.Timestamp` |
| 97 | + (which is a subclass of :class:`datetime.datetime`). |
| 98 | +
|
| 99 | + area: |
| 100 | + Sequence of four floats ``[lat_max, lon_min, lat_min, lon_max]``. |
| 101 | +
|
| 102 | + Returns |
| 103 | + ------- |
| 104 | + HindcastConfig |
| 105 | + """ |
| 106 | + if isinstance(dt, str): |
| 107 | + try: |
| 108 | + import pandas as pd # preferred: handles non-ISO formats too |
| 109 | + dt = pd.Timestamp(dt) |
| 110 | + except ImportError: |
| 111 | + # Fallback for environments without pandas: accept ISO format strings |
| 112 | + dt = _dt.datetime.fromisoformat(dt) |
| 113 | + # At this point dt is a datetime.datetime (pd.Timestamp inherits from it) |
| 114 | + if not isinstance(dt, _dt.datetime): |
| 115 | + raise TypeError( |
| 116 | + f"dt must be a str, datetime.datetime, or pandas.Timestamp; got {type(dt)!r}" |
| 117 | + ) |
| 118 | + time_str = f"{dt.hour:02d}:{dt.minute:02d}" |
| 119 | + return cls( |
| 120 | + year=int(dt.year), |
| 121 | + month=int(dt.month), |
| 122 | + day=int(dt.day), |
| 123 | + time=time_str, |
| 124 | + area=list(area), |
| 125 | + ) |
| 126 | + |
| 127 | + def validate(self) -> None: |
| 128 | + """Validate the parsed configuration values. |
| 129 | +
|
| 130 | + Raises |
| 131 | + ------ |
| 132 | + ValueError |
| 133 | + If any required field is missing or any value is out of range. |
| 134 | + """ |
| 135 | + for field_name in ("year", "month", "day", "time", "area"): |
| 136 | + if getattr(self, field_name, None) is None: |
| 137 | + raise ValueError(f"Missing required field: {field_name}") |
| 138 | + if len(self.area) != 4: |
| 139 | + raise ValueError( |
| 140 | + "'area' must have exactly 4 values: lat_max, lon_min, lat_min, lon_max" |
| 141 | + ) |
| 142 | + lat_max, lon_min, lat_min, lon_max = self.area |
| 143 | + if lat_max <= lat_min: |
| 144 | + raise ValueError( |
| 145 | + "area: lat_max (1st value) must be greater than lat_min (3rd value)" |
| 146 | + ) |
| 147 | + if lon_max <= lon_min: |
| 148 | + raise ValueError( |
| 149 | + "area: lon_max (4th value) must be greater than lon_min (2nd value)" |
| 150 | + ) |
0 commit comments