Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
4241 lines (3677 loc) · 175 KB
/
Copy pathapp.py
File metadata and controls
4241 lines (3677 loc) · 175 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Import the required libraries
import logging
import json
from flask import Flask, render_template, request, jsonify, Response, send_file
import threading
import time
from scipy.signal import butter, filtfilt, iirnotch
import numpy as np
from flask_socketio import SocketIO, emit
import mne
from datetime import datetime
import io
import zipfile
import tempfile
import os
import sys
import types
import importlib.util
import csv
import re
from pathlib import Path
# Configure logging for detailed information during execution
logging.basicConfig(level=logging.INFO)
# Initialize Flask app and SocketIO for WebSocket support
app = Flask(__name__)
socketio = SocketIO(
app,
cors_allowed_origins="*",
async_mode="threading",
ping_interval=20,
ping_timeout=60
)
# BrainFlow is imported lazily so the web app can launch in simulation mode even
# when hardware-specific dependencies are missing or incompatible.
def ensure_pkg_resources_compat():
"""Provide the tiny pkg_resources API BrainFlow still uses.
Recent setuptools versions removed pkg_resources. Current BrainFlow still uses
pkg_resources.resource_filename(...) to locate its native libraries, so we
provide a small compatibility shim instead of pinning setuptools to an old
version.
"""
try:
import pkg_resources # noqa: F401
return
except ModuleNotFoundError:
pass
shim = types.ModuleType("pkg_resources")
def resource_filename(package_or_requirement, resource_name):
spec = importlib.util.find_spec(str(package_or_requirement))
if spec is None or spec.origin is None:
raise ModuleNotFoundError(f"Cannot locate package {package_or_requirement!r}")
base = Path(spec.origin).resolve().parent
return str(base / resource_name)
shim.resource_filename = resource_filename
sys.modules["pkg_resources"] = shim
def get_brainflow_api():
ensure_pkg_resources_compat()
try:
from brainflow.board_shim import BoardShim, BrainFlowInputParams, BoardIds, BrainFlowError
except Exception as exc:
raise RuntimeError(
"BrainFlow hardware support is not available in this environment. "
"Install/update BrainFlow, or use Simulation Mode. Original error: "
f"{exc}"
) from exc
return BoardShim, BrainFlowInputParams, BoardIds, BrainFlowError
def create_brainflow_params():
_, BrainFlowInputParams, _, _ = get_brainflow_api()
params = BrainFlowInputParams()
params.serial_port = os.environ.get("PIEEG_SERIAL_PORT", "/dev/spidev0.0")
return params
# ── Acquisition settings ────────────────────────────────────────────────────
# These are the runtime defaults. Most can be changed live via /update-settings
# without restarting the stream.
#
# enabled_channels — how many channels to read and stream.
# • PiEEG board → up to 8
# • DSI-24 headset → up to 24
# • High-density cap → up to 128 (N-Pulse uses caps up to 128 ch)
# The default is 8 (matches the PiEEG hardware we currently have).
MAX_CHANNELS = 128 # hard upper limit for EEG channels (/update-settings)
MAX_EMG_CHANNELS = 16 # hard upper limit for EMG channels (N-Pulse bracelet)
enabled_channels = 8
ref_enabled = True # whether the REF electrode is active (PiEEG)
biasout_enabled = True # whether the BIASOUT/DRL electrode is active (PiEEG)
fs = 250 # sampling frequency in Hz
bandpass_enabled = False
baseline_correction_enabled = False
smoothing_enabled = False
downsample_factor = 1
current_stream_sampling_rate = fs
features_enabled = False
lowcut = 3.0 # bandpass low-cut frequency (Hz)
highcut = 45.0 # bandpass high-cut frequency (Hz)
order = 2 # Butterworth filter order
# Rolling data buffers — resized dynamically in update_collected_buffer()
# whenever the channel count changes. Initialised for 8 channels at startup.
collected_data = [[] for _ in range(enabled_channels)]
collected_data_lock = threading.Lock()
# Per-channel baseline offsets computed during the calibration step.
# Subtracted from each sample when baseline_correction_enabled is True.
calibration_values = [0] * MAX_CHANNELS
spi = None
chip = None
line = None
running = False
simulation_mode = False
simulation_data_file = None
simulation_data_index = 0
simulation_loaded_data = None
simulation_loaded_events = {
"events": [],
"columns": [],
"sidecar": {},
"source_format": None
}
simulation_events_lock = threading.Lock()
current_signal_type = 'eeg'
hardware_source = "pieeg" # pieeg | dsi_lsl
lsl_stream_type = os.environ.get("DSI_LSL_TYPE", "EEG")
lsl_stream_name = os.environ.get("DSI_LSL_NAME", "")
lsl_resolve_timeout = float(os.environ.get("DSI_LSL_TIMEOUT", "8"))
# Which channels of the LSL stream are EEG and which are EMG (1-based, e.g. "1-128",
# "135-139,141-143"). Needed when one amplifier stream carries both (CHUV eegoSports:
# 1-128 EEG, 129-176 bipolar EMG/AUX inputs, 177 TRIGGER). Empty EMG = no EMG.
lsl_eeg_channels = os.environ.get("EEG_LSL_CHANNELS", "auto")
lsl_emg_channels = os.environ.get("EMG_LSL_CHANNELS", "auto")
# Column of the amplifier stream that carries the Arduino triggers (CHUV: 177).
# Empty = no live markers from the stream.
# "auto" (default for all three) = detected from the first seconds of data
# (see detect_channel_layout); an explicit list always wins.
CHANNEL_DETECT_SECONDS = 2.0
lsl_trigger_channel = os.environ.get("TRIGGER_LSL_CHANNEL", "auto")
# EMG hardware backend: Upside Down Labs Chords firmware on Arduino UNO R4.
# Leave EMG_SERIAL_PORT empty to auto-detect (/dev/ttyACM*, COM*, etc.).
emg_serial_port = os.environ.get("EMG_SERIAL_PORT", "").strip()
emg_baud_rate = int(os.environ.get("EMG_BAUD_RATE", "230400"))
emg_sampling_rate = float(os.environ.get("EMG_SAMPLING_RATE", "500"))
emg_chords_channels = int(os.environ.get("EMG_CHANNELS", "6"))
CHORDS_SYNC_BYTE_1 = 0xC7
CHORDS_SYNC_BYTE_2 = 0x7C
CHORDS_END_BYTE = 0x01
CHORDS_HEADER_LEN = 3
CHORDS_PACKET_LEN = CHORDS_HEADER_LEN + (emg_chords_channels * 2) + 1
CHORDS_ADC_MIDPOINT = float(os.environ.get("EMG_ADC_MIDPOINT", "8192")) # UNO R4 uses 14-bit ADC in the Chords sketch
recording_active = False
recording_paused = False
recording_data = []
recording_sampling_rate = fs
recording_start_time = None
recording_metadata = {}
event_markers = []
recording_lock = threading.Lock()
event_lock = threading.Lock()
metadata_cache = {}
# ---------------------------------------------------------------------------
# Dual-stream mode — run EEG and EMG acquisition simultaneously so both
# signals can be visualised side-by-side in the same browser session.
# When dual_stream_mode is True:
# • The primary acquisition thread streams EEG (or whatever the user picked)
# and emits 'eeg_data' Socket.IO events as usual.
# • A secondary background thread runs an independent EMG generator and
# emits 'emg_data' Socket.IO events on a separate channel.
# • The frontend renders two independent chart panels, one per signal.
# ---------------------------------------------------------------------------
dual_stream_mode = False # toggled by /toggle-dual-mode
emg_enabled_channels = 8 # number of EMG channels shown in the second panel (max MAX_EMG_CHANNELS)
# ── File-replay playback controls ───────────────────────────────────────────
# These variables let the user pause and seek within a loaded recording file,
# similar to a video player scrubber. They are only relevant when
# simulation_loaded_data is set and the acquisition thread is running
# read_eeg_data_file_simulation().
#
# stream_paused — when True the replay loop sleeps instead of emitting
# samples, effectively freezing the waveform.
# seek_requested — when True the replay loop jumps to seek_target_sample
# on its next iteration instead of advancing normally.
# seek_target_sample — sample index to jump to (set by /seek-stream).
# replay_total_samples — total sample count of the currently loaded file;
# sent to the frontend so it can size the scrubber.
stream_paused = False
seek_requested = False
seek_target_sample = 0
replay_total_samples = 0 # set when a file is loaded / replay starts
replay_sampling_rate = 0.0 # file's own sampling rate (needed to convert samples ↔ seconds)
playback_lock = threading.Lock() # guards the three seek/pause variables
# Separate rolling buffer for EMG data in dual-stream mode.
# The primary 'collected_data' buffer continues to hold EEG data.
emg_collected_data = [[] for _ in range(8)]
emg_collected_data_lock = threading.Lock()
# EMG recording buffer — filled only while recording_active is True.
# Mirrors recording_data / recording_sampling_rate for the secondary EMG
# stream so both modalities can be exported to BIDS at stop-recording time.
emg_recording_data = []
emg_recording_sampling_rate = 250
filter_state = {
"bandpass": None,
"notch_50": None,
"notch_60": None,
"sampling_rate": fs
}
filter_lock = threading.Lock()
qc_stats = {
"total_chunks": 0,
"bad_chunks": 0,
"bad_channels": 0
}
qc_lock = threading.Lock()
chunk_counter = 0
chunk_counter_lock = threading.Lock()
max_buffer_seconds = 300 # rolling buffer for exports (5 minutes default)
max_record_seconds = 1800 # cap recording buffer to 30 minutes to prevent runaway memory
# BIDS output root; files are written under sub-XX/ses-YY/[eeg|emg|motion]
BIDS_ROOT = os.path.join(os.getcwd(), "bids_output")
BIDS_MODALITY_FOLDERS = {
"eeg": "eeg",
"emg": "emg",
"motion": "motion"
}
BIDS_MODALITY_SUFFIX = {
"eeg": "eeg",
"emg": "emg",
"motion": "motion"
}
def cleanup_spi_gpio():
"""Clean up SPI and GPIO resources"""
global spi, chip, line
try:
logging.info("Cleaning up SPI and GPIO...")
if spi:
spi.close()
spi = None
logging.info("SPI closed.")
if line:
line.release()
line = None
logging.info("GPIO line released.")
if chip:
chip.close()
chip = None
logging.info("GPIO chip closed.")
except Exception as e:
logging.error(f"SPI and GPIO cleanup error: {e}")
def check_gpio_conflicts():
"""Check if GPIO is already in use"""
try:
import gpiod
# Attempt to open the GPIO line to see if it's already in use
test_chip = gpiod.Chip('/dev/gpiochip0')
test_line = test_chip.get_line(26)
test_line.request(consumer="test", type=gpiod.LINE_REQ_EV_FALLING_EDGE)
test_line.release()
test_chip.close()
return False # No conflicts
except Exception:
return True # Conflicts detected
def compute_chunk_size(sampling_rate):
"""Return samples per ~100 ms chunk"""
return max(1, int(sampling_rate * 0.1))
def find_emg_serial_port():
"""Return the configured or auto-detected Arduino/Chords serial port."""
if emg_serial_port:
return emg_serial_port
try:
from serial.tools import list_ports
except ImportError as exc:
raise RuntimeError("pyserial is required for EMG hardware mode. Install it with: pip install pyserial") from exc
ports = list(list_ports.comports())
if not ports:
raise RuntimeError("No serial ports found. Plug in the Arduino UNO R4 and check that it appears as /dev/ttyACM* or COM*.")
# Prefer Arduino/UNO R4-looking ports, otherwise fall back to the first ACM/USB/COM port.
keywords = ("arduino", "uno", "r4", "renesas", "usb serial", "acm", "ch340")
for port in ports:
haystack = " ".join(str(x or "") for x in (port.device, port.description, port.manufacturer, port.product)).lower()
if any(k in haystack for k in keywords):
return port.device
for port in ports:
dev = str(port.device)
if dev.startswith(("/dev/ttyACM", "/dev/ttyUSB", "COM")):
return dev
available = ", ".join(p.device for p in ports)
raise RuntimeError(f"Could not auto-detect Arduino serial port. Available ports: {available}. Set EMG_SERIAL_PORT manually.")
CHORDS_NO_PACKET_TIMEOUT = 3.0 # s without a valid packet -> stop with an error
def read_chords_packet(ser, deadline=None):
"""Read one binary packet emitted by the Chords UNO-R4 firmware.
Packet format: 0xC7 0x7C counter [ch1_hi ch1_lo ... ch6_hi ch6_lo] 0x01.
Returns a list of uint16 ADC values, or None on timeout.
"""
while running:
if deadline is not None and time.time() > deadline:
return None
first = ser.read(1)
if not first:
return None
if first[0] != CHORDS_SYNC_BYTE_1:
continue
second = ser.read(1)
if not second:
return None
if second[0] != CHORDS_SYNC_BYTE_2:
continue
rest = ser.read(CHORDS_PACKET_LEN - 2)
if len(rest) != CHORDS_PACKET_LEN - 2:
return None
packet = bytes([CHORDS_SYNC_BYTE_1, CHORDS_SYNC_BYTE_2]) + rest
if packet[-1] != CHORDS_END_BYTE:
# Bad alignment; continue scanning until the next sync bytes.
continue
values = []
for ch in range(emg_chords_channels):
idx = CHORDS_HEADER_LEN + 2 * ch
values.append((packet[idx] << 8) | packet[idx + 1])
return values
return None
def update_filter_coefficients(sampling_rate):
"""Pre-compute filter coefficients based on current settings and sampling rate"""
global filter_state
with filter_lock:
filter_state["sampling_rate"] = sampling_rate
filter_state["bandpass"] = None
filter_state["notch_50"] = None
filter_state["notch_60"] = None
if bandpass_enabled:
try:
filter_state["bandpass"] = butter(order, [lowcut, highcut], btype='band', fs=sampling_rate)
except Exception as e:
logging.error(f"Failed to compute bandpass filter: {e}")
try:
filter_state["notch_50"] = iirnotch(50, 30, sampling_rate)
filter_state["notch_60"] = iirnotch(60, 30, sampling_rate)
except Exception as e:
logging.error(f"Failed to compute notch filters: {e}")
def apply_filters(data_transposed, sampling_rate, signal_type=None):
"""Apply bandpass and notch filters when enabled.
Parameters
----------
data_transposed : np.ndarray, shape (channels, samples)
Raw chunk of biosignal data.
sampling_rate : float
Sampling frequency in Hz (needed by the filter).
signal_type : str or None
'eeg', 'emg', or 'motion'. Falls back to the global
current_signal_type when None. Used to decide whether
50/60 Hz power-line notch filters are applied — we only
apply them to EEG because EMG has a much wider bandwidth
and the notch would remove real muscle-activity content.
"""
# Resolve which signal type is being processed
sig = signal_type if signal_type is not None else current_signal_type
with filter_lock:
bp_coeffs = filter_state.get("bandpass")
notch_50 = filter_state.get("notch_50")
notch_60 = filter_state.get("notch_60")
# --- Bandpass filter (optional, user-controlled) ---
if bandpass_enabled and bp_coeffs:
b, a = bp_coeffs
try:
min_len = 3 * max(len(a), len(b))
if data_transposed.shape[1] >= min_len:
data_transposed = filtfilt(b, a, data_transposed, axis=1)
else:
logging.debug("Skipping bandpass: chunk too short for filtfilt")
except Exception as e:
logging.error(f"Bandpass filtering failed: {e}")
# --- 50 Hz and 60 Hz notch filters (EEG only) ---
# Power-line interference is a major EEG artefact but notching EMG
# signals would remove muscle energy in those frequency bands.
if sig == 'eeg':
for notch in (notch_50, notch_60):
if notch:
b, a = notch
try:
min_len = 3 * max(len(a), len(b))
if data_transposed.shape[1] >= min_len:
data_transposed = filtfilt(b, a, data_transposed, axis=1)
except Exception as e:
logging.error(f"Notch filtering failed: {e}")
return data_transposed
def describe_software_filters(signal_type=None):
"""Describe every processing step that was applied before data was saved.
IMPORTANT for anyone training a decoder on these recordings:
the recording buffer is fed from process_and_emit_chunk(), which filters,
baseline-corrects, smooths and downsamples *before* anything reaches disk.
The saved EDF therefore contains processed data, not raw samples, and no
raw copy is kept. This function reports exactly what was done, so the
sidecar never claims the file is unprocessed when it isn't.
Returns a dict describing each active stage, or "n/a" if nothing was applied.
"""
sig = signal_type if signal_type is not None else current_signal_type
filters = {}
if bandpass_enabled:
filters["Bandpass filter"] = {
"type": "Butterworth, zero-phase (filtfilt)",
"lower cutoff (Hz)": lowcut,
"upper cutoff (Hz)": highcut,
"order": order
}
# The notch is applied to EEG only — see apply_filters().
if sig == 'eeg':
filters["Notch filter"] = {
"type": "IIR notch, zero-phase (filtfilt)",
"frequencies (Hz)": [50, 60],
"quality factor": 30
}
if baseline_correction_enabled:
filters["Baseline correction"] = (
"Per-channel DC offset subtracted, measured by /calibrate"
)
if smoothing_enabled:
filters["Smoothing"] = {"type": "Moving average", "window (samples)": 3}
if downsample_factor and int(downsample_factor) > 1:
filters["Downsampling"] = {"factor": int(downsample_factor)}
return filters or "n/a"
def software_versions_string():
"""Report the package versions actually installed, not a hard-coded string."""
try:
from importlib.metadata import version, PackageNotFoundError
except ImportError:
return "unknown"
parts = []
for package, label in (
("numpy", "NumPy"),
("scipy", "SciPy"),
("mne", "MNE-Python"),
("brainflow", "BrainFlow"),
):
try:
parts.append(f"{label} {version(package)}")
except PackageNotFoundError:
continue
return ", ".join(parts) if parts else "unknown"
def apply_smoothing(data_transposed, window=3):
"""Optional moving average smoothing"""
if not smoothing_enabled or window <= 1:
return data_transposed
try:
kernel = np.ones(window) / window
return np.apply_along_axis(lambda m: np.convolve(m, kernel, mode='same'), axis=1, arr=data_transposed)
except Exception as e:
logging.error(f"Smoothing failed: {e}")
return data_transposed
def compute_qc_metrics(chunk, sampling_rate, acquisition_ts, server_ts):
"""Compute quick QC stats per channel"""
metrics = []
bad_channels = 0
if chunk.size == 0:
return metrics, bad_channels
means = np.mean(chunk, axis=1)
stds = np.std(chunk, axis=1)
ptps = np.ptp(chunk, axis=1)
for idx in range(chunk.shape[0]):
mean_val = means[idx]
std_val = stds[idx]
ptp_val = ptps[idx]
bad = bool(abs(mean_val) > 500 or ptp_val > 2000 or ptp_val < 0.5)
if bad:
bad_channels += 1
metrics.append({
"channel": f"CH{idx + 1}",
"mean": float(mean_val),
"std": float(std_val),
"ptp": float(ptp_val),
"bad": bad
})
payload = {
"timestamp": server_ts,
"sampling_rate": sampling_rate,
"signal_type": current_signal_type,
"acquisition_timestamp": acquisition_ts,
"latency_ms": (server_ts - acquisition_ts) * 1000 if acquisition_ts else None,
"metrics": metrics
}
socketio.emit('qc_metrics', payload)
with qc_lock:
qc_stats["total_chunks"] += 1
qc_stats["bad_chunks"] += 1 if bad_channels > 0 else 0
qc_stats["bad_channels"] += bad_channels
return metrics, bad_channels
def compute_bandpower(chunk, sfreq, bands):
"""Compute bandpower using a simple Welch estimate"""
if chunk.size == 0:
return {name: [0.0] * chunk.shape[0] for name in bands}
band_results = {name: [] for name in bands}
try:
from scipy.signal import welch
for ch in chunk:
freqs, psd = welch(ch, sfreq, nperseg=min(len(ch), 256))
for band_name, (low, high) in bands.items():
mask = (freqs >= low) & (freqs <= high)
band_results[band_name].append(float(np.trapz(psd[mask], freqs[mask])) if np.any(mask) else 0.0)
except Exception as e:
logging.error(f"Bandpower computation failed: {e}")
band_results = {name: [0.0] * chunk.shape[0] for name in bands}
return band_results
def compute_emg_features(chunk):
"""Compute EMG RMS and MAV per channel"""
if chunk.size == 0:
return [0.0] * chunk.shape[0], [0.0] * chunk.shape[0]
rms = []
mav = []
for ch in chunk:
if len(ch) == 0:
rms.append(0.0)
mav.append(0.0)
continue
rms.append(float(np.sqrt(np.mean(np.square(ch)))))
mav.append(float(np.mean(np.abs(ch))))
return rms, mav
def emit_features(chunk, sampling_rate, acquisition_ts, signal_type=None):
"""Compute and emit per-signal-type features to the frontend.
For EEG → band power (delta / theta / alpha / beta) via Welch PSD.
For EMG → RMS and MAV (Mean Absolute Value) per channel.
For Motion → no features (skipped to reduce Socket.IO traffic).
Parameters
----------
signal_type : str or None
Override the global current_signal_type. Needed in dual-stream
mode so each thread knows which signal it is processing.
"""
if not features_enabled:
return
# Resolve signal type (supports dual-stream where both threads run at once)
sig = signal_type if signal_type is not None else current_signal_type
server_ts = time.time()
payload = {
"timestamp": server_ts,
"sampling_rate": sampling_rate,
"signal_type": sig
}
if sig == 'motion':
# Motion features are not yet implemented — placeholder for future IMU metrics
payload["features"] = {}
elif sig == 'eeg':
# EEG: compute power in each classical frequency band
bands = {
"delta": (1, 4), # slow waves, deep sleep
"theta": (4, 8), # drowsiness, memory
"alpha": (8, 13), # relaxation, closed eyes
"beta": (13, 30) # active thinking, motor activity
}
bandpower = compute_bandpower(chunk, sampling_rate, bands)
payload["features"] = {"bands": bandpower}
else:
# EMG: amplitude-based features — useful for detecting muscle contractions
# RMS = root-mean-square → reflects signal power / muscle force
# MAV = mean absolute value → simpler alternative to RMS, faster to compute
rms, mav = compute_emg_features(chunk)
payload["features"] = {"rms": rms, "mav": mav}
payload["acquisition_timestamp"] = acquisition_ts
payload["latency_ms"] = (server_ts - acquisition_ts) * 1000 if acquisition_ts else None
socketio.emit('features', payload)
def apply_baseline_correction(data_transposed):
"""Subtract calibration baseline when enabled"""
if not baseline_correction_enabled:
return data_transposed
try:
for idx in range(min(len(calibration_values), data_transposed.shape[0])):
data_transposed[idx] = data_transposed[idx] - calibration_values[idx]
except Exception as e:
logging.error(f"Baseline correction failed: {e}")
return data_transposed
def process_and_emit_chunk(data_transposed, sampling_rate, acquisition_ts=None, signal_type=None,
display_channels=None):
"""Central processing pipeline shared by every acquisition path.
This function is the single place where raw samples go through the full
signal-processing chain before being pushed to the browser. All
acquisition threads (hardware, simulation, file-replay, dual-stream EMG)
call this function with their raw data.
Pipeline stages
---------------
1. apply_filters – bandpass + notch (EEG only)
2. apply_baseline_correction – subtract per-channel DC offset
3. apply_smoothing – optional moving-average
4. apply_downsampling – optional decimation to reduce frontend load
After processing:
• Data is pushed to the rolling export buffer (and recording buffer if active).
• A Socket.IO event is emitted to the browser:
'eeg_data' → for EEG / Motion / single-stream EMG
'emg_data' → for the secondary EMG stream in dual-stream mode
• QC metrics and signal features are computed and emitted separately.
Parameters
----------
data_transposed : np.ndarray, shape (channels, samples)
sampling_rate : float — Hz of the incoming data
acquisition_ts : float — Unix timestamp when the hardware captured the chunk
signal_type : str or None — 'eeg', 'emg', 'motion'. Overrides the
global current_signal_type. Required in dual-stream
mode so each thread identifies its own signal correctly.
display_channels: int or None — how many channels to show (Enabled Channels).
The recording buffer always keeps every channel; only the
live view, rolling buffer, QC and features are cut.
"""
if data_transposed is None or data_transposed.size == 0:
return
# Resolve the signal type for this chunk
sig = signal_type if signal_type is not None else current_signal_type
acquisition_ts = acquisition_ts or time.time()
try:
# --- Signal processing chain ---
processed = apply_filters(data_transposed, sampling_rate, signal_type=sig)
processed = apply_baseline_correction(processed)
processed = apply_smoothing(processed)
processed, effective_rate = apply_downsampling(processed, sampling_rate)
all_channels = processed.tolist()
if display_channels and processed.shape[0] > display_channels:
processed = processed[:display_channels]
data_for_frontend = processed.tolist()
# --- Buffer routing ---
# In dual-stream mode the secondary EMG thread writes to a dedicated
# emg_collected_data buffer so it doesn't overwrite the EEG data.
# Both modalities get their own recording buffers so stop-recording can
# export a BIDS-compliant EDF for each signal independently.
if sig == 'emg' and dual_stream_mode:
update_emg_collected_buffer(data_for_frontend, effective_rate)
buffer_emg_recording_data(all_channels, effective_rate)
else:
update_collected_buffer(data_for_frontend, effective_rate)
buffer_recording_data(all_channels, effective_rate)
# --- Emit to frontend ---
# 'emg_data' drives the second chart panel; 'eeg_data' drives the first.
server_ts = time.time()
event_name = 'emg_data' if (sig == 'emg' and dual_stream_mode) else 'eeg_data'
socketio.emit(event_name, {
'channels': data_for_frontend,
'sampling_rate': effective_rate,
'signal_type': sig,
'timestamp': server_ts,
'acquisition_timestamp': acquisition_ts,
'latency_ms': (server_ts - acquisition_ts) * 1000 if acquisition_ts else None,
'downsample_factor': downsample_factor
})
# --- Quality control and feature extraction ---
compute_qc_metrics(processed, effective_rate, acquisition_ts, server_ts)
emit_features(processed, effective_rate, acquisition_ts, signal_type=sig)
with chunk_counter_lock:
global chunk_counter
chunk_counter += 1
if chunk_counter % 20 == 0:
logging.info(f"Streamed {chunk_counter} chunks @ {effective_rate} Hz (signal={sig})")
except Exception as e:
logging.error(f"Chunk processing error: {e}")
raise
def apply_downsampling(data_transposed, sampling_rate):
"""Downsample data and return the effective sampling rate"""
global downsample_factor, current_stream_sampling_rate
factor = max(1, int(downsample_factor))
if factor > 1 and data_transposed.shape[1] > 0:
data_transposed = data_transposed[:, ::factor]
effective_rate = sampling_rate / factor if factor > 0 else sampling_rate
current_stream_sampling_rate = effective_rate
return data_transposed, effective_rate
def buffer_recording_data(chunk, sampling_rate):
"""Append streamed samples to the recording buffer when enabled"""
global recording_data, recording_sampling_rate
if not recording_active or recording_paused:
return
if not chunk:
return
with recording_lock:
if not recording_data or len(recording_data) != len(chunk):
recording_data = [[] for _ in range(len(chunk))]
for idx, channel_data in enumerate(chunk):
recording_data[idx].extend(channel_data)
max_samples = int(sampling_rate * max_record_seconds)
if len(recording_data[idx]) > max_samples:
recording_data[idx] = recording_data[idx][-max_samples:]
recording_sampling_rate = sampling_rate
def buffer_emg_recording_data(chunk, sampling_rate):
"""Append secondary EMG stream samples to emg_recording_data while recording.
This is the dual-stream counterpart of buffer_recording_data. It is only
called from process_and_emit() when sig == 'emg' and dual_stream_mode is
True, ensuring the EEG and EMG recording buffers are always independent and
can be exported as two separate BIDS-compliant modality folders.
"""
global emg_recording_data, emg_recording_sampling_rate
if not recording_active or recording_paused:
return
if not chunk:
return
with recording_lock:
if not emg_recording_data or len(emg_recording_data) != len(chunk):
emg_recording_data = [[] for _ in range(len(chunk))]
for idx, channel_data in enumerate(chunk):
emg_recording_data[idx].extend(channel_data)
max_samples = int(sampling_rate * max_record_seconds)
if len(emg_recording_data[idx]) > max_samples:
emg_recording_data[idx] = emg_recording_data[idx][-max_samples:]
emg_recording_sampling_rate = sampling_rate
def update_collected_buffer(data_for_frontend, sampling_rate):
"""Keep rolling buffer for exports"""
global collected_data
if not data_for_frontend:
return
with collected_data_lock:
if not collected_data or len(collected_data) != len(data_for_frontend):
collected_data = [[] for _ in range(len(data_for_frontend))]
max_samples = int(sampling_rate * max_buffer_seconds)
for idx, channel_data in enumerate(data_for_frontend):
collected_data[idx].extend(channel_data)
if len(collected_data[idx]) > max_samples:
collected_data[idx] = collected_data[idx][-max_samples:]
def update_emg_collected_buffer(data_for_frontend, sampling_rate):
"""Keep a rolling 5-minute buffer of EMG data in dual-stream mode.
This is the EMG equivalent of update_collected_buffer. Having separate
buffers means EEG and EMG data never overwrite each other, and both can
be exported independently after a session.
"""
global emg_collected_data
if not data_for_frontend:
return
with emg_collected_data_lock:
# Resize buffer if the channel count changed (e.g. user adjusted EMG channels)
if not emg_collected_data or len(emg_collected_data) != len(data_for_frontend):
emg_collected_data = [[] for _ in range(len(data_for_frontend))]
max_samples = int(sampling_rate * max_buffer_seconds)
for idx, channel_data in enumerate(data_for_frontend):
emg_collected_data[idx].extend(channel_data)
# Drop oldest samples once the rolling window is full
if len(emg_collected_data[idx]) > max_samples:
emg_collected_data[idx] = emg_collected_data[idx][-max_samples:]
def reset_recording_state():
"""Reset recording-related state (EEG and EMG)"""
global recording_active, recording_paused, recording_data, recording_start_time
global event_markers, recording_metadata, recording_sampling_rate
global emg_recording_data
with recording_lock, event_lock:
recording_active = False
recording_paused = False
recording_data = []
emg_recording_data = []
recording_start_time = None
event_markers = []
recording_metadata = {}
recording_sampling_rate = current_stream_sampling_rate
def create_events_tsv(events):
"""Create BIDS events.tsv content from recorded markers.
`duration` is written as "n/a" when a marker has no measured extent, which
BIDS permits and which is the honest answer. A hard-coded 0 would claim
every event was instantaneous, and a decoder cannot learn from that: to
train a gesture classifier you need to know which *window* of signal the
gesture covered, not just when someone pressed a button.
Give a marker a real duration either by sending `duration` to /add-marker,
or by calling /end-marker when the movement finishes.
"""
lines = ["onset\tduration\ttrial_type\tdescription\n"]
for evt in events:
onset = evt.get('offset', 0)
label = evt.get('label', 'marker')
description = evt.get('description', '')
duration = evt.get('duration')
if isinstance(duration, (int, float)) and duration >= 0:
duration_str = f"{duration:.3f}"
else:
duration_str = "n/a"
lines.append(f"{onset:.3f}\t{duration_str}\t{label}\t{description}\n")
return "".join(lines)
def reset_qc_stats():
"""Reset QC counters"""
with qc_lock:
qc_stats["total_chunks"] = 0
qc_stats["bad_chunks"] = 0
qc_stats["bad_channels"] = 0
def bids_label(value, fallback):
"""Return a non-empty BIDS label"""
label = str(value).strip() if value is not None else ""
return label or fallback
def bids_cache_key(subject_id, session_id, task, run, modality):
"""Stable key for metadata cache"""
return f"sub-{subject_id}_ses-{session_id}_task-{task}_run-{run}_{modality}"
def ensure_dataset_description():
"""Write dataset_description.json at the BIDS root if it is missing.
This file is REQUIRED by BIDS: without it the folder is not a valid
dataset and bids-validator rejects it outright, no matter how correct
the recordings inside are. It is written once and then left alone, so
anyone can edit the authors or licence by hand without it being
overwritten on the next recording.
"""
os.makedirs(BIDS_ROOT, exist_ok=True)
path = os.path.join(BIDS_ROOT, "dataset_description.json")
if os.path.exists(path):
return path
description = {
"Name": "N-Pulse BMI biosignal recordings",
"BIDSVersion": "1.11.0",
"DatasetType": "raw",
"License": "CC-BY-4.0",
"Authors": ["EPFL N-Pulse"],
"Acknowledgements": "Recorded with the N-Pulse visual interface.",
"HowToAcknowledge": "Please cite the EPFL N-Pulse association.",
"GeneratedBy": [{
"Name": "N-Pulse visual interface",
"Description": "Flask + Socket.IO acquisition, visualisation and BIDS export tool."
}]
}
try:
with open(path, "w") as f:
json.dump(description, f, indent=2)
logging.info("Created %s", path)
except Exception as exc:
# A missing description must not abort an ongoing recording.
logging.error("Could not write dataset_description.json: %s", exc)
return path
def ensure_bids_dirs(subject_id, session_id, modality):
"""Ensure BIDS directory structure exists"""
ensure_dataset_description()
modality_folder = BIDS_MODALITY_FOLDERS.get(modality, modality)
modality_dir = os.path.join(
BIDS_ROOT,
f"sub-{subject_id}",
f"ses-{session_id}",
modality_folder
)
os.makedirs(modality_dir, exist_ok=True)
return modality_dir
def bids_basename(subject_id, session_id, task, run, modality):
"""BIDS-compliant base filename (without extension)"""
suffix = BIDS_MODALITY_SUFFIX.get(modality, modality)
return f"sub-{subject_id}_ses-{session_id}_task-{task}_run-{run}_{suffix}"
def bids_core_prefix(subject_id, session_id, task, run):
"""Filename prefix without modality suffix (used for channels/events)"""
return f"sub-{subject_id}_ses-{session_id}_task-{task}_run-{run}"
def coerce_metadata_value(value):
"""Try to coerce stringified numbers/booleans into native types"""
if isinstance(value, (int, float, bool)) or value is None:
return value
if isinstance(value, str):
try:
return json.loads(value)
except Exception:
return value
return value
def get_default_metadata_fields(modality, sampling_rate, n_channels, task_label=None, subject=None, session=None, run=None):
"""Default metadata rows for the metadata editor"""
base_fields = [
# Recording identifiers
{"key": "Subject", "value": subject or "01", "include": True},
{"key": "Session", "value": session or "01", "include": True},
{"key": "TaskName", "value": task_label or "rest", "include": True},
{"key": "Run", "value": run or "01", "include": True},
{"key": "TaskDescription", "value": f"Signal recording during {task_label or 'rest'}", "include": True},
{"key": "Instructions", "value": "Please remain still and relaxed during the recording", "include": True},
{"key": "InstitutionName", "value": "PiEEG Laboratory", "include": True},
# Subject info
{"key": "SubjectAge", "value": "", "include": True},
{"key": "SubjectSex", "value": "", "include": True},
{"key": "SubjectHandedness", "value": "", "include": True},
{"key": "SubjectPosition", "value": "sitting", "include": True},
# Session info
{"key": "SessionDate", "value": "", "include": True},
{"key": "SessionDuration", "value": "", "include": True},
# Device info
{"key": "Manufacturer", "value": "PiEEG", "include": True},
{"key": "ManufacturersModelName", "value": "PiEEG Board", "include": True},
{"key": "DeviceFirmware", "value": "", "include": True},
{"key": "CommunicationProtocol", "value": "SPI", "include": True},
{"key": "SamplingFrequency", "value": sampling_rate, "include": True},
{"key": "PowerLineFrequency", "value": 50, "include": True},
{"key": "SoftwareVersions", "value": software_versions_string(), "include": True},
# Signal and channels
{"key": "RecordingType", "value": "continuous", "include": True},
{"key": "SignalType", "value": modality, "include": True},
{"key": "NumberOfChannels", "value": n_channels, "include": True},
# Environment
{"key": "EnvironmentLocation", "value": "Campus Biotech", "include": True},
{"key": "EnvironmentNoise", "value": "quiet", "include": True},
{"key": "EnvironmentTemperature", "value": "", "include": True},
# Filters
{"key": "FilterHighPass", "value": lowcut, "include": True},
{"key": "FilterLowPass", "value": highcut, "include": True},
{"key": "FilterOrder", "value": order, "include": True}
]
if modality == "eeg":
base_fields.extend([
{"key": "EEGChannelCount", "value": n_channels, "include": True},
{"key": "EEGReference", "value": "Common average reference" if ref_enabled else "n/a", "include": True},
{"key": "EEGGround", "value": "BIASOUT" if biasout_enabled else "n/a", "include": True},
{"key": "EEGPlacementScheme", "value": "Custom", "include": True}
])
elif modality == "emg":
# EMGReference and EMGPlacementScheme are REQUIRED by BIDS for the emg
# data type. They are exposed in the metadata editor so the operator can