Flux Post-Processing Chain - Single-Call run_chain

The flux post-processing chain ships two entry points:

  • run_chain(data, FluxConfig) — single-call driver for the standard FLUXNET-style workflow. Fixed sensible defaults for per-detector and per-model knobs, only the high-level decisions are on FluxConfig.

  • The composable per-level API — full control over every knob, every detector class, every model hyperparameter. See postprocessingchain_composable.py for that path.

This example shows the simple path: load data, build one FluxConfig, hand it to run_chain, inspect the results. Use this when you want the chain to “just work” and plan to tune later.

The chain that run_chain runs:

  • L2 — Quality-flag expansion from EddyPro diagnostics (whatever tests

    you enabled in FluxConfig.level2_test_settings).

  • L3.1 — Single-point storage correction (FC -> NEE).

  • L3.2 — Hampel outlier detection with separate day / night sigmas.

    Mandatory because L3.3 depends on outlier-screened data.

  • L3.3 — USTAR filtering, either with a constant threshold you supply

    ('constant') or detected from the data via the FLUXNET bootstrap method ('bootstrap').

  • L4.1 — Gap-filling with whichever of MDS / Random Forest / XGBoost

    you enabled. The default ML FeatureEngineer ships with a symmetric [-2, 2] lag window, first/second-order differencing, 4 / 12 / 48-record rolling median + std, and vectorised timestamps. SHAP feature reduction is on.

  • L4.2 — NEE -> GPP + RECO partitioning with whichever of the four

    variants you enabled via the partition_* flags, or the one selected with partition_method / partition_mode. One fit per USTAR scenario; nighttime variants read their gap-filled NEE from the L4.1 method named by partition_gapfill_method.

Imports

from diive.configs.exampledata import load_exampledata_parquet_lae_level1_30MIN
from diive.flux.postprocessingchain import (
    FluxConfig,
    add_driver,
    init_flux_data,
    run_chain,
)

Load data

One month from the CH-LAE 2024 example dataset keeps the runtime small. The example data already contains SW_IN_POT / DAYTIME / NIGHTTIME columns from previous processing; we drop them so init_flux_data can compute them fresh (it raises on a collision with reserved names).

df = load_exampledata_parquet_lae_level1_30MIN()
df = df.loc['2024-06':'2024-06']
df = df.drop(columns=[c for c in ('SW_IN_POT', 'DAYTIME', 'NIGHTTIME')
                      if c in df.columns])
  > Loaded .parquet file
/home/docs/checkouts/diive/checkouts/latest/diive/configs/exampledata/exampledat
a_PARQUET_CH-LAE_22.4_FLUXES_LEVEL-1_IRGA72+METEO7_2024_SUBSET.parquet (0.007
seconds).

Step 1 — initialise the container

init_flux_data calculates potential radiation, derives day / night flags, and assembles the frozen FluxMeta record that every level reads from. daytime_accept_qcf_below=2 keeps QCF=0 (all tests pass) and QCF=1 (soft warnings); set to 1 for the stricter QCF=0-only acceptance.

data = init_flux_data(
    df=df,
    fluxcol="FC",
    site_lat=47.478333,  # CH-LAE
    site_lon=8.364389,
    utc_offset=1,
    nighttime_threshold=20,
    daytime_accept_qcf_below=2,
    nighttime_accept_qcf_below=2,
)
print(data)
────────────────────────── Initializing flux data: FC ──────────────────────────
  > Detected base variable CO2 for FC. (CO2 was used to calculate FC.)
  > Potential radiation calculated (SW_IN_POT)
  > Day/night flags: DAYTIME, NIGHTTIME
FluxLevelData(
  flux        = 'FC'
  levels run  = []
  fpc_df      = 1440 rows x 5 cols
  columns     = [FC, USTAR, SW_IN_POT, DAYTIME, NIGHTTIME]
  filtered    = None (no level has run yet)
)

Step 2 — register VPD in kPa

MDS needs VPD in kPa, which the input VPD here already is. Register it under a short name via add_driver — this puts the column into data.full_df (where L4.1 reads from), not into data.fpc_df. With VPD in hPa, divide by 10 first. You can also point mds_vpd= at the original column directly and skip this step.

if 'VPD_T1_47_1_gfXG' in df.columns:
    vpd_kpa = df['VPD_T1_47_1_gfXG'].rename('VPD_kPa')
    data = add_driver(data, vpd_kpa)

Step 3 — build the FluxConfig

Only fluxcol and ustar_thresholds are always required. Other fields are required depending on what is enabled: the mds_* columns because MDS is on, gapfilling_features because at least one ML method is on. The outlier_sigma_* fields are optional overrides. If you forget any of them, run_chain raises one cumulative error listing every missing field instead of failing partway through.

Omitting level2_test_settings lets the chain apply DEFAULT_LEVEL2_TEST_SETTINGS — ssitc + gas_completeness + spectral_correction_factor + raw_data_screening_vm97 with spikes and dropout enabled. To opt into the analyzer-specific signal-strength test, set signal_strength_col=... on the config. To take full control, pass an explicit level2_test_settings dict.

cfg = FluxConfig(
    fluxcol='FC',
    # USTAR filtering: one constant threshold (e.g. from REddyProc). With
    # multiple thresholds you would also pass ustar_labels=['CUT_16', ...].
    ustar_thresholds=[0.18],
    ustar_labels=['CUT_50'],
    # L3.2 Hampel: chain uses the Hampel filter's own defaults
    # (window_length=48*13 records = 13 days at 30-min sampling,
    # n_sigma_daytime=n_sigma_nighttime=5.5, use_differencing=True,
    # separate day/night). Set outlier_sigma_daytime / outlier_sigma_nighttime
    # / outlier_window_length only when you need to deviate.
    #
    # L2 quality tests: defaults apply (ssitc + gas_completeness + scf +
    # vm97). This line adds the optional signal-strength test:
    signal_strength_col='CUSTOM_SIGNAL_STRENGTH_IRGA72_MEAN',
    # L4.1 MDS (driver columns must already be in data.full_df)
    mds_swin='SW_IN_T1_47_1_gfXG',
    mds_ta='TA_T1_47_1_gfXG',
    mds_vpd='VPD_kPa',
    # L4.1 ML: RF is off to keep the example fast, XGBoost is on.
    gapfill_mds=True,
    gapfill_rf=False,
    gapfill_xgb=True,
    gapfill_reduce_features=True,  # SHAP reduction — the default
    gapfilling_features=['TA_T1_47_1_gfXG', 'SW_IN_T1_47_1_gfXG', 'VPD_kPa'],
    # L4.2 NEE partitioning — enable all four variants (off by default). Each
    # runs once per USTAR scenario. The partition_* driver columns must be in
    # data.full_df; lat / lon / utc_offset come from init_flux_data. The
    # nighttime variants read their gap-filled NEE from the L4.1 method named by
    # partition_gapfill_method (MDS here). The daytime variants fit measured NEE.
    # Daytime ONEFlux also reads that gap-filled NEE for windows without
    # measured nighttime NEE.
    # This LAE subset ships only gap-filled meteo, so the "measured" partition_ta
    # / partition_sw_in reuse the gap-filled columns (a real workflow points them
    # at the raw measured series).
    # To run one variant only, set partition_method='nighttime' or 'daytime'
    # with partition_mode='oneflux' (default) or 'reddyproc' instead of the flags.
    partition_nighttime_oneflux=True,
    partition_nighttime_reddyproc=True,
    partition_daytime_reddyproc=True,
    partition_daytime_oneflux=True,
    partition_gapfill_method='mds',
    partition_ta='TA_T1_47_1_gfXG',          # measured TA (stand-in: gap-filled)
    partition_sw_in='SW_IN_T1_47_1_gfXG',    # measured SW_IN (stand-in: gap-filled)
    partition_ta_f='TA_T1_47_1_gfXG',        # gap-filled TA
    partition_sw_in_f='SW_IN_T1_47_1_gfXG',  # gap-filled SW_IN
    partition_vpd_f='VPD_kPa',               # gap-filled VPD (kPa, registered above)
)

Step 4 — run the chain

One call drives every level. Each per-level callable underneath stays exactly the same as what the composable example invokes by hand; run_chain just routes the FluxConfig fields to them.

data = run_chain(data, cfg)
print(f"\nlevels run: {data.level_ids}")
print(data.summary())
─────────────────────── run_chain: full pipeline for FC ────────────────────────
─────────────────────── Level 2: Quality Flag Expansion ────────────────────────
  > SSITC TEST: Generated new flag variable FLAG_L2_FC_SSITC_TEST, values taken
from output variable FC_SSITC_TEST ...
  > FLUX BASE VARIABLE COMPLETENESS TEST: Generated new flag variable
FLAG_L2_FC_COMPLETENESS_TEST, newly calculated from variable CO2, with flag 0
(good values) where available number of records for CO2 >= 0.99, flag 1 (ok
values) >= 0.97 and < 0.99, flag 2 (bad values) < 0.97...
  > SPECTRAL CORRECTION FACTOR TEST: Generating new flag variable
FLAG_L2_FC_SCF_TEST, newly calculated from output variable FC_SCF, with flag 0
(good values) where FC_SCF < 2, flag 1 (ok values) where FC_SCF >= 2 and < 4,
flag 2 (bad values) where FC_SCF >= 4...
  > SIGNAL STRENGTH TEST: Generating new flag variable
FLAG_L2_FC_SIGNAL_STRENGTH_TEST, newly calculated from output variable
CUSTOM_SIGNAL_STRENGTH_IRGA72_MEAN, with flag 0 (good values) where
CUSTOM_SIGNAL_STRENGTH_IRGA72_MEAN >= 60, flag 2 (bad values) where
CUSTOM_SIGNAL_STRENGTH_IRGA72_MEAN < 60 ...
  > RAW DATA TEST: Generated new flag variable
FLAG_L2_FC_CO2_VM97_SPIKE_HF_TEST, values taken from output variable
CO2_VM97_TEST from position 1, based on CO2, with flag 0 (good values) where
test passed, flag 2 (bad values) where test failed (for hard flags) or flag 1
(ok values) where test failed (for soft flags) ...
  > RAW DATA TEST: Generated new flag variable
FLAG_L2_FC_CO2_VM97_DROPOUT_HF_TEST, values taken from output variable
CO2_VM97_TEST from position 3, based on CO2, with flag 0 (good values) where
test passed, flag 2 (bad values) where test failed (for hard flags) or flag 1
(ok values) where test failed (for soft flags) ...
──────────────────────── Level 3.1: Storage Correction ─────────────────────────
  > Calculating storage-corrected flux NEE_L3.1 from flux FC + storage term
SC_SINGLE
  > ++Added flag column FLAG_L3.2_NEE_L3.1_QCF_OUTLIER_HAMPEL_TEST to flag data
──────────────────── Level 3.2: Stepwise Outlier Detection ─────────────────────
────────────────────────── Level 3.3: USTAR Filtering ──────────────────────────
───────────────────────── Level 4.1: Gap-Filling (MDS) ─────────────────────────
─────────────────────── Level 4.1: Gap-Filling (XGBoost) ───────────────────────
─────── Level 4.2: NEE Partitioning (Nighttime ONEFlux, Reichstein 2005) ───────
  ! Nighttime partitioning: no short-term E0; using full-year E0.
  ! Nighttime partitioning: no well-constrained short-term E0; year left
unpartitioned (ONEFlux parity).
────── Level 4.2: NEE Partitioning (Nighttime REddyProc, Reichstein 2005) ──────
  ! Nighttime partitioning (ReddyProc): fewer than 3 well-constrained short-term
E0 estimates; record left unpartitioned (REddyProc abort, code -111).
──────── Level 4.2: NEE Partitioning (Daytime REddyProc, Lasslop 2010) ─────────
  ! Daytime partitioning (ReddyProc): too few nighttime E0 estimates (1
windows); record left unpartitioned.
───────── Level 4.2: NEE Partitioning (Daytime ONEFlux, Lasslop 2010) ──────────

levels run: ['L2', 'L3.1', 'L3.2', 'L3.3', 'L4.1', 'L4.2']
Data availability summary  —  flux: 'FC'
Site: lat=47.478333, lon=8.364389, UTC+1
QCF thresholds: daytime accept QCF < 2  |  nighttime accept QCF < 2
  (QCF=0: all tests pass; QCF=1: soft warnings; QCF=2: hard failure)
Total records: 1440
  Daytime records:    946
  Nighttime records:  494

  L2  (after QC flags)               1101 valid ( 76.5%)  |  day:   776  night:   325
  L2  (QCF=0 only, high-quality)      545 valid ( 37.8%)  |  day:   428  night:   117
  L3.1 (storage-corrected)           1101 valid ( 76.5%)  |  day:   776  night:   325
  L3.2 (outlier-cleaned)             1089 valid ( 75.6%)  |  day:   769  night:   320
  L3.3 USTAR=CUT_50                   945 valid ( 65.6%)  |  day:   697  night:   248
  L3.3 USTAR=CUT_50 (QCF=0 only)      510 valid ( 35.4%)  |  day:   402  night:   108

Gap-filling (L4.1)  [measured / gap-filled / fallback]:
  mds CUT_50      total:   945  |  measured:   945  |  gap-filled:     0 (0.0%)
  xgb CUT_50      total:  1440  |  measured:   945  |  gap-filled:   495 (34.4%)

Partitioning (L4.2)  [RECO / GPP valid records]:
  nt_of CUT_50      RECO:     0  |  GPP:     0
  nt_rp CUT_50      RECO:     0  |  GPP:     0
  dt_rp CUT_50      RECO:     0  |  GPP:     0
  dt_of CUT_50      RECO:  1440  |  GPP:  1440

fpc_df columns (73): FC, USTAR, SW_IN_POT, DAYTIME, NIGHTTIME, FLAG_L2_FC_MISSING_TEST, FLAG_L2_FC_SSITC_TEST, FLAG_L2_FC_COMPLETENESS_TEST, FLAG_L2_FC_SCF_TEST, FLAG_L2_FC_SIGNAL_STRENGTH_TEST, FLAG_L2_FC_CO2_VM97_SPIKE_HF_TEST, FLAG_L2_FC_CO2_VM97_DROPOUT_HF_TEST, SUM_L2_FC_HARDFLAGS, SUM_L2_FC_SOFTFLAGS, SUM_L2_FC_FLAGS, FLAG_L2_FC_QCF, FC_L2_QCF, FC_L2_QCF0, SC_SINGLE, SC_SINGLE_gfRMED_L3.1, FLAG_SC_SINGLE_gfRMED_L3.1_ISFILLED, NEE_L3.1, SUM_L3.1_NEE_HARDFLAGS, SUM_L3.1_NEE_SOFTFLAGS, SUM_L3.1_NEE_FLAGS, FLAG_L3.1_NEE_QCF, NEE_L3.1_QCF, NEE_L3.1_QCF0, FLAG_L3.2_NEE_L3.1_QCF_OUTLIER_HAMPEL_TEST, SUM_L3.2_NEE_L3.1_HARDFLAGS, SUM_L3.2_NEE_L3.1_SOFTFLAGS, SUM_L3.2_NEE_L3.1_FLAGS, FLAG_L3.2_NEE_L3.1_QCF, NEE_L3.1_L3.2_QCF, NEE_L3.1_L3.2_QCF0, FLAG_L3.3_CUT_50_NEE_L3.1_USTAR_TEST, SUM_L3.3_CUT_50_NEE_L3.1_HARDFLAGS, SUM_L3.3_CUT_50_NEE_L3.1_SOFTFLAGS, SUM_L3.3_CUT_50_NEE_L3.1_FLAGS, FLAG_L3.3_CUT_50_NEE_L3.1_QCF, NEE_L3.1_L3.3_CUT_50_QCF, NEE_L3.1_L3.3_CUT_50_QCF0, NEE_L3.1_L3.3_CUT_50_QCF_gfMDS, FLAG_NEE_L3.1_L3.3_CUT_50_QCF_gfMDS_ISFILLED, NEE_L3.1_L3.3_CUT_50_QCF_gfXG, FLAG_NEE_L3.1_L3.3_CUT_50_QCF_gfXG_ISFILLED, NEE_NIGHT_OF_CUT_50, RECO_NT_OF_CUT_50, RECO_NT_OF_ROB_CUT_50, GPP_NT_OF_CUT_50, GPP_NT_OF_ROB_CUT_50, RREF_NT_OF_CUT_50, E0_NT_OF_CUT_50, NEE_NIGHT_RP_CUT_50, RECO_NT_RP_CUT_50, GPP_NT_RP_CUT_50, RREF_NT_RP_CUT_50, E0_NT_RP_CUT_50, RECO_DT_RP_CUT_50, GPP_DT_RP_CUT_50, K_DT_RP_CUT_50, BETA_DT_RP_CUT_50, ALPHA_DT_RP_CUT_50, RREF_DT_RP_CUT_50, E0_DT_RP_CUT_50, RECO_DT_OF_CUT_50, GPP_DT_OF_CUT_50, SE_GPP_DT_OF_CUT_50, ALPHA_DT_OF_CUT_50, BETA_DT_OF_CUT_50, K_DT_OF_CUT_50, RREF_DT_OF_CUT_50, E0_DT_OF_CUT_50

Step 5 — gap-filled columns

gapfilled_cols() returns {method: {ustar_scenario: column_name}}. This is the canonical way to discover which columns in fpc_df hold the gap-filled flux — no need to dig through model instances.

cols = data.gapfilled_cols()
print(f"\nGap-filled columns: {cols}")
Gap-filled columns: {'mds': {'CUT_50': 'NEE_L3.1_L3.3_CUT_50_QCF_gfMDS'}, 'xgb': {'CUT_50': 'NEE_L3.1_L3.3_CUT_50_QCF_gfXG'}}

Step 6 — partitioning columns (L4.2)

partitioned_cols() is the L4.2 analogue of gapfilled_cols(): it returns {variant: {ustar_scenario: [column, ...]}} for the GPP / RECO and fitted-parameter columns each partitioning variant added to fpc_df. The fitted instances live under data.levels.level42_<variant>[scenario].

part_cols = data.partitioned_cols()
for variant, scen_cols in part_cols.items():
    for scen, names in scen_cols.items():
        print(f"L4.2 {variant} {scen}: {names}")
L4.2 nt_of CUT_50: ['NEE_NIGHT_OF_CUT_50', 'RECO_NT_OF_CUT_50', 'RECO_NT_OF_ROB_CUT_50', 'GPP_NT_OF_CUT_50', 'GPP_NT_OF_ROB_CUT_50', 'RREF_NT_OF_CUT_50', 'E0_NT_OF_CUT_50']
L4.2 nt_rp CUT_50: ['NEE_NIGHT_RP_CUT_50', 'RECO_NT_RP_CUT_50', 'GPP_NT_RP_CUT_50', 'RREF_NT_RP_CUT_50', 'E0_NT_RP_CUT_50']
L4.2 dt_rp CUT_50: ['RECO_DT_RP_CUT_50', 'GPP_DT_RP_CUT_50', 'K_DT_RP_CUT_50', 'BETA_DT_RP_CUT_50', 'ALPHA_DT_RP_CUT_50', 'RREF_DT_RP_CUT_50', 'E0_DT_RP_CUT_50']
L4.2 dt_of CUT_50: ['RECO_DT_OF_CUT_50', 'GPP_DT_OF_CUT_50', 'SE_GPP_DT_OF_CUT_50', 'ALPHA_DT_OF_CUT_50', 'BETA_DT_OF_CUT_50', 'K_DT_OF_CUT_50', 'RREF_DT_OF_CUT_50', 'E0_DT_OF_CUT_50']

Step 7 — side-by-side comparison plots

plot_gapfilled_heatmaps shows the measured series plus one heatmap panel per gap-filling method, all on a shared colour scale. plot_cumulative_comparison overlays the cumulative sums on a single axis so you can see how much the methods diverge over the period.

Both helpers default to showplot=True; pass showplot=False for headless / batch use.

data.plot_gapfilled_heatmaps(ustar_scenario='CUT_50', showplot=False)
data.plot_cumulative_comparison(
    ustar_scenario='CUT_50',
    conv_factor=12.011 * 1e-6 * 1800,  # umol CO2 m-2 s-1 -> gC m-2 (per 30-min record)
    units='gC m-2',
    showplot=False,
)
  • Gap-filled flux heatmaps  --  FC  |  USTAR scenario: CUT_50, Before gap-filling  (CUT_50), MDS  (CUT_50), XGBoost  (CUT_50)
  • Cumulative gap-filled flux  --  FC  |  USTAR scenario: CUT_50

Bootstrap USTAR — drop-in alternative

Replace ustar_thresholds/ustar_labels with the bootstrap-mode fields to have the chain detect USTAR thresholds from the data using the FLUXNET-standard multi-year bootstrap (ONEFlux moving-point method). Three scenarios (CUT_16 / CUT_50 / CUT_84) are produced by default; the fitted detector lands on data.levels.ustar_detection for post-hoc inspection. run_chain applies the constant (CUT) threshold; for per-year VUT filtering use the composable run_level33_ustar_detection(..., mode='vut').

Not run here to keep the example fast:

cfg_boot = FluxConfig(
    fluxcol='FC',
    ustar_detection_mode='bootstrap',
    ustar_bootstrap_ta_col='TA_T1_47_1_gfXG',
    ustar_bootstrap_swin_col='SW_IN_T1_47_1_gfXG',
    ustar_bootstrap_n_iter=100,
    ustar_bootstrap_percentiles=(16, 50, 84),
    outlier_sigma_daytime=5.5,
    outlier_sigma_nighttime=5.5,
    level2_test_settings={'ssitc': {'apply': True, 'setflag_timeperiod': None}},
    mds_swin='SW_IN_T1_47_1_gfXG',
    mds_ta='TA_T1_47_1_gfXG',
    mds_vpd='VPD_kPa',
    gapfilling_features=['TA_T1_47_1_gfXG', 'SW_IN_T1_47_1_gfXG', 'VPD_kPa'],
)
data_boot = run_chain(init_flux_data(df, ...), cfg_boot)
print(data_boot.levels.ustar_detection.summary())

When to drop down to the composable API

run_chain is intentionally simple — it ships fixed defaults for every per-detector / per-model knob. Reach for the composable per-level callables (see postprocessingchain_composable.py) when you need:

  • a non-Hampel L3.2 detector (z-score rolling, abslim, manual removal), or a multi-step L3.2 pipeline

  • L3.3 diagnostic plotting (showplot=True) or a custom bootstrap detector class

  • L4.1 MDS tolerances (swin_tol / ta_tol / vpd_tol)

  • RF / XGBoost hyperparameters (n_estimators, max_depth, …)

  • a custom FeatureEngineer — use make_level41_engineer for a default that you can override piecewise

Total running time of the script: (0 minutes 2.255 seconds)

Gallery generated by Sphinx-Gallery