Note
Go to the end to download the full example code.
Vapor Pressure Deficit (VPD) Calculations¶
Demonstrates calculating VPD from air temperature and relative humidity using the Magnus formula. VPD is a key driver variable in ecosystem flux analysis, representing the drying power of the atmosphere.
Best for: Understanding atmospheric water stress and its drivers.
Basic VPD Calculation¶
Calculate VPD from air temperature (TA) and relative humidity (RH). Demonstrates direct VPD calculation using the Magnus formula.
import diive as dv
# Load example data
df = dv.load_exampledata_parquet()
# Variables
ta_col = 'Tair_f' # Gap-filled air temperature
rh_col = 'RH' # Relative humidity
vpd_col = 'VPD_calculated'
# Subset data
subset_df = df[[ta_col, rh_col]].copy()
# Calculate VPD from TA and RH
subset_df[vpd_col] = dv.variables.calc_vpd_from_ta_rh(df=subset_df, ta_col=ta_col, rh_col=rh_col)
# Print statistics
print("VPD Calculation")
print("=" * 50)
print(f"Data points: {len(subset_df)}")
print(f"Missing values (RH): {subset_df[rh_col].isnull().sum()}")
print(f"VPD range: {subset_df[vpd_col].min():.3f} to {subset_df[vpd_col].max():.3f} kPa")
print(f"Mean VPD: {subset_df[vpd_col].mean():.3f} kPa")
print(f"\nFirst 10 rows:")
print(subset_df.head(10))
> Loaded .parquet file
/home/docs/checkouts/diive/checkouts/latest/diive/configs/exampledata/exampledat
a_PARQUET_CH-DAV_FP2022.5_2013-2022_ID20230206154316_30MIN.parquet (0.050
seconds).
VPD Calculation
==================================================
Data points: 175296
Missing values (RH): 707
VPD range: 0.000 to 3.216 kPa
Mean VPD: 0.323 kPa
First 10 rows:
Tair_f RH VPD_calculated
TIMESTAMP_MIDDLE
2013-01-01 00:15:00 -1.618 31.933 0.369156
2013-01-01 00:45:00 -1.630 32.600 0.365215
2013-01-01 01:15:00 -1.644 38.867 0.330913
2013-01-01 01:45:00 -1.657 37.767 0.336544
2013-01-01 02:15:00 -0.567 39.533 0.354322
2013-01-01 02:45:00 -0.200 36.667 0.381218
2013-01-01 03:15:00 -0.100 35.800 0.389270
2013-01-01 03:45:00 -0.300 35.767 0.383820
2013-01-01 04:15:00 -1.600 42.400 0.312805
2013-01-01 04:45:00 -1.267 40.200 0.332837
VPD Calculation with Gap Analysis¶
Calculate VPD and analyze gaps in the data. Shows how RH gaps affect VPD calculations and the extent of missing values.
# Load example data
df = dv.load_exampledata_parquet()
# Variables
ta_col = 'Tair_f' # Gap-filled air temperature
rh_col = 'RH' # Relative humidity
vpd_col = 'VPD_kPa'
# Subset data - use 1 year to keep example quick
df_subset = df.loc[(df.index.year == 2018)].copy()
subset_df = df_subset[[ta_col, rh_col]].copy()
# Calculate VPD
subset_df[vpd_col] = dv.variables.calc_vpd_from_ta_rh(df=subset_df, ta_col=ta_col, rh_col=rh_col)
print("\nVPD Calculation Analysis (Year 2018)")
print("=" * 50)
print(f"Data points: {len(subset_df)}")
print(f"Original gaps in RH: {subset_df[rh_col].isnull().sum()} records")
print(f"Gaps propagated to VPD: {subset_df[vpd_col].isnull().sum()} records")
print(f"\nVPD Statistics:")
print(subset_df[vpd_col].describe())
print(f"\nTA and RH Statistics:")
print(f"TA: {subset_df[ta_col].min():.1f}°C to {subset_df[ta_col].max():.1f}°C")
print(f"RH: {subset_df[rh_col].min():.1f}% to {subset_df[rh_col].max():.1f}%")
> Loaded .parquet file
/home/docs/checkouts/diive/checkouts/latest/diive/configs/exampledata/exampledat
a_PARQUET_CH-DAV_FP2022.5_2013-2022_ID20230206154316_30MIN.parquet (0.049
seconds).
VPD Calculation Analysis (Year 2018)
==================================================
Data points: 17520
Original gaps in RH: 300 records
Gaps propagated to VPD: 300 records
VPD Statistics:
count 17220.000000
mean 0.356615
std 0.382699
min 0.000000
25% 0.075784
50% 0.225221
75% 0.482207
max 2.271730
Name: VPD_kPa, dtype: float64
TA and RH Statistics:
TA: -23.1°C to 25.2°C
RH: 9.1% to 100.0%
VPD Gap-Filling with XGBoost¶
Often RH data has gaps. VPD can be gap-filled using air temperature as a predictor. XGBoostTS uses gradient boosting with configurable feature engineering for gap-filling. Note: This section is computationally intensive and may take 1-2 minutes to run.
from diive.gapfilling.xgboost_ts import XGBoostTS
from diive.core.ml.feature_engineer import FeatureEngineer
# Load example data - use 1 year subset for faster training
df = dv.load_exampledata_parquet()
df_subset = df.loc[(df.index.year == 2021)].copy()
# Variables
ta_col = 'Tair_f'
rh_col = 'RH'
vpd_col = 'VPD_kPa'
vpd_gf_col = 'VPD_kPa_gfilled'
# Subset and calculate VPD
subset_df = df_subset[[ta_col, rh_col]].copy()
subset_df[vpd_col] = dv.variables.calc_vpd_from_ta_rh(df=subset_df, ta_col=ta_col, rh_col=rh_col)
# Feature engineering for XGBoost
engineer = FeatureEngineer(
target_col=vpd_col,
features_lag=[-2, -1],
features_rolling=[6, 12],
features_diff=[1],
features_ema=[6],
features_poly_degree=1,
vectorize_timestamps=True,
)
df_engineered = engineer.fit_transform(subset_df)
# Gap-fill VPD using XGBoost
xgbts = XGBoostTS(
input_df=df_engineered,
target_col=vpd_col,
n_estimators=50,
max_depth=5,
learning_rate=0.1,
)
# Train model (suppress visualization issues in terminal/batch environments)
try:
xgbts.trainmodel()
except Exception as e:
# Model is still trained even if visualization fails; suppress error for batch execution
pass
xgbts.fillgaps()
subset_df[vpd_gf_col] = xgbts.get_gapfilled_target()
print("\nVPD Gap-Filling with XGBoost (Year 2021)")
print("=" * 50)
print(f"Original VPD gaps: {subset_df[vpd_col].isnull().sum()} records")
print(f"Gap-filled VPD gaps: {subset_df[vpd_gf_col].isnull().sum()} records")
print(f"\nVPD Statistics (before gap-filling):")
print(subset_df[vpd_col].describe())
print(f"\nModel performance:")
for key, val in list(xgbts.scores_.items())[:3]:
print(f" {key}: {val:.4f}")
> Loaded .parquet file
/home/docs/checkouts/diive/checkouts/latest/diive/configs/exampledata/exampledat
a_PARQUET_CH-DAV_FP2022.5_2013-2022_ID20230206154316_30MIN.parquet (0.049
seconds).
VPD Gap-Filling with XGBoost (Year 2021)
==================================================
Original VPD gaps: 17 records
Gap-filled VPD gaps: 0 records
VPD Statistics (before gap-filling):
count 17503.000000
mean 0.288325
std 0.347593
min 0.000000
25% 0.046101
50% 0.166326
75% 0.393456
max 2.492866
Name: VPD_kPa, dtype: float64
Model performance:
mae: 0.0054
medae: 0.0033
mse: 0.0001
VPD Pattern Visualization¶
Visualize VPD patterns using heatmap showing daily and hourly breakdown. Reveals diurnal and seasonal patterns in vapor pressure deficit.
# Load example data
df = dv.load_exampledata_parquet()
# Variables
ta_col = 'Tair_f'
rh_col = 'RH'
vpd_col = 'VPD_kPa'
# Subset and calculate VPD
subset_df = df[[ta_col, rh_col]].copy()
subset_df[vpd_col] = dv.variables.calc_vpd_from_ta_rh(df=subset_df, ta_col=ta_col, rh_col=rh_col)
print("\nVPD Pattern Visualization")
print("=" * 50)
print(f"Data points: {len(subset_df)}")
print(f"VPD statistics:")
print(subset_df[vpd_col].describe())
# Create heatmap visualization
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
fig = plt.figure(facecolor='white', figsize=(16, 5), constrained_layout=True)
gs = gridspec.GridSpec(1, 3, figure=fig, wspace=0.2)
ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[0, 1])
ax3 = fig.add_subplot(gs[0, 2])
dv.plotting.HeatmapDateTime(series=subset_df[vpd_col]).plot(ax=ax1)
dv.plotting.HeatmapDateTime(series=subset_df[ta_col]).plot(ax=ax2)
dv.plotting.HeatmapDateTime(series=subset_df[rh_col]).plot(ax=ax3)
ax1.set_title("VPD (kPa)", fontsize=12, fontweight='bold')
ax2.set_title("Air Temperature (°C)", fontsize=12, fontweight='bold')
ax3.set_title("Relative Humidity (%)", fontsize=12, fontweight='bold')
ax2.tick_params(left=True, labelleft=False)
ax3.tick_params(left=True, labelleft=False)
fig.show()

> Loaded .parquet file
/home/docs/checkouts/diive/checkouts/latest/diive/configs/exampledata/exampledat
a_PARQUET_CH-DAV_FP2022.5_2013-2022_ID20230206154316_30MIN.parquet (0.051
seconds).
VPD Pattern Visualization
==================================================
Data points: 175296
VPD statistics:
count 174589.000000
mean 0.322881
std 0.371367
min 0.000000
25% 0.065685
50% 0.197982
75% 0.437258
max 3.215735
Name: VPD_kPa, dtype: float64
Total running time of the script: (0 minutes 4.231 seconds)




