Reproduce twelve seasons over Indonesia

CCA, PCR, raw CFSv2 and climatology · seasons centred on 2023

This companion notebook teaches the analysis of forecasts produced through PyCPT. Reading its already-executed outputs requires only a browser. Running the default cells uses saved results and scientific Python packages: no PyCPT installation, CPT executable, IRI Data Library credentials, data downloads or new fitting are required. Use the complete tutorial kit, which includes the data and helper code.

An optional OND section shows the actual PyCPT calibration calls. That extension requires PyCPT with its compatible CPT engine; it uses local inputs and needs no IRI Data Library authentication. Outputs go to temp/, preserving the research archive.

Learning goals. Select target seasons without a year-label error; compare four forecast methods on identical country-land cells; calculate spatial errors; inspect geographic differences; distinguish training sensitivity from independent evidence.

1. Find the project and check the teaching data

Run from the repository or tutorial-kit folder, or a directory beneath it. The notebook discovers that root so it also works when Jupyter starts in docs/notebooks/. For default execution, select a kernel with NumPy, pandas, xarray, Matplotlib, netCDF4 and IPython installed. The kit’s environment/offline-analysis.yml provides the scientific-Python package specification; Python (Tutorial Analysis) is the suggested kernel name. An existing working tutorial kernel can also be used. PyCPT and its CPT executable are needed only if you enable the optional refit. Hash verification detects changed data before calculating results.

from pathlib import Path
import sys
root = next((p for p in (Path.cwd(), *Path.cwd().parents)
             if (p / "pycpt_tutorial").is_dir() and (p / "docs/data").is_dir()), None)
if root is None:
    raise FileNotFoundError("Open this notebook inside the full repository or extracted tutorial kit.")
sys.path.insert(0, str(root))
import json
import hashlib
import datetime as dt
import numpy as np
import pandas as pd
import xarray as xr
import matplotlib.pyplot as plt
from IPython.display import display, HTML
from pycpt_tutorial import teaching as teach
from pycpt_tutorial.export import save_netcdf
%matplotlib inline
teach.style()
data_dir = root / "docs/data"
artifacts = root / "docs/assets/seasonal-2023"
artifacts.mkdir(parents=True, exist_ok=True)
provenance = teach.verify_bundle(data_dir)
def load(name):
    with xr.open_dataset(data_dir / name) as source:
        return source.load()
data = load("indonesia-seasons-2023.nc")
context = load("verification-context-2021-2024.nc")
print(f"Verified {len(provenance['outputs'])} input files; {int(data.evaluation_mask.sum()):,} country-land cells.")
Verified 5 input files; 69,640 country-land cells.

2. Keep actual dates visible

A season is a three-month rainfall total, not a single month. This tutorial orders seasons by their midpoint in 2023. DJF spans December 2022–February 2023; NDJ spans November 2023–January 2024. The research archive uses ending-year labels, so that last window is stored as NDJ 2024. Keep this source label unchanged.

Each forecast was initialized on the first day of the month before its target begins. The three CFSv2 lead centres are 1.5, 2.5 and 3.5 months. Monthly rates were integrated with actual month lengths before this teaching copy was made.

calendar = pd.DataFrame({
    "Season": data.season.values,
    "Initialization": pd.to_datetime(data.initialization.values).strftime("%d %b %Y"),
    "Target starts": pd.to_datetime(data.target_start.values).strftime("%d %b %Y"),
    "Target ends": pd.to_datetime(data.target_end.values).strftime("%d %b %Y"),
    "Research ending year": data.source_season_year.values,
})
assert np.all(pd.DatetimeIndex(data.target_midpoint.values).year == 2023)
assert int(data.source_season_year.sel(season="NDJ")) == 2024
calendar.to_csv(artifacts / "calendar.csv", index=False)
display(HTML(calendar.to_html(index=False, classes="table table-sm", border=0)))
Table 22.1
Season Initialization Target starts Target ends Research ending year
DJF 01 Nov 2022 01 Dec 2022 28 Feb 2023 2023
JFM 01 Dec 2022 01 Jan 2023 31 Mar 2023 2023
FMA 01 Jan 2023 01 Feb 2023 30 Apr 2023 2023
MAM 01 Feb 2023 01 Mar 2023 31 May 2023 2023
AMJ 01 Mar 2023 01 Apr 2023 30 Jun 2023 2023
MJJ 01 Apr 2023 01 May 2023 31 Jul 2023 2023
JJA 01 May 2023 01 Jun 2023 31 Aug 2023 2023
JAS 01 Jun 2023 01 Jul 2023 30 Sep 2023 2023
ASO 01 Jul 2023 01 Aug 2023 31 Oct 2023 2023
SON 01 Aug 2023 01 Sep 2023 30 Nov 2023 2023
OND 01 Sep 2023 01 Oct 2023 31 Dec 2023 2023
NDJ 01 Oct 2023 01 Nov 2023 31 Jan 2024 2024

3. Define a fair comparison

Observation: local CHIRPS v3.0 rainfall at its native 0.05° grid, at every pixel that touches Indonesia (the supplied 38-province boundary, so coastal pixels and small islands are included). It is a gridded observational estimate, not independent station validation. Raw: the same CFSv2 ensemble-mean seasonal forecast supplied at 1°, interpolated to the observation grid. A 0.05° output does not establish 0.05° dynamical skill.

Climatology: the mean observed total over the fitting period, unchanged from year to year. CCA/PCR: regression-calibrated forecasts, each trained separately for each target season. The main illustration uses 1991–2020; 1983–2010 is a sensitivity check. This choice is stated upfront rather than selecting a different winner each season.

The fits retain three predictor EOFs; CCA additionally retains three predictand EOFs and two CCA modes. Counts are fixed, not optimized. CPT used synchronous predictors and five-sample cyclic CV, refitting within folds, then fitted the full training period for the later forecasts. No transform, tailoring, dry mask or skill mask was enabled. CPT automatically zero-bounds rainfall. These are current-vintage retrospective replays.

mask = data.evaluation_mask.astype(bool)
pixels = int(mask.sum())
weights = data.evaluation_weight.where(mask, 0)
weights = weights / weights.sum(("Y", "X"))
assert np.isclose(float(weights.sum()), 1)
assert int(data.forecast_rainfall.count()) == 12 * 7 * pixels
assert int(data.observed_rainfall.count()) == 12 * pixels
main_variants = teach.MAIN
print(f"Same observations, {pixels:,} pixels and normalized area weights for every method.")
Same observations, 69,640 pixels and normalized area weights for every method.

4. Calculate errors, rather than ranking maps by appearance

For each seasonal window and forecast, calculate \(e_i=f_i-o_i\), \(\mathrm{RMSE}=\sqrt{\sum_i w_i e_i^2}\), \(\mathrm{MAE}=\sum_i w_i|e_i|\), and \(\mathrm{bias}=\sum_i w_i e_i\). The weights sum to one. Positive bias means a forecast is too wet.

These are spatial scores across Indonesia for one seasonal forecast, not the error of a national-mean time series. RMSE penalizes large local errors strongly. Assertions below independently reproduce the saved scores for every selected window, including NDJ’s different source year.

error = data.forecast_rainfall - data.observed_rainfall
scores = xr.Dataset({
    "rmse": np.sqrt((error ** 2 * weights).sum(("Y", "X"))),
    "mae": (abs(error) * weights).sum(("Y", "X")),
    "bias": (error * weights).sum(("Y", "X")),
})
for variable in scores:
    scores[variable].attrs["units"] = "mm"
    for season in teach.SEASONS:
        archived = context[variable].sel(season=season,
            season_year=int(data.source_season_year.sel(season=season)))
        np.testing.assert_allclose(scores[variable].sel(season=season), archived, atol=1e-3, rtol=1e-5)   # fields are stored in single precision
scores = scores.assign_coords(target_start=data.target_start, target_end=data.target_end,
                             initialization=data.initialization, source_season_year=data.source_season_year)
save_netcdf(scores, artifacts / "verification-2023.nc", overwrite=True,
    metadata={"calendar": "Midpoint year2023; source NDJ ending-year2024", "comparison": "Deterministic spatial scores; no probability-skill inference"})
scores.to_dataframe().reset_index().to_csv(artifacts / "metrics-2023.csv", index=False)
rmse = scores.rmse.to_pandas().reindex(teach.SEASONS)
main_rmse = rmse[main_variants].rename(columns=teach.LABELS)
display(HTML(main_rmse.round(2).to_html(classes="table table-sm", border=0)))
Table 22.2
forecast_variant Raw CFSv2 Climatology CCA PCR
season
DJF 489.130005 169.750000 174.539993 173.050003
JFM 473.950012 169.809998 162.720001 169.179993
FMA 415.640015 149.029999 139.320007 147.669998
MAM 370.220001 146.630005 135.130005 137.539993
AMJ 350.989990 157.759995 150.050003 148.669998
MJJ 382.019989 144.889999 143.100006 142.990005
JJA 378.589996 132.669998 180.899994 177.449997
JAS 323.320007 124.739998 164.089996 161.000000
ASO 287.739990 192.240005 111.809998 112.849998
SON 268.470001 213.339996 107.309998 105.930000
OND 292.739990 232.320007 124.190002 120.389999
NDJ 393.600006 177.130005 157.350006 168.419998
fig = teach.rmse_overview(main_rmse)
teach.save_figure(fig, artifacts, "rmse-overview")
plt.show()
Four methods by twelve seasons: both calibrated forecasts beat the raw model throughout; climatology wins DJF, JJA and JAS.
Figure 22.1: Spatial RMSE across the twelve seasons centred on 2023. Lower is better; bold entries identify the lowest unrounded score in each season. All methods use the same country-land cells and weights.

A calibrated forecast should be compared with both the raw model and climatology. Correcting a large raw bias does not automatically beat a simple observed average. The following reduction is \(100(1-\mathrm{RMSE}_{model}/\mathrm{RMSE}_{climo})\). It is an RMSE reduction, not a ranked probability skill score or a significance test.

gains = pd.DataFrame({method: 100 * (1 - main_rmse[method] / main_rmse["Climatology"])
                      for method in ("CCA", "PCR")})
gains.to_csv(artifacts / "rmse-reduction-vs-climatology.csv")
fig = teach.gain_bars(gains)
teach.save_figure(fig, artifacts, "gain-bars")
plt.show()
Paired CCA and PCR bars show seasonal improvements and deterioration against climatology, including losses in DJF, JJA and JAS.
Figure 22.2: RMSE reduction relative to the 1991–2020 climatology forecast. Positive values mean lower error after calibration; negative values favour climatology.

5. Walk through OND before looking across every season

OND 2023 was initialized on 1 September and verifies over 1 October–31 December. Read the five maps on the same rainfall scale. CHIRPS3 is the verification reference; the other panels are forecasts. More spatial detail is not itself evidence of better forecasts. The common scale saturates its highest 1% to keep lower totals legible.

fig = teach.ond_maps(data)
teach.save_figure(fig, artifacts, "ond-maps")
plt.show()
Five Indonesia maps compare observed rainfall with raw CFSv2, climatology, CCA and PCR for October–December 2023.
Figure 22.3: OND 2023 observed and forecast rainfall on a common scale. Only country-land cells are shaded. The upper 1% is saturated for display; numeric files retain all values. Grey land shows other countries; Indonesia has no boundary fill, with dark country and thin province outlines.

Inspect the actual fitting inputs

These NetCDF files are the inputs of the OND 1991-2020 fit. They retain the forecast initialization and target coordinates and the missing-value metadata required by cptcore. Predictors and observations have different spatial grids; their training target dates must match. The observation mean also checks the OND climatology baseline.

X = load("ond-training-predictor.nc").precipitation
Y = load("ond-training-observations.nc").precipitation
F = load("ond-forecast-predictor.nc").precipitation
np.testing.assert_array_equal(X["T"], Y["T"])
assert X.sizes["T"] == Y.sizes["T"] == 30 and F.sizes["T"] == 1
assert pd.Timestamp(Y.Tf.max().item()) < pd.Timestamp(F.S.min().item())
np.testing.assert_allclose(Y.mean("T").values[mask.values],
    data.forecast_rainfall.sel(season="OND", forecast_variant="climatology_1991_2020").values[mask.values], atol=.01, rtol=0)
print(f"X: {dict(X.sizes)}; Y: {dict(Y.sizes)}; F: {dict(F.sizes)}")
print("Training and forecast dates are separate; climatology check passed.")
X: {'T': 30, 'Y': 41, 'X': 71}; Y: {'T': 30, 'Y': 380, 'X': 960}; F: {'T': 1, 'Y': 41, 'X': 71}
Training and forecast dates are separate; climatology check passed.

Optional: rerun CCA and PCR in new scratch directories

Keep RERUN_CPT = False for the default offline analysis, which needs no PyCPT or CPT installation. Set it to True only in the tested PyCPT fitting environment, after conda activation sets CPT_BIN_DIR for the compatible engine. The supplied fitting setup is PyCPT 2.10.4, cptio 1.4.0 and CPT 17.8.3. All OND inputs are local; no IRI Data Library authentication is needed for this refit.

The visible settings below reproduce the fixed-mode design. The scoped reader handles the audited initialization-date headers without changing forecast numbers. This refits OND only, not all twelve seasons. New logs and outputs go to a unique temp/ directory. Returned forecasts are checked against the saved case before export. The first published execution uses saved results; the optional path is tested separately.

RERUN_CPT = False
if RERUN_CPT:
    from cptcore import canonical_correlation_analysis, principal_components_regression
    from pycpt_tutorial.cpt_dates import verified_midnight_reader
    import tempfile
    (root / "temp").mkdir(exist_ok=True)
    work = Path(tempfile.mkdtemp(prefix="ond-tutorial-", dir=root / "temp"))
    settings = dict(x_eof_modes=(3, 3), validation="CROSSVALIDATION", crossvalidation_window=5,
                    synchronous_predictors=True, transform_predictand=None, tailoring=None,
                    drymask_threshold=None, skillmask_threshold=None)
    expected_dates = [pd.Timestamp(v).to_pydatetime() for v in np.concatenate([X.S.values, F.S.values])]
    for method, function in (("cca", canonical_correlation_analysis), ("pcr", principal_components_regression)):
        options = dict(settings)
        if method == "cca":
            options.update(y_eof_modes=(3, 3), cca_modes=(2, 2))
        with verified_midnight_reader(function, expected_dates):
            result = function(X, Y, F=F, **options, cpt_kwargs={
                "outputdir": work / method, "log": work / f"{method}.log",
                "project_file": work / f"{method}-commands.txt"})
        forecast = result[1].reindex(X=data.X, Y=data.Y, method="nearest", tolerance=1e-3).where(mask)
        saved = data.forecast_rainfall.sel(season="OND", forecast_variant=f"{method}_1991_2020")
        np.testing.assert_allclose(forecast.deterministic.isel(T=0), saved, atol=.01, rtol=0, equal_nan=True)
        save_netcdf(forecast, work / f"{method}-forecast.nc", overwrite=False)
    print(f"CCA/PCR reruns match saved OND forecasts; new outputs: {work}")
else:
    print("Calibration rerun skipped; all comparisons use the hash-verified saved results.")
Calibration rerun skipped; all comparisons use the hash-verified saved results.

6. Read the forecast itself: anomaly and probabilities

The scores above say how good each forecast was. A forecast user asks something more direct first: how much rain, how does that compare with normal, and how likely is a dry or a wet season? CPT answers all three for every fit. This section shows those products for each of the twelve seasons, from the same CCA and PCR fits (1991-2020).

  • Normal is the mean of the 30 observed training totals, 1991-2020, at each pixel.
  • Anomaly is the forecast total minus the normal, in mm; percent of normal is their ratio.
  • Tercile probabilities are CPT’s chances that the total falls in the driest third, the middle third or the wettest third of the 30 training totals. The boundaries are the 33rd and 67th percentiles; NumPy’s hazen rule reproduces CPT’s own (Learn chapter 5 checks this).
  • The most likely category is the one with the highest probability.

The file read here was packaged from the saved fits by scripts/prepare_forecast_products_2023.py; nothing is refitted.

products_record = json.loads((data_dir / "products-provenance.json").read_text())
products_file = data_dir / "indonesia-seasons-2023-products.nc"
assert hashlib.sha256(products_file.read_bytes()).hexdigest() == products_record["output"][products_file.name]["sha256"]
products = load(products_file.name)
assert bool((products.evaluation_mask == data.evaluation_mask).all())
CATEGORIES = ["below", "near", "above"]

most_likely = products.probability.fillna(-1).argmax("category").where(mask)            # 0 below, 1 near, 2 above
observed_category = products.observed_category.where(mask)
area = lambda field: float((field * weights).sum(("Y", "X")))               # weights sum to 1 over the scored pixels

rows = []
for season in data.season.values:
    normal = products.normal.sel(season=season)
    observed = data.observed_rainfall.sel(season=season)
    seen = observed_category.sel(season=season)
    for method in ["cca", "pcr"]:
        forecast = data.forecast_rainfall.sel(season=season, forecast_variant=f"{method}_1991_2020")
        likely = most_likely.sel({"season": season, "method": method})
        p = products.probability.sel({"season": season, "method": method})
        given = sum(p.sel(category=name).where(seen == k, 0) for k, name in enumerate(CATEGORIES))
        row = {"season": season, "method": method.upper(),
               "normal (mm)": area(normal), "forecast (mm)": area(forecast), "observed (mm)": area(observed),
               "forecast anomaly (mm)": area(forecast - normal), "observed anomaly (mm)": area(observed - normal),
               "forecast (% of normal)": 100 * area(forecast) / area(normal), "observed (% of normal)": 100 * area(observed) / area(normal)}
        for k, name in enumerate(CATEGORIES):
            row[f"forecast area most likely {name} (%)"] = 100 * area(likely == k)
            row[f"observed area {name} (%)"] = 100 * area(seen == k)
        row["area where the most likely category was observed (%)"] = 100 * area(likely == seen)
        row["mean probability given to the observed category (%)"] = area(given)
        rows.append(row)
product_table = pd.DataFrame(rows).set_index(["season", "method"])
product_table.to_csv(artifacts / "forecast-products-2023.csv", float_format="%.3f")
show = product_table.xs("CCA", level="method")[["normal (mm)", "forecast (mm)", "observed (mm)", "forecast (% of normal)", "observed (% of normal)",
                                               "forecast area most likely below (%)", "forecast area most likely above (%)",
                                               "observed area below (%)", "observed area above (%)",
                                               "area where the most likely category was observed (%)"]]
display(HTML(show.round(0).astype(int).to_html(classes="table table-sm", border=0)))
normal (mm) forecast (mm) observed (mm) forecast (% of normal) observed (% of normal) forecast area most likely below (%) forecast area most likely above (%) observed area below (%) observed area above (%) area where the most likely category was observed (%)
season
DJF 832 941 900 113 108 20 78 18 44 45
JFM 819 903 897 110 110 15 82 12 46 43
FMA 815 852 876 104 107 27 67 15 41 38
MAM 800 826 842 103 105 24 63 18 36 40
AMJ 721 729 738 101 102 27 51 27 35 45
MJJ 623 612 645 98 103 41 41 19 34 34
JJA 546 417 541 76 99 91 7 14 29 17
JAS 511 354 482 69 94 93 5 20 20 25
ASO 563 448 442 80 79 86 1 60 9 60
SON 666 460 503 69 76 100 0 70 3 70
OND 794 623 625 79 79 96 4 75 6 76
NDJ 839 717 790 85 94 91 8 47 21 51

Read the table row by row: the area-mean normal, forecast and observed totals; the forecast and the outcome as a percentage of normal; the share of Indonesia’s area the CCA forecast placed in the dry and wet categories, and the share that ended there; and the share of area where the most likely category was the one observed. A forecast that always named one category would score the observed share of that category, so the last column should be read against the observed columns. The CSV also holds the PCR rows, the anomalies in mm and the mean probability given to the observed category.

One season is one outcome: these columns describe 2023, not the reliability of the probabilities, which this case does not test.

fig = teach.forecast_products(data, products, "OND", "cca")
teach.save_figure(fig, artifacts, "ond-forecast-products")
plt.show()
Four stacked Indonesia maps: forecast percent of normal, observed percent of normal, most likely category with probability and observed category for October-December 2023.
Figure 22.4: OND 2023, CCA calibrated on 1991-2020: the forecast and the observation as a percentage of normal, then CPT’s most likely tercile category shaded by its probability and the category that was observed.

7. Inspect geographic differences across all twelve seasons

Subtract each calibrated absolute error from climatology’s absolute error at the same cell. Positive values mean calibration helped there; negative values mean climatology did better. A lower national RMSE can coexist with local deterioration. The atlas shows both models for every season, rather than selecting only favourable maps. Colours saturate beyond ±300 mm; downloadable numeric fields retain all values.

reference_error = abs(error.sel(forecast_variant="climatology_1991_2020"))
local_gain = reference_error - abs(error.sel(forecast_variant=["cca_1991_2020", "pcr_1991_2020"]))
local_gain.attrs.update(units="mm", long_name="Absolute-error reduction relative to climatology")
save_netcdf(local_gain.rename("absolute_error_reduction"), artifacts / "local-error-reduction-2023.nc",
    metadata={"units": "mm", "positive_means": "Calibration has smaller absolute error than climatology"}, overwrite=True)
fig = teach.error_atlas(data)
teach.save_figure(fig, artifacts, "error-atlas")
plt.show()
Twenty-four maps show geographically mixed CCA and PCR error reductions across all twelve seasons, including local failures.
Figure 22.5: Local absolute-error reduction relative to climatology for CCA and PCR in every season. Green means calibration helps, brown means it worsens the local forecast; colours saturate beyond ±300 mm. Grey land shows other countries; Indonesia has no boundary fill, with dark country and thin province outlines.

8. Compare provinces

The supplied file contains 38 provinces. The regions are defined from these boundaries before inspecting their forecast errors, and every province is kept. Analysis uses the unsimplified polygons, not the display GeoJSON. Each 0.05° pixel belongs to the province that covers the largest part of it; because a pixel is kept only if it touches a province, every scored pixel has one. Cosine-latitude weights are the same as in the national scores. See the weighting example.

These are province means of the same pixel errors. They add no information to the forecasts, which come from a 1° model, and small provinces have few pixels. The boundary snapshot is not a certification of current or historical official administrative limits.

from pycpt_tutorial.regions import score_pixels_by_region
region_dir = data_dir / 'regions'
region_provenance = json.loads((region_dir / 'provenance.json').read_text())
for name, record in region_provenance['outputs'].items():
    assert hashlib.sha256((region_dir / name).read_bytes()).hexdigest() == record['sha256'], name
def load_region(name):
    with xr.open_dataset(region_dir / name) as source:
        return source.load()
regional_annual = load_region('province-context-annual.nc')
regional_pooled = load_region('province-context-pooled.nc')
province_names = [str(v) for v in data.province.values]
assert len(province_names) == 38
label = data.province_index.values[mask.values]              # the province of every scored pixel
pixel_weight = data.evaluation_weight.values[mask.values]
assert label.min() >= 0 and label.max() == 37
region_mass = np.bincount(label, weights=pixel_weight, minlength=38)
region_pixels = np.bincount(label, minlength=38)
region_fraction = xr.DataArray(region_mass / region_mass.sum(), dims='region', coords={'region': province_names})
print(f"All 38 provinces retained; every one of the {pixels:,} scored pixels belongs to a province.")
All 38 provinces retained; every one of the 69,640 scored pixels belongs to a province.
support_table = pd.DataFrame({
    'Region': province_names,
    'Country weight (%)': 100*region_fraction.values,
    'Pixels': region_pixels,
})
support_table.to_csv(artifacts / 'province-support.csv', index=False)
display(HTML(support_table.round(2).to_html(index=False, classes='table table-sm', border=0)))
Table 22.3
Region Country weight (%) Pixels
Aceh 3.00 2087
Bali 0.35 243
Banten 0.55 386
Bengkulu 1.03 720
Daerah Khusus Ibukota Jakarta 0.08 58
Daerah Istimewa Yogyakarta 0.16 113
Gorontalo 0.66 459
Jambi 2.34 1623
Jawa Barat 1.84 1291
Jawa Tengah 1.74 1221
Jawa Timur 2.66 1868
Kalimantan Barat 7.28 5057
Kalimantan Selatan 1.89 1315
Kalimantan Tengah 7.30 5073
Kalimantan Timur 6.17 4287
Kalimantan Utara 3.54 2460
Kepulauan Bangka Belitung 1.09 756
Kepulauan Riau 1.13 782
Lampung 1.73 1208
Maluku 3.32 2313
Maluku Utara 2.28 1581
Nusa Tenggara Barat 1.25 879
Nusa Tenggara Timur 2.90 2041
Papua 4.27 2972
Papua Pegunungan 2.42 1684
Papua Selatan 5.80 4055
Papua Tengah 2.99 2083
Riau 4.46 3097
Sulawesi Barat 0.86 596
Sulawesi Selatan 2.49 1734
Sulawesi Tengah 3.60 2500
Sulawesi Tenggara 2.13 1482
Sulawesi Utara 0.97 676
Sumatera Barat 2.24 1553
Sumatera Selatan 4.14 2880
Sumatera Utara 3.69 2568
Papua Barat 3.25 2263
Papua Barat Daya 2.41 1676
fig = teach.province_map(data.province_index.where(mask), len(province_names), pixels)
teach.save_figure(fig, artifacts, 'province-support-map')
plt.show()
Indonesia map with each pixel coloured by its province, with country and province boundaries.
Figure 22.6: The province of every scored 0.05° pixel: the province that covers the largest part of the pixel. Colours only separate neighbouring provinces.

Average the squared, absolute and signed pixel errors within each province, with the same area weights, then take the root of the mean square. For province weight fraction \(a_r\), national MSE must equal \(\sum_r a_r\,\mathrm{MSE}_r\). National RMSE is the square root of that result, not an average of province RMSEs. The following code checks the identity and the archived province scores.

pixel_error = error.transpose('season', 'forecast_variant', 'Y', 'X').values[:, :, mask.values]
parts = score_pixels_by_region(pixel_error, label, pixel_weight, 38)
regional = xr.Dataset({name: (('season', 'forecast_variant', 'region'), values) for name, values in parts.items()},
                      coords={'season': error.season.values, 'forecast_variant': error.forecast_variant.values, 'region': province_names})
for variable in regional:
    regional[variable].attrs['units'] = 'mm2' if variable == 'mse' else 'mm'
for variable in ('rmse','mae','bias'):
    combined = np.sqrt((regional.mse*region_fraction).sum('region')) if variable=='rmse' else (regional[variable]*region_fraction).sum('region')
    np.testing.assert_allclose(combined, scores[variable].transpose('season', 'forecast_variant'), atol=1e-3, rtol=1e-5)
for season in teach.SEASONS:
    selected = regional_annual.sel(season=season, season_year=int(data.source_season_year.sel(season=season)))
    for variable in regional:
        np.testing.assert_allclose(regional[variable].sel(season=season).transpose('forecast_variant', 'region'),
                                   selected[variable].transpose('forecast_variant', 'region'), atol=1e-3, rtol=1e-5)
save_netcdf(regional, artifacts / 'province-verification-2023.nc', overwrite=True,
            metadata={'scope':'Province means of the 0.05 degree pixel errors; each pixel belongs to one province',
                      'calendar':'Target midpoints2023, NDJ source ending-year2024'})
regional.to_dataframe().reset_index().to_csv(artifacts / 'province-metrics-2023.csv', index=False)
regional_annual.to_dataframe().reset_index().to_csv(artifacts / 'province-metrics-context-annual.csv', index=False)
regional_pooled.to_dataframe().reset_index().to_csv(artifacts / 'province-metrics-context-pooled.csv', index=False)
print('Province MSE, MAE and bias recombine to the national scores.')
Province MSE, MAE and bias recombine to the national scores.
ond_province_rmse = regional.rmse.sel(season='OND', forecast_variant=main_variants).transpose('region','forecast_variant').to_pandas().rename(columns=teach.LABELS)
ond_province_rmse.to_csv(artifacts / 'province-ond-2023-rmse.csv')
display(HTML(ond_province_rmse.round(2).to_html(classes='table table-sm', border=0)))
Table 22.4
forecast_variant Raw CFSv2 Climatology CCA PCR
region
Aceh 491.18 242.26 284.75 281.98
Bali 124.55 356.53 120.26 109.35
Banten 451.97 371.45 158.11 85.89
Bengkulu 333.42 449.46 192.06 141.99
Daerah Khusus Ibukota Jakarta 58.40 204.99 87.57 65.94
Daerah Istimewa Yogyakarta 140.02 296.09 110.35 119.85
Gorontalo 158.31 60.43 125.77 128.66
Jambi 278.96 237.62 94.57 89.00
Jawa Barat 305.77 391.42 109.88 82.96
Jawa Tengah 224.75 379.67 111.50 107.46
Jawa Timur 174.67 308.46 61.37 58.39
Kalimantan Barat 354.08 134.76 136.15 141.66
Kalimantan Selatan 302.01 96.22 131.00 152.40
Kalimantan Tengah 273.99 184.76 70.34 78.10
Kalimantan Timur 203.96 204.66 52.34 69.58
Kalimantan Utara 216.91 309.20 115.25 98.12
Kepulauan Bangka Belitung 370.79 193.95 185.32 191.20
Kepulauan Riau 259.19 103.39 117.05 127.08
Lampung 137.37 334.40 93.17 61.41
Maluku 213.80 207.48 91.89 80.12
Maluku Utara 143.56 274.11 55.21 64.71
Nusa Tenggara Barat 265.73 199.85 51.47 52.85
Nusa Tenggara Timur 280.11 165.27 59.51 57.79
Papua 115.95 274.50 183.40 183.63
Papua Pegunungan 399.05 122.86 69.65 70.92
Papua Selatan 372.21 257.46 112.87 116.92
Papua Tengah 455.99 199.66 101.04 95.55
Riau 323.38 113.82 133.55 148.66
Sulawesi Barat 320.62 110.66 101.98 69.67
Sulawesi Selatan 222.35 196.48 97.20 79.07
Sulawesi Tengah 222.99 151.02 78.08 68.03
Sulawesi Tenggara 113.60 144.20 74.39 61.31
Sulawesi Utara 152.51 325.89 117.11 133.96
Sumatera Barat 398.35 388.82 277.98 230.29
Sumatera Selatan 147.83 330.07 103.33 96.46
Sumatera Utara 282.20 107.24 162.13 152.57
Papua Barat 409.13 164.12 97.84 85.87
Papua Barat Daya 276.11 196.16 53.07 67.51
fig = teach.province_heatmap(regional.sel(region=province_names), 'Province-weighted forecast errors · seasons centred on 2023')
teach.save_figure(fig, artifacts, 'province-gains-2023')
plt.show()
Two heatmaps compare CCA and PCR against climatology across all 38 provinces and 12 target windows centred on 2023.
Figure 22.7: RMSE reductions for CCA and PCR relative to 1991–2020 climatology in every supplied province. Green means smaller error, brown larger error. Values below −100% saturate; files retain all values. These are province means of the 0.05° pixel errors.

Repeat the comparison using all four original ending-year 2021–2024 labels. Pool annual MSE before taking its square root; each year has equal weight. This context includes2023 and is not independent confirmation of it. It does, however, expose patterns that change when the other archived years are included. Seven forecast variants, both training periods, raw and matched climatologies remain in the downloadable annual and pooled tables.

np.testing.assert_allclose(regional_pooled.rmse, np.sqrt(regional_annual.mse.mean('season_year')), atol=1e-8, rtol=0)
fig = teach.province_heatmap(regional_pooled.sel(region=province_names), 'Province-weighted forecast errors · ending-year 2021–2024 pooled context')
teach.save_figure(fig, artifacts, 'province-gains-context')
plt.show()
Two heatmaps show CCA and PCR RMSE reductions relative to matched climatology for all 38 provinces in the original four-year context.
Figure 22.8: The same provinces and fixed colour scale using pooled ending-year 2021–2024 errors. This includes2023, not an independent validation set. Equal-year MSE is averaged before the square root.
(root / 'docs/_includes').mkdir(exist_ok=True)
#| label: regional-findings
def province_win_counts(ds):
    chosen = ds.sel(region=province_names)
    base = chosen.rmse.sel(forecast_variant='climatology_1991_2020')
    return {m: (chosen.rmse.sel(forecast_variant=f'{m.lower()}_1991_2020') < base).sum('region').to_pandas().reindex(teach.SEASONS) for m in ('CCA','PCR')}
counts23 = province_win_counts(regional)
counts4 = province_win_counts(regional_pooled)
province_counts = pd.DataFrame({'2023 CCA':counts23['CCA'], '2023 PCR':counts23['PCR'],
                                'Four-year CCA':counts4['CCA'], 'Four-year PCR':counts4['PCR']})
province_counts.index.name = 'Season'
province_counts.to_csv(artifacts / 'province-improvement-counts.csv')
display(HTML(province_counts.to_html(classes='table table-sm', border=0)))
regional_summary = {'provinces':38, 'pixels':pixels, 'pixels_by_province':dict(zip(province_names, region_pixels.tolist())),
                   'province_counts':province_counts.to_dict(),
                   'scope':'Descriptive province means of pixel errors; overlapping seasons and four years do not establish operational skill'}
(artifacts / 'regional-findings.json').write_text(json.dumps(regional_summary, indent=2)+'\n')
regional_text = (f"For OND 2023, CCA has lower RMSE than climatology in **{int(counts23['CCA']['OND'])} of 38 provinces**, "
                 f"and PCR in **{int(counts23['PCR']['OND'])} of 38**. For JJA 2023, the corresponding counts are "
                 f"**{int(counts23['CCA']['JJA'])}** and **{int(counts23['PCR']['JJA'])}**. "
                 f"In the four-year pooled JJA context, they become **{int(counts4['CCA']['JJA'])}** and **{int(counts4['PCR']['JJA'])}**. "
                 "Those changes show why one year should not be turned into a province-specific forecast recommendation.")
small = support_table.sort_values('Pixels').iloc[0]
regional_text += (f" The smallest province is **{small['Region']}**, with **{int(small['Pixels']):,} pixels**. "
                  "Pixel counts describe support; neighbouring pixels are not independent samples.")
(root / 'docs/_includes/regional-findings.qmd').write_text(regional_text+'\n')
coverage_text = (f"Every one of the **{pixels:,}** scored pixels touches a province and belongs to the one that covers most of it, "
                 "so there is no unassigned remainder. The 38 province scores recombine to the national scores.")
(root / 'docs/_includes/regional-coverage.qmd').write_text(coverage_text+'\n')
print('Regional findings and all-season count table exported; counts are descriptive, not independent samples.')
2023 CCA 2023 PCR Four-year CCA Four-year PCR
Season
DJF 17 20 15 20
JFM 20 15 21 20
FMA 22 14 23 23
MAM 19 19 22 23
AMJ 24 23 11 14
MJJ 24 25 31 30
JJA 7 7 31 28
JAS 14 13 31 28
ASO 34 34 34 34
SON 32 33 35 34
OND 31 31 32 32
NDJ 23 23 21 23
Regional findings and all-season count table exported; counts are descriptive, not independent samples.

9. Keep the training-period sensitivity visible

Compare the same forecast windows using 1983–2010 (28 training seasons) and 1991–2020 (30). The common older start avoids missing 1981 initializations for the cross-year seasons in the original all-season design. This changes training years, sample count, EOF bases and fitted relationships together. It is not a controlled estimate of the effect of sample count alone, and does not justify selecting whichever period happens to win a particular 2023 season.

sensitivity = rmse[[f"{m}_{p}" for m in ("climatology", "cca", "pcr") for p in ("1983_2010", "1991_2020")]]
sensitivity.to_csv(artifacts / "training-period-sensitivity.csv")
fig = teach.sensitivity_plot(rmse)
teach.save_figure(fig, artifacts, "training-sensitivity")
plt.show()
Two line charts compare CCA and PCR spatial RMSE under1983–2010 and1991–2020 training.
Figure 22.9: The same target windows with two fixed training intervals. Both sample count and training years change; this is a sensitivity comparison, not a period-selection rule.
display(HTML(sensitivity.round(2).to_html(classes="table table-sm", border=0)))
Table 22.5
forecast_variant climatology_1983_2010 climatology_1991_2020 cca_1983_2010 cca_1991_2020 pcr_1983_2010 pcr_1991_2020
season
DJF 175.630005 169.750000 172.509995 174.539993 173.270004 173.050003
JFM 168.880005 169.809998 153.529999 162.720001 155.580002 169.179993
FMA 153.190002 149.029999 138.190002 139.320007 147.800003 147.669998
MAM 156.360001 146.630005 149.800003 135.130005 152.309998 137.539993
AMJ 164.419998 157.759995 155.350006 150.050003 149.589996 148.669998
MJJ 149.559998 144.889999 166.199997 143.100006 161.740005 142.990005
JJA 135.860001 132.669998 254.449997 180.899994 252.630005 177.449997
JAS 137.899994 124.739998 198.800003 164.089996 197.850006 161.000000
ASO 214.500000 192.240005 122.339996 111.809998 127.480003 112.849998
SON 224.600006 213.339996 119.589996 107.309998 119.800003 105.930000
OND 237.100006 232.320007 141.050003 124.190002 135.259995 120.389999
NDJ 180.860001 177.130005 164.559998 157.350006 171.050003 168.419998

10. Put a single year in a broader context

The original benchmark covers ending-year labels 2021–2024. Retain that convention here: its NDJ windows are November 2020–January 2021 through November 2023–January 2024. This is not four complete midpoint-calendar-year collections. The 2023-centred selection above uses the final NDJ window.

Pooled RMSE takes the square root after averaging squared errors across years and locations; it is not the arithmetic mean of annual RMSE. The assertions below check that identity with equal annual coverage. Four years, overlapping seasons and spatially correlated cells do not establish general operational forecast skill.

pooled = context.pooled_rmse.sel(evaluation_set="all_four_years")
np.testing.assert_allclose(pooled, np.sqrt((context.rmse ** 2).mean("season_year")), atol=1e-8, rtol=0)
context_table = pooled.to_pandas().reindex(teach.SEASONS)[main_variants].rename(columns=teach.LABELS)
context_table.to_csv(artifacts / "context-ending-years-2021-2024.csv")
fig = teach.context_plot(context_table)
teach.save_figure(fig, artifacts, "multiyear-context")
plt.show()
Four lines compare pooled forecast errors over twelve seasons, with climatology still competitive in some windows.
Figure 22.10: Pooled spatial errors in the original ending-year 2021–2024 benchmark. These labels differ from the midpoint-year selection used for the main 2023 case.

11. Export findings for the story and check provenance

The story includes the following generated text. Its numerical claims come from the same scores used in the figures, so a revised execution cannot silently leave manually copied numbers in the narrative. The final hash check confirms that none of the packaged inputs changed during execution.

wins = {m: int((main_rmse[m] < main_rmse["Climatology"]).sum()) for m in ("CCA", "PCR")}
raw_wins = {m: int((main_rmse[m] < main_rmse["Raw CFSv2"]).sum()) for m in ("CCA", "PCR")}
best = main_rmse.idxmin(axis=1)
climo_best = best.index[best == "Climatology"].tolist()
ond = main_rmse.loc["OND"]
period_wins = {m: int((rmse[f"{m}_1991_2020"] < rmse[f"{m}_1983_2010"]).sum()) for m in ("cca", "pcr")}
summary = {"main_year_convention": "Midpoints in2023; NDJ source ending-year2024", "main_training_period": "1991–2020",
           "calibration_beats_climatology_seasons": wins, "calibration_beats_raw_seasons": raw_wins,
           "lowest_rmse_method_by_season": best.to_dict(), "ond_rmse_mm": ond.to_dict(),
           "recent_training_lower_rmse_seasons": period_wins,
           "original_context_pooled_rmse_mm": context_table.to_dict(), "data_input_hashes": provenance["outputs"]}
(artifacts / "findings.json").write_text(json.dumps(summary, indent=2) + "\n")
text = (f"Across the twelve windows centred on 2023, CCA reduced spatial RMSE relative to the raw model in **{raw_wins['CCA']} seasons**; "
        f"PCR did so in **{raw_wins['PCR']}**. Against the more demanding climatology baseline, CCA improved in **{wins['CCA']} of 12** "
        f"and PCR in **{wins['PCR']} of 12**.\n\n"
        + (f"Climatology had the lowest RMSE of all four methods in **{', '.join(climo_best)}**. " if climo_best else "Climatology was not the lowest-RMSE method in this particular set of windows. ")
        + "These are descriptive comparisons for these forecast windows, not a test of statistical significance.")
includes = root / "docs/_includes"
includes.mkdir(exist_ok=True)
(includes / "seasonal-findings.qmd").write_text(text + "\n")
ond_text = (f"For OND, spatial RMSE was **{ond['Raw CFSv2']:.1f} mm** for the raw model and **{ond['Climatology']:.1f} mm** for climatology, "
            f"compared with **{ond['CCA']:.1f} mm** for CCA and **{ond['PCR']:.1f} mm** for PCR. "
            "Those numbers describe errors over the scored pixels; they are not national-mean rainfall totals.")
(includes / "ond-findings.qmd").write_text(ond_text + "\n")
teach.verify_bundle(data_dir)
display(HTML(f"<p><strong>Input integrity passed.</strong> CCA beats climatology in {wins['CCA']}/12 seasons; PCR in {wins['PCR']}/12.</p>"))

Input integrity passed. CCA beats climatology in 9/12 seasons; PCR in 9/12.

What this notebook does not establish

The twelve windows overlap; they are not twelve independent annual samples. The reference observations and archived model fields use current data vintages, not an exact reconstruction of everything available when forecasts were issued. The CFSv2 archive appends operational forecasts from April 2011; continuity does not establish homogeneity. Physical EOF/CCA-pattern review, independent station checks, longer validation and predefined regional diagnostics remain follow-up work.

Native probabilities are deliberately outside this first comparison. Their category reference dates differ from some training periods; zero-bounded outputs do not always equal their unbounded locations. Some high-level notebook probability scores are in-sample, and flexible exceedance calculations differ from native CPT17. Read the book’s methods and limitations page before using those outputs.

Sources: IRI CPT teaching reference, official notebook collection, and the project’s frozen research cases (research/cases/).

References

  1. IRI. Guide to PyCPT 2 for Seasonal Climate Forecasts (Jupyter Book, 2 September 2023 build): The Climate Predictability Tool (CPT). https://iri.columbia.edu/~awr/pycpt/seasonal-jupyterbook/html_2sep2023/cpt.html
  2. IRI. PyCPT example notebooks. GitHub repository iri-pycpt/notebooks. https://github.com/iri-pycpt/notebooks
  3. xarray. Compare weighted and unweighted mean temperature (example gallery). https://docs.xarray.dev/en/stable/examples/area_weighted_temperature.html
  4. Shapely. shapely.contains_xy. https://shapely.readthedocs.io/en/stable/reference/shapely.contains_xy.html
  5. IRI Data Library. NMME NCEP-CFSv2 hindcasts, PENTAD_SAMPLES_FULL, precipitation. https://iridl.ldeo.columbia.edu/SOURCES/.Models/.NMME/.NCEP-CFSv2/.HINDCAST/.PENTAD_SAMPLES_FULL/.prec/ Browsing Data Library pages requires signing in (checked 10 November 2026); PyCPT’s data requests in this tutorial succeeded without a key.
  6. Saha, S., Moorthi, S., Wu, X., et al. (2014). The NCEP Climate Forecast System Version 2. Journal of Climate, 27(6), 2185-2208. https://doi.org/10.1175/JCLI-D-12-00823.1
  7. Kirtman, B., Min, D., Infanti, J., et al. (2014). The North American Multimodel Ensemble: Phase-1 seasonal-to-interannual prediction; Phase-2 toward developing intraseasonal prediction. Bulletin of the American Meteorological Society, 95(4), 585-601. https://doi.org/10.1175/BAMS-D-12-00050.1
  8. Climate Hazards Center, UC Santa Barbara. CHIRPS: Rainfall Estimates from Rain Gauge and Satellite Observations (CHIRPS version 3.0 page). https://www.chc.ucsb.edu/data/chirps3
  9. Funk, C., Peterson, P., Landsfeld, M., et al. (2014). A quasi-global precipitation time series for drought monitoring. U.S. Geological Survey Data Series 832. https://doi.org/10.3133/ds832
Back to top