Skip to content

Instantly share code, notes, and snippets.

@ctralie
Created August 9, 2025 14:42
Show Gist options
  • Save ctralie/53309676a5794b8aa37a43150623b754 to your computer and use it in GitHub Desktop.
Save ctralie/53309676a5794b8aa37a43150623b754 to your computer and use it in GitHub Desktop.
def get_distmat_psd(D, sr):
"""
Compute the power spectral density of the diagonals of
a distance matrix
Parameters
----------
D: ndarray(N, N)
Distance matrix
sr: int
Sample rate (e.g. 30 frames per second in video)
Returns
-------
diags: ndarray(N)
Mean of diagonals
ks: ndarray(N//2+1)
Frequencies, in cycles/second
psd: ndarray(N//2+1)
Power spectral density associated to each frequency
"""
N = D.shape[0]
diags = np.zeros(N)
for i in range(N):
diags[i] = np.mean(np.diag(D, i))
# Compute the power spectral density
psd = np.abs(np.fft.rfft(diags - np.mean(diags)))**2
# Do a dimension analysis to determine the frequency, in cycles/sec
# of each Fourier frequency bin
# (k cycles/interval) * (1 interval / N samples) * (sr samples / sec)
ks = np.arange(psd.size) * sr / N # cycles / sec
return diags, ks, psd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment