Note
Go to the end to download the full example code.
Self-Heating Correction: Complete Production Workflow¶
Complete production workflow for self-heating correction: create scaling factors table from parallel measurements, then apply to long-term flux data.
This comprehensive example demonstrates the full SCOP methodology: 1. Calibration phase: Create reusable scaling factors lookup table from parallel IRGA measurements 2. Application phase: Apply the table to long-term data without parallel measurements
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.
Includes multiple visualizations throughout the workflow: - Diurnal cycle plots: Mean daily cycles of correction term (instrument heating patterns) - Optimization results: Scaling factors by USTAR class with uncertainty bounds - Correction dashboards: Before/after flux comparison, correction magnitude, budget impact
Best for: Understanding the complete self-heating correction pipeline from calibration to operational correction of multi-year flux datasets, with full diagnostic visualizations.
Complete SCOP Workflow Overview¶
Sun-induced heating of open-path IRGA sensors creates spurious negative CO2 flux (artificial uptake bias). The SCOP (Self-heating Correction for Open-Path) method corrects this in two phases:
Phase 1: Calibration (Parallel Measurements Period) 1. ScopPhysics: Calculate unscaled flux correction term (FCT_UNSC) 2. ScopOptimizer: Optimize scaling factors using closed-path reference 3. Output: Scaling factors lookup table (20 USTAR classes × day/night)
Only the CO2 flux is corrected. There is no self-heating correction for LE.
Phase 2: Application (Long-term Operational Period) 1. ScopPhysics: Calculate correction term for long-term data 2. ScopApplicator: Apply lookup table to correct open-path fluxes 3. Output: Corrected flux time series ready for gap-filling and analysis
The scaling factors table remains valid across seasons/years as long as instrument configuration is unchanged.
import pandas as pd
import time
from datetime import datetime
from diive.flux.lowres.selfheating import ScopPhysics, ScopOptimizer, ScopApplicator
from diive.configs.exampledata import load_exampledata_parquet_lae
print("=" * 80)
print("SCOP Self-Heating Correction: Complete Production Workflow")
print("=" * 80)
================================================================================
SCOP Self-Heating Correction: Complete Production Workflow
================================================================================
PHASE 1: CALIBRATION — Create Scaling Factors Table¶
Use a period with parallel measurements (open-path IRGA75 + closed-path IRGA72) to create the scaling factors lookup table.
print("\n" + "=" * 80)
print("PHASE 1: CALIBRATION — Create Scaling Factors Lookup Table")
print("=" * 80)
# Load parallel measurement data
df_calibration = load_exampledata_parquet_lae()
# Calibrate on the first half of 2017 and apply to the second half (below). The two
# phases must run on *different* periods, otherwise the example demonstrates fitting
# and re-fitting the same data instead of transferring a table to a period with no
# closed-path reference. Splitting one year in half also keeps the two physics runs
# and the bootstrap quick; in production the calibration period is the whole parallel
# campaign.
df_calibration = df_calibration.loc["2017-01-01 00:15:00":"2017-06-30 23:45:00"].copy()
print(f"\nCalibration data period: {df_calibration.index.min()} to {df_calibration.index.max()}")
print(f"Total records: {len(df_calibration):,}")
print(f"\nAvailable parallel measurements:")
print(f" IRGA75 (open-path): NEE_L3.1_L3.2_QCF_IRGA75, CO2_MOLAR_DENSITY_IRGA75")
print(f" IRGA72 (closed-path): NEE_L3.1_L3.2_QCF_IRGA72, CO2_MOLAR_DENSITY_IRGA72")
================================================================================
PHASE 1: CALIBRATION — Create Scaling Factors Lookup Table
================================================================================
> 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).
Calibration data period: 2017-01-01 00:15:00 to 2017-06-30 23:45:00
Total records: 8,688
Available parallel measurements:
IRGA75 (open-path): NEE_L3.1_L3.2_QCF_IRGA75, CO2_MOLAR_DENSITY_IRGA75
IRGA72 (closed-path): NEE_L3.1_L3.2_QCF_IRGA72, CO2_MOLAR_DENSITY_IRGA72
Step 1a: Physics-based correction term (Calibration Period)¶
ScopPhysics calculates the unscaled flux correction term (FCT_UNSC) by modeling thermal exchange between instrument surfaces and passing air.
print(f"\n" + "=" * 80)
print("Step 1a: Physics Calculation (Calibration Period)")
print("=" * 80)
tic = time.time()
physics_calib = ScopPhysics(
ta=df_calibration["TA_T1_47_1_gfXG_IRGA72"].copy(),
gas_density=df_calibration["CO2_MOLAR_DENSITY_IRGA75"].copy() * 1000,
rho_a=df_calibration["AIR_DENSITY_IRGA72"].copy(),
rho_v=df_calibration["VAPOR_DENSITY_IRGA72"].copy(),
u=df_calibration["U_IRGA72"].copy(),
c_p=df_calibration["AIR_CP_IRGA72"].copy(),
ustar=df_calibration["USTAR_IRGA72"].copy(),
lat=47.478333, # CH-LAE
lon=8.364389,
utc_offset=1,
)
physics_calib.run(correction_method_base="JAR09", gapfill=True)
results_physics_calib = physics_calib.get_results()
elapsed = time.time() - tic
print(f"\n[OK] Physics calculation completed in {elapsed:.1f}s")
physics_calib.stats()
# Plot diurnal cycles of correction term
print(f"\nGenerating diurnal cycle plots...")
physics_calib.plot_diel_cycles(showplot=False)

================================================================================
Step 1a: Physics Calculation (Calibration Period)
================================================================================
! 120 data points resulted in NaN due to ustar <= 0.
> Aerodynamic resistance: Mean = 24.40 s m-1
> Dry air density: Mean = 1.1447 kg m-3
> 49 feature(s), 7,043 complete record(s) of 8,568 (2017-01-01 00:15:00 to
2017-06-30 23:45:00)
> Train/test split: 5,282 train / 1,761 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 8568 records where all features available.
> Filling 1525 missing records in FCT_UNSC_gfXG ...
> Fallback: filling 0 remaining gaps in FCT_UNSC_gfXG ...
>
XGBoost Performance Metrics:
> mae: 1.0892
> medae: 0.6037
> mse: 4.4364
> rmse: 2.1063
> mape: 0.0803
> maxe: 39.1409
> r2: 0.9752
> (i) XGBoost left 120 gaps (expected at edges with insufficient drivers)
[OK] Physics calculation completed in 3.2s
=================================================================
SCOP PHYSICS DIAGNOSTICS (CO2)
=================================================================
1. DATA COVERAGE & GAP-FILLING
------------------------------
Total Timestamps : 8,688
Raw Physics Calculated : 7,043 ( 81.1%)
Final Gap-Filled (GF) : 8,568 ( 98.6%)
-> Gap-filled (XGBoost): 1,525 ( 17.6%)
2. INSTRUMENT SELF-HEATING (Ts - Ta)
------------------------------
Avg Daytime Heating : +2.41 °C
Max Daytime Heating : +4.01 °C
Avg Nighttime Offset : +1.81 °C
3. UNSCALED CORRECTION TERM (FCT_unsc)
(Units: µmol m-2 s-1)
------------------------------
DAYTIME : +20.8897 ± 16.4420 [Range: -0.02 to 79.89]
NIGHTTIME : +12.3645 ± 12.4336 [Range: -0.77 to 79.15]
4. KEY DRIVERS (Daytime Avg)
------------------------------
Radiation (SW_IN) : 621 W m-2
Wind Speed (U) : 2.47 m s-1
Aero Resistance (Ra) : 11.0 s m-1
=================================================================
Generating diurnal cycle plots...
> Plotting Physics Diel Cycles...
<Figure size 2200x1200 with 8 Axes>
Step 2a: Optimize scaling factors (Calibration Period)¶
ScopOptimizer determines optimal scaling factors in 20 USTAR classes (production settings) by comparing open-path flux against closed-path reference. Bootstrap runs provide uncertainty quantification.
print(f"\n" + "=" * 80)
print("Step 2a: Scaling Factor Optimization (Calibration Period)")
print("=" * 80)
print("Creating scaling factors table from parallel measurements...")
tic = time.time()
optimizer = ScopOptimizer(
fct_unsc=results_physics_calib["FCT_UNSC_gfXG"],
class_var=df_calibration["USTAR_IRGA72"].copy(),
n_classes=20, # Production: 20 classes
n_bootstrap_runs=20, # kept small for the example; use 100 in production
flux_openpath=df_calibration["NEE_L3.1_L3.2_QCF_IRGA75"].copy(),
flux_closedpath=df_calibration["NEE_L3.1_L3.2_QCF_IRGA72"].copy(),
daytime=results_physics_calib["DAYTIME"],
)
scaling_factors_df = optimizer.run()
elapsed = time.time() - tic
print(f"\n[OK] Optimization completed in {elapsed:.1f}s")
print(f" Scaling factors table: {len(scaling_factors_df)} rows")
print(f" - Daytime bins: {(scaling_factors_df['DAYTIME'] == 1.0).sum()}")
print(f" - Nighttime bins: {(scaling_factors_df['DAYTIME'] == 0.0).sum()}")
print(f" Bootstrap runs: {optimizer.n_bootstrap}")
optimizer.stats()
# Plot optimization results
print(f"\nGenerating optimization results plots...")
optimizer.plot(showplot=False)

================================================================================
Step 2a: Scaling Factor Optimization (Calibration Period)
================================================================================
Creating scaling factors table from parallel measurements...
[OK] Optimization completed in 0.4s
Scaling factors table: 40 rows
- Daytime bins: 20
- Nighttime bins: 20
Bootstrap runs: 20
===========================================================================
SCALING FACTOR OPTIMIZATION REPORT
===========================================================================
Flux Type : CO2
Bootstrap Runs : 20
Total Bins : 40
---------------------------------------------------------------------------
1. GLOBAL SUMMARY (Median of Bins)
...........................................................................
Period | Median SF | Mean Uncertainty (IQR) | N_Avg
Nighttime | 0.078 | 0.030 | 63
Daytime | 0.170 | 0.040 | 131
2. DETAILED BIN BREAKDOWN
...........................................................................
Bin | Class Range | N | Median SF | 99% CI | Error
(SOS)
---------------------------------------------------------------------------
--- DAYTIME ---
0 | 0.03 - 0.15 | 97 | 0.364 | [0.21-0.57] |
645.11
1 | 0.15 - 0.20 | 110 | 0.340 | [0.24-0.46] |
1118.08
2 | 0.20 - 0.24 | 113 | 0.232 | [0.15-0.46] |
1093.57
3 | 0.24 - 0.28 | 115 | 0.302 | [0.24-0.42] |
1419.39
4 | 0.28 - 0.32 | 123 | 0.322 | [0.25-0.35] |
887.92
5 | 0.32 - 0.35 | 128 | 0.286 | [0.22-0.35] |
1577.77
6 | 0.35 - 0.39 | 142 | 0.248 | [0.18-0.32] |
1825.53
7 | 0.39 - 0.43 | 140 | 0.195 | [0.16-0.23] |
1421.19
8 | 0.43 - 0.46 | 129 | 0.202 | [0.16-0.23] |
992.12
9 | 0.46 - 0.50 | 139 | 0.173 | [0.13-0.22] |
1713.36
10 | 0.50 - 0.55 | 143 | 0.167 | [0.12-0.18] |
699.03
11 | 0.55 - 0.58 | 146 | 0.133 | [0.10-0.16] |
1083.30
12 | 0.58 - 0.63 | 152 | 0.158 | [0.13-0.18] |
1321.34
13 | 0.63 - 0.67 | 139 | 0.121 | [0.09-0.19] |
2014.65
14 | 0.67 - 0.72 | 152 | 0.114 | [0.09-0.14] |
1296.18
15 | 0.72 - 0.78 | 140 | 0.123 | [0.10-0.14] |
881.55
16 | 0.78 - 0.85 | 144 | 0.120 | [0.10-0.14] |
991.91
17 | 0.85 - 0.94 | 145 | 0.101 | [0.09-0.12] |
1874.04
18 | 0.94 - 1.11 | 140 | 0.087 | [0.05-0.11] |
1901.24
19 | 1.12 - 1.89 | 85 | 0.012 | [0.00-0.07] |
1592.86
--- NIGHTTIME ---
0 | 0.01 - 0.10 | 71 | 0.097 | [0.04-0.30] |
158.41
1 | 0.10 - 0.13 | 65 | 0.104 | [0.06-0.20] |
131.43
2 | 0.13 - 0.15 | 63 | 0.204 | [0.14-0.25] |
107.42
3 | 0.15 - 0.18 | 61 | 0.128 | [0.08-0.20] |
158.50
4 | 0.18 - 0.21 | 54 | 0.154 | [0.09-0.23] |
92.74
5 | 0.21 - 0.23 | 65 | 0.096 | [0.06-0.14] |
159.53
6 | 0.23 - 0.26 | 80 | 0.099 | [0.05-0.17] |
376.47
7 | 0.26 - 0.29 | 70 | 0.075 | [0.05-0.12] |
168.33
8 | 0.29 - 0.32 | 63 | 0.078 | [0.04-0.15] |
205.07
9 | 0.32 - 0.35 | 69 | 0.123 | [0.05-0.19] |
296.19
10 | 0.35 - 0.39 | 65 | 0.107 | [0.08-0.14] |
137.34
11 | 0.39 - 0.44 | 76 | 0.078 | [0.06-0.14] |
280.56
12 | 0.44 - 0.49 | 61 | 0.077 | [0.04-0.13] |
196.57
13 | 0.49 - 0.55 | 76 | 0.054 | [0.04-0.08] |
145.81
14 | 0.55 - 0.61 | 66 | 0.054 | [0.03-0.08] |
134.75
15 | 0.61 - 0.69 | 67 | 0.066 | [0.05-0.11] |
183.08
16 | 0.69 - 0.79 | 59 | 0.055 | [0.04-0.09] |
181.06
17 | 0.79 - 0.90 | 68 | 0.068 | [0.06-0.09] |
242.30
18 | 0.91 - 1.10 | 44 | 0.079 | [0.04-0.09] |
185.63
19 | 1.14 - 1.43 | 16 | 0.026 | [0.01-0.05] |
30.04
===========================================================================
Generating optimization results plots...
> Plotting Scaling Factors...
<Figure size 1000x700 with 1 Axes>
Step 3a: Validate table on parallel data (Calibration Period)¶
ScopApplicator uses the optimized table to correct the calibration period data. Results should closely match the closed-path reference.
print(f"\n" + "=" * 80)
print("Step 3a: Validation on Parallel Data (Calibration Period)")
print("=" * 80)
tic = time.time()
applicator_calib = ScopApplicator(
fct_unsc=results_physics_calib["FCT_UNSC_gfXG"],
scaling_factors_df=scaling_factors_df,
flux_openpath=df_calibration["NEE_L3.1_L3.2_QCF_IRGA75"].copy(),
classvar=df_calibration["USTAR_IRGA72"].copy(),
daytime=results_physics_calib["DAYTIME"].copy()
)
applicator_calib.run()
results_calib_df = applicator_calib.get_results()
elapsed = time.time() - tic
print(f"\n[OK] Correction applied in {elapsed:.1f}s")
flux_op_uncorr = df_calibration["NEE_L3.1_L3.2_QCF_IRGA75"]
flux_op_corr = results_calib_df['NEE_OP_CORR']
flux_cp_ref = df_calibration["NEE_L3.1_L3.2_QCF_IRGA72"]
print(f"\nFlux statistics (calibration period):")
print(f" Open-path (uncorrected): {flux_op_uncorr.mean():>8.3f} µmol m-2 s-1 (N={flux_op_uncorr.count()})")
print(f" Open-path (corrected): {flux_op_corr.mean():>8.3f} µmol m-2 s-1")
print(f" Closed-path (reference): {flux_cp_ref.mean():>8.3f} µmol m-2 s-1 (N={flux_cp_ref.count()})")
print(f"\nTable validation statistics:")
applicator_calib.stats(flux_closedpath=flux_cp_ref)
# Plot correction validation dashboard
print(f"\nGenerating correction validation dashboard...")
applicator_calib.plot_dashboard(flux_closedpath=flux_cp_ref, showplot=False)

================================================================================
Step 3a: Validation on Parallel Data (Calibration Period)
================================================================================
! (!) Warning: 120 fluxes missing Scaling Factor (due to missing
USTAR_IRGA72).
> Imputing using Month-Daytime-Hour-Minute Diel Cycle Median...
> > Successfully imputed 120 missing Scaling Factors.
[OK] Correction applied in 0.0s
Flux statistics (calibration period):
Open-path (uncorrected): -4.687 µmol m-2 s-1 (N=4715)
Open-path (corrected): -2.501 µmol m-2 s-1
Closed-path (reference): -1.891 µmol m-2 s-1 (N=5455)
Table validation statistics:
===========================================================================
FLUX CORRECTION REPORT
===========================================================================
Flux Type : CO2
Total Records : 4,715
---------------------------------------------------------------------------
1. SCALING FACTOR ASSIGNMENT (Method Used)
...........................................................................
Direct Lookup (Valid USTAR_IRGA72) : 4,715 (100.0%)
i Gap-Filled (MDV Imputation) : 0 ( 0.0%)
Median Scaling Factor (Day) : 0.167
Median Scaling Factor (Night) : 0.079
2. CORRECTION IMPACT (Budget) (Units: Sum)
...........................................................................
Uncorrected Sum : -22,100
Corrected Sum : -11,790
Net Adjustment : 10,310 (+46.7%)
3. ACCURACY vs REFERENCE
...........................................................................
Reference Sum : -12,535
Recovery (Corrected / Ref) : 94.1%
RMSE : 3.107
Slope (m) : 1.026
===========================================================================
Generating correction validation dashboard...
> Generating Comprehensive Flux Dashboard (Large Font Edition)...
<Figure size 2400x2000 with 13 Axes>
Scaling Factors Lookup Table Details¶
The scaling factors table is the key output of the calibration phase. Each bin shows the median scaling factor (SF_MEDIAN) and uncertainty ranges (quartiles and percentiles). The table is indexed by USTAR class and day/night.
Key patterns to look for in the printed table: - Daytime factors exceed nighttime factors: heating is radiation-driven - Low USTAR gives larger factors: poor wind mixing accumulates the heating effect - High USTAR gives smaller factors: better wind mixing removes the heat
A class with fewer than ScopOptimizer.MIN_ROWS_PER_CLASS complete records is not fitted and gets no row of its own, so the table can hold fewer than 2 x n_classes rows. ScopOptimizer.run() warns which classes those were, and ScopApplicator resolves their records to a neighbouring class’s factor.
print(f"\n" + "=" * 80)
print("SCALING FACTORS LOOKUP TABLE")
print("=" * 80)
print(f"\nTable structure: {len(scaling_factors_df)} rows × {len(scaling_factors_df.columns)} columns")
print(f" Daytime bins: {(scaling_factors_df['DAYTIME'] == 1.0).sum()} of 20 USTAR classes")
print(f" Nighttime bins: {(scaling_factors_df['DAYTIME'] == 0.0).sum()} of 20 USTAR classes")
print(f"\nMedian scaling factors:")
dt_sf = scaling_factors_df[scaling_factors_df['DAYTIME'] == 1.0]['SF_MEDIAN']
nt_sf = scaling_factors_df[scaling_factors_df['DAYTIME'] == 0.0]['SF_MEDIAN']
print(f" Daytime median: {dt_sf.median():.4f} (range: {dt_sf.min():.4f} - {dt_sf.max():.4f})")
print(f" Nighttime median: {nt_sf.median():.4f} (range: {nt_sf.min():.4f} - {nt_sf.max():.4f})")
print(f"\nDaytime scaling factors (sample of first 10 bins):")
dt_sample = scaling_factors_df[scaling_factors_df['DAYTIME'] == 1.0][['GROUP_CLASSVAR', 'GROUP_CLASSVAR_MIN', 'GROUP_CLASSVAR_MAX', 'SF_MEDIAN', 'SF_Q25', 'SF_Q75']].head(10)
for idx, row in dt_sample.iterrows():
iqr = row['SF_Q75'] - row['SF_Q25']
print(f" Bin {int(row['GROUP_CLASSVAR']):2d} (USTAR {row['GROUP_CLASSVAR_MIN']:5.3f}-{row['GROUP_CLASSVAR_MAX']:5.3f}): {row['SF_MEDIAN']:.4f} ± {iqr:.4f}")
print(f"\nFull scaling factors table (all {len(scaling_factors_df)} bins):")
print(scaling_factors_df[['DAYTIME', 'GROUP_CLASSVAR', 'GROUP_CLASSVAR_MIN', 'GROUP_CLASSVAR_MAX', 'SF_MEDIAN', 'SF_Q25', 'SF_Q75']].to_string(index=False))
================================================================================
SCALING FACTORS LOOKUP TABLE
================================================================================
Table structure: 40 rows × 12 columns
Daytime bins: 20 of 20 USTAR classes
Nighttime bins: 20 of 20 USTAR classes
Median scaling factors:
Daytime median: 0.1700 (range: 0.0119 - 0.3640)
Nighttime median: 0.0783 (range: 0.0260 - 0.2044)
Daytime scaling factors (sample of first 10 bins):
Bin 0 (USTAR 0.034-0.148): 0.3640 ± 0.1410
Bin 1 (USTAR 0.150-0.202): 0.3396 ± 0.0849
Bin 2 (USTAR 0.203-0.240): 0.2317 ± 0.1059
Bin 3 (USTAR 0.240-0.277): 0.3019 ± 0.0781
Bin 4 (USTAR 0.278-0.316): 0.3223 ± 0.0366
Bin 5 (USTAR 0.316-0.354): 0.2863 ± 0.0328
Bin 6 (USTAR 0.354-0.390): 0.2485 ± 0.0342
Bin 7 (USTAR 0.391-0.429): 0.1949 ± 0.0370
Bin 8 (USTAR 0.429-0.463): 0.2023 ± 0.0168
Bin 9 (USTAR 0.464-0.504): 0.1729 ± 0.0345
Full scaling factors table (all 40 bins):
DAYTIME GROUP_CLASSVAR GROUP_CLASSVAR_MIN GROUP_CLASSVAR_MAX SF_MEDIAN SF_Q25 SF_Q75
0.0 0.0 0.009705 0.096451 0.097392 0.060174 0.128668
0.0 1.0 0.097288 0.125969 0.103717 0.086052 0.119264
0.0 2.0 0.126229 0.153234 0.204362 0.180711 0.211678
0.0 3.0 0.154278 0.175524 0.127872 0.106128 0.153747
0.0 4.0 0.175830 0.205114 0.154198 0.130319 0.182283
0.0 5.0 0.205670 0.233637 0.095957 0.079699 0.108700
0.0 6.0 0.233973 0.261193 0.099111 0.077142 0.118229
0.0 7.0 0.262006 0.288081 0.075158 0.061615 0.091231
0.0 8.0 0.288266 0.318849 0.077901 0.062385 0.096140
0.0 9.0 0.319154 0.350800 0.122974 0.100852 0.150222
0.0 10.0 0.351838 0.393617 0.106821 0.091548 0.119360
0.0 11.0 0.394306 0.437695 0.077979 0.072020 0.091130
0.0 12.0 0.439479 0.491564 0.077045 0.067282 0.089632
0.0 13.0 0.493223 0.551757 0.054120 0.048068 0.062841
0.0 14.0 0.552011 0.608313 0.053934 0.049003 0.062132
0.0 15.0 0.611962 0.689758 0.066425 0.059845 0.072239
0.0 16.0 0.689831 0.791907 0.055408 0.046867 0.068995
0.0 17.0 0.794678 0.901162 0.067932 0.063199 0.076984
0.0 18.0 0.905212 1.101810 0.078679 0.069131 0.085337
0.0 19.0 1.135670 1.432790 0.025977 0.016184 0.037303
1.0 0.0 0.034350 0.148293 0.364047 0.321975 0.462949
1.0 1.0 0.150059 0.201708 0.339601 0.278428 0.363371
1.0 2.0 0.202819 0.239636 0.231693 0.200655 0.306529
1.0 3.0 0.239810 0.277214 0.301892 0.280930 0.359063
1.0 4.0 0.277994 0.315933 0.322336 0.301604 0.338162
1.0 5.0 0.316363 0.353507 0.286259 0.266749 0.299522
1.0 6.0 0.353601 0.390182 0.248456 0.233410 0.267581
1.0 7.0 0.390734 0.428841 0.194851 0.173866 0.210880
1.0 8.0 0.428941 0.463351 0.202277 0.191725 0.208490
1.0 9.0 0.463950 0.503596 0.172916 0.155756 0.190237
1.0 10.0 0.503653 0.545359 0.167057 0.159385 0.170876
1.0 11.0 0.545667 0.583925 0.132996 0.118491 0.142496
1.0 12.0 0.584412 0.627375 0.158480 0.145563 0.163802
1.0 13.0 0.627962 0.669595 0.121421 0.110047 0.139100
1.0 14.0 0.669737 0.718454 0.113776 0.110349 0.115678
1.0 15.0 0.719067 0.780076 0.123372 0.114277 0.127100
1.0 16.0 0.780865 0.848157 0.120266 0.112915 0.126130
1.0 17.0 0.848605 0.937463 0.101307 0.095404 0.105704
1.0 18.0 0.938638 1.109200 0.086614 0.072669 0.095385
1.0 19.0 1.116500 1.888570 0.011945 0.000006 0.041171
PHASE 2: APPLICATION — Correct Long-Term Data¶
Now apply the scaling factors table to open-path flux data from a period the optimization never saw. The same physics model is used, but no closed-path reference and no optimization are needed: the correction comes from the pre-computed table.
print(f"\n" + "=" * 80)
print("PHASE 2: APPLICATION — Correct Long-Term Flux Data")
print("=" * 80)
# Load the operational period: the second half of 2017, held back from calibration.
# Only the open-path flux and the physics drivers are used below, so this stands in
# for the multi-year, open-path-only record a real application would have.
df_longterm = load_exampledata_parquet_lae()
df_longterm = df_longterm.loc["2017-07-01 00:15:00":"2017-12-31 23:45:00"].copy()
print(f"\nLong-term data period: {df_longterm.index.min()} to {df_longterm.index.max()}")
print(f"Total records: {len(df_longterm):,}")
print("Note: half a year here; in practice this would be the multi-year record.")
================================================================================
PHASE 2: APPLICATION — Correct Long-Term Flux Data
================================================================================
> 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).
Long-term data period: 2017-07-01 00:15:00 to 2017-12-31 23:45:00
Total records: 8,832
Note: half a year here; in practice this would be the multi-year record.
Step 1b: Physics calculation (Long-term Period)¶
Apply ScopPhysics to the long-term dataset using the same methodology as calibration.
print(f"\n" + "=" * 80)
print("Step 1b: Physics Calculation (Long-term Period)")
print("=" * 80)
tic = time.time()
physics_longterm = ScopPhysics(
ta=df_longterm["TA_T1_47_1_gfXG_IRGA72"].copy(),
gas_density=df_longterm["CO2_MOLAR_DENSITY_IRGA75"].copy() * 1000,
rho_a=df_longterm["AIR_DENSITY_IRGA72"].copy(),
rho_v=df_longterm["VAPOR_DENSITY_IRGA72"].copy(),
u=df_longterm["U_IRGA72"].copy(),
c_p=df_longterm["AIR_CP_IRGA72"].copy(),
ustar=df_longterm["USTAR_IRGA72"].copy(),
lat=47.478333,
lon=8.364389,
utc_offset=1,
)
physics_longterm.run(correction_method_base="JAR09", gapfill=True)
results_physics_longterm = physics_longterm.get_results()
elapsed = time.time() - tic
print(f"\n[OK] Physics calculation completed in {elapsed:.1f}s")
physics_longterm.stats()
# Plot diurnal cycles for long-term period
print(f"\nGenerating diurnal cycle plots...")
physics_longterm.plot_diel_cycles(showplot=False)

================================================================================
Step 1b: Physics Calculation (Long-term Period)
================================================================================
! 115 data points resulted in NaN due to ustar <= 0.
> Aerodynamic resistance: Mean = 30.19 s m-1
> Dry air density: Mean = 1.1307 kg m-3
> 49 feature(s), 6,411 complete record(s) of 8,717 (2017-07-01 00:15:00 to
2017-12-31 23:45:00)
> Train/test split: 4,808 train / 1,603 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 8717 records where all features available.
> Filling 2306 missing records in FCT_UNSC_gfXG ...
> Fallback: filling 0 remaining gaps in FCT_UNSC_gfXG ...
>
XGBoost Performance Metrics:
> mae: 0.6915
> medae: 0.3851
> mse: 1.7379
> rmse: 1.3183
> mape: 0.0688
> maxe: 21.8372
> r2: 0.9798
> (i) XGBoost left 115 gaps (expected at edges with insufficient drivers)
[OK] Physics calculation completed in 3.2s
=================================================================
SCOP PHYSICS DIAGNOSTICS (CO2)
=================================================================
1. DATA COVERAGE & GAP-FILLING
------------------------------
Total Timestamps : 8,832
Raw Physics Calculated : 6,411 ( 72.6%)
Final Gap-Filled (GF) : 8,717 ( 98.7%)
-> Gap-filled (XGBoost): 2,306 ( 26.1%)
2. INSTRUMENT SELF-HEATING (Ts - Ta)
------------------------------
Avg Daytime Heating : +2.23 °C
Max Daytime Heating : +3.57 °C
Avg Nighttime Offset : +1.97 °C
3. UNSCALED CORRECTION TERM (FCT_unsc)
(Units: µmol m-2 s-1)
------------------------------
DAYTIME : +15.5544 ± 11.3015 [Range: -1.03 to 57.68]
NIGHTTIME : +9.4167 ± 9.1589 [Range: -0.31 to 55.67]
4. KEY DRIVERS (Daytime Avg)
------------------------------
Radiation (SW_IN) : 577 W m-2
Wind Speed (U) : 2.52 m s-1
Aero Resistance (Ra) : 12.7 s m-1
=================================================================
Generating diurnal cycle plots...
> Plotting Physics Diel Cycles...
<Figure size 2200x1200 with 8 Axes>
Step 2b: Apply lookup table (Long-term Period)¶
Use ScopApplicator with the pre-computed scaling factors table to correct long-term fluxes. No optimization is needed; the table provides scaling factors.
print(f"\n" + "=" * 80)
print("Step 2b: Apply Scaling Factors Table (Long-term Period)")
print("=" * 80)
print("Correcting long-term fluxes using pre-computed lookup table...")
tic = time.time()
applicator_longterm = ScopApplicator(
fct_unsc=results_physics_longterm["FCT_UNSC_gfXG"],
scaling_factors_df=scaling_factors_df, # Reuse table from calibration
flux_openpath=df_longterm["NEE_L3.1_L3.2_QCF_IRGA75"].copy(),
classvar=df_longterm["USTAR_IRGA72"].copy(),
daytime=results_physics_longterm["DAYTIME"].copy()
)
applicator_longterm.run()
results_longterm_df = applicator_longterm.get_results()
elapsed = time.time() - tic
print(f"\n[OK] Correction applied in {elapsed:.1f}s")
================================================================================
Step 2b: Apply Scaling Factors Table (Long-term Period)
================================================================================
Correcting long-term fluxes using pre-computed lookup table...
! (!) Warning: 115 fluxes missing Scaling Factor (due to missing
USTAR_IRGA72).
> Imputing using Month-Daytime-Hour-Minute Diel Cycle Median...
> > Successfully imputed 115 missing Scaling Factors.
[OK] Correction applied in 0.0s
Long-Term Correction Results¶
Examine the correction impact on the long-term dataset. The scaling factors table applies systematic correction across all seasons and years.
print(f"\n" + "=" * 80)
print("Long-Term Correction Impact Summary")
print("=" * 80)
flux_longterm_uncorr = df_longterm["NEE_L3.1_L3.2_QCF_IRGA75"]
flux_longterm_corr = results_longterm_df['NEE_OP_CORR']
print(f"\nFlux statistics (long-term period):")
print(f" Open-path (uncorrected): {flux_longterm_uncorr.mean():>8.3f} µmol m-2 s-1 (N={flux_longterm_uncorr.count()})")
print(f" Open-path (corrected): {flux_longterm_corr.mean():>8.3f} µmol m-2 s-1")
print(f" Correction (mean): {(flux_longterm_corr - flux_longterm_uncorr).mean():>8.3f} µmol m-2 s-1")
# Budget impact
budget_uncorr = flux_longterm_uncorr.sum()
budget_corr = flux_longterm_corr.sum()
budget_change = budget_corr - budget_uncorr
print(f"\nBudget impact over the application period (cumulative):")
print(f" Uncorrected sum: {budget_uncorr:>12,.0f} µmol m-2")
print(f" Corrected sum: {budget_corr:>12,.0f} µmol m-2")
print(f" Net adjustment: {budget_change:>12,.0f} µmol m-2 ({(budget_change/abs(budget_uncorr))*100:+.1f}%)")
print(f"\nDetailed correction statistics:")
applicator_longterm.stats()
# Plot long-term correction dashboard
print(f"\nGenerating long-term correction dashboard...")
applicator_longterm.plot_dashboard(showplot=False)

================================================================================
Long-Term Correction Impact Summary
================================================================================
Flux statistics (long-term period):
Open-path (uncorrected): -5.495 µmol m-2 s-1 (N=4166)
Open-path (corrected): -3.802 µmol m-2 s-1
Correction (mean): 1.693 µmol m-2 s-1
Budget impact over the application period (cumulative):
Uncorrected sum: -22,890 µmol m-2
Corrected sum: -15,837 µmol m-2
Net adjustment: 7,053 µmol m-2 (+30.8%)
Detailed correction statistics:
===========================================================================
FLUX CORRECTION REPORT
===========================================================================
Flux Type : CO2
Total Records : 4,166
---------------------------------------------------------------------------
1. SCALING FACTOR ASSIGNMENT (Method Used)
...........................................................................
Direct Lookup (Valid USTAR_IRGA72) : 4,166 (100.0%)
i Gap-Filled (MDV Imputation) : 0 ( 0.0%)
Median Scaling Factor (Day) : 0.195
Median Scaling Factor (Night) : 0.097
2. CORRECTION IMPACT (Budget) (Units: Sum)
...........................................................................
Uncorrected Sum : -22,890
Corrected Sum : -15,837
Net Adjustment : 7,053 (+30.8%)
===========================================================================
Generating long-term correction dashboard...
> Generating Comprehensive Flux Dashboard (Large Font Edition)...
<Figure size 2400x2000 with 13 Axes>
Scaling factor assignment distribution (Long-term)¶
Display how scaling factors were assigned across USTAR bins for the long-term period.
print(f"\n" + "=" * 80)
print("Scaling Factor Assignment (Long-term)")
print("=" * 80)
sf_col = results_longterm_df['SF']
group_col = results_longterm_df['GROUP_CLASSVAR']
print(f"\nScaling factor statistics by USTAR class:")
for daytime_flag, label in [(1.0, "DAYTIME"), (0.0, "NIGHTTIME")]:
mask = results_physics_longterm['DAYTIME'] == daytime_flag
if mask.sum() > 0:
print(f"\n{label}:")
for bin_id in range(10): # Show first 10 bins as example
bin_mask = (group_col == bin_id) & mask
if bin_mask.sum() > 0:
sf_vals = sf_col[bin_mask]
print(f" Bin {int(bin_id):2d}: SF={sf_vals.mean():.4f} ± {sf_vals.std():.4f} (N={bin_mask.sum()})")
================================================================================
Scaling Factor Assignment (Long-term)
================================================================================
Scaling factor statistics by USTAR class:
DAYTIME:
Bin 0: SF=0.3640 ± 0.0000 (N=226)
Bin 1: SF=0.3396 ± 0.0000 (N=235)
Bin 2: SF=0.2317 ± 0.0000 (N=183)
Bin 3: SF=0.3019 ± 0.0000 (N=215)
Bin 4: SF=0.3223 ± 0.0000 (N=260)
Bin 5: SF=0.2863 ± 0.0000 (N=225)
Bin 6: SF=0.2485 ± 0.0000 (N=250)
Bin 7: SF=0.1949 ± 0.0000 (N=244)
Bin 8: SF=0.2023 ± 0.0000 (N=242)
Bin 9: SF=0.1729 ± 0.0000 (N=244)
NIGHTTIME:
Bin 0: SF=0.0974 ± 0.0000 (N=270)
Bin 1: SF=0.1037 ± 0.0000 (N=273)
Bin 2: SF=0.2044 ± 0.0000 (N=256)
Bin 3: SF=0.1279 ± 0.0000 (N=222)
Bin 4: SF=0.1542 ± 0.0000 (N=289)
Bin 5: SF=0.0960 ± 0.0000 (N=255)
Bin 6: SF=0.0991 ± 0.0000 (N=194)
Bin 7: SF=0.0752 ± 0.0000 (N=210)
Bin 8: SF=0.0779 ± 0.0000 (N=210)
Bin 9: SF=0.1230 ± 0.0000 (N=202)
Using the Scaling Factors Table in Future Applications¶
The scaling factors table is now ready for operational use. It can be saved and applied to any future period at the same site as long as the instrument configuration remains unchanged.
# Save table for future use
scaling_factors_df.to_csv("scaling_factors_table.csv", index=False)
# Later: Load and apply to new data period
sf_table = pd.read_csv("scaling_factors_table.csv")
applicator = ScopApplicator(
fct_unsc=fct_unsc_future,
scaling_factors_df=sf_table,
flux_openpath=flux_future,
classvar=ustar_future,
daytime=daytime_future
)
applicator.run()
corrected_flux = applicator.get_results()['NEE_OP_CORR']
print(f"\n" + "=" * 80)
print("PRODUCTION WORKFLOW COMPLETE")
print("=" * 80)
print(f"\n[OK] Calibration phase: Scaling factors table created ({len(scaling_factors_df)} bins)")
print(f"[OK] Application phase: Long-term fluxes corrected ({flux_longterm_corr.count()} records)")
print(f"\nScaling factors table ready for:")
print(f" - Operational correction of multi-year flux datasets")
print(f" - Annual carbon budget calculations")
print(f" - Ecosystem response analysis")
print(f" - Gap-filling and quality control workflows")
dt_string = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"\nFinished. {dt_string}")
================================================================================
PRODUCTION WORKFLOW COMPLETE
================================================================================
[OK] Calibration phase: Scaling factors table created (40 bins)
[OK] Application phase: Long-term fluxes corrected (4166 records)
Scaling factors table ready for:
- Operational correction of multi-year flux datasets
- Annual carbon budget calculations
- Ecosystem response analysis
- Gap-filling and quality control workflows
Finished. 2026-10-21 00:20:42
Total running time of the script: (0 minutes 10.744 seconds)