scipy.signal.correlate
correlate — SciPy v1.18.0 Manual
Implement a matched filter using cross-correlation, to recover a signal that has passed through a noisy channel. >>> import numpy as np >>> from scipy import signal >>> import matplotlib.pyplot as plt >>> rng = np.random.default_rng() >>> sig = np.repeat([
docs.scipy.org
correlate(in1, in2, mode='full', method='auto')
2개의 N-dimensinal array를 교차상관한다. mode에 따라서 output size가 결정됨.
- in1, in2 : 두 input의 차원은 같아야함
- mode= 'full'
- 부분적으로 1 sample만 겹치는 경우까지 전부 포함
- 개념적으로 y를 x 위에서 왼쪽 끝부터 오른쪽 끝까지 쭉 움직이면서 correlation을 계산
- 따라서 만약 len(in1)=N, len(in2)=M 이면 len(output)=N+M-1
- 따라서 모든 lag에 대한 correlation 정도를 알 수 있음.
- 만약 모든 lag에 대해서 조사를 하고 lag를 제한을 두면 효과적으로 사용 가능
max_lag_sec = 2.0
max_lag_sample = int(max_lag_sec / dt)
mask = np.abs(lags) <= max_lag_sample
corr_search = corr[mask]
lags_search = lags[mask]
idx = np.argmax(corr_search)
best_lag = lags_search[idx]
- mode = 'same'
- mode='full' correlation의 중앙 부분만 잘라서 반환 이때 output의 길이는 in1이랑 같게
- len(output) = len(in1)
len(master), len(slave)
>>> 1000,1000
##full
signal.correlate(master, slave, mode='full')
lag
-999 ---------------- 0 ---------------- +999
가능한 모든 shift를 계산
##same
signal.correlate(master, slave, mode='same')
FULL
-999 ---------------- 0 ---------------- +999
|<------ SAME ------>|
- mode = 'valid'
- 한 신호가 다른 신호 안에 완전히 들어와 있을 때만 correlation을 계산
- 출력길이는 N-M+1
- template matching에 유용함
- template이 trace 밖으로 삐져나가는 위치는 아예 계산하지 않으므로
- "template 전체가 trace에 존재하는 위치에서만 비교하겠다"
그림으로 비교하면
len(in1)
>>> 5
len(in2)
>>> 3
##full
x x x x x
y y y
y y y
y y y
y y y
y y y
y y y
y y y
총 7 positions
##same
x x x x x
y y y
y y y
y y y
y y y
y y y
총 5 positions
##valid
x x x x x
y y y
y y y
y y y
총 3 positions
- method
- direct
- time domain에서 직접 수행(시그마 직접 계산)
- C[k]=n∑x[n]y[n−k]
- fft
- freq. domain에서 두 spectrum을 곱하고 다시 IFFT
- auto
- scipy가 직접 판단 (신호길이에 따라 direct와 auto의 계산 효율 차이가 많이 나기 때문)
- direct