Download generator.py from putty77/metronome-r2: direct link, hf CLI and curl.
- Browser
- Download file 23.7 kB
-
https://huggingface.co/putty77/metronome-r2/resolve/main/generator.py
- Command line
-
hf download hf://putty77/metronome-r2/generator.py
-
curl -L -o generator.py https://huggingface.co/putty77/metronome-r2/resolve/main/generator.py
23.7 kB
| """metronome-v1 — cascade SN91 data generator. | |
| Design goals (see /root/91/STRATEGY.md): | |
| * throughput: fully vectorized numpy, all families O(L) / O(L log L); | |
| no torch, no pandas, no O(L^3) GP draws. Target >=400k pts/s/core. | |
| * prefix-stable interleaved mixture: series are produced in fixed-size | |
| blocks; block b depends only on (seed, b), every block carries the full | |
| family mixture, so ANY consumed prefix matches the intended mixture and | |
| the heat (same generation_seed) trains on a representative prefix. | |
| * determinism: one np.random.Generator per block from | |
| SeedSequence([seed, block]); no wall clock, no hash(), no threads, no | |
| global RNG. Elementwise numpy / pocketfft / scipy lfilter only (no large | |
| matmul reductions => digest independent of BLAS thread count). | |
| * eval-shaped priors: seasonal periods {3,7,24,48,60,96,120,144,240,288} | |
| (the forge pool's FREQ_MAP), regime-switching mean-reversion with | |
| stochastic volatility, calendar-style multiplicative seasonality, | |
| counts / bounded / censored series, steps + spikes, heavy raw-scale | |
| diversity (the arcsinh causal scaler sees shape only), plus online | |
| TSMixup / reversal / quantization / constant-left-prefix augmentation. | |
| * contract: uniform length 4096 (1:1 stream-points -> trained-tokens, | |
| single trainer bucket), float64, finite, |x| <= 1e6. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import os | |
| from collections.abc import Iterator | |
| import numpy as np | |
| from scipy.signal import lfilter | |
| from cascade.interface import DataGenerator | |
| L = 4096 # uniform emitted length == context_length | |
| BLOCK = 256 # series per generation block | |
| MAX_ABS = 1.0e6 # safety clip (contract ceiling is float32 max) | |
| # Seasonal periods present in the eval pool (tsbench_forge FREQ_MAP) plus a | |
| # few off-grid periods for breadth. Weights tilt toward the common cadences. | |
| EVAL_PERIODS = np.array([3, 7, 24, 48, 60, 96, 120, 144, 240, 288], dtype=np.float64) | |
| EVAL_PERIOD_W = np.array([.04, .14, .20, .12, .08, .10, .08, .08, .08, .08]) | |
| OFFGRID_PERIODS = np.array([5, 12, 16, 30, 36, 72, 168, 336, 512, 720, 1024, 2048], dtype=np.float64) | |
| # cadence-consistent daily+weekly pairs in SAMPLE units: (daily cycle, weekly | |
| # cycle) for each cadence the eval pool carries; second period capped so >=2 | |
| # full cycles fit in L=4096. | |
| PERIOD_PAIRS = np.array([ | |
| [24, 168], [48, 336], [96, 672], [144, 1008], [288, 2016], | |
| [60, 1440], [7, 30], [120, 840], [240, 1680], [24, 720], | |
| ], dtype=np.float64) | |
| _FREQS = np.fft.rfftfreq(L) # (F,) cycles/sample | |
| _F = _FREQS.shape[0] | |
| _T = np.arange(L, dtype=np.float64) | |
| def _norm_rows(x: np.ndarray) -> np.ndarray: | |
| """Standardize each row to ~unit scale (leaves shape, kills blowups).""" | |
| mu = x.mean(axis=-1, keepdims=True) | |
| sd = x.std(axis=-1, keepdims=True) | |
| return (x - mu) / np.maximum(sd, 1e-9) | |
| def _spectral_sample(rng: np.random.Generator, power: np.ndarray) -> np.ndarray: | |
| """Draw stationary Gaussian rows with the given (R, F) power spectrum. | |
| Circulant-embedding style: amplitude = sqrt(power), phases uniform. | |
| O(L log L) per row via batched irfft; unit-variance normalized. | |
| """ | |
| r = power.shape[0] | |
| phase = rng.uniform(0.0, 2.0 * np.pi, size=(r, _F)) | |
| spec = np.sqrt(np.maximum(power, 0.0)) * np.exp(1j * phase) | |
| spec[:, 0] = 0.0 # zero mean; level added separately | |
| x = np.fft.irfft(spec, n=L, axis=-1) | |
| return _norm_rows(x) | |
| def _comb_power(rng: np.random.Generator, periods: np.ndarray) -> np.ndarray: | |
| """(R, F) spectral lines at 1/p and harmonics with decaying amplitude.""" | |
| r = periods.shape[0] | |
| power = np.zeros((r, _F)) | |
| n_harm = rng.integers(1, 6, size=r) | |
| decay = rng.uniform(0.4, 0.95, size=r) | |
| width = rng.uniform(0.0, 2e-4, size=r) # 0 => pure line, >0 => drifting phase | |
| for i in range(r): | |
| p = periods[i] | |
| for k in range(1, int(n_harm[i]) + 1): | |
| f0 = k / p | |
| if f0 > 0.5: | |
| break | |
| amp = decay[i] ** (k - 1) | |
| if width[i] > 0.0: | |
| power[i] += amp * np.exp(-0.5 * ((_FREQS - f0) / (width[i] + 1e-5)) ** 2) | |
| else: | |
| idx = int(round(f0 * L)) | |
| if 0 < idx < _F: | |
| power[i, idx] += amp * L # line mass | |
| return power | |
| # ---------------------------------------------------------------- families | |
| def fam_spectral_gp(rng: np.random.Generator, n: int) -> np.ndarray: | |
| """KernelSynth-class GP textures via spectral synthesis. | |
| Mixture of: smooth low-pass bumps (RBF/Matern-like), quasi-periodic | |
| combs at eval + off-grid periods, and 1/f^alpha long-memory floors. | |
| """ | |
| power = np.zeros((n, _F)) | |
| # smooth component: gaussian bump at f=0 with random bandwidth | |
| bw = 10.0 ** rng.uniform(-3.2, -0.8, size=(n, 1)) # lengthscale ~ 1/bw | |
| power += rng.uniform(0.2, 1.0, size=(n, 1)) * np.exp(-0.5 * (_FREQS / bw) ** 2) | |
| # long-memory / random-walk floor | |
| alpha = rng.uniform(0.3, 2.6, size=(n, 1)) | |
| has_pl = rng.random(size=(n, 1)) < 0.55 | |
| power += np.where(has_pl, rng.uniform(0.05, 0.6, size=(n, 1)) | |
| * (_FREQS + 1.0 / L) ** (-alpha), 0.0) | |
| # periodic combs | |
| use_comb = rng.random(n) < 0.75 | |
| if use_comb.any(): | |
| m = int(use_comb.sum()) | |
| on_grid = rng.random(m) < 0.7 | |
| p_grid = rng.choice(EVAL_PERIODS, size=m, p=EVAL_PERIOD_W) | |
| p_off = rng.choice(OFFGRID_PERIODS, size=m) | |
| periods = np.where(on_grid, p_grid, p_off) * rng.uniform(0.98, 1.02, size=m) | |
| power[use_comb] += rng.uniform(0.5, 6.0, size=(m, 1)) * _comb_power(rng, periods) | |
| x = _spectral_sample(rng, power) | |
| # second comb at the cadence-paired weekly period (genuine multi-seasonality) | |
| dual = rng.random(n) < 0.35 | |
| if dual.any(): | |
| m = int(dual.sum()) | |
| pair = PERIOD_PAIRS[rng.integers(0, len(PERIOD_PAIRS), size=m)] | |
| p2 = np.where(rng.random(m) < 0.7, pair[:, 1], pair[:, 0]) | |
| x[dual] += rng.uniform(0.2, 1.0, size=(m, 1)) * _spectral_sample( | |
| rng, _comb_power(rng, p2) + 1e-6) | |
| return x | |
| _AR_GRID = np.array([0.85, 0.93, 0.97, 0.99, 0.995, 0.999, 0.9997]) | |
| def fam_ou_sde(rng: np.random.Generator, n: int) -> np.ndarray: | |
| """Regime-switching mean-reverting SDE with stochastic volatility. | |
| AR(1) core (exact OU discretization) grouped by coefficient for | |
| vectorized lfilter; slow log-vol envelope (heteroskedasticity), 1-3 | |
| regime shifts in mean level, optional fBm-like long-memory add-on. | |
| """ | |
| a_idx = rng.integers(0, len(_AR_GRID), size=n) | |
| # stochastic volatility: smooth log-vol from low-pass spectral noise | |
| volp = np.exp(-0.5 * (_FREQS / 10.0 ** rng.uniform(-3.3, -2.0, size=(n, 1))) ** 2) | |
| logv = _spectral_sample(rng, volp) * rng.uniform(0.1, 0.9, size=(n, 1)) | |
| eps = rng.standard_normal((n, L)) | |
| heavy = rng.random(n) < 0.3 # Student-t innovations | |
| if heavy.any(): | |
| m = int(heavy.sum()) | |
| df = rng.uniform(3.0, 12.0, size=(m, 1)) | |
| eps[heavy] = rng.standard_t(df, size=(m, L)) | |
| eps *= np.exp(logv) | |
| x = np.empty((n, L)) | |
| for gi, a in enumerate(_AR_GRID): | |
| rows = a_idx == gi | |
| if rows.any(): | |
| x[rows] = lfilter([1.0], [1.0, -a], eps[rows], axis=-1) | |
| x = _norm_rows(x) | |
| # regime shifts in level (smoothed steps) | |
| k = rng.integers(0, 4, size=n) | |
| for i in range(n): | |
| for _ in range(int(k[i])): | |
| cp = int(rng.integers(L // 16, L - L // 16)) | |
| x[i, cp:] += rng.normal(0.0, 1.4) | |
| # optional seasonal overlay on the mean | |
| seas = rng.random(n) < 0.45 | |
| if seas.any(): | |
| m = int(seas.sum()) | |
| p = rng.choice(EVAL_PERIODS, size=m, p=EVAL_PERIOD_W) | |
| x[seas] += rng.uniform(0.3, 1.6, size=(m, 1)) * np.sin( | |
| 2 * np.pi * _T / p[:, None] + rng.uniform(0, 2 * np.pi, size=(m, 1))) | |
| return x | |
| def fam_calendar(rng: np.random.Generator, n: int) -> np.ndarray: | |
| """ForecastPFN-style multiplicative trend x multi-seasonality x noise. | |
| Pure integer-grid harmonics (no pandas). Two independent draws are | |
| sigmoid-blended (regime transition) like TempoPFN's transition_ratio=1. | |
| """ | |
| def draw(m: int) -> np.ndarray: | |
| # trend: linear + clamped exponential | |
| slope = rng.normal(0.0, 0.6 / L, size=(m, 1)) | |
| eb = np.exp(np.clip(rng.normal(0.0, 0.4 / L, size=(m, 1)), -2.3 / L, 2.3 / L)) | |
| trend = (1.0 + slope * _T) * eb ** _T | |
| # seasonality: product of two Fourier stacks; ~40% of rows carry a | |
| # cadence-consistent daily+weekly pair, the rest distinct eval periods | |
| seas = np.ones((m, L)) | |
| pair = PERIOD_PAIRS[rng.integers(0, len(PERIOD_PAIRS), size=m)] | |
| use_pair = rng.random(m) < 0.4 | |
| p_a = np.where(use_pair, pair[:, 0], rng.choice(EVAL_PERIODS, size=m, p=EVAL_PERIOD_W)) | |
| p_b_ind = rng.choice(EVAL_PERIODS, size=m, p=EVAL_PERIOD_W) | |
| p_b_ind = np.where(p_b_ind == p_a, p_b_ind * 2.0, p_b_ind) # dedupe stacks | |
| p_b = np.where(use_pair, pair[:, 1], p_b_ind) | |
| for stack, p_sel in enumerate((p_a, p_b)): | |
| on = rng.random(m) < (0.9 if stack == 0 else 0.6) | |
| if not on.any(): | |
| continue | |
| p = p_sel[:, None] | |
| amp = rng.uniform(0.05, 0.55, size=(m, 1)) * on[:, None] | |
| h1 = np.sin(2 * np.pi * _T / p + rng.uniform(0, 2 * np.pi, (m, 1))) | |
| h2 = rng.uniform(0.2, 0.7, (m, 1)) * np.sin( | |
| 4 * np.pi * _T / p + rng.uniform(0, 2 * np.pi, (m, 1))) | |
| # asymmetric diurnal-like shape via squashing | |
| comp = np.tanh(1.3 * (h1 + h2)) | |
| seas *= 1.0 + amp * comp | |
| base = trend * seas | |
| # multiplicative Weibull noise, median 1 | |
| k = rng.uniform(1.0, 5.0, size=(m, 1)) | |
| scale = rng.choice([0.05, 0.35, 0.8], size=(m, 1), p=[0.6, 0.3, 0.1]) \ | |
| * rng.uniform(0.5, 1.5, size=(m, 1)) | |
| w = rng.weibull(k, size=(m, L)) / (np.log(2.0) ** (1.0 / k)) | |
| return base * (1.0 + scale * (w - 1.0)) | |
| x1, x2 = draw(n), draw(n) | |
| c = rng.uniform(0.2 * L, 0.8 * L, size=(n, 1)) | |
| wdt = rng.uniform(L / 40, L / 6, size=(n, 1)) | |
| s = 1.0 / (1.0 + np.exp(-(_T - c) / wdt)) | |
| return _norm_rows(x1 * (1 - s) + x2 * s) | |
| def fam_cauker_lite(rng: np.random.Generator, n: int) -> np.ndarray: | |
| """SCM over fast spectral-GP roots with nonlinear activations.""" | |
| roots = fam_spectral_gp(rng, 2 * n) | |
| a, b = roots[:n], roots[n:] | |
| w = rng.normal(0.0, 1.0, size=(n, 2, 1)) | |
| bias = rng.normal(0.0, 0.5, size=(n, 1)) | |
| z = w[:, 0] * a + w[:, 1] * b + bias | |
| act = rng.integers(0, 5, size=n) | |
| x = np.empty_like(z) | |
| for i in range(n): | |
| zi = z[i] | |
| k = act[i] | |
| if k == 0: | |
| x[i] = np.maximum(zi, 0.15 * zi) # leaky relu (floor effects) | |
| elif k == 1: | |
| x[i] = np.tanh(zi) # saturating | |
| elif k == 2: | |
| x[i] = np.sin(rng.uniform(0.5, 2.5) * zi) | |
| elif k == 3: | |
| c = rng.uniform(1.0, 5.0) | |
| x[i] = np.mod(zi, c) # circular re-indexing | |
| else: | |
| x[i] = zi | |
| return _norm_rows(x) | |
| def fam_steps_spikes(rng: np.random.Generator, n: int) -> np.ndarray: | |
| """Changepoint step processes and spike trains (obs/web style).""" | |
| x = np.zeros((n, L)) | |
| kind = rng.random(n) | |
| for i in range(n): | |
| if kind[i] < 0.55: # step / level-shift process | |
| k = int(rng.integers(3, 40)) | |
| pos = np.sort(rng.integers(1, L, size=k)) | |
| jumps = rng.normal(0.0, 1.0, size=k) * rng.choice([0.3, 1.0, 3.0]) | |
| s = np.zeros(L) | |
| s[pos] = jumps | |
| x[i] = np.cumsum(s) | |
| if rng.random() < 0.5: # decay back (spike-and-decay) | |
| a = rng.uniform(0.95, 0.999) | |
| x[i] = lfilter([1.0], [1.0, -a], s) | |
| else: # spike train on quiet baseline | |
| base = rng.normal(0.0, rng.uniform(0.005, 0.15), size=L) | |
| k = int(rng.integers(3, 25)) | |
| pos = rng.integers(8, L - 8, size=k) | |
| amp = rng.uniform(3.0, 30.0, size=k) * rng.choice([-1.0, 1.0], size=k) \ | |
| if rng.random() < 0.3 else rng.uniform(3.0, 30.0, size=k) | |
| widths = rng.integers(1, 40, size=k) | |
| for p, a_, w_ in zip(pos, amp, widths): | |
| lo, hi = max(0, p - w_), min(L, p + w_ + 1) | |
| tri = 1.0 - np.abs(np.arange(lo - p, hi - p)) / (w_ + 1.0) | |
| base[lo:hi] += a_ * np.maximum(tri, 0.0) | |
| x[i] = base | |
| if rng.random() < 0.4: # periodic carrier underneath | |
| p = rng.choice(EVAL_PERIODS, p=EVAL_PERIOD_W) | |
| x[i] += rng.uniform(0.2, 1.0) * np.sin(2 * np.pi * _T / p + rng.uniform(0, 6.28)) | |
| return _norm_rows(x) | |
| def fam_ets_arma(rng: np.random.Generator, n: int) -> np.ndarray: | |
| """ETS/ARMA state-space: damped trends + AR(2)/MA noise, grouped lfilter.""" | |
| eps = rng.standard_normal((n, L)) | |
| heavy = rng.random(n) < 0.3 # Student-t innovations | |
| if heavy.any(): | |
| m = int(heavy.sum()) | |
| eps[heavy] = rng.standard_t(rng.uniform(3.0, 12.0, size=(m, 1)), size=(m, L)) | |
| x = np.empty((n, L)) | |
| # AR(2) with complex roots => pseudo-cyclic; group by small param grid | |
| p_grid = [(1.6, -0.64), (1.2, -0.36), (0.5, 0.3), (1.7, -0.72), (0.95, 0.0), (1.4, -0.45)] | |
| gi = rng.integers(0, len(p_grid), size=n) | |
| for g, (a1, a2) in enumerate(p_grid): | |
| rows = gi == g | |
| if rows.any(): | |
| x[rows] = lfilter([1.0], [1.0, -a1, -a2], eps[rows], axis=-1) | |
| x = _norm_rows(x) | |
| # damped local trend | |
| damp = rng.random(n) < 0.6 | |
| if damp.any(): | |
| m = int(damp.sum()) | |
| phi = rng.uniform(0.95, 0.9995, size=(m, 1)) | |
| slope = rng.normal(0.0, 2.0 / L, size=(m, 1)) | |
| x[damp] += slope * (1.0 - phi ** _T) / (1.0 - phi + 1e-9) | |
| # multiplicative seasonality | |
| seas = rng.random(n) < 0.5 | |
| if seas.any(): | |
| m = int(seas.sum()) | |
| p = rng.choice(EVAL_PERIODS, size=m, p=EVAL_PERIOD_W)[:, None] | |
| x[seas] *= 1.0 + rng.uniform(0.1, 0.5, size=(m, 1)) * np.sin( | |
| 2 * np.pi * _T / p + rng.uniform(0, 6.28, size=(m, 1))) | |
| return x | |
| def fam_counts_bounded(rng: np.random.Generator, n: int) -> np.ndarray: | |
| """Non-negative counts (Poisson/NB on seasonal intensity), 0-100 bounded | |
| saturating signals, and zero-inflated intermittent demand.""" | |
| n_int = n // 4 # intermittent-demand slice | |
| n = n - n_int | |
| half = n // 2 | |
| out = np.empty((n + n_int, L)) | |
| if n_int: | |
| occ = rng.random((n_int, L)) < rng.uniform(0.05, 0.4, size=(n_int, 1)) | |
| mag = rng.gamma(shape=rng.uniform(1.0, 4.0, size=(n_int, 1)), | |
| scale=rng.uniform(1.0, 20.0, size=(n_int, 1)), size=(n_int, L)) | |
| base = np.abs(rng.normal(0.0, 0.02, size=(n_int, L))) | |
| out[n:] = np.round(occ * mag) + base | |
| # counts: lam = exp(seasonal + trend + noise), Poisson or NB | |
| base = fam_spectral_gp(rng, half) * rng.uniform(0.2, 0.9, size=(half, 1)) | |
| lam = np.exp(np.clip(base + rng.uniform(0.0, 5.0, size=(half, 1)), -6, 12)) | |
| nb = rng.random(half) < 0.4 | |
| counts = rng.poisson(lam).astype(np.float64) | |
| if nb.any(): # overdispersed: gamma-mixed poisson | |
| g = rng.gamma(shape=rng.uniform(0.5, 3.0, size=(int(nb.sum()), 1)), | |
| scale=1.0, size=(int(nb.sum()), L)) | |
| counts[nb] = rng.poisson(lam[nb] * g).astype(np.float64) | |
| # viral spikes with decay on a few | |
| spike = rng.random(half) < 0.35 | |
| for i in np.where(spike)[0]: | |
| p0 = int(rng.integers(L // 8, L - 64)) | |
| dur = int(rng.integers(20, 400)) | |
| mag = rng.uniform(3.0, 50.0) | |
| t = np.arange(min(dur, L - p0)) | |
| counts[i, p0:p0 + len(t)] *= 1.0 + mag * np.exp(-t / max(dur / 4.0, 2.0)) | |
| out[:half] = counts | |
| # bounded 0..100 with saturation flats | |
| m = n - half | |
| raw = fam_spectral_gp(rng, m) * rng.uniform(15.0, 60.0, size=(m, 1)) \ | |
| + rng.uniform(10.0, 90.0, size=(m, 1)) | |
| out[half:n] = np.clip(raw, 0.0, 100.0) | |
| return out | |
| def fam_waveforms(rng: np.random.Generator, n: int) -> np.ndarray: | |
| """Sines/sawtooth with AM/FM drift — cheap regime coverage.""" | |
| p = np.where(rng.random(n) < 0.7, | |
| rng.choice(EVAL_PERIODS, size=n, p=EVAL_PERIOD_W), | |
| rng.uniform(8, 1500, size=n))[:, None] | |
| phase = rng.uniform(0, 2 * np.pi, size=(n, 1)) | |
| fm = 1.0 + rng.uniform(0.0, 0.05, size=(n, 1)) * np.sin( | |
| 2 * np.pi * _T / (p * rng.uniform(5, 15, size=(n, 1)))) | |
| ph = 2 * np.pi * np.cumsum(fm / p, axis=-1) + phase | |
| saw = rng.random(n) < 0.35 | |
| x = np.where(saw[:, None], | |
| 2.0 * (np.mod(ph / (2 * np.pi), 1.0)) - 1.0, | |
| np.sin(ph)) | |
| am = 1.0 + rng.uniform(0.05, 0.45, size=(n, 1)) * np.sin( | |
| 2 * np.pi * _T / (p * rng.uniform(4, 12, size=(n, 1))) + rng.uniform(0, 6.28, (n, 1))) | |
| x = x * am + rng.normal(0.0, 1.0, size=(n, L)) * rng.uniform(0.02, 0.35, size=(n, 1)) | |
| x += rng.normal(0.0, 1.5 / L, size=(n, 1)) * _T | |
| return x | |
| def fam_weather(rng: np.random.Generator, n: int) -> np.ndarray: | |
| """Weather archetypes: skew-locked diurnal + band-limited synoptic drift. | |
| Sub-kinds: temperature-like (diurnal + fronts), bounded 0-100 saturating | |
| (cloud/humidity), positive skewed (wind), slow pressure walk. | |
| """ | |
| p = PERIOD_PAIRS[rng.integers(0, len(PERIOD_PAIRS) - 3, size=n), 0][:, None] | |
| phase = rng.uniform(0, 2 * np.pi, size=(n, 1)) | |
| skew = rng.uniform(0.1, 0.6, size=(n, 1)) | |
| diurnal = np.sin(2 * np.pi * _T / p + phase) \ | |
| + skew * np.sin(4 * np.pi * _T / p + 2 * phase + rng.uniform(0, 1, (n, 1))) | |
| # slowly varying diurnal amplitude (seasonal envelope analogue) | |
| envp = np.exp(-0.5 * (_FREQS / 10.0 ** rng.uniform(-3.4, -2.6, size=(n, 1))) ** 2) | |
| env = 1.0 + 0.35 * _spectral_sample(rng, envp) | |
| # synoptic band: energy around periods 2p..10p (weather fronts) | |
| f0 = 1.0 / (rng.uniform(2.0, 10.0, size=(n, 1)) * p) | |
| syn_pow = np.exp(-0.5 * ((_FREQS - f0) / (0.6 * f0 + 1e-6)) ** 2) \ | |
| + 0.3 * np.exp(-0.5 * (_FREQS / (2 * f0 + 1e-6)) ** 2) | |
| synoptic = _spectral_sample(rng, syn_pow) | |
| amp_d = rng.uniform(0.4, 2.0, size=(n, 1)) | |
| amp_s = rng.uniform(0.4, 1.5, size=(n, 1)) | |
| base = amp_d * env * diurnal + amp_s * synoptic \ | |
| + rng.normal(0.0, 1.0, size=(n, L)) * rng.uniform(0.03, 0.25, size=(n, 1)) | |
| kind = rng.random(n) | |
| x = np.empty((n, L)) | |
| tmp = kind < 0.45 # temperature-like: as-is | |
| x[tmp] = base[tmp] | |
| bnd = (kind >= 0.45) & (kind < 0.70) # bounded 0-100, saturating | |
| if bnd.any(): | |
| m = int(bnd.sum()) | |
| x[bnd] = 100.0 / (1.0 + np.exp(-rng.uniform(0.8, 2.5, size=(m, 1)) * base[bnd])) | |
| wnd = (kind >= 0.70) & (kind < 0.90) # positive, right-skewed wind | |
| if wnd.any(): | |
| m = int(wnd.sum()) | |
| x[wnd] = np.abs(base[wnd]) ** rng.uniform(1.0, 1.6, size=(m, 1)) | |
| prs = kind >= 0.90 # pressure-like slow walk | |
| if prs.any(): | |
| m = int(prs.sum()) | |
| walkp = (_FREQS + 1.0 / L) ** -rng.uniform(1.8, 2.4, size=(m, 1)) | |
| x[prs] = 3.0 * _spectral_sample(rng, walkp) + 0.15 * base[prs] | |
| return x | |
| _FAMILIES = [ | |
| ("spectral_gp", fam_spectral_gp), | |
| ("ou_sde", fam_ou_sde), | |
| ("calendar", fam_calendar), | |
| ("cauker_lite", fam_cauker_lite), | |
| ("steps_spikes", fam_steps_spikes), | |
| ("ets_arma", fam_ets_arma), | |
| ("counts_bounded", fam_counts_bounded), | |
| ("waveforms", fam_waveforms), | |
| ("weather", fam_weather), | |
| ] | |
| _DEFAULT_WEIGHTS = { | |
| "spectral_gp": 0.22, "ou_sde": 0.16, "calendar": 0.14, "cauker_lite": 0.06, | |
| "steps_spikes": 0.11, "ets_arma": 0.08, "counts_bounded": 0.08, | |
| "waveforms": 0.04, "weather": 0.11, | |
| } | |
| class Generator(DataGenerator): | |
| """metronome-v1: interleaved fast mixture, uniform L=4096, prefix-stable.""" | |
| def __init__(self, config_dir: str, *, seed: int) -> None: | |
| cfg_path = os.path.join(config_dir, "config.json") | |
| cfg = {} | |
| if os.path.isfile(cfg_path): | |
| with open(cfg_path, encoding="utf-8") as fh: | |
| cfg = json.load(fh) | |
| w = dict(_DEFAULT_WEIGHTS) | |
| w.update(cfg.get("weights", {})) | |
| names = [nm for nm, _ in _FAMILIES] | |
| probs = np.array([max(float(w.get(nm, 0.0)), 0.0) for nm in names]) | |
| self._probs = probs / probs.sum() | |
| self._seed = int(seed) & 0x7FFFFFFF | |
| self._aug = cfg.get("augment", {}) | |
| def name(self) -> str: | |
| return "metronome-v1" | |
| # -------------------------------------------------------------- blocks | |
| def _block(self, b: int) -> np.ndarray: | |
| rng = np.random.default_rng(np.random.SeedSequence([self._seed, b])) | |
| fam_idx = rng.choice(len(_FAMILIES), size=BLOCK, p=self._probs) | |
| x = np.empty((BLOCK, L), dtype=np.float64) | |
| for fi, (_, fn) in enumerate(_FAMILIES): | |
| rows = np.where(fam_idx == fi)[0] | |
| if rows.size: | |
| x[rows] = fn(rng, rows.size) | |
| aug = self._aug | |
| r = rng.random(BLOCK) | |
| # TSMixup: convex combos within the block (cross-family) | |
| p_mix = float(aug.get("tsmixup", 0.15)) | |
| mix_rows = np.where(r < p_mix)[0] | |
| for i in mix_rows: | |
| k = int(rng.integers(2, 4)) | |
| others = rng.integers(0, BLOCK, size=k) | |
| wts = rng.dirichlet(np.ones(k + 1)) | |
| x[i] = wts[0] * x[i] + sum(wts[j + 1] * x[others[j]] for j in range(k)) | |
| # time reversal / sign flip | |
| rev = rng.random(BLOCK) < float(aug.get("reverse", 0.08)) | |
| x[rev] = x[rev, ::-1] | |
| flip = rng.random(BLOCK) < float(aug.get("signflip", 0.12)) | |
| x[flip] = -x[flip] | |
| # raw scale + offset diversity (shape is the signal; scale exercises | |
| # the causal scaler and the CRPS |y|-weighting) | |
| scale = 10.0 ** rng.uniform(-2.0, 4.5, size=(BLOCK, 1)) | |
| keep_raw = rng.random(BLOCK) < 0.25 # counts/bounded stay natural | |
| scale[keep_raw] = 1.0 | |
| off = rng.normal(0.0, 2.0, size=(BLOCK, 1)) * scale | |
| x = x * scale + off | |
| # quantization / integerization (count-like discreteness) | |
| q = np.where(rng.random(BLOCK) < float(aug.get("quantize", 0.12)))[0] | |
| for i in q: | |
| step = 10.0 ** rng.integers(-2, 3) | |
| x[i] = np.round(x[i] / step) * step | |
| # censoring at a bound (saturation flats) | |
| c = np.where(rng.random(BLOCK) < float(aug.get("censor", 0.08)))[0] | |
| for i in c: | |
| lo = np.quantile(x[i], rng.uniform(0.02, 0.25)) | |
| x[i] = np.maximum(x[i], lo) | |
| # constant left prefix — mimics the eval wrapper's left-pad fill | |
| pre = np.where(rng.random(BLOCK) < float(aug.get("pad_prefix", 0.12)))[0] | |
| for i in pre: | |
| cut = int(rng.integers(512, 3584)) | |
| x[i, :cut] = x[i, cut] | |
| np.nan_to_num(x, copy=False, nan=0.0, posinf=MAX_ABS, neginf=-MAX_ABS) | |
| np.clip(x, -MAX_ABS, MAX_ABS, out=x) | |
| return x | |
| def generate(self, n_series: int) -> Iterator[np.ndarray]: | |
| remaining = int(n_series) | |
| b = 0 | |
| while remaining > 0: | |
| block = self._block(b) | |
| take = min(BLOCK, remaining) | |
| for i in range(take): | |
| yield np.ascontiguousarray(block[i]) | |
| remaining -= take | |
| b += 1 | |