Note
Go to the end to download the full example code.
Marginal Distribution Sampling (MDS)¶
Gap-fill time series using Marginal Distribution Sampling.
MDS fills gaps by using the average flux value during similar meteorological conditions (radiation, temperature, vapor pressure deficit). Uses a hierarchical quality-based approach with progressively relaxed meteorological similarity windows.
Best for: Ecosystem flux gap-filling when ML training data is unavailable or when physical similarity-based reconstruction is preferred over statistical learning.
References:
Reichstein et al. (2005). On the separation of net ecosystem exchange into assimilation and ecosystem respiration. Global Change Biology, 11(9), 1424-1439. https://doi.org/10.1111/j.1365-2486.2005.001002.x
Vekuri et al. (2023). A widely-used eddy covariance gap-filling method creates systematic bias in carbon balance estimates. Scientific Reports, 13(1), 1720. https://doi.org/10.1038/s41598-023-28827-2
Overview: Marginal Distribution Sampling (MDS)¶
MDS is an unsupervised gap-filling method that finds periods with similar meteorological conditions and uses their mean flux as the gap-filled value.
Why MDS? - No training/validation data required (unsupervised) - Fast execution - Physically meaningful (based on meteorological similarity) - No overfitting risk - Widely used in FLUXNET, ICOS, REddyProc
How it works (a port of the ONEFlux gf_mds cascade):
For each gap, look for similar meteorological conditions
Similarity defined by: radiation (Rg), temperature (Ta), VPD
Relax step by step: all three drivers in a 14-day, then a 28-day window; Rg only in 14 days; the mean diurnal cycle (same time of day +/- 1 h) over 1-5 days; the drivers again in windows up to 154 days; finally the diurnal cycle in ever wider windows
Fill gap with mean flux from similar periods
Three modes:
mode='diive'(default): ONEFlux’s windows, tolerances and order of methods, but methods 1 and 2 (the ones that match on Rg) fill with the symmetric mean of Vekuri et al. (2023). The similar records are split into those with less and those with more Rg than the gap record, and the fill is the mean of the two group means. This removes a bias that appears when Rg is spread unevenly inside the tolerance. It applies to daytime records only (Rg >= 20 W m-2), as in the paper.mode='oneflux': the plain mean of the similar records. This reproduces ONEFlux’sgf_mdsbit for bit. Use it when results must match ONEFlux, for example in a comparison with FLUXNET or ICOS data products.mode='reddyproc': the plain mean with REddyProc’s windows. This reproduces REddyProc’ssMDSGapFill. Gaps longer than 60 days stay unfilled.
Flag and quality:
The gap-fill flag is method * 1000 + window in days (0 = measured), with method 1 = Rg+Ta+VPD, 2 = Rg only, 3 = diurnal cycle. For example, 1014 means all three drivers in a 14-day window.
The ONEFlux quality (1-3, 1 = best) condenses method and window; the report lists both.
import time
import matplotlib.pyplot as plt
import numpy as np
import diive as dv
from diive.gapfilling.mds import mds_quality_description
Load and prepare data¶
df = dv.load_exampledata_parquet()
# Example: Use full year 2022 (realistic scenario with large gaps)
# Note: Takes longer to process; comment out to use July subset below
print("Loading example data (2022)...")
df_full_year = df.loc[df.index.year == 2022].copy()
# Select high-quality data only (filter by QCF flag)
print("Filtering data by quality flag (QCF=0 only)...")
target_col = 'NEE_CUT_REF_orig'
df_full_year.loc[df_full_year['QCF_NEE'] > 0, target_col] = np.nan
print(f"Data summary:")
print(f" Period: {df_full_year.index.min().date()} to {df_full_year.index.max().date()}")
print(f" Total records: {len(df_full_year)}")
print(f" Available NEE: {df_full_year[target_col].notna().sum()}")
print(
f" Missing NEE: {df_full_year[target_col].isna().sum()} ({100 * df_full_year[target_col].isna().sum() / len(df_full_year):.1f}%)")
# Use faster subset for demonstration (comment this out for full-year analysis)
print("\nUsing July subset for faster execution (comment out for full year)...")
df = df_full_year.loc[(df_full_year.index.month == 7)].copy()
print(f"Using data: {len(df)} records")
print(f" Available NEE: {df[target_col].notna().sum()}")
print(f" Missing NEE: {df[target_col].isna().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).
Loading example data (2022)...
Filtering data by quality flag (QCF=0 only)...
Data summary:
Period: 2022-01-01 to 2022-12-31
Total records: 17520
Available NEE: 4438
Missing NEE: 13082 (74.7%)
Using July subset for faster execution (comment out for full year)...
Using data: 1488 records
Available NEE: 564
Missing NEE: 924
MDS setup and configuration¶
Configure meteorological variables and similarity tolerances. CRITICAL: Variables must be in correct units!
# Flux and meteorological variables
flux_col = 'NEE_CUT_REF_orig' # Flux variable to gap-fill
ta_col = 'Tair_f' # Air temperature (in C)
swin_col = 'Rg_f' # Short-wave radiation (in W/m2)
vpd_col = 'VPD_f' # Vapor pressure deficit (in hPa in this dataset)
# MDS tolerance parameters
swin_tol = [20, 50] # W/m2: low radiation 20, high radiation 50
ta_tol = 2.5 # C: temperature tolerance
vpd_tol = 0.5 # kPa: VPD tolerance (convert from hPa)
avg_min_n_vals = 5 # Min flux values needed to calculate average
print("MDS Configuration:")
print(f" Flux column: {flux_col}")
print(f" Ta tolerance: +or- {ta_tol} C")
print(f" Rg tolerance: low={swin_tol[0]}, high={swin_tol[1]} W/m2")
print(f" VPD tolerance: +or- {vpd_tol} kPa")
print(f" Min values for average: {avg_min_n_vals}")
# Convert VPD from hPa to kPa
df[vpd_col] = df[vpd_col] * 0.1
MDS Configuration:
Flux column: NEE_CUT_REF_orig
Ta tolerance: +or- 2.5 C
Rg tolerance: low=20, high=50 W/m2
VPD tolerance: +or- 0.5 kPa
Min values for average: 5
Run MDS gap-filling¶
print("\nStarting MDS gap-filling...")
start_time = time.perf_counter()
mds = dv.gapfilling.FluxMDS(
df=df,
flux=flux_col,
ta=ta_col,
swin=swin_col,
vpd=vpd_col,
swin_tol=swin_tol,
ta_tol=ta_tol,
vpd_tol=vpd_tol,
avg_min_n_vals=avg_min_n_vals,
mode='diive', # the default, written out here
verbose=1
)
mds.run()
elapsed_time = time.perf_counter() - start_time
print(f"Execution time: {elapsed_time:.2f} seconds")
Starting MDS gap-filling...
Execution time: 0.09 seconds
Results: Gap-filling report¶
print("\n" + "=" * 70)
print("MDS GAP-FILLING RESULTS")
print("=" * 70)
mds.report()
======================================================================
MDS GAP-FILLING RESULTS
======================================================================
─────────────────── 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 564 (37.9%)
Missing before 924 (62.1%)
Filled 924 (100.0% of gaps)
Remaining missing 0 (0.0% of total)
Final coverage 1,488 (100.0%)
Mean quality (1-3) 1.115 (1 = tightest match)
───────────────────────────── Quality Distribution ─────────────────────────────
Flag Count % Description
0 564 37.9% measured
1014 724 48.7% SWIN, TA, VPD: 14 d window (quality 1)
1028 90 6.0% SWIN, TA, VPD: 28 d window (quality 2)
1042 5 0.3% SWIN, TA, VPD: 42 d window (quality 2)
1056 2 0.1% SWIN, TA, VPD: 56 d window (quality 2)
2014 95 6.4% SWIN only: 14 d window (quality 1)
3003 6 0.4% diurnal cycle: 3 d window (quality 2)
3005 2 0.1% diurnal cycle: 5 d window (quality 2)
─────────────────────────── Model Performance Scores ───────────────────────────
Mae 2.3726
Medae 1.8471
Mse 9.5646
Rmse 3.0927
Mape 0.6573
Maxe 12.2919
R2 0.7054
Mean Quality Flag Gap Predictions 1.1136
Flag = method*1000 + window; quality 1-3 collapses the window (1 = tightest
match).
Results: Performance scores¶
Scores compare MDS predictions at measured records with the measured values. In the default mode=’diive’ each measured record is left out of its own prediction, so the scores are out-of-sample. In mode=’oneflux’ and mode=’reddyproc’ they are in-sample and usually higher.
print("\nPerformance Scores (out-of-sample):")
print(f" R2: {mds.scores_['r2']:.4f}")
print(f" RMSE: {mds.scores_['rmse']:.4f} (root mean squared error)")
print(f" MAE: {mds.scores_['mae']:.4f} (mean absolute error)")
print(f" Median AE: {mds.scores_['medae']:.4f}")
print(f" Max Error: {mds.scores_['maxe']:.4f}")
print(f" Mean quality flag: {mds.scores_['mean_quality_flag_gap_predictions']:.2f} (lower=better)")
Performance Scores (out-of-sample):
R2: 0.7054
RMSE: 3.0927 (root mean squared error)
MAE: 2.3726 (mean absolute error)
Median AE: 1.8471
Max Error: 12.2919
Mean quality flag: 1.11 (lower=better)
Results: Quality flag analysis¶
Understand how many gaps were filled at each flag value (method * 1000 + window in days, see above)
gf_df = mds.gapfilling_df_
flag_col = [c for c in gf_df.columns if 'FLAG' in c and 'FILLED' in c][0]
print("\nGap-filling quality distribution:")
quality_counts = gf_df[flag_col].value_counts().sort_index()
for quality_level, count in quality_counts.items():
if quality_level == 0:
label = "Measured (not gap-filled)"
else:
label = mds_quality_description(quality_level)
percent = 100 * count / len(gf_df)
print(f" {label:.<40} {count:>6} ({percent:>5.1f}%)")
Gap-filling quality distribution:
Measured (not gap-filled)............... 564 ( 37.9%)
SWIN, TA, VPD: 14 d window (quality 1).. 724 ( 48.7%)
SWIN, TA, VPD: 28 d window (quality 2).. 90 ( 6.0%)
SWIN, TA, VPD: 42 d window (quality 2).. 5 ( 0.3%)
SWIN, TA, VPD: 56 d window (quality 2).. 2 ( 0.1%)
SWIN only: 14 d window (quality 1)...... 95 ( 6.4%)
diurnal cycle: 3 d window (quality 2)... 6 ( 0.4%)
diurnal cycle: 5 d window (quality 2)... 2 ( 0.1%)
Visualization: Time series comparison¶
Compare original (with gaps) vs gap-filled
print("\nGenerating visualizations...")
# Get original and gap-filled series
original_col = flux_col
gapfilled_col = mds.target_gapfilled
# Plot time series
fig, ax = plt.subplots(figsize=(14, 6))
ax.plot(gf_df.index, gf_df[original_col], 'k-', alpha=0.5, linewidth=1, label='Measured')
ax.plot(gf_df.index, gf_df[gapfilled_col], 'b-', alpha=0.7, linewidth=1, label='Gap-filled')
ax.set_xlabel('Date')
ax.set_ylabel('NEE (umol/m2/s)')
ax.set_title('MDS Gap-Filling: Measured vs Gap-Filled NEE')
ax.legend()
ax.grid(True, alpha=0.3)
plt.tight_layout()
fig.show()

Generating visualizations...
Visualization: Cumulative flux¶
fig, ax = plt.subplots(figsize=(14, 6))
ax.plot(gf_df.index, gf_df[original_col].cumsum(), 'k-', alpha=0.5, linewidth=1.5, label='Measured (incomplete)')
ax.plot(gf_df.index, gf_df[gapfilled_col].cumsum(), 'b-', alpha=0.7, linewidth=1.5, label='Gap-filled (complete)')
ax.set_xlabel('Date')
ax.set_ylabel('Cumulative NEE (umol/m2/s)')
ax.set_title('Cumulative Flux: Impact of Gap-Filling')
ax.legend()
ax.grid(True, alpha=0.3)
plt.tight_layout()
fig.show()

Visualization: Heatmap comparison¶
fig, axes = plt.subplots(1, 2, figsize=(16, 6))
hm_original = dv.plotting.HeatmapDateTime(series=gf_df[original_col])
hm_original.plot(
ax=axes[0],
format_style=dv.plotting.FormatStyle(title='Original NEE (with gaps)')
)
hm_gapfilled = dv.plotting.HeatmapDateTime(series=gf_df[gapfilled_col])
hm_gapfilled.plot(
ax=axes[1],
format_style=dv.plotting.FormatStyle(title='Gap-filled NEE (complete)')
)
plt.tight_layout()
fig.show()

Compare the two modes on one year¶
Fill the full year 2022 once with each mode, with ONEFlux’s default
tolerances. Only gaps filled by method 1 or 2 during daytime can differ.
VPD is still in hPa in df_full_year, so vpd_in_kpa=False tells
FluxMDS to scale its tolerance instead of the data.
filled = {}
for mode in ['diive', 'oneflux']:
m = dv.gapfilling.FluxMDS(df=df_full_year, flux=flux_col, ta=ta_col, swin=swin_col,
vpd=vpd_col, vpd_in_kpa=False, mode=mode, verbose=0)
m.run()
filled[mode] = m.gapfilling_df_[m.target_gapfilled]
isgap = df_full_year[flux_col].isna()
diff = (filled['diive'] - filled['oneflux'])[isgap]
differs = diff.abs() > 0
# umol CO2 m-2 s-1 per half-hour -> g C m-2: 1800 s * 12.011 g C mol-1 * 1e-6
to_gc = 1800 * 12.011e-6
sum_diive = filled['diive'].sum() * to_gc
sum_oneflux = filled['oneflux'].sum() * to_gc
print("\nMDS mode 'diive' vs 'oneflux' (2022):")
print(f" Gap records: {isgap.sum()}")
print(f" Filled values that differ: {differs.sum()} ({100 * differs.sum() / isgap.sum():.1f}% of gaps)")
print(f" Mean difference where they differ: {diff[differs].mean():.3f} umol m-2 s-1")
print(f" Largest absolute difference: {diff.abs().max():.3f} umol m-2 s-1")
print(f" Annual NEE, mode='diive': {sum_diive:.1f} g C m-2")
print(f" Annual NEE, mode='oneflux': {sum_oneflux:.1f} g C m-2")
print(f" Difference (diive - oneflux): {sum_diive - sum_oneflux:.1f} g C m-2")
print("\n[OK] MDS gap-filling demonstration complete")
MDS mode 'diive' vs 'oneflux' (2022):
Gap records: 13082
Filled values that differ: 3178 (24.3% of gaps)
Mean difference where they differ: -0.117 umol m-2 s-1
Largest absolute difference: 4.451 umol m-2 s-1
Annual NEE, mode='diive': -30.5 g C m-2
Annual NEE, mode='oneflux': -22.5 g C m-2
Difference (diive - oneflux): -8.0 g C m-2
[OK] MDS gap-filling demonstration complete
Total running time of the script: (0 minutes 2.087 seconds)