import random import math import numpy as np import torch from torch.distributions import Normal, Beta, Exponential, StudentT from scipy.stats import beta as scipy_beta # ───────────────────────── helper: icdf() calculation on torch ────────────────────────── def _neg_log1p(u): """ Compute -log(1 - u) in a numerically stable way for u close to 0. Args: u: Tensor with values in [0, 1). Returns: Tensor of -log(1 - u), clamped to be non-negative. """ return (-torch.log1p(-u)).clamp_min(0.0) def exp_icdf(u, rate): """ Inverse CDF (quantile function) of the Exponential distribution. Args: u : Tensor of shape (...,) with values in (0, 1). rate : Scale parameter λ > 0, broadcastable with u. Returns: Tensor of the same shape as u containing the quantiles. """ return _neg_log1p(u) / rate def beta_icdf(p, a, b, n_grid: int = 1000): """ Approximate inverse CDF (quantile function) of the Beta distribution via numerical CDF inversion on a uniform grid followed by linear interpolation. Args: p : Tensor of probabilities in (0, 1), shape (N,) or (N, D). a : Alpha (concentration1) parameter(s), broadcastable to (1, D). b : Beta (concentration0) parameter(s), broadcastable to (1, D). n_grid : Number of grid points used to approximate the CDF (default 1000). Returns: Tensor of quantiles with shape (N, D), clamped to [0, 1]. """ p = torch.as_tensor(p, dtype=torch.float32) a = torch.as_tensor(a, dtype=torch.float32) b = torch.as_tensor(b, dtype=torch.float32) if a.size() == torch.Size([]): a = a.expand(1) if b.size() == torch.Size([]): b = b.expand(1) x = torch.linspace(0.0, 1.0, n_grid + 1, dtype=torch.float32, device=p.device) mid = (x[:-1] + x[1:]) / 2.0 mid = mid.view(-1, 1) # shape [n_grid, 1] dx = 1.0 / n_grid log_norm = torch.lgamma(a) + torch.lgamma(b) - torch.lgamma(a + b) pdf_mid = torch.exp((a - 1) * torch.log(mid) + (b - 1) * torch.log1p(-mid) - log_norm) # [n_grid, D] cdf = torch.cumsum(pdf_mid, dim=0) * dx # [n_grid, D] cdf = torch.cat([torch.zeros(1, cdf.shape[1], device=p.device), cdf], dim=0) # [n_grid+1, D] # Expand p to match shape [N, D] if p.ndim == 1: p = p.unsqueeze(1) if a.ndim == 1: a = a.unsqueeze(0) b = b.unsqueeze(0) if p.shape[1] != a.shape[1]: p = p.expand(-1, a.shape[1]) # Searchsorted per-dimension N, D = p.shape idx = torch.empty((N, D), dtype=torch.long, device=p.device) for d in range(D): idx[:, d] = torch.searchsorted(cdf[:, d], p[:, d], right=False).clamp(1, n_grid) # Gather x and y for interpolation x0 = x[idx - 1] x1 = x[idx] y0 = torch.empty_like(p) y1 = torch.empty_like(p) for d in range(D): y0[:, d] = cdf[idx[:, d] - 1, d] y1[:, d] = cdf[idx[:, d], d] t = (p - y0) / (y1 - y0 + 1e-12) return torch.clamp(x0 + t * (x1 - x0), 0., 1.) def student_t_icdf(u, df): """ Approximate inverse CDF (quantile function) of the Student-t distribution. Uses the relationship between the Student-t and Beta distributions: p-value of |t| under t(df) equals the regularised incomplete beta function evaluated at df/(df + t^2). Args: u : Tensor of probabilities in (0, 1). df : Degrees-of-freedom parameter, broadcastable with u. Returns: Tensor of quantiles with the same shape as u. """ u = torch.as_tensor(u, dtype=torch.float32) df = torch.as_tensor(df, dtype=torch.float32) p = 2.0 * torch.minimum(u, 1 - u) p = p.to(df.device) x = beta_icdf(p, 0.5 * df, torch.tensor(0.5,device = p.device)) t = torch.sqrt(df * (1.0 / x - 1.0)) return torch.where(u > 0.5, t, -t) def normal_cdf(x): """ CDF of the standard normal distribution evaluated element-wise. Args: x: Tensor of real-valued inputs. Returns: Tensor of probabilities in (0, 1) with the same shape as x. """ return 0.5*(1+torch.special.erf(x/math.sqrt(2))) def normal_ppf(u): """ Percent-point function (inverse CDF) of the standard normal distribution. Args: u: Tensor of probabilities in (0, 1). Returns: Tensor of quantiles with the same shape as u. """ return Normal(0,1).icdf(u) # ─────────────── low-level helpers ─────────────── def rand_corr_batch(batch, d, identity=False, device='cuda'): """ Generate a batch of random (or identity) correlation matrices. A valid positive-definite correlation matrix is produced by forming A @ A^T and normalising so that every diagonal entry equals 1. Args: batch : Number of correlation matrices to generate. d : Dimension of each matrix. identity : If True, return identity matrices instead of random ones. device : Torch device string (default 'cuda'). Returns: Tensor of shape (B, d, d) containing correlation matrices on the specified device with dtype torch.float32. """ if identity: eye = torch.eye(d, device=device, dtype=torch.float32) return eye.expand(batch, -1, -1).clone() A = torch.rand(batch, d, d, device=device, dtype=torch.float32) psd = A @ A.transpose(-1, -2) diag= torch.diagonal(psd, dim1=-2, dim2=-1) norm= torch.sqrt(torch.clamp(diag, 1e-12)) C = psd / (norm.unsqueeze(-1)*norm.unsqueeze(-2)) C.diagonal(dim1=-2, dim2=-1).fill_(1.) C += torch.eye(d, device=device, dtype=torch.float32).unsqueeze(0)*1e-6 return C def mvn_sample(chol, device): """ Draw one sample per batch from a zero-mean multivariate normal distribution parameterised by its Cholesky factor. Args: chol : Lower-triangular Cholesky factor of shape (B, d, d) or (d, d). A 2-D input is broadcast to batch size 1. device : Torch device on which to allocate the standard normal noise. Returns: Tensor of shape (B, d) containing the multivariate normal samples. """ # chol: (B,d,d) or (d,d) if chol.dim() == 2: chol = chol.unsqueeze(0) B,d = chol.shape[:2] z = torch.randn(B, d, 1, device=device, dtype=torch.float32) return (chol @ z).squeeze(-1) # (B,d) # ─────────────── mixture helpers ─────────────── class GaussianMix: """ A univariate Gaussian mixture model that supports CDF and quantile queries. Components are specified as (weight, mean, std) tuples; weights are automatically normalised to sum to 1. """ def __init__(self, comps, device='cpu'): """ Initialise the Gaussian mixture. Args: comps : Iterable of (weight, mean, std) tuples defining each component. device : Torch device on which to store parameter tensors (default 'cpu'). """ w, mu, sigma = zip(*comps) self.device = device self.w = torch.tensor(w, device=device, dtype=torch.float32) self.mu = torch.tensor(mu, device=device, dtype=torch.float32) self.sigma = torch.tensor(sigma, device=device, dtype=torch.float32) self.w /= self.w.sum() def cdf(self, x): """ Evaluate the mixture CDF at x. Args: x: Scalar or tensor of query points. Returns: Tensor of CDF values in [0, 1] with the same shape as x. """ x = torch.as_tensor(x, dtype=torch.float32, device=self.device) z = (x.unsqueeze(-1) - self.mu) / (self.sigma * math.sqrt(2)) return (self.w * (0.5 * (1 + torch.erf(z)))).sum(-1) def ppf_bounds(self): """ Return conservative lower and upper bounds for the support of the mixture. Returns: Tuple (lo, hi) of floats representing the ±5-sigma range across all mixture components. """ lo = (self.mu - 5 * self.sigma).min().item() hi = (self.mu + 5 * self.sigma).max().item() return lo, hi def ppf(self, u, tol=1e-5, max_iter=100): """ Quantile function of the mixture via bisection search. Args: u : Tensor of probabilities in (0, 1), shape (...). tol : Convergence tolerance on the bracket width (default 1e-5). max_iter : Maximum number of bisection iterations (default 100). Returns: Tensor of quantiles with the same shape as u. """ u = torch.as_tensor(u, device=self.device, dtype=torch.float32) low, high = self.ppf_bounds() low = torch.full_like(u, low) high = torch.full_like(u, high) for _ in range(max_iter): mid = 0.5 * (low + high) cdf_mid = self.cdf(mid) low = torch.where(cdf_mid < u, mid, low) high = torch.where(cdf_mid >= u, mid, high) if torch.max(high - low) < tol: break return 0.5 * (low + high) class BetaMix: """ A univariate Beta mixture model with per-component location-scale transforms. Each component is specified as (weight, alpha, beta, loc, scale) so that the effective random variable is loc + scale * Beta(alpha, beta). """ def __init__(self, comps, device='cuda'): """ Initialise the Beta mixture. Args: comps : Iterable of (weight, alpha, beta, loc, scale) tuples. device : Torch device on which to store parameter tensors (default 'cuda'). """ self.comps = comps self.w = torch.tensor([c[0] for c in comps], device=device, dtype=torch.float32) self.a = torch.tensor([c[1] for c in comps], device=device, dtype=torch.float32) self.b = torch.tensor([c[2] for c in comps], device=device, dtype=torch.float32) self.loc = torch.tensor([c[3] for c in comps], device=device, dtype=torch.float32) self.sc = torch.tensor([c[4] for c in comps], device=device, dtype=torch.float32) self.w /= self.w.sum() self.device = device def cdf(self, x: torch.Tensor): """ Evaluate the mixture CDF at x using SciPy's Beta CDF (CPU fallback). Args: x: Tensor of query points. Returns: Tensor of CDF values in [0, 1] with the same shape as x, returned on the device specified at construction time. """ # Fallback to CPU-based computation x_cpu = x.detach().cpu().numpy() cdf_vals = np.zeros_like(x_cpu) for w, a, b, loc, scale in zip(self.w, self.a, self.b, self.loc, self.sc): dist = scipy_beta(a=a.item(), b=b.item(), loc=loc.item(), scale=scale.item()) cdf_vals += w.item() * dist.cdf(x_cpu) return torch.tensor(cdf_vals, device=self.device, dtype=torch.float32) def ppf_bounds(self): """ Return conservative lower and upper bounds for the support of the mixture. Returns: Tuple (lo, hi) of floats corresponding to the minimum loc and the maximum loc + scale across all components. """ lo = (self.loc).min().item() hi = (self.loc + self.sc).max().item() return lo, hi # ─────────────── marginal catalogue ─────────────── def rand_def(device='cuda', PPF_GRID=1_000): """ Randomly sample a marginal distribution specification. Picks uniformly from: Normal, Beta, Exponential, StudentT, Gaussian mixture, and Beta mixture. For parametric torch distributions the spec contains the distribution object directly; for mixture models an interpolation grid is precomputed and stored instead. Args: device : Torch device on which to allocate tensors (default 'cuda'). PPF_GRID : Number of grid points for the quantile interpolation table used by mixture distributions (default 1000). Returns: dict with key 'kind': - 'torch' → also has key 'dist' (a torch.distributions instance). - 'interp' → also has keys 'u', 'x', 'lo', 'hi' for grid interpolation. """ cat = random.choice(["normal","beta","beta_mix","expo","gauss_mix","beta_mix","student"]) if cat=="normal": return dict(kind="torch", dist=Normal(torch.tensor(random.uniform(-1,1)), torch.tensor(random.uniform(1.5,2)))) if cat=="beta": return dict(kind="torch", dist=Beta(torch.tensor(random.uniform(1,5)), torch.tensor(random.uniform(1,5)))) if cat=="expo": return dict(kind="torch", dist=Exponential(torch.tensor(random.uniform(1,2)))) if cat=="student": return dict(kind="torch", dist=StudentT(torch.tensor(random.randint(3,10)))) if cat=="gauss_mix": comps = [(random.uniform(0.3,0.7), random.uniform(-3,3), random.uniform(0.5,1.5)) for _ in range(random.randint(1,3))] mix = GaussianMix(comps) else: comps = [(random.uniform(0.3,0.7), random.uniform(1,5), random.uniform(1,5), -5.0, 10.0) for _ in range(random.randint(1,3))] mix = BetaMix(comps,device=device) # build interpolation grids u_grid = torch.linspace(0.001,0.999,PPF_GRID, device=device, dtype=torch.float32) lo,hi = mix.ppf_bounds() x_grid = torch.linspace(lo,hi,PPF_GRID, device=device, dtype=torch.float32) #cdf_vals = mix.cdf(x_grid) return dict(kind="interp", u=u_grid, x=x_grid, lo=lo, hi=hi) class CopulaGenerator: """ Generates labelled anomaly-detection datasets via a Gaussian copula. The joint distribution is built by: 1. Sampling from a multivariate normal with a random correlation structure. 2. Mapping each marginal through its CDF to obtain uniform scores. 3. Applying per-dimension quantile functions drawn from ``rand_def`` to produce the final heterogeneous features. Inliers follow the base copula; outliers are injected by either perturbing the uniform scores toward the tails or by replacing a random sub-block of the Cholesky factor with an independent structure. """ def __init__(self, num_dims, device="cuda", ppf_grid=2_000): """ Initialise the copula generator. Args: num_dims : Number of feature dimensions (d). device : Torch device (default 'cuda'). ppf_grid : Grid resolution for quantile interpolation tables used by mixture marginals (default 2000). """ self.num_dims = num_dims self.device = device self.dtype = torch.float32 self.ppf_grid = ppf_grid self.chol_base = torch.linalg.cholesky( rand_corr_batch(1, num_dims, device=device)[0] ) self.specs = [rand_def(device=device, PPF_GRID=ppf_grid) for _ in range(num_dims)] def sample_inliers(self, num_inliers): """ Sample inlier observations from the base copula. Draws from the zero-mean multivariate normal defined by the stored Cholesky factor. The raw Gaussian samples are returned without marginal transformation so that ``_transform`` can be applied later. Args: num_inliers : Number of inlier samples to generate. Returns: Tensor of shape (num_inliers, num_dims) containing the raw Gaussian-copula samples. """ z = torch.randn(num_inliers, self.num_dims, device=self.device, dtype=self.dtype) samples = (z @ self.chol_base.T) return samples def sample_outliers(self, num_outliers, method="probabilistic", strength=0.2): """ Generate outlier observations in Gaussian-copula space. Two injection strategies are supported: ``'probabilistic'`` Samples from the base copula, converts to uniform marginals, then forces a random subset of dimensions toward 0 or 1 to create extreme-value anomalies. ``'dependence'`` Replaces a contiguous block of the Cholesky factor with a randomly rotated version, breaking the local correlation structure. Args: num_outliers : Number of outlier samples to generate. method : Injection strategy – ``'probabilistic'`` or ``'dependence'`` (default ``'probabilistic'``). strength : Controls how extreme the perturbation is. For ``'probabilistic'`` this is the tail-fraction pushed; for ``'dependence'`` it is the mixing weight of the random sub-block (default 0.2). Returns: Tensor of shape (num_outliers, num_dims) in Gaussian-copula space (before marginal transformation). Raises: ValueError: If ``method`` is not one of the supported strategies. """ if method == "probabilistic": # 1. Sample from base MVN z = torch.randn(num_outliers, self.num_dims, device=self.device, dtype=self.dtype) samples = (z @ self.chol_base.T) # 2. Transform to uniform U = normal_cdf(samples) min_k = max(1, math.ceil(0.02 * self.num_dims)) max_k = max(min_k, math.floor(0.2 * self.num_dims)) # Ensure min_k < max_k + 1 to avoid invalid range if min_k >= max_k + 1: max_k = min_k # fallback: both min_k and max_k equal, will result in k_row = min_k k_row = torch.randint(min_k, max_k + 1, (num_outliers,), device=self.device) #k_row = torch.randint(5, 6, (num_outliers,), device=self.device) perm = torch.rand(num_outliers, self.num_dims, device=self.device).argsort(dim=1) sel_mask = torch.arange(self.num_dims, device=self.device).expand(num_outliers, -1) < k_row.unsqueeze(1) mask = torch.zeros_like(U, dtype=torch.bool).scatter(1, perm, sel_mask) push0 = torch.rand_like(U) < 0.5 z_mask, o_mask = mask & push0, mask & ~push0 noise = torch.empty_like(U) noise[z_mask] = strength * torch.rand(z_mask.sum(), device=self.device) * 0.5 noise[o_mask] = 1.0 - strength * torch.rand(o_mask.sum(), device=self.device) * 0.5 U[mask] = noise[mask] samples = Normal(0, 1).icdf(U) return samples elif method == "dependence": d, device = self.num_dims, self.device base_L = self.chol_base # 1) Random block lengths k and start indices i0 –– now 1 … d inclusive lowerbound = int(1+ d//3) upperbound = min(int(1+ 2 * d//3),d+1) if lowerbound == upperbound: upperbound += 1 k = torch.randint(lowerbound, upperbound, (num_outliers,), device=device) # (B,) #int(1+ d//2) k_max = int(k.max()) # Vectorised start positions: i0[b] ∈ {0 … d-k[b]} # torch.randint can’t take a per-element “high”, so we synthesise i0 using rand(): max_start = d - k # (B,) i0 = (torch.rand(num_outliers, device=device) * (max_start + 1) ).floor().long() # (B,) i1 = i0 + k # (B,) exclusive end index L_rand_full = torch.linalg.cholesky( rand_corr_batch(num_outliers, k_max, identity=True, device=device) # (B,k_max,k_max) ) rows = torch.arange(k_max, device=device).view(1, k_max, 1) # (1,k_max,1) cols = torch.arange(k_max, device=device).view(1, 1, k_max) # (1,1,k_max) keep = (rows < k.view(-1, 1, 1)) & (cols < k.view(-1, 1, 1)) # (B,k_max,k_max) L_rand_pad = torch.zeros(num_outliers, d, d, device=device) # (B,d,d) L_rand_pad[:, :k_max, :k_max][keep] = L_rand_full[keep] L_mix = base_L.expand(num_outliers, -1, -1).clone() row = torch.arange(d, device=device).view(1, d) # (1,d) mask_rows = (row >= i0.view(-1, 1)) & (row < i1.view(-1, 1)) # (B,d) col = torch.arange(d, device=device).view(1, 1, d) # (1,1,d) mask = mask_rows.unsqueeze(-1) & (col < row.unsqueeze(-1) + 1) L_mix = torch.where(mask, (1- strength) * L_mix + strength *L_rand_pad, L_mix) L_mix.diagonal(dim1=-2, dim2=-1).clamp_(min=1e-6) return mvn_sample(L_mix, device=device) else: raise ValueError(f"Unsupported outlier injection method: {method}") def _transform(self, samples): """ Map Gaussian-copula samples to the target marginal distributions. Converts each column of ``samples`` through the standard-normal CDF to obtain uniform scores, then applies the per-dimension quantile function stored in ``self.specs``. Distribution-specific dispatch: - ``Normal``, ``Beta``, ``Exponential``, ``StudentT`` → vectorised GPU operations (batched across all columns of the same type). - Mixture (``kind='interp'``) → fast linear interpolation on the precomputed PPF grid. Args: samples : Tensor of shape (N, D) in Gaussian-copula space. Returns: Tensor of shape (N, D) with each column drawn from its target marginal distribution. """ U = normal_cdf(samples) eps = 1e-6 U = torch.clamp(U, eps, 1-eps) #make sure U does not approch infty N, D = U.shape X = torch.empty_like(U) # Group columns by distribution type interp_cols, normal_cols, beta_cols, exp_cols, student_cols = [], [], [], [], [] for d, spec in enumerate(self.specs): if spec["kind"] == "interp": interp_cols.append(d) elif spec["kind"] == "torch": dist = spec["dist"] if isinstance(dist, Normal): normal_cols.append(d) elif isinstance(dist, Beta): beta_cols.append(d) elif isinstance(dist, Exponential): exp_cols.append(d) elif isinstance(dist, StudentT): student_cols.append(d) # ---------- Interp mixture sampling ---------- for d in interp_cols: u = U[:, d] spec = self.specs[d] grid_min = spec["u"][0] grid_max = spec["u"][-1] n_bins = len(spec["u"]) - 1 bin_width = (grid_max - grid_min) / n_bins # Clamp u to grid range u_clamped = torch.clamp(u, grid_min, grid_max - 1e-6) # Fast approximate bin index (assumes linear CDF grid) idx = ((u_clamped - grid_min) / bin_width).long().clamp(0, n_bins - 1) idx = torch.clamp(idx, 1, len(spec["u"]) - 1) u_lo, u_hi = spec["u"][idx - 1], spec["u"][idx] x_lo, x_hi = spec["x"][idx - 1], spec["x"][idx] X[:, d] = x_lo + (u - u_lo) * (x_hi - x_lo) / (u_hi - u_lo) # ---------- Normal ---------- if normal_cols: loc = torch.tensor([self.specs[d]["dist"].loc for d in normal_cols], device=self.device).view(1, -1) scale = torch.tensor([self.specs[d]["dist"].scale for d in normal_cols], device=self.device).view(1, -1) dist = Normal(loc, scale) X[:, normal_cols] = dist.icdf(U[:, normal_cols]) # ---------- Beta ---------- if beta_cols: a = torch.tensor([self.specs[d]["dist"].concentration1 for d in beta_cols], device=self.device).view(1, -1) b = torch.tensor([self.specs[d]["dist"].concentration0 for d in beta_cols], device=self.device).view(1, -1) X[:, beta_cols] = beta_icdf(U[:, beta_cols], a, b) # ---------- Exponential ---------- if exp_cols: rate = torch.tensor([self.specs[d]["dist"].rate for d in exp_cols], device=self.device).view(1, -1) X[:, exp_cols] = exp_icdf(U[:, exp_cols], rate) # ---------- StudentT ---------- if student_cols: df = torch.tensor([self.specs[d]["dist"].df for d in student_cols], device=self.device).view(1, -1) X[:, student_cols] = student_t_icdf(U[:, student_cols], df) return X @torch.no_grad() def draw_batched_data(self, num_inliers, num_local_anomalies): """ Generate a labelled dataset of inliers and outliers. Randomly selects an outlier-injection method and strength, draws both populations, concatenates them, applies the marginal transformation, and then splits the result back into inlier and outlier tensors. Args: num_inliers : Number of normal (inlier) observations. num_local_anomalies: Number of anomalous (outlier) observations. Returns: Tuple ``(X_inliers, X_outliers)`` where each element is a Tensor of shape (n, num_dims) already transformed to the target marginals. """ METHOD = random.choice(['dependence']) #["disturb_covariance"])#,"probabilistic"]) # or add "probabilistic" STRENGTH = random.uniform(0.2,0.4) if METHOD == 'probabilistic' else random.uniform(0.97,0.99) inliers = self.sample_inliers(num_inliers) outliers = self.sample_outliers(num_local_anomalies, method=METHOD, strength=STRENGTH) combined = torch.cat([inliers, outliers], dim=0) X_combined = self._transform(combined) X_inliers = X_combined[:num_inliers] X_outliers = X_combined[num_inliers:] return X_inliers, X_outliers def make_Copula(device, max_feature_dim=100, min_feature_dim=2, dim=None): """ Convenience factory for ``CopulaGenerator`` with a randomised feature dimension. Args: device : Torch device string (e.g. ``'cuda'``, ``'cpu'``). max_feature_dim : Upper bound (exclusive) for the random feature count when ``dim`` is not provided (default 100). min_feature_dim : Lower bound (inclusive) for the random feature count when ``dim`` is not provided (default 2). dim : If given, use this exact feature dimension instead of sampling randomly. Returns: A freshly initialised ``CopulaGenerator`` instance. """ if dim is not None: num_features = dim else: num_features = np.random.randint(min_feature_dim, max_feature_dim) return CopulaGenerator(num_dims=num_features, device=device)