# Estimating Equilibrium Climate Sensitivity (ECS) in CMIP6 models¶

Authors: Henry Drake and Ryan Abernathey

Definition: Equilibrium Climate Sensitivity is defined as change in global-mean near-surface air temperature (GMST) change due to an instantaneous doubling of CO$_{2}$ concentrations and once the coupled ocean-atmosphere-sea ice system has acheived a statistical equilibrium (i.e. at the top-of-atmosphere, incoming solar shortwave radiation is balanced by reflected solar shortwave and outgoing thermal longwave radiation).

This notebook uses the "Gregory method" to approximate the ECS of CMIP6 models based on the first 150 years after an abrupt quadrupling of CO$_{2}$ concentrations. The "Gregory Method" extrapolates the quasi-linear relationship between GMST and radiative imbalance at the top-of-atmosphere to estimate how much warming would occur if the system were in radiative balance at the top-of-atmosphere, which is by definition the equilibrium response. In particular, we extrapolate the linear relationship that occurs between 100 and 150 years after the abrupt quadrupling. Since the radiative forcing due to CO$_{2}$ is a logarithmic function of the CO$_{2}$ concentration, the GMST change from a first doubling is roughly the same as for a second doubling (to first order, we can assume feedbacks as constant), which means that the GMST change due to a quadrupling of CO$_{2}$ is roughly $\Delta T_{4 \times \text{CO}_{2}} = 2 \times \text{ECS}$. See also Mauritsen et al. 2019 for a detailed application of the Gregory Method (with modifications) for the case of one specific CMIP6 model, the MPI-M Earth System Model.

For another take on applying the Gregory method to estimate ECS, see Angeline Pendergrass' code.

### Python packages¶

In [ ]:
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
import xarray as xr
import xesmf as xe
import cartopy
from tqdm.autonotebook import tqdm  # Fancy progress bars for our loops!
import intake
import fsspec

%matplotlib inline
plt.rcParams['figure.figsize'] = 12, 6
%config InlineBackend.figure_format = 'retina'


### Compute Cluster¶

Here we use a dask cluster to parallelize our analysis. The cluster scales up and down adaptively.

In [ ]:
from dask_gateway import Gateway

gateway = Gateway()
cluster = gateway.new_cluster()
client = Client(cluster)
cluster


## Data catalogs¶

This notebook uses intake-esm to ingest and organize climate model output from the fresh-off-the-supercomputers Phase 6 of the Coupled Model Intercomparison Project (CMIP6).

The file https://storage.googleapis.com/cmip6/cmip6-zarr-consolidated-stores.csv in google cloud storage contains thousands of lines of metadata, each describing an individual climate model experiment's simulated data.

For example, the first line in the csv file contains the precipitation rate (variable_id = 'pr'), as a function of latitude, longitude, and time, in an individual climate model experiment with the BCC-ESM1 model (source_id = 'BCC-ESM1') developed by the Beijing Climate Center (institution_id = 'BCC'). The model is forced by the forcing experiment SSP370 (experiment_id = 'ssp370'), which stands for the Shared Socio-Economic Pathway 3 that results in a change in radiative forcing of $\Delta F = 7.0$ W/m$^{2}$ from pre-industrial to 2100. This simulation was run as part of the AerChemMIP activity, which is a spin-off of the CMIP activity that focuses specifically on how aerosol chemistry affects climate.

In [ ]:
df = pd.read_csv('https://storage.googleapis.com/cmip6/cmip6-zarr-consolidated-stores.csv')


The file pangeo-cmip6.json describes the structure of the CMIP6 metadata and is formatted so as to be read in by the intake.open_esm_datastore method, which categorizes all of the data pointers into a tiered collection. For example, this collection contains the simulated data from 28691 individual experiments, representing 48 different models from 23 different scientific institutions. There are 190 different climate variables (e.g. sea surface temperature, sea ice concentration, atmospheric winds, dissolved organic carbon in the ocean, etc.) available for 29 different forcing experiments.

### Use Intake ESM¶

Intake-esm is a new package designed to make working with these data archives a bit simpler.

In [ ]:
col = intake.open_esm_datastore("https://storage.googleapis.com/cmip6/pangeo-cmip6.json")
col


Here, we show the various forcing experiments that climate modellers ran in these simulations.

In [ ]:
df['experiment_id'].unique()


## Analysis of Climate Model Output Data¶

intake-esm enables loading data directly into an xarray.DataArray, a metadata-aware extension of numpy arrays. xarray objects leverage dask to only read data into memory as needed for any specific operation (i.e. lazy evaluation). Think of xarray Datasets as ways of conveniently organizing large arrays of floating point numbers (e.g. climate model data) on an n-dimensional discrete grid, with important metadata such as units, variable, names, etc.

Note that data on the cloud are in zarr format, an extension of the metadata-aware format netcdf commonly used in geosciences.

intake-esm has rules for aggegating datasets; these rules are defined in the collection-specification file.

#### Choice of simulated forcing experiments¶

Here, we choose the piControl experiment (in which CO2 concentrations are held fixed at a pre-industrial level of ~300 ppm) and abrupt-4xCO2 experiment (in which CO2 concentrations are instantaneously quadrupled - or doubled twice - from a pre-industrial controrl state). Since the radiative forcing of CO2 is roughly a logarithmic function of CO2 concentrations, the ECS is roughly independent of the initial CO2 concentration. Thus, if one doubling of CO2 results in $ECS$ of warming, then two doublings (or, a quadrupling) results in $2 \times ECS$ of warming.

Ideally, we would choose the abrupt-2xCO2 forcing experiment, but more 4xCO2 data are currently avaiable in Google Cloud Storage, making for a better example.

### Prepare Data¶

In [ ]:
query = dict(
experiment_id=['abrupt-4xCO2','piControl'], # pick the abrupt-4xCO2 and piControl forcing experiments
table_id='Amon',                            # choose to look at atmospheric variables (A) saved at monthly resolution (mon)
variable_id=['tas', 'rsut','rsdt','rlut'],  # choose to look at near-surface air temperature (tas) as our variable
member_id = 'r1i1p1f1',                     # arbitrarily pick one realization for each model (i.e. just one set of initial conditions)
)

col_subset = col.search(require_all_on=["source_id"], **query)
col_subset.df.groupby("source_id")[
["experiment_id", "variable_id", "table_id"]
].nunique()


The following functions help us load and homogenize the data. We use some dask.delayed programming to open the datasets in parallel.

In [ ]:
def drop_all_bounds(ds):
"""Drop coordinates like 'time_bounds' from datasets,
which can lead to issues when merging."""
drop_vars = [vname for vname in ds.coords
if (('_bounds') in vname ) or ('_bnds') in vname]
return ds.drop(drop_vars)

def open_dsets(df):
"""Open datasets from cloud storage and return xarray dataset."""
dsets = [xr.open_zarr(fsspec.get_mapper(ds_url), consolidated=True)
.pipe(drop_all_bounds)
for ds_url in df.zstore]
try:
ds = xr.merge(dsets, join='exact')
return ds
except ValueError:
return None

def open_delayed(df):
"""A dask.delayed wrapper around open_dsets.
Allows us to open many datasets in parallel."""


Create a nested dictionary of models and experiments. It will be structured like this:

{'CESM2':
{
'piControl': <xarray.Dataset>,
'abrupt-4xCO2': <xarray.Dataset>
},
...
}
In [ ]:
from collections import defaultdict

dsets = defaultdict(dict)
for group, df in col_subset.df.groupby(by=['source_id', 'experiment_id']):
dsets[group[0]][group[1]] = open_delayed(df)


Open one of the datasets directly, just to show what it looks like:

In [ ]:
%time open_dsets(df)


Now use dask to do this in parallel on all of the datasets:

In [ ]:
dsets_ = dask.compute(dict(dsets))[0]


### Reduce Data via Global Mean¶

We don't want to load all of the raw model data into memory right away. Instead, we want to reduce the data by taking the global mean. We need to remember to weight this global mean by a factor proportional to cos(lat).

In [ ]:
def get_lat_name(ds):
"""Figure out what is the latitude coordinate for each dataset."""
for lat_name in ['lat', 'latitude']:
if lat_name in ds.coords:
return lat_name
raise RuntimeError("Couldn't find a latitude coordinate")

def global_mean(ds):
"""Return global mean of a whole dataset."""
lat = ds[get_lat_name(ds)]
weight /= weight.mean()
other_dims = set(ds.dims) - {'time'}
return (ds * weight).mean(other_dims)


We now apply this function, plus resampling to annual mean data, to all of the datasets. We also concatenate the experiments together into a single Dataset for each model. This is the most complex cell in the notebook. A lot is happening here.

In [ ]:
expts = ['piControl', 'abrupt-4xCO2']
expt_da = xr.DataArray(expts, dims='experiment_id',
coords={'experiment_id': expts})

dsets_aligned = {}

for k, v in tqdm(dsets_.items()):
expt_dsets = v.values()
if any([d is None for d in expt_dsets]):
print(f"Missing experiment for {k}")
continue

for ds in expt_dsets:
ds.coords['year'] = ds.time.dt.year - ds.time.dt.year[0]

# workaround for
# https://github.com/pydata/xarray/issues/2237#issuecomment-620961663
dsets_ann_mean = [v[expt].pipe(global_mean)
.swap_dims({'time': 'year'})
.drop('time')
.coarsen(year=12).mean()
for expt in expts]

# align everything with the 4xCO2 experiment
dsets_aligned[k] = xr.concat(dsets_ann_mean, join='right',
dim=expt_da)


### Do the Computation¶

Up to this point, no computations have actually happened. Everything has been "lazy". Now we trigger the computation to actual occur and load the global / annual mean data into memory.

In [ ]:
dsets_aligned_ = dask.compute(dsets_aligned)[0]


Now we concatenate across models to produce one big dataset with all the required variables.

In [ ]:
source_ids = list(dsets_aligned_.keys())
source_da = xr.DataArray(source_ids, dims='source_id',
coords={'source_id': source_ids})

big_ds = xr.concat([ds.reset_coords(drop=True)
for ds in dsets_aligned_.values()],
dim=source_da)
big_ds


### Calculated Derived Variables¶

We need to calculate the net radiative imbalance, plus the anomaly of the abrupt 4xCO2 run compared to the piControl run.

In [ ]:
big_ds['imbalance'] = big_ds['rsdt'] - big_ds['rsut'] - big_ds['rlut']

ds_mean = big_ds[['tas', 'imbalance']].sel(experiment_id='piControl').mean(dim='year')
ds_anom = big_ds[['tas', 'imbalance']] - ds_mean

ds_anom.tas.attrs['long_name'] = 'Global Mean Surface Temp Anom'
ds_anom.tas.attrs['units'] = 'K'
ds_anom.imbalance.attrs['long_name'] = 'Global Mean Radiative Imbalance'
ds_anom.imbalance.attrs['units'] = 'W m$^{-2}$'

ds_anom


### Plot Timeseries¶

Here we plot the global mean surface temperature for each model:

In [ ]:
ds_anom.tas.plot.line(col='source_id', x='year', col_wrap=5)


We can see that the models cover different time intervals. Let's limit the rest of our analysis to the first 150 years.

In [ ]:
# limit to the gregory 150-year period
first_150_years = slice(0, 149)
ds_anom.tas.sel(year=first_150_years).plot.line(col='source_id', x='year', col_wrap=5)


In [ ]:
ds_anom.imbalance.sel(year=first_150_years).plot.line(col='source_id', x='year', col_wrap=5)


### Calculate ECS¶

In [ ]:
ds_abrupt = ds_anom.sel(year=first_150_years, experiment_id='abrupt-4xCO2').reset_coords(drop=True)

def calc_ecs(ds):
# Some sources don't have all 150 years, drop those missing values.
a, b = np.polyfit(ds.tas.dropna("year"),
ds.imbalance.dropna("year"), 1)
ecs = -0.5 * (b/a)
return xr.DataArray(ecs)

ds_abrupt['ecs'] = ds_abrupt.groupby('source_id').apply(calc_ecs)
ds_abrupt


Reproduce a plot similar to Mark Zelinka's:

In [ ]:
fg = ds_abrupt.plot.scatter(x='tas', y='imbalance', col='source_id', col_wrap=5)

def calc_and_plot_ecs(x, y, **kwargs):
x = x[~np.isnan(x)]
y = y[~np.isnan(y)]
a, b = np.polyfit(x, y, 1)
ecs = -0.5 * b/a
plt.autoscale(False)
plt.plot([0, 10], np.polyval([a, b], [0, 10]), 'k')
plt.text(4, 6, f'ECS = {ecs:3.2f}', fontdict={'weight': 'bold', 'size': 12})
plt.grid()

fg.map(calc_and_plot_ecs, 'tas', 'imbalance')

In [ ]:
ds_abrupt.ecs.plot.hist();

In [ ]:
ds_abrupt.ecs.to_dataframe().sort_values('ecs').plot(kind='bar')