forked from PNNL-Comp-Mass-Spec/Thermo-Raw-File-Reader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathXRawFileIO.cs
3161 lines (2627 loc) · 127 KB
/
XRawFileIO.cs
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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using PRISM;
using ThermoFisher.CommonCore.Data;
using ThermoFisher.CommonCore.Data.Business;
using ThermoFisher.CommonCore.Data.Interfaces;
using ThermoFisher.CommonCore.MassPrecisionEstimator;
using ThermoFisher.CommonCore.RawFileReader;
using ThermoFisher.CommonCore.BackgroundSubtraction;
using ThermoFisher.CommonCore.Data.FilterEnums;
// The methods in this class use ThermoFisher.CommonCore.RawFileReader.dll
// and related DLLs to extract scan header info and mass spec data (m/z and intensity lists)
// from Thermo .Raw files (LTQ, LTQ-FT, Orbitrap, Exactive, TSQ, etc.)
//
// For more information about the ThermoFisher.CommonCore DLLs,
// see the RawFileReaderLicense.doc file in the lib directory;
// see also http://planetorbitrap.com/rawfilereader#.W5BAoOhKjdM
// For questions, contact Jim Shofstahl at ThermoFisher.com
// -------------------------------------------------------------------------------
// Written by Matthew Monroe and Bryson Gibbons for the Department of Energy (PNNL, Richland, WA)
// Originally used XRawfile2.dll (in November 2004)
// Switched to MSFileReader.XRawfile2.dll in March 2012
// Switched to ThermoFisher.CommonCore DLLs in 2018
//
// E-mail: [email protected] or [email protected]
// Website: https://omics.pnl.gov/ or https://www.pnnl.gov/sysbio/ or https://panomics.pnnl.gov/
// -------------------------------------------------------------------------------
//
// Licensed under the 2-Clause BSD License; you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
// https://opensource.org/licenses/BSD-2-Clause
//
// Copyright 2018 Battelle Memorial Institute
// ReSharper disable UnusedMember.Global
namespace ThermoRawFileReader
{
/// <summary>
/// Class for reading Thermo .raw files
/// </summary>
[CLSCompliant(true)]
public class XRawFileIO : EventNotifier, IDisposable
{
#region "Constants"
// Note that each of these strings has a space at the end; this is important to avoid matching inappropriate text in the filter string
private const string MS_ONLY_C_TEXT = " c ms ";
private const string MS_ONLY_P_TEXT = " p ms ";
private const string MS_ONLY_P_NSI_TEXT = " p NSI ms ";
private const string MS_ONLY_PZ_TEXT = " p Z ms "; // Likely a zoom scan
private const string MS_ONLY_DZ_TEXT = " d Z ms "; // Dependent zoom scan
private const string MS_ONLY_PZ_MS2_TEXT = " d Z ms2 "; // Dependent MS2 zoom scan
private const string MS_ONLY_Z_TEXT = " NSI Z ms "; // Likely a zoom scan
private const string FULL_MS_TEXT = "Full ms ";
private const string FULL_PR_TEXT = "Full pr "; // TSQ: Full Parent Scan, Product Mass
private const string SIM_MS_TEXT = "SIM ms ";
private const string FULL_LOCK_MS_TEXT = "Full lock ms "; // Lock mass scan
private const string MRM_Q1MS_TEXT = "Q1MS ";
private const string MRM_Q3MS_TEXT = "Q3MS ";
private const string MRM_SRM_TEXT = "SRM ms2";
private const string MRM_FullNL_TEXT = "Full cnl "; // MRM neutral loss; yes, cnl starts with a c
private const string MRM_SIM_PR_TEXT = "SIM pr "; // TSQ: Isolated and fragmented parent, monitor multiple product ion ranges; e.g., Biofilm-1000pg-std-mix_06Dec14_Smeagol-3
// This RegEx matches Full ms2, Full ms3, ..., Full ms10, Full ms11, ...
// It also matches p ms2
// It also matches SRM ms2
// It also matches CRM ms3
// It also matches Full msx ms2 (multiplexed parent ion selection, introduced with the Q-Exactive)
private const string MS2_REGEX = "(?<ScanMode> p|Full|SRM|CRM|Full msx) ms(?<MSLevel>[2-9]|[1-9][0-9]) ";
private const string ION_MODE_REGEX = "[+-]";
private const string MASS_LIST_REGEX = "\\[[0-9.]+-[0-9.]+.*\\]";
private const string MASS_RANGES_REGEX = "(?<StartMass>[0-9.]+)-(?<EndMass>[0-9.]+)";
// This RegEx matches text like [email protected] or [email protected] or [email protected]@cid20.00
private const string PARENT_ION_REGEX = "(?<ParentMZ>[0-9.]+)@(?<CollisionMode1>[a-z]*)(?<CollisionEnergy1>[0-9.]+)(@(?<CollisionMode2>[a-z]+)(?<CollisionEnergy2>[0-9.]+))?";
// This RegEx is used to extract parent ion m/z from a filter string that does not contain msx
// ${ParentMZ} will hold the last parent ion m/z found
// For example, 756.71 in FTMS + p NSI d Full ms3 [email protected] [email protected] [195.00-2000.00]
private const string PARENT_ION_ONLY_NON_MSX_REGEX = @"[Mm][Ss]\d*[^\[\r\n]* (?<ParentMZ>[0-9.]+)@?[A-Za-z]*\d*\.?\d*(\[[^\]\r\n]\])?";
// This RegEx is used to extract parent ion m/z from a filter string that does contain msx
// ${ParentMZ} will hold the first parent ion m/z found (the first parent ion m/z corresponds to the highest peak)
// For example, 636.04 in FTMS + p NSI Full msx ms2 [email protected] [email protected] [email protected] [88.00-1355.00]
private const string PARENT_ION_ONLY_MSX_REGEX = @"[Mm][Ss]\d* (?<ParentMZ>[0-9.]+)@?[A-Za-z]*\d*\.?\d*[^\[\r\n]*(\[[^\]\r\n]+\])?";
// This RegEx looks for "sa" prior to Full ms"
private const string SA_REGEX = " sa Full ms";
private const string MSX_REGEX = " Full msx ";
private const string COLLISION_SPEC_REGEX = "(?<MzValue> [0-9.]+)@";
private const string MZ_WITHOUT_COLLISION_ENERGY = "ms[2-9](?<MzValue> [0-9.]+)$";
#endregion
#region "Classwide Variables"
/// <summary>
/// Maximum size of the scan info cache
/// </summary>
private int mMaxScansToCacheInfo = 50000;
/// <summary>
/// The the full path to the currently loaded .raw file
/// </summary>
private string mCachedFilePath;
/// <summary>
/// The scan info cache
/// </summary>
private readonly Dictionary<int, clsScanInfo> mCachedScanInfo = new Dictionary<int, clsScanInfo>();
/// <summary>
/// This linked list tracks the scan numbers stored in mCachedScanInfo,
/// allowing for quickly determining the oldest scan added to the cache when the cache limit is reached
/// </summary>
private readonly LinkedList<int> mCachedScans = new LinkedList<int>();
/// <summary>
/// Reader that implements ThermoFisher.CommonCore.Data.Interfaces.IRawDataPlus
/// </summary>
private IRawDataPlus mXRawFile;
/// <summary>
/// Cached file header
/// </summary>
private IFileHeader mXRawFileHeader;
private bool mCorruptMemoryEncountered;
private static readonly Regex mFindMS = new Regex(MS2_REGEX, RegexOptions.IgnoreCase | RegexOptions.Compiled);
private static readonly Regex mIonMode = new Regex(ION_MODE_REGEX, RegexOptions.Compiled);
private static readonly Regex mMassList = new Regex(MASS_LIST_REGEX, RegexOptions.Compiled);
private static readonly Regex mMassRanges = new Regex(MASS_RANGES_REGEX, RegexOptions.Compiled);
private static readonly Regex mFindParentIon = new Regex(PARENT_ION_REGEX, RegexOptions.IgnoreCase | RegexOptions.Compiled);
private static readonly Regex mFindParentIonOnlyNonMsx = new Regex(PARENT_ION_ONLY_NON_MSX_REGEX, RegexOptions.IgnoreCase | RegexOptions.Compiled);
private static readonly Regex mFindParentIonOnlyMsx = new Regex(PARENT_ION_ONLY_MSX_REGEX, RegexOptions.IgnoreCase | RegexOptions.Compiled);
private static readonly Regex mFindSAFullMS = new Regex(SA_REGEX, RegexOptions.IgnoreCase | RegexOptions.Compiled);
private static readonly Regex mFindFullMSx = new Regex(MSX_REGEX, RegexOptions.IgnoreCase | RegexOptions.Compiled);
private static readonly Regex mCollisionSpecs = new Regex(COLLISION_SPEC_REGEX, RegexOptions.Compiled);
private static readonly Regex mMzWithoutCE = new Regex(MZ_WITHOUT_COLLISION_ENERGY, RegexOptions.Compiled);
#endregion
#region "Properties"
/// <summary>
/// File info for the currently loaded .raw file
/// </summary>
public RawFileInfo FileInfo { get; } = new RawFileInfo();
/// <summary>
/// Thermo reader options
/// </summary>
public ThermoReaderOptions Options { get; }
/// <summary>
/// Maximum number of scan metadata cached; defaults to 50000
/// </summary>
/// <remarks>Set to 0 to disable caching</remarks>
public int ScanInfoCacheMaxSize
{
get => mMaxScansToCacheInfo;
set
{
mMaxScansToCacheInfo = value;
if (mMaxScansToCacheInfo <= 0)
{
mMaxScansToCacheInfo = 0;
}
if (mCachedScanInfo.Count <= 0)
return;
if (mMaxScansToCacheInfo == 0)
{
mCachedScanInfo.Clear();
mCachedScans.Clear();
}
else
{
RemoveCachedScanInfoOverLimit(mMaxScansToCacheInfo);
}
}
}
/// <summary>
/// First scan number in the .Raw file
/// </summary>
public int ScanStart => FileInfo.ScanStart;
/// <summary>
/// Last scan number in the .Raw file
/// </summary>
public int ScanEnd => FileInfo.ScanEnd;
/// <summary>
/// When true, additional messages are reported via Debug events
/// </summary>
public bool TraceMode { get; set; }
#endregion
#region "Events"
#pragma warning disable 618
/// <summary>
/// Event handler for reporting error messages
/// </summary>
[Obsolete("Subscribe to ErrorEvent")]
public event ReportErrorEventHandler ReportError;
/// <summary>
/// Event handler delegate for reporting error messages
/// </summary>
/// <param name="message"></param>
[Obsolete("Used by obsolete event ReportError")]
public delegate void ReportErrorEventHandler(string message);
/// <summary>
/// Event handler for reporting warning messages
/// </summary>
[Obsolete("Subscribe to WarningEvent")]
public event ReportWarningEventHandler ReportWarning;
/// <summary>
/// Event handler delegate for reporting warning messages
/// </summary>
/// <param name="message"></param>
[Obsolete("Used by obsolete event ReportWarning")]
public delegate void ReportWarningEventHandler(string message);
#pragma warning restore 618
/// <summary>
/// Report an error message to the error event handler
/// </summary>
/// <param name="message"></param>
/// <param name="ex">Optional exception</param>
private void RaiseErrorMessage(string message, Exception ex = null)
{
OnErrorEvent(message, ex);
#pragma warning disable 618
ReportError?.Invoke(message);
#pragma warning restore 618
}
/// <summary>
/// Report a warning message to the warning event handler
/// </summary>
/// <param name="message"></param>
private void RaiseWarningMessage(string message)
{
OnWarningEvent(message);
#pragma warning disable 618
ReportWarning?.Invoke(message);
#pragma warning restore 618
}
#endregion
private void CacheScanInfo(int scan, clsScanInfo scanInfo)
{
if (ScanInfoCacheMaxSize == 0)
{
return;
}
if (mCachedScanInfo.ContainsKey(scan))
{
// Updating an existing item
mCachedScanInfo.Remove(scan);
mCachedScans.Remove(scan);
}
RemoveCachedScanInfoOverLimit(mMaxScansToCacheInfo - 1);
mCachedScanInfo.Add(scan, scanInfo);
mCachedScans.AddLast(scan);
}
private void RemoveCachedScanInfoOverLimit(int limit)
{
if (mCachedScanInfo.Count <= limit)
return;
// Remove the oldest entry/entries in mCachedScanInfo
while (mCachedScanInfo.Count > limit)
{
var scan = mCachedScans.First();
mCachedScans.RemoveFirst();
if (mCachedScanInfo.ContainsKey(scan))
{
mCachedScanInfo.Remove(scan);
}
}
}
private static string CapitalizeCollisionMode(string collisionMode)
{
if (string.Equals(collisionMode, "EThcD", StringComparison.InvariantCultureIgnoreCase))
{
return "EThcD";
}
if (string.Equals(collisionMode, "ETciD", StringComparison.InvariantCultureIgnoreCase))
{
return "ETciD";
}
return collisionMode.ToUpper();
}
/// <summary>
/// Test the functionality of the reader - can we instantiate the MSFileReader Object?
/// </summary>
/// <returns></returns>
[Obsolete("Use 'IsMSFileReaderInstalled' instead.")]
public bool CheckFunctionality()
{
if (!IsMSFileReaderInstalled())
{
return false;
}
return true;
}
/// <summary>
/// Tests to see if we can load the needed Thermo MSFileReader DLL class without errors
/// </summary>
/// <returns></returns>
// ReSharper disable once InconsistentNaming
[Obsolete("This method checks for MSFileReader.XRawFile, but we now use ThermoFisher.CommonCore.Data.dll, so this method always returns true")]
public bool IsMSFileReaderInstalled()
{
var result = IsMSFileReaderInstalled(out var error);
if (!string.IsNullOrWhiteSpace(error))
{
RaiseErrorMessage(error);
}
return result;
}
/// <summary>
/// Tests to see if we can load the needed Thermo MSFileReader DLL class without errors
/// </summary>
/// <param name="error">Reason for failure</param>
/// <returns></returns>
// ReSharper disable once InconsistentNaming
[Obsolete("This method checks for MSFileReader.XRawFile, but we now use ThermoFisher.CommonCore.Data.dll, so this method always returns true")]
public static bool IsMSFileReaderInstalled(out string error)
{
error = "";
return true;
// ReSharper disable once HeuristicUnreachableCode
#pragma warning disable CS0162 // Unreachable code detected
var typeAvailable = false;
var canInstantiateType = false;
var bitness = "x86";
if (Environment.Is64BitProcess)
{
bitness = "x64";
}
try
{
//Assembly.Load("Interop.MSFileReaderLib"); // by name; is a COM library
// TypeLib CLSID GUID {F0C5F3E3-4F2A-443E-A74D-0AABE3237494}
// Class XRawfile CLSID GUID {1d23188d-53fe-4c25-b032-dc70acdbdc02}
//var type = Type.GetTypeFromCLSID(new Guid("{1d23188d-53fe-4c25-b032-dc70acdbdc02}"), true); // always returns a com object
var type = Type.GetTypeFromProgID("MSFileReader.XRawfile"); // Returns null if exact name isn't found.
if (type != null)
{
typeAvailable = true;
// Probably enough to just check for being able to get the type
//return true;
// This just becomes an extra sanity check
var obj = Activator.CreateInstance(type);
if (obj != null)
{
canInstantiateType = true;
return true;
}
}
}
catch (Exception)
{
if (typeAvailable && !canInstantiateType)
{
error = "MSFileReader is installed, but not for this platform. Install MSFileReader " + bitness;
}
else
{
error = "MSFileReader is not installed. Install MSFileReader " + bitness;
}
return false;
}
return false;
#pragma warning restore CS0162 // Unreachable code detected
}
/// <summary>
/// Close the .raw file
/// </summary>
public void CloseRawFile()
{
try
{
mXRawFile?.Dispose();
mCorruptMemoryEncountered = false;
}
catch (AccessViolationException)
{
// Ignore this error
}
catch (Exception)
{
// Ignore any errors
}
finally
{
mXRawFile = null;
mCachedFilePath = string.Empty;
FileInfo.Clear();
}
}
private static bool ContainsAny(string stringToSearch, IEnumerable<string> itemsToFind, int indexSearchStart = 0)
{
return itemsToFind.Any(item => ContainsText(stringToSearch, item, indexSearchStart));
}
private static bool ContainsText(string stringToSearch, string textToFind, int indexSearchStart = 0)
{
// Note: need to append a space since many of the search keywords end in a space
if ((stringToSearch + " ").IndexOf(textToFind, StringComparison.InvariantCultureIgnoreCase) >= indexSearchStart)
{
return true;
}
return false;
}
/// <summary>
/// Determines the MRM scan type by parsing the scan filter string
/// </summary>
/// <param name="filterText"></param>
/// <returns>MRM scan type enum</returns>
public static MRMScanTypeConstants DetermineMRMScanType(string filterText)
{
var eMRMScanType = MRMScanTypeConstants.NotMRM;
if (string.IsNullOrWhiteSpace(filterText))
{
return eMRMScanType;
}
var mrmQMSTags = new List<string> {
MRM_Q1MS_TEXT,
MRM_Q3MS_TEXT
};
if (ContainsAny(filterText, mrmQMSTags, 1))
{
eMRMScanType = MRMScanTypeConstants.MRMQMS;
}
else if (ContainsText(filterText, MRM_SRM_TEXT, 1))
{
eMRMScanType = MRMScanTypeConstants.SRM;
}
else if (ContainsText(filterText, MRM_SIM_PR_TEXT, 1))
{
// This is not technically SRM, but the data looks very similar, so we'll track it like SRM data
eMRMScanType = MRMScanTypeConstants.SRM;
}
else if (ContainsText(filterText, MRM_FullNL_TEXT, 1))
{
eMRMScanType = MRMScanTypeConstants.FullNL;
}
else if (ContainsText(filterText, SIM_MS_TEXT, 1))
{
eMRMScanType = MRMScanTypeConstants.SIM;
}
return eMRMScanType;
}
/// <summary>
/// Determine the Ionization mode by parsing the scan filter string
/// </summary>
/// <param name="filterText"></param>
/// <returns></returns>
public static IonModeConstants DetermineIonizationMode(string filterText)
{
// Determine the ion mode by simply looking for the first + or - sign
var ionMode = IonModeConstants.Unknown;
if (string.IsNullOrWhiteSpace(filterText))
{
return ionMode;
}
// For safety, remove any text after a square bracket
var charIndex = filterText.IndexOf('[');
Match reMatch;
if (charIndex > 0)
{
reMatch = mIonMode.Match(filterText.Substring(0, charIndex));
}
else
{
reMatch = mIonMode.Match(filterText);
}
if (reMatch.Success)
{
switch (reMatch.Value)
{
case "+":
ionMode = IonModeConstants.Positive;
break;
case "-":
ionMode = IonModeConstants.Negative;
break;
default:
ionMode = IonModeConstants.Unknown;
break;
}
}
return ionMode;
}
/// <summary>
/// Parse out the MRM_QMS or SRM mass info from filterText
/// </summary>
/// <param name="filterText"></param>
/// <param name="mrmScanType"></param>
/// <param name="mrmInfo">Output: MRM info class</param>
/// <remarks>We do not parse mass information out for Full Neutral Loss scans</remarks>
public static void ExtractMRMMasses(string filterText, MRMScanTypeConstants mrmScanType, out MRMInfo mrmInfo)
{
// Parse out the MRM_QMS or SRM mass info from filterText
// It should be of the form
// SIM: p NSI SIM ms [330.00-380.00]
// or
// MRM_Q1MS_TEXT: p NSI Q1MS [179.652-184.582, 505.778-510.708, 994.968-999.898]
// or
// MRM_Q3MS_TEXT: p NSI Q3MS [150.070-1500.000]
// or
// MRM_SRM_TEXT: c NSI SRM ms2 [email protected] [397.209-392.211, 579.289-579.291]
// Note: we do not parse mass information out for Full Neutral Loss scans
// MRM_FullNL_TEXT: c NSI Full cnl 162.053 [300.000-1200.000]
mrmInfo = new MRMInfo();
if (string.IsNullOrWhiteSpace(filterText))
{
return;
}
if (!(mrmScanType == MRMScanTypeConstants.SIM |
mrmScanType == MRMScanTypeConstants.MRMQMS |
mrmScanType == MRMScanTypeConstants.SRM))
{
// Unsupported MRM type
return;
}
// Parse out the text between the square brackets
var reMatch = mMassList.Match(filterText);
if (!reMatch.Success)
{
return;
}
reMatch = mMassRanges.Match(reMatch.Value);
while (reMatch.Success)
{
try
{
// Note that group 0 is the full mass range (two mass values, separated by a dash)
// Group 1 is the first mass value
// Group 2 is the second mass value
var mrmMassRange = new udtMRMMassRangeType
{
StartMass = double.Parse(reMatch.Groups["StartMass"].Value),
EndMass = double.Parse(reMatch.Groups["EndMass"].Value)
};
var centralMass = mrmMassRange.StartMass + (mrmMassRange.EndMass - mrmMassRange.StartMass) / 2;
mrmMassRange.CentralMass = Math.Round(centralMass, 6);
mrmInfo.MRMMassList.Add(mrmMassRange);
}
catch (Exception)
{
// Error parsing out the mass values; skip this group
}
reMatch = reMatch.NextMatch();
}
}
/// <summary>
/// Parse out the parent ion from filterText
/// </summary>
/// <param name="filterText"></param>
/// <param name="parentIonMz">Parent ion m/z (output)</param>
/// <returns>True if success</returns>
/// <remarks>If multiple parent ion m/z values are listed then parentIonMz will have the last one. However, if the filter text contains "Full msx" then parentIonMz will have the first parent ion listed</remarks>
/// <remarks>
/// This was created for use in other programs that only need the parent ion m/z, and no other functions from ThermoRawFileReader.
/// Other projects that use this:
/// PHRPReader (https://github.com/PNNL-Comp-Mass-Spec/PHRP)
///
/// To copy this, take the code from this function, plus the regex strings <see cref="PARENT_ION_ONLY_NON_MSX_REGEX"/> and <see cref="PARENT_ION_ONLY_MSX_REGEX"/>,
/// with their uses in <see cref="mFindParentIonOnlyNonMsx"/> and <see cref="mFindParentIonOnlyMsx"/>
/// </remarks>
public static bool ExtractParentIonMZFromFilterText(string filterText, out double parentIonMz)
{
Regex matcher;
if (filterText.ToLower().Contains("msx"))
{
matcher = mFindParentIonOnlyMsx;
}
else
{
matcher = mFindParentIonOnlyNonMsx;
}
var match = matcher.Match(filterText);
if (match.Success)
{
var parentIonMzText = match.Groups["ParentMZ"].Value;
var success = double.TryParse(parentIonMzText, out parentIonMz);
return success;
}
parentIonMz = 0;
return false;
}
/// <summary>
/// Parse out the parent ion and collision energy from filterText
/// </summary>
/// <param name="filterText"></param>
/// <param name="parentIonMz">Parent ion m/z (output)</param>
/// <param name="msLevel">MSLevel (output)</param>
/// <param name="collisionMode">Collision mode (output)</param>
/// <returns>True if success</returns>
/// <remarks>If multiple parent ion m/z values are listed then parentIonMz will have the last one. However, if the filter text contains "Full msx" then parentIonMz will have the first parent ion listed</remarks>
public static bool ExtractParentIonMZFromFilterText(string filterText, out double parentIonMz, out int msLevel, out string collisionMode)
{
return ExtractParentIonMZFromFilterText(filterText, out parentIonMz, out msLevel, out collisionMode, out _);
}
/// <summary>
/// Parse out the parent ion and collision energy from filterText
/// </summary>
/// <param name="filterText"></param>
/// <param name="parentIonMz">Parent ion m/z (output)</param>
/// <param name="msLevel">MSLevel (output)</param>
/// <param name="collisionMode">Collision mode (output)</param>
/// <param name="parentIons">Output: parent ion list</param>
/// <returns>True if success</returns>
/// <remarks>If multiple parent ion m/z values are listed then parentIonMz will have the last one. However, if the filter text contains "Full msx" then parentIonMz will have the first parent ion listed</remarks>
public static bool ExtractParentIonMZFromFilterText(
string filterText,
out double parentIonMz,
out int msLevel,
out string collisionMode,
out List<udtParentIonInfoType> parentIons)
{
// filterText should be of the form "+ c d Full ms2 [email protected] [ 350.00-2000.00]"
// or "+ c d Full ms3 [email protected] [email protected] [ 350.00-2000.00]"
// or "ITMS + c NSI d Full ms10 [email protected]"
// or "ITMS + c NSI d sa Full ms2 [email protected] [50.00-1880.00]" ' Note: sa stands for "supplemental activation"
// or "ITMS + c NSI d Full ms2 [email protected] [50.00-1880.00]"
// or "ITMS + c NSI d Full ms2 [email protected] [195.00-2000.00]"
// or "ITMS + c NSI d Full ms2 [email protected] [50.00-2000.00]"
// or "ITMS + c ESI d Full ms2 [email protected] [50.00-2000.00]"
// or "FTMS + p NSI Full ms [400.00-2000.00]" (high res full MS)
// or "ITMS + c ESI Full ms [300.00-2000.00]" (low res full MS)
// or "ITMS + p ESI d Z ms [1108.00-1118.00]" (zoom scan)
// or "+ p ms2 [email protected] [210.00-1200.00]
// or "+ c NSI SRM ms2 [email protected] [507.259-507.261, 635-319-635.32]
// or "FTMS + p NSI d Full msx ms2 [email protected] [email protected] [100.00-1475.00]"
// or "ITMS + c NSI r d sa Full ms2 [email protected]@cid20.00 [120.0000-2000.0000]"
// or "+ c NSI SRM ms2 748.371 [701.368-701.370, 773.402-773.404, 887.484-887.486, 975.513-975.515"
var bestParentIon = new udtParentIonInfoType();
bestParentIon.Clear();
msLevel = 1;
parentIonMz = 0;
collisionMode = string.Empty;
var matchFound = false;
parentIons = new List<udtParentIonInfoType>();
try
{
var supplementalActivationEnabled = mFindSAFullMS.IsMatch(filterText);
var multiplexedMSnEnabled = mFindFullMSx.IsMatch(filterText);
var success = ExtractMSLevel(filterText, out msLevel, out var mzText);
if (!success)
{
return false;
}
// Use a RegEx to extract out the last parent ion mass listed
// For example, grab 1312.95 out of "[email protected] [ 350.00-2000.00]"
// or, grab 873.85 out of "[email protected] [email protected] [ 350.00-2000.00]"
// or, grab 756.98 out of "[email protected] [50.00-2000.00]"
// or, grab 748.371 out of "748.371 [701.368-701.370, 773.402-773.404, 887.484-887.486, 975.513-975.515"
//
// However, if using multiplex ms/ms (msx) then we return the first parent ion listed
// For safety, remove any text after a square bracket
var bracketIndex = mzText.IndexOf('[');
if (bracketIndex > 0)
{
mzText = mzText.Substring(0, bracketIndex);
}
// Find all of the parent ion m/z's present in mzText
var startIndex = 0;
do
{
var reMatchParentIon = mFindParentIon.Match(mzText, startIndex);
if (!reMatchParentIon.Success)
{
// Match not found
// If mzText only contains a number, we will parse it out later in this function
break;
}
// Match found
parentIonMz = double.Parse(reMatchParentIon.Groups["ParentMZ"].Value);
collisionMode = string.Empty;
float collisionEnergyValue = 0;
matchFound = true;
startIndex = reMatchParentIon.Index + reMatchParentIon.Length;
collisionMode = GetCapturedValue(reMatchParentIon, "CollisionMode1");
var collisionEnergy = GetCapturedValue(reMatchParentIon, "CollisionEnergy1");
if (!string.IsNullOrWhiteSpace(collisionEnergy))
{
float.TryParse(collisionEnergy, out collisionEnergyValue);
}
float collisionEnergy2Value = 0;
var collisionMode2 = GetCapturedValue(reMatchParentIon, "CollisionMode2");
if (!string.IsNullOrWhiteSpace(collisionMode2))
{
var collisionEnergy2 = GetCapturedValue(reMatchParentIon, "CollisionEnergy2");
float.TryParse(collisionEnergy2, out collisionEnergy2Value);
}
var allowSecondaryActivation = true;
if (string.Equals(collisionMode, "ETD", StringComparison.InvariantCultureIgnoreCase) & !string.IsNullOrWhiteSpace(collisionMode2))
{
if (string.Equals(collisionMode2, "CID", StringComparison.InvariantCultureIgnoreCase))
{
collisionMode = "ETciD";
allowSecondaryActivation = false;
}
else if (string.Equals(collisionMode2, "HCD", StringComparison.InvariantCultureIgnoreCase))
{
collisionMode = "EThcD";
allowSecondaryActivation = false;
}
}
if (allowSecondaryActivation && !string.IsNullOrWhiteSpace(collisionMode))
{
if (supplementalActivationEnabled)
{
collisionMode = "sa_" + collisionMode;
}
}
var parentIonInfo = new udtParentIonInfoType
{
MSLevel = msLevel,
ParentIonMZ = parentIonMz,
CollisionEnergy = collisionEnergyValue,
CollisionEnergy2 = collisionEnergy2Value
};
if (collisionMode != null)
parentIonInfo.CollisionMode = string.Copy(collisionMode);
if (collisionMode2 != null)
parentIonInfo.CollisionMode2 = string.Copy(collisionMode2);
parentIons.Add(parentIonInfo);
if (!multiplexedMSnEnabled || parentIons.Count == 1)
{
bestParentIon = parentIonInfo;
}
} while (startIndex < mzText.Length - 1);
if (matchFound)
{
// Update the output values using bestParentIon
msLevel = bestParentIon.MSLevel;
parentIonMz = bestParentIon.ParentIonMZ;
collisionMode = bestParentIon.CollisionMode;
return true;
}
// Match not found using RegEx
// Use manual text parsing instead
var atIndex = mzText.LastIndexOf('@');
if (atIndex > 0)
{
mzText = mzText.Substring(0, atIndex);
var spaceIndex = mzText.LastIndexOf(' ');
if (spaceIndex > 0)
{
mzText = mzText.Substring(spaceIndex + 1);
}
try
{
parentIonMz = double.Parse(mzText);
matchFound = true;
}
catch (Exception)
{
parentIonMz = 0;
}
}
else if (mzText.Length > 0)
{
// Find the longest contiguous number that mzText starts with
var charIndex = -1;
while (charIndex < mzText.Length - 1)
{
if (char.IsNumber(mzText[charIndex + 1]) || mzText[charIndex + 1] == '.')
{
charIndex += 1;
}
else
{
break;
}
}
if (charIndex >= 0)
{
try
{
parentIonMz = double.Parse(mzText.Substring(0, charIndex + 1));
matchFound = true;
var parentIonMzOnly = new udtParentIonInfoType();
parentIonMzOnly.Clear();
parentIonMzOnly.MSLevel = msLevel;
parentIonMzOnly.ParentIonMZ = parentIonMz;
parentIons.Add(parentIonMzOnly);
}
catch (Exception)
{
parentIonMz = 0;
}
}
}
}
catch (Exception)
{
matchFound = false;
}
return matchFound;
}
/// <summary>
/// Extract the MS Level from the filter string
/// </summary>
/// <param name="filterText"></param>
/// <param name="msLevel"></param>
/// <param name="mzText"></param>
/// <returns>True if found and False if no match</returns>
/// <remarks>
/// Looks for "Full ms2" or "Full ms3" or " p ms2" or "SRM ms2" in filterText
/// Populates msLevel with the number after "ms" and mzText with the text after "ms2"
/// </remarks>
public static bool ExtractMSLevel(string filterText, out int msLevel, out string mzText)
{
var matchTextLength = 0;
msLevel = 1;
var charIndex = 0;
var reMatchMS = mFindMS.Match(filterText);
if (reMatchMS.Success)
{
msLevel = Convert.ToInt32(reMatchMS.Groups["MSLevel"].Value);
charIndex = filterText.IndexOf(reMatchMS.ToString(), StringComparison.InvariantCultureIgnoreCase);
matchTextLength = reMatchMS.Length;
}
if (charIndex > 0)
{
// Copy the text after "Full ms2" or "Full ms3" in filterText to mzText
mzText = filterText.Substring(charIndex + matchTextLength).Trim();
return true;
}
mzText = string.Empty;
return false;
}
/// <summary>
/// Populate mFileInfo
/// </summary>
/// <returns>True if no error, False if an error</returns>
private bool FillFileInfo()
{
try
{
if (mXRawFile == null)
return false;