Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// Cargo.toml dependencies:
- /// [dependencies]
- /// serialport = "4"
- /// byteorder = "1"
- /// thiserror = "1"
- /// tokio = { version = "1", features = ["full"] }
- /// ringbuf = "0.3"
- mod openbci_hal;
- use openbci_hal::{HalError, OpenBciBoard, SamplePacket};
- use std::time::{Duration, Instant};
- // ── Configuration ─────────────────────────────────────────────────────────────
- /// How long to record for a baseline/post-stim epoch.
- const EPOCH_DURATION: Duration = Duration::from_millis(500);
- /// OpenBCI Cyton sample rate in Hz (board default, no Daisy).
- const SAMPLE_RATE_HZ: f64 = 250.0;
- /// Estimated samples per epoch (used for Vec pre-allocation).
- const SAMPLES_PER_EPOCH: usize = (SAMPLE_RATE_HZ * 0.5) as usize + 8;
- /// How many biphasic pulses to deliver in the stimulation phase.
- const STIM_PULSES: u32 = 10;
- /// Inter-pulse interval.
- const IPI: Duration = Duration::from_millis(50);
- /// Pulse duration (phase width) in microseconds — 200 µs is a common safe value.
- const PULSE_WIDTH_US: u32 = 200;
- /// Stimulation amplitude sent to HAL for safety validation.
- /// Your hardware stimulator must be independently set to this value.
- const STIM_AMPLITUDE_UA: f32 = 200.0; // 200 µA — well within cortical safety limits
- /// GPIO channel index on the Cyton board (0 = D11).
- const STIM_GPIO_CHANNEL: u8 = 0;
- /// Z-score threshold above which a channel is flagged as responding.
- const SIGNIFICANCE_THRESHOLD: f64 = 2.0;
- // ── Epoch type ────────────────────────────────────────────────────────────────
- /// A recorded epoch: one Vec<f32> per board channel, each holding raw µV samples.
- struct Epoch {
- /// `channels[ch][sample]` → µV
- channels: Vec<Vec<f32>>,
- channel_count: usize,
- sample_count: usize,
- }
- impl Epoch {
- fn new(channel_count: usize) -> Self {
- Self {
- channels: vec![Vec::with_capacity(SAMPLES_PER_EPOCH); channel_count],
- channel_count,
- sample_count: 0,
- }
- }
- fn push(&mut self, packet: &SamplePacket) {
- for (ch, &v) in packet.channels_uv.iter().enumerate() {
- if ch < self.channel_count {
- self.channels[ch].push(v);
- }
- }
- self.sample_count += 1;
- }
- /// Mean voltage per channel across the epoch.
- fn channel_means(&self) -> Vec<f64> {
- self.channels
- .iter()
- .map(|samples| {
- let sum: f64 = samples.iter().map(|&v| v as f64).sum();
- sum / samples.len().max(1) as f64
- })
- .collect()
- }
- /// Variance (σ²) per channel across the epoch.
- fn channel_variances(&self) -> Vec<f64> {
- self.channels
- .iter()
- .map(|samples| {
- let n = samples.len() as f64;
- if n < 2.0 {
- return 0.0;
- }
- let mean: f64 = samples.iter().map(|&v| v as f64).sum::<f64>() / n;
- samples
- .iter()
- .map(|&v| {
- let d = v as f64 - mean;
- d * d
- })
- .sum::<f64>()
- / (n - 1.0) // Bessel-corrected sample variance
- })
- .collect()
- }
- }
- // ── Recording helper ──────────────────────────────────────────────────────────
- /// Collect samples from `board` for `duration`, returning a filled Epoch.
- fn record_epoch(board: &mut OpenBciBoard, duration: Duration) -> Result<Epoch, HalError> {
- let mut epoch = Epoch::new(board.channel_count);
- let deadline = Instant::now() + duration;
- while Instant::now() < deadline {
- let packet = board.read_packet()?;
- epoch.push(&packet);
- }
- Ok(epoch)
- }
- // ── Variance analysis ─────────────────────────────────────────────────────────
- #[derive(Debug)]
- pub struct VarianceReport {
- /// Per-channel absolute mean shift (post − baseline), in µV.
- pub mean_shift_uv: Vec<f64>,
- /// Per-channel variance in baseline epoch (σ², µV²).
- pub baseline_variance: Vec<f64>,
- /// Per-channel variance in post-stim epoch (σ², µV²).
- pub post_variance: Vec<f64>,
- /// Z-score of mean shift normalised by baseline std deviation.
- /// Values > SIGNIFICANCE_THRESHOLD indicate likely stimulus response.
- pub z_scores: Vec<f64>,
- /// Indices of channels that exceeded the significance threshold.
- pub responding_channels: Vec<usize>,
- /// Mean absolute Z-score across all channels.
- pub mean_z: f64,
- }
- fn compute_variance_report(baseline: &Epoch, post: &Epoch) -> VarianceReport {
- let baseline_means = baseline.channel_means();
- let post_means = post.channel_means();
- let baseline_variance = baseline.channel_variances();
- let post_variance = post.channel_variances();
- let n = baseline.channel_count;
- let mut mean_shift_uv = Vec::with_capacity(n);
- let mut z_scores = Vec::with_capacity(n);
- let mut responding_channels = Vec::new();
- for ch in 0..n {
- let shift = (post_means[ch] - baseline_means[ch]).abs();
- mean_shift_uv.push(shift);
- // σ of the baseline distribution — guard against near-zero noise floors.
- let baseline_std = baseline_variance[ch].sqrt().max(0.01);
- let z = shift / baseline_std;
- z_scores.push(z);
- if z > SIGNIFICANCE_THRESHOLD {
- responding_channels.push(ch);
- }
- }
- let mean_z = z_scores.iter().sum::<f64>() / n.max(1) as f64;
- VarianceReport {
- mean_shift_uv,
- baseline_variance,
- post_variance,
- z_scores,
- responding_channels,
- mean_z,
- }
- }
- fn deliver_stim_train(board: &mut OpenBciBoard) -> Result<(), HalError> {
- println!(
- " Delivering {} biphasic pulses @ {} µA, {} µs phase width...",
- STIM_PULSES, STIM_AMPLITUDE_UA, PULSE_WIDTH_US
- );
- for pulse in 0..STIM_PULSES {
- board.trigger_stim_pulse(STIM_GPIO_CHANNEL, STIM_AMPLITUDE_UA, PULSE_WIDTH_US)?;
- println!(" Pulse {}/{} delivered.", pulse + 1, STIM_PULSES);
- std::thread::sleep(IPI);
- }
- Ok(())
- }
- // ── Entry point ───────────────────────────────────────────────────────────────
- fn main() -> Result<(), HalError> {
- println!("OpenBCI Neural Acquisition Pipeline");
- println!("=====================================");
- // Connect — auto-detect FTDI dongle on any available serial port.
- println!("[1/5] Scanning serial ports for OpenBCI Cyton...");
- let mut board = OpenBciBoard::auto_connect(false)?;
- println!(
- " Connected. Channel count: {}",
- board.channel_count
- );
- // Start streaming.
- println!("[2/5] Starting data stream...");
- board.start_stream()?;
- // Discard the first 250 ms — the ADS1299 input bias network needs
- // time to settle after stream start.
- println!(" Settling ADS1299 input bias network (250 ms)...");
- let _ = record_epoch(&mut board, Duration::from_millis(250))?;
- // ── Stage 1: Baseline ───────────────────────────────────────────────────
- println!("[3/5] Recording baseline epoch ({} ms)...", EPOCH_DURATION.as_millis());
- let baseline = record_epoch(&mut board, EPOCH_DURATION)?;
- println!(
- " Captured {} samples across {} channels.",
- baseline.sample_count, baseline.channel_count
- );
- // Print baseline mean µV per channel.
- let baseline_means = baseline.channel_means();
- println!(" Baseline means (µV):");
- for (ch, mean) in baseline_means.iter().enumerate() {
- println!(" Ch{:02}: {:+.2} µV", ch + 1, mean);
- }
- // ── Stage 2: Stimulation ────────────────────────────────────────────────
- println!("[4/5] Stimulation phase...");
- deliver_stim_train(&mut board)?;
- // Brief post-stim blank (artefact rejection window — stimulator recovery).
- println!(" Post-stim blank window (10 ms artefact rejection)...");
- let _ = record_epoch(&mut board, Duration::from_millis(10))?;
- // ── Stage 3: Post-stimulus epoch ────────────────────────────────────────
- println!(" Recording post-stimulus epoch ({} ms)...", EPOCH_DURATION.as_millis());
- let post_epoch = record_epoch(&mut board, EPOCH_DURATION)?;
- println!(
- " Captured {} samples.",
- post_epoch.sample_count
- );
- board.stop_stream()?;
- // ── Stage 4: Analysis ───────────────────────────────────────────────────
- println!("[5/5] Computing variance report...");
- let report = compute_variance_report(&baseline, &post_epoch);
- println!("\n── Variance Report ──────────────────────────────────────────");
- println!(" Mean Z-score across all channels: {:.4}", report.mean_z);
- println!(" Significance threshold: Z > {}", SIGNIFICANCE_THRESHOLD);
- println!(
- " Responding channels (Z > {:.1}): {:?}",
- SIGNIFICANCE_THRESHOLD, report.responding_channels
- );
- println!();
- println!(" Ch | Mean Shift (µV) | Baseline σ² (µV²) | Post σ² (µV²) | Z-score");
- println!(" ───┼────────────────┼───────────────────┼────────────────┼────────");
- for ch in 0..baseline.channel_count {
- println!(
- " {:2} │ {:>14.3} │ {:>17.3} │ {:>14.3} │ {:>7.3}{}",
- ch + 1,
- report.mean_shift_uv[ch],
- report.baseline_variance[ch],
- report.post_variance[ch],
- report.z_scores[ch],
- if report.responding_channels.contains(&ch) { " ◄" } else { "" }
- );
- }
- if board.dropped_packets > 0 {
- eprintln!(
- "\nWarning: {} dropped packet(s) detected via sequence gaps.",
- board.dropped_packets
- );
- }
- println!("\nPipeline complete.");
- Ok(())
- }
Advertisement
Add Comment
Please, Sign In to add comment