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.
- simons/__init__.py +10 -0
- simons/config.py +82 -0
- simons/covariates.py +338 -0
- simons/forecast.py +578 -0
- simons/model.py +696 -0
- simons/periodicity.py +188 -0
- simons/predictor.py +56 -0
- simons/synth/__init__.py +5 -0
- simons/synth/augment.py +143 -0
- simons/synth/base.py +448 -0
- simons/synth/calendar.py +157 -0
- simons/synth/causal.py +193 -0
- simons/synth/covariates/__init__.py +1 -0
- simons/synth/covariates/classical.py +637 -0
- simons/synth/covariates/effects.py +155 -0
- simons/synth/covariates/energy.py +528 -0
- simons/synth/covariates/families.py +296 -0
- simons/synth/covariates/generic.py +342 -0
- simons/synth/heavy.py +234 -0
- simons/synth/mech.py +636 -0
- simons/synth/multi.py +274 -0
- simons/synth/nonstat.py +204 -0
- simons/synth/observe.py +117 -0
- simons/training/__init__.py +1 -0
- simons/training/__main__.py +77 -0
- simons/training/augment.py +125 -0
- simons/training/clusters.py +215 -0
- simons/training/config.py +321 -0
- simons/training/covariates/__init__.py +1 -0
- simons/training/covariates/roles.py +370 -0
- simons/training/covariates/stream.py +243 -0
- simons/training/covariates/windows.py +239 -0
- simons/training/data.py +319 -0
- simons/training/distributed.py +124 -0
- simons/training/mixture.py +140 -0
- simons/training/network.py +115 -0
- simons/training/objective.py +193 -0
- simons/training/optim.py +164 -0
- simons/training/packing.py +94 -0
- simons/training/schedule.py +117 -0
- simons/training/soup.py +93 -0
- simons/training/stitching.py +50 -0
- simons/training/trainer.py +571 -0
- simons/training/warp.py +144 -0
- simons_forecasting-0.1.3.dist-info/METADATA +156 -0
- simons_forecasting-0.1.3.dist-info/RECORD +49 -0
- simons_forecasting-0.1.3.dist-info/WHEEL +4 -0
- simons_forecasting-0.1.3.dist-info/licenses/LICENSE +202 -0
- simons_forecasting-0.1.3.dist-info/licenses/NOTICE +57 -0
simons/periodicity.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""Detect dominant history periods and encode their phases in the slowest rotary pairs."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
|
|
5
|
+
import torch
|
|
6
|
+
|
|
7
|
+
MIN_OBSERVED = 64
|
|
8
|
+
LOCAL = 16
|
|
9
|
+
MAX_LOCAL = 128
|
|
10
|
+
EULER = 0.5772156649
|
|
11
|
+
TABLE_BLOCK = 256
|
|
12
|
+
TABLE_SPAN = 8192 # longer spans have large tables: 1 GiB for 16,384 steps, 4 GiB for 32,768
|
|
13
|
+
PEAK_COLUMNS = 512
|
|
14
|
+
|
|
15
|
+
_TABLES = {}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _waves(steps: torch.Tensor, periods: torch.Tensor):
|
|
19
|
+
"""cos and sin [L,P] float32 of float32 `periods` [P] at float64 `steps` [L]."""
|
|
20
|
+
angle = 2 * math.pi * torch.remainder(steps[:, None] / periods.double()[None], 1.0)
|
|
21
|
+
return angle.cos().float(), angle.sin().float()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _refine_table(length: int, device):
|
|
25
|
+
key = (length, str(device))
|
|
26
|
+
if key not in _TABLES:
|
|
27
|
+
with torch.inference_mode(False), torch.no_grad():
|
|
28
|
+
candidates = torch.arange(2, length // 2 + 1, device=device, dtype=torch.float32)
|
|
29
|
+
steps = torch.arange(length, device=device, dtype=torch.float64)
|
|
30
|
+
cos = torch.empty(length, candidates.numel(), device=device,
|
|
31
|
+
dtype=torch.float32)
|
|
32
|
+
sin = torch.empty_like(cos)
|
|
33
|
+
# Blockwise fp64 angles avoid allocating a full fp64 DFT table.
|
|
34
|
+
for start in range(0, candidates.numel(), TABLE_BLOCK):
|
|
35
|
+
block = slice(start, start + TABLE_BLOCK)
|
|
36
|
+
cos[:, block], sin[:, block] = _waves(steps, candidates[block])
|
|
37
|
+
_TABLES[key] = (candidates, cos, sin)
|
|
38
|
+
return _TABLES[key]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _power(z: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
|
|
42
|
+
"""Squared projections [N,P] of z [N,L] on the cos and sin waves [L,P]."""
|
|
43
|
+
if not z.is_cuda:
|
|
44
|
+
return (z @ cos) ** 2 + (z @ sin) ** 2
|
|
45
|
+
# TF32 only changes the argmax among near-tied neighboring integer periods.
|
|
46
|
+
previous = torch.backends.cuda.matmul.allow_tf32
|
|
47
|
+
torch.backends.cuda.matmul.allow_tf32 = True
|
|
48
|
+
try:
|
|
49
|
+
return (z @ cos) ** 2 + (z @ sin) ** 2
|
|
50
|
+
finally:
|
|
51
|
+
torch.backends.cuda.matmul.allow_tf32 = previous
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _peak_power(z: torch.Tensor, candidates: torch.Tensor, wanted: torch.Tensor) -> torch.Tensor:
|
|
55
|
+
"""`_power` [N,P] of z [N,L] for the `wanted` [P] candidate periods, -1 elsewhere, from waves
|
|
56
|
+
built here instead of the table."""
|
|
57
|
+
steps = torch.arange(z.shape[-1], device=z.device, dtype=torch.float64)
|
|
58
|
+
out = z.new_full((z.shape[0], candidates.numel()), -1.0)
|
|
59
|
+
index = torch.nonzero(wanted)[:, 0]
|
|
60
|
+
for start in range(0, index.numel(), TABLE_BLOCK):
|
|
61
|
+
block = index[start : start + TABLE_BLOCK]
|
|
62
|
+
out[:, block] = _power(z, *_waves(steps, candidates[block]))
|
|
63
|
+
return out
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def detect_periods(values: torch.Tensor, context: int, slots: int, alpha: float, local: float,
|
|
67
|
+
patch: int) -> torch.Tensor:
|
|
68
|
+
"""Return [...,slots] dominant periods in steps (0: none) from values[..., :context].
|
|
69
|
+
Input must contain at least `context` steps; periods dividing `patch` are excluded."""
|
|
70
|
+
shape = values.shape[:-1]
|
|
71
|
+
with torch.autocast(device_type=values.device.type, enabled=False):
|
|
72
|
+
x = values[..., :context].reshape(-1, context).float()
|
|
73
|
+
observed = torch.isfinite(x)
|
|
74
|
+
weight = observed.float()
|
|
75
|
+
count = weight.sum(-1, keepdim=True)
|
|
76
|
+
safe = count.clamp_min(1)
|
|
77
|
+
x0 = torch.where(observed, x, 0).double()
|
|
78
|
+
w = weight.double()
|
|
79
|
+
mean = x0.sum(-1, keepdim=True) / safe.double()
|
|
80
|
+
centred = (x0 - mean) * w
|
|
81
|
+
t = torch.arange(context, device=x.device, dtype=torch.float64)
|
|
82
|
+
t_mean = (t * w).sum(-1, keepdim=True) / safe.double()
|
|
83
|
+
tc = (t - t_mean) * w
|
|
84
|
+
slope = (tc * centred).sum(-1, keepdim=True) / (tc * tc).sum(-1, keepdim=True).clamp_min(
|
|
85
|
+
1e-12
|
|
86
|
+
)
|
|
87
|
+
centred = (centred - slope * tc) * w
|
|
88
|
+
std = ((centred**2).sum(-1, keepdim=True) / safe.double()).sqrt().clamp_min(1e-8)
|
|
89
|
+
z = (centred / std).float()
|
|
90
|
+
spectrum = torch.fft.rfft(z, n=context, dim=-1)
|
|
91
|
+
power = spectrum.real**2 + spectrum.imag**2
|
|
92
|
+
half = context // 2
|
|
93
|
+
power = power[:, 1 : half + 1]
|
|
94
|
+
total = power.sum(-1, keepdim=True).clamp_min(1e-12)
|
|
95
|
+
intensity = power / total
|
|
96
|
+
threshold = math.log(half / alpha) / half
|
|
97
|
+
bins = torch.arange(1, half + 1, device=x.device, dtype=torch.float32)
|
|
98
|
+
period = context / bins
|
|
99
|
+
left = torch.nn.functional.pad(intensity[:, :-1], (1, 0), value=float("inf"))
|
|
100
|
+
right = torch.nn.functional.pad(intensity[:, 1:], (0, 1), value=float("inf"))
|
|
101
|
+
peak = (intensity > left) & (intensity > right) & (intensity > threshold)
|
|
102
|
+
# Require at least 2.5 cycles in the observed history.
|
|
103
|
+
longest = torch.floor(count / 2.5)
|
|
104
|
+
peak &= (period >= 2) & (period <= longest)
|
|
105
|
+
peak &= count >= MIN_OBSERVED
|
|
106
|
+
# Exponential noise has E[log I] = log(mean) - Euler gamma.
|
|
107
|
+
# Scale the window with zero-padding to cover short series' broad spectral peaks.
|
|
108
|
+
logi = intensity.clamp_min(1e-12).log()
|
|
109
|
+
w = (LOCAL * context / safe).round().clamp(LOCAL, MAX_LOCAL).long()
|
|
110
|
+
csum = torch.nn.functional.pad(logi.cumsum(-1), (1, 0))
|
|
111
|
+
k = torch.arange(half, device=x.device)[None]
|
|
112
|
+
lo_i = (k - w).clamp_min(0)
|
|
113
|
+
hi_i = (k + w + 1).clamp_max(half)
|
|
114
|
+
background = (csum.gather(-1, hi_i) - csum.gather(-1, lo_i)) / (hi_i - lo_i)
|
|
115
|
+
background = (background + EULER).exp()
|
|
116
|
+
peak &= intensity > local * background
|
|
117
|
+
score = torch.where(peak, intensity, torch.zeros_like(intensity))
|
|
118
|
+
top, index = score.topk(min(3 * slots, half), dim=-1)
|
|
119
|
+
candidates = torch.arange(2, half + 1, device=x.device, dtype=torch.float32)
|
|
120
|
+
centre = (index.float() + 1)[..., None]
|
|
121
|
+
offset = (context / candidates)[None, None] - centre
|
|
122
|
+
near = offset.abs() < 1
|
|
123
|
+
# A kept period is a candidate next to a peak, or the fallback when no candidate is. On a
|
|
124
|
+
# CPU, a long span with few such candidates skips its table; the periods match the table's
|
|
125
|
+
# unless two neighboring candidates tie within float32 rounding.
|
|
126
|
+
wanted = None
|
|
127
|
+
if context > TABLE_SPAN and z.device.type == "cpu":
|
|
128
|
+
wanted = (near & (top > 0)[..., None]).flatten(0, 1).any(0)
|
|
129
|
+
if wanted is None or int(wanted.sum()) > PEAK_COLUMNS:
|
|
130
|
+
exact = _power(z, *_refine_table(context, x.device)[1:])
|
|
131
|
+
else:
|
|
132
|
+
exact = _peak_power(z, candidates, wanted)
|
|
133
|
+
refined = torch.where(near, exact[:, None], torch.full_like(offset, -1)).argmax(-1)
|
|
134
|
+
periods = candidates[refined]
|
|
135
|
+
keep = top > 0
|
|
136
|
+
# A period dividing the patch length has the same phase in every patch.
|
|
137
|
+
keep &= torch.remainder(float(patch), periods) != 0
|
|
138
|
+
same = periods[:, :, None] == periods[:, None, :]
|
|
139
|
+
earlier = torch.ones_like(same[0]).tril(-1)
|
|
140
|
+
keep &= ~(same & earlier & keep[:, None, :]).any(-1)
|
|
141
|
+
order = torch.arange(keep.shape[-1], device=x.device).expand_as(keep)
|
|
142
|
+
order = torch.where(keep, order, order + keep.shape[-1]).argsort(-1)[:, :slots]
|
|
143
|
+
periods = torch.where(keep, periods, torch.zeros_like(periods)).gather(-1, order)
|
|
144
|
+
return periods.reshape(*shape, slots)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def select_periods(config, values: torch.Tensor, history: int, far_len: int) -> torch.Tensor:
|
|
148
|
+
"""Return [B,V,slots] periods for values [B,V,T] with `history` history steps.
|
|
149
|
+
Use the detector span matching observed history; `far_len=0` selects full history."""
|
|
150
|
+
|
|
151
|
+
def detect(x, context):
|
|
152
|
+
return detect_periods(x, context, config.period_slots, config.period_alpha,
|
|
153
|
+
config.period_local, config.patch_length)
|
|
154
|
+
|
|
155
|
+
if not far_len:
|
|
156
|
+
return detect(values, history)
|
|
157
|
+
near_history = history - far_len
|
|
158
|
+
out = detect(values[..., far_len:], near_history)
|
|
159
|
+
has_far = torch.isfinite(values[..., :far_len]).any(-1, keepdim=True)
|
|
160
|
+
mid = min(config.detector_mid, history)
|
|
161
|
+
mid_start = history - mid
|
|
162
|
+
if mid > near_history and bool(has_far.any()):
|
|
163
|
+
out = torch.where(has_far, detect(values[..., mid_start:], mid), out)
|
|
164
|
+
if mid_start > 0:
|
|
165
|
+
older = torch.isfinite(values[..., :mid_start]).any(-1, keepdim=True)
|
|
166
|
+
if bool(older.any()):
|
|
167
|
+
out = torch.where(older, detect(values, history), out)
|
|
168
|
+
return out
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def period_rotary(periods: torch.Tensor, starts: torch.Tensor, patch: int, half: int):
|
|
172
|
+
"""Return rotary cos/sin [N,1,S,half] for token starts [S] in raw steps (float64).
|
|
173
|
+
The slowest `slots` pairs encode detected periods; missing periods have zero phase."""
|
|
174
|
+
n, slots = periods.shape
|
|
175
|
+
size = starts.shape[0]
|
|
176
|
+
frequency = 10000 ** (-torch.arange(half, device=periods.device, dtype=torch.float32) / half)
|
|
177
|
+
base = (starts / patch).float()[:, None] * frequency
|
|
178
|
+
steps = starts.double()
|
|
179
|
+
angle = base.expand(n, size, half).clone()
|
|
180
|
+
p = periods.double()
|
|
181
|
+
valid = p > 0
|
|
182
|
+
safe = torch.where(valid, p, torch.ones_like(p))
|
|
183
|
+
for k in range(slots):
|
|
184
|
+
cycles = steps[None, :] / safe[:, k : k + 1]
|
|
185
|
+
phase = 2 * math.pi * (cycles - torch.floor(cycles))
|
|
186
|
+
phase = torch.where(valid[:, k : k + 1], phase, torch.zeros_like(phase))
|
|
187
|
+
angle[:, :, half - slots + k] = phase.float()
|
|
188
|
+
return angle.cos()[:, None], angle.sin()[:, None]
|
simons/predictor.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""GluonTS predictor for Simons; requires GluonTS."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
from gluonts.model.forecast import QuantileForecast
|
|
5
|
+
|
|
6
|
+
from .forecast import QUANTILES, forecast_series
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class SimonsPredictor:
|
|
10
|
+
"""Yield GluonTS forecasts for entries with target [T] or [V,T] and start (pandas Period).
|
|
11
|
+
Forecast arrays [10,H] or [10,H,V] hold quantiles 0.1,...,0.9 and their mean.
|
|
12
|
+
With covariate weights and `use_covariates`, the entries' `feat_dynamic_real` [C,T+H] and
|
|
13
|
+
`past_feat_dynamic_real` [C,T] are passed; `**options` go to `forecast_series`."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, model, prediction_length: int, batch_size: int = 1024,
|
|
16
|
+
use_covariates: bool = True, **options):
|
|
17
|
+
self.model = model
|
|
18
|
+
self.prediction_length = prediction_length
|
|
19
|
+
self.batch_size = batch_size
|
|
20
|
+
self.use_covariates = use_covariates and bool(model.config.covariates)
|
|
21
|
+
self.options = options
|
|
22
|
+
|
|
23
|
+
def predict(self, dataset, **kwargs):
|
|
24
|
+
"""Yield forecasts lazily in groups of `batch_size` entries."""
|
|
25
|
+
keys = [str(q) for q in QUANTILES] + ["mean"]
|
|
26
|
+
for entries in batcher(dataset, self.batch_size):
|
|
27
|
+
targets = [np.asarray(entry["target"], dtype=np.float32) for entry in entries]
|
|
28
|
+
covariates = {}
|
|
29
|
+
if self.use_covariates and any("feat_dynamic_real" in e or
|
|
30
|
+
"past_feat_dynamic_real" in e for e in entries):
|
|
31
|
+
covariates = {
|
|
32
|
+
"future_covariates": [e.get("feat_dynamic_real") for e in entries],
|
|
33
|
+
"past_covariates": [e.get("past_feat_dynamic_real") for e in entries],
|
|
34
|
+
}
|
|
35
|
+
forecasts = forecast_series(self.model, targets, self.prediction_length,
|
|
36
|
+
self.batch_size, **covariates, **self.options)
|
|
37
|
+
for entry, target, prediction in zip(entries, targets, forecasts):
|
|
38
|
+
array = prediction.T if target.ndim == 1 else prediction.transpose(2, 1, 0)
|
|
39
|
+
yield QuantileForecast(
|
|
40
|
+
forecast_arrays=np.concatenate([array, array.mean(axis=0, keepdims=True)]),
|
|
41
|
+
start_date=entry["start"] + target.shape[-1],
|
|
42
|
+
forecast_keys=keys,
|
|
43
|
+
item_id=entry.get("item_id"),
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def batcher(iterable, size: int):
|
|
48
|
+
"""Consecutive lists of at most `size` items, reading the iterable lazily."""
|
|
49
|
+
batch = []
|
|
50
|
+
for item in iterable:
|
|
51
|
+
batch.append(item)
|
|
52
|
+
if len(batch) == size:
|
|
53
|
+
yield batch
|
|
54
|
+
batch = []
|
|
55
|
+
if batch:
|
|
56
|
+
yield batch
|
simons/synth/__init__.py
ADDED
simons/synth/augment.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Augment standardized synthetic series with mixing, seasonality, filtering and quantization."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
|
|
5
|
+
import torch
|
|
6
|
+
|
|
7
|
+
from simons.synth.base import _logu, _standardise, _u
|
|
8
|
+
|
|
9
|
+
CATEGORIES = ("mix", "season", "filter", "lattice")
|
|
10
|
+
CONFIG = None
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def configure(categories, rate, weights):
|
|
14
|
+
global CONFIG
|
|
15
|
+
cats = tuple(c for c in str(categories or "").split(",") if c)
|
|
16
|
+
if not cats or rate <= 0:
|
|
17
|
+
CONFIG = None
|
|
18
|
+
return
|
|
19
|
+
if not set(cats) <= set(CATEGORIES):
|
|
20
|
+
raise ValueError(f"augmentation categories must be some of {CATEGORIES}")
|
|
21
|
+
if weights is None:
|
|
22
|
+
w = [1.0] * len(cats)
|
|
23
|
+
else:
|
|
24
|
+
w = [float(v) for v in str(weights).split(",")]
|
|
25
|
+
if len(w) != len(cats) or min(w) < 0 or sum(w) <= 0:
|
|
26
|
+
raise ValueError("weights needs one nonnegative weight per category")
|
|
27
|
+
CONFIG = {"categories": cats, "rate": float(rate), "weights": tuple(w)}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _dirichlet15(gen, n, k, device):
|
|
31
|
+
"""Draw Dirichlet(1.5) rows using Gamma(1.5) = Exp(1) + z^2 / 2."""
|
|
32
|
+
g = -torch.log(_u(gen, (n, k), device=device).clamp_min(1e-12))
|
|
33
|
+
g = g + 0.5 * torch.randn((n, k), generator=gen, device=device) ** 2
|
|
34
|
+
return g / g.sum(-1, keepdim=True)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _mix(gen, x):
|
|
38
|
+
n, length = x.shape
|
|
39
|
+
device = x.device
|
|
40
|
+
p1 = torch.randperm(n, generator=gen, device=device)
|
|
41
|
+
p2 = torch.randperm(n, generator=gen, device=device)
|
|
42
|
+
three = _u(gen, (n, 1), device=device) < 0.5
|
|
43
|
+
wa = _dirichlet15(gen, n, 3, device)
|
|
44
|
+
wb = _dirichlet15(gen, n, 3, device)
|
|
45
|
+
two = torch.tensor([1.0, 1.0, 0.0], device=device)
|
|
46
|
+
wa = torch.where(three, wa, wa * two)
|
|
47
|
+
wb = torch.where(three, wb, wb * two)
|
|
48
|
+
wa, wb = wa / wa.sum(-1, keepdim=True), wb / wb.sum(-1, keepdim=True)
|
|
49
|
+
t = torch.arange(length, device=device, dtype=torch.float32)[None] / length
|
|
50
|
+
centre = _u(gen, (n, 1), 0.2, 0.8, device)
|
|
51
|
+
width = _logu(gen, (n, 1), 0.01, 0.2, device)
|
|
52
|
+
s = torch.sigmoid((t - centre) / width)
|
|
53
|
+
s = torch.where(_u(gen, (n, 1), device=device) < 0.5, s, 0.0)
|
|
54
|
+
y = (wa[:, :1] * (1 - s) + wb[:, :1] * s) * x
|
|
55
|
+
y = y + (wa[:, 1:2] * (1 - s) + wb[:, 1:2] * s) * x[p1]
|
|
56
|
+
return y + (wa[:, 2:] * (1 - s) + wb[:, 2:] * s) * x[p2]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
_DAY_STEPS = (24.0, 96.0, 288.0, 48.0, 1.0)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _season(gen, x):
|
|
63
|
+
n, length = x.shape
|
|
64
|
+
device = x.device
|
|
65
|
+
t = torch.arange(length, device=device, dtype=torch.float32)[None]
|
|
66
|
+
c = _u(gen, (n, 1), 0.2, 2.0, device)
|
|
67
|
+
a = _u(gen, (n, 1), 0.2, 0.8, device)
|
|
68
|
+
day = torch.tensor(_DAY_STEPS, device=device)[
|
|
69
|
+
torch.randint(len(_DAY_STEPS), (n, 1), generator=gen, device=device)]
|
|
70
|
+
phase = _u(gen, (n, 1), device=device)
|
|
71
|
+
week_pos = torch.remainder(t / (7 * day) + phase, 1.0)
|
|
72
|
+
weekend = (week_pos >= 5 / 7).float()
|
|
73
|
+
up = torch.where(_u(gen, (n, 1), device=device) < 0.25, 1.0, -1.0)
|
|
74
|
+
square = 1 + up * a * weekend
|
|
75
|
+
cycles = _u(gen, (n, 1), 1.0, 4.0, device)
|
|
76
|
+
sine = 1 + a * torch.sin(2 * math.pi * (cycles * t / length + phase))
|
|
77
|
+
m = torch.where(_u(gen, (n, 1), device=device) < 0.5, square, sine)
|
|
78
|
+
base = x - x.amin(-1, keepdim=True) + c
|
|
79
|
+
return base * m
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _filter(gen, x, taps=32):
|
|
83
|
+
n, length = x.shape
|
|
84
|
+
device = x.device
|
|
85
|
+
size = torch.randint(2, taps + 1, (n, 1), generator=gen, device=device)
|
|
86
|
+
j = torch.arange(taps, device=device)[None]
|
|
87
|
+
live = j < size
|
|
88
|
+
smooth_w = -torch.log(_u(gen, (n, taps), device=device).clamp_min(1e-12)) * live
|
|
89
|
+
smooth_w = smooth_w / smooth_w.sum(-1, keepdim=True)
|
|
90
|
+
signed_w = torch.randn((n, taps), generator=gen, device=device) * live
|
|
91
|
+
signed_w = signed_w / signed_w.abs().sum(-1, keepdim=True).clamp_min(1e-6)
|
|
92
|
+
w = torch.where(_u(gen, (n, 1), device=device) < 0.7, smooth_w, signed_w)
|
|
93
|
+
# Repeat the first value on the left to avoid a start-up transient.
|
|
94
|
+
padded = torch.cat([x[:, :1].expand(n, taps - 1), x], -1)
|
|
95
|
+
y = torch.zeros_like(x)
|
|
96
|
+
for k in range(taps):
|
|
97
|
+
y = y + w[:, k : k + 1] * padded[:, taps - 1 - k : taps - 1 - k + length]
|
|
98
|
+
diff = torch.cat([torch.zeros_like(x[:, :1]), x[:, 1:] - x[:, :-1]], -1)
|
|
99
|
+
integ = x.cumsum(-1)
|
|
100
|
+
kind = _u(gen, (n, 1), device=device)
|
|
101
|
+
return torch.where(kind < 0.15, diff, torch.where(kind < 0.3, integ, y))
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _lattice(gen, x):
|
|
105
|
+
n, length = x.shape
|
|
106
|
+
device = x.device
|
|
107
|
+
delta = _logu(gen, (n, 1), 0.05, 0.5, device)
|
|
108
|
+
offset = _u(gen, (n, 1), device=device)
|
|
109
|
+
quant = delta * torch.floor(x / delta + offset)
|
|
110
|
+
q = _u(gen, (n, 1), 0.05, 0.5, device)
|
|
111
|
+
ordered = x.sort(-1).values
|
|
112
|
+
floor = ordered.gather(-1, (q * (length - 1)).long())
|
|
113
|
+
censored = torch.maximum(x, floor)
|
|
114
|
+
return torch.where(_u(gen, (n, 1), device=device) < 0.4, censored, quant)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
_MAKERS = {"mix": _mix, "season": _season, "filter": _filter, "lattice": _lattice}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def apply(gen, x):
|
|
121
|
+
"""Augment standardised [n, L] series x; returns standardised series."""
|
|
122
|
+
if CONFIG is None:
|
|
123
|
+
return x
|
|
124
|
+
n, _ = x.shape
|
|
125
|
+
device = x.device
|
|
126
|
+
cats, weights = CONFIG["categories"], CONFIG["weights"]
|
|
127
|
+
active = _u(gen, (n, 1), device=device) < CONFIG["rate"]
|
|
128
|
+
count = torch.where(_u(gen, (n, 1), device=device) < 0.3, 2, 1)
|
|
129
|
+
# Gumbel top-k samples weighted categories without replacement.
|
|
130
|
+
w = torch.tensor(weights, device=device)[None]
|
|
131
|
+
logw = torch.log(w.clamp_min(1e-12))
|
|
132
|
+
gumbel = -torch.log(-torch.log(_u(gen, (n, len(cats)), device=device).clamp(1e-12, 1 - 1e-7)))
|
|
133
|
+
keys = logw + gumbel
|
|
134
|
+
rank = keys.argsort(-1, descending=True).argsort(-1)
|
|
135
|
+
chosen = active & (rank < count) & (w > 0) # [n, C]
|
|
136
|
+
for c in CATEGORIES:
|
|
137
|
+
if c not in cats:
|
|
138
|
+
continue
|
|
139
|
+
col = cats.index(c)
|
|
140
|
+
y = _standardise(_MAKERS[c](gen, x))
|
|
141
|
+
y = torch.where(torch.isfinite(y), y, 0)
|
|
142
|
+
x = torch.where(chosen[:, col : col + 1], y, x)
|
|
143
|
+
return x
|