"""Synthetic data with known structure.
Every generator returns data whose segments, states, classes or warpings
are known, so that the methods of the package can be evaluated exactly.
Segmentation benchmarks return ``(X, change_points, states)``; collection
benchmarks return ``(collection, labels)``.
"""
from __future__ import annotations
import numpy as np
from scipy.integrate import solve_ivp
from scipy.interpolate import CubicSpline
from .._base import check_random_state
__all__ = [
"make_piecewise_stationary",
"make_correlation_switching",
"make_dynamic_switching",
"make_regime_process",
"make_energy_process",
"simulate_ph_cstr",
"simulate_mma_cstr",
"MMA_PARAMETERS",
"make_cbf",
"make_synthetic_control",
"make_signatures",
"make_motion_collection",
"make_correlation_sequences",
"make_dynamic_sequences",
"random_time_warp",
]
def _segment_lengths(n_segments, length, rng, vary):
if np.isscalar(length):
if vary:
w = rng.uniform(1 - vary, 1 + vary, n_segments)
lens = np.maximum(10, np.round(length * n_segments * w / w.sum())).astype(int)
else:
lens = np.full(n_segments, int(length))
else:
lens = np.asarray(length, int)
return lens
[docs]
def make_piecewise_stationary(n_segments: int = 4, length=200, n_variables: int = 3, change: str = "mean",
n_states: int | None = None, noise: float = 1.0, vary: float = 0.0, random_state=None):
"""Piecewise stationary Gaussian series.
Parameters
----------
change : {"mean", "variance", "correlation", "all"}
What differs between the states.
n_states : int, optional
Number of distinct states (segments cycle through them); default: one
state per segment.
vary : float
Relative variation of the segment lengths (0 = equal lengths).
Returns
-------
X : array (T, n)
change_points : array
states : array (n_segments,)
"""
rng = check_random_state(random_state)
k = n_segments if n_states is None else n_states
lens = _segment_lengths(n_segments, length, rng, vary)
params = []
for _ in range(k):
mu = rng.normal(0, 3, n_variables) if change in ("mean", "all") else np.zeros(n_variables)
if change in ("correlation", "all"):
A = rng.normal(size=(n_variables, n_variables))
C = A @ A.T
d = np.sqrt(np.diag(C))
C = C / np.outer(d, d)
else:
C = np.eye(n_variables)
if change in ("variance", "all"):
s = rng.uniform(0.3, 3.0, n_variables)
C = C * np.outer(s, s)
params.append((mu, C))
if n_states is None:
states = np.arange(n_segments)
else:
seq = [int(rng.integers(k))]
for _ in range(n_segments - 1):
s = int(rng.integers(k - 1)) if k > 1 else 0
seq.append(s if s < seq[-1] else s + 1 if k > 1 else 0)
states = np.array(seq)
parts = []
for s, L in zip(states, lens, strict=True):
mu, C = params[s]
parts.append(rng.multivariate_normal(mu, noise * C, size=int(L)))
X = np.vstack(parts)
return X, np.cumsum(lens)[:-1], np.asarray(states)
[docs]
def make_correlation_switching(n_segments: int = 4, length=200, n_variables: int = 3, n_latent: int = 1,
noise: float = 0.05, n_states: int | None = None, min_angle_deg: float = 45.0,
random_state=None):
"""Segments with equal means and variances but different correlation
structure: in every state the variables are driven by ``n_latent``
hidden factors through a different (random orthonormal) loading matrix,
whose principal subspaces are at least ``min_angle_deg`` apart.
Univariate statistics cannot see these changes; PCA-based methods can
(the setting of correlation-based segmentation and warping)."""
from ..representation.pca_models import principal_angles
rng = check_random_state(random_state)
k = n_segments if n_states is None else n_states
loads: list[np.ndarray] = []
min_angle = np.deg2rad(min_angle_deg)
for _ in range(k):
for _attempt in range(500):
Q, _ = np.linalg.qr(rng.normal(size=(n_variables, n_variables)))
W = Q[:, :n_latent]
if np.min(np.linalg.norm(W, axis=1)) < 0.25: # every variable takes part
continue
if all(np.min(principal_angles(W, V)) >= min_angle for V in loads):
break
loads.append(W)
states = np.arange(n_segments) % k
lens = _segment_lengths(n_segments, length, rng, 0.0)
parts = []
for s, L in zip(states, lens, strict=True):
z = rng.normal(size=(int(L), n_latent))
Xs = z @ loads[s].T + noise * rng.normal(size=(int(L), n_variables))
Xs = Xs / Xs.std(0)
parts.append(Xs)
return np.vstack(parts), np.cumsum(lens)[:-1], states
[docs]
def make_dynamic_switching(order: int = 1, n_segments: int = 3, length: int = 300, noise: float = 0.01,
random_state=None):
"""Linear time-variant SISO systems of Bankó (2015, Ch. 4).
A first-order system :math:`y(k+1)=a\\,y(k)+b\\,u(k)` or a second-order
system :math:`y(k+1)=a_1y(k)+a_2y(k-1)+b\\,u(k)` is driven by a random
step input; the parameters switch at the change points while the static
gain is kept, so the segments differ only in their *dynamics*. Columns:
``[u, y]``.
"""
rng = check_random_state(random_state)
T = n_segments * length
u = np.repeat(rng.uniform(-1, 1, T // 10 + 1), 10)[:T]
y = np.zeros(T)
states = np.arange(n_segments)
if order == 1:
poles = np.linspace(0.3, 0.95, n_segments)
rng.shuffle(poles)
for k in range(1, T):
a = poles[min((k - 1) // length, n_segments - 1)]
y[k] = a * y[k - 1] + (1 - a) * u[k - 1]
elif order == 2:
zeta = np.linspace(0.2, 1.2, n_segments)
rng.shuffle(zeta)
w = 0.3
for k in range(2, T):
z = zeta[min((k - 1) // length, n_segments - 1)]
r = np.exp(-z * w)
th = w * np.sqrt(max(1 - z**2, 1e-6)) if z < 1 else 0.0
a1 = 2 * r * np.cos(th) if z < 1 else 2 * r
a2 = -(r**2)
b = 1 - a1 - a2
y[k] = a1 * y[k - 1] + a2 * y[k - 2] + b * u[k - 1]
else:
raise ValueError("order must be 1 or 2")
X = np.column_stack([u, y + noise * rng.normal(size=T)])
return X, np.arange(1, n_segments) * length, states
[docs]
def make_regime_process(n_regimes: int = 3, n_segments: int = 8, length=150, n_variables: int = 4, noise: float = 0.1,
vary: float = 0.4, random_state=None):
"""Recurring operating regimes of a process: every regime has its own
operating point and latent correlation structure; the regimes recur in
random order with smooth transitions. Returns ``(X, change_points,
states)``; ``states`` labels the recurring regimes (state detection)."""
rng = check_random_state(random_state)
lens = _segment_lengths(n_segments, length, rng, vary)
regs = []
for _ in range(n_regimes):
Q, _ = np.linalg.qr(rng.normal(size=(n_variables, n_variables)))
regs.append((rng.normal(0, 2, n_variables), Q[:, :2] * np.array([2.0, 1.0])))
states = [int(rng.integers(n_regimes))]
for _ in range(n_segments - 1):
s = int(rng.integers(n_regimes - 1))
states.append(s if s < states[-1] else s + 1)
parts = []
for s, L in zip(states, lens, strict=True):
mu, W = regs[s]
z = rng.normal(size=(int(L), 2))
parts.append(mu + z @ W.T + noise * rng.normal(size=(int(L), n_variables)))
X = np.vstack(parts)
cps = np.cumsum(lens)[:-1]
for c in cps: # short smooth transitions
w = 4
lo, hi = max(c - w, 0), min(c + w, len(X))
a, b = X[lo], X[hi - 1]
X[lo:hi] = np.linspace(a, b, hi - lo) + noise * rng.normal(size=(hi - lo, n_variables))
return X, cps, np.asarray(states)
[docs]
def make_energy_process(n_segments: int = 4, length=250, random_state=None):
"""Energy monitoring data in the spirit of Abonyi et al. (2013): the
specific energy consumption (column 0, the key energy indicator) depends
linearly on the load and the feed temperature (columns 1--2) with
coefficients that change between operating ranges; the load itself
varies smoothly. Returns ``(X, change_points, states)``."""
rng = check_random_state(random_state)
lens = _segment_lengths(n_segments, length, rng, 0.3)
T = int(lens.sum())
load = np.cumsum(rng.normal(0, 0.05, T))
load = 70 + 15 * np.tanh(load / 3) + 3 * np.sin(np.arange(T) / 40)
feed = 20 + 5 * np.sin(np.arange(T) / 90 + 1) + rng.normal(0, 0.5, T)
coefs = [(rng.uniform(1.0, 3.0), rng.uniform(-0.08, -0.01), rng.uniform(-0.2, 0.2)) for _ in range(n_segments)]
kei = np.empty(T)
t0 = 0
for (a0, a1, a2), L in zip(coefs, lens, strict=True):
sl = slice(t0, t0 + int(L))
kei[sl] = a0 * 10 + a1 * load[sl] * 3 + a2 * feed[sl]
t0 += int(L)
kei += rng.normal(0, 0.15, T)
return np.column_stack([kei, load, feed]), np.cumsum(lens)[:-1], np.arange(n_segments)
[docs]
def simulate_ph_cstr(base_flow=None, T: int = 600, dt: float = 0.25, acid_flow: float = 1.0, volume: float = 2.0,
c_acid: float = 0.01, c_base: float = 0.01, noise: float = 0.01, random_state=None):
"""pH neutralization of a strong acid by a strong base in a continuous
stirred tank (the pH case study of Bankó, 2015, Ch. 4).
Component balances of the acid- and base-derived ions,
:math:`V\\dot x_a=F_ac_a-(F_a+F_b)x_a`, :math:`V\\dot x_b=F_bc_b-(F_a+F_b)x_b`,
and the charge balance :math:`[H^+]-K_w/[H^+]+x_b-x_a=0` give a static
titration curve whose slope -- the process gain -- changes by orders of
magnitude around neutrality, so the local dynamics differ between
operating ranges.
Parameters
----------
base_flow : array (T,), optional
Base (NaOH) flow rate profile; default: random steps around the
neutralization point.
Returns
-------
X : array (T, 2)
Columns ``[F_base, pH]``.
"""
rng = check_random_state(random_state)
if base_flow is None:
levels = rng.uniform(0.6, 1.4, T // 60 + 1) * acid_flow * c_acid / c_base
base_flow = np.repeat(levels, 60)[:T]
Fb = np.asarray(base_flow, float)
T = len(Fb)
Kw = 1e-14
xa, xb = c_acid / 2, c_base / 2
pH = np.empty(T)
for k in range(T):
Ft = acid_flow + Fb[k]
for _ in range(4): # sub-steps for stability
xa += dt / 4 * (acid_flow * c_acid - Ft * xa) / volume
xb += dt / 4 * (Fb[k] * c_base - Ft * xb) / volume
d = xb - xa
h = (-d + np.sqrt(d * d + 4 * Kw)) / 2
pH[k] = -np.log10(h)
return np.column_stack([Fb, pH + noise * rng.normal(size=T)])
#: Kinetic and operating parameters of the isothermal free-radical
#: polymerization of methyl methacrylate in a CSTR (Doyle, Ogunnaike and
#: Pearson, 1995), the case study of Dobos, Bankó and Abonyi (2009, 2010).
MMA_PARAMETERS = {
"kp": 2.4952e6, "kfm": 2.4522e3, "kI": 1.0225e-1, "kTc": 1.3281e10, "kTd": 1.0930e11, "f": 0.58,
"F": 1.0, "V": 0.1, "CIin": 8.0, "Cmin": 6.0, "Mm": 100.12,
}
[docs]
def simulate_mma_cstr(initiator_flow, t_end: float | None = None, dt: float = 0.05, params: dict | None = None,
x0=None, return_states: bool = False):
"""Isothermal MMA polymerization CSTR (four states, one input).
States: monomer and initiator concentrations :math:`C_m, C_I` and the
zeroth and first moments :math:`D_0, D_1` of the dead polymer chains;
input: initiator flow rate :math:`F_I` (m³/h); output: number-average
molecular weight :math:`y=D_1/D_0` (kg/kmol). The nominal input
:math:`F_I=0.016783` gives :math:`y\\approx 25\\,000`.
Parameters
----------
initiator_flow : array (T,) or callable
Input profile sampled every ``dt`` hours (or a function of time).
params : dict, optional
Overrides of :data:`MMA_PARAMETERS` (e.g. perturbed ``kp``, ``kI``
for sensitivity analysis).
Returns
-------
y : array (T,)
Number-average molecular weight (or ``(y, states)``).
"""
p = dict(MMA_PARAMETERS)
if params:
p.update(params)
if callable(initiator_flow):
n = int(round((t_end or 10.0) / dt))
tt = np.arange(n) * dt
FI = np.array([initiator_flow(s) for s in tt])
else:
FI = np.asarray(initiator_flow, float)
tt = np.arange(len(FI)) * dt
def rhs(t, x, fi):
Cm, CI, D0, D1 = x
P0 = np.sqrt(max(2 * p["f"] * p["kI"] * CI / (p["kTd"] + p["kTc"]), 0.0))
F, V = p["F"], p["V"]
return [
-(p["kp"] + p["kfm"]) * Cm * P0 + F * (p["Cmin"] - Cm) / V,
-p["kI"] * CI + (fi * p["CIin"] - F * CI) / V,
(0.5 * p["kTc"] + p["kTd"]) * P0**2 + p["kfm"] * Cm * P0 - F * D0 / V,
p["Mm"] * (p["kp"] + p["kfm"]) * Cm * P0 - F * D1 / V,
]
x = np.array([5.506774, 0.132906, 0.0019752, 49.38182] if x0 is None else x0, float)
X = np.empty((len(FI), 4))
for k, fi in enumerate(FI):
X[k] = x
sol = solve_ivp(rhs, (0.0, dt), x, args=(fi,), method="LSODA", rtol=1e-8, atol=1e-12)
x = sol.y[:, -1]
y = X[:, 3] / X[:, 2]
return (y, X) if return_states else y
[docs]
def make_cbf(n_per_class: int = 30, length: int = 128, random_state=None):
"""Cylinder--Bell--Funnel data (Saito, 1994): three classes of univariate
patterns with random onset, duration and amplitude."""
rng = check_random_state(random_state)
X, y = [], []
t = np.arange(length)
for cls in range(3):
for _ in range(n_per_class):
a = rng.integers(length // 8, length // 4)
b = a + rng.integers(length // 4, length * 3 // 4)
b = min(b, length - 1)
eta = rng.normal()
chi = (t >= a) & (t <= b)
if cls == 0:
s = (6 + eta) * chi
elif cls == 1:
s = (6 + eta) * chi * (t - a) / max(b - a, 1)
else:
s = (6 + eta) * chi * (b - t) / max(b - a, 1)
X.append((s + rng.normal(size=length))[:, None])
y.append(cls)
return X, np.array(y)
[docs]
def make_synthetic_control(n_per_class: int = 30, length: int = 60, random_state=None):
"""Synthetic control chart patterns (Alcock and Manolopoulos, 1999):
normal, cyclic, increasing trend, decreasing trend, upward shift,
downward shift."""
rng = check_random_state(random_state)
t = np.arange(length)
X, y = [], []
for cls in range(6):
for _ in range(n_per_class):
base = 30 + 2 * rng.uniform(-3, 3, length)
if cls == 1:
base = base + rng.uniform(10, 15) * np.sin(2 * np.pi * t / rng.uniform(10, 15))
elif cls == 2:
base = base + rng.uniform(0.2, 0.5) * t
elif cls == 3:
base = base - rng.uniform(0.2, 0.5) * t
elif cls in (4, 5):
s = rng.integers(length // 3, 2 * length // 3)
base = base + (1 if cls == 4 else -1) * rng.uniform(7.5, 20) * (t >= s)
X.append(base[:, None])
y.append(cls)
return X, np.array(y)
[docs]
def random_time_warp(x, strength: float = 0.15, n_knots: int = 4, length: int | None = None, random_state=None):
"""Apply a smooth, monotone random time warping to a series (and resample
it to ``length``). The result has the dimensionality of ``x``."""
rng = check_random_state(random_state)
A = np.asarray(x, float)
flat = A.ndim == 1
if flat:
A = A[:, None]
T = len(A)
L = T if length is None else int(length)
knots = np.linspace(0, 1, n_knots + 2)
inc = np.exp(rng.normal(0, strength, n_knots + 1))
warp = np.r_[0, np.cumsum(inc)]
warp /= warp[-1]
phi = CubicSpline(knots, warp, bc_type="natural")
u = np.clip(np.sort(phi(np.linspace(0, 1, L))), 0, 1)
src = np.linspace(0, 1, T)
out = np.column_stack([np.interp(u, src, A[:, j]) for j in range(A.shape[1])])
return out[:, 0] if flat else out
[docs]
def make_signatures(n_writers: int = 6, n_per_writer: int = 10, length: int = 150, n_strokes: int = 6,
noise: float = 0.03, warp: float = 0.2, spread: float = 1.0, random_state=None):
"""Synthetic on-line signatures: pen trajectories with five channels
``[x, y, pressure, azimuth, altitude]``.
Every writer has a template drawn from a smooth random curve (a common
base curve plus a writer-specific deviation scaled by ``spread``; small
values make the writers similar and the task harder); genuine samples are
randomly time-warped, slightly rescaled and noisy copies.
The channels are strongly correlated and the correlation structure
changes along the trajectory, which makes the data a stand-in for the
SVC2004 signatures used to validate correlation-based DTW (Bankó and
Abonyi, 2012). Returns ``(collection, writer_labels)``.
"""
rng = check_random_state(random_state)
data, labels = [], []
tk = np.linspace(0, 1, n_strokes + 2)
s = np.linspace(0, 1, length)
bx, by, bp = rng.normal(0, 1, len(tk)).cumsum(), rng.normal(0, 1, len(tk)), rng.uniform(0.3, 1.0, len(tk))
for w in range(n_writers):
cx = CubicSpline(tk, bx + spread * rng.normal(0, 1, len(tk)).cumsum())
cy = CubicSpline(tk, by + spread * rng.normal(0, 1, len(tk)))
cp = CubicSpline(tk, np.clip(bp + spread * rng.normal(0, 0.3, len(tk)), 0.05, None))
x, yv, pr = cx(s), cy(s), cp(s)
az = np.arctan2(np.gradient(yv), np.gradient(x))
alt = 0.5 + 0.3 * np.tanh(np.gradient(pr) * 30)
tmpl = np.column_stack([x, yv, pr, np.unwrap(az), alt])
for _ in range(n_per_writer):
Lr = int(length * rng.uniform(0.85, 1.15))
sample = random_time_warp(tmpl, warp, length=Lr, random_state=rng)
sample = sample * rng.uniform(0.9, 1.1, 5) + rng.normal(0, 0.05, 5)
sample = sample + noise * rng.normal(size=sample.shape) * sample.std(0)
data.append(sample)
labels.append(w)
return data, np.array(labels)
[docs]
def make_motion_collection(n_per_class: int = 20, length: int = 100, n_channels: int = 6, n_classes: int = 4,
random_state=None):
"""Multivariate motion-like series (accelerometer + gyroscope): every
class is an activity with its own frequency content and inter-channel
phase pattern, with random phase, amplitude and time warping."""
rng = check_random_state(random_state)
t = np.linspace(0, 1, length)
protos = []
for _ in range(n_classes):
f = rng.uniform(1, 6, n_channels)
ph = rng.uniform(0, 2 * np.pi, n_channels)
amp = rng.uniform(0.3, 2.0, n_channels)
protos.append((f, ph, amp))
data, labels = [], []
for c, (f, ph, amp) in enumerate(protos):
for _ in range(n_per_class):
shift = rng.uniform(0, 2 * np.pi)
X = amp * np.sin(2 * np.pi * np.outer(t, f) + ph + shift) * rng.uniform(0.8, 1.2)
X = random_time_warp(X, 0.1, random_state=rng) + 0.2 * rng.normal(size=X.shape)
data.append(X)
labels.append(c)
return data, np.array(labels)
def _orthonormal_loadings(n_variables, n_latent, k, rng, min_angle_deg=45.0):
from ..representation.pca_models import principal_angles
out: list[np.ndarray] = []
for _ in range(k):
for _attempt in range(500):
Q, _ = np.linalg.qr(rng.normal(size=(n_variables, n_variables)))
W = Q[:, :n_latent]
if np.min(np.linalg.norm(W, axis=1)) < 0.25:
continue
if all(np.min(principal_angles(W, V)) >= np.deg2rad(min_angle_deg) for V in out):
break
out.append(W)
return out
[docs]
def make_correlation_sequences(n_classes: int = 4, n_per_class: int = 10, n_regimes: int = 4, regime_length: int = 40,
n_variables: int = 8, n_latent: int = 2, noise: float = 0.5, length_jitter: float = 0.3,
random_state=None):
"""Collection whose classes differ only in the *sequence of correlation
structures*.
A pool of ``n_regimes`` latent-factor loading patterns is shared by all
classes; a class is a random sequence of four regimes from the pool, and
every series of the class realizes it with random regime durations and
white latent factors. All channels have zero mean and unit variance in
every regime, so the series look like noise to lock-step and
sample-level elastic measures, while correlation-based DTW (Bankó and
Abonyi, 2012) sees the regime sequence. Returns ``(collection, labels)``.
"""
rng = check_random_state(random_state)
loads = _orthonormal_loadings(n_variables, n_latent, n_regimes, rng)
seqs = []
while len(seqs) < n_classes:
q = [int(rng.integers(n_regimes))]
for _ in range(3):
v = int(rng.integers(n_regimes - 1))
q.append(v if v < q[-1] else v + 1)
if q not in seqs:
seqs.append(q)
data, labels = [], []
for c, q in enumerate(seqs):
for _ in range(n_per_class):
parts = []
for r in q:
L = max(10, int(regime_length * rng.uniform(1 - length_jitter, 1 + length_jitter)))
z = rng.normal(size=(L, n_latent))
P = z @ loads[r].T + noise * rng.normal(size=(L, n_variables))
parts.append(P / P.std(0))
data.append(np.vstack(parts))
labels.append(c)
return data, np.array(labels)
[docs]
def make_dynamic_sequences(n_classes: int = 3, n_per_class: int = 10, regime_length: int = 80, noise: float = 0.01,
length_jitter: float = 0.25, random_state=None):
"""Collection of input--output series ``[u, y]`` of a first-order system
whose time constant follows a class-specific sequence of three values
(fast, medium, slow). The static gain is one in every regime, so the
classes differ only in their *dynamics* -- the setting of the
process-dynamics-aware correlation-based DTW of Bankó (2015, thesis II).
Returns ``(collection, labels)``."""
rng = check_random_state(random_state)
poles = [0.3, 0.75, 0.95]
import itertools
orders = list(itertools.permutations(range(3)))
rng.shuffle(orders)
data, labels = [], []
for c in range(n_classes):
order = orders[c % len(orders)]
for _ in range(n_per_class):
lens = [max(30, int(regime_length * rng.uniform(1 - length_jitter, 1 + length_jitter))) for _ in order]
T = sum(lens)
u = np.repeat(rng.uniform(-1, 1, T // 8 + 1), 8)[:T]
a_seq = np.concatenate([[poles[k]] * L for k, L in zip(order, lens, strict=True)])
y = np.zeros(T)
for k in range(1, T):
y[k] = a_seq[k] * y[k - 1] + (1 - a_seq[k]) * u[k - 1]
data.append(np.column_stack([u, y + noise * rng.normal(size=T)]))
labels.append(c)
return data, np.array(labels)