Skip to content

Instantly share code, notes, and snippets.

@jcheong0428
Last active February 7, 2022 04:25
Show Gist options
  • Save jcheong0428/7d5759f78145fc0dc979337f82c6ea33 to your computer and use it in GitHub Desktop.
Save jcheong0428/7d5759f78145fc0dc979337f82c6ea33 to your computer and use it in GitHub Desktop.
Cross correlation function
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()
@jcheong0428
Copy link
Author

jcheong0428 commented Oct 31, 2019

May I ask how to choose the values of seconds and fps ?

That would be based on what frame rate your data was recorded in and how many seconds you want to plot for the cross correlation.

@GBente
Copy link

GBente commented Apr 18, 2020

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):

d1 = df['Move1'].loc[(t)*samples_per_split:(t+1)*samples_per_split]
d2 = df['Move2'].loc[(t)*samples_per_split:(t+1)*samples_per_split]

rs = [crosscorr(d1,d2, lag) for lag in range(-int(seconds*fps),int(seconds*fps+1))]
rss.append(rs)

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment