climpred

repository·main·Indexed 42 days ago

https://github.com/pangeo-data/climpred

A library for climate prediction ensemble analysis and verification. It provides core abstractions via HindcastEnsemble and PerfectModelEnsemble for managing datasets, pre-processing (bias removal, smoothing, seasonality removal), and visualization. The package includes a comprehensive metrics module for error (MSE, RMSE, MAE), correlation (Pearson, Spearman), probabilistic (CRPS, Brier score), and bias evaluation, as well as bootstrapping tools for skill estimation.

Tokens
34.5K
Snippets
115
Records
173
Agent score
51%

What's inside climpred

  1. Understand the scope and purpose of climpred

    main

    climpred is a package designed for analyzing output from initialized dynamical forecast models, covering scales from short-term weather forecasts to decadal climate forecasts.

    Core Capabilities:

    • Forecast Assessment: Provides tools to assess forecasts against validation products like observations, reanalysis products, control simulations, or baseline forecasts.
    • Verification Metrics: Includes deterministic and probabilistic verification metrics (e.g., mean absolute error, rank histograms) and advanced contingency table-derived metrics.
    • Data Handling: Uses xarray to manage core prediction ensemble dimensions (ensemble member, initialization date, and lead time) and dask for out-of-memory computations on large datasets.

    User Responsibility: Users are expected to perform their own domain-specific post-processing of model output before using climpred for analysis.

  2. Explore climpred examples by prediction timescale

    main

    The climpred project provides various example notebooks categorized by the prediction timescale and application. You can find examples for the following categories:

    • Numerical Weather Prediction (NWP): Forecasts using GEFS 6h or Herbie.
    • Subseasonal: Daily and weekly examples, including S2S (Subseasonal-to-Seasonal) workflows with IRIDL or ECMWF.
    • Monthly and Seasonal: ENSO-related subseasonal and seasonal examples.
    • Decadal: Predictability demos, tropical Pacific SSTs, potential predictability diagnosis, and significance testing.
    • Misc: GPU usage and instructions for setting up your own data.
  3. How to use metrics in climpred compute functions

    main

    High-level functions in climpred such as HindcastEnsemble.verify, HindcastEnsemble.bootstrap, PerfectModelEnsemble.verify, and PerfectModelEnsemble.bootstrap accept a metric argument. This argument determines which metric is used to compute predictability.

    Internally, metric functions require forecast and observations as inputs. You must also specify the dim argument to indicate the dimensions over which the metric is applied and subsequently reduced.

  4. Configure requirements for Verification products

    main

    Verification products used with climpred must meet the following criteria:

    • Minimum Dimension: Must contain a time dimension.
    • Time Coverage: For optimal use, the time dimension should cover the full length of the init dimension in the prediction ensemble.
    • Calendar Consistency: The time dimension must use the same calendar type as the accompanying prediction ensemble.
    • Type: The time dimension must be a pandas.DatetimeIndex or xarray.CFTimeIndex.
      • Note: If the time dimension is an int, it is assumed to be annual data starting Jan 1st (this triggers a UserWarning).
    • Additional Dimensions: Can include spatial or vertical dimensions such as lat, lon, or depth.
  5. Use Probabilistic Metrics in climpred

    main

    Probabilistic metrics in climpred account for the spread of ensemble simulations and assign probability values between 0 and 1 to forecasts. To use these metrics, pass the corresponding keyword to the metric= argument in compute functions.

    Available probabilistic metrics and their keywords:

    • Continuous Ranked Probability Score (CRPS): crps
    • Continuous Ranked Probability Skill Score (CRPSS): crpss
    • Continuous Ranked Probability Skill Score Ensemble Spread: crpss_es
    • Brier Score: brier_score
    • Threshold Brier Score: threshold_brier_score
    • Ranked Probability Score: rps
    • Reliability: reliability
    • Discrimination: discrimination
    • Rank Histogram: rank_histogram
    • Logarithmic Ensemble Spread Score: less
    # Example of how keywords are used (conceptually)
    # print(f"Keywords: {metric_aliases['crps']}")
    # Use 'crps' in your compute function call
  6. Choose an alignment strategy for date pairing

    main

    A core feature of climpred is managing the alignment of initialization dates with target verification dates across multiple lead times. Users can choose from three primary strategies to handle disparities in calendars or observational gaps:

    1. Maximize degrees of freedom: Select all initialization dates that verify with available observations at each lead. In this mode, initializations and verification dates are not held constant across different leads.
    2. Identical initializations: Use the same set of initializations that can verify over the given observational window at all leads. Here, the verification dates change at each lead.
    3. Identical verification window: Use the same verification window at each lead, while allowing the set of initializations used at each lead to change.
  7. Understand the core prediction ensemble abstractions

    main

    climpred uses an object-oriented approach to verify different types of prediction systems. The primary abstraction is the PredictionEnsemble parent class, which is implemented through two specialized subclasses:

    1. HindcastEnsemble: Used for traditional hindcasts. It is instantiated with an initialized hindcast ensemble dataset and requires an observational dataset for verification.
    2. PerfectModelEnsemble: Used for the "perfect-model" framework (investigating theoretical predictability limits). It is instantiated with an initialized perfect-model ensemble dataset and accepts a control dataset for evaluation.

    Both types can optionally track an uninitialized dataset, which represents a historical simulation evolving via internal climate variability or used to isolate external forcing.

    # Example of the hierarchy (conceptual)
    # PredictionEnsemble
    # ├── HindcastEnsemble (requires observations)
    # └── PerfectModelEnsemble (requires control)
  8. Understand Simulation Design types in climpred

    main

    In climpred, simulation designs are categorized into two main ensemble types, which dictate how members are initialized and used for verification:

    1. Hindcast Ensemble (HindcastEnsemble): Ensemble members are initialized from a simulation (typically a reconstruction from reanalysis) or an analysis at specific initialization dates and integrated for a set number of lead years. Use HindcastEnsemble.add_observations to provide reconstruction/assimilation data.
    2. Perfect Model Experiment (PerfectModelEnsemble): Ensemble members are initialized from a control simulation (added via PerfectModelEnsemble.add_control) at randomly chosen initialization dates and integrated for lead years. This setup is used to estimate (Potential) Predictability by comparing the ensemble against the control simulation.

    Additionally, you can work with Uninitialized Ensembles (HindcastEnsemble.add_uninitialized), which are generated by perturbing initial conditions only once in a historical run. These serve as a baseline to distinguish between internal climate variability and the forced response.

  9. Configure metric normalization factors

    main

    The climpred normalization logic adjusts metrics (like nrmse) based on the comparison style to ensure comparable values when predictability saturates. The normalization factor depends on the comparison keyword:

    Comparison StyleNormalization Factor
    m2c, m2m, m2o2
    m2e, e2c, e2o1
  10. Configure dimension requirements for PredictionEnsemble

    main

    To use the PredictionEnsemble class, your xarray.Dataset must follow a specific naming convention for its dimensions. At a minimum, it requires the init and lead dimensions. If your dataset uses CF convention standard_name attributes that match these concepts, climpred will automatically rename them to the required internal names.

    Required Dimensions

    • init: Represents the initialization time steps (the start date of the experiment).
      • Type: pandas.DatetimeIndex or xarray.CFTimeIndex.
      • Note: If provided as an int, it is assumed to be annual data starting Jan 1st (this triggers a UserWarning).
      • CF Convention: forecast_reference_time.
    • lead: Represents the lead time of the forecasts from initialization.
      • Type: int, float, or pandas.Timedelta (up to weeks).
      • Attribute Requirement: You must specify the units in the lead.attrs["units"] attribute.
      • Valid Units: "years", "seasons", "months", "weeks", "pentads", "days", "hours", "minutes", or "seconds".
      • CF Convention: forecast_period.
      • Note: If lead is a pandas.Timedelta up to weeks, it is converted to an int and the units are set automatically. For larger timedeltas (months, seasons, years), conversion is not possible.
    • member (Optional/Conditional): Holds ensemble members. Required for probabilistic metrics.
      • Type: int or str.
      • CF Convention: realization.

    Additional dimensions like lat, lon, or depth will be broadcasted automatically.

  11. Understand the core prediction ensemble abstractions

    main

    The climpred library is built around two primary prediction ensemble classes that inherit from a common base class, PredictionEnsemble. While PredictionEnsemble provides shared functionality and properties, it cannot be instantiated directly. Users should use either HindcastEnsemble or PerfectModelEnsemble depending on their data source:

    • HindcastEnsemble: Used when the ensemble is initialized from observations (e.g., assimilations, reanalysis). These are typically verified against real-world observation-like products.
    • PerfectModelEnsemble: Used when the ensemble is initialized from a control simulation at randomly chosen dates. Since these lack real-world observations, they are compared against each other or the original control run.
  12. Evaluate Forecast Skill and Accuracy

    main

    To assess how well a forecasting system performs, climpred uses several metrics and concepts:

    • Skill (HindcastEnsemble.verify): The current ability of the ensemble to predict the real world. It is calculated by comparing the prediction ensemble against observations, reanalysis, or analysis.
    • Accuracy: The average correspondence between forecast pairs and observations. Common metrics include:
      • Mean Absolute Error (climpred.metrics._mae)
      • Mean Square Error (climpred.metrics._mse)
    • Association: The strength of the relationship between forecasts and observations, typically measured via:
      • Anomaly Correlation Coefficient (ACC) using Pearson product-moment correlation (climpred.metrics._pearson_r)
      • Spearman's Rank correlation (climpred.metrics._spearman_r)
    • Skill Score: A normalized measure of improvement over a reference forecast (like persistence). It is defined as: $$S = \frac{A_{f} - A_{r}}{A_{p} - A_{r}}$$ where $A_{f}$ is forecast accuracy, $A_{p}$ is perfect forecast accuracy, and $A_{r}$ is reference forecast accuracy.