-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReadGen2Data.py
1790 lines (1630 loc) · 84.6 KB
/
ReadGen2Data.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
import os, re, struct, glob, copy, collections.abc, biosppy, time
import pandas as pd, datetime as dt, numpy as np
import matplotlib.pyplot as plt, matplotlib.dates as md
from scipy import signal
from scipy.stats import describe, moment
from skimage.restoration import denoise_wavelet
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import auc
from sklearn.metrics import RocCurveDisplay
from sklearn.model_selection import StratifiedKFold
from scipy.signal import find_peaks
from scipy.interpolate import interp1d
from matplotlib.lines import Line2D
# A class to represent a pretty float to 2 decimal places.
class PrettyFloat2(float):
def __repr__(self):
return "%0.2f" % self
# A class to represent a pretty float to 4 decimal places.
class PrettyFloat4(float):
def __repr__(self):
return "%0.4f" % self
# A class to represent a pretty float to 6 decimal places.
class PrettyFloat6(float):
def __repr__(self):
return "%0.6f" % self
class ConvenienceFunctions(object):
def __init__(self):
pass
def ReadJsonAsPdAndFilter(jsonPath, filterList=[]):
'''
Reads the json file and returns a pandas dataframe with the filtered columns
Parameters
----------
jsonPath : str
Path to the json file
filterList : list of tuples
List of properties to filter the filenames by
Example: [('lowNoise','True'), ('site','SiteY'), ('subjectType','LVO')]
Returns
-------
pdData : pandas dataframe
Pandas dataframe with the filtered columns
'''
pdData = pd.read_json(jsonPath)
for filter in filterList:
pdData = pdData[pdData[filter[0]] == filter[1]]
pdData = pdData.reset_index(drop=True)
return pdData
def CleanName(name):
'''
Cleans the name of the file by converting to upper case and removing the leading zeros in any number
Parameters
----------
name : str
Name of the file
Returns
-------
name : str
Cleaned name of the file
'''
#Split the name into parts aphabet and number
parts = re.split('(\d+)', name)
#Check if the first part is a number
if parts[0].isdigit():
return name.lstrip('0')
return parts[0].upper() + parts[1].lstrip('0')
def NormalizeFeaturesAndRunKFoldCrossValidationWithRF(x, y, folds=5, RFDepth=3, featureNames=None):
'''
Normalizes the features and runs k-fold cross validation with RF
Parameters
----------
x : numpy array
Features
y : numpy array
Labels
folds : int
Number of folds for k-fold cross validation
RFDepth : int
Depth of the random forest
featureNames : list of str
Names of the features
Returns
-------
mean_auc : float
Mean AUC of the ROC curve
'''
sc = StandardScaler()
X_scaled = sc.fit_transform(x)
if featureNames is not None:
if RFDepth > 0:
clf = RandomForestClassifier(max_depth=RFDepth)
else:
clf = RandomForestClassifier()
clf.fit(X_scaled, y.ravel())
#Get feature importance sorted by importance
featureImportance = np.argsort(clf.feature_importances_)[::-1]
#Print feature importance and names on the same line with 4 decimal places and stop at 5 features
for i in range(len(featureImportance)):
print(featureNames[featureImportance[i]], PrettyFloat4(clf.feature_importances_[featureImportance[i]]),featureImportance[i], end=", ")
if i == 4:
break
print()
#Set a seed for reproducibility(should be random otherwise)
np.random.seed(454545)
#Create ROC curve with RF using k-fold cross validation
cv = StratifiedKFold(n_splits=folds)
if RFDepth > 0:
classifier = RandomForestClassifier(max_depth=RFDepth)
else:
classifier = RandomForestClassifier()
tprs = []
aucs = []
mean_fpr = np.linspace(0, 1, 100)
fig, ax = plt.subplots(figsize=(6, 6))
for fold, (train, test) in enumerate(cv.split(X_scaled, y.ravel())):
classifier.fit(X_scaled[train], y[train].ravel())
viz = RocCurveDisplay.from_estimator(
classifier,
X_scaled[test],
y[test].ravel(),
name=f"ROC fold {fold}",
alpha=0.3,
lw=1,
ax=ax,
)
interp_tpr = np.interp(mean_fpr, viz.fpr, viz.tpr)
interp_tpr[0] = 0.0
tprs.append(interp_tpr)
aucs.append(viz.roc_auc)
ax.plot([0, 1], [0, 1], "k--", label="chance level (AUC = 0.5)")
mean_tpr = np.mean(tprs, axis=0)
mean_tpr[-1] = 1.0
mean_auc = auc(mean_fpr, mean_tpr)
std_auc = np.std(aucs)
ax.plot(
mean_fpr,
mean_tpr,
color="b",
label=r"Mean ROC (AUC = %0.2f $\pm$ %0.2f)" % (mean_auc, std_auc),
lw=2,
alpha=0.8,
)
std_tpr = np.std(tprs, axis=0)
tprs_upper = np.minimum(mean_tpr + std_tpr, 1)
tprs_lower = np.maximum(mean_tpr - std_tpr, 0)
ax.fill_between(
mean_fpr,
tprs_lower,
tprs_upper,
color="grey",
alpha=0.2,
label=r"$\pm$ 1 std. dev.",
)
ax.set(
xlim=[-0.05, 1.05],
ylim=[-0.05, 1.05],
xlabel="False Positive Rate",
ylabel="True Positive Rate",
title=f"Mean ROC curve with variability",
)
ax.axis("square")
ax.legend(loc="lower right")
plt.show()
return mean_auc, (mean_fpr, mean_tpr)
class ScanParams(object):
"""Class to store the scan parameters - device parameters, physical constant, processing flags"""
def __init__(self, scanPath, calPathIn = None, scanTypeIn = 2, correctionTypeIn = -1):
"""
Creates a parameter object of HeadScanParams class
Parameters
----------
scanName : str
Folder on disk where the scan data is stored
calPathIn : str
Folder to the disk where the calibration data is stored
scanTypeIn : str
0 - Unilateral, 1 - Bilateral, 2 - Long scan, 3 - Four Camera, 4 - Four Camera long scan
Pattern used to scan subject
"""
#TODO: Move the general scan params into this class
self.path = scanPath
self.scanType = scanTypeIn-1
#0 - Initial device scan order Right Horizontal, Left Horizontal, Right Temple, Left Temple
#1 - Simultaneous scan order Horizontal, Near, Temple, Horizontal Repeat
#All processing is done Ch0 and then Ch1
self.cameraGain = [[16,16,16,16,1,1,1,1],[16,1,16,16,16,1,16,16]] #1 is high
self.cameraPosition = [['RH','LH','RV','LV','RN','LN','RN','LN',],
['RH','LN','RV','RH','LH','RN','LV','LH',]]
self.correctionType = correctionTypeIn
self.printStats = False
self.imageWidth = 2320
self.histLength = 1028 #Includes the last four numbers added on
self.numBinsHist = 1024
self.darkBinThresh = [256,128]
self.hiGainSetting = []
self.noisyBinMin = 100
self.dt = 0.025
class PulseFeatures(object):
"""
Class to store the pulse features
Parameters
----------
samplingIn : float
Sampling rate of the input data
"""
def __init__(self,samplingIn=1/40):
self.sampling = samplingIn
self.areaUnderCurve = None
self.areaUnderCurveP1 = None
self.amplitude = None
self.average = None
self.unbiasedAmp = None
self.modulationDepth= None
self.skewness = None
self.kurtosis = None
self.pulseCanopy = None
self.pulseOnset = None
self.pulseOnsetProp = None
self.secondMoment = None
self.veloCurveIndex = None
self.veloCurveIndexHann = None
self.veloCurveIndexNorm = None
self.veloCurveIndexHannNorm = None
self.noiseMetric = None
self.featureList = ['modulationDepth','areaUnderCurve','areaUnderCurveP1','skewness','kurtosis','pulseCanopy','pulseOnset','pulseOnsetProp','secondMoment','amplitude','unbiasedAmp','veloCurveIndex','veloCurveIndexHann',
'veloCurveIndexNorm','veloCurveIndexHannNorm','noiseMetric']
self.featureNames = ['Modulation depth','Area under curve','Area under curve P1','Skewness','Kurtosis',
'Pulse canopy','Pulse onset','Pulse onset proportion','Second Moment','Amplitude','Unbiased Amplitude','Velocity curve index',
'Velocity curve index Hanning','Velocity curve index normalized','Velocity curve index Hanning normalized','noiseMetric']
self.featruesAndNames = dict(zip(self.featureList,self.featureNames))
def GetAreaUnderCurve(self, goldenPulse):
'''
Returns the area under the curve for the input waveform
Parameters
----------
goldenPulse : 1D numpy array
Input goldenPulse
Returns
-------
areaUnderCurve : float
Area under the curve
'''
mini = np.amin(goldenPulse)
goldenPulse -= mini
maxi = np.amax(goldenPulse)
goldenPulse /= maxi
#Smooth data for better peak detection
#100 ms window is the length we are shooting for
window = round(0.1/(self.sampling))
smoothPulse = signal.convolve(goldenPulse,
signal.hann(window)/np.sum(signal.hann(window)),
'same')
argmax = np.argmax(smoothPulse)
return np.sum(goldenPulse), np.sum(smoothPulse[:argmax])
def ComputeVCI(self, goldenPulseIn, hanningFilter=False):
'''
Computes the velocity curve index for the input waveform
Parameters
----------
goldenPulseIn : 1D numpy array
Input goldenPulse
hanningFilter : bool
If true, apply a hanning filter to the input waveform
Returns
-------
canopyVCI : float
Velocity curve index for the canopy
pulseLengthNormalizedCanopyVCI : float
Velocity curve index for the canopy normalized by the pulse length
'''
#Strech pulse between 0-1
goldenPulse = copy.deepcopy(goldenPulseIn)
goldenPulse -= np.amin(goldenPulse)
goldenPulse /= np.amax(goldenPulse)
goldenPulse = 1-goldenPulse
gPIndex = np.arange(len(goldenPulse))*self.sampling
#We use 4x oversampling to get a smoother gradient
gPIndexUpSamp = np.arange(len(goldenPulse)*4)*self.sampling/4
gPUpSample = np.interp(gPIndexUpSamp, gPIndex, goldenPulse)
if hanningFilter:
#90 ms window is the length we are shooting for
window = round(0.09/(self.sampling/4))
gPUpSample = signal.convolve(gPUpSample,
signal.hann(window)/np.sum(signal.hann(window)),
'same')
grad = np.gradient(gPUpSample,self.sampling/4)
grad2 = np.gradient(grad,self.sampling/4)
k = np.abs(grad2)/((1+grad**2)**1.5)
indsInCanopy = gPUpSample > 0.25
indsInCanopy = np.flatnonzero(indsInCanopy)
canopyVCI = np.sum(k[indsInCanopy])
return canopyVCI, canopyVCI/len(gPIndexUpSamp)
def ComputeWaveformAttributes(self, goldenPulse):
'''
Computes the following features:
Canopy - the proportion of time spent above 25% of the systolic-diastolic range
Onset - the time taken to reach systolic maximum from onset 0-90% ranges are used to filter out fit/averaging noise
Relative onset - time spent in systolic part relative to whole pulse
Parameters
----------
goldenPulse : 1D numpy array
Fitted/average pulses in the scan
Returns
-------
canopy : float
Proportion of time spent above 25% of the systolic-diastolic range
onset : float
Time taken to reach systolic maximum from onset 0-90% ranges are used to filter out fit/averaging noise
onsetProp : float
Time spent in systolic part relative to whole pulse
variance : float
Variance of the pulse
velCurInd : float
Velocity curve index for the canopy
velCurIndNorm : float
Velocity curve index for the canopy normalized for the pulse length
velCurIndHann : float
Velocity curve index for the canopy with a hanning filter
velCurIndHannNorm : float
Velocity curve index for the canopy with a hanning filter normalized for the pulse length
'''
pulseRange = np.nanmax(goldenPulse)-np.nanmin(goldenPulse)
totalTime = np.count_nonzero(~np.isnan(goldenPulse))
indsInCanopy = goldenPulse < np.nanmax(goldenPulse)-pulseRange*0.25
velCurInd, velCurIndNorm = self.ComputeVCI(goldenPulse)
velCurIndHann, velCurIndHannNorm = self.ComputeVCI(goldenPulse,True)
canopy = np.sum(indsInCanopy)/totalTime
startInd = np.nanargmax(goldenPulse[:5])
sysRange = np.nanmax(goldenPulse)-pulseRange*0.9
sysInds = goldenPulse>sysRange
endInd = np.nonzero(~sysInds)[0][0]
onset = float(abs(endInd-startInd))*self.sampling
onsetProp = float(abs(endInd-startInd))/totalTime
return canopy, onset, onsetProp, moment(goldenPulse,2), velCurInd, velCurIndHann, velCurIndNorm, velCurIndHannNorm
def GetWaveformAttributesForSingleChannelPulse(self,goldenPulse):
'''
Computes the following features:
Area under curve
Area under curve for the systolic part
Amplitude
Modulation depth
Skewness
Kurtosis
Canopy - the proportion of time spent above 25% of the systolic-diastolic range
Onset - the time taken to reach systolic maximum from onset 0-90% ranges are used to filter out fit/averaging noise
Relative onset - time spent in systolic part relative to whole pulse
Parameters
----------
goldenPulse : 1D numpy array
Fitted/average pulses in the scan
'''
if np.isnan(goldenPulse).all():
return
gpDistribution = goldenPulse-np.amin(goldenPulse)
gpDistribution = np.amax(gpDistribution)-gpDistribution
gpDistribution = gpDistribution / np.sum(gpDistribution)
self.areaUnderCurve, self.areaUnderCurveP1 = self.GetAreaUnderCurve(np.copy(gpDistribution))
self.amplitude = np.amax(goldenPulse) - np.amin(goldenPulse)
self.modulationDepth = self.amplitude/np.mean(goldenPulse)
gpDescription = describe(gpDistribution)
self.skewness = gpDescription.skewness
self.kurtosis = gpDescription.kurtosis
canopy, onset, onsetProp, secMoment, vci, vciHann, vciNorm, vciHannNorm = \
self.ComputeWaveformAttributes(goldenPulse)
self.pulseCanopy = canopy
self.pulseOnset = onset
self.pulseOnsetProp = onsetProp
self.secondMoment = secMoment
self.veloCurveIndex = vci
self.veloCurveIndexHann = vciHann
self.veloCurveIndexNorm = vciNorm
self.veloCurveIndexHannNorm = vciHannNorm
def AppendWaveformAttributesForSingleChannelPulse(self,pulseIn):
'''
Computes the following features:
Area under curve
Area under curve for the systolic part
Amplitude
Modulation depth
Skewness
Kurtosis
Canopy - the proportion of time spent above 25% of the systolic-diastolic range
Onset - the time taken to reach systolic maximum from onset 0-90% ranges are used to filter out fit/averaging noise
Relative onset - time spent in systolic part relative to whole pulse
Parameters
----------
goldenPulse : 1D numpy array
Fitted/average pulses in the scan
'''
pulse = np.copy(pulseIn)
#If this is the first pulse, then initialize the arrays
if self.areaUnderCurve is None:
for feature in self.featureList:
self.__dict__[feature] = []
#Drop leading nan values
while np.isnan(pulse[0]):
pulse = pulse[1:]
#Drop trailing nan values
while np.isnan(pulse[-1]):
pulse = pulse[:-1]
# if any of the remaining values are nan, then skip this pulse
if np.isnan(pulse).any():
for feature in self.featureList:
self.__dict__[feature].append(np.nan)
return
gpDistribution = pulse-np.amin(pulse)
gpDistribution = np.amax(gpDistribution)-gpDistribution
gpDistribution = gpDistribution / np.sum(gpDistribution)
areaUnderCurve, areaUnderCurveP1 = self.GetAreaUnderCurve(np.copy(gpDistribution))
self.areaUnderCurve.append(areaUnderCurve)
self.areaUnderCurveP1.append(areaUnderCurveP1)
self.amplitude.append(np.amax(pulse) - np.amin(pulse))
self.average.append(np.mean(pulse))
self.unbiasedAmp.append(np.amax(pulse[:int(pulse.shape[0]/2)]) - np.amin(pulse[:int(pulse.shape[0]/2)]))
self.modulationDepth.append( self.amplitude/np.mean(pulse) )
gpDescription = describe(gpDistribution)
self.skewness.append( gpDescription.skewness )
self.kurtosis.append( gpDescription.kurtosis )
canopy, onset, onsetProp, secMoment, vci, vciHann, vciNorm, vciHannNorm = \
self.ComputeWaveformAttributes(pulse)
self.pulseCanopy.append(canopy)
self.pulseOnset.append(onset)
self.pulseOnsetProp.append(onsetProp)
self.secondMoment.append(secMoment)
self.veloCurveIndex.append(vci)
self.veloCurveIndexHann.append(vciHann)
self.veloCurveIndexNorm.append(vciNorm)
self.veloCurveIndexHannNorm.append(vciHannNorm)
slopeChangeCount = np.absolute(np.diff(np.heaviside(np.diff(pulse,n=1),1))).sum()
self.noiseMetric.append(slopeChangeCount)
class ChannelData(object):
'''
Class to hold data for a single channel
'''
def __init__(self):
self.imagePathLaserOff = None
self.imageLaserOffHistWidth = None
self.imageLaserOffImgMean = None
self.imagePathLaserOn = None
self.histogramPath = None
self.darkHistogramPath = None
self.dataAvailable = True
self.contrastNoFilter = None
self.correctedMean = None
self.contrast = None
self.imageMean = None
self.imageStd = None
self.camTemps = None
self.hr = None
self.initialCamTemp = None
self.timeStamps = None
self.NCCPulse = None
self.goldenPulse = None
self.pulseSegments = None
self.onsets = None
self.pulseValid = None
self.splinePulse = None
self.channelPosition = None
self.goldenPulseFeatures = None
self.pulseSegmentsFeatures = None
self.contrastVertNorm = None
self.imgMeanVertNorm = None
class ReadGen2Data:
'''
Class to read in data from Gen2 camera
'''
def __init__(self, pathIn, deviceID=-1, correctionTypeIn=0, scanTypeIn=1, enablePlotsIn=False, filterDriftIn=False,
filterNoiseIn=True):
self.path = pathIn
#Check if dark hitogram is present
tmpList = glob.glob(os.path.join(self.path,"histo_output_darkscan_ch_*"))
if len(tmpList)==0:
self.darkHistogramsAvailable = False
else:
self.darkHistogramsAvailable = True
#Set 4 channel scan and long scan types automagically
if 'LONGSCAN_4C' in self.path:
scanTypeIn = 4
correctionTypeIn = 1
print('Long scan with 4 channels detected. Setting scanType to {} and correctionType to {}.'.format(scanTypeIn,correctionTypeIn))
elif 'LONGSCAN' in self.path:
scanTypeIn = 2
correctionTypeIn = 1
print('Long scan detected. Setting scanType to {} and correctionType to {}.'.format(scanTypeIn,correctionTypeIn))
elif 'FULLSCAN_4C' in self.path:
scanTypeIn = 3
correctionTypeIn = 1
print('4 channel scan detected. Setting scanType to {} and correctionType to {}.'.format(scanTypeIn,correctionTypeIn))
elif 'FULLSCAN' in self.path and self.darkHistogramsAvailable:
scanTypeIn = 1
correctionTypeIn = 1
print('Simultaneous scan detected. Setting scanType to {} and correctionType to {}.'.format(scanTypeIn,correctionTypeIn))
if not self.darkHistogramsAvailable:
if scanTypeIn==2:
correctionTypeIn = 2
else:
correctionTypeIn = 0
print('Dark histograms not available. Setting correctionType to {} for scanType {}.'.format(correctionTypeIn,scanTypeIn))
self.scanType = scanTypeIn
#0 - Initial device scan order Right Horizontal, Left Horizontal, Right Temple, Left Temple
#1 - Simultaneous scan order Horizontal, Near, Temple, Horizontal Repeat
#2 - Long scan
#3 - 4 channel scan
#4 - Long scan with 4 channels
#All processing is done Ch0 and then Ch1
self.cameraGain = [[16,16,16,16,1,1,1,1], #Initial unilateral scan
[16,1,16,16,16,1,16,16], #Simultaneous scan
[16,16], #Long scan
[16,16,1,16,
1,16,16,1,
16,16,1,16,
1,16,16,1], #4 channel scan
[16,1,16,1], #Long scan with 4 channels
]
self.cameraPosition = [['RH','LH','RV','LV','RN','LN','RN','LN',], #Initial unilateral scan
['RH','LN','RV','RH','LH','RN','LV','LH',], #Simultaneous scan
['RH','LH'], #Long scan
['RH','RH','LN','RH',
'LN','RV','RV','LN',
'LH','LH','RN','LH',
'RN','LV','LV','RN',], #4 channel scan
['RH','LN','LH','RN'], #Long scan with 4 channels
]
self.correctionType = correctionTypeIn
self.longScanCorrectionFactor = None
self.printStats = False
self.enablePlots = enablePlotsIn
self.filterDrift = filterDriftIn
self.filterNoise = filterNoiseIn
self.imageWidth = 2320
self.histLength = 1028 #Includes the last four numbers added on
self.numBinsHist = 1024
self.darkBinThresh = [256,128]
self.hiGainSetting = []
self.noisyBinMin = 100
self.ADCgain = 0.12 # photons/electrons
self.dt = 0.025
self.minbpm = 30
self.maxbpm = 180
self.deviceID = deviceID
self.debugMode = 1 # 0: default. 1: also loads dark images, saves full channel outputs
if scanTypeIn==2 or scanTypeIn==4:
#Get number of histograms in the folder
numScans = len(glob.glob1(self.path,"*histo_output_longscan_*"))
self.channelData = [ ChannelData() for i in range(numScans) ]
else:
if self.scanType<2:
self.channelData = [ ChannelData() for i in range(8) ]
else:
self.channelData = [ ChannelData() for i in range(16) ]
def printTimestamp(self, timestamp):
time_sec = timestamp // 1000000000
time_ns = timestamp % 1000000000
time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time_sec))
time_str += '.{:03d}'.format(time_ns // 1000000)
print(time_str)
def GetTimestamps(self, tsBytes):
'''
Returns the timestamps for the histogram bins
Parameters
----------
tsBytes : 2D numpy array
Histogram bins
Returns
-------
timestamps : 1D list
Timestamps for the histogram bins
'''
#Check if all the input bins are zero
if np.all(tsBytes==0):
return None
timestamps = []
for i in range(tsBytes.shape[0]):
if tsBytes[i,0]==0 and tsBytes[i,1]==0:
break
lowerTS = tsBytes[i,0]
upperTS = tsBytes[i,1]
timestamps.append( int(upperTS)<<32 | int(lowerTS) )
return timestamps
def ReadHistogram(self, histogramPath):
'''
Reads the histogram file and returns the histogram data, object mean, object std, camera temperature and timestamps
'''
histogramFile = open(histogramPath, 'rb')
histogramData1 = histogramFile.read()
histogramFile.close()
histogramu32 = np.frombuffer(histogramData1, dtype=np.uint32)
histogramData = np.copy(histogramu32)
histogramData = histogramData.reshape((histogramu32.shape[0]//(self.numBinsHist+4),self.numBinsHist+4))
timeStamps = self.GetTimestamps(histogramData[:,14:16])
histogramData = histogramData[:,:-4]
histogramData[:,14:18] = 0
histogramf32 = np.frombuffer(histogramData1, dtype=np.float32)
histogramTemp = np.copy(histogramf32)
histogramTemp = histogramTemp.reshape((histogramf32.shape[0]//(self.numBinsHist+4),self.numBinsHist+4))
obMean = np.copy(histogramTemp[:,16])
obStd = np.copy(histogramTemp[:,17])
histogramu8 = np.frombuffer(histogramData1, dtype=np.uint8)
histogramTemp = np.copy(histogramu8)
histogramTemp = histogramTemp.reshape((int(histogramu8.shape[0]/4)//(self.histLength),self.histLength*4))
camTemps = np.flip(histogramTemp[:,4104:4108],axis=1)
camInd = int(re.split('scan_ch_', histogramPath)[1][0])
if(self.scanType <3):
camTemps[:,[1,3]] = camTemps[:,[1,3]] * 1.5625 - 45 # full camera temperature data output
camTemps = camTemps[:,camInd*2+1] # selecting single camera's temp
else:
camTemps[:,camInd] = camTemps[:,camInd] * 1.5625 - 45 # full camera temperature data output
camTemps = camTemps[:,camInd] # selecting single camera's temp
return histogramData, obMean, obStd, camTemps, timeStamps
def GetHistogramStats(self, hist, bins):
binsSq = np.multiply(bins,bins)
if hist.ndim==2:
mean = np.zeros(hist.shape[0])
std = np.zeros(hist.shape[0])
histWid = np.zeros(hist.shape[0])
for i in range(hist.shape[0]):
hist[i][hist[i]<self.noisyBinMin] = 0
mean[i] = np.dot(hist[i],bins)/np.sum(hist[i])
var = (np.dot(hist[i],binsSq)-mean[i]*mean[i]*np.sum(hist[i]))/(np.sum(hist[i])-1)
std[i] = np.sqrt(var)
histWid[i] = np.sum(hist[i]>100)
else:
hist[hist<self.noisyBinMin] = 0
mean = np.dot(hist,bins)/np.sum(hist)
var = (np.dot(hist,binsSq)-mean*mean*np.sum(hist))/(np.sum(hist)-1)
std = np.sqrt(var)
histWid = np.sum(hist>100)
return mean, std, histWid
def GetImageStats(self, image):
histDark, bins = np.histogram(image[:20,:], bins=list(range(self.numBinsHist)))
histDark = histDark[:-1]; bins = bins[:-2] #Remove the 1023 bin
obMean, obStd, obWidth = self.GetHistogramStats(histDark, bins)
histExp, bins = np.histogram(image[20:,:], bins=list(range(self.numBinsHist)))
histExp = histExp[:-1]; bins = bins[:-2]
expRowsMean, expRowsStd, expRowsWidth = self.GetHistogramStats(histExp, bins)
return expRowsMean, expRowsStd, expRowsWidth, obMean, obStd, obWidth
def ReadImage(self, imagePath):
imageFile = open(imagePath, 'rb')
imageData = imageFile.read()
imageFile.close()
if len(imageData)%self.imageWidth:
print('Incomplete image file. Skipping',imagePath)
imageData = np.array([])
else:
imageData = np.array(struct.unpack('<'+str(int(len(imageData)/2))+'H',imageData)).reshape((int(len(imageData)/(self.imageWidth*2)),self.imageWidth))
return imageData
def natural_sort(self,l):
convert = lambda text: int(text) if text.isdigit() else text.lower()
alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
return sorted(l, key=alphanum_key)
def CheckFolderForHistogramsAndImages(self, chPos):
if self.scanType==2 or self.scanType==4:
histogramPatternCh = os.path.join( self.path, "histo_output_longscan_ch_{}*.bin".format(chPos) )
else:
histogramPatternCh = os.path.join( self.path, "histo_output_fullscan_ch_{}*.bin".format(chPos) )
chHistFiles = sorted(glob.glob(histogramPatternCh))
darkHistogramPatternCh = os.path.join( self.path, "histo_output_darkscan_ch_{}*.bin".format(chPos) )
chDarkHistFiles = sorted(glob.glob(darkHistogramPatternCh))
imagePatternCh = os.path.join( self.path, "csix_raw_output_ch_{}*_exp0_*x*_10bit_bayer.y".format(chPos) )
chImageFiles = self.natural_sort(glob.glob(imagePatternCh))
if self.scanType==2 or self.scanType==4 or len(chImageFiles)==8: #Long scans can have arbitrary number of images
chImageFiles = chImageFiles
elif len(chImageFiles)==16: #When we have two or more images for laser on/off. Pick every other one.
skipNum = len(chImageFiles)%8
chImageFiles = [chImageFiles[i] for i in range(len(chImageFiles)) if i % 2 == skipNum]
else:
chImageFiles = []
errorString = 'Missing image files for channel '+str(chPos)+' in the folder:'+self.path
raise ValueError(errorString)
return chHistFiles, chImageFiles, chDarkHistFiles
def ReadHistogramAndImageFileNames(self):
if self.scanType < 3:
numChannels = 2
else:
numChannels = 4
if self.scanType==2 or self.scanType==4:
numScansPerChannel = len(glob.glob1(self.path,"*histo_output_longscan_ch_0_*"))
else:
numScansPerChannel = 4
for i in range(numChannels):
chHistPaths, chImages, chDarkHistPaths = self.CheckFolderForHistogramsAndImages(i)
if (not(self.scanType!=2 or self.scanType!=4)) and len(chHistPaths)!=4: #Long scans can have arbitrary number of histograms
errorString = 'Missing histogram files for ch '+' in the folder:'+self.path
raise ValueError(errorString)
for ind, histFileName in enumerate(chHistPaths):
self.channelData[i*numScansPerChannel+ind].histogramPath = histFileName
for ind in range(0, len(chImages), 2):
self.channelData[i*numScansPerChannel+int(ind/2)].imagePathLaserOff = chImages[ind]
self.channelData[i*numScansPerChannel+int(ind/2)].imagePathLaserOn = chImages[ind+1]
for ind, histFileName in enumerate(chDarkHistPaths):
self.channelData[i*numScansPerChannel+ind].darkHistogramPath = histFileName
if 0: #Debugging filenames
for ch in self.channelData:
print(os.path.split(ch.histogramPath)[1],' Lsr off:', os.path.split(ch.imagePathLaserOff)[1],
' Lsr on:', os.path.split(ch.imagePathLaserOn)[1],
' Dark Hist:', os.path.split(ch.darkHistogramPath)[1])
return
def computeCorrectionForLongScansWithNoDarkHists(self,chPos):
chStrs = ['ch_0','ch_1']
chStr = chStrs[chPos]
chInd = [i for i, x in enumerate(self.channelData) if x.imagePathLaserOff.find(chStr) != -1]
imageMainRowsMean = np.zeros((len(chInd)+1,))
imageMainRowsStd = np.zeros((len(chInd)+1,))
for ind, i in enumerate(chInd):
imageMain = self.ReadImage(self.channelData[i].imagePathLaserOff)
imageMainRowsMean[ind], imageMainRowsStd[ind], _, _, _, _ = self.GetImageStats(imageMain)
#Code to fit a line to the last two points
#x = np.linspace(len(chInd)-1,len(chInd),len(chInd)+1)
#p = np.polyfit(x[-3:-1], imageMainRowsMean[-3:-1], 1)
#imageMainRowsMean[-1] = np.polyval(p, x[-1])
#p = np.polyfit(x[-3:-1], imageMainRowsStd[-3:-1], 1)
#imageMainRowsStd[-1] = np.polyval(p, x[-1])
#self.longScanCorrectionFactor = [imageMainRowsMean, imageMainRowsStd]
#Code to fit fourth order polynomial to the image mean and std
x = np.linspace(0,len(chInd)-1,len(chInd))
pMean = np.polyfit(x, imageMainRowsMean[:-1], 4)
pStd = np.polyfit(x, imageMainRowsStd[:-1], 4)
self.longScanCorrectionFactor = [pMean, pStd]
return
def ComputeContrastForChannel(self, channelData, gain, cameraPositionStr, chInd=-1, scanInd=-1):
scanHistograms, obMeanScan, obStdScan, camTemps, timeStamps = self.ReadHistogram(channelData.histogramPath)
if len(scanHistograms)==0:
channelData.dataAvailable = False
return
imgLaserOff = self.ReadImage(channelData.imagePathLaserOff)
lsrOffMean, imgMainLsrOffStd, lsrOffWidth, lsrOffObMean, lsrOffObStd, lsrOffObWidth = self.GetImageStats(imgLaserOff)
imgLaserOn = self.ReadImage(channelData.imagePathLaserOn)
lsrOnMean, lsrOnStd, lsrOnWidth, lsrOnObMean, lsrOnObStd, lsrOnObWidth = self.GetImageStats(imgLaserOn)
if self.debugMode > 0:
# Histogram Stats for Laser On
channelData.histLsrOnPath = channelData.histogramPath
channelData.histMainLsrOn = scanHistograms
channelData.histObLsrOnMean = obMeanScan
channelData.histObLsrOnStd = obStdScan
channelData.histLsrOnCamTemps = camTemps
channelData.histLsrOnTimeStamp = timeStamps
# Image Stats for Laser On
channelData.imageLaserOffHistWidth = lsrOffWidth
channelData.imageLaserOffImgMean = lsrOffMean
channelData.imgLsrOffPath = channelData.imagePathLaserOff
channelData.imgMainLsrOffMean = lsrOffMean
channelData.imgMainLsrOffStd = imgMainLsrOffStd
channelData.imgMainLsrOffHistWid = lsrOffWidth
# channelData.imgMainLsrOffHistRaw = [] # not output currently
channelData.imgObLsrOffMean = lsrOffObMean
channelData.imgObLsrOffStd = lsrOffObStd
# channelData.imgObLsrOffHistRaw = [] # not output currently
# Image Stats for Laser Off
channelData.imgLsrOnPath = channelData.imagePathLaserOn
channelData.imgMainLsrOnMean = lsrOnMean
channelData.imgMainLsrOnStd = lsrOnStd
channelData.imgMainLsrOnHistWid = lsrOnWidth
# channelData.imgMainLsrOnHistRaw = [] # not output currently
channelData.imgObLsrOnMean = lsrOnObMean
channelData.imgObLsrOnStd = lsrOnObStd
# channelData.imgObLsrOnHistRaw = [] # not output currently
bins = np.array(list(range(scanHistograms.shape[1]-1)))
scanMean, scanStd, scanHistWidths = self.GetHistogramStats(scanHistograms[:,:-1],bins)
channelData.histMainLsrOnMean = scanMean
channelData.histMainLsrOnStd = scanStd
if self.printStats:
expMeanPr, expStdPr, lsrOffDarkMeanPr, lsrOffDarkStdPr = map(PrettyFloat4, (lsrOffMean, imgMainLsrOffStd, lsrOffObMean, lsrOffObStd))
print(cameraPositionStr,' Laser off Dark Row Mean:', lsrOffDarkMeanPr, ' Std:', lsrOffDarkStdPr,
' Exposed rows Mean:', expMeanPr, ' Std:', expStdPr )
print(cameraPositionStr,' Laser on Dark Row Mean:', PrettyFloat4(lsrOnObMean), ' Std:', PrettyFloat4(lsrOnObStd),
' Exposed rows Mean:', PrettyFloat4(lsrOnMean), ' Std:', PrettyFloat4(lsrOnStd),
' Histogram bright mean:', PrettyFloat4(scanMean[0]), ' Std:', PrettyFloat4(scanStd[0]),
' Histogram ob mean:', PrettyFloat4(obMeanScan[0]), ' Std:', PrettyFloat4(obStdScan[0]))
if self.correctionType==0:
#mean correction: scan mean - line fit to scan ob rows - offset between main row pixels and ob row pixels in img when laser is off
#variance correction: scan variance - variance main when laser off - gain*corrected mean(above)
t = range(0, len(obMeanScan))
p = np.polyfit(t, obMeanScan, 1)
obMeanScanFit = np.polyval(p, t)
channelData.correctedMean = scanMean-(obMeanScanFit+(lsrOffMean-obMeanScanFit[0]))
if np.any(channelData.correctedMean<0):
channelData.correctedMean = scanMean-obMeanScanFit
print('Negative correctedMean in channel. Turning off dark frame offset correction for channel ',cameraPositionStr)
varCorrected = scanStd**2-imgMainLsrOffStd**2-self.ADCgain*gain*channelData.correctedMean
if np.any(varCorrected<0):
varCorrected = scanStd**2
print('Negative variance in channel with correction. Turning off variance correction for channel ',cameraPositionStr)
if self.correctionType==1:
# mean correction - line fit to dark imgMain and dark hist
# variance corrections from linear fitted dark imgMain and dark hist
histMainLsrOff, histObLsrOffMean, histObLsrOffStd, histLsrOffCamTemps, histLsrOffTimeStamp = self.ReadHistogram(channelData.darkHistogramPath)
histMainLsrOffMean, histMainLsrOffStd, histMainLsrOffHistWid = self.GetHistogramStats(histMainLsrOff[:,:-1],bins)
if self.debugMode > 0:
# Histogram Stats for Laser Off
channelData.histLsrOffPath = channelData.darkHistogramPath
channelData.histMainLsrOff = histMainLsrOff
channelData.histObLsrOffMean = histObLsrOffMean
channelData.histObLsrOffStd = histObLsrOffStd
channelData.histLsrOffCamTemps = histLsrOffCamTemps
channelData.histLsrOffTimeStamp = histLsrOffTimeStamp
channelData.histMainLsrOffMean = histMainLsrOffMean
channelData.histMainLsrOffStd = histMainLsrOffStd
channelData.histMainLsrOffHistWid = histMainLsrOffHistWid
t = np.array(np.arange(scanHistograms.shape[0]+2))
polyFit2 = np.poly1d(np.polyfit(np.array([t[0],t[-2],t[-1]]), np.array([lsrOffMean, histMainLsrOffMean[0], histMainLsrOffMean[1],]),1))
lsrOffMeanFit = polyFit2(t)[:-2]
polyFit2 = np.poly1d(np.polyfit(np.array([t[0],t[-2],t[-1]]), np.array([imgMainLsrOffStd, histMainLsrOffStd[0], histMainLsrOffStd[1]]),1))
lsrOffStdFit = polyFit2(t)[:-2]
channelData.correctedMean = scanMean-lsrOffMeanFit
if np.any(channelData.correctedMean<0):
t = range(0, len(obMeanScan))
p = np.polyfit(t, obMeanScan, 1)
obMeanScanFit = np.polyval(p, t)
channelData.correctedMean = scanMean-obMeanScanFit
print('Negative correctedMean in channel. Turning off dark frame offset correction for channel ',cameraPositionStr)
varCorrected = scanStd**2-lsrOffStdFit**2-self.ADCgain*gain*channelData.correctedMean
if np.any(varCorrected<0):
varCorrected = scanStd**2-imgMainLsrOffStd**2-self.ADCgain*gain*channelData.correctedMean
print('Negative variance in channel with correction. Turning off std fit correction for channel ',cameraPositionStr)
if np.any(varCorrected<0):
varCorrected = scanStd**2
print('Negative variance in channel with correction. Turning off variance correction for channel ',cameraPositionStr)
if self.correctionType==2:
# mean correction - line fit to dark imgMain across all scans for the channel
# variance corrections - line fit to dark imgMain across all scans for the channel
if self.longScanCorrectionFactor is None or scanInd==0:
self.computeCorrectionForLongScansWithNoDarkHists(chInd)
#Code to fit a line between all the points and to the last two points to extrapolate for the last scan
#scanMeanCorrection = np.linspace(self.longScanCorrectionFactor[0][scanInd],self.longScanCorrectionFactor[0][scanInd+1],scanMean.shape[0])
#scanStdCorrection = np.linspace(self.longScanCorrectionFactor[1][scanInd],self.longScanCorrectionFactor[1][scanInd+1],scanMean.shape[0])
scanMeanCorrection = np.polyval(self.longScanCorrectionFactor[0], np.linspace(scanInd,scanInd+1,scanMean.shape[0]))
scanStdCorrection = np.polyval(self.longScanCorrectionFactor[1], np.linspace(scanInd,scanInd+1,scanMean.shape[0]))
channelData.correctedMean = scanMean-scanMeanCorrection
varCorrected = scanStd**2-scanStdCorrection**2-self.ADCgain*gain*channelData.correctedMean
if np.any(channelData.correctedMean<0) or np.any(varCorrected<0):
self.correctionType = 0
print('Negative correctedMean or variance in channel with correction. Turning off correction for channel ',cameraPositionStr)
channelData.correctedMean = scanMean
varCorrected = scanStd**2
contrast = np.sqrt(varCorrected)/channelData.correctedMean
channelData.contrastNoFilter = np.copy(contrast)
if self.filterDrift:
soshp = signal.butter(2,1/10,'hp',fs=40,output='sos')
contrastMean = np.mean(contrast)
contrastHP = signal.sosfiltfilt(soshp, contrast-contrastMean)+contrastMean
contrast = np.copy(contrastHP)
if self.filterNoise:
contrast = denoise_wavelet(contrast, method='BayesShrink', mode='soft', wavelet_levels=6, wavelet='sym3', rescale_sigma='True')
channelData.contrast = contrast
channelData.channelPosition = cameraPositionStr
channelData.lsrOffObWidth = lsrOffObWidth
channelData.camTemps = camTemps
channelData.initialCamTemp = camTemps[0]
channelData.timeStamps = timeStamps
return
def ReadDataAndComputeContrast(self):
self.ReadHistogramAndImageFileNames()
for ind,channel in enumerate(self.channelData):
if self.scanType==2:
indPos = int(ind*2/len(self.channelData))
scanInd = ind%int(len(self.channelData)/2)
elif self.scanType==4:
indPos = int(ind*4/len(self.channelData))
if self.scanType==2:
self.ComputeContrastForChannel(channel, self.cameraGain[self.scanType][indPos],
self.cameraPosition[self.scanType][indPos], indPos, scanInd)
elif self.scanType==4:
self.ComputeContrastForChannel(channel, self.cameraGain[self.scanType][indPos],
self.cameraPosition[self.scanType][indPos])
else:
self.ComputeContrastForChannel(channel, self.cameraGain[self.scanType][ind],
self.cameraPosition[self.scanType][ind])
def WaveformVertNorm(self, x, period):
# from Soren's containwaveform2 in headscan_gen2_fcns_v5.py
d = np.floor(0.7*period)
p1 = find_peaks(-x, distance=d)
p1 = p1[0]
z1 = x[p1]
p2 = find_peaks(x, distance=d)
p2 = p2[0]
z2 = x[p2]
d = np.floor(0.7*period)
x = self.flattenbottom(x, d)
x = self.flattenbottom(x, d)
x[x<0]=0
#get top peaks
p = find_peaks(x, distance=d)
p = p[0]
if len(p)<2:
return x
z = x[p]
g = interp1d(p, z, bounds_error=False, fill_value=(z[0], z[-1]))
gg = g(np.arange(len(x)))
gg[:p[0]]=z[0]
gg[p[-1]:]=z[-1]
x /= gg
x[x>1]=1
return x
def flattenbottom(self, x, d):
p = find_peaks(-x, distance=d)
p = p[0]
if len(p)<2:
return x
z = x[p]