Daily Correlation Analysis

Calculate daily correlation coefficients between pairs of time series. This demonstrates how to identify relationships and detect anomalies on a per-day basis.

Daily correlation is useful for: - Quality assurance (checking sensor performance or timestamp shifts) - Identifying days with unusual relationships - Comparing observed vs. modeled variables - Understanding temporal variability in ecosystem processes

Best for: Understanding daily-scale relationships between variables, detecting measurement quality issues, and identifying anomalous days.

Overview: Why Daily Correlation?

Calculating correlation on a per-day basis reveals temporal patterns that would be hidden by single overall correlation values.

Use cases:

  1. Quality check: Observed radiation should be highly correlated with potential radiation (physics-based). Low daily correlations suggest sensor issues or timestamp problems.

  2. Physical relationships: Temperature often correlates with radiation on daily timescales.

  3. Ecosystem responses: Biological variables (e.g., photosynthesis) show variable relationships with drivers across different days.

Load Data and Prepare Variables

import diive as dv
from diive.variables.radiation import potrad

# Load example data (use full year 2022)
df = dv.load_exampledata_parquet()
df = df.loc[df.index.year == 2022].copy()

# Extract key variables
rg_series = df['Rg_f'].copy()         # Observed global radiation
ta_series = df['Tair_f'].copy()       # Air temperature
nee_series = df['NEE_CUT_REF_f'].copy()  # Net ecosystem exchange (CO2 flux)

print(f"Data Summary:")
print(f"  Period: {df.index.min().date()} to {df.index.max().date()}")
print(f"  Records: {len(df)}")
print(f"\nVariables:")
print(f"  Rg_f (observed radiation): {rg_series.min():.1f} to {rg_series.max():.1f} W/m2")
print(f"  Tair_f (air temperature): {ta_series.min():.1f} to {ta_series.max():.1f} C")
print(f"  NEE_CUT_REF_f (CO2 flux): {nee_series.min():.2f} to {nee_series.max():.2f} umol m-2 s-1")

# Calculate potential solar radiation (clear-sky reference).
# StepwiseMeteoScreeningDb.analysis_potential_radiation_correlation runs the same
# quality check against the same reference.
sw_pot = potrad(
    timestamp_index=rg_series.index,
    lat=46.81533,   # Site latitude
    lon=9.85591,    # Site longitude
    utc_offset=1     # UTC+1
)

print(f"\nCalculated potential radiation (SW_IN_POT): {sw_pot.min():.1f} to {sw_pot.max():.1f} W/m²")
  > 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).
Data Summary:
  Period: 2022-01-01 to 2022-12-31
  Records: 17520

Variables:
  Rg_f (observed radiation): 0.0 to 1084.1 W/m2
  Tair_f (air temperature): -15.1 to 26.6 C
  NEE_CUT_REF_f (CO2 flux): -27.09 to 19.91 umol m-2 s-1

Calculated potential radiation (SW_IN_POT): 0.0 to 1221.2 W/m²

Example 1: Quality Check - Observed vs Potential Radiation

Observed radiation should be highly correlated with potential radiation (clear-sky model). Low daily correlations indicate sensor issues, clouds, or timestamp problems.

print(f"\n{'='*60}")
print(f"EXAMPLE 1: Observed Radiation vs Potential Radiation")
print(f"{'='*60}")
print(f"\nExpectation: High correlations (>0.8) indicate good measurement quality")
print(f"and clear-sky conditions. Low correlations suggest clouds or issues.")

corr1 = dv.analysis.DailyCorrelation(
    s1=rg_series,
    s2=sw_pot,
    mincorr=0.8
)

print(f"\nDaily correlations (first 10 days):")
print(corr1.correlations.head(10))

print(f"\nSummary statistics:")
print(f"  Count: {len(corr1.correlations)}")
print(f"  Mean: {corr1.correlations.mean():.4f}")
print(f"  Median: {corr1.correlations.median():.4f}")
print(f"  Min: {corr1.correlations.min():.4f}")
print(f"  Max: {corr1.correlations.max():.4f}")
print(f"  Std: {corr1.correlations.std():.4f}")

print(f"\nDays with HIGHEST correlations (best match):")
highest = corr1.correlations.nlargest(5)
for date, corr_val in highest.items():
    print(f"  {date.date()}: {corr_val:.4f}")

print(f"\nDays with LOWEST correlations (worst match - likely cloudy):")
lowest = corr1.correlations.nsmallest(5)
for date, corr_val in lowest.items():
    print(f"  {date.date()}: {corr_val:.4f}")
============================================================
EXAMPLE 1: Observed Radiation vs Potential Radiation
============================================================

Expectation: High correlations (>0.8) indicate good measurement quality
and clear-sky conditions. Low correlations suggest clouds or issues.

Daily correlations (first 10 days):
DATE
2022-01-01    0.961175
2022-01-02    0.955483
2022-01-03    0.954425
2022-01-04    0.957044
2022-01-05    0.985966
2022-01-06    0.928265
2022-01-07    0.986360
2022-01-08    0.941120
2022-01-09    0.946650
2022-01-10    0.975060
Freq: D, Name: daycorrs, dtype: float64

Summary statistics:
  Count: 365
  Mean: 0.9245
  Median: 0.9528
  Min: 0.4871
  Max: 0.9932
  Std: 0.0705

Days with HIGHEST correlations (best match):
  2022-01-21: 0.9932
  2022-11-28: 0.9923
  2022-02-16: 0.9912
  2022-12-13: 0.9901
  2022-10-16: 0.9897

Days with LOWEST correlations (worst match - likely cloudy):
  2022-06-28: 0.4871
  2022-11-04: 0.5649
  2022-06-03: 0.5763
  2022-04-30: 0.6563
  2022-07-04: 0.6899

Example 2: Physical Relationship - Temperature vs Radiation

Air temperature typically correlates positively with solar radiation on clear days, but relationships vary with season, cloud cover, and advection of air masses.

print(f"\n{'='*60}")
print(f"EXAMPLE 2: Air Temperature vs Observed Radiation")
print(f"{'='*60}")
print(f"\nExpectation: Positive correlations on clear days, variable on cloudy days.")
print(f"Low/negative correlations indicate advection or unusual conditions.")

corr2 = dv.analysis.DailyCorrelation(
    s1=ta_series,
    s2=rg_series,
    mincorr=0.5
)

print(f"\nDaily correlations (first 10 days):")
print(corr2.correlations.head(10))

print(f"\nSummary statistics:")
print(f"  Count: {len(corr2.correlations)}")
print(f"  Mean: {corr2.correlations.mean():.4f}")
print(f"  Median: {corr2.correlations.median():.4f}")
print(f"  Min: {corr2.correlations.min():.4f}")
print(f"  Max: {corr2.correlations.max():.4f}")
print(f"  Std: {corr2.correlations.std():.4f}")

print(f"\nDays with strong positive correlation (T increases with radiation):")
positive = corr2.correlations.nlargest(5)
for date, corr_val in positive.items():
    print(f"  {date.date()}: {corr_val:.4f}")

print(f"\nDays with weak/negative correlation (unusual patterns):")
negative = corr2.correlations.nsmallest(5)
for date, corr_val in negative.items():
    print(f"  {date.date()}: {corr_val:.4f}")
============================================================
EXAMPLE 2: Air Temperature vs Observed Radiation
============================================================

Expectation: Positive correlations on clear days, variable on cloudy days.
Low/negative correlations indicate advection or unusual conditions.

Daily correlations (first 10 days):
DATE
2022-01-01    0.854452
2022-01-02    0.828606
2022-01-03    0.754225
2022-01-04    0.729151
2022-01-05    0.020350
2022-01-06    0.695185
2022-01-07    0.560809
2022-01-08    0.660095
2022-01-09    0.338367
2022-01-10    0.659329
Freq: D, Name: daycorrs, dtype: float64

Summary statistics:
  Count: 365
  Mean: 0.6638
  Median: 0.7207
  Min: -0.4272
  Max: 0.9146
  Std: 0.2060

Days with strong positive correlation (T increases with radiation):
  2022-03-19: 0.9146
  2022-06-27: 0.9060
  2022-10-07: 0.9046
  2022-01-25: 0.8987
  2022-11-13: 0.8934

Days with weak/negative correlation (unusual patterns):
  2022-02-02: -0.4272
  2022-07-01: -0.3914
  2022-02-21: -0.2831
  2022-02-07: -0.2090
  2022-04-09: -0.1129

Example 3: Ecosystem Driver-Response - Temperature vs NEE

Net ecosystem exchange (NEE) of CO2 represents photosynthesis and respiration. The relationship with temperature varies with season: weak in summer (light-limited), stronger in spring/fall (temperature-controlled respiration).

print(f"\n{'='*60}")
print(f"EXAMPLE 3: Air Temperature vs NEE (CO2 Flux)")
print(f"{'='*60}")
print(f"\nExpectation: Variable correlations across seasons. Winter/spring")
print(f"often show positive correlations (warmer = more respiration).")
print(f"Summer shows weak/negative correlations (light-limited photosynthesis).")

corr3 = dv.analysis.DailyCorrelation(
    s1=ta_series,
    s2=nee_series
)

print(f"\nDaily correlations (first 10 days):")
print(corr3.correlations.head(10))

print(f"\nSummary statistics:")
print(f"  Count: {len(corr3.correlations)}")
print(f"  Mean: {corr3.correlations.mean():.4f}")
print(f"  Median: {corr3.correlations.median():.4f}")
print(f"  Min: {corr3.correlations.min():.4f}")
print(f"  Max: {corr3.correlations.max():.4f}")
print(f"  Std: {corr3.correlations.std():.4f}")

print(f"\nDays with strong positive correlation (warmth increases CO2 release):")
positive_nee = corr3.correlations.nlargest(5)
for date, corr_val in positive_nee.items():
    print(f"  {date.date()}: {corr_val:.4f}")

print(f"\nDays with negative correlation (warmth increases CO2 uptake):")
negative_nee = corr3.correlations.nsmallest(5)
for date, corr_val in negative_nee.items():
    print(f"  {date.date()}: {corr_val:.4f}")
============================================================
EXAMPLE 3: Air Temperature vs NEE (CO2 Flux)
============================================================

Expectation: Variable correlations across seasons. Winter/spring
often show positive correlations (warmer = more respiration).
Summer shows weak/negative correlations (light-limited photosynthesis).

Daily correlations (first 10 days):
DATE
2022-01-01    0.588741
2022-01-02    0.206918
2022-01-03   -0.066644
2022-01-04    0.095609
2022-01-05   -0.237885
2022-01-06   -0.055403
2022-01-07   -0.452075
2022-01-08   -0.214663
2022-01-09   -0.327657
2022-01-10   -0.423444
Freq: D, Name: daycorrs, dtype: float64

Summary statistics:
  Count: 365
  Mean: -0.4582
  Median: -0.5776
  Min: -0.9450
  Max: 0.7110
  Std: 0.3337

Days with strong positive correlation (warmth increases CO2 release):
  2022-01-23: 0.7110
  2022-01-01: 0.5887
  2022-01-16: 0.5770
  2022-02-10: 0.5593
  2022-12-18: 0.4606

Days with negative correlation (warmth increases CO2 uptake):
  2022-08-18: -0.9450
  2022-07-29: -0.8834
  2022-04-06: -0.8646
  2022-04-07: -0.8588
  2022-04-16: -0.8580

Comparing All Three Relationships

Summary of what daily correlation reveals across different types of variable relationships.

print(f"\n{'='*60}")
print(f"SUMMARY: Correlation Patterns Across Relationships")
print(f"{'='*60}")

print(f"\n1. Observed vs Potential Radiation (physical law):")
print(f"   Mean correlation: {corr1.correlations.mean():.4f}")
print(f"   Range: {corr1.correlations.min():.4f} to {corr1.correlations.max():.4f}")
print(f"   (High & consistent - expected)")

print(f"\n2. Temperature vs Radiation (physical relationship):")
print(f"   Mean correlation: {corr2.correlations.mean():.4f}")
print(f"   Range: {corr2.correlations.min():.4f} to {corr2.correlations.max():.4f}")
print(f"   (Variable - influenced by season, cloud cover, advection)")

print(f"\n3. Temperature vs NEE (biological process):")
print(f"   Mean correlation: {corr3.correlations.mean():.4f}")
print(f"   Range: {corr3.correlations.min():.4f} to {corr3.correlations.max():.4f}")
print(f"   (Highly variable - controlled by multiple factors)")

print(f"\n{'='*60}")
print(f"Key Insights:")
print(f"{'='*60}")
print(f"• Physical relationships (1) are stable and high")
print(f"• Environmental relationships (2) vary with conditions")
print(f"• Biological relationships (3) are complex and variable")
print(f"• Daily correlation reveals patterns masked by overall statistics")
print(f"• Anomalous days can indicate measurement issues or unusual conditions")
============================================================
SUMMARY: Correlation Patterns Across Relationships
============================================================

1. Observed vs Potential Radiation (physical law):
   Mean correlation: 0.9245
   Range: 0.4871 to 0.9932
   (High & consistent - expected)

2. Temperature vs Radiation (physical relationship):
   Mean correlation: 0.6638
   Range: -0.4272 to 0.9146
   (Variable - influenced by season, cloud cover, advection)

3. Temperature vs NEE (biological process):
   Mean correlation: -0.4582
   Range: -0.9450 to 0.7110
   (Highly variable - controlled by multiple factors)

============================================================
Key Insights:
============================================================
• Physical relationships (1) are stable and high
• Environmental relationships (2) vary with conditions
• Biological relationships (3) are complex and variable
• Daily correlation reveals patterns masked by overall statistics
• Anomalous days can indicate measurement issues or unusual conditions

Advanced Class Methods

The DailyCorrelation class provides additional analysis methods beyond simple statistics. Demonstrate comprehensive summary and sorting.

print(f"\n{'='*60}")
print(f"ADVANCED: Using Class Methods for Deep Analysis")
print(f"{'='*60}")

# Use Example 1 (Observed vs Potential Radiation) for demonstration
print(f"\nExample 1: Comprehensive Summary Statistics")
print(f"-" * 60)
summary_stats = corr1.summary()
print(f"  Count:          {summary_stats['count']}")
print(f"  Mean:           {summary_stats['mean']:.4f}")
print(f"  Median:         {summary_stats['median']:.4f}")
print(f"  Std Dev:        {summary_stats['std']:.4f}")
print(f"  Range:          {summary_stats['min']:.4f} to {summary_stats['max']:.4f}")
print(f"  1st percentile: {summary_stats['p1']:.4f}")
print(f"  99th percentile:{summary_stats['p99']:.4f}")
print(f"  Skewness:       {summary_stats['skewness']:.4f}")
print(f"  Kurtosis:       {summary_stats['kurtosis']:.4f}")
print(f"  Normality test: p-value = {summary_stats['normality_pvalue']:.6f}")

# Sort by correlation strength
print(f"\nDays Sorted by Correlation Strength (Top 5):")
best_days = corr1.get_days_by_correlation(high=True)
print(best_days.head(5).to_string())

print(f"\nDays Sorted by Correlation Strength (Bottom 5):")
worst_days = corr1.get_days_by_correlation(high=False)
print(worst_days.head(5).to_string())
============================================================
ADVANCED: Using Class Methods for Deep Analysis
============================================================

Example 1: Comprehensive Summary Statistics
------------------------------------------------------------
  Count:          365
  Mean:           0.9245
  Median:         0.9528
  Std Dev:        0.0705
  Range:          0.4871 to 0.9932
  1st percentile: 0.6778
  99th percentile:0.9898
  Skewness:       -2.4202
  Kurtosis:       8.0540
  Normality test: p-value = 0.000000

Days Sorted by Correlation Strength (Top 5):
        date  correlation
0 2022-01-21     0.993165
1 2022-11-28     0.992347
2 2022-02-16     0.991224
3 2022-12-13     0.990076
4 2022-10-16     0.989699

Days Sorted by Correlation Strength (Bottom 5):
        date  correlation
0 2022-06-28     0.487097
1 2022-11-04     0.564872
2 2022-06-03     0.576271
3 2022-04-30     0.656339
4 2022-07-04     0.689862

Visualization: Daily Correlation Plot

The plot shows: - Top panel: daily correlation time series with high/low thresholds - Middle panel: all low-correlation days overlaid (grey) - Bottom rows: the 3 lowest and 3 highest correlation days individually

corr1.plot(showplot=True)
Comparison between Rg_f and SW_IN_POT, Correlation between SW_IN_POT and Rg_f per day (n = 365) median = 0.953, 99th percentile = 0.990, 1st percentile = 0.678, min / max = 0.487 / 0.993, Found 21 low correlation days, 2022-06-03, r = 0.576, 2022-06-28, r = 0.487, 2022-11-04, r = 0.565, 2022-01-21, r = 0.993, 2022-02-16, r = 0.991, 2022-11-28, r = 0.992
<Figure size 800x1200 with 8 Axes>

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

Gallery generated by Sphinx-Gallery