/** This file tests the routines in correlation.frink. */ use correlation.frink list = [1,2,1,4,1,8,1,2,1,4,1,8,1,2,1,4,1,8] /** Calculate the autocorrelation in a repeating list with sub-patterns. This should obtain an offset of 6 being the highest correlation. */ println["List: Perfect repetition with period 6"] println[formatTable[stableSort[autocorrelation[list]]]] println[] println["List: Partial autocorrelation, perfect repetition with period 6"] println[formatTable[stableSort[partialAutocorrelation[list]]]] println[] // The previous list with a bit of noise. Hopefully the period will still be 6 println["List2: imperfect repetition with period 6"] list2 = [1,2,1,4,1,8,1,2,3,4,1,8,1,2,1,5,1,8] println[formatTable[stableSort[acFFT[list2]]]] println[] // The list made very noisy because each point is perturbed by Gaussian noise // centered around the true value with standard deviation = 1 // (Note that results will vary between runs.) // Hopefully the strongest period will still be detected at 6. list3 = new array for a = list list3.push[randomGaussian[a, 1]] println["List3: noisy list with gaussian noise, period 6"] //println["Noisy list is $list3"] println["Results:"] //println[formatTable[stableSort[autocorrelation[list3]]]] println[] // Find when the digits in a number repeat themselves. The precision may have // to be increased for larger denominators, as 1/n may repeat after as many as // n-1 digits. for b = 1 to 200 { setPrecision[b*2+10] digits = array[chars[toString[1./b]]] setPrecision[20] r = stableSort[autocorrelation[digits]] // println[r] println["1/$b appears to repeat most strongly after " + r@0@0 + " terms."] } println[] // Calculate the autocorrelation of a sinewave. The period should be close // to the number divided by in the "step" below, although if the step is // small, then the offsets near 1 will be the strongest (as the sine wave is // shifted very slightly relative to itself.) setPrecision[15] period = 17.1 c = new array for i = 0 to 10 pi step (2 pi / period) c.push[sin[i]] println["Autocorrelation of sinewave with period $period"] println[formatTable[format[stableSort[acFFT[c]], 1, 12]]] println["\nPartial Autocorrelation of sinewave with period $period"] println[formatTable[stableSort[partialAutocorrelation[c]]]] /** Autocorrelation function using FFT. This reproduces the behavior of the autocorrelation function. */ acFFT[x] := { res = autocorrelationFFT[x] n0 = res.popFirst[] // Eliminate 0 term // println["unscaled is $unscaled"] return sort[zipShorter[count[1], Re[res]], {|a,b| -(a@1 <=> b@1)}] } stableSort[x] := reverse[sort[x, byColumns[[1,0]]]]