High-Quality Flux Analysis with Hampel Filtering

Robust outlier detection for CO2 flux using Hampel filter with day/night separation.

Demonstrates robust outlier detection for CO2 flux (NEE) using the Hampel filter (Median Absolute Deviation) with automatic day/night separation based on solar geometry. The Hampel method is ideal for removing measurement spikes while preserving ecosystem signal.

Best for: Identifying and removing measurement spikes in CO2 flux data.

Load and prepare CO2 flux data

Load example eddy covariance data and select records with good quality flags.

from diive.configs.exampledata import load_exampledata_parquet_cha
from diive.flux.lowres.hqflux import analyze_highest_quality_flux

df = load_exampledata_parquet_cha()
keeprows = df['FC_SSITC_TEST'] == 0
df = df[keeprows].copy()
flux_fc = df['FC'].copy()

print("=" * 80)
print("Data Summary")
print("=" * 80)
print(f"\nData: {flux_fc.name}")
print(f"Period: {flux_fc.index.min().date()} to {flux_fc.index.max().date()}")
print(f"Total records: {len(flux_fc)}")
print(f"Valid records: {flux_fc.count()}")
print(f"Missing: {flux_fc.isnull().sum()} ({flux_fc.isnull().sum() / len(flux_fc) * 100:.1f}%)")
  > Loaded .parquet file
/home/docs/checkouts/diive/checkouts/latest/diive/configs/exampledata/exampledat
a_PARQUET_CH-CHA_FP2025.3_subset_30MIN.parquet (0.026 seconds).
================================================================================
Data Summary
================================================================================

Data: FC
Period: 2015-01-01 to 2015-12-31
Total records: 5665
Valid records: 5665
Missing: 0 (0.0%)

Apply Hampel filter with day/night separation

Run high-quality flux analysis using Hampel filter (Median Absolute Deviation). Automatically separates daytime and nighttime using solar elevation angle, with separate strictness thresholds for each period.

results = analyze_highest_quality_flux(
    flux=flux_fc,
    lat=47.210222,  # CH-CHA tower (Swiss FluxNet site page, WGS84)
    lon=8.410444,
    utc_offset=1,  # CET
    window_length=48 * 13,  # 13 days at 30-min frequency
    n_sigma_daytime=5.5,
    n_sigma_nighttime=5.5,
    use_differencing=True,  # Papale method: isolate spikes from trends
    showplot=True
)
  • FC filtered by FLAG_FC_OUTLIER_HAMPEL_TEST, n_iterations = 1, n_outliers = 19
  • Hampel filter daytime/nighttime: FC, n_iterations = 1, n_outliers = 19
  • Highest-quality fluxes FC after Hampel outlier removal
  >
>>> Removing outliers from highest-quality fluxes (FC)
  > >>> Outlier removal method: Hampel filter (MAD-based)
  > >>> Parameters: window_length=624, n_sigma_daytime=5.5,
n_sigma_nighttime=5.5, use_differencing=True
  > Detect frequency: 30min (timedelta, 67% match)
  > Regularize gaps: OK
  [Dt/Nt] ITER #01 | Outliers:    19 (  0.34%) | Day:    15 | Night:     4
  >
>>> Outlier Detection Summary:
  > >>> Total records:     5665
  > >>> Measured records:  5665
  > >>> Valid records:     5646 (99.7% of measured)
  > >>> Outliers detected: 19 (0.3% of measured)
  > >>> Largest non-outlier flux >= 0 DAYTIME:   85.836700
  > >>> Smallest non-outlier flux >= 0 DAYTIME:  0.005859
  > >>> Largest non-outlier flux < 0 DAYTIME:    -0.000095
  > >>> Smallest non-outlier flux < 0 DAYTIME:   -79.367200
  > >>> Largest outlier flux >= 0 DAYTIME:   52.775600
  > >>> Smallest outlier flux >= 0 DAYTIME:  12.617900
  > >>> Largest outlier flux < 0 DAYTIME:    -5.439650
  > >>> Smallest outlier flux < 0 DAYTIME:   -85.178400
  > >>> Largest non-outlier flux >= 0 NIGHTTIME:   61.246300
  > >>> Smallest non-outlier flux >= 0 NIGHTTIME:  0.086871
  > >>> Largest non-outlier flux < 0 NIGHTTIME:    -0.118833
  > >>> Smallest non-outlier flux < 0 NIGHTTIME:   -49.505600
  > >>> Largest outlier flux >= 0 NIGHTTIME:   17.317200
  > >>> Smallest outlier flux >= 0 NIGHTTIME:  5.767250
  > >>> Largest outlier flux < 0 NIGHTTIME:    -3.646830
  > >>> Smallest outlier flux < 0 NIGHTTIME:   -3.646830

Examine results

Inspect the filtered data and understand the Hampel filter method.

print(f"\n" + "=" * 80)
print("Results Summary")
print("=" * 80)
print(f"Filtered data shape: {results.shape}")
print(f"Columns: {list(results.columns)}")

print(f"\nInterpretation:")
print(f"  - Rolling median ± 3 SD shows expected CO2 flux range")
print(f"  - Points outside this range may indicate sensor issues or extreme events")

print(f"\nHampel Filter Method:")
print(f"  - Median Absolute Deviation (MAD) for robust statistics")
print(f"  - Double-differencing (Papale et al. 2006) to remove biological trends")
print(f"  - Automatic day/night thresholds based on solar elevation angle")

print("\n[OK] High-quality flux analysis complete.")
================================================================================
Results Summary
================================================================================
Filtered data shape: (5665, 8)
Columns: ['FLUX_DAYTIME', 'ROLLING_MEDIAN_DAYTIME', 'SD_DAYTIME', 'WINSIZE_DAYTIME', 'FLUX_NIGHTTIME', 'ROLLING_MEDIAN_NIGHTTIME', 'SD_NIGHTTIME', 'WINSIZE_NIGHTTIME']

Interpretation:
  - Rolling median ± 3 SD shows expected CO2 flux range
  - Points outside this range may indicate sensor issues or extreme events

Hampel Filter Method:
  - Median Absolute Deviation (MAD) for robust statistics
  - Double-differencing (Papale et al. 2006) to remove biological trends
  - Automatic day/night thresholds based on solar elevation angle

[OK] High-quality flux analysis complete.

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

Gallery generated by Sphinx-Gallery