-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathbrpylib.py
1667 lines (1481 loc) · 72 KB
/
brpylib.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
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
# -*- coding: utf-8 -*-
"""
Collection of classes used for reading headers and data from Blackrock files
current version: 2.0.1 --- 11/12/2021
@author: Mitch Frankel - Blackrock Microsystems
Stephen Hou - v1.4.0 edits
David Kluger - v2.0.0 overhaul
Version History:
v1.0.0 - 07/05/2016 - initial release - requires brMiscFxns v1.0.0
v1.1.0 - 07/08/2016 - inclusion of NsxFile.savesubsetnsx() for saving subset of Nsx data to disk4
v1.1.1 - 07/09/2016 - update to NsxFile.savesubsetnsx() for option (not)overwriting subset files if already exist
bug fixes in NsxFile class as reported from beta user
v1.2.0 - 07/12/2016 - bug fixes in NsxFile.savesubsetnsx()
added version control and checking for brMiscFxns
requires brMiscFxns v1.1.0
v1.3.0 - 07/22/2016 - added 'samp_per_s' to NsxFile.getdata() output
added close() method to NsxFile and NevFile objects
NsxFile.getdata() now pre-allocates output['data'] as zeros - speed and safety
v1.3.1 - 08/02/2016 - bug fixes to NsxFile.getdata() for usability with Python 2.7 as reported from beta user
patch for use with multiple NSP sync (overwriting of initial null data from initial data packet)
__future__ import for use with Python 2.7 (division)
minor modifications to allow use of Python 2.6+
v1.3.2 - 08/12/2016 - bug fixes to NsXFile.getdata()
v1.4.0 - 06/22/2017 - inclusion of wave_read parameter to NevFile.getdata() for including/excluding waveform data
v2.0.0 - 04/27/2021 - numpy-based architecture rebuild of NevFile.getdata()
v2.0.1 - 11/12/2021 - fixed indexing error in NevFile.getdata()
Added numpy architecture to NsxFile.getdata()
v2.0.2 - 03/21/2023 - added logic to NsxFile.getdata() for where PTP timestamps are applied to every continuous sample
v2.0.3 - 05/11/2023 - Fixed bug with memmap and file.seek
"""
from __future__ import division # for those using Python 2.6+
from collections import namedtuple
from datetime import datetime
from math import ceil
from os import path as ospath
from struct import calcsize, pack, unpack, unpack_from
import numpy as np
from .brMiscFxns import brmiscfxns_ver, openfilecheck
# Version control set/check
brpylib_ver = "2.0.3"
brmiscfxns_ver_req = "1.2.0"
if brmiscfxns_ver.split(".") < brmiscfxns_ver_req.split("."):
raise Exception(
"brpylib requires brMiscFxns "
+ brmiscfxns_ver_req
+ " or higher, please use latest version"
)
# Patch for use with Python 2.6+
try:
input = raw_input
except NameError:
pass
# Define global variables to remove magic numbers
# <editor-fold desc="Globals">
WARNING_SLEEP_TIME = 5
DATA_PAGING_SIZE = 1024**3
DATA_FILE_SIZE_MIN = 1024**2 * 10
STRING_TERMINUS = "\x00"
UNDEFINED = 0
ELEC_ID_DEF = "all"
START_TIME_DEF = 0
DATA_TIME_DEF = "all"
DOWNSAMPLE_DEF = 1
START_OFFSET_MIN = 0
STOP_OFFSET_MIN = 0
UV_PER_BIT_21 = 0.25
WAVEFORM_SAMPLES_21 = 48
NSX_BASIC_HEADER_BYTES_22 = 314
NSX_EXT_HEADER_BYTES_22 = 66
DATA_BYTE_SIZE = 2
TIMESTAMP_NULL_21 = 0
MAX_SAMP_PER_S = 30000
NO_FILTER = 0
BUTTER_FILTER = 1
SERIAL_MODE = 0
RB2D_MARKER = 1
RB2D_BLOB = 2
RB3D_MARKER = 3
BOUNDARY_2D = 4
MARKER_SIZE = 5
DIGITAL_PACKET_ID = 0
NEURAL_PACKET_ID_MIN = 1
NEURAL_PACKET_ID_MAX = 16384
COMMENT_PACKET_ID = 65535
VIDEO_SYNC_PACKET_ID = 65534
TRACKING_PACKET_ID = 65533
BUTTON_PACKET_ID = 65532
CONFIGURATION_PACKET_ID = 65531
PARALLEL_REASON = 1
PERIODIC_REASON = 64
SERIAL_REASON = 129
LOWER_BYTE_MASK = 255
FIRST_BIT_MASK = 1
SECOND_BIT_MASK = 2
CLASSIFIER_MIN = 1
CLASSIFIER_MAX = 16
CLASSIFIER_NOISE = 255
CHARSET_ANSI = 0
CHARSET_UTF = 1
CHARSET_ROI = 255
COMM_RGBA = 0
COMM_TIME = 1
BUTTON_PRESS = 1
BUTTON_RESET = 2
CHG_NORMAL = 0
CHG_CRITICAL = 1
ENTER_EVENT = 1
EXIT_EVENT = 2
# </editor-fold>
# Define a named tuple that has information about header/packet fields
FieldDef = namedtuple("FieldDef", ["name", "formatStr", "formatFnc"])
# <editor-fold desc="Header processing functions">
def processheaders(curr_file, packet_fields):
"""
:param curr_file: {file} the current BR datafile to be processed
:param packet_fields : {named tuple} the specific binary fields for the given header
:return: a fully unpacked and formatted tuple set of header information
Read a packet from a binary data file and return a list of fields
The amount and format of data read will be specified by the
packet_fields container
"""
# This is a lot in one line. First I pull out all the format strings from
# the basic_header_fields named tuple, then concatenate them into a string
# with '<' at the front (for little endian format)
packet_format_str = "<" + "".join([fmt for name, fmt, fun in packet_fields])
# Calculate how many bytes to read based on the format strings of the header fields
bytes_in_packet = calcsize(packet_format_str)
packet_binary = curr_file.read(bytes_in_packet)
# unpack the binary data from the header based on the format strings of each field.
# This returns a list of data, but it's not always correctly formatted (eg, FileSpec
# is read as ints 2 and 3 but I want it as '2.3'
packet_unpacked = unpack(packet_format_str, packet_binary)
# Create a iterator from the data list. This allows a formatting function
# to use more than one item from the list if needed, and the next formatting
# function can pick up on the correct item in the list
data_iter = iter(packet_unpacked)
# create an empty dictionary from the name field of the packet_fields.
# The loop below will fill in the values with formatted data by calling
# each field's formatting function
packet_formatted = dict.fromkeys([name for name, fmt, fun in packet_fields])
for name, fmt, fun in packet_fields:
packet_formatted[name] = fun(data_iter)
return packet_formatted
def format_filespec(header_list):
return str(next(header_list)) + "." + str(next(header_list)) # eg 2.3
def format_timeorigin(header_list):
year = next(header_list)
month = next(header_list)
_ = next(header_list)
day = next(header_list)
hour = next(header_list)
minute = next(header_list)
second = next(header_list)
millisecond = next(header_list)
return datetime(year, month, day, hour, minute, second, millisecond * 1000)
def format_stripstring(header_list):
string = bytes.decode(next(header_list), "latin-1")
return string.split(STRING_TERMINUS, 1)[0]
def format_none(header_list):
return next(header_list)
def format_freq(header_list):
return str(float(next(header_list)) / 1000) + " Hz"
def format_filter(header_list):
filter_type = next(header_list)
if filter_type == NO_FILTER:
return "none"
elif filter_type == BUTTER_FILTER:
return "butterworth"
def format_charstring(header_list):
return int(next(header_list))
def format_digconfig(header_list):
config = next(header_list) & FIRST_BIT_MASK
if config:
return "active"
else:
return "ignored"
def format_anaconfig(header_list):
config = next(header_list)
if config & FIRST_BIT_MASK:
return "low_to_high"
if config & SECOND_BIT_MASK:
return "high_to_low"
else:
return "none"
def format_digmode(header_list):
dig_mode = next(header_list)
if dig_mode == SERIAL_MODE:
return "serial"
else:
return "parallel"
def format_trackobjtype(header_list):
trackobj_type = next(header_list)
if trackobj_type == UNDEFINED:
return "undefined"
elif trackobj_type == RB2D_MARKER:
return "2D RB markers"
elif trackobj_type == RB2D_BLOB:
return "2D RB blob"
elif trackobj_type == RB3D_MARKER:
return "3D RB markers"
elif trackobj_type == BOUNDARY_2D:
return "2D boundary"
elif trackobj_type == MARKER_SIZE:
return "marker size"
else:
return "error"
def getdigfactor(ext_headers, idx):
max_analog = ext_headers[idx]["MaxAnalogValue"]
min_analog = ext_headers[idx]["MinAnalogValue"]
max_digital = ext_headers[idx]["MaxDigitalValue"]
min_digital = ext_headers[idx]["MinDigitalValue"]
return float(max_analog - min_analog) / float(max_digital - min_digital)
# </editor-fold>
# <editor-fold desc="Header dictionaries">
nev_header_dict = {
"basic": [
FieldDef("FileTypeID", "8s", format_stripstring), # 8 bytes - 8 char array
FieldDef("FileSpec", "2B", format_filespec), # 2 bytes - 2 unsigned char
FieldDef("AddFlags", "H", format_none), # 2 bytes - uint16
FieldDef("BytesInHeader", "I", format_none), # 4 bytes - uint32
FieldDef("BytesInDataPackets", "I", format_none), # 4 bytes - uint32
FieldDef("TimeStampResolution", "I", format_none), # 4 bytes - uint32
FieldDef("SampleTimeResolution", "I", format_none), # 4 bytes - uint32
FieldDef("TimeOrigin", "8H", format_timeorigin), # 16 bytes - 8 x uint16
FieldDef(
"CreatingApplication", "32s", format_stripstring
), # 32 bytes - 32 char array
FieldDef("Comment", "256s", format_stripstring), # 256 bytes - 256 char array
FieldDef("NumExtendedHeaders", "I", format_none),
], # 4 bytes - uint32
"ARRAYNME": FieldDef(
"ArrayName", "24s", format_stripstring
), # 24 bytes - 24 char array
"ECOMMENT": FieldDef(
"ExtraComment", "24s", format_stripstring
), # 24 bytes - 24 char array
"CCOMMENT": FieldDef(
"ContComment", "24s", format_stripstring
), # 24 bytes - 24 char array
"MAPFILE": FieldDef(
"MapFile", "24s", format_stripstring
), # 24 bytes - 24 char array
"NEUEVWAV": [
FieldDef("ElectrodeID", "H", format_none), # 2 bytes - uint16
FieldDef(
"PhysicalConnector", "B", format_charstring
), # 1 byte - 1 unsigned char
FieldDef("ConnectorPin", "B", format_charstring), # 1 byte - 1 unsigned char
FieldDef("DigitizationFactor", "H", format_none), # 2 bytes - uint16
FieldDef("EnergyThreshold", "H", format_none), # 2 bytes - uint16
FieldDef("HighThreshold", "h", format_none), # 2 bytes - int16
FieldDef("LowThreshold", "h", format_none), # 2 bytes - int16
FieldDef(
"NumSortedUnits", "B", format_charstring
), # 1 byte - 1 unsigned char
FieldDef(
"BytesPerWaveform", "B", format_charstring
), # 1 byte - 1 unsigned char
FieldDef("SpikeWidthSamples", "H", format_none), # 2 bytes - uint16
FieldDef("EmptyBytes", "8s", format_none),
], # 8 bytes - empty
"NEUEVLBL": [
FieldDef("ElectrodeID", "H", format_none), # 2 bytes - uint16
FieldDef("Label", "16s", format_stripstring), # 16 bytes - 16 char array
FieldDef("EmptyBytes", "6s", format_none),
], # 6 bytes - empty
"NEUEVFLT": [
FieldDef("ElectrodeID", "H", format_none), # 2 bytes - uint16
FieldDef("HighFreqCorner", "I", format_freq), # 4 bytes - uint32
FieldDef("HighFreqOrder", "I", format_none), # 4 bytes - uint32
FieldDef("HighFreqType", "H", format_filter), # 2 bytes - uint16
FieldDef("LowFreqCorner", "I", format_freq), # 4 bytes - uint32
FieldDef("LowFreqOrder", "I", format_none), # 4 bytes - uint32
FieldDef("LowFreqType", "H", format_filter), # 2 bytes - uint16
FieldDef("EmptyBytes", "2s", format_none),
], # 2 bytes - empty
"DIGLABEL": [
FieldDef("Label", "16s", format_stripstring), # 16 bytes - 16 char array
FieldDef("Mode", "?", format_digmode), # 1 byte - boolean
FieldDef("EmptyBytes", "7s", format_none),
], # 7 bytes - empty
"NSASEXEV": [
FieldDef("Frequency", "H", format_none), # 2 bytes - uint16
FieldDef(
"DigitalInputConfig", "B", format_digconfig
), # 1 byte - 1 unsigned char
FieldDef(
"AnalogCh1Config", "B", format_anaconfig
), # 1 byte - 1 unsigned char
FieldDef("AnalogCh1DetectVal", "h", format_none), # 2 bytes - int16
FieldDef(
"AnalogCh2Config", "B", format_anaconfig
), # 1 byte - 1 unsigned char
FieldDef("AnalogCh2DetectVal", "h", format_none), # 2 bytes - int16
FieldDef(
"AnalogCh3Config", "B", format_anaconfig
), # 1 byte - 1 unsigned char
FieldDef("AnalogCh3DetectVal", "h", format_none), # 2 bytes - int16
FieldDef(
"AnalogCh4Config", "B", format_anaconfig
), # 1 byte - 1 unsigned char
FieldDef("AnalogCh4DetectVal", "h", format_none), # 2 bytes - int16
FieldDef(
"AnalogCh5Config", "B", format_anaconfig
), # 1 byte - 1 unsigned char
FieldDef("AnalogCh5DetectVal", "h", format_none), # 2 bytes - int16
FieldDef("EmptyBytes", "6s", format_none),
], # 2 bytes - empty
"VIDEOSYN": [
FieldDef("VideoSourceID", "H", format_none), # 2 bytes - uint16
FieldDef("VideoSource", "16s", format_stripstring), # 16 bytes - 16 char array
FieldDef("FrameRate", "f", format_none), # 4 bytes - single float
FieldDef("EmptyBytes", "2s", format_none),
], # 2 bytes - empty
"TRACKOBJ": [
FieldDef("TrackableType", "H", format_trackobjtype), # 2 bytes - uint16
FieldDef("TrackableID", "I", format_none), # 4 bytes - uint32
# FieldDef('PointCount', 'H', format_none), # 2 bytes - uint16
FieldDef("VideoSource", "16s", format_stripstring), # 16 bytes - 16 char array
FieldDef("EmptyBytes", "2s", format_none),
], # 2 bytes - empty
}
nsx_header_dict = {
"basic_21": [
FieldDef("Label", "16s", format_stripstring), # 16 bytes - 16 char array
FieldDef("Period", "I", format_none), # 4 bytes - uint32
FieldDef("ChannelCount", "I", format_none),
], # 4 bytes - uint32
"basic": [
FieldDef("FileSpec", "2B", format_filespec), # 2 bytes - 2 unsigned char
FieldDef("BytesInHeader", "I", format_none), # 4 bytes - uint32
FieldDef("Label", "16s", format_stripstring), # 16 bytes - 16 char array
FieldDef("Comment", "256s", format_stripstring), # 256 bytes - 256 char array
FieldDef("Period", "I", format_none), # 4 bytes - uint32
FieldDef("TimeStampResolution", "I", format_none), # 4 bytes - uint32
FieldDef("TimeOrigin", "8H", format_timeorigin), # 16 bytes - 8 uint16
FieldDef("ChannelCount", "I", format_none),
], # 4 bytes - uint32
"extended": [
FieldDef("Type", "2s", format_stripstring), # 2 bytes - 2 char array
FieldDef("ElectrodeID", "H", format_none), # 2 bytes - uint16
FieldDef(
"ElectrodeLabel", "16s", format_stripstring
), # 16 bytes - 16 char array
FieldDef("PhysicalConnector", "B", format_none), # 1 byte - uint8
FieldDef("ConnectorPin", "B", format_none), # 1 byte - uint8
FieldDef("MinDigitalValue", "h", format_none), # 2 bytes - int16
FieldDef("MaxDigitalValue", "h", format_none), # 2 bytes - int16
FieldDef("MinAnalogValue", "h", format_none), # 2 bytes - int16
FieldDef("MaxAnalogValue", "h", format_none), # 2 bytes - int16
FieldDef("Units", "16s", format_stripstring), # 16 bytes - 16 char array
FieldDef("HighFreqCorner", "I", format_freq), # 4 bytes - uint32
FieldDef("HighFreqOrder", "I", format_none), # 4 bytes - uint32
FieldDef("HighFreqType", "H", format_filter), # 2 bytes - uint16
FieldDef("LowFreqCorner", "I", format_freq), # 4 bytes - uint32
FieldDef("LowFreqOrder", "I", format_none), # 4 bytes - uint32
FieldDef("LowFreqType", "H", format_filter),
], # 2 bytes - uint16
"data": [
FieldDef("Header", "B", format_none), # 1 byte - uint8
FieldDef("Timestamp", "I", format_none), # 4 bytes - uint32
FieldDef("NumDataPoints", "I", format_none),
], # 4 bytes - uint32]
}
# </editor-fold>
# <editor-fold desc="Safety check functions">
def check_elecid(elec_ids):
if type(elec_ids) is str and elec_ids != ELEC_ID_DEF:
print(
"\n*** WARNING: Electrode IDs must be 'all', a single integer, or a list of integers."
)
print(" Setting elec_ids to 'all'")
elec_ids = ELEC_ID_DEF
if elec_ids != ELEC_ID_DEF and type(elec_ids) is not list:
if type(elec_ids) == range:
elec_ids = list(elec_ids)
elif type(elec_ids) == int:
elec_ids = [elec_ids]
return elec_ids
def check_starttime(start_time_s):
if not isinstance(start_time_s, (int, float)) or (
isinstance(start_time_s, (int, float)) and start_time_s < START_TIME_DEF
):
print("\n*** WARNING: Start time is not valid, setting start_time_s to 0")
start_time_s = START_TIME_DEF
return start_time_s
def check_datatime(data_time_s):
if (type(data_time_s) is str and data_time_s != DATA_TIME_DEF) or (
isinstance(data_time_s, (int, float)) and data_time_s < 0
):
print("\n*** WARNING: Data time is not valid, setting data_time_s to 'all'")
data_time_s = DATA_TIME_DEF
return data_time_s
def check_downsample(downsample):
if not isinstance(downsample, int) or downsample < DOWNSAMPLE_DEF:
print(
"\n*** WARNING: downsample must be an integer value greater than 0. "
" Setting downsample to 1 (no downsampling)"
)
downsample = DOWNSAMPLE_DEF
if downsample > 1:
print(
"\n*** WARNING: downsample will be deprecated in a future version."
" Set downsample to 1 (default) to match future behavior."
"\n*** WARNING: downsample does not perform anti-aliasing."
)
return downsample
def check_dataelecid(elec_ids, all_elec_ids):
unique_elec_ids = set(elec_ids)
all_elec_ids = set(all_elec_ids)
# if some electrodes asked for don't exist, reset list with those that do, or throw error and return
if not unique_elec_ids.issubset(all_elec_ids):
if not unique_elec_ids & all_elec_ids:
print("\nNone of the elec_ids passed exist in the data, returning None")
return None
else:
print(
"\n*** WARNING: Channels "
+ str(sorted(list(unique_elec_ids - all_elec_ids)))
+ " do not exist in the data"
)
unique_elec_ids = unique_elec_ids & all_elec_ids
return sorted(list(unique_elec_ids))
def check_filesize(file_size):
if file_size < DATA_FILE_SIZE_MIN:
print("\n file_size must be larger than 10 Mb, setting file_size=10 Mb")
return DATA_FILE_SIZE_MIN
else:
return int(file_size)
# </editor-fold>
class NevFile:
"""
attributes and methods for all BR event data files. Initialization opens the file and extracts the
basic header information.
"""
def __init__(self, datafile=""):
self.datafile = datafile
self.basic_header = {}
self.extended_headers = []
# Run openfilecheck and open the file passed or allow user to browse to one
self.datafile = openfilecheck(
"rb",
file_name=self.datafile,
file_ext=".nev",
file_type="Blackrock NEV Files",
)
# extract basic header information
self.basic_header = processheaders(self.datafile, nev_header_dict["basic"])
# Extract extended headers
for i in range(self.basic_header["NumExtendedHeaders"]):
self.extended_headers.append({})
header_string = bytes.decode(
unpack("<8s", self.datafile.read(8))[0], "latin-1"
)
self.extended_headers[i]["PacketID"] = header_string.split(
STRING_TERMINUS, 1
)[0]
self.extended_headers[i].update(
processheaders(
self.datafile, nev_header_dict[self.extended_headers[i]["PacketID"]]
)
)
# Must set this for file spec 2.1 and 2.2
if (
header_string == "NEUEVWAV"
and float(self.basic_header["FileSpec"]) < 2.3
):
self.extended_headers[i]["SpikeWidthSamples"] = WAVEFORM_SAMPLES_21
def getdata(self, elec_ids="all", wave_read="read"):
"""
This function is used to return a set of data from the NEV datafile.
:param elec_ids: [optional] {list} User selection of elec_ids to extract specific spike waveforms (e.g., [13])
:param wave_read: [optional] {STR} 'read' or 'no_read' - whether to read waveforms or not
:return: output: {Dictionary} with one or more of the following dictionaries (all include TimeStamps)
dig_events: Reason, Data, [for file spec 2.2 and below, AnalogData and AnalogDataUnits]
spike_events: Units='nV', ChannelID, NEUEVWAV_HeaderIndices, Classification, Waveforms
comments: CharSet, Flag, Data, Comment
video_sync_events: VideoFileNum, VideoFrameNum, VideoElapsedTime_ms, VideoSourceID
tracking_events: ParentID, NodeID, NodeCount, TrackingPoints
button_trigger_events: TriggerType
configuration_events: ConfigChangeType
Note: For digital and neural data - TimeStamps, Classification, and Data can be lists of lists when more
than one digital type or spike event exists for a channel
"""
# Initialize output dictionary and reset position in file (if read before, may not be here anymore)
output = dict()
# Safety checks
elec_ids = check_elecid(elec_ids)
######
# extract raw data
self.datafile.seek(0, 2)
lData = self.datafile.tell()
nPackets = int(
(lData - self.basic_header["BytesInHeader"])
/ self.basic_header["BytesInDataPackets"]
)
self.datafile.seek(self.basic_header["BytesInHeader"], 0)
rawdata = self.datafile.read()
# rawdataArray = np.reshape(np.fromstring(rawdata,'B'),(nPackets,self.basic_header['BytesInDataPackets']))
# Find all timestamps and PacketIDs
if self.basic_header["FileTypeID"] == "BREVENTS":
tsBytes = 8
ts = np.ndarray(
(nPackets,),
"<L",
rawdata,
0,
(self.basic_header["BytesInDataPackets"],),
)
else:
tsBytes = 4
ts = np.ndarray(
(nPackets,),
"<I",
rawdata,
0,
(self.basic_header["BytesInDataPackets"],),
)
PacketID = np.ndarray(
(nPackets,),
"<H",
rawdata,
tsBytes,
(self.basic_header["BytesInDataPackets"],),
)
# identify packet indices by type. if packet type is found, typecast rawdata into meaningful data arrays
# neural and analog input data:
neuralPackets = [
idx
for idx, element in enumerate(PacketID)
if NEURAL_PACKET_ID_MIN <= element <= NEURAL_PACKET_ID_MAX
]
if len(neuralPackets) > 0:
ChannelID = PacketID
if type(elec_ids) is list:
elecindices = [
idx
for idx, element in enumerate(ChannelID[neuralPackets])
if element in elec_ids
]
neuralPackets = [neuralPackets[index] for index in elecindices]
spikeUnit = np.ndarray(
(nPackets,),
"<B",
rawdata,
tsBytes + 2,
(self.basic_header["BytesInDataPackets"],),
)
output["spike_events"] = {
"TimeStamps": list(ts[neuralPackets]),
"Unit": list(spikeUnit[neuralPackets]),
"Channel": list(ChannelID[neuralPackets]),
}
if wave_read == "read":
wfs = np.ndarray(
(
nPackets,
int((self.basic_header["BytesInDataPackets"] - (tsBytes + 4))/2),
),
"<h",
rawdata,
tsBytes + 4,
(self.basic_header["BytesInDataPackets"], 2),
)
output["spike_events"].update({"Waveforms": wfs[neuralPackets, :]})
# digital events, i.e. digital inputs and serial inputs
digiPackets = [
idx for idx, element in enumerate(PacketID) if element == DIGITAL_PACKET_ID
]
if len(digiPackets) > 0:
insertionReason = np.ndarray(
(nPackets,),
"<B",
rawdata,
tsBytes + 2,
(self.basic_header["BytesInDataPackets"],),
)
digiVals = np.ndarray(
(nPackets,),
"<I",
rawdata,
tsBytes + 4,
(self.basic_header["BytesInDataPackets"],),
)
output["digital_events"] = {
"TimeStamps": list(ts[digiPackets]),
"InsertionReason": list(insertionReason[digiPackets]),
"UnparsedData": list(digiVals[digiPackets]),
}
# comments + NeuroMotive events that are stored like comments
commentPackets = [
idx for idx, element in enumerate(PacketID) if element == COMMENT_PACKET_ID
]
if len(commentPackets) > 0:
charSet = np.ndarray(
(nPackets,),
"<B",
rawdata,
tsBytes + 2,
(self.basic_header["BytesInDataPackets"],),
)
tsStarted = np.ndarray(
(nPackets,),
"<I",
rawdata,
tsBytes + 4,
(self.basic_header["BytesInDataPackets"],),
)
charSet = charSet[commentPackets]
charSetList = np.array([None] * len(charSet))
ANSIPackets = [
idx for idx, element in enumerate(charSet) if element == CHARSET_ANSI
]
if len(ANSIPackets) > 0:
charSetList[ANSIPackets] = "ANSI"
UTFPackets = [
idx for idx, element in enumerate(charSet) if element == CHARSET_UTF
]
if len(UTFPackets) > 0:
charSetList[UTFPackets] = "UTF "
# need to transfer comments from neuromotive. identify region of interest (ROI) events...
ROIPackets = [
idx for idx, element in enumerate(charSet) if element == CHARSET_ROI
]
lcomment = self.basic_header["BytesInDataPackets"] - tsBytes - 10
comments = np.chararray(
(nPackets, lcomment),
1,
False,
rawdata,
tsBytes + 8,
(self.basic_header["BytesInDataPackets"], 1),
)
# extract only the "true" comments, distinct from ROI packets
trueComments = np.setdiff1d(
list(range(0, len(commentPackets) - 1)), ROIPackets
)
trueCommentsidx = np.asarray(commentPackets)[trueComments]
textComments = comments[trueCommentsidx]
commentsFinal = []
for text in textComments:
stringarray = text.tostring()
stringvector = stringarray.decode("latin-1")
stringvector = stringvector[0:-1]
validstring = stringvector.replace("\x00", "")
commentsFinal.append(validstring)
# Remove the ROI comments from the list
subsetInds = list(
set(list(range(0, len(charSetList) - 1))) - set(ROIPackets)
)
output["comments"] = {
"TimeStamps": list(ts[trueCommentsidx]),
"TimeStampsStarted": list(tsStarted[trueCommentsidx]),
"Data": commentsFinal,
"CharSet": list(charSetList[subsetInds]),
}
# parsing and outputing ROI events
if len(ROIPackets) > 0:
nmPackets = np.asarray(ROIPackets)
nmCommentsidx = np.asarray(commentPackets)[ROIPackets]
nmcomments = comments[nmCommentsidx]
nmcomments[:, -1] = ":"
nmstringarray = nmcomments.tostring()
nmstringvector = nmstringarray.decode("latin-1")
nmstringvector = nmstringvector[0:-1]
nmvalidstrings = nmstringvector.replace("\x00", "")
nmcommentsFinal = nmvalidstrings.split(":")
ROIfields = [l.split(":") for l in ":".join(nmcommentsFinal).split(":")]
ROIfieldsRS = np.reshape(ROIfields, (len(ROIPackets), 5))
output["tracking_events"] = {
"TimeStamps": list(ts[nmCommentsidx]),
"ROIName": list(ROIfieldsRS[:, 0]),
"ROINumber": list(ROIfieldsRS[:, 1]),
"Event": list(ROIfieldsRS[:, 2]),
"Frame": list(ROIfieldsRS[:, 3]),
}
# NeuroMotive video syncronization packets
vidsyncPackets = [
idx
for idx, element in enumerate(PacketID)
if element == VIDEO_SYNC_PACKET_ID
]
if len(vidsyncPackets) > 0:
fileNumber = np.ndarray(
(nPackets,),
"<H",
rawdata,
tsBytes + 2,
(self.basic_header["BytesInDataPackets"],),
)
frameNumber = np.ndarray(
(nPackets,),
"<I",
rawdata,
tsBytes + 4,
(self.basic_header["BytesInDataPackets"],),
)
elapsedTime = np.ndarray(
(nPackets,),
"<I",
rawdata,
tsBytes + 8,
(self.basic_header["BytesInDataPackets"],),
)
sourceID = np.ndarray(
(nPackets,),
"<I",
rawdata,
tsBytes + 12,
(self.basic_header["BytesInDataPackets"],),
)
output["video_sync_events"] = {
"TimeStamps": list(ts[vidsyncPackets]),
"FileNumber": list(fileNumber[vidsyncPackets]),
"FrameNumber": list(frameNumber[vidsyncPackets]),
"ElapsedTime": list(elapsedTime[vidsyncPackets]),
"SourceID": list(sourceID[vidsyncPackets]),
}
# Neuromotive object tracking packets
trackingPackets = [
idx for idx, element in enumerate(PacketID) if element == TRACKING_PACKET_ID
]
if len(trackingPackets) > 0:
trackerObjs = [
sub["VideoSource"]
for sub in self.extended_headers
if sub["PacketID"] == "TRACKOBJ"
]
trackerIDs = [
sub["TrackableID"]
for sub in self.extended_headers
if sub["PacketID"] == "TRACKOBJ"
]
output["tracking"] = {
"TrackerIDs": trackerIDs,
"TrackerTypes": [
sub["TrackableType"]
for sub in self.extended_headers
if sub["PacketID"] == "TRACKOBJ"
],
}
parentID = np.ndarray(
(nPackets,),
"<H",
rawdata,
tsBytes + 2,
(self.basic_header["BytesInDataPackets"],),
)
nodeID = np.ndarray(
(nPackets,),
"<H",
rawdata,
tsBytes + 4,
(self.basic_header["BytesInDataPackets"],),
)
nodeCount = np.ndarray(
(nPackets,),
"<H",
rawdata,
tsBytes + 6,
(self.basic_header["BytesInDataPackets"],),
)
markerCount = np.ndarray(
(nPackets,),
"<H",
rawdata,
tsBytes + 8,
(self.basic_header["BytesInDataPackets"],),
)
bodyPointsX = np.ndarray(
(nPackets,),
"<H",
rawdata,
tsBytes + 10,
(self.basic_header["BytesInDataPackets"],),
)
bodyPointsY = np.ndarray(
(nPackets,),
"<H",
rawdata,
tsBytes + 12,
(self.basic_header["BytesInDataPackets"],),
)
# Need to parse by the tracker object to create clean outputs
R = 0
E = 0
for i in range(0, len(trackerObjs)):
indices = [
idx
for idx, element in enumerate(nodeID[trackingPackets])
if element == i
]
# Static objects create single rectangles that only get sent over into the file once
if len(indices) == 1:
if trackerObjs[i] == "TrackingROI":
trackerObjs[i] = trackerObjs[i] + str(R)
R += 1
elif trackerObjs[i] == "EventROI":
trackerObjs[i] = trackerObjs[i] + str(E)
E += 1
bodyPointsX = np.ndarray(
(nPackets, 4),
"<H",
rawdata,
tsBytes + 10,
(self.basic_header["BytesInDataPackets"], 2),
)
bodyPointsY = np.ndarray(
(nPackets, 4),
"<H",
rawdata,
tsBytes + 12,
(self.basic_header["BytesInDataPackets"], 2),
)
selectedIndices = [trackingPackets[index] for index in indices]
tempDict = {
"TimeStamps": list(ts[selectedIndices]),
"ParentID": list(parentID[selectedIndices]),
"NodeCount": list(nodeCount[selectedIndices]),
"MarkerCount": list(markerCount[selectedIndices]),
"X": list(bodyPointsX[selectedIndices]),
"Y": list(bodyPointsY[selectedIndices]),
}
output["tracking"].update({trackerObjs[i]: tempDict})
output["tracking"].update({"TrackerObjs": trackerObjs})
# patient trigger events
buttonPackets = [
idx for idx, element in enumerate(PacketID) if element == BUTTON_PACKET_ID
]
if len(buttonPackets) > 0:
trigType = np.ndarray(
(nPackets,),
"<H",
rawdata,
tsBytes + 2,
(self.basic_header["BytesInDataPackets"],),
)
output["PatientTrigger"] = {
"TimeStamps": list(ts[buttonPackets]),
"TriggerType": list(trigType[buttonPackets]),
}
# configuration packets
configPackets = [
idx
for idx, element in enumerate(PacketID)
if element == CONFIGURATION_PACKET_ID
]
if len(configPackets) > 0:
changeType = np.ndarray(
(nPackets,),
"<H",
rawdata,
tsBytes + 2,
(self.basic_header["BytesInDataPackets"],),
)
output["reconfig"] = {
"TimeStamps": list(ts[configPackets]),
"ChangeType": list(ts[configPackets]),
}
return output
def processroicomments(
self, comments
): # obsolete in v2.0.0+, ROI comments come out parsed from NevFile.getdata()
"""
used to process the comment data packets associated with NeuroMotive region of interest enter/exit events.
requires that read_data() has already been run.
:return: roi_events: a dictionary of regions, enter timestamps, and exit timestamps for each region
"""
roi_events = {"Regions": [], "EnterTimeStamps": [], "ExitTimeStamps": []}
for i in range(len(comments["TimeStamps"])):
if comments["CharSet"][i] == "NeuroMotive ROI":
temp_data = pack("<I", comments["Data"][i])
roi = unpack_from("<B", temp_data)[0]
event = unpack_from("<B", temp_data, 1)[0]
# Determine the label of the region source
source_label = next(
d["VideoSource"]
for d in self.extended_headers
if d["TrackableID"] == roi
)
# update the timestamps for events
if source_label in roi_events["Regions"]:
idx = roi_events["Regions"].index(source_label)
else:
idx = -1