Last active
October 19, 2020 13:11
-
-
Save golanlevin/79ee7bac5b9fa8e02fdbb0a8ad3b7416 to your computer and use it in GitHub Desktop.
Autocorrelation demo in Processing
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
float mysteryLag; | |
float signalA[]; | |
float signalB[]; | |
float autoCorr[]; | |
int nData; | |
void setup() { | |
size(512, 700); | |
nData = 512; | |
signalA = new float[nData]; | |
signalB = new float[nData]; | |
autoCorr = new float[nData]; | |
} | |
void draw() { | |
background(200); | |
noiseSeed(55); | |
mysteryLag = 0.96*mysteryLag + 0.04*mouseX; | |
for (int i=0; i<nData; i++) { | |
float tA = map(i, 0, nData, 0, TWO_PI*5.5); | |
float tB = map(i-mysteryLag, 0, nData, 0, TWO_PI*5.5); | |
signalA[i] = 40 * (sin(tA + 3.0*(noise(tA*0.6)-0.5)) + 2.5*(noise(tA*0.4)-0.5)); | |
signalB[i] = 40 * (sin(tB + random(2.0,4.0)*(noise(tB*random(0.5,0.7) + 10.0*random(-1,1))-0.5)) + 2.5*(noise(tB*0.4)-0.5) + 0.2*random(-1,1)); | |
if (random(1.0) < 0.07) { | |
signalB[i] = 40 * random(-1, 1); | |
} | |
} | |
for (int lag=0; lag<nData; lag++) { | |
float sum = 0; | |
for (int i=0; i<nData; i++) { | |
if ((lag+i) < nData) { | |
sum += signalA[i] * signalB[lag+i]; | |
} | |
} | |
sum /= nData; | |
autoCorr[lag] = sum; | |
} | |
// find max of autocorr. The index of the peak is our mysterylag! | |
float autocorrMax = 0; | |
int indexOfAutocorrMax =0; | |
for (int i=0; i<nData; i++){ | |
if (autoCorr[i] > autocorrMax){ | |
autocorrMax = autoCorr[i]; | |
indexOfAutocorrMax = i; | |
} | |
} | |
noFill(); | |
stroke(0); | |
beginShape(); | |
for (int i=0; i<nData; i++) { | |
vertex(i, 400 + signalA[i]); | |
} | |
endShape(); | |
line(0, 400, width, 400); | |
beginShape(); | |
for (int i=0; i<nData; i++) { | |
vertex(i, 550 + signalB[i]); | |
} | |
endShape(); | |
line(0, 550, width, 550); | |
float autoCorrScale = -10.0; | |
beginShape(); | |
for (int i=0; i<nData; i++) { | |
vertex(i, 200 + autoCorr[i]/autoCorrScale); | |
} | |
endShape(); | |
fill(0); | |
line(0, 200, width, 200); | |
line(0, 200+ autocorrMax/autoCorrScale, width, 200+ autocorrMax/autoCorrScale); | |
line(indexOfAutocorrMax, 200, indexOfAutocorrMax, 200+ autocorrMax/autoCorrScale); | |
text("Computed Lag = " + indexOfAutocorrMax, indexOfAutocorrMax, 200 + autocorrMax/autoCorrScale - 7); | |
text("Actual lag = " + mysteryLag, 20, 20); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment