1
0

library_ieeg.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. from scipy import io as sio
  2. import mne
  3. import numpy as np
  4. from .utils import upsample_events
  5. # loader for test data
  6. def raw_preprocessing(data_file, finger_model='cylinder', epoch_time=1., fs=1000):
  7. data = sio.loadmat(data_file, simplify_cells=True, squeeze_me=True)
  8. # to double
  9. raw = data['data'].astype(np.float64).T * 0.0298 * 1e-6 # to V
  10. stim_events = data['stim'].astype(np.float64)
  11. # deal with line noise
  12. raw = mne.filter.notch_filter(raw, fs, [60, 120, 180], trans_bandwidth=3, verbose=False)
  13. events = extract_events(stim_events, fs)
  14. # upsampling
  15. events = upsample_events(events, int(epoch_time * fs))
  16. info = mne.create_info([f'ch_{i}' for i in range(raw.shape[0])], sfreq=fs, ch_types='ecog')
  17. # build raw
  18. raw = mne.io.RawArray(raw, info)
  19. annotations = mne.annotations_from_events(events, fs, {1: finger_model, 0: 'rest'})
  20. raw.set_annotations(annotations)
  21. return raw
  22. def extract_events(stim_events, fs=1000.):
  23. diff_stim = np.diff(stim_events)
  24. shift_idx = int(0.5 * fs) # shift by 500 ms, compensate for reaction time
  25. # hand only
  26. onsets = np.flatnonzero(diff_stim == 12) + shift_idx
  27. offsets = np.flatnonzero(diff_stim == -12)
  28. # handle cut
  29. if len(onsets) != len(offsets):
  30. # cut first trial
  31. if offsets[0] <= onsets[0]:
  32. offsets = offsets[1:]
  33. # cut last trial
  34. else:
  35. onsets = onsets[:-1]
  36. rest_onset = offsets + shift_idx
  37. if len(np.unique(offsets - onsets)) > 1:
  38. raise ValueError('Unequal trial length?')
  39. trial_length = (offsets - onsets)[0]
  40. # build events
  41. events = np.zeros((len(onsets) * 2, 3), dtype=np.int64)
  42. events[::2, 0] = onsets
  43. events[:, 1] = trial_length
  44. events[1::2, 0] = rest_onset
  45. events[::2, 2] = 1
  46. return events