-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpyhxexpress_04mar2024.py
2139 lines (1872 loc) · 108 KB
/
pyhxexpress_04mar2024.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
'''
pyHXEXPRESS
'''
#%matplotlib widget
import numpy as np, pandas as pd
import scipy.stats as stats
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import matplotlib.cm as cm
from matplotlib.font_manager import FontProperties
from matplotlib.backends.backend_pdf import PdfPages
#import fitz #!pip install pymupdf
#import matplotlib.colors as mcolors
import os
import sys
import importlib
import tensorflow as tf
from keras.models import load_model
from scipy.optimize import curve_fit
from scipy.optimize import differential_evolution
#from scipy.stats import rankdata, skew
#from scipy.special import comb
from math import gamma, lgamma, exp
from pyteomics import mass
#!pip install brain-isotopic-distribution
from brainpy import isotopic_variants
import random
from datetime import datetime
from collections import Counter
from Bio import SeqIO
import config
rng=np.random.default_rng(seed=config.Random_Seed)
now = datetime.now()
date = now.strftime("%d%b%Y")
mpl_colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
mpl_colors_dark = ['#005794', '#df5f0e', '#0c800c', '#b60708', '#74479d', '#6c362b', '#b357a2', '#5f5f5f', '#9c9d02', '#079eaf']
mpl_colors_light = ['#2f97e4', '#ff9f2e', '#4cc04c', '#f64748', '#b487ed', '#ac766b', '#f397e2', '#9f9f9f', '#dcdd42', '#37deef']
mpl_colors_light2 = ['#4fb7f4', '#ffbf4e', '#6ce06c', '#f66768', '#d4a7fd', '#cc968b', '#f3b7f2', '#bfbfbf', '#fcfd62', '#57feff']
colors2d = [mpl_colors_dark, mpl_colors, mpl_colors_light,mpl_colors_light2]
import warnings
warnings.simplefilter (action='ignore', category=FutureWarning)
# class dotdict(dict):
# """dot.notation access to dictionary attributes"""
# __getattr__ = dict.get
# __setattr__ = dict.__setitem__
# __delattr__ = dict.__delitem__
# obsolete function after introduction of import config
# def get_parameters(PARAMS_FILE):
# params_dir = os.path.split(PARAMS_FILE)
# curr_dir = os.getcwd()
# os.chdir(params_dir[0])
# para_file = params_dir[1].rsplit('.')[0]
# #p,m = PARAMS_FILE.rsplit('.',1)
# mod = importlib.import_module(para_file)
# importlib.reload(mod)
# values = {v: getattr(mod, v)
# for v in mod.__dict__
# if not v.startswith("_")}
# globals().update({v: getattr(mod, v)
# for v in mod.__dict__
# if not v.startswith("_")})
# os.chdir(curr_dir)
# return values
def write_parameters(write_dir=os.getcwd(),overwrite=False):
'''
save current user settings to a python file
this can be read in using:
> import pyhxexpress as hxex
> import file_name.py as config
> hxex.config = config #must run to update parameters to be used
file needs to be in same file location as the current working directory set in the notebook (this is the default save location)
'''
all_params = ['Allow_Overwrite', 'BestFit_of_X', 'Binomial_dCorr', 'Data_DIR', 'Data_Type', 'DiffEvo_kwargs', 'DiffEvo_threshold','Dfrac', 'Env_limit',
'Env_threshold', 'FullDeut_Time', 'Hide_Figure_Output', 'Keep_Raw', 'Limit_by_envelope', 'Max_Pops', 'Metadf_File', 'Min_Pops', 'Nboot',
'Ncurve_p_accept', 'Nex_Max_Scale', 'Nterm_subtract', 'Output_DIR', 'Overlay_replicates', 'Peak_Resolution', 'Pop_Thresh', 'Preset_Pops',
'Preset_Pops_File', 'process_ALL', 'Random_Seed', 'Read_Spectra_List', 'Residual_Cutoff','Save_Spectra', 'Scale_Y_Values', 'setNoise',
'SVG', 'Test_Data', 'Use_DiffEvo', 'User_mutants', 'User_peptides', 'WRITE_PARAMS', 'Y_ERR', 'Zero_Filling']
filename = "hdxms_params_"+config.date+".py"
write_file = os.path.join(write_dir,filename)
if not overwrite:
add_string=""
i = 0
while os.path.exists(write_file):
i += 1
add_string=str(i)
write_file = os.path.join(write_dir,"hdxms_params_"+config.date+"_"+add_string+".py")
with open(write_file,"w") as p_file:
print_name = os.path.join(os.path.basename(os.path.normpath(write_dir)),filename)
print("Saving config parameters to "+print_name+"\n")
#write header
p_file.write("import os\n"+
"from datetime import datetime\n"+
"now = datetime.now()\n"+
"date = now.strftime('%d%b%Y')\n\n")
p_file.write("#config parameters "+str(config.date)+"\n")
for p in all_params:
# #print(p,globals().get(p))
# if type(vars().get(p)) == str:
# p_file.write(p+" = \""+str(globals().get(p))+"\"\n")
# else: p_file.write(p+" = "+str(globals().get(p))+"\n")
try:
if type(getattr(config,p)) == str:
#p_file.write(p+" = \""+str(getattr(config,p))+"\"\n")
p_file.write(p+" = r\""+os.path.normpath(getattr(config,p))+"\"\n")
else:
p_file.write(p+" = "+str(getattr(config,p))+"\n")
except:
p_file.write("# missing parameter "+p+"\n")
## Functions to read data in different formats
def get_hxexpress_meta(hx_file):
'''
this was written for a specific filename format: SAMPLE_START-END-PEPTIDE-zCHARGE-usertext.xlsx
'''
labels = hx_file.split('-')
metadata = {}
metadata['file']=hx_file
metadata['sample'] = str(labels[0]).rsplit('_',1)[0] #split off the peptide start_seq
start_seq = str(labels[0]).rsplit('_',1)[-1]
end_seq = labels[-4] #end sequence is fourth from end, allows for whatever sample name formatting
metadata['start_seq'] = int(start_seq)
metadata['end_seq'] = int(end_seq)
metadata['peptide_range'] = '-'.join([start_seq,end_seq])
metadata['charge']=float(labels[-2][1:])
metadata['peptide'] = labels[-3]
return metadata
def save_metadf(metadf,filename=None):
'''
save the metadf (or other dataframe) as csv file
'''
savedf = metadf.copy()
int_cols = ['charge','start_seq','end_seq','rep']
if not os.path.exists(config.Output_DIR): os.makedirs(config.Output_DIR)
for ic in int_cols:
if ic in savedf.columns:
savedf[ic] = savedf[ic].astype(int)
if filename:
saveto = os.path.join(config.Output_DIR,filename)
else:
saveto = os.path.join(config.Output_DIR,'hdx_spectra_list_metadf_'+date+'.csv')
savedf.to_csv(saveto,index_label='Index',mode='w')
def read_metadf(filename):
'''
read in the metadf dataframe from a csv file
'''
try:
readfrom = os.path.join(config.Data_DIR,filename)
readmetadf = pd.read_csv(readfrom).drop('Index',axis=1)
return readmetadf
except:
print("No file found for spectra list")
return
def get_metadf():
if config.Read_Spectra_List:
metadf = read_metadf(config.Metadf_File)
else:
metadf = pd.DataFrame()
if config.Data_Type == 1:
if config.Test_Data:
metadf = read_metadf(config.Metadf_File)
else:
hx_files = [ f for f in os.listdir(config.Data_DIR) if f[-5:]=='.xlsx' ]
if not config.process_ALL:
if 'all' not in config.User_mutants[0].lower():
#available_mutants = set([um for hx in hx_files for um in User_mutants if um in hx])
hx_files = [hx for um in config.User_mutants for hx in hx_files if um == hx.split('-')[0].rsplit('_',1)[0]]
if 'all' not in config.User_peptides[0].lower():
#available_charges = set([up for hx in hx_files for up in User_peptides if up in hx])
hx_files = [hx for up in config.User_peptides for hx in hx_files if up in hx]
#HSPB1_B1B5_0001-0011-MTERRVPFSLL-z2-allspectra.xlsx
#metadf = pd.DataFrame() #dataframe to hold filenames and sample/peptide/charge info
for f in hx_files:
meta = get_hxexpress_meta(f)
metadf = metadf.append(meta,ignore_index=True)
elif config.Data_Type == 2:
fasta_files = [ f for f in os.listdir(config.Data_DIR) if f[-6:]=='.fasta' ]
if len(fasta_files)==0: print("no fasta files found")
mutants = [ff.split('.')[0] for ff in fasta_files]
mutant_dirs = [os.path.split(f)[-1] for f in os.scandir(os.path.join(config.Data_DIR)) if f.is_dir()]
mutants = [o for o in mutant_dirs if o in mutants] #ignore any extra fasta files
if (not config.process_ALL) and (config.User_mutants[0].lower() != 'all'):
check = all(item in mutants for item in config.User_mutants)
if not check:
missing = list(set(config.User_mutants)-set(mutants))
remaining = list(set(config.User_mutants)-set(missing))
print("missing fasta files for: ", *list(set(config.User_mutants)-set(mutants)))
mutants = [o for o in config.User_mutants if o in remaining]
if len(mutants): print("only processing",*mutants)
else: mutants = config.User_mutants
smeta = {}
#metadf = pd.DataFrame()
for mutant in mutants:
peptide_dirs = [f.path for f in os.scandir(os.path.join(config.Data_DIR,mutant)) if f.is_dir()]
peptide_ids = [os.path.split(ff)[-1] for ff in peptide_dirs]
peptide_ranges = [ff.rsplit('-',1)[0] for ff in peptide_ids]
if (not config.process_ALL) and (config.User_peptides[0].lower() != 'all'):
check = all(item in peptide_ranges for item in config.User_peptides)
if not check:
print("missing peptides for: ",mutant, *list(set(config.User_peptides)-set(peptide_ranges)))
missing = list(set(config.User_peptides)-set(peptide_ranges))
remaining = list(set(config.User_peptides)-set(missing))
peptide_ranges = [o for o in config.User_peptides if o in remaining]
else:
peptide_ranges = config.User_peptides
peptide_dirs = list(filter(lambda x: any(userpep in x for userpep in config.User_peptides),peptide_dirs))
fasta_sequence = SeqIO.parse(open(os.path.join(config.Data_DIR,str(mutant)+'.fasta')),'fasta')
for fasta in fasta_sequence:
sequence = str(fasta.seq)
for spec_dir,peptide_range in zip(peptide_dirs,peptide_ranges):
csv_files = [ f for f in os.listdir(spec_dir) if f[-4:]=='.csv' ]
charges = set([int(c[-5]) for c in csv_files if c[-5].isdigit() and c[-6]=='z'])
for charge in charges:
smeta['file']=os.path.split(spec_dir)[1]
smeta['sample']=os.path.split(os.path.split(spec_dir)[0])[1]
smeta['charge']=float(charge)
smeta['peptide_range']=peptide_range
startseq = int(peptide_range.split('-')[0])
endseq = int(peptide_range.split('-')[1])
smeta['start_seq'] = startseq
smeta['end_seq'] = endseq
smeta['peptide'] = sequence[startseq-1:endseq]
#metadf = metadf.append(smeta, ignore_index = True)
metadf = pd.concat([metadf,pd.DataFrame([smeta])],ignore_index = True)
else: print("Must specify Data_Type: 1 for HX-Express allspectra format or 2 for SpecExport")
if metadf.empty: raise Exception("No data found. Check Data_Type specification and Data_DIR")
else:
metadf = metadf.sort_values(['peptide_range','sample','charge',],ignore_index=True)
print("Found",len(metadf['sample'].unique()),"sample types with",len(metadf),"total datasets to analyze.")
return metadf
def makelist(thing):
'''
utility function to make any variable into a list
'''
thing = [thing] if not isinstance(thing, list) else thing
return thing
def filter_df(metadf=pd.DataFrame(),samples=None,range=None,peptide_ranges=None,
charge=None,index=None,timept=None,timeidx=None,peptides=None,rep=None,data_ids=None,quiet=True):
''' Utility function to Filter metadf (or any other dataframe) based on user specified values
samples = ['sample1','sample2'] or 'sample1'
range = [start,end]
peptide_ranges = ['0001-0015','0030-0042'] or '0001-0015'
charge = [1,2,3] or 1.0
index = [15,58,72] or [*range(0,50)] (Note: can just use filtered = metadf[0:50])
timept = [0.0,5.0,1e6] or 0.0
timeidx = [0,1,...,]
peptides = ['PEPTIDESEQ','PEPITYPEPTIDE'] or 'PEPTIDESEQ'
rep = [1,2,3] or 1
data_id = [0,1,...]
'''
filtered = metadf.copy()
if samples:
try: filtered = filtered[filtered['sample'].isin(makelist(samples))]
except:
if not quiet: print("no column named sample")
if not filtered.empty and range:
try:
if set(['start_seq','end_seq']).issubset(filtered.columns):
filtered = filtered[(filtered['start_seq']>= range[0]) & (filtered['end_seq'] <= range[1])]
elif 'peptide_range' in filtered.columns:
filtered[['start_seq','end_seq']] = filtered['peptide_range'].str.split('-',expand=True).astype('int')
filtered = filtered[(filtered['start_seq']>= range[0]) & (filtered['end_seq'] <= range[1])]
filtered = filtered.drop(columns=['start_seq','end_seq'])
else: print("Missing start/end seq or peptide_range column")
except:
print("Filter error: specify range=[start,end]")
return
if not filtered.empty and charge:
try: filtered = filtered[filtered['charge'].isin(makelist(charge))]
except: print("no column named charge")
if not filtered.empty and (data_ids or data_ids == 0):
if 'data_id' in filtered.columns:
filtered = filtered[filtered['data_id'].isin(makelist(data_ids))]
else: index = data_ids
if not filtered.empty and (index or index == 0):
filtered = filtered[filtered.index.isin(makelist(index))]
if not filtered.empty and (timept or timept == 0): #not in metadf but use to filter all_results_dataframe for Fixed_Pops
try: filtered = filtered[filtered['time'].isin(makelist(timept))]
except: print("no column named time")
if not filtered.empty and (timeidx or timeidx == 0): #not in metadf but use to filter all_results_dataframe for Fixed_Pops
try: filtered = filtered[filtered['time_idx'].isin(makelist(timeidx))]
except: print("no column named time_idx")
if not filtered.empty and peptides: #not in metadf but use to filter all_results_dataframe for Fixed_Pops
try: filtered = filtered[filtered['peptide'].isin(makelist(peptides))]
except: print("no column named peptide")
if not filtered.empty and peptide_ranges:
try: filtered = filtered[filtered['peptide_range'].isin(makelist(peptide_ranges))]
except: print("no column named peptide_ranges")
if not filtered.empty and (rep or rep == 0):
try: filtered = filtered[filtered['rep'].isin(makelist(rep))]
except: print("no column named rep")
if quiet == False:
print("Dataframe filtered to",len(filtered),"from",len(metadf),"total entries")
if len(filtered) == 0: print("Warning: No datasets selected")
return filtered
#safety function in case peptide sequence is bad
def goodseq(seq):
try:
mass.most_probable_isotopic_composition(sequence=seq)
return True
except:
print(f"Sequence {seq} is not defined")
#exit()
return False
def read_hexpress_data(f,dfrow,keep_raw = False,mod_dict={}):
def pops(row): #just for test data
pop = 0
for col in ['p1','p2','p3']:
if row[col] > 0: pop += 1
return pop
raw=[]
all_raw = pd.DataFrame()
dfs = pd.DataFrame()
deutdata = pd.DataFrame()
peaks=[]
sample = dfrow['sample']
start_seq = dfrow['start_seq']
end_seq = dfrow['end_seq']
peptide_range = dfrow['peptide_range']
charge = dfrow['charge']
peptide = dfrow['peptide']
data_id = dfrow.name
file=os.path.join(config.Data_DIR, f)
try:
if (file[-4:] == 'xlsx') or (file[-3:] == 'xls'):
ftype = 'excel'
timepts = pd.read_excel(file,header=None,nrows=1) #get headers
elif file[-4:] == 'csv':
ftype = 'csv'
timepts = pd.read_csv(file,header=None,nrows=1) #get headers
except IOError as e:
print (f"Could not read: {f} check path or if file is open")
return deutdata
#print(timepts)
times =[x for x in timepts.values[0] if str(x) != 'nan']
# print(times)
delays = []
for i,dtime in enumerate(times):
rep = 1
if dtime[0:6] == 'undeut': delay = 0.0
elif dtime[0:2] == 'TD': delay = config.FullDeut_Time #1e6
else:
tp = float(dtime.split(' ')[0].split('.')[0])
tunit = dtime.split(' ')[-1]
#print(tp, tunit)
delay = tp * np.power(60.0,'smh'.find(tunit[0]))
# if Test_Data:
# delay = tp * 60.0 #force to minutes, inconsistent dummy time units across sets
delays += [delay]
rep = Counter(delays)[delay]
# #print(i,time)
if ftype == 'excel':
raw = pd.read_excel(file,skiprows=1,header=None,usecols=[i*2,i*2+1],names=['mz','Intensity']).dropna()
elif ftype == 'csv':
raw = pd.read_csv(file,skiprows=1,header=None,usecols=[i*2,i*2+1],names=['mz','Intensity']).dropna()
raw = raw.sort_values('mz').reset_index()
peaks = peak_picker( raw, peptide, charge, resolution=config.Peak_Resolution,count_sc=0,mod_dict=mod_dict)
peaks['time']=delay
peaks['data_id']=data_id
peaks['sample']=sample
peaks['peptide']=peptide
peaks['charge']=charge
peaks['rep']=rep
peaks['peptide_range']=peptide_range
peaks['start_seq']=start_seq
peaks['end_seq']=end_seq
peaks['file']=dfrow['file']
if keep_raw:
raw['time']=delay
raw['data_id']=data_id
raw['sample']=sample
raw['peptide']=peptide
raw['charge']=charge
raw['rep']=rep
raw['peptide_range']=peptide_range
raw['start_seq']=start_seq
raw['end_seq']=end_seq
raw['file']=dfrow['file']
all_raw = pd.concat([all_raw,raw],ignore_index=True)
dfs = pd.concat([dfs,peaks],ignore_index=True)
deutdata = dfs.copy()
time_points = sorted(set(deutdata.time))
#n_time_points = len(time_points)
deutdata['time_idx'] = [ time_points.index(t) for t in deutdata.time ]
## read in solution file
if config.Test_Data:
file=os.path.join(config.Data_DIR, "bimodal_solutions2.txt")
solution = pd.read_csv(file,delim_whitespace=True,)
solution = solution.sort_values('time').reset_index()
solution['npops'] = solution.apply(pops,axis=1)
all_raw['time_idx'] = [ time_points.index(t) for t in all_raw.time ]
return deutdata, all_raw, solution
elif keep_raw:
all_raw['time_idx'] = [ time_points.index(t) for t in all_raw.time ]
return deutdata, all_raw
else: return deutdata
def read_specexport_data(csv_files,spec_path,row,keep_raw,mod_dict={}):
'''
read the HDExaminer exported data
'''
raw=[]
dfs = []
deutdata = pd.DataFrame()
rawdata = pd.DataFrame()
peaks=[]
for f in csv_files:
fileinfo = f.split('.')[0].split('-')
# print(fileinfo, len(fileinfo))
rep = float(fileinfo[-2])
if fileinfo[0] == 'Non': time = 0.0
elif fileinfo[0] == 'Full': time = config.FullDeut_Time #1e6
else: time = float(fileinfo[0][:-1]) * np.power(60.0,'smh'.find(fileinfo[0][-1]))
raw = pd.read_csv( os.path.join(spec_path,f),delimiter=",",header=None, names=["mz","Intensity"]).dropna()
raw = raw.sort_values('mz').reset_index()
peaks = peak_picker( raw, row['peptide'], row['charge'],resolution=config.Peak_Resolution,mod_dict=mod_dict )
peaks['time']=time
peaks['rep']=rep
peaks['data_id']=row.name
peaks['sample']=row['sample']
peaks['charge']=row['charge']
peaks['peptide']=row['peptide']
peaks['peptide_range']=row['peptide_range']
try: peaks[['start_seq','end_seq']] = peaks['peptide_range'].str.split('-',expand=True).astype('int')
except: pass
peaks['file']=row['file']
if peaks.Intensity.sum() > 0:
dfs.append( peaks )
else: print (" File "+f+" contains no Intensity data at expected m/z values") #peaks['sample']+' '+peaks['peptide']+
if keep_raw:
raw['time']=time
raw['data_id']=row.name
raw['sample']=row['sample']
raw['peptide']=row['peptide']
raw['charge']=row['charge']
raw['rep']=rep
raw['peptide_range']=row['peptide_range']
try: raw[['start_seq','end_seq']] = raw['peptide_range'].str.split('-',expand=True).astype('int')
except: pass
raw['file']=row['file']
rawdata = pd.concat([rawdata,raw],ignore_index=True)
if len(dfs) > 0:
deutdata = pd.concat(dfs, ignore_index=True,)
time_points = sorted(set(deutdata.time))
#n_time_points = len(time_points)
deutdata['time_idx'] = [ time_points.index(t) for t in deutdata.time ]
deutdata['charge'] = row['charge']
if keep_raw:
time_points = sorted(set(rawdata.time))
rawdata['time_idx'] = [ time_points.index(t) for t in rawdata.time ]
return deutdata, rawdata
else: return deutdata
def get_na_isotope(peptide,charge,npeaks=None,mod_dict={}):
'''
Get the Natural Abundance isotopic pattern for a given peptide,charge
If npeaks=None the isotopic_variants routine will vary npeaks depending on composition
e.g. 'YGGFL' will have 7 peaks but 'RDKVQKEYALFYKLD' has 15.
Letting value float depending on peptide length
'''
pepcomp = {}
na_isotope=[]
if goodseq(peptide): comp = mass.Composition(peptide)
else: comp = {}
for key in list(comp):
pepcomp[key] = comp[key]
pepcomp['H'] = pepcomp['H']-count_amides(peptide,count_sc=0.0)
#pepcomp = {'H': 53, 'C': 34, 'O': 15, 'N': 7}
if mod_dict:
pkeys = list(pepcomp.keys())
tkeys = list(mod_dict.keys())
bothkeys = list(set(pkeys) and set(tkeys))
for k in bothkeys:
pepcomp[k] = pepcomp[k] + mod_dict[k]
theoretical_isotopic_cluster = isotopic_variants(pepcomp, npeaks=npeaks, charge=charge)
for ipeak in theoretical_isotopic_cluster:
na_isotope = np.append(na_isotope, ipeak.intensity)
return na_isotope
def count_amides (peptide,count_sc=0.0):
'''
calculate the number of exchanging amides
'''
ex_sc = 0
proline = peptide[config.Nterm_subtract:].count('P')
for sidechain in 'STYCDEHW':
ex_sc += peptide.count(sidechain)
for sidechain in 'R':
ex_sc += 2*peptide.count(sidechain)
for sidechain in 'KQN':
ex_sc += 2*peptide.count(sidechain)
n_amides = len(peptide)-proline-config.Nterm_subtract+int(ex_sc*count_sc)
return n_amides
def peak_picker(data, peptide,charge,resolution=50.0,count_sc=0.0,mod_dict={}):
'''
find the peaks at the expected m/z values (+/- resolution in ppm)
'''
padding = config.Zero_Filling
min_pts = config.Max_Pops*3+2 #minimum number of datapoints necessary for max pop fit
na_buffer = len(get_na_isotope(peptide,charge,mod_dict=mod_dict))//2
n_amides = max(count_amides(peptide,count_sc=0.0),min_pts) + na_buffer + padding #include count from Isotopic Envelope
undeut_mz = mass.calculate_mass(sequence=peptide,show_unmodified_termini=True,charge=charge)
#print("undeut",undeut_mz)
if mod_dict:
undeut_mz += mass.calculate_mass(composition=mod_dict,charge=charge)
#print("undeut_mod",undeut_mz)
#n_deut = np.arange(n_amides+1) #ExMS instead
#pred_mzs = undeut_mz + (n_deut*1.006277)/charge #ExMS instead
# Use ExMS method of expected mz values https://pubs.acs.org/doi/10.1007/s13361-011-0236-3
delta_m = [1.003355, 1.003355, 1.004816, 1.004816, 1.006277] #dmC, dmC, dmHCavg, dmHCavg, dmH ...
dmz = [0.0]
for nd in range(0,n_amides):
dm = delta_m[nd] if nd < 5 else delta_m[-1]
dmz += [dmz[nd] + dm/charge]
pred_mzs = np.array(dmz) + undeut_mz
mz_mid = pred_mzs.mean()
#attempt to set threshold based on user noise value
if config.setNoise:
threshold = config.setNoise
#print("config.SetNoise threshold",threshold)
else:
threshold = config.Y_ERR/100.0 * data.Intensity.max()
#print("config.Y_ERR threshold",threshold)
peaks = []
zeroes = 0
# need to make sure the max_Int is a peak so we don't grab side values from overlapping peaks
for i,pred_mz in enumerate(pred_mzs):
#mass accuracy is in ppm, so default is 50ppm
mz_range = pred_mz * (1.0+np.array([-1,1])*resolution/1e6)
#sort data in range, grab first entry which is the peak
focal_data = data.copy()[data.mz.between(*mz_range)]
focal_data['n_deut'] = i
focal_data = focal_data.sort_values('Intensity',ascending=False)#.reset_index(drop=True)
if (len(focal_data) > 0):
if (focal_data.index[0] not in (focal_data.index.min(),focal_data.index.max())):
max_Int = focal_data['Intensity'].max()
else: max_Int = 0.0
focal_data.reset_index(drop=True)
#testing keeping value as threshold but counting as a zero
# still getting 0 intenist peaks instead of low intensity values
intensity = max_Int
if (intensity < threshold and pred_mz > mz_mid): zeroes += 1
#previous 2 lines instead of following 3
# if max_Int < threshold: intensity = 0.0
# else: intensity = max_Int
# if (intensity == 0.0 and pred_mz > mz_mid): zeroes += 1
else:
intensity = 0.0
if (pred_mz > mz_mid): zeroes += 1
#I don't remember what this next bit was meant to do but it zeroes out some real peaks ><
# if len(pred_mzs) - i < padding + 1:
# intensity = 0.0
# zeroes += 1
peak = pd.DataFrame({'mz':[pred_mz],'Intensity':[intensity],'n_deut':[i]})
peaks.append( peak )
if (zeroes >= padding) and (i >= min_pts):
break #if we have enough zeroes and enough points, we're done peak_picking
#print(n_amides, zeroes, mz_mid)
peaks = pd.concat(peaks,ignore_index=True)
# #clean up right side zero points
# x = peaks['Intensity'].to_numpy()
# cz = 0
# for i in range(min_pts,len(x))[::-1]:
# if x[i] < threshold:
# cz += 1
# else: break
# # print ("zero points:",cz)
# # print ("points to cut:",(cz-padding))
# # print ("last index:",len(new_x)-(cz-padding + 1))
# l_idx = len(x) - (cz - padding + 1)
# peaks = peaks[peaks['n_deut'] <= l_idx]
## adding this section to get X_features at the peakpick step
try:
envelope_height = peaks['Intensity'].max() * config.Env_threshold
env, env_Int = get_mz_env(envelope_height,peaks,pts=True)
y=np.array(peaks.Intensity.copy())
env_symmetry_adj = 2.0 - (y.max() - env_Int)/y.max()
peaks['env_width'] = charge*(env[1]-env[0])
peaks['env_symm'] = env_symmetry_adj
#peaks['skewness'] = skew(y_norm,bias=False)
except:
print("")
peaks['max_namides']=count_amides(peptide,count_sc=0.0)
return peaks #pd.concat(peaks,ignore_index=True)
def get_mz_env(value, df, colname='Intensity',pts=False):
'''
get mz values at value = envelope_height (e.g. 0.1*maxIntensity)
to define the envelope width, for assessment of expected polymodal fits
'''
df = df.copy().reset_index()
boolenv = df[colname].gt(value)
#envpts = boolenv.value_counts()[True] # number of points in envelope
loweridx = df[colname].where(boolenv).first_valid_index()
upperidx = df[colname].where(boolenv).last_valid_index()
if df[colname].iloc[0] > value:
min_mz = df['mz'].iloc[0] #envelope starts with first datapoint
left_Int = df[colname].iloc[0]
else:
x1a = df[colname].iloc[loweridx]
x1b = df[colname].iloc[loweridx-1]
y1a = df['mz'].iloc[loweridx]
y1b = df['mz'].iloc[loweridx-1]
min_mz = y1a + (y1b - y1a) * (value - x1a)/(x1b - x1a)
left_Int = value
if df[colname].iloc[-1] > value:
max_mz = df['mz'].iloc[-1] #envelope goes to end of datapoints, poorly picked masspec?
else:
x2a = df[colname].iloc[upperidx]
x2b = df[colname].iloc[upperidx+1]
y2a = df['mz'].iloc[upperidx]
y2b = df['mz'].iloc[upperidx+1]
max_mz = y2a + (y2b - y2a) * (value - x2a)/(x2b - x2a)
if pts: return np.array([min_mz, max_mz]), left_Int
else: return np.array([min_mz, max_mz])
## Multi-binomial Functions
def nCk_real(n,k):
'''
real (vs integer) version of the NchooseK function
'''
#print("n,k:",n,k)
if n == k: return 1.0
elif n - k + 1 <= 0: return 0.0
#if n - k <= 0: return 0.0
elif n+k > 50: # https://stats.stackexchange.com/questions/72185/how-can-i-prevent-overflow-for-the-gamma-function
log_nCk = lgamma(n+1) - lgamma(k+1) - lgamma(n-k+1)
return exp(log_nCk)
else: return gamma(n+1)/(gamma(k+1)*gamma(n-k+1))
def binom(bins, n, p):
'''
basic (but not simple) binomial function
'''
k = np.arange(bins+1).astype('float64')
nCk = [nCk_real(n,y) for y in k]
with np.errstate(all='ignore'):
# suppress errors: np.power may nan or overflow but we fix it after
# this attempt was unstable near p = 1
# fp1 = np.float_power(p,k)
# fp2 = np.float_power(1-p,n-k) #fits, but np.power overflows
# binoval = nCk*fp1*fp2
# binoval = np.nan_to_num(binoval,nan=0.0)
t_fp1, t_fp2, t_binoval = [], [], []
for ki in k.astype(int):
if nCk[ki] == 0:
t_binoval += [0.0]
t_fp1 += [0.0]
t_fp2 += [0.0]
else:
t_fp1 += [np.power(p,ki)]
fp2_val = np.clip(np.float_power(1-p,n-ki),sys.float_info.min,sys.float_info.max)
t_fp2 += [fp2_val]
t_binoval += [nCk[ki] * t_fp1[ki] * t_fp2[ki]]
binoval = np.array(t_binoval/sum(t_binoval))
binoval = np.nan_to_num(binoval,nan=0.0)
return binoval
def binom_isotope(bins, n,p):
'''
binomial function using the Natural Abundance isotopic envelope
'''
bs = binom(bins,n,p)
newbs=np.zeros(len(bs) + len(Current_Isotope)+1)
for i in range(len(bs)):
for j in range(len(Current_Isotope)):
newbs[i+j] += bs[i]*Current_Isotope[j]
return newbs[0:bins+1]
def n_binomials( bins, *params ): #allfracsversion
'''
basic binomial for n populations
'''
# params takes the form [scaler, n_1, ..., n_n, mu_1, ..., mu_n, frac_1, ..., frac_n]
n_curves = int( (len(params)+1) / 3.0 )
log_scaler = params[0]
n_array=np.array(params[1:n_curves+1])
mu_array = np.array( params[n_curves+1:2*n_curves+1] )
frac_array=[]
frac_array = np.array( params[ -n_curves: ] )
frac_array = frac_array/np.sum(frac_array)
poissons = [ frac * binom( bins,n, mu ) for frac, n, mu in zip( frac_array, n_array, mu_array ) ]
return np.power( 10.0, log_scaler ) * np.sum( poissons, axis=0, )
def n_binom_isotope( bins, *params ): #allfracsversion
'''
n population binomial using the Natural Abundance isotopic envelope
'''
# params takes the form [ scaler, mu_1, ..., mu_n, frac_1, ..., frac_n]
n_curves = int(( len(params) + 1) / 3.0 )
log_scaler = params[0]
n_array = np.array( params[1:n_curves+1] )
mu_array = np.array( params[n_curves+1:2*n_curves+1] )
frac_array = np.array( params[ -n_curves: ] )
frac_array = frac_array/np.sum(frac_array)
poissons = [ frac * binom_isotope( bins, n, mu ) for frac, n, mu in zip( frac_array, n_array, mu_array ) ]
truncated = np.power( 10.0, log_scaler ) * np.sum( poissons, axis=0, )[0:bins+1]
return truncated
def calc_rss( true, pred,yerr_systematic=0.0 ):
'''
calculate the residual squared sum
'''
return np.sum( (pred-true)**2 + yerr_systematic**2 )
def get_params(*fit, sort = False, norm = False, unpack = True):
'''
extract the fit parameters from the fits
'''
# assuming all fracs
# binom eqs of form: scaler, nex * n_curves, mu * n_curves, frac * n_curves
# if sort then reorder nex,mu,frac in order of mu*nexs
# if norm, then fracs will be scaled to sum to 1.0
# need to be mindful of mixing up corresponding errors when sorting and norming
num_curves = int((len(fit)-1)/3)
scaler = fit[0]
nexs = np.array(fit[1:num_curves+1])
mus = np.array(fit[num_curves+1:num_curves*2+1])
fracs = np.array(fit[-num_curves:])
if sort:
mn = nexs*mus
use_index = mn.argsort()
nexs = nexs[use_index]
mus = mus[use_index]#[::-1]]
fracs = fracs[use_index]#[::-1]]
if norm:
sumfracs = np.sum(fracs)
#print("fracs",fracs,sumfracs)
if sumfracs > 0: fracs = fracs/sumfracs
if unpack:
return scaler, nexs, mus, fracs
else:
return np.concatenate((np.array([scaler]),nexs,mus,fracs))
def init_params(n_curves,max_n_amides,seed=None):
'''
generate intial guess parameters for the fits
'''
init_rng = np.random.default_rng(seed=seed)
log_scaler_guess = 0.0
nex_guess = list(max_n_amides/config.Nex_Max_Scale*init_rng.random(n_curves)) #was same for all at max/2 in < ver3.0
nex_low = 0.0
sampled = init_rng.random(n_curves*2) #array for both mus and fracs
mu_guess = list(sampled[0:n_curves]) #[0.9, 0.9, 0.9] #
frac_guess = sampled[-n_curves:]#[0.70, 0.25, 0.05] #allfracs
frac_guess = list(frac_guess/np.sum(frac_guess))
frac_uppers = [1.0]*n_curves
initial_estimate = [ log_scaler_guess ] + nex_guess + mu_guess[0:n_curves] + frac_guess[0:n_curves]
lower_bounds = [ 0.0 ] + [nex_low]* n_curves + [0.0]* n_curves*2
upper_bounds = [ 1.0, ] + [max_n_amides]* n_curves + [ 1.0 ] *n_curves + frac_uppers[0:n_curves]
bounds = ( lower_bounds, upper_bounds, )
#print("intial seed, initial estimate",seed,initial_estimate)
return initial_estimate, bounds
def minimize_func(params, *data):
'''
residual sum squared to be minimized using scipy.optimize.differential_evolution
'''
bins,y = data
result = np.sum( (n_fitfunc(bins,*params)-y)**2 )
return result #**0.5
def fit_bootstrap(p0_boot, bounds, datax, datay, sigma_res=None,yerr_systematic=0.0,nboot=100,
ax=None,yscale=1.0):
'''
perform a bootstrap type routine, nboot independent fits of the data + noise
'''
#p0_boot is a list of all p0 initial parameters with nboot entries
#if ax != None: ax.plot( mz, datay, color = 'cyan', linestyle='solid',label='boot_datay' )
p0 = p0_boot[0]
num_curves = int((len(p0)-1)/3)
if sigma_res==None:
# Fit first time if no residuals
pfit, perr = curve_fit( n_fitfunc, datax, datay, p0, maxfev=int(1e6),
bounds = bounds )
print("Ran initial bootstrap curve_fit to generate residuals")
# Get the stdev of the residuals
residuals = n_fitfunc(datax,*pfit) - datay
sigma_res = np.std(residuals)
sigma_err_total = np.sqrt(sigma_res**2 + yerr_systematic**2)
# nboot random data sets are generated and fitted
ps = []
ps_cov = []
centers = []
boot_residuals = []
for i in range(nboot):
p0 = p0_boot[i]
randomdataY = []
randomDelta = []
randomDelta = rng.normal(0., sigma_err_total, len(datay))
randomDelta = [0 if a==0 else b for a,b in zip(datay,randomDelta)] #don't change y if y=0
randomdataY = datay + randomDelta
#if datapoint is zero, leave as zero and don't let value go negative
randomdataY = np.clip(randomdataY, 0.0, np.array(datay)*2)#np.inf)
#print(randomdataY)
if (len(p0) > len(randomdataY)):
print(f"attempting to fit more parameters than data points in bootstrap")
#should be able to exit at this point, haven't updated last fit parameters including p_err
break # exit the for n_curves loop
try:
#print(len(p0),len(bounds[0]),len(bounds[1]))
randomfit, randomcov = curve_fit( n_fitfunc, datax, randomdataY, p0, maxfev=int(1e6),
bounds = bounds )
except RuntimeError:
break
randomfit[0] = np.power( 10.0, randomfit[0] )
#rfit = randomfit
rfit = get_params(*randomfit,sort=True,norm=True,unpack=False) #randomfit #
ps.append(rfit)
ps_cov.append(randomcov) ## this won't work if ever Sorting
if ax != None: ax.plot( mz, randomdataY*yscale, color = 'orchid', linestyle='dashed', linewidth=2)
# ax.plot( mz, randomdataY, color = 'green', linestyle='dashed', )
tempr = rfit.copy()
tempr[0] = np.log10(rfit[0])
boot_y = n_fitfunc(datax, *tempr)
boot_residual = calc_rss(boot_y , datay)
if ax != None: ax.plot( mz, boot_y*yscale, color = 'darkviolet', linestyle='solid', alpha=0.2 )
s,n,m,f = get_params(*rfit,norm=True,unpack=True) #already did 10**s in rfit
kcenter = [] #get centroids of each population
for k in range( num_curves ):
bfit_yk = s * f[k] * fitfunc( datax, n[k], m[k], ) * yscale
kcenter += [sum(bfit_yk * mz)/sum(bfit_yk)]
#plot_label = ('pop'+str(k+1)+' = '+format(frac,'.2f')+'\nNex'+str(k+1)+' = '+format(nex,'.1f'))
if ax != None: ax.plot( mz, bfit_yk, color = 'green', linestyle='dashed',linewidth=3,alpha=0.2)#label=plot_label)
centers.append(kcenter)
boot_residuals.append(boot_residual/datax) #normalize by number of bins
#print("boot_residuals:",len(boot_residuals),boot_residuals)
ps = np.array(ps)
# mean_pfit = np.mean(ps,axis=0)
# You can choose the confidence interval that you want for your
# parameter estimates:
Nsigma = 1. # 1sigma corresponds to 68.3% confidence interval
# 2sigma corresponds to 95.44% confidence interval
if ps.ndim == 2: ps[:,0] = np.log10(ps[:,0])
# err_pfit = Nsigma * np.std(ps,axis=0)
# mean_pfit[0] = np.log10(mean_pfit[0])
# pfit_bootstrap = mean_pfit
# perr_bootstrap = err_pfit
return ps, boot_residuals, np.array(centers) #return all the bootstrap fits
#return pfit_bootstrap, perr_bootstrap, np.array(centers)
def get_TDenv(datafits,mod_dict={}):
'''
calculate the TD envelope to use as an X_feature in the ML prediction
'''
global Current_Isotope
df = datafits.copy()
test_set = df[['peptide','max_namides']].drop_duplicates()
test_peptides = dict(zip(test_set['peptide'],test_set['max_namides']))
for peptide,namides in test_peptides.items():
charge = 1
Current_Isotope= get_na_isotope(peptide,charge,npeaks=None,mod_dict=mod_dict)
TD_max_spectrum = n_binom_isotope(namides+5,0.0, namides, config.Dfrac, 1.0) #use Dfrac for expected TDenv
TD_spec = pd.DataFrame(zip(np.arange(len(TD_max_spectrum)),TD_max_spectrum),columns=['mz','Intensity'])
[left,right] = get_mz_env(0.1*max(TD_max_spectrum),TD_spec,colname='Intensity')
TD_env_width = (right - left)*charge
peptide_idx = df[(df['peptide'] == peptide)].index
df.loc[peptide_idx,'TD_env_width'] = TD_env_width
return df
def predict_pops(trained_model,datafits):
'''
Predict 1 or more populations based on trained model and X_features
'''
df = datafits.copy()
if 'TD_env_width' not in df.columns:
df = get_TDenv(df)
X_features = ['env_width','env_symm','max_namides','TD_env_width'] #"model4"
Xtest = df[X_features].to_numpy()
Xtest_pred = trained_model.predict(Xtest)
ytest_pred = np.argmax(Xtest_pred,axis=1)
ytest_pred_binary = np.array([min(y,1) for y in ytest_pred])+1
df['pred_pops'] = ytest_pred_binary
return df
## Function to perform the fits on the metadf list of spectra
def run_hdx_fits(metadf,user_deutdata=pd.DataFrame(),user_rawdata=pd.DataFrame(),update_deutdata = False):
'''
Run the whole thing based on the metadf file: read in data, pick peaks, do fits, plot it all
metadf: meta data dataframe with list of all sample/peptide/charge/filename information
user_alldeutdata: optional peak picked data, to limit run (update_deutdata = False)
or to update a subset of deutdata (full set determined from metadf)
user_allrawdata: user specified raw data instead of that found at filename
'''
GP = config.Generate_Plots
global n_fitfunc, fitfunc, mz, Current_Isotope, now, date, deutdata, rawdata, reportdf
global deutdata_all, rawdata_all, solution, data_fits, data_fit, config_df, fitparams_all
def MinimizeStopper(xk=None,convergence=None):
'''
callback function to stop scipy.optimize.differential_evolution function
when the minimize_func value is below a threshold
use with config.DiffEvo_kwargs = {'callback':MinimizeStopper,'polish':True,'maxiter':100}
'''
return minimize_func(xk,*args) < config.DiffEvo_threshold