2D Grid Aggregation

Aggregate time series data over a 2D grid using different binning strategies.

Grid aggregation is useful for: - Understanding relationships between two variables by binning a third - Detecting patterns in 2D parameter space (e.g., radiation vs. temperature effects) - Creating heatmap visualizations of aggregated data - Comparing different binning methods (quantiles, equal-width, custom)

Best for: Exploring multivariate relationships and creating summary statistics over 2D bins of measurement space.

Overview: Why Grid Aggregation?

Grid aggregation creates bins across two dimensions (X and Y) and aggregates a third variable (Z) within each bin. This reveals patterns that might be hidden in raw time series data.

Use cases: 1. Understand how vapor pressure deficit (VPD) varies with radiation and temperature 2. Analyze ecosystem responses across multiple environmental gradients 3. Create reference surfaces (e.g., mean stomatal conductance vs. light and VPD) 4. Compare data distribution across environmental conditions

Load Data and Prepare Variables

import diive as dv

# Load example data
df = dv.load_exampledata_parquet()

# Extract subset: May-September daytime data only
vpd_col = 'VPD_f'      # Vapor pressure deficit (Z-axis)
ta_col = 'Tair_f'      # Air temperature (Y-axis)
swin_col = 'Rg_f'      # Shortwave radiation (X-axis)

subset = df[[vpd_col, ta_col, swin_col]].copy()
subset = subset.loc[(subset.index.month >= 5) & (subset.index.month <= 9)].copy()  # May-Sept
subset = subset[subset[swin_col] > 0].copy()  # Daytime only (radiation > 0)
subset = subset.dropna()

print(f"Data Summary:")
print(f"  Period: {subset.index.min().date()} to {subset.index.max().date()}")
print(f"  Records: {len(subset)}")
print(f"  Radiation: {subset[swin_col].min():.1f} to {subset[swin_col].max():.1f} W/m2")
print(f"  Temperature: {subset[ta_col].min():.1f} to {subset[ta_col].max():.1f} C")
print(f"  VPD: {subset[vpd_col].min():.2f} to {subset[vpd_col].max():.2f} hPa")
  > 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).
Data Summary:
  Period: 2013-05-01 to 2022-09-30
  Records: 45447
  Radiation: 0.0 to 1197.8 W/m2
  Temperature: -6.5 to 28.7 C
  VPD: 0.00 to 32.12 hPa

Example 1: Quantile Binning

Divide X and Y into equal-frequency bins (quantile-based). Each bin contains approximately the same number of records.

print(f"\n{'='*60}")
print(f"EXAMPLE 1: Quantile Binning (10 bins each axis)")
print(f"{'='*60}")
print(f"This divides data into bins with equal record counts.")
print(f"Useful for: Understanding patterns across equal-populated regions.\n")

qa = dv.analysis.GridAggregator(
    x=subset[swin_col],
    y=subset[ta_col],
    z=subset[vpd_col],
    binning_type='quantiles',
    n_bins=10,
    min_n_vals_per_bin=5,
    aggfunc='mean'
)

print(f"Aggregated data (wide format):")
print(qa.df_agg_wide)

print(f"\nData shape: {qa.df_agg_wide.shape}")
print(f"Non-missing cells: {qa.df_agg_wide.notna().sum().sum()} / {qa.df_agg_wide.size}")
============================================================
EXAMPLE 1: Quantile Binning (10 bins each axis)
============================================================
This divides data into bins with equal record counts.
Useful for: Understanding patterns across equal-populated regions.

Aggregated data (wide format):
BIN_Rg_f         0.0        10.0       20.0  ...       70.0       80.0       90.0
BIN_Tair_f                                   ...
0.0          0.738029   0.882306   0.907608  ...   1.906702   2.124990   2.569857
10.0         1.109053   1.247962   1.250752  ...   2.827544   3.221641   3.404728
20.0         1.359257   1.609306   1.517805  ...   3.519970   3.936581   4.287607
30.0         1.803614   1.966310   1.899482  ...   4.207591   4.818127   5.080783
40.0         2.191474   2.617581   2.407728  ...   4.944201   5.332908   6.178695
50.0         3.147071   3.443443   3.602171  ...   6.001373   6.345775   7.025564
60.0         4.698872   5.107422   5.021604  ...   7.160304   7.789453   8.057696
70.0         6.514295   6.915953   7.306498  ...   8.860974   9.411137   9.825721
80.0         9.090340   9.430653   9.720280  ...  11.251576  12.075453  12.163915
90.0        13.102229  13.863063  14.488767  ...  16.459568  16.957323  17.613251

[10 rows x 10 columns]

Data shape: (10, 10)
Non-missing cells: 100 / 100

Example 2: Equal-Width Binning

Divide X and Y into equal-width bins (uniform spacing). Each bin spans the same range of values.

print(f"\n{'='*60}")
print(f"EXAMPLE 2: Equal-Width Binning (10 bins each axis)")
print(f"{'='*60}")
print(f"This divides data into bins with equal value ranges.")
print(f"Useful for: Physical interpretation with consistent bin sizes.\n")

qe = dv.analysis.GridAggregator(
    x=subset[swin_col],
    y=subset[ta_col],
    z=subset[vpd_col],
    binning_type='equal_width',
    n_bins=10,
    min_n_vals_per_bin=5,
    aggfunc='mean'
)

print(f"Aggregated data (wide format):")
print(qe.df_agg_wide)

print(f"\nData shape: {qe.df_agg_wide.shape}")
print(f"Non-missing cells: {qe.df_agg_wide.notna().sum().sum()} / {qe.df_agg_wide.size}")
============================================================
EXAMPLE 2: Equal-Width Binning (10 bins each axis)
============================================================
This divides data into bins with equal value ranges.
Useful for: Physical interpretation with consistent bin sizes.

Aggregated data (wide format):
BIN_Rg_f     0.001      119.781    239.561   ...   838.460    958.240    1078.020
BIN_Tair_f                                   ...
-6.487       0.885972   0.959000   1.066091  ...        NaN        NaN        NaN
-2.967       0.580404   0.628393   0.840132  ...        NaN        NaN        NaN
 0.553       0.854034   0.863293   1.170580  ...   2.506971   2.589103        NaN
 4.073       1.206237   1.314746   1.767464  ...   3.668349   3.117379   2.823077
 7.593       1.870587   2.090561   2.920073  ...   5.377300   5.287563   3.440083
 11.113      3.569341   3.986919   4.730117  ...   6.971063   7.864038   6.080944
 14.633      7.080506   7.569661   8.232150  ...  10.106191  10.408848  11.175375
 18.153     11.504943  11.778267  12.495388  ...  13.895101  14.398662  14.086500
 21.673     16.235518  17.125154  18.071866  ...  19.002774  19.621618        NaN
 25.193           NaN  22.926800  25.323125  ...  25.918773  25.083786        NaN

[10 rows x 10 columns]

Data shape: (10, 10)
Non-missing cells: 85 / 100

Example 3: Custom Binning

Define custom bin edges based on domain knowledge or data characteristics.

print(f"\n{'='*60}")
print(f"EXAMPLE 3: Custom Binning")
print(f"{'='*60}")
print(f"This uses user-specified bin edges for fine control.")
print(f"Useful for: Aligning bins with ecologically meaningful thresholds.\n")

# Create custom bins based on data ranges
custom_x_bins = list(range(0, 1300, 100))  # 0 to 1200 W/m2 in 100 W/m2 steps
custom_y_bins = list(range(-7, 30, 1))     # -7 to 29 C in 1 C steps

qc = dv.analysis.GridAggregator(
    x=subset[swin_col],
    y=subset[ta_col],
    z=subset[vpd_col],
    binning_type='custom',
    custom_x_bins=custom_x_bins,
    custom_y_bins=custom_y_bins,
    min_n_vals_per_bin=5,
    aggfunc='mean'
)

print(f"Aggregated data (wide format):")
print(qc.df_agg_wide)

print(f"\nData shape: {qc.df_agg_wide.shape}")
print(f"Non-missing cells: {qc.df_agg_wide.notna().sum().sum()} / {qc.df_agg_wide.size}")
============================================================
EXAMPLE 3: Custom Binning
============================================================
This uses user-specified bin edges for fine control.
Useful for: Aligning bins with ecologically meaningful thresholds.

Aggregated data (wide format):
BIN_Rg_f       0.0        100.0      200.0   ...     900.0      1000.0  1100.0
BIN_Tair_f                                   ...
-7.0              NaN        NaN        NaN  ...        NaN        NaN     NaN
-6.0         1.044286        NaN        NaN  ...        NaN        NaN     NaN
-5.0         1.432600        NaN        NaN  ...        NaN        NaN     NaN
-4.0         0.672158   0.775143   1.241000  ...        NaN        NaN     NaN
-3.0         0.683549   0.482833   0.829625  ...        NaN        NaN     NaN
-2.0         0.615644   0.653917   0.614000  ...        NaN        NaN     NaN
-1.0         0.645220   0.487575   0.809250  ...        NaN        NaN     NaN
 0.0         0.567952   0.572082   0.778158  ...        NaN        NaN     NaN
 1.0         0.776714   0.789706   0.844698  ...        NaN        NaN     NaN
 2.0         0.848726   0.894984   0.976529  ...   2.490400   2.832667     NaN
 3.0         0.947599   0.913623   1.012191  ...   2.491429   2.950111     NaN
 4.0         1.042389   1.100966   1.141092  ...   3.138875   2.710125  2.5444
 5.0         1.105174   1.149132   1.305670  ...   3.311450        NaN     NaN
 6.0         1.338332   1.324763   1.695147  ...   3.836800        NaN     NaN
 7.0         1.392146   1.527657   1.976034  ...   4.290450   4.043800     NaN
 8.0         1.610481   1.553884   1.948760  ...   4.639483   3.825800     NaN
 9.0         1.865438   2.027337   2.620090  ...   4.975533   4.346800     NaN
 10.0        2.222196   2.386764   2.859538  ...   6.249157   5.658050     NaN
 11.0        2.618762   2.996427   3.531139  ...   6.604337   6.754238     NaN
 12.0        3.300454   3.466720   4.117252  ...   7.382966   7.041051     NaN
 13.0        4.387348   4.549711   4.837850  ...   7.618117   7.983079     NaN
 14.0        5.182279   5.584073   5.724940  ...   8.309779   7.775923     NaN
 15.0        6.393801   6.595335   6.756005  ...   9.238272   9.954333     NaN
 16.0        7.344802   7.924250   8.245268  ...  10.305640  10.133240     NaN
 17.0        8.585728   9.157985   9.606868  ...  11.313235  10.828538     NaN
 18.0        9.847364   9.904171  10.678149  ...  12.326974  12.063511     NaN
 19.0       10.930955  11.522896  12.033541  ...  13.852043  13.451853     NaN
 20.0       12.584513  13.082683  13.415195  ...  15.068458  15.604958     NaN
 21.0       14.150488  14.646457  15.143567  ...  16.639743  16.755364     NaN
 22.0       15.537478  15.921030  16.844683  ...  17.877455  18.285000     NaN
 23.0       17.897160  18.026789  18.377846  ...  19.674237  20.059444     NaN
 24.0       19.261000  20.327800  20.144421  ...  22.124855        NaN     NaN
 25.0             NaN        NaN  23.157167  ...  24.434457        NaN     NaN
 26.0             NaN        NaN        NaN  ...  26.475944        NaN     NaN
 27.0             NaN        NaN        NaN  ...  28.666429        NaN     NaN
 28.0             NaN        NaN        NaN  ...        NaN        NaN     NaN

[36 rows x 12 columns]

Data shape: (36, 12)
Non-missing cells: 304 / 432

Accessing Results

The GridAggregator provides multiple output formats.

print(f"\n{'='*60}")
print(f"Output Formats")
print(f"{'='*60}")

# Wide format: rows=Y bins, columns=X bins, values=aggregated Z
print(f"\nWide format (rows=temperature, cols=radiation):")
print(f"  Shape: {qa.df_agg_wide.shape}")
print(f"  Use for: Matrix operations, heatmap visualization")

# Long format: each row is one bin combination
print(f"\nLong format (one row per bin combination):")
df_long = qa.df_agg_long
print(df_long.head(10))
print(f"  Shape: {df_long.shape}")
print(f"  Use for: Direct data export, statistical analysis")

# Non-aggregated long format: includes original data with bin assignments
print(f"\nNon-aggregated long format (all original records with bin assignments):")
df_data = qa.df_long
print(df_data.head(5))
print(f"  Shape: {df_data.shape}")
print(f"  Columns: {df_data.columns.tolist()}")
print(f"  Use for: Understanding bin composition, detailed analysis")
============================================================
Output Formats
============================================================

Wide format (rows=temperature, cols=radiation):
  Shape: (10, 10)
  Use for: Matrix operations, heatmap visualization

Long format (one row per bin combination):
   BIN_Tair_f  BIN_Rg_f      VPD_f
0         0.0       0.0   0.738029
1        10.0       0.0   1.109053
2        20.0       0.0   1.359257
3        30.0       0.0   1.803614
4        40.0       0.0   2.191474
5        50.0       0.0   3.147071
6        60.0       0.0   4.698872
7        70.0       0.0   6.514295
8        80.0       0.0   9.090340
9        90.0       0.0  13.102229
  Shape: (100, 3)
  Use for: Direct data export, statistical analysis

Non-aggregated long format (all original records with bin assignments):
                INDEX     Rg_f  Tair_f  ...  BIN_Rg_f  BIN_Tair_f  BIN_COMBINED_STR
0 2013-05-01 05:15:00    2.912   7.667  ...       0.0        20.0          0.0+20.0
1 2013-05-01 05:45:00   21.093   5.967  ...      10.0        10.0         10.0+10.0
2 2013-05-01 06:15:00   50.277   6.167  ...      20.0        10.0         20.0+10.0
3 2013-05-01 06:45:00   96.650   6.700  ...      30.0        10.0         30.0+10.0
4 2013-05-01 07:15:00  162.190   6.900  ...      40.0        10.0         40.0+10.0

[5 rows x 7 columns]
  Shape: (45447, 7)
  Columns: ['INDEX', 'Rg_f', 'Tair_f', 'VPD_f', 'BIN_Rg_f', 'BIN_Tair_f', 'BIN_COMBINED_STR']
  Use for: Understanding bin composition, detailed analysis

Comparing Binning Methods

Different binning strategies reveal different patterns.

print(f"\n{'='*60}")
print(f"Summary: Binning Method Comparison")
print(f"{'='*60}")

print(f"\n1. Quantile binning:")
print(f"   Grid shape: {qa.df_agg_wide.shape}")
print(f"   Bin interpretation: Equal number of records per bin")
print(f"   Best for: Detecting patterns in data-rich regions")

print(f"\n2. Equal-width binning:")
print(f"   Grid shape: {qe.df_agg_wide.shape}")
print(f"   Bin interpretation: Uniform value spacing")
print(f"   Best for: Physical interpretation and reproducibility")

print(f"\n3. Custom binning:")
print(f"   Grid shape: {qc.df_agg_wide.shape}")
print(f"   Bin interpretation: User-specified thresholds")
print(f"   Best for: Aligning with domain-specific boundaries")

print(f"\nKey Insights:")
print(f"• Quantile binning distributes records evenly across bins")
print(f"• Equal-width binning may have uneven record distribution")
print(f"• Custom binning allows domain-specific flexibility")
print(f"• Output includes both aggregated and original data")
============================================================
Summary: Binning Method Comparison
============================================================

1. Quantile binning:
   Grid shape: (10, 10)
   Bin interpretation: Equal number of records per bin
   Best for: Detecting patterns in data-rich regions

2. Equal-width binning:
   Grid shape: (10, 10)
   Bin interpretation: Uniform value spacing
   Best for: Physical interpretation and reproducibility

3. Custom binning:
   Grid shape: (36, 12)
   Bin interpretation: User-specified thresholds
   Best for: Aligning with domain-specific boundaries

Key Insights:
• Quantile binning distributes records evenly across bins
• Equal-width binning may have uneven record distribution
• Custom binning allows domain-specific flexibility
• Output includes both aggregated and original data

Total running time of the script: (0 minutes 0.313 seconds)

Gallery generated by Sphinx-Gallery