|
11 | 11 | from datetime import datetime, timezone |
12 | 12 | from typing import Optional |
13 | 13 |
|
| 14 | +# Seconds per Julian year (365.25 days) — matches Ocotillo's trend MV, which |
| 15 | +# divides the per-second regression slope by 31557600 to get ft/year. |
| 16 | +_SECONDS_PER_YEAR = 31557600.0 |
| 17 | + |
| 18 | +# Trend classification thresholds, ported verbatim from the Ocotillo |
| 19 | +# ogc_depth_to_water_trend_wells materialized view. |
| 20 | +_TREND_SLOPE_THRESHOLD = 0.25 # ft/year |
| 21 | +_TREND_MIN_RECORDS = 10 |
| 22 | +_TREND_MIN_RECORDS_WITH_SPAN = 4 |
| 23 | +_TREND_MIN_SPAN_YEARS = 2.0 |
| 24 | + |
| 25 | +# Human-readable description of the trend method, embedded in the product so |
| 26 | +# consumers know how the classification was derived. |
| 27 | +TREND_METHOD_DESCRIPTION = ( |
| 28 | + "Depth-to-water trend per well. A least-squares linear regression " |
| 29 | + "(equivalent to PostgreSQL REGR_SLOPE) is fit to depth-to-water-below-" |
| 30 | + "ground-surface (feet) against observation time; the per-second slope is " |
| 31 | + "scaled by 31,557,600 s/yr (a 365.25-day year) to slope_ft_per_year. A well " |
| 32 | + "is classified only when it has at least 10 measurements, or at least 4 " |
| 33 | + "measurements spanning at least 2 years; otherwise 'not enough data'. When " |
| 34 | + "classified: slope > 0.25 ft/yr is 'increasing' (water level getting " |
| 35 | + "DEEPER, i.e. a declining water table), slope < -0.25 ft/yr is 'decreasing' " |
| 36 | + "(water level getting SHALLOWER), otherwise 'stable'. Ported from the " |
| 37 | + "Ocotillo API ogc_depth_to_water_trend_wells materialized view." |
| 38 | +) |
| 39 | + |
14 | 40 |
|
15 | 41 | def _timestamp_now() -> str: |
16 | 42 | return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") |
17 | 43 |
|
18 | 44 |
|
| 45 | +def _parse_epoch_seconds(date, time) -> Optional[float]: |
| 46 | + """Best-effort parse of a DIE date (+optional time) to POSIX seconds (UTC).""" |
| 47 | + if not date: |
| 48 | + return None |
| 49 | + text = f"{date}T{time}" if time else str(date) |
| 50 | + text = text.replace("Z", "") |
| 51 | + for parse in (datetime.fromisoformat,): |
| 52 | + try: |
| 53 | + dt = parse(text) |
| 54 | + if dt.tzinfo is None: |
| 55 | + dt = dt.replace(tzinfo=timezone.utc) |
| 56 | + return dt.timestamp() |
| 57 | + except (ValueError, TypeError): |
| 58 | + pass |
| 59 | + try: |
| 60 | + dt = datetime.fromisoformat(str(date)).replace(tzinfo=timezone.utc) |
| 61 | + return dt.timestamp() |
| 62 | + except (ValueError, TypeError): |
| 63 | + return None |
| 64 | + |
| 65 | + |
| 66 | +def _regr_slope(xs: list, ys: list) -> Optional[float]: |
| 67 | + """Least-squares slope of ys on xs (PostgreSQL REGR_SLOPE). None if x has no |
| 68 | + variance (fewer than 2 distinct x values).""" |
| 69 | + n = len(xs) |
| 70 | + if n < 2: |
| 71 | + return None |
| 72 | + mx = sum(xs) / n |
| 73 | + my = sum(ys) / n |
| 74 | + sxx = sum((x - mx) ** 2 for x in xs) |
| 75 | + if sxx == 0: |
| 76 | + return None |
| 77 | + sxy = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) |
| 78 | + return sxy / sxx |
| 79 | + |
| 80 | + |
| 81 | +def _classify_trend(slope_ft_per_year, record_count, span_years) -> str: |
| 82 | + qualifies = record_count >= _TREND_MIN_RECORDS or ( |
| 83 | + record_count >= _TREND_MIN_RECORDS_WITH_SPAN |
| 84 | + and span_years >= _TREND_MIN_SPAN_YEARS |
| 85 | + ) |
| 86 | + if not qualifies or slope_ft_per_year is None: |
| 87 | + return "not enough data" |
| 88 | + if slope_ft_per_year > _TREND_SLOPE_THRESHOLD: |
| 89 | + return "increasing" |
| 90 | + if slope_ft_per_year < -_TREND_SLOPE_THRESHOLD: |
| 91 | + return "decreasing" |
| 92 | + return "stable" |
| 93 | + |
| 94 | + |
19 | 95 | def _make_feature(record, collection_id: str) -> dict: |
20 | 96 | """Build one OGC-compliant Feature from a SummaryRecord or SiteRecord.""" |
21 | 97 | source = getattr(record, "source", "") |
@@ -174,6 +250,125 @@ def dump_major_chemistry_collection(path: str, records: list, meta: dict) -> dic |
174 | 250 | return collection |
175 | 251 |
|
176 | 252 |
|
| 253 | +def dump_waterlevel_trend_collection( |
| 254 | + path: str, |
| 255 | + site_records: list, |
| 256 | + timeseries_records: list, |
| 257 | + meta: dict, |
| 258 | +) -> dict: |
| 259 | + """ |
| 260 | + Write an OGC FeatureCollection of per-well depth-to-water trends to *path*. |
| 261 | + One Feature per well. |
| 262 | +
|
| 263 | + *site_records* and *timeseries_records* are index-aligned: ``site_records[i]`` |
| 264 | + is the well and ``timeseries_records[i]`` is its list of ParameterRecord |
| 265 | + observations (DIE water-level values are already depth-to-water below ground |
| 266 | + surface in feet, so no measuring-point adjustment is applied here). |
| 267 | +
|
| 268 | + Each feature carries: record_count, first/last_observation_datetime, |
| 269 | + span_years, slope_ft_per_year, trend_category, well_depth(+units). The |
| 270 | + collection carries ``trend_method`` describing the calculation. See |
| 271 | + TREND_METHOD_DESCRIPTION. |
| 272 | +
|
| 273 | + §V: MUST include top-level id, type, numberReturned, timeStamp. |
| 274 | + §V: Each Feature MUST have top-level id. |
| 275 | + """ |
| 276 | + collection_id = meta.get("id", "collection") |
| 277 | + |
| 278 | + features = [] |
| 279 | + for site, obs_list in zip(site_records, timeseries_records): |
| 280 | + pairs = [] |
| 281 | + for obs in obs_list: |
| 282 | + value = getattr(obs, "parameter_value", None) |
| 283 | + epoch = _parse_epoch_seconds( |
| 284 | + getattr(obs, "date_measured", None), getattr(obs, "time_measured", None) |
| 285 | + ) |
| 286 | + if value is None or epoch is None: |
| 287 | + continue |
| 288 | + try: |
| 289 | + pairs.append((epoch, float(value))) |
| 290 | + except (TypeError, ValueError): |
| 291 | + continue |
| 292 | + |
| 293 | + pairs.sort(key=lambda p: p[0]) |
| 294 | + record_count = len(pairs) |
| 295 | + xs = [p[0] for p in pairs] |
| 296 | + ys = [p[1] for p in pairs] |
| 297 | + |
| 298 | + if record_count >= 2: |
| 299 | + span_years = (xs[-1] - xs[0]) / _SECONDS_PER_YEAR |
| 300 | + slope = _regr_slope(xs, ys) |
| 301 | + slope_ft_per_year = None if slope is None else slope * _SECONDS_PER_YEAR |
| 302 | + else: |
| 303 | + span_years = 0.0 |
| 304 | + slope_ft_per_year = None |
| 305 | + |
| 306 | + trend_category = _classify_trend(slope_ft_per_year, record_count, span_years) |
| 307 | + |
| 308 | + source = getattr(site, "source", "") or "" |
| 309 | + rid = getattr(site, "id", "") or "" |
| 310 | + feature_id = f"{source}:{rid}" if source and rid else str(rid) |
| 311 | + |
| 312 | + def _iso(epoch): |
| 313 | + if epoch is None: |
| 314 | + return None |
| 315 | + return datetime.fromtimestamp(epoch, tz=timezone.utc).strftime( |
| 316 | + "%Y-%m-%dT%H:%M:%SZ" |
| 317 | + ) |
| 318 | + |
| 319 | + props = { |
| 320 | + "source": source, |
| 321 | + "id": rid, |
| 322 | + "name": getattr(site, "name", None), |
| 323 | + "well_depth": getattr(site, "well_depth", None), |
| 324 | + "well_depth_units": getattr(site, "well_depth_units", None), |
| 325 | + "record_count": record_count, |
| 326 | + "first_observation_datetime": _iso(xs[0]) if record_count else None, |
| 327 | + "last_observation_datetime": _iso(xs[-1]) if record_count else None, |
| 328 | + "span_years": round(span_years, 3), |
| 329 | + "slope_ft_per_year": ( |
| 330 | + None if slope_ft_per_year is None else round(slope_ft_per_year, 4) |
| 331 | + ), |
| 332 | + "trend_category": trend_category, |
| 333 | + } |
| 334 | + |
| 335 | + lat = getattr(site, "latitude", None) |
| 336 | + lon = getattr(site, "longitude", None) |
| 337 | + elev = getattr(site, "elevation", None) |
| 338 | + coords = [lon, lat] if elev is None else [lon, lat, elev] |
| 339 | + |
| 340 | + features.append({ |
| 341 | + "type": "Feature", |
| 342 | + "id": feature_id, |
| 343 | + "geometry": {"type": "Point", "coordinates": coords}, |
| 344 | + "properties": props, |
| 345 | + }) |
| 346 | + |
| 347 | + collection = { |
| 348 | + "type": "FeatureCollection", |
| 349 | + "id": collection_id, |
| 350 | + "title": meta.get("title", collection_id), |
| 351 | + "description": meta.get("description", ""), |
| 352 | + "trend_method": TREND_METHOD_DESCRIPTION, |
| 353 | + "timeStamp": _timestamp_now(), |
| 354 | + "numberMatched": len(features), |
| 355 | + "numberReturned": len(features), |
| 356 | + "links": [ |
| 357 | + { |
| 358 | + "href": meta.get("href", ""), |
| 359 | + "rel": "self", |
| 360 | + "type": "application/geo+json", |
| 361 | + } |
| 362 | + ], |
| 363 | + "features": features, |
| 364 | + } |
| 365 | + |
| 366 | + with open(path, "w", encoding="utf-8") as f: |
| 367 | + json.dump(collection, f, indent=2, default=str) |
| 368 | + |
| 369 | + return collection |
| 370 | + |
| 371 | + |
177 | 372 | def dump_timeseries_collection( |
178 | 373 | path: str, |
179 | 374 | site_records: list, |
|
0 commit comments