import numpy as np import pandas as pd import torch from copulae.core import pseudo_obs from .utils import search_alpha def empirical_copula_loss(x, data, epsilon): pseudo_data = pseudo_obs(data) return np.fabs( np.mean( np.all( np.less_equal(pseudo_data, np.array([x] * pseudo_data.shape[1])), axis=1 ) ) - 1 + epsilon ) import numpy as np import pandas as pd import torch from copulae.core import pseudo_obs from .utils import search_alpha class copulaCPTS: """ Copula conformal prediction with two-step calibration. This class implements the Copula Conformal Prediction for Time Series (CopulaCPTS) method as described in the accompanying paper. The core idea is to leverage copulas to model the joint probability of uncertainty for multiple predicted time steps, leading to more efficient and valid confidence regions. """ def __init__(self, model, cali_x, cali_y): """ Initializes the CopulaCPTS object. Args: model: The trained forecasting model (f_hat in the paper). This model should have a `predict` method that takes input features (x) and returns the predicted output (y_hat). cali_x: The input features for the initial calibration dataset (D_cal in the paper). cali_y: The corresponding target values for the initial calibration dataset (D_cal in the paper). """ self.model = model # These attributes will store the two split calibration sets: D_cal_1 and D_cal_2. # D_cal_1 (cali_x, cali_y) is used for estimating the CDF of nonconformity scores. # D_cal_2 (copula_x, copula_y) is used for calibrating the copula. self.cali_x = None self.cali_y = None self.copula_x = None self.copula_y = None self.split_cali(cali_x, cali_y) # Stores the nonconformity scores from the D_cal_1 set. # This corresponds to S_1 in the paper. self.nonconformity = None # Dictionary to store prediction results for different epsilon values. self.results_dict = {} def split_cali(self, cali_x, cali_y, split=0.6): """ Splits the initial calibration dataset (D_cal) into two subsets: D_cal_1 and D_cal_2. D_cal_1 (cali_x, cali_y) is used to calculate the nonconformity scores (s_j^i) and build the empirical CDF (F_hat_j) for each time step. D_cal_2 (copula_x, copula_y) is used to evaluate the cumulative probability of anomaly scores (u_j^i) and calibrate the empirical copula (C_empirical). This split corresponds to the "Randomly split D_cal into D_cal_1 and D_cal_2" step in Algorithm 1 of the paper. Args: cali_x: Input features of the combined calibration set. cali_y: Target values of the combined calibration set. split (float): The proportion of data to be allocated to D_cal_1. The paper states "Randomly split D_cal into D_cal_1 and D_cal_2" without specifying a split ratio. A default of 0.6 for D_cal_1 is a common heuristic for such splits, but the paper does not explicitly provide this value. """ if self.copula_x is not None: ####REVISE # This check prevents re-splitting if it has already been done. print("already split") return size = cali_x.shape[0] halfsize = int(split * size) np.random.seed(42) ####REVISE # Randomly select indices for D_cal_1. idx = np.random.choice(range(size), halfsize, replace=False) # Assign data to D_cal_1 (cali_x, cali_y). self.cali_x = cali_x[idx] self.cali_y = cali_y[idx] # Assign remaining data to D_cal_2 (copula_x, copula_y). self.copula_x = cali_x[list(set(range(size)) - set(idx))] self.copula_y = cali_y[list(set(range(size)) - set(idx))] def calibrate(self): """ Calculates nonconformity scores for the D_cal_1 dataset (self.cali_x, self.cali_y). This corresponds to the steps: - "hat_y_1:k <- hat_f(x_1:t^i)" - "s^i_j <- ||y^i_j - hat_y^i_j||" for (x_1:t^i, y_1:k^i) in D_cal_1 in Algorithm 1. The nonconformity score used here is the L2 distance, as stated in the paper ("L-2 distance s^i_j = A(z^i)_j = ||y^i_j - hat_f(x^i)_j ||"). """ pred_y = self.model.predict(self.cali_x) # Calculate L2 norm (Euclidean distance) for nonconformity. # dim=-1 ensures the norm is calculated across the last dimension (e.g., d for R^d). # .detach().numpy() converts the PyTorch tensor to a NumPy array. nonconformity = torch.norm((pred_y - self.cali_y), p=2, dim=-1).detach().numpy() self.nonconformity = nonconformity def calibrate_l1(self): """ Calculates nonconformity scores using the L1 distance for the D_cal_1 dataset. The paper mentions that L1 distance can also be chosen for nonconformity scores, depending on domain needs. This method provides that alternative. """ pred_y = self.model.predict(self.cali_x) # Calculate L1 norm (Manhattan distance) for nonconformity. nonconformity = torch.norm((pred_y - self.cali_y), p=1, dim=-1).detach().numpy() self.nonconformity = nonconformity def predict(self, X_test, epsilon=0.1): """ Generates conformal prediction intervals for new test data. This method combines the steps of "Calibrating CDF on D_cal_1", "Copula Calibration on D_cal_2", and "Prediction" as described in the paper. The paper states that for "Calibrating CDF on D_cal_1", equation (2) is used: F_hat_j(s_j) := (1 / (|S_1_j|+1)) * (tau + sum(1_{s^i_j < s_j})), where tau ~ (0,1). In implementation, the paper mentions "we treat tau=1 for simplicity and better coverage." However, the current code's calculation of `alphas` directly implements the `F_hat_j(s_j)` using an empirical frequency approach (count of nonconformity scores from D_cal_1 that are less than a given score from D_cal_2), which is equivalent to `tau=1` and `1_{s^i_j < s_j}` for discrete nonconformity scores. For "Copula Calibration on D_cal_2", equation (3) calculates U: U = {u^i}, where u^i = (F_hat_1(s^i_1), ..., F_hat_k(s^i_k)). The code calculates `alphas` in this step, where `scores` are the nonconformity scores for D_cal_2 (S_2 in the paper) and `self.nonconformity` are the scores for D_cal_1 (S_1 in the paper). The loop `(scores[i] > self.nonconformity).mean(axis=0)` effectively calculates `1 - F_hat_j(s_j)` or a similar proportion related to `F_hat_j`. Specifically, `(scores[i] > self.nonconformity).mean(axis=0)` calculates the proportion of nonconformity scores from `self.nonconformity` (D_cal_1) that are *less than or equal to* the current `scores[i]` (from D_cal_2), which is effectively `1 - F_hat_j(s_j)` if `F_hat_j` is defined as `P(S <= s)`. If `F_hat_j` is defined as `P(S < s)`, then it would be `1 - P(S >= s)`. Given the paper's definition of `F_hat_j(s_j)` using `< s_j`, the code calculates `P(S_1_j >= s_j)`. This is a discrepancy; the paper calculates `F_hat_j(s_j)` (a CDF), while the code calculates a complementary probability based on `>` operator. This could affect the interpretation of `alphas` as `u^i` from equation (3). Equation (4) from the paper involves searching for `u*` such that `C_empirical(u*) >= 1-alpha`. The code uses `search_alpha` function for this, which implements a numerical optimization (SGD based on Appendix B.2) to find `threshold`. This `threshold` is analogous to `u*` in the paper, but its exact meaning might differ due to the `alphas` calculation discrepancy. Finally, the radius is obtained by `F_hat_j^{-1}(u*_j)`. The code retrieves the `quantile` by finding the index `int(threshold[i] * mapping_shape) + 1` in the sorted `self.nonconformity` (which represents the empirical distribution of S_1). This corresponds to finding the empirical inverse CDF. Args: X_test: Input features for which to generate predictions. epsilon (float): The significance level (alpha in the paper, usually 0.1 for 90% confidence). Returns: tuple: A tuple containing: - y_pred (torch.Tensor): The raw predictions from the model for X_test. - radius (numpy.ndarray): The radius for the confidence region at each time step. This is equivalent to s*_j in the paper. """ # Calculate nonconformity scores for D_cal_2 (copula_x, copula_y). # This corresponds to S_2 in the paper. pred_y = self.model.predict(self.copula_x) scores = torch.norm((pred_y - self.copula_y), p=2, dim=-1).detach().numpy() # Calculate 'alphas' which are conceptually related to u^i in the paper. # For each score in D_cal_2, it calculates the proportion of nonconformity scores # from D_cal_1 that are *greater than* that score. # Discrepancy: The paper defines u^i = F_hat_j(s^i_j) where F_hat_j is a CDF (P(S < s)). # The code calculates (scores[i] > self.nonconformity).mean(axis=0) which means # P(S_1_j < scores[i]). If 'alphas' here are to represent u_j^i from the paper, # then the comparison operator should be consistent with the CDF definition. # Given the paper's CDF is P(S < s), this looks like 1 - P(S_1_j <= scores[i]). # The exact implication of this difference on the search for `threshold` (u*) # needs careful consideration with respect to the theoretical validity proof. alphas = [] for i in range(scores.shape[0]): a = (scores[i] > self.nonconformity).mean(axis=0) alphas.append(a) alphas = np.array(alphas) # Search for the optimal threshold (u* in the paper) using the `search_alpha` utility. # This corresponds to solving Eq. (4) from the paper, which involves optimizing # the empirical copula C_empirical. The `search_alpha` function, based on Appendix B.2, # is implemented using SGD to find this threshold. threshold = search_alpha(alphas, epsilon, epochs=800) # Map the threshold (u*) back to the nonconformity score space (s*). # This effectively performs the inverse CDF operation: s*_j = F_hat_j^{-1}(u*_j). # `self.nonconformity` (S_1) is used to construct the empirical inverse CDF. mapping_shape = self.nonconformity.shape[0] # Sorts the nonconformity scores for each time step (j) to facilitate quantile lookup. mapping = { i: sorted(self.nonconformity[:, i].tolist()) for i in range(alphas.shape[1]) } quantile = [] for i in range(alphas.shape[1]): # Calculate the index for the quantile. # `threshold[i]` represents the target quantile (u*_j). # `mapping_shape` is |S_1_j|. The index `int(threshold[i] * mapping_shape) + 1` # aims to find the score at the corresponding quantile in the sorted S_1_j. idx = int(threshold[i] * mapping_shape) + 1 if idx >= mapping_shape: idx = mapping_shape - 1 # Handle edge case for highest quantile. quantile.append(mapping[i][idx]) # The calculated quantiles are the radii (s*_j) for each time step. radius = np.array(quantile) # Make predictions for the test data. y_pred = self.model.predict(X_test) # Store the results for later access. self.results_dict[epsilon] = {"y_pred": y_pred, "radius": radius} return y_pred, radius def calc_area(self, radius): """ Calculates the area of the confidence regions assuming 2D circular regions. This corresponds to "Area_1-alpha = E[||Gamma_1-alpha(x)||]" metric in the paper. For d-dimensional balls and L2 nonconformity, the area (or volume in higher dimensions) of a ball with radius r is proportional to r^d. For d=2, it's pi * r^2. The paper uses L2 distance for nonconformity and states "The confidence region Gamma_1-alpha(x) therefore is a d-dimensional ball." The sum is across k prediction steps, each having its own radius. """ area = sum([np.pi * r**2 for r in radius]) return area def calc_area_l1(self, radius): """ Calculates the area of confidence regions assuming 2D regions based on L1 distance. If nonconformity is measured by L1 distance in 2D, the confidence region would be a square (diamond shape) with vertices at (+-r, 0) and (0, +-r). The area of such a square with L1 radius 'r' is 2 * r^2. """ area = sum([2 * r**2 for r in radius]) return area def calc_area_3d(self, radius): """ Calculates the volume of the confidence regions assuming 3D spherical regions. For d=3, the volume of a sphere with radius r is (4/3) * pi * r^3. """ area = sum([4 / 3.0 * np.pi * r**3 for r in radius]) return area def calc_area_1d(self, radius): """ Calculates the 'area' (length) of confidence regions assuming 1D intervals. For 1D, the confidence region is an interval of length 2*r centered at the prediction. The paper's "Area" metric is more general. For 1D, it would be the length of the interval, or just the sum of radii if each radius defines a single "side" in a broader sense. Here, it sums the radii, which if interpreting a 1D interval as [-r, r] (length 2r), then this is just the sum of r's. """ area = sum(radius) return area def calc_coverage(self, radius, y_pred, y_test): """ Calculates the empirical coverage of the confidence regions for 2D (L2 norm). This corresponds to the "Coverage_1-alpha" metric in the paper: P[forall j in {1..k}, y_j in Gamma_1-alpha_j] >= 1-alpha. The code checks if the nonconformity score for each test point and each time step is less than its corresponding radius. Then it checks if *all* time steps for a given test point are covered. Args: radius (numpy.ndarray): The calculated radii (s*_j) for each time step. y_pred (torch.Tensor): The model's predictions for the test data. y_test (torch.Tensor): The true target values for the test data. Returns: float: The empirical coverage, a value between 0 and 1. """ # Calculate nonconformity scores for the test data. testnonconformity = torch.norm((y_pred - y_test), p=2, dim=-1).detach().numpy() circle_covs = [] # Iterate through each time step (j from 1 to k). for j in range(y_test.shape[-2]): # -2 likely refers to the time step dimension (k). # Check if the nonconformity for a given time step is within its radius. circle_covs.append(testnonconformity[:, j] < radius[j]) circle_covs = np.array(circle_covs) # `np.all(circle_covs, axis=0)` checks if all time steps are covered for each sample. # `np.mean(...)` calculates the proportion of samples where all time steps are covered. coverage = np.mean(np.all(circle_covs, axis=0)) return coverage def calc_coverage_l1(self, radius, y_pred, y_test): """ Calculates the empirical coverage of the confidence regions using L1 norm. This is analogous to `calc_coverage` but uses the L1 distance for nonconformity. """ testnonconformity = ( torch.norm((y_pred - y_test), p=1, dim=-1).detach().numpy() ) circle_covs = [] for j in range(y_test.shape[-2]): circle_covs.append(testnonconformity[:, j] < radius[j]) circle_covs = np.array(circle_covs) coverage = np.mean(np.all(circle_covs, axis=0)) return coverage def calc_coverage_3d(self, radius, y_pred, y_test): """ Calculates coverage for 3D confidence regions (reusing L2 calculation). Since the nonconformity score calculation (L2 norm) is the same regardless of the dimension for the definition of the ball, this method simply calls `calc_coverage`. """ return self.calc_coverage(radius, y_pred, y_test) def calc_coverage_1d(self, radius, y_pred, y_test): """ Calculates coverage for 1D confidence regions (reusing L2 calculation). Similar to `calc_coverage_3d`, the L2 norm for 1D data is simply the absolute difference, which is what `calc_coverage` would use for 1D. """ return self.calc_coverage(radius, y_pred, y_test)