code: def detect_anomalies(
      train_data: pd.DataFrame,
      label: str,
      test_data: Optional[pd.DataFrame] = None,
      val_data: Optional[pd.DataFrame] = None,
      explain_top_n_anomalies: Optional[int] = None,
      show_top_n_anomalies: Optional[int] = 10,
      threshold_stds: float = 3,
      show_help_text: bool = True,
      state: Union[None, dict, AnalysisState] = None,
      sample: Union[None, int, float] = DEFAULT_SAMPLE_SIZE,
      return_state: bool = False,
      fig_args: Optional[Dict[str, Any]] = None,
      chart_args: Optional[Dict[str, Any]] = None,
      **anomaly_detector_kwargs,
  ) -> Optional[AnalysisState]:
      """
      Anomaly Detection
  
      This method is used to identify unusual patterns or behaviors in data that deviate significantly from the norm.
      It's best used when finding outliers, rare events, or suspicious activities that could indicate fraud, defects, or system failures.
  
      When interpreting anomaly scores, consider:
  
      - `Threshold`:
          Determine a suitable threshold to separate normal from anomalous data points, based on domain knowledge or statistical methods.
      - `Context`:
          Examine the context of anomalies, including time, location, and surrounding data points, to identify possible causes.
      - `False positives/negatives`:
          Be aware of the trade-offs between false positives (normal points classified as anomalies) and false negatives (anomalies missed).
      - `Feature relevance`:
          Ensure the features used for anomaly detection are relevant and contribute to the model's performance.
      - `Model performance`:
          Regularly evaluate and update the model to maintain its accuracy and effectiveness.
  
      It's important to understand the context and domain knowledge before deciding on an appropriate approach to deal with anomalies.
      The choice of method depends on the data's nature, the cause of anomalies, and the problem being addressed.
      The common ways to deal with anomalies:
  
      - `Removal`:
          If an anomaly is a result of an error, noise, or irrelevance to the analysis, it can be removed from the dataset
          to prevent it from affecting the model's performance.
      - `Imputation`:
          Replace anomalous values with appropriate substitutes, such as the mean, median, or mode of the feature,
          or by using more advanced techniques like regression or k-nearest neighbors.
      - `Transformation`:
          Apply transformations like log, square root, or z-score to normalize the data and reduce the impact of extreme values.
          Absolute dates might be transformed into relative features like age of the item.
      - `Capping`:
          Set upper and lower bounds for a feature, and replace values outside these limits with the bounds themselves.
          This method is also known as winsorizing.
      - `Separate modeling`:
          Treat anomalies as a distinct group and build a separate model for them, or use specialized algorithms designed
          for handling outliers, such as robust regression or one-class SVM.
      - `Incorporate as a feature`:
          Create a new binary feature indicating the presence of an anomaly, which can be useful if anomalies have predictive value.
  
      State attributes
  
      - `anomaly_detection.scores.<dataset>`
          scores for each of the datasets passed into analysis (i.e. `train_data`, `test_data`)
      - `state.anomaly_detection.anomalies.<dataset>`
          data points considered as anomalies - original rows with added `score` column sorted in descending score order.
          defined by `threshold_stds` parameter
      - `anomaly_detection.anomaly_score_threshold`
          anomaly score threshold above which data points are considered as anomalies;
          defined by `threshold_stds` parameter
  
      Parameters
      ----------
      train_data: DataFrame
          training dataset
      label: str
          target variable
      test_data: Optional[pd.DataFrame], default = None
          test dataset
      val_data: Optional[pd.DataFrame], default = None
          validation dataset
      explain_top_n_anomalies: Optional[int], default = None
          explain the anomaly scores for n rows with the highest scores; don't perform analysis if value is `None` or `0`
      show_top_n_anomalies: Optional[int], default = 10
          display n rows with highest anomaly scores
      threshold_stds: float, default = 3
          specifies how many standard deviations above mean anomaly score considered as anomalies
          (only needed for visualization, does not affect scores calculation)
      show_help_text:bool, default = True
          if `True` shows additional information how to interpret the data
      state: Union[None, dict, AnalysisState], default = None
          pass prior state if necessary; the object will be updated during `anlz_facets` `fit` call.
      sample: Union[None, int, float], default = 10000
          sample size; if `int`, then row number is used;
          `float` must be between 0.0 and 1.0 and represents fraction of dataset to sample;
          `None` means no sampling
          See also :func:`autogluon.eda.analysis.dataset.Sampler`
      return_state: bool, default = False
          return state if `True`
      fig_args: Optional[Dict[str, Any]], default = None,
          kwargs to pass into visualization component
      chart_args: Optional[dict], default = None
          kwargs to pass into visualization component
      anomaly_detector_kwargs
          kwargs to pass into :py:class:`~autogluon.eda.analysis.anomaly.AnomalyDetectorAnalysis`
  
      >>> import autogluon.eda.auto as auto
      >>>
      >>> state = auto.detect_anomalies(
      >>>     train_data=...,
      >>>     test_data=...,  # optional
      >>>     label=...,
      >>>     threshold_stds=3,
      >>>     show_top_n_anomalies=5,
      >>>     explain_top_n_anomalies=3,
      >>>     return_state=True,
      >>>     chart_args={
      >>>         'normal.color': 'lightgrey',
      >>>         'anomaly.color': 'orange',
      >>>     }
      >>> )
      >>>
      >>> # Getting anomaly scores from the analysis
      >>> train_anomaly_scores = state.anomaly_detection.scores.train_data
      >>> test_anomaly_scores = state.anomaly_detection.scores.test_data
      >>>
      >>> # Anomaly score threshold for specified level - see `threshold_stds` parameter
      >>> anomaly_score_threshold = state.anomaly_detection.anomaly_score_threshold
  
      Returns
      -------
      state after `fit` call if `return_state` is `True`; `None` otherwise
  
      See Also
      --------
      :py:class:`~autogluon.eda.analysis.anomaly.AnomalyDetectorAnalysis`
      :py:class:`~autogluon.eda.visualization.anomaly.AnomalyScoresVisualization`
      """
      fig_args_defaults = {"figsize": (12, 6)}
      fig_args = {
          **fig_args_defaults,
          **get_empty_dict_if_none(fig_args).copy(),
      }
  
      chart_args = get_empty_dict_if_none(chart_args).copy()
  
      store_explainability_data = (
          explain_top_n_anomalies is not None
      ) and explain_top_n_anomalies > 0
      _state: AnalysisState = analyze(  # type: ignore[assignment]  # always has value: return_state=True
          train_data=train_data,
          test_data=test_data,
          val_data=val_data,
          label=label,
          state=state,
          sample=sample,
          return_state=True,
          anlz_facets=[
              ProblemTypeControl(),
              ApplyFeatureGenerator(
                  category_to_numbers=True,
                  children=[
                      AnomalyDetectorAnalysis(
                          store_explainability_data=store_explainability_data,
                          **anomaly_detector_kwargs,
                      ),
                  ],
              ),
          ],
      )
  
      analyze(
          state=_state,
          viz_facets=[
              MarkdownSectionComponent("### Anomaly Detection Report"),
              MarkdownSectionComponent(
                  "When interpreting anomaly scores, consider:\n"
                  "* **Threshold**: Determine a suitable threshold to separate normal from anomalous data points, "
                  "    based on domain knowledge or statistical methods.\n"
                  "* **Context**: Examine the context of anomalies, including time, location, and surrounding data points, to identify possible causes.\n"
                  "* **False positives/negatives**: Be aware of the trade-offs between false positives (normal points classified as anomalies) "
                  "    and false negatives (anomalies missed).\n"
                  "* **Feature relevance**: Ensure the features used for anomaly detection are relevant and contribute to the model's performance.\n"
                  "* **Model performance**: Regularly evaluate and update the model to maintain its accuracy and effectiveness.\n\n"
                  "It's important to understand the context and domain knowledge before deciding on an appropriate approach to deal with anomalies."
                  "The choice of method depends on the data's nature, the cause of anomalies, and the problem being addressed."
                  "The common ways to deal with anomalies:\n\n"
                  "* **Removal**: If an anomaly is a result of an error, noise, or irrelevance to the analysis, it can be removed from the dataset "
                  "    to prevent it from affecting the model's performance.\n"
                  "* **Imputation**: Replace anomalous values with appropriate substitutes, such as the mean, median, or mode of the feature,"
                  "    or by using more advanced techniques like regression or k-nearest neighbors.\n"
                  "* **Transformation**: Apply transformations like log, square root, or z-score to normalize the data and reduce the impact of extreme values.\n"
                  "    Absolute dates might be transformed into relative features like age of the item.\n"
                  "* **Capping**: Set upper and lower bounds for a feature, and replace values outside these limits with the bounds themselves."
                  "    This method is also known as winsorizing.\n"
                  "* **Separate modeling**: Treat anomalies as a distinct group and build a separate model for them, or use specialized algorithms designed"
                  "    for handling outliers, such as robust regression or one-class SVM.\n"
                  "* **Incorporate as a feature**: Create a new binary feature indicating the presence of an anomaly, "
                  "    which can be useful if anomalies have predictive value.\n\n"
                  "<sub><sup>Use `show_help_text=False` to hide this information when calling this function.</sup></sub>",
                  condition_fn=lambda _: show_help_text,
              ),
              AnomalyScoresVisualization(
                  threshold_stds=threshold_stds,
                  headers=True,
                  fig_args=fig_args,
                  **chart_args,
              ),
          ],
      )
  
      # Store anomalies with the scores into the state
      _state.anomaly_detection.anomalies = {}
      anomaly_score_threshold = (
          _state.anomaly_detection.scores.train_data.std()
          * threshold_stds
      )
      _state.anomaly_detection.anomaly_score_threshold = (
          anomaly_score_threshold
      )
      for ds, df in AbstractAnalysis.available_datasets(
          AnalysisState(
              {
                  "train_data": train_data,
                  "test_data": test_data,
                  "val_data": val_data,
              }
          )
      ):
          anomaly_scores = _state.anomaly_detection.scores[ds]
          anomaly_idx = (
              anomaly_scores[anomaly_scores >= anomaly_score_threshold]
              .sort_values(ascending=False)
              .index
          )
          _state.anomaly_detection.anomalies[ds] = df.loc[
              anomaly_idx
          ].join(anomaly_scores)
  
          if (
              (show_top_n_anomalies is not None)
              and (show_top_n_anomalies > 0)
              and (len(anomaly_idx) > 0)
          ):
              analyze(
                  state=_state,
                  viz_facets=[
                      MarkdownSectionComponent(
                          markdown=f"**Top-{show_top_n_anomalies} `{ds}` anomalies (total: {len(anomaly_idx)})**"
                      ),
                      PropertyRendererComponent(
                          f"anomaly_detection.anomalies.{ds}",
                          transform_fn=(
                              lambda d: d.head(show_top_n_anomalies)
                          ),
                      ),
                  ],
              )
  
          if store_explainability_data:
              analyze(
                  state=_state,
                  viz_facets=[
                      MarkdownSectionComponent(
                          markdown="⚠️ Please note that the feature values shown on the charts below are transformed "
                          "into an internal representation; they may be encoded or modified based on internal preprocessing. "
                          "Refer to the original datasets for the actual feature values."
                      ),
                      MarkdownSectionComponent(
                          markdown="⚠️ The detector has seen this dataset; the may result in overly optimistic estimates. "
                          "Although the anomaly score in the explanation might not match, the magnitude of the feature scores "
                          "can still be utilized to evaluate the impact of the feature on the anomaly score.",
                          condition_fn=(
                              lambda _: ds == "train_data"
                          ),  # noqa: B023
                      ),
                  ],
              )
  
              explain_rows(
                  **_state.anomaly_detection.explain_rows_fns[ds](
                      anomaly_idx[:explain_top_n_anomalies]
                  ),
                  plot="waterfall",
              )
  
      return _state if return_state else None
  
imports: import logging
  from typing import Any, Dict, List, Optional, Tuple, Union
  import pandas
  from autogluon.common.utils.log_utils import verbosity2loglevel
  from autogluon.features import CategoryFeatureGenerator
  from autogluon.tabular import TabularPredictor
  from ..None import AnalysisState
  from ..analysis import AnomalyDetectorAnalysis, ApplyFeatureGenerator, AutoGluonModelEvaluator, AutoGluonModelQuickFit, Correlation, DistributionFit, FeatureInteraction, MissingValuesAnalysis, ProblemTypeControl, ShapAnalysis, TrainValidationSplit, XShiftDetector
  from ..analysis.base import AbstractAnalysis, BaseAnalysis, SaveArgsToState
  from ..analysis.dataset import DatasetSummary, LabelInsightsAnalysis, RawTypesAnalysis, Sampler, SpecialTypesAnalysis, VariableTypeAnalysis
  from ..analysis.interaction import FeatureDistanceAnalysis
  from ..state import is_key_present_in_state
  from ..utils.common import expand_nested_args_into_nested_maps, get_empty_dict_if_none
  from ..utils.defaults import QuickFitDefaults
  from ..visualization import AnomalyScoresVisualization, ConfusionMatrix, CorrelationVisualization, DatasetStatistics, DatasetTypeMismatch, ExplainForcePlot, ExplainWaterfallPlot, FeatureImportance, FeatureInteractionVisualization, LabelInsightsVisualization, MarkdownSectionComponent, MissingValues, ModelLeaderboard, PropertyRendererComponent, RegressionEvaluation, XShiftSummary
  from ..visualization.base import AbstractVisualization
  from ..visualization.interaction import FeatureDistanceAnalysisVisualization, PDPInteractions
  from ..visualization.layouts import SimpleVerticalLinearLayout
label_desc: Use image node_id 18 for calling a global function with example usage: detect_anomalies(train_data, label, test_data, val_data, explain_top_n_anomalies, show_top_n_anomalies, threshold_stds, show_help_text, state, sample, return_state, fig_args, chart_args) and returns: unknown