Preprocessing Examples

Cleaning measured data before analysis: correcting known sensor issues, flagging implausible records, and aggregating those flags into an overall quality judgement.

The examples are grouped into three subsections, in the order they are normally applied.

Contents

Corrections (corrections/, 7 examples) — fix a known, systematic error in the measurement: sensor offsets against a replicate, wind direction offsets, the nighttime zero offset of a radiation sensor, and setting values to a threshold or to missing.

Outlier detection (outlier_detection/, 9 examples) — flag records that cannot be right: absolute limits, Hampel, local standard deviation, z-score variants, local outlier factor, trimming and manual removal, plus chaining several methods with StepwiseOutlierDetection.

Quality control (qaqc/, 3 examples) — aggregate the individual test flags into one overall quality flag with FlagQCF, read the EddyPro quality flags, and detect timestamp shifts by comparing measured with potential shortwave radiation.

Running Examples

uv run python examples/preprocessing/outlier_detection/outlier_hampel.py
uv run python examples/run_all_examples.py

Data Corrections Examples

Examples demonstrating data corrections including sensor offset detection, bias removal, and value clipping.

7 examples covering physical corrections, calibration drift detection, and data validation.

Contents by Correction Type

Sensor Offset & Bias Corrections

  • correction_relativehumidity_offset.py — Fix RH saturation issues (measurements >100%)

  • correction_radiation_offset.py — Correct radiation nighttime offset (non-zero readings at night)

  • correction_measurement_offset_replicate.py — Detect constant bias between two instruments

  • correction_winddir_offset.py — Correct wind direction calibration drift

Value Replacement & Clipping

  • correction_set_exact_values_to_missing.py — Replace exact values with NaN (error codes, sentinel values)

  • correction_setto_value.py — Replace values in specific periods (e.g., known malfunction times)

  • correction_setto_threshold.py — Clip values to physically realistic min/max bounds

Use Cases

Fix humidity oversaturation:

import diive as dv

# RH sensor drifts >100% due to aging/contamination.
# The daily mean excess is removed as offset, values are capped at 100%.
corrected = dv.corrections.remove_relativehumidity_offset(series=df['RH'], showplot=True)

Remove nighttime radiation offset:

import diive as dv

# Radiation sensor reads non-zero at night (thermal offset).
# Nighttime is derived from solar geometry, so the site location is needed.
corrected = dv.corrections.remove_nighttime_zero_offset(
    series=df['SW_IN'],
    lat=47.478333,
    lon=8.364389,
    utc_offset=1,
    showplot=True
)

Detect instrument offset:

import diive as dv

# Two sensors show constant bias, offset found by brute-force search
offset_corrector = dv.corrections.MeasurementOffsetFromReplicate(
    measurement=df['TA_primary'],
    replicate=df['TA_reference'],
    offset_start=-10,
    offset_end=10,
    offset_stepsize=0.1
)
offset = offset_corrector.get_offset()  # Detected offset, added to correct
corrected = offset_corrector.get_corrected_measurement()

Mask known problems:

import numpy as np
import diive as dv

# Instrument malfunction from 2024-01-15 through 2024-01-17.
# Each entry in *dates* is either a single timestamp or a [start, end] range,
# both ends included. A bare date covers the whole day, so this range runs
# to the last record of 2024-01-17.
corrected = dv.corrections.setto_value(
    series=df['CO2'],
    dates=[['2024-01-15', '2024-01-17']],
    value=np.nan,
    verbose=1
)

Running Examples

# Sensor bias corrections
uv run python examples/preprocessing/corrections/correction_relativehumidity_offset.py
uv run python examples/preprocessing/corrections/correction_radiation_offset.py
uv run python examples/preprocessing/corrections/correction_measurement_offset_replicate.py
uv run python examples/preprocessing/corrections/correction_winddir_offset.py

# Value replacement & clipping
uv run python examples/preprocessing/corrections/correction_set_exact_values_to_missing.py
uv run python examples/preprocessing/corrections/correction_setto_value.py
uv run python examples/preprocessing/corrections/correction_setto_threshold.py

# Run all correction examples
uv run python examples/run_all_examples.py

Set Exact Values to Missing (NaN)

Set Exact Values to Missing (NaN)

Correct Relative Humidity Saturation

Correct Relative Humidity Saturation

Set Time Range Values to Constant

Set Time Range Values to Constant

Clip Values to Minimum/Maximum Limits

Clip Values to Minimum/Maximum Limits

Correct Radiation Zero Offset (Nighttime)

Correct Radiation Zero Offset (Nighttime)

Correct Wind Direction Offset

Correct Wind Direction Offset

Correct Measurement Offset from Replicate

Correct Measurement Offset from Replicate

Outlier Detection Methods Examples

Examples demonstrating 9 outlier detection methods for quality control, anomaly identification, and data cleaning.

Methods by Complexity

Beginner (simple, deterministic):

  • outlier_absolutelimits.py — Enforce physical min/max constraints

  • outlier_manualremoval.py — Explicitly flag known problematic timestamps or periods

  • outlier_trim.py — Symmetric trimmed mean approach (TrimLow)

Intermediate (statistical, adaptive):

  • outlier_hampel.py — Median Absolute Deviation (MAD) in rolling windows

  • outlier_zscore.py — Z-score thresholding (global, rolling, day/night, increments)

  • outlier_localsd.py — Local standard deviation with adaptive windows

  • outlier_incremental.py — Detect spikes via abrupt changes between records

Advanced (machine learning, multi-method):

  • outlier_lof.py — Local Outlier Factor (density-based anomalies)

  • outlier_stepwise.py — Chain multiple methods for progressive filtering

Related Documentation

See dv.outliers for available detection classes:

  • AbsoluteLimits — Threshold-based detection

  • Hampel — MAD-based robust detection

  • LocalSD — Adaptive local threshold

  • zScore — Statistical threshold

  • zScoreRolling — Adaptive rolling threshold

  • zScoreIncrements — Spike detection on record-to-record increments

  • LocalOutlierFactor — Density-based detection

  • TrimLow — Symmetric trimmed-mean removal

  • ManualRemoval — Flag known problematic timestamps/periods

StepwiseOutlierDetection (multi-stage orchestration) is not part of dv.outliers. Import it from diive.preprocessing.outlier_detection.

Use Cases

Quick spike detection (Hampel filter):

import diive as dv

# Detection using the Median Absolute Deviation in a rolling window
detector = dv.outliers.Hampel(
    series=df['NEE'],
    n_sigma=5.5,
    window_length=48 * 13,  # record count (13 days of 30-min data), or a time span such as '13D'
    separate_day_night=True,
    lat=47.286417,
    lon=7.733750,
    utc_offset=1
)
detector.calc(repeat=False)

flag = detector.flag  # 0=tested and accepted, 2=outlier, NaN=not testable (missing value)
cleaned = detector.filteredseries  # outliers set to NaN

Statistical thresholding (Z-score):

from diive.preprocessing.outlier_detection import StepwiseOutlierDetection

# Global z-score
detector = StepwiseOutlierDetection(dfin=df, col='FCH4', site_lat=47.5, site_lon=8.4, utc_offset=1)
detector.flag_outliers_zscore_test(thres_zscore=4)

# Day/night separated z-score
detector.flag_outliers_zscore_test(
    thres_zscore=4,
    separate_day_night=True
)

Absolute physical limits:

import diive as dv

# Enforce known physical bounds
detector = dv.outliers.AbsoluteLimits(
    series=df['RH'],
    minval=0,
    maxval=100
)
detector.calc()

flag = detector.flag  # 0=tested and accepted, 2=outlier, NaN=not testable (missing value)
cleaned = detector.filteredseries

Multi-stage filtering (sequential chain):

from diive.preprocessing.outlier_detection import StepwiseOutlierDetection

# Progressive filtering: aggressive first, then refine
detector = StepwiseOutlierDetection(dfin=df, col='NEE', site_lat=46.8, site_lon=8.6, utc_offset=1)

detector.flag_outliers_hampel_test(n_sigma=5.5, separate_day_night=True)
detector.addflag()

# The global knob applies to both periods; override one with n_sd_daytime /
# n_sd_nighttime (and winsize_daytime / winsize_nighttime) if they should differ
detector.flag_outliers_localsd_test(n_sd=3.5, winsize=24, separate_day_night=True)
detector.addflag()

detector.flag_outliers_zscore_test(thres_zscore=4)
detector.addflag()

# View final cleaned series
cleaned = detector.series_hires_cleaned

Running Examples

# Beginner-friendly (simple, deterministic)
uv run python examples/preprocessing/outlier_detection/outlier_absolutelimits.py
uv run python examples/preprocessing/outlier_detection/outlier_manualremoval.py
uv run python examples/preprocessing/outlier_detection/outlier_trim.py

# Intermediate (statistical, adaptive)
uv run python examples/preprocessing/outlier_detection/outlier_hampel.py
uv run python examples/preprocessing/outlier_detection/outlier_zscore.py
uv run python examples/preprocessing/outlier_detection/outlier_localsd.py
uv run python examples/preprocessing/outlier_detection/outlier_incremental.py

# Advanced (machine learning, multi-method)
uv run python examples/preprocessing/outlier_detection/outlier_lof.py
uv run python examples/preprocessing/outlier_detection/outlier_stepwise.py

# Run all outlier detection examples
uv run python examples/run_all_examples.py

Choosing a Method

Situation

Recommended Method

Why

Quick QA/QC

Hampel

Fast, robust to skew, works with non-normal distributions

Known physical limits

AbsoluteLimits

Simple, deterministic, no parameters to tune

Normal distribution

zScore

Works well when data is normally distributed

Varying patterns

LocalSD

Adaptive to local variability

Abrupt changes

Incremental

Detects step changes, not global outliers

Unknown patterns

LOF

Density-based, finds anomalies without assumptions

Multiple tests

StepwiseOutlierDetection

Combine methods, each filters progressively

Increment-Based Detection

Increment-Based Detection

Local Outlier Factor

Local Outlier Factor

Absolute Limits

Absolute Limits

Manual Removal

Manual Removal

Trim Filter

Trim Filter

Z-Score Detection

Z-Score Detection

Hampel Filter

Hampel Filter

Local Standard Deviation

Local Standard Deviation

Sequential Outlier Detection

Sequential Outlier Detection

Quality Assurance / Quality Control (QA/QC) Examples

Examples demonstrating quality control methods, flag generation, and data quality assessment.

Contents

  • qc_overall_flag.py — Overall Quality Control Flag (QCF) combining multiple test flags

  • qc_eddypro_flags.py — EddyPro quality flag extraction (signal strength, VM97 tests, completeness)

  • qaqc_detect_timestamp_shifts.py — Detect clock/timestamp errors by comparing measured vs potential shortwave radiation (FFT phase shift, cross-correlation, noon-shift peak detection)

Related Documentation

dv.qaqc exports:

  • FlagQCF: Overall quality flag combining individual tests

  • StepwiseMeteoScreeningDb: Stepwise meteo screening of variables from an InfluxDB database (needs the db extra)

  • Measurement, MEASUREMENTS: Meteo measurement groups used by the screening workflow (e.g. TA, SW)

  • CorrectionSpec, CORRECTIONS: The corrections the screening workflow offers

  • corrections_for_measurement(), correction_spec(): Which corrections apply to a measurement, and the details of one correction

  • detect_measurement(), measurement_label(): Guess the measurement from a variable name, and a display label for a measurement code

The EddyPro flag functions are not re-exported by dv.qaqc. Import them from diive.preprocessing.qaqc:

  • flag_signal_strength_eddypro_test() — Signal quality

  • flags_vm97_eddypro_fluxnetfile_tests() — Vickers & Mahrt (1997) raw data tests

  • flag_ssitc_eddypro_test() — Steady State and Integral Turbulence Characteristics

  • flag_spectral_correction_factor_eddypro_test() — Spectral correction assessment

DetectTimestampShifts — timestamp shift detection via radiation phase analysis — is imported from its module:

from diive.preprocessing.qaqc.detect_timestamp_shifts import DetectTimestampShifts

Use Cases

Generate overall quality flag (QCF):

from diive.preprocessing.qaqc import FlagQCF

# Combine multiple individual quality tests into single QCF
qcf = FlagQCF(
    df=df,
    target_col='NEE',
    swinpot_col='SW_IN_POT',  # Optional: enables day/night separation
    idstr='_L41'
)
qcf.calculate(daytime_accept_qcf_below=2)  # Accept good+medium daytime

# QCF values: 0=good, 1=marginal, 2=poor
filtered = df[qcf.filteredseries.notna()]  # Records accepted by the thresholds
highest_quality = df[qcf.filteredseries_hq.notna()]  # Only QCF=0

# Reports and plots
qcf.report_qcf_series()  # Summary statistics
qcf.report_qcf_flags()  # Per-test breakdown
qcf.showplot_qcf_heatmaps()  # Visualization

Extract EddyPro quality flags:

from diive.preprocessing.qaqc import (
    flag_signal_strength_eddypro_test,
    flags_vm97_eddypro_fluxnetfile_tests,
    flag_ssitc_eddypro_test
)

# Signal quality (IRGA, anemometer)
sig_flag = flag_signal_strength_eddypro_test(
    df=df,
    signal_strength_col='CUSTOM_SIGNAL_STRENGTH_IRGA72_MEAN',
    var_col='FC',  # only used to name the flag
    method='discard below',  # flag 2 where signal strength < threshold
    threshold=99,
    idstr='_L41'
)

# VM97 raw data tests, read from the 8-digit integer in column CO2_VM97_TEST
vm97_flags = flags_vm97_eddypro_fluxnetfile_tests(
    df=df,
    flux='FC',
    fluxbasevar='CO2',
    idstr='_L41',
    spikes=True,
    amplitude=True,
    dropout=True,
    abslim=True,
    skewkurt_hf=True,
    skewkurt_sf=True,
    discont_hf=True,
    discont_sf=True
)
# One flag column per test switched on above: spikes, amplitude, dropout,
# abslim, skewkurt_hf, skewkurt_sf, discont_hf, discont_sf

# Stationarity test, read from column FC_SSITC_TEST
ssitc_flag = flag_ssitc_eddypro_test(df=df, flux='FC', idstr='_L41')

Quality Flag Schema

QCF (Overall Quality Control Flag):

  • 0 = Good quality (all tests pass)

  • 1 = Marginal quality (1-3 soft warnings, no hard fails)

  • 2 = Poor quality (>3 soft warnings OR ≥1 hard fail)

EddyPro test results:

  • 0 = Pass

  • 1 = Soft warning (marginal)

  • 2 = Hard fail (reject)

Running Examples

# Generate overall quality flags from multiple tests
uv run python examples/preprocessing/qaqc/qc_overall_flag.py

# Extract and convert EddyPro-specific quality flags
uv run python examples/preprocessing/qaqc/qc_eddypro_flags.py

# Detect clock/timestamp errors from measured vs potential radiation
uv run python examples/preprocessing/qaqc/qaqc_detect_timestamp_shifts.py

# Run all QA/QC examples
uv run python examples/run_all_examples.py

FLUXNET Standards

Quality control follows FLUXNET conventions:

  • Quality tests applied independently

  • Results combined into overall QCF score

  • Day/night thresholds differ (nighttime stricter)

  • USTAR filtering applied to flux only, not energy variables

  • Multiple percentile scenarios for uncertainty quantification

Detect Timestamp Shifts

Detect Timestamp Shifts

EddyPro Quality Flags

EddyPro Quality Flags

Overall Quality Control Flag (QCF)

Overall Quality Control Flag (QCF)

Gallery generated by Sphinx-Gallery