-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresponse_method.py
More file actions
2117 lines (1825 loc) · 82.3 KB
/
Copy pathresponse_method.py
File metadata and controls
2117 lines (1825 loc) · 82.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
response_method.py
------------------
Refactor: use complex astronomic forcing functions (Munk & Cartwright style), while keeping
a *real* least-squares system by splitting complex inputs into Re/Im regressors.
NEW IN THIS DROP-IN REPLACEMENT
-------------------------------
ForcingGenerator now supports an optional on-disk cache of computed forcing on a regular grid
(default chunking = per-year, grid freq = "6min"). You can:
- Opt in to cache (speed):
forcing_use_cache=True
- Force recomputation (no cache):
forcing_use_cache=False or forcing_force_recompute=True
- Validate that cached forcing matches uncached forcing:
forcing_validate_cache=True
Caching is transparent to the rest of the model: build_design_matrix() still receives a base_df
on a regular grid and interpolates to lagged times.
Key points
----------
- ForcingGenerator.compute_base(..., complex_inputs=True) returns complex-valued columns.
- build_design_matrix(..., complex_inputs=True, split_complex=True) builds real regressors:
y(t) ≈ Σ_l [ a_l Re{x(t+lag_l)} + b_l Im{x(t+lag_l)} ] + ...
which is equivalent to:
y(t) ≈ Re{ Σ_l w_l x(t+lag_l) } with w_l = a_l - i b_l
- admittance() reconstructs complex weights w_l and returns complex H(f).
- harmonic_from_admittance() supports complex forcing_df directly.
Dependencies
------------
Required:
numpy, pandas
Optional (recommended):
scipy, skyfield
Optional:
sklearn (StandardScaler; fallback provided)
"""
from __future__ import annotations
import math
import os
import json
import hashlib
import warnings
from dataclasses import dataclass
from typing import Dict, List, Optional, Sequence, Tuple, Union
import numpy as np
import pandas as pd
# Optional sklearn scaler
try:
from sklearn.preprocessing import StandardScaler as _SkStandardScaler
except Exception: # pragma: no cover
_SkStandardScaler = None
# Optional SciPy
try:
from scipy.special import lpmv, eval_legendre
from scipy.special import gammaln as _gammaln
except Exception as _scipy_err: # pragma: no cover
lpmv = None
eval_legendre = None
_gammaln = None
_SCIPY_IMPORT_ERROR = _scipy_err
else:
_SCIPY_IMPORT_ERROR = None
# Optional Skyfield
try:
from skyfield.api import load, wgs84
except Exception as _skyfield_err: # pragma: no cover
load = None
wgs84 = None
_SKYFIELD_IMPORT_ERROR = _skyfield_err
else:
_SKYFIELD_IMPORT_ERROR = None
# ---------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------
def cosd(x_deg):
return np.cos(np.deg2rad(x_deg))
def _to_datetime_index(index) -> pd.DatetimeIndex:
return pd.DatetimeIndex(index)
class _StandardScalerFallback:
"""Minimal StandardScaler-like behavior (mean/std), used if sklearn isn't available."""
def __init__(self):
self.mean_ = None
self.scale_ = None
def fit(self, X: np.ndarray):
mu = np.nanmean(X, axis=0)
sig = np.nanstd(X, axis=0)
sig = np.where(sig < 1e-12, 1.0, sig)
self.mean_ = mu
self.scale_ = sig
return self
def transform(self, X: np.ndarray) -> np.ndarray:
return (X - self.mean_) / self.scale_
def fit_transform(self, X: np.ndarray) -> np.ndarray:
return self.fit(X).transform(X)
def _get_scaler():
return _SkStandardScaler() if _SkStandardScaler is not None else _StandardScalerFallback()
def _ensure_dir(path: str):
os.makedirs(path, exist_ok=True)
def _as_utc_index(idx: pd.DatetimeIndex) -> pd.DatetimeIndex:
"""Return a tz-aware UTC index representing the same instants."""
idx = pd.DatetimeIndex(idx)
if idx.tz is None:
return idx.tz_localize("UTC")
return idx.tz_convert("UTC")
def _maybe_back_to_tz(idx_utc: pd.DatetimeIndex, tz) -> pd.DatetimeIndex:
"""Convert UTC tz-aware index back to tz (or drop tz if tz is None)."""
if tz is None:
# drop tz info (keep same instants expressed as naive UTC timestamps)
return idx_utc.tz_convert("UTC").tz_localize(None)
return idx_utc.tz_convert(tz)
def _date_range_inclusive_left(start, end, freq: str, tz="UTC") -> pd.DatetimeIndex:
"""
Make a date_range [start, end) with step=freq.
Safe for both tz-aware and naive inputs.
"""
start = pd.Timestamp(start)
end = pd.Timestamp(end)
# Normalize timezone correctly
if start.tz is None:
start = start.tz_localize(tz)
else:
start = start.tz_convert(tz)
if end.tz is None:
end = end.tz_localize(tz)
else:
end = end.tz_convert(tz)
try:
return pd.date_range(start=start, end=end, freq=freq, inclusive="left")
except TypeError: # older pandas
return pd.date_range(start=start, end=end - pd.Timedelta(nanoseconds=1), freq=freq)
def _interp_df_time(base_df: pd.DataFrame, target_times: pd.DatetimeIndex) -> np.ndarray:
"""
Time interpolation for real or complex DataFrame columns (vectorized over cols).
Returns ndarray shape (len(target_times), n_cols) with dtype float64 or complex128.
"""
base_index = pd.DatetimeIndex(base_df.index)
t0 = base_index.view("int64").astype(np.float64) / 1e9
t1 = pd.DatetimeIndex(target_times).view("int64").astype(np.float64) / 1e9
X0 = base_df.to_numpy()
is_complex = np.iscomplexobj(X0)
out = np.empty((len(t1), X0.shape[1]), dtype=np.complex128 if is_complex else np.float64)
order = np.argsort(t0)
t0s = t0[order]
X0s = X0[order, :]
for j in range(X0s.shape[1]):
col = X0s[:, j]
if is_complex:
out[:, j] = np.interp(t1, t0s, np.real(col)) + 1j * np.interp(t1, t0s, np.imag(col))
else:
out[:, j] = np.interp(t1, t0s, col.astype(np.float64))
return out
# ---------------------------------------------------------------------
# Default input configuration
# ---------------------------------------------------------------------
DEFAULT_INPUT_CONFIG: Dict[str, Dict] = {
"Radiational": {"degrees": [1, 2], "orders": {1: [1], 2: [1, 2]}},
"Gravitational": {"degrees": [2, 3], "orders": {2: [1, 2], 3: [1, 2, 3]}},
}
# ---------------------------------------------------------------------
# Forcing generation (COMPLEX) + OPTIONAL DISK CACHE
# ---------------------------------------------------------------------
class ForcingGenerator:
"""
Generate complex-valued gravitational/radiational input functions at a station.
Caching
-------
If use_cache=True, forcing is computed on a canonical UTC grid at cache_freq (default "6min"),
stored per-year, and later re-used and time-interpolated to the requested index.
Cache safety:
- Cache files are keyed by (lat, lon, ephemeris, input_config, complex_inputs, cache_freq).
- Changing any of these automatically uses a different cache key (no stale mixing).
"""
def __init__(
self,
lat: float,
lon: float,
*,
input_config: Optional[dict] = None,
ephemeris: str = "de421.bsp",
skyfield_cache: Optional[dict] = None,
# cache controls
use_cache: bool = False,
cache_dir: Optional[str] = None,
cache_freq: str = "6min",
cache_dtype: Union[str, np.dtype] = "float64",
cache_chunk: str = "year", # currently only "year" supported
):
if _SCIPY_IMPORT_ERROR is not None:
raise ImportError(
"ForcingGenerator requires SciPy (scipy.special.lpmv, scipy.special.eval_legendre). "
"Install with: pip install scipy"
) from _SCIPY_IMPORT_ERROR
self.lat = float(lat)
self.lon = float(lon)
self.input_config = dict(input_config) if input_config is not None else dict(DEFAULT_INPUT_CONFIG)
self.ephemeris = ephemeris
self._skyfield_cache = skyfield_cache if skyfield_cache is not None else {}
# Physical-ish constants (scaling consistency matters more than absolute)
self.M_E = 5.9722e24
self.M_M = 7.3e22
self.M_S = 1.989e30
self.E_r = 6371.01e3
self.solar_constant = 1.946 / 100
# cache configuration
self.use_cache_default = bool(use_cache)
self.cache_freq_default = str(cache_freq)
self.cache_chunk_default = str(cache_chunk)
self.cache_dtype_default = np.dtype(cache_dtype).name
if cache_dir is None:
cache_dir = os.path.join(os.path.expanduser("~"), ".cache", "response_method_forcing")
self.cache_dir_default = str(cache_dir)
_ensure_dir(self.cache_dir_default)
# diagnostic report from last compute_base() call
self.last_cache_report_: Optional[dict] = None
# ---------- public cache helpers ----------
def set_cache(
self,
*,
use_cache: Optional[bool] = None,
cache_dir: Optional[str] = None,
cache_freq: Optional[str] = None,
cache_dtype: Optional[Union[str, np.dtype]] = None,
cache_chunk: Optional[str] = None,
):
if use_cache is not None:
self.use_cache_default = bool(use_cache)
if cache_dir is not None:
self.cache_dir_default = str(cache_dir)
_ensure_dir(self.cache_dir_default)
if cache_freq is not None:
self.cache_freq_default = str(cache_freq)
if cache_dtype is not None:
self.cache_dtype_default = np.dtype(cache_dtype).name
if cache_chunk is not None:
self.cache_chunk_default = str(cache_chunk)
def clear_cache(self, *, years: Optional[Sequence[int]] = None, complex_inputs: Optional[bool] = None):
"""
Delete cache files for this generator configuration. If years is None, deletes all years.
If complex_inputs is None, deletes both complex and real cache variants.
"""
if years is not None:
years = [int(y) for y in years]
variants = []
if complex_inputs is None:
variants = [True, False]
else:
variants = [bool(complex_inputs)]
removed = 0
for cx in variants:
key = self._cache_key(complex_inputs=cx, cache_freq=self.cache_freq_default)
if years is None:
# delete all matching
for fn in os.listdir(self.cache_dir_default):
if fn.startswith(f"forcing_{key}_") and fn.endswith(".npz"):
try:
os.remove(os.path.join(self.cache_dir_default, fn))
removed += 1
except OSError:
pass
else:
for y in years:
path = self._cache_path(year=y, key=key)
if os.path.exists(path):
try:
os.remove(path)
removed += 1
except OSError:
pass
return removed
# ---------- skyfield ----------
def _get_skyfield(self):
if _SKYFIELD_IMPORT_ERROR is not None:
raise ImportError(
"Skyfield is required to generate forcing inputs. Install with: pip install skyfield"
) from _SKYFIELD_IMPORT_ERROR
if "tscale" not in self._skyfield_cache:
self._skyfield_cache["tscale"] = load.timescale()
if "planets" not in self._skyfield_cache:
self._skyfield_cache["planets"] = load(self.ephemeris)
return self._skyfield_cache["tscale"], self._skyfield_cache["planets"]
# ---------- spherical harmonics ----------
@staticmethod
def _norm_factor(degree: int, order: int) -> float:
from math import factorial, sqrt, pi
return sqrt(((2 * degree + 1) / (4 * pi)) * (factorial(degree - order) / factorial(degree + order)))
@classmethod
def spherical_harmonic_dir(cls, degree: int, order: int, theta_rad: np.ndarray, phi_rad: np.ndarray) -> np.ndarray:
"""
Complex spherical harmonic Y_degree^order(θ, φ) for directional angles:
- θ = colatitude (zenith angle)
- φ = azimuth (or longitude-like angle)
"""
degree = int(degree)
order = int(order)
if order < 0 or degree < 0 or order > degree:
raise ValueError("Require 0 <= order <= degree.")
mu = np.cos(theta_rad)
Plm = lpmv(order, degree, mu)
norm = cls._norm_factor(degree, order)
return norm * Plm * np.exp(1j * order * phi_rad)
# ---------- astro compute ----------
def _compute_astro(self, index: pd.DatetimeIndex) -> dict:
index = _to_datetime_index(index)
tscale, planets = self._get_skyfield()
times = tscale.from_datetimes(index.to_pydatetime())
earth = planets["earth"]
moon = planets["moon"]
sun = planets["sun"]
earth2moon = (moon.at(times) - earth.at(times)).distance().m
earth2sun = (sun.at(times) - earth.at(times)).distance().m
observer = earth + wgs84.latlon(self.lat, self.lon)
app_moon = observer.at(times).observe(moon).apparent()
alt_moon, az_moon, dist_moon = app_moon.altaz()
zenith_moon = 90.0 - alt_moon.degrees
app_sun = observer.at(times).observe(sun).apparent()
alt_sun, az_sun, dist_sun = app_sun.altaz()
zenith_sun = 90.0 - alt_sun.degrees
max_deg = 0
for it in ("Radiational", "Gravitational"):
max_deg = max(max_deg, max(self.input_config.get(it, {}).get("degrees", [0])))
mu_moon = cosd(zenith_moon)
mu_sun = cosd(zenith_sun)
solar_leg = {n: eval_legendre(n, mu_sun) for n in range(max_deg + 1)}
lunar_leg = {n: eval_legendre(n, mu_moon) for n in range(max_deg + 1)}
return {
"station2moon": dist_moon.m,
"station2sun": dist_sun.m,
"earth2moon": earth2moon,
"earth2sun": earth2sun,
"zenith_moon_deg": np.asarray(zenith_moon, dtype=float),
"zenith_sun_deg": np.asarray(zenith_sun, dtype=float),
"az_moon_deg": np.asarray(az_moon.degrees, dtype=float),
"az_sun_deg": np.asarray(az_sun.degrees, dtype=float),
"mu_moon": np.asarray(mu_moon, dtype=float),
"mu_sun": np.asarray(mu_sun, dtype=float),
"mean_r_moon": float(np.mean(earth2moon)),
"mean_r_sun": float(np.mean(earth2sun)),
"Solar_Legendre": solar_leg,
"Lunar_Legendre": lunar_leg,
}
# ---------- forcing pieces ----------
def radiational(self, degree: int, order: int, astro: dict) -> np.ndarray:
degree = int(degree)
order = int(order)
if degree > 2:
raise ValueError("Radiational currently implemented for degree <= 2.")
parallax = 1.0 / 23455.0
k_n = [1 / 4 + (1 / 6) * parallax, (1 / 2) + (3 / 8) * parallax, (5 / 16) + (1 / 3) * parallax]
k = k_n[degree]
zenith_sun = astro["zenith_sun_deg"]
az_sun = np.deg2rad(astro["az_sun_deg"])
theta_sun = np.deg2rad(zenith_sun)
station2sun = astro["station2sun"]
mean_r_sun = astro["mean_r_sun"]
Ydir = self.spherical_harmonic_dir(degree, order, theta_sun, az_sun)
amp = self.solar_constant * (mean_r_sun / station2sun) * k
rad = amp * Ydir
rad = np.asarray(rad, dtype=np.complex128)
rad[(zenith_sun >= 90.0) & (zenith_sun <= 180.0)] = 0.0
return rad
def gravitational(self, degree: int, order: int, astro: dict) -> np.ndarray:
degree = int(degree)
order = int(order)
if degree > 3:
raise ValueError("Gravitational currently implemented for degree <= 3.")
earth2moon = astro["earth2moon"]
earth2sun = astro["earth2sun"]
mean_r_moon = astro["mean_r_moon"]
mean_r_sun = astro["mean_r_sun"]
theta_m = np.deg2rad(astro["zenith_moon_deg"])
phi_m = np.deg2rad(astro["az_moon_deg"])
theta_s = np.deg2rad(astro["zenith_sun_deg"])
phi_s = np.deg2rad(astro["az_sun_deg"])
Y_moon = self.spherical_harmonic_dir(degree, order, theta_m, phi_m)
Y_sun = self.spherical_harmonic_dir(degree, order, theta_s, phi_s)
K_n_Moon = self.E_r * (self.M_M / self.M_E) * (self.E_r / earth2moon) ** (degree + 1)
K_n_Sun = self.E_r * (self.M_S / self.M_E) * (self.E_r / earth2sun) ** (degree + 1)
grav_Moon = K_n_Moon * (mean_r_moon / earth2moon) ** (degree + 1) * Y_moon
grav_Sun = K_n_Sun * (mean_r_sun / earth2sun) ** (degree + 1) * Y_sun
return np.asarray(grav_Moon + grav_Sun, dtype=np.complex128)
# ---------- caching internals ----------
def _cache_key(self, *, complex_inputs: bool, cache_freq: str) -> str:
payload = {
"v": 1,
"lat": float(self.lat),
"lon": float(self.lon),
"ephemeris": str(self.ephemeris),
"input_config": self.input_config,
"complex_inputs": bool(complex_inputs),
"cache_freq": str(cache_freq),
}
s = json.dumps(payload, sort_keys=True, default=str).encode("utf-8")
return hashlib.sha1(s).hexdigest()[:12]
def _cache_path(self, *, year: int, key: str) -> str:
return os.path.join(self.cache_dir_default, f"forcing_{key}_{int(year)}.npz")
def _load_year_cache(self, *, year: int, key: str, complex_inputs: bool) -> Optional[pd.DataFrame]:
path = self._cache_path(year=year, key=key)
if not os.path.exists(path):
return None
try:
z = np.load(path, allow_pickle=False)
cols = z["cols"].astype(str).tolist()
t_ns = z["t_ns"].astype(np.int64)
idx_utc = pd.to_datetime(t_ns, utc=True)
if complex_inputs:
xr = z["X_real"]
xi = z["X_imag"]
X = xr.astype(np.float64) + 1j * xi.astype(np.float64)
else:
X = z["X_real"].astype(np.float64)
return pd.DataFrame(X, index=idx_utc, columns=cols)
except Exception as e:
warnings.warn(f"Failed to load cache file {path!r} (will recompute): {e}")
return None
def _save_year_cache(
self,
*,
year: int,
key: str,
df_utc: pd.DataFrame,
complex_inputs: bool,
cache_dtype: np.dtype,
):
path = self._cache_path(year=year, key=key)
idx = pd.DatetimeIndex(df_utc.index)
if idx.tz is None:
raise ValueError("Internal error: cache DataFrame must be UTC tz-aware.")
if str(idx.tz) != "UTC":
idx = idx.tz_convert("UTC")
cols = np.asarray(df_utc.columns, dtype="U")
t_ns = idx.view("int64").astype(np.int64)
X = df_utc.to_numpy()
if complex_inputs:
xr = np.asarray(np.real(X), dtype=cache_dtype)
xi = np.asarray(np.imag(X), dtype=cache_dtype)
np.savez_compressed(path, t_ns=t_ns, cols=cols, X_real=xr, X_imag=xi)
else:
xr = np.asarray(X, dtype=cache_dtype)
np.savez_compressed(path, t_ns=t_ns, cols=cols, X_real=xr)
def _compute_base_uncached(self, index: pd.DatetimeIndex, *, complex_inputs: bool = True) -> pd.DataFrame:
"""Original forcing computation (no disk cache). Expects index tz-aware UTC (recommended)."""
index = _to_datetime_index(index)
astro = self._compute_astro(index)
cols: Dict[str, np.ndarray] = {}
for input_type, cfg in self.input_config.items():
degrees = cfg.get("degrees", [])
orders_map = cfg.get("orders", {})
if input_type not in ("Radiational", "Gravitational"):
continue
for deg in degrees:
for ord_ in orders_map.get(int(deg), []):
if input_type == "Radiational":
vals = self.radiational(deg, ord_, astro)
else:
vals = self.gravitational(deg, ord_, astro)
name = f"{input_type}_{int(deg)}_{int(ord_)}"
vals = np.asarray(vals)
cols[name] = vals.astype(np.complex128) if complex_inputs else np.real(vals).astype(np.float64)
return pd.DataFrame(cols, index=index)
# ---------- public forcing API ----------
def compute_base(
self,
index: pd.DatetimeIndex,
*,
complex_inputs: bool = True,
# cache controls (overrides defaults if not None)
use_cache: Optional[bool] = None,
cache_dir: Optional[str] = None,
cache_freq: Optional[str] = None,
cache_dtype: Optional[Union[str, np.dtype]] = None,
cache_chunk: Optional[str] = None,
force_recompute: bool = False,
validate_cache: bool = False,
validate_atol: float = 0.0,
validate_rtol: float = 0.0,
) -> pd.DataFrame:
"""
Return base forcing inputs on `index`.
If use_cache=True, uses disk cache (computes & stores missing years).
If force_recompute=True, recomputes even if cache exists (but can still write cache).
If validate_cache=True and use_cache=True, recomputes uncached and compares.
"""
idx_req = _to_datetime_index(index)
tz_in = idx_req.tz
idx_req_utc = _as_utc_index(idx_req)
# resolve cache options
if use_cache is None:
use_cache = self.use_cache_default
if cache_dir is not None:
self.cache_dir_default = str(cache_dir)
_ensure_dir(self.cache_dir_default)
if cache_freq is None:
cache_freq = self.cache_freq_default
if cache_dtype is None:
cache_dtype = np.dtype(self.cache_dtype_default)
else:
cache_dtype = np.dtype(cache_dtype)
if cache_chunk is None:
cache_chunk = self.cache_chunk_default
cache_chunk = str(cache_chunk).lower().strip()
if cache_chunk != "year":
raise ValueError("Only cache_chunk='year' is supported in this implementation.")
report = {
"use_cache": bool(use_cache),
"force_recompute": bool(force_recompute),
"cache_freq": str(cache_freq),
"cache_dtype": cache_dtype.name,
"cache_dir": str(self.cache_dir_default),
"complex_inputs": bool(complex_inputs),
"loaded_years": [],
"computed_years": [],
"validated": False,
"max_abs_diff": None,
}
if not use_cache:
df = self._compute_base_uncached(idx_req_utc, complex_inputs=complex_inputs)
out = df.copy()
out.index = _maybe_back_to_tz(pd.DatetimeIndex(out.index), tz_in)
self.last_cache_report_ = report
return out
key = self._cache_key(complex_inputs=complex_inputs, cache_freq=cache_freq)
years = np.unique(idx_req_utc.year)
pieces = []
for y in years:
df_y = None
if (not force_recompute):
df_y = self._load_year_cache(year=int(y), key=key, complex_inputs=complex_inputs)
if df_y is not None:
report["loaded_years"].append(int(y))
if df_y is None:
# compute this year on canonical UTC grid
start = pd.Timestamp(f"{int(y)}-01-01", tz="UTC")
end = pd.Timestamp(f"{int(y)+1}-01-01", tz="UTC")
grid_y = _date_range_inclusive_left(start, end, freq=str(cache_freq), tz="UTC")
df_y = self._compute_base_uncached(grid_y, complex_inputs=complex_inputs)
report["computed_years"].append(int(y))
# save cache
try:
self._save_year_cache(year=int(y), key=key, df_utc=df_y, complex_inputs=complex_inputs, cache_dtype=cache_dtype)
except Exception as e:
warnings.warn(f"Failed to write cache for year={y}: {e}")
pieces.append(df_y)
base_utc = pd.concat(pieces).sort_index()
# Return at requested times (interpolate if needed)
# We interpolate even if exact alignment holds; cheap and robust.
vals = _interp_df_time(base_utc, idx_req_utc)
out = pd.DataFrame(vals, index=idx_req_utc, columns=base_utc.columns)
out.index = _maybe_back_to_tz(pd.DatetimeIndex(out.index), tz_in)
if validate_cache:
df_unc = self._compute_base_uncached(idx_req_utc, complex_inputs=complex_inputs)
vals_unc = df_unc.to_numpy()
vals_cache = out.copy()
vals_cache.index = idx_req_utc # align instants for numeric compare
vals_cache = vals_cache.to_numpy()
diff = np.abs(vals_unc - vals_cache)
max_abs = float(np.nanmax(diff)) if diff.size else 0.0
report["validated"] = True
report["max_abs_diff"] = max_abs
if (validate_atol > 0) or (validate_rtol > 0):
denom = np.maximum(np.abs(vals_unc), 1.0)
ok = np.all(diff <= (validate_atol + validate_rtol * denom))
if not ok:
raise AssertionError(
f"Forcing cache validation failed: max_abs_diff={max_abs:.3e} "
f"(atol={validate_atol}, rtol={validate_rtol}). "
f"Try cache_dtype='float64' or set force_recompute=True to rebuild cache."
)
self.last_cache_report_ = report
return out
# ---------------------------------------------------------------------
# Design matrix
# ---------------------------------------------------------------------
@dataclass
class DesignMatrix:
X: np.ndarray
Y: np.ndarray
feature_names: List[str]
y_names: List[str]
index: pd.DatetimeIndex
linear_groups: Dict[str, List[int]]
x_scaler_mean: Optional[np.ndarray] = None
x_scaler_scale: Optional[np.ndarray] = None
# Trend embedding (linear-in-time admittance)
trend: bool = False
trend_t0: Optional[pd.Timestamp] = None
# Physical-covariate embedding (admittance varies with named covariates z_k(t))
covariate_names: Optional[List[str]] = None
covariate_means: Optional[Dict[str, float]] = None
# ---------------------------------------------------------------------
# Trend / time helpers
# ---------------------------------------------------------------------
#: Marker appended to a feature name to flag its time-trend (tau-interaction) copy.
TREND_SUFFIX = "::trend"
#: Prefix for markers that flag a physical-covariate interaction copy of a weight.
#: The companion column for covariate ``z_k`` is named ``<base>::cov:<name>`` and
#: carries ``z_k(t) * regressor``, so the response weight (and hence the admittance)
#: becomes ``w(t) = w0 + tau*w_trend + sum_k z_k(t)*w_k``.
COV_PREFIX = "::cov:"
def cov_suffix(name: str) -> str:
"""Feature-name suffix carrying the interaction with covariate ``name``."""
return COV_PREFIX + str(name)
#: Days in a (Julian) year; matches VTide's convention for cross-comparison.
DAYS_PER_YEAR = 365.2425
def _midpoint_timestamp(index: pd.DatetimeIndex) -> pd.Timestamp:
"""Midpoint instant of a DatetimeIndex (used as the trend reference epoch)."""
index = pd.DatetimeIndex(index)
return index[0] + (index[-1] - index[0]) / 2
def tau_years(index, t0) -> np.ndarray:
"""
Centered time coordinate in years relative to epoch ``t0``.
Uses Julian dates and a 365.2425-day year so that the response-method trend
is expressed on exactly the same time axis as VTide's linear amplitude model.
"""
index = pd.DatetimeIndex(index)
jd = index.to_julian_date().to_numpy().astype(np.float64)
jd0 = float(pd.Timestamp(t0).to_julian_date())
return (jd - jd0) / DAYS_PER_YEAR
def make_uniform_lags(steps: int, tau_hours: float, *, symmetrical: bool = False) -> List[float]:
steps = int(steps)
tau_hours = float(tau_hours)
lags = [-(s * tau_hours) for s in range(steps, 0, -1)] + [0.0]
if symmetrical:
lags += [(s * tau_hours) for s in range(1, steps + 1)]
return lags
def _interp_base_to_times(base_df: pd.DataFrame, target_times: pd.DatetimeIndex) -> np.ndarray:
"""Time interpolation for real or complex base_df columns."""
return _interp_df_time(base_df, target_times)
def build_design_matrix(
ts: pd.DataFrame,
*,
forcing_generator: Optional[ForcingGenerator] = None,
base_df: Optional[pd.DataFrame] = None,
lat: Optional[float] = None,
lon: Optional[float] = None,
input_config: Optional[dict] = None,
ephemeris: str = "de421.bsp",
y_cols: Optional[List[str]] = None,
lags_hours: Optional[Sequence[float]] = None,
uniform_lags: Optional[Tuple[int, float]] = None,
symmetrical: bool = False,
base_freq: str = "6min",
linear_inputs: Optional[List[str]] = None,
include_radiational: bool = True,
include_gravitational: bool = True,
complex_inputs: bool = True,
split_complex: bool = True,
bilinear: bool = False,
bilinear_pairs: Optional[List[Tuple[str, str]]] = None,
bilinear_lag_pairs: Optional[List[Tuple[float, float]]] = None,
bilinear_same_lag: bool = True,
add_constant: bool = True,
standardize_X: bool = True,
sample_weight: Union[str, np.ndarray, None] = None,
drop_constant_imag: bool = True,
imag_tol: float = 1e-12,
# linear-in-time trend embedding
trend: bool = False,
trend_t0=None,
# physical-covariate embedding: {name: per-timestamp series aligned to ts.index}
covariates: Optional[Dict[str, np.ndarray]] = None,
# forcing cache passthrough (all optional)
forcing_use_cache: Optional[bool] = None,
forcing_force_recompute: bool = False,
forcing_validate_cache: bool = False,
forcing_cache_dir: Optional[str] = None,
forcing_cache_freq: Optional[str] = None,
forcing_cache_dtype: Optional[Union[str, np.dtype]] = None,
forcing_validate_atol: float = 0.0,
forcing_validate_rtol: float = 0.0,
) -> Tuple[DesignMatrix, Optional[np.ndarray]]:
if not isinstance(ts.index, pd.DatetimeIndex):
raise ValueError("ts must have a DatetimeIndex")
index = pd.DatetimeIndex(ts.index)
# Linear-in-time trend basis: centered time in years (tau) at the reference epoch.
# Each lag-weight gets a companion regressor (tau * regressor) so the response
# weights -- and hence the admittance H(f) -- become w(t) = w0 + w1 * tau.
if trend:
if trend_t0 is None:
trend_t0 = _midpoint_timestamp(index)
trend_t0 = pd.Timestamp(trend_t0)
tau_full = tau_years(index, trend_t0)
else:
trend_t0 = None
tau_full = None
# Physical-covariate embedding. Each named covariate z_k(t) gets companion
# regressors z_k * regressor, so the response weights -- and hence the
# admittance H(f) -- become w(t) = w0 + sum_k z_k(t) * w_k. Covariates are
# centered to their record mean so H0(f) is the mean-state admittance and the
# recovered w_k are sensitivities per physical unit of z_k.
cov_centered: Dict[str, np.ndarray] = {}
cov_means: Dict[str, float] = {}
if covariates:
for name, arr in covariates.items():
a = np.asarray(arr, dtype=np.float64).ravel()
if a.shape[0] != len(index):
raise ValueError(
f"covariate {name!r} has length {a.shape[0]}, expected len(index)={len(index)}"
)
m = float(np.nanmean(a))
cov_centered[name] = a - m
cov_means[name] = m
cov_names = list(cov_centered.keys())
if y_cols is None:
if "observations" in ts.columns:
y_cols = ["observations"]
elif all(c in ts.columns for c in ["u", "v"]):
y_cols = ["u", "v"]
else:
raise ValueError("Could not infer y_cols; provide y_cols explicitly.")
y_cols = list(y_cols)
Y_raw = ts[y_cols].to_numpy()
if Y_raw.ndim == 1:
Y_raw = Y_raw.reshape(-1, 1)
if lags_hours is None:
if uniform_lags is None:
raise ValueError("Provide either lags_hours or uniform_lags=(steps,tau_hours)")
lags_hours = make_uniform_lags(uniform_lags[0], uniform_lags[1], symmetrical=symmetrical)
lags_hours = [float(x) for x in lags_hours]
# Build base_df on a regular grid for interpolation
if base_df is None:
if forcing_generator is None:
if lat is None or lon is None:
raise ValueError("Provide lat/lon or forcing_generator or base_df")
forcing_generator = ForcingGenerator(lat=lat, lon=lon, input_config=input_config, ephemeris=ephemeris)
min_lag = float(np.min(lags_hours))
max_lag = float(np.max(lags_hours))
start = (index.min() + pd.Timedelta(hours=min_lag)).floor(base_freq)
end = (index.max() + pd.Timedelta(hours=max_lag)).ceil(base_freq)
grid = pd.date_range(start=start, end=end, freq=base_freq, tz=index.tz)
base_df = forcing_generator.compute_base(
grid,
complex_inputs=complex_inputs,
use_cache=forcing_use_cache,
cache_dir=forcing_cache_dir,
cache_freq=forcing_cache_freq,
cache_dtype=forcing_cache_dtype,
force_recompute=forcing_force_recompute,
validate_cache=forcing_validate_cache,
validate_atol=forcing_validate_atol,
validate_rtol=forcing_validate_rtol,
)
# filter columns by type
keep_cols = []
for c in base_df.columns:
if (not include_radiational) and c.startswith("Radiational_"):
continue
if (not include_gravitational) and c.startswith("Gravitational_"):
continue
keep_cols.append(c)
base_df = base_df[keep_cols]
if linear_inputs is None:
linear_inputs = list(base_df.columns)
else:
missing = [c for c in linear_inputs if c not in base_df.columns]
if missing:
raise ValueError(f"linear_inputs missing from base_df: {missing}")
linear_inputs = list(linear_inputs)
base_col_to_j = {c: j for j, c in enumerate(base_df.columns)}
base_is_complex = np.iscomplexobj(base_df.to_numpy())
if complex_inputs and not base_is_complex:
raise ValueError("complex_inputs=True requires complex base_df (compute_base(complex_inputs=True)).")
if complex_inputs and not split_complex:
raise ValueError("This refactor expects split_complex=True when complex_inputs=True (real LS system).")
# interpolate all base columns for each lag
lag_to_vals: Dict[float, np.ndarray] = {}
for lag in lags_hours:
target_times = index + pd.Timedelta(hours=lag)
lag_to_vals[lag] = _interp_base_to_times(base_df, target_times)
feature_blocks: List[np.ndarray] = []
feature_names: List[str] = []
linear_groups: Dict[str, List[int]] = {}
def _append_real_col(col: np.ndarray, name: str, group_key: Optional[str] = None,
trendable: bool = True):
col = np.asarray(col, dtype=np.float64)
feature_blocks.append(col.reshape(-1, 1))
feature_names.append(name)
if group_key is not None:
linear_groups.setdefault(group_key, []).append(len(feature_names) - 1)
# Companion tau-interaction column => time-rate of this lag weight.
if trend and trendable:
feature_blocks.append((tau_full * col).reshape(-1, 1))
feature_names.append(name + TREND_SUFFIX)
if group_key is not None:
linear_groups.setdefault(group_key + TREND_SUFFIX, []).append(len(feature_names) - 1)
# Companion covariate-interaction columns => sensitivity of this lag weight
# to each physical covariate z_k.
if trendable and cov_names:
for cname in cov_names:
feature_blocks.append((cov_centered[cname] * col).reshape(-1, 1))
feature_names.append(name + cov_suffix(cname))
if group_key is not None:
linear_groups.setdefault(group_key + cov_suffix(cname), []).append(len(feature_names) - 1)
# linear terms
for c in linear_inputs:
j = base_col_to_j[c]
for lag in lags_hours:
col = lag_to_vals[lag][:, j]
if complex_inputs:
re = np.real(col)
im = np.imag(col)
_append_real_col(re, f"{c}_Re@{lag:.6g}h", group_key=f"{c}_Re")
if (not drop_constant_imag) or (np.nanmax(np.abs(im)) > imag_tol):
_append_real_col(im, f"{c}_Im@{lag:.6g}h", group_key=f"{c}_Im")
else:
_append_real_col(col, f"{c}@{lag:.6g}h", group_key=c)
# bilinear terms (optional)
if bilinear:
if bilinear_pairs is None:
bilinear_pairs = []
for i in range(len(linear_inputs)):
for j2 in range(i, len(linear_inputs)):
bilinear_pairs.append((linear_inputs[i], linear_inputs[j2]))
else:
bilinear_pairs = list(bilinear_pairs)
if bilinear_lag_pairs is None:
if bilinear_same_lag:
bilinear_lag_pairs = [(lag, lag) for lag in lags_hours]
else:
bilinear_lag_pairs = [(0.0, 0.0)]
else:
bilinear_lag_pairs = [(float(a), float(b)) for (a, b) in bilinear_lag_pairs]
for (c1, c2) in bilinear_pairs:
j1 = base_col_to_j[c1]
j2 = base_col_to_j[c2]
for (lag1, lag2) in bilinear_lag_pairs:
x1 = lag_to_vals[lag1][:, j1]
x2 = lag_to_vals[lag2][:, j2]
prod = x1 * x2
if complex_inputs:
_append_real_col(np.real(prod), f"{c1}*{c2}_Re@{lag1:.6g}h,{lag2:.6g}h", trendable=False)
_append_real_col(np.imag(prod), f"{c1}*{c2}_Im@{lag1:.6g}h,{lag2:.6g}h", trendable=False)
else:
_append_real_col(prod, f"{c1}*{c2}@{lag1:.6g}h,{lag2:.6g}h", trendable=False)
# constant (kept at index 0). With trend, a companion 'const::trend' column
# absorbs a linear mean-sea-level drift, analogous to VTide's trend term.
if add_constant:
front_blocks = [np.ones((len(index), 1), dtype=np.float64)]
front_names = ["const"]
if trend: