forked from NeuralEnsemble/python-neo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathneurosharectypesio.py
446 lines (364 loc) · 17.3 KB
/
neurosharectypesio.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
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
"""
NeuroshareIO is a wrap with ctypes of neuroshare DLLs.
Neuroshare is a C API for reading neural data.
Neuroshare also provides a Matlab and a Python API on top of that.
Neuroshare is an open source API but each dll is provided directly by the vendor.
The neo user have to download separtatly the dll on neurosharewebsite:
http://neuroshare.sourceforge.net/
For some vendors (Spike2/CED , Clampfit/Abf, ...), neo.io also provides pure Python
Neo users you should prefer them of course :)
Supported : Read
Author: sgarcia
"""
import sys
import ctypes
import os
import warnings
import numpy as np
import quantities as pq
from neo.io.baseio import BaseIO
from neo.core import Segment, AnalogSignal, SpikeTrain, Event
ns_OK = 0 # Function successful
ns_LIBERROR = -1 # Generic linked library error
ns_TYPEERROR = -2 # Library unable to open file type
ns_FILEERROR = -3 # File access or read error
ns_BADFILE = -4 # Invalid file handle passed to function
ns_BADENTITY = -5 # Invalid or inappropriate entity identifier specified
ns_BADSOURCE = -6 # Invalid source identifier specified
ns_BADINDEX = -7 # Invalid entity index specified
class NeuroshareError(Exception):
def __init__(self, lib, errno):
self.lib = lib
self.errno = errno
pszMsgBuffer = ctypes.create_string_buffer(256)
self.lib.ns_GetLastErrorMsg(pszMsgBuffer, ctypes.c_uint32(256))
errstr = '{}: {}'.format(errno, pszMsgBuffer.value)
Exception.__init__(self, errstr)
class DllWithError():
def __init__(self, lib):
self.lib = lib
def __getattr__(self, attr):
f = getattr(self.lib, attr)
return self.decorate_with_error(f)
def decorate_with_error(self, f):
def func_with_error(*args):
errno = f(*args)
if errno != ns_OK:
raise NeuroshareError(self.lib, errno)
return errno
return func_with_error
class NeurosharectypesIO(BaseIO):
"""
Class for reading file trougth neuroshare API.
The user need the DLLs in the path of the file format.
Usage:
>>> from neo import io
>>> r = io.NeuroshareIO(filename='a_file', dllname=the_name_of_dll)
>>> seg = r.read_segment(import_neuroshare_segment=True)
>>> print seg.analogsignals # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
[<AnalogSignal(array([ -1.77246094e+02, -2.24707031e+02, -2.66015625e+02,
...
>>> print seg.spiketrains
[]
>>> print seg.events
Note:
neuroshare.ns_ENTITY_EVENT: are converted to neo.EventArray
neuroshare.ns_ENTITY_ANALOG: are converted to neo.AnalogSignal
neuroshare.ns_ENTITY_NEURALEVENT: are converted to neo.SpikeTrain
neuroshare.ns_ENTITY_SEGMENT: is something between serie of small AnalogSignal
and Spiketrain with associated waveforms.
It is arbitrarily converted as SpikeTrain.
"""
is_readable = True
is_writable = False
supported_objects = [Segment, AnalogSignal, Event, SpikeTrain]
readable_objects = [Segment]
writeable_objects = []
has_header = False
is_streameable = False
read_params = {Segment: []}
write_params = None
name = 'neuroshare'
extensions = ['mcd']
mode = 'file'
def __init__(self, filename='', dllname=''):
"""
Arguments:
filename: the file to read
ddlname: the name of neuroshare dll to be used for this file
"""
BaseIO.__init__(self)
self.dllname = dllname
self.filename = str(filename)
def read_segment(self, import_neuroshare_segment=True,
lazy=False):
"""
Arguments:
import_neuroshare_segment: import neuroshare segment as SpikeTrain
with associated waveforms or not imported at all.
"""
assert not lazy, 'Do not support lazy'
seg = Segment(file_origin=os.path.basename(self.filename), )
if self.dllname == '':
warnings.warn('No neuroshare dll provided. Can not load data.')
return Segment()
if sys.platform.startswith('win'):
neuroshare = ctypes.windll.LoadLibrary(self.dllname)
elif sys.platform.startswith('linux'):
neuroshare = ctypes.cdll.LoadLibrary(self.dllname)
neuroshare = DllWithError(neuroshare)
# elif sys.platform.startswith('darwin'):
# API version
info = ns_LIBRARYINFO()
neuroshare.ns_GetLibraryInfo(ctypes.byref(info), ctypes.sizeof(info))
seg.annotate(neuroshare_version=str(info.dwAPIVersionMaj)
+ '.' + str(info.dwAPIVersionMin))
# open file
hFile = ctypes.c_uint32(0)
neuroshare.ns_OpenFile(ctypes.c_char_p(bytes(self.filename, 'utf-8')), ctypes.byref(hFile))
fileinfo = ns_FILEINFO()
neuroshare.ns_GetFileInfo(hFile, ctypes.byref(fileinfo), ctypes.sizeof(fileinfo))
# read all entities
for dwEntityID in range(fileinfo.dwEntityCount):
entityInfo = ns_ENTITYINFO()
neuroshare.ns_GetEntityInfo(hFile, dwEntityID, ctypes.byref(
entityInfo), ctypes.sizeof(entityInfo))
# EVENT
if entity_types[entityInfo.dwEntityType] == 'ns_ENTITY_EVENT':
pEventInfo = ns_EVENTINFO()
neuroshare.ns_GetEventInfo(hFile, dwEntityID, ctypes.byref(
pEventInfo), ctypes.sizeof(pEventInfo))
if pEventInfo.dwEventType == 0: # TEXT
pData = ctypes.create_string_buffer(pEventInfo.dwMaxDataLength)
elif pEventInfo.dwEventType == 1: # CVS
pData = ctypes.create_string_buffer(pEventInfo.dwMaxDataLength)
elif pEventInfo.dwEventType == 2: # 8bit
pData = ctypes.c_byte(0)
elif pEventInfo.dwEventType == 3: # 16bit
pData = ctypes.c_int16(0)
elif pEventInfo.dwEventType == 4: # 32bit
pData = ctypes.c_int32(0)
pdTimeStamp = ctypes.c_double(0.)
pdwDataRetSize = ctypes.c_uint32(0)
times = []
labels = []
for dwIndex in range(entityInfo.dwItemCount):
neuroshare.ns_GetEventData(hFile, dwEntityID, dwIndex,
ctypes.byref(pdTimeStamp), ctypes.byref(pData),
ctypes.sizeof(pData), ctypes.byref(pdwDataRetSize))
times.append(pdTimeStamp.value)
labels.append(str(pData.value))
times = times * pq.s
labels = np.array(labels, dtype='U')
ea = Event(name=str(entityInfo.szEntityLabel), times=times, labels=labels)
seg.events.append(ea)
# analog
if entity_types[entityInfo.dwEntityType] == 'ns_ENTITY_ANALOG':
pAnalogInfo = ns_ANALOGINFO()
neuroshare.ns_GetAnalogInfo(hFile, dwEntityID, ctypes.byref(
pAnalogInfo), ctypes.sizeof(pAnalogInfo))
dwIndexCount = entityInfo.dwItemCount
pdwContCount = ctypes.c_uint32(0)
pData = np.zeros((entityInfo.dwItemCount,), dtype='float64')
total_read = 0
while total_read < entityInfo.dwItemCount:
dwStartIndex = ctypes.c_uint32(total_read)
dwStopIndex = ctypes.c_uint32(entityInfo.dwItemCount - total_read)
neuroshare.ns_GetAnalogData(hFile, dwEntityID, dwStartIndex,
dwStopIndex, ctypes.byref(pdwContCount),
pData[total_read:].ctypes.data_as(
ctypes.POINTER(ctypes.c_double)))
total_read += pdwContCount.value
try:
signal = pq.Quantity(pData, units=pAnalogInfo.szUnits.decode(), copy=False)
unit_annotation = None
except LookupError:
signal = pq.Quantity(pData, units='dimensionless', copy=False)
unit_annotation = pAnalogInfo.szUnits.decode()
# t_start
dwIndex = 0
pdTime = ctypes.c_double(0)
neuroshare.ns_GetTimeByIndex(hFile, dwEntityID, dwIndex, ctypes.byref(pdTime))
anaSig = AnalogSignal(signal,
sampling_rate=pAnalogInfo.dSampleRate * pq.Hz,
t_start=pdTime.value * pq.s,
name=str(entityInfo.szEntityLabel),
)
anaSig.annotate(probe_info=str(pAnalogInfo.szProbeInfo))
if unit_annotation is not None:
anaSig.annotate(units=unit_annotation)
seg.analogsignals.append(anaSig)
# segment
if entity_types[
entityInfo.dwEntityType] == 'ns_ENTITY_SEGMENT' and import_neuroshare_segment:
pdwSegmentInfo = ns_SEGMENTINFO()
if not str(entityInfo.szEntityLabel).startswith('spks'):
continue
neuroshare.ns_GetSegmentInfo(hFile, dwEntityID,
ctypes.byref(pdwSegmentInfo),
ctypes.sizeof(pdwSegmentInfo))
nsource = pdwSegmentInfo.dwSourceCount
pszMsgBuffer = ctypes.create_string_buffer(" " * 256)
neuroshare.ns_GetLastErrorMsg(ctypes.byref(pszMsgBuffer), 256)
for dwSourceID in range(pdwSegmentInfo.dwSourceCount):
pSourceInfo = ns_SEGSOURCEINFO()
neuroshare.ns_GetSegmentSourceInfo(hFile, dwEntityID, dwSourceID,
ctypes.byref(pSourceInfo),
ctypes.sizeof(pSourceInfo))
pdTimeStamp = ctypes.c_double(0.)
dwDataBufferSize = pdwSegmentInfo.dwMaxSampleCount * pdwSegmentInfo.dwSourceCount
pData = np.zeros((dwDataBufferSize), dtype='float64')
pdwSampleCount = ctypes.c_uint32(0)
pdwUnitID = ctypes.c_uint32(0)
nsample = int(dwDataBufferSize)
times = np.empty((entityInfo.dwItemCount), dtype='f')
waveforms = np.empty((entityInfo.dwItemCount, nsource, nsample), dtype='f')
for dwIndex in range(entityInfo.dwItemCount):
neuroshare.ns_GetSegmentData(
hFile, dwEntityID, dwIndex,
ctypes.byref(pdTimeStamp),
pData.ctypes.data_as(ctypes.POINTER(ctypes.c_double)),
dwDataBufferSize * 8,
ctypes.byref(pdwSampleCount),
ctypes.byref(pdwUnitID))
times[dwIndex] = pdTimeStamp.value
waveforms[dwIndex, :, :] = pData[:nsample * nsource].reshape(
nsample, nsource).transpose()
sptr = SpikeTrain(times=pq.Quantity(times, units='s', copy=False),
t_stop=times.max(),
waveforms=pq.Quantity(waveforms, units=str(
pdwSegmentInfo.szUnits), copy=False),
left_sweep=nsample / 2.
/ float(pdwSegmentInfo.dSampleRate) * pq.s,
sampling_rate=float(pdwSegmentInfo.dSampleRate) * pq.Hz,
name=str(entityInfo.szEntityLabel),
)
seg.spiketrains.append(sptr)
# neuralevent
if entity_types[entityInfo.dwEntityType] == 'ns_ENTITY_NEURALEVENT':
pNeuralInfo = ns_NEURALINFO()
neuroshare.ns_GetNeuralInfo(hFile, dwEntityID,
ctypes.byref(pNeuralInfo), ctypes.sizeof(pNeuralInfo))
pData = np.zeros((entityInfo.dwItemCount,), dtype='float64')
dwStartIndex = 0
dwIndexCount = entityInfo.dwItemCount
neuroshare.ns_GetNeuralData(hFile, dwEntityID, dwStartIndex,
dwIndexCount,
pData.ctypes.data_as(ctypes.POINTER(ctypes.c_double)))
times = pData * pq.s
t_stop = times.max()
sptr = SpikeTrain(times, t_stop=t_stop,
name=str(entityInfo.szEntityLabel), )
seg.spiketrains.append(sptr)
# close
neuroshare.ns_CloseFile(hFile)
seg.check_relationships()
return seg
# neuroshare structures
class ns_FILEDESC(ctypes.Structure):
_fields_ = [('szDescription', ctypes.c_char * 32),
('szExtension', ctypes.c_char * 8),
('szMacCodes', ctypes.c_char * 8),
('szMagicCode', ctypes.c_char * 16),
]
class ns_LIBRARYINFO(ctypes.Structure):
_fields_ = [('dwLibVersionMaj', ctypes.c_uint32),
('dwLibVersionMin', ctypes.c_uint32),
('dwAPIVersionMaj', ctypes.c_uint32),
('dwAPIVersionMin', ctypes.c_uint32),
('szDescription', ctypes.c_char * 64),
('szCreator', ctypes.c_char * 64),
('dwTime_Year', ctypes.c_uint32),
('dwTime_Month', ctypes.c_uint32),
('dwTime_Day', ctypes.c_uint32),
('dwFlags', ctypes.c_uint32),
('dwMaxFiles', ctypes.c_uint32),
('dwFileDescCount', ctypes.c_uint32),
('FileDesc', ns_FILEDESC * 16),
]
class ns_FILEINFO(ctypes.Structure):
_fields_ = [('szFileType', ctypes.c_char * 32),
('dwEntityCount', ctypes.c_uint32),
('dTimeStampResolution', ctypes.c_double),
('dTimeSpan', ctypes.c_double),
('szAppName', ctypes.c_char * 64),
('dwTime_Year', ctypes.c_uint32),
('dwTime_Month', ctypes.c_uint32),
('dwReserved', ctypes.c_uint32),
('dwTime_Day', ctypes.c_uint32),
('dwTime_Hour', ctypes.c_uint32),
('dwTime_Min', ctypes.c_uint32),
('dwTime_Sec', ctypes.c_uint32),
('dwTime_MilliSec', ctypes.c_uint32),
('szFileComment', ctypes.c_char * 256),
]
class ns_ENTITYINFO(ctypes.Structure):
_fields_ = [('szEntityLabel', ctypes.c_char * 32),
('dwEntityType', ctypes.c_uint32),
('dwItemCount', ctypes.c_uint32),
]
entity_types = {0: 'ns_ENTITY_UNKNOWN',
1: 'ns_ENTITY_EVENT',
2: 'ns_ENTITY_ANALOG',
3: 'ns_ENTITY_SEGMENT',
4: 'ns_ENTITY_NEURALEVENT',
}
class ns_EVENTINFO(ctypes.Structure):
_fields_ = [
('dwEventType', ctypes.c_uint32),
('dwMinDataLength', ctypes.c_uint32),
('dwMaxDataLength', ctypes.c_uint32),
('szCSVDesc', ctypes.c_char * 128),
]
class ns_ANALOGINFO(ctypes.Structure):
_fields_ = [
('dSampleRate', ctypes.c_double),
('dMinVal', ctypes.c_double),
('dMaxVal', ctypes.c_double),
('szUnits', ctypes.c_char * 16),
('dResolution', ctypes.c_double),
('dLocationX', ctypes.c_double),
('dLocationY', ctypes.c_double),
('dLocationZ', ctypes.c_double),
('dLocationUser', ctypes.c_double),
('dHighFreqCorner', ctypes.c_double),
('dwHighFreqOrder', ctypes.c_uint32),
('szHighFilterType', ctypes.c_char * 16),
('dLowFreqCorner', ctypes.c_double),
('dwLowFreqOrder', ctypes.c_uint32),
('szLowFilterType', ctypes.c_char * 16),
('szProbeInfo', ctypes.c_char * 128),
]
class ns_SEGMENTINFO(ctypes.Structure):
_fields_ = [
('dwSourceCount', ctypes.c_uint32),
('dwMinSampleCount', ctypes.c_uint32),
('dwMaxSampleCount', ctypes.c_uint32),
('dSampleRate', ctypes.c_double),
('szUnits', ctypes.c_char * 32),
]
class ns_SEGSOURCEINFO(ctypes.Structure):
_fields_ = [
('dMinVal', ctypes.c_double),
('dMaxVal', ctypes.c_double),
('dResolution', ctypes.c_double),
('dSubSampleShift', ctypes.c_double),
('dLocationX', ctypes.c_double),
('dLocationY', ctypes.c_double),
('dLocationZ', ctypes.c_double),
('dLocationUser', ctypes.c_double),
('dHighFreqCorner', ctypes.c_double),
('dwHighFreqOrder', ctypes.c_uint32),
('szHighFilterType', ctypes.c_char * 16),
('dLowFreqCorner', ctypes.c_double),
('dwLowFreqOrder', ctypes.c_uint32),
('szLowFilterType', ctypes.c_char * 16),
('szProbeInfo', ctypes.c_char * 128),
]
class ns_NEURALINFO(ctypes.Structure):
_fields_ = [
('dwSourceEntityID', ctypes.c_uint32),
('dwSourceUnitID', ctypes.c_uint32),
('szProbeInfo', ctypes.c_char * 128),
]