Gap-Filling Method Comparison

Compare three gap-filling methods: MDS, Random Forest, and XGBoost.

Demonstrates gap-filling workflow comparison with performance metrics and cumulative carbon flux visualization. Uses one month of data for fast execution.

Methods compared: - MDS: Meteorological similarity, no training required - Random Forest: Machine learning bagging approach - XGBoost: Machine learning gradient boosting approach

Gap-filling method comparison

This example demonstrates a complete gap-filling comparison workflow: 1. Load one month of example ecosystem flux data 2. Gap-fill using MDS method (meteorological similarity) 3. Gap-fill using Random Forest (machine learning - bagging) 4. Gap-fill using XGBoost (machine learning - boosting) 5. Compare results with performance metrics 6. Visualize cumulative carbon flux from all three methods

import time

import matplotlib.pyplot as plt
import pandas as pd

import diive as dv
from diive.core.ml.feature_engineer import FeatureEngineer

Load and prepare data

df_orig = dv.load_exampledata_parquet()
# Use May 2022 for fast example execution
df = df_orig.loc[(df_orig.index.year == 2022) & (df_orig.index.month == 5)].copy()

# Target and features
TARGET_COL = 'NEE_CUT_REF_orig'
MDS_FEATURES = ['Tair_f', 'Rg_f', 'VPD_f']
RF_FEATURES = ['Tair_f', 'Rg_f', 'VPD_f']

print("\n" + "=" * 80)
print("GAP-FILLING METHOD COMPARISON".center(80))
print("=" * 80)
print(f"Data period: {df.index.min().date()} to {df.index.max().date()}")
print(f"Total records: {len(df)}")
print(f"Missing values (gaps): {df[TARGET_COL].isnull().sum()}")
  > Loaded .parquet file
/home/docs/checkouts/diive/checkouts/latest/diive/configs/exampledata/exampledat
a_PARQUET_CH-DAV_FP2022.5_2013-2022_ID20230206154316_30MIN.parquet (0.050
seconds).

================================================================================
                         GAP-FILLING METHOD COMPARISON
================================================================================
Data period: 2022-05-01 to 2022-05-31
Total records: 1488
Missing values (gaps): 795

Method 1: MDS (Marginal Distribution Sampling)

MDS fills gaps using average flux from similar meteorological conditions. Advantages: No training required, fast. Disadvantages: May miss non-linear patterns. FluxMDS runs in its default mode='diive' (Vekuri et al. 2023 symmetric mean). Use mode='oneflux' for values that match ONEFlux bit for bit.

print("\n" + "-" * 80)
print("METHOD 1: MARGINAL DISTRIBUTION SAMPLING (MDS)".ljust(80))
print("-" * 80)

start_time = time.perf_counter()

mds = dv.gapfilling.FluxMDS(
    df=df,
    flux=TARGET_COL,
    ta='Tair_f',
    swin='Rg_f',
    vpd='VPD_f',
    vpd_in_kpa=False,  # VPD_f in the example data is in hPa: 0.5 kPa -> 5 hPa
    swin_tol=[20, 50],
    ta_tol=2.5,
    vpd_tol=0.5,
    avg_min_n_vals=5,
    verbose=0
)
mds.run()
mds_gapfilled = mds.get_gapfilled_target()
mds_time = time.perf_counter() - start_time

print(f"Execution time: {mds_time:.2f}s")
mds.report()
--------------------------------------------------------------------------------
METHOD 1: MARGINAL DISTRIBUTION SAMPLING (MDS)
--------------------------------------------------------------------------------
Execution time: 0.08s
─────────────────── MDS Gap-Filling Report: NEE_CUT_REF_orig ───────────────────
  Reference: ONEFlux marginal distribution sampling (Reichstein 2005 / Vekuri
2023)

  Algorithm: 6-stage expanding-window similarity cascade
    method 1 (SWIN+TA+VPD), 2 (SWIN only), 3 (diurnal cycle)
    flag = method*1000 + window (days); quality 1-3 collapses the window
────────────────────────────────── Parameters ──────────────────────────────────
  Flux variable          NEE_CUT_REF_orig
  SWIN tolerance         [20, 50] W m-2
  TA tolerance           2.5 deg C
  VPD tolerance          0.5 kPa
  Min samples for mean   5
  Mode                   diive
────────────────────────────── Data & Performance ──────────────────────────────
  Total records                 1,488
  Available before                693  (46.6%)
  Missing before                  795  (53.4%)
  Filled                          795  (100.0% of gaps)
  Remaining missing                 0  (0.0% of total)
  Final coverage                1,488  (100.0%)
  Mean quality (1-3)            1.056  (1 = tightest match)
───────────────────────────── Quality Distribution ─────────────────────────────
  Flag    Count        %    Description
  0         693    46.6%    measured
  1014      714    48.0%    SWIN, TA, VPD: 14 d window (quality 1)
  1028       28     1.9%    SWIN, TA, VPD: 28 d window (quality 2)
  2014       53     3.6%    SWIN only: 14 d window (quality 1)
─────────────────────────── Model Performance Scores ───────────────────────────
  Mae                                 2.7390
  Medae                               2.0650
  Mse                                 14.7553
  Rmse                                3.8413
  Mape                                0.9878
  Maxe                                21.6465
  R2                                  0.5966
  Mean Quality Flag Gap Predictions   1.0352

  Flag = method*1000 + window; quality 1-3 collapses the window (1 = tightest
match).

Method 2: Random Forest

Machine learning bagging approach. Uses identical feature engineering as XGBoost for fair comparison.

print("\n" + "-" * 80)
print("METHOD 2: RANDOM FOREST WITH FEATURE ENGINEERING".ljust(80))
print("-" * 80)

start_time = time.perf_counter()

# Prepare subset with target and RF features
df_rf = df[[TARGET_COL] + RF_FEATURES].copy()

# Create engineered features (production settings for CO2 flux)
engineer = FeatureEngineer(
    target_col=TARGET_COL,
    features_lag=[-2, -1],
    features_lag_stepsize=1,
    features_lag_exclude_cols=None,
    features_rolling=[2, 4, 12, 24, 48],
    features_rolling_exclude_cols=None,
    features_rolling_stats=['mean', 'median', 'min', 'max'],
    features_diff=[1, 2],
    features_diff_exclude_cols=None,
    features_ema=[6, 12, 24, 48],
    features_ema_exclude_cols=None,
    features_poly_degree=2,
    features_poly_exclude_cols=None,
    features_stl=False,
    features_stl_method='stl',
    features_stl_seasonal_period=None,
    features_stl_exclude_cols=None,
    features_stl_components=None,
    vectorize_timestamps=True,
    add_continuous_record_number=False,
    sanitize_timestamp=False
)
df_engineered = engineer.fit_transform(df_rf)

# Create and train RF model
rfts = dv.gapfilling.RandomForestTS(
    input_df=df_engineered,
    target_col=TARGET_COL,
    verbose=0,
    below_zero=None,  # How to treat negative predictions: None=keep, 'zero'=clip to 0
    # Use 'zero' or 'nan' for variables that cannot be negative (e.g. VPD, SW_IN, PPFD).
    # NEE can be negative (carbon uptake), so None is correct here.
    n_estimators=50,
    random_state=42,
    max_depth=None,
    min_samples_split=10,
    min_samples_leaf=5,
    n_jobs=-1
)

# Train model
rfts.trainmodel(showplot_scores=False, showplot_importance=False)

# Gap-fill
rfts.fillgaps(showplot_scores=False, showplot_importance=False)
rf_gapfilled = rfts.get_gapfilled_target()
rf_time = time.perf_counter() - start_time

print(f"Execution time: {rf_time:.2f}s")
rfts.report_gapfilling()
--------------------------------------------------------------------------------
METHOD 2: RANDOM FOREST WITH FEATURE ENGINEERING
--------------------------------------------------------------------------------
Execution time: 1.05s
───────────────────────────── GAP-FILLING RESULTS ──────────────────────────────

Scores and importances from predicted (793) vs observed (693) targets.

## TARGET
- period:  2022-05-01 00:15:00 to 2022-05-31 23:45:00
- potential values: 1488
- observed (NEE_CUT_REF_orig):  missing 795
- gap-filled (NEE_CUT_REF_orig_gfRF):  1488 values, missing 0
- flag FLAG_NEE_CUT_REF_orig_gfRF_ISFILLED:  0=observed (693)  1=gap-filled
(793)  2=fallback (2)

## FEATURE IMPORTANCES  (119 features, SHAP TreeExplainer)

               SHAP_IMPORTANCE   SHAP_SD
.Rg_f_POL2            1.668952  0.835846
Rg_f                  1.576770  0.835468
.Tair_f_DIFF1         0.737646  0.367638
.Tair_f_SD12          0.617646  0.394572
.Tair_f_DIFF2         0.146325  0.144444
...                        ...       ...
.SEASON_SIN           0.000000  0.000000
.YEAR                 0.000000  0.000000
.MONTH_SIN            0.000000  0.000000
.WEEK_COS             0.000000  0.000000
.YEARMONTH            0.000000  0.000000

[119 rows x 2 columns]

## MODEL  (test size 25.0%)
- estimator:  RandomForestRegressor(min_samples_leaf=5, min_samples_split=10,
n_estimators=50,
                      n_jobs=-1, random_state=42)
- parameters:  {'bootstrap': True, 'ccp_alpha': 0.0, 'criterion':
'squared_error', 'max_depth': None, 'max_features': 1.0, 'max_leaf_nodes': None,
'max_samples': None, 'min_impurity_decrease': 0.0, 'min_samples_leaf': 5,
'min_samples_split': 10, 'min_weight_fraction_leaf': 0.0, 'monotonic_cst': None,
'n_estimators': 50, 'n_jobs': -1, 'oob_score': False, 'random_state': 42,
'verbose': 0, 'warm_start': False}

## MODEL SCORES (in-sample: predicted on ALL data incl. training rows;
optimistically biased)
- MAE:   1.621686387801698 (mean absolute error)
- MedAE: 1.0732865182872686 (median absolute error)
- MSE:   6.67791891218918 (mean squared error)
- RMSE:  2.5841669667784974 (root mean squared error)
- MAXE:  18.72442138822289 (max error)
- MAPE:  0.465 (mean absolute percentage error)
- R2:    0.8174194804960631

## MODEL SCORES (out-of-sample: held-out test set, 25.0%; generalization
estimate)
- MAE:   2.426457868181828 (mean absolute error)
- MedAE: 1.7662137818847825 (median absolute error)
- MSE:   13.268147856392961 (mean squared error)
- RMSE:  3.6425468914473784 (root mean squared error)
- MAXE:  18.23183114035964 (max error)
- MAPE:  0.480 (mean absolute percentage error)
- R2:    0.6242294839254898

Method 3: XGBoost

Machine learning gradient boosting approach. Uses the same engineered features as Random Forest for fair comparison.

print("\n" + "-" * 80)
print("METHOD 3: XGBOOST WITH FEATURE ENGINEERING".ljust(80))
print("-" * 80)

start_time = time.perf_counter()

# Reuse engineered features from Random Forest (same features for fair comparison)
xgbts = dv.gapfilling.XGBoostTS(
    input_df=df_engineered,
    target_col=TARGET_COL,
    verbose=0,
    below_zero=None,  # How to treat negative predictions: None=keep, 'zero'=clip to 0
    # Use 'zero' or 'nan' for variables that cannot be negative (e.g. VPD, SW_IN, PPFD).
    # NEE can be negative (carbon uptake), so None is correct here.
    n_estimators=50,
    random_state=42,
    max_depth=6,
    learning_rate=0.1,
    early_stopping_rounds=10,
    n_jobs=-1
)

# Train model
xgbts.trainmodel(showplot_scores=False, showplot_importance=False)

# Gap-fill
xgbts.fillgaps(showplot_scores=False, showplot_importance=False)
xgb_gapfilled = xgbts.get_gapfilled_target()
xgb_time = time.perf_counter() - start_time

print(f"Execution time: {xgb_time:.2f}s")
xgbts.report_gapfilling()
--------------------------------------------------------------------------------
METHOD 3: XGBOOST WITH FEATURE ENGINEERING
--------------------------------------------------------------------------------
Execution time: 0.51s
───────────────────────────── GAP-FILLING RESULTS ──────────────────────────────

Scores and importances from predicted (793) vs observed (693) targets.

## TARGET
- period:  2022-05-01 00:15:00 to 2022-05-31 23:45:00
- potential values: 1488
- observed (NEE_CUT_REF_orig):  missing 795
- gap-filled (NEE_CUT_REF_orig_gfXG):  1488 values, missing 0
- flag FLAG_NEE_CUT_REF_orig_gfXG_ISFILLED:  0=observed (693)  1=gap-filled
(793)  2=fallback (2)

## FEATURE IMPORTANCES  (119 features, SHAP TreeExplainer)

               SHAP_IMPORTANCE   SHAP_SD
Rg_f                  3.348229  1.573636
.Tair_f_DIFF1         0.895526  0.468795
.Tair_f_SD12          0.415007  0.271453
.Rg_f-2               0.225155  0.331933
.Tair_f_SD24          0.201983  0.140042
...                        ...       ...
.WEEK_COS             0.000000  0.000000
.DOY_COS              0.000000  0.000000
.YEARMONTH            0.000000  0.000000
.YEARDOY              0.000000  0.000000
.YEARWEEK             0.000000  0.000000

[119 rows x 2 columns]

## MODEL  (test size 25.0%)
- estimator:  XGBRegressor(base_score=None, booster=None, callbacks=None,
             colsample_bylevel=None, colsample_bynode=None,
             colsample_bytree=None, device=None, early_stopping_rounds=10,
             enable_categorical=True, eval_metric=None, feature_types=None,
             feature_weights=None, gamma=None, grow_policy=None,
             importance_type=None, interaction_constraints=None,
             learning_rate=0.1, max_bin=None, max_cat_threshold=None,
             max_cat_to_onehot=None, max_delta_step=None, max_depth=6,
             max_leaves=None, min_child_weight=None, missing=nan,
             monotone_constraints=None, multi_strategy=None, n_estimators=50,
             n_jobs=-1, num_parallel_tree=None, ...)
- parameters:  {'objective': 'reg:squarederror', 'base_score': None, 'booster':
None, 'callbacks': None, 'colsample_bylevel': None, 'colsample_bynode': None,
'colsample_bytree': None, 'device': None, 'early_stopping_rounds': 10,
'enable_categorical': True, 'eval_metric': None, 'feature_types': None,
'feature_weights': None, 'gamma': None, 'grow_policy': None, 'importance_type':
None, 'interaction_constraints': None, 'learning_rate': 0.1, 'max_bin': None,
'max_cat_threshold': None, 'max_cat_to_onehot': None, 'max_delta_step': None,
'max_depth': 6, 'max_leaves': None, 'min_child_weight': None, 'missing': nan,
'monotone_constraints': None, 'multi_strategy': None, 'n_estimators': 50,
'n_jobs': -1, 'num_parallel_tree': None, 'random_state': 42, 'reg_alpha': None,
'reg_lambda': None, 'sampling_method': None, 'scale_pos_weight': None,
'subsample': None, 'tree_method': None, 'validate_parameters': None,
'verbosity': None}

## MODEL SCORES (in-sample: predicted on ALL data incl. training rows;
optimistically biased)
- MAE:   1.5121980743598282 (mean absolute error)
- MedAE: 1.0163027572631835 (median absolute error)
- MSE:   5.580908049120739 (mean squared error)
- RMSE:  2.3623945583074684 (root mean squared error)
- MAXE:  17.544220335006713 (max error)
- MAPE:  0.478 (mean absolute percentage error)
- R2:    0.8474127786948334

## MODEL SCORES (out-of-sample: held-out test set, 25.0%; generalization
estimate)
- MAE:   2.5640888778104864 (mean absolute error)
- MedAE: 1.8272821350097663 (median absolute error)
- MSE:   14.596446668716322 (mean squared error)
- RMSE:  3.820529631964176 (root mean squared error)
- MAXE:  17.544220335006713 (max error)
- MAPE:  0.475 (mean absolute percentage error)
- R2:    0.5866104028291474

Performance comparison

print("\n" + "=" * 80)
print("PERFORMANCE COMPARISON".center(80))
print("=" * 80)

comparison_data = {
    'Metric': ['Execution Time (s)', 'Training Required', 'Features Used', 'Approach'],
    'MDS': [f'{mds_time:.2f}', 'No', 'Meteorological', 'Similarity-based'],
    'Random Forest': [f'{rf_time:.2f}', 'Yes', 'Engineered (45+)', 'Bagging'],
    'XGBoost': [f'{xgb_time:.2f}', 'Yes', 'Engineered (45+)', 'Boosting']
}
print("\n" + pd.DataFrame(comparison_data).to_string(index=False))
================================================================================
                             PERFORMANCE COMPARISON
================================================================================

            Metric              MDS    Random Forest          XGBoost
Execution Time (s)             0.08             1.05             0.51
 Training Required               No              Yes              Yes
     Features Used   Meteorological Engineered (45+) Engineered (45+)
          Approach Similarity-based          Bagging         Boosting

Cumulative carbon flux comparison

Convert fluxes to carbon units and plot cumulative sums for all three methods.

print("\n" + "-" * 80)
print("CUMULATIVE CARBON FLUX VISUALIZATION".ljust(80))
print("-" * 80)

# Prepare cumulative data
observed = df[TARGET_COL]
df_cumulative = pd.DataFrame({
    'Observed': observed,
    'MDS': mds_gapfilled,
    'Random Forest': rf_gapfilled,
    'XGBoost': xgb_gapfilled
})

# Convert from umol CO2 m-2 s-1 to g C m-2 30min-1
df_cumulative = df_cumulative.multiply(0.02161926)
series_units = r'($\mathrm{gC\ m^{-2}}$)'

# Create cumulative plot
dv.plotting.Cumulative(
    df=df_cumulative,
    units=series_units,
    start_year=2022,
    end_year=2022
).plot()
Cumulatives (2022-05-01 00:15:00-2022-05-31 23:45:00)
--------------------------------------------------------------------------------
CUMULATIVE CARBON FLUX VISUALIZATION
--------------------------------------------------------------------------------

<Axes: xlabel='Date', ylabel='Cumulative ($\\mathrm{gC\\ m^{-2}}$)'>

Time series heatmap comparison

print("\n" + "-" * 80)
print("TIME SERIES HEATMAP COMPARISON".ljust(80))
print("-" * 80)

fig, axes = plt.subplots(1, 4, figsize=(28, 5),
                         gridspec_kw={'wspace': 0.12},
                         constrained_layout=True)

# Observed
dv.plotting.HeatmapDateTime(series=observed).plot(ax=axes[0])
axes[0].set_title('Observed\n(with gaps)', fontsize=11, fontweight='bold')

# MDS gap-filled
dv.plotting.HeatmapDateTime(series=mds_gapfilled).plot(ax=axes[1])
axes[1].set_title('MDS\nGap-Filled', fontsize=11, fontweight='bold')

# RF gap-filled
dv.plotting.HeatmapDateTime(series=rf_gapfilled).plot(ax=axes[2])
axes[2].set_title('Random Forest\nGap-Filled', fontsize=11, fontweight='bold')

# XGB gap-filled
dv.plotting.HeatmapDateTime(series=xgb_gapfilled).plot(ax=axes[3])
axes[3].set_title('XGBoost\nGap-Filled', fontsize=11, fontweight='bold')

fig.suptitle('Gap-Filling Method Comparison', fontsize=13, fontweight='bold', y=1.00)
plt.show()

print("[OK] Gap-filling method comparison complete.")
Gap-Filling Method Comparison, Observed (with gaps), MDS Gap-Filled, Random Forest Gap-Filled, XGBoost Gap-Filled
--------------------------------------------------------------------------------
TIME SERIES HEATMAP COMPARISON
--------------------------------------------------------------------------------
[OK] Gap-filling method comparison complete.

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

Gallery generated by Sphinx-Gallery