-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHeuristicProcessor.py
1864 lines (1831 loc) · 114 KB
/
HeuristicProcessor.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
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 8 20:24:43 2023
@author: lacter
"""
import pandas as pd
import time
from progress.bar import Bar
import pyopenms
import math
import numpy as np
import bisect
import re
import os
from scipy.optimize import linear_sum_assignment
import warnings
'''---------'''
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import os
from PyQt5 import QtWidgets,QtCore
import pathos
import multiprocessing as mp
import pickle
class HeuristicProcessorUI(QWidget):
def __init__(self):
super().__init__()
self.initUI()
# 设置标题
self.resize(600,700)
self.centerWindow()
# 设置参数字典
self.Data_params={}
self.Calculate_params={'MS1_Tor':0.000010,'smooth':5,'min_Int':9000,'Points':17}
def CloseEvent(self,event):
os._exit(0)
def initUI(self):
globallayout = QVBoxLayout()
# Data import
Data_import_Widget = QWidget()
Data_import_Layout = QGridLayout()
# Union
self.Label_SampleSelect = QLabel('Select data')
self.Label_RIISSelect = QLabel('Select Calibrants data')
self.Label_HeuristicListSelect = QLabel('Select heuristic list')
self.Label_Params_Select = QLabel('Set params')
self.TextBrowser_SampleSelect = QTableWidget()
self.TextBrowser_SampleSelect.setColumnCount(4)
self.TextBrowser_SampleSelect.setHorizontalHeaderLabels(['Name','Type','Group','Index'])
self.TextBrowser_SampleSelect.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)
self.TextBrowser_SampleSelect.horizontalHeader().setStretchLastSection(True)
self.TextBrowser_RIISSelect = QLabel('*')
self.TextBrowser_HeuristicListSelect = QLabel('*')
self.PushButton_SampleSelect = QPushButton('Select')
self.PushButton_RIISSelect = QPushButton('Select')
self.PushButton_HeuristicListSelect = QPushButton('Select')
self.PushButton_SampleSelect.setToolTip('Select sample *.mzML documents')
self.PushButton_RIISSelect.setToolTip('Select RIIS *.xlsx or *.xls document')
self.PushButton_HeuristicListSelect.setToolTip('Select Heuristic List *.xlsx or *.xls document')
# Slot
self.PushButton_SampleSelect.clicked.connect(self.SelectSampleFile)
self.PushButton_RIISSelect.clicked.connect(self.SelectRIISFile)
self.PushButton_HeuristicListSelect.clicked.connect(self.SelectHeuristicList)
Data_import_Layout.addWidget(self.Label_SampleSelect,1,0)
Data_import_Layout.addWidget(self.TextBrowser_SampleSelect, 2, 0) # row 1, column 0
Data_import_Layout.addWidget(self.PushButton_SampleSelect, 2, 1) # row 1, column 1
Data_import_Layout.addWidget(self.Label_RIISSelect,5,0)
Data_import_Layout.addWidget(self.TextBrowser_RIISSelect, 6, 0)
Data_import_Layout.addWidget(self.PushButton_RIISSelect, 6, 1) # 行,列,行高,列宽
Data_import_Layout.addWidget(self.Label_HeuristicListSelect,7,0)
Data_import_Layout.addWidget(self.TextBrowser_HeuristicListSelect, 8, 0)
Data_import_Layout.addWidget(self.PushButton_HeuristicListSelect, 8, 1) # 行,列,行高,列宽
Data_import_Widget.setLayout(Data_import_Layout)
# Params setting
Params_setting_Widget = QWidget()
Params_setting_Layout = QGridLayout()
# Union
self.Lable_MS_Tor = QLabel('MS1 Tolerance(ppm)')
self.Lable_RT_Tor = QLabel('RT Tolerance(%)')
self.Lable_Int_min = QLabel('Min intensity')
self.Lable_Point = QLabel('Min scan points')
self.Lable_SN = QLabel('Signal/Noise')
self.Lable_SB = QLabel('Signal/Blank')
self.LineEdit_MS_Tor = QLineEdit('10')
self.LineEdit_RT_Tor = QLineEdit('2')
self.LineEdit_Int_min = QLineEdit('9000')
self.LineEdit_Point = QLineEdit('17')
self.LineEdit_SN = QLineEdit('10')
self.LineEdit_SB = QLineEdit('5')
self.LineEdit_MS_Tor.setToolTip('Under this threshold will be recognized as same m/z')
self.LineEdit_RT_Tor.setToolTip('Under this threshold will be recognized as same RT')
self.LineEdit_Int_min.setToolTip('Under this threshold will be deleted')
self.LineEdit_Point.setToolTip('Scan points under this threshold will be deleted')
self.LineEdit_SN.setToolTip('Under this threshold will be deleted')
self.LineEdit_SB.setToolTip('Under this threshold will be deleted')
Params_setting_Layout.addWidget(self.Label_Params_Select,0,0)
#Params_setting_Layout.addWidget(self.Lable_MS_Tor,1,0)
Params_setting_Layout.addWidget(self.Lable_MS_Tor,1,0)
Params_setting_Layout.addWidget(self.LineEdit_MS_Tor,1,1)
Params_setting_Layout.addWidget(self.Lable_RT_Tor,1,2)
Params_setting_Layout.addWidget(self.LineEdit_RT_Tor,1,3)
Params_setting_Layout.addWidget(self.Lable_Int_min,1,4)
Params_setting_Layout.addWidget(self.LineEdit_Int_min,1,5)
Params_setting_Layout.addWidget(self.Lable_Point,2,0)
Params_setting_Layout.addWidget(self.LineEdit_Point,2,1)
Params_setting_Layout.addWidget(self.Lable_SN,2,2)
Params_setting_Layout.addWidget(self.LineEdit_SN,2,3)
Params_setting_Layout.addWidget(self.Lable_SB,2,4)
Params_setting_Layout.addWidget(self.LineEdit_SB,2,5)
Params_setting_Widget.setLayout(Params_setting_Layout)
# Run button
Run_button_Widget = QWidget()
Run_button_Layout = QGridLayout()
# Union
self.PushButton_Run = QPushButton('Run')
self.Label_Run1 = QLabel('')
self.Label_Run2 = QLabel('')
self.Label_Run3 = QLabel('')
Run_button_Layout.addWidget(self.Label_Run1,0,0)
Run_button_Layout.addWidget(self.Label_Run2,0,1)
Run_button_Layout.addWidget(self.Label_Run3,0,2)
Run_button_Layout.addWidget(self.PushButton_Run,0,3)
Run_button_Widget.setLayout(Run_button_Layout)
self.PushButton_Run.clicked.connect(self.Run)
# statusbar
StatusBar_Widget = QWidget()
StatusBar_Layout = QGridLayout()
# Union
self.Label_process = QLabel('Processing bar')
self.Label_process_sub = QLabel('Step')
self.process_bar = QProgressBar()
self.process_bar.setStyleSheet("QProgressBar { border: 2px solid grey; border-radius: 5px; color: rgb(20,20,20); background-color: #FFFFFF; text-align: center;}QProgressBar::chunk {background-color: rgb(100,200,200); border-radius: 10px; margin: 0.1px; width: 1px;}")
font = QFont()
font.setBold(True)
font.setWeight(30)
self.process_bar.setFont(font)
self.process_bar.setMaximum(100)
self.process_bar.setMinimum(0)
self.process_bar.setValue(0)
StatusBar_Layout.addWidget(self.Label_process,0,0)
StatusBar_Layout.addWidget(self.Label_process_sub,1,0)
StatusBar_Layout.addWidget(self.process_bar,1,1)
StatusBar_Widget.setLayout(StatusBar_Layout)
# Global Layout setting
globallayout.addWidget(Data_import_Widget)
globallayout.addWidget(Params_setting_Widget)
globallayout.addWidget(Run_button_Widget)
globallayout.addWidget(StatusBar_Widget)
self.setLayout(globallayout)
self.setWindowTitle('Heuristic Processor')
def centerWindow(self):
screen = QDesktopWidget().screenGeometry()
size = self.geometry()
LeftValue = int((screen.width()-size.width())/2)
TopValue = int((screen.height()-size.height())/2)
self.move(LeftValue,TopValue)
def SelectSampleFile(self):
FileName,FileType = QFileDialog.getOpenFileNames(self,"选取文件",os.getcwd(),"mzML Files(*.mzML)")
for i in FileName:
Combox_Type = QComboBox()
Combox_Type.addItems(['Sample','QC','Blank','MS2'])
Combox_Type.setCurrentText('Sample')
Combox_Type.currentIndexChanged.connect(self.SampleTypeChange)
LineEdit_Index= QLineEdit(str(self.TextBrowser_SampleSelect.rowCount()+1))
LineEdit_Index.textChanged.connect(self.SampleIndexChange)
LineEdit_Group= QLineEdit('1')
LineEdit_Group.textChanged.connect(self.SampleGroupChange)
name_begin = i.rfind('/')
if name_begin == -1:
name_begin = FileName.rfind('\\')
name_end = len(i)
self.Data_params[i[name_begin+1:name_end-5]] = {'Name':i[name_begin+1:name_end-5],'Path':i,'Type':'Sample','Group':1,'Index':str(self.TextBrowser_SampleSelect.rowCount()),'Combox':Combox_Type,'LineEdit_Index':LineEdit_Index,'LineEdit_Group':LineEdit_Group,'rowCount':self.TextBrowser_SampleSelect.rowCount()}
self.TextBrowser_SampleSelect.insertRow(self.TextBrowser_SampleSelect.rowCount())
self.TextBrowser_SampleSelect.setItem(self.TextBrowser_SampleSelect.rowCount()-1,0,QTableWidgetItem(i[name_begin+1:name_end-5]))
self.TextBrowser_SampleSelect.setCellWidget(self.TextBrowser_SampleSelect.rowCount()-1,1,self.Data_params[i[name_begin+1:name_end-5]]['Combox'])
self.TextBrowser_SampleSelect.setCellWidget(self.TextBrowser_SampleSelect.rowCount()-1,2,self.Data_params[i[name_begin+1:name_end-5]]['LineEdit_Group'])
self.TextBrowser_SampleSelect.setCellWidget(self.TextBrowser_SampleSelect.rowCount()-1,3,self.Data_params[i[name_begin+1:name_end-5]]['LineEdit_Index'])
QApplication.processEvents()
def SelectRIISFile(self):
FileName,FileType = QFileDialog.getOpenFileName(self,"选取文件",os.getcwd(),"Excel Files(*.xlsx)")
name_begin = FileName.rfind('/')
if name_begin == -1:
name_begin = FileName.rfind('\\')
name_end = len(FileName)
self.TextBrowser_RIISSelect.setText(FileName[name_begin+1:name_end])
self.RIISPath = FileName
def SelectHeuristicList(self):
FileName,FileType = QFileDialog.getOpenFileName(self,"选取文件",os.getcwd(),"Pickle Files(*.pkl)")
name_begin = FileName.rfind('/')
if name_begin == -1:
name_begin = FileName.rfind('\\')
name_end = len(FileName)
self.TextBrowser_HeuristicListSelect.setText(FileName[name_begin+1:name_end])
self.HeuristicListPath = FileName
def SampleTypeChange(self):
for i in self.Data_params.keys():
if self.sender() == self.Data_params[i]['Combox']:
self.Data_params[i]['Type'] = self.Data_params[i]['Combox'].currentText()
if self.Data_params[i]['Combox'].currentText() == 'QC':
self.Data_params[i]['Group'] = 'QC'
self.Data_params[i]['LineEdit_Group'] = QLineEdit('QC')
self.Data_params[i]['LineEdit_Group'].setReadOnly(True)
self.TextBrowser_SampleSelect.setCellWidget(self.Data_params[i]['rowCount'],2,self.Data_params[i]['LineEdit_Group'])
elif self.Data_params[i]['Combox'].currentText() == 'MS2':
self.Data_params[i]['Group'] = 'MS2'
self.Data_params[i]['LineEdit_Group'] = QLineEdit('MS2')
self.Data_params[i]['LineEdit_Group'].setReadOnly(True)
self.TextBrowser_SampleSelect.setCellWidget(self.Data_params[i]['rowCount'],2,self.Data_params[i]['LineEdit_Group'])
elif self.Data_params[i]['Combox'].currentText() == 'Blank':
self.Data_params[i]['Group'] = 'Blank'
self.Data_params[i]['LineEdit_Group'] = QLineEdit('Blank')
self.Data_params[i]['LineEdit_Group'].setReadOnly(True)
self.TextBrowser_SampleSelect.setCellWidget(self.Data_params[i]['rowCount'],2,self.Data_params[i]['LineEdit_Group'])
else:
self.Data_params[i]['LineEdit_Group'] = QLineEdit('1')
self.TextBrowser_SampleSelect.setCellWidget(self.Data_params[i]['rowCount'],2,self.Data_params[i]['LineEdit_Group'])
QApplication.processEvents()
def SampleIndexChange(self):
for i in self.Data_params.keys():
if self.sender() == self.Data_params[i]['LineEdit_Index']:
self.Data_params[i]['Index'] = self.Data_params[i]['LineEdit_Index'].text()
def SampleGroupChange(self):
for i in self.Data_params.keys():
if self.sender() == self.Data_params[i]['LineEdit_Group']:
self.Data_params[i]['Group'] = self.Data_params[i]['LineEdit_Group'].text()
def processbar_fresh(self,*arg):
self.process_bar.setValue(self.process_bar.value()+1)
QApplication.processEvents()
def Run(self):
self.SampleData = {}
self.BlankData = {}
self.SampleClass = {}
self.MS2_Data = {}
self.QCData = {}
for i in self.Data_params.keys():
if self.Data_params[i]['Type'] == 'Sample':
self.SampleData[i] = self.Data_params[i]
self.SampleClass[i] = self.Data_params[i]['Group']
elif self.Data_params[i]['Type'] == 'MS2':
self.MS2_Data[i] = self.Data_params[i]
elif self.Data_params[i]['Type'] == 'Blank':
self.BlankData[i] = self.Data_params[i]
elif self.Data_params[i]['Type'] == 'QC':
self.QCData[i] = self.Data_params[i]
for i in self.SampleData.keys():
name_begin = self.SampleData[i]['Path'].rfind('/')
if name_begin > 0:
self.filepath_title = self.SampleData[i]['Path'][0:name_begin]+'/'
else:
name_begin = self.SampleData[i]['Path'].rfind('\\')
self.filepath_title = self.SampleData[i]['Path'][0:name_begin]+'\\'
break
ClassList = []
for i in self.SampleClass.keys():
ClassList.append(self.SampleClass[i])
ClassList = list(set(ClassList))
self.Align_path = self.filepath_title+'Alignment-'+str(time.localtime()[1])+str(time.localtime()[2])+str(time.localtime()[3])+str(time.localtime()[4])+'.xlsx'
''' --- Load Sample Data ---'''
self.Label_process_sub.setText('Load Data')
self.process_bar.setMaximum(len(self.SampleData.keys()))
self.process_bar.setValue(0)
pool = mp.Pool(os.cpu_count()-2)
pool_result = {}
for i in self.SampleData.keys():
pool_result[i] = pool.apply_async(EazyMZDataProcess,args=(self.SampleData[i]['Path'],))
pool.close()
pool.join()
for i in self.SampleData.keys():
self.SampleData[i]['Data'] = pool_result[i].get()
for i in self.SampleData.keys():
self.process_bar.setValue(self.process_bar.value()+1)
QApplication.processEvents()
self.SampleData[i]['Data'].set_param('MS1_Tor',float(self.LineEdit_MS_Tor.text())/1000000)
self.SampleData[i]['Data'].set_param('RT_Tor',float(self.LineEdit_RT_Tor.text())/100)
self.SampleData[i]['Data'].set_param('min_Int',int(self.LineEdit_Int_min.text()))
self.SampleData[i]['Data'].set_param('Points',int(self.LineEdit_Point.text()))
self.SampleData[i]['Data'].set_RIIS(self.RIISPath)
self.Label_process_sub.setText('Load QC Data')
''' --- Load QC Data ---'''
pool = mp.Pool(os.cpu_count()-2)
pool_result = {}
for i in self.QCData.keys():
pool_result[i] = pool.apply_async(EazyMZDataProcess,args=(self.QCData[i]['Path'],))
pool.close()
pool.join()
for i in self.QCData.keys():
self.QCData[i]['Data'] = pool_result[i].get()
for i in self.QCData.keys():
self.process_bar.setValue(self.process_bar.value()+1)
QApplication.processEvents()
self.QCData[i]['Data'].set_param('MS1_Tor',float(self.LineEdit_MS_Tor.text())/1000000)
self.QCData[i]['Data'].set_param('RT_Tor',float(self.LineEdit_RT_Tor.text())/100)
self.QCData[i]['Data'].set_param('min_Int',int(self.LineEdit_Int_min.text()))
self.QCData[i]['Data'].set_param('Points',int(self.LineEdit_Point.text()))
self.QCData[i]['Data'].set_RIIS(self.RIISPath)
temp_key = list(self.SampleData.keys())[0]
self.Polarity = self.SampleData[temp_key]['Data'].get_param('Polarity')
''' --- Load Blank Data ---'''
self.Label_process_sub.setText('Load Blank Data')
self.process_bar.setMaximum(len(self.BlankData.keys()))
self.process_bar.setValue(0)
for i in self.BlankData.keys():
self.process_bar.setValue(self.process_bar.value()+1)
QApplication.processEvents()
self.BlankData[i]['Data'] = EazyMZDataProcess(self.BlankData[i]['Path'])
self.BlankData[i]['Data'].set_RIIS(self.RIISPath)
self.BlankData[i]['Data'].set_param('MS1_Tor',float(self.LineEdit_MS_Tor.text())/1000000)
self.BlankData[i]['Data'].set_param('RT_Tor',float(self.LineEdit_Point.text())/100)
''' --- Load MS2 Data ---'''
self.Label_process_sub.setText('Load MS2 Data')
self.process_bar.setMaximum(len(self.MS2_Data.keys()))
self.process_bar.setValue(0)
for i in self.MS2_Data.keys():
self.process_bar.setValue(self.process_bar.value()+1)
QApplication.processEvents()
self.MS2_Data[i]['Data'] = EazyMZDataProcess(self.MS2_Data[i]['Path'])
self.MS2_Data[i]['Data'].set_RIIS(self.RIISPath)
self.MS2_Data[i]['Data'].set_param('MS1_Tor',float(self.LineEdit_MS_Tor.text())/1000000)
self.MS2_Data[i]['Data'].set_param('RT_Tor',float(self.LineEdit_Point.text())/100)
''' --- Heuristic List ---'''
self.Label_process_sub.setText('Set Heuristic List')
MS_Tor = float(self.LineEdit_MS_Tor.text())/1000000
with open(self.HeuristicListPath,'rb') as f:
Alltemp_HPL = pickle.load(f)
temp_Heuristic_peak_list = []
for ii in range(len(Alltemp_HPL)):
if len(temp_Heuristic_peak_list) == 0:
temp_Heuristic_peak_list = Alltemp_HPL.iloc[[0],:].copy()
temp_Heuristic_peak_list['PeakNumber'] = 1
else:
MZ = Alltemp_HPL.at[ii,'AverageMZ']
RI_left = Alltemp_HPL.at[ii,'RI_left']
RI_right = Alltemp_HPL.at[ii,'RI_right']
RI = Alltemp_HPL.at[ii,'RI']
same_list = list(filter(lambda x:EazyMZDataProcess.ppm_compare(MZ,temp_Heuristic_peak_list.at[x,'AverageMZ'])<MS_Tor and
((RI_left<=temp_Heuristic_peak_list.at[x,'RI_right'] and RI_right>=temp_Heuristic_peak_list.at[x,'RI_right']) or
(RI_left<=temp_Heuristic_peak_list.at[x,'RI_left'] and RI_right>=temp_Heuristic_peak_list.at[x,'RI_left'])),range(len(temp_Heuristic_peak_list))))
contain_list = list(filter(lambda x:EazyMZDataProcess.ppm_compare(MZ,temp_Heuristic_peak_list.at[x,'AverageMZ'])<MS_Tor and (RI_left>=temp_Heuristic_peak_list.at[x,'RI_left'] and RI_right<=temp_Heuristic_peak_list.at[x,'RI_right']),range(len(temp_Heuristic_peak_list))))
if len(same_list) == 0 :
if len(contain_list) == 0:
iii = Alltemp_HPL.iloc[[ii],:].copy()
iii['PeakNumber'] = 1
temp_Heuristic_peak_list = pd.concat([temp_Heuristic_peak_list,iii])
temp_Heuristic_peak_list.reset_index(drop=True,inplace=True)
temp_Heuristic_peak_list.loc[len(temp_Heuristic_peak_list)-1,'RI_List'] = [RI]
elif len(contain_list) == 1:
temp_Heuristic_peak_list.loc[contain_list[0],'PeakNumber'] = temp_Heuristic_peak_list.loc[contain_list[0],'PeakNumber']+1
temp_Heuristic_peak_list.loc[contain_list[0],'MZ_List'].append(MZ)
temp_Heuristic_peak_list.loc[contain_list[0],'RI_List'].append(RI)
temp_Heuristic_peak_list.loc[contain_list[0],'AverageMZ'] = np.mean(temp_Heuristic_peak_list.loc[contain_list[0],'MZ_List'])
elif len(same_list) == 1 :
if RI_left<temp_Heuristic_peak_list.at[same_list[0],'RI_left']:
temp_Heuristic_peak_list.loc[same_list[0],'RI_left'] = RI_left
if RI_right>temp_Heuristic_peak_list.at[same_list[0],'RI_right']:
temp_Heuristic_peak_list.loc[same_list[0],'RI_right'] = RI_right
temp_Heuristic_peak_list.loc[same_list[0],'MZ_List'].append(MZ)
temp_Heuristic_peak_list.loc[same_list[0],'RI_List'].append(RI)
temp_Heuristic_peak_list.loc[same_list[0],'AverageMZ'] = np.mean(temp_Heuristic_peak_list.loc[same_list[0],'MZ_List'])
temp_Heuristic_peak_list.loc[same_list[0],'PeakNumber'] = temp_Heuristic_peak_list.loc[same_list[0],'PeakNumber']+1
elif len(same_list) == 2 :
iii = Alltemp_HPL.iloc[[ii],:].copy()
iii['PeakNumber'] = temp_Heuristic_peak_list.loc[same_list[0],'PeakNumber'] + temp_Heuristic_peak_list.loc[same_list[1],'PeakNumber'] + 1
iii.loc[ii,'RI_right'] = max([RI_right,temp_Heuristic_peak_list.loc[same_list[0],'RI_right'],temp_Heuristic_peak_list.loc[same_list[1],'RI_right']])
iii.loc[ii,'RI_left'] = min([RI_left,temp_Heuristic_peak_list.loc[same_list[0],'RI_left'],temp_Heuristic_peak_list.loc[same_list[1],'RI_left']])
iii['MZ_List'] = iii['MZ_List'].astype('object')
iii.at[ii,'MZ_List'] = list(temp_Heuristic_peak_list.loc[same_list[0],'MZ_List'] + temp_Heuristic_peak_list.loc[same_list[1],'MZ_List'] + iii.loc[ii,'MZ_List'])
iii['RI_List'] = iii['RI_List'].astype('object')
iii.at[ii,'RI_List'] = list(temp_Heuristic_peak_list.loc[same_list[0],'RI_List'] + temp_Heuristic_peak_list.loc[same_list[1],'RI_List'] + [iii.loc[ii,'RI']])
iii.loc[ii,'AverageMZ'] = float(np.mean(iii.loc[ii,'MZ_List']))
temp_Heuristic_peak_list.drop(same_list,inplace=True)
temp_Heuristic_peak_list = pd.concat([temp_Heuristic_peak_list,iii])
temp_Heuristic_peak_list.reset_index(drop=True,inplace=True)
self.HeuristicList = temp_Heuristic_peak_list.copy()
''' --- Peak Picking Sample ---'''
for i in self.SampleData.keys():
self.SampleData[i]['Data'].Heuristic_peak_list = self.HeuristicList.copy()
self.Label_process_sub.setText('Heuristic detect')
pool = mp.Pool(os.cpu_count()-2)
pool_result = {}
self.process_bar.setMaximum(len(self.SampleData.keys()))
self.process_bar.setValue(0)
QApplication.processEvents()
for i in self.SampleData.keys():
print('Load Data '+str(i))
pool_result[i]=pool.apply_async(self.SampleData[i]['Data'].Heuristic_PeakDetect,callback=self.processbar_fresh)
pool.close()
pool.join()
for i in self.SampleData.keys():
self.SampleData[i]['Data'].Final_Peak_Detect = pool_result[i].get()[0].copy()
self.SampleData[i]['Data'].Heuristic_peak_list = pool_result[i].get()[1].copy()
self.Label_process.setText('Calculate RI & SN')
for i in self.SampleData.keys():
self.SampleData[i]['Data'].Calculate_RI()
self.SampleData[i]['Data'].Calculate_SN(drop=True,Threshold=int(self.LineEdit_SN.text()))
for i in self.SampleData.keys():
self.SampleData[i]['Data'].OutputSinglePeakListPath = self.SampleData[i]['Path'][0:len(self.SampleData[i]['Path'])-5]+'-'+str(time.localtime()[1])+str(time.localtime()[2])+str(time.localtime()[3])+str(time.localtime()[4])+'.xlsx'
pool = mp.Pool(os.cpu_count()-2)
for i in self.SampleData.keys():
#pool.apply_async(self.SampleData[i]['Data'].Final_Peak_Detect.to_excel,(self.SampleData[i]['Path'][0:len(self.SampleData[i]['Path'])-5]+'-'+str(time.localtime()[1])+str(time.localtime()[2])+str(time.localtime()[3])+str(time.localtime()[4])+'.xlsx',))
pool.apply_async(self.SampleData[i]['Data'].OutputSinglePeakList,)
pool.close()
pool.join()
''' --- Peak Picking QC ---'''
self.Label_process_sub.setText('QC Data Heuristic detect')
for i in self.QCData.keys():
self.QCData[i]['Data'].Heuristic_peak_list = self.HeuristicList.copy()
pool = mp.Pool(os.cpu_count()-2)
pool_result = {}
self.process_bar.setMaximum(len(self.QCData.keys()))
self.process_bar.setValue(0)
QApplication.processEvents()
for i in self.QCData.keys():
pool_result[i]=pool.apply_async(self.QCData[i]['Data'].Heuristic_PeakDetect,callback=self.processbar_fresh)
pool.close()
pool.join()
for i in self.QCData.keys():
self.QCData[i]['Data'].Final_Peak_Detect = pool_result[i].get()[0].copy()
self.QCData[i]['Data'].Heuristic_peak_list = pool_result[i].get()[1].copy()
''' --- Alignment ---'''
self.Label_process.setText('Data Alignment')
self.Align = DataAlignment(self.Label_process,self.process_bar)
for i in self.SampleData.keys():
self.Align.add_Data(self.SampleData[i]['Data'],Tag='Sample')
for i in self.QCData.keys():
self.Align.add_Data(self.QCData[i]['Data'],Tag='QC')
for i in self.BlankData.keys():
self.Align.add_Data(self.BlankData[i]['Data'],Tag='Blank')
self.Align.set_param('RI_Alignment',True)
self.Align.set_param('MZ_Tor',float(self.LineEdit_MS_Tor.text())/1000000)
self.Align.set_param('RT_Tor',float(self.LineEdit_Point.text())/100)
self.Align.RenewRefList()
''' MS2 assine'''
for i in self.MS2_Data.keys():
V_List_Num = list(self.MS2_Data[i]['Data'].MS2_Data['Pre_MZ'][int(len(self.MS2_Data[i]['Data'].MS2_Data['Pre_MZ'])/2):int(len(self.MS2_Data[i]['Data'].MS2_Data['Pre_MZ'])/2)+50])
V_List_Count = []
Count = 1
for ii in range(1,len(V_List_Num)):
if abs(V_List_Num[ii-1]-V_List_Num[ii])/V_List_Num[ii] <= float(self.LineEdit_MS_Tor.text())/1000000:
Count = Count + 1
else:
V_List_Count.append(Count)
Count = 1
V_List_Count = pd.Series(V_List_Count[2:len(V_List_Count)-2])
V_List = []
for ii in range(V_List_Count.mode()[0]):
V_List.append('CE'+str(ii+1))
break
for i in self.MS2_Data.keys():
self.MS2_Data[i]['Data'].MS2_Data['CE'] = V_List[0]
for ii in range(1,len(self.MS2_Data[i]['Data'].MS2_Data)):
if self.MS2_Data[i]['Data'].MS2_Data['Pre_MZ'][ii] == self.MS2_Data[i]['Data'].MS2_Data['Pre_MZ'][ii-1]:
V_Place = list(filter(lambda x:V_List[x]==self.MS2_Data[i]['Data'].MS2_Data['CE'][ii-1],range(len(V_List))))[0]
if V_Place == len(V_List)-1:
self.MS2_Data[i]['Data'].MS2_Data['CE'][ii] = V_List[0]
else:
self.MS2_Data[i]['Data'].MS2_Data['CE'][ii] = V_List[V_Place+1]
else:
self.MS2_Data[i]['Data'].MS2_Data['CE'][ii] = V_List[0]
self.Align.RefList['MS2_MZ'] = self.Align.RefList['MS2_MZ'].astype('object')
self.Align.RefList['MS2_Int'] = self.Align.RefList['MS2_Int'].astype('object')
self.Label_process.setText('MS2 Data Processing')
self.Label_process_sub.setText('MS2 assign')
self.process_bar.setMaximum(len(self.Align.RefList))
self.process_bar.setValue(0)
QApplication.processEvents()
self.MergeMS2 = []
for i in self.MS2_Data.keys():
self.MS2_Data[i]['Data'].Calculate_MS2_RI()
if len(self.MergeMS2) == 0:
self.MergeMS2 = self.MS2_Data[i]['Data'].MS2_Data.copy()
else:
self.MergeMS2 = pd.concat([self.MergeMS2,self.MS2_Data[i]['Data'].MS2_Data])
if len(self.MergeMS2)>0:
self.MergeMS2.reset_index(drop=True,inplace=True)
temp_MZ_Tor = self.Align.AlignmentParam['MZ_Tor']
for i in range(len(self.Align.RefList)):
self.process_bar.setValue(self.process_bar.value()+1)
QApplication.processEvents()
Valified_List = list(filter(lambda x:abs(self.Align.RefList.at[i,'m/z']-self.MergeMS2.at[x,'Pre_MZ'])/self.Align.RefList.at[i,'m/z']<temp_MZ_Tor and self.Align.RefList.at[i,'RI']*(1-float(self.LineEdit_RT_Tor.text())/100)<self.MergeMS2.at[x,'Scan_RI']<self.Align.RefList.at[i,'RI']*((1+float(self.LineEdit_RT_Tor.text())/100)),range(len(self.MergeMS2))))
if len(Valified_List) >0:
Valified_Index = Valified_List[np.where(abs(np.array(self.MergeMS2.loc[Valified_List,'Scan_RI'])-self.Align.RefList.at[i,'RI'])==min(abs(np.array(self.MergeMS2.loc[Valified_List,'Scan_RI'])-self.Align.RefList.at[i,'RI'])))[0][0]]
CE_Index = list(filter(lambda x:V_List[x]==self.MergeMS2.at[Valified_Index+3,'CE'],range(len(V_List))))[0]
if Valified_Index-CE_Index > 0 and Valified_Index+len(V_List)-CE_Index < len(self.MergeMS2):
Valified_Index_List = list(range(Valified_Index-CE_Index,Valified_Index+len(V_List)-CE_Index))
elif Valified_Index-CE_Index < 0:
Valified_Index_List = list(range(0,Valified_Index+len(V_List)-CE_Index))
elif Valified_Index+len(V_List)-CE_Index > len(self.MergeMS2):
Valified_Index_List = list(range(Valified_Index-CE_Index,len(self.MergeMS2)))
MZ_List = []
Int_List = []
for ii in Valified_Index_List:
if abs(self.MergeMS2.at[ii,'Pre_MZ'] - self.Align.RefList.at[i,'m/z']) / self.Align.RefList.at[i,'m/z']<temp_MZ_Tor:
if len(MZ_List) == 0:
MZ_List = self.MergeMS2.at[i,'MZ_List']
Int_List = self.MergeMS2.at[i,'Int_List']
else:
for iii in range(len(self.MergeMS2.at[i,'MZ_List'])):
MS2_Merge_Index = list(filter(lambda x:abs(MZ_List[x]-self.MergeMS2.at[i,'MZ_List'][iii])/MZ_List[x]<temp_MZ_Tor,range(len(MZ_List))))
if len(MS2_Merge_Index) == 0:
MZ_List.append(self.MergeMS2.at[i,'MZ_List'][iii])
Int_List.append(self.MergeMS2.at[i,'Int_List'][iii])
elif Int_List[MS2_Merge_Index[0]] < self.MergeMS2.at[i,'Int_List'][iii]:
MZ_List[MS2_Merge_Index[0]] = self.MergeMS2.at[i,'MZ_List'][iii]
Int_List[MS2_Merge_Index[0]] = self.MergeMS2.at[i,'Int_List'][iii]
temp_range = pd.DataFrame({'MZ_List':MZ_List,'Int_List':Int_List})
temp_range.sort_values(by='MZ_List',inplace=True)
temp_range.reset_index(drop=True,inplace=True)
MZ_List = list(temp_range['MZ_List'])
Int_List = list(temp_range['Int_List'])
self.Align.RefList.at[i,'MS2_MZ'] = MZ_List.copy()
self.Align.RefList.at[i,'MS2_Int'] = Int_List.copy()
''' Filter '''
for i in ClassList:
self.Align.RefList['Fill Group '+str(i)] = 0
for ii in range(len(self.Align.RefList)):
Number_Class = 0
for iii in self.SampleClass.keys():
if self.SampleClass[iii] == i:
Number_Class += 1
if self.Align.RefList[iii][ii] >0:
self.Align.RefList['Fill Group '+str(i)][ii] += 1
self.Align.RefList['Fill Group '+str(i)][ii] = self.Align.RefList['Fill Group '+str(i)][ii]/Number_Class
#self.Align.RefList.to_excel(self.filepath_title+'Alignment-Origin-'+str(time.localtime()[1])+str(time.localtime()[2])+str(time.localtime()[3])+str(time.localtime()[4])+'.xlsx',index=False)
self.Align.BlankFilter()
''' --- Output ---'''
self.Align.RefList.insert(0,'ID',[0]*len(self.Align.RefList))
self.Align.RefList.sort_values(by='m/z',ascending=True,inplace=True)
self.Align.RefList.reset_index(drop=True,inplace=True)
for ID_i in range(len(self.Align.RefList)):
self.Align.RefList['ID'][ID_i] = ID_i+1
self.Align.RefList['m/z'][ID_i] = np.around(self.Align.RefList['m/z'][ID_i],5)
self.Align.RefList['RI'][ID_i] = np.around(self.Align.RefList['RI'][ID_i],1)
self.Align.RefList['RT'][ID_i] = np.around(self.Align.RefList['RT'][ID_i],2)
self.Align.RefList.rename(columns={'m/z':'Average m/z'},inplace=True)
mgf_output = ''
csv_mgf = pd.DataFrame(columns=['row ID','row m/z','row retention time','Peak height'])
for i in range(len(self.Align.RefList)):
if type(self.Align.RefList['MS2_MZ'][i]) == list:
MZ = np.around(self.Align.RefList['Average m/z'][i],5)
RT = np.around(self.Align.RefList['RT'][i]/60,2)
Int = self.Align.RefList['Int'][i]
temp_csv_mgf = pd.DataFrame([(i+1,MZ,RT,Int)],columns=['row ID','row m/z','row retention time','Peak height'])
csv_mgf = pd.concat([csv_mgf,temp_csv_mgf])
if self.Polarity == 'Positive':
mgf_output = mgf_output+'BEGIN IONS\nFEATURE_ID='+str(i+1)+'\nPEPMASS='+str(MZ)+'\nRTINSECONDS='+str(np.around(RT*60,3))+'\nCHARGE=1+\nMSLEVEL=2\n'
elif self.Polarity == 'Negative':
mgf_output = mgf_output+'BEGIN IONS\nFEATURE_ID='+str(i+1)+'\nPEPMASS='+str(MZ)+'\nRTINSECONDS='+str(np.around(RT*60,3))+'\nCHARGE=1-\nMSLEVEL=2\n'
for ii in range(len(self.Align.RefList['MS2_MZ'][i])):
mgf_output = mgf_output+str(np.around(self.Align.RefList['MS2_MZ'][i][ii],5))+' '+str(np.around(self.Align.RefList['MS2_Int'][i][ii],3))+'\n'
mgf_output = mgf_output+'END IONS\n\n'
if len(mgf_output)>0:
with open(self.filepath_title+'tandemMS-'+str(time.localtime()[1])+str(time.localtime()[2])+str(time.localtime()[3])+str(time.localtime()[4])+'.mgf','w')as mgfFile:
mgfFile.write(mgf_output)
csv_mgf.to_csv(self.filepath_title+'tandemMS-'+str(time.localtime()[1])+str(time.localtime()[2])+str(time.localtime()[3])+str(time.localtime()[4])+'.csv',index=False)
self.Align.RefList.rename(columns={'Int':'Average Intensity'},inplace=True)
self.Align.RefList.rename(columns={'RT':'Average RT(s)'},inplace=True)
self.Align.RefList.rename(columns={'RI':'Average RI'},inplace=True)
self.Align.RefList.rename(columns={'MS_List':'m/z value in each sample'},inplace=True)
self.Align.RefList.rename(columns={'RT_List':'RI value in each sample'},inplace=True)
self.Align.RefList.rename(columns={'MS2_Int':'Intensity values of product ions'},inplace=True)
self.Align.RefList.rename(columns={'MS2_MZ':'m/z values of product ions'},inplace=True)
self.Align.RefList.rename(columns={'SimilarityScore':'Average Similarity Score'},inplace=True)
self.Align.RefList.rename(columns={'SC_List':'Similarity Score in each sample'},inplace=True)
self.Align.RefList.rename(columns={'max_SampleInt':'Max sample intensity'},inplace=True)
self.Align.RefList.rename(columns={'mean_BlankInt':'Average blank intensity'},inplace=True)
self.Align.RefList.to_excel(self.filepath_title+'Alignment-'+str(time.localtime()[1])+str(time.localtime()[2])+str(time.localtime()[3])+str(time.localtime()[4])+'.xlsx',index=False)
self.Label_process_sub.setText('Finished')
self.process_bar.setMaximum(100)
self.process_bar.setValue(100)
class ProgressBar(QDialog):
def __init__(self,parent=None):
super(ProgressBar,self).__init__(parent)
self.resize(500,32)
self.progressBar = QProgressBar(self)
self.progressBar.setMaximum(500)
self.progressBar.setMinimum(0)
self.progressBar.setValue(0)
self.centerWindow()
self.show()
def setValue(self,task_Number,total_task_Number,value):
if total_task_Number == 1:
self.setWindowTitle('Processing')
else:
self.setWindowTitle('Processing '+str(task_Number)+'/'+str(total_task_Number))
self.progressBar.setValue(value)
def centerWindow(self):
screen = QDesktopWidget().screenGeometry()
size = self.geometry()
LeftValue = int((screen.width()-size.width())/2)
TopValue = int((screen.height()-size.height())/2)
self.move(LeftValue,TopValue)
class EazyMZDataProcess(object):
def __init__(self,DataPath):
if DataPath.rfind('/') != -1 :
self.DataName = DataPath[DataPath.rfind('/')+1:len(DataPath)-5]
else:
self.DataName = DataPath[DataPath.rfind('\\')+1:len(DataPath)-5]
self.OriginData = pyopenms.MSExperiment()
self.file_path = DataPath
''' 储存文件pyopenms.MzMLFile().store("filtered.mzML", exp) '''
if self.file_path.endswith('mzML'):
pyopenms.MzMLFile().load(self.file_path,self.OriginData)
elif self.file_path.endswith('mzXML'):
pyopenms.MzXMLFile().load(self.file_path,self.OriginData)
self.OriginData.sortSpectra(True)
self.__param = {'MS1_Tor':0.000010,'RT_Tor':2,'min_Int':10000,'min_RT':6,'max_Noise':2000,
'Deconvolution':False,'FeatureDetectPlot':3,'MergeRule':'Intersection',
'UpDown_gap':10,'saveAutoList':False,'smooth':5,'Points':25}
self.Origin_RT_List = np.array([])
self.Origin_MZ_List = []
self.Origin_Int_List = []
self.MS2_Pre = []
self.MS2_RT_List = []
self.MS2_MZ_List = []
self.MS2_Int_List = []
self.MS2_RelInt=[]
for i in self.OriginData:
if i.getMSLevel()==1:
MZ_temp, Int_temp = i.get_peaks()
self.Origin_MZ_List.append(np.around(MZ_temp,5))
self.Origin_Int_List.append(np.around(Int_temp,0))
self.Origin_RT_List = np.append(self.Origin_RT_List,i.getRT())
if i.getMSLevel()==2:
Pre_temp = i.getPrecursors()[0].getMZ()
MZ_temp,Int_temp=i.get_peaks()
temp_range = list(filter(lambda x:MZ_temp[x]<=Pre_temp,range(len(MZ_temp)))) # and Int_temp[x]>1000
temp_range = list(filter(lambda x:len(np.where(abs(MZ_temp[temp_range]-MZ_temp[x])/MZ_temp[x]<self.__param['MS1_Tor']))==1 or
Int_temp[x]==max(Int_temp[np.where(abs(MZ_temp[temp_range]-MZ_temp[x])/MZ_temp[x]<self.__param['MS1_Tor'])]),temp_range))
if len(temp_range)>0:
MZ_temp = MZ_temp[temp_range]
Int_temp = Int_temp[temp_range]
self.MS2_Pre.append(Pre_temp)
self.MS2_RT_List.append(i.getRT())
self.MS2_MZ_List.append(np.around(MZ_temp,5))
self.MS2_Int_List.append(np.around(Int_temp,0))
self.MS2_RelInt.append(max(Int_temp[temp_range]))
else:
MZ_temp = []
Int_temp = []
self.MS2_Pre.append(Pre_temp)
self.MS2_RT_List.append(i.getRT())
self.MS2_MZ_List.append(np.around(MZ_temp,5))
self.MS2_Int_List.append(np.around(Int_temp,0))
self.MS2_RelInt.append(0)
self.Origin_RT_List = np.around(self.Origin_RT_List,3)
self.MS2_RT_List = np.around(self.MS2_RT_List,3)
self.MS1_Data = {'Scan_Time':self.Origin_RT_List,'MZ_List':self.Origin_MZ_List,'Int_List':self.Origin_Int_List}
self.MS1_Data = pd.DataFrame(self.MS1_Data)
self.MS2_Data = {'Scan_Time':self.MS2_RT_List,'Pre_MZ':self.MS2_Pre,'MZ_List':self.MS2_MZ_List,'Int_List':self.MS2_Int_List,'Rel_Int':self.MS2_RelInt}
self.MS2_Data = pd.DataFrame(self.MS2_Data)
self.__param['Flow_RT'] = int(self.__param['min_RT']/(4*sum(np.diff(self.Origin_RT_List))/len(np.diff(self.Origin_RT_List))))+1
if self.OriginData[0].getInstrumentSettings().getPolarity() == 1:
self.__param['Polarity'] = 'Positive'
elif self.OriginData[0].getInstrumentSettings().getPolarity() == 2:
self.__param['Polarity'] = 'Negative'
else:
self.__param['Polarity'] = 'Not give'
print('Uncertain Polarity')
self.OriginData = []
def add_0(x):
x.append(0)
return x
def add_Blank(self,DataPath):
self.BlankData = pyopenms.MSExperiment()
if DataPath.endswith('mzML'):
pyopenms.MzMLFile().load(DataPath,self.BlankData)
elif DataPath.endswith('mzXML'):
pyopenms.MzXMLFile().load(DataPath,self.BlankData)
self.BlankData.sortSpectra(True)
self.Blank_RT_List = np.array([])
self.Blank_MZ_List = []
self.Blank_Int_List = []
for i in self.BlankData:
if i.getMSLevel()==1:
MZ_temp, Int_temp = i.get_peaks()
self.Blank_MZ_List.append(np.around(MZ_temp,5))
self.Blank_Int_List.append(np.around(Int_temp,0))
self.Blank_RT_List = np.append(self.Blank_RT_List,i.getRT())
self.Blank_RT_List = np.around(self.Blank_RT_List,3)
def add_RT(x, RT):
x.append(RT)
return x
def add_param(self,name,value):
self.__param[name]=value
print('set',name,' = ',value)
def add_Heuristic_peak_list(self,path):
Heuristic_peak_list = pd.read_excel(path)
Heuristic_peak_list['RI_left'] = Heuristic_peak_list['RI'].apply(lambda x:x*0.98)
Heuristic_peak_list['RI_right'] = Heuristic_peak_list['RI'].apply(lambda x:x*1.02)
Heuristic_peak_list['MZ_List'] = Heuristic_peak_list['AverageMZ'].apply(lambda x:[x])
Heuristic_peak_list['RI_List'] = Heuristic_peak_list['RI'].apply(lambda x:[x])
Alltemp_HPL=pd.DataFrame(columns=['AverageMZ','RT','MZ_List','RT_List'])
Alltemp_HPL['AverageMZ'] = Alltemp_HPL['AverageMZ'].map(lambda x:'%.4f'%x)
sub_HPL_dict = {}
for i in list(set(Heuristic_peak_list['Gradient Code'])):
sub_Heuristic_peak_list = Heuristic_peak_list[Heuristic_peak_list['Gradient Code']==i].copy()
sub_Heuristic_peak_list.reset_index(drop=True,inplace=True)
sub_HPL_dict[i] = sub_Heuristic_peak_list.copy()
for i in sub_HPL_dict.keys():
sub_HPL_dict[i].sort_values('AverageMZ',ascending=(False),inplace=True)
sub_HPL_dict[i].reset_index(drop=True,inplace=True)
Alltemp_HPL.sort_values('AverageMZ',ascending=(False),inplace=True)
Alltemp_HPL.reset_index(drop=True,inplace=True)
temp_Data = sub_HPL_dict[i].copy()
init_RefMZ = pd.DataFrame(columns=['AverageMZ','MZList','RowIndex'])
init_SampleMZ = pd.DataFrame(columns=['AverageMZ','MZList','RowIndex'])
Sample_Time = temp_Data.loc[:,'RI']
for ii in range(len(Alltemp_HPL)):
if len(init_RefMZ)==0:
init_RefMZ.loc[len(init_RefMZ)] = [Alltemp_HPL.at[ii,'AverageMZ'],[Alltemp_HPL.at[ii,'AverageMZ']],[ii]]
else:
if abs(init_RefMZ.at[len(init_RefMZ)-1,'AverageMZ']-Alltemp_HPL.at[ii,'AverageMZ'])/Alltemp_HPL.at[ii,'AverageMZ']<self.__param['MS1_Tor']:
init_RefMZ.at[len(init_RefMZ)-1,'MZList'].append(Alltemp_HPL.at[ii,'AverageMZ'])
init_RefMZ.at[len(init_RefMZ)-1,'RowIndex'].append(ii)
init_RefMZ.at[len(init_RefMZ)-1,'AverageMZ']=np.mean(init_RefMZ.at[len(init_RefMZ)-1,'MZList'])
else:
init_RefMZ.loc[len(init_RefMZ)] = [Alltemp_HPL.at[ii,'AverageMZ'],[Alltemp_HPL.at[ii,'AverageMZ']],[ii]]
for ii in range(len(temp_Data)):
if len(init_SampleMZ)==0:
init_SampleMZ.loc[len(init_SampleMZ)] = [temp_Data.at[ii,'AverageMZ'],[temp_Data.at[ii,'AverageMZ']],[ii]]
else:
if abs(init_SampleMZ.at[len(init_SampleMZ)-1,'AverageMZ']-temp_Data.at[ii,'AverageMZ'])/temp_Data.at[ii,'AverageMZ']<self.__param['MS1_Tor']:
init_SampleMZ.at[len(init_SampleMZ)-1,'MZList'].append(temp_Data.at[ii,'AverageMZ'])
init_SampleMZ.at[len(init_SampleMZ)-1,'RowIndex'].append(ii)
init_SampleMZ.at[len(init_SampleMZ)-1,'AverageMZ']=np.mean(init_SampleMZ.at[len(init_SampleMZ)-1,'MZList'])
else:
init_SampleMZ.loc[len(init_SampleMZ)] = [temp_Data.at[ii,'AverageMZ'],[temp_Data.at[ii,'AverageMZ']],[ii]]
add_MZ = []
add_RT = []
add_MS_List = []
add_RT_List = []
for ii in range(len(init_SampleMZ)):
Sample_MZ = init_SampleMZ.at[ii,'AverageMZ']
match_Index = list(filter(lambda x:abs(init_RefMZ.at[x,'AverageMZ']-Sample_MZ)/Sample_MZ<self.__param['MS1_Tor'],range(len(init_RefMZ))))
if len(match_Index)>1:
Ref_Index = init_RefMZ.at[match_Index[0],'RowIndex']
for i_mI in range(1,len(match_Index)):
Ref_Index = Ref_Index + init_RefMZ.at[match_Index[i_mI],'RowIndex']
elif len(match_Index)==1:
Ref_Index = init_RefMZ.at[match_Index[0],'RowIndex']
else:
for i_add in init_SampleMZ.at[ii,'RowIndex']:
add_MZ.append(temp_Data.at[i_add,'AverageMZ'])
add_RT.append(Sample_Time[i_add])
add_MS_List.append([temp_Data.at[i_add,'AverageMZ']])
add_RT_List.append([Sample_Time[i_add]])
continue
Score_matrix= np.zeros([len(Ref_Index),len(init_SampleMZ.at[ii,'RowIndex'])])
for i_Ref in range(len(Ref_Index)):
for i_Sample in range(len(init_SampleMZ.at[ii,'RowIndex'])):
i_Ref_MZ = Alltemp_HPL.at[Ref_Index[i_Ref],'AverageMZ']
i_Sample_MZ = temp_Data.at[init_SampleMZ.at[ii,'RowIndex'][i_Sample],'AverageMZ']
i_Ref_Time = Alltemp_HPL.at[Ref_Index[i_Ref],'RT']
i_Sample_Time = Sample_Time[init_SampleMZ.at[ii,'RowIndex'][i_Sample]]
if abs(i_Ref_MZ-i_Sample_MZ)/i_Ref_MZ<self.__param['MS1_Tor'] and abs(i_Ref_Time-i_Sample_Time)/i_Ref_Time<self.__param['RT_Tor']:
Score_matrix[i_Ref,i_Sample] = 0.5*np.exp(-0.5*((i_Sample_Time-i_Ref_Time)/(i_Ref_Time*self.__param['RT_Tor']))**2)+(1-0.5)*np.exp(-0.5*((i_Sample_MZ-i_Ref_MZ)/(i_Sample_MZ*self.__param['MS1_Tor']))**2)
Sm_row,Sm_col = linear_sum_assignment(Score_matrix,True)
for i_Sm_row,i_Sm_col in zip(Sm_row,Sm_col):
if Score_matrix[i_Sm_row,i_Sm_col] != 0:
Alltemp_HPL.at[Ref_Index[i_Sm_row],'MZ_List'].append(temp_Data.at[init_SampleMZ.at[ii,'RowIndex'][i_Sm_col],'AverageMZ'])
Alltemp_HPL.at[Ref_Index[i_Sm_row],'RT_List'].append(Sample_Time[init_SampleMZ.at[ii,'RowIndex'][i_Sm_col]])
Alltemp_HPL.at[Ref_Index[i_Sm_row],'RT'] = np.mean(Alltemp_HPL.at[Ref_Index[i_Sm_row],'RT_List'])
Alltemp_HPL.at[Ref_Index[i_Sm_row],'AverageMZ'] = np.mean(Alltemp_HPL.at[Ref_Index[i_Sm_row],'MZ_List'])
else:
add_MZ.append(temp_Data.at[init_SampleMZ.at[ii,'RowIndex'][i_Sm_col],'AverageMZ'])
add_RT.append(Sample_Time[init_SampleMZ.at[ii,'RowIndex'][i_Sm_col]])
add_MS_List.append([temp_Data.at[init_SampleMZ.at[ii,'RowIndex'][i_Sm_col],'AverageMZ']])
add_RT_List.append([Sample_Time[init_SampleMZ.at[ii,'RowIndex'][i_Sm_col]]])
miss_col = list(filter(lambda x:x not in Sm_col,range(len(init_SampleMZ.at[ii,'RowIndex']))))
for i_miss in miss_col:
add_MZ.append(temp_Data.at[init_SampleMZ.at[ii,'RowIndex'][i_miss],'AverageMZ'])
add_RT.append(Sample_Time[init_SampleMZ.at[ii,'RowIndex'][i_miss]])
add_MS_List.append([temp_Data.at[init_SampleMZ.at[ii,'RowIndex'][i_miss],'AverageMZ']])
add_RT_List.append([Sample_Time[init_SampleMZ.at[ii,'RowIndex'][i_miss]]])
add_RefList = pd.DataFrame({'AverageMZ': add_MZ,'RT': add_RT,'MZ_List':add_MS_List,'RT_List':add_RT_List})
Alltemp_HPL = pd.concat([Alltemp_HPL, add_RefList])
Alltemp_HPL.reset_index(drop=True, inplace=True)
Alltemp_HPL = Alltemp_HPL.fillna(0)
Alltemp_HPL['RT'] = Alltemp_HPL['RT_List'].apply(lambda x:sum(x)/len(x))
Alltemp_HPL.rename(columns={'RT':'RI'},inplace=True)
Alltemp_HPL.rename(columns={'RT_List':'RI_List'},inplace=True)
Alltemp_HPL['RI_left'] = Alltemp_HPL['RI'].apply(lambda x:x*(1-self.__param['RT_Tor']))
Alltemp_HPL['RI_right'] = Alltemp_HPL['RI'].apply(lambda x:x*(1+self.__param['RT_Tor']))
Alltemp_HPL.sort_values('AverageMZ',ascending=(True),inplace=True)
Alltemp_HPL.reset_index(drop=True,inplace=True)
self.Heuristic_normal_list = Alltemp_HPL.copy()
temp_Heuristic_peak_list = []
for ii in range(len(Alltemp_HPL)):
if len(temp_Heuristic_peak_list) == 0:
temp_Heuristic_peak_list = Alltemp_HPL.iloc[[0],:].copy()
temp_Heuristic_peak_list['PeakNumber'] = 1
else:
MZ = Alltemp_HPL.at[ii,'AverageMZ']
RI_left = Alltemp_HPL.at[ii,'RI_left']
RI_right = Alltemp_HPL.at[ii,'RI_right']
RI = Alltemp_HPL.at[ii,'RI']
same_list = list(filter(lambda x:EazyMZDataProcess.ppm_compare(MZ,temp_Heuristic_peak_list.at[x,'AverageMZ'])<self.__param['MS1_Tor'] and
((RI_left<=temp_Heuristic_peak_list.at[x,'RI_right'] and RI_right>=temp_Heuristic_peak_list.at[x,'RI_right']) or
(RI_left<=temp_Heuristic_peak_list.at[x,'RI_left'] and RI_right>=temp_Heuristic_peak_list.at[x,'RI_left'])),range(len(temp_Heuristic_peak_list))))
contain_list = list(filter(lambda x:EazyMZDataProcess.ppm_compare(MZ,temp_Heuristic_peak_list.at[x,'AverageMZ'])<self.__param['MS1_Tor'] and (RI_left>=temp_Heuristic_peak_list.at[x,'RI_left'] and RI_right<=temp_Heuristic_peak_list.at[x,'RI_right']),range(len(temp_Heuristic_peak_list))))
if len(same_list) == 0 :
if len(contain_list) == 0:
iii = Alltemp_HPL.iloc[[ii],:].copy()
iii['PeakNumber'] = 1
temp_Heuristic_peak_list = pd.concat([temp_Heuristic_peak_list,iii])
temp_Heuristic_peak_list.reset_index(drop=True,inplace=True)
temp_Heuristic_peak_list.loc[len(temp_Heuristic_peak_list)-1,'RI_List'] = [RI]
elif len(contain_list) == 1:
temp_Heuristic_peak_list.loc[contain_list[0],'PeakNumber'] = temp_Heuristic_peak_list.loc[contain_list[0],'PeakNumber']+1
temp_Heuristic_peak_list.loc[contain_list[0],'MZ_List'].append(MZ)
temp_Heuristic_peak_list.loc[contain_list[0],'RI_List'].append(RI)
temp_Heuristic_peak_list.loc[contain_list[0],'AverageMZ'] = np.mean(temp_Heuristic_peak_list.loc[contain_list[0],'MZ_List'])
elif len(same_list) == 1 :
if RI_left<temp_Heuristic_peak_list.at[same_list[0],'RI_left']:
temp_Heuristic_peak_list.loc[same_list[0],'RI_left'] = RI_left
if RI_right>temp_Heuristic_peak_list.at[same_list[0],'RI_right']:
temp_Heuristic_peak_list.loc[same_list[0],'RI_right'] = RI_right
temp_Heuristic_peak_list.loc[same_list[0],'MZ_List'].append(MZ)
temp_Heuristic_peak_list.loc[same_list[0],'RI_List'].append(RI)
temp_Heuristic_peak_list.loc[same_list[0],'AverageMZ'] = np.mean(temp_Heuristic_peak_list.loc[same_list[0],'MZ_List'])
temp_Heuristic_peak_list.loc[same_list[0],'PeakNumber'] = temp_Heuristic_peak_list.loc[same_list[0],'PeakNumber']+1
elif len(same_list) == 2 :
iii = Alltemp_HPL.iloc[[ii],:].copy()
iii['PeakNumber'] = temp_Heuristic_peak_list.loc[same_list[0],'PeakNumber'] + temp_Heuristic_peak_list.loc[same_list[1],'PeakNumber'] + 1
iii.loc[ii,'RI_right'] = max([RI_right,temp_Heuristic_peak_list.loc[same_list[0],'RI_right'],temp_Heuristic_peak_list.loc[same_list[1],'RI_right']])
iii.loc[ii,'RI_left'] = min([RI_left,temp_Heuristic_peak_list.loc[same_list[0],'RI_left'],temp_Heuristic_peak_list.loc[same_list[1],'RI_left']])
iii['MZ_List'] = iii['MZ_List'].astype('object')
iii.at[ii,'MZ_List'] = list(temp_Heuristic_peak_list.loc[same_list[0],'MZ_List'] + temp_Heuristic_peak_list.loc[same_list[1],'MZ_List'] + iii.loc[ii,'MZ_List'])
iii['RI_List'] = iii['RI_List'].astype('object')
iii.at[ii,'RI_List'] = list(temp_Heuristic_peak_list.loc[same_list[0],'RI_List'] + temp_Heuristic_peak_list.loc[same_list[1],'RI_List'] + [iii.loc[ii,'RI']])
iii.loc[ii,'AverageMZ'] = float(np.mean(iii.loc[ii,'MZ_List']))
temp_Heuristic_peak_list.drop(same_list,inplace=True)
temp_Heuristic_peak_list = pd.concat([temp_Heuristic_peak_list,iii])
temp_Heuristic_peak_list.reset_index(drop=True,inplace=True)
self.Heuristic_peak_list = temp_Heuristic_peak_list.copy()
def ThreeZero(x):
if len(x) >= 3:
if x[-1] == 0 and x[-2] == 0 and x[-3] == 0:
return False
else:
return True
else:
return True
def ClosestPosition(TargetNumber, List):
if TargetNumber >= List[-1]:
#print("Close error +")
return len(List)-1
elif TargetNumber <= List[0]:
#print("Close error -")
return 0
position = bisect.bisect_left(List, TargetNumber)
before = List[position-1]
after = List[position]
if after - TargetNumber < TargetNumber - before:
return position
else:
return position-1
def ppm_compare(a, b):
ppm_result = abs(a-b)/b
return ppm_result
'''
def Draw_TIC(self):
TIC_Int_List = []
for i in range(len(self.Origin_Int_List)):
TIC_Int_List.append(sum(self.Origin_Int_List[i]))
plt.plot(self.Origin_RT_List,TIC_Int_List)
plt.show()
TIC_Table = {'ScanTime':self.Origin_RT_List,'Intensity':TIC_Int_List}
TIC_Table = pd.DataFrame(TIC_Table)
#TIC_Table.to_excel(OutputPath+'TIC.xlsx')
return TIC_Table
'''
def CosineSimilarity(ExestList, NewList, LOG=False):
if len(ExestList) == 0 :
return 0
else:
if len(ExestList) != len(NewList):
print("CosineSimilarity error", len(ExestList), len(NewList))
return 0
if LOG == True:
temp_ExestList = []
for i in range(len(ExestList)):
if ExestList[i] != 0:
temp_ExestList.append(math.log(ExestList[i]))
else:
temp_ExestList.append(0)
ExestList = temp_ExestList
temp_NewList = []
for ii in range(len(NewList)):
if NewList[ii] != 0:
temp_NewList.append(math.log(NewList[ii]))
else:
temp_NewList.append(0)
NewList = temp_NewList
ExestList = np.array(ExestList)
NewList = np.array(NewList)
CosineSimilarityValue = ExestList.dot(
NewList)/(np.linalg.norm(ExestList) * np.linalg.norm(NewList))
return CosineSimilarityValue
def Calculate_SB(self,drop=False,limit=5):
self.Final_Peak_Detect['BLANK'] = 0
for i in range(len(self.Final_Peak_Detect)):
RTL = self.Final_Peak_Detect.at[i,'RTList'][0]
RTR = self.Final_Peak_Detect.at[i,'RTList'][-1]
MZ = self.Final_Peak_Detect.at[i,'AverageMZ']
[RT_List,Int_List] = self.ExtractBlankPoint(MZ,RTR,RTL,smooth_index=5)
self.Final_Peak_Detect.at[i,'BLANK'] = max(1,max(Int_List))
self.Final_Peak_Detect['S/B'] = self.Final_Peak_Detect['Int']/self.Final_Peak_Detect['BLANK']
if drop == True:
self.Final_Peak_Detect = self.Final_Peak_Detect[self.Final_Peak_Detect['S/B']>limit].copy()
self.Final_Peak_Detect.reset_index(drop=True,inplace=True)
def ExtractDataPoint(self,MZ, RTR, RTL,s_min=False, plt_for_test=False,smooth_index=5):
smooth_index =(smooth_index-1)//2
if smooth_index<0:
smooth_index=0
if s_min == True:
RTR = RTR * 60 # min -> s
RTL = RTL * 60
RTR_place = EazyMZDataProcess.ClosestPosition(RTR,self.Origin_RT_List)
RTL_place = EazyMZDataProcess.ClosestPosition(RTL,self.Origin_RT_List)
RT_List = self.Origin_RT_List[RTL_place:RTR_place]
Int_List = []
#MZ_List=[]
for i in range(RTL_place, RTR_place):
if len(self.Origin_MZ_List[i])>0:
if len(self.Origin_MZ_List[i])>=4:
MZ_place = EazyMZDataProcess.ClosestPosition(MZ,self.Origin_MZ_List[i])
if MZ_place > len(self.Origin_MZ_List[i])-3 and MZ_place>=3:
MZ_place = len(self.Origin_MZ_List[i])-3
elif MZ_place < 2:
MZ_place = 2
temp_int = []
#temp_MZ = []
for ii in range(MZ_place-2, MZ_place+2):
if MZ*(1-self.__param['MS1_Tor']) < self.Origin_MZ_List[i][ii] < MZ*(1+self.__param['MS1_Tor']):
temp_int.append(self.Origin_Int_List[i][ii])
#temp_MZ.append(Origin_MZ_List[i][ii])
if not temp_int:
Int_List.append(0)
#MZ_List.append(0)
else:
temp_int = np.array(temp_int)
Int_List.append(temp_int.max())
#MZ_List.append()
else:
Int_List.append(0)
else:
Int_List.append(0)
# smooth
def GaussSmooth(x):
if len(x)==5:
op = x[0]*0.07+x[1]*0.23+x[2]*0.4+x[3]*0.23+x[4]*0.07
elif len(x)==3:
op = x[0]*0.17 +x[1]*0.66 +x[2]*0.17
else:
op = sum(x)/len(x)
return op
if smooth_index != 0:
Int_List = list(map(lambda x:GaussSmooth(Int_List[x-smooth_index:x+smooth_index+1]) if x in range(smooth_index,len(Int_List)-smooth_index) else Int_List[x],range(len(Int_List))))
'''
if plt_for_test == True:
plt.figure()
plt.title(str(MZ))
plt.plot(RT_List,Int_List)
plt.figure()
'''
return RT_List, Int_List
def ExtractBlankPoint(self,MZ, RTR, RTL,s_min=False, plt_for_test=False,smooth_index=5):
smooth_index =(smooth_index-1)//2
if smooth_index<0:
smooth_index=0
if s_min == True: