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
simons/synth/base.py ADDED
@@ -0,0 +1,448 @@
1
+ """Generate synthetic series on device and mix them into training batches."""
2
+
3
+ import math
4
+
5
+ import numpy as np
6
+ import torch
7
+ import torch.nn.functional as F
8
+
9
+ PERIOD_BANK = (4, 6, 7, 10, 12, 14, 24, 26, 30, 40, 48, 52, 60, 96, 168, 288, 336, 365, 672, 730)
10
+ SEASON_BANK = (4, 6, 7, 10, 12, 14, 24, 26, 30, 48, 52, 60, 96, 168, 288, 336, 365)
11
+ MULTIPLES = (2, 4, 7, 12, 24, 52)
12
+ SYNTHETIC_ID = 1_000_000
13
+
14
+
15
+ def _u(gen, shape, lo=0.0, hi=1.0, device="cpu"):
16
+ return torch.rand(shape, generator=gen, device=device) * (hi - lo) + lo
17
+
18
+
19
+ def _logu(gen, shape, lo, hi, device):
20
+ return torch.exp(_u(gen, shape, math.log(lo), math.log(hi), device))
21
+
22
+
23
+ def _randn(gen, shape, device):
24
+ return torch.randn(shape, generator=gen, device=device)
25
+
26
+
27
+ _BANKS = {}
28
+
29
+
30
+ def _bank(values, device):
31
+ """Cache device copies to avoid blocking host-to-device copies on each step."""
32
+ key = (values, str(device))
33
+ if key not in _BANKS:
34
+ _BANKS[key] = torch.tensor(values, dtype=torch.float32, device=device)
35
+ return _BANKS[key]
36
+
37
+
38
+ def _choice(gen, values, shape, device):
39
+ bank = _bank(values, device)
40
+ return bank[torch.randint(len(values), shape, generator=gen, device=device)]
41
+
42
+
43
+ def _categorical(gen, probabilities, n, device):
44
+ edges = _bank(tuple(float(x) for x in torch.tensor(probabilities).cumsum(0)[:-1]), device)
45
+ return (_u(gen, (n, 1), device=device) > edges).sum(-1)
46
+
47
+
48
+ def _standardise(x):
49
+ x = x - x.mean(-1, keepdim=True)
50
+ return x / x.std(-1, keepdim=True).clamp_min(1e-6)
51
+
52
+
53
+ def _periods(gen, n, device):
54
+ bank = _choice(gen, PERIOD_BANK, (n,), device)
55
+ free = _logu(gen, (n,), 2.0, 700.0, device)
56
+ return torch.where(_u(gen, (n,), device=device) < 0.6, bank, free)
57
+
58
+
59
+ def _periodic(gen, period, length, device, harmonics=12):
60
+ """Draw Fourier series with min(12, p/2) harmonics and Gaussian-decaying variance."""
61
+ n = period.shape[0]
62
+ k = torch.arange(1, harmonics + 1, device=device, dtype=torch.float32)
63
+ smooth = _u(gen, (n, 1), 1.0, 6.0, device)
64
+ var = torch.exp(-(k**2) / (2 * smooth**2)) * (k[None] <= (period[:, None] / 2).floor())
65
+ a = torch.randn((n, harmonics), generator=gen, device=device) * var.sqrt()
66
+ b = torch.randn((n, harmonics), generator=gen, device=device) * var.sqrt()
67
+ t = torch.arange(length, device=device, dtype=torch.float32)
68
+ phase = 2 * math.pi * torch.remainder(t[None, None] * k[None, :, None]
69
+ / period[:, None, None], 1)
70
+ x = (a[..., None] * phase.cos() + b[..., None] * phase.sin()).sum(1)
71
+ return _standardise(x)
72
+
73
+
74
+ def _spectral(gen, length, device, spectrum):
75
+ """Sample a stationary path with power spectrum `spectrum(omega)` [n,L+1] on a 2L grid."""
76
+ grid = 2 * length
77
+ omega = 2 * math.pi * torch.arange(grid // 2 + 1, device=device, dtype=torch.float32) / grid
78
+ amp = spectrum(omega).clamp_min(0).sqrt()
79
+ amp[:, 0] = 0
80
+ xi = torch.complex(
81
+ torch.randn(amp.shape, generator=gen, device=device),
82
+ torch.randn(amp.shape, generator=gen, device=device),
83
+ )
84
+ return _standardise(torch.fft.irfft(amp * xi, n=grid)[:, :length])
85
+
86
+
87
+ def _smooth(gen, n, length, device):
88
+ """Sample an RBF or Matern GP with nu in {0.5, 1.5, 2.5}; nu=0.5 gives OU paths."""
89
+ scale = _logu(gen, (n, 1), 0.003, 1.0, device) * length
90
+ nu = _choice(gen, (0.5, 1.5, 2.5, 100.0), (n, 1), device)
91
+
92
+ def spectrum(omega):
93
+ w = omega[None] * scale
94
+ matern = (1 + w**2 / (2 * nu.clamp_max(10))) ** (-(nu.clamp_max(10) + 0.5))
95
+ rbf = torch.exp(-(w**2) / 2)
96
+ return torch.where(nu > 10, rbf, matern)
97
+
98
+ return _spectral(gen, length, device, spectrum)
99
+
100
+
101
+ def kernel_family(gen, n, length, device, max_components=5):
102
+ """Return float32 KernelSynth series [n,length] from random periodic, GP, noise and trends."""
103
+ m, slots = n * max_components, max_components
104
+ t = torch.arange(length, device=device, dtype=torch.float32) / length
105
+ count = torch.randint(1, slots + 1, (n,), generator=gen, device=device)
106
+ kind = _categorical(gen, (0.4, 0.25, 0.15, 0.2), m, device)
107
+ period = _periods(gen, m, device).view(slots, n)
108
+ multiple = period[:1] * _choice(gen, MULTIPLES, (slots, n), device)
109
+ harmonic = _u(gen, (slots, n), device=device) < 0.4
110
+ harmonic[0] = False
111
+ period = torch.where(harmonic, multiple, period).flatten()
112
+ periodic = _periodic(gen, period, length, device)
113
+ smooth = _smooth(gen, m, length, device)
114
+ sigma = torch.where(_u(gen, (m, 1), device=device) < 0.5, 0.1, 1.0)
115
+ white = torch.randn((m, length), generator=gen, device=device) * sigma
116
+ slope = torch.randn((m, 1), generator=gen, device=device) * 2
117
+ linear = slope * (t[None] - 0.5) * 2
118
+ ramp = _u(gen, (m, 1), 0.05, 1.0, device) + t[None] * torch.sign(slope)
119
+ ramp = ramp - torch.minimum(ramp.amin(-1, keepdim=True), torch.zeros_like(ramp[:, :1]))
120
+ amplitude = _logu(gen, (m, 1), 0.1, 3.0, device)
121
+ k = kind[:, None]
122
+ component = torch.where(
123
+ k == 0, periodic * amplitude,
124
+ torch.where(k == 1, smooth * amplitude, torch.where(k == 2, white, linear)),
125
+ )
126
+ factor = torch.where(k == 3, ramp, component / amplitude)
127
+ component, factor = component.view(slots, n, length), factor.view(slots, n, length)
128
+ product = (_u(gen, (slots, n, 1), device=device) < 0.2)
129
+ acc = component[0]
130
+ for slot in range(1, slots):
131
+ combined = torch.where(product[slot], acc * factor[slot], acc + component[slot])
132
+ acc = torch.where((slot < count)[:, None], combined, acc)
133
+ return acc
134
+
135
+
136
+ def _arma_response(gen, n, grid, device, seasonal_period):
137
+ """Return a random stable SARMA filter response [n,grid/2+1] (complex)."""
138
+ omega = 2 * math.pi * torch.arange(grid // 2 + 1, device=device, dtype=torch.float32) / grid
139
+ z = torch.polar(torch.ones_like(omega), -omega)[None]
140
+ use_ar = _u(gen, (n, 1), device=device) < 0.7
141
+ use_seasonal = _u(gen, (n, 1), device=device) < 0.6
142
+ use_seasonal |= ~use_ar
143
+ response = torch.ones((n, omega.shape[0]), dtype=torch.complex64, device=device)
144
+ pairs = torch.randint(0, 4, (n, 1), generator=gen, device=device)
145
+ for j in range(3):
146
+ r = _u(gen, (n, 1), 0.0, 0.95, device) * ((j < pairs) & use_ar)
147
+ theta = _u(gen, (n, 1), 0.0, math.pi, device)
148
+ response = response / (1 - 2 * r * theta.cos() * z + r**2 * z**2)
149
+ real = _u(gen, (n, 1), -0.95, 0.95, device) * (_u(gen, (n, 1), device=device) < 0.5) * use_ar
150
+ response = response / (1 - real * z)
151
+ zeros = torch.randint(0, 3, (n, 1), generator=gen, device=device)
152
+ for j in range(2):
153
+ r = _u(gen, (n, 1), 0.0, 1.0, device) * (j < zeros)
154
+ theta = _u(gen, (n, 1), 0.0, math.pi, device)
155
+ response = response * (1 - 2 * r * theta.cos() * z + r**2 * z**2)
156
+ s = seasonal_period[:, None]
157
+ zs = torch.polar(torch.ones_like(omega[None] * s), -omega[None] * s)
158
+ phi = _u(gen, (n, 1), 0.2, 0.9, device) * use_seasonal
159
+ theta_s = (_u(gen, (n, 1), -0.6, 0.6, device) * use_seasonal
160
+ * (_u(gen, (n, 1), device=device) < 0.5))
161
+ response = response * (1 - theta_s * zs) / (1 - phi * zs)
162
+ d = _u(gen, (n, 1), 0.0, 1.0, device) * (_u(gen, (n, 1), device=device) < 0.3)
163
+ diff = (1 - z).abs().clamp_min(1e-4)
164
+ angle = torch.angle(1 - z)
165
+ magnitude, phase = torch.broadcast_tensors(diff ** (-d), -d * angle)
166
+ response = response * torch.polar(magnitude.contiguous(), phase.contiguous())
167
+ response[:, 0] = 0
168
+ return response
169
+
170
+
171
+ def _seasonal_cumsum(x, period, active, bank=SEASON_BANK):
172
+ """Compute y_t = y_{t-p} + x_t for active rows with p in `bank`; preserve other rows."""
173
+ out = x
174
+ length = x.shape[-1]
175
+ for s in bank:
176
+ pad = (-length) % s
177
+ y = F.pad(x, (0, pad)).unflatten(-1, (-1, s)).cumsum(-2).flatten(-2)[:, :length]
178
+ out = torch.where((active & (period == s))[:, None], y, out)
179
+ return out
180
+
181
+
182
+ def _sarima_paths(gen, n, length, device):
183
+ season = _choice(gen, SEASON_BANK, (n,), device)
184
+ grid = 2 * length
185
+ response = _arma_response(gen, n, grid, device, season)
186
+ noise = torch.fft.rfft(torch.randn((n, grid), generator=gen, device=device))
187
+ y = _standardise(torch.fft.irfft(noise * response, n=grid)[:, length:])
188
+ integrate = _u(gen, (n, 1), device=device) < 0.4
189
+ y = torch.where(integrate, _standardise(y.cumsum(-1)), y)
190
+ seasonal = _u(gen, (n,), device=device) < 0.3
191
+ y = _seasonal_cumsum(y, season, seasonal)
192
+ return _standardise(y)
193
+
194
+
195
+ def _stretch(y, factor):
196
+ """Interpolate [n,L] paths at t / factor for each row."""
197
+ length = y.shape[-1]
198
+ position = torch.arange(length, device=y.device, dtype=torch.float32)[None] / factor[:, None]
199
+ low = position.floor().long().clamp_max(length - 1)
200
+ high = (low + 1).clamp_max(length - 1)
201
+ frac = position - low
202
+ return y.gather(-1, low) * (1 - frac) + y.gather(-1, high) * frac
203
+
204
+
205
+ def sarima_family(gen, n, length, device):
206
+ """Return float32 seasonal ARIMA series [n,length] with optional slow envelopes."""
207
+ paths = _sarima_paths(gen, 2 * n, length, device)
208
+ base, extra = paths[:n], paths[n:]
209
+ factor = torch.randint(4, 65, (n,), generator=gen, device=device).float()
210
+ extra = _stretch(extra, factor)
211
+ interact = _u(gen, (n, 1), device=device) < 0.7
212
+ multiplicative = _u(gen, (n, 1), device=device) < 0.5
213
+ lo, hi = extra.amin(-1, keepdim=True), extra.amax(-1, keepdim=True)
214
+ unit = 2 * (extra - lo) / (hi - lo).clamp_min(1e-6) - 1
215
+ weight = _u(gen, (n, 1), device=device)
216
+ level = _u(gen, (n, 1), 0.0, 3.0, device) # Let the envelope act on nonzero means too.
217
+ mixed = torch.where(
218
+ multiplicative,
219
+ (1 + weight * unit) * (base + level),
220
+ base + _logu(gen, (n, 1), 0.2, 3.0, device) * extra,
221
+ )
222
+ return torch.where(interact, mixed, base)
223
+
224
+
225
+ def _noisers(gen, x, probability):
226
+ """Return (values, is_count) with Poisson count rates lambda0 * minmax(x)."""
227
+ n, length = x.shape
228
+ device = x.device
229
+ kind = torch.randint(0, 4, (n, 1), generator=gen, device=device)
230
+ active = _u(gen, (n, 1), device=device) < probability
231
+ lo, hi = x.amin(-1, keepdim=True), x.amax(-1, keepdim=True)
232
+ unit = (x - lo) / (hi - lo).clamp_min(1e-6)
233
+ rate = _logu(gen, (n, 1), 0.05, 50.0, device) * unit
234
+ rate = rate * torch.where(
235
+ kind == 1, torch.exp(0.5 * torch.randn((n, length), generator=gen, device=device)), 1.0
236
+ )
237
+ counts = torch.poisson(rate, generator=gen)
238
+ sigma = _u(gen, (n, 1), 0.05, 0.5, device)
239
+ shocks = (unit + 0.1) * torch.exp(sigma * torch.randn((n, length), generator=gen,
240
+ device=device))
241
+ spikes = (torch.rand((n, length), generator=gen, device=device) < 0.01) * torch.randn(
242
+ (n, length), generator=gen, device=device
243
+ ) * _u(gen, (n, 1), 3.0, 10.0, device)
244
+ out = torch.where(kind <= 1, counts, torch.where(kind == 2, shocks, x + spikes))
245
+ is_count = active & (kind <= 1)
246
+ return torch.where(active, out, x), is_count
247
+
248
+
249
+ def draw(n, length, gen, device, families=("kernel", "sarima"), weights=None):
250
+ """Return standardized float32 [n,length] series from weighted families, then augment them."""
251
+ if n < 1:
252
+ raise ValueError("draw needs n >= 1")
253
+ if weights is None:
254
+ split = [n // len(families)] * len(families)
255
+ else:
256
+ total = sum(weights)
257
+ split = [int(n * w / total) for w in weights]
258
+ split[0] += n - sum(split)
259
+ from simons.synth import augment
260
+
261
+ makers = family_makers(families)
262
+ parts = [makers[f](gen, k, length, device) for f, k in zip(families, split) if k]
263
+ x = torch.cat(parts)
264
+ x = x[torch.randperm(n, generator=gen, device=device)]
265
+ x = torch.where(torch.isfinite(x), x, 0)
266
+ x = _standardise(x)
267
+ return augment.apply(gen, x)
268
+
269
+
270
+ def family_makers(families) -> dict:
271
+ """Return {name: maker(gen,n,length,device)} for the requested families."""
272
+ from simons.synth.calendar import MAKERS as CALENDAR
273
+ from simons.synth.causal import MAKERS as CAUSAL
274
+ from simons.synth.heavy import MAKERS as HEAVY
275
+ from simons.synth.mech import MAKERS as MECH
276
+ from simons.synth.nonstat import MAKERS as NONSTAT
277
+
278
+ makers = {"kernel": kernel_family, "sarima": sarima_family, **NONSTAT, **CAUSAL, **HEAVY,
279
+ **MECH, **CALENDAR}
280
+ unknown = sorted(set(families) - set(makers))
281
+ if unknown:
282
+ raise ValueError(f"unknown synthetic families {unknown}")
283
+ return makers
284
+
285
+
286
+ def post(x, gen, noise=0.0, pad=0.4, missing=0.1, min_observed=96, group=None,
287
+ return_flip=False):
288
+ """Apply observation effects, random units, padding and gaps to standardized x [n,L].
289
+ `group` [n] shares flips/padding; `return_flip` also returns time-flip flags [n,1]."""
290
+ n, length = x.shape
291
+ device = x.device
292
+
293
+ def shared(v):
294
+ return v if group is None else v[group]
295
+
296
+ flip = shared(_u(gen, (n, 1), device=device) < 0.25)
297
+ x = torch.where(flip, x.flip(-1), x)
298
+ x, is_count = _noisers(gen, x, noise) if noise > 0 else (x, torch.zeros_like(flip))
299
+ from simons.synth import observe
300
+
301
+ chosen = None
302
+ if observe.CONFIG is not None:
303
+ chosen = observe.choose(gen, n, device, is_count)
304
+ linked = observe.has(chosen, "link")
305
+ x = torch.where(linked, observe.link(gen, x, observe.has(chosen, "mult")), x)
306
+ sign = torch.where(_u(gen, (n, 1), device=device) < 0.25, -1.0, 1.0)
307
+ scale = _logu(gen, (n, 1), 1e-2, 1e4, device)
308
+ offset = _u(gen, (n, 1), -3.0, 3.0, device)
309
+ positive = _u(gen, (n, 1), device=device) < 0.3
310
+ y = sign * x
311
+ y = torch.where(positive, y - y.amin(-1, keepdim=True), y + offset)
312
+ if chosen is not None:
313
+ y = torch.where(linked, x, y) # Linked rows are already positive, so apply scaling only.
314
+ x = torch.where(is_count, x, y * scale)
315
+ x = torch.where(torch.isfinite(x), x, 0)
316
+ if chosen is not None:
317
+ x = observe.record(gen, x, chosen)
318
+ t = torch.arange(length, device=device)[None]
319
+ observed = shared(_logu(gen, (n, 1), min_observed, length, device).long())
320
+ short = shared(_u(gen, (n, 1), device=device) < pad)
321
+ x = torch.where(short & (t < length - observed), float("nan"), x)
322
+ holes = _u(gen, (n, 1), device=device) < missing
323
+ rate = _logu(gen, (n, 1), 0.001, 0.02, device)
324
+ span = torch.randint(1, 33, (n, 1), generator=gen, device=device)
325
+ starts = torch.rand((n, length), generator=gen, device=device) < rate
326
+ latest = torch.where(starts, t, -10**6).cummax(-1).values
327
+ hole = holes & (t - latest < span)
328
+ hole[:, -32:] = False # Keep the last patch observed.
329
+ x = torch.where(hole, float("nan"), x)
330
+ if return_flip:
331
+ return x.float(), flip
332
+ return x.float()
333
+
334
+
335
+ def generate(
336
+ n: int,
337
+ length: int,
338
+ gen: torch.Generator,
339
+ device,
340
+ families=("kernel", "sarima"),
341
+ noise: float = 0.0,
342
+ pad: float = 0.4,
343
+ missing: float = 0.1,
344
+ min_observed: int = 96,
345
+ weights=None,
346
+ ) -> torch.Tensor:
347
+ """Return float32 [n,length] synthetic series in random units; NaN marks missing values."""
348
+ x = draw(n, length, gen, device, families, weights)
349
+ return post(x, gen, noise, pad, missing, min_observed)
350
+
351
+
352
+ class SyntheticMixer:
353
+ """Replace the last round(fraction * rows) batch rows from a reusable synthetic-series pool."""
354
+
355
+ def __init__(self, fraction, gen, families=("kernel", "sarima"), noise=0.0, pad=0.4,
356
+ pool_steps=1, weights=None, multi=None, observe=None):
357
+ self.fraction, self.gen, self.families = fraction, gen, tuple(families)
358
+ self.multi, self.pool_ids, self.last_ids = multi, None, None
359
+ self.noise, self.pad, self.pool_steps = noise, pad, max(1, int(pool_steps))
360
+ self.weights = weights
361
+ self.observe = observe
362
+ self.pool, self.used = None, 0
363
+ self.track_first, self.pool_first, self.last_first = 0, None, None
364
+ self.first_event = None
365
+ self.first_offset = 0
366
+
367
+ def _build(self, size, length, device):
368
+ from simons.synth import observe
369
+
370
+ saved = observe.CONFIG
371
+ observe.CONFIG = self.observe
372
+ try:
373
+ pool_ids = None
374
+ if self.multi is None:
375
+ pool = generate(size, length, self.gen, device, self.families, self.noise,
376
+ self.pad, weights=self.weights)
377
+ else:
378
+ built = self.multi.build(size, length, self.gen, device, self.families,
379
+ self.noise, self.pad, self.weights)
380
+ pool, pool_ids = built[0], tuple(built[1:])
381
+ finally:
382
+ observe.CONFIG = saved
383
+ pool_first, first_event = None, None
384
+ if self.track_first:
385
+ seen = torch.isfinite(pool).unflatten(-1, (-1, self.track_first)).any(-1)
386
+ position = torch.arange(seen.shape[-1], device=seen.device)
387
+ first = torch.where(seen, position, seen.shape[-1]).amin(-1)
388
+ if first.is_cuda: # first_rows waits for this asynchronous copy only when needed.
389
+ pool_first = torch.empty(first.shape, dtype=first.dtype, pin_memory=True)
390
+ pool_first.copy_(first, non_blocking=True)
391
+ first_event = torch.cuda.Event()
392
+ first_event.record()
393
+ else:
394
+ pool_first = first
395
+ return pool, pool_ids, pool_first, first_event
396
+
397
+ def take(self, n, length, device):
398
+ if self.pool is None or self.pool.shape[1] != length or self.used + n > len(self.pool):
399
+ self.pool, ids, self.pool_first, self.first_event = self._build(
400
+ n * self.pool_steps, length, device)
401
+ if ids is not None:
402
+ self.pool_ids = ids
403
+ self.used = 0
404
+ out = self.pool[self.used : self.used + n]
405
+ if self.multi is not None:
406
+ self.last_ids = tuple(a[self.used : self.used + n] for a in self.pool_ids)
407
+ if self.track_first:
408
+ self.last_first = (self.pool_first, self.first_event, self.used, self.used + n)
409
+ self.used += n
410
+ return out
411
+
412
+ def last_meta(self):
413
+ """Device [n, 3] covariate-role metadata of the last call's series, or None."""
414
+ if self.multi is None or self.last_ids is None or len(self.last_ids) < 3:
415
+ return None
416
+ return self.last_ids[2]
417
+
418
+ def host_ids(self, count, width):
419
+ """Host [count, width] series IDs of the last call's synthetic rows."""
420
+ if self.multi is not None:
421
+ return self.last_ids[0].reshape(count, width)
422
+ return SYNTHETIC_ID + np.arange(count * width).reshape(count, width)
423
+
424
+ def first_rows(self):
425
+ """Host first-observed patches of the last call's synthetic series (numpy), or None."""
426
+ if self.last_first is None:
427
+ return None
428
+ first, event, start, stop = self.last_first
429
+ if event is not None:
430
+ event.synchronize()
431
+ return first[start:stop].numpy() + self.first_offset
432
+
433
+ def __call__(self, sequence, series_ids):
434
+ rows, width, length = sequence.shape
435
+ count = round(self.fraction * rows)
436
+ if count <= 0:
437
+ self.last_first = None
438
+ return sequence, series_ids
439
+ synthetic = self.take(count * width, length, sequence.device)
440
+ sequence = sequence.clone()
441
+ series_ids = series_ids.clone()
442
+ sequence[rows - count :] = synthetic.view(count, width, length).to(sequence.dtype)
443
+ if self.multi is not None:
444
+ ids = self.last_ids[1].to(series_ids.device)
445
+ else:
446
+ ids = SYNTHETIC_ID + torch.arange(count * width, device=series_ids.device)
447
+ series_ids[rows - count :] = ids.view(count, width)
448
+ return sequence, series_ids
@@ -0,0 +1,157 @@
1
+ """Calendar series with workday/weekend profiles, holidays and seasonal variation."""
2
+
3
+ import math
4
+
5
+ import torch
6
+ import torch.nn.functional as F
7
+
8
+ from simons.synth.base import _bank, _categorical, _logu, _spectral, _standardise, _u
9
+
10
+ GRID = 288
11
+ STEPS_PER_DAY = (12.0, 24.0, 48.0, 96.0, 144.0, 288.0, 1.0)
12
+ STEPS_WEIGHTS = (0.08, 0.26, 0.12, 0.14, 0.06, 0.12, 0.22)
13
+ BUMPS = 4
14
+ HARMONICS = 6
15
+
16
+
17
+ def _circ(h, c):
18
+ """Return signed circular distance on [0,1)."""
19
+ return torch.remainder(h - c + 0.5, 1.0) - 0.5
20
+
21
+
22
+ def _profiles(gen, n, device):
23
+ """Return positive workday/weekend profiles [n,GRID], including the weekend level factor."""
24
+ h = (torch.arange(GRID, device=device, dtype=torch.float32) / GRID)[None, None] # [1,1,G]
25
+ count = torch.randint(1, BUMPS + 1, (n, 1), generator=gen, device=device)
26
+ live = (torch.arange(BUMPS, device=device)[None] < count).float() # [n, B]
27
+ centre = _u(gen, (n, BUMPS), 0.18, 0.92, device)
28
+ width = _logu(gen, (n, BUMPS), 0.015, 0.12, device)
29
+ height = _logu(gen, (n, BUMPS), 0.2, 2.0, device) * live
30
+ action = _categorical(gen, (0.25, 0.3, 0.25, 0.2), n * BUMPS, device).view(n, BUMPS)
31
+ shift = _u(gen, (n, BUMPS), 1.0, 3.0, device) / 24
32
+ e_centre = torch.where(action == 2, centre + shift, centre)
33
+ e_width = torch.where(action == 3, width * _u(gen, (n, BUMPS), 1.5, 3.0, device), width)
34
+ e_height = torch.where(action == 1, 0.0, torch.where(
35
+ action == 3, height * _u(gen, (n, BUMPS), 0.3, 0.7, device), height))
36
+ e_height = e_height * _u(gen, (n, BUMPS), 0.6, 1.2, device)
37
+
38
+ def bumps(c, w, a):
39
+ d = _circ(h, c[..., None]) / w[..., None]
40
+ return (a[..., None] * torch.exp(-0.5 * d * d)).sum(1) # [n, G]
41
+
42
+ k = torch.arange(1, HARMONICS + 1, device=device, dtype=torch.float32)[None]
43
+ nh = torch.randint(2, HARMONICS + 1, (n, 1), generator=gen, device=device)
44
+ var = torch.exp(-k / _u(gen, (n, 1), 0.8, 2.5, device)) * (k <= nh)
45
+ amp = _u(gen, (n, 1), 0.0, 0.6, device)
46
+ a = torch.randn((n, HARMONICS), generator=gen, device=device) * var.sqrt() * amp
47
+ b = torch.randn((n, HARMONICS), generator=gen, device=device) * var.sqrt() * amp
48
+ ang = 2 * math.pi * k[..., None] * h[0] # [1, K, G]
49
+ fourier = (a[..., None] * ang.cos() + b[..., None] * ang.sin()).sum(1)
50
+ e_fourier = fourier * _u(gen, (n, 1), 0.3, 1.0, device)
51
+ work = bumps(centre, width, height) + fourier
52
+ wend = bumps(e_centre, e_width, e_height) + e_fourier
53
+ low = torch.minimum(work.amin(-1, keepdim=True), wend.amin(-1, keepdim=True))
54
+ base = _u(gen, (n, 1), 0.05, 1.0, device)
55
+ work, wend = work - low + base, wend - low + base
56
+ level = torch.where(_u(gen, (n, 1), device=device) < 0.25,
57
+ _logu(gen, (n, 1), 1.05, 1.8, device),
58
+ _logu(gen, (n, 1), 0.35, 0.95, device))
59
+ return work, wend * level
60
+
61
+
62
+ def calendar_family(gen, n, length, device):
63
+ """Return float32 standardized calendar series [n,length] on `device`, drawn from `gen`."""
64
+ t = torch.arange(length, device=device, dtype=torch.float32)[None]
65
+ days = length # Allocate enough days for the daily-data case P = 1.
66
+ dd = torch.arange(days, device=device, dtype=torch.float32)[None]
67
+ P = _bank(STEPS_PER_DAY, device)[_categorical(gen, STEPS_WEIGHTS, n, device)][:, None]
68
+ sub = P > 1.5
69
+ offset = torch.floor(_u(gen, (n, 1), device=device) * P)
70
+ pos = t + offset
71
+ day = torch.floor(pos / P)
72
+ hour = (pos - day * P) / P
73
+ day_l = day.long().clamp(0, days - 1)
74
+ week_phase = torch.randint(0, 7, (n, 1), generator=gen, device=device).float()
75
+ dow_axis = torch.remainder(dd + week_phase, 7.0)
76
+ year_phase = _u(gen, (n, 1), 0.0, 365.25, device)
77
+ doy_axis = torch.remainder(dd + year_phase, 365.25)
78
+ two_types = _u(gen, (n, 1), device=device) < 0.4
79
+ saturday = torch.where(two_types, 1.0, _u(gen, (n, 1), 0.2, 0.8, device))
80
+ s = torch.where(dow_axis >= 5.5, 1.0, torch.where(dow_axis >= 4.5, saturday, 0.0))
81
+ s = torch.where((_u(gen, (n, 1), device=device) < 0.1) & (dow_axis < 5.5), 0.0, s)
82
+ workday = s < 0.5
83
+ rate = _logu(gen, (n, 1), 0.005, 0.05, device)
84
+ random_hol = (_u(gen, (n, days), device=device) < rate) & workday
85
+ fixed = torch.floor(_u(gen, (n, 8), 0.0, 365.0, device))
86
+ use_fixed = torch.arange(8, device=device)[None] < torch.randint(0, 9, (n, 1), generator=gen,
87
+ device=device)
88
+ fixed_hol = ((torch.floor(doy_axis)[..., None] == fixed[:, None]) & use_fixed[:, None]).any(-1)
89
+ holiday = (random_hol | fixed_hol) & (_u(gen, (n, 1), device=device) < 0.85)
90
+ nxt = F.pad(holiday[:, 1:], (0, 1))
91
+ prv = F.pad(holiday[:, :-1], (1, 0))
92
+ bridge = ((nxt & (dow_axis < 0.5)) | (prv & (dow_axis > 3.5) & (dow_axis < 4.5))) & ~holiday
93
+ s = torch.where(holiday, 1.0, s)
94
+ s = torch.where(bridge, torch.maximum(s, _u(gen, (n, 1), 0.3, 0.7, device)), s)
95
+ n_days = torch.ceil(length / P)
96
+ ev_live = torch.arange(3, device=device)[None] < torch.randint(0, 4, (n, 1), generator=gen,
97
+ device=device)
98
+ ev_len = _logu(gen, (n, 3), 3.0, 14.0, device)
99
+ ev_start = _u(gen, (n, 3), device=device) * (n_days + ev_len) - ev_len
100
+ ev_ramp = _u(gen, (n, 3), 0.5, 2.5, device)
101
+ ev_w = ((torch.minimum(dd[..., None] - ev_start[:, None] + 1,
102
+ ev_start[:, None] + ev_len[:, None] - dd[..., None])
103
+ / ev_ramp[:, None]).clamp(0, 1) * ev_live[:, None]) # [n, D, 3]
104
+ ev_level = torch.log(_logu(gen, (n, 3), 0.5, 1.6, device))
105
+ ev_type = _u(gen, (n, 3), 0.0, 0.9, device)
106
+ log_level = (ev_w * ev_level[:, None]).sum(-1)
107
+ s = torch.maximum(s, (ev_w * ev_type[:, None]).amax(-1))
108
+ wd = torch.exp(_u(gen, (n, 1), 0.0, 0.12, device) * torch.randn((n, 7), generator=gen,
109
+ device=device))
110
+ log_level = log_level + torch.log(wd.gather(1, dow_axis.long().clamp(0, 6)))
111
+ tau_d = _logu(gen, (n, 1), 1.0, 30.0, device)
112
+ ou_d = _spectral(gen, days, device, lambda w: 1.0 / (1.0 + (w[None] * tau_d) ** 2))
113
+ log_level = log_level + _u(gen, (n, 1), 0.0, 0.12, device) * ou_d
114
+ ya = _u(gen, (n, 1), 0.0, 0.4, device) * (_u(gen, (n, 1), device=device) < 0.7)
115
+ yp = _u(gen, (n, 2), 0.0, 2 * math.pi, device)
116
+ ang = 2 * math.pi * doy_axis / 365.25
117
+ log_level = log_level + ya * (torch.sin(ang + yp[:, :1]) + 0.4 * torch.sin(2 * ang + yp[:, 1:]))
118
+ jitter = (_u(gen, (n, 1), 0.0, 0.012, device)
119
+ * torch.randn((n, days), generator=gen, device=device))
120
+ work, wend = _profiles(gen, n, device)
121
+ s_t = s.gather(1, day_l)
122
+ h = torch.remainder(hour + jitter.gather(1, day_l), 1.0)
123
+ idx = (h * GRID).long().clamp(0, GRID - 1)
124
+ hl = torch.where(sub, idx, 0) # Daily data uses the mean profile instead of an intraday point.
125
+ prof_w = torch.where(sub, work.gather(1, hl), work.mean(-1, keepdim=True))
126
+ prof_e = torch.where(sub, wend.gather(1, hl), wend.mean(-1, keepdim=True))
127
+ activity = ((1 - s_t) * prof_w + s_t * prof_e) * torch.exp(log_level.gather(1, day_l))
128
+ night_c = _u(gen, (n, 1), -0.08, 0.08, device)
129
+ half = _u(gen, (n, 1), 0.1, 0.27, device)
130
+ dl = torch.where(P <= 48, _u(gen, (n, 1), 0.0, 0.35, device), 0.0)
131
+ half = half * (1 + dl * torch.sin(ang + yp[:, :1]).gather(1, day_l))
132
+ night = (_circ(hour, night_c).abs() < half) & sub & (_u(gen, (n, 1), device=device) < 0.3)
133
+ floor = torch.where(_u(gen, (n, 1), device=device) < 0.5, 0.0,
134
+ activity.amin(-1, keepdim=True) * _u(gen, (n, 1), 0.0, 1.0, device))
135
+ activity = torch.where(night, floor, activity)
136
+ sd = activity.std(-1, keepdim=True).clamp_min(1e-6)
137
+ tau_n = _logu(gen, (n, 1), 1.0, 30.0, device)
138
+ noise = _spectral(gen, length, device, lambda w: 1.0 / (1.0 + (w[None] * tau_n) ** 2))
139
+ sigma = _logu(gen, (n, 1), 0.01, 0.2, device)
140
+ tau_s = _logu(gen, (n, 1), 0.05, 0.5, device) * length
141
+ slow = _spectral(gen, length, device, lambda w: 1.0 / (1.0 + (w[None] * tau_s) ** 2))
142
+ slow = (slow * _u(gen, (n, 1), 0.0, 0.25, device)
143
+ + _u(gen, (n, 1), -0.5, 0.5, device) * (t / length - 0.5))
144
+ mode = _categorical(gen, (0.45, 0.35, 0.2), n, device)[:, None]
145
+ additive = activity + sd * (sigma * noise + slow)
146
+ multiplicative = activity * torch.exp(sigma * noise + 0.5 * slow)
147
+ capacity_at = activity.mean(-1, keepdim=True) + sd * _u(gen, (n, 1), 0.2, 1.5, device)
148
+ g = _logu(gen, (n, 1), 1.0, 10.0, device) / sd
149
+ capacity = (-F.softplus(g * (activity - capacity_at)) / g
150
+ + sd * (0.3 * sigma * noise + 0.3 * slow))
151
+ capacity = torch.where(night, capacity.amax(-1, keepdim=True), capacity)
152
+ y = torch.where(mode == 0, additive, torch.where(mode == 1, multiplicative, capacity))
153
+ y = torch.where(torch.isfinite(y), y, 0)
154
+ return _standardise(y)
155
+
156
+
157
+ MAKERS = {"calendar": calendar_family}