Analyze a Parameter Ensemble#

In the previous notebook we ran 6 ensemble members, each setting one of 3 FATES parameters to its minimum or maximum value. Together with the default run (BONA.FATESsp), that gives the 2N + 1 = 7 runs of a one-at-a-time (OAT) experiment.

In this notebook we will:

  1. Load the output of every member, and of the default run

  2. Compare each member to the default over time

  3. Summarize how sensitive each output is to each parameter

OAT tells us the direction and size of each parameter’s effect around the default. It can’t tell us how parameters interact, or how the model responds between the minimum and maximum (see the overview).

We will look at five outputs:

Variable

Description

Units

FATES_GPP

Gross primary production

kg C m-2 s-1 (we’ll convert to g C m-2 d-1)

EFLX_LH_TOT

Total latent heat flux

W m-2

FCTR

Canopy transpiration

W m-2

FSH

Sensible heat flux

W m-2

FSA

Absorbed solar radiation

W m-2

Note: Unlike previous notebooks in this section, we will no longer be using the meristem environment as our kernel. Check (or change) your kernel (see upper right corner, above). It should be either NPL 2025a or NPL 2025b.
from pathlib import Path
import functools
import os
import json

import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import seaborn as sns
import pandas as pd
import numpy as np
import xarray as xr

user = os.getenv('USER')
print(f"username is {user}, update to your username if this is not correct")
VARIABLES = ["FATES_GPP", "FCTR", "FSH", "FSA", "EFLX_LH_TOT", "FSR"]
YEARS = slice("2014-01-01", "2015-12-31")

Step 1: Load the manifest#

The manifest we wrote at the end of the last notebook has one row per member. For each member it records which parameter was changed and in which direction (from the paramgen key), whether the run finished, and where its output was archived.

manifest = pd.read_csv(f"/glade/u/home/{user}/oat_manifest.csv")
manifest[["member", "parameter", "direction", "run_status", "run_archive_dir"]]
not_done = manifest[manifest["run_status"] != "done"]
if not_done.empty:
    print("All members are done.")
else:
    print("These members haven't finished; see Step 7 of the previous notebook:")
    print(not_done[["member", "run_status"]])

If any members are not done, either wait for them to finish, or if they failed, fix any problems and retry (see previous notebook).


Step 2: Load the model output#

The functions below open every monthly h0a file for one run, keep our variables and years, and convert GPP to more readable units.

def preprocess(data_set, variables) -> xr.Dataset:
    """Preprocesses an xarray Dataset by subsetting to specific variables"""
    return data_set[variables]


def load_run(archive_dir, variables=VARIABLES, years=YEARS):
    """Load one run's monthly averaged (h0a) history output as an xarray Dataset."""
    files = sorted(Path(archive_dir, "lnd", "hist").glob("*.clm2.h0a*.nc"))
    ds = xr.open_mfdataset(
        files,
        preprocess=functools.partial(preprocess, variables=variables),
        combine="by_coords",
        decode_timedelta=True,
        )

    ds = ds.sel(time=years)

    # kg C m-2 s-1 -> g C m-2 d-1
    ds["FATES_GPP"] = ds["FATES_GPP"] * 1000 * 86400
    ds["FATES_GPP"].attrs["units"] = "g C m-2 d-1"
    ds["FATES_GPP"].attrs["long_name"] = "gross primary production"
    
    return ds.load().isel(lndgrid=0)

Load every member, and stack them along a new member dimension. We also attach each member’s parameter and direction, so we can select members by them later.

ensemble = xr.concat(
    [load_run(d) for d in manifest["run_archive_dir"]],
    dim=pd.Index(manifest["member"], name="member"),
)
ensemble = ensemble.assign_coords(
    parameter=("member", manifest["parameter"].values),
    direction=("member", manifest["direction"].values),
)
ensemble

Now load the default run:

default_archive = f"/glade/derecho/scratch/{user}/archive/BONA.FATESsp"
default = load_run(default_archive)
default
Important Note: Remember that these cases (the base case and every OAT member) used CLM_FORCE_COLDSTART=on. So in our first two years (2014-2015), soil moisture and soil temperature are still spinning up. The comparison is still fair, because every member and the default go through the same transient states. Each difference is still caused by its parameter. However, the absolute values for 2014–2015 aren't equilibrium values. Thus, effects that work through soil water, like stomatal conductance under drying soils, may be muted or exaggerated compared with a spun-up run.
How would you fix this?
Click here for the solution
Spin the model up first (~60 years for SP mode) and start the OAT members from that restart (finidat= ...; CLM_FORCE_COLDSTART=off).

Step 3: Compare each member to the default#

Each member changes only one parameter, so any difference from the default run is caused by that parameter. Plot, for each parameter, the default run along with its minimum and maximum members.

Grab the correct data arrays#

This helper function gives a member name given its parameter and direction:

def get_member(manifest, parameter, direction):
    """Name of the member that set `parameter` to its `direction` ('minimum' or 'maximum')."""
    rows = manifest[(manifest["parameter"] == parameter) & (manifest["direction"] == direction)]
    return rows["member"].item()

First we will pick a parameter and variable and pull out the minimum, maximum, and default data arrays for that variable:

var = "FATES_GPP"
param = "fates_leaf_vcmax25top"

lo = ensemble[var].sel(member=get_member(manifest, param, "minimum"))
hi = ensemble[var].sel(member=get_member(manifest, param, "maximum"))
base = default[var]

lo

Plot the time series#

Next we will plot them next to each other:

fig, ax = plt.subplots(figsize=(9, 4), constrained_layout=True)

# the two min/max members, plus the default
lo.plot(ax=ax, color="tab:blue", lw=1.5, ls="--", label="minimum")
hi.plot(ax=ax, color="tab:red", lw=1.5, ls="--", label="maximum")
base.plot(ax=ax, color="k", lw=1.5, label="default")

# shaded envelope between min and max
ax.fill_between(base["time"].values, lo, hi, color="tab:gray", alpha=0.2,
                linewidth=0, label="min–max range")

units = lo.attrs.get("units", "")
long_name = lo.attrs.get("long_name", var)
ax.set_title(param, loc="left", fontweight="bold")
ax.set_xlabel("")
ax.set_ylabel(f"{long_name} ({units})" if units else var)
ax.grid(alpha=0.3)
ax.spines[["top", "right"]].set_visible(False)
ax.legend(frameon=False, ncol=1, loc="upper right", bbox_to_anchor=(1.25, 1.0));

Let’s turn that code into helper functions so we can explore more parameters and variables:

def plot_time_series(ensemble, default, variable, parameter, manifest):
    """Plot the minimum, maximum, and default values for a given OAT parameter"""

    # get the correct data arrays
    lo = ensemble[variable].sel(member=get_member(manifest, parameter, "minimum"))
    hi = ensemble[variable].sel(member=get_member(manifest, parameter, "maximum"))
    base = default[variable]

    fig, ax = plt.subplots(figsize=(9, 4), constrained_layout=True)
    
    # shaded envelope between min and max
    ax.fill_between(base["time"].values, lo, hi, color="tab:gray", alpha=0.2, linewidth=0, label="min–max range")
    
    # the two min/max members, plus the default
    lo.plot(ax=ax, color="tab:blue", lw=1.5, ls="--", label="minimum")
    hi.plot(ax=ax, color="tab:red", lw=1.5, ls="--", label="maximum")
    base.plot(ax=ax, color="k", lw=1.5, label="default")
    
    units = lo.attrs.get("units", "")
    long_name = lo.attrs.get("long_name", variable)
    ax.set_title(parameter, loc="left", fontweight="bold")
    ax.set_xlabel("")
    ax.set_ylabel(f"{long_name} ({units})" if units else variable)
    ax.grid(alpha=0.3)
    ax.spines[["top", "right"]].set_visible(False)
    ax.legend(frameon=False, ncol=1, loc="upper right", bbox_to_anchor=(1.25, 1.0));

We will use this helper function to explore parameter sensitivity.

parameters = manifest.parameter.unique()
variables = list(ensemble.data_vars)

print(f"Available parameters are: {', '.join(parameters)}")
print("--------")
print(f"Available variables are: {', '.join(variables)}")

Explore#

Update the variable and parameter for the below function to explore:

plot_time_series(ensemble, default, 'FATES_GPP', 'fates_leaf_vcmax25top', manifest)
Interpretation exercise 1

Why is FSA almost insensitive to vcmax25top and stomatal_intercept, but sensitive to clumping index?

Hint: FSA is absorbed solar radiation. What kinds of things affect this? Remember that we are in SP (satellite phenology) mode.

Click here for the solution

In this configuration of FATES, only clumping index (of the 3 parameters) changes how much radiation the canopy absorbs. In FATES-SP mode, LAI is prescribed, so there is no structural feedback from GPP to absorbed light.

Interpretation exercise 2

When FCTR goes up, what happens to FSH, and why?

Hint: FCTR = canopy transpiration; FSH = sensible heat flux

Click here for the solution
This correlation is due to energy partitioning. When canopy transpiration (and thus latent heat) increases, sensible heat decreases.

Step 4: When in the year does each parameter matter?#

Let’s also take the difference of each member from the default run directly to better investigate where in the seasonal cycle each parameter matters most.

We can calculate ensemble[var] - default[var] directly because xarray broadcasts across each member automatically (the time coordinates all match up). Do this below:

var = 'FATES_GPP'
diff = ensemble[var] - default[var]
diff

Now calculate monthly climatology with .groupby("time.month").mean() on that difference:

climo = diff.groupby("time.month").mean()
climo

Now let’s do this calculation across all the variables and plot the output. A helper function for this is below:

def plot_seasonal_diff(ensemble, default, manifest, parameters, variables):
    
    colors = dict(zip(parameters, plt.cm.tab10.colors))

    fig, axes = plt.subplots(3, 2, figsize=(12, 7), sharex=True, layout="constrained")
    for ax, var in zip(axes.flat, variables):
        diff = ensemble[var] - default[var]
        climo = diff.groupby("time.month").mean()
        for param in parameters:
            ax.plot(climo.month, climo.sel(member=get_member(manifest, param, 'maximum')), color=colors[param], ls="-", label=param)
            ax.plot(climo.month, climo.sel(member=get_member(manifest, param, 'minimum')), color=colors[param], ls="--")
    
        ax.axhline(0, color="k", lw=0.8)
        ax.set_xticks(range(1, 13), list("JFMAMJJASOND"))
        ax.set_ylabel(f"Δ {var} ({default[var].attrs['units']})")
    
    handles, labels = axes.flat[0].get_legend_handles_labels()
    handles += [Line2D([], [], color="k", ls="-"), Line2D([], [], color="k", ls="--")]
    labels += ["maximum", "minimum"]
    fig.legend(handles, labels, loc="outside right center")
plot_seasonal_diff(ensemble, default, manifest, parameters, variables)
Interpretation exercise 3

In which months does each parameter change GPP and FCTR? How might only looking at an annual mean (see below) understate these effects at a boreal site?

Click here for the solution

When do the parameters matter? Almost all of the differences happen between April and October. From November to March the canopy is mostly inactive and the site is snow-covered, so changing a photosynthesis or stomatal parameter has a much lower effect. The differences grow in May, peak in June–July, and fade by October.

  • GPP and FCTR respond most to fates_leaf_vcmax25top.
  • FSA responds mostly to fates_rad_leaf_clumping_index. In summer, a less-clumped canopy (maximum value) puts more of the light onto leaves, which reflect more than the dark ground below, so the surface absorbs less. In spring, the FSA differences for all parameters come from changes in snow cover and melt timing.

Why does an annual mean understate these effects? At a boreal site like BONA, about half the year contributes much less to the difference. Averaging those near-zero months with the growing season dilutes the signal. A parameter that changes summer canopy transpiration may change mean annual transpiration by much less. Always check when a parameter matters, not just how much it matters on average.

Note: each month here is an average of only two years, so treat single-month spikes (especially in spring) with caution.

Step 5. Look at sensitivity of annual variables#

Next we will calculate annual sums or means of our variables and investigate parameter sensitivity of annual metrics.

Below is a helper function for calculating annual means and sums.

def annual_metric(data_array, how, conversion_factor=None):
    """Calculates annual mean or sum of an input DataArray, applies a 
    conversion factor if supplied
    """
    if conversion_factor is not None:
        data_array = data_array * conversion_factor

    months = data_array["time.daysinmonth"]
    annual_sum = (months * data_array).groupby("time.year").sum()
    units = data_array.attrs["units"]

    if how == 'mean':
        annual_mean = annual_sum / 365.0
        annual_mean.attrs["units"] = units
        return annual_mean
    elif how == 'sum':
        annual_sum.attrs["units"] = units.replace("d", "yr")
        return annual_sum
        
    raise ValueError(
        f"`how` must be 'mean' or 'sum', not {how}"
    )


variable_dict = {
    'FATES_GPP': 'sum',
    'FCTR': 'mean',
    'FSH': 'mean',
    'FSA': 'mean',
    'EFLX_LH_TOT': 'mean',
    'SNOW_DEPTH': 'mean',
    'FSR': 'mean',
}

Dot plots#

First let’s look at one variable and for every parameter plot the value at the minimum, maximum, and default:

variable = 'FATES_GPP'
ann_var = annual_metric(ensemble[variable], variable_dict[variable])
ann_default = annual_metric(default[variable], variable_dict[variable])

dfs = []
for parameter in parameters:
    param_values = {}
    param_values['low'] = ann_var.sel(member=get_member(manifest, parameter, "minimum")).mean(dim='year').values
    param_values['high'] = ann_var.sel(member=get_member(manifest, parameter, "maximum")).mean(dim='year').values
    dfs.append(pd.DataFrame(param_values, index=[parameter]))
var_df = pd.concat(dfs)


var_df

Now we can plot these minimum, maximum, and default values:

fig, ax = plt.subplots(figsize=(6, 3), constrained_layout=True)

# sort by difference
var_df['diff'] = np.abs(var_df['high'] - var_df['low'])
var_df = var_df.sort_values(by='diff')
y = np.arange(len(var_df))

# plot default down the middle
ax.axvline(ann_default.mean(dim='year').values, color="k", lw=1,
           label="default", linestyle='dashed')

# plot min, max, and line in between
ax.scatter(var_df["low"], y, color="tab:blue", s=50, zorder=3, label="minimum")
ax.scatter(var_df["high"], y, color="tab:red", s=50, zorder=3, label="maximum")
ax.hlines(y, var_df["low"], var_df["high"], color="gray", lw=1, zorder=2)

ax.set_yticks(y, var_df.index)
units = ann_var.units
ax.set_xlabel(f"{variable} ({units})")
ax.grid(axis="x", alpha=0.3)
ax.spines[["top", "right"]].set_visible(False)
ax.legend(frameon=False, loc="center left", bbox_to_anchor=(1.02, 0.5));
Interpretation exercise 4

Which parameter matters most for annual GPP? Is the response symmetric around the default?

Hint: Compare how far the minimum and maximum points sit from the default line. Then compare that to how far each parameter’s minimum and maximum values are from its default (see main.csv, fates_leaf_vcmax25top.csv, and the default parameter file). Look closely at the fates_leaf_stomatal_intercept minimum.

Click here for the solution

fates_leaf_vcmax25top dominates. The other two parameters change annual GPP by only a small amount.

The vcmax response is not symmetric, and the asymmetry is the opposite of what the parameter range would suggest. For the dominant PFT at BONA (needleleaf evergreen tree), the default vcmax25top is 62 μmol m-2 s-1 and the OAT range is ~22–129, so the maximum is further from the default than the minimum. Even so, the minimum changes GPP more.

fates_leaf_stomatal_intercept is asymmetric for a different reason: its minimum (10000) is the default for every PFT that grows at BONA, so the “minimum” member is identical to the default run. When an OAT range isn’t centered on the default, always check where the default sits.

Plotting a heatmap#

Next we will loop through each variable and parameter and calculate parameter sensitivity as: abs(hi_value - lo_value)/default.

dfs = []
for variable in variables:
    
    # calculate annual metric
    ann_var = annual_metric(ensemble[variable], variable_dict[variable])
    ann_default = annual_metric(default[variable], variable_dict[variable])
    
    sensitivity = {}
    for parameter in parameters:
        annual_lo = ann_var.sel(member=get_member(manifest, parameter, "minimum"))
        annual_hi = ann_var.sel(member=get_member(manifest, parameter, "maximum"))
        sensitivity[parameter] = (np.abs(annual_hi - annual_lo)/ann_default).mean(dim='year').values
    dfs.append(pd.DataFrame(sensitivity, index=[variable]))
    
sens_df = pd.concat(dfs)

sens_df

We can then plot a heatmap of these sensitivity values:

plt.figure(figsize=(8, 6))
sns.heatmap(
    sens_df.T, 
    annot=True, 
    cmap="viridis", 
    cbar=True,
    cbar_kws={'label': 'Sensitivity Index'},
    vmin=0,
    vmax=1
)
plt.xticks(rotation=15, ha="right")
plt.yticks(rotation=0)
plt.tight_layout();

Step 6: Response vs. parameter value#

So far we have plotted which member changed what. Now let’s plot model output against the actual value of each parameter. With OAT we have three points per parameter: minimum, default, and maximum.

The minimum, maximum, and default values come from the same files we used to build the ensemble in the parameter ensemble creation notebook.

meristem_dir = Path(f"/glade/u/home/{user}/code/meristem")
fates_example_dir = meristem_dir / "examples/paramgen/fates_example"
param_dir = fates_example_dir / "fates_param_dir"

main_df = pd.read_csv(param_dir / "main.csv", index_col=0)

with open(fates_example_dir / "default_fates_param.json", encoding="utf-8") as f:
    default_params = json.load(f)["parameters"]

The below helper function lets us read in the parameter values for the minimum, maximum, and default members:

def get_param_values(parameter, pft):
    """Return (minimum, default, maximum) of `parameter` for one PFT (1-based index)."""

    # default value; vcmax25top has an extra leaf-age dimension, so index the last axis
    default_value = np.array(default_params[parameter]["data"])[..., pft - 1].item()

    param_min = main_df.loc[parameter, "param_min"]
    param_max = main_df.loc[parameter, "param_max"]

    # PFT-specific ranges live in their own csv file
    if param_min == "pft":
        pft_df = pd.read_csv(param_dir / f"{parameter}.csv", index_col=0, encoding="utf-8-sig")
        param_min = pft_df.loc[pft, "param_min"]
        param_max = pft_df.loc[pft, "param_max"]

    return float(param_min), float(default_value), float(param_max)

Total GPP at BONA comes from several PFTs, and each PFT has its own default and range for some parameters (e.g., fates_leaf_vcmax25top). To see how GPP responds to a parameter’s value, we can look at each PFT’s GPP against that PFT’s own parameter value.

FATES writes PFT-level GPP to FATES_GPP_PF. Let’s load it for every member and the default run:

def load_gpp_pf(archive_dir, years=YEARS):
    """Load one run's monthly PFT-level GPP (FATES_GPP_PF) in g C m-2 d-1."""
    files = sorted(Path(archive_dir, "lnd", "hist").glob("*.clm2.h0a*.nc"))
    ds = xr.open_mfdataset(
        files,
        preprocess=functools.partial(preprocess, variables=["FATES_GPP_PF"]),
        combine="by_coords",
        decode_timedelta=True,
    )
    gpp_pf = ds["FATES_GPP_PF"].sel(time=years).load().isel(lndgrid=0)

    # kg C m-2 s-1 -> g C m-2 d-1
    gpp_pf = gpp_pf * 1000 * 86400
    gpp_pf.attrs["units"] = "g C m-2 d-1"

    # label PFTs 1, 2, ... to match the parameter files
    return gpp_pf.assign_coords(fates_levpft=np.arange(1, gpp_pf.sizes["fates_levpft"] + 1))


ensemble_gpp_pf = xr.concat(
    [load_gpp_pf(d) for d in manifest["run_archive_dir"]],
    dim=pd.Index(manifest["member"], name="member"),
)
default_gpp_pf = load_gpp_pf(default_archive)

Which PFTs actually grow at BONA? Calculate each PFT’s annual GPP in the default run:

pft_names = pd.read_csv(param_dir / "fates_leaf_vcmax25top.csv", index_col=0, encoding="utf-8-sig")["pft_name"]

ann_default_pf = annual_metric(default_gpp_pf, "sum").mean("year").to_series()
ann_default_pf.index = pft_names.loc[ann_default_pf.index] + " (" + ann_default_pf.index.astype(str) + ")"
ann_default_pf.round(1)

At BONA we see that there are 4 PFTs: needleleaf evergreen trees, arctic C3 grasses, deciduous arctic shrubs, and deciduous extratropical shrubs.

We will subset to just these PFTs:

ann_pf = annual_metric(default_gpp_pf, "sum").mean("year")
active_pfts = [int(p) for p in ann_pf.fates_levpft if ann_pf.sel(fates_levpft=p) > 0.0 * ann_pf.sum()]

Now plot each PFT’s annual GPP against its own parameter value. The dotted lines connect the minimum and maximum members directly: this is what you would assume if the response were linear.

def plot_gpp_pf_response(ensemble_gpp_pf, default_gpp_pf, manifest, parameters, pfts):
    """Plot annual PFT-level GPP vs. each PFT's own parameter value (min, default, max)."""

    ann_members = annual_metric(ensemble_gpp_pf, "sum").mean("year")
    ann_default = annual_metric(default_gpp_pf, "sum")
    units = ann_default.attrs["units"]
    ann_default = ann_default.mean("year")

    colors = dict(zip(pfts, plt.cm.tab10.colors))
    markers = {"minimum": "v", "default": "o", "maximum": "^"}

    fig, axes = plt.subplots(1, len(parameters), figsize=(4.5 * len(parameters), 4),
                             sharey=True, layout="constrained")

    for ax, parameter in zip(axes, parameters):
        lo = ann_members.sel(member=get_member(manifest, parameter, "minimum"))
        hi = ann_members.sel(member=get_member(manifest, parameter, "maximum"))

        for pft in pfts:
            x = get_param_values(parameter, pft)
            y = [float(da.sel(fates_levpft=pft)) for da in (lo, ann_default, hi)]

            # straight line from minimum to maximum
            ax.plot([x[0], x[2]], [y[0], y[2]], color=colors[pft], ls=":", lw=1.5)

            # the three OAT points, connected in order of parameter value
            order = np.argsort(x)
            ax.plot(np.array(x)[order], np.array(y)[order], color=colors[pft], lw=1)
            for xi, yi, direction in zip(x, y, markers):
                ax.scatter(xi, yi, color=colors[pft], marker=markers[direction], s=60, zorder=3)

        ax.set_title(parameter, fontsize=10, fontweight="bold")
        ax.set_xlabel("parameter value (PFT-specific)")
        ax.grid(alpha=0.3)
        ax.spines[["top", "right"]].set_visible(False)

    axes[0].set_ylabel(f"PFT GPP ({units})")

    # legend: colors for PFTs, marker shapes for members
    handles = [plt.Line2D([], [], color=colors[p], lw=2, label=f"{pft_names.loc[p]} ({p})") for p in pfts]
    handles += [plt.Line2D([], [], color="gray", marker=m, ls="", label=d) for d, m in markers.items()]
    handles += [plt.Line2D([], [], color="gray", ls=":", label="straight line (min to max)")]
    fig.legend(handles=handles, loc="outside right center", frameon=False)
plot_gpp_pf_response(ensemble_gpp_pf, default_gpp_pf, manifest, parameters, active_pfts)
Interpretation exercise 5

Suppose you only had the minimum and maximum runs for fates_leaf_vcmax25top and assumed GPP changes linearly between them. For each PFT, would you over- or underestimate GPP at the default value? What does that tell you about the shape of the response?

Click here for the solution

For almost every PFT the default point sits above the dotted line, so a linear assumption underestimates GPP at the default.

Three points are enough to show that the response bends, but not where or how sharply.

Step 7: Compare to observations:#

So far we have only compared ensemble members to each other or to the default. It can also be useful to compare to observations, especially in the context of potential parameter calibration exercises.

We have access to eddy covariance flux data from BONA’s towers. We will look at observations from 2018-2019.

How the observation files were downloaded The files come from NEON's public bucket. To download them yourself:

from urllib.request import urlretrieve
base_url = "https://storage.neonscience.org/neon-ncar/NEON/eval_files/v4/BONA"
for year in [2018, 2019]:
    for month in range(1, 13):
        file_name = f"BONA_eval_{year}-{month:02d}.nc"
        urlretrieve(f"{base_url}/{file_name}", OBS_DIR / file_name)
Important Note: From our base case (BONA.FATESsp), we can see that the DATM data used to force this case runs from 2018 to 2021 (check out DATM_YR_START, DATM_YR_END, and DATM_YR_ALIGN) in any of the cases. The model cycles through those 4 years, so model year 2014 uses year 2018 meteorology and 2015 uses 2019. Thus, the model dates in our output files don't actually match the real dates. To compare with tower data, we must line up model 2014–2015 with observations from 2018–2019.

Load the observational data#

Load the observational data from BONA:

OBS_DIR = Path("/glade/campaign/cgd/tss/tutorials/neon_v3/eval_files/BONA")

# observation variable to model variable to compare it with
OBS_VARIABLES = {"GPP_DT": "FATES_GPP", "EFLX_LH_TOT": "EFLX_LH_TOT", "FSH": "FSH"}

# umol CO2 m-2 s-1 -> g C m-2 d-1
UMOL_CO2_TO_G_C_PER_DAY = 1e-6 * 12.011 * 86400


def load_neon_obs(model_time, obs_dir=OBS_DIR, variables=OBS_VARIABLES, neon_site='BONA'):
    """Load half-hourly NEON flux observations, average them to monthly means,
    and put them on the model's time axis."""
    files = sorted(obs_dir.glob(f"{neon_site}_eval_*.nc"))
    ds = xr.open_mfdataset(files, combine="by_coords")[list(variables)]
    ds = ds.squeeze(drop=True).load().sel(time=slice('2018-01-01', '2019-12-31'))

    monthly = ds.resample(time="1MS").mean()

    monthly["GPP_DT"] = monthly["GPP_DT"] * UMOL_CO2_TO_G_C_PER_DAY
    monthly["GPP_DT"].attrs["units"] = "g C m-2 d-1"

    monthly = monthly.rename(variables)

    # model year 2014 used 2018 meteorology (DATM_YR_ALIGN), so line up month by month
    if monthly.sizes["time"] != model_time.sizes["time"]:
        raise ValueError("observations and model have a different number of months")
    if not (monthly["time.month"].values == model_time["time.month"].values).all():
        raise ValueError("observation and model months don't line up")

    return monthly.assign_coords(time=model_time.values)
compare_vars = list(OBS_VARIABLES.values())

obs = load_neon_obs(default["time"])
obs

Now we can compare the BONA tower observations with the FATES output

def plot_obs_comparison(ensemble, default, obs, variables):
    """Plot the ensemble min–max range, the default run, and observations for each variable."""
    fig, axes = plt.subplots(len(variables), 1, figsize=(9, 3 * len(variables)),
                             sharex=True, layout="constrained")
    for ax, variable in zip(np.atleast_1d(axes), variables):
        time = default["time"].values
        # range across ALL members (every parameter, both directions)
        ax.fill_between(time, ensemble[variable].min("member"), ensemble[variable].max("member"),
                        color="tab:gray", alpha=0.3, linewidth=0, label="ensemble range")
        
        default[variable].plot(ax=ax, color="k", lw=1.5, label="default")
        obs[variable].plot(ax=ax, color="tab:orange", marker="o", ls="", label="NEON observations")

        ax.set_title(variable, loc="left", fontweight="bold")
        ax.set_xlabel("")
        ax.set_ylabel(default[variable].attrs.get("units", ""))
        ax.grid(alpha=0.3)
        ax.spines[["top", "right"]].set_visible(False)

    np.atleast_1d(axes)[0].legend(frameon=False, loc="upper left", bbox_to_anchor=(1.01, 1.0))
plot_obs_comparison(ensemble, default, obs, compare_vars)

The shaded range tells us whether any member reaches the observations. Let’s compare each ensemble member:

def plot_obs_comparison_by_member(ensemble, default, obs, variables, parameters):
    """Plot the ensemble min and max, the default run, and observations for each variable."""

    colors = dict(zip(parameters, plt.cm.tab10.colors))
    
    fig, axes = plt.subplots(len(variables), 1, figsize=(9, 3 * len(variables)),
                             sharex=True, layout="constrained")
    
    for ax, variable in zip(np.atleast_1d(axes), variables):
        for param in parameters:
            lo = ensemble[variable].sel(member=get_member(manifest, param, "minimum"))
            hi = ensemble[variable].sel(member=get_member(manifest, param, "maximum"))
            lo.plot(ax=ax, color=colors[param], linestyle='--')
            hi.plot(ax=ax, color=colors[param], label=param)
        
        default[variable].plot(ax=ax, color="gray", lw=1.5, label="default")
        obs[variable].plot(ax=ax, color="black", marker="o", ls="",
                           markeredgecolor='white', zorder=5, ms=6,
                           label="NEON observations")

        ax.set_title(variable, loc="left", fontweight="bold")
        ax.set_xlabel("")
        ax.set_ylabel(default[variable].attrs.get("units", ""))
        ax.grid(alpha=0.3)
        ax.spines[["top", "right"]].set_visible(False)

    handles, labels = np.atleast_1d(axes)[0].get_legend_handles_labels()
    handles += [Line2D([], [], color="k", lw=1, ls="-"), Line2D([], [], color="k", lw=1, ls="--")]
    labels += ["maximum", "minimum"]
    fig.legend(handles, labels, frameon=False, loc="outside right center")
plot_obs_comparison_by_member(ensemble, default, obs, compare_vars, parameters)
Interpretation exercise 6

  1. Do the observations fall inside the ensemble range? In which months and for which variables do they not?
  2. Which parameter, changed in which direction, moves the model closest to the observed summer GPP? Does that same change improve latent and sensible heat?
Click here for the solution
  1. Mostly no. In midsummer, observed GPP is near the bottom of the range, observed latent heat is below it, and observed sensible heat is well above it. The default run produces too much summer GPP, too much latent heat, and not enough sensible heat.

  2. Lowering fates_leaf_vcmax25top brings summer GPP close to the observations. It also moves latent and sensible heat in the right direction, but not far enough.

Wrap up#

You now know how to use the meristem package to perform a parameter sensitivity experiment. You can use this tool to investigate any parameter’s influence on any process. There are several directions you might want to go next depending on your research project.

  • You might test whether a parameter’s response is non-linear by running additional settings beyond the minimum and maximum, or using the Morris sampling method (a built-in option in the meristem package).

  • You can investigate parameter interactions by modifying multiple parameters at the same time, or running a Sobol sensitivity experiment.

  • Once you understand which parameters are most influential on the processes you are interested in, you can select a subset to calibrate.

To use an emulator-based calibration method, the next step will be to run a Latin Hypercube sample.

  • meristem has an option to use a Latin Hypercube sampling design.

  • A rule of thumb for training an emulator is to start with 10xN ensemble members where N is the number of parameters.

  • There are many different emulator-based calibration methods; we recommend starting with the ESEm package.

Challenge exercise

  1. Run another PPE using a Latin Hypercube sampling design with these three parameters.
  2. For more information, look at the meristem docs/paramgen.md.