class_docstr: This class enables Greykite based anomaly detection algorithms.
      It takes a ``forecast_config`` and ``ad_config`` (see Parameters) and builds a detector which
      uses the forecast as baseline.
  
      The fit consists of following stages:
  
      - Fit a forecast model using the ``forecast_config`` passed
      - Fit a volatility model using
          `~greykite.algo.uncertainty.conditional.conf_interval.conf_interval`
          to optimize over
  
          -- ``volatility_features_list``
          -- ``coverage_grid``
  
          specified in ``ad_config`` passed.
  
  Parameters
  ----------
  ad_config: `~greykite.detection.detector.config.ADConfig` or None, default None
      Config object for anomaly detection to use.
  forecast_config : `~greykite.framework.templates.model_templates.ForecastConfig` or None, default None
      Config object for forecast to use.
  reward : See docstring for
      `~greykite.detection.detector.detector.Detector`
  
  Attributes
  ----------
  anomaly_percent_dict : `dict` or None,
      See attributes of `~greykite.detection.detector.detector.Detector`
  forecast_result : `~greykite.framework.pipeline.pipeline.ForecastResult` or None
      See class:`~greykite.framework.pipeline.pipeline.ForecastResult`
      for details.
  forecast_estimator : `~greykite.sklearn.estimator.base_forecast_estimator.BaseForecastEstimator` or None
      See class: `~greykite.sklearn.estimator.base_forecast_estimator.BaseForecastEstimator`
      for more details.
  ci_model : `dict`
      This is the fitted volatility model which is the returned dictionary from
      `greykite.algo.uncertainty.conditional.conf_interval`.
  fit_info : `dict` or None
      See attributes of `~greykite.detection.detector.detector.Detector`.
  anomaly_df : `pandas.DataFrame` or None
      A dataframe which includes the start and end times of observed anomalies.
  fit_data : `~greykite.detection.detector.data.DetectorData` or None
      The data used in the `fit` method.
class_docstr_tok: ["This","class","enables","Greykite","based","anomaly","detection","algorithms",".","It","takes","a","``","forecast_config","``","and","``","ad_config","``","(","see","Parameters",")","and","builds","a","detector","which","uses","the","forecast","as","baseline",".","The","fit","consists","of","following","stages",":","-","Fit","a","forecast","model","using","the","``","forecast_config","``","passed","-","Fit","a","volatility","model","using","`","~greykite.algo.uncertainty.conditional.conf_interval.conf_interval","`","to","optimize","over","--","``","volatility_features_list","``","--","``","coverage_grid","``","specified","in","``","ad_config","``","passed",".","Parameters","--","--","--","--","--","ad_config",":","`","~greykite.detection.detector.config.ADConfig","`","or","None",",","default","None","Config","object","for","anomaly","detection","to","use",".","forecast_config",":","`","~greykite.framework.templates.model_templates.ForecastConfig","`","or","None",",","default","None","Config","object","for","forecast","to","use",".","reward",":","See","docstring","for","`","~greykite.detection.detector.detector.Detector","`","Attributes","--","--","--","--","--","anomaly_percent_dict",":","`","dict","`","or","None",",","See","attributes","of","`","~greykite.detection.detector.detector.Detector","`","forecast_result",":","`","~greykite.framework.pipeline.pipeline.ForecastResult","`","or","None","See","class",":","`","~greykite.framework.pipeline.pipeline.ForecastResult","`","for","details",".","forecast_estimator",":","`","~greykite.sklearn.estimator.base_forecast_estimator.BaseForecastEstimator","`","or","None","See","class",":","`","~greykite.sklearn.estimator.base_forecast_estimator.BaseForecastEstimator","`","for","more","details",".","ci_model",":","`","dict","`","This","is","the","fitted","volatility","model","which","is","the","returned","dictionary","from","`","greykite.algo.uncertainty.conditional.conf_interval","`",".","fit_info",":","`","dict","`","or","None","See","attributes","of","`","~greykite.detection.detector.detector.Detector","`",".","anomaly_df",":","`","pandas.DataFrame","`","or","None","A","dataframe","which","includes","the","start","and","end","times","of","observed","anomalies",".","fit_data",":","`","~greykite.detection.detector.data.DetectorData","`","or","None","The","data","used","in","the","`","fit","`","method","."]
docstr: The fit method for Greykite based method.
  The fit consists of following stages:
  
      - Fit a forecast model using the ``forecast_config`` passed
      - Fit a volatility model using
          `~greykite.algo.uncertainty.conditional.conf_interval.conf_interval`
          to optimize over
  
          -- ``volatility_features_list``
          -- ``coverage_grid``
  
          specified in ``ad_config`` passed.
  
  Parameters
  ----------
  data : `~greykite.detection.detector.data.DetectorData`
      The input data which needs to include the input timeseries in ``df``
      attribute. We assume df includes minimally these two columns:
  
      - ``TIME_COL``
      - ``VALUE_COL``
  
      and if labels are also available in this datasets we expect the labels
      to be available in ``ANOMALY_COL``
docstr_tok: ["The","fit","method","for","Greykite","based","method",".","The","fit","consists","of","following","stages",":","-","Fit","a","forecast","model","using","the","``","forecast_config","``","passed","-","Fit","a","volatility","model","using","`","~greykite.algo.uncertainty.conditional.conf_interval.conf_interval","`","to","optimize","over","--","``","volatility_features_list","``","--","``","coverage_grid","``","specified","in","``","ad_config","``","passed",".","Parameters","--","--","--","--","--","data",":","`","~greykite.detection.detector.data.DetectorData","`","The","input","data","which","needs","to","include","the","input","timeseries","in","``","df","``","attribute",".","We","assume","df","includes","minimally","these","two","columns",":","-","``","TIME_COL","``","-","``","VALUE_COL","``","and","if","labels","are","also","available","in","this","datasets","we","expect","the","labels","to","be","available","in","``","ANOMALY_COL","``"]
code: def fit(self, data):
      """The fit method for Greykite based method.
      The fit consists of following stages:
  
          - Fit a forecast model using the ``forecast_config`` passed
          - Fit a volatility model using
              `~greykite.algo.uncertainty.conditional.conf_interval.conf_interval`
              to optimize over
  
              -- ``volatility_features_list``
              -- ``coverage_grid``
  
              specified in ``ad_config`` passed.
  
      Parameters
      ----------
      data : `~greykite.detection.detector.data.DetectorData`
          The input data which needs to include the input timeseries in ``df``
          attribute. We assume df includes minimally these two columns:
  
          - ``TIME_COL``
          - ``VALUE_COL``
  
          and if labels are also available in this datasets we expect the labels
          to be available in ``ANOMALY_COL``
      """
      fit_data = deepcopy(data)
      df = fit_data.df.copy()
      if df is None:
          raise ValueError(
              "observed dataframe (df) must be available in fit data"
          )
      if VALUE_COL not in df.columns:
          raise ValueError(
              f"observed dataframe (df) must be include {VALUE_COL} column"
          )
      if TIME_COL not in df.columns:
          raise ValueError(
              f"observed dataframe (df) must be include {TIME_COL} column"
          )
  
      # Initializes the forecaster and extracts the forecast parameters.
      forecaster = Forecaster()
      forecast_params = forecaster.apply_forecast_config(
          df=df, config=self.forecast_config
      )
      freq = forecast_params["freq"] or infer_freq(
          df, time_col=TIME_COL
      )
      if freq is None:
          raise ValueError(
              "Frequency could not be inferred as timestamps were too irregular."
          )
  
      # Sets train end date to be the last date in the data.
      # This way the Forecaster does not drop anomalous dates from the training data if
      # the anomaly is at the end of the data.
      train_end_date = (
          forecast_params.get("train_end_date", None)
          or df[TIME_COL].max()
      )
      date_format = forecast_params["date_format"]
  
      # Logs warnings if the data is not regularly spaced.
      # The missing timestamps are filled in the `get_canonical_data` function.
      time_stats = describe_timeseries(df=df, time_col=TIME_COL)
      if not time_stats["regular_increments"]:
          log_message(
              "Input time series data is not regularly spaced. "
              f"Minimum time increment: {time_stats['min_delta']}. "
              f"Maximum time increment: {time_stats['max_delta']}. "
              "We will attempt to fill in missing times.",
              LoggingLevelEnum.WARNING,
          )
  
      # Logs warnings if the data has repeated timestamps.
      # The repeated timestamps are removed in the `get_canonical_data` function.
      ts_unique, ts_count = np.unique(df[TIME_COL], return_counts=True)
      if max(ts_count) > 1:
          log_message(
              "The data timestamps had repeated values. "
              f"One timestamp had {max(ts_count)} repetitions. "
              "We will attempt to remove repeated timestamps and only keep first instance.",
              LoggingLevelEnum.WARNING,
          )
  
      # Gets the canonical data.
      canonical_data_dict = get_canonical_data(
          df=df,
          time_col=TIME_COL,
          value_col=VALUE_COL,
          freq=freq,
          date_format=date_format,
          train_end_date=train_end_date,
          anomaly_info=None,
      )
      df = canonical_data_dict["df"].reset_index(drop=True)
  
      # The following code checks for the existence of anomaly labels in the input `data`
      # and `forecast_config`, extracts them if available and merges them into a single dataframe.
      # Updated data is saved in `self.fit_data`.
      fit_data.df = df
      self.fit_data = self.merge_anomaly_info(
          fit_data=fit_data, freq=freq
      )
  
      # Builds the anomaly info.
      if self.anomaly_df is None:
          anomaly_info = None
      else:
          anomaly_info = {
              "value_col": VALUE_COL,
              "anomaly_df": self.anomaly_df,
          }
  
      # Updates `metadata_param` in the `forecast_config`.
      if self.forecast_config.metadata_param is None:
          self.forecast_config.metadata_param = MetadataParam()
      self.forecast_config.metadata_param.time_col = TIME_COL
      self.forecast_config.metadata_param.value_col = VALUE_COL
      self.forecast_config.metadata_param.train_end_date = (
          train_end_date
      )
      self.forecast_config.metadata_param.freq = freq
      self.forecast_config.metadata_param.anomaly_info = anomaly_info
  
      # Fits the forecast model.
      self.forecast_result = forecaster.run_forecast_config(
          df=df, config=self.forecast_config
      )
      forecast_estimator = self.forecast_result.model[-1]
      self.forecast_estimator = forecast_estimator
  
      default_param = {}
      optim_res = self.optimize_param(
          data=self.fit_data,
          param_iterable=self.param_iterable,
          default_param=default_param,
          phase="fit",
      )
  
      self.fit_info = {
          "param": optim_res["best_param"],
          "param_full": optim_res["best_param_full"],
          "obj_value": optim_res["best_obj_value"],
          "param_obj_list": optim_res["param_obj_list"],
          "best_calc_result": optim_res["best_calc_result"],
      }
      self.fitted_df = self.fit_info["best_calc_result"].data.pred_df
  
imports: from copy import deepcopy
  import numpy
  import pandas
  from greykite.algo.uncertainty.conditional.conf_interval import conf_interval
  from greykite.algo.uncertainty.conditional.conf_interval import predict_ci
  from greykite.common.constants import ACTUAL_COL
  from greykite.common.constants import ANOMALY_COL
  from greykite.common.constants import END_TIME_COL
  from greykite.common.constants import ERR_STD_COL
  from greykite.common.constants import PREDICTED_ANOMALY_COL
  from greykite.common.constants import PREDICTED_COL
  from greykite.common.constants import PREDICTED_LOWER_COL
  from greykite.common.constants import PREDICTED_UPPER_COL
  from greykite.common.constants import QUANTILE_SUMMARY_COL
  from greykite.common.constants import RESIDUAL_COL
  from greykite.common.constants import START_TIME_COL
  from greykite.common.constants import TIME_COL
  from greykite.common.constants import VALUE_COL
  from greykite.common.evaluation import ElementwiseEvaluationMetricEnum
  from greykite.common.features.adjust_anomalous_data import adjust_anomalous_data
  from greykite.common.features.timeseries_features import add_daily_events
  from greykite.common.features.timeseries_features import add_time_features_df
  from greykite.common.logging import LoggingLevelEnum
  from greykite.common.logging import log_message
  from greykite.common.time_properties import describe_timeseries
  from greykite.common.time_properties import get_canonical_data
  from greykite.common.time_properties import infer_freq
  from greykite.detection.detector.ad_utils import add_new_params_to_records
  from greykite.detection.detector.ad_utils import get_anomaly_df
  from greykite.detection.detector.ad_utils import get_anomaly_df_from_outliers
  from greykite.detection.detector.ad_utils import get_canonical_anomaly_df
  from greykite.detection.detector.config import ADConfig
  from greykite.detection.detector.config_to_reward import config_to_reward
  from greykite.detection.detector.constants import DEFAULT_COVERAGE_GRID
  from greykite.detection.detector.constants import PHASE_PREDICT
  from greykite.detection.detector.constants import Z_SCORE_COL
  from greykite.detection.detector.detector import Detector
  from greykite.detection.detector.optimizer import CalcResult
  from greykite.framework.templates.autogen.forecast_config import ForecastConfig
  from greykite.framework.templates.autogen.forecast_config import MetadataParam
  from greykite.framework.templates.forecaster import Forecaster
label_desc: Use image node_id 2 for calling the GreykiteDetector obj's underlying member method code with example usage: obj.fit(data) without return types