Nathan A. Baune·workshop

This page is also the handout. Press P for a full-screen view. Every figure is simulated in the page; several of them move, and two have sliders.

Where this started

My first exposure to programming and to signals wasn't neuroscience. It was music.

It's sort of wild that no matter how circuitous my path has felt to me, it has all come full loop. I was a music minor learning music composition and signal engineering.

A Max/MSP patch: boxes for audio operations joined by patch cords, with effects such as EQ, distortion, reverb and a compressor down the right side
Max/MSP: a visual programming environment for sound. Each box is an operation and each cord carries a signal or a message.
The Audacity audio editor showing a stereo recording as two waveforms on a time axis
Audacity: an audio editor. A recording is drawn as amplitude against time, the same picture as every trace in this talk.

Part 1

Signals, in time and in frequency

A recording is a representation of numbers and assumptions, or even promises, about when each one was taken. This part is about how the numbers get made, and two ways of looking at them: over time, and by frequency.

Sampling · 1

The body is analog, the file is digital, and a converter sits between them

Analog

A voltage on a wire. It has a value at every instant, and that value can be anything within its range. Muscle and brain potentials, a force plate's output and a photodiode's current are all analog.

Digital

A list of numbers. It has a value only at certain instants, and each value is one of a fixed set of levels. A computer can store, copy and compute on nothing else.

The signal chain inside almost every recording system. Diagram.

The analog-to-digital converter (ADC) is where the continuous signal is turned into discrete numbers. A digital-to-analog converter (DAC) does the reverse, for example when a system offers an "analog out" of data it has already digitized. Each conversion is a place where timing and shape can change.

An "analog output" on a digital system has usually been through an ADC, a processor and a DAC. It is a reconstruction, and it is usually late.

Sampling · 2

An ADC makes two separate cuts: one in time, one in amplitude

Simulated. Grey: the analog signal. Blue: what the converter stores. Move the sliders.

Sample rate: how often

Samples per second, in hertz. It sets the fastest change you can see and the finest timing you can report: at 1000 Hz, one sample is 1 ms.

Bit depth: how finely

The number of levels is 2bits. It sets the smallest change in amplitude you can see. It does nothing for timing.

The two are independent. A 24-bit recording at 100 Hz knows the amplitude very well and the time of an event only to the nearest 10 ms.

Sampling · 3

Sample too slowly and a fast signal shows up as a slow one that was never there

Simulated. A sine wave whose frequency sweeps up and down, sampled at a fixed 10 Hz (dots). Red: the slowest sine that passes through the same dots.
fmax < fs / 2 the Nyquist limit: you need more than two samples per cycle

Above that limit the samples are still perfectly valid numbers. They describe a different, slower signal, and nothing in the file tells you. This is aliasing, and it cannot be undone after the fact.

That is why a low-pass filter sits in front of the ADC. It removes the fast changes that the sample rate cannot represent, before sampling. Part 2 covers filters. The same rule applies when you downsample later: filter first, then drop samples.

Sampling · 4

Bit depth is a ruler: range divided by the number of levels

smallest step = input range / 2bits
Bit depthLevelsStep over a 10 V range (±5 V)
12-bit4,0962.44 mV
16-bit65,536153 µV
24-bit16,777,2160.6 µV
  • Range and gain matter as much as bits. A 50 µV signal on a 16-bit, ±5 V input never moves the converter by one step. This is why biosignals are amplified before conversion.
  • Too much gain clips. A signal beyond the range is recorded as a flat line at the rail. That data is gone.
  • A logic pulse needs one bit. A 0 to 5 V sync signal is fine on any converter. What it needs is sample rate.

The step sizes are arithmetic: 10 V divided by 2 to the power of the bit depth. Real converters have noise, so the usable resolution is somewhat worse than the table.

Waveforms · 1

Sine, square, triangle, sawtooth: a waveform is named for its shape

Simulated. Four waveforms at the same frequency and height. Right: how much of each harmonic each one contains. A harmonic is a sine wave at 1×, 2×, 3× … the waveform's own frequency; the next card explains.
WaveformWhat it doesWhat it is made ofWhere you meet it
SineSwings smoothly up and downOne frequency and nothing elseTest tones; 60 Hz line noise; the building block of the FFT
SquareJumps between two levels and holds eachThe base frequency plus odd harmonics (3×, 5×, 7× …)Digital logic; clocks; triggers; sync pulses
TriangleRamps up, then ramps down at the same rateOdd harmonics that fade quicklySmooth back-and-forth sweeps
SawtoothRamps steadily, then snaps backEvery harmonic (2×, 3×, 4× …)Ramps and sweeps; counters that reset

A pulse is a square wave whose high and low times are not equal. The fraction of time spent high is its duty cycle.

These are general-purpose tools. A music synthesizer builds a new instrument by starting from one of these shapes and filtering it. The same shapes test equipment, drive stimulators, carry digital data, and, in this talk, line up recordings from different devices.

The sharper the corners, the more high harmonics a waveform contains.

Waveforms · 2

A harmonic is a sine wave at a whole-number multiple of the base frequency

Simulated. Three sine waves at 1×, 2× and 3× a base frequency of 100 Hz, and their sum. The dashed lines mark one cycle of the base frequency.

The idea

Take a waveform that repeats 100 times a second. That 100 Hz is its base frequency, also called the fundamental. Its harmonics are sine waves at 200 Hz, 300 Hz, 400 Hz and so on: exactly 2, 3, 4 … times the base.

Each harmonic fits a whole number of cycles into one cycle of the base. So when you add them, the sum still repeats 100 times a second. Only its shape has changed.

Why it matters

  • The mix of harmonics is the shape. A sine has none beyond the base itself. A square, a triangle and a sawtooth are three different recipes.
  • It is what you hear as tone. A flute and a violin playing the same note share a base frequency and differ in their harmonics.
  • It is what a filter acts on. Part 2 shows what happens to a shape when some of its harmonics are removed.

The bar charts on the previous card are these recipes: one bar per harmonic, its height showing how much of that sine wave the shape contains.

Frequency · 1

Any signal is a sum of sine waves

Simulated. A square wave (grey) built by adding sine waves at 1, 3, 5, 7 … times its frequency (purple). Right: the amplitude of each sine in the sum so far.
X[k] = Σn=0N−1 x[n] · e−i 2π k n / N the discrete Fourier transform; the FFT is a fast way to compute it

The transform asks, for each frequency k: how well does a sine wave at this frequency match the data? The answer has a size (how much) and a phase (where in its cycle).

Sharp edges need high frequencies. A square wave contains harmonics without end. Take the high ones away and its corners round off; take the low ones away and only its edges are left. Part 2 does exactly that.

Frequency · 2

A spectrum shows what is hard to see in the trace

Simulated. One second at 500 Hz: a 10 Hz rhythm, 60 Hz line noise and broadband noise.
  • The highest frequency shown is fs/2. Anything above it was aliased before you got here.
  • Frequency resolution is 1 / duration. One second of data gives 1 Hz bins; ten seconds gives 0.1 Hz. Sample rate does not improve it.
  • Anything regular stands out as a peak. A heartbeat, blinking if it is regular enough, or the dynamics across neural populations in EEG each appear at their own frequency.
  • Check a spectrum before choosing a filter. It tells you where the noise is.

Frequency · 3

The FFT assumes your snippet repeats forever, so the ends matter

Simulated. A 10.5 Hz sine, one second long. Left: the snippet placed end to end, as the FFT treats it. Right: its spectrum with no window and with a Hann window.

If the snippet does not hold a whole number of cycles, its ends do not meet. That jump is a sharp edge, and sharp edges spread energy across many frequencies. This is leakage.

A window (Hann, Hamming) fades the ends to zero so they meet. The peak gets a little wider, and the leakage far from it drops by orders of magnitude.

Frequency · 4

A spectrogram is many short FFTs side by side

Simulated. A tone that rises from 5 to 60 Hz over four seconds, with a brief 90 Hz burst. Darker means more power.
Δt · Δf ≥ a constant short windows: good timing, blurry frequency. Long windows: the reverse.

You choose the window length, and with it the trade. No setting gives sharp timing and sharp frequency together, which is why time-frequency plots of a brief event always look smeared along one axis.

Part 2

Filters and correlation

One operation, sliding a set of weights along the data, does most of the work in signal processing. This part covers what it does to a signal, including what your equipment did before you saw anything.

Filters · 1

A filter is a weighted moving window

Simulated. A moving average: each output point (blue) is the mean of the raw samples (grey) inside the shaded window.
y[n] = Σk h[k] · x[n − k] convolution: h is the set of weights, the filter's "kernel"

A moving average uses equal weights. Change the weights and you change which frequencies pass. Every digital filter you use is some version of this sum; the differences are in how the weights were chosen and whether the filter also feeds its own past output back in.

  • Low-pass, high-pass, band-pass and notch filters all work this way. Only the weights differ: all positive for a low-pass; summing to zero for a high-pass.
  • Impulse response: what a filter puts out when you feed it a single blip. It is the filter's set of weights, read out one at a time.
  • FIR, finite impulse response: the filter uses a window of inputs only, so after one blip its output stops when the window has passed. A moving average is FIR.
  • IIR, infinite impulse response: the filter also reuses its own past outputs, so after one blip its output fades away but never strictly ends. It acts like a very long window with fading weights. Butterworth filters are IIR.

Keep this picture. Cross-correlation at the end of this part and the convolution layer of a neural network in part 3 are the same sliding sum.

Filters · 2

Four filters, named for what they let through

Simulated. Top: a slow 0.5 Hz drift, a 10 Hz rhythm, 60 Hz line noise and broadband noise, added together. Below: the same second of data after each filter (second-order, zero-phase).
FilterKeepsTypical use
Low-passBelow the cutoffSmoothing; envelopes; anti-aliasing
High-passAbove the cutoffRemoving drift and electrode offset
Band-passBetween two cutoffsIsolating a rhythm or the EMG band
NotchEverything but one narrow bandRemoving 60 Hz line noise

Filters · 3

"Butterworth" is one recipe for the weights, and each recipe makes a different trade

ButterworthChebyshev (type I, 1 dB ripple)Bessel
Simulated. Three fourth-order low-pass filters with the same 20 Hz cutoff, applied causally. Left: what each does to a step. Right: how much of each frequency each one passes.
FamilyWhat it is built to doWhat you pay
ButterworthPass the wanted frequencies at full size, with no rippleA moderate roll-off, and some overshoot at edges
ChebyshevCut off more steeply for the same orderRipple in what it passes, and more ringing
EllipticCut off most steeply of allRipple on both sides of the cutoff, and the most timing distortion
BesselDelay every frequency by nearly the same amount, so shapes and edges surviveThe gentlest roll-off
  • Butterworth is the usual choice for EMG and movement data because a flat passband leaves the amplitudes you measure alone.
  • "Order" sets how steep the cutoff is: about 6 dB per octave for each order.
  • "Fourth-order zero-lag Butterworth" usually means a second-order filter run forward and then backward. That doubles the order and also lowers the effective cutoff, which needs correcting for.

If the edge is what you care about, as with a sync pulse, the overshoot and ringing in the left panel are the cost to weigh, more than the steepness on the right.

Filters · 4

A filter moves your events in time

rawcausal low-pass (what hardware and real-time software do)zero-phase low-pass (offline, forward and backward)
Simulated. A response that starts at the dashed line, low-passed two ways with the same 6 Hz cutoff.

Causal

Uses only the past, so the output is late. Any filter running in hardware or in real time is causal. The delay depends on the filter and can differ by frequency.

Zero-phase

Run the filter forward, then backward (filtfilt). The delays cancel, but the output now starts before the event. Onset times measured on it are early.

Neither is free. If you measure latency or onset, know which filters the signal has been through, and apply the same ones to every channel you compare.

Filters · 5

Your EMG or EEG system filtered the signal before you saw it

In the hardware

  • A high-pass, from AC coupling, so electrode offsets do not saturate the amplifier.
  • A low-pass in front of the ADC, for anti-aliasing.
  • On many EMG systems, a fixed band-pass in the sensor itself.
  • Sometimes a processed output: rectified, smoothed, or RMS.
  • On wireless systems, a fixed transmission delay.

In the software

  • Display filters: high-pass, low-pass and notch settings in the viewer.
  • On some systems these change only the picture. On others they change what is saved.
  • Export options that filter, rectify or downsample on the way out.

Four questions for every system: What filters are in the hardware? Does the display filter change the saved file? Is any channel rectified or smoothed? What is the fixed delay, and has anyone measured it? There are more than four questions, but they come later.

These are general patterns, not a statement about any one product. The answers are in each system's manual and settings, and the delay is worth measuring yourself.

Filters · 6

Put a square wave through that chain and it stops looking like a square wave

Simulated. One square wave, recorded four ways. Dashed lines mark the true transitions. High-pass 20 Hz; envelope is an 8 Hz low-pass of the rectified trace; both causal.
  • High-pass: the flat tops are "DC", so they are removed. Only the transitions survive, as spikes: up for a rise, down for a fall.
  • Rectified: every spike points up. You can no longer tell a rise from a fall.
  • Envelope: a bump after every transition, smeared and late.

The shape is lost, but the transition times are not. This matters for any sync pulse recorded on an EMG or EEG channel: compare when the edges happen, not what the waveform looks like.

If you send a trigger into a spare EMG channel and it "looks wrong", this is usually why. The channel is doing what it was built to do.

Correlation · 1

Cross-correlation: slide one signal over the other and score the match

Simulated. Blue: a reference pattern. Red: a noisy copy recorded 0.42 s late. Bottom: the match score at each shift. The peak is the delay.
r[τ] = Σn x[n] · y[n + τ] τ is the lag; the τ with the largest r is the best alignment

This is the standard way to find the delay between two recordings of the same thing. It works well when the two copies look alike and when the pattern does not repeat. Part 3 comes back to both conditions.

Correlation · 2

Convolution and correlation are the same sliding sum

Convolution (filtering)

y[n] = Σk h[k] · x[n − k]

The kernel is flipped in time, then slid along the signal.

Cross-correlation (matching)

r[n] = Σk h[k] · x[n + k]

The kernel is slid along as it is, not flipped.

  • Filtering with a kernel is correlating with that kernel reversed.
  • Template matching is filtering with the template reversed. Engineers call this a matched filter.
  • The FFT connects them: convolution in time is multiplication in frequency, which is how long correlations are computed quickly.

One operation, three names. Smoothing a trace, finding a delay and detecting a known shape are all "slide a kernel, multiply, add".

Part 3

Time across devices

Each device counts its own samples with its own clock. The question "when did this happen?" has a different answer in every file, until you give them something in common.

Time · 1

Every device has its own clock, its own start and its own grid

Simulated. 100 ms of four recorders. Each tick is one sample. The dashed line is one event; the dot is the first sample at which each device can know about it.
RecorderRateOne sample lasts
EMG2000 Hz0.5 ms
EEG1000 Hz1 ms
Motion capture100 Hz10 ms
Video30 fps33.3 ms
Video24 fps41.7 ms

The rates here are examples. The point is that the grids do not line up, and a device cannot time an event more finely than its own sample period without extra work.

Time · 2

Four things go wrong, and they look different

Simulated and exaggerated. Grey: the true transitions. Colour: where the recording puts them. The connecting lines show the error for each one.
ErrorWhat it isWhere it comes from
Offset (delay)Everything late by the same amountDifferent start times; filters; wireless links; buffers
JitterEach sample a little early or late, at randomSoftware timing; USB polling; operating-system scheduling
DriftAn error that grows steadilyTwo clocks running at slightly different rates
Dropped or misplaced samplesA sudden step in the errorLost packets; buffer overruns; a frame the camera skipped

Time · 3

Drift: no two crystals tick at the same rate

Calculated, not measured: error = rate difference × elapsed time. The tick marks at the top are exaggerated so the slip is visible.

A device keeps time by counting the vibrations of a quartz crystal. Every crystal is slightly off its nominal frequency, by an amount quoted in parts per million (ppm), and the error changes with temperature and age. Two devices that both say "1000 Hz" are running at two slightly different rates.

tdevice = (1 + ε) · ttrue + b b is the offset; ε is the rate error, e.g. 20 ppm = 0.000020
Rate differenceAfter 10 minutesAfter 1 hourAfter 24 hours
20 ppm12 ms72 ms1.7 s
50 ppm30 ms180 ms4.3 s

For a ten-minute trial this is a few samples. For continuous recording over a day it is seconds, and it is why one alignment at the start cannot be enough.

Time · 4

Dropped samples: the count is right until it isn't

Simulated. Top: when the samples were really taken; six are lost. Bottom: the file, where time is computed as sample number ÷ sample rate.

Most files do not store a time for every sample. They store a start time and a rate, and time is computed from the sample count. If samples go missing and the count carries on, everything afterwards is labelled early, by exactly the missing amount.

A hole

Samples are missing but the timestamps on either side are honest. Nothing needs correcting; you only need to know the gap is there.

A lost-count step

The counter falls behind, so later samples are labelled early. The timeline has to be split and re-anchored at the step.

Misplaced samples are the related case: data arrives in bursts over USB or a network and is stamped on arrival, so the timestamps bunch together even though the sampling was even.

Time · 5

A pulse can fall between a camera's frames and never be recorded

Simulated. Shaded bars: when a 30 fps camera's shutter is open (an 8 ms exposure, chosen for illustration). Three light pulses of different lengths drift across. Blue: at least one frame catches it. Red: none does.
  • A frame is 33.3 ms at 30 fps and 41.7 ms at 24 fps. A pulse must last longer than one whole frame interval to be caught whatever its timing.
  • The same holds for any sampler. A pulse shorter than one sample period can fall between two samples.
  • Some inputs need a minimum duration. Trigger and digital inputs often ignore pulses below a set width. Check the manual for the number.

Design the signal for the slowest device that has to see it.

Time · 6

Some timing is handled for you. Do not assume which

Diagram. Lab Streaming Layer (LSL) stamps a sample when the software hands it over, using that computer's clock. It then measures and corrects the difference between computers' clocks.

What LSL does

  • Each sample is stamped from the sending computer's clock.
  • Every few seconds it exchanges a short burst of packets with each other computer, much as internet time servers do, and estimates the offset between the two clocks.
  • Its documentation puts the remaining error well below a millisecond on modern hardware.

What it cannot do

  • It cannot see anything that happened before the sample reached it: a wireless link, a driver buffer, the device's own processing.
  • A sample that was 20 ms old when it arrived is stamped 20 ms late, precisely.
  • LSL leaves that to whoever writes the stream: there is a header field for a known constant lag, and the reader is expected to subtract it.

Synchronizing the clocks is not the same as knowing when the sample was taken.

This is not a flaw in LSL. It does its part well and says plainly where its part ends.

Time · 7

"Supports LSL" does not mean the delay has been corrected

Many systems now ship with an LSL output. Whether that output subtracts the system's own delay is a separate question, and the answer varies by product.

SystemThe delayWhat happens to it
Cometa wireless EMGA fixed delay, 21 ms on the system used for this work, between a sample being taken and its arrival at the laptopThe vendor's own software corrects for it. A separate LSL bridge has to subtract it too; the one written for this work had to have that added.
An unnamed EEG vendor's wireless EMGData travels through an Android phone and local Wi-FiThe built-in LSL output does not appear to correct for the transmission delay.
  • Ask of every stream: at what point in the chain is the timestamp applied, and what happened before that point?
  • A fixed delay can be subtracted once you know it. A variable one, like Wi-Fi or Bluetooth, is harder: samples often show up in packets, not always in the correct order, and possibly without timestamps. No single number removes that.
  • Measure it. Put a known signal into the sensor and into a wired input together, and compare.

The two examples are from the presenter's own work with those systems, not from the vendors' documentation. Software changes, so check the version you have.

Time · 8

The experiment's own timing is not guaranteed either

Illustrative simulation, not measurements from the platform; the spread is drawn to match the range of about 120 ms seen there. Each dot is one trial's interval between two events that the script asked to be 4 seconds apart.

What happened here

The perturbation platform is driven by an old dedicated controller that can time its operations to better than a millisecond. The 4-second interval between two perturbations was originally timed by the MATLAB script, on Windows 11, which then called the controller.

Timed that way, the interval varied by up to about 120 ms. It was not a clean 4 seconds until the wait was moved onto the controller.

Why

  • A desktop operating system shares the processor among many programs. It makes no promise about when your script runs next.
  • A script's "wait 4 seconds" means "at least 4 seconds, then whenever I am next scheduled".
  • A dedicated controller does one job on a fixed cycle.

Windows is a terrible offender when it comes to precision timing. Mac isn't much better. Plain Linux is better, largely because you have more control. But really, you need a real-time Linux machine or microcontrollers for more precise timing.

Put the timing on the device that can keep it, and record what was delivered, not what was requested.

The intended timing in a script is a plan. The sync channel and the device's own log are the record of what took place.

Time · 9

One sync pulse at the start fixes one of the four errors

What every device recordsOffsetDriftJitterLost samples
One pulse at the startYesNoNoNo
One pulse at the start and one at the endYesIf it is steadyNoNo
A regular square wave throughoutAmbiguousYesYesAmbiguous
A known, non-repeating pattern throughoutYesYesYesYes

A regular square wave gives you an edge to measure every half period, which is good. Its problem is that every cycle looks like every other cycle, so if you are off by one whole period, or lose one, nothing tells you.

Time · 10

A regular wave matches itself at every period; a random one matches once

Simulated. Each signal correlated with a copy of itself at shifts from −3 to +3 seconds.

Slide a regular square wave over itself and it fits perfectly at zero shift, and again one period later, and again one period after that. The correlation cannot tell those alignments apart.

Make the interval lengths unpredictable and only one shift lines everything up. The correlation has a single sharp peak, and any stretch of the signal identifies where in the sequence it came from.

PRE-Sync · 1

PRE-Sync sends every device the same pseudo-random square wave

Generated in the page with the same generator (xorshift32, seed 42) and default ranges as the PRE-Sync firmware. Numbers are interval lengths in ms. Timecode frames are left out here, and this drawing has not been checked edge for edge against the device.
The PRE-Sync box held in one hand: a grey 3D-printed case with a row of eight BNC connectors along one edge, a lit indicator and a neuron design on the lid
The PRE-Sync box: eight BNC outputs, one per recorder.

What it is

  • A small box with BNC outputs. One cable to each recorder.
  • A 0 to 5 V square wave: plain logic levels any system can record.
  • Each HIGH and each LOW lasts between 50 and 500 ms, chosen in 0.25 ms steps.

Why those choices

  • Square: the information is in the edge times, which survive filtering (Filters · 6).
  • 50 ms minimum: longer than a video frame at 24 or 30 fps.
  • Pseudo-random: one correlation peak, and it can be regenerated.

PRE-Sync is open source (MIT licence): firmware for an ATmega32U4 board plus analysis code. The link is on the last card.

PRE-Sync · 2

"Pseudo-random" means it looks random and is completely known

The interval lengths come from a small deterministic generator. Give it the same seed and the same settings and it produces the same sequence, on the device or on your laptop.

So the true waveform does not have to be recorded by a trusted reference device. It can be regenerated from code. Every recorded edge then has a known true time, and the difference between the two is that recorder's error.

This is the ground truth. Recordings are not aligned to each other. Each one is aligned, independently, to the same computed waveform.

# regenerate the expected waveform
python sync_align.py generate \
  --seed 42 --duration 60 \
  --fs 1000 -o expected.csv
  • No reference device to trust.
  • No error passed along a chain of pairwise alignments.
  • Two recordings that never overlapped in time still land on one timeline.

Record the seed, the settings and the firmware's protocol version with the data. Without them the waveform cannot be regenerated.

PRE-Sync · 3

The pattern takes 37 years to repeat

Property, at the default settingsValueHow it was checked
Possible lengths for one interval1,80150 to 500 ms in 0.25 ms steps
Intervals before the sequence repeats4,294,967,295 (232 − 1)The generator was run until it returned to its seed
Time before the sequence repeats37.4 yearsSum of all interval lengths in one cycle: 1,181,115,980 s
Mean interval275.0 msSame run
Longest run of intervals that occurs in two places5All 4,294,967,295 positions in the cycle were compared
Shortest chunk that is never repeated6 intervals (7 edges): 1.65 s on average, 3 s at mostSame comparison
The same, if lengths are known only to the nearest 1 ms8 intervals (9 edges): 2.2 s on average, 4 s at mostSame comparison, with lengths grouped into 1 ms bins

Any six consecutive intervals occur exactly once in the whole 37 years. So a few seconds of recording, taken from anywhere, can be placed at one position in the sequence and nowhere else. Four intervals are already enough for 99.96% of positions.

What this does not cover: it assumes the interval lengths are measured correctly. With timing noise, missing edges or a slow recorder, use a longer stretch. The timecode frames, when they are on, give the position outright.

These figures are for the pseudo-random train alone, computed on a laptop from the firmware's generator; they are properties of the mathematics, not measurements of a device.

PRE-Sync · 4

The wire carries more than high and low: the timing is the message

Schematic, drawn to the frame layout in the PRE-Sync interface document: 5 ms pulses; a 15 ms gap means 0 and a 25 ms gap means 1. The example shows run 138 at 20 seconds; the four checksum bits are computed with the firmware's rule.

The voltage only ever takes two values, but when it changes is continuous, and that is where the information is. Every 10 seconds the train pauses for a short timecode frame in which the gap lengths spell out a number:

  • Run ID (16 bits): which power-up or restart of the box this is.
  • Elapsed seconds (32 bits): how far into that run. The first edge of the frame is exactly on that second.
  • Checksum (4 bits): so a damaged frame is rejected, not misread.

A recording that contains one frame knows where it is in absolute generator time, with no pattern search, and whether two files came from the same run.

The same idea runs through radio time signals and video timecode: a two-level line whose pulse timing encodes a clock reading.

PRE-Sync · 5

The toolkit turns each recording's sync channel into one shared timeline

from align import Source, align_recordings

srcs = [
  Source.from_continuous('vicon', vicon_sync, fs=1000),
  Source.from_edges('eeg', rising_times,
                    polarity='rising'),
  Source.from_continuous('daq', daq_sync, fs=2048),
]
res = align_recordings(srcs, mode='global_time')

The same functions, with the same names, exist in Python, MATLAB and R.

Three ways it locks on

  • Timecode frames: absolute position and run identity.
  • Edge timing: matches transition times. Works after an EMG amplifier has reshaped the wave.
  • Cross-correlation: when both copies still look alike.

What comes back

  • Offset and drift for each recording, with a spread.
  • Gaps and steps, reported and not silently merged.
  • Every recording on generator time, at its own sample rate.

Edge times are in seconds, so recordings at different sample rates compare directly. Nothing has to be resampled to find the alignment.

PRE-Sync · 6

Against a known waveform, the four errors separate on one plot

Simulated. Each dot is one transition: its recorded time minus its true time. Built with a 20 ms offset, 40 ppm drift, 1.5 ms jitter and one block of lost samples.
On the plotIsCorrect it by
Where the line startsOffsetShifting the timestamps
The slope of the lineDriftRescaling the time axis
The scatter about the lineJitterNothing; report it as your timing uncertainty
A step in the lineLost samplesSplitting the timeline at the step

Corrections are made to the time labels. The samples themselves are left alone, and resampling onto a common grid, if you need it, is the last step.

Next · 1

A convolutional network is a stack of learned cross-correlations

In an image network, a small kernel slides over rows and columns of pixels. In a 1-D CNN the same kernel slides along time, over one channel or many. Each kernel is a little template, and its output is how well the signal matches that template at each moment.

That is the sliding sum from part 2. The difference is that the weights are learned from examples, not designed.

  • The library documentation says so directly: PyTorch defines its Conv1d layer with "the valid cross-correlation operator".
  • CNNs on raw time series are established in this field. EEGNet (Lawhern et al., 2018) is a compact example for EEG.
  • Once trained, running one is cheap: a few small kernels and some additions.

Classical alignment is a single hand-made kernel: the known waveform. A network can learn many, including what the waveform looks like after a particular amplifier has reshaped it.

Next · 2

Because the signal can be simulated, the training data is unlimited and already labelled

Diagram of a proposed approach. It has not been built or tested.

The idea

  • Generate the square wave from a seed.
  • Damage it on purpose: add delay, jitter, drift, dropped blocks, filtering, rectification and noise, each by a known amount.
  • Train a small 1-D CNN to recover those amounts.

What would have to be shown

  • That it matches the classical estimate on clean signals.
  • That it does better on reshaped ones.
  • That it holds on real recordings it has never seen.

Most learning problems are short of labelled data. Here the label is free, because the simulation knows exactly what it did to the signal.

In practice

Eight habits for time-series data

  • Keep the raw file. Never overwrite it with a filtered or resampled version.
  • Write down the chain. Sample rate, bit depth, range, gain, and every hardware and software filter.
  • Record a sync channel on every device, for the whole recording, not only at the start.
  • Store what makes the sync signal reproducible: seed, settings and protocol version.
  • Filter before you downsample.
  • Correct time labels, not samples. Resample last, and only if you need a common grid.
  • Apply the same filters to channels you compare in time.
  • Report timing uncertainty. The jitter you measured is a result.

Summary

What to take away

  • A recording is a representation of numbers and assumptions, or even promises, about time. Sample rate sets the timing; bit depth sets the amplitude.
  • Filters change shape and timing, and your equipment applied some before you saw the data.
  • Filtering and cross-correlation are the same sliding sum, and the FFT shows what each one does to a signal.
  • Every device has its own clock. Offset, jitter, drift and lost samples are different problems with different fixes.
  • A known, non-repeating signal recorded on every device lets you measure all four, against a ground truth you can regenerate.

Sources

Read more

  • PRE-Sync: firmware, interface document and analysis toolkit (MIT licence). gitlab.com/neurotrophy-git/arduino-sync-pulse-generator. The signal defaults, frame layout, function names and code examples on this page are from its README, docs/INTERFACE.md and config.h.
  • Lawhern VJ, Solon AJ, Waytowich NR, Gordon SM, Hung CP, Lance BJ (2018). EEGNet: a compact convolutional neural network for EEG-based brain-computer interfaces. Journal of Neural Engineering 15(5):056013. doi:10.1088/1741-2552/aace8c (found through PubMed, PMID 29932424).
  • PyTorch documentation, torch.nn.Conv1d: "where ⋆ is the valid cross-correlation operator". docs.pytorch.org
  • Marsaglia G (2003). Xorshift RNGs. Journal of Statistical Software 8(14). doi:10.18637/jss.v008.i14. The generator family PRE-Sync uses.

All figures are simulated or calculated in this page. No recorded data is shown.