|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# Copyright (c) 2023, 2025 Oracle and/or its affiliates. |
| 4 | +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/ |
| 5 | + |
| 6 | +import os |
| 7 | +import tempfile |
| 8 | +import pandas as pd |
| 9 | +import pytest |
| 10 | +from copy import deepcopy |
| 11 | +from ads.opctl.operator.lowcode.forecast.__main__ import operate |
| 12 | +from ads.opctl.operator.lowcode.forecast.operator_config import ForecastOperatorConfig |
| 13 | + |
| 14 | +DATASET_PREFIX = f"{os.path.dirname(os.path.abspath(__file__))}/../data/timeseries/" |
| 15 | + |
| 16 | +TEMPLATE_YAML = { |
| 17 | + "kind": "operator", |
| 18 | + "type": "forecast", |
| 19 | + "version": "v1", |
| 20 | + "spec": { |
| 21 | + "historical_data": { |
| 22 | + "url": f"{DATASET_PREFIX}dataset1.csv", |
| 23 | + }, |
| 24 | + "output_directory": { |
| 25 | + "url": "results", |
| 26 | + }, |
| 27 | + "model": "prophet", |
| 28 | + "target_column": "Y", |
| 29 | + "datetime_column": { |
| 30 | + "name": "Date", |
| 31 | + }, |
| 32 | + "horizon": 5, |
| 33 | + "generate_explanations": False, |
| 34 | + }, |
| 35 | +} |
| 36 | + |
| 37 | +@pytest.fixture(autouse=True) |
| 38 | +def operator_setup(): |
| 39 | + with tempfile.TemporaryDirectory() as tmpdirname: |
| 40 | + yield tmpdirname |
| 41 | + |
| 42 | +class TestForecastApiOptions: |
| 43 | + def test_custom_filenames(self, operator_setup): |
| 44 | + """Tests that custom filenames are correctly used.""" |
| 45 | + tmpdirname = operator_setup |
| 46 | + yaml_i = deepcopy(TEMPLATE_YAML) |
| 47 | + yaml_i["spec"]["output_directory"]["url"] = tmpdirname |
| 48 | + yaml_i["spec"]["report_filename"] = "my_report.html" |
| 49 | + yaml_i["spec"]["metrics_filename"] = "my_metrics.csv" |
| 50 | + yaml_i["spec"]["test_metrics_filename"] = "my_test_metrics.csv" |
| 51 | + yaml_i["spec"]["forecast_filename"] = "my_forecast.csv" |
| 52 | + yaml_i["spec"]["test_data"] = { |
| 53 | + "url": f"{DATASET_PREFIX}dataset1.csv" |
| 54 | + } |
| 55 | + |
| 56 | + operator_config = ForecastOperatorConfig.from_dict(yaml_i) |
| 57 | + operate(operator_config) |
| 58 | + |
| 59 | + output_files = os.listdir(tmpdirname) |
| 60 | + assert "my_report.html" in output_files |
| 61 | + assert "my_metrics.csv" in output_files |
| 62 | + assert "my_test_metrics.csv" in output_files |
| 63 | + assert "my_forecast.csv" in output_files |
| 64 | + |
| 65 | + def test_report_theme(self, operator_setup): |
| 66 | + """Tests that the report theme is correctly applied.""" |
| 67 | + tmpdirname = operator_setup |
| 68 | + yaml_i = deepcopy(TEMPLATE_YAML) |
| 69 | + yaml_i["spec"]["output_directory"]["url"] = tmpdirname |
| 70 | + yaml_i["spec"]["report_theme"] = "dark" |
| 71 | + |
| 72 | + operator_config = ForecastOperatorConfig.from_dict(yaml_i) |
| 73 | + operate(operator_config) |
| 74 | + |
| 75 | + with open(os.path.join(tmpdirname, "report.html"), "r") as f: |
| 76 | + report_content = f.read() |
| 77 | + assert "dark" in report_content |
| 78 | + |
| 79 | + def test_disable_report_generation(self, operator_setup): |
| 80 | + """Tests that report generation can be disabled.""" |
| 81 | + tmpdirname = operator_setup |
| 82 | + yaml_i = deepcopy(TEMPLATE_YAML) |
| 83 | + yaml_i["spec"]["output_directory"]["url"] = tmpdirname |
| 84 | + yaml_i["spec"]["generate_report"] = False |
| 85 | + |
| 86 | + operator_config = ForecastOperatorConfig.from_dict(yaml_i) |
| 87 | + operate(operator_config) |
| 88 | + |
| 89 | + output_files = os.listdir(tmpdirname) |
| 90 | + assert "report.html" not in output_files |
| 91 | + |
| 92 | + def test_previous_output_dir(self, operator_setup): |
| 93 | + """Tests that a previous model can be loaded.""" |
| 94 | + tmpdirname = operator_setup |
| 95 | + |
| 96 | + # First run: generate a model |
| 97 | + first_run_dir = os.path.join(tmpdirname, "first_run") |
| 98 | + os.makedirs(first_run_dir) |
| 99 | + yaml1 = deepcopy(TEMPLATE_YAML) |
| 100 | + yaml1["spec"]["output_directory"]["url"] = first_run_dir |
| 101 | + yaml1["spec"]["generate_model_pickle"] = True |
| 102 | + |
| 103 | + operator_config1 = ForecastOperatorConfig.from_dict(yaml1) |
| 104 | + operate(operator_config1) |
| 105 | + |
| 106 | + # Second run: use the previous model |
| 107 | + second_run_dir = os.path.join(tmpdirname, "second_run") |
| 108 | + os.makedirs(second_run_dir) |
| 109 | + yaml2 = deepcopy(TEMPLATE_YAML) |
| 110 | + yaml2["spec"]["output_directory"]["url"] = second_run_dir |
| 111 | + yaml2["spec"]["previous_output_dir"] = first_run_dir |
| 112 | + |
| 113 | + operator_config2 = ForecastOperatorConfig.from_dict(yaml2) |
| 114 | + operate(operator_config2) |
| 115 | + |
| 116 | + # Check that the second run produced a forecast |
| 117 | + output_files = os.listdir(second_run_dir) |
| 118 | + assert "forecast.csv" in output_files |
| 119 | + |
| 120 | + def test_generate_model_artifacts(self, operator_setup): |
| 121 | + """Tests that model artifacts are correctly generated.""" |
| 122 | + tmpdirname = operator_setup |
| 123 | + yaml_i = deepcopy(TEMPLATE_YAML) |
| 124 | + yaml_i["spec"]["output_directory"]["url"] = tmpdirname |
| 125 | + yaml_i["spec"]["generate_model_parameters"] = True |
| 126 | + yaml_i["spec"]["generate_model_pickle"] = True |
| 127 | + |
| 128 | + operator_config = ForecastOperatorConfig.from_dict(yaml_i) |
| 129 | + operate(operator_config) |
| 130 | + |
| 131 | + output_files = os.listdir(tmpdirname) |
| 132 | + assert "model_params.json" in output_files |
| 133 | + |
| 134 | + def test_metric(self, operator_setup): |
| 135 | + """Tests that the metric is correctly used.""" |
| 136 | + tmpdirname = operator_setup |
| 137 | + yaml_i = deepcopy(TEMPLATE_YAML) |
| 138 | + yaml_i["spec"]["output_directory"]["url"] = tmpdirname |
| 139 | + yaml_i["spec"]["metric"] = "RMSE" |
| 140 | + yaml_i["spec"]["test_data"] = { |
| 141 | + "url": f"{DATASET_PREFIX}dataset1.csv" |
| 142 | + } |
| 143 | + |
| 144 | + operator_config = ForecastOperatorConfig.from_dict(yaml_i) |
| 145 | + operate(operator_config) |
| 146 | + |
| 147 | + metrics = pd.read_csv(os.path.join(tmpdirname, "metrics.csv")) |
| 148 | + assert "RMSE" in metrics["Metric"].values |
| 149 | + |
| 150 | + def test_outlier_treatment(self, operator_setup): |
| 151 | + """Tests that outlier treatment is correctly applied.""" |
| 152 | + tmpdirname = operator_setup |
| 153 | + |
| 154 | + # Create a dataset with outliers |
| 155 | + data = pd.read_csv(f"{DATASET_PREFIX}dataset1.csv") |
| 156 | + data.loc[5, "Y"] = 1000 |
| 157 | + data.loc[15, "Y"] = -1000 |
| 158 | + historical_data_path = os.path.join(tmpdirname, "historical_data.csv") |
| 159 | + data.to_csv(historical_data_path, index=False) |
| 160 | + |
| 161 | + # Run with outlier treatment |
| 162 | + yaml_with = deepcopy(TEMPLATE_YAML) |
| 163 | + yaml_with["spec"]["historical_data"]["url"] = historical_data_path |
| 164 | + yaml_with["spec"]["output_directory"]["url"] = os.path.join(tmpdirname, "with_treatment") |
| 165 | + yaml_with["spec"]["preprocessing"] = {"steps": {"outlier_treatment": True}} |
| 166 | + |
| 167 | + operate(ForecastOperatorConfig.from_dict(yaml_with)) |
| 168 | + |
| 169 | + # Run without outlier treatment |
| 170 | + yaml_without = deepcopy(TEMPLATE_YAML) |
| 171 | + yaml_without["spec"]["historical_data"]["url"] = historical_data_path |
| 172 | + yaml_without["spec"]["output_directory"]["url"] = os.path.join(tmpdirname, "without_treatment") |
| 173 | + yaml_without["spec"]["preprocessing"] = {"steps": {"outlier_treatment": False}} |
| 174 | + |
| 175 | + operate(ForecastOperatorConfig.from_dict(yaml_without)) |
| 176 | + |
| 177 | + # Check that outliers are present in the forecast without treatment |
| 178 | + forecast_without = pd.read_csv(os.path.join(tmpdirname, "without_treatment", "forecast.csv")) |
| 179 | + assert 1000 in forecast_without["yhat"].values |
| 180 | + assert -1000 in forecast_without["yhat"].values |
| 181 | + |
| 182 | + # Check that outliers are not present in the forecast with treatment |
| 183 | + forecast_with = pd.read_csv(os.path.join(tmpdirname, "with_treatment", "forecast.csv")) |
| 184 | + assert 1000 not in forecast_with["yhat"].values |
| 185 | + assert -1000 not in forecast_with["yhat"].values |
| 186 | + |
| 187 | + def test_missing_value_imputation(self, operator_setup): |
| 188 | + """Tests that missing value imputation is correctly applied.""" |
| 189 | + tmpdirname = operator_setup |
| 190 | + |
| 191 | + # Create a dataset with missing values |
| 192 | + data = pd.read_csv(f"{DATASET_PREFIX}dataset1.csv") |
| 193 | + data.loc[5, "Y"] = None |
| 194 | + data.loc[15, "Y"] = None |
| 195 | + historical_data_path = os.path.join(tmpdirname, "historical_data.csv") |
| 196 | + data.to_csv(historical_data_path, index=False) |
| 197 | + |
| 198 | + # Run with missing value imputation |
| 199 | + yaml_i = deepcopy(TEMPLATE_YAML) |
| 200 | + yaml_i["spec"]["historical_data"]["url"] = historical_data_path |
| 201 | + yaml_i["spec"]["output_directory"]["url"] = tmpdirname |
| 202 | + yaml_i["spec"]["preprocessing"] = {"steps": {"missing_value_imputation": True}} |
| 203 | + |
| 204 | + results = operate(ForecastOperatorConfig.from_dict(yaml_i)) |
| 205 | + forecast = results.get_forecast() |
| 206 | + |
| 207 | + # Check that there are no missing values in the forecast |
| 208 | + assert not forecast["yhat"].isnull().any() |
| 209 | + assert "model.pkl" in output_files |
| 210 | + |
| 211 | + def test_confidence_interval_width(self, operator_setup): |
| 212 | + """Tests that the confidence interval width is correctly applied.""" |
| 213 | + tmpdirname = operator_setup |
| 214 | + yaml_i = deepcopy(TEMPLATE_YAML) |
| 215 | + yaml_i["spec"]["output_directory"]["url"] = tmpdirname |
| 216 | + yaml_i["spec"]["confidence_interval_width"] = 0.95 |
| 217 | + |
| 218 | + operator_config = ForecastOperatorConfig.from_dict(yaml_i) |
| 219 | + results = operate(operator_config) |
| 220 | + forecast = results.get_forecast() |
| 221 | + |
| 222 | + # Check that the confidence interval is close to the specified width |
| 223 | + # This is a basic check, a more robust check would involve statistical tests |
| 224 | + assert "yhat_upper" in forecast.columns |
| 225 | + assert "yhat_lower" in forecast.columns |
| 226 | + |
| 227 | + def test_tuning(self, operator_setup): |
| 228 | + """Tests that tuning is correctly applied.""" |
| 229 | + tmpdirname = operator_setup |
| 230 | + yaml_i = deepcopy(TEMPLATE_YAML) |
| 231 | + yaml_i["spec"]["output_directory"]["url"] = tmpdirname |
| 232 | + yaml_i["spec"]["tuning"] = {"n_trials": 5} |
| 233 | + yaml_i["spec"]["generate_model_parameters"] = True |
| 234 | + |
| 235 | + operator_config = ForecastOperatorConfig.from_dict(yaml_i) |
| 236 | + operate(operator_config) |
| 237 | + |
| 238 | + output_files = os.listdir(tmpdirname) |
| 239 | + assert "model_params.json" in output_files |
0 commit comments