simons-forecasting 0.1.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. simons/__init__.py +10 -0
  2. simons/config.py +82 -0
  3. simons/covariates.py +338 -0
  4. simons/forecast.py +578 -0
  5. simons/model.py +696 -0
  6. simons/periodicity.py +188 -0
  7. simons/predictor.py +56 -0
  8. simons/synth/__init__.py +5 -0
  9. simons/synth/augment.py +143 -0
  10. simons/synth/base.py +448 -0
  11. simons/synth/calendar.py +157 -0
  12. simons/synth/causal.py +193 -0
  13. simons/synth/covariates/__init__.py +1 -0
  14. simons/synth/covariates/classical.py +637 -0
  15. simons/synth/covariates/effects.py +155 -0
  16. simons/synth/covariates/energy.py +528 -0
  17. simons/synth/covariates/families.py +296 -0
  18. simons/synth/covariates/generic.py +342 -0
  19. simons/synth/heavy.py +234 -0
  20. simons/synth/mech.py +636 -0
  21. simons/synth/multi.py +274 -0
  22. simons/synth/nonstat.py +204 -0
  23. simons/synth/observe.py +117 -0
  24. simons/training/__init__.py +1 -0
  25. simons/training/__main__.py +77 -0
  26. simons/training/augment.py +125 -0
  27. simons/training/clusters.py +215 -0
  28. simons/training/config.py +321 -0
  29. simons/training/covariates/__init__.py +1 -0
  30. simons/training/covariates/roles.py +370 -0
  31. simons/training/covariates/stream.py +243 -0
  32. simons/training/covariates/windows.py +239 -0
  33. simons/training/data.py +319 -0
  34. simons/training/distributed.py +124 -0
  35. simons/training/mixture.py +140 -0
  36. simons/training/network.py +115 -0
  37. simons/training/objective.py +193 -0
  38. simons/training/optim.py +164 -0
  39. simons/training/packing.py +94 -0
  40. simons/training/schedule.py +117 -0
  41. simons/training/soup.py +93 -0
  42. simons/training/stitching.py +50 -0
  43. simons/training/trainer.py +571 -0
  44. simons/training/warp.py +144 -0
  45. simons_forecasting-0.1.3.dist-info/METADATA +156 -0
  46. simons_forecasting-0.1.3.dist-info/RECORD +49 -0
  47. simons_forecasting-0.1.3.dist-info/WHEEL +4 -0
  48. simons_forecasting-0.1.3.dist-info/licenses/LICENSE +202 -0
  49. simons_forecasting-0.1.3.dist-info/licenses/NOTICE +57 -0
@@ -0,0 +1,155 @@
1
+ """Add generated covariate effects to corpus-series windows."""
2
+
3
+ import numpy as np
4
+
5
+ MAX_COV = 16
6
+ NONE_RELEVANT = 0.35
7
+ RELEVANT = 0.5
8
+
9
+
10
+ def smooth(x, k):
11
+ """Trailing mean of x over k steps (the first value held before the start)."""
12
+ if k <= 1:
13
+ return x
14
+ c = np.cumsum(np.pad(x, (k, 0), mode="edge"))
15
+ return (c[k:] - c[:-k]) / k
16
+
17
+
18
+ def log_uniform(rng, lo, hi):
19
+ """Log-uniform draw in [lo, hi]."""
20
+ return float(np.exp(rng.uniform(np.log(lo), np.log(hi))))
21
+
22
+
23
+ def base_window(base, rng, L):
24
+ """(window [L] float64, freq) of a random channel of `base.uni`: a random window, or the whole
25
+ channel left-padded with NaN when it is shorter than L."""
26
+ a, freq = base.uni[rng.integers(len(base.uni))]
27
+ if len(a) >= L:
28
+ s = rng.integers(0, len(a) - L + 1)
29
+ y0 = a[s:s + L].astype("float64")
30
+ else:
31
+ y0 = np.concatenate([np.full(L - len(a), np.nan), a]).astype("float64")
32
+ return y0, freq
33
+
34
+
35
+ def covariate_window(base, rng, L):
36
+ """A window [L] float64 of a random channel of `base.uni` as a covariate: left-padded with NaN
37
+ when short, then every NaN filled with the window's mean (0 when it has none)."""
38
+ b, _ = base.uni[rng.integers(len(base.uni))]
39
+ s0 = rng.integers(0, max(1, len(b) - L + 1))
40
+ x = b[s0:s0 + L].astype("float64")
41
+ if len(x) < L:
42
+ x = np.concatenate([np.full(L - len(x), np.nan), x])
43
+ return np.where(np.isfinite(x), x, np.nanmean(x) if np.isfinite(x).any() else 0.0)
44
+
45
+
46
+ def gen_covariate(kind, L, rng):
47
+ t = np.arange(L, dtype="float64")
48
+ if kind == "event":
49
+ if rng.random() < 0.5:
50
+ p = rng.choice([7, 12, 24, 52, 168, 30])
51
+ phase = rng.integers(p)
52
+ width = rng.integers(1, max(2, p // 4))
53
+ x = (((t + phase) % p) < width).astype(float)
54
+ else:
55
+ starts = rng.random(L) < rng.uniform(0.005, 0.08)
56
+ length = rng.integers(1, 15)
57
+ x = np.convolve(starts.astype(float), np.ones(length), mode="full")[:L].clip(0, 1)
58
+ return x
59
+ if kind == "smooth":
60
+ walk = np.cumsum(rng.normal(size=L)) * rng.uniform(0, 0.3)
61
+ p = rng.uniform(8, 400)
62
+ x = walk + np.sin(2 * np.pi * t / p + rng.uniform(0, 6.3)) * rng.uniform(0.5, 2)
63
+ return smooth(x + rng.normal(size=L) * rng.uniform(0, 0.5), int(rng.integers(1, 8)))
64
+ if kind == "step":
65
+ changes = rng.random(L) < rng.uniform(0.002, 0.03)
66
+ levels = rng.normal(size=changes.sum() + 1)
67
+ return levels[np.cumsum(changes)]
68
+ if kind == "calendar":
69
+ p = rng.choice([7, 24, 12, 52, 168, 96, 48])
70
+ if rng.random() < 0.5:
71
+ return np.sin(2 * np.pi * t / p + rng.uniform(0, 6.3))
72
+ return ((t + rng.integers(p)) % p) / p
73
+ raise ValueError(kind)
74
+
75
+
76
+ def effect(x, rng):
77
+ shape = rng.choice(["linear", "relu", "tanh", "square"], p=[0.5, 0.2, 0.2, 0.1])
78
+ z = (x - np.nanmean(x)) / (np.nanstd(x) + 1e-9)
79
+ if shape == "relu":
80
+ z = np.maximum(z - rng.normal(0, 0.5), 0)
81
+ elif shape == "tanh":
82
+ z = np.tanh(z * rng.uniform(0.5, 2))
83
+ elif shape == "square":
84
+ z = z ** 2
85
+ lag = int(rng.choice([0, 0, 0, 0, 1, 2, 3]))
86
+ if lag:
87
+ z = np.concatenate([np.full(lag, z[0]), z[:-lag]])
88
+ if rng.random() < 0.3:
89
+ k = rng.uniform(0.3, 0.9)
90
+ from scipy.signal import lfilter
91
+
92
+ z = lfilter([1.0], [1.0, -k], z) * (1 - k)
93
+ return z / (np.std(z) + 1e-9)
94
+
95
+
96
+ def synthetic(base, rng, hist: int, horizon: int):
97
+ """Return float32 (target [hist+horizon], covariates [C,hist+horizon]).
98
+ Draw a window from `base.uni`, a list of (values,freq) pairs."""
99
+ L = hist + horizon
100
+ y0, _ = base_window(base, rng, L)
101
+ hist_part = y0[:hist]
102
+ mu, sd = np.nanmean(hist_part), np.nanstd(hist_part)
103
+ if not np.isfinite(sd) or sd == 0:
104
+ sd = 1.0
105
+ if not np.isfinite(mu):
106
+ mu = 0.0
107
+ z0 = (y0 - mu) / sd
108
+ if rng.random() < 0.25:
109
+ z0 = z0 * rng.uniform(0, 0.3)
110
+ n = int(rng.integers(1, 7))
111
+ kinds = rng.choice(["event", "smooth", "step", "calendar", "forecast", "real"], size=n,
112
+ p=[0.25, 0.2, 0.12, 0.1, 0.13, 0.2])
113
+ none_relevant = rng.random() < NONE_RELEVANT
114
+ covs, total = [], np.zeros(L)
115
+ multiplicative = rng.random() < 0.2
116
+ pending_forecasts = 0
117
+ for kind in kinds:
118
+ if kind == "forecast":
119
+ pending_forecasts += 1
120
+ continue
121
+ if kind == "real":
122
+ x = covariate_window(base, rng, L)
123
+ else:
124
+ x = gen_covariate(kind, L, rng)
125
+ if not none_relevant and rng.random() < RELEVANT:
126
+ total += (effect(x, rng) * rng.choice([-1, 1])
127
+ * np.exp(rng.uniform(np.log(0.05), np.log(2.5))))
128
+ covs.append(x)
129
+ if multiplicative:
130
+ y = z0 + (np.abs(np.nan_to_num(z0)) + 1) * 0.5 * total
131
+ else:
132
+ y = z0 + total
133
+ y = y + rng.normal(size=L) * rng.uniform(0, 0.3)
134
+ for _ in range(pending_forecasts):
135
+ err = (smooth(rng.normal(size=L), int(rng.integers(1, 12))) * rng.uniform(0.05, 1.5)
136
+ * np.nanstd(y))
137
+ f = y + err
138
+ if rng.random() < 0.3:
139
+ f = f * rng.uniform(0.7, 1.3) + rng.normal() * np.nanstd(y)
140
+ covs.append(f)
141
+ if not covs:
142
+ covs.append(gen_covariate("calendar", L, rng))
143
+ rng.shuffle(covs)
144
+ covs = np.stack(covs)
145
+ for i in range(len(covs)):
146
+ if rng.random() < 0.15:
147
+ covs[i, hist:] = np.nan
148
+ if rng.random() < 0.1:
149
+ covs[i, rng.random(L) < rng.uniform(0, 0.1)] = np.nan
150
+ scale, offset = 10 ** rng.uniform(-2, 4), rng.normal() * 10 ** rng.uniform(-1, 4)
151
+ y = y * scale + offset
152
+ y[~np.isfinite(y0)] = np.nan
153
+ if rng.random() < 0.3:
154
+ covs = covs * 10 ** rng.uniform(-2, 3, size=(len(covs), 1))
155
+ return y.astype("float32"), covs.astype("float32")
@@ -0,0 +1,528 @@
1
+ """Energy targets driven by latent weather, with issued-forecast covariates."""
2
+
3
+ import numpy as np
4
+ from scipy.ndimage import uniform_filter1d
5
+ from scipy.signal import lfilter
6
+ from scipy.special import expit, ndtr
7
+
8
+ DEFAULT_CFG = {
9
+ "kinds": {"load": 0.35, "pv": 0.2, "wind": 0.2, "price": 0.15, "tariff": 0.1},
10
+ "spd": {24: 0.45, 48: 0.25, 96: 0.25, 288: 0.05},
11
+ }
12
+
13
+
14
+ def _ar1(rng, shape, phi, axis=-1):
15
+ """Draw stationary unit-variance AR(1) paths along `axis` with scalar coefficient phi."""
16
+ e = rng.standard_normal(shape)
17
+ phi = float(phi)
18
+ s = np.sqrt(max(1 - phi * phi, 1e-6))
19
+ idx = [slice(None)] * e.ndim
20
+ idx[axis] = 0
21
+ e[tuple(idx)] /= s
22
+ return lfilter([s], [1.0, -phi], e, axis=axis)
23
+
24
+
25
+ def _phi(phi_hour, spd):
26
+ return float(phi_hour) ** (24.0 / spd)
27
+
28
+
29
+ def _ewma(x, alpha):
30
+ y, _ = lfilter([alpha], [1.0, -(1 - alpha)], x, zi=[(1 - alpha) * x[0]])
31
+ return y
32
+
33
+
34
+ def _smooth(x, size):
35
+ size = int(size)
36
+ return x if size <= 1 else uniform_filter1d(x, size, mode="nearest")
37
+
38
+
39
+ def _u(rng, a, b):
40
+ return float(rng.uniform(a, b))
41
+
42
+
43
+ class Calendar:
44
+ def __init__(self, rng, L, spd):
45
+ self.L, self.spd = L, spd
46
+ self.t = np.arange(L)
47
+ off = int(rng.integers(spd))
48
+ tt = self.t + off
49
+ self.day = tt // spd
50
+ self.hour = (tt % spd) * (24.0 / spd)
51
+ doy0 = int(rng.integers(365))
52
+ self.doy = (doy0 + self.day) % 365
53
+ self.wday = (int(rng.integers(7)) + self.day) % 7
54
+ hol = rng.choice(365, size=int(rng.integers(0, 13)), replace=False)
55
+ self.holiday = np.isin(self.doy, hol)
56
+ self.dtype = np.where((self.wday == 6) | self.holiday, 2, np.where(self.wday == 5, 1, 0))
57
+ self.ndays = int(self.day[-1]) + 1
58
+ self.off = off
59
+
60
+
61
+ def _clear_sky(cal, lat):
62
+ decl = np.deg2rad(23.45) * np.sin(2 * np.pi * (284 + cal.doy) / 365.0)
63
+ omega = np.deg2rad(15.0 * (cal.hour + 0.5 * 24.0 / cal.spd - 12.0))
64
+ la = np.deg2rad(lat)
65
+ se = np.sin(la) * np.sin(decl) + np.cos(la) * np.cos(decl) * np.cos(omega)
66
+ se = np.clip(se, 0, None)
67
+ cs = np.where(se > 0.01, 1098.0 * se * np.exp(-0.057 / np.maximum(se, 0.01)), 0.0)
68
+ return cs, se
69
+
70
+
71
+ def _weibull(z, k, c):
72
+ u = np.clip(ndtr(z), 1e-9, 1 - 1e-9)
73
+ return c * (-np.log1p(-u)) ** (1.0 / k)
74
+
75
+
76
+ class Weather:
77
+ """Latent weather at one site (+ helpers to draw correlated sites)."""
78
+
79
+ def __init__(self, rng, cal):
80
+ L, spd = cal.L, cal.spd
81
+ self.cal = cal
82
+ lat = _u(rng, 25, 60) if rng.random() < 0.78 else _u(rng, -45, -10)
83
+ peak = 200 if lat > 0 else 20
84
+ seas = np.cos(2 * np.pi * (cal.doy + cal.hour / 24.0 - peak) / 365.0)
85
+ self.c_mean = rng.normal(0.4, 1.0)
86
+ self.c_gain = _u(rng, 1.5, 3.0)
87
+ self.c_phi = _u(rng, 0.85, 0.97)
88
+ zc = _ar1(rng, L, _phi(self.c_phi, spd)) + 0.4 * seas * rng.choice([-1, 1])
89
+ self.zc = zc
90
+ fast = _u(rng, 0.0, 0.8)
91
+ self.zc_fast = fast * _ar1(rng, L, _phi(_u(rng, 0.3, 0.8), spd))
92
+ self.cloud = expit(self.c_gain * (zc + self.zc_fast + self.c_mean))
93
+ self.cs, self.sin_elev = _clear_sky(cal, lat)
94
+ self.kc = 1 - 0.75 * self.cloud ** 3.4
95
+ self.ghi = self.cs * self.kc
96
+ Tm, Aa, Ad = _u(rng, -5, 25), _u(rng, 3, 13), _u(rng, 2, 8)
97
+ hpk = _u(rng, 13, 16)
98
+ diur = np.cos(2 * np.pi * (cal.hour - hpk) / 24.0) * (0.55 + 0.45 * (1 - self.cloud))
99
+ syn = _ar1(rng, L, _phi(_u(rng, 0.95, 0.99), spd)) * _u(rng, 2, 6)
100
+ self.T = Tm + Aa * seas + Ad * diur + syn
101
+ spread = (np.exp(_ar1(rng, L, _phi(0.99, spd)) * 0.4) * _u(rng, 2, 9)
102
+ * (0.6 + 0.4 * (1 - self.cloud)))
103
+ self.Td = self.T - spread
104
+ self.w_k, self.w_c = _u(rng, 1.6, 2.6), _u(rng, 5, 10)
105
+ ds, hw = _u(rng, 0, 0.3), _u(rng, 0, 24)
106
+ self.w_phi = _u(rng, 0.85, 0.97)
107
+ zw = _ar1(rng, L, _phi(self.w_phi, spd))
108
+ self.zw_diur = ds * np.cos(2 * np.pi * (cal.hour - hw) / 24.0) * 2
109
+ self.zw = (zw + self.zw_diur) / np.sqrt(1 + 2 * ds * ds)
110
+ self.ws = _weibull(self.zw, self.w_k, self.w_c)
111
+ theta0 = _u(rng, 0, 2 * np.pi)
112
+ self.theta = (theta0 + np.cumsum(rng.standard_normal(L)) * _u(rng, 0.02, 0.12)
113
+ * np.sqrt(24.0 / spd))
114
+
115
+ def cloud_sites(self, rng, n, rho):
116
+ """n cloud fields sharing this site's latent with correlation rho."""
117
+ zi = _ar1(rng, (n, self.cal.L), _phi(self.c_phi, self.cal.spd), axis=1)
118
+ zf = _ar1(rng, (n, self.cal.L), _phi(0.6, self.cal.spd), axis=1) * np.std(self.zc_fast)
119
+ z = rho * self.zc[None] + np.sqrt(1 - rho * rho) * zi + zf
120
+ return expit(self.c_gain * (z + self.c_mean))
121
+
122
+
123
+ class IssuePlan:
124
+ """Issue times and leads shared by all forecasts of one NWP/TSO product."""
125
+
126
+ def __init__(self, rng, cal, hist):
127
+ spd = cal.spd
128
+ self.cal, self.hist = cal, hist
129
+ L = cal.L
130
+ o = round(_u(rng, 6, 12) * spd / 24.0)
131
+ dd = 1 if rng.random() < 0.8 else 2
132
+ day = cal.day
133
+ issue_hist = (day - dd) * spd + o - cal.off
134
+ self.mode = "latest" if rng.random() < 0.6 else "archive"
135
+ t = cal.t
136
+ origin_day = cal.day[hist] if hist < L else cal.day[-1]
137
+ last_issue = (origin_day * spd + o - cal.off)
138
+ if last_issue > hist:
139
+ last_issue -= spd
140
+ issue = issue_hist.copy()
141
+ block = day
142
+ if self.mode == "latest":
143
+ issue[hist:] = last_issue
144
+ block = np.where(t >= hist, block.max() + 1, block)
145
+ self.lead = (t - issue).astype(float)
146
+ self.lead_h = self.lead * 24.0 / spd
147
+ self.block = block
148
+ self.nblocks = int(block.max()) + 1
149
+ self.timing = rng.random() < 0.5
150
+ self.delta = np.round(rng.normal(0, _u(rng, 0.5, 3), self.nblocks) * spd / 24.0).astype(int)
151
+ self.smooth = max(1, round(_u(rng, 1, 6) * spd / 24.0))
152
+ self.cut = None
153
+ if rng.random() < 0.1 and L - hist > 2:
154
+ self.cut = int(rng.integers(hist + 1, L))
155
+ self.actuals_hist = rng.random() < 0.15
156
+
157
+
158
+ def issue(x, plan, rng, rel_sd, diurnal=True, timing=False):
159
+ """An issued forecast of truth x under `plan`; rel_sd: day-ahead error sd / std(x)."""
160
+ cal = plan.cal
161
+ L, spd = cal.L, cal.spd
162
+ s = float(np.nanstd(x)) + 1e-9
163
+ xs = _smooth(x, plan.smooth if rng.random() < 0.8 else 1)
164
+ if timing and plan.timing:
165
+ idx = np.clip(cal.t - plan.delta[plan.block], 0, L - 1)
166
+ xs = xs[idx]
167
+ clim = _smooth(x, 7 * spd)
168
+ if diurnal:
169
+ hb = (cal.t + cal.off) % spd
170
+ prof = np.bincount(hb, weights=x - clim, minlength=spd) / np.maximum(
171
+ np.bincount(hb, minlength=spd), 1)
172
+ clim = clim + prof[hb]
173
+ rho0, rho1 = _u(rng, 0.8, 1.0), _u(rng, 0.0, 0.12)
174
+ rho = np.clip(rho0 - rho1 * plan.lead_h / 24.0, 0.25, 1.0)
175
+ f = clim + rho * (xs - clim)
176
+ if diurnal and rng.random() < 0.6:
177
+ f = f - _u(rng, 0, 0.3) * prof[hb]
178
+ f = f + rng.normal(0, 0.15) * s
179
+ phi = _phi(_u(rng, 0.8, 0.98), spd)
180
+ e = _ar1(rng, L, phi)
181
+ starts = np.r_[True, plan.block[1:] != plan.block[:-1]]
182
+ if starts.sum() > 1:
183
+ e2 = rng.standard_normal(plan.nblocks)
184
+ e = np.sqrt(0.5) * e + np.sqrt(0.5) * e2[plan.block]
185
+ if rng.random() < 0.3:
186
+ g = rng.chisquare(3, plan.nblocks) / 3.0
187
+ e = e / np.sqrt(g[plan.block]) * np.sqrt(1 / 3.0)
188
+ kappa = _u(rng, 0, 1.5)
189
+ sd = rel_sd * np.sqrt(1 + kappa * np.clip(plan.lead_h - 24, 0, None) / 24.0)
190
+ f = f + sd * s * e
191
+ if rng.random() < 0.1:
192
+ k = int(rng.integers(1, L))
193
+ f[k:] = f[k:] * _u(rng, 0.9, 1.1) + rng.normal(0, 0.1) * s
194
+ if plan.actuals_hist:
195
+ f[: plan.hist] = x[: plan.hist]
196
+ if plan.cut is not None:
197
+ f[plan.cut:] = np.nan
198
+ return f
199
+
200
+
201
+ class WeatherForecast:
202
+ """Issued forecasts of a Weather's variables under one plan (physically consistent)."""
203
+
204
+ def __init__(self, W, plan, rng):
205
+ q = _u(rng, 0.5, 1.6)
206
+ self.T = issue(W.T, plan, rng, 0.25 * q)
207
+ self.Td = issue(W.Td, plan, rng, 0.3 * q)
208
+ zc = issue(W.zc, plan, rng, 0.35 * q, diurnal=False, timing=True)
209
+ self.cloud = expit(W.c_gain * (zc + W.c_mean))
210
+ self.ghi = W.cs * (1 - 0.75 * self.cloud ** 3.4)
211
+ zw = issue(W.zw, plan, rng, 0.5 * q, diurnal=False, timing=True)
212
+ self.ws = _weibull(zw, W.w_k, W.w_c)
213
+ self.theta = (W.theta + rng.normal(0, 0.3)
214
+ + _ar1(rng, W.cal.L, _phi(0.95, W.cal.spd)) * 0.2 * q)
215
+ for v in ("T", "Td", "cloud", "ghi", "ws", "theta"):
216
+ a = getattr(self, v)
217
+ if plan.cut is not None:
218
+ a[plan.cut:] = np.nan
219
+
220
+
221
+ def _daily_profile(rng, spd):
222
+ K = int(rng.integers(2, 5))
223
+ h = np.arange(spd) * 2 * np.pi / spd
224
+ p = np.zeros(spd)
225
+ for k in range(1, K + 1):
226
+ p += rng.normal(0, 1.0 / k) * np.cos(k * h + _u(rng, 0, 2 * np.pi))
227
+ p += _u(rng, 0.5, 1.5) * -np.cos(h - _u(rng, -0.6, 0.6))
228
+ return (p - p.mean()) / (p.std() + 1e-9)
229
+
230
+
231
+ class LoadModel:
232
+ def __init__(self, rng, cal):
233
+ spd = cal.spd
234
+ self.cal = cal
235
+ prof = np.stack([_daily_profile(rng, spd) for _ in range(3)])
236
+ prof[1] = 0.6 * prof[0] + 0.4 * prof[1]
237
+ prof[2] = 0.5 * prof[0] + 0.5 * prof[2]
238
+ amp = _u(rng, 0.1, 0.35)
239
+ lev = np.array([1.0, _u(rng, 0.8, 0.97), _u(rng, 0.7, 0.93)])
240
+ hb = (cal.t + cal.off) % spd
241
+ shape = lev[cal.dtype] * (1 + amp * prof[cal.dtype, hb])
242
+ self.occ = np.tanh(prof[0, hb])
243
+ trend = 1 + rng.normal(0, 0.05) * cal.t / cal.L
244
+ self.base = shape * trend * (1 + _u(rng, 0, 0.08) * rng.choice([-1, 1]) * np.cos(
245
+ 2 * np.pi * (cal.doy - 15) / 365.0))
246
+ self.alpha = 1 - 0.5 ** (1.0 / (np.exp(_u(rng, np.log(1), np.log(24))) * spd / 24.0))
247
+ self.lo = _u(rng, 12, 18)
248
+ self.hi = self.lo + _u(rng, 0, 6)
249
+ heat_cool = rng.random()
250
+ self.bh = _u(rng, 0.01, 0.06) * (heat_cool > 0.15)
251
+ self.bc = _u(rng, 0.01, 0.1) * (heat_cool < 0.85)
252
+ self.pc = _u(rng, 1.0, 1.5)
253
+ self.hmod = _u(rng, 0, 0.6)
254
+ self.hum = _u(rng, 0, 0.5) if rng.random() < 0.5 else 0.0
255
+ self.light = _u(rng, 0, 0.05) if rng.random() < 0.5 else 0.0
256
+ self.season_mod = _u(rng, 0, 0.3)
257
+
258
+ def __call__(self, T, Td, ghi, cs):
259
+ Ts = _ewma(np.nan_to_num(T, nan=np.nanmean(T)), self.alpha)
260
+ hdd = np.maximum(self.lo - Ts, 0)
261
+ Te = Ts + self.hum * np.maximum(np.nan_to_num(Td, nan=0.0) - 12, 0) * 0.5
262
+ cdd = np.maximum(Te - self.hi, 0) ** self.pc
263
+ hm = 1 + self.hmod * self.occ
264
+ resp = hm * (self.bh * hdd + self.bc * cdd)
265
+ if self.light:
266
+ dark = 1 - np.clip(np.nan_to_num(ghi) / np.maximum(cs.max(), 1), 0, 1)
267
+ resp = resp + self.light * dark * (self.occ > -0.3)
268
+ return self.base * (1 + resp)
269
+
270
+
271
+ class PVModel:
272
+ def __init__(self, rng, W):
273
+ self.W = W
274
+ self.gamma = -_u(rng, 0.003, 0.0045)
275
+ self.kT = _u(rng, 20, 35) / 1000.0
276
+ self.dcac = _u(rng, 1.1, 1.4)
277
+ self.tilt = _u(rng, 0, 0.4)
278
+ self.eta = _u(rng, 0.9, 0.97)
279
+ self.nsites = 1 if rng.random() < 0.6 else int(rng.integers(2, 9))
280
+ self.rho = _u(rng, 0.5, 0.95)
281
+ cal = W.cal
282
+ self.curtail = np.ones(cal.L)
283
+ if rng.random() < 0.15:
284
+ days = rng.random(cal.ndays) < _u(rng, 0.05, 0.4)
285
+ mid = (cal.hour > _u(rng, 9, 11)) & (cal.hour < _u(rng, 13, 16))
286
+ self.curtail = np.where(days[cal.day] & mid, _u(rng, 0.3, 0.8), 1.0)
287
+ self.soil = 1 - (_u(rng, 0, 0.08) * (cal.t % int(rng.integers(cal.spd * 5, cal.spd * 40)))
288
+ / (cal.spd * 40))
289
+
290
+ def power(self, cloud, T):
291
+ W = self.W
292
+ k = 1 - 0.75 * np.clip(cloud, 0, 1) ** 3.4
293
+ poa = W.cs * k * (1 + self.tilt * (1 - W.sin_elev)) * (W.sin_elev > 0.02)
294
+ Tc = np.nan_to_num(T, nan=np.nanmean(T)) + self.kT * poa
295
+ pdc = poa / 1000.0 * (1 + self.gamma * (Tc - 25))
296
+ pac = np.minimum(pdc * self.dcac * self.eta, 1.0)
297
+ if pac.ndim == 2:
298
+ pac = pac.mean(0)
299
+ return np.clip(pac, 0, None) * self.soil
300
+
301
+ def truth_clouds(self, rng):
302
+ if self.nsites == 1:
303
+ return self.W.cloud
304
+ return self.W.cloud_sites(rng, self.nsites, self.rho)
305
+
306
+ def __call__(self, cloud, T, truth=True):
307
+ p = self.power(cloud, T)
308
+ return p * self.curtail if truth else p
309
+
310
+
311
+ _GH_X, _GH_W = np.polynomial.hermite_e.hermegauss(7)
312
+ _GH_W = _GH_W / _GH_W.sum()
313
+
314
+
315
+ class WindModel:
316
+ def __init__(self, rng, W):
317
+ self.W = W
318
+ self.ci, self.rated = _u(rng, 2.5, 4), _u(rng, 10, 14)
319
+ self.co = _u(rng, 20, 25)
320
+ self.sig0, self.sig1 = _u(rng, 0.4, 0.8), _u(rng, 0.1, 0.25)
321
+ self.wake = _u(rng, 0, 0.2)
322
+ self.theta0 = _u(rng, 0, np.pi)
323
+ self.shear = _u(rng, 0.8, 1.25)
324
+ cal = W.cal
325
+ changes = rng.random(cal.L) < _u(rng, 0.0005, 0.005)
326
+ levels = np.clip(1 - np.abs(rng.normal(0, 0.06, changes.sum() + 1)), 0.6, 1)
327
+ self.avail = levels[np.cumsum(changes)]
328
+ self.cap = np.ones(cal.L)
329
+ if rng.random() < 0.1:
330
+ blocks = rng.random(cal.ndays) < 0.1
331
+ self.cap = np.where(blocks[cal.day], _u(rng, 0.3, 0.8), 1.0)
332
+
333
+ def curve(self, v):
334
+ mid, s = (self.ci + self.rated) / 2, (self.rated - self.ci) / 7.0
335
+ p = expit((v - mid) / s)
336
+ p = np.where(v < self.ci, 0.0, p)
337
+ return np.clip((p - expit((self.ci - mid) / s))
338
+ / (expit((self.rated - mid) / s) - expit((self.ci - mid) / s)), 0, 1)
339
+
340
+ def __call__(self, ws, theta, truth=True):
341
+ v = np.nan_to_num(ws, nan=np.nanmean(ws)) * self.shear
342
+ sig = self.sig0 + self.sig1 * v
343
+ vv = v[:, None] + sig[:, None] * _GH_X[None]
344
+ p = (self.curve(np.clip(vv, 0, None)) * _GH_W).sum(1)
345
+ ev = np.where(v > self.co, 1, np.where(v < self.co - 3, -1, 0))
346
+ idx = np.where(ev != 0, np.arange(len(v)), 0)
347
+ np.maximum.accumulate(idx, out=idx)
348
+ state = ev[idx] == 1
349
+ p = np.where(state, 0.0, p)
350
+ p = p * (1 - self.wake * np.cos(np.nan_to_num(theta) - self.theta0) ** 2)
351
+ if truth:
352
+ p = p * self.avail * self.cap
353
+ return p
354
+
355
+
356
+ def _cfg(cfg):
357
+ out = {**DEFAULT_CFG, **(cfg or {})}
358
+ out["kinds"] = {**DEFAULT_CFG["kinds"], **((cfg or {}).get("kinds") or {})}
359
+ return out
360
+
361
+
362
+ def _tso_forecast(rng, truth_fn_value, y_true, plan):
363
+ """Evaluate target response on forecast drivers with smooth error shared across issues."""
364
+ s = float(np.nanstd(y_true)) + 1e-9
365
+ e = _ar1(rng, len(y_true), _phi(_u(rng, 0.8, 0.98), plan.cal.spd))
366
+ f = truth_fn_value + _u(rng, 0.02, 0.25) * s * e + rng.normal(0, 0.05) * s
367
+ if plan.actuals_hist:
368
+ f[: plan.hist] = y_true[: plan.hist]
369
+ if plan.cut is not None:
370
+ f[plan.cut:] = np.nan
371
+ return f
372
+
373
+
374
+ def sample(base, rng, hist: int, horizon: int, cfg=None):
375
+ """Return float32 (target [hist+horizon], covariates [C,hist+horizon]); NaN marks gaps.
376
+ `cfg` overrides DEFAULT_CFG and merges `kinds` by key; `base` is unused."""
377
+ c = _cfg(cfg)
378
+ L = hist + horizon
379
+ kinds = list(c["kinds"])
380
+ kp = np.array([c["kinds"][k] for k in kinds], float)
381
+ kind = kinds[rng.choice(len(kinds), p=kp / kp.sum())]
382
+ spds = list(c["spd"])
383
+ sp = np.array([c["spd"][k] for k in spds], float)
384
+ spd = int(spds[rng.choice(len(spds), p=sp / sp.sum())])
385
+ cal = Calendar(rng, L, spd)
386
+ W = Weather(rng, cal)
387
+ plan = IssuePlan(rng, cal, hist)
388
+ Wf = WeatherForecast(W, plan, rng)
389
+ covs = []
390
+ noise_sd = _u(rng, 0.005, 0.03)
391
+ tso = rng.random() < 0.3
392
+ want = int(rng.choice([1, 2, 3], p=[0.35, 0.4, 0.25]))
393
+
394
+ def obs_noise(n):
395
+ return _ar1(rng, n, _phi(_u(rng, 0.3, 0.9), spd))
396
+
397
+ temp_f = rng.random() < 0.15
398
+ def T_out(a):
399
+ return a * 1.8 + 32 if temp_f else a
400
+
401
+ if kind == "load":
402
+ lm = LoadModel(rng, cal)
403
+ net = rng.random() < 0.3
404
+ y = lm(W.T, W.Td, W.ghi, W.cs)
405
+ yf = lm(Wf.T, Wf.Td, Wf.ghi, W.cs)
406
+ if net:
407
+ pv = PVModel(rng, W)
408
+ share = _u(rng, 0.05, 0.4)
409
+ y = y - share * pv(pv.truth_clouds(rng), W.T)
410
+ yf = yf - share * pv(Wf.cloud, Wf.T, truth=False)
411
+ y = y * (1 + noise_sd * obs_noise(L))
412
+ opts = [T_out(Wf.T), T_out(Wf.Td), Wf.ghi, 100 * Wf.cloud]
413
+ order = [0, *rng.permutation([1, 2, 3])]
414
+ if net: # Embedded PV makes irradiance relevant, so prefer it second.
415
+ order = [0, 2, 1, 3] if rng.random() < 0.7 else order
416
+ for i in order[:want]:
417
+ covs.append(opts[i])
418
+ scale = 10 ** _u(rng, 0.5, 4)
419
+ elif kind == "pv":
420
+ pm = PVModel(rng, W)
421
+ y = pm(pm.truth_clouds(rng), W.T)
422
+ yf = pm(Wf.cloud, Wf.T, truth=False)
423
+ y = np.clip(y + noise_sd * 0.3 * obs_noise(L) * (W.cs > 0), 0, None)
424
+ opts = [Wf.ghi, 100 * Wf.cloud, T_out(Wf.T)]
425
+ order = [0, 1, 2] if rng.random() < 0.7 else [1, 0, 2]
426
+ for i in order[:want]:
427
+ covs.append(opts[i])
428
+ scale = 10 ** _u(rng, 0.5, 4)
429
+ elif kind == "wind":
430
+ wm = WindModel(rng, W)
431
+ y = wm(W.ws, W.theta)
432
+ yf = wm(Wf.ws, Wf.theta, truth=False)
433
+ y = np.clip(y + noise_sd * obs_noise(L), 0, None)
434
+ u, v = -Wf.ws * np.sin(Wf.theta), -Wf.ws * np.cos(Wf.theta)
435
+ if rng.random() < 0.5:
436
+ opts = [Wf.ws, u, v]
437
+ else:
438
+ opts = [Wf.ws, np.degrees(np.mod(Wf.theta, 2 * np.pi)), T_out(Wf.T)]
439
+ for i in range(want):
440
+ covs.append(opts[i])
441
+ scale = 10 ** _u(rng, 0.5, 4)
442
+ elif kind == "price":
443
+ lm = LoadModel(rng, cal)
444
+ pm, wm = PVModel(rng, W), WindModel(rng, W)
445
+ ws_share, pv_share = _u(rng, 0, 0.6), _u(rng, 0, 0.4)
446
+ load, load_f = lm(W.T, W.Td, W.ghi, W.cs), lm(Wf.T, Wf.Td, Wf.ghi, W.cs)
447
+ wind, wind_f = wm(W.ws, W.theta), wm(Wf.ws, Wf.theta, truth=False)
448
+ pv, pv_f = pm(pm.truth_clouds(rng), W.T), pm(Wf.cloud, Wf.T, truth=False)
449
+ R = load - ws_share * wind - pv_share * pv
450
+ Rf = load_f - ws_share * wind_f - pv_share * pv_f
451
+ Rmax = float(np.quantile(R, 0.99)) + 1e-6
452
+ Rmin = float(np.quantile(R, 0.01))
453
+ kappa = _u(rng, 1, 4)
454
+ a0, b = _u(rng, 0, 60), _u(rng, 10, 80)
455
+ fuel = np.exp(np.cumsum(rng.normal(0, _u(rng, 0, 0.03), cal.ndays))[cal.day])
456
+
457
+ def stack(Rx):
458
+ z = (Rx - Rmin) / max(Rmax - Rmin, 1e-6)
459
+ return fuel * (a0 + b * np.expm1(kappa * z) / np.expm1(kappa))
460
+
461
+ y = stack(R)
462
+ yf = stack(Rf)
463
+ capq = float(np.quantile(R, _u(rng, 0.95, 0.995)))
464
+ over = np.clip((R - capq) / max(Rmax - capq, 1e-6), 0, None)
465
+ spikes = (R > capq) & (rng.random(L) < _u(rng, 0.05, 0.5))
466
+ y = y + spikes * (0.3 + over) * np.exp(rng.normal(np.log(_u(rng, 0.5, 5) * b), 0.5, L))
467
+ if rng.random() < 0.4:
468
+ lowq = float(np.quantile(R, _u(rng, 0.01, 0.1)))
469
+ floor = -_u(rng, 0, 60)
470
+ y = np.where(R < lowq, np.minimum(y, floor + (y - floor) * _u(rng, 0, 0.3)), y)
471
+ y = y + _u(rng, 0.01, 0.08) * np.nanstd(y) * obs_noise(L)
472
+ opts = [load_f, ws_share * wind_f + pv_share * pv_f, Rf, ws_share * wind_f,
473
+ pv_share * pv_f]
474
+ choice = [[0], [0, 1], [0, 3, 4], [2], [0, 1, 2]][
475
+ int(rng.choice(5, p=[0.3, 0.3, 0.2, 0.1, 0.1]))]
476
+ for i in choice:
477
+ scl = 10 ** _u(rng, 2, 4)
478
+ covs.append(opts[i] * scl)
479
+ scale = 1.0
480
+ else:
481
+ lm = LoadModel(rng, cal)
482
+ bl = lm(W.T, W.Td, W.ghi, W.cs)
483
+ blf = lm(Wf.T, Wf.Td, Wf.ghi, W.cs)
484
+ hours = cal.hour
485
+ ev_day = rng.random(cal.ndays) < _u(rng, 0.1, 0.5)
486
+ h0, dur = _u(rng, 16, 19), _u(rng, 2, 5)
487
+ high = ev_day[cal.day] & (hours >= h0) & (hours < h0 + dur)
488
+ low_day = rng.random(cal.ndays) < _u(rng, 0.0, 0.4)
489
+ l0 = _u(rng, 0, 6)
490
+ low = low_day[cal.day] & (hours >= l0) & (hours < l0 + _u(rng, 2, 6)) & ~high
491
+ eh, el = -_u(rng, 0.05, 0.4), _u(rng, 0.0, 0.3)
492
+ r = eh * high + el * low
493
+ k = _u(rng, 0.5, 0.95) ** (24.0 / spd)
494
+ deferred = -eh * high
495
+ reb = _u(rng, 0, 1) * lfilter([1 - k], [1, -k], deferred) * ~high
496
+ y = bl * (1 + r + reb)
497
+ yf = blf * (1 + r + reb)
498
+ y = y * (1 + _u(rng, 0.01, 0.05) * obs_noise(L))
499
+ covs += [high.astype(float), low.astype(float)]
500
+ if rng.random() < 0.4:
501
+ covs.append(T_out(Wf.T))
502
+ scale = 10 ** _u(rng, 0.5, 4)
503
+ if tso:
504
+ tf = _tso_forecast(rng, yf, y, plan)
505
+ covs.append(tf * scale if rng.random() < 0.85 else tf)
506
+ if rng.random() < 0.5:
507
+ for _ in range(int(rng.integers(1, 3))):
508
+ if rng.random() < 0.5:
509
+ W2 = Weather(rng, cal)
510
+ covs.append(issue(W2.T, plan, rng, 0.3))
511
+ else:
512
+ p = rng.choice([spd, 7 * spd, spd // 2])
513
+ covs.append(np.sin(2 * np.pi * cal.t / p + _u(rng, 0, 6.3)))
514
+ covs = np.stack(covs).astype("float64")
515
+ y = y * scale
516
+ for i in range(len(covs)):
517
+ r = rng.random()
518
+ if r < 0.1:
519
+ covs[i, hist:] = np.nan
520
+ elif r < 0.35 and hist > 64:
521
+ covs[i, : int(rng.integers(0, hist - 32))] = np.nan
522
+ if rng.random() < 0.1:
523
+ covs[i, rng.random(L) < _u(rng, 0, 0.1)] = np.nan
524
+ if rng.random() < 0.05:
525
+ y[rng.random(L) < _u(rng, 0, 0.05)] = np.nan
526
+ covs = covs[rng.permutation(len(covs))]
527
+ return y.astype("float32"), covs.astype("float32")
528
+