Analysis (dv.analysis)

Time series analysis: correlation, causality, gaps, binning, decomposition and compound extremes.

Imported as diive.analysis, reached as dv.analysis after import diive as dv.

ANALYSIS: TIME SERIES ANALYSIS METHODS

Gap statistics, correlation and driver ranking, Granger causality, seasonal-trend decomposition, harmonic analysis and spectrograms, histograms, percentiles, grid aggregation, stratified binning, optimum ranges, compound extremes, dataframe profiling and binned curve fitting. Provisional tools are in experimental.

Part of the diive library: https://github.com/holukas/diive

class diive.analysis.BinFitterCP(df, xcol, ycol, predict_max_x=None, predict_min_x=None, n_predictions=1000, n_bins_x=10, bins_y_agg='mean', fit_type='quadratic_offset')[source]

Bases: object

Fit polynomial functions to binned data with confidence intervals and prediction bands.

Bins data into quantile bins along the x-axis (similar record counts per bin), aggregates y-values within each bin, and fits polynomial functions (linear, quadratic, cubic) with 95% confidence intervals and prediction bands. Useful for analyzing driver-response relationships in ecosystem data. Call run() to fit, then read fit_results.

Examples

See examples/fits/fit_binfittercp.py for binned fitting of a temperature-VPD relationship, result exploration and interval interpretation. See examples/fits/fit_fitter.py for an ecosystem driver-response (NEE-VPD) fit.

Parameters:
  • df (DataFrame)

  • xcol (str)

  • ycol (str)

  • predict_max_x (float)

  • predict_min_x (float)

  • n_predictions (int)

  • n_bins_x (int)

  • bins_y_agg (Literal['mean', 'median'])

  • fit_type (Literal['linear', 'quadratic_offset', 'quadratic', 'cubic'])

__init__(df, xcol, ycol, predict_max_x=None, predict_min_x=None, n_predictions=1000, n_bins_x=10, bins_y_agg='mean', fit_type='quadratic_offset')[source]

Fit function to (binned) data and give the confidence interval (CI) and prediction interval (PI).

Parameters:
  • df (DataFrame) – Dataframe with data for variables xcol and ycol. Rows with NaN in either are dropped.

  • xcol (str) – Variable name in df, will be used for creating n_bins_x number of bins.

  • ycol (str) – Variable name in df, will be aggregated in x-bins using method bins_y_agg.

  • predict_max_x (float) – Currently unused. Predictions cover the x range of the fitted data.

  • predict_min_x (float) – Currently unused. Predictions cover the x range of the fitted data.

  • n_predictions (int) – Number of predictions, e.g. 1000 means y will be predicted for 1000 x-values. A value that is not an int uses the number of records, values below 2 use 2.

  • n_bins_x (int) – Number of bins for y-aggregation. Bins are quantile bins of xcol, so each bin holds about the same number of records. If n_bins_x=0, then the fit is done for the unbinned data.

  • bins_y_agg (Literal['mean', 'median']) – Aggregation type for y in each x-bin. Options: ‘mean’, ‘median’

  • fit_type (Literal['linear', 'quadratic_offset', 'quadratic', 'cubic']) – Fit type to fit to the bins. Options: ‘linear’ (ax+b), ‘quadratic_offset’ (ax^2+bx+c), ‘quadratic’ (ax^2+bx, no offset), ‘cubic’ (ax^3+bx^2+cx+d). Unknown values fall back to ‘quadratic_offset’.

run()[source]

Run the binned curve fit.

property result: dict

fit results dict.

Type:

Primary result

get_results()[source]

Return the fit results.

showplot(ax=None, show_unbinned_data=True, show_bin_variation=True, unbinned_alpha=0.5, highlight_year=None, bin_size=90, bin_color='black', bin_edgecolor='none', bin_marker='o', bin_alpha=1, fitline_color='red', label='label', showfit=True, show_prediction_interval=True, xlim=None, ylim=None, title=None, xlabel=None, ylabel=None)[source]

Plot the data, the bins and the fitted curve with its intervals. Needs run() first.

Parameters:
  • ax – Axes to draw on. A new figure is created and shown when None.

  • show_unbinned_data (bool) – Show the input records as open circles.

  • show_bin_variation (bool) – Show the spread in each bin: SD error bars for bins_y_agg='mean', the interquartile range for 'median'.

  • unbinned_alpha (float) – Transparency of the input records.

  • highlight_year (int) – Highlight the fitted points of this year. Needs the fitted data to have a DatetimeIndex, so in practice unbinned data (n_bins_x=0).

  • bin_size (int) – Marker size of the bins.

  • bin_color (str) – Marker color of the bins.

  • bin_edgecolor (str) – Marker edge color of the bins.

  • bin_marker (str) – Marker style of the bins and the highlighted year.

  • bin_alpha (float) – Transparency of the bins.

  • fitline_color (str) – Color of the fit line, confidence region and prediction interval.

  • label (str) – Legend label prefix for the highlighted year.

  • showfit (bool) – Show the fit line and the 95% confidence region.

  • show_prediction_interval (bool) – Also show the 95% prediction interval (needs showfit).

  • xlim (tuple) – x-axis limits as (min, max).

  • ylim (tuple) – y-axis limits as (min, max).

  • title (str) – Axes title. Defaults to a description of the bins.

  • xlabel (str) – x-axis label. Defaults to xcol.

  • ylabel (str) – y-axis label. Defaults to ycol.

Returns:

(last scatter drawn, fit line, confidence region, upper prediction band, highlighted year). Each is None when not drawn.

Return type:

Tuple of artists

class diive.analysis.CompoundExtremes(var1, var2, agg='monthly', agg_func='mean', var1_extreme='high', var2_extreme='low', threshold=2.0, var1_threshold=None, var2_threshold=None, standardize_by='season', var1_label=None, var2_label=None, compound_label='Compound', none_label='None')[source]

Bases: object

Detect compound extremes from two standardized drivers. See __init__().

Parameters:
  • var1 (Series)

  • var2 (Series)

  • agg (Literal['monthly', 'daily'])

  • agg_func (Literal['mean', 'median', 'min', 'max', 'sum'])

  • var1_extreme (Literal['high', 'low'])

  • var2_extreme (Literal['high', 'low'])

  • threshold (float)

  • var1_threshold (float)

  • var2_threshold (float)

  • standardize_by (Literal['season', 'record'])

  • var1_label (str)

  • var2_label (str)

  • compound_label (str)

  • none_label (str)

__init__(var1, var2, agg='monthly', agg_func='mean', var1_extreme='high', var2_extreme='low', threshold=2.0, var1_threshold=None, var2_threshold=None, standardize_by='season', var1_label=None, var2_label=None, compound_label='Compound', none_label='None')[source]

Classify months or days into compound-extreme categories.

Each period is aggregated to the chosen resolution, both variables are standardized to z-scores, and a period is flagged extreme for a variable when its z-score crosses the threshold in the variable’s extreme direction. The four categories are: none, var1-only, var2-only, and compound (both).

Parameters:
  • var1 (Series) – First driver, e.g. VPD. Any sampling frequency (aggregated internally).

  • var2 (Series) – Second driver, e.g. soil water content.

  • agg (Literal['monthly', 'daily']) – Temporal resolution to analyze. ‘monthly’ -> month-start periods, ‘daily’ -> calendar days.

  • agg_func (Literal['mean', 'median', 'min', 'max', 'sum']) – Aggregation applied when resampling to agg resolution.

  • var1_extreme (Literal['high', 'low']) – Which tail of var1 counts as extreme. ‘high’ flags z >= threshold (e.g. high VPD), ‘low’ flags z <= -threshold.

  • var2_extreme (Literal['high', 'low']) – Which tail of var2 counts as extreme (e.g. ‘low’ for soil water content -> drought).

  • threshold (float) – z-score magnitude (always positive) used for both variables unless overridden per variable.

  • var1_threshold (float) – Optional per-variable threshold magnitude for var1 (falls back to threshold).

  • var2_threshold (float) – Optional per-variable threshold magnitude for var2.

  • standardize_by (Literal['season', 'record']) –

    How z-scores are computed.

    • ’season’: deseasonalized — each period is standardized against the same position in the seasonal cycle (calendar month for monthly, day-of-year for daily). Removes the seasonal cycle so genuinely anomalous periods stand out. This is the default and the standard choice for compound-extreme detection.

    • ’record’: a single mean/std over the whole aggregated record. Simpler, but the seasonal cycle of variables such as VPD dominates the z-score.

  • var1_label (str) – Human-readable label for the var1-only category (default: the var1 series name).

  • var2_label (str) – Human-readable label for the var2-only category (default: the var2 series name).

  • compound_label (str) – Label for the compound (both-extreme) category.

  • none_label (str) – Label for the no-extreme category.

Properties:

.results: DataFrame indexed by period with aggregated values, z-scores,
    per-variable extreme flags, the CATEGORY code, and a human LABEL.
.counts: Per-category record counts (Series, indexed by label).
.labels: Period-name Series (e.g. '2022-08') for annotating plots.

Example

See examples/analysis/analysis_compound_extremes.py.

See also

diive.plotting.CompoundExtremesPlot : the quadrant scatter for these results.

property results: DataFrame

Classification results, one row per analyzed period.

property counts: Series

Record count per category label (ordered none/var1/var2/compound).

property labels: Series

Period-name labels (e.g. ‘2022-08’) aligned to the results index.

property label_map: dict

Category code -> human label mapping.

diive.analysis.count_gaps(s)[source]

Number of gaps = maximal runs of consecutive missing values.

A single missing value is one gap; ten consecutive missing values are still one gap. Counts the starts of NaN runs (cheap, no grouping needed) — the same notion of “gap” used by GapStats/GapFinder.

Return type:

int

Parameters:

s (Series)

class diive.analysis.DailyCorrelation(s1, s2, mincorr=0.8)[source]

Bases: object

Calculate daily correlation between two time series.

Computes correlation for each day and provides tools for analysis: - Access correlations via .correlations property or .summary() - Identify best/worst correlation days with .get_days_by_correlation() - Detect anomalous days with .detect_anomalies() - Visualize results with .plot()

Parameters:
  • s1 (Series) – any time series, timestamp must overlap with s2

  • s2 (Series) – any time series, timestamp must overlap with s1

  • mincorr (float) – minimum absolute correlation for plot thresholds, must be between -1 and 1 (inclusive). Example: with 0.8, correlations between -0.8 and +0.8 are low, correlations smaller than -0.8 and higher than +0.8 are high.

Variables:
  • daycorrs – Series with correlations for each day

  • df – Combined DataFrame with both input series and date column

Properties:

correlations: Daily correlations as pandas Series result: Same as correlations

Methods:
  • summary() – Summary statistics (mean, median, skewness, kurtosis, normality)

  • get_days_by_correlation (high) – Days sorted by absolute correlation

  • detect_anomalies (method, threshold) – Identify outlier correlation days

  • plot() – Figure with the daily correlations and example days with low and high correlation

Parameters:

Example

See examples/analysis/analysis_daily_correlation.py. It covers quality checks (observed vs. potential radiation), physical relationships (temperature vs. radiation), biological processes (temperature vs. CO2 flux), summary statistics and anomaly detection.

__init__(s1, s2, mincorr=0.8)[source]

Compute daily correlations between two series. See the class docstring for parameters.

Parameters:
property result: Series

daily correlations as a pandas Series.

Type:

Primary result

property correlations: Series

Daily correlations as a pandas Series.

summary()[source]

Get summary statistics of the daily correlations.

Returns:

  • count: number of valid (non-NaN) days

  • median: median correlation

  • mean: mean correlation

  • std: standard deviation

  • min: minimum correlation

  • max: maximum correlation

  • p1: 1st percentile

  • p99: 99th percentile

  • skewness: distribution skewness (0 for a symmetric distribution)

  • kurtosis: excess kurtosis (0 for a normal distribution, >0 for heavy tails)

  • normality_statistic: Shapiro-Wilk test statistic

  • normality_pvalue: p-value (>0.05 suggests normal distribution)

All float fields are NaN when no valid days exist.

Return type:

dict

get_days_by_correlation(high=True)[source]

Get days sorted by correlation strength (absolute correlation).

Parameters:

high (bool) – if True, return the strongest correlations first (descending absolute value). If False, return the weakest first (ascending).

Return type:

DataFrame

Returns:

DataFrame with columns [‘date’, ‘correlation’] sorted by absolute correlation. Days with no valid correlation (NaN) are excluded.

detect_anomalies(method='zscore', threshold=2.0)[source]

Identify anomalous correlation days.

Parameters:
  • method (str) – detection method: - ‘zscore’: z-score based (default, detects outliers) - ‘iqr’: interquartile range method (robust to extreme outliers)

  • threshold (float) – sensitivity threshold: - zscore: standard deviations from mean (default 2.0 = ~95% confidence) - iqr: multiplier for IQR (default 2.0 = moderate sensitivity)

Return type:

DataFrame

Returns:

DataFrame with columns [‘date’, ‘correlation’, ‘anomaly_score’, ‘is_anomaly’] sorted by anomaly score (highest first).

Example

Dates with z-score > 2.0 are flagged as anomalies (unusual correlation days).

plot(showplot=True)[source]

Display daily correlation analysis plot.

Parameters:

showplot (bool) – if True, call plt.show() to display the figure interactively. Set to False when rendering in non-interactive environments (Sphinx Gallery, headless testing).

Return type:

Figure

Returns:

matplotlib Figure.

diive.analysis.daily_correlation

alias of DailyCorrelation

diive.analysis.dataframe_overview(df)[source]

Dataset-level facts for a profiling header.

Returns a dict with: n_rows, n_cols, n_cells, missing_cells, missing_perc, duplicate_timestamps (duplicated index labels), duplicate_rows, start, end, freq (the index freqstr if set, else pd.infer_freq, else None), and memory_bytes (deep memory usage). Timestamp/freq fields are None when the index is not a DatetimeIndex.

Return type:

dict

Parameters:

df (DataFrame)

class diive.analysis.GrangerCausality(x, y, max_lag=5, verbose=True)[source]

Bases: object

Test if one time series Granger-causes another.

Granger causality tests whether past values of variable X improve predictions of variable Y beyond what Y’s own past values provide. This is predictive causality, not true causality (correlation or reverse causation possible).

Parameters:
  • x (Series) – Time series that may cause y (pandas Series)

  • y (Series) – Time series potentially caused by x (pandas Series)

  • max_lag (int) – Maximum lag order to test (default: 5)

  • verbose (bool) – Currently unused. Call report() to print the results.

Example

See examples/analysis/analysis_granger.py for complete examples.

>>> import diive as dv, pandas as pd, numpy as np
>>> idx = pd.date_range('2024-06-01', periods=200, freq='30min')
>>> radiation, co2_flux = pd.Series(np.arange(200.), index=idx), pd.Series(np.sin(np.arange(200.)), index=idx)
>>> gc = dv.analysis.GrangerCausality(x=radiation, y=co2_flux, max_lag=10)
__init__(x, y, max_lag=5, verbose=True)[source]

Initialize Granger causality test.

Parameters:
p_values()[source]

Extract the p-value of the SSR-based F-test for each lag.

Return type:

DataFrame

Returns:

DataFrame with columns Lag and p_value, one row per lag from 1 to max_lag.

significant_lag(alpha=0.05)[source]

Find first lag where X Granger-causes Y (p < alpha).

Parameters:

alpha (float) – Significance level (default: 0.05)

Return type:

int

Returns:

Lag order if significant, None otherwise

report(alpha=0.05)[source]

Print summary of Granger causality results.

Interpretation: A p-value < alpha at a given lag means past values of X significantly improve predictions of Y beyond what Y’s own past provides.

Parameters:

alpha (float)

class diive.analysis.StratifiedAnalysis(df, zvar, xvar, yvar, n_bins_z=48, n_bins_x=2, conversion=None, agg='median')[source]

Bases: object

Analyze y across bins of x, stratified into bins of z. See __init__().

Parameters:
__init__(df, zvar, xvar, yvar, n_bins_z=48, n_bins_x=2, conversion=None, agg='median')[source]

Stratified binning analysis: analyze variable y across bins of x, stratified by z.

Creates hierarchical bins: stratifies data by variable z into quantile-based bins, then within each z bin, further bins by variable x, and aggregates y within each bin.

Parameters:
  • df (DataFrame) – Dataframe containing at least zvar, xvar and yvar. Only those three columns are used: they are extracted first, then rows missing any of them are dropped. Gaps in the frame’s other columns do not remove records.

  • zvar (str) – Name of the stratification variable, will be shown as colors (z) in the plot.

  • xvar (str) – Name of the x-axis binning variable, will be shown on the x-axis (x) in the plot.

  • yvar (str) – Name of the variable of interest, will be shown on the y-axis (y) in the plot.

  • n_bins_z (int) – Number of stratification bins for zvar. Must be >0 and <= 120.

  • n_bins_x (int) – Number of bins for xvar within each z bin. Must be >= 2.

  • conversion (str) – Convert all three variables before binning. Options: ‘z-score’, ‘percentile’, or None (default, no conversion).

  • agg (str) – Aggregation method for binning, e.g. ‘median’, ‘mean’.

Properties:

.results: All binned results in one DataFrame with a z_bin_label column (after .calcbins()) .binaggs: Dict of DataFrames, one per z bin .n_records_input / .n_records_used: Records received vs. records analyzed

Methods:
  • .calcbins() – Compute binned aggregates (.run() does the same)

  • .get_binaggs() – Return results dictionary

  • .showplot_decoupling_sbm() – Visualize results with line plot and error bars

Parameters:

Example

See examples/analysis/analysis_decoupling.py for complete examples demonstrating stratified binning across temperature ranges, result access, and visualization.

See also

SortingBinsMethod : Alias of StratifiedAnalysis, kept for backward compatibility.

property df: DataFrame

The three analysis variables, without the records that gap any of them.

property binaggs: dict

Per-z-bin aggregates as a dict of DataFrames (raises if calcbins() not yet run).

run(**kwargs)[source]

Unified trigger. Delegates to .calcbins().

property result: DataFrame

all binned results as a single DataFrame.

Type:

Primary result

get_binaggs()[source]

Return the dict of DataFrames keyed by z bin label (same as binaggs).

Return type:

dict

property results: DataFrame

All binned results as a single DataFrame.

Concatenates all z-bins with a ‘z_bin_label’ column indicating bin membership.

calcbins()[source]

Compute the stratified bin aggregates (with counts and 16th/84th percentile errors) into binaggs.

showplot_decoupling_sbm(ax=None, saveplot=False, title=None, path=None, emphasize_lines=True, **kwargs)[source]

Plot y-vs-x curves with error bars, one line per z bin (a stratified-bin-means plot).

Parameters:
  • ax – Optional matplotlib axes to draw on; a new figure is created if None.

  • saveplot (bool) – If True, save the figure as PNG to path. With ax, the figure that holds ax is saved.

  • title (str) – Optional figure title, shown only when the method creates the figure (ax is None). Also used in the file name of the saved figure.

  • path (Path) – Folder for the saved figure when saveplot is True.

  • emphasize_lines (bool) – If True, draw thicker lines with a thin black line on top.

  • **kwargs – legend=False hides the legend. Other keywords are forwarded to ax.plot for each z-bin line.

class diive.analysis.GapFinder(series, max_length=None, min_length=None, sort_results=True)[source]

Bases: object

Find gaps in time series.

Detects consecutive missing values (NaN) and reports their locations, duration, and statistics. Useful for understanding data quality and planning gap-filling strategies.

Uses a cumulative-sum grouping trick to identify consecutive NaN runs in a single vectorized pass — no explicit loops.

Parameters:
  • series (Series) – Time series with a DatetimeIndex

  • max_length (int) – Only return gaps with GAP_LENGTH <= max_length (upper size filter)

  • min_length (int) – Only return gaps with GAP_LENGTH >= min_length (lower size filter)

  • sort_results (bool) – Sort results by GAP_LENGTH descending (default True)

Properties:

.results: DataFrame with columns GAP_START, GAP_END, GAP_LENGTH, GAP_DURATION.
    GAP_DURATION is NaT when time resolution cannot be inferred.
.summary: Dict of headline statistics (n_gaps, missing_pct, longest gap, etc.).
Methods:
  • .showfig() – Two-panel figure — availability heatmap and gap-length histogram.

  • .gap_at (timestamp) – The gap containing a timestamp, or the nearest one.

Parameters:

Example

See examples/analysis/analysis_gapfinder.py for complete usage including size filtering, summary statistics, and visualization.

See also

TimestampSanitizer : Handles missing time steps and data gaps at source.

__init__(series, max_length=None, min_length=None, sort_results=True)[source]
Parameters:
  • series (Series) – Time series with a DatetimeIndex

  • max_length (int) – Only return gaps with GAP_LENGTH <= max_length (upper size filter)

  • min_length (int) – Only return gaps with GAP_LENGTH >= min_length (lower size filter)

  • sort_results (bool) – Sort results by GAP_LENGTH descending (default True)

property results: DataFrame

Gap detection results as DataFrame.

Columns: GAP_START, GAP_END, GAP_LENGTH, GAP_DURATION. GAP_DURATION is NaT when time resolution cannot be inferred. Sorted by gap length descending if sort_results=True.

property summary: dict

Headline gap statistics as a dict.

Keys: n_gaps, total_missing_records, missing_pct, longest_gap_records, median_gap_records, mean_gap_records, longest_gap_duration. n_gaps and the gap-length keys reflect any max_length / min_length filters. total_missing_records and missing_pct count all missing records.

gap_at(timestamp)[source]

Return the detected gap containing timestamp, or the nearest one.

The returned row (a pandas.Series) has GAP_START, GAP_END, GAP_LENGTH and GAP_DURATION. Returns None if no gaps were found. Handy for interactive tools that map a clicked time to a gap.

Parameters:

timestamp – A datetime / pandas Timestamp (tz-aware values are accepted and reduced to tz-naive wall time).

showfig(saveplot=False, title=None, path=None)[source]

Display gap analysis visualizations.

Two-panel figure:

  • Top: daily data availability heatmap (day-of-year × year)

  • Bottom: gap length histogram with duration reference lines

Parameters:
  • saveplot (bool) – Save figure to file

  • title (str) – Figure title

  • path (Path | str) – Directory for saved figure

plot_availability_heatmap(ax)[source]

Heatmap of daily data availability: day-of-year (x) vs year (y).

Blue = fully available, red = all missing (RdYlBu colormap). Shows seasonal and annual patterns in data loss.

plot_gap_length_histogram(ax)[source]

Histogram of gap lengths on a log scale with duration reference lines.

Duration references (1h, 1 day, 1 week) are inferred from the time resolution of the input series.

class diive.analysis.GapStats(series, long_gap_records=48)[source]

Bases: object

Extended gap analysis with seasonal breakdown and long-gap flagging.

Wraps GapFinder and adds monthly statistics, annual coverage, identification of long gaps, and a four-panel visualization.

Use GapFinder when you only need per-gap locations and headline counts. Use GapStats when you need seasonal context, annual trends, or a report of which specific long gaps occurred.

Parameters:
  • series (Series) – Time series with a DatetimeIndex.

  • long_gap_records (int) – Gaps with GAP_LENGTH >= this value are reported separately as long gaps. Default is 48, which equals one day for 30-min data. Pass None to disable long-gap identification.

Properties:

.results: Gap table (chronological) with YEAR and MONTH columns added. .monthly_stats: Per-calendar-month missing statistics, all years combined. .annual_coverage: Per-year data coverage percentages. .long_gaps: Subset of .results where GAP_LENGTH >= long_gap_records. .summary: Extended headline statistics dict.

Methods:
  • .gap_at (timestamp) – The gap containing a timestamp, or the nearest one (row includes YEAR / MONTH).

  • .report() – Rich-formatted console report — rules, coloured tables, long-gap list, monthly and annual breakdowns.

  • .showfig() – Four-panel figure with RdYlBu availability heatmap, gap spike timeline, monthly polar chart, gap-length histogram.

  • .plot_availability_heatmap (ax) – Heatmap panel for custom figures.

  • .plot_gap_spike_timeline (ax) – Gap spike panel for custom figures.

  • .plot_monthly_polar (ax) – Polar monthly chart (requires polar axes).

  • .plot_monthly_gap_distribution (ax) – Flat bar chart alternative to polar.

Parameters:

Example

See examples/analysis/analysis_gapstats.py for complete usage.

Typical flux-chain usage after L3.3:

from diive.analysis import GapStats

for scen, series in data.levels.filteredseries_level33_qcf.items():
    gs = GapStats(series, long_gap_records=48)
    print(gs)
    gs.showfig(title=f"Gap analysis — {scen}")

See also

GapFinder : Lightweight gap detection (used internally by GapStats).

__init__(series, long_gap_records=48)[source]

Compute gap statistics for a series. See the class docstring for parameters.

Parameters:
property results: DataFrame

Gap table sorted chronologically, with YEAR and MONTH columns.

Columns: GAP_START, GAP_END, GAP_LENGTH, GAP_DURATION, YEAR, MONTH.

property monthly_stats: DataFrame

Per-calendar-month gap statistics, all years combined.

Columns: total_records, missing_records, missing_pct, n_gaps. Index: MONTH (1-12).

property annual_coverage: DataFrame

Per-year data coverage.

Columns: total_records, valid_records, missing_records, coverage_pct. Index: YEAR.

property long_gaps: DataFrame

Gaps with GAP_LENGTH >= long_gap_records, sorted by length descending.

Empty DataFrame if long_gap_records is None or no qualifying gaps exist.

property summary: dict

Extended headline statistics dict.

Includes all keys from GapFinder.summary plus: n_long_gaps, long_gap_records_threshold, worst_month (1-12 or None), worst_month_missing_pct, annual_coverage (dict mapping year to coverage_pct).

gap_at(timestamp)[source]

Return the gap containing timestamp, or the nearest one.

The returned row (a pandas.Series) includes the YEAR / MONTH columns alongside GAP_START, GAP_END, GAP_LENGTH and GAP_DURATION. Returns None if no gaps were found. Handy for interactive tools that map a clicked time to a gap.

Parameters:

timestamp – A datetime / pandas Timestamp (tz-aware values are accepted and reduced to tz-naive wall time).

report()[source]

Rich-formatted console report of gap statistics.

Prints colour-coded sections using the diive Rich console: - Overview (missing%, gap count, long-gap count) - Long gaps table (sorted longest-first, top 20) - Monthly missing table (all years combined) - Annual coverage table (only when series spans > 1 year)

showfig(saveplot=False, title=None, path=None)[source]

Four-panel gap analysis figure.

Layout (top to bottom):

  • Row 1 (full width): daily availability heatmap, blue = data, red = gap

  • Row 2 (full width): gap spike timeline — each gap as a coloured vertical line, tall spikes mark long gaps

  • Row 3 left: monthly missing-data polar chart (Jan at top, clockwise)

  • Row 3 right: gap-length histogram (log scale)

Parameters:
  • saveplot (bool) – Save figure to file.

  • title (str) – Figure title.

  • path (Path | str) – Directory for saved figure.

plot_availability_heatmap(ax)[source]

Daily availability heatmap: day-of-year (x) vs year (y).

Blue = fully available, red = all missing. Uses the RdYlBu colormap with white year-separator lines and faint month grid lines.

Parameters:

ax – Matplotlib Axes to draw on.

plot_gap_spike_timeline(ax)[source]

Gap spike chart: each gap as a coloured vertical line on a time axis.

Short gaps form a low-amplitude base layer; long gaps spike upward in deep red. A dashed threshold line marks long_gap_records. The top-3 longest gaps are annotated.

Parameters:

ax – Matplotlib Axes to draw on.

plot_monthly_polar(ax)[source]

Polar bar chart of monthly missing-data percentage.

12 bars radiate clockwise from January at the top. Bar length encodes missing% for that calendar month (all years combined). Color intensity follows the same scale: light yellow = low missing, deep red = high.

Parameters:

ax – Matplotlib polar Axes (created with projection='polar').

plot_monthly_gap_distribution(ax)[source]

Monthly missing-data bar chart with gap-count annotations.

Suitable for embedding in custom multi-panel figures. For the full built-in figure use showfig(), which uses the polar variant.

Bar height = percentage of records missing for that calendar month (all years combined). Bar annotation = number of gap periods.

Parameters:

ax – Matplotlib Axes to draw on.

class diive.analysis.GridAggregator(x, y, z, binning_type, n_bins=10, min_n_vals_per_bin=1, aggfunc='mean', custom_x_bins=None, custom_y_bins=None)[source]

Bases: object

Aggregate z over a 2D grid of x and y bins.

x and y are binned by quantiles, equal-width bins or custom bin edges, then z is aggregated in each x/y cell with a named statistic or a custom callable. Binning and aggregation run on initialization.

Bin labels: quantile bins are labelled by their lower percentile (0, 10, …, 90 for 10 bins). Equal-width and custom bins are labelled by their lower edge.

Properties:

df_long: Input records with their x and y bin labels (not aggregated). df_agg_wide: Aggregated z as a grid (y bins as rows, x bins as columns, empty bins NaN). df_agg_long: The same aggregates, one row per cell (empty cells dropped, except for custom bins).

Example

See examples/analysis/analysis_gridaggregator.py for complete examples demonstrating quantile binning, equal-width binning, and custom binning methods with output format comparisons.

Variables:
  • x (pd.Series) – X-axis data to be used in binning.

  • y (pd.Series) – Y-axis data to be used in binning.

  • z (pd.Series) – Z-axis data to be aggregated based on X and Y bins.

  • binning_type (Literal['quantiles', 'equal_width', 'custom']) – Type of binning method used (‘quantiles’, ‘equal_width’, or ‘custom’).

  • n_bins (int) – Number of bins for ‘quantiles’ or ‘equal_width’ binning. Ignored if the binning type is ‘custom’.

  • min_n_vals_per_bin (int) – Minimum required values in a bin to include in aggregation.

  • custom_x_bins (Union[np.ndarray, list, None]) – Custom bin edges for the X-axis when binning type is ‘custom’.

  • custom_y_bins (Union[np.ndarray, list, None]) – Custom bin edges for the Y-axis when binning type is ‘custom’.

  • x_col_name (str) – Name derived from the X data series or defaulted to ‘x_data’.

  • y_col_name (str) – Name derived from the Y data series or defaulted to ‘y_data’.

  • z_col_name (str) – Name derived from the Z data series or defaulted to ‘z_data’.

  • x_bin_col_name (str) – Column name for X-axis binning results in the internal DataFrame.

  • y_bin_col_name (str) – Column name for Y-axis binning results in the internal DataFrame.

  • aggfunc (Union[Literal['mean', 'min', 'max', 'median', 'sum', 'count'], Callable]) – Aggregation function for binning operation. May be a string literal or custom callable.

Parameters:
__init__(x, y, z, binning_type, n_bins=10, min_n_vals_per_bin=1, aggfunc='mean', custom_x_bins=None, custom_y_bins=None)[source]

Initializes the class with input data, binning configurations, and aggregation setup. Handles preparation of internal DataFrame for processing, determines column names, validates inputs, and performs data binning and aggregation on initialization.

Parameters:
  • x (Series) – Input series for x-coordinates or independent variable.

  • y (Series) – Input series for y-coordinates or independent variable.

  • z (Series) – Input series for z-values or dependent variable to be aggregated.

  • binning_type (Literal['quantiles', 'equal_width', 'custom']) – Type of binning strategy to apply for x and y dimensions. Options include quantiles, equal-width, or custom boundaries.

  • n_bins (int) – Number of bins to create for x and y when using quantiles or equal-width binning. Defaults to 10.

  • min_n_vals_per_bin (int) – Minimum number of records an x/y cell needs. Cells with fewer records are left empty (NaN). Defaults to 1.

  • aggfunc (Union[Literal['mean', 'min', 'max', 'median', 'sum', 'count'], Callable]) – Aggregation function to apply to z-values within each bin. Can be a predefined function string (‘mean’, ‘min’, ‘max’, ‘median’, ‘sum’, ‘count’) or a callable. Defaults to ‘mean’.

  • custom_x_bins (Union[ndarray, list, None]) – Custom bin edges for x-dimension. Must be a sorted array or list of values when provided. Defaults to None.

  • custom_y_bins (Union[ndarray, list, None]) – Custom bin edges for y-dimension. Must be a sorted array or list of values when provided. Defaults to None.

Raises:

ValueError – If input series lengths do not match, binning type is invalid, or custom bins are not formatted correctly.

property df_long: DataFrame

A property that retrieves a long-form (non-aggregated) pandas DataFrame.

The property ensures that the DataFrame is not empty and that it contains columns. A copy of the DataFrame is returned to preserve data integrity and prevent external modifications.

property df_agg_wide: DataFrame

Provides a read-only property to access the aggregated wide DataFrame.

property df_agg_long: DataFrame

Property to access the aggregated long DataFrame. Ensures that the DataFrame is available and not empty before returning a copy.

diive.analysis.harmonic_analysis(series, period, n_harmonics=10, window='hamming', verbose=False)[source]

Extract amplitude and phase of harmonic components.

Performs FFT and identifies harmonics at multiples of the fundamental frequency (1/period).

Parameters:
  • series (Series) – Input time series. NaN values are dropped before the FFT, and the remaining records are treated as evenly spaced.

  • period (int) – Fundamental period in observations.

  • n_harmonics (int) – Number of harmonics to extract. Default 10.

  • window (str) – Window function (‘hamming’, ‘hann’, ‘blackman’). Default ‘hamming’.

  • verbose (bool) – Print analysis details. Default False.

Returns:

  • ‘fundamental_frequency’: float, fundamental frequency (1/period)

  • ’harmonics’: list of dicts with ‘harmonic_number’, ‘target_frequency’, ‘actual_frequency’ (nearest FFT bin), ‘amplitude’, ‘phase’, ‘power’. Harmonics at or above the Nyquist frequency are left out.

  • ’frequencies’: np.ndarray, all frequency bins (cycles per record)

  • ’amplitudes’: np.ndarray, amplitude at each frequency

  • ’phases’: np.ndarray, phase at each frequency (radians)

  • ’power’: np.ndarray, power (amplitude squared)

Return type:

Dict

Notes

  • Window function reduces spectral leakage

  • Amplitudes are divided by the window’s coherent gain (its mean), so the taper does not scale them down and a given signal returns the same amplitude under any window

  • Phase is in radians [-π, π]

  • Harmonics are ordered by harmonic number (1st, 2nd, 3rd, etc.)

Example

See examples/analysis/analysis_harmonic.py for diel and annual harmonic decomposition of flux and meteo data, plus the effect of the window.

class diive.analysis.Histogram(series=None, method='n_bins', n_bins=10, ignore_fringe_bins=None, s=None)[source]

Bases: object

Compute a histogram from a Series. See __init__().

Parameters:
__init__(series=None, method='n_bins', n_bins=10, ignore_fringe_bins=None, s=None)[source]

Calculate histogram from Series.

Parameters:
  • series (Series) – A pandas Series. NaN values are ignored.

  • method (Literal['n_bins', 'uniques']) –

    Method used for binning data Options:

    • ’uniques’: One bin per unique value.

    • ’n_bins’: n_bins bins of equal width

  • n_bins (int) – Number of bins, needed if method is ‘n_bins’, otherwise ignored.

  • ignore_fringe_bins (list) – List of integers [i, j] with length 2 If a list is provided, then the first i and last j number of bins are removed from the results and ignored during distribution analysis.

  • s (Series) – Deprecated alias for series.

Properties:

.results: Histogram results as DataFrame with BIN_START_INCL and COUNTS columns .peakbins: Start values of the 5 bins with the most counts

Example

See examples/analysis/analysis_histogram_distribution.py for complete examples.

property results: DataFrame

Return the histogram as DataFrame with columns BIN_START_INCL and COUNTS.

property peakbins

Return the start values of the five bins with the most counts, in decreasing order of counts.

class diive.analysis.FindOptimumRange(df, xcol, ycol, n_bins=100, bins_agg='median', rwinsize=0.1, ragg='mean', define_optimum='max', threshold=0.95, prominence_threshold=1.0)[source]

Bases: object

Find the range of a driver (x) for which a response (y) is optimized. See __init__().

Parameters:
__init__(df, xcol, ycol, n_bins=100, bins_agg='median', rwinsize=0.1, ragg='mean', define_optimum='max', threshold=0.95, prominence_threshold=1.0)[source]

Find x range for optimum y.

Bins x data and aggregates y values per bin, then applies rolling aggregation to identify the range where y is optimized (min or max). The optimum range is defined as the contiguous region of bins where the smoothed curve stays within threshold of the peak, measured relative to the full curve range. Useful for finding optimal conditions for ecosystem responses.

Parameters:
  • df (DataFrame) – Input DataFrame

  • xcol (str) – Column name of driver variable (x)

  • ycol (str) – Column name of response variable (y)

  • n_bins (int) – Number of quantile bins for the x data (bins with equal record counts)

  • bins_agg (Literal['median', 'mean']) – Aggregation method for y values within bins (default: ‘median’)

  • rwinsize (float) – Window size for rolling aggregation (as fraction of total bins)

  • ragg (Literal['mean', 'median']) – Rolling aggregation method (default: ‘mean’)

  • define_optimum (Literal['min', 'max']) – Whether optimum is ‘min’ or ‘max’ of y

  • threshold (float) – Fraction of the curve range defining the optimum region. Bins are included while the smoothed value stays within (1 - threshold) of the curve range from the peak (default: 0.95). Must be in (0, 1).

  • prominence_threshold (float) – Minimum peak prominence (in units of curve std) required to consider the optimum meaningful. The peak prominence is |peak - curve_mean| / curve_std. Results below this value set is_optimum_prominent=False (default: 1.0).

Properties:
.results_optrange: Dictionary with optimum range results and data.

Includes is_optimum_prominent (bool) and optimum_prominence (float) flagging whether the peak stands out from the curve mean by at least prominence_threshold std.

Methods:
  • .find_optimum() – Calculate optimum range

  • .showfig() – Display analysis visualizations

Parameters:

Example

See examples/analysis/analysis_optimumrange.py for complete examples.

property results_optrange: dict

Return optimum range results

find_optimum()[source]

Run the binning, rolling aggregation and optimum-range search; populate results_optrange.

showfig(saveplot=False, title=None, path=None, xlabel=None, ylabel=None, xunit=None, yunit=None)[source]

Display the optimum-range analysis figure.

Parameters:
  • saveplot (bool) – If True, save the figure as PNG to path.

  • title (str) – Optional figure title, also used in the file name of the saved figure.

  • path (Path | str) – Folder for the saved figure when saveplot is True.

  • xlabel (str) – Axis label for the driver (x); defaults to the column name.

  • ylabel (str) – Axis label for the response (y); defaults to the column name.

  • xunit (str) – Optional unit appended to the x label.

  • yunit (str) – Optional unit appended to the y label.

plot_vals_in_optimum_range(ax)[source]

Plot optimum range: values in, above and below optimum per year

plot_bin_aggregates(ax, xlabel=None, ylabel=None, xunit=None, yunit=None)[source]

Plot bin aggregates with smoothed curve overlaid and optimum range shaded.

Parameters:
plot_optimum_range_timeseries(ax)[source]

Plot percentage of data in each category as a time series over years.

plot_rolling_bin_aggregates(ax)[source]

Plot the rolling mean (with std) of the binned y aggregates. Needs ragg='mean'.

diive.analysis.percentiles101(series, showplot=True, verbose=True)[source]

Calculate percentiles 0-100 for series.

Parameters:
  • series (Series) – Input series. NaN values are ignored.

  • showplot (bool) – Shows plot of percentiles 0-100 if True.

  • verbose (bool) – Prints some percentiles if True.

Return type:

DataFrame

Returns:

Dataframe with columns PERCENTILE (0 to 100) and VALUE, one row per percentile.

Example

See examples/analysis/analysis_quantiles.py for complete examples.

diive.analysis.profile_dataframe(df)[source]

Per-variable profiling table — one row per column.

Columns (see PROFILE_COLUMNS): VARIABLE, DTYPE, COUNT (non-missing), MISSING, MISSING_PERC, N_GAPS (consecutive-NaN runs), N_UNIQUE, N_ZEROS, CONSTANT (≤1 unique non-missing value), and the numeric summaries MEAN, SD, MIN, MEDIAN, MAX (NaN for non-numeric columns).

Parameters:

df (DataFrame) – Dataframe to profile (any index; numeric stats apply to numeric cols).

Return type:

DataFrame

Returns:

DataFrame with one row per input column and the columns above. Empty (but correctly-columned) when df has no columns.

diive.analysis.rank_drivers(df, target, features=None, method='pearson', max_lag=0, min_records=30)[source]

Rank candidate variables by how strongly they correlate with a target.

For each candidate column, computes its correlation with target. When max_lag > 0, the candidate is shifted by every lag in [-max_lag, +max_lag] (in records) and the lag with the strongest absolute correlation is reported — so lead/lag relationships (storage, advection, phenology) surface rather than only the contemporaneous one.

Pure ranking utility: no plotting, no side effects. Intended for “what drives this variable?” exploration and for shortlisting gap-filling features.

Parameters:
  • df (DataFrame) – DataFrame holding the target and candidate columns (DatetimeIndex when max_lag > 0, so a shift equals a fixed time step).

  • target (str) – Target column name.

  • features (list) – Candidate columns to rank. Default: every numeric column except the target. Non-existent names and the target are dropped.

  • method (str) – 'pearson' (linear) or 'spearman' (rank/monotonic).

  • max_lag (int) – Maximum absolute lag in records to scan (0 = contemporaneous only). A positive BEST_LAG means the driver leads the target — its value that many records earlier aligns best with the target.

  • min_records (int) – Minimum overlapping non-NaN pairs required at a lag; candidates that never reach it are dropped.

Return type:

DataFrame

Returns:

DataFrame (index 0..n-1) with columns DRIVER, CORR (signed correlation at the best lag), ABS_CORR, BEST_LAG (records), N (overlapping pairs), sorted by ABS_CORR descending. Empty when the target is constant/all-NaN or no candidate qualifies.

Example

>>> import diive as dv, pandas as pd, numpy as np
>>> idx = pd.date_range('2024-06-01', periods=200, freq='30min')
>>> df = pd.DataFrame({'NEE': np.sin(np.arange(200.)), 'TA': np.arange(200.)}, index=idx)
>>> ranked = dv.analysis.rank_drivers(df, target='NEE', method='pearson', max_lag=4)
class diive.analysis.SeasonalTrendDecomposition(series, timestamp=None, method='stl', seasonal_period=None, trend_window=None, robust=True, seasonal_deg=1, trend_deg=1, seasonal_jump=1, trend_jump=1, n_harmonics=10, harmonic_window='hamming', verbose=False)[source]

Bases: object

Decompose time series into seasonal, trend, and residual components.

Supports multiple decomposition methods optimized for different use cases: - STL (default): Robust, handles gaps and non-stationary data - Classical: Simple moving-average based, assumes stationarity - Harmonic: Fourier-based, reveals frequency-domain structure

Lazy evaluation: Components are computed once on first access and cached.

Example

See examples/analysis/analysis_seasonaltrend.py for complete examples.

Parameters:
__init__(series, timestamp=None, method='stl', seasonal_period=None, trend_window=None, robust=True, seasonal_deg=1, trend_deg=1, seasonal_jump=1, trend_jump=1, n_harmonics=10, harmonic_window='hamming', verbose=False)[source]

Initialize SeasonalTrendDecomposition.

Parameters:
  • series (Series) – Time series to decompose (may contain NaN).

  • timestamp (Optional[DatetimeIndex]) – DateTime index. Inferred from series.index if None. Stored as .timestamp, not used by the decomposition.

  • method (str) – Decomposition method: ‘stl’ (default) — Seasonal-Trend Loess (robust, gap-tolerant) ‘classical’ — Moving-average (simple, stationary-only) ‘harmonic’ — Fourier-based (frequency analysis). The trend component is zero for this method.

  • seasonal_period (Optional[int]) – Seasonal period in observations. Auto-detected if None via periodogram. Example: 365 for daily data (annual cycle)

  • trend_window (Optional[int]) – Trend smoothing window length (STL only). Default: 2 * seasonal_period + 1

  • robust (bool) – Use robust fitting (less sensitive to outliers). Default True. Only applies to STL method.

  • seasonal_deg (int) – Loess polynomial degree for seasonal (0 or 1). Default 1.

  • trend_deg (int) – Loess polynomial degree for trend (0 or 1). Default 1.

  • seasonal_jump (int) – STL seasonal jump size (speed optimization). Default 1.

  • trend_jump (int) – STL trend jump size (speed optimization). Default 1.

  • n_harmonics (int) – Number of harmonics for harmonic method. Default 10.

  • harmonic_window (str) – Window function for harmonic (‘hamming’, ‘hann’, ‘blackman’). Default ‘hamming’.

  • verbose (bool) – Print decomposition details. Default False.

Raises:
  • ValueError – If series is empty or method is invalid.

  • TypeError – If series not pd.Series.

property seasonal: Series

Seasonal component (recurring patterns).

Returns:

pd.Series with seasonal component. Same index as input series.

NaN where input was NaN.

property trend: Series

Trend component (long-term direction).

Returns:

pd.Series with trend component. Same index as input series.

NaN where input was NaN (or by design for classical method).

property residual: Series

Residual component (noise and anomalies).

Returns:

pd.Series with residual component. Same index as input series.

NaN where input was NaN.

property seasonality_strength: float

Strength of seasonality (0–1).

Seasonal variance divided by the sum of seasonal and residual variance. The trend is not involved: this is the detrended-variance form of the Wang/Hyndman seasonal strength 1 - var(residual) / var(seasonal + residual), which it equals when the two components are uncorrelated. Higher = stronger recurring patterns.

Returns:

Seasonality strength, 0.0–1.0

Return type:

float

detrend()[source]

Remove trend component from series.

Returns:

seasonal + residual (trend removed)

Return type:

Series

deseasonalize()[source]

Remove seasonal component from series.

Returns:

trend + residual (seasonality removed)

Return type:

Series

reconstruct(keep_components=None, model='additive')[source]

Reconstruct series from selected components.

Parameters:
  • keep_components (Optional[List[str]]) – Components to include. Options: ‘trend’, ‘seasonal’, ‘residual’ Default None = all components

  • model (str) – Combination model: ‘additive’ (default) → sum components ‘multiplicative’ → multiply components

Returns:

Reconstructed series

Return type:

Series

summary()[source]

Text summary of decomposition results.

Returns:

Formatted summary with method, period, strength, and component statistics

Return type:

str

detection_results()[source]

Get seasonality detection results (if period was auto-detected).

Returns:

  • ‘primary_period’: int, dominant seasonal period

  • ’secondary_periods’: list of int, other strong periods

  • ’strength’: float (0–1), seasonality strength

  • ’all_periods’: list of (period, power) tuples, ranked

Return type:

Dict

diive.analysis.spectrogram(series, nperseg=256, noverlap=None, window='hann', scaling='spectrum', detrend='constant', verbose=False)[source]

Spectrogram (short-time Fourier transform): how the frequency content of a series evolves over time.

Splits the series into overlapping windows and computes a spectrum for each, revealing when each cyclic component is strong. For eddy-covariance data this shows, e.g., the 1-cycle-per-day photosynthesis rhythm strengthening in the growing season and fading in winter — information a single static spectrum (harmonic_analysis()) cannot show.

Parameters:
  • series (Series) – Input time series. NaN values are dropped first, and the remaining records are treated as evenly spaced.

  • nperseg (int) – Samples per segment (window length). Larger = finer frequency resolution but coarser time resolution. Clamped to the series length. Default 256.

  • noverlap (int) – Samples of overlap between segments. Default nperseg // 2.

  • window (str) – Window function (‘hann’, ‘hamming’, ‘blackman’, …). Default ‘hann’.

  • scaling (str) – ‘spectrum’ (power spectrum) or ‘density’ (power spectral density). Default ‘spectrum’.

  • detrend (str) – Per-segment detrending (‘constant’, ‘linear’, or False). Default ‘constant’.

  • verbose (bool) – Print details. Default False.

Returns:

  • ‘frequencies’: np.ndarray, frequency bins (cycles per record)

  • ’times’: np.ndarray, segment-centre positions (records from start)

  • ’power’: np.ndarray, 2D [n_frequencies, n_times] power

  • ’power_db’: np.ndarray, 10*log10(power) for plotting (decibels)

Return type:

Dict

Notes

  • Frequencies are in cycles per record; multiply by the sampling rate to interpret (e.g. x48 for cycles/day on half-hourly data).

  • nperseg trades frequency resolution against time resolution.