In the previous articles I studied the spectrum of a signal and the way a tone spreads across the FFT frequencies. Now I change point of view. If I know the shape of a signal I am looking for, I can try to recognize it directly in the acquired samples, without necessarily starting from its spectrum. How can I establish not only whether two signals look alike, but also how far one is shifted with respect to the other?

This is the question that leads me to correlation. I deliberately start with two simple pulses, because I want to be able to predict the numbers before reading the program’s result. I use GX-TXT v0.9.8.10-dev-112-p012, Scientific Worksheet 2.1.2, Math Numeric 1.67.0 and Scientific Dataset Plot 4.4.3. For now all the data are synthetic.

1. Comparing two sequences by shifting one against the other

I call b[n] the reference and c[n] the signal to compare. I consider two real records of equal length N, with samples spaced Δt = 1/fs apart. To define the linear correlation I extend each sequence with zeros outside the N samples. I adopt the convention

\[ R_{cb}[k] = \sum_{n} c[n+k]\,b[n], \qquad k = -(N-1),\dots,N-1. \]

I sum the products only where the two records overlap, since elsewhere one of the factors is zero. With complex signals the second factor would have to be conjugated. If k is positive, I am comparing a later sample of the first signal with the current sample of the second. I do not subtract the means and I do not divide by N: this is the raw correlation, not the Pearson coefficient. Nor do I confuse it with a circular correlation, in which the ends would wrap around and join.

Delay and position of the maximum

If the first signal is a copy of the second delayed by d samples, c[n]=b[n−d], then Rcb[k]=Rbb[k−d], for the zero-extended sequences and assuming the delay has not cut off part of the pulse. The maximum therefore moves by d samples. The corresponding time scale is τ=k/fs.

Try it yourself with GX-TXT

I ran the experiments below with GX-TXT, a free software you can install on Linux. There is no need to trust my numbers: follow the steps, rebuild the pulses, the sine wave and the noise, and compare your correlations with mine. Then change something — the delay between the pulses, the normalization, the seed or the noise amplitude — and watch how the maxima move and how the amplitude estimate changes. It is the best way to really understand what a correlation measures, and to have some fun too.

2. I set up an experiment whose answer I already know

I create a session independent of the Fourier one with Sessions → Session → New Session. I set the name LockIn_05_correlazione_autocorrelazione (1), then Create (2).

In the Viewers tab (3), I search for Worksheet (4) and open the viewer (5).

I choose 8 samples with fs=2000 Hz, that is Δt=0.5 ms. I want an imposed delay of 2 samples (1 ms). The amplitudes are dimensionless numbers: I am not yet representing real voltages, so I can concentrate on the shape and on the sign of the lag. With Go to (6), Cell & Formula (7) and the formula area (8), I apply the following three expressions to the cells with Apply (9). Save (10) stores the sheet before the guided operations.

CellFormulaMeaning
A1=vector(0,1,2,3,4,5,6,7)Sample index n
B1=vector(0,0,1,2,1,0,0,0)Reference b[n]
C1=vector(0,0,0,0,1,2,1,0)Delayed pulse c[n]

The source cell shows the resulting vector expression; the rows below show the expanded samples. The reference has its maximum at index 3 and the second pulse at index 5. When I realign them, the three non-zero products are 1×1, 2×2 and 1×1: I therefore expect a maximum of 6. At zero lag only one common sample of value 1 remains.

3. I compute the cross-correlation

I open Functions (11), search for and select numeric.signal_correlation (12). I set first = C1:C8, second = B1:B8 (13), Options = normalization="none" sample_rate=2000 (14). I press Preview fields (17) and wait for it to complete. In Result field (15) I choose the lags field, leave First result row = 1 and Result row count empty; Output cell = D1 (16). I press Apply result (18). Column D contains all 15 integer lags, from −7 to +7.

I repeat Apply result choosing value_real and destination E1, without changing the inputs. I wait for the operation to finish; then I choose delay_seconds (19), destination F1 (20) and apply the result. In E10 (21) I read the maximum 6, associated with D10=2; in F1 (22) I read 0.001 s. The result matches the delay I introduced. The positive sign is not a graphical detail: it depends precisely on the order of the arguments.

3.1. What if I swap the order of the two signals?

In the same panel I set first = B1:B8 (23), second = C1:C8 (24), without changing the normalization or the sampling rate. After Preview fields I select value_real, Output cell = G1 (25), then Apply result. In G6 (26), associated with D6=−2, I again read 6. I have reversed the sign of the delay, not the shape of the pulse: for real signals Rbc[k]=Rcb[−k].

4. I compare the reference with itself

I choose B1:B8 both in first (27) and in second (28), again with normalization=”none” and sample_rate=2000. After Preview fields I capture value_real in H1 (29) and apply the result. The maximum is in H8 (30), that is at k=0, and equals 6. In this case I get a symmetric sequence: the pulse is most similar to itself when it is not shifted.

At zero delay the raw correlation equals the sum of squares: Rbb[0]=Σb[n]²=6. Dividing by N=8 gives the mean square value 0.75. For a real signal the autocorrelation is even; moreover, from the Cauchy–Schwarz inequality, |Rbb[k]| ≤ Rbb[0]. This is a general property of the raw correlation of the zero-extended finite sequence, not only of our pulses.

I report the values read directly in columns D, E, G and H. The lags outside this detail, that is from −7 to −5 and from 5 to 7, have all three correlations equal to zero.

Lag kRcb (E)Rbc (G)Rbb (H)
−4010
−3040
−2061
−1044
0116
1404
2601
3400
4100

5. Making the delay visible

GX-TXT procedure: charts, publication and labels (figures 8–11)

I select A1:C8, open Chart (31), then Add selection (32). I check X column = A, Y columns = B C, rows 1–8 (33), title Reference B and delayed pulse C - sample index, Kind = line, Panels = overlay, Marker = circle (34), legend inside. I set X minimum/maximum = 0 and 7, Y minimum/maximum = −0.2 and 2.5 (35). The margin below zero makes the zero samples readable. I press Apply (36).

I create a second view by selecting D1:E15 and pressing Add selection (37). In this new chart I set X column = D and Y columns = E G H (38); rows 1–15, line, overlay, circle, legend inside. The title is Raw correlation - C with B, B with C, B with B. I set X from −7 to 7 samples and Y from −0.5 to 7 (39), both linear, then Apply (40). I want to include all lags, not only those with non-zero values.

I save the Worksheet. I publish chart_2 with Publish immutable Graph to Plots (41) and check the confirmation (42). I then select chart_1 from the Live native charts selector and use the same command, once the previous operations have finished. If a busy warning appears during publication, I do not duplicate the operation: I check which Datasets and graphs are already present. In my case both graphs are available in Plots after saving the session configuration.

In Plots I select the correlation variant p0001, Presentation → Title and labels; I set X / bottom label = Lag (samples) (43) and Y Left label = Raw correlation (dimensionless) (44), then Save (45) and Render → Rerender selected. In the pulse variant p0002 I repeat the procedure with Sample index n and Amplitude (dimensionless). I save the configuration again.

In the pulse plot the blue maximum is at index 3 and the red one at index 5: the distance is 2 samples. The circles are the actual samples; the lines are only a visual aid and do not represent measurements between samples.

In the second plot I look at the three curves: blue E is Rcb, red G is Rbc, green H is Rbb. The three maxima have the same height, but they lie at +2, −2 and 0 respectively. The shape of the cross-correlation coincides with that of the shifted autocorrelation: the delay has become a position that can be read on an axis. This first check lets me fix the sign convention without relying on an ambiguous result or on an interpretation of the plot alone.

6. Why are there four normalizations?

I measured a delay and obtained a maximum of 6. But that number depends on the number of samples and on their amplitudes. If I multiplied both pulses by two, the sum of products would become four times larger even without changing the shape or the delay. I need to distinguish what I want to measure: the total product, the mean product, or the similarity independent of the amplitude scale.

I take again the raw correlation Rcb[k] of the previous experiment, with N=8 and integer lags from −7 to +7. For two records of equal length the four options are:

OptionDefinitionMeaning
noneRcb[k]Sum of the overlapping products.
biasedRcb[k]/NFixed denominator, equal to the record length.
unbiasedRcb[k]/(N−|k|)Denominator equal to the number of overlapping pairs.
coefficientRcb[k]/√(Σc[n]² Σb[n]²)Normalization by the full norms of the two signals.

The first three keep the units of the product of the signals, if these have physical units; the fourth is dimensionless. Here all the inputs are already dimensionless. The coefficient is not Pearson’s: I have not subtracted the means, and the denominator uses the whole record, not only the overlapping stretch. For non-zero norms the Cauchy–Schwarz inequality limits its magnitude to 1, up to numerical rounding. The biased/unbiased naming refers to correlation estimators of stationary processes: it does not imply that every estimate on a deterministic pulse, or every position of the maximum, is free of distortion.

In the Worksheet I go back to Functions and numeric.signal_correlation (46), leaving first = C1:C8 and second = B1:B8. In Options (47) I set normalization="biased" sample_rate=2000. After Preview fields (50), I select value_real in Result field (48), destination I1 (49) and Apply result (51). The maximum I10 (52) is 0.75: indeed 6/8=0.75.

Now I change only Options (53) to normalization="unbiased" sample_rate=2000 and Output cell to J1 (54), repeat Preview fields and Apply result with value_real. In J10 (55) I read 1. At lag 2 there are 8−2=6 pairs available, so 6/6=1. At lag 1 I get 4/7 and at lag 3 I get 4/5: although they start from the same sum 4, the results differ.

Finally I set normalization="coefficient" sample_rate=2000 (56), destination K1 (57), Preview fields, value_real and Apply result. The two sums of squares are both 6, so the denominator is √(6×6)=6. In K10 (58) I read 1. In the native CSV the value is 1.0000000000000002: the difference from unity is of the order of machine precision, not a physical correlation greater than 1.

These are the Worksheet results, rounded for reading; all lags not shown in the table are zero.

LagNone (E)Biased (I)Unbiased (J)Coefficient (K)
010.1250.1250.166667
140.50.5714290.666667
260.7511
340.50.80.666667
410.1250.250.166667

6.1. Normalization can change the shape too

GX-TXT procedure: chart, publication and labels (figures 17–19)

I select D1:E14 as a starting point and open Chart (59). I press Add selection (60): the new chart_3 does not replace the two previous views. I set X column = D, Y columns = I J K (61), First row = 1 and Last row = 15 (62), title Correlation - biased I, unbiased J, coefficient K, Kind = line, Panels = overlay, Marker = circle, Legend = inside. I use X from −7 to +7 and Y from −0.05 to 1.1 (63), linear scales, so as not to clip the maximum and to keep the markers on zero visible. I press Apply (64).

I save the Worksheet and publish the graph with Publish immutable Graph to Plots (65); I wait for the confirmation (66). In this run publication succeeded without the busy warning encountered earlier. In Plots the variant p0003 is present. I select Presentation → Title and labels, set X / bottom label = Lag (samples) (67) and Y Left label = Normalized correlation (dimensionless) (68), Save (69), then Render → Rerender selected.

I look at the blue curve (biased) and the green one (coefficient): both keep the shape of the raw peak, because each uses a constant divisor. The red curve (unbiased) is instead asymmetric about k=2, even though the raw correlation is symmetric about that point. Its two samples adjacent to the maximum are about 0.571 and 0.8. The shape of the pulse has not changed: what changes is the number of pairs available as the lag varies.

The maximum at 2 samples is common to the four normalizations in this test, but it is not a general guarantee for the unbiased mode: extreme delays rely on few pairs and can have higher variability in the presence of noise. Moreover, a high coefficient is not, by itself, a probability of having found the signal. To understand how this method really helps the lock-in I need to move to a sinusoidal reference and introduce noise, keeping the checks in the absence and in the presence of the signal separate.

7. Autocorrelation of a sine wave observed for a finite time

I now leave isolated pulses and go back to a periodic waveform, because the lock-in reference will be sinusoidal. If the signal is x[n] = sin(ωn), with ω = 2πf0/fs, the product of two samples k apart can be written as

\[ x[n+k]\,x[n] = \tfrac{1}{2}\cos(\omega k) – \tfrac{1}{2}\cos(2\omega n + \omega k). \]

For a finite record of N samples, extended with zeros outside the window, for k ≥ 0 I set M=N−k. The raw correlation is

\[ R_{xx}[k] = \frac{M}{2}\cos(\omega k) – \frac{1}{2}\sum_{n=0}^{M-1}\cos(2\omega n+\omega k). \]

For negative lags Rxx[−k]=Rxx[k]. In the biased normalization I divide by N; in the unbiased one I divide by M. The ideal correlation of a unit-amplitude sine wave, averaged over whole periods, is ½ cos(ωk). But in the finite record the second sum is not always zero: besides the number of available pairs, what matters is the portion of the period that actually overlaps. So I do not confuse the finite linear correlation with the periodic or circular one.

7.1. I generate a coherent sine wave in a separate sheet

In the Worksheet I save a new sheet using the + button (70), name it Sinusoide (71) and confirm with Apply (72), then Save. I keep the pulse sheet without overwriting it. I choose N=40, fs=2000 Hz, f0=200 Hz: 10 samples per period, four periods in the nominal record T=N/fs=20 ms, with the last sample at 19.5 ms. The amplitude is dimensionless and unitary, the initial phase zero.

In Functions I select numeric.uniform_grid (73): start=0, stop=0.0195, spacing=40 and Options=mode="count" (74). I press Preview fields (77), select x (75), Output cell=A1 (76) and Apply result (78). I get the grid A1:A40 with a step of 0.0005 s.

I select signal.generate.sine (79). I set time=A1:A40, frequency=200, modulation=empty(), Options=amplitude=1 phase_rad=0 (80). After Preview fields I choose value_real (81), Output cell=B1 (82) and Apply result (83). The signal reaches about ±0.9511 in the samples closest to the peaks: the mathematical amplitude is 1, but the continuous peaks fall between two sampled instants. This is not a defect of the generator.

7.2. I compare the two normalizations on the same record

In Functions I choose numeric.signal_correlation (84). I enter B1:B40 both in first and in second; Options=normalization="biased" sample_rate=2000 (85). After Preview fields I choose lags in Result field (86) and Output cell=C1, then Apply result. I repeat with value_real and Output cell=D1 (87), pressing Apply result (88) and waiting for completion. Columns C and D contain the 79 lags from −39 to +39 and the biased autocorrelation.

I change Options (89) to normalization="unbiased" sample_rate=2000, destination E1 (90), repeat Preview fields and select value_real, then Apply result (91). Now D and E are two results of the same autocorrelation, obtained with different divisors.

For multiples of five samples, that is multiples of the half-period, M is a multiple of five and the second sum of the formula vanishes. I therefore expect Rbiased[k] = (40−|k|) cos(2πk/10)/80 and Runbiased[k] = ½ cos(2πk/10) at these points. The numbers read from the published Dataset confirm the prediction (rounded):

Lag (samples)Delay (ms)Biased (D)Unbiased (E)
000.50000.5000
52.5−0.4375−0.5000
1050.37500.5000
20100.25000.5000
30150.12500.5000
3517.5−0.0625−0.5000
3618−0.050564−0.505636
3919.500

The value at lag 0 is the mean of the squares, equal to 0.5. At integer delays of 5 ms the signal comes back in phase with itself: at k=10, 20, 30 the biased normalization drops from 0.375 to 0.25 and 0.125, while the unbiased one stays at 0.5. At odd half-periods the products become predominantly negative. The value −0.505636 at k=36 is not an error: only four pairs remain and the divisor M does not guarantee the 0.5 limit of the average over a whole period. At k=39 only the product with the initial zero sample remains, so both correlations are zero. These two points are useful precisely because they show the limits of interpreting the red curve as an ideal cosine.

7.3. The graphical representation

GX-TXT procedure: chart, publication and labels (figures 26–28)

I select C1:D10 as a starting point and open Chart (92), then Add selection (93). In the new chart_4 I set X column=C and Y columns=D E (94), rows 1–79 (95), title 200 Hz sine autocorrelation - biased D and unbiased E, Kind=line, Panels=overlay, Marker=circle, Legend=inside. I set X minimum/maximum=−39 and +39, Y minimum/maximum=−0.65 and +0.65 (96). Both scales are linear: I want to be able to read the negative values too. I press Apply (97).

I save the Worksheet. I publish the graph with Publish immutable Graph to Plots (98) and check the confirmation (99). In Plots I select the variant p0004; with Presentation → Title and labels I set Lag (samples) (100) and Autocorrelation (dimensionless) (101), then Save (102) and Render → Rerender selected.

In the blue plot the decrease of the maxima is due to the progressively smaller overlap of the records, not to a physical damping of the sine wave. The red plot compensates for the decreasing number of pairs and makes the periodicity more evident; near the ends, however, the result is less representative of an average over whole periods. The circles are the 79 computed values: the segments do not imply an interpolation of the delays between samples.

The distance between consecutive positive maxima, ten samples, corresponds to 5 ms, that is to the 200 Hz frequency. A sine wave, however, does not provide a unique delay identifier: shifts of a whole period can give the same phase. This is why a synchronous detection must use a phase reference and distinguish the in-phase contribution from the quadrature one. The comparison with a noisy signal will be the next step; for now I have not yet verified the ability to extract the signal from noise.

8. White noise and the persistence of periodicity

In the experiments with pulses and sine waves I observed the correlation of deterministic signals. What happens instead when the signal is no longer clearly visible in the individual samples? I build three comparable records: the noise n[n], a sine wave s[n] and their sum y[n]=s[n]+n[n]. I use exactly the same noise realization in the control and in the sum, so the comparison does not depend on a change of seed.

For discrete white noise with zero mean and variance σ², samples at different delays are uncorrelated. The theoretical ensemble autocorrelation is

\[ R_{nn}[k] = E\{n[j+k]\,n[j]\} = \sigma^2\,\delta[k]. \]

δ[k] is one at zero lag and zero elsewhere. It does not mean that, in a single acquisition, all products at non-zero lags cancel exactly. If I use the biased normalization, the expectation of the white-noise estimate is still zero at non-zero lags, but the individual results fluctuate. Moreover, I have not subtracted the sample mean.

The autocorrelation of the sum, with the same fixed divisor N for each term, satisfies exactly

\[ \hat R_{yy}[k] = \hat R_{ss}[k] + \hat R_{nn}[k] + \hat R_{sn}[k] + \hat R_{ns}[k]. \]

For a deterministic sine wave and independent zero-mean noise, the two cross terms have zero expectation. On the finite record, on average, what remains is therefore the biased correlation of the sine wave plus the noise contribution at zero lag. The cross terms and the noise fluctuations are not zero, however, in the single realization. The autocorrelation is neither a reconstruction of the waveform nor a proof of statistical significance.

8.1. I build the three records on the same time axis

I create a third sheet in the same Worksheet, named Rumore, using the + button as in figure 21. I save. In Functions I select numeric.uniform_grid (103), start=0, stop=0.0995, spacing=200, Options=mode="count" (104). After Preview fields I choose x (105), Output cell=A1 (106), Apply result (107). I get 200 samples at 2 kHz, from time zero to 99.5 ms; T=N/fs=100 ms.

I choose signal.generate.white_noise (108), time=A1:A200, frequency and modulation=empty(). Options=amplitude=1 seed=33001 (109). The seed is fixed before the comparison and is not selected on the basis of the shape of the autocorrelation. As explained in article 02, amplitude is the theoretical standard deviation, not the RMS value imposed on the single sequence. After Preview fields I select value_real, Output cell=B1 (110) and Apply result (111).

With signal.generate.sine (112) I choose time=A1:A200, frequency=200, modulation=empty(), Options=amplitude=1 phase_rad=0 (113). I capture value_real in C1 (114), with Apply result (115). The sine wave contains 20 periods and its theoretical mean square value is 0.5. The noise has theoretical variance 1: the signal-to-noise ratio in terms of mean square values is therefore 0.5 (about −3 dB). In this test all amplitudes are dimensionless.

I select D1, open Cell & Formula and enter (116) =numeric.add(B1:B200,C1:C200). I press Apply (117); column D (118) shows the sample-by-sample sum. I save the sheet. Columns B and C remain unchanged.

8.2. I compute the three autocorrelations with the same estimator

In Functions I choose numeric.signal_correlation (119), first and second=B1:B200 (120), Options=normalization="biased" sample_rate=2000 (121). After Preview fields I select lags in Result field (122), Output cell=E1 (123) and Apply result (124). I then capture value_real in F1 using the same result. The 399 rows correspond to the integer lags from −199 to +199; row 200 is zero lag. The figure shows the second result, F1.

I repeat the same operation with first and second=D1:D200 (125), keeping normalization and sampling rate unchanged. After Preview fields I capture value_real in G1 (126). Finally I use first and second=C1:C200 (127) and capture value_real in H1 (128), the deterministic control on the same grid.

I report some values read directly from the new published Dataset. The physical delay is k/fs; the numbers in the table are rounded.

Lag (samples)Noise FSum GSine H
01.0047371.6971750.500000
50.173649−0.489444−0.487500
100.0725010.7277180.475000
15−0.072613−0.691331−0.462500
20−0.0603000.5553220.450000
30−0.0038260.5774970.425000
500.0387640.5568190.375000
1000.0451540.3913740.250000

At zero lag I read the mean square value of the three records. The noise is about 1.004737, not exactly 1. The sum is about 1.697175, not 1.5: the latter is the theoretical expected value, not a constraint imposed on the realization. Even the sum of the two individual mean square values does not match that of the mixed signal, precisely because on the finite record there is the cross term. At lags 5, 10, 15, 20 and beyond, instead, I see that the periodicity of the sine wave remains in column G, superimposed on the random fluctuations.

8.3. Full view and detail: do not mistake the central peak for a tone

GX-TXT procedure: full chart, publication and labels (figures 37–39)

I select E1:F10, open Chart and press Add selection. I configure chart_5 with X column=E, Y columns=F G H (129), rows 1–399 (130), title Biased ACF - noise F, sine plus noise G, sine H, Kind=line, Panels=overlay, Marker=none, Legend=inside. I use X from −199 to +199 and Y from −0.8 to 2 (131), linear scales. I press Apply (132), then Save. In the full view I do not use markers because 399 points per curve would make the oscillations less readable.

With Publish immutable Graph to Plots (133) I publish the Dataset and the graph; the message (134) confirms the new variant p0005, without a contention warning. In Plots I select this variant; Presentation → Title and labels, X / bottom label=Lag (samples) (135) and Y Left label=Autocorrelation (dimensionless) (136), Save (137), Render → Rerender selected.

The blue noise curve F shows a peak at k=0 and relatively small fluctuations elsewhere. The green curve H shows the effect of finite duration already studied: the envelope shrinks towards the edges. In the red curve G the central peak also includes the noise, but the oscillations remain recognizable. The peak at zero does not prove the presence of a sine wave: white noise too has a non-zero mean square value.

GX-TXT procedure: chart_6 detail view (figure 41)

To read the individual lags I create another view in the Worksheet, chart_6, from the same selection E1:F10. I keep X=E and Y=F G H; I set First row=170 and Last row=230 (138), that is the 61 lags between −30 and +30. Marker=circle (139). I use X from −30 to +30 and keep the same Y scale from −0.8 to 2 (140). I press Apply (141) and save. This detail remains a live Worksheet chart; I do not duplicate the full Dataset already published.

In the detail the distance between recurring maxima is ten samples, that is about 5 ms: a periodicity compatible with 200 Hz. The circles identify the discrete values; axis E is the lag in samples and the three curves F, G, H are the dimensionless autocorrelations. One can also see that some noise values at non-zero lags are appreciable and that the sum does not exactly reproduce the curve of the pure sine wave.

I have therefore verified the persistence of periodicity in a single synthetic realization with a theoretical signal-to-noise ratio of 0.5. I have not yet estimated the false positive rate, nor shown that the method works at any signal-to-noise ratio. The next check will be the correlation with the sinusoidal reference, comparing the noise alone and the mixed signal. This will take me from the simple search for periodicity to the principle of synchronous detection.

9. Correlation with a known reference: the principle of synchronous detection

The periodicity recognizable in the autocorrelation tells me that I can look for a repetitive structure even in the presence of noise. A lock-in, however, has one more piece of information: a reference generated or acquired synchronously with the source. Instead of comparing the mixed signal y with itself, I compare it with the reference s. I use exactly the data of the Rumore sheet from the previous step: B contains n, C contains s and D contains y=s+n. N=200, fs=2000 Hz, f0=200 Hz, reference amplitude 1 and Gaussian noise with theoretical standard deviation 1. I do not generate a new random sequence.

With the lag convention already verified, and biased normalization, I get

\[ \hat R_{ys}[k] = \frac{1}{N}\sum_{j} y[j+k]\,s[j] = \hat R_{ss}[k] + \hat R_{ns}[k]. \]

The sum is over the overlapping samples, with zero extension. The identity holds for every lag of the single realization, without resorting to an ensemble average: correlation is linear with respect to the first input. The R̂nn term that characterized the autocorrelation of the mixed signal no longer appears.

9.1. Control without signal and measurement with signal

I reopen the Rumore sheet, open Functions and select numeric.signal_correlation (142). I set first=B1:B200 (143), second=C1:C200 (144), Options=normalization="biased" sample_rate=2000 (145). I press Preview fields (148); after the capture I choose value_real (146), Output cell=I1 (147), then Apply result (149). The result I1:I399 is the correlation of the noise alone with the reference.

I repeat the operation changing first to D1:D200 (150), without modifying the reference C or the options, and the destination to J1 (151). After Preview fields I choose value_real and Apply result. Columns I and J use the same lags from −199 to +199 as column E. Column H already contains R̂ss, computed in the previous step.

9.2. I verify linearity over the whole result

I select K1 (152), open Cell & Formula and enter (153) the residual, then Apply (154):

=numeric.subtract(numeric.subtract(J1:J399,I1:I399),H1:H399)

I do not compare only the maximum or a point chosen after the fact. I want to check all 399 lags. With Go to (155) I reach L1; I enter (156) and apply (157) the following formula. The vector returns, in order, the three correlations at zero lag, the RMS of the 399 residuals and the two amplitude estimates, in L1:L6 (158).

=vector(I200,J200,H200,numeric.rms(K1:K399),2*I200,2*J200)
CellQuantityResult
L1R̂ns[0]0.09621929
L2R̂ys[0]0.59621929
L3R̂ss[0]0.50000000
L4RMS of the linearity residual1.1834769 × 10−16
L5Estimated amplitude in the control0.19243858
L6Estimated amplitude with signal1.19243858

The RMS of the residual is compatible with the precision of the numerical representation: the check covers all the rows. It does not prove that the noise disappears; it proves that the signal contribution and the noise contribution add linearly in the correlated output.

9.3. From correlation to amplitude

At zero lag the biased correlation is exactly the mean of the product between input and reference. If the input is A s[j]+n[j], with unit reference s[j]=sin(2πf0j/fs), in phase and over an integer number of periods, then Σs[j]²=N/2. Hence

\[ T = \hat R_{ys}[0] = \frac{A}{2} + \frac{1}{N}\sum_{j} n[j]\,s[j], \qquad \hat A = 2T. \]

Why  = 2T

The factor 2 is not an arbitrary gain adjustment: it comes from the mean square of the unit sinusoidal reference. It holds here for the tone at the same frequency and phase; the general situation with a different phase will be treated with quadrature references.

The control without signal returns an apparent amplitude of 0.19243858; with the unit-amplitude signal I get 1.19243858. The error of this realization is about +19.24%. Subtracting the two values I recover 1 within rounding, because I deliberately used the same noise. This is a paired numerical check, not a technique for subtracting unknown noise from a real measurement.

9.4. An oscillation in the result is not enough to declare the tone present

GX-TXT procedure: full chart, publication, detail and labels (figures 47–49)

I select I1:J10 and open Chart (159), then Add selection. I configure chart_7 with X column=E, Y columns=I J H (160), rows 1–399 (161), title Correlation with reference - noise I, mixed J, sine H, Kind=line, Panels=overlay, Marker=none, Legend=inside. I set X from −199 to +199 and Y from −0.75 to +0.75 (162), then Apply (163). I save the Worksheet.

I publish the full view with Publish immutable Graph to Plots (164); the message (165) confirms the new Dataset and the variant p0006. I also create chart_8 in the same Worksheet, with the same columns, rows 170–230 (169), Marker=circle (170), X from −30 to +30, Y from −0.75 to +0.75 (171), Apply (172). The zoomed view stays live: a second immutable Dataset is not needed. I save again. After closing the Worksheet, in Plots I select p0006 and use Presentation → Title and labels; I set Lag (samples) (166) and Correlation (dimensionless) (167), Save (168), then Render → Rerender selected.

GX-TXT procedure: chart_8 detail settings (figure 51)

The blue curve I, obtained from the noise alone, also has an oscillating structure. This is an important effect: shifting a sinusoidal reference means changing the phase with which the random samples are weighted; the products at neighbouring lags are not independent tests. Even when the expected value of the correlation is zero, a single realization can have a random projection onto the in-phase and quadrature components. The size of this projection and the overlap of the records change as the lag varies.

A fixed lag, not the maximum over 399 delays

For this reason I do not treat the maximum over 399 delays as 399 independent checks, and I do not apply to the maximum a threshold computed for a single lag. In our experiment the frequency and phase of the reference are known by construction; zero lag is fixed by the problem, not chosen because it gives the most convenient peak. This is the measurement I want to interpret statistically.

9.5. How significant is the projection at zero lag?

I can derive the exact distribution of T under the assumptions of the synthetic model. I assume independent Gaussian samples with zero mean and known standard deviation σ=1. The reference is deterministic, not estimated from the noise samples. The weighted sum of Gaussian variables is Gaussian, with

\[ E[T] = \frac{A}{2}, \qquad \operatorname{Var}(T) = \frac{\sigma^2}{N^2}\sum_{j} s[j]^2 = \frac{\sigma^2}{2N}. \]

With N=200, the theoretical standard deviation of T is 0.05; that of  is 0.10. To illustrate a two-sided test at 5% under the hypothesis A=0 I use the threshold |T| > 1.96×0.05=0.098. This threshold is illustrative and does not belong to a preregistered experimental protocol. It refers exclusively to the zero lag, fixed and known, with known σ; not to the search for the maximum over several lags, frequencies or phases.

RecordTT / 0.05Comparison with the threshold
Noise only0.096219291.9244Does not exceed 0.098
Sine + noise0.5962192911.9244Exceeds 0.098

The control without signal lies close to the threshold: its value is not zero, but it is compatible with a noise fluctuation. The mixed signal clearly exceeds the theoretical threshold. For Â=1.19244 the two-sided 95% Gaussian confidence interval, under the same assumptions, is  ± 1.96×0.10, that is about [0.9964; 1.3884]. It contains the true amplitude 1, but this measurement is still affected by noise. I do not interpret the 95% as the probability that the single true amplitude lies in the interval once the data have been observed.

The statistical derivation is analytical; the values of the correlations, of the residual and of the amplitude estimates are those produced by the Worksheet. I ran a single realization with a paired control. I have not measured the false positive rate empirically, nor verified the adequacy of the threshold for coloured noise, unknown σ, search over several frequencies or a non-synchronous reference. These are different conditions that require other checks.

10. What I learned for the lock-in

I measured the delay between two pulses, verified the four normalizations, studied the autocorrelation of a finite sinusoidal record and compared noise, sine wave and sum. Moving to the known reference I verified linearity over all lags and derived the amplitude estimate from the mean of the product. I also distinguished the random projection of the noise from the statistically detectable signal in the ideal case with known phase.

Results at a glance

  • 8-sample pulses at 2 kHz: raw correlation maximum 6 at lag +2 (C with B), at lag −2 when the inputs are swapped and at lag 0 in the autocorrelation; estimated delay 0.001 s.
  • Normalizations at lag 2: none 6, biased 0.75, unbiased 1, coefficient 1 (1.0000000000000002 in the native CSV).
  • 200 Hz sine wave, N=40: biased autocorrelation 0.5, 0.375, 0.25 and 0.125 at lags 0, 10, 20 and 30; unbiased 0.5 at the same lags, −0.505636 at lag 36.
  • Gaussian noise σ=1 (seed 33001), N=200: zero-lag value 1.004737 for the noise, 1.697175 for the sum, 0.5 for the sine wave.
  • Correlation with the reference at zero lag: T=0.09621929 without signal (1.92 standard deviations) and 0.59621929 with the signal (11.92); estimated amplitude 1.19243858, 95% interval about [0.9964; 1.3884]; RMS of the linearity residual 1.18 × 10−16.

The correlation at zero lag is the link with the circuit: I do not necessarily need to build all 399 delays. What I need is to multiply the input signal by the reference and keep the mean or slowly varying part of the product. In the next article, Multiplying two signals: mixing, I will study this multiplication directly, the components at the sum and difference frequencies and their meaning for mixing.

#electronics #GX-TXT #signals

Other steps of this project

Leave a Reply

Your email address will not be published. Required fields are marked *