Gap-filling (dv.gapfilling)¶
Machine-learning and meteorological-similarity gap-filling, plus the feature engineering that feeds the models.
Imported as diive.gapfilling, reached as dv.gapfilling after import diive as dv.
GAP-FILLING: TIME SERIES IMPUTATION METHODS¶
ML and statistical methods for filling missing data: Random Forest, XGBoost, MDS, linear interpolation, long-term per-year models and a dedicated SW_IN gap-filler. Feature engineering pipeline and model scoring included.
Part of the diive library: https://github.com/holukas/diive
- class diive.gapfilling.FeatureEngineer(target_col, verbose=0, features_lag=None, features_lag_stepsize=1, features_lag_exclude_cols=None, features_rolling=None, features_rolling_exclude_cols=None, features_rolling_stats=None, features_diff=None, features_diff_exclude_cols=None, features_ema=None, features_ema_exclude_cols=None, features_poly_degree=None, features_poly_exclude_cols=None, features_stl=False, features_stl_method='stl', features_stl_seasonal_period=None, features_stl_exclude_cols=None, features_stl_components=None, vectorize_timestamps=False, add_continuous_record_number=False, sanitize_timestamp=False)[source]¶
Bases:
objectStandalone feature engineering for time series data.
Separates feature engineering from gap-filling models, enabling: - Pre-computation of features once, reuse across multiple models - Independent testing and debugging - Composition-based API: engineer features → pass to any model - Feature reuse with non-gap-filling models
Usage:
engineer = FeatureEngineer( target_col='target_column_name', features_lag=[-1, 1], features_rolling=[12], # ... other parameters ) df_engineered = engineer.fit_transform(input_df) # Pass df_engineered to gap-filling models
See also
examples/gapfilling/gapfill_randomforest.py — Random Forest gap-filling with feature engineering examples/gapfilling/gapfill_xgboost.py — XGBoost gap-filling with feature engineering examples/gapfilling/gapfill_comparison.py — Multi-method comparison using engineered features
- Parameters:
target_col (str)
verbose (int)
features_lag (list)
features_lag_stepsize (int)
features_lag_exclude_cols (list)
features_rolling (list)
features_rolling_exclude_cols (list)
features_rolling_stats (list)
features_diff (list)
features_diff_exclude_cols (list)
features_ema (list)
features_ema_exclude_cols (list)
features_poly_degree (int)
features_poly_exclude_cols (list)
features_stl (bool)
features_stl_method (str)
features_stl_seasonal_period (int)
features_stl_exclude_cols (list)
features_stl_components (list)
vectorize_timestamps (bool)
add_continuous_record_number (bool)
sanitize_timestamp (bool)
- __init__(target_col, verbose=0, features_lag=None, features_lag_stepsize=1, features_lag_exclude_cols=None, features_rolling=None, features_rolling_exclude_cols=None, features_rolling_stats=None, features_diff=None, features_diff_exclude_cols=None, features_ema=None, features_ema_exclude_cols=None, features_poly_degree=None, features_poly_exclude_cols=None, features_stl=False, features_stl_method='stl', features_stl_seasonal_period=None, features_stl_exclude_cols=None, features_stl_components=None, vectorize_timestamps=False, add_continuous_record_number=False, sanitize_timestamp=False)[source]¶
Initialize feature engineer with 8-stage composable pipeline.
The FeatureEngineer creates temporal and statistical features from time series data. Set unused parameters to None/False to skip those stages. All features use naming convention: .{col}_{TYPE}{detail} (e.g., .Tair_f_MEAN12 for rolling mean with window 12, .Tair_f_POL2 for the squared values). Lags are named .{col}-1 and .{col}+1. Columns already carrying that . prefix in the input are never used as sources by the per-column stages, so running the engineer on its own output adds nothing rather than engineering the engineered columns.
=== STAGE 1: LAG FEATURES (Temporal Context) ===
- Parameters:
features_lag (
list) –[min_lag, max_lag] range for creating lag features. Default: None (disabled) Typical values:
None: Disable (very fast, but no temporal context)
[-1, -1]: Only past value (minimal, good for speed tests)
[-1, 1]: Past and future lags (captures local patterns)
[-2, 2]: Extended range for slower-moving signals
Effect on time series: Creates past/future context. Negative lag=past, positive lag=future. Example: [-1, 1] with stepsize=1 creates lags [-1, 0, 1] but 0 is excluded, resulting in [-1, 1].
features_lag_stepsize (
int) –Step between lags when range is large. Default: 1 (every lag value) Typical values:
1: Include all lags in range ([-2,2,stepsize=1] → [-2,-1,1,2])
2: Skip every other ([-4,4,stepsize=2] → [-4,-2,2,4], faster)
Effect: Reduces number of features for large lag ranges. Trades feature detail for speed.
features_lag_exclude_cols (
list) – Column names to exclude from lagging. Default: None (lag all columns except target) Typical use: Skip invariant columns like site ID, quality flags Effect: None means “lag everything”. Empty list [] means same (lag all).target_col (str)
verbose (int)
features_rolling (list)
features_rolling_exclude_cols (list)
features_rolling_stats (list)
features_diff (list)
features_diff_exclude_cols (list)
features_ema (list)
features_ema_exclude_cols (list)
features_poly_degree (int)
features_poly_exclude_cols (list)
features_stl (bool)
features_stl_method (str)
features_stl_seasonal_period (int)
features_stl_exclude_cols (list)
features_stl_components (list)
vectorize_timestamps (bool)
add_continuous_record_number (bool)
sanitize_timestamp (bool)
=== STAGE 2: ROLLING STATISTICS (Local Context Windows) ===
- Parameters:
features_rolling (
list) –Window sizes for rolling aggregation. Default: None (disabled) Typical values:
None: Disable (very fast)
[12, 24]: 12 and 24 hour windows for 30-min flux data
[7, 30]: Weekly and monthly windows for daily data
Effect on time series: Creates local averages. For 30-min data, window=12 means ~6-hour rolling window. Captures short-term trends and noise.
features_rolling_stats (
list) –Statistics to compute (beyond default mean/std). Default: None (use mean + std only) Typical values:
None: Just mean and std deviation (fast)
[‘median’, ‘min’, ‘max’]: Robust to outliers
[‘median’, ‘min’, ‘max’, ‘q25’, ‘q75’]: Full distribution
Effect: None means only mean+std computed. Other stats add robustness to outliers and capture asymmetric distributions.
features_rolling_exclude_cols (
list) – Exclude columns from rolling. Default: None (roll all columns except target) Typical use: Skip categorical or invariant columns Effect: None means “roll everything”.target_col (str)
verbose (int)
features_lag (list)
features_lag_stepsize (int)
features_lag_exclude_cols (list)
features_diff (list)
features_diff_exclude_cols (list)
features_ema (list)
features_ema_exclude_cols (list)
features_poly_degree (int)
features_poly_exclude_cols (list)
features_stl (bool)
features_stl_method (str)
features_stl_seasonal_period (int)
features_stl_exclude_cols (list)
features_stl_components (list)
vectorize_timestamps (bool)
add_continuous_record_number (bool)
sanitize_timestamp (bool)
=== STAGE 3: TEMPORAL DIFFERENCING (Rate of Change) ===
- Parameters:
features_diff (
list) –Difference orders [1, 2, …]. Default: None (disabled) Typical values:
None: Disable (no rate-of-change features)
[1]: First-order differences (rate of change)
[1, 2]: First and second differences (rate + acceleration)
Effect on time series: Order-1 differencing removes trends, reveals variability. Order-2 reveals acceleration. Essential for detecting rapidly changing signals (e.g., convection events, sensor failures).
features_diff_exclude_cols (
list) – Exclude from differencing. Default: None (diff all columns except target)target_col (str)
verbose (int)
features_lag (list)
features_lag_stepsize (int)
features_lag_exclude_cols (list)
features_rolling (list)
features_rolling_exclude_cols (list)
features_rolling_stats (list)
features_ema (list)
features_ema_exclude_cols (list)
features_poly_degree (int)
features_poly_exclude_cols (list)
features_stl (bool)
features_stl_method (str)
features_stl_seasonal_period (int)
features_stl_exclude_cols (list)
features_stl_components (list)
vectorize_timestamps (bool)
add_continuous_record_number (bool)
sanitize_timestamp (bool)
=== STAGE 4: EXPONENTIAL MOVING AVERAGE (Weighted Historical Context) ===
- Parameters:
features_ema (
list) –EMA spans [6, 24, 48, …]. Default: None (disabled) Typical values:
None: Disable (no long-term memory)
[6, 24]: 6-hr and 24-hr exponential moving averages (for 30-min data)
[7, 30]: Weekly and monthly for daily data
Effect on time series: EMA gives more weight to recent values while remembering history. Span=6 means ~6 timesteps influence (20% decaying weight structure). Essential for multi-timescale patterns.
features_ema_exclude_cols (
list) – Exclude from EMA. Default: None (apply EMA to all columns except target)target_col (str)
verbose (int)
features_lag (list)
features_lag_stepsize (int)
features_lag_exclude_cols (list)
features_rolling (list)
features_rolling_exclude_cols (list)
features_rolling_stats (list)
features_diff (list)
features_diff_exclude_cols (list)
features_poly_degree (int)
features_poly_exclude_cols (list)
features_stl (bool)
features_stl_method (str)
features_stl_seasonal_period (int)
features_stl_exclude_cols (list)
features_stl_components (list)
vectorize_timestamps (bool)
add_continuous_record_number (bool)
sanitize_timestamp (bool)
=== STAGE 5: POLYNOMIAL EXPANSION (Non-linear Relationships) ===
- Parameters:
features_poly_degree (
int) –Polynomial degree. Default: None (disabled) Typical values:
None: Disable (linear relationships only)
2: Squared terms (quadratic relationships, most common)
3: Cubic terms (rare, very non-linear)
Effect on time series: Degree=2 creates X² features for each column. Essential for capturing saturation effects (e.g., photosynthesis plateaus at high light). Quadratic relationships common in ecology.
features_poly_exclude_cols (
list) – Exclude from polynomial. Default: None (apply to all columns except target)target_col (str)
verbose (int)
features_lag (list)
features_lag_stepsize (int)
features_lag_exclude_cols (list)
features_rolling (list)
features_rolling_exclude_cols (list)
features_rolling_stats (list)
features_diff (list)
features_diff_exclude_cols (list)
features_ema (list)
features_ema_exclude_cols (list)
features_stl (bool)
features_stl_method (str)
features_stl_seasonal_period (int)
features_stl_exclude_cols (list)
features_stl_components (list)
vectorize_timestamps (bool)
add_continuous_record_number (bool)
sanitize_timestamp (bool)
=== STAGE 6: STL DECOMPOSITION (Trend/Seasonal Separation) ===
- Parameters:
features_stl (
bool) – Enable STL decomposition. Default: False (disabled) Set to: True or False Effect if False: No decomposition, skip this stage entirely (fast). Effect if True: Separates time series into trend, seasonal, residual components. Requires specifying seasonal_period and method.features_stl_method (
str) –Decomposition algorithm. Default: ‘stl’ (Seasonal-Trend Loess) Options:
’stl’: Robust, handles gaps, works with non-stationary data (best)
’classical’: Moving average method, assumes stationarity
’harmonic’: FFT-based, no series length constraints, very fast
Effect: ‘stl’ recommended for flux data (has gaps, strong seasonality). ‘harmonic’ for very long series or when speed critical. Gaps: ‘stl’ and ‘harmonic’ decompose a gappy column and return components that are NaN at its gaps (the same records the column itself already loses); ‘classical’ cannot, and skips the column with a warning.
features_stl_seasonal_period (
int) –Seasonal period in timesteps. Default: None (auto-detect via periodogram if features_stl=True) Typical values for 30-min flux data:
None: Auto-detect (recommended, ~48 for daily cycle)
48: Daily cycle (30-min × 48 = 24 hours)
336: Weekly cycle (30-min × 336 = 7 days)
17520: Annual cycle (30-min × 17520 = 365 days)
Effect: None means auto-detect from data (slower but robust). Explicit value is faster. Wrong period produces useless seasonal component.
features_stl_exclude_cols (
list) – Exclude from STL. Default: None (apply to all columns except target) Typical use: Skip columns without strong seasonalityfeatures_stl_components (
list) –Components to extract. Default: None (extract all: trend, seasonal, residual) Options:
None: All three components
[‘trend’]: Trend only (removes noise and seasonality)
[‘trend’, ‘seasonal’]: Trend and seasonal (removes residual noise)
[‘trend’, ‘seasonal’, ‘residual’]: All components (default)
Effect: None extracts all. Selecting subset reduces features but keeps what’s needed. Trend alone useful for detrending, removes diurnal cycles.
target_col (str)
verbose (int)
features_lag (list)
features_lag_stepsize (int)
features_lag_exclude_cols (list)
features_rolling (list)
features_rolling_exclude_cols (list)
features_rolling_stats (list)
features_diff (list)
features_diff_exclude_cols (list)
features_ema (list)
features_ema_exclude_cols (list)
features_poly_degree (int)
features_poly_exclude_cols (list)
vectorize_timestamps (bool)
add_continuous_record_number (bool)
sanitize_timestamp (bool)
=== STAGE 7: TIMESTAMP FEATURES (Diurnal/Seasonal Cycles) ===
- Parameters:
vectorize_timestamps (
bool) –Add timestamp-derived features. Default: False (disabled, fast) Set to: True or False Effect if False: No timestamp features (skip stage, 2-3% speedup). Effect if True: Creates 14 features: .YEAR, sin/cos versions of season, month, week, DOY (day-of-year) and hour for circular encoding, and the combined .YEARMONTH, .YEARDOY and .YEARWEEK. The linear season, month, week, DOY and hour columns are dropped. Captures diurnal cycles (photosynthesis) and seasonal patterns (dormancy). Typical use:
False: For fast testing or when temporal patterns already captured
True: Essential for gap-filling (captures daily/seasonal cycles)
Effect on time series: Sine/cosine encoding treats day-of-year as circular (Dec→Jan continuous). Creates cyclic features that models can learn (e.g., morning vs evening photosynthesis).
target_col (str)
verbose (int)
features_lag (list)
features_lag_stepsize (int)
features_lag_exclude_cols (list)
features_rolling (list)
features_rolling_exclude_cols (list)
features_rolling_stats (list)
features_diff (list)
features_diff_exclude_cols (list)
features_ema (list)
features_ema_exclude_cols (list)
features_poly_degree (int)
features_poly_exclude_cols (list)
features_stl (bool)
features_stl_method (str)
features_stl_seasonal_period (int)
features_stl_exclude_cols (list)
features_stl_components (list)
add_continuous_record_number (bool)
sanitize_timestamp (bool)
=== STAGE 8: SEQUENTIAL RECORD NUMBERING (Temporal Ordering) ===
- Parameters:
add_continuous_record_number (
bool) –Add sequential 1,2,3,… numbering. Default: False (disabled) Set to: True or False Effect if False: No record number (skip stage). Effect if True: Creates column .RECORDNUMBER = 1, 2, 3, … Captures long-term drift (instrument drift, ecosystem changes). Typical use:
False: Most cases (minimal benefit, adds collinearity)
True: When long-term drift is important (>1 year data)
Effect on time series: Linear feature captures systematic drift over time (e.g., accumulation, senescence).
target_col (str)
verbose (int)
features_lag (list)
features_lag_stepsize (int)
features_lag_exclude_cols (list)
features_rolling (list)
features_rolling_exclude_cols (list)
features_rolling_stats (list)
features_diff (list)
features_diff_exclude_cols (list)
features_ema (list)
features_ema_exclude_cols (list)
features_poly_degree (int)
features_poly_exclude_cols (list)
features_stl (bool)
features_stl_method (str)
features_stl_seasonal_period (int)
features_stl_exclude_cols (list)
features_stl_components (list)
vectorize_timestamps (bool)
sanitize_timestamp (bool)
=== DATA QUALITY ===
- Parameters:
sanitize_timestamp (
bool) –Validate and prepare timestamps. Default: False (skip validation, assume clean timestamps) Set to: True or False Effect if False: Trust input timestamps (fast, assumes clean). Effect if True: Validate and fix timestamp issues (duplicates, gaps, non-monotonic) and convert the index to TIMESTAMP_MIDDLE. This runs after all features are computed, so it does not change how they were built. Typical use:
False: When data already validated (production)
True: First-time data processing (safety check)
target_col (str)
verbose (int)
features_lag (list)
features_lag_stepsize (int)
features_lag_exclude_cols (list)
features_rolling (list)
features_rolling_exclude_cols (list)
features_rolling_stats (list)
features_diff (list)
features_diff_exclude_cols (list)
features_ema (list)
features_ema_exclude_cols (list)
features_poly_degree (int)
features_poly_exclude_cols (list)
features_stl (bool)
features_stl_method (str)
features_stl_seasonal_period (int)
features_stl_exclude_cols (list)
features_stl_components (list)
vectorize_timestamps (bool)
add_continuous_record_number (bool)
=== METADATA ===
- Parameters:
target_col (
str) – Column name of target variable. Effect: Excluded from all engineered features. All features created from other columns, target preserved unchanged in output.verbose (
int) –Progress reporting. Default: 0 (silent) Options:
0: No output
1: Progress updates (recommended)
2+: Detailed logging (debugging)
features_lag (list)
features_lag_stepsize (int)
features_lag_exclude_cols (list)
features_rolling (list)
features_rolling_exclude_cols (list)
features_rolling_stats (list)
features_diff (list)
features_diff_exclude_cols (list)
features_ema (list)
features_ema_exclude_cols (list)
features_poly_degree (int)
features_poly_exclude_cols (list)
features_stl (bool)
features_stl_method (str)
features_stl_seasonal_period (int)
features_stl_exclude_cols (list)
features_stl_components (list)
vectorize_timestamps (bool)
add_continuous_record_number (bool)
sanitize_timestamp (bool)
=== EXAMPLE SCENARIOS ===
Quick/Minimal (testing, fastest):
FeatureEngineer( target_col='NEE', features_lag=[-1, -1], # Only past # All others: None/False (disabled) ) # ~5 features total
Fast/Standard (production, balanced):
FeatureEngineer( target_col='NEE', features_lag=[-1, 1], features_rolling=[12, 24], features_diff=[1], vectorize_timestamps=True, ) # ~15-20 features total
Comprehensive (research, most detailed):
FeatureEngineer( target_col='NEE', features_lag=[-2, 2], features_rolling=[6, 12, 24], features_rolling_stats=['median', 'min', 'max'], features_diff=[1, 2], features_ema=[6, 24], features_poly_degree=2, features_stl=True, features_stl_seasonal_period=48, vectorize_timestamps=True, ) # ~50-100 features total
- Returns:
None. Configure with __init__, call fit_transform(df) to engineer features.
- Parameters:
target_col (str)
verbose (int)
features_lag (list)
features_lag_stepsize (int)
features_lag_exclude_cols (list)
features_rolling (list)
features_rolling_exclude_cols (list)
features_rolling_stats (list)
features_diff (list)
features_diff_exclude_cols (list)
features_ema (list)
features_ema_exclude_cols (list)
features_poly_degree (int)
features_poly_exclude_cols (list)
features_stl (bool)
features_stl_method (str)
features_stl_seasonal_period (int)
features_stl_exclude_cols (list)
features_stl_components (list)
vectorize_timestamps (bool)
add_continuous_record_number (bool)
sanitize_timestamp (bool)
- class diive.gapfilling.GapFillingResult(gapfilled, flag, scores, gapfilling_df, scores_traintest=None, feature_importances=None, feature_importances_traintest=None, feature_importances_reduction=None, model=None, accepted_features=None, rejected_features=None)[source]¶
Bases:
objectStructured output from a gap-filling run.
Returned by the
.resultsproperty onRandomForestTS,XGBoostTS,FluxMDS, and their variants.- Variables:
gapfilled (
Series) – Gap-filled target time series (observed + filled values).flag (
Series) – Quality flag — 0 = observed, 1 = gap-filled, 2 = fallback (ML only).scores (
dict) – In-sample performance metrics — the final model predicting on ALL complete rows, including the rows it was trained on, so these are optimistically biased. Dict with keys mae, medae, mse, rmse, mape, maxe, r2. Use scores_traintest for an honest generalization estimate.gapfilling_df (
DataFrame) – Full results DataFrame (all auxiliary columns included).scores_traintest (
Optional[dict]) – Held-out (out-of-sample) metrics from the train/test split — the generalization estimate; same keys as scores. The test set is a random subset of complete rows (scattered in time), not a temporal block, because gap records are predicted from drivers measured at the same timestamp. None for MDS.feature_importances (
Optional[DataFrame]) – SHAP importances from the gap-filling model. None for MDS.feature_importances_traintest (
Optional[DataFrame]) – SHAP importances from the train/test model. None for MDS.feature_importances_reduction (
Optional[DataFrame]) – SHAP importances measured during feature reduction, over the feature set as it stood before anything was dropped and including the.RANDOMbenchmark column the threshold is derived from. This is the only view carrying the benchmark itself, so it is what to inspect to see why a feature was kept or dropped. None unlessreduce_featuresran.model (
Optional[object]) – Trained sklearn/XGBoost regressor. None for MDS.accepted_features (
Optional[list]) – Feature names kept after SHAP-based reduction. None if not run.rejected_features (
Optional[list]) – Feature names removed after SHAP-based reduction. None if not run.
- Parameters:
gapfilled (Series)
flag (Series)
scores (dict)
gapfilling_df (DataFrame)
scores_traintest (dict | None)
feature_importances (DataFrame | None)
feature_importances_traintest (DataFrame | None)
feature_importances_reduction (DataFrame | None)
model (object | None)
accepted_features (list | None)
rejected_features (list | None)
Example
>>> import diive as dv >>> df = dv.load_exampledata_parquet()[['NEE_CUT_REF_f', 'Tair_f', 'Rg_f']] >>> rf = dv.gapfilling.RandomForestTS(input_df=df, target_col='NEE_CUT_REF_f') >>> rf.run() # then rf.results -> .gapfilled, .flag, .scores['r2'], .model
- __init__(gapfilled, flag, scores, gapfilling_df, scores_traintest=None, feature_importances=None, feature_importances_traintest=None, feature_importances_reduction=None, model=None, accepted_features=None, rejected_features=None)¶
- Parameters:
gapfilled (Series)
flag (Series)
scores (dict)
gapfilling_df (DataFrame)
scores_traintest (dict | None)
feature_importances (DataFrame | None)
feature_importances_traintest (DataFrame | None)
feature_importances_reduction (DataFrame | None)
model (object | None)
accepted_features (list | None)
rejected_features (list | None)
- Return type:
None
- diive.gapfilling.linear_interpolation(series, limit=3, verbose=False)[source]¶
Fill gaps in series with linear interpolation up to a specified size.
Fills missing values in a time series using linear interpolation, with control over the maximum consecutive gap size to fill. Gaps larger than the specified limit are preserved for other gap-filling methods (ML, MDS).
- Parameters:
series (
Series) – Time series with missing values (NaN). Must be a pandas Series with DatetimeIndex.limit (
int) – Maximum number of consecutive missing values to fill. Must be ≥ 1. Default: 3. Example: limit=1 fills only isolated single-value gaps, limit=5 fills gaps up to 5 consecutive records.verbose (
bool) – Print summary statistics table showing method parameters, input/output data, gap analysis, and gap size distribution. Default: False.
- Returns:
- Same index and name as input, with gaps ≤ limit
filled using linear interpolation. Gaps exceeding the limit remain as NaN. Original non-gap values are preserved.
- Return type:
- Raises:
TypeError – If series is not a pandas.Series.
ValueError – If series is empty, limit < 1, or index is not DatetimeIndex.
Examples
See examples/gapfilling/gapfill_interpolate_generous.py for examples demonstrating conservative (limit=1) vs. generous (limit=5) gap-filling strategies.
- class diive.gapfilling.FluxMDS(df, flux, swin, ta, vpd, swin_tol=None, ta_tol=2.5, vpd_tol=0.5, avg_min_n_vals=2, mode='diive', fill_marginal_gaps=True, vpd_in_kpa=True, swin_qc=None, ta_qc=None, vpd_qc=None, verbose=1, **legacy)[source]¶
Bases:
_MdsGapFillingBaseGap-filling for ecosystem fluxes using Marginal Distribution Sampling (MDS).
Fills missing flux data by matching meteorologically similar conditions (SWIN, TA, VPD) following ONEFlux’s 6-stage expanding-window cascade (Reichstein 2005). The cascade is shared with the daytime-partitioning NEE uncertainty (
diive.gapfilling.similarity).mode='diive'(default) fills with the symmetric mean of Vekuri et al. (2023) in the methods that match on SWIN, which removes a bias in the filled fluxes and the carbon balance. Validated against'oneflux'with synthetic truth and each site-year’s real gaps at 8 forest sites from 68 N to 30 S (8-11 years each): the annual balance error fell at 6 sites, most in the north and the tropics (FI-Var +11.0 -> +2.5, FI-Hyy +8.1 -> +1.4, GF-Guy +68.2 -> +60.0 g C m-2 y-1), barely at two drylands (IL-Yat, AU-GWW), and rose slightly at the deciduous DE-Hai (-9.7 -> -12.8), where the daytime error is already negative. The RMSE changed by -0.4 to +0.5 %. Harness:diive-data/references/mds_vekuri_validation.mode='oneflux'fills with the plain mean, as ONEFlux does (use it to compare with ICOS or FLUXNET products), andmode='reddyproc'follows REddyProc’ssMDSGapFill. Seemodein__init__.The time windows count records, so the data must be on a regular time grid. Data with missing timestamps (an index without a frequency) are put on the grid first, and the results are on that grid. See
dfin__init__.Measured agreement (
mode='oneflux'): compared with ONEFlux’sgf_mdstool, compiled from the ONEFlux 1.3.7 C source and run on the same input with the settings of ONEFlux’s pipeline (VPD in hPa,vpd_in_kpa=False). Filled values, SDs, sample counts, methods and windows are bitwise identical in every gap and every measured record, and so are the annual sums: NEE and LE for CH-DAV 2016 and 2019, NEE, H and LE for CH-LAE 2017-2019, each with the data’s own gaps, extra gaps of 2-30 days, missing drivers, 60+ day gaps at both ends of the year, and hourly data (65 runs). Harness:diive-data/references/mds_parity_oneflux. ONEFlux’s own NEE gap-filling (nee_proc) passes gap-filled drivers with their QC flags: with the same drivers andswin_qc/ta_qc/vpd_qc, FluxMDS matches it bitwise too (CH-DAV 2016/2019, CH-LAE 2017-2019). Without the QC columns, CH-LAE annual NEE differed by 3-10 gC m-2 (1-5 % of the gaps).Measured agreement (
mode='reddyproc'): compared with REddyProc 1.3.4sMDSGapFill(default method) on the same input, every gap value agrees to 2e-13 (R sums the mean in long double) and the annual sums are equal: NEE and LE for CH-DAV 2016 and 2019, NEE, H and LE for CH-LAE 2017-2019, with the data’s own gaps, extra gaps, missing drivers and gaps longer than 60 days (46 runs). Harness:diive-data/references/mds_parity_reddyproc.Examples
See examples/gapfilling/gapfill_mds.py for basic usage.
- Parameters:
- __init__(df, flux, swin, ta, vpd, swin_tol=None, ta_tol=2.5, vpd_tol=0.5, avg_min_n_vals=2, mode='diive', fill_marginal_gaps=True, vpd_in_kpa=True, swin_qc=None, ta_qc=None, vpd_qc=None, verbose=1, **legacy)¶
Gap-fill an ecosystem flux by marginal distribution sampling (MDS).
Missing values are replaced by the average measured flux during meteorologically similar conditions, using ONEFlux’s 6-stage expanding-window cascade.
- Parameters:
df (
DataFrame) – DataFrame with flux, swin, ta and vpd, with a datetime index. MDS needs a regular index without missing timestamps, because its time windows count records. Ifdf.indexhas no frequency set, the data are put on a regular grid at the detected time resolution: missing timestamps are added as empty (NaN) records and filled like other gaps. Records that are not on the grid are removed, with a warning that gives their number. The results are on this regular grid. df itself is not changed.flux (
str) – flux variable to gap-fill.swin (
str) – short-wave incoming radiation (W m-2).ta (
str) – air temperature (deg C).vpd (
str) – vapor pressure deficit. Unit set by vpd_in_kpa.swin_tol (
list) – SWIN tolerance clamp[min, max]in W m-2 (default[20, 50]). Following ONEFlux, a record’s SWIN tolerance is its own SWIN clamped into this range (grows with radiation).ta_tol (
float) – TA similarity tolerance (deg C, default 2.5).vpd_tol (
float) – VPD similarity tolerance (kPa, default 0.5 = ONEFlux 5 hPa).avg_min_n_vals (
int) – minimum similar samples to accept a fill. ONEFlux gap-filling uses 2 (default); larger values are stricter.mode (
str) –'diive'(default),'oneflux'or'reddyproc'. All three use the same tolerances and order of methods.'oneflux'fills with the plain mean of the similar records and reproduces ONEFlux’sgf_mdsbit for bit. Use it when results must match ICOS or FLUXNET products, which are gap-filled with ONEFlux.'reddyproc'reproduces REddyProc 1.3.4sMDSGapFill(default method, plain mean): its look-up windows include both ends and stop at +/-70 days, its last diurnal-cycle windows are +/-7, 14, …, 210 days, and every gap longer than 60 days stays unfilled, whateverfill_marginal_gapssays.'diive'uses ONEFlux’s windows.'diive'uses the symmetric mean of Vekuri et al. (2023) in the methods that match on SWIN (1 and 2): the similar records are split into those with less and those with more SWIN than the record being filled (records with equal SWIN count in both, as in ONEFlux’sgf_mds), and the fill is the mean of the two group means. This removes the bias from an uneven spread of SWIN within the tolerance. As in the paper, it applies to daytime records only (SWIN >= 20 W m-2); below that the plain mean is kept (REddyProc’sVekuri23uses 10 W m-2). At gaps, the SD, the sample count and the quality flags are the same in'diive'and'oneflux'. At measured records,'diive'leaves the record out of its own sample, so the scores are out-of-sample. ONEFlux keeps it, which with the symmetric mean would let the record echo itself.fill_marginal_gaps (
bool) – if True (default), fill everything (ONEFluxgf_mdsgap-filling behaviour). If False, leave leading/ trailing gaps longer than 60 days unfilled (the ONEFluxuncert_via_gapFilllongestMarginalgapguard).vpd_in_kpa (
bool) – if True (default), vpd is in kPa and vpd_tol applies directly. If False, vpd is in hPa and the kPa vpd_tol is converted to hPa (0.5 kPa -> 5 hPa, as in ONEFlux).swin_qc (
str) – optional column in df with the QC flag of that driver, 0 = measured, above 0 = gap-filled: a diiveFLAG_..._ISFILLEDcolumn or a FLUXNET*_F_QCcolumn. Given together with a gap-filled driver column, MDS works as ONEFlux does for NEE (nee_proc): the record being filled compares against its own driver value, gap-filled or not, but only records whose flag is 0 serve as similar samples. A missing flag (NaN) does not exclude a record. Methods 1 (all drivers) and 2 (SWIN) are affected, the diurnal cycle is not. Each driver is handled on its own. Default: no QC, every record with a driver value is a candidate (ONEFluxenergy_proc, H and LE).ta_qc (
str) – optional column in df with the QC flag of that driver, 0 = measured, above 0 = gap-filled: a diiveFLAG_..._ISFILLEDcolumn or a FLUXNET*_F_QCcolumn. Given together with a gap-filled driver column, MDS works as ONEFlux does for NEE (nee_proc): the record being filled compares against its own driver value, gap-filled or not, but only records whose flag is 0 serve as similar samples. A missing flag (NaN) does not exclude a record. Methods 1 (all drivers) and 2 (SWIN) are affected, the diurnal cycle is not. Each driver is handled on its own. Default: no QC, every record with a driver value is a candidate (ONEFluxenergy_proc, H and LE).vpd_qc (
str) – optional column in df with the QC flag of that driver, 0 = measured, above 0 = gap-filled: a diiveFLAG_..._ISFILLEDcolumn or a FLUXNET*_F_QCcolumn. Given together with a gap-filled driver column, MDS works as ONEFlux does for NEE (nee_proc): the record being filled compares against its own driver value, gap-filled or not, but only records whose flag is 0 serve as similar samples. A missing flag (NaN) does not exclude a record. Methods 1 (all drivers) and 2 (SWIN) are affected, the diurnal cycle is not. Each driver is handled on its own. Default: no QC, every record with a driver value is a candidate (ONEFluxenergy_proc, H and LE).verbose (
int) – verbosity level.
- Raises:
KeyError – If a column named in the arguments is not in df.
ValueError – If mode is not valid, or if
df.indexhas no frequency set and its time resolution cannot be detected.
- get_flag()¶
Gap-filling flag: 0 = observed, else granular (method*1000+window).
- get_gapfilled_target()¶
Gap-filled target time series.
- gfsuffix = '_gfMDS'¶
- plot_quality_timeseries(ax=None, legend=True, ax_labels_fontsize=None, legend_textsize=None, legend_ncol=None)¶
Gap-filled series over time, each point coloured + markered by its MDS flag level (0 = measured, else granular). Two-phase:
ax=Nonebuilds a standalone figure; pass anaxto embed it. Returns the axes.
- quality_breakdown()¶
Per-flag-level breakdown of the gap-filling flag.
One row per flag value present (sorted): level 0 = measured, else the granular
method*1000+windowflag. Columns:level,count,pct(% of all records),description.- Return type:
- report()¶
Print a comprehensive MDS gap-filling report.
- report_scores()¶
Print model performance scores with interpretation.
- property result: DataFrame¶
full gap-filling DataFrame (target + flag columns).
- Type:
Primary result
- property results: GapFillingResult¶
Structured result after
run().
- run(progress_callback=None)¶
Execute the ONEFlux MDS cascade in the selected mode.
- Parameters:
progress_callback – optional
callable(filled, total, quality, n_filled, remaining)for a GUI progress bar (gap counts).
- showplot()¶
Display MDS gap-filling results with plots.
- class diive.gapfilling.RandomForestTS(input_df, target_col, verbose=True, test_size=0.25, below_zero=None, **kwargs)[source]¶
Bases:
MlRegressorGapFillingBaseGap-fill a time series with scikit-learn Random Forest regression.
See
__init__()for parameters, methods and attributes.- __init__(input_df, target_col, verbose=True, test_size=0.25, below_zero=None, **kwargs)[source]¶
Gap-filling for time series using Random Forest regression.
Trains a Random Forest model on complete observations to predict missing values. Combines robustness to outliers with interpretability through feature importance analysis. Requires pre-engineered features from FeatureEngineer.
- Parameters:
input_df (
DataFrame) – DataFrame with target and pre-engineered feature columns. Features should be created with FeatureEngineer. Timestamps in DatetimeIndex.target_col (
str) – Column name of variable to gap-fill (string or tuple).verbose (
bool) – Verbosity level: 0=silent, 1=progress, 2+=detailed. Default: True (equivalent to 1).test_size (
float) – Fraction of complete data for testing (0.0-1.0). Default: 0.25. Only complete rows used for split.below_zero (
str) – How to treat predicted values below zero for variables that cannot be negative (e.g. VPD, SW_IN, PPFD). None (default): keep as-is. ‘zero’: clip to 0.**kwargs – Random Forest hyperparameters (n_estimators, max_depth, min_samples_split, min_samples_leaf, random_state, n_jobs, etc). See scikit-learn RandomForestRegressor documentation.
- Methods:
trainmodel() – Train on training data, evaluate on test data.
fillgaps() – Train on all complete data, predict missing values.
reduce_features() – Feature selection based on SHAP importance.
report_traintest() – Print model evaluation metrics.
report_gapfilling() – Print gap-filling results.
get_gapfilled_target() – Return gap-filled series.
get_flag() – Return gap-filling flags (0=observed, 1=gap-filled, 2=fallback).
- Variables:
model – Trained RandomForestRegressor instance.
gapfilling_df – DataFrame with gap-filled target.
feature_importances – SHAP feature importance.
scores – In-sample scores of the gap-filling model (MAE, RMSE, R²).
scores_traintest – Scores on the held-out test split.
Examples
See examples/gapfilling/gapfill_randomforest.py for complete examples. See examples/gapfilling/gapfill_comparison.py for side-by-side comparison with MDS and XGBoost gap-filling.
- property feature_importances_reduction_: DataFrame¶
a model with an added random variable, fitted and explained on the same training data
- Type:
Return feature importance from feature reduction
- property feature_importances_traintest_: DataFrame¶
Return feature importance from model training on training data, with importances calculated using test data (holdout set)
- fillgaps(showplot_scores=True, showplot_importance=True, progress_callback=None)¶
Gap-fill data with previously built model
No new model is built here, instead the last model built in the preceding step .trainmodel() is used.
y = target X = features
- Parameters:
showplot_scores (
bool) – shows plot of predicted vs observedshowplot_importance (
bool) – shows plot of SHAP feature importancesprogress_callback – Optional
callable(fraction: float)invoked as the full-record SHAP importance computation advances (0.0 -> 1.0). This is the slowest part on large records, and a caller can use it to drive a progress bar. When None (default) the SHAP call runs in one shot. The results are the same either way.
- get_flag()¶
Gap-filling flag, where 0=observed, 1=gap-filled, 2=gap-filled with fallback
- get_gapfilled_target()¶
Gap-filled target time series
- property model_¶
Return the model (trained on the training set).
- plot_feature_importances(ax=None, traintest=False, max_features=None, color='#003A70', error_color='#C41E3A', show_values=True, title='SHAP feature importance')¶
Plot SHAP feature importances as a horizontal bar chart (two-phase).
Importances are mean
|SHAP value|per feature with SD error bars, sorted ascending so the strongest feature sits at the top.Two-phase rendering: with
ax=Nonea new standalone figure is created and shown; passing an existingaxdraws into it and returns it without showing — for embedding in a GUI canvas or a multi-panel figure.- Parameters:
ax – Target matplotlib Axes. None creates (and shows) a new figure.
traintest (
bool) – Plot the train/test (held-out) importances instead of the final gap-filling model’s importances.max_features (
int) – Keep only the top-N features by importance (None = all).color (
str) – Bar fill color.error_color (
str) – SD error-bar color.show_values (
bool) – Annotate each bar with its importance value.title (
str) – Axes title.
- Returns:
The matplotlib Axes drawn into.
- reduce_features(shap_threshold_factor=0.5)¶
Reduce number of features using SHAP importance
A random variable is added to features and SHAP importances are calculated. The SHAP importance of the random variable is the benchmark to determine whether a feature is relevant. Features where SHAP importance is smaller or equal to (random_importance + k * random_sd) are rejected, where k is shap_threshold_factor.
- Parameters:
shap_threshold_factor (
float) – Factor k for SHAP-based feature reduction threshold. Threshold is calculated as: random_importance + k * random_sd Default 0.5 uses 0.5-sigma confidence (lenient). Higher values are more conservative (reject more features). Lower values are more lenient.
- report_feature_reduction()¶
Results from feature reduction
- report_gapfilling()¶
Results from gap-filling
- report_traintest()¶
Results from model training on test data
- property result: DataFrame¶
full gap-filling DataFrame (target + flag columns).
- Type:
Primary result
- property results: GapFillingResult¶
Structured result after .run() — all outputs in one object.
Returns a
GapFillingResultwith:gapfilled,flag,scores,scores_traintest,feature_importances,feature_importances_traintest,gapfilling_df,model,accepted_features,rejected_features.
- run(**kwargs)¶
Unified trigger: trains model then fills gaps.
- property scores_: dict¶
the final model predicting on ALL complete rows, including the rows it was trained on, so these are optimistically biased. For an honest generalization estimate use
scores_traintest_(computed on the held-out test set).- Type:
In-sample scores of the gap-filling model
- property scores_traintest_: dict¶
model trained on the training split, scored on the unseen test split.
The test split is a RANDOM subset (
test_size, default 25%) of the complete rows, scattered across the record, not a temporal block. This is the correct validation for gap-filling, where each gap record is predicted from the drivers measured at the same timestamp. A block split would measure transferability to an unseen period instead. See the train/test split in__init__for the full rationale.- Type:
Held-out generalization scores
- trainmodel(showplot_scores=True, showplot_importance=True)¶
Train the model for gap-filling and score it on the held-out test set.
No gap-filling is done here, only the model is trained (on
train_df) and evaluated on the unseentest_df. That test set is a random subset of the complete rows (scattered in time, not a temporal block). This is the correct validation for gap-filling, where each gap record is predicted from the drivers measured at the same timestamp. See the train/test split in__init__()for the rationale.
- class diive.gapfilling.QuickFillRFTS(df, target_col)[source]¶
Bases:
objectQuick gap-filling using RandomForestTS with pre-defined minimal parameters
The purpose of this class is preliminary/exploratory gap-filling for quick tests and rapid prototyping. It is NOT meant for production/final gap-filling.
Uses minimal feature engineering and model complexity for speed:
FeatureEngineer with a single lag of one record: [-1, -1]
Vectorized timestamp features, but no rolling statistics, differencing, EMA, polynomial or STL features
RandomForestTS with n_estimators=9 (fast, low quality)
min_samples_split=10 and min_samples_leaf=5 to keep the trees small
- Methods:
fill() – Train the model and fill the gaps
report() – Print the gap-filling report
gapfilling_df() – DataFrame with gap-filled target and flags
get_gapfilled_target() – Series with gap-filled values
get_flag() – Series with gap-filling flags (0=observed, 1=filled, 2=fallback)
- Parameters:
- __init__(df, target_col)[source]¶
Set up minimal feature engineering and a small Random Forest. See the class docstring.
- class diive.gapfilling.OptimizeParamsTS(df, target_col, regressor_class, **model_params)[source]¶
Bases:
objectOptimize hyperparameters for any sklearn-compatible regressor using time series cross-validation.
Supports Random Forest, XGBoost, and any model implementing the sklearn regressor interface. Uses GridSearchCV with TimeSeriesSplit to avoid data leakage on time series data.
optimize()uses the complete rows only. It holds out the last 25% of them (in time order), runs the grid search with 10 TimeSeriesSplit folds and negative mean squared error as score on the first 75%, and then scores the best model on the held-out 25%.- Visualization Features:
Parameter slice plots showing sensitivity to each hyperparameter
Parallel coordinates plot colored by performance (red=poor, blue=excellent)
Convergence analysis and parameter importance
Filters out non-optimized parameters (single value only)
See also
examples/gapfilling/gapfill_optimize_randomforest.py — Random Forest hyperparameter optimization examples/gapfilling/gapfill_optimize_xgboost.py — XGBoost hyperparameter optimization
- __init__(df, target_col, regressor_class, **model_params)[source]¶
Optimize regressor hyperparameters using GridSearchCV with time series CV.
- Parameters:
df (
DataFrame) – DataFrame with target and predictor time series (must have complete rows)target_col (
str) – Column name of target variableregressor_class – Regressor class (not instance), e.g. RandomForestRegressor, XGBRegressor, or any sklearn-compatible regressor
**model_params (
dict) –Parameter ranges to test as lists, e.g.:
{ 'n_estimators': [10, 50, 100, 200], 'max_depth': [5, 10, 15, None], 'min_samples_split': [2, 5, 10], 'min_samples_leaf': [1, 2, 4] }
- Methods:
optimize() – Run GridSearchCV to find best parameters
report_optimization (top_n=5) – Print comprehensive report with recommendations
Examples
# Random Forest optimization from sklearn.ensemble import RandomForestRegressor opt = OptimizeParamsTS(df=df, target_col='NEE', regressor_class=RandomForestRegressor, n_estimators=[10, 50, 100], max_depth=[5, 10, 15]) opt.optimize() opt.report_optimization() # XGBoost optimization import xgboost as xgb opt = OptimizeParamsTS(df=df, target_col='NEE', regressor_class=xgb.XGBRegressor, n_estimators=[50, 100, 200], max_depth=[3, 6, 9]) opt.optimize() opt.report_optimization()
- plot_optimization_analysis()[source]¶
Comprehensive visualization of hyperparameter optimization results.
Creates a dynamic grid showing: - (top-left) Optimization convergence history - (top-right) Parameter importance analysis - (remaining) Parameter slices for each numeric parameter - (separate figure) Parallel coordinates plot
Requires: matplotlib, numpy
- diive.gapfilling.OptimizeParamsRFTS¶
alias of
OptimizeParamsTS
- class diive.gapfilling.XGBoostTS(input_df, target_col, verbose=0, test_size=0.25, below_zero=None, shap_max_rows=None, **kwargs)[source]¶
Bases:
MlRegressorGapFillingBaseGap-fill a time series with XGBoost gradient-boosting regression.
See
__init__()for parameters, methods and attributes.- Parameters:
- __init__(input_df, target_col, verbose=0, test_size=0.25, below_zero=None, shap_max_rows=None, **kwargs)[source]¶
Gap-filling for time series using XGBoost gradient boosting.
Trains an XGBoost model on complete observations to predict missing values. Effective for non-linear relationships and complex temporal patterns. Requires pre-engineered features from FeatureEngineer.
- Parameters:
input_df (
DataFrame) – DataFrame with target and pre-engineered feature columns. Features should be created with FeatureEngineer. Timestamps in DatetimeIndex.target_col (
str) – Column name of variable to gap-fill (string or tuple).verbose (
int) – Verbosity level: 0=silent, 1=progress, 2+=detailed. Default: 0.test_size (
float) – Fraction of complete data for testing (0.0-1.0). Default: 0.25. Only complete rows used for split.below_zero (
str) – How to treat predicted values below zero for variables that cannot be negative (e.g. VPD, SW_IN, PPFD). None (default): keep as-is. ‘zero’: clip to 0.shap_max_rows (
int) – Cap on rows used for SHAP feature importances. None (default): explain every row. Set this on long records, where SHAP dominates runtime. See MlRegressorGapFillingBase.**kwargs – XGBoost hyperparameters (n_estimators, max_depth, learning_rate, min_child_weight, early_stopping_rounds, random_state, n_jobs, subsample, colsample_bytree, etc). See xgboost documentation.
- Methods:
trainmodel() – Train on training data, evaluate on test data.
fillgaps() – Train on all complete data, predict missing values.
reduce_features() – Feature selection based on SHAP importance.
report_traintest() – Print model evaluation metrics.
report_gapfilling() – Print gap-filling results.
get_gapfilled_target() – Return gap-filled series.
get_flag() – Return gap-filling flags (0=observed, 1=gap-filled, 2=fallback).
- Variables:
model – Trained XGBRegressor instance.
gapfilling_df – DataFrame with gap-filled target.
feature_importances – SHAP feature importance.
scores – In-sample scores of the gap-filling model (MAE, RMSE, R²).
scores_traintest – Scores on the held-out test split.
Examples
See examples/gapfilling/gapfill_xgboost.py for complete example. See examples/gapfilling/gapfill_comparison.py for side-by-side comparison with MDS and Random Forest gap-filling.
- property feature_importances_reduction_: DataFrame¶
a model with an added random variable, fitted and explained on the same training data
- Type:
Return feature importance from feature reduction
- property feature_importances_traintest_: DataFrame¶
Return feature importance from model training on training data, with importances calculated using test data (holdout set)
- fillgaps(showplot_scores=True, showplot_importance=True, progress_callback=None)¶
Gap-fill data with previously built model
No new model is built here, instead the last model built in the preceding step .trainmodel() is used.
y = target X = features
- Parameters:
showplot_scores (
bool) – shows plot of predicted vs observedshowplot_importance (
bool) – shows plot of SHAP feature importancesprogress_callback – Optional
callable(fraction: float)invoked as the full-record SHAP importance computation advances (0.0 -> 1.0). This is the slowest part on large records, and a caller can use it to drive a progress bar. When None (default) the SHAP call runs in one shot. The results are the same either way.
- get_flag()¶
Gap-filling flag, where 0=observed, 1=gap-filled, 2=gap-filled with fallback
- get_gapfilled_target()¶
Gap-filled target time series
- property model_¶
Return the model (trained on the training set).
- plot_feature_importances(ax=None, traintest=False, max_features=None, color='#003A70', error_color='#C41E3A', show_values=True, title='SHAP feature importance')¶
Plot SHAP feature importances as a horizontal bar chart (two-phase).
Importances are mean
|SHAP value|per feature with SD error bars, sorted ascending so the strongest feature sits at the top.Two-phase rendering: with
ax=Nonea new standalone figure is created and shown; passing an existingaxdraws into it and returns it without showing — for embedding in a GUI canvas or a multi-panel figure.- Parameters:
ax – Target matplotlib Axes. None creates (and shows) a new figure.
traintest (
bool) – Plot the train/test (held-out) importances instead of the final gap-filling model’s importances.max_features (
int) – Keep only the top-N features by importance (None = all).color (
str) – Bar fill color.error_color (
str) – SD error-bar color.show_values (
bool) – Annotate each bar with its importance value.title (
str) – Axes title.
- Returns:
The matplotlib Axes drawn into.
- reduce_features(shap_threshold_factor=0.5)¶
Reduce number of features using SHAP importance
A random variable is added to features and SHAP importances are calculated. The SHAP importance of the random variable is the benchmark to determine whether a feature is relevant. Features where SHAP importance is smaller or equal to (random_importance + k * random_sd) are rejected, where k is shap_threshold_factor.
- Parameters:
shap_threshold_factor (
float) – Factor k for SHAP-based feature reduction threshold. Threshold is calculated as: random_importance + k * random_sd Default 0.5 uses 0.5-sigma confidence (lenient). Higher values are more conservative (reject more features). Lower values are more lenient.
- report_feature_reduction()¶
Results from feature reduction
- report_gapfilling()¶
Results from gap-filling
- report_traintest()¶
Results from model training on test data
- property result: DataFrame¶
full gap-filling DataFrame (target + flag columns).
- Type:
Primary result
- property results: GapFillingResult¶
Structured result after .run() — all outputs in one object.
Returns a
GapFillingResultwith:gapfilled,flag,scores,scores_traintest,feature_importances,feature_importances_traintest,gapfilling_df,model,accepted_features,rejected_features.
- run(**kwargs)¶
Unified trigger: trains model then fills gaps.
- property scores_: dict¶
the final model predicting on ALL complete rows, including the rows it was trained on, so these are optimistically biased. For an honest generalization estimate use
scores_traintest_(computed on the held-out test set).- Type:
In-sample scores of the gap-filling model
- property scores_traintest_: dict¶
model trained on the training split, scored on the unseen test split.
The test split is a RANDOM subset (
test_size, default 25%) of the complete rows, scattered across the record, not a temporal block. This is the correct validation for gap-filling, where each gap record is predicted from the drivers measured at the same timestamp. A block split would measure transferability to an unseen period instead. See the train/test split in__init__for the full rationale.- Type:
Held-out generalization scores
- trainmodel(showplot_scores=True, showplot_importance=True)¶
Train the model for gap-filling and score it on the held-out test set.
No gap-filling is done here, only the model is trained (on
train_df) and evaluated on the unseentest_df. That test set is a random subset of the complete rows (scattered in time, not a temporal block). This is the correct validation for gap-filling, where each gap record is predicted from the drivers measured at the same timestamp. See the train/test split in__init__()for the rationale.
- diive.gapfilling.prediction_scores(predictions, targets)[source]¶
Calculate regression performance metrics for model predictions.
Computes seven standard regression quality metrics comparing predicted values to observed targets. Useful for evaluating gap-filling models and other regression tasks.
- Parameters:
predictions (
array) – Array of predicted values.targets (
array) – Array of observed target values (same length as predictions).
- Returns:
- Performance metrics with keys:
mae: Mean Absolute Error (average absolute difference)
medae: Median Absolute Error (robust to outliers)
mse: Mean Squared Error (penalizes larger errors more)
rmse: Root Mean Squared Error (same units as targets)
mape: Mean Absolute Percentage Error (relative error %)
maxe: Maximum Error (largest single prediction error)
r2: Coefficient of Determination (0-1, higher is better)
- Return type:
See: https://scikit-learn.org/stable/modules/model_evaluation.html#regression-metrics
- class diive.gapfilling.LongTermGapFillingRandomForestTS(input_df, target_col, verbose=0, test_size=0.25, below_zero=None, **kwargs)[source]¶
Bases:
LongTermGapFillingBaseLong-term Random Forest gap-filling with per-year models. See
__init__().- __init__(input_df, target_col, verbose=0, test_size=0.25, below_zero=None, **kwargs)[source]¶
Long-term Random Forest gap-filling with per-year models.
- Parameters:
input_df (
DataFrame) – DataFrame with target and pre-engineered feature columns.target_col (
str) – Column name of variable to gap-fill.verbose (
int) – Verbosity level: 0=silent, 1=progress, 2+=detailed.test_size (
float) – Fraction of complete data for testing (0.0-1.0).below_zero (
str) – How to treat predicted values below zero for variables that cannot be negative (e.g. VPD, SW_IN, PPFD). None (default): keep as-is. ‘zero’: clip to 0.**kwargs – Random Forest hyperparameters passed to RandomForestRegressor.
- create_yearpools()¶
For each year create a dataset comprising the respective year and the two neighboring years.
- property features_reduced_across_years: list¶
Return features after reduction that were selected in at least one year.
- fillgaps()¶
Train the model for each year and fill its gaps.
- get_flag()¶
Gap-filling flag across all years (0=observed, 1=gap-filled, 2=fallback).
The flag column name is consistent across the per-year models (it derives from the target name), so it is read from the first yearly model.
- Return type:
- get_gapfilled_target()¶
Gap-filled target series across all years (alias of
gapfilled_).- Return type:
- initialize_yearly_models()¶
Initialize model for each year
- reduce_features_across_years(shap_threshold_factor=0.5)¶
Reduce features and detect features that were selected in at least one year.
- Parameters:
shap_threshold_factor (float)
- run(reduce_features=False, shap_threshold_factor=0.5)¶
Run the full long-term gap-filling flow in one call.
Convenience wrapper around the staged API (
create_yearpools->initialize_yearly_models-> optionalreduce_features_across_years->fillgaps), mirroring the single-model classes’run().- Parameters:
- Returns:
self (so callers can chain
.gapfilled_etc.).
- property scores_traintest_overall_: dict¶
Held-out test scores averaged across all years (one value per metric).
- showplot_feature_ranks_per_year(title=None, subtitle=None)¶
Plot a bump chart of each feature’s importance rank across years.
- class diive.gapfilling.LongTermGapFillingXGBoostTS(input_df, target_col, verbose=0, test_size=0.25, below_zero=None, **kwargs)[source]¶
Bases:
LongTermGapFillingBaseLong-term XGBoost gap-filling with per-year models. See
__init__().- __init__(input_df, target_col, verbose=0, test_size=0.25, below_zero=None, **kwargs)[source]¶
Long-term XGBoost gap-filling with per-year models.
- Parameters:
input_df (
DataFrame) – DataFrame with target and pre-engineered feature columns.target_col (
str) – Column name of variable to gap-fill.verbose (
int) – Verbosity level: 0=silent, 1=progress, 2+=detailed.test_size (
float) – Fraction of complete data for testing (0.0-1.0).below_zero (
str) – How to treat predicted values below zero for variables that cannot be negative (e.g. VPD, SW_IN, PPFD). None (default): keep as-is. ‘zero’: clip to 0.**kwargs – XGBoost hyperparameters passed to XGBRegressor.
- create_yearpools()¶
For each year create a dataset comprising the respective year and the two neighboring years.
- property features_reduced_across_years: list¶
Return features after reduction that were selected in at least one year.
- fillgaps()¶
Train the model for each year and fill its gaps.
- get_flag()¶
Gap-filling flag across all years (0=observed, 1=gap-filled, 2=fallback).
The flag column name is consistent across the per-year models (it derives from the target name), so it is read from the first yearly model.
- Return type:
- get_gapfilled_target()¶
Gap-filled target series across all years (alias of
gapfilled_).- Return type:
- initialize_yearly_models()¶
Initialize model for each year
- reduce_features_across_years(shap_threshold_factor=0.5)¶
Reduce features and detect features that were selected in at least one year.
- Parameters:
shap_threshold_factor (float)
- run(reduce_features=False, shap_threshold_factor=0.5)¶
Run the full long-term gap-filling flow in one call.
Convenience wrapper around the staged API (
create_yearpools->initialize_yearly_models-> optionalreduce_features_across_years->fillgaps), mirroring the single-model classes’run().- Parameters:
- Returns:
self (so callers can chain
.gapfilled_etc.).
- property scores_traintest_overall_: dict¶
Held-out test scores averaged across all years (one value per metric).
- showplot_feature_ranks_per_year(title=None, subtitle=None)¶
Plot a bump chart of each feature’s importance rank across years.
- class diive.gapfilling.SWINGapFillerXGBoost(series, lat, lon, utc_offset, context_df=None, nighttime_threshold=0.001, correct_nighttime_offset=True, interpolate_short_gaps='auto', reduce_features=False, feature_kwargs=None, verbose=0, **kwargs)[source]¶
Bases:
objectPhysics-aware gap-filling for shortwave incoming radiation using XGBoost.
Partitions the time series into daytime and nighttime using potential radiation: - Nighttime gaps are set to zero (no solar radiation after sunset, physically correct) - Daytime gaps are filled with XGBoost trained on daytime observations only
By default, only potential radiation (SW_IN_POT) and timestamp features are used. No additional driver variables are required. SW_IN_POT, calculated from site latitude and longitude, encodes solar angle, day length, and seasonal amplitude — the dominant drivers of SW_IN variability — and is the single most important predictor.
Feature engineering is applied to the full time series before subsetting to daytime, so rolling features correctly span day/night boundaries.
- Why a dedicated class instead of XGBoostTS with SW_IN_POT as a driver:
SW_IN needs corrections that no other gap-filling target needs, and one of them — the nighttime zero-offset correction (correct_nighttime_offset) — does part of the gap-filling itself. It subtracts the daily mean nighttime reading as an offset and then sets every nighttime record to exactly zero, which fills the nighttime gaps whether or not they were gaps to begin with. Correction and fill are therefore one operation for this variable and have to happen in one place, in this order, before the model ever sees the daytime subset. That ordering, plus the SW_IN_POT day/night split it shares with the correction (see nighttime_threshold), is what this class exists to own.
- What the default configuration can and cannot do:
With no context_df, every feature is a deterministic function of the timestamp — SW_IN_POT, the timestamp features and the record number are all fixed once the time is known. The model therefore reproduces a climatology, the expected SW_IN for that time of day and year, and has no way to know whether a given gap was overcast or clear. That is the accuracy ceiling, and no further feature derived from the timestamp can raise it: on CH-DAV 30-min data, SW_IN_POT plus timestamps (15 features) scores the same daytime-gap RMSE as the same set expanded with rolling and EMA variants of SW_IN_POT (29 features) — 138 W m-2 either way.
Two things do raise it, and both are worth more than any feature tuning:
A second radiation measurement passed through context_df — a co-located pyranometer, a PPFD sensor, or a nearby station. It is the only routinely available source of sky-state information. On CH-DAV, adding PPFD moved daytime-gap RMSE from 138 to 26 W m-2 wherever that second sensor was available.
interpolate_short_gaps for gaps of a couple of records, which uses the target’s own neighbours — information the model never sees, since the feature engineer excludes the target from every feature. It defaults to
'auto', which switches it on only when no context_df is given: it helps under the ceiling but overwrites better model fills once a strong context sensor is present.
- Parameters:
series (
Series) – SW_IN time series to gap-fill (W m-2). NaN values are gaps.lat (
float) – Site latitude in degrees North (-90 to 90).lon (
float) – Site longitude in degrees East (-180 to 180).utc_offset (
int) – UTC offset of the timestamp index, e.g. 1 for UTC+01:00.context_df (
DataFrame) –Optional DataFrame of additional driver variables. Must share the same DatetimeIndex as series. When provided, these columns are included in feature engineering alongside SW_IN_POT. Column names must not collide with the target column name or with
'SW_IN_POT'. Default: None (only SW_IN_POT and timestamp features are used).The most valuable thing to put here by far is a second radiation measurement — a co-located pyranometer, a PPFD sensor, or a nearby station. Unlike TA or VPD it measures the sky state directly, which is exactly what the timestamp cannot supply (see above). It does not need to be in W m-2 or gap-free: the model learns the relationship from whatever overlap exists, and records where it is missing simply fall back to the climatology the default configuration would have produced anyway.
Preference order for a context_df radiation source, best first: a co-located second sensor (pyranometer or PPFD) that sees the same sky; a nearby station’s radiation if the site is climatically similar; and, where no local or neighbouring sensor exists, satellite or reanalysis SW_IN such as ERA5-Land. All wire in the same way through context_df; each carries synoptic sky state the timestamp cannot, so even a coarse reanalysis product beats the timestamp-only climatology.
nighttime_threshold (
float) – Potential-radiation cutoff (W m-2). Records withSW_IN_POT < nighttime_thresholdare classified as nighttime; records withSW_IN_POT >= nighttime_thresholdare daytime. Default: 0.001, which matches the threshold used internally byremove_nighttime_zero_offsetso that the day/night split is consistent whether or not offset correction is enabled.correct_nighttime_offset (
bool) – If True, apply remove_nighttime_zero_offset() to the series before gap-filling. This corrects sensors that measure small non-zero (often negative) values at night by subtracting the daily mean nighttime value as an offset from the whole series, then setting nighttime to zero. The corrected series is used for all subsequent gap-filling steps and is stored in gapfilling_df as ‘{target_col}_offset_corrected’. Default: True. On an already quality-controlled series this is close to a no-op; on a raw pyranometer record it removes the thermal-offset bias. Set to False if the input is already offset-corrected.interpolate_short_gaps (
int|str|None) –Maximum gap length, in records, to fill by interpolating the clearness index (SW_IN / SW_IN_POT) instead of the model. Interpolation never bridges a night.
Default:
'auto'— enabled at a 2-record limit when context_df is None, disabled when a context driver is given, which is the branch that measured better in each case (see below). Pass an integer for an explicit record limit, or None to disable it outright.Worth enabling when the model is climatology-bound (no context_df): the model cannot see the target’s own neighbours — the feature engineer excludes the target from every feature — so a short gap is exactly the case it is blind to.
2(1 h on 30-min data) is the recommended limit. Measured on CH-DAV 30-min data with 15% scattered gaps, daytime gap RMSE against a model-only fill: 125 -> 88 at1, 125 -> 77 at2, and no further gain above that — a scattered-gap record holds almost no longer runs. Raising the limit has little upside: interpolation still wins on gaps as long as 8 h (189 vs 219 W m-2) but collapses once a gap outlasts the observations bracketing it (1 day: 337 vs 172).And the reason
'auto'turns it off once a context driver is present: interpolation overwrites the model on the gaps it covers. That is a gain under the ceiling, but a strong, near-complete second radiation sensor in context_df resolves short gaps better than clearness-index interpolation does, so enabling it there raises RMSE (CH-DAV: context-only 13.5 vs context+interp 66 W m-2). Note that'auto'keys off whether context_df was passed at all, not off how good or complete that driver is — with a weak or very gappy context sensor, an explicit integer may beat it.reduce_features (
bool) – Apply SHAP-based feature reduction after initial training. Removes features whose importance is at or below the random-noise baseline. Increases training time but can improve generalisation. Default: False.feature_kwargs (
dict) –FeatureEngineer arguments, overriding the SW_IN defaults in
_FE_DEFAULTS(see that constant for the values and the reasoning). Every FeatureEngineer parameter is reachable this way, including the diff, polynomial and STL stages, which are off by default.target_colandverboseare set by this class and rejected here. Window sizes are in records and assume 30-min data — scale them to your frequency.Three of the defaults are worth understanding before overriding them:
features_lag=[]. Lag features are a bad trade here. The model predicts only records where every feature is present and sends the rest to a timestamp-only fallback, so a lag converts “this record’s neighbour is missing” into “this record cannot be filled properly”. On CH-DAV with a PPFD reference,[-2, 2]pushed 1157 of 2556 otherwise-fillable records to the fallback and raised their RMSE from 26 to 97 W m-2, on top of costing 20% of the training rows. On SW_IN_POT lags are harmless (it never has gaps) but useless, being the same function of the timestamp. Set them only for a gap-free driver where they earn their keep.features_rolling/features_emaexclude SW_IN_POT. Rolling and EMA variants of a deterministic timestamp curve carry nothing beyond its raw value and the timestamp features. Both stages therefore act on context drivers only, and with no context_df they have no effect at all.add_continuous_record_number=True. Lets the model isolate periods — a sensor swap, progressive soiling, a calibration change. Safe for gap-filling, which only interpolates within the record, so the trees never extrapolate it. Measured neutral on CH-DAV’s quality-controlled Rg_f, which has no drift to find; cheap insurance on long raw records.Example:
feature_kwargs={'features_rolling': [2, 4, 12], # 15-min data 'features_diff': [1]} # enable diff stage
verbose (
int) – Verbosity level: 0=silent, 1=progress, 2+=detailed. Default: 0.**kwargs – XGBoost hyperparameters forwarded to XGBRegressor (n_estimators, max_depth, learning_rate, subsample, colsample_bytree, random_state, etc.), overriding the SW_IN defaults in
_XGB_DEFAULTS: n_estimators=3000, max_depth=6, early_stopping_rounds=20, random_state=42. If you raise n_estimators, keep early stopping on — see the note at_XGB_DEFAULTSfor why.
- Methods:
run() – Execute the full gap-filling workflow. Returns self for chaining.
- Variables:
results – GapFillingResult populated after run(). Contains gapfilled series, flags, scores, SHAP importances, and the trained XGBoost model.
daytime_model – The XGBoostTS instance that filled the daytime gaps, kept so the fill can be inspected after the fact — most usefully via its
traintest_details_, which holds the held-out test set and makes a real predicted-vs-measured validation plot possible. None when there were no daytime gaps, since the model is then never built.
- Result flags:
0 = observed (any period) 1 = daytime gap, filled by the XGBoost model 2 = daytime gap, filled by the timestamp-only fallback model, i.e. a driver was missing here so the full model could not predict 3 = nighttime gap, set to zero by physics 4 = daytime gap, filled by clearness-index interpolation (only when interpolate_short_gaps is set)
Values 0/1/2 carry the same meaning as everywhere else in diive (see GapFillingResult). Values 3 (physics branch) and 4 (interpolation) are specific to this class. Flag 2 matters most when context_df is used: it marks records where the extra drivers were unavailable and the fill therefore fell back to timestamps alone.
Example
See examples/gapfilling/gapfill_swin.py for a complete worked example.
- SWINPOT_COL = 'SW_IN_POT'¶
- FLAG_COL = 'flag'¶
- KT_MIN_SWINPOT = 50.0¶
- FLAG_OBSERVED = 0¶
- FLAG_MODEL = 1¶
- FLAG_FALLBACK = 2¶
- FLAG_NIGHTTIME_ZERO = 3¶
- FLAG_INTERPOLATED = 4¶
- __init__(series, lat, lon, utc_offset, context_df=None, nighttime_threshold=0.001, correct_nighttime_offset=True, interpolate_short_gaps='auto', reduce_features=False, feature_kwargs=None, verbose=0, **kwargs)[source]¶
Construct the gap-filler. See the class docstring for the full parameter list.
- property results: GapFillingResult¶
GapFillingResult produced by
run()(raises if called before run).
- property daytime_model_: XGBoostTS | None¶
The XGBoostTS that filled the daytime gaps (None if there were none).
Exposed so a caller can validate the fill against data the model never saw:
daytime_model_.traintest_details_carries the held-out test set, which is what a predicted-vs-measured plot needs. The results themselves stay onresults— this is the model, not a second copy of the output.
- run()[source]¶
Execute gap-filling: optional offset correction, nighttime zeros, daytime XGBoost.
Progress: at
verbose>=1each stage prints one dense result line with its elapsed time; on an interactive terminal or in Jupyter a transient spinner (and, for the SHAP fill, a progress bar) shows the current stage while it runs, so a long step is not a silent pause. Sub-component chatter is suppressed at this level and shown only atverbose>=2. Setverbose=0to silence.- Return type:
- Returns:
self — for method chaining.