-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpreprocess.py
More file actions
1693 lines (1536 loc) · 70.5 KB
/
preprocess.py
File metadata and controls
1693 lines (1536 loc) · 70.5 KB
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
from typing import List
import numpy as np
import numbers
import os
import scipy.signal as sig
from scipy.stats import pearsonr
from scipy.optimize import minimize
from itertools import chain
import matplotlib.pyplot as plt
import pickle
import pandas as pd
import logging
import re
import sys
from datetime import datetime
import scipy.io as sio
__version__ = '0.0.5'
# def logging_test():
# logging.debug('bli')
# logging.warning('blibli')
# #
# Plot activity of electrodes in the wireless files
def plotWireless(fileName, plotLimit, channels, samplingRate=32000, nChannels=32, ):
logging.info('started plotWireless function')
if type(channels) is not list:
channels = [channels]
logging.debug('input was not in the format of a list, corrected')
fig, axes = plt.subplots()
plotRange = range(plotLimit[0] * samplingRate, plotLimit[1] * samplingRate)
xRange: List[float] = [x / samplingRate for x in plotRange]
with open(fileName, 'rb') as fid:
allChannels = np.fromfile(fid, dtype=np.uint16)
for channelNum in channels:
channel = (allChannels[channelNum - 1::nChannels] - 32768).astype(np.int16)
axes.plot(xRange, channel[plotRange], label=f'Elec {channelNum}')
axes.set_xlabel('Time (s)')
axes.set_title(f'File {fileName} Electrode {channelNum}')
axes.legend(loc='upper left')
return fig, axes
def plotAO(fileDir, filePrefix, fileList, plotLimit, channels, samplingRate=44000, nChannels=32, ):
logging.info('started plotAO function')
if type(channels) is not list:
channels = [channels]
logging.debug('input was not in the format of a list, corrected')
fig, axes = plt.subplots()
plotRange = range(plotLimit[0] * samplingRate, plotLimit[1] * samplingRate)
xRange: List[float] = [x / samplingRate for x in plotRange]
for elecNum in channels:
logging.info(f'Processing electrode {elecNum}')
elecName = f'CRAW_{elecNum:03d}'
elecData = [None] * len(fileList)
for i, fileNum in enumerate(fileList):
fileName = f'{fileDir}{filePrefix}{fileNum:04d}.mat'
matList = sio.loadmat(fileName, variable_names=elecName)
elecData[i] = matList[elecName][0, :]
allData = np.concatenate(elecData)
axes.plot(xRange, allData[plotRange], label=f'Elec {elecNum}')
axes.set_xlabel(f'Time (s)')
axes.set_title(f'AO files in {fileDir}, channels: {channels}')
axes.legend(loc='upper left')
return fig, axes
#
# Transform wireless files to concatenated binary, single electrode, files
#
def wirelessToBin(inDir, outDir, files, elecList, nChannels=32, verbose=False):
logging.info('started wirelessToBin function')
nSamples = 0
if not (outDir is None):
safeOutputDir(outDir)
# Open all the output files
if not (outDir is None):
rangeStr = "-F{0}T{1}".format(files[0], files[-1])
ofids = openFids(outDir, elecList, "Elec{0}" + rangeStr + ".bin", "wb")
# Read each wireless file and separate to electrodes
for file in files:
fileName = file
if type (fileName) != str:
fileName0 = f'NEUR{file:04d}.DT2'
fileName1 = f'BACK{file:04d}.DT2'
else:
fileName0 = fileName
if not (inDir is None):
fileName0 = os.path.join (inDir, fileName0)
fileName1 = os.path.join (inDir, fileName1)
# fileName = "{0}NEUR{1}{2}.DT2".format(inDir, '0' * (4 - len(str(file))), file)
if os.path.isfile(fileName0):
fileName = fileName0
else:
fileName = fileName1
# fileName = "{0}BACK{1}{2}.DT2".format(inDir, '0' * (4 - len(str(file))), file)
if verbose:
print(f'Transforming {fileName} to binary')
fid = open(fileName, 'rb')
fileData = np.fromfile(fid, dtype=np.uint16)
nSamples += fileData.shape[0] // nChannels
for elec in elecList:
try:
channelData = (fileData[elec - 1::nChannels] - 32768).astype(np.int16)
except ValueError as err:
logging.error('channel or file defined as input does not exist')
if not (outDir is None):
channelData.tofile(ofids[elec])
fid.close()
# Close all the output files
if not (outDir is None):
closeFids(ofids, elecList)
return nSamples
def AOtoBin(fileDir, filePrefix, fileList, elecList, saveLfp=True, saveRaw=True, saveFilter=True, sampRate=44000,
lfpBand=[2, 300], filterBand=[300, 6000]):
bPass, aPass = sig.butter(4, [300 / (sampRate / 2), 6000 / (sampRate / 2)], btype='bandpass')
# [bf, af] = sig.butter(4, [f/(1000/2) for f in freq], btype='band')
bNotch, aNotch = sig.iirnotch(50 / (1000 / 2), 30)
for elecNum in elecList:
elecName = f'CRAW_{elecNum:03d}'
logging.info(f'Processing electrode: {elecName}')
if saveRaw:
if not os.path.exists(os.path.join(fileDir, 'Raw')):
os.mkdir(os.path.join(fileDir, 'Raw'))
rawDir = os.path.join(fileDir, 'Raw', "")
outRawFileName = f'{rawDir}{filePrefix}Raw{elecNum:03d}-{fileList[0]}-{fileList[-1]}.bin'
if saveFilter:
if not os.path.exists(os.path.join(fileDir, 'Filter')):
os.mkdir(os.path.join(fileDir, 'Filter'))
fiterDir = os.path.join(fileDir, 'Filter', '')
outFilterFileName = f'{fiterDir}{filePrefix}Filter{elecNum:03d}-{fileList[0]}-{fileList[-1]}.bin'
if saveLfp:
if not os.path.exists(os.path.join(fileDir, 'Lfp')):
os.mkdir(os.path.join(fileDir, 'Lfp'))
lfpDir = os.path.join(fileDir, 'Lfp', '')
outLfpFileName = f'{lfpDir}{filePrefix}Lfp{elecNum:03d}-{fileList[0]}-{fileList[-1]}.bin'
elecData = [None] * len(fileList)
for i, fileNum in enumerate(fileList):
fileName = f'{fileDir}{filePrefix}{fileNum:04d}.mat'
logging.info(f'Processing electrode: {fileName}')
matList = sio.loadmat(fileName, variable_names=elecName)
elecData[i] = matList[elecName][0, :]
allData = np.concatenate(elecData)
allData = allData.astype(np.int16)
if saveRaw:
allData.tofile(outRawFileName)
if saveFilter:
filtData = sig.filtfilt(bPass, aPass, allData)
filtData.astype(np.int16).tofile(outFilterFileName)
if saveLfp:
lfpData = sig.decimate(allData, int(sampRate / 1000), ftype='fir')
lfpData = sig.filtfilt(bNotch, aNotch, lfpData)
lfpData.astype(np.int16).tofile(outLfpFileName)
#
# Plot activity of electrode in a bin file
#
def plotBin(fileName, plotLimit, samplingRate=32000, axes=None):
logging.info("started plotBin function")
if not axes:
fig, axes = plt.subplots()
plotRange = range(int(plotLimit[0] * samplingRate), (int(plotLimit[1] * samplingRate) - 1))
xRange = [x / samplingRate for x in plotRange]
try:
with open(fileName, 'rb') as fid:
channel = np.fromfile(fid, dtype=np.int16)
axes.plot(xRange, channel[plotRange])
axes.set_xlabel('Time (s)')
axes.set_title(f'File {fileName}')
except IOError:
logging.warning(f'Unable to open file: {fileName}')
if 'fig' in locals():
return fig, axes
return axes
# The function plots a whole electrode Data set
def plotAllBin(fileName, elecNumber, samplingRate=32000, axes=None):
logging.info("started plotBin function")
if not axes:
fig, axes = plt.subplots()
try:
with open(fileName, 'rb') as fid:
channel = np.fromfile(fid, dtype=np.int16)
axes.plot(channel)
axes.set_xlabel('Time (s)')
axes.set_title("All electrode " + elecNumber, fontsize=20)
fig.set_size_inches((30, 5))
except IOError:
logging.warning(f'Unable to open file: {fileName}')
if 'fig' in locals():
return fig, axes
return axes
# The function shows a single electrode data by path
def showElectrode(path, elecNumber, plotLimit, title):
fig, axes = plotBin(path, plotLimit)
axes.set_title('Electrode ' + str(elecNumber) + title, fontsize=20)
fig.set_size_inches((30, 5))
plt.show()
# The function plot 5 seconds from the start, middle and ending of the data set
def plot5Sec(filePath, axes, elec, samplingRate=32000):
# finds max X value of the data set
maxX = axes[1].dataLim.intervalx[1]
# divide by sampling rate to get the time
time = maxX / samplingRate
# show start middle and end
start = [0, 5]
end = [time - 5, time]
middle = [(time / 2) - 2.5, (time / 2) + 2.5]
showElectrode(filePath, elec, start, " Start")
showElectrode(filePath, elec, middle, " Middle")
showElectrode(filePath, elec, end, " End")
#
# Iterate over binary files and remove the median
#
def remMedian(inDir, outDir, elecList, rangeStr, batchSize=100000, verbose=False):
logging.info("started remMedian function")
nElecs = len(elecList)
safeOutputDir(outDir)
# Open all the input and output files
fileName = "{0}Elec{1}-F0T{2}.bin"
ifids = openFids(inDir, elecList, 'Elec{0}' + rangeStr + '.bin', "rb")
ofids = openFids(outDir, elecList, 'Elec{0}' + rangeStr + '.bin', "wb")
if verbose:
logging.info(f'File size {int(os.fstat(ifids[elecList[0]].fileno()).st_size / np.int16().itemsize)} samples')
# Remove median from each channel
location, readMore = 0, True
inBuffer = np.zeros((nElecs, batchSize), dtype=np.int16)
while readMore:
if verbose:
print(f'Location {location}')
for i, elec in enumerate(elecList):
data = np.fromfile(ifids[elec], count=batchSize, dtype=np.int16)
if i == 0 and data.shape[0] != batchSize:
inBuffer = np.zeros((nElecs, data.shape[0]), dtype=np.int16)
readMore = False
inBuffer[i, :] = data
for i, elec in enumerate(elecList):
notElec = list(range(0, i)) + list(range(i + 1, nElecs))
outBuffer = inBuffer[i, :] - np.median(inBuffer[notElec, :], axis=0)
outBuffer.astype(np.int16).tofile(ofids[elec])
location += data.shape[0]
# Close all the input and output files
closeFids(ifids, elecList)
closeFids(ofids, elecList)
def raw_to_noise_correlation(k, signal, sigMedian):
return np.sum((signal - k * sigMedian) ** 2)
def find_k(signal, sigMedian):
best_k = minimize(raw_to_noise_correlation, 0, args=(signal, sigMedian))
return best_k
#
# Iterate over binary files and remove the median multiplied by a scalar
#
def remScaledMedian(inDir, outDir, elecList, rangeStr, batchSize=100000, verbose=False):
logging.info("started remMedian function")
nElecs = len(elecList)
safeOutputDir(outDir)
# Open all the input and output files
fileName = "{0}Elec{1}-F0T{2}.bin"
ifids = openFids(inDir, elecList, 'Elec{0}' + rangeStr + '.bin', "rb")
ofids = openFids(outDir, elecList, 'Elec{0}' + rangeStr + '.bin', "wb")
if verbose:
logging.info(f'File size {int(os.fstat(ifids[elecList[0]].fileno()).st_size / np.int16().itemsize)} samples')
# Remove median from each channel
location, readMore = 0, True
inBuffer = np.zeros((nElecs, batchSize), dtype=np.int16)
first = True
scalars = []
while readMore:
if verbose:
print(f'Location {location}')
for i, elec in enumerate(elecList):
data = np.fromfile(ifids[elec], count=batchSize, dtype=np.int16)
if i == 0 and data.shape[0] != batchSize:
inBuffer = np.zeros((nElecs, data.shape[0]), dtype=np.int16)
readMore = False
inBuffer[i, :] = data
for i, elec in enumerate(elecList):
notElec = list(range(0, i)) + list(range(i + 1, nElecs))
if first:
scalars.append(find_k(inBuffer[i, :], np.mean(inBuffer[notElec, :], axis=0)).x)
outBuffer = inBuffer[i, :] - scalars[i] * np.mean(inBuffer[notElec, :], axis=0)
outBuffer.astype(np.int16).tofile(ofids[elec])
if first:
first = False
print(scalars)
location += data.shape[0]
# Close all the input and output files
closeFids(ifids, elecList)
closeFids(ofids, elecList)
#
# Transform wireless data to motion data
#
DATAFILELEN = 16*1024*1024
DATANCHANNELS=32
DATAFREQ=32000
DMCHANNEL=0
DMSIGNATURE = np.array ([13579, 24680])
DMTSFACTOR = 16
DMSAMPLERATE= 1000 # Hz
DATAMAGNETSAMPLERATE= 111 # Hz
DMHEADERSIZE = 12
BLOCKLEN = 64*1024
BLOCKSIGNATURE = [
0x90ef, 0x5678, 0xabcd, 0x1234, # Signature
0x1, 0x0, # Format version.
0x0, 0x1 # Size of block (64KB)
]
NEURONTYPE = 2
MOTIONTYPE = 3
# Find runs of ones. See
# https://newbedev.com/find-length-of-sequences-of-identical-values-in-a-numpy-array-run-length-encoding
#
# Parameters:
# bits - An arrray of 0-s and 1-s.
#
# Returns:
# start, finish, length - Start, finish and length of runs of 1-s in bits array.
#
def runs_of_ones_array (bits):
"""
Find runs of ones.
Parameters:
bits - An arrray of 0-s and 1-s.
Returns:
start, finish, length - Start, finish and length of runs of 1-s in bits array.
"""
# Make sure array is bound by 0-s.
bounded = np.concatenate (([0], bits, [0]))
# Run start is +1, run end is -1.
diffs = np.diff (bounded)
# Compute lengths.
begin, = np.where (diffs > 0)
finish, = np.where (diffs < 0)
return begin, finish, finish-begin
#
# Transform wireless data to neural data
#
def wirelessToChannels (base, files, prefix='NEUR',
verbose=False, nchannels=DATANCHANNELS,
freq=DATAFREQ, savetype=np.int16):
logging.info("started wirelessToMotion function")
# sensors = ['acc', 'gyr', 'mag']
# axes = ['x', 'y', 'z']
# files = (f if type (f) is str else f'{prefix}{f:04d}.DF1'
# for f in files)
# if not base is None:
# files = (os.path.join (base, datafile) for datafile in files)
channeldata = []
btimestamps = []
for datafile in files:
if verbose:
print(f'Read raw file {datafile}')
fd = open(datafile, 'rb')
data = np.fromfile(fd, dtype=np.uint16)
fd.close()
#
# Generic Stage
#
# Data files should be fixed length.
if len (data)*2 != DATAFILELEN:
raise Exception (f'File {datafile} size is {len (data)*2}!')
# File is composed of 64KB blocks.
blocks = data.reshape (-1, BLOCKLEN // 2)
# Test blocks signatures.
goodblocks = np.all (blocks [:, :len(BLOCKSIGNATURE)] == BLOCKSIGNATURE,
axis=1)
# Extract timestamps.
timestamps = np.dot (blocks [:, 8:10], [[1], [2**16]])
timestamps = timestamps.astype (np.uint32).reshape (-1)
# Extract data partitions.
# Partition info are 3 uint32: Type, Start, Length.
nblocks = len (blocks)
compmat = (np.diag (np.ones (7*6)) [::2] +
np.diag (np.ones (7*6)) [1::2] * 2**16).T
partinfo = np.dot (blocks [:, 12:54], compmat).reshape (nblocks, -1, 3)
# Get reference to neuronal data.
ind0, ind1 = np.where (partinfo [goodblocks, :, 0] == 2)
if np.any (np.unique (ind0, return_counts=True) [1] > 1):
raise f'Non unique neuronal data partition in {datafile}'
# Extract the data.
ilast, plast = ind0 [-1], ind1 [-1]
t0, tn = timestamps [ind0 [0]], timestamps [ilast]
if len (btimestamps) > 0 and btimestamps [-1] [1] != t0:
if verbose:
logging.warning (f'Timestamp discontinuity between files '+
f'{btimestamps [-1] [1]}..{t0})')
logging.warning ('Adjusting blocks.')
diff = t0 - btimestamps [-1] [1]
if diff > 0:
# Pad with zeros
channeldata.append (np.zeros (
(int (diff * freq // 1000), nchannels)
))
else:
# Truncate previous data.
index = len (channeldata)-1
while diff > 0 and index >= 0:
trunc = int (diff * freq // 1000)
if trunc > len (channeldata [index]):
trunc = len (channeldata [index])
channeldata [index] = channeldata [index] [:trunc]
index -= 1
#
# Neuronal Data Handling
#
channels = np.zeros ((int ((tn - t0) * freq // 1000 +
partinfo [ilast, plast, 2] // (2*nchannels)),
nchannels), dtype=savetype)
prevend = -1
for i0, i1, ti in zip (ind0, ind1, timestamps [ind0]):
_, start, length = partinfo [i0, i1]
# Timestamp is too coarse, but we assume it's precise. It may cause
# a glitch once in a while, but it seems the data is synchronised to
# the timestamp.
cs = (ti-t0) * int(freq // 1000)
ce = cs + int (length // (2*nchannels))
# print (cs, ce, ce - cs, length // (2*nchannels))
# print (channels [cs:ce, :].shape)
# print (blocks [i0, int (start // 2):int ((start + length) // 2)]
# .reshape (-1, nchannels).shape)
channels [cs:ce, :] = (
blocks [i0, int (start // 2):int ((start + length) // 2)]
.reshape (-1, nchannels) - 2**15
).astype (savetype)
prevend = ti + (length // (2*nchannels*(freq // 1000)))
channeldata.append (channels)
btimestamps.append ([t0, prevend])
for i in range(len(channeldata)):
channeldata[i] = channeldata[i].astype(savetype)
return np.concatenate (channeldata).astype(savetype), btimestamps
def getDataFiles (inDir, files, prefix=['NEUR'], suffix='DF1', verbose=False):
"""
Get the data files from the file list.
Parameters:
inDir - Directroy where the files reside (None only uses file path in files).
files - A list of file names or file numbers.
prefix - List of filename prefix. When files are provided as numbers, the prefix
list is used to search for the file in inDir. First matched file is
used as the file.
suffix - Data files suffix. Used to construct filename when files are provided
as numbers.
verbose - Whether to use verbose logging. At this time ignored.
Returns:
A list of valid data file paths.
Note:
If a file is not found, a warning is logged, but processing continues.
"""
filepaths = []
for f in files:
if type (f) is str:
pass
elif isinstance (f, numbers.Real):
alternatives = (os.path.join (inDir, f'{pfx}{f:04d}.{suffix}')
for pfx in prefix)
alternatives = (alt for alt in alternatives if os.path.exists (alt))
try:
f = next (iter (alternatives))
except StopIteration as e:
logging.warning (f'Missing file {f}')
continue
filepaths.append (f)
return filepaths
#
# Transform wireless files to concatenated binary, single electrode, files
#
def wirelessToBinV2(inDir, outDir, files, elecList,
prefix=['NEUR'], suffix='DF1',
nchannels=DATANCHANNELS, freq=DATAFREQ,
verbose=False, savetype=np.int16):
"""
Read data files and return the neuronal channels data, optionally save them in
files. Data is saved as numpy binary data. (X.tofile)
Parameters:
inDir - Directroy where the files reside (None only uses file path in files).
outDir - Output files directory. If None, no files are saved.
files - A list of file names or file numbers.
eleList - A list of electrodes to save (0-nchannels).
prefix - List of filename prefix. When files are provided as numbers, the prefix
list is used to search for the file in inDir. First matched file is
used as the file. Default ['NEUR'].
suffix - Data files suffix. Used to construct filename when files are provided
as numbers. Default 'DF1'.
nchannels - Number of neuronal channels recorded. Default is DATANCHANNELS (32).
freq - Sampling frequency. Default is DATAFREQ (32KHz).
verbose - Whether to log more information.
Returns:
channels, timestamps
Channels [nsamples x nchannels] is the neuronal data. All channels are returned.
Timestamps [nblocks x 2] are the beginning and finish timestamps of each block.
"""
#
# Get input file list.
#
filepaths = getDataFiles (inDir, files, prefix, suffix, verbose)
channels, timestamps = wirelessToChannels (None, filepaths, verbose=verbose,
nchannels=nchannels, freq=freq,
savetype=savetype)
elecfiles = None
if not (outDir is None):
safeOutputDir (outDir)
#
# Find first and last file numbers.
#
nums = (int (re.sub ('\D', '', os.path.basename (f).split ('.') [0]))
for f in filepaths)
nums = sorted (nums)
file0, filen = nums [0], nums [-1]
#
# Create electrode files.
#
elecfilenames = (os.path.join (outDir, f'Elec{e}-F{file0}T{filen}.bin')
for e in elecList)
for elec, name in zip (elecList, elecfilenames):
channels [:, elec].tofile (open (name, 'wb'))
if verbose:
logging.info (f'Electrode {elec} dumped to file {name}.')
return channels, np.linspace (0,
(timestamps [-1][1] - timestamps [0][0])/1000,
len (channels))
#
# Transform wireless data to motion data
#
def wirelessToMotion (base, files, outdir=None, prefix='NEUR',
verbose=False, tolerance=2, blocktolerance=3):
logging.info("started wirelessToMotion function")
sensors = ['acc', 'gyr', 'mag']
axes = ['x', 'y', 'z']
files = (f if type (f) is str else f'{prefix}{f:04d}.DT2'
for f in files)
if not base is None:
files = (os.path.join (base, datafile) for datafile in files)
timestamps = []
datawords = []
offsets = []
spans = []
goodblocks = []
# Original data for each of the data types.
origdata = [[], [], []]
prevtimestamp = 0
for datafile in files:
if verbose:
print(f'Read raw file {datafile}')
fd = open(datafile, 'rb')
data = np.fromfile(fd, dtype=np.uint16)
fd.close()
# Data files should be fixed length.
if len (data)*2 != DATAFILELEN:
raise Exception (f'File {datafile} size is {len (data)*2}!')
# Data shape is n x channels
data = data.reshape (-1, DATANCHANNELS)
#
# Motion data is in blocks of 1024 words.
# As motion data is a channel in the data, each block neuronal data is
# 1024*32KHz = 32mSec. However for motion data we have timestamps. In
# cases where we don't have a timestamp (bad block) we assume 32mSec.
#
motiondata = data [:,DMCHANNEL].reshape (-1, 1024)
cgoodblocks = (
np.all (motiondata [:, :2] == DMSIGNATURE, axis=1) &
(motiondata [:, 9] == 0)
)
cbadblocks = np.nonzero (np.logical_not (cgoodblocks)) [0]
if not np.any (cgoodblocks):
# No good blocks in file. Add zeros to data.
timestamps.append (np.zeros_like (cgoodblocks))
datawords.append (np.zeros_like (cgoodblocks))
offsets.append (np.zeros_like (cgoodblocks))
spans.append (np.ones_like (cgoodblocks)*32)
goodblocks.append (cgoodblocks)
origdata.append (np.zeros ((1, 9)))
ctimestamps = np.array (motiondata [:, 10] + motiondata [:, 11] * 2**16)
cdatawords = motiondata [:, 6:9]
coffsets = motiondata [:, 2:5]
cspans = np.zeros_like (ctimestamps)
cspans [:-1] = ctimestamps [1:] - ctimestamps [:-1]
# Sanity check on timestamps
insaneblocks = (cspans > 2048) | (cspans < 0)
cgoodblocks [insaneblocks] = False
cbadblocks = np.nonzero (np.logical_not (cgoodblocks)) [0]
if len (cbadblocks) > 0:
start, finish, length = runs_of_ones_array (
np.logical_not (cgoodblocks))
logging.warning (f'{datafile}: Bad blocks at: ' +
' '.join ([f'{s}-{f-1} ({l})' for s, f, l in
zip (start, finish, length)]))
# logging.info (f'CSpans {cspans}')
# logging.info (f'CTimestamps {ctimestamps}')
# Fix last block of previous file using first timestamp.
if len (spans) > 0:
spans [-1] [-1] = ctimestamps [0] - timestamps [-1] [-1]
else:
# Handle first file. First block is empty.
cspans [0] = 0
#
# Handle badblocks:
# Block timespan
# --------------
# Since we have no indication of the block's timestamp we need to make
# assumptions. Since a single block is 1024 words @ 32KHz, each block
# spans 32mSec of neuronal data.
#
# Values
# ------
# Insert 0 value for the appropriate length. Since the block is bad we
# just overwrite the block with zeros and reference them. Although
# magnetormeter data is usually sampled at a lower frequency, we're
# resampling the data anyhow, so it's not importanct to follow the
# sample rate.
#
cspans [cbadblocks] = 32 * 16
motiondata [cbadblocks,
DMHEADERSIZE:(DMHEADERSIZE+32*3*3)] = 0
cdatawords [cbadblocks] = [32*3, 32*3, 32*3]
coffsets [cbadblocks] = (DMHEADERSIZE + 32*3*0,
DMHEADERSIZE + 32*3*1,
DMHEADERSIZE + 32*3*2)
#
# Add data to processes files lists.
#
timestamps.append (ctimestamps)
datawords.append (cdatawords)
offsets.append (coffsets)
spans.append (cspans)
goodblocks.append (cgoodblocks)
origdata [0].append (np.concatenate (
[motiondata [block, offset:offset+datalen].astype (np.int16)
for block, (offset, datalen)
in enumerate (zip (coffsets [:,0], cdatawords [:,0]))]
))
origdata [1].append (np.concatenate (
[motiondata [block, offset:offset+datalen].astype (np.int16)
for block, (offset, datalen)
in enumerate (zip (coffsets [:,1], cdatawords [:,1]))]
))
origdata [2].append (np.concatenate (
[motiondata [block, offset:offset+datalen].astype (np.int16)
for block, (offset, datalen)
in enumerate (zip (coffsets [:,2], cdatawords [:,2]))]
))
# print ([(block, offset, datalen, motiondata [block].shape)
# for block, (offset, datalen)
# in enumerate (zip (coffsets [0], cdatawords [0]))])
prevtimestamp = ctimestamps [-1]
# Flatten data from all files and remove trailing empty blocks
goodblocks = np.concatenate (goodblocks)
if not np.any (goodblocks):
logging.error (f'No good blocks were found in files.')
resampled = np.zeros ((0, 3*3))
df = pd.DataFrame (resampled,
columns=pd.MultiIndex
.from_product ([sensors, axes],
names=['sensorName', 'sensorNum']))
return df
# We drop the last block so we have valid timestamps.
lastgood = np.where (goodblocks) [0] [-1]
goodblocks = goodblocks [:lastgood]
origdata = [np.concatenate (data).reshape (-1, 3) for data in origdata]
timestamps = np.concatenate (timestamps) [:lastgood+1]
timestamps = timestamps / DMSAMPLERATE / DMTSFACTOR
datawords = np.concatenate (datawords) [:lastgood]
offsets = np.concatenate (offsets) [:lastgood]
spans = (np.concatenate (spans) / DMTSFACTOR) [:lastgood].astype (int)
# Fix last span. As we don't have the next timestamp, we assume 32mSec.
spans [-1] = 32
# Resample data if necessary. Mismatched is 0 for correct # of samples.
resampled = np.zeros ((int (np.sum (spans)), 3*3))
mismatched = (spans.reshape (-1, 1) - datawords [:lastgood]/3)
intolerable = np.abs (mismatched) > tolerance
btimes = np.concatenate (([0], np.add.accumulate (spans))).astype (int)
# logging.info (f'BTimes {btimes}')
logging.info (f'Resampling')
for datatype in range (2):
# Copy non mismatched good blocks
logging.info (f'Copying good blocks {datatype}.')
boffsets = np.concatenate (([0],
np.add.accumulate (datawords [:, datatype]/3))).astype (int)
s, f, n = runs_of_ones_array ((mismatched [:, datatype] == 0) * 1)
for bstart, bfinish, nblocks in zip (s, f, n):
target0 = btimes [bstart]
target1 = btimes [bfinish]
source0 = boffsets [bstart]
source1 = boffsets [bfinish]
resampled [target0:target1, datatype*3:(datatype+1)*3] = (
origdata [datatype] [source0:source1]
)
# Fix over tolerance blocks.
logging.info (f'Fixing intolerable blocks {datatype}.')
for b,e,l in zip (*runs_of_ones_array (intolerable [:, datatype])):
# This is a reversed graph with X as the position of samples
# (integer values are samples), and Y the timestampes. Since we need
# to interpolate on a different timescale we compute the timestamp
# of each sampled point within a block by interpolation of Y, and
# setting the expected number of samples within the block (instead
# of the existing one).
# Generate resampled x points in the run
x = np.arange (np.sum (datawords [b:e, datatype] / 3))
# Compute the location of sampled timestamps
xp = np.add.accumulate (
np.concatenate (([0], datawords [b:e, datatype] / 3))
)
# The timestamps at block boundaries
yp = timestamps [b:e+1] * DMSAMPLERATE
source0 = boffsets [b]
source1 = boffsets [e]
target0 = btimes [b]
target1 = btimes [e]
# Use interpolate to locate the sample timestamps within blocks.
st = np.interp (x, xp, yp)
# Reset start to 0
st = (st - st [0])
# Resample the run
logging.info (f'Resampling run {b}-{e}:{l}')
logging.info (f's0 {source0}:s1 {source1}, t0 {target0}:t1 {target1}')
for i, ri in zip (range (3), range (datatype*3, datatype*3+3)):
resampled [target0:target1, ri] = np.interp (
np.arange (target1 - target0),
st, origdata [datatype] [source0:source1, i])
# Set fixed blocks as good.
# Fix blocks within tolerance where aberration persists.
summed = np.add.accumulate (mismatched [:, datatype])
# Compute over tolerance blocks
state = summed [0]
fixedpos = 0
dataoff = datatype*3
logging.info (f'Fixing long aberration {datatype}.')
for i in np.where (summed [:-1] != summed [1:]) [0]:
# Have we handled this transition already
if i < fixedpos or intolerable [i+1, datatype]:
# print (f'Skipping fixed {fixedpos} or intolerable block {i+1}')
state = summed [i+1]
continue
# Does this aberration right itself.
pos0 = np.where (summed [i+2:i+1+blocktolerance] == state) [0]
# print (i+1, pos0)
if len (pos0) > 0:
# We have a 0 - This block rights itself in the next blocks.
pos0 = pos0 [0] + i+2
# print (f'Self righting block {i+1} @ {pos0}: {source0}:{source1} -> {target0}:{target1}/{state}')
# Check no intolerable blocks interrupt.
if not np.any (intolerable [pos0:i+1+blocktolerance, datatype]):
source0 = boffsets [i+1]
source1 = boffsets [pos0+1]
target0 = btimes [i+1]
target1 = btimes [pos0+1]
resampled [target0:target1, dataoff:dataoff+3] = (
origdata [datatype] [source0:source1]
)
fixedpos = pos0
continue
# We need to resample the block.
#x = np.arange (np.sum (datawords [b:e, datatype] / 3))
# Compute the location of sampled timestamps
#xp = np.array ([0, datawords [i+1] / 3)
# The timestamps at block boundaries
#yp = timestamps [i+1:i+3] * DMSAMPLERATE
source0 = boffsets [i+1]
source1 = boffsets [i+2]
target0 = btimes [i+1]
target1 = btimes [i+2]
# Use interpolate to locate the sample timestamps within blocks.
#st = np.interp (x, xp, yp)
# Reset start to 0
#st = (st - st [0])
st = np.linspace (0,
timestamps [i+2]-timestamps [i+1],
source1-source0+1) [:-1] * DMSAMPLERATE
# Resample the run
for si, ti in zip (range (3), range (datatype*3, datatype*3+3)):
# print ('Data')
# print (origdata [datatype] [source0:source1, i])
# print ('Sample times')
# print (st)
# print (f'New range: {target1 - target0}')
resampled [target0:target1, ti] = np.interp (
np.arange (target1 - target0),
st, origdata [datatype] [source0:source1, si])
# print (f'Resampled block {source0}:{source1} -> {target0}:{target1}/{state} {i}{summed [i-5:i+5]}')
state = summed [i+1]
fixedpos = i+1
# Handle the magnetometer data using resample. Since it's sampled at 111Hz,
# we'll resample every 9 blocks taking 7 blocks each time.
boffsets = np.concatenate (([0],
np.add.accumulate (datawords [:, 2]/3))).astype (int)
logging.info (f'Resampling magnetometer.')
for b, e, l in zip (*runs_of_ones_array (goodblocks [:-1])):
logging.info (f'Run {b}-{e}:{l}')
for si, ti in zip (range (3), range (6, 9)):
if l < 9:
source0 = boffsets [b]
source1 = boffsets [e]
target0 = btimes [b]
target1 = btimes [e]
# For short sequences we have to resample as is
resampled [target0:target1, ti] = (
sig.resample (origdata [2] [source0:source1, si],
target1 - target0)
)
continue
# First block has a boundary issue
source0 = boffsets [b]
source1 = boffsets [b+9]
target0 = btimes [b]
target1 = btimes [b+8]
target2 = btimes [b+9]
resampled [target0:target1, ti] = (
sig.resample (origdata [2] [source0:source1, si],
target2 - target0) [:target1 - target0]
)
# Handle all interim resamples (available
data = []
# for bi in range (b+8, e-8, 7):
# try:
# data.append (sig.resample (origdata [2] [boffsets [bi]:boffsets [bi+9],
# si],
# btimes [bi+8] - btimes [bi-1])
# [btimes [bi]-btimes [bi-1]:btimes [bi+7] - btimes [bi-1]])
# except Exception as e:
# print (f'Exception @{bi}')
# print (btimes [bi-1], btimes [bi+8])
# print (boffsets [bi], boffsets [bi+9])
# traceback.print_exception (type (ex), ex, ex.__traceback__)
data = [sig.resample (origdata [2] [boffsets [bi]:boffsets [bi+9],
si],
btimes [bi+8] - btimes [bi-1])
[btimes [bi]-btimes [bi-1]:btimes [bi+7] - btimes [bi-1]]
for bi in range (b+8, e-8, 7)]
data = np.concatenate (data)
target0 = target1
target1 = target0 + len (data)
resampled [target0:target1, ti] = data
# Handle last resample block
nb = b+8 + (e - b-8) // 7 * 7
source0 = boffsets [nb - 1]
source1 = boffsets [e+1]
targetb = btimes [nb-1]
target0 = btimes [nb]
target1 = btimes [e+1]
resampled [target0:target1, ti] = (
sig.resample (origdata [2] [source0:source1, si],
target1 - targetb) [target0-targetb:]
)
df = pd.DataFrame (resampled,
columns=pd.MultiIndex
.from_product ([sensors, axes],
names=['sensorName', 'sensorNum']),)
return df
#
# Transform wireless data to motion data
#
def wirelessToMotionV2 (base, files, prefix=[ 'NEUR' ], suffix='DF1',
verbose=False, tolerance=2, blocktolerance=3):
logging.info("started wirelessToMotion function")
sensors = ['acc', 'gyr', 'mag']
axes = ['x', 'y', 'z']
files = getDataFiles (base, files, prefix, suffix, verbose)
btimestamps = [] # These are the block timestamps. They're mostly ignored.
timestamps = []
datawords = []
offsets = []
spans = []
goodblocks = []
# Original data for each of the data types.
origdata = [[], [], []]
prevtimestamp = 0
for datafile in files:
if verbose:
print(f'Read raw file {datafile}')
fd = open(datafile, 'rb')
data = np.fromfile(fd, dtype=np.uint16)
fd.close()
#
# Generic Stage
#
# Data files should be fixed length.
if len (data)*2 != DATAFILELEN:
raise Exception (f'File {datafile} size is {len (data)*2}!')
# File is composed of 64KB blocks.
blocks = data.reshape (-1, BLOCKLEN // 2)
# Test blocks signatures.
filegoodblocks = np.all (
blocks [:, :len(BLOCKSIGNATURE)] == BLOCKSIGNATURE, axis=1)
# Extract timestamps.
#timestamps = np.dot (blocks [:, 8:10], [[1], [2**16]])
#timestamps = timestamps.astype (np.uint32).reshape (-1)
# Extract data partitions.
# Partition info are 3 uint32: Type, Start, Length.
nblocks = len (blocks)
compmat = (np.diag (np.ones (7*6)) [::2] +
np.diag (np.ones (7*6)) [1::2] * 2**16).T
partinfo = np.dot (blocks [:, 12:54], compmat).reshape (nblocks, -1, 3)
# Get reference to neuronal data.
ind0, ind1 = np.where (partinfo [filegoodblocks, :, 0] == MOTIONTYPE)
if np.any (np.unique (ind0, return_counts=True) [1] > 1):
raise f'Non unique neuronal data partition in {datafile}'
motiondata = []
for i0, i1 in zip (ind0, ind1):
_, start, length = partinfo [i0, i1]
motiondata.append (
blocks [i0, int (start // 2):int ((start + length) // 2)]
)
motionheads = np.array ([d [:16] for d in motiondata])
cgoodblocks = (
np.all (motionheads [:, :2] == DMSIGNATURE, axis=1) &
(motionheads [:, 9] == 0)
)
# print (f'{datafile}: Blocks shape {blocks.shape} Good {cgoodblocks}')
cbadblocks = np.nonzero (np.logical_not (cgoodblocks)) [0]
if not np.any (cgoodblocks):
# No good blocks in file. Add zeros to data.
timestamps.append (np.zeros_like (cgoodblocks))
datawords.append (np.zeros_like (cgoodblocks))
offsets.append (np.zeros_like (cgoodblocks))
spans.append (np.ones_like (cgoodblocks)*32)
goodblocks.append (cgoodblocks)
origdata.append (np.zeros ((1, 9)))
ctimestamps = np.array (motionheads [:, 10] +
motionheads [:, 11] * 2**16)
ctimestamps2 = np.array ((motionheads [:, 10],
motionheads [:, 11]))
cdatawords = motionheads [:, 6:9]
coffsets = motionheads [:, 2:5]
cspans = np.zeros_like (ctimestamps)
cspans [:-1] = ctimestamps [1:] - ctimestamps [:-1]
# Sanity check on timestamps
insaneblocks = (cspans > 2048) | (cspans < 0)