-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathraw_parser.py
More file actions
2627 lines (1996 loc) · 102 KB
/
Copy pathraw_parser.py
File metadata and controls
2627 lines (1996 loc) · 102 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import numpy as np
import time
import clr
import System
from tqdm import tqdm
import pyarrow as pa
import pyarrow.parquet as pq
import re
import ctypes
clr.AddReference('System')
from System.Threading import Thread
from System.Globalization import CultureInfo
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture
CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture
System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture
de_fr = CultureInfo('fr-FR')
other = CultureInfo('en-US')
Thread.CurrentThread.CurrentCulture = other
Thread.CurrentThread.CurrentUICulture = other
path = os.path.dirname(os.path.abspath(__file__))
clr.AddReference(os.path.join(path, "os_data/ThermoFisher.CommonCore.Data.dll"))
clr.AddReference(os.path.join(path, "os_data/ThermoFisher.CommonCore.RawFileReader.dll"))
import ThermoFisher
from ThermoFisher.CommonCore.Data.Interfaces import IScanEventBase, IScanEvent
from System.Runtime.InteropServices import GCHandle, GCHandleType
#from scan_dumper import ScanDumper
_NUM_RE = re.compile(r"[-+]?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
def _cancel_requested(should_stop=None) -> bool:
if should_stop is None:
return False
try:
return bool(should_stop())
except Exception:
return False
def _to_float(x, default=np.nan):
if x is None:
return default
if isinstance(x, (int, float, np.floating, np.integer)):
try:
return float(x)
except Exception:
return default
s = str(x).strip()
if not s:
return default
m = _NUM_RE.search(s)
if not m:
return default
token = m.group(0).replace(",", ".")
try:
return float(token)
except Exception:
return default
def _to_int(x, default=-1):
v = _to_float(x, default=np.nan)
if v is None or (isinstance(v, float) and np.isnan(v)):
return default
try:
return int(v)
except Exception:
return default
def DotNetArrayToNPArray(src, dtype=None):
'''
See https://mail.python.org/pipermail/pythondotnet/2014-May/001527.html
'''
if src is None:
return np.array([], dtype=np.float64)
src_hndl = GCHandle.Alloc(src, GCHandleType.Pinned)
try:
src_ptr = src_hndl.AddrOfPinnedObject().ToInt64()
bufType = ctypes.c_double*len(src)
cbuf = bufType.from_address(src_ptr)
dest = np.frombuffer(cbuf, dtype=cbuf._type_).copy()
finally:
if src_hndl.IsAllocated: src_hndl.Free()
return dest
class MetaXtract:
# Inspired by pyRawFileReader in [pDeep3](https://github.com/pFindStudio/pDeep3)@Zeng,Wen-Feng
def __init__(self, filename, **kwargs):
self.filename = os.path.abspath(filename)
self.filename = os.path.normpath(self.filename)
self.source = ThermoFisher.CommonCore.RawFileReader.RawFileReaderAdapter.FileFactory(self.filename)
if not self.source.IsOpen:
raise IOError(
"RAWfile '{0}' could not be opened, is the file accessible ?".format(
self.filename))
self.source.SelectInstrument(ThermoFisher.CommonCore.Data.Business.Device.MS, 1)
try:
self.StartTime = self.source.RunHeaderEx.StartTime # Start time of the first scan or reading for the current controller
self.EndTime = self.source.RunHeaderEx.EndTime # End time of the last scan or reading for the current controller
self.FirstSpectrumNumber = self.source.RunHeaderEx.FirstSpectrum # First scan or reading number for the current controller
self.LastSpectrumNumber = self.source.RunHeaderEx.LastSpectrum # Last scan or reading number for the current controller
self.LowMass = self.source.RunHeaderEx.LowMass # Lowest mass or wavelength recorded for the current controller.
self.HighMass = self.source.RunHeaderEx.HighMass # Highest mass or wavelength recorded for the current controller
self.MassResolution = self.source.RunHeaderEx.MassResolution # Mass resolution value recorded for the current controller. The value is returned as one half of the mass resolution.
self.InstrumentCount = self.source.InstrumentCount # Number of instruments
self.NumSpectra = self.source.RunHeaderEx.SpectraCount # Total number of MS1 and MS2 spectra
self.NumMS2Centroid = 0
self.NumMS2Profile = 0
self.NumMS1 = 0
self.MS2ScanNumbers = []
self.MS1ScanNumbers = []
self.DiffScans = 0
self.AccScans = 0
self.PositiveTestFile = None
self.NegativeTestFile = None
self.PositiveTestFile = "./p.log" # This file contains the positive selected precursor masses with digits improvement
self.NegativeTestFile = "./n.log" # This file contains the mono preucursor masses, which contains only four digits
#with open(self.PositiveTestFile, 'w') as file:
# pass
#with open(self.NegativeTestFile, 'w') as file:
# pass
except Exception as e:
raise IOError(f'{e}')
def GetMS2PeakListArraysFromScanNumber(self, scanNumber: int):
return self.GetMS2PeakListArraysFromScanNumberTest(scanNumber)
def CountMS2(self, should_stop=None) -> None:
"""
Count number of MS2 spectra in the raw file.
This function takes a no arguments, it fills the internal class variables NumMS2Centroid, NumMS2Profile, and NumMS1.
Args:
self (class object): the main class object of the Raw_Parser.
Returns:
None.
Raises:
ValueError: If the structure of the raw file uncompleted or contains error, which makes no possibility to
parse and count the different spectras from it.
"""
try:
if not hasattr(self, 'NumSpectra') or not isinstance(self.NumSpectra, int):
raise ValueError("Invalid or missing 'NumSpectra' attribute.")
self.NumMS2Centroid = 0
self.NumMS2Profile = 0
self.NumMS1 = 0
for scanNumber in range(1, self.NumSpectra + 1):
if _cancel_requested(should_stop):
break
try:
scanStatistics = self.source.GetScanStatsForScanNumber(scanNumber)
scanEvent = self.source.GetScanEventForScanNumber(scanNumber)
if scanStatistics is None or scanEvent is None:
print(f"Warning: Scan {scanNumber} returned None values and was skipped.")
continue
scanMSOrder = int(IScanEventBase(scanEvent).MSOrder)
if getattr(scanStatistics, 'IsCentroidScan', False):
if scanMSOrder == 2:
self.NumMS2Centroid += 1
self.MS2ScanNumbers.append(scanNumber)
else:
self.NumMS1 += 1
self.MS1ScanNumbers.append(scanNumber)
else:
if scanMSOrder == 2:
self.NumMS2Profile += 1
else:
self.NumMS1 += 1
self.MS1ScanNumbers.append(scanNumber)
except AttributeError as e:
print(f"Error processing scan {scanNumber}: {e}")
continue
except Exception as e:
print(f"Unexpected error at scan {scanNumber}: {e}")
continue
except ValueError as e:
print(f"ValueError encountered: {e}")
except Exception as e:
print(f"Critical error during CountMS2 execution: {e}")
def GetMS2MonoMzFromScanNumber(self, scanNumber: int) -> float:
"""
Get MS2 monoisotopic M/Z from specific scan.
This function takes the scan number as argument and use it to map the trailer information from the raw file to
the index of the scan.
Args:
self (class object): the main class object of the Raw_Parser.
scanNumber (int): number of the target scan.
Returns:
float conversion from the monoisotopic M/Z mass.
Raises:
ValueError: If the structure of the raw file uncompleted or contains error, which makes no possibility to
parse and extract the 'Monoisotopic M/Z' from it.
"""
try:
if not isinstance(scanNumber, int) or scanNumber < 1:
raise ValueError(f"Invalid scan number: {scanNumber}")
trailerData = self.source.GetTrailerExtraInformation(scanNumber)
if trailerData is None:
raise ValueError(f"No trailer data found for scan number {scanNumber}")
if not hasattr(trailerData, 'Labels') or not hasattr(trailerData, 'Values'):
raise ValueError(f"Trailer data structure missing required attributes for scan {scanNumber}")
trailerDataLabels = [x[:-1] if x and x[-1] == ":" else x for x in trailerData.Labels or []]
trailerDataDict = dict(zip(trailerDataLabels, trailerData.Values or []))
mono_mz = trailerDataDict.get('Monoisotopic M/Z', np.nan)
#return float(mono_mz) if mono_mz is not None else np.nan
return _to_float(mono_mz, default=np.nan)
except ValueError as ve:
print(f"ValueError: {ve}")
return np.nan
except Exception as e:
print(f"Unexpected error while processing scan {scanNumber}: {e}")
return np.nan
def GetTrailerExtraInformaionEdited(self, scanNumber: int) -> dict:
"""
Get trailer extra information edited
This function takes the scan number as argument and use it to extract the trailer information and change them regarding
the target dict.
Args:
self (class object): the main class object of the Raw_Parser.
scanNumber (int): number of the target scan.
Returns:
dict conversion from the raw dict.
Raises:
ValueError: If the structure of the raw file uncompleted or contains error, which makes no possibility to
parse and extract the 'trailer information from it.
"""
try:
if not isinstance(scanNumber, int) or scanNumber < 1:
raise ValueError(f"Invalid scan number provided: {scanNumber}")
trailerData = self.source.GetTrailerExtraInformation(scanNumber)
if trailerData is None:
raise ValueError(f"No trailer data found for scan number {scanNumber}")
if not hasattr(trailerData, 'Labels') or not hasattr(trailerData, 'Values'):
raise ValueError(f"Trailer data for scan {scanNumber} is missing required attributes")
trailerDataLabels = [
x[:-1] if x and x[-1] == ":" else x for x in (trailerData.Labels or [])
]
trailerDataDict = dict(zip(trailerDataLabels, trailerData.Values or []))
return trailerDataDict
except ValueError as ve:
print(f"ValueError: {ve}")
return {}
except Exception as e:
print(f"Unexpected error while processing scan {scanNumber}: {e}")
return {}
def GetMS2ChargeFromScanNumber(self, scanNumber: int) -> int:
"""
Get MS2-scan's charge from specific scan.
This function takes the scan number as argument and use it to map the trailer information from the raw file to
the index of the scan.
Args:
self (class object): the main class object of the Raw_Parser.
scanNumber (int): number of the target scan.
Returns:
int conversion from the charge state of the precursor.
Raises:
ValueError: If the structure of the raw file uncompleted or contains error, which makes no possibility to
parse and extract the 'Charge State' from it.
"""
try:
if not isinstance(scanNumber, int) or scanNumber < 1:
raise ValueError(f"Invalid scan number provided: {scanNumber}")
trailerData = self.source.GetTrailerExtraInformation(scanNumber)
if trailerData is None:
raise ValueError(f"No trailer data found for scan number {scanNumber}")
if not hasattr(trailerData, 'Labels') or not hasattr(trailerData, 'Values'):
raise ValueError(f"Trailer data for scan {scanNumber} is missing required attributes")
trailerDataLabels = [
x[:-1] if x and x[-1] == ":" else x for x in (trailerData.Labels or [])
]
trailerDataDict = dict(zip(trailerDataLabels, trailerData.Values or []))
charge_state = trailerDataDict.get('Charge State', -1)
return int(charge_state) if charge_state is not None else -1
except ValueError as ve:
print(f"ValueError: {ve}")
return -1
except Exception as e:
print(f"Unexpected error while processing scan {scanNumber}: {e}")
return -1
def GetMS2MZArrayFromScanNumber(self, scanNumber: int) -> np.array:
"""
Get MS2 MZ array from specific scan.
This function takes the scan number as argument and use it to map the trailer information from the raw file to
the index of the scan.
Args:
self (class object): the main class object of the Raw_Parser.
scanNumber (int): number of the target scan.
Returns:
np.array[float] of the M/Z masses of the corresponding scan.
Raises:
ValueError: If the structure of the raw file uncompleted or contains error, which makes no possibility to
parse and extract the spectra masses from it.
"""
try:
if not isinstance(scanNumber, int) or scanNumber < 1:
raise ValueError(f"Invalid scan number provided: {scanNumber}")
scanStatistics = self.source.GetScanStatsForScanNumber(scanNumber)
if scanStatistics is None:
raise ValueError(f"No scan statistics found for scan number {scanNumber}")
if not hasattr(scanStatistics, 'IsCentroidScan') or not scanStatistics.IsCentroidScan:
raise ValueError(f"Scan {scanNumber} is not a centroid scan")
scanEvent = self.source.GetScanEventForScanNumber(scanNumber)
if scanEvent is None:
raise ValueError(f"No scan event found for scan number {scanNumber}")
scanMSOrder = int(IScanEventBase(scanEvent).MSOrder)
if scanMSOrder != 2:
raise ValueError(f"Scan {scanNumber} is not an MS2 scan")
stream = self.source.GetCentroidStream(scanNumber, False)
if stream is None or not hasattr(stream, 'Masses'):
raise ValueError(f"Failed to retrieve centroid data for scan {scanNumber}")
mz_array = np.array(DotNetArrayToNPArray(stream.Masses, float))
return mz_array
except ValueError as ve:
print(f"ValueError: {ve}")
return np.array([])
except Exception as e:
print(f"Unexpected error while processing scan {scanNumber}: {e}")
return np.array([])
def CheckMS2Centroid(self, scanNumber: int) -> bool:
"""
Check if scan is centroid.
This function takes the scan number as argument and use it to map the trailer information from the raw file to
the index of the scan.
Args:
self (class object): the main class object of the Raw_Parser.
scanNumber (int): number of the target scan.
Returns:
bool the bool value indicates if the scan is centroid.
Raises:
ValueError: If the structure of the raw file uncompleted or contains error, which makes no possibility to
parse and extract the scan realted identifier from it.
"""
#return (self.source.GetScanStatsForScanNumber(scanNumber)).IsCentroidScan
try:
if not isinstance(scanNumber, int) or scanNumber < 1:
raise ValueError(f"Invalid scan number provided: {scanNumber}")
scanStats = self.source.GetScanStatsForScanNumber(scanNumber)
if scanStats is None:
raise ValueError(f"No scan statistics found for scan number {scanNumber}")
if not hasattr(scanStats, 'IsCentroidScan'):
raise ValueError(f"Scan statistics do not contain centroid scan information for scan {scanNumber}")
return bool(scanStats.IsCentroidScan)
except ValueError as ve:
print(f"ValueError: {ve}")
return False
except Exception as e:
print(f"Unexpected error while processing scan {scanNumber}: {e}")
return False
def CheckRoundDigits(self, isolationMzPossiblyWithOffset: float, monoMZ: float) -> bool:
"""
Check the possibility of masses improvement regarding MS2 scan.
This function is used as a feedback stop to use new value of the mass or keep
the one read directly from the raw file. The function checks if rounding
three digits of each masses will give the same value. Using this step, we
are able to improve the precursor mass of some scans without any need to
do any extra computations.
Args:
self (class object): the main class object of the Raw_Parser.
isolationMzPossiblyWithOffset (float): precursor mass from the reaction.
monoMZ (float): precursor mass which is extracted from the raw file as
monoisotopic M/Z mass.
Returns:
bool the bool value indicates if both values are same with digits improvement.
Raises:
ValueError: If the structure of the raw file uncompleted or contains error, which makes no possibility to
parse and extract the scan realted identifier from it.
"""
rounded_isolationMzPossiblyWithOffset = round(isolationMzPossiblyWithOffset, 3)
rounded_monoMZ = round(monoMZ, 3)
return (rounded_isolationMzPossiblyWithOffset == rounded_monoMZ)
def GetMS2IntensitiesArrayFromScanNumber(self, scanNumber: int) -> np.array:
"""
Get intensity list from the scan number.
This function extracts the intensities list using the scan number from
the raw file by parsing the statistics c# object.
Args:
self (class object): the main class object of the Raw_Parser.
scanNumber (int): number of the target scan.
Returns:
np.array[float] values of the intensites called from raw file.
Raises:
ValueError: If the structure of the raw file uncompleted or contains error, which makes no possibility to
parse and extract the inteisites list from it.
"""
try:
if not isinstance(scanNumber, int) or scanNumber < 1:
raise ValueError(f"Invalid scan number provided: {scanNumber}")
if not self.CheckMS2Centroid(scanNumber):
raise ValueError(f"Scan {scanNumber} is not a centroid scan.")
scanEvent = self.source.GetScanEventForScanNumber(scanNumber)
if scanEvent is None:
raise ValueError(f"No scan event found for scan number {scanNumber}")
scanMSOrder = int(IScanEventBase(scanEvent).MSOrder)
if scanMSOrder != 2:
raise ValueError(f"Scan {scanNumber} is not an MS2 scan.")
stream = self.source.GetCentroidStream(scanNumber, False)
if stream is None or not hasattr(stream, 'Intensities'):
raise ValueError(f"Failed to retrieve intensity data for scan {scanNumber}")
intensity_array = np.array(DotNetArrayToNPArray(stream.Intensities, float))
return intensity_array
except ValueError as ve:
print(f"ValueError: {ve}")
return np.array([])
except Exception as e:
print(f"Unexpected error while processing scan {scanNumber}: {e}")
return np.array([])
def GetMasterScanNumber(self, MS2ScarNumber: int) -> int:
"""
Get master scan number of the MS2 scan.
This function extracts the master scan number from the MS2 scan.
Args:
self (class object): the main class object of the Raw_Parser.
MS2ScarNumber (int): number of the MS2 scan.
Returns:
int master scan number as integer value.
Raises:
ValueError: If the structure of the raw file uncompleted or contains error, which makes no possibility to
parse and extract the master scan number from it.
"""
try:
if not isinstance(MS2ScarNumber, int) or MS2ScarNumber < 1:
raise ValueError(f"Invalid MS2 scan number provided: {MS2ScarNumber}")
trailerData = self.source.GetTrailerExtraInformation(MS2ScarNumber)
if trailerData is None:
raise ValueError(f"No trailer data found for scan number {MS2ScarNumber}")
if not hasattr(trailerData, 'Labels') or not hasattr(trailerData, 'Values'):
raise ValueError(f"Trailer data for scan {MS2ScarNumber} is missing required attributes")
trailerDataLabels = [x[:-1] if x and x[-1] == ":" else x for x in (trailerData.Labels or [])]
trailerDataDict = dict(zip(trailerDataLabels, trailerData.Values or []))
master_scan_number = trailerDataDict.get('Master Scan Number', -1)
return int(master_scan_number) if master_scan_number is not None else -1
except ValueError as ve:
print(f"ValueError: {ve}")
return -1
except Exception as e:
print(f"Unexpected error while processing scan {MS2ScarNumber}: {e}")
return -1
def GetSPSMass(self, MS2ScarNumber: int) -> np.array:
"""
Get list of SPSMass from MS2 scan number.
This function uses trainer information to extraxt SPS mass if available.
Args:
self (class object): the main class object of the Raw_Parser.
MS2ScarNumber (int): number of the MS2 scan.
Returns:
np.array[float] list of sps masses.
Raises:
ValueError: If the structure of the raw file uncompleted or contains error, which makes no possibility to
parse and extract the sps masses from it.
"""
try:
if not isinstance(MS2ScarNumber, int) or MS2ScarNumber < 1:
raise ValueError(f"Invalid MS2 scan number provided: {MS2ScarNumber}")
trailerData = self.source.GetTrailerExtraInformation(MS2ScarNumber)
if trailerData is None:
raise ValueError(f"No trailer data found for scan number {MS2ScarNumber}")
if not hasattr(trailerData, 'Labels') or not hasattr(trailerData, 'Values'):
raise ValueError(f"Trailer data for scan {MS2ScarNumber} is missing required attributes")
trailerDataLabels = [x[:-1] if x and x[-1] == ":" else x for x in (trailerData.Labels or [])]
trailerDataDict = dict(zip(trailerDataLabels, trailerData.Values or []))
sps_masses = trailerDataDict.get('SPS Masses', None)
if sps_masses is None or sps_masses == -1:
raise ValueError(f"SPS Masses not found for scan number {MS2ScarNumber}")
return np.array(DotNetArrayToNPArray(sps_masses, float))
except ValueError as ve:
print(f"ValueError: {ve}")
return np.array([])
except Exception as e:
print(f"Unexpected error while processing scan {MS2ScarNumber}: {e}")
return np.array([])
def GetMSOrder(self, scanNumber: int) -> int:
"""
Get MS order from the input scan (MS1 or MS2)
This function uses the scan event .
Args:
self (class object): the main class object of the Raw_Parser.
MS2ScarNumber (int): number of the MS2 scan.
Returns:
np.array[float] list of sps masses.
Raises:
ValueError: If the structure of the raw file uncompleted or contains error, which makes no possibility to
parse and extract the sps masses from it.
"""
try:
if not isinstance(scanNumber, int) or scanNumber < 1:
raise ValueError(f"Invalid scan number provided: {scanNumber}")
scanEvent = self.source.GetScanEventForScanNumber(scanNumber)
if scanEvent is None:
raise ValueError(f"No scan event found for scan number {scanNumber}")
ms_order = IScanEventBase(scanEvent).MSOrder
if ms_order is None:
raise ValueError(f"MS order could not be determined for scan number {scanNumber}")
return int(ms_order)
except ValueError as ve:
print(f"ValueError: {ve}")
return -1
except Exception as e:
print(f"Unexpected error while processing scan {scanNumber}: {e}")
return -1
def GetMS2PrecursorMassFromScanNumber(self, scanNumber: int) -> float:
"""
Get MS2 precursor mass
This function compare the mono isotopic mass with the reactions mass,
which has been used for fragmentation and retrives the correct or
improved precursor mass (with more digits)
Args:
self (class object): the main class object of the Raw_Parser.
MS2ScarNumber (int): number of the MS2 scan.
Returns:
float precursor mass.
Raises:
ValueError: If the structure of the raw file uncompleted or contains error, which makes no possibility to
parse and extract the precursor mass from the raw file.
"""
try:
if not isinstance(scanNumber, int) or scanNumber < 1:
raise ValueError(f"Invalid scan number provided: {scanNumber}")
scanMSOrder = self.GetMSOrder(scanNumber)
if scanMSOrder != 2:
raise ValueError(f"Scan {scanNumber} is not an MS2 scan.")
filterObj = self.source.GetFilterForScanNumber(scanNumber)
if filterObj is None:
raise ValueError(f"No filter found for scan number {scanNumber}")
isolationMzPossiblyWithOffset = filterObj.GetMass(scanMSOrder - 2)
scanEvent = self.source.GetScanEventForScanNumber(scanNumber)
if scanEvent is None:
raise ValueError(f"No scan event found for scan number {scanNumber}")
reaction = scanEvent.GetReaction(0)
if reaction is None:
raise ValueError(f"No reaction data found for scan number {scanNumber}")
trailerDataExtra = self.source.GetTrailerExtraInformation(scanNumber)
if trailerDataExtra is None or not hasattr(trailerDataExtra, 'Labels') or not hasattr(trailerDataExtra, 'Values'):
raise ValueError(f"Trailer data is incomplete for scan number {scanNumber}")
trailerDataLabels = [x[:-1] if x and x[-1] == ":" else x for x in (trailerDataExtra.Labels or [])]
trailerDataDict = dict(zip(trailerDataLabels, trailerDataExtra.Values or []))
# Retrieve monoisotopic mass and isolation width
isolationWidth = self.GetMS2IsolationWidthFromScanNumber(scanNumber)
monoMZ = self.GetMS2MonoMzFromScanNumber(scanNumber)
precursorMass = None
if self.CheckRoundDigits(isolationMzPossiblyWithOffset, monoMZ) or (isolationMzPossiblyWithOffset - monoMZ) < 0:
self.AccScans += 1
charge = self.GetMS2ChargeFromScanNumber(scanNumber)
offset = reaction.IsolationWidthOffset
diff = isolationMzPossiblyWithOffset - monoMZ
log = f'scan {scanNumber} monoMZ {monoMZ} precursorMZ {isolationMzPossiblyWithOffset} diff {diff} charge {charge} offset {offset} iso.width {isolationWidth}\n'
#with open(self.PositiveTestFile, 'a') as file: file.write(log)
precursorMass = isolationMzPossiblyWithOffset
else:
self.DiffScans += 1
charge = self.GetMS2ChargeFromScanNumber(scanNumber)
offset = reaction.IsolationWidthOffset
diff = isolationMzPossiblyWithOffset - monoMZ
log = f'scan {scanNumber} monoMZ {monoMZ} precursorMZ {isolationMzPossiblyWithOffset} diff {diff} charge {charge} offset {offset} iso.width {isolationWidth}\n'
#with open(self.NegativeTestFile, 'a') as file: file.write(log)
precursorMass = monoMZ
return precursorMass
except ValueError as ve:
print(f"ValueError: {ve}")
return np.nan
except Exception as e:
print(f"Unexpected error while processing scan {scanNumber}: {e}")
return np.nan
def GetMS2IsolationWidthFromScanNumber(self, scanNumber: int)-> float:
"""
Get MS2 isolation width
This function creates the trailer extra information to parse the
applied MS2 isolation width while creating the raw file.
Args:
self (class object): the main class object of the Raw_Parser.
scarNumber (int): number of the MS2 scan.
Returns:
float isolation width.
Raises:
ValueError: If the structure of the raw file uncompleted or contains error, which makes no possibility to
parse and extract the ms2 isolation width from the raw file.
"""
try:
if not isinstance(scanNumber, int) or scanNumber < 1:
raise ValueError(f"Invalid scan number provided: {scanNumber}")
trailerData = self.source.GetTrailerExtraInformation(scanNumber)
if trailerData is None:
raise ValueError(f"No trailer data found for scan number {scanNumber}")
if not hasattr(trailerData, 'Labels') or not hasattr(trailerData, 'Values'):
raise ValueError(f"Trailer data for scan {scanNumber} is missing required attributes")
trailerDataLabels = [
x[:-1] if x and x[-1] == ":" else x for x in (trailerData.Labels or [])
]
trailerDataDict = dict(zip(trailerDataLabels, trailerData.Values or []))
isolation_width = trailerDataDict.get('MS2 Isolation Width', np.nan)
#return float(isolation_width) if isolation_width is not None else np.nan
return _to_float(isolation_width, default=np.nan)
except ValueError as ve:
print(f"ValueError: {ve}")
return np.nan
except Exception as e:
print(f"Unexpected error while processing scan {scanNumber}: {e}")
return np.nan
def GetPrecursorIntensityFromScanNumber(self, scanNumber: int) -> float:
"""
Get MS2 precursor intensity from MS2 or MS1 scans
This function reads from scan statisticsthe MS2/MS1 masses.
Args:
self (class object): the main class object of the Raw_Parser.
scarNumber (int): number of the MS2 scan.
Returns:
np.array[float] list of MS1/MS2 masses.
Raises:
ValueError: If the structure of the raw file uncompleted or contains error, which makes no possibility to
parse and extract the ms2/ms1 masses lists from the raw file.
"""
MS1MasterScan = self.GetMasterScanNumber(scanNumber)
monoMZ = self.GetMS2MonoMzFromScanNumber(scanNumber)
if MS1MasterScan is None or np.isnan(monoMZ):
raise ValueError(f"Could not retrieve valid data for scan number {scanNumber}")
try:
scanStatistics = self.source.GetScanStatsForScanNumber(MS1MasterScan)
if scanStatistics is None:
raise ValueError(f"No scan statistics found for master scan {MS1MasterScan}")
intensitiesArray = []
MZArray = []
if (scanStatistics.IsCentroidScan):
stream = self.source.GetCentroidStream(MS1MasterScan, False)
if stream is None or not hasattr(stream, 'Masses') or not hasattr(stream, 'Intensities'):
raise ValueError(f"Failed to retrieve centroid data for scan {MS1MasterScan}")
MZArray = np.array(stream.Masses)
intensitiesArray = np.array(stream.Intensities)
else:
segmentedScan = self.source.GetSegmentedScanFromScanNumber(MS1MasterScan, scanStatistics)
if segmentedScan is None or not hasattr(segmentedScan, 'Positions') or not hasattr(segmentedScan, 'Intensities'):
raise ValueError(f"Failed to retrieve segmented scan data for scan {MS1MasterScan}")
MZArray = np.array(segmentedScan.Positions)
intensitiesArray = np.array(segmentedScan.Intensities)
idx = np.searchsorted(MZArray, monoMZ, side='left')
if idx >= len(intensitiesArray):
raise ValueError(f"MonoMZ {monoMZ} is out of range for scan {scanNumber}")
intensity = intensitiesArray[idx]
#print(intensity)
return _to_float(intensity) if not np.isnan(intensity) else np.nan
except Exception:
return np.nan
def CloseRAWFile(self) -> None:
"""
Close the raw file
Args:
self (class object): the main class object of the Raw_Parser.
Returns:
None.
Raises:
ValueError: If the structure of the raw file uncompleted or contains error.
"""
self.source.Dispose()
def GetRAWFileName(self) -> str:
"""
Get the raw file name
Args:
self (class object): the main class object of the Raw_Parser.
Returns:
str input file name.
Raises:
ValueError: If the structure of the raw file uncompleted or not found.
"""
return self.source.FileName
def GetUserID(self) -> str: #the login ID of the user who acquired the data
"""
Get the login ID of the user who acquired the data
Args:
self (class object): the main class object of the Raw_Parser.
Returns:
str user id.
Raises:
ValueError: If the structure of the raw file uncompleted or contains error.
"""
#return self.source.CreatorId
try:
if not hasattr(self, 'source') or self.source is None:
raise ValueError("The raw file source is not available.")
user_id = getattr(self.source, 'CreatorId', None)
if user_id is None:
raise ValueError("User ID could not be retrieved from the raw file.")
return str(user_id)
except ValueError as ve:
print(f"ValueError: {ve}")
return ""
except Exception as e:
print(f"Unexpected error while retrieving user ID: {e}")
return ""
def GetFileCreationDate(self) -> str:
"""
Get raw file creation date
Args:
self (class object): the main class object of the Raw_Parser.
Returns:
str raw file creation date.
Example: 4/10/2019 8:45:37 PM
Raises:
ValueError: If the structure of the raw file uncompleted or contains error.
"""
#return str(self.source.CreationDate)
try:
if not hasattr(self, 'source') or self.source is None:
raise ValueError("The raw file source is not available.")
creation_date = getattr(self.source, 'CreationDate', None)
if creation_date is None:
raise ValueError("File creation date could not be retrieved from the raw file.")
return str(creation_date)
except ValueError as ve:
print(f"ValueError: {ve}")
return ""
except Exception as e:
print(f"Unexpected error while retrieving file creation date: {e}")
return ""
def GetElaspedScanTimeFromScanNumber(self, scanNumber: int) -> float:
"""
Get Elapsed Scan Time (sec) of specific scan
This function returns the Elapsed Scan Time (sec) from the target scan.
Args:
self (class object): the main class object of the Raw_Parser.
scanNumber (int): scan number.
Returns:
float Elapsed Scan Time (sec).
Raises:
ValueError: If the structure of the raw file uncompleted or contains error, which makes no possibility to
parse and extract the Elapsed Scan Time (sec) for target scan.
"""
try:
if not isinstance(scanNumber, int) or scanNumber < 1:
raise ValueError(f"Invalid scan number: {scanNumber}")
trailerData = self.source.GetTrailerExtraInformation(scanNumber)
if trailerData is None:
raise ValueError(f"No trailer data found for scan number {scanNumber}")
if not hasattr(trailerData, 'Labels') or not hasattr(trailerData, 'Values'):
raise ValueError(f"Trailer data structure missing required attributes for scan {scanNumber}")
trailerDataLabels = [x[:-1] if x and x[-1] == ":" else x for x in trailerData.Labels or []]
trailerDataDict = dict(zip(trailerDataLabels, trailerData.Values or []))
injection_time = trailerDataDict.get('Elapsed Scan Time (sec)', np.nan)
return _to_float(injection_time, default=np.nan)
#return float(injection_time) if injection_time is not None else np.nan
except ValueError as ve:
print(f"ValueError: {ve}")
return np.nan
except Exception as e:
print(f"Unexpected error while processing scan {scanNumber}: {e}")
return np.nan
def GetIonInjectionTimeFromScanNumber(self, scanNumber: int) -> float:
"""
Get ion injection time of specific scan
This function returns the ion injection time from the target scan.
Args:
self (class object): the main class object of the Raw_Parser.
scanNumber (int): scan number.