This repository has been archived by the owner on Jun 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 31
/
kilosort2.py
207 lines (166 loc) · 8.23 KB
/
kilosort2.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
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
"""
Important note.
For facilities
kilosort2_path
npy_matlab_path have been removed from args
so only the
klp = os.getenv('KILOSORT_PATH')
npp = os.getenv('NPY_MATLAB_PATH')
is left.
We will be able to add this with a class method
"""
from pathlib import Path
import os
import sys
import shutil
import numpy as np
from spiketoolkit.sorters.basesorter import BaseSorter
import spikeextractors as se
from ..sorter_tools import _call_command_split
def check_if_installed(kilosort2_path, npy_matlab_path):
if kilosort2_path is None or npy_matlab_path is None:
return False
if kilosort2_path is not None and kilosort2_path.startswith('"'):
kilosort2_path = kilosort2_path[1:-1]
kilosort2_path = Path(kilosort2_path).absolut()
if npy_matlab_path is not None and npy_matlab_path.startswith('"'):
npy_matlab_path = npy_matlab_path[1:-1]
npy_matlab_path = Path(npy_matlab_path).absolut()
if (Path(kilosort2_path) / 'master_kilosort.m').is_file() \
or not (Path(npy_matlab_path) / 'npy-matlab' / 'readNPY.m').is_file():
return True
else:
return False
class Kilosort2Sorter(BaseSorter):
"""
"""
sorter_name = 'kilosort2'
installed = check_if_installed(os.getenv('KILOSORT2_PATH'), os.getenv('NPY_MATLAB_PATH'))
kilosort2_path = os.getenv('KILOSORT2_PATH')
npy_matlab_path = os.getenv('NPY_MATLAB_PATH')
_default_params = {
'file_name': None,
'probe_file': None,
'detect_threshold': 5,
'electrode_dimensions': None,
'car': True,
'npy_matlab_path': None,
'kilosort2_path': None,
'minFR': 0.1,
}
installation_mesg = """\nTo use Kilosort run:\n
>>> git clone https://github.com/cortex-lab/KiloSort
>>> git clone https://github.com/kwikteam/npy-matlab\n
and provide the installation path with the 'kilosort2_path' and
npy_matlab_path' arguments or by setting the KILOSORT_PATH
and NPY_MATLAB_PATH environment variables.\n\n
More information on KiloSort at:
https://github.com/MouseLand/Kilosort2
"""
def __init__(self, **kargs):
BaseSorter.__init__(self, **kargs)
@staticmethod
def set_kilosort2_path(kilosort2_path):
os.environ["KILOSORT2_PATH"] = kilosort2_path
Kilosort2Sorter.kilosort2_path = kilosort2_path
Kilosort2Sorter.installed = check_if_installed(Kilosort2Sorter.kilosort2_path, Kilosort2Sorter.npy_matlab_path)
@staticmethod
def set_npy_matlab_path(npy_matlab_path):
os.environ["NPY_MATLAB_PATH"] = npy_matlab_path
Kilosort2Sorter.npy_matlab_path = npy_matlab_path
Kilosort2Sorter.installed = check_if_installed(Kilosort2Sorter.kilosort2_path, Kilosort2Sorter.npy_matlab_path)
def set_params(self, **params):
BaseSorter.set_params(self, **params)
if params.get('npy_matlab_path', None) is not None:
Kilosort2Sorter.set_npy_matlab_path(params['npy_matlab_path'])
else:
Kilosort2Sorter.set_npy_matlab_path(os.getenv('NPY_MATLAB_PATH'))
if params.get('kilosort2_path', None) is not None:
Kilosort2Sorter.set_kilosort2_path(params['kilosort2_path'])
else:
Kilosort2Sorter.set_kilosort2_path(os.getenv('KILOSORT2_PATH'))
def _setup_recording(self, recording, output_folder):
source_dir = Path(__file__).parent
p = self.params
if not check_if_installed(Kilosort2Sorter.kilosort2_path, Kilosort2Sorter.npy_matlab_path):
raise Exception(Kilosort2Sorter.installation_mesg)
# save binary file
if p['file_name'] is None:
self.file_name = Path('recording')
elif p['file_name'].suffix == '.dat':
self.file_name = p['file_name'].stem
p['file_name'] = self.file_name
se.write_binary_dat_format(recording, output_folder / self.file_name, dtype='int16')
# set up kilosort2 config files and run kilosort2 on data
with (source_dir / 'kilosort2_master.txt').open('r') as f:
kilosort2_master = f.readlines()
with (source_dir / 'kilosort2_config.txt').open('r') as f:
kilosort2_config = f.readlines()
with (source_dir / 'kilosort2_channelmap.txt').open('r') as f:
kilosort2_channelmap = f.readlines()
nchan = recording.get_num_channels()
dat_file = (output_folder / (self.file_name.name + '.dat')).absolute()
kilo_thresh = p['detect_threshold']
sample_rate = recording.get_sampling_frequency()
if not Kilosort2Sorter.installed:
raise ImportError('Kilosort2 is not installed', Kilosort2Sorter.installation_mesg)
abs_channel = (output_folder / 'kilosort2_channelmap.m').absolute()
abs_config = (output_folder / 'kilosort2_config.m').absolute()
kilosort2_path = Path(Kilosort2Sorter.kilosort2_path).absolute()
npy_matlab_path = Path(Kilosort2Sorter.npy_matlab_path).absolute() / 'npy-matlab'
if p['car']:
use_car = 1
else:
use_car = 0
kilosort2_master = ''.join(kilosort2_master).format(kilosort2_path, npy_matlab_path,
output_folder, abs_channel, abs_config)
kilosort2_config = ''.join(kilosort2_config).format(nchan, nchan, sample_rate, dat_file, p['minFR'],
kilo_thresh, use_car)
electrode_dimensions = p['electrode_dimensions']
if 'group' in recording.get_channel_property_names():
groups = [recording.get_channel_property(ch, 'group') for ch in recording.get_channel_ids()]
else:
groups = 'ones(1, Nchannels)'
if 'location' not in recording.get_channel_property_names():
print("'location' information is not found. Using linear configuration")
for i_ch, ch in enumerate(recording.get_channel_ids()):
recording.set_channel_property(ch, 'location', [0, i_ch])
positions = np.array([recording.get_channel_property(chan, 'location') for chan in recording.get_channel_ids()])
if electrode_dimensions is None:
kilosort2_channelmap = ''.join(kilosort2_channelmap
).format(nchan,
list(positions[:, 0]),
list(positions[:, 1]),
groups,
sample_rate)
elif len(electrode_dimensions) == 2:
kilosort2_channelmap = ''.join(kilosort2_channelmap
).format(nchan,
list(positions[:, electrode_dimensions[0]]),
list(positions[:, electrode_dimensions[1]]),
groups,
recording.get_sampling_frequency())
else:
raise Exception("Electrode dimension should be a list of len 2")
for fname, value in zip(['kilosort2_master.m', 'kilosort2_config.m',
'kilosort2_channelmap.m'],
[kilosort2_master, kilosort2_config,
kilosort2_channelmap]):
with (output_folder / fname).open('w') as f:
f.writelines(value)
def _run(self, recording, output_folder):
cmd = "matlab -nosplash -nodisplay -r 'run {}; quit;'".format(output_folder / 'kilosort2_master.m')
if self.debug:
print(cmd)
if "win" in sys.platform:
cmd_list = ['matlab', '-nosplash', '-nodisplay', '-wait',
'-r','run {}; quit;'.format(output_folder / 'kilosort2_master.m')]
else:
cmd_list = ['matlab', '-nosplash', '-nodisplay',
'-r', 'run {}; quit;'.format(output_folder / 'kilosort2_master.m')]
# retcode = _run_command_and_print_output_split(cmd_list)
_call_command_split(cmd_list)
@staticmethod
def get_result_from_folder(output_folder):
sorting = se.KiloSortSortingExtractor(output_folder)
return sorting