Download annotations/annotation_18/test.py from mcy98/RECODE-H: direct link, hf CLI and curl.
- Browser
- Download file 9.91 kB
-
https://huggingface.co/datasets/mcy98/RECODE-H/resolve/main/annotations/annotation_18/test.py
- Command line
-
hf download hf://datasets/mcy98/RECODE-H/annotations/annotation_18/test.py
-
curl -L -o test.py https://huggingface.co/datasets/mcy98/RECODE-H/resolve/main/annotations/annotation_18/test.py
9.91 kB
| import unittest | |
| import numpy as np | |
| import torch | |
| # Import the canonical and generated CopulaCPTS implementations | |
| from src.models.canonical import copulaCPTS as CanonicalCopulaCPTS | |
| from src.models.copulaCPTS import copulaCPTS as GeneratedCopulaCPTS | |
| class DummyModel: | |
| def predict(self, x): | |
| """ | |
| Given input shape [N, 35, 2], returns a 'forecast' of shape [N, 24, 2]. | |
| We'll make a simple 'predict the last value carried forward' or similar logic. | |
| """ | |
| # For illustration: predict the mean over the input time window, repeated | |
| mean_val = x.mean(dim=1, keepdim=True) # shape [N, 1, 2] | |
| pred = mean_val.repeat(1, 24, 1) # shape [N, 24, 2] | |
| return pred | |
| def assert_arraylike_equal(self, can_val, gen_val, places=6, msg=''): | |
| # Helper for floats, arrays, tensors, tuples recursively | |
| if isinstance(can_val, torch.Tensor): | |
| can_val, gen_val = can_val.detach().cpu().numpy(), gen_val.detach().cpu().numpy() | |
| if isinstance(can_val, (np.ndarray, list, tuple)): | |
| np.testing.assert_allclose(can_val, gen_val, rtol=10**(-places), err_msg=msg) | |
| else: | |
| self.assertAlmostEqual(can_val, gen_val, places=places, msg=msg) | |
| def generate_ar5_series(length, num_features, coeffs, noise_std=0.5, seed=None): | |
| """ | |
| Simulate a single multivariate AR(5) time series sample. | |
| Returns shape [length, num_features]. | |
| """ | |
| if seed is not None: | |
| np.random.seed(seed) | |
| x = np.zeros((length, num_features)) | |
| # Start with some random initial values for the first 5 steps | |
| x[:5] = np.random.randn(5, num_features) | |
| for t in range(5, length): | |
| for d in range(num_features): | |
| # AR(5) for each feature independently | |
| ar_part = sum(coeffs[d, i] * x[t-1-i, d] for i in range(5)) | |
| noise = np.random.randn() * noise_std | |
| x[t, d] = ar_part + noise | |
| return x | |
| def prepare_time_series_data(seed: int = 42): | |
| """ | |
| Generate AR(5) multi-step time series dataset: | |
| - x_train: [2000, 35, 2], y_train: [2000, 24, 2] | |
| - x_cali: [500, 35, 2], y_cali: [500, 24, 2] | |
| - x_test: [500, 35, 2], y_test: [500, 24, 2] | |
| """ | |
| torch.manual_seed(seed) | |
| np.random.seed(seed) | |
| num_features = 2 | |
| input_length = 35 | |
| output_length = 24 | |
| total_length = input_length + output_length # 59 | |
| sizes = { | |
| 'train': 2000, | |
| 'cali': 500, | |
| 'test': 500 | |
| } | |
| data = {} | |
| # Generate fixed AR(5) coefficients for each feature, for reproducibility | |
| coeffs = np.random.uniform(-0.8, 0.8, size=(num_features, 5)) | |
| # Optionally, normalize coeffs for stability (sum < 1 for stationarity) | |
| for d in range(num_features): | |
| coeffs[d] /= (np.abs(coeffs[d]).sum() + 0.1) | |
| for split, N in sizes.items(): | |
| series = [] | |
| for n in range(N): | |
| sample = generate_ar5_series(total_length, num_features, coeffs, seed=seed+n) | |
| series.append(sample) | |
| arr = np.stack(series, axis=0) # [N, 59, 2] | |
| data[f'x_{split}'] = torch.tensor(arr[:, :input_length], dtype=torch.float32) | |
| data[f'y_{split}'] = torch.tensor(arr[:, input_length:], dtype=torch.float32) | |
| return { | |
| 'x_train': data['x_train'], 'y_train': data['y_train'], | |
| 'x_cali': data['x_cali'], 'y_cali': data['y_cali'], | |
| 'x_test': data['x_test'], 'y_test': data['y_test'], | |
| } | |
| class TestCopulaCPTSImplementations(unittest.TestCase): | |
| def setUpClass(cls): | |
| torch.manual_seed(42) | |
| np.random.seed(42) | |
| # Load and downsample data for efficiency | |
| data = prepare_time_series_data() | |
| cls.cali_x = data['x_cali'] | |
| cls.cali_y = data['y_cali'] | |
| cls.test_x = data['x_test'] | |
| cls.test_y = data['y_test'] | |
| cls.model = DummyModel() | |
| cls.epsilon = 0.2 | |
| print("\nInitializing canonical CopulaCPTS instance...") | |
| cls.canonical = CanonicalCopulaCPTS(cls.model, cls.cali_x, cls.cali_y) | |
| print("Canonical CopulaCPTS initialized.") | |
| print("\nInitializing generated CopulaCPTS instance...") | |
| cls.generated = GeneratedCopulaCPTS(cls.model, cls.cali_x, cls.cali_y) | |
| print("Generated CopulaCPTS initialized.") | |
| # --- Helper for output comparison --- | |
| def assertOutputsEqual(self, can_out, gen_out, msg='', places=6): | |
| # Compare types first | |
| self.assertEqual(type(can_out), type(gen_out), msg=f"{msg} Type mismatch: {type(can_out)} vs {type(gen_out)}") | |
| # Numeric: check allclose | |
| if isinstance(can_out, (float, np.float32, np.float64)): | |
| self.assertAlmostEqual(can_out, gen_out, places=places, msg=msg) | |
| elif isinstance(can_out, (np.ndarray, list, tuple, torch.Tensor)): | |
| if isinstance(can_out, torch.Tensor): # To numpy | |
| can_out = can_out.detach().cpu().numpy() | |
| if isinstance(gen_out, torch.Tensor): | |
| gen_out = gen_out.detach().cpu().numpy() | |
| np.testing.assert_allclose(can_out, gen_out, rtol=10**(-places), err_msg=msg) | |
| elif isinstance(can_out, dict): | |
| self.assertEqual(can_out.keys(), gen_out.keys(), msg=f"{msg} Dict keys differ.") | |
| for k in can_out: | |
| self.assertOutputsEqual(can_out[k], gen_out[k], msg=f"{msg} key '{k}'", places=places) | |
| else: | |
| self.assertEqual(can_out, gen_out, msg=msg) | |
| # ---- Test methods ---- | |
| def test_split_cali(self): | |
| """Test split_cali on both implementations.""" | |
| split = 0.5 | |
| self.canonical.split_cali(self.cali_x, self.cali_y, split) | |
| self.generated.split_cali(self.cali_x, self.cali_y, split) | |
| self.assertOutputsEqual(self.canonical.cali_x.shape, self.generated.cali_x.shape, msg='cali_x shape') | |
| self.assertOutputsEqual(self.canonical.cali_y.shape, self.generated.cali_y.shape, msg='cali_y shape') | |
| self.assertOutputsEqual(self.canonical.copula_x.shape, self.generated.copula_x.shape, msg='copula_x shape') | |
| self.assertOutputsEqual(self.canonical.copula_y.shape, self.generated.copula_y.shape, msg='copula_y shape') | |
| def test_calibrate(self): | |
| self.canonical.calibrate() | |
| self.generated.calibrate() | |
| self.assertOutputsEqual(self.canonical.nonconformity, self.generated.nonconformity, msg='nonconformity (L2)') | |
| def test_calibrate_l1(self): | |
| self.canonical.calibrate_l1() | |
| self.generated.calibrate_l1() | |
| self.assertOutputsEqual(self.canonical.nonconformity, self.generated.nonconformity, msg='nonconformity (L1)') | |
| def test_predict(self): | |
| y_pred_can, radius_can = self.canonical.predict(self.test_x, self.epsilon) | |
| y_pred_gen, radius_gen = self.generated.predict(self.test_x, self.epsilon) | |
| self.assertOutputsEqual(y_pred_can, y_pred_gen, msg='predict: y_pred') | |
| self.assertOutputsEqual(radius_can, radius_gen, msg='predict: radius') | |
| def test_calc_area(self): | |
| self.canonical.calibrate() | |
| radius = self.canonical.nonconformity[0] | |
| area_can = self.canonical.calc_area(radius) | |
| area_gen = self.generated.calc_area(radius) | |
| self.assertOutputsEqual(area_can, area_gen, msg='calc_area') | |
| def test_calc_area_l1(self): | |
| self.canonical.calibrate_l1() | |
| radius = self.canonical.nonconformity[0] | |
| area_can = self.canonical.calc_area_l1(radius) | |
| area_gen = self.generated.calc_area_l1(radius) | |
| self.assertOutputsEqual(area_can, area_gen, msg='calc_area_l1') | |
| def test_calc_area_3d(self): | |
| self.canonical.calibrate() | |
| radius = self.canonical.nonconformity[0] | |
| area_can = self.canonical.calc_area_3d(radius) | |
| area_gen = self.generated.calc_area_3d(radius) | |
| self.assertOutputsEqual(area_can, area_gen, msg='calc_area_3d') | |
| def test_calc_area_1d(self): | |
| self.canonical.calibrate() | |
| radius = self.canonical.nonconformity[0] | |
| area_can = self.canonical.calc_area_1d(radius) | |
| area_gen = self.generated.calc_area_1d(radius) | |
| self.assertOutputsEqual(area_can, area_gen, msg='calc_area_1d') | |
| def test_calc_coverage(self): | |
| self.canonical.calibrate() | |
| radius = self.canonical.nonconformity[0] | |
| y_pred = self.canonical.model.predict(self.test_x) | |
| y_test = self.test_y | |
| cov_can = self.canonical.calc_coverage(radius, y_pred, y_test) | |
| cov_gen = self.generated.calc_coverage(radius, y_pred, y_test) | |
| self.assertOutputsEqual(cov_can, cov_gen, msg='calc_coverage') | |
| def test_calc_coverage_l1(self): | |
| self.canonical.calibrate_l1() | |
| radius = self.canonical.nonconformity[0] | |
| y_pred = self.canonical.model.predict(self.test_x) | |
| y_test = self.test_y | |
| cov_can = self.canonical.calc_coverage_l1(radius, y_pred, y_test) | |
| cov_gen = self.generated.calc_coverage_l1(radius, y_pred, y_test) | |
| self.assertOutputsEqual(cov_can, cov_gen, msg='calc_coverage_l1') | |
| def test_calc_coverage_3d(self): | |
| self.canonical.calibrate() | |
| radius = self.canonical.nonconformity[0] | |
| y_pred = self.canonical.model.predict(self.test_x) | |
| y_test = self.test_y | |
| cov_can = self.canonical.calc_coverage_3d(radius, y_pred, y_test) | |
| cov_gen = self.generated.calc_coverage_3d(radius, y_pred, y_test) | |
| self.assertOutputsEqual(cov_can, cov_gen, msg='calc_coverage_3d') | |
| def test_calc_coverage_1d(self): | |
| self.canonical.calibrate() | |
| radius = self.canonical.nonconformity[0] | |
| y_pred = self.canonical.model.predict(self.test_x) | |
| y_test = self.test_y | |
| cov_can = self.canonical.calc_coverage_1d(radius, y_pred, y_test) | |
| cov_gen = self.generated.calc_coverage_1d(radius, y_pred, y_test) | |
| self.assertOutputsEqual(cov_can, cov_gen, msg='calc_coverage_1d') | |
| if __name__ == '__main__': | |
| unittest.main(verbosity=2) | |