Note
Go to the end to download the full example code.
Self-Heating Correction (SCOP Methodology)¶
Remove spurious CO2 flux caused by sun-induced heating of open-path IRGA sensors.
Demonstrates SCOP (Self-heating Correction for Open-Path) methodology to remove spurious CO2 flux measurements caused by sun-induced heating of instrument surfaces.
Includes physics modeling, optimization of scaling factors, and correction application.
The correction applies to the CO2 flux (NEE) only. Whether a self-heating correction applies to the latent heat flux (LE) is unresolved in eddy covariance, so diive offers none, and this example has no LE counterpart.
Best for: Correcting systematic bias in open-path IRGA CO2 flux measurements.
Self-heating correction workflow¶
The SCOP methodology uses three steps: 1. ScopPhysics: Calculate unscaled flux correction term (FCT_UNSC) 2. ScopOptimizer: Optimize scaling factors using closed-path reference 3. ScopApplicator: Apply final correction to open-path flux
from diive.flux.lowres.selfheating import ScopPhysics, ScopOptimizer, ScopApplicator
from diive.configs.exampledata import load_exampledata_parquet_lae
import time
print("=" * 80)
print("SCOP Self-Heating Correction Workflow")
print("=" * 80)
# Load example data with parallel IRGA measurements
df = load_exampledata_parquet_lae()
# One full year (2017). The parallel campaign starts 27 May 2016, so 2017 is the
# first calendar year carrying both instruments over all seasons - which is what
# the day/night and USTAR-binned optimization needs.
df = df.loc["2017-01-01 00:15:00":"2017-12-31 23:45:00"].copy()
print(f"\nData period: {df.index.min()} to {df.index.max()}")
print(f"Total records: {len(df)}")
================================================================================
SCOP Self-Heating Correction Workflow
================================================================================
> Loaded .parquet file
/home/docs/checkouts/diive/checkouts/latest/diive/configs/exampledata/exampledat
a_PARQUET_CH-LAE_FP2025.X_22_IRGA75+IRGA72_FPC_NEE-QCF11-L3.2_2016-2017.parquet
(0.006 seconds).
Data period: 2017-01-01 00:15:00 to 2017-12-31 23:45:00
Total records: 17520
Step 1: Calculate physics-based correction term¶
Use ScopPhysics to calculate the unscaled flux correction term (FCT_UNSC) based on radiation, temperature, and wind speed.
print(f"\n" + "=" * 80)
print("Step 1: Physics-Based Correction Term Calculation")
print("=" * 80)
tic = time.time()
physics = ScopPhysics(
ta=df["TA_T1_47_1_gfXG_IRGA72"].copy(),
gas_density=df["CO2_MOLAR_DENSITY_IRGA75"].copy() * 1000, # Convert to umol m-3
rho_a=df["AIR_DENSITY_IRGA72"].copy(),
rho_v=df["VAPOR_DENSITY_IRGA72"].copy(),
u=df["U_IRGA72"].copy(),
c_p=df["AIR_CP_IRGA72"].copy(),
ustar=df["USTAR_IRGA72"].copy(),
lat=47.478333, # CH-LAE
lon=8.364389, # CH-LAE
utc_offset=1,
)
physics.run(correction_method_base="JAR09", gapfill=True)
physics.stats()
results_physics_df = physics.get_results()
elapsed = time.time() - tic
print(f"\n[OK] Physics calculation completed in {elapsed:.1f}s")
print(f" Correction term (FCT_UNSC) calculated")
print(f" Gap-filled term available as FCT_UNSC_gfXG")
print(f" (the _gfXG suffix names the gap-filling regressor, XGBoost)")
================================================================================
Step 1: Physics-Based Correction Term Calculation
================================================================================
! 235 data points resulted in NaN due to ustar <= 0.
> Aerodynamic resistance: Mean = 27.32 s m-1
> Dry air density: Mean = 1.1376 kg m-3
> 49 feature(s), 13,451 complete record(s) of 17,285 (2017-01-01 00:15:00 to
2017-12-31 23:45:00)
> Train/test split: 10,088 train / 3,363 test (25% held out)
> Test set is a RANDOM subset of the complete records, not a temporal block.
This reproduces the gap-filling task: gaps lie between observed records and are
filled from the drivers at the same timestamp.
v Training complete.
> Predicted 17285 records where all features available.
> Filling 3834 missing records in FCT_UNSC_gfXG ...
> Fallback: filling 0 remaining gaps in FCT_UNSC_gfXG ...
>
XGBoost Performance Metrics:
> mae: 1.0158
> medae: 0.5570
> mse: 3.5826
> rmse: 1.8928
> mape: 0.0832
> maxe: 40.5474
> r2: 0.9744
> (i) XGBoost left 235 gaps (expected at edges with insufficient drivers)
=================================================================
SCOP PHYSICS DIAGNOSTICS (CO2)
=================================================================
1. DATA COVERAGE & GAP-FILLING
------------------------------
Total Timestamps : 17,520
Raw Physics Calculated : 13,451 ( 76.8%)
Final Gap-Filled (GF) : 17,285 ( 98.7%)
-> Gap-filled (XGBoost): 3,834 ( 21.9%)
2. INSTRUMENT SELF-HEATING (Ts - Ta)
------------------------------
Avg Daytime Heating : +2.32 °C
Max Daytime Heating : +4.01 °C
Avg Nighttime Offset : +1.89 °C
3. UNSCALED CORRECTION TERM (FCT_unsc)
(Units: µmol m-2 s-1)
------------------------------
DAYTIME : +18.5470 ± 14.9045 [Range: -1.10 to 79.89]
NIGHTTIME : +10.8876 ± 11.4013 [Range: -0.49 to 79.15]
4. KEY DRIVERS (Daytime Avg)
------------------------------
Radiation (SW_IN) : 600 W m-2
Wind Speed (U) : 2.50 m s-1
Aero Resistance (Ra) : 11.8 s m-1
=================================================================
[OK] Physics calculation completed in 5.6s
Correction term (FCT_UNSC) calculated
Gap-filled term available as FCT_UNSC_gfXG
(the _gfXG suffix names the gap-filling regressor, XGBoost)
Step 2: Optimize scaling factors¶
Use ScopOptimizer to find optimal scaling factors by comparing open-path and closed-path measurements. Both fluxes and the correction term are in umol m-2 s-1, so the optimization needs no unit conversion.
print(f"\n" + "=" * 80)
print("Step 2: Scaling Factor Optimization")
print("=" * 80)
tic = time.time()
optimizer = ScopOptimizer(
fct_unsc=results_physics_df["FCT_UNSC_gfXG"],
class_var=df["USTAR_IRGA72"].copy(),
n_classes=5,
n_bootstrap_runs=5,
flux_openpath=df["NEE_L3.1_L3.2_QCF_IRGA75"].copy(),
flux_closedpath=df["NEE_L3.1_L3.2_QCF_IRGA72"].copy(),
daytime=results_physics_df["DAYTIME"],
)
scaling_factors_df = optimizer.run()
optimizer.stats()
elapsed = time.time() - tic
print(f"\n[OK] Optimization completed in {elapsed:.1f}s")
print(f" Scaling factors determined for {len(scaling_factors_df)} USTAR classes")
print(f" {optimizer.n_bootstrap} bootstrap runs executed")
================================================================================
Step 2: Scaling Factor Optimization
================================================================================
===========================================================================
SCALING FACTOR OPTIMIZATION REPORT
===========================================================================
Flux Type : CO2
Bootstrap Runs : 5
Total Bins : 10
---------------------------------------------------------------------------
1. GLOBAL SUMMARY (Median of Bins)
...........................................................................
Period | Median SF | Mean Uncertainty (IQR) | N_Avg
Nighttime | 0.098 | 0.006 | 496
Daytime | 0.181 | 0.010 | 985
2. DETAILED BIN BREAKDOWN
...........................................................................
Bin | Class Range | N | Median SF | 99% CI | Error
(SOS)
---------------------------------------------------------------------------
--- DAYTIME ---
0 | 0.03 - 0.28 | 906 | 0.317 | [0.30-0.37] |
27872.18
1 | 0.28 - 0.41 | 998 | 0.274 | [0.25-0.28] |
29089.03
2 | 0.42 - 0.56 | 1055 | 0.181 | [0.17-0.19] |
40544.03
3 | 0.56 - 0.75 | 1046 | 0.134 | [0.13-0.14] |
37770.36
4 | 0.75 - 1.97 | 921 | 0.081 | [0.08-0.10] |
32190.74
--- NIGHTTIME ---
0 | 0.01 - 0.17 | 597 | 0.111 | [0.10-0.13] |
3427.87
1 | 0.17 - 0.28 | 573 | 0.104 | [0.09-0.13] |
5591.31
2 | 0.28 - 0.42 | 520 | 0.098 | [0.07-0.13] |
8120.59
3 | 0.42 - 0.63 | 477 | 0.073 | [0.06-0.11] |
7509.54
4 | 0.63 - 1.43 | 314 | 0.062 | [0.05-0.07] |
3809.24
===========================================================================
[OK] Optimization completed in 0.1s
Scaling factors determined for 10 USTAR classes
5 bootstrap runs executed
Step 3: Apply correction¶
Use ScopApplicator to apply the optimized correction to the flux data.
print(f"\n" + "=" * 80)
print("Step 3: Correction Application")
print("=" * 80)
tic = time.time()
applicator = ScopApplicator(
fct_unsc=results_physics_df["FCT_UNSC_gfXG"],
scaling_factors_df=scaling_factors_df,
flux_openpath=df["NEE_L3.1_L3.2_QCF_IRGA75"].copy(),
classvar=df["USTAR_IRGA72"].copy(),
daytime=results_physics_df["DAYTIME"].copy()
)
applicator.run()
results_df = applicator.get_results()
corrected_flux = results_df['NEE_OP_CORR']
elapsed = time.time() - tic
print(f"\n[OK] Correction applied in {elapsed:.1f}s")
print(f" Original flux (open-path): {df['NEE_L3.1_L3.2_QCF_IRGA75'].mean():.3f} µmol m-2 s-1")
print(f" Corrected flux (open-path): {corrected_flux.mean():.3f} µmol m-2 s-1")
print(f" Reference flux (closed-path):{df['NEE_L3.1_L3.2_QCF_IRGA72'].mean():>7.3f} µmol m-2 s-1")
================================================================================
Step 3: Correction Application
================================================================================
! (!) Warning: 235 fluxes missing Scaling Factor (due to missing
USTAR_IRGA72).
> Imputing using Month-Daytime-Hour-Minute Diel Cycle Median...
> > Successfully imputed 235 missing Scaling Factors.
[OK] Correction applied in 0.0s
Original flux (open-path): -5.066 µmol m-2 s-1
Corrected flux (open-path): -3.081 µmol m-2 s-1
Reference flux (closed-path): -2.208 µmol m-2 s-1
Step 4: Check the correction against the reference¶
The correction removes an artificial CO2 uptake, so the corrected open-path flux must move towards the closed-path reference rather than away from it. Passing the reference to stats() adds a section with recovery, RMSE and regression slope, which is how the correction is verified: the scaling factors were fitted to this reference, so this is a sanity check on the fit, not independent validation.
applicator.stats(flux_closedpath=df["NEE_L3.1_L3.2_QCF_IRGA72"])
print("\n[OK] Self-heating correction workflow complete.")
===========================================================================
FLUX CORRECTION REPORT
===========================================================================
Flux Type : CO2
Total Records : 8,881
---------------------------------------------------------------------------
1. SCALING FACTOR ASSIGNMENT (Method Used)
...........................................................................
Direct Lookup (Valid USTAR_IRGA72) : 8,881 (100.0%)
i Gap-Filled (MDV Imputation) : 0 ( 0.0%)
Median Scaling Factor (Day) : 0.181
Median Scaling Factor (Night) : 0.098
2. CORRECTION IMPACT (Budget) (Units: Sum)
...........................................................................
Uncorrected Sum : -44,990
Corrected Sum : -27,361
Net Adjustment : 17,628 (+39.2%)
3. ACCURACY vs REFERENCE
...........................................................................
Reference Sum : -27,847
Recovery (Corrected / Ref) : 98.3%
RMSE : 3.294
Slope (m) : 1.021
===========================================================================
[OK] Self-heating correction workflow complete.
Total running time of the script: (0 minutes 5.840 seconds)