-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathIDEASpecPy_Feb_2024.py
More file actions
4045 lines (3231 loc) · 168 KB
/
IDEASpecPy_Feb_2024.py
File metadata and controls
4045 lines (3231 loc) · 168 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 winreg import DisableReflectionKey
from scipy.signal import savgol_filter
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.signal import savgol_filter
from scipy.optimize import curve_fit #see the following link for info on curve_fit
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import datetime
import os.path as path
#import matplotlib.colors
import matplotlib.cm as cm
import glob
import re
import os, fnmatch
import json
from pathlib import Path
import hashlib
from IPython.display import HTML
import pprint
from sklearn.decomposition import FastICA, PCA
import scipy.optimize
from scipy.stats import linregress
#test for update synchronization
global s_offset
wavelengths = [475,488,505,520,535,545]
wls = wavelengths
driftTraces=np.array([-0.97930457, -0.84510825, -0.76824325, -0.68557158, -0.65721521,
-0.71411414, -0.80057651, -0.9111386 , -0.99341127, -1. ,
-0.90233654, -0.7229873 , -0.50413059, -0.30143799, -0.150493 ,
-0.05590374, 0.00378046, 0.03427544, 0.04805041, 0.05288039,
0.05259516, 0.033782 , 0. ])
driftTracesWLs=np.array([460, 465, 470, 475, 480, 485, 490, 495, 500, 505, 510, 515, 520, 525, 530, 535, 540, 545, 550, 555, 560, 565, 570])
print("I am renewed!")
"""
old values
ecs=np.array([-0.86,-0.62,0.23,1.,0.51, 0.2])
qE=np.array([-.01,-.5,-.2,2.9,5.2,3.2])
qE=qE/np.max(qE)
#Zx=np.array([-0.45,-0.24,1.3,0.45,0.31,0.16])
#Zx=Zx-.3
Zx = np.array([-0.01708832, 0.02287851, 0.56242522, 0.51708838, 0.2996292 , 0.15525777])
scatter=np.array([1.1,.6,.25,.1,.07,.05])
scatter = scatter + .3
drift=np.array([.2,.4,.6,.75,.65,.55])
"""
global fudge
global scatter_var
global drift_var
# New values??
# Define the spectral signatures (the set of effective extinction coefficients) for the species
# to deconvolute. This case, the electrochromic shift ('ecs'), the 535nm 'qE' signal, the
# signal associated with violaxantin-->zeaxanthin conversion ('Zx') and signals associated with
# changing leaf orientation ('drift') and light scattering ('scatter').
#Define the ecs coeffficients
def closestToDf(df, param, v):# finds the index of the value for param closes to the value v
x=(df[param]-v)**2
xx=x.sort_values(axis=0)
return df.iloc[xx.index[0]]
def closestToList(alist, v):# finds the index of the value for param closes to the value v
xx=(np.array(alist)-v)**2
return xx.argmin()
def hx():
print("hello")
def defineFitCoefficients():
ecs=2*np.array([-1.18558135, -0.72516973, 0.13613229, 1. , 0.21642832,-0.46697259])
ecs=ecs+.5
#Define the qE coeffficients
qE=np.array([-.01,-.5,-.2,2.9,5.2,3.2])
qE=10*qE/np.max(qE)
#Define the qE coeffficients
Zx=np.array([-0.00179332, -0.00144022, 0.00184943, -0.00044366, -0.00158732,-0.00190934])
Zx=Zx/np.max(Zx)
# Zx=Zx+2.0
# Zx=np.array([-0.15,-0.24,0.8,0.45,0.11,0.03])
# Zx=Zx-2
#Define the 'scatter' coeffficients
scatter=10*np.array([1.1,.6,.25,.1,.07,.05])
#scatter = np.array([0,0,0,0,0,0])
#drift=-10*np.array([.2,.4,.6,.75,.65,.55])
#Define the 'drift' coeffficients
drift=np.array([-0.65471441, 0.35155469, 2.03802372, 3.25785718, 3.482087 , 3.36204459])
# drift=np.array([1.2, 1.35155469, 2.03802372, 3.25785718, 3.482087 , 3.36204459])
print("Component spectra reset.")
return (ecs,qE,Zx,drift,scatter)
ecs,qE,Zx,drift,scatter=defineFitCoefficients()
def cols_with (df, part, ignore_case = True):
cols = []
for col in list(df.columns):
if ignore_case:
col_lc = str.lower(col)
part = str.lower(part)
else:
col_lc = col
if part in col_lc:
cols.append(col)
return cols
#baseFileName='/Users/davidkramer/Dropbox/Data/atsuko/jsontest 050919/col-0_3g-simple_1'
# def hi():
# print("hey there!")
# print("Again, I am renewed!")
# def fixIt (baseFileName):
# # if (destinationBaseFileName==""):
# # destinationBaseFileName=baseFileName
# print(baseFileName)
# filesToCombine = glob.glob(baseFileName + '.dat' '*.json')
# print(filesToCombine)
# # f= open(destinationBaseFileName+'_combined.json',"w+")
# # f.write('[')
# # f.close()
# # f= open(destinationBaseFileName+'_combined.json',"a+")
# #print("combining files:")
# for index, file in enumerate(filesToCombine):
# print(file)
# #print(file)
# # c = open(file,"r+")
# # f.write(c.read())
# # if (index<len(filesToCombine)-1):
# # f.write(', ')
# # f.write(']')
# # f.close()
# # print('Combined ' + str(index + 1) + " json files.")
# with open(file) as myfile:
# content = myfile.read()
# text = re.search(r'"I_File_Name".*.dat,', content, re.DOTALL).group()
# with open("result.txt", "w") as myfile2:
# myfile2.write(text)
def CharlieDAS(df, traceColName):
"""
CharlieDAS(df = dataframe containing the experimental results,
traceColName = a string for the column that contains the kinetic trace.
returns a new dataframe with the transposed data set with columns:
time wl1 wl2 wl3...
CharlieDAS takes in a decay associated spectra experiment from Charlie-type IDEASpec
intruments. These contain a range of traces, each at different wavelengths. The fumnction
combines the traces into a matrix and transposes them so that each row is a different time
point and each column is the absorbance change at a given wavelength.
The traces in col traceColName must have the same length!
"""
df=df.sort_values('wl')
wls = list(df['wl'])
times = df['1_time'][0] # make a list of the times col values in the first dataFrame to use in contructing
# the new transposed dataFrame
allData = []
for i, wl in enumerate(wls):
t = df[df['wl']==wl][traceColName]
trace=list(t.loc[t.index[0]])
allData.append(trace)
allData=np.asarray(allData)
allDataT = allData.transpose()
timePoint=0
tdf = pd.DataFrame([np.append(times[timePoint], allDataT[timePoint])], columns = ["time"] + wls)
for timePoint in range(1,allDataT.shape[0]):
tdf = tdf.append(pd.DataFrame([np.append(times[timePoint], allDataT[timePoint])], columns = ["time"] + wls), ignore_index=True)
return tdf
import json
def generateCombinedJSON (baseFileName, destinationBaseFileName="", append_bases = [''], verbose = False):
if (destinationBaseFileName==""):
destinationBaseFileName=baseFileName
oldJSON = glob.glob(baseFileName + '.datcombined' '*.json')
# print("removed old JSON files:" + str(oldJSON))
# for oldJSONfile in oldJSON:
# os.rename(oldJSONfile, oldJSONfile + 'x')
# append_bases = ['']
for append_base in append_bases:
if verbose:
print(append_base)
addendum = baseFileName + '.dat' + append_base
filesToCombine = glob.glob(addendum + '*.json')
if (len(filesToCombine)<1):
print("No JSON files with base file name = " + baseFileName + "found ")
return
f= open(destinationBaseFileName+'_combined.json',"w+")
f.write('[')
f.close()
f= open(destinationBaseFileName+'_combined.json',"a+")
if verbose:
print("combined file to: " + destinationBaseFileName)
for index, file in enumerate(filesToCombine):
#print(file)
succeeded = False
try:
with open(file) as json_file:
jd = json.load(json_file)
succeeded = True
except:
print("failed:" + file)
succeeded = False
if(succeeded == True):
c = open(file,"r+")
f.write(c.read())
if (index<len(filesToCombine)-1):
f.write(', ')
f.write(']')
f.close()
if verbose:
print('Combined JSON = ' + destinationBaseFileName)
# """
# Recalculates the Abs data using a particular set of I0 points
# input the dataframe, and optionally a list of
# measuring_light_names and the suffix to use,
# and a list of points to average for the I0 value to use in the calculation.
# for example,
# recalcAbsUsingI0 (sample_df, ['475', '488', '505', '520', '535', '545'], I_suffix='_I', [0,1]):
# the '_I' will be attached to the end of the wavelength when searching the dataframe
# in this
# """
print('combineExperiment exists')
def combineExperiment(baseFileNames, destinationFolder):
#dictionary holding all experiments
experiment = {}
for baseFileName in baseFileNames:
experiment_name = baseFileName.split('/')[-1]
if (destinationFolder == ''):
destinationBaseFileName=baseFileName #'/Volumes/D_KRAMER/Thekla/Data FL and LL grown plants/FL'
else:
destinationBaseFileName = destinationFolder + experiment_name
#test if combined_json already exists
destinationCombinedJSONfileName = destinationBaseFileName + '_combined.json'
combined_json_exists = path.isfile(destinationCombinedJSONfileName)
# combined_json_exists= False
if (combined_json_exists == True):
print("Found existing combined JSON, called:" + destinationCombinedJSONfileName)
else:
print("Generating new combined JSON, called")
# each experiment should contain a gob of json files. We will combine them
# go through all baseFileNames and generate the ombined json.
# call the function that combines the individual JSON files into one big one and saves to
print(baseFileName)
if (combined_json_exists == False):
generateCombinedJSON(baseFileName, destinationBaseFileName)
# folder_name=''
#Define the file name for the main program to open.
file_name= destinationBaseFileName + '_combined.json'
# open the combined JSON into a dictionary of data frames
experiment[experiment_name] = {}
df = pd.read_json(file_name)
#remove spaces from column names
cols = df.columns
newCols = []
for k in cols:
newCols.append(k.strip())
df.columns = newCols
df.columns
experiment[experiment_name]['data']=df
#reorder the data fram by the start_time, so the traces are in chronological order
experiment[experiment_name]['data'] = experiment[experiment_name]['data'].sort_values('start_time')
# if notes were taken, add them to the combined json
try:
notes_file = open(baseFileName + '.dat_notes.txt', 'r')
experiment[experiment_name]['notes'] = notes_file.read()
except:
experiment[experiment_name]['notes'] = ""
#make a list that contains the names of all the experiments
allExperiments = list(experiment.keys())
return experiment, allExperiments
def recalcAbsUsingPointsFromI_no_offset (df, list_of_measuring_lights, I_suffix='_I', I0_points=[10,20], trim_points=[0,-1], newSufficx='_rDA'):
if (I0_points[0] == I0_points[1]):
I0_points[1]=I0_points[0]+1
for wl in list_of_measuring_lights:
df[str(wl) + newSufficx] = 0
df[str(wl) + newSufficx] = df[str(wl) + newSufficx].astype('object')
for wl in list_of_measuring_lights:
I0 = np.mean(df.iloc[0][str(wl)+ '_I'][I0_points[0]:I0_points[1]])
# print(I0)
# I0=np.mean(np.array(df.loc[t, str(wl)+ '_I'][I0_points[0]:I0_points[1]]))
for t in df.index: #range(len(df)): #['475']:
daTrace = -1*np.log10(np.array(df[str(wl)+ '_I'][t])/I0) #np.array(df[wl+ '_I'][t][0]))
df[str(wl) + newSufficx][t] = daTrace #[trim_points[0]:trim_points[1]]
def recalcAbsUsingPointsFromI (df, list_of_measuring_lights, I_suffix='_I', I0_points=[0,1], trim_points=[0,-1], newSufficx='_rDA'):
if (I0_points[0] == I0_points[1]):
I0_points[1]=I0_points[0]+1
for wl in list_of_measuring_lights:
df[str(wl) + newSufficx] = 0
df[str(wl) + newSufficx] = df[str(wl) + newSufficx].astype('object')
for t in df.index: #range(len(df)): #['475']:
for wl in list_of_measuring_lights:
# print(wl)
I0=np.mean(np.array(df[str(wl)+ '_I'][t][I0_points[0]:I0_points[1]]))
daTrace = -1*np.log10(np.array(df[str(wl)+ '_I'][t])/I0) #np.array(df[wl+ '_I'][t][0]))
df[str(wl) + newSufficx][t] = daTrace[trim_points[0]:trim_points[1]]
def recalcAbsUsingPointsFromI_selected_indexes (df, list_of_measuring_lights, I_suffix='_I',
I0_points=[0,1], trim_points=[0,-1], newSufficx='_rDA',
indexes = []):
if (len(indexes) == 0):
indexes = df.index
if (I0_points[0] == I0_points[1]):
I0_points[1]=I0_points[0]+1
for wl in list_of_measuring_lights:
df[str(wl) + newSufficx] = 0
df[str(wl) + newSufficx] = df[str(wl) + newSufficx].astype('object')
for t in indexes: #range(len(df)): #['475']:
for wl in list_of_measuring_lights:
# print(wl)
I0=np.mean(np.array(df[str(wl)+ '_I'][t][I0_points[0]:I0_points[1]]))
daTrace = -1*np.log10(np.array(df[str(wl)+ '_I'][t])/I0) #np.array(df[wl+ '_I'][t][0]))
df[str(wl) + newSufficx][t] = daTrace[trim_points[0]:trim_points[1]]
def recalcAbsUsingI0_no_offset (df, list_of_measuring_lights, I_suffix='_I', I0_suffix='_I0', newSuffix='_rDA'):
"""
Recalculate the absorbance traces using the reference channel as the _I0 values. Do not subtrace off any
offsets. This is useful for cases where series of traces are to be combined, among which the relative changes
in the absorbance are desired.
"""
for wl in list_of_measuring_lights: #df['measuring_light_names'][0]:
newColName=str(wl) + newSuffix
df[newColName] = 0
df[newColName] = df[newColName].astype('object')
for t in df.index: #['475']:
for wl in list_of_measuring_lights: #df['measuring_light_names'][t]:
newColName=str(wl) + newSuffix
I0=np.array(df.loc[t,str(wl)+ I0_suffix])
I=np.array(df.loc[t, str(wl)+ I_suffix])
daTrace = -1*np.log10(I/I0) #np.array(df[wl+ '_I'][t][0]))
df[newColName][t] = daTrace #[trim_points[0]:trim_points[1]]
def recalcAbsUsingI0_pt0_offset (df, list_of_measuring_lights, I_suffix='_I', I0_suffix='_I0', newSuffix='_rDA'):
for wl in list_of_measuring_lights: #df['measuring_light_names'][0]:
newColName=str(wl) + newSuffix
df[newColName] = 0
df[newColName] = df[newColName].astype('object')
for t in df.index: #['475']:
for wl in list_of_measuring_lights: #df['measuring_light_names'][t]:
newColName=str(wl) + newSuffix
I0=np.array(df.loc[t,str(wl)+ I0_suffix])
I=np.array(df.loc[t, str(wl)+ I_suffix])
daTrace = np.array(-1*np.log10(I/I0)) #np.array(df[wl+ '_I'][t][0]))
daTrace = daTrace - daTrace[0]
df[newColName][t] = daTrace #[trim_points[0]:trim_points[1]]
def recalcAbsUsingBurnInProfile (df, wavelengths, I_suffix, burn_in_profile, burn_in_suffix, burn_in_index, I0_trace=0, I0_points=[-1,-1], newSuffix='_rDA'):
"""
# Recalculates the Abs data using a particular set of I0 points
# and a separately measured "burn in" profile.
# for example,
# recalcAbsUsingBurnInProfile (sample_df, ['475', '488', '505', '520', '535', '545'], '_I',
# burn_in_profile, '_I', [0,1], '_rDA'):
# burn_in_profile points to a location in a dataframe containing traces taken with the same protocol, but
# without a photosynthetically active sample, e.g. a sheet of green paper.
# New columns with named wavelength + newSuffix (in this case '_rDA') will be generated and attached to the
# dataframe
"""
for wli in wavelengths: # generate new columns to hold objects
wl=str(wli)
df[wl + newSuffix] = 0
df[wl + newSuffix] = df[wl + newSuffix].astype('object')
for t in range(len(df)):
for wli in wavelengths:
wl=str(wli)
I0=np.array(burn_in_profile.loc[burn_in_index][wl+ burn_in_suffix])
I0=I0/np.mean(I0[I0_points[0]:I0_points[1]])
I = np.array(df[wl+ I_suffix][t])
Iz = np.array(df[wl+ I_suffix][I0_trace])
if (I0_points[0]>-1): # if negative number is input, do not do
I = I/np.mean(Iz[I0_points[0]:I0_points[1]])
# elif (I[0]<0):
# I=-1*I
daTrace = -1*np.log10(I/I0) #np.array(df[wl+ '_I'][t][0]))
df[wl + newSuffix][t] = daTrace #[trim_points[0]:trim_points[1]]
for wli in wavelengths:
wl=str(wli)
df[wl + newSuffix][t] = np.array(df[wl + newSuffix][t])-np.mean(np.array(df[wl + newSuffix][I0_trace])[I0_points[0]:I0_points[1]])
# The subtraceBaseline funciton adds a set of traces where the baseline is subtracted. The baseline MUST BE
# the same trace EXCEPT that no catinic was changed AND it is saved with a specific label, e.g. "baseline".
# The wavelengths paramter is a list of the wavelengths upon which traces to subtract.
# The suffix paramter is the suffix for the traces of interest (e.g. '_calc')
# def subtractBaseline(sample_df, wavelengths, traceSuffix, baselineSuffix, newSuffix, baselineLabel = 'baseline'):
# """
# The subtraceBaseline funciton adds a set of traces where the baseline is subtracted. The baseline MUST BE
# the same trace EXCEPT that no catinic was changed AND it is saved with a specific trace_label, e.g. "baseline".
# The wavelengths paramter is a list of the wavelengths upon which traces to subtract.
# The suffix paramter is the suffix for the traces of interest (e.g. '_calc')
# fpor example:
# wavelenths = [475,488,505,520,535,545]
# Ipy.subtractBaseline(sample_df, wavelengths, "_calc", "_calc_m_b", 'baseline)
# where sample_df is the dataframe holding the data sets, wavelenths are the wavelengths of interest
# the columns you wish to subtract the baseline from are '475_calc', '488_calc'...
# the trace with the baseline data has trace_label of 'baseline'
# and you wish to name the new columns '475_calc_m_b', '488_calc_m_b'...
# """
# baseline=sample_df[sample_df['trace_label']==baselineLabel]
# bindex=baseline.index[0]
# traces=sample_df[sample_df['trace_label']=='fluct']
# for wli in range(len(wavelengths)):
# wl=str(wavelengths[wli])
# #print(wl)
# sample_df[wl + newSuffix] = 0
# sample_df[wl + newSuffix] = sample_df[wl + newSuffix].astype('object')
# for i in range(0, len(sample_df[wl+traceSuffix])): # cycle through the traces for each wl
# #print(i)
# sample_df[wl + newSuffix][i] = np.array(sample_df[wl + traceSuffix][i]) - np.array(baseline[wl + baselineSuffix][bindex])
# #len(sample_df['475_time'][0]), len(sample_df['475_I'][0])
def subtractBaseline(sample_df, wavelengths, suffix, AvPoints, new_suffix = '_sub'):
"""
The subtraceBaseline function adds a set of traces where the baseline is subtracted. The baseline MUST BE
the same trace EXCEPT that no atinic was changed AND it is saved with a specific label, e.g. "baseline".
The wavelengths paramter is a list of the wavelengths upon which traces to subtract.
The suffix paramter is the suffix for the traces of interest (e.g. '_calc')
"""
#plt.figure()
for wavelength in wavelengths: # generate new columns to hold objects
# wl=str(wli)
data_col = str(wavelength) + suffix
if (new_suffix == ''):
newColName = data_col
else:
newColName = str(wavelength) + new_suffix #+ '_sub'
sample_df[newColName] = 0
sample_df[newColName] = sample_df[newColName].astype('object')
for index in sample_df.index:
# print(AvPoints)
avbl = np.mean(sample_df[data_col][index][AvPoints[0]:AvPoints[1]])
# print(avbl)
dif = np.array(sample_df[data_col][index])-avbl
# print(dif)
sample_df[newColName][index] = dif
return sample_df
from scipy.optimize import curve_fit #see the following link for info on curve_fit
def fit_burn(x,a,b,c):
"""
Function for fitting absorbance traces to a funciton to account for
I will fit the baseline with a hyperbolic or exponential
a is the amplitude of the burn-in
b is the time constant
c is the offset
"""
fit_burn = c + a/(1+x/b)
return (fit_burn)
def burnCorrection(sample_df,wavelengths,suffix,baselineArray,newSuffix = '_bcor', retainOffset = False):
fit_b=baselineArray[0]
fit_e=baselineArray[1]
print("de-burning")
for i in range(len(wavelengths)):
wl = str(wavelengths[i])
sample_df[str(wl) + newSuffix] = 0
sample_df[str(wl) + newSuffix] = sample_df[str(wl) + newSuffix].astype('object')
# print(str(wl) + newSuffix)
tName = wl + suffix
# print("response (x) colummn = " + tName)
xName = wl + '_time'
# print("time column = " + xName)
#corTraces=[]
#print(len(sample_df[tName]))
# sample_df_s = sample_df[tName].select_dtypes(include=['object'])
mask = sample_df[tName].apply(lambda x: isinstance(x, list))
for traceNum in sample_df.index: #range (0, len(sample_df[tName])):
# print('trace index = ' + str(traceNum))
if (1): #mask[traceNum] == True):
# print('trace Name = ' + str(tName))
y_data = sample_df.loc[traceNum, tName]
# print(len(y_data))
# x_data=np.array(sample_df.loc[traceNum, xName])
# x_data=x_data-x_data[0]
x_data = np.linspace(0,len(y_data)-1, len(y_data))
popt, pcov = curve_fit(fit_burn, x_data[fit_b:fit_e], y_data[fit_b:fit_e], p0=[.1,.1,.001], maxfev=100000 ) #bounds=([-np.inf, 0, -np.inf], np.inf), )
# print(popt)
corTrace=[]
offset = 0.0
if (retainOffset == True):
offset = np.mean(y_data[fit_b:fit_e])
# print(len(x_data), len(y_data))
for i, x in enumerate(y_data):
vc = y_data[i] - fit_burn(x_data[i], popt[0],popt[1],popt[2]) + offset
corTrace.append(vc)
# print(str(wl) + newSuffix)
# print(corTrace)
sample_df[str(wl) + newSuffix].loc[traceNum]=np.array(corTrace)
# print(sample_df[str(wl) + newSuffix].loc[traceNum])
# sample_df[str(wl) + newSuffix][traceNum]=np.array(corTrace)
# sample_df.loc[traceNum, str(wl) + newSuffix]=corTrace
def burnCorrectionTwoRegions(sample_df,wavelengths,suffix,baselineArray,newSuffix = '_bcor', retainOffset = False):
fit_b=baselineArray[0]
fit_e=baselineArray[1]
print("de-burning")
for i in range(len(wavelengths)):
wl = str(wavelengths[i])
sample_df[str(wl) + newSuffix] = 0
sample_df[str(wl) + newSuffix] = sample_df[str(wl) + newSuffix].astype('object')
# print(str(wl) + newSuffix)
tName = wl + suffix
# print("response (x) colummn = " + tName)
xName = wl + '_time'
# print("time column = " + xName)
#corTraces=[]
#print(len(sample_df[tName]))
for traceNum in sample_df.index: #range (0, len(sample_df[tName])):
#print('trace index = ' + str(traceNum))
#print('trace Name = ' + str(tName))
y_data=np.array(sample_df.loc[traceNum, tName])
# x_data=np.array(sample_df.loc[traceNum, xName])
# x_data=x_data-x_data[0]
x_data = np.linspace(0,len(y_data)-1, len(y_data))
popt, pcov = curve_fit(fit_burn, x_data[fit_b:fit_e], y_data[fit_b:fit_e], p0=[.1,.1,.001], maxfev=100000 ) #bounds=([-np.inf, 0, -np.inf], np.inf), )
corTrace=[]
offset = 0.0
if (retainOffset == True):
offset = np.mean(y_data[fit_b:fit_e])
# print(len(x_data), len(y_data))
for i, x in enumerate(y_data):
vc = y_data[i] - fit_burn(x_data[i], popt[0],popt[1],popt[2]) + offset
corTrace.append(vc)
# print(str(wl) + newSuffix)
# print(corTrace)
sample_df[str(wl) + newSuffix].loc[traceNum]=np.array(corTrace)
def burnCorrectionMultipleRegions(sample_df, wavelengths, suffix, baselineArrays, newSuffix = '_bcor', retainOffset = False):
"""
baselineArrays is a list of lists containing segments to use in the
burn-in fit.
Each list with a begin and end point
"""
print("de-burning")
for i in range(len(wavelengths)):
wl = str(wavelengths[i])
sample_df[str(wl) + newSuffix] = 0
sample_df[str(wl) + newSuffix] = sample_df[str(wl) + newSuffix].astype('object')
tName = wl + suffix
xName = wl + '_time'
for traceNum in sample_df.index: #range (0, len(sample_df[tName])):
#print('trace index = ' + str(traceNum))
#print('trace Name = ' + str(tName))
y_data=np.array(sample_df.loc[traceNum, tName])
# x_data=np.array(sample_df.loc[traceNum, xName])
# x_data=x_data-x_data[0]
x_data = np.linspace(0,len(y_data)-1, len(y_data))
fit_x = np.array([])
fit_y = np.array([])
for baselineArray in baselineArrays:
fit_b=baselineArray[0]
fit_e=baselineArray[1]
fit_x = np.concatenate((fit_x[fit_b:fit_e], x_data[fit_b:fit_e]))
fit_y = np.concatenate((fit_y[fit_b:fit_e], y_data[fit_b:fit_e]))
popt, pcov = curve_fit(fit_burn, fit_x, fit_y, p0=[.1,.1,.001], maxfev=100000 ) #bounds=([-np.inf, 0, -np.inf], np.inf), )
corTrace=[]
offset = 0.0
if (retainOffset == True):
offset = np.mean(fit_y)
# print(len(x_data), len(y_data))
for i, x in enumerate(y_data):
vc = y_data[i] - fit_burn(x_data[i], popt[0],popt[1],popt[2]) + offset
corTrace.append(vc)
# print(str(wl) + newSuffix)
# print(corTrace)
sample_df[str(wl) + newSuffix].loc[traceNum]=np.array(corTrace)
def smoothTracesWL(sample_df, wavelengths, suffix, smooth_window=50, newSuffix = '_smooth'):
for i in range(len(wavelengths)):
wl = str(wavelengths[i])
tName = wl + suffix
newColName= tName + newSuffix
sample_df[newColName] = 0
sample_df[newColName] = sample_df[newColName].astype('object')
for traceNum in sample_df.index: # cycle through each trace in experiment
subtrace=sample_df.loc[traceNum, tName]
smoothedTrace=savgol_filter(subtrace , smooth_window, 3)
sample_df[newColName][traceNum]=smoothedTrace
def smoothTraces(df,tName,smooth_window=25,newSuffix = '_smooth'):
"""
smoothTraces(dataFrame, name of the column holding the traces to be smoothed, smooth wondow (must be odd), suffix for the new column name)
"""
if (smooth_window % 2) == 0:
smooth_window = smooth_window+1
newColName= tName + newSuffix
df[newColName] = 0
df[newColName] = df[newColName].astype('object')
for traceNum in range(len(df[tName])): # cycle through each trace in experiment
subtrace=df[tName].iloc[traceNum]
smoothedTrace=savgol_filter(subtrace , smooth_window, 3)
df[newColName].iloc[traceNum]=smoothedTrace
def subtractStraightLine(df,y_column_name, beg_points_array,end_points_array, newSuffix = '_sub',x_column_name=None):
"""
subtractStraightLine(dataFrame, name of the column holding the x-values of the traces,
name of the column holding the y-values of the traces,
[beg, end time point indexes for the left-hand point for subtraced line],
[beg, end time point indexes for the RIGHT hand point of line. Values within range will be averaged],
suffix for the new column name)
"""
newColName= y_column_name + newSuffix
df[newColName] = 0
df[newColName] = df[newColName].astype('object')
for traceNum in range(len(df[y_column_name])): # cycle through each trace in experiment
subtrace_y=np.array(df[y_column_name].iloc[traceNum])
subtrace_y = subtrace_y - np.mean(subtrace_y[beg_points_array[0]:beg_points_array[1]]) #subtract the first point so that the y-intercept will be zero
if (x_column_name==None):
subtrace_x=np.linspace(0,len(subtrace_y), len(subtrace_y))
else:
subtrace_x=df[x_column_name].iloc[traceNum]
x1 = np.mean(subtrace_x[beg_points_array[0]:beg_points_array[1]])
x2 = np.mean(subtrace_x[end_points_array[0]:end_points_array[1]])
y1 = np.mean(subtrace_y[beg_points_array[0]:beg_points_array[1]])
y2 = np.mean(subtrace_y[end_points_array[0]:end_points_array[1]])
slope = (y2-y1)/(x2-x1)
subtracted_trace = []
for i in range(len(subtrace_y)):
y_offset = slope*subtrace_x[i]
subtracted_trace.append(subtrace_y[i]-y_offset)
df[newColName].iloc[traceNum]=subtracted_trace
def generateDAS(sample_df, wavelengths, suffix='_rDA', newColName='das', selected_indexes = []):
"""
Generate a series of decay associated spectra from a series of kinetic traces, each taken at a differnet wavelength.
This is for traces with multiple measuring LEDs.
IMPORTANT: It is NOT for data with traces taken with different m easuring LEDs at different wavelengths, e.g. as in Charlie results.
generateDAS(sample_df (the dataFrame), wavelengths (a list of wavelengths), suffix='_rDA'
(the name of the columns that contain the wavelength with the given suffix e.g. 505_rDA, newColName='das'),
a new suffix for the DAS series.
selected_indexes is a list of indexes to use
"""
sample_df[newColName] = 0
sample_df[newColName] = sample_df[newColName].astype('object')
# global test_wl
# test_wl = []
selected_indexes = list(selected_indexes)
if (selected_indexes == []):
use_index = sample_df.index
print("using all indexes: " + str(use_index))
else:
use_index = selected_indexes
print("using selected_indexes :" + str(use_index))
for t_index in use_index:
# print(t)
dass=[]
wl = str(wavelengths[0]) #start with the first wl
# print(len(sample_df[wl + suffix][t_index]))
# try:
if (type(sample_df[str(wl) + suffix][t_index]) == np.nan):
print("Nan")
else:
for pt in range(len(sample_df[wl + suffix][t_index])): #cycle through all points in the trace
das=[]
#test_wl = []
for wl in range(len(wavelengths)):
das.append(sample_df[str(wavelengths[wl]) + suffix][t_index][pt])
#test_wl.append(wavelengths[wl])
dass.append(das)
# except:
# pass
# print(test_wl)
sample_df[newColName][t_index] = dass
return sample_df
def generateDAS_baseline_subtracted(sample_df, wavelengths, suffix='_rDA', newColName='das'):
"""
Generate a series of decay associated spectra from a series of kinetic traces, each taken at a differnet wavelength.
In this version, a baseline is subtraced between the points with the lowest and highest wavelenghth
This is for traces with multiple measuring LEDs.
IMPORTANT: It is NOT for data with traces taken with different m easuring LEDs at different wavelengths, e.g. as in Charlie results.
generateDAS(sample_df (the dataFrame), wavelengths (a list of wavelengths), suffix='_rDA'
(the name of the columns that contain the wavelength with the given suffix e.g. 505_rDA, newColName='das'),
a new suffix for the DAS series.
"""
sample_df[newColName] = 0
sample_df[newColName] = sample_df[newColName].astype('object')
for t in sample_df.index:
dass=[]
wl = str(wavelengths[0]) #start with the first wl
for pt in range(len(sample_df[wl + suffix][t])): #cycle through all points in the trace
das=[]
for wl in range(len(wavelengths)):
das.append(sample_df[str(wavelengths[wl]) + suffix][t][pt])
das = np.array(das) # convert to an array
das = das - das[0] # subtract off the value of the first point
das_at_max_wl = das[-1] #assuming that the wavelengths are in ascending order!!
# print(das_at_max_wl)
max_wl_change = wavelengths[-1] - wavelengths[0]
slope = das_at_max_wl/max_wl_change
# print(slope)
for i in range(1,len(das)):
das[i] = das[i] - slope * (wavelengths[i]- wavelengths[0])
dass.append(das)
sample_df[newColName][t] = dass
def fit_spec_5_old(x,a,b,c,d,e): #function to fit the spectroscopic data
global ecs
global qE
global Zx
global scatter
global drift
# Expecting absorbance data from 5 wavelengths per time point
# The component spectra also have 7 wavelength
#print(len(components[0]),len(components[1]),len(components[2]),len(components[3]))
fit_spectrum = a*ecs + b*qE + c*Zx + d*scatter #+ e*drift
return (fit_spectrum)
def fit_spec_5_4_old(x,a,b,c,d,e): #function to fit the spectroscopic data
global ecs
global qE
global Zx
global scatter
global drift
# Expecting absorbance data from 5 wavelengths per time point
# The component spectra also have 7 wavelength
#print(len(components[0]),len(components[1]),len(components[2]),len(components[3]))
fit_spectrum = a*ecs + b*qE + c*Zx + d*scatter + e*drift
return (fit_spectrum)
def fit_spec_5_4_genotype(xxspecs,a,b,c,d,e): #function to fit the spectroscopic data
# xxecs, xxqE, xxZx, xxscatter, xxdrift = xxspecs
# Expecting absorbance data from 5 wavelengths per time point
# The component spectra also have 5 wavelength
fit_spectrum = a*xxspecs[0] + b*xxspecs[1] + c*xxspecs[2] + d*xxspecs[3] + e*xxspecs[4]
return (fit_spectrum)
def fit_spec_5_4_var(x,a,b,c,d,e): #function to fit the spectroscopic data
global ecs
global qE
global Zx
global scatter_var
global drift
global drift_var
# Expecting absorbance data from 5 wavelengths per time point
# The component spectra also have 7 wavelength
#print(len(components[0]),len(components[1]),len(components[2]),len(components[3]))
fit_spectrum = a*ecs + b*qE + c*Zx + d * scatter_var + e*drift_var
return (fit_spectrum)
# def fit_spec_5(x,a,b,c,d,e): #function to fit the spectroscopic data
# global ecs
# global qE
# global Zx
# global scatter
# global drift
# # Expecting absorbance data from 5 wavelengths per time point
# # The component spectra also have 7 wavelength
# #print(len(components[0]),len(components[1]),len(components[2]),len(components[3]))
# fit_spectrum = a*ecs + b*qE + c*Zx + d*scatter + e*drift
# return (fit_spectrum)
def fit_spec_5(x,a,b,c,d,e): #function to fit the spectroscopic data
global ecs
global qE
global Zx
global scatter
global drift
ecs, qE, Zx, scatter, drift = x
# print(x,a,b,c,d,e)
# print(type(ecs))
# print(type(qE))
# print(type(Zx))
# print(type(scatter))
# print(type(drift))
# Expecting absorbance data from 5 wavelengths per time point
# The component spectra also have 7 wavelength
#print(len(components[0]),len(components[1]),len(components[2]),len(components[3]))
fit_spectrum = a*ecs + b*qE + c*Zx + d*scatter + e*drift
# print(fit_spectrum)
return (fit_spectrum)
def fit_spec_5_Thekla(x,a,b,c,d,e): #function to fit the spectroscopic data
global ecs
global qE
global Zx
global scatter
global drift
# Expecting absorbance data from 5 wavelengths per time point
# The component spectra also have 7 wavelength
#print(len(components[0]),len(components[1]),len(components[2]),len(components[3]))
fit_spectrum = a*ecs + b*qE + c*Zx + d*scatter #+ e*drift
return (fit_spectrum)
# def fitDAS_5(sample_df, wavelengths, dasColName, newSuffix=''):
# components = ['ecs', 'qE', 'Zx', 'scatter', 'drift']
# for c in components:
# newColName= c + newSuffix
# sample_df[newColName] = 0
# sample_df[newColName] = sample_df[newColName].astype('object')
# for traceNum in range (0, len(sample_df[dasColName])): # cycle through each trace in experiment
# comp={}
# for c in components:
# comp[c]=[]
# for time_index in range(len(sample_df[dasColName][0])):
# y_data=sample_df[dasColName][traceNum][time_index]
# popt, pcov = curve_fit(fit_spec_5, wavelengths, y_data, p0=[0,0,0,0,0])
# for i, c in enumerate(components):
# comp[c].append(popt[i])
# for c in components:
# newColName= c + newSuffix
# sample_df[newColName][traceNum] = comp[c]
# this cell only defines a function, see the next cell for an example of how you would use this function
# add/replace one row to the given dataframe, by computing averages for certain rows/columns
def compute_average_row( sample_df, rows_to_average, columns_to_average, label_for_new_averaged_row):
# build a list of cell values for the new row, including blanks for non-relevenat columns
values_for_new_row = []
for column in sample_df.columns:
if column in columns_to_average:
# collect all values to be averaged
array_to_average_2d = []
for row in rows_to_average:
array_to_average_2d.append(np.array(sample_df.loc[row,column]))
# compute average
values_for_new_row.append(np.mean(np.array(array_to_average_2d), axis=0))
else:
values_for_new_row.append("")
# add the new row
if label_for_new_averaged_row in sample_df.index:
sample_df = sample_df.drop(label_for_new_averaged_row,axis=0)
sample_df.loc[label_for_new_averaged_row] = values_for_new_row
def fitDAS_5(sample_df, wavelengths, dasColName, specs, newSuffix='', zeroEnds = False, ):
components = ['ecs', 'qE', 'Zx', 'scatter', 'drift']
# global ecs
# global qE
# global Zx
# global drift
# global scatter
if (zeroEnds == True):
ecs=ecs-np.linspace(ecs[0],ecs[-1],len(ecs))
qE=qE-np.linspace(qE[0],qE[-1],len(qE))
Zx=Zx-np.linspace(Zx[0],ecs[-1],len(Zx))
drift=drift-np.linspace(drift[0],drift[-1],len(drift))
scatter=scatter-np.linspace(scatter[0],scatter[-1],len(scatter))
#drift = np.linspace(-1,15,len(wavelengths)) #
#scatter = np.linspace(10,10,len(wavelengths))