-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrs_tools.py
2580 lines (2190 loc) · 114 KB
/
rs_tools.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
#rs_tools.py
################################################################################
#
# RS_tools version 0.3.1
#
###############################################################################
#
#
# Section 1: Classes
#
# This section contains the Classes that are used in analysis of line-scanning RS data
# These classes were written in-house, and any internet resources were used as guides
#
#
class Parameters():
import numpy as np
pass
class Collection:
'''
This is a collection class, that describes one hyperspectral 'map'.
'''
def __init__(self):
self.Summary=Summary()
self.Environment=Environment()
self.Collector=Collector()
self.Image=Image()
#self.tape_advance=[]
#self.find_tape=[]
#self.identification=[]
#self.focus=[]
#self.Image=[]
def build_Summary(self,root,Directory = ''):
#This builds the summary structure
self.Summary.System=root.attrib['System']
self.Summary.Date=root.attrib['Date']
self.Summary.Image_Start=self.Collector.Start_Time
self.Summary.Image_End = self.Collector.Date
self.Summary.ID = self.Collector.ID
self.Summary.Directory = Directory
self.Summary.binwn = []
class Environment:
def __init__(self):
self.Temperature = []
self.RelativeHumidity=[]
self.Date=[]
self.ID=[]
def load_Environment(self,Info):
self.Date=Info.attrib['Date']
self.ID = Info.attrib['ID']
for Metric in Info.iter('Metric'):
if Metric.attrib['Name'] == 'Temperature (C)':
self.Temperature=float(Metric.text)
#print float(Metric.text)
elif Metric.attrib['Name'] == 'Relative Humidity':
self.RelativeHumidity=float(Metric.text)
#print float(Metric.text)
class Summary:
def __init__(self):
self.System = []
self.Date=[]
self.Imaging_Start=[]
self.Save_Name=''
self.Imaging_End=[]
self.Collection_Start=[]
self.Collection_End=[]
self.Identification_Time = []
self.Collection_Verified = False
self.Background_Subtracted = False
self.Cosmic_Removed = False
self.nCosmic = 0
self.nSaturation = 0
self.Saturation_Matrix=[]
self.nBurning = 0
self.Spectra_Quality= []
self.Cleaned = False
self.QC_applied = False
self.ID=[]
self.Directory=[]
self.Background_Data=[]
self.Bin_Wavenumber=[]
self.Error=False
self.Bleach=False
class Collector:
def __init__(self):
self.Data_File = []
self.Start_Time=[]
self.Average_Current_uamps=[]
self.Perc_Average_Current_in_Target=[]
self.Perc_in_Target=[]
self.Average_Voltage_kV=[]
self.Last_Ceiling_Voltage_kV=[]
self.Perc_Voltage_Limited=[]
self.Quenches=[]
self.Voltage_Mismatches=[]
self.Resets=[]
self.Over_Temps=[]
self.Date=[]
self.ID=[]
def load_Collector(self,Info):
self.Date=Info.attrib['Date']
self.ID = Info.attrib['ID']
for Metric in Info.iter('Metric'):
if Metric.attrib['Name'] == 'Data File':
self.Data_File=Metric.text
elif Metric.attrib['Name'] == 'Start Time':
self.Start_Time=Metric.text
elif Metric.attrib['Name'] == 'Average Current (uamps)':
self.Average_Current_uamps=float(Metric.text)
elif Metric.attrib['Name'] == '% Average Current in Target':
self.Perc_Average_Current_in_Target=float(Metric.text)
elif Metric.attrib['Name'] == '% in Target':
self.Perc_in_Target=float(Metric.text)
elif Metric.attrib['Name'] == 'Average Voltage (kV)':
self.Average_Voltage_kV=float(Metric.text)
elif Metric.attrib['Name'] == 'Last Ceiling Voltage (kV)':
self.Last_Ceiling_Voltage_kV=float(Metric.text)
elif Metric.attrib['Name'] == '% Voltage Limited':
self.Perc_Voltage_Limited=float(Metric.text)
elif Metric.attrib['Name'] == 'Quenches':
self.Quenches=float(Metric.text)
elif Metric.attrib['Name'] == 'Voltage Mismatches':
self.Voltage_Mismatches=float(Metric.text)
elif Metric.attrib['Name'] == 'Resets':
self.Resets=float(Metric.text)
elif Metric.attrib['Name'] == 'Over Temps':
self.Over_Temps=float(Metric.text)
class Image:
#One "Image" for every "Image" on the CCD
def __init__(self):
#These are the variables read in by the load_Image pogram
#These are read in by the XML file.
self.Date=[] #Date and time of the image
self.ID=[]
self.Bleach_Name=[]
self.Spot_UID=[] #Generally empty, but we have this in case you want a unique collection Hash identifier
self.x_location = 0.
self.z_location = 0.
self.Replicate_Data=[]
self.Replicate_Name=[]
self.Bleach_Data=[]
self.Target_Data=[]
self.Fluorescence_Data=[]
self.Fluorescence_Sum=[]
self.Fluorescence_Max=[]
self.Raman_Sum = []
self.Raman_Max = []
self.Clip_Ind = []
self.Replicate_Time = [] #This will tell you about the replicate time
#These could be used to tell you if QC is performed on the image.
self.Cleaned=False
self.Background=False
self.Fluorescence=False
self.Good = True
################################################################################
################################################################################
################################################################################
#
#
# Section 2: Loading/Outputting Data Files
#
#
#
def load_summary(directory_load,QC=False,QC_Dir = '',QC_Name='colldata.txt'):
import glob
import os
import numpy as np
from pandas import Timedelta
from re import sub
import ntpath
import pdb
from pandas import to_datetime
#pdb.set_trace()
allfile2load = glob.glob(os.path.join(directory_load,'*summary.txt'))
if len(allfile2load) == 1:
file2load = allfile2load[0]
myRebs = Collection()
myRebs.Image = []
#myRebs.Summary.Background_Data=load_bkr(directory_load)
#Loop through the 'info' categories, fill xml data as required
#myRebs[i].Summary.load_Summary(root.iter('Summary'))
with open(file2load,'r') as f:
#Load the header
stl = f.readline()
#Get the start date in 'nice' string format
stl = f.readline().strip().split(' ')#Contains the date in nice 'string format'
myRebs.Summary.Save_Name = stl[3]
f.readline() #Blank Line in file
f.readline() #Run Notes
f.readline() #Machine
f.readline() #X steps
f.readline() #X step size
f.readline() #z range
f.readline() #Timage - t9ime of each image
f.readline() #Number of replicates
#Get start time
stl=f.readline().strip().split(' ') #Start Time
try:
myRebs.Summary.Imaging_Start=to_datetime(stl[3] + ' ' + stl[4] + ' ' + stl[5])
except:
myRebs.Summary.Imaging_Start=to_datetime(stl[-3] + ' ' + stl[-2] + ' ' + stl[-1])
f.readline() #Number of replicates
f.readline() #Number of replicates
#Now we have finished loading the header.
##########
#
# NOw step through and load the images
#
my_img_num = -1
#mlp = 0
for line in f:
#print 'MLP:' + str(mlp)
#mlp = mlp + 1
line_seperated = line.split()
if len(line_seperated) == 0:
continue
elif line_seperated[0] == 'Event':
pass
elif line_seperated[0] == 'Quality':
pass
elif line_seperated[0] == '#---------------------------------------------':
break
elif line_seperated[0] == 'Image':
myRebs.Image.append(Image())
my_img_num = my_img_num + 1
print(my_img_num)
locs = line_seperated[2].strip('()').split(',')
myRebs.Image[my_img_num].x_location = float(locs[0])
myRebs.Image[my_img_num].z_location = float(locs[1])
replicate_ind=0
elif line_seperated[0] == 'Replicate':
path_load = os.path.join(directory_load,line_seperated[-1])
if replicate_ind == 0:
#First replicate - just output to matrix
try:
newrd = load_rebspng(path_load)
except:
print(("Error in Load_Summary on",path_load))
print(("Image Number:",my_img_num+1))
print("I am going to continue, but note that you will have one less replicate")
myRebs.Image[my_img_num].Good=False
continue
myRebs.Image[my_img_num].Replicate_Data = newrd
myRebs.Image[my_img_num].Replicate_Name = [line_seperated[-1]]
#extract the replicate time
try:
myRebs.Image[my_img_num].Replicate_Time = line_seperated[2].split('(')[1].strip('(s):')
except:
myRebs.Image[my_img_num].Replicate_Time = line_seperated[1].split("(")[1].strip(")")
#Set replicate_ind to 1 indicating that we have more replicates
replicate_ind = 1
else:
oldrd = myRebs.Image[my_img_num].Replicate_Data
try:
newrd = load_rebspng(path_load)
except:
print(("Error in Load_Summary on",path_load))
print(("Image Number:",my_img_num))
print("I am going to continue, but note that you will have one less replicate")
myRebs.Image[my_img_num].Good=False
continue
myRebs.Image[my_img_num].Replicate_Data = np.dstack((oldrd,newrd))
myRebs.Image[my_img_num].Replicate_Name.append(line_seperated[-1])
else:
pass
myimsize = myRebs.Image[0].Replicate_Data.shape
#import pdb
#pdb.set_trace()
myRebs.Summary.Spectra_Quality=np.zeros((my_img_num,int(myimsize[0])))
return myRebs
else:
raise IOError(12,'NoFileFound')
return
#'File not Found','noFile',os.path.join(directory_load,'*SpotInfo.txt'))
def load_spotinfo(directory_load,QC=False,QC_Dir = '',QC_Name='colldata.txt'):
import glob
import os
import numpy as np
from pandas import Timedelta
from re import sub
import ntpath
allfile2load = glob.glob(os.path.join(directory_load,'*SpotInfo.txt'))
if len(allfile2load) == 1:
file2load = allfile2load[0]
myRebs = Collection()
myRebs.Image = []
myRebs.Summary.Background_Data=load_bkr(directory_load)
myRebs.Summary.Imaging_Start=convert_rebspath_to_datetime(directory_load)
myRebs.Summary.Save_Name = myRebs.Summary.Imaging_Start.strftime('%Y%m%d_%H%M%S')
with open(file2load,'r') as f:
#currentStatus = 'data'
stl = f.readline
print(f)
#Read first six lines
stl = f.readline().strip().split('--')
f.readline() #Blank Line in file
f.readline() #This is session ID (throwing out for now)
cidl = f.readline().strip().split('=') #This is Collection ID
f.readline() #This is spot ID (throwing out for now
f.readline() #Blank Line
if stl[0] == '' and cidl[0] == '':
#IN this case, the spotinfo exists, but was not written to (e.g. power failure).
myBackupRebs = load_rebsdirectory(directory_load)
#raise IOError(11,'REBS Shutdown')
return myBackupRebs
my_img_num = -1
#print os.path.basename(file2load)
myRebs.Collector.Data_File = os.path.basename(os.path.dirname(file2load))
for line in f:
line_seperated = line.split()
if len(line_seperated) == 0:
continue
elif line_seperated[0] == 'Targeting':
# For Every Targeting Data, Append a new image
myRebs.Image.append(Image())
my_img_num = my_img_num + 1
replicate_ind = 0
myRebs.Image[my_img_num].x_location = my_img_num*2
# Set up the Path Name to Use
path_load = convert_rebspath_to_computerpath(line,directory_load)
myRebs.Image[my_img_num].Target_Data = load_rebspng(path_load)
elif line_seperated[0] == 'Bleaching':
path_load = convert_rebspath_to_computerpath(line,directory_load)
myRebs.Image[my_img_num].Bleach_Data = load_rebspng(path_load)
myRebs.Image[my_img_num].Bleach_Name = ntpath.basename(path_load)
elif line_seperated[0] == 'Identification':
path_load = convert_rebspath_to_computerpath(line,directory_load)
if replicate_ind == 0:
#First replicate - just output to matrix
myRebs.Image[my_img_num].Replicate_Data = load_rebspng(path_load)
myRebs.Image[my_img_num].Replicate_Name = [ntpath.basename(path_load)]
replicate_ind = 1
else:
oldrd = myRebs.Image[my_img_num].Replicate_Data
myRebs.Image[my_img_num].Replicate_Data = np.dstack((oldrd,load_rebspng(path_load)))
myRebs.Image[my_img_num].Replicate_Name.append(ntpath.basename(path_load))
#Concatenate these two matrices together
elif "_".join(line_seperated[4:7]) == 'Requested_identification_time':
myRebs.Summary.Identification_Time = float(sub('[()]', '', line_seperated[7]))
myRebs.Summary.Imaging_End = myRebs.Summary.Imaging_Start + Timedelta(myRebs.Summary.Identification_Time,'s')
elif "_".join(line_seperated[3:6]) == 'Spot_Identification_Ended.':
#end_time = line.split('--')[0]
pass
if line.strip() == '-- SUMMARY --':
break
for line in f:
#Loop through Summary
if line.strip() == '-- Totals --':
break
for line in f:
#Loop through Summary
pass
if len(myRebs.Image) == 0:
#Currently an IO Error.
#Someday we may change this to a 'warning'
raise IOError(11,'NoImagesFound')
myimsize = myRebs.Image[0].Replicate_Data.shape
myRebs.Summary.Spectra_Quality=np.zeros([myimsize[0],my_img_num+1])
return myRebs
else:
raise IOError(12,'NoFileFound')
def load_rebsdirectory(input_directory):
import glob
import os
import ntpath
import numpy as np
myRebs = Collection()
myRebs.Image = []
myRebs.Summary.Background_Data=load_bkr(input_directory)
myRebs.Summary.Imaging_Start=convert_rebspath_to_datetime(input_directory)
#Add to note that there is an error.
myRebs.Summary.Error = True
print('Using Simple REBS loader....caution is indicated. May break other code')
myRebs.Collector.Data_File = os.path.basename(input_directory)
my_img_num = -1
search_path = os.path.join(input_directory,'REBS RN*.png')
all_files = glob.glob(search_path)
for myfile in all_files:
if 'bkr' in os.path.basename(myfile):
continue
elif 'bkt' in os.path.basename(myfile):
continue
elif 'bkrs' in os.path.basename(myfile):
continue
elif 'bkts' in os.path.basename(myfile):
continue
elif '_t' in os.path.basename(myfile):
#We have a new target.
myRebs.Image.append(Image())
my_img_num = my_img_num + 1
replicate_ind = 0
#print(myfile)
elif '_b' in os.path.basename(myfile):
#print(myfile)
myRebs.Image[my_img_num].Bleach_Data = load_rebspng(myfile)
myRebs.Image[my_img_num].Bleach_Name = ntpath.basename(myfile)
elif '_r' in os.path.basename(myfile):
#print(myfile)
if replicate_ind == 0:
#First replicate - just output to matrix
myRebs.Image[my_img_num].Replicate_Data = load_rebspng(myfile)
myRebs.Image[my_img_num].Replicate_Name = [ntpath.basename(myfile)]
replicate_ind = 1
else:
oldrd = myRebs.Image[my_img_num].Replicate_Data
myRebs.Image[my_img_num].Replicate_Data = np.dstack((oldrd,load_rebspng(myfile)))
myRebs.Image[my_img_num].Replicate_Name.append(ntpath.basename(myfile))
return myRebs
def load_bkr(mydir='',clean=True):
# Given a directory, finds the background file, and loads it
# if no directory, uses current directory
# To manually load background file, just use load_rebspng
#
import glob
import numpy as np
import os
import ntpath
#Search for a file in the path that is a png with *bkr* in the name
mysearchpath = os.path.join(mydir,'*_bkr.png')
bkrfilename = glob.glob(mysearchpath)
print(bkrfilename)
#Check if we found anything
if not bkrfilename:
#If not, print error, return NaN
print('No BKR file found')
return np.NaN
else:
#Otherwise, check if we only found one file
if len(bkrfilename) == 1:
#If only one file, add the path to the filename
bkrfile2load = bkrfilename[0]
#Load the file
bkr = load_rebspng(bkrfile2load)
return bkr
else:
#Otherwise, there are mutiple files
print('Mutiple files Found, be more specific')
return np.NaN
def load_rebspng(myfile):
# Loads the raw REBS png as a file and returns the data
# Needs to be a full directory path and filename
import matplotlib.image as mpimg
import numpy as np
try:
myimg_rebs = mpimg.imread(myfile)
return myimg_rebs
except IOError as e:
print(myfile)
print("I/O error({0}): {1}".format(e.errno, e.strerror))
raise e
except:
print("Non-IO error")
raise
def cl_output_sep(f_data,f_meta,nrtd,collection_num = 0):
""" exports seperated data from the collection file. This means that individual replicates are retained
replicate number is included in the meta file. (So be very careful to analyze correctly)
inputs:
f_data: this is a file handle pointing to the data file
nrtd: this is a collection class containing the data from one collectionimport numpy as np
f_meta: this is a meta file containing the metadata from the collection.
collection_num: this is the number of collection. If you are analyzing a lot of collections, this could be nice to have
as a simple way to seperate out the collections. defaults to zero
outputs:
there are no outputs
usage:
XXXXXX
"""
import numpy as np
num_rows,num_wns,num_replicates = nrtd.Image[0].Replicate_Data.shape
for i,Image in enumerate(nrtd.Image):
for j in range(0,num_rows):
for k in range(0,num_replicates):
#Get the values to be written
t = nrtd.Summary.Imaging_Start
x = Image.x_location
z = Image.z_location
y = j
rep = k
cn = collection_num
p1 = 0.0
p2 = 0.0
p3 = 0.0
p4 = 0.0
p5 = 0.0
if len(Image.Fluorescence_Sum) > 0:
Fluo = Image.Fluorescence_Sum[j,k]
Flt = Image.Total_Sum[j,k]
else:
Fluo = 0.0
Flt = 0.0
mydata = nrtd.Image[i].Replicate_Data[j,:,k]
#Write Metadata
#f_meta.write('DateTime,x,y,z,r,cn,fl,flt,p1,p2,p3,p4,p5\n')
f_meta.write(str(t))
f_meta.write(',%03d,%03d,%03d,%03d,%03d,%1.4f,%1.4f,%03d,%03d,%03d,%03d,%03d' % (x,y,z,rep,cn,Fluo,Flt,p1,p2,p3,p4,p5))
f_meta.write('\n')
#write the rest + newline
datastr = '%1.4f' + ',%1.4f'*1023
#Interpolate NaN values
try:
nans,x=nan_helper(mydata)
mydata[nans] = np.interp(x(nans),x(~nans),mydata[~nans])
f_data.write(datastr % tuple(mydata.tolist()))
f_data.write('\n')
except:
f_data.write(datastr % tuple(mydata.tolist()))
f_data.write('\n')
#rt.dc_output_sep(f_data,dc,f_meta,t,dx,dz,collection_num=0,Fluo=fl,Flt=ft)
def dc_output_sep(f_data,dc,f_meta,t,dx,dz,collection_num=0,Fsum=[0],Fmax=[0],Rmax=[0],Rqc=[0],dump_nans=False):
import numpy as np
#Outputs the collection
#This is called 'sep' becuase it outputs location data
# seperately from 'meta' data
#Primarily used for (for example) getting data into hyperspec format.
# Note vor rebstools v21 and up: there was a major change in the computation and order of some of these
#values. For example, the x_position is no longer determined via strtX, but rather via dx.
#To maintain continuity, we also add a value for 'replicate number' - for this scenario the replicate number will always be 'zero'
(n_rows,n_columns,n_images) = dc.shape
for i in range(0,n_images):
for j in range(0,n_rows):
#t = nrtd.Summary.Imaging_Start
x = dx[i]# this is the image location
y = j
z = dz[i]
#z: this is the image height
rep = 0 #Set to zero because we are analyzing the 'dir cube'
cn = collection_num
#These are placeholders
p3 = 0.0
p4 = 0.0
p5 = 0.0
Fl = Fsum[j,i] if len(Fsum)> 1 else 0.0
Fx = Fmax[j,i] if len(Fmax) > 1 else 0.0
Rx = Rmax[j,i] if len(Rmax) > 1 else 0.0
qc = Rqc[j,i] if len(Rqc) > 1 else 0.0
#Write the data
datastr = '%1.4f' + ',%1.4f'*1023
#Interpolate NaN values
mydata = dc[j,:,i]
try:
nans,ind=nan_helpfcn(mydata)
mydata[nans] = np.interp(ind(nans),ind(~nans),mydata[~nans])
#note: This will throw an exception if you have all nan's
f_data.write(datastr % tuple(mydata.tolist()))
f_data.write('\n')
dump_meta = True #Everything worked, we need to output the metadata
#Write the date
except:
#Generally this meanss that there was a problem interpolating NaN Values.
#IN this case, the dump_nan boolean will help us decide if we want to dump our NaN values or not
if dump_nans == True:
print("Error in nan_helper at",i,j, "trying normal data write")
f_data.write(datastr % tuple(mydata.tolist()))
f_data.write('\n')
dump_meta = True #We still need to output the appropriate metadata file
else:
print("Error in nan_helper at",i,j,"skipping")
dump_meta = False #Since we skipped dumping the datafile, we do not want to dump the metadata for the corresponding data point.
if dump_meta == True:
f_meta.write(str(t))
#import pdb
#pdb.set_trace()
try:
f_meta.write(',%03d,%03d,%03d,%03d,%03d,%1.5f,%1.5f,%1.5f,%03d,%03d,%03d,%03d' % (x,y,z,rep,cn,Fl,Fx,Rx,qc,p3,p4,p5))
except:
import pdb
pdb.set_trace()
print("Problem with meta file at",i,j,"writing -999 for all parameters")
f_meta.write(',%03d,%03d,%03d,%03d,%03d,%1.5f,%1.5f,%1.5f,%03d,%03d,%03d,%03d' % (-999,-999,-999,-999,-999,-999,-999,-999,-999,-999,-999,-999))
f_meta.write('\n')
def dc_output_sep_fl(f_data,dc,f_fluo,fc,f_meta,t,dx,dz,collection_num=0,Fsum=[0],Fmax=[0],Rmax=[0],Rqc=[0],dump_nans=False):
import numpy as np
#Outputs the collection
#This is called 'sep' becuase it outputs location data
# seperately from 'meta' data
#Primarily used for (for example) getting data into hyperspec format.
# Note vor rebstools v21 and up: there was a major change in the computation and order of some of these
#values. For example, the x_position is no longer determined via strtX, but rather via dx.
#To maintain continuity, we also add a value for 'replicate number' - for this scenario the replicate number will always be 'zero'
(n_rows,n_columns,n_images) = dc.shape
for i in range(0,n_images):
for j in range(0,n_rows):
#t = nrtd.Summary.Imaging_Start
x = dx[i]# this is the image location
y = j
z = dz[i]
#z: this is the image height
rep = 0 #Set to zero because we are analyzing the 'dir cube'
cn = collection_num
#These are placeholders
p2 = 0.0
p3 = 0.0
p4 = 0.0
p5 = 0.0
Fl = Fsum[j,i] if len(Fsum)> 1 else 0.0
Fx = Fmax[j,i] if len(Fmax) > 1 else 0.0
Rx = Rmax[j,i] if len(Rmax) > 1 else 0.0
qc = Rqc[j,i] if len(Rqc) > 1 else 0.0
#Write the data
datastr = '%1.4f' + ',%1.4f'*1023
#Interpolate NaN values
mydata = dc[j,:,i]
mydata_fl = fc[j,:,i]
try:
nans,ind=nan_helpfcn(mydata)
mydata[nans] = np.interp(ind(nans),ind(~nans),mydata[~nans])
#note: This will throw an exception if you have all nan's
f_data.write(datastr % tuple(mydata.tolist()))
f_data.write('\n')
dump_meta = True #Everything worked, we need to output the metadata
#Write the date
except:
#Generally this meanss that there was a problem interpolating NaN Values.
#IN this case, the dump_nan boolean will help us decide if we want to dump our NaN values or not
if dump_nans == True:
print("Error in nan_helpfcn at",i,j, "trying normal data write")
f_data.write(datastr % tuple(mydata.tolist()))
f_data.write('\n')
dump_meta = True #We still need to output the appropriate metadata file
else:
print("Error in nan_helpfcn at",i,j,"skipping")
dump_meta = False #Since we skipped dumping the datafile, we do not want to dump the metadata for the corresponding data point.
f_fluo.write(datastr % tuple(mydata_fl.tolist()))
f_fluo.write('\n')
if dump_meta == True:
f_meta.write(str(t))
#import pdb
#pdb.set_trace()
try:
f_meta.write(',%03d,%03d,%03d,%03d,%03d,%1.5f,%1.5f,%1.5f,%03d,%03d,%03d,%03d' % (x,y,z,rep,cn,Fl,Fx,Rx,qc,p3,p4,p5))
except:
import pdb
pdb.set_trace()
print("Problem with meta file at",i,j,"writing -999 for all parameters")
f_meta.write(',%03d,%03d,%03d,%03d,%03d,%1.5f,%1.5f,%1.5f,%03d,%03d,%03d,%03d' % (-999,-999,-999,-999,-999,-999,-999,-999,-999,-999,-999,-999))
f_meta.write('\n')
def output_Rdata_single(dc,dx,dz,t,path_to_output='',x_values=None,Output_Name=''):
''' The purpose of this code is to output a single collection in hyperspec format
the point is if you just need to do something quickly
inputs:
dc,dx,dz,t : these are the outputs by process_collection
path_to_output (optional): this is the output location. Default: home directory
x_values: what are the bin wavenumber values. default: Rn14 values
output_name: what do you want the output data file to be
outputs:
none
'''
import os
if x_values is None:
x_values = get_rebs_calibration(rn=14)
#Dumps a single dircube to an R file (appropriately named)
fname_data = t.strftime('%Y%m%d_%H%M%S') + '.rdat'
fname_meta = t.strftime('%Y%m%d_%H%M%S') + '.rmta'
path_data = os.path.join(path_to_output,fname_data)
path_meta = os.path.join(path_to_output,fname_meta)
#
with open(path_data,'w') as f_data, open(path_meta,'w') as f_meta:
datastr = '%1.4f' + ',%1.4f'*1023 + '\n'
f_data.write(datastr % tuple(x_values))
f_meta.write('DateTime,x,y,p1,p2\n')
dc_output_sep(f_data,dc,f_meta,t,dx,dz)
################################################################################
################################################################################
################################################################################
#
#
# Section 3: Processing Data
#
#
#
#
#
def clean_collection(nrtd):
from copy import deepcopy
import numpy as np
#This handles a case where you had a Target image taken
#But are missing a replicate data
nurtd = deepcopy(nrtd)
nurtd.Image = [Image for Image in nrtd.Image if np.size(Image.Replicate_Data)>1]
return nurtd
def remove_saturation(nrtd,st=10,saturation_limit=0.99):
print("No longer used...saturation is removed (if desired) after QC Spectrum")
print("Please use detect_saturation() and qc_spectrum() to remove saturated spectra")
print("I am running detect_saturation instead....")
nrtd = detect_saturation(nrtd,st,saturation_limit)
return nrtd
def detect_saturation(nrtd,st=10,saturation_limit=0.99):
""" this detects
IMPORTANT NOTE: This relies on the maximum value being 1 and minimum zero.
If you use another loader or have other values (e.g. you have a shorter bleach spectrum
Then make sure you run this analysis prior to running "use_bleach".
Note: 11/2018: Note: Previous iterations of this code (remove_saturation()) removed saturation
Current version does not remove saturation, it just sets spectra_quality to 1.
Future iterations might show the number and location of saturations (so one could select to use non-saturated spectra). .
Notes:
-This code removes saturations in the bleach spectra as well as in replicate spectra
- For counting num_saturation - this code *ONLY* currently counts the number of saturations
-This code works for n replicates
Inputs:
nrtd: this is a collection class. It should have been already loaded
st: this is the saturation tolerance....i.e. the number of points
that can reach saturation before removing that spectra.
Reccomend at least higher than 1 so that a few saturation peaks
won't result in removal of the entire spectra"
Usage:
myCollection = remove_saturation(myCollection,st=5)
This assumes that the data have been normalized
"""
import numpy as np
saturation_tolerance=st
num_saturation = 0
satmat = np.empty((0,5))
for i,Image in enumerate(nrtd.Image):
len_reps = Image.Replicate_Data.shape[2]
if len(Image.Bleach_Data) > 0:
#If we have bleach data
bleach_data = Image.Bleach_Data
bd = bleach_data[:,100::] >= saturation_limit
sv = np.nansum(bd,axis=1)
badrows = np.where(sv>saturation_tolerance)
nrtd.Summary.Spectra_Quality[badrows,i] = 1
for j in range(0,len_reps):
rv=j
bd = Image.Replicate_Data[:,100::,j] >= saturation_limit
sv = np.nansum(bd,axis=1)
badrows = np.where(sv>saturation_tolerance)
# added 5/2017 - count saturation
num_saturation = num_saturation + sum(sv>saturation_tolerance)
if len(badrows[0]>0):
try:
for k,mybadrow in enumerate(badrows[0]):
rowvs = np.array([-999,i,mybadrow,rv,sv[mybadrow]])
satmat = np.vstack((satmat,rowvs))
except:
import pdb
print("Error in detect_saturation")
pdb.set_trace()
# added 5/2017 - remove all replicates
#Image.Replicate_Data[badrows,:,:] = np.NaN
#Set the image quality to 1 for 'saturated'
nrtd.Summary.Spectra_Quality[badrows,i] = 1
#Image.Replicate_Data[badrows,:,j] = np.NaN
nrtd.Summary.NSaturation = num_saturation
nrtd.Summary.Saturation_Matrix=satmat
return nrtd
def clean_badlocs(nrtd,rn=0):
""" All the different Rebs instruments have problem pixels.
Maybe something is on the CCD (and should be cleaned)? Some pixels
are 'hot'. In any case, we use this to remove the pixels that clearly
are bad. We go throuhgh and manually determine the bad locations.
Notes:
-This code analyzes the bleached data!
-This code works for n replicates
- This code deletes the first 50 pixels
Inputs:
nrtd: This is a collection class
rn: this is the ars serial number, which tells you which set of
bad locations to use
Outputs:
nrtd: this is a collection class
Usage:
>>> myCollection = clean_badlocs(myCollection,rn=13)
"""
#Cleans known bad pixels
#From arrays
import sys
import numpy as np
if rn == 14:
#Originally the size here was 38
#Modified to 36- may need to check date
allbadlocs = np.zeros((36,1024),dtype=bool)
allbadlocs[:,0:51] = True #This is a modification. Remove all points below ~150
allbadlocs[0,list(range(813,814))] = True
allbadlocs[2,list(range(974,981))] = True
allbadlocs[3,list(range(974,981))] = True
allbadlocs[7,list(range(968,976))] = True
allbadlocs[8,list(range(970,976))] = True
allbadlocs[10,list(range(943,952))] = True
allbadlocs[11,list(range(234,240)) + list(range(943,952))] = True
allbadlocs[12,813] = True
allbadlocs[16,list(range(970,980))] = True
allbadlocs[17,list(range(966,980))] = True
allbadlocs[22,list(range(779,790))] = True
allbadlocs[23,list(range(779,790))] = True
allbadlocs[24,list(range(542,549)) + list(range(780,790)) ] = True
allbadlocs[25,list(range(542,550)) + list(range(780,788)) ] = True
allbadlocs[26,list(range(542,551))] = True
allbadlocs[27,list(range(542,552))] = True
allbadlocs[28,list(range(542,552))] = True
allbadlocs[34,847] = True
elif rn == 13:
allbadlocs = np.zeros((44,1024),dtype=bool)
allbadlocs[:,0:51] = True #This is a modification. Remove all points below ~150 cm -1
allbadlocs[0,list(range(506,523))] = True
allbadlocs[1,list(range(506,525))+list(range(750,751))] = True
allbadlocs[2,list(range(506,530))] = True
allbadlocs[3,list(range(506,525))] = True
allbadlocs[4,list(range(424,436))+list(range(510,520))] = True
allbadlocs[5,list(range(251,252)) + list(range(424,436))+list(range(510,520))] = True
allbadlocs[6,list(range(424,436))+list(range(510,520))] = True
allbadlocs[7,list(range(424,436))+list(range(510,520)) + list(range(251,252))] = True
allbadlocs[8,list(range(122,123)) + list(range(424,436))+ list(range(511,517))] = True
allbadlocs[9,list(range(251,252)) + list(range(511,517))] = True
allbadlocs[10,list(range(511,517))] = True
allbadlocs[11,list(range(511,517))] = True
allbadlocs[12,list(range(511,517))] = True
allbadlocs[13,list(range(481,490))+ list(range(511,517))] = True
allbadlocs[14,list(range(481,490))+ list(range(511,517))] = True
allbadlocs[15,list(range(481,490))+ list(range(511,517))] = True
allbadlocs[16,list(range(119,122)) + list(range(481,490)) + list(range(511,517))] = True
allbadlocs[17,list(range(119,122))+ list(range(481,490))+ list(range(511,517))] = True
allbadlocs[18,list(range(119,122)) + list(range(481,490))+ list(range(511,517))] = True
allbadlocs[19,list(range(119,122)) + list(range(481,490))+ list(range(511,517))] = True
allbadlocs[20,list(range(480,492))] = True
allbadlocs[21,list(range(474,490))] = True
allbadlocs[22,list(range(474,489))] = True
allbadlocs[23,list(range(474,488))] = True
allbadlocs[24,list(range(474,488))] = True
allbadlocs[25,list(range(350,351)) + list(range(474,488))] = True #Commented this out - we think this might be real - this addition of 350-353 was 'new'- possibly a resonance raman?
#allbadlocs[25,list(range(474,488))] = True
allbadlocs[28,list(range(135,136))] = True
allbadlocs[31,list(range(350,351))] = True #Commented this out - we think this might be a real particle - this has been here for a long time
allbadlocs[36,list(range(146,147))] = True
allbadlocs[35,list(range(146,147))] = True
allbadlocs[37,list(range(350,351))] = True #Commented this out - we think this might be a real raman peak - this has been here for a long time
allbadlocs[42,list(range(350,351))] = True #Commented this out - we think this might be a real raman peak - this has been here for a long time
allbadlocs[43,list(range(924,925))] = True
elif rn == 11:
allbadlocs = np.zeros((37,1024),dtype=bool)
allbadlocs[7,list(range(237,238)) ] = True
allbadlocs[8,list(range(235,239)) ] = True
allbadlocs[9,list(range(235,239)) ] = True
allbadlocs[10,list(range(235,240)) ] = True
allbadlocs[11,list(range(236,239)) ] = True
allbadlocs[13,list(range(477,482)) ] = True
allbadlocs[14,list(range(476,483)) ] = True
allbadlocs[15,list(range(474,485)) ] = True
allbadlocs[16,list(range(474,486)) ] = True
allbadlocs[17,list(range(474,486)) ] = True
allbadlocs[18,list(range(475,486)) ] = True
allbadlocs[19,list(range(482,487)) ] = True
allbadlocs[20,list(range(482,487)) ] = True
allbadlocs[21,list(range(483,486)) + list(range(663,667)) ] = True
allbadlocs[22,list(range(662,668)) ] = True
allbadlocs[23,list(range(662,668)) ] = True
allbadlocs[24,list(range(662,668)) ] = True
allbadlocs[25,list(range(662,668)) ] = True
allbadlocs[26,list(range(662,668)) ] = True
allbadlocs[27,list(range(662,668)) ] = True
allbadlocs[28,list(range(663,667)) ] = True
else:
print('no RN specified - Could not clean bad locations (clean_badlocs)')
return nrtd
for i,Image in enumerate(nrtd.Image):
#print i
if len(Image.Bleach_Data) > 0:
#If we have bleach data, remove the bad bleach locations
nrtd.Image[i].Bleach_Data[allbadlocs] = np.NaN
try:
nrtd.Image[i].Bleach_Data = np.apply_along_axis(lininterp_nan,1,nrtd.Image[i].Bleach_Data)
except Exception as e:
#Error, likely row removed due to saturation
print(('Clean_badlocs: Error with interp ',i,'b'))
print(e)
nrtd.Image[i].Bleach_Data[:,0] = 0
nrtd.Image[i].Bleach_Data[np.where(nrtd.Image[i].Bleach_Data[:,1023]==np.nan),1023] = 0
try:
nrtd.Image[i].Bleach_Data = np.apply_along_axis(lininterp_nan,1,nrtd.Image[i].Bleach_Data)
except:
print(("Still oculdn't fix error, (blc) removing all data",i))
print(sys.exc_info()[0])
nrtd.Image[i].Bleach_Data = np.zeros(nrtd.Image[i].Bleach_Data.shape)
num_replicates = Image.Replicate_Data.shape[2]
for j in range(0,num_replicates):
#print j
rdata = nrtd.Image[i].Replicate_Data[:,:,j]
rdata[allbadlocs] = np.NaN
try:
nrtd.Image[i].Replicate_Data[:,:,j] = np.apply_along_axis(lininterp_nan,1,rdata)
except Exception as e:
print(("Clean_badlocs: Error with interp",i,j))