Skip to main content

kitchen_views/
sync.rs

1//! Aligning clocks. A camera, an ephys probe and a behaviour rig each count time on their own
2//! oscillator: the same moment reads differently on each, and the difference drifts (tens of
3//! parts per million is common). Rigs share **sync pulses**: one TTL line recorded by every
4//! device. The times of the same pulses on two clocks give the map between them, a line:
5//!
6//! `t_reference = slope · t_source + offset`
7//!
8//! [`fit`] finds it from the two lists of pulse times, without assuming they start together or
9//! that no pulse was lost: the pulses are paired by their intervals (irregular intervals, a
10//! "barcode", pair unambiguously; perfectly regular pulses are paired from the first one), the
11//! line is fitted by least squares, pulses that sit off it are dropped, and the line is fitted
12//! again. The [`Alignment`] keeps how good it is (residuals), so a view can say "aligned to
13//! 0.2 ms" or warn.
14//!
15//! Plain data (serde): an alignment is saved as an artifact beside the sources, with its
16//! provenance, and every app and the orchestrator use the same one.
17
18use serde::{Deserialize, Serialize};
19
20/// A map from a source's clock to the reference clock.
21#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
22pub struct Alignment {
23    pub slope: f64,
24    pub offset: f64,
25    /// Pulses the line was fitted on (0: set by hand).
26    pub pulses: usize,
27    /// Root mean square of the residuals of those pulses, in seconds.
28    pub rms: f64,
29    /// The largest residual, in seconds.
30    pub max: f64,
31    /// The pulses were regular, so they were paired from the first one: right only when both
32    /// recordings saw that first pulse.
33    pub ambiguous: bool,
34}
35
36impl Alignment {
37    /// Same clock.
38    pub fn identity() -> Self {
39        Self::offset(0.0)
40    }
41
42    /// A constant shift (`t_reference = t_source + seconds`), set by hand.
43    pub fn offset(seconds: f64) -> Self {
44        Self { slope: 1.0, offset: seconds, pulses: 0, rms: 0.0, max: 0.0, ambiguous: false }
45    }
46
47    /// A source time on the reference clock.
48    pub fn to_reference(&self, t: f64) -> f64 {
49        self.slope * t + self.offset
50    }
51
52    /// A reference time on the source's clock.
53    pub fn to_source(&self, t: f64) -> f64 {
54        (t - self.offset) / self.slope
55    }
56
57    /// The drift, in parts per million (`+20`: the source's clock runs 20 ppm slow).
58    pub fn drift_ppm(&self) -> f64 {
59        (self.slope - 1.0) * 1e6
60    }
61}
62
63/// Why clocks could not be aligned.
64#[derive(Clone, Debug, PartialEq)]
65pub enum SyncError {
66    /// Fewer than two pulses in one of the lists.
67    TooFewPulses { source: usize, reference: usize },
68    /// No pairing of the pulses agrees with a line.
69    NoMatch,
70}
71
72impl std::fmt::Display for SyncError {
73    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74        match self {
75            SyncError::TooFewPulses { source, reference } => write!(
76                f,
77                "too few sync pulses to align: {source} in the source, {reference} in the reference (at least 2 each)"
78            ),
79            SyncError::NoMatch => {
80                write!(f, "the sync pulses of the two recordings do not line up: are they the same TTL line?")
81            }
82        }
83    }
84}
85
86impl std::error::Error for SyncError {}
87
88/// The rising edges of a digital line sampled at `rate` Hz, in seconds: where it goes from
89/// `false` to `true`. `start` is the time of the first sample.
90pub fn rising_edges(line: &[bool], rate: f64, start: f64) -> Vec<f64> {
91    line.windows(2).enumerate().filter(|(_, w)| !w[0] && w[1]).map(|(i, _)| start + (i + 1) as f64 / rate).collect()
92}
93
94/// The rising edges of an analog channel crossing `threshold` upwards.
95pub fn threshold_edges(samples: &[f32], threshold: f32, rate: f64, start: f64) -> Vec<f64> {
96    let line: Vec<bool> = samples.iter().map(|&v| v > threshold).collect();
97    rising_edges(&line, rate, start)
98}
99
100/// The map from `source` pulse times to `reference` pulse times (both sorted, seconds).
101pub fn fit(source: &[f64], reference: &[f64]) -> Result<Alignment, SyncError> {
102    if source.len() < 2 || reference.len() < 2 {
103        return Err(SyncError::TooFewPulses { source: source.len(), reference: reference.len() });
104    }
105    let (shift, ambiguous) = interval_shift(source, reference);
106    // A first line from the pulses paired by the shift whose intervals agree (a pulse lost on
107    // one side shifts the pairs after it: those intervals disagree and are left out)
108    let paired = |i: usize| {
109        let j = i as isize + shift;
110        (j >= 0 && (j as usize) < reference.len()).then(|| j as usize)
111    };
112    let mut pairs = Vec::new();
113    for i in 0..source.len() - 1 {
114        let (Some(j), Some(k)) = (paired(i), paired(i + 1)) else { continue };
115        let (da, db) = (source[i + 1] - source[i], reference[k] - reference[j]);
116        if (da - db).abs() <= (0.01 * db.abs()).max(1e-3) {
117            pairs.push((source[i], reference[j]));
118            pairs.push((source[i + 1], reference[k]));
119        }
120    }
121    pairs.dedup();
122    let first = least_squares(&pairs).ok_or(SyncError::NoMatch)?;
123    // Paired again by nearness on that line (lost pulses drop out), outliers dropped, refitted
124    let tolerance = 0.25 * median_interval(reference);
125    let near = pair_near(source, reference, &first, tolerance);
126    if near.len() < 2 {
127        return Err(SyncError::NoMatch);
128    }
129    let line = least_squares(&near).ok_or(SyncError::NoMatch)?;
130    let kept = drop_outliers(&near, &line);
131    let line = least_squares(&kept).unwrap_or(line);
132    let residuals: Vec<f64> = kept.iter().map(|&(s, r)| (line.0 * s + line.1 - r).abs()).collect();
133    let rms = (residuals.iter().map(|r| r * r).sum::<f64>() / residuals.len() as f64).sqrt();
134    let max = residuals.iter().copied().fold(0.0, f64::max);
135    Ok(Alignment { slope: line.0, offset: line.1, pulses: kept.len(), rms, max, ambiguous })
136}
137
138/// The index shift `k` pairing `source[i]` with `reference[i + k]` whose intervals agree best,
139/// and whether the intervals were too regular to tell (then `k` pairs the first pulses).
140fn interval_shift(source: &[f64], reference: &[f64]) -> (isize, bool) {
141    let a: Vec<f64> = source.windows(2).map(|w| w[1] - w[0]).collect();
142    let b: Vec<f64> = reference.windows(2).map(|w| w[1] - w[0]).collect();
143    let regular = |v: &[f64]| {
144        let mean = v.iter().sum::<f64>() / v.len() as f64;
145        let sd = (v.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / v.len() as f64).sqrt();
146        sd < 0.01 * mean.abs()
147    };
148    if a.len() < 3 || b.len() < 3 || (regular(&a) && regular(&b)) {
149        return (0, true);
150    }
151    let min_overlap = a.len().min(b.len()).min(5).max(2);
152    // The best agreement; among equal ones (a repeating pattern) the longest overlap
153    let mut best = (0isize, f64::INFINITY, 0usize);
154    for k in -(a.len() as isize - 1)..(b.len() as isize) {
155        let (mut sum, mut n) = (0.0, 0usize);
156        for (i, x) in a.iter().enumerate() {
157            let j = i as isize + k;
158            if j >= 0 && (j as usize) < b.len() {
159                sum += (x - b[j as usize]).abs();
160                n += 1;
161            }
162        }
163        if n < min_overlap {
164            continue;
165        }
166        let score = sum / n as f64;
167        if score < best.1 - 1e-6 || (score <= best.1 + 1e-6 && n > best.2) {
168            best = (k, score, n);
169        }
170    }
171    (best.0, false)
172}
173
174/// For each source pulse, the reference pulse nearest where the line puts it, within `tolerance`.
175fn pair_near(source: &[f64], reference: &[f64], line: &(f64, f64), tolerance: f64) -> Vec<(f64, f64)> {
176    source
177        .iter()
178        .filter_map(|&s| {
179            let t = line.0 * s + line.1;
180            let i = reference.partition_point(|&r| r < t);
181            let candidates = [i.checked_sub(1), Some(i)];
182            let nearest = candidates
183                .into_iter()
184                .flatten()
185                .filter_map(|j| reference.get(j))
186                .min_by(|x, y| (*x - t).abs().total_cmp(&(*y - t).abs()))?;
187            ((nearest - t).abs() <= tolerance).then_some((s, *nearest))
188        })
189        .collect()
190}
191
192/// The pairs within 5 median absolute deviations of the line (all of them when that leaves
193/// fewer than 2).
194fn drop_outliers(pairs: &[(f64, f64)], line: &(f64, f64)) -> Vec<(f64, f64)> {
195    let mut res: Vec<f64> = pairs.iter().map(|&(s, r)| (line.0 * s + line.1 - r).abs()).collect();
196    res.sort_by(f64::total_cmp);
197    let mad = res[res.len() / 2].max(1e-9);
198    let kept: Vec<(f64, f64)> =
199        pairs.iter().copied().filter(|&(s, r)| (line.0 * s + line.1 - r).abs() <= 5.0 * mad).collect();
200    if kept.len() >= 2 { kept } else { pairs.to_vec() }
201}
202
203/// Slope and offset of `r = slope · s + offset`, least squares (centred, for precision with
204/// large times).
205fn least_squares(pairs: &[(f64, f64)]) -> Option<(f64, f64)> {
206    if pairs.len() < 2 {
207        return None;
208    }
209    let n = pairs.len() as f64;
210    let ms = pairs.iter().map(|p| p.0).sum::<f64>() / n;
211    let mr = pairs.iter().map(|p| p.1).sum::<f64>() / n;
212    let sxx: f64 = pairs.iter().map(|p| (p.0 - ms).powi(2)).sum();
213    if sxx <= 0.0 {
214        return None;
215    }
216    let sxy: f64 = pairs.iter().map(|p| (p.0 - ms) * (p.1 - mr)).sum();
217    let slope = sxy / sxx;
218    Some((slope, mr - slope * ms))
219}
220
221fn median_interval(t: &[f64]) -> f64 {
222    let mut d: Vec<f64> = t.windows(2).map(|w| w[1] - w[0]).collect();
223    d.sort_by(f64::total_cmp);
224    d[d.len() / 2]
225}
226
227#[cfg(test)]
228mod tests {
229    use super::*;
230
231    /// Pulses at irregular intervals (a barcode: 0.5 to 1.4 s, pseudo-random), seconds.
232    fn barcode(n: usize) -> Vec<f64> {
233        let (mut t, mut state) = (3.0, 12345u64);
234        (0..n)
235            .map(|_| {
236                state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
237                t += 0.5 + ((state >> 33) % 1000) as f64 * 0.0009;
238                t
239            })
240            .collect()
241    }
242
243    #[test]
244    fn aligns_drifting_clocks_with_lost_pulses() {
245        let src = barcode(60);
246        // The reference runs 25 ppm faster and started 12.3 s earlier; it missed pulse 17, and
247        // the source missed its first four
248        let mut reference: Vec<f64> = src.iter().map(|&s| 1.000_025 * s + 12.3).collect();
249        reference.remove(17);
250        let a = fit(&src[4..], &reference).unwrap();
251        assert!((a.slope - 1.000_025).abs() < 1e-9, "{a:?}");
252        assert!((a.offset - 12.3).abs() < 1e-6, "{a:?}");
253        assert!(!a.ambiguous && a.pulses >= 54 && a.max < 1e-9);
254        assert!((a.drift_ppm() - 25.0).abs() < 1e-3);
255        assert!((a.to_source(a.to_reference(100.0)) - 100.0).abs() < 1e-9);
256    }
257
258    #[test]
259    fn regular_pulses_pair_from_the_first_and_say_so() {
260        let src: Vec<f64> = (0..20).map(|i| i as f64).collect();
261        let reference: Vec<f64> = src.iter().map(|s| s + 0.4).collect();
262        let a = fit(&src, &reference).unwrap();
263        assert!(a.ambiguous);
264        assert!((a.offset - 0.4).abs() < 1e-9);
265        assert!(matches!(fit(&[1.0], &reference), Err(SyncError::TooFewPulses { .. })));
266    }
267
268    #[test]
269    fn edges_rise_where_the_line_goes_high() {
270        let line = [false, false, true, true, false, true];
271        assert_eq!(rising_edges(&line, 10.0, 1.0), vec![1.2, 1.5]);
272        assert_eq!(threshold_edges(&[0.0, 3.0, 0.0], 1.5, 2.0, 0.0), vec![0.5]);
273    }
274}