-
Notifications
You must be signed in to change notification settings - Fork 0
/
run_spikesorting.py
165 lines (120 loc) · 6.75 KB
/
run_spikesorting.py
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
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 5 14:02:41 2023 by Guido Meijer
"""
import os
import numpy as np
import json
from datetime import datetime
from probeinterface import Probe
import spikeinterface.extractors as se
import spikeinterface.preprocessing as spre
from spikeinterface.extractors.neuropixels_utils import get_neuropixels_sample_shifts
from spikeinterface.sorters import run_sorter
from spikeinterface.core import extract_waveforms
from spikeinterface.postprocessing import compute_spike_amplitudes, compute_correlograms
from spikeinterface.qualitymetrics import compute_quality_metrics
from spikeinterface.exporters import export_report
# Set data path
SPIKE_SORTER = 'kilosort3'
DATA_FOLDER = 'D:\\NeuropixelData'
# Load in channel locations (only for data collected with OpenEphys GUI < 0.6)
channel_locs = np.load('C:\\Users\\Neuropixel\\Documents\\spikeinterface\\channel_locations.npy')
# Search for spikesort_me.flag
print('Looking for spikesort_me.flag..')
for root, directory, files in os.walk(DATA_FOLDER):
if 'spikesort_me.flag' in files:
print(f'\nFound spikesort_me.flag in {root}')
# OpenEphys recording
if 'continuous.dat' in files:
print('OpenEphys recording detected')
# Load in recording
split_path = root.split(os.sep)[:-5]
oe_path = os.path.join(split_path[0] + os.sep, *split_path)
rec = se.read_openephys(oe_path, stream_id=root[-1])
# Get OpenEphys GUI version
split_path = root.split(os.sep)[:-2]
meta_path = os.path.join(split_path[0] + os.sep, *split_path)
info = json.load(open(os.path.join(meta_path, 'structure.oebin'), 'r'))
print(f'GUI version {info["GUI version"]}')
# For OpenEphys GUI version < 6, we need to add the channel location information
if int(info['GUI version'][2]) < 6:
# Add channel locations
probe = Probe(ndim=2, si_units='um')
probe.set_contacts(positions=channel_locs, shapes='circle', shape_params={'radius': 5})
probe.set_device_channel_indices(np.arange(channel_locs.shape[0]))
rec.set_probe(probe, in_place=True)
# High pass filter
#rec = spre.highpass_filter(rec)
# Correct for inter sample shift
#inter_sample_shifts = get_neuropixels_sample_shifts(384, 12)
#rec = spre.phase_shift(rec, inter_sample_shift=inter_sample_shifts)
"""
# Detect bad channels
bad_channel_ids, channel_labels = spre.detect_bad_channels(rec, method='mad')
rec = rec.remove_channels(bad_channel_ids)
# Do common reference to remove artifacts
rec = spre.common_reference(rec, operator="median", reference="global")
# Correct for inter sample shifts
rec = spre.highpass_filter(rec)
rec = spre.phase_shift(rec, inter_sample_shift=inter_sample_shifts)
# bad channels
bad_channel_ids, channel_labels = spre.detect_bad_channels(rec)
out_channels = rec.channel_ids[channel_labels=="out"]
noise_and_dead_channels = rec.channel_ids[np.isin(channel_labels, ("noise", "dead"))]
# remove out channels
rec = rec.remove_channels(out_channels)
# interpolate the rest
rec = spre.interpolate_bad_channels(rec, noise_and_dead_channels)
rec = spre.highpass_spatial_filter(rec)
# remove interpolated channels after highpass spatial
rec = rec.remove_channels(noise_and_dead_channels)
"""
else:
# Correct for inter sample shifts
rec = spre.highpass_filter(rec)
rec = spre.phase_shift(rec)
# Detect and interpolate bad channels
channel_labels, all_channels = spre.detect_bad_channels(rec)
out_channels = rec.channel_ids[channel_labels=="out"]
noise_and_dead_channels = rec.channel_ids[np.isin(channel_labels, ("noise", "dead"))]
rec = rec.remove_channels(out_channels)
rec = spre.interpolate_bad_channels(rec, noise_and_dead_channels)
rec = spre.highpass_spatial_filter(rec)
# SpikeGLX recording
elif any(s.endswith('ap.bin') for s in files):
print('SpikeGLX recording detected')
# Load in recording
rec = se.read_spikeglx(root, stream_id=f'{root[-5:]}.ap')
# Pre-process
rec = spre.highpass_filter(rec)
rec = spre.phase_shift(rec)
bad_channel_ids, all_channels = spre.detect_bad_channels(rec)
rec = spre.interpolate_bad_channels(rec, bad_channel_ids)
rec = spre.highpass_spatial_filter(rec)
# Run Kilosort3
try:
print(f'Starting spike sorting at {datetime.now().strftime("%H:%M")}')
sort = run_sorter(SPIKE_SORTER, rec, output_folder=os.path.join(root, SPIKE_SORTER),
verbose=True, docker_image=True)
except Exception as err:
print(err)
# Log error to disk
logf = open(os.path.join(root, 'error_log.txt'), 'w')
logf.write(str(err))
logf.close()
# Continue with next recording
continue
"""
# Export to phy
we = extract_waveforms(rec, sort, os.path.join(root, SPIKE_SORTER, 'sorter_output'), sparse=True)
# some computations are done before to control all options
compute_spike_amplitudes(we)
compute_correlograms(we)
compute_quality_metrics(we, metric_names=['snr', 'isi_violation', 'presence_ratio'])
# the export process
export_report(we, output_folder=os.path.join(root, SPIKE_SORTER, 'sorter_report'))
"""
# Delete spikesort_me.flag
print(f'Done! At {datetime.now().strftime("%H:%M")}')
os.remove(os.path.join(root, 'spikesort_me.flag'))