Last active
February 7, 2022 04:25
-
-
Save jcheong0428/7d5759f78145fc0dc979337f82c6ea33 to your computer and use it in GitHub Desktop.
Cross correlation function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def crosscorr(datax, datay, lag=0, wrap=False): | |
""" Lag-N cross correlation. | |
Shifted data filled with NaNs | |
Parameters | |
---------- | |
lag : int, default 0 | |
datax, datay : pandas.Series objects of equal length | |
Returns | |
---------- | |
crosscorr : float | |
""" | |
if wrap: | |
shiftedy = datay.shift(lag) | |
shiftedy.iloc[:lag] = datay.iloc[-lag:].values | |
return datax.corr(shiftedy) | |
else: | |
return datax.corr(datay.shift(lag)) | |
d1 = df['S1_Joy'] | |
d2 = df['S2_Joy'] | |
seconds = 5 | |
fps = 30 | |
rs = [crosscorr(d1,d2, lag) for lag in range(-int(seconds*fps),int(seconds*fps+1))] | |
offset = np.floor(len(rs)/2)-np.argmax(rs) | |
f,ax=plt.subplots(figsize=(14,3)) | |
ax.plot(rs) | |
ax.axvline(np.ceil(len(rs)/2),color='k',linestyle='--',label='Center') | |
ax.axvline(np.argmax(rs),color='r',linestyle='--',label='Peak synchrony') | |
ax.set(title=f'Offset = {offset} frames\nS1 leads <> S2 leads',ylim=[.1,.31],xlim=[0,301], xlabel='Offset',ylabel='Pearson r') | |
ax.set_xticks([0, 50, 100, 151, 201, 251, 301]) | |
ax.set_xticklabels([-150, -100, -50, 0, 50, 100, 150]); | |
plt.legend() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Dear author.
This is a very helpful program. I have one question though
I use the following code adapted from yours to calculate lagged cross-correlation.
The sample has 1499 measures recorded with 25 Hz (mocap data)
While the heatmap graph for the rolling cross-correlation looks perfect the graph for the windowed one looks strange leaving white space (no data) at the beginning and the end of the X axis. This results from NaNs in the matrix. Can you help me understand
seconds = 6
fps = 25
no_splits = 25
samples_per_split = df.shape[0]/no_splits
rss=[]
for t in range(0, no_splits):
rss = pd.DataFrame(rss)
f,ax = plt.subplots(figsize=(12,10))
sns.heatmap(rss,cmap='RdBu_r',ax=ax)
ax.set(title=f'Windowed Time Lagged Cross Correlation',xlim=[0,301], xlabel='Offset',ylabel='Window epochs')
ax.set_xticks([0,50, 100, 151, 201, 251, 301])
ax.set_xticklabels([-150, -100, -50, 0, 50, 100, 150])
plt.show