peachyontop

Acquisition Pipeline

Mar 20th, 2026 (edited)
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 11.06 KB | None | 0 0
  1. /// Cargo.toml dependencies:
  2. /// [dependencies]
  3. /// serialport  = "4"
  4. /// byteorder   = "1"
  5. /// thiserror   = "1"
  6. /// tokio       = { version = "1", features = ["full"] }
  7. /// ringbuf     = "0.3"
  8.  
  9. mod openbci_hal;
  10.  
  11. use openbci_hal::{HalError, OpenBciBoard, SamplePacket};
  12. use std::time::{Duration, Instant};
  13.  
  14. // ── Configuration ─────────────────────────────────────────────────────────────
  15.  
  16. /// How long to record for a baseline/post-stim epoch.
  17. const EPOCH_DURATION: Duration = Duration::from_millis(500);
  18.  
  19. /// OpenBCI Cyton sample rate in Hz (board default, no Daisy).
  20. const SAMPLE_RATE_HZ: f64 = 250.0;
  21.  
  22. /// Estimated samples per epoch (used for Vec pre-allocation).
  23. const SAMPLES_PER_EPOCH: usize = (SAMPLE_RATE_HZ * 0.5) as usize + 8;
  24.  
  25. /// How many biphasic pulses to deliver in the stimulation phase.
  26. const STIM_PULSES: u32 = 10;
  27.  
  28. /// Inter-pulse interval.
  29. const IPI: Duration = Duration::from_millis(50);
  30.  
  31. /// Pulse duration (phase width) in microseconds — 200 µs is a common safe value.
  32. const PULSE_WIDTH_US: u32 = 200;
  33.  
  34. /// Stimulation amplitude sent to HAL for safety validation.
  35. /// Your hardware stimulator must be independently set to this value.
  36. const STIM_AMPLITUDE_UA: f32 = 200.0; // 200 µA — well within cortical safety limits
  37.  
  38. /// GPIO channel index on the Cyton board (0 = D11).
  39. const STIM_GPIO_CHANNEL: u8 = 0;
  40.  
  41. /// Z-score threshold above which a channel is flagged as responding.
  42. const SIGNIFICANCE_THRESHOLD: f64 = 2.0;
  43.  
  44. // ── Epoch type ────────────────────────────────────────────────────────────────
  45.  
  46. /// A recorded epoch: one Vec<f32> per board channel, each holding raw µV samples.
  47. struct Epoch {
  48.     /// `channels[ch][sample]` → µV
  49.     channels: Vec<Vec<f32>>,
  50.     channel_count: usize,
  51.     sample_count: usize,
  52. }
  53.  
  54. impl Epoch {
  55.     fn new(channel_count: usize) -> Self {
  56.         Self {
  57.             channels: vec![Vec::with_capacity(SAMPLES_PER_EPOCH); channel_count],
  58.             channel_count,
  59.             sample_count: 0,
  60.         }
  61.     }
  62.  
  63.     fn push(&mut self, packet: &SamplePacket) {
  64.         for (ch, &v) in packet.channels_uv.iter().enumerate() {
  65.             if ch < self.channel_count {
  66.                 self.channels[ch].push(v);
  67.             }
  68.         }
  69.         self.sample_count += 1;
  70.     }
  71.  
  72.     /// Mean voltage per channel across the epoch.
  73.     fn channel_means(&self) -> Vec<f64> {
  74.         self.channels
  75.             .iter()
  76.             .map(|samples| {
  77.                 let sum: f64 = samples.iter().map(|&v| v as f64).sum();
  78.                 sum / samples.len().max(1) as f64
  79.             })
  80.             .collect()
  81.     }
  82.  
  83.     /// Variance (σ²) per channel across the epoch.
  84.     fn channel_variances(&self) -> Vec<f64> {
  85.         self.channels
  86.             .iter()
  87.             .map(|samples| {
  88.                 let n = samples.len() as f64;
  89.                 if n < 2.0 {
  90.                     return 0.0;
  91.                 }
  92.                 let mean: f64 = samples.iter().map(|&v| v as f64).sum::<f64>() / n;
  93.                 samples
  94.                     .iter()
  95.                     .map(|&v| {
  96.                         let d = v as f64 - mean;
  97.                         d * d
  98.                     })
  99.                     .sum::<f64>()
  100.                     / (n - 1.0) // Bessel-corrected sample variance
  101.             })
  102.             .collect()
  103.     }
  104. }
  105.  
  106. // ── Recording helper ──────────────────────────────────────────────────────────
  107.  
  108. /// Collect samples from `board` for `duration`, returning a filled Epoch.
  109. fn record_epoch(board: &mut OpenBciBoard, duration: Duration) -> Result<Epoch, HalError> {
  110.     let mut epoch = Epoch::new(board.channel_count);
  111.     let deadline = Instant::now() + duration;
  112.  
  113.     while Instant::now() < deadline {
  114.         let packet = board.read_packet()?;
  115.         epoch.push(&packet);
  116.     }
  117.  
  118.     Ok(epoch)
  119. }
  120.  
  121. // ── Variance analysis ─────────────────────────────────────────────────────────
  122.  
  123. #[derive(Debug)]
  124. pub struct VarianceReport {
  125.     /// Per-channel absolute mean shift (post − baseline), in µV.
  126.     pub mean_shift_uv: Vec<f64>,
  127.     /// Per-channel variance in baseline epoch (σ², µV²).
  128.     pub baseline_variance: Vec<f64>,
  129.     /// Per-channel variance in post-stim epoch (σ², µV²).
  130.     pub post_variance: Vec<f64>,
  131.     /// Z-score of mean shift normalised by baseline std deviation.
  132.     /// Values > SIGNIFICANCE_THRESHOLD indicate likely stimulus response.
  133.     pub z_scores: Vec<f64>,
  134.     /// Indices of channels that exceeded the significance threshold.
  135.     pub responding_channels: Vec<usize>,
  136.     /// Mean absolute Z-score across all channels.
  137.     pub mean_z: f64,
  138. }
  139.  
  140. fn compute_variance_report(baseline: &Epoch, post: &Epoch) -> VarianceReport {
  141.     let baseline_means = baseline.channel_means();
  142.     let post_means = post.channel_means();
  143.     let baseline_variance = baseline.channel_variances();
  144.     let post_variance = post.channel_variances();
  145.  
  146.     let n = baseline.channel_count;
  147.     let mut mean_shift_uv = Vec::with_capacity(n);
  148.     let mut z_scores = Vec::with_capacity(n);
  149.     let mut responding_channels = Vec::new();
  150.  
  151.     for ch in 0..n {
  152.         let shift = (post_means[ch] - baseline_means[ch]).abs();
  153.         mean_shift_uv.push(shift);
  154.  
  155.         // σ of the baseline distribution — guard against near-zero noise floors.
  156.         let baseline_std = baseline_variance[ch].sqrt().max(0.01);
  157.         let z = shift / baseline_std;
  158.         z_scores.push(z);
  159.  
  160.         if z > SIGNIFICANCE_THRESHOLD {
  161.             responding_channels.push(ch);
  162.         }
  163.     }
  164.  
  165.     let mean_z = z_scores.iter().sum::<f64>() / n.max(1) as f64;
  166.  
  167.     VarianceReport {
  168.         mean_shift_uv,
  169.         baseline_variance,
  170.         post_variance,
  171.         z_scores,
  172.         responding_channels,
  173.         mean_z,
  174.     }
  175. }
  176.  
  177. fn deliver_stim_train(board: &mut OpenBciBoard) -> Result<(), HalError> {
  178.     println!(
  179.         "  Delivering {} biphasic pulses @ {} µA, {} µs phase width...",
  180.         STIM_PULSES, STIM_AMPLITUDE_UA, PULSE_WIDTH_US
  181.     );
  182.  
  183.     for pulse in 0..STIM_PULSES {
  184.         board.trigger_stim_pulse(STIM_GPIO_CHANNEL, STIM_AMPLITUDE_UA, PULSE_WIDTH_US)?;
  185.         println!("  Pulse {}/{} delivered.", pulse + 1, STIM_PULSES);
  186.         std::thread::sleep(IPI);
  187.     }
  188.  
  189.     Ok(())
  190. }
  191.  
  192. // ── Entry point ───────────────────────────────────────────────────────────────
  193.  
  194. fn main() -> Result<(), HalError> {
  195.     println!("OpenBCI Neural Acquisition Pipeline");
  196.     println!("=====================================");
  197.  
  198.     // Connect — auto-detect FTDI dongle on any available serial port.
  199.     println!("[1/5] Scanning serial ports for OpenBCI Cyton...");
  200.     let mut board = OpenBciBoard::auto_connect(false)?;
  201.     println!(
  202.         "      Connected. Channel count: {}",
  203.         board.channel_count
  204.     );
  205.  
  206.     // Start streaming.
  207.     println!("[2/5] Starting data stream...");
  208.     board.start_stream()?;
  209.  
  210.     // Discard the first 250 ms — the ADS1299 input bias network needs
  211.     // time to settle after stream start.
  212.     println!("      Settling ADS1299 input bias network (250 ms)...");
  213.     let _ = record_epoch(&mut board, Duration::from_millis(250))?;
  214.  
  215.     // ── Stage 1: Baseline ───────────────────────────────────────────────────
  216.     println!("[3/5] Recording baseline epoch ({} ms)...", EPOCH_DURATION.as_millis());
  217.     let baseline = record_epoch(&mut board, EPOCH_DURATION)?;
  218.     println!(
  219.         "      Captured {} samples across {} channels.",
  220.         baseline.sample_count, baseline.channel_count
  221.     );
  222.  
  223.     // Print baseline mean µV per channel.
  224.     let baseline_means = baseline.channel_means();
  225.     println!("      Baseline means (µV):");
  226.     for (ch, mean) in baseline_means.iter().enumerate() {
  227.         println!("        Ch{:02}: {:+.2} µV", ch + 1, mean);
  228.     }
  229.  
  230.     // ── Stage 2: Stimulation ────────────────────────────────────────────────
  231.     println!("[4/5] Stimulation phase...");
  232.     deliver_stim_train(&mut board)?;
  233.  
  234.     // Brief post-stim blank (artefact rejection window — stimulator recovery).
  235.     println!("      Post-stim blank window (10 ms artefact rejection)...");
  236.     let _ = record_epoch(&mut board, Duration::from_millis(10))?;
  237.  
  238.     // ── Stage 3: Post-stimulus epoch ────────────────────────────────────────
  239.     println!("      Recording post-stimulus epoch ({} ms)...", EPOCH_DURATION.as_millis());
  240.     let post_epoch = record_epoch(&mut board, EPOCH_DURATION)?;
  241.     println!(
  242.         "      Captured {} samples.",
  243.         post_epoch.sample_count
  244.     );
  245.  
  246.     board.stop_stream()?;
  247.  
  248.     // ── Stage 4: Analysis ───────────────────────────────────────────────────
  249.     println!("[5/5] Computing variance report...");
  250.     let report = compute_variance_report(&baseline, &post_epoch);
  251.  
  252.     println!("\n── Variance Report ──────────────────────────────────────────");
  253.     println!("  Mean Z-score across all channels: {:.4}", report.mean_z);
  254.     println!("  Significance threshold:           Z > {}", SIGNIFICANCE_THRESHOLD);
  255.     println!(
  256.         "  Responding channels (Z > {:.1}):   {:?}",
  257.         SIGNIFICANCE_THRESHOLD, report.responding_channels
  258.     );
  259.     println!();
  260.     println!("  Ch | Mean Shift (µV) | Baseline σ² (µV²) | Post σ² (µV²)  | Z-score");
  261.     println!("  ───┼────────────────┼───────────────────┼────────────────┼────────");
  262.     for ch in 0..baseline.channel_count {
  263.         println!(
  264.             "  {:2} │ {:>14.3} │ {:>17.3} │ {:>14.3} │ {:>7.3}{}",
  265.             ch + 1,
  266.             report.mean_shift_uv[ch],
  267.             report.baseline_variance[ch],
  268.             report.post_variance[ch],
  269.             report.z_scores[ch],
  270.             if report.responding_channels.contains(&ch) { " ◄" } else { "" }
  271.         );
  272.     }
  273.  
  274.     if board.dropped_packets > 0 {
  275.         eprintln!(
  276.             "\nWarning: {} dropped packet(s) detected via sequence gaps.",
  277.             board.dropped_packets
  278.         );
  279.     }
  280.  
  281.     println!("\nPipeline complete.");
  282.     Ok(())
  283. }
Advertisement
Add Comment
Please, Sign In to add comment