To dynamically capture the correlation between two large arrays (each >4 million values) locally — meaning their correlation may change depending on the position in the array — you’ll want to use a sliding window correlation approach.
✅ Goal:
Create a new array of correlation values that describe local correlation between the two arrays at different positions.
📌 Method: Sliding Window Pearson Correlation
Here's how you can do it:
Step 1: Choose a window size
Decide on a window size, e.g., 1000, 5000, or 100, depending on how localized you want the analysis to be.
- Large window → smooth signal but misses short-term decorrelations
- Small window → captures quick fluctuations but may be noisy
Step 2: Slide the window across the arrays
At each step, compute the Pearson correlation coefficient in that window.
Step 3: Store the correlation value
Either store a single value per window (resulting in a shorter correlation array), or use a moving window (e.g., stride of 1), storing a value for each window center.
🧠 Formula
For windowed Pearson correlation at position i:
corr[i] = corrcoef(array1[i : i+win], array2[i : i+win])[0,1]
Use numpy or scipy to calculate this.
✅ Example in Python (with NumPy):
import numpy as np
def windowed_correlation(arr1, arr2, window_size):
assert len(arr1) == len(arr2), "Arrays must be the same length"
n = len(arr1)
half_win = window_size // 2
corr_arr = np.empty(n)
corr_arr[:] = np.nan # start with NaNs
for i in range(half_win, n - half_win):
x = arr1[i - half_win : i + half_win]
y = arr2[i - half_win : i + half_win]
if np.std(x) == 0 or np.std(y) == 0:
corr_arr[i] = np.nan # Avoid division by zero
else:
corr_arr[i] = np.corrcoef(x, y)[0, 1]
return corr_arr
You can reduce steps by using optimized/convolutional methods — this is a starting point.
🧪 Optional Enhancements
✅ Smoothing
Apply a moving average (or Gaussian filter) to smooth the resulting correlation signal.
✅ Speed Up (Optional for huge arrays)
- Use Numba to JIT compile.
- Use Strided views for vectorization.
- Use rolling window tools like
pandas.Series.rolling().corr() (see below).
🛠️ Alternative with pandas (slightly higher-level)
import pandas as pd
df = pd.DataFrame({'a': array1, 'b': array2})
rolling_corr = df['a'].rolling(1000).corr(df['b'])
rolling_corr will be a series of correlation values (with NaNs at the start depending on window size).
🧠 Interpretation:
- Values near 1 → strong positive correlation
- Values near -1 → strong negative correlation
- Values near 0 → no correlation
Summary
| Step | Description |
|---|
| 1 | Choose window size for "locality" |
| 2 | Slide the window across the arrays |
| 3 | Compute correlation in each window |
| 4 | Store result in a new array |
| 5 | (Optional) Smooth / threshold / detect zones using correlation sign or magnitude |
Let me know if you want this as a vectorized implementation to maximize performance!