Variables (dv.variables)¶
Derived variables and feature calculations, from potential radiation and VPD to day/night flags.
Imported as diive.variables, reached as dv.variables after import diive as dv.
VARIABLES: DERIVED METEOROLOGICAL VARIABLES¶
Calculate derived variables: radiation, thermodynamic properties, temporal features, and synthetic data for testing. Composable functions and classes for feature creation.
Part of the diive library: https://github.com/holukas/diive
- diive.variables.potrad(timestamp_index, lat, lon, utc_offset)[source]¶
Calculate potential shortwave-incoming radiation, ONEFlux/FLUXNET parity
Faithful port of
get_rpotin ONEFluxoneflux_steps/common/common.c(https://github.com/fluxnet/ONEFlux), the routine that produces theSW_IN_POTcolumn of FLUXNET/AmeriFlux/ICOS products. Its defining properties:solar constant 1376 W m-2,
Spencer (1971) declination and earth-sun distance (eccentricity) series, which carry the +/-3.4% annual amplitude cycle,
true solar noon from the NOAA solar position algorithm, i.e. the equation of time is included, so solar noon is not pinned to a fixed clock time,
the returned value is the mean over each averaging period, computed from 1-minute steps, not an instantaneous value at timestamp_index.
Timestamps are assumed to be TIMESTAMP_MIDDLE (the diive convention): the record at
tcovers[t - period/2, t + period/2). The averaging period is inferred from the median spacing of timestamp_index (median, so gaps do not skew it). ONEFlux itself only defines 30-minute and hourly output; any other period is handled as the natural generalisation of the same algorithm, including periods that do not tile the day. ONEFlux resolves potential radiation on a 1-minute grid, so a sub-minute record cannot average over anything finer and gets the 1-minute value.Daylight saving is not applied: utc_offset is the local standard time offset, matching FLUXNET convention.
- Parameters:
timestamp_index (
DatetimeIndex) – time series index (TIMESTAMP_MIDDLE)lat (
float) – latitudelon (
float) – longitudeutc_offset (
int) – UTC offset of timestamp_index, e.g. 1 for UTC+01:00
- Return type:
- Returns:
potential radiation, named
SW_IN_POT
Example
See examples/features/feature_potentialradiation.py for complete examples.
- diive.variables.aerodynamic_resistance(u_ms, ustar_ms)[source]¶
Calculates aerodynamic resistance (ra) using wind speed and friction velocity.
“The aerodynamic resistance is determined directly from the friction velocity USTAR (m s-1) and the horizontal wind speed u (m s-1) as ra = u / (USTAR^2) according to the simplified bulk approach described in Stull [1988].” (Kittler et al., 2017)
This uses the momentum transfer approximation: ra = u / ustar^2. Reference: Kittler et al. (2017), eq.(5).
- diive.variables.dry_air_density(rho_a, rho_v)[source]¶
Calculates the partial density of dry air from moist air density.
This function isolates the dry air component by subtracting the water vapor density (absolute humidity) from the total density of the moist air parcel. This relies on the definition of total density in a gas mixture: rho_total = rho_dry + rho_vapor.
Note
Input series must have matching indices/lengths. Molar masses are not required for this calculation as the inputs are already in density units (kg m-3).
- Parameters:
- Returns:
The calculated dry air density (rho_d) in [kg m-3]. Where rho_v is larger than rho_a the result is negative, which points to bad input data. A warning is shown in that case.
- Return type:
- diive.variables.calc_vpd_from_ta_rh(df, rh_col, ta_col)[source]¶
Calculate VPD from air temperature and relative humidity
- Parameters:
- Return type:
- Returns:
VPD in kPa as Series
- Original code in ReddyProc:
VPD.V.n <- 6.1078 * (1 - rH / 100) * exp(17.08085 * Tair / (234.175 + Tair)) # See Kolle Logger Tools Software 2012 (Magnus coefficients for water between 0 and 100 degC) # Data vector of vapour pressure deficit (VPD, hPa (mbar))
- Reference:
Checked against ReddyProc output, virtually the same, differences only 8 digits after comma.
See also
examples
- diive.variables.air_temp_from_sonic_temp(sonic_temp, h2o)[source]¶
Calculate air temperature from sonic temperature and water vapor concentration.
This function computes the air temperature from the provided sonic temperature and water vapor concentration using a specific formula. The calculation takes into account the relationship between sonic temperature, air temperature, and the effect of water vapor on sonic wave speed.
Based on the code in:
- Striednig, M., Graus, M., Märk, T. D., & Karl, T. G. (2020). InnFLUX – an open-source
code for conventional and disjunct eddy covariance analysis of trace gas measurements: An urban test case. Atmospheric Measurement Techniques, 13(3), 1447–1465. https://doi.org/10.5194/amt-13-1447-2020 Source code: https://www.atm-phys-chem.at/innflux/ Source code: https://git.uibk.ac.at/acinn/apc/innflux Source code: https://git.uibk.ac.at/acinn/apc/innflux/-/blob/master/innFLUX_step1.m?ref_type=heads#L329
- Parameters:
- Returns:
Air temperature data in Kelvin.
- Return type:
Example
See examples/features/feature_sonic_temp_conversion.py for complete example.
See also
latent_heat_of_vaporization : Calculate latent heat from air temperature et_from_le : Convert latent heat flux to evapotranspiration
- diive.variables.latent_heat_of_vaporization(ta)[source]¶
Calculate latent heat of vaporization as a function of air temperature.
- Kudos:
Based on code of the R package ‘bigleaf’: https://rdrr.io/cran/bigleaf/src/R/meteorological_variables.r (latent.heat.vaporization)
- Reference:
Stull, B., 1988: An Introduction to Boundary Layer Meteorology (p.641) Kluwer Academic Publishers, Dordrecht, Netherlands
- Parameters:
ta (
Series) – air temperature (°C)- Return type:
- Returns:
Latent heat of vaporization (J kg-1)
Example
See examples/features/feature_latent_heat.py for complete example.
See also
et_from_le : Convert latent heat flux to evapotranspiration
- diive.variables.et_from_le(le, ta)[source]¶
Convert latent heat flux (energy) to evapotranspiration (mass).
- Kudos:
Based on code of the R package ‘bigleaf’: https://rdrr.io/cran/bigleaf/src/R/unit_conversions.r (LE.to.ET)
- Parameters:
- Return type:
- Returns:
Evapotranspiration (mm H2O h-1)
Example
See examples/features/feature_evapotranspiration.py for complete example.
See also
latent_heat_of_vaporization : Calculate latent heat from air temperature
- class diive.variables.DaytimeNighttimeFlag(timestamp_index, utc_offset, lat, lon, nighttime_threshold=20)[source]¶
Bases:
objectDerive daytime/nighttime flags from potential radiation. See
__init__().- Parameters:
timestamp_index (DatetimeIndex)
utc_offset (int)
lat (float)
lon (float)
nighttime_threshold (float)
- swinpot_col = 'SW_IN_POT'¶
- daytime_col = 'DAYTIME'¶
- nighttime_col = 'NIGHTTIME'¶
- __init__(timestamp_index, utc_offset, lat, lon, nighttime_threshold=20)[source]¶
Calculate flags to identify daytime and nighttime data from potential radiation.
- Parameters:
timestamp_index (
DatetimeIndex) – Time series index, flags and potential radiation are calculated using this indexutc_offset (
int) – UTC offset of timestamp_index, e.g. 1 for UTC+01:00lat (
float) – Latitudelon (
float) – Longitudenighttime_threshold (
float) – Threshold for potential radiation below which data are flagged as nighttime (W m-2)
Example
See examples/features/feature_daynightflag.py for complete examples.
- diive.variables.daytime_nighttime_flag_from_swinpot(swinpot, nighttime_threshold=20, daytime_col='DAYTIME', nighttime_col='NIGHTTIME')[source]¶
Create flags to identify daytime and nighttime data
- Parameters:
- Returns:
daytime with flags 1=daytime, 0=not daytime nighttime with flags 1=nighttime, 0=not nighttime
- Return type:
- class diive.variables.TimeSince(series, upper_lim=None, lower_lim=None, include_lim=True)[source]¶
Bases:
objectCount consecutive records since last occurrence of a condition.
Counts the number of records elapsed since a time series last fell inside a specified limit range. Useful for tracking dry periods (time since last rain), frost periods (time since freezing), warm spells, or any event-based analysis.
The class maintains a flag indicating whether each record is inside or outside the specified range, then counts consecutive “outside range” records backward in time to get the time-since count.
- Parameters:
series (
Series) – Input time series to analyze. Index should be datetime-like for proper time-based interpretation.upper_lim (
float) – Upper limit of the range. Records <= upper_lim (or < upper_lim if include_lim=False) are considered “inside range”. If None, there is no upper limit. Default is None.lower_lim (
float) – Lower limit of the range. Records >= lower_lim (or > lower_lim if include_lim=False) are considered “inside range”. If None, there is no lower limit. Default is None.include_lim (
bool) – If True (default), limits are inclusive (<=, >=). If False, limits are exclusive (<, >). Example: include_lim=False with lower_lim=0 counts records where value > 0.
- Variables:
series (pd.Series) – Input time series.
upper_lim (float) – Upper limit (None if not specified).
lower_lim (float) – Lower limit (None if not specified).
include_lim (bool) – Whether limits are inclusive.
timesince_col (str) – Name of the output column (format: TIMESINCE_{series_name}).
flag_col (str) – Name of the flag column (“FLAG_IS_OUTSIDE_RANGE”).
- Methods:
calc() – Calculate time-since counts based on limits. Must be called before accessing results.
get_timesince() -> pd.Series – Get the time-since values as a Series.
get_full_results() -> pd.DataFrame – Get complete results including original series, flags, and time-since counts.
Examples
Records since the last rain (dry-period length):
>>> import diive as dv, pandas as pd >>> idx = pd.date_range('2024-07-01', periods=6, freq='30min') >>> prec = pd.Series([0.0, 0.0, 1.2, 0.0, 0.0, 0.0], index=idx, name='PREC') >>> dv.variables.TimeSince(prec, lower_lim=0, include_lim=False).calc()
See also
examplesNotes
Time-since counts reset whenever a record falls within the range.
NaN values are treated as “outside range” to avoid artificial resets.
Use include_lim=False for strict inequalities (e.g., precipitation > 0).
Use include_lim=True for inclusive boundaries (e.g., temperature <= 0).
- upper_lim_col = 'UPPER_LIMIT'¶
- lower_lim_col = 'LOWER_LIMIT'¶
- flag_col = 'FLAG_IS_OUTSIDE_RANGE'¶
- __init__(series, upper_lim=None, lower_lim=None, include_lim=True)[source]¶
Initialize TimeSince counter.
- Parameters:
series (
Series) – Input time series to analyze.upper_lim (
float) – Upper limit threshold. Default None (no upper constraint).lower_lim (
float) – Lower limit threshold. Default None (no lower constraint).include_lim (
bool) – If True, use <= and >= (inclusive). If False, use < and > (exclusive). Default is True.
- property timesince_df¶
Get internal results dataframe.
- Returns:
DataFrame containing original series, limit columns, flag, and time-since counts.
- Return type:
pd.DataFrame
- Raises:
Exception – If data is empty or not initialized.
- get_timesince()[source]¶
Get time-since counts as a Series.
Must call calc() before accessing results.
- Returns:
Integer count of records since the last inside-range occurrence. Column name is TIMESINCE_{original_series_name}.
- Return type:
- get_full_results()[source]¶
Get complete results including series, flags, and time-since counts.
Must call calc() before accessing results.
- Returns:
DataFrame with columns: - {series_name}: Original input series - UPPER_LIMIT: Upper limit values - LOWER_LIMIT: Lower limit values - FLAG_IS_OUTSIDE_RANGE: 0 if inside range, 1 if outside/NaN - TIMESINCE_{series_name}: Record count since last inside-range occurrence
- Return type:
- calc()[source]¶
Calculate time-since counts.
Determines which records are inside/outside the specified range, creates a binary flag, then counts consecutive records since the last inside-range occurrence.
The algorithm: 1. Identifies records inside the limit range (flag=0) 2. Identifies records outside the limit range or with NaN values (flag=1) 3. Counts consecutive flag=1 records backward in time 4. Resets count to 0 when flag=0 (inside range) is encountered
Results are stored internally and accessible via get_timesince() or get_full_results().
- Returns:
Modifies internal state; results accessed via get_timesince() or get_full_results().
- Return type:
None
- diive.variables.lagged_variants(df, lag, stepsize=1, exclude_cols=None, verbose=0)[source]¶
Create lagged variants of variables
Shifts all records in df by lag records and stores the lagged variants as new columns.
For example, lagging the two variables TA and SW_IN with the settings lag=[-2, 1] and stepsize=1 creates the new variables .TA-2 (two records before TA), .TA-1 (one record before TA), .TA+1 (one record after TA), .SW_IN-2, .SW_IN-1, and .SW_IN+1. Note that the minus sign means “before”, the plus sign means “after”.
Can be used to investigate correlations between a scalar and the preceding or subsequent records of another scalar.
Note
The timestamp index of df must be regular and complete, i.e., all timestamps of the respective time resolution must be present. Otherwise shifting variables by x records might lead to undesirable results.
Shifting moves records beyond the start or end of the record, which leaves gaps at the series edges. Those gaps are filled with the nearest value, but only for source columns that contained no missing values to begin with: for a gappy source, filling the edges cannot be told apart from filling its genuine gaps, so the edges stay missing.
Example
See examples/features/feature_laggedvariants.py for complete examples.
- Parameters:
df (
DataFrame) – dataframe that contains variables that will be laggedlag (
list[int,int]) – list of integers given as number of records, defining the range of generated lag times For example lag=[-3, 2] and stepsize=1 will generated lagged variants -3, -2, -1, +1 and +2stepsize (
int) – stepsize between the different lagged variants given as number of records For example lag=[-8, 4] and stepsize=2 will generated lagged variants -8, -6, -4, -2 and +2exclude_cols (
list) – list of column names, these variables will not be laggedverbose (
int) – if True, print more output to console
- Return type:
- Returns:
input dataframe with added lagged variants
- diive.variables.generate_noisy_timeseries(start_date='2024-01-01', periods=365, freq='D', trend_slope=0.05, seasonal_strength=5.0, noise_level=2.0, outlier_fraction=0.02, random_seed=42)[source]¶
Generate synthetic time series DataFrame containing trend, seasonality, Gaussian noise, and random outliers.
The synthetic data is constructed using an additive model: y(t) = Trend(t) + Seasonality(t) + Noise(t) + Outliers(t)
- Parameters:
start_date (str or datetime) – The start date for the time index. Defaults to ‘2024-01-01’.
periods (int) – The number of time steps (data points) to generate. Defaults to 365.
freq (str) – The frequency string for the time index (e.g., ‘D’ for daily, ‘h’ for hourly, 30min for half-hourly). Defaults to ‘D’.
trend_slope (float) – The slope of the linear trend component. Positive values indicate an upward trend; negative values indicate a downward trend. Defaults to 0.05.
seasonal_strength (float) – The amplitude of the sine wave component representing seasonality. Defaults to 5.0.
noise_level (float) – The standard deviation of the normal (Gaussian) distribution used to generate white noise. Defaults to 2.0.
outlier_fraction (float) – The proportion of data points to replace with outliers (between 0.0 and 1.0). Outliers are random spikes with magnitude 5x-10x the noise level. Defaults to 0.02 (2%).
random_seed (int) – The seed for the random number generator to ensure reproducibility. Defaults to 42.
- Returns:
- A DataFrame with a DatetimeIndex and the following columns:
’base_signal’: The underlying signal (trend + seasonality) without noise.
’noise’: The isolated Gaussian noise component.
’observed_value’: The final synthetic data (base_signal + noise + outliers).
- Return type:
pd.DataFrame
- diive.variables.add_impulse_noise(series, factor_low=-10, factor_high=10, contamination=0.04, seed=None)[source]¶
Create impulse noise based on series
- Parameters:
series (
Series) – time seriesfactor_low (
float) – Low factor for noise creation, defines the lower bound of the noise, calculated as factor_low * abs(min(series)).factor_high (
float) – High factor for noise creation, defines the upper bound of the noise, calculated as factor_high * abs(max(series)).contamination (
float) – Fraction of series to add noise to.seed (
int) – Random seed.
- Returns:
Series with added noise
- diive.variables.combine_variables(series1, series2, method='multiply', name=None)[source]¶
Combine two time series element-wise by an arithmetic operation.
The two series are aligned on their (timestamp) index and combined record by record.
methodselects the operation:method
symbol
addsubtractmultiplydivide/
Both operands must be present. Wherever either input is missing the result is NaN — combining two variables is only defined where both were measured, so the record count of the result is the size of their overlap, not of either input. Expect to lose records here; that is the honest outcome, and
diive.analysis.count_gaps()or a simple.notna().sum()tells you how many.There is deliberately no option to substitute the operation’s identity (0 for add/subtract, 1 for multiply/divide) for a missing operand. It reads as “keep the one-sided record”, but the result is misleading:
A + BwithAmissing returnsB, which is not a sum, and for the non-commutative operations it is worse —A - Breturns-BandA / Breturns1 / B. Substituting a value for a gap is a gap-filling decision; make it explicitly with the gap-filling tools (ormethod='fillgaps'below) rather than as a side effect of arithmetic.method='fillgaps'is the one method that spans the union: it keepsseries1and fills only its gaps (NaNs) with the matching values ofseries2(aseries1.combine_first(series2)). Use it when you want “take B where A is missing” — that is what it means, stated plainly.- Parameters:
- Return type:
- Returns:
The combined series, indexed by the union of the two inputs’ indexes and valid only where both inputs are.
- diive.variables.combine_variables_to_code(var1, var2, method='multiply', name=None)[source]¶
Render a
combine_variables()call as a runnable snippet.Assumes
dvand a DataFramedfare already in scope. Returns the snippet ending in a newline (the result is bound tocombined).
- diive.variables.calc_vpd_from_ta_rh_to_code(ta_col, rh_col, name=None)[source]¶
Render a
calc_vpd_from_ta_rh()call as a runnable snippet.Assumes
dvand a DataFramedfare already in scope. Returns the snippet ending in a newline (the result is bound tovpd, in kPa).
- diive.variables.potrad_to_code(lat, lon, utc_offset, name=None)[source]¶
Render a
potrad()call as a runnable snippet.Assumes
dvand a DataFramedfare already in scope. Returns the snippet ending in a newline (the result is bound toswinpot, in W m-2).- Parameters:
lat (
float) – Site latitude in decimal degrees (north positive).lon (
float) – Site longitude in decimal degrees (east positive).utc_offset (
int) – UTC offset (hours) of the timestamps, e.g. 1 for UTC+01:00.name (
str|None) – Output series name, rendered as a trailing.rename()when it differs from the library function’s own name ('SW_IN_POT').
- Return type:
- diive.variables.classify_variable(name)[source]¶
Classify a variable from its column name.
- Parameters:
name (
str) – Variable / column name, e.g.'GPP_CUT_REF_f'.- Return type:
- Returns:
A
VariableClass(kind,category) for recognised variables, orNoneif the name matches no known prefix.
Examples
>>> import diive as dv >>> dv.variables.classify_variable('NEE_CUT_REF_f') VariableClass(kind='NEE', category='carbon') >>> dv.variables.classify_variable('LE_f') VariableClass(kind='LE', category='water') >>> dv.variables.classify_variable('QC_NEE') is None True
- diive.variables.auto_pick_column(columns, needle, *, prefer=None, avoid=None)[source]¶
First column name matching
needleby the FluxNet naming conventions.Name-based seeding for variable pickers: scan
columnsfor one whose upper-cased name containsneedle. Withpreferset, a column that also containspreferranks ahead of a plain match;avoidexcludes columns containing that substring. Returns""when nothing matches.needle/prefer/avoidare compared against the upper-cased column name, so pass them upper-cased (the FluxNet column convention).
- diive.variables.driver_flag_columns(columns, driver)[source]¶
Quality-flag columns that belong to the column
driver, in input order.Matches the flag naming of diive (
FLAG_<driver>_..._ISFILLED) and of FLUXNET (<driver>_QC): a column qualifies when its upper-cased name contains the upper-cased driver name and ends in_ISFILLEDor_QC. The driver column itself is never returned. Used to suggest the driver QC columns for MDS gap-filling (FluxMDS(swin_qc=, ta_qc=, vpd_qc=)).
- class diive.variables.VariableClass(kind, category)[source]¶
Bases:
NamedTupleResult of
classify_variable().- Variables:
- Parameters: