forked from PNNL-Comp-Mass-Spec/MASIC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
clsSICProcessing.cs
1345 lines (1157 loc) · 62.4 KB
/
clsSICProcessing.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.Generic;
using System.Linq;
using MASIC.DataOutput;
using MASICPeakFinder;
namespace MASIC
{
public class clsSICProcessing : clsMasicEventNotifier
{
private const string CREATING_SICS = "Creating SIC's for parent ions";
private readonly clsMASICPeakFinder mMASICPeakFinder;
private readonly clsMRMProcessing mMRMProcessor;
/// <summary>
/// Constructor
/// </summary>
public clsSICProcessing(clsMASICPeakFinder peakFinder, clsMRMProcessing mrmProcessor)
{
mMASICPeakFinder = peakFinder;
mMRMProcessor = mrmProcessor;
}
private static short ComputeMzSearchChunkProgress(
int parentIonsProcessed, int parentIonsCount,
int surveyScanIndex, int surveyScansCount,
double mzSearchChunkProgressFraction)
{
var progressAddon = surveyScanIndex / (double)surveyScansCount * mzSearchChunkProgressFraction * 100;
if (parentIonsCount < 1)
{
return (short)Math.Round(progressAddon, 0);
}
var percentComplete = parentIonsProcessed / (double)(parentIonsCount - 1) * 100 + progressAddon;
return (short)Math.Round(percentComplete, 0);
}
private static List<clsMzBinInfo> CreateMZLookupList(
clsMASICOptions masicOptions,
clsScanList scanList,
bool processSIMScans,
int simIndex)
{
var mzBinList = new List<clsMzBinInfo>(scanList.ParentIons.Count);
var sicOptions = masicOptions.SICOptions;
for (var parentIonIndex = 0; parentIonIndex < scanList.ParentIons.Count; parentIonIndex++)
{
bool includeParentIon;
if (scanList.ParentIons[parentIonIndex].MRMDaughterMZ > 0)
{
includeParentIon = false;
}
else if (masicOptions.CustomSICList.LimitSearchToCustomMZList)
{
// Always include CustomSICPeak entries
includeParentIon = scanList.ParentIons[parentIonIndex].CustomSICPeak;
}
else
{
// Use processingSIMScans and .SIMScan to decide whether or not to include the entry
var surveyScan = scanList.SurveyScans[scanList.ParentIons[parentIonIndex].SurveyScanIndex];
if (processSIMScans)
{
if (surveyScan.SIMScan)
{
if (surveyScan.SIMIndex == simIndex)
{
includeParentIon = true;
}
else
{
includeParentIon = false;
}
}
else
{
includeParentIon = false;
}
}
else
{
includeParentIon = !surveyScan.SIMScan;
}
}
if (includeParentIon)
{
var newMzBin = new clsMzBinInfo()
{
MZ = scanList.ParentIons[parentIonIndex].MZ,
ParentIonIndex = parentIonIndex
};
if (scanList.ParentIons[parentIonIndex].CustomSICPeak)
{
newMzBin.MZTolerance = scanList.ParentIons[parentIonIndex].CustomSICPeakMZToleranceDa;
newMzBin.MZToleranceIsPPM = false;
}
else
{
newMzBin.MZTolerance = sicOptions.SICTolerance;
newMzBin.MZToleranceIsPPM = sicOptions.SICToleranceIsPPM;
}
mzBinList.Add(newMzBin);
}
}
// Sort mzBinList by m/z
var sortedMzBins = mzBinList.OrderBy(item => item.MZ).ToList();
return sortedMzBins;
}
/// <summary>
/// Create selected ion chromatograms for the parent ions
/// </summary>
/// <param name="scanList"></param>
/// <param name="spectraCache"></param>
/// <param name="masicOptions"></param>
/// <param name="dataOutputHandler"></param>
/// <param name="sicProcessor"></param>
/// <param name="xmlResultsWriter"></param>
/// <returns></returns>
public bool CreateParentIonSICs(
clsScanList scanList,
clsSpectraCache spectraCache,
clsMASICOptions masicOptions,
clsDataOutput dataOutputHandler,
clsSICProcessing sicProcessor,
clsXMLResultsWriter xmlResultsWriter)
{
var success = false;
if (scanList.ParentIons.Count <= 0)
{
// No parent ions
if (masicOptions.SuppressNoParentIonsError)
{
return true;
}
SetLocalErrorCode(clsMASIC.eMasicErrorCodes.NoParentIonsFoundInInputFile);
return false;
}
if (scanList.SurveyScans.Count <= 0)
{
// No survey scans
if (masicOptions.SuppressNoParentIonsError)
{
return true;
}
SetLocalErrorCode(clsMASIC.eMasicErrorCodes.NoSurveyScansFoundInInputFile);
return false;
}
try
{
var parentIonsProcessed = 0;
masicOptions.LastParentIonProcessingLogTime = DateTime.UtcNow;
UpdateProgress(0, CREATING_SICS);
Console.Write(CREATING_SICS);
ReportMessage(CREATING_SICS);
// Create an array of m/z values in scanList.ParentIons, then sort by m/z
// Next, step through the data in order of m/z, creating SICs for each grouping of m/z's within half of the SIC tolerance
// First process the non SIM, non MRM scans
// If this file only has MRM scans, then CreateMZLookupList will return False
var mzBinList = CreateMZLookupList(masicOptions, scanList, false, 0);
if (mzBinList.Count > 0)
{
success = ProcessMZList(scanList, spectraCache, masicOptions,
dataOutputHandler, xmlResultsWriter,
mzBinList, false, 0, ref parentIonsProcessed);
}
if (success && !masicOptions.CustomSICList.LimitSearchToCustomMZList)
{
// Now process the SIM scans (if any)
// First, see if any SIMScans are present and determine the maximum SIM Index
var simIndexMax = -1;
foreach (var parentIon in scanList.ParentIons)
{
var surveyScan = scanList.SurveyScans[parentIon.SurveyScanIndex];
if (surveyScan.SIMScan)
{
if (surveyScan.SIMIndex > simIndexMax)
{
simIndexMax = surveyScan.SIMIndex;
}
}
}
// Now process each SIM Scan type
for (var simIndex = 0; simIndex <= simIndexMax; simIndex++)
{
var mzBinListSIM = CreateMZLookupList(masicOptions, scanList, true, simIndex);
if (mzBinListSIM.Count > 0)
{
ProcessMZList(scanList, spectraCache, masicOptions,
dataOutputHandler, xmlResultsWriter,
mzBinListSIM, true, simIndex, ref parentIonsProcessed);
}
}
}
// Lastly, process the MRM scans (if any)
if (scanList.MRMDataPresent)
{
mMRMProcessor.ProcessMRMList(scanList, spectraCache, sicProcessor, xmlResultsWriter, mMASICPeakFinder, ref parentIonsProcessed);
}
Console.WriteLine();
return true;
}
catch (Exception ex)
{
ReportError("Error creating Parent Ion SICs", ex, clsMASIC.eMasicErrorCodes.CreateSICsError);
return false;
}
}
private clsSICStatsPeak ExtractSICDetailsFromFullSIC(
int mzIndexWork,
List<clsBaselineNoiseStatsSegment> baselineNoiseStatSegments,
int fullSICDataCount,
int[,] fullSICScanIndices,
double[,] fullSICIntensities,
double[,] fullSICMasses,
clsScanList scanList,
int scanIndexObservedInFullSIC,
clsSICDetails sicDetails,
clsMASICOptions masicOptions,
clsScanNumScanTimeConversion scanNumScanConverter,
bool customSICPeak,
float customSICPeakScanOrAcqTimeTolerance)
{
// Minimum number of scans to extend left or right of the scan that meets the minimum intensity threshold requirement
const int MINIMUM_NOISE_SCANS_TO_INCLUDE = 10;
float customSICScanToleranceMinutesHalfWidth = 0;
// Pointers to entries in fullSICScanIndices() and fullSICIntensities()
int scanIndexStart = 0, scanIndexEnd = 0;
var maximumIntensity = 0.0;
var sicOptions = masicOptions.SICOptions;
var baselineNoiseStats = mMASICPeakFinder.LookupNoiseStatsUsingSegments(scanIndexObservedInFullSIC, baselineNoiseStatSegments);
// Initialize the peak
var sicPeak = new clsSICStatsPeak()
{
BaselineNoiseStats = baselineNoiseStats
};
// Initialize the values for the maximum width of the SIC peak; these might get altered for custom SIC values
var maxSICPeakWidthMinutesBackward = sicOptions.MaxSICPeakWidthMinutesBackward;
var maxSICPeakWidthMinutesForward = sicOptions.MaxSICPeakWidthMinutesForward;
// Limit the data examined to a portion of fullSICScanIndices() and fullSICIntensities, populating udtSICDetails
try
{
// Initialize customSICScanToleranceHalfWidth
if (customSICPeakScanOrAcqTimeTolerance < float.Epsilon)
{
customSICPeakScanOrAcqTimeTolerance = masicOptions.CustomSICList.ScanOrAcqTimeTolerance;
}
if (customSICPeakScanOrAcqTimeTolerance < float.Epsilon)
{
// Use the entire SIC
// Specify this by setting customSICScanToleranceMinutesHalfWidth to the maximum scan time in .MasterScanTimeList()
if (scanList.MasterScanOrderCount > 0)
{
customSICScanToleranceMinutesHalfWidth = scanList.MasterScanTimeList[scanList.MasterScanOrderCount - 1];
}
else
{
customSICScanToleranceMinutesHalfWidth = float.MaxValue;
}
}
else
{
if (masicOptions.CustomSICList.ScanToleranceType == clsCustomSICList.eCustomSICScanTypeConstants.Relative && customSICPeakScanOrAcqTimeTolerance > 10)
{
// Relative scan time should only range from 0 to 1; we'll allow values up to 10
customSICPeakScanOrAcqTimeTolerance = 10;
}
customSICScanToleranceMinutesHalfWidth = scanNumScanConverter.ScanOrAcqTimeToScanTime(
scanList, customSICPeakScanOrAcqTimeTolerance / 2, masicOptions.CustomSICList.ScanToleranceType, true);
}
if (customSICPeak)
{
if (maxSICPeakWidthMinutesBackward < customSICScanToleranceMinutesHalfWidth)
{
maxSICPeakWidthMinutesBackward = customSICScanToleranceMinutesHalfWidth;
}
if (maxSICPeakWidthMinutesForward < customSICScanToleranceMinutesHalfWidth)
{
maxSICPeakWidthMinutesForward = customSICScanToleranceMinutesHalfWidth;
}
}
// Initially use just 3 survey scans, centered around scanIndexObservedInFullSIC
if (scanIndexObservedInFullSIC > 0)
{
scanIndexStart = scanIndexObservedInFullSIC - 1;
scanIndexEnd = scanIndexObservedInFullSIC + 1;
}
else
{
scanIndexStart = 0;
scanIndexEnd = 1;
scanIndexObservedInFullSIC = 0;
}
if (scanIndexEnd >= fullSICDataCount)
scanIndexEnd = fullSICDataCount - 1;
}
catch (Exception ex)
{
ReportError("Error initializing SIC start/end indices", ex, clsMASIC.eMasicErrorCodes.CreateSICsError);
}
if (scanIndexEnd >= scanIndexStart)
{
var scanIndexMax = 0;
try
{
// Start by using the 3 survey scans centered around scanIndexObservedInFullSIC
maximumIntensity = -1;
scanIndexMax = -1;
for (var scanIndex = scanIndexStart; scanIndex <= scanIndexEnd; scanIndex++)
{
if (fullSICIntensities[mzIndexWork, scanIndex] > maximumIntensity)
{
maximumIntensity = fullSICIntensities[mzIndexWork, scanIndex];
scanIndexMax = scanIndex;
}
}
}
catch (Exception ex)
{
ReportError("Error while creating initial SIC", ex, clsMASIC.eMasicErrorCodes.CreateSICsError);
}
// Now extend the SIC, stepping left and right until a threshold is reached
var leftDone = false;
var rightDone = false;
// The index of the first scan found to be below threshold (on the left)
var scanIndexBelowThresholdLeft = -1;
// The index of the first scan found to be below threshold (on the right)
var scanIndexBelowThresholdRight = -1;
while (scanIndexStart > 0 && !leftDone || scanIndexEnd < fullSICDataCount - 1 && !rightDone)
{
try
{
// Extend the SIC to the left until the threshold is reached
if (scanIndexStart > 0 && !leftDone)
{
if (fullSICIntensities[mzIndexWork, scanIndexStart] < sicOptions.SICPeakFinderOptions.IntensityThresholdAbsoluteMinimum ||
fullSICIntensities[mzIndexWork, scanIndexStart] < sicOptions.SICPeakFinderOptions.IntensityThresholdFractionMax * maximumIntensity ||
fullSICIntensities[mzIndexWork, scanIndexStart] < sicPeak.BaselineNoiseStats.NoiseLevel)
{
if (scanIndexBelowThresholdLeft < 0)
{
scanIndexBelowThresholdLeft = scanIndexStart;
}
else if (scanIndexStart <= scanIndexBelowThresholdLeft - MINIMUM_NOISE_SCANS_TO_INCLUDE)
{
// We have now processed MINIMUM_NOISE_SCANS_TO_INCLUDE+1 scans that are below the thresholds
// Stop creating the SIC to the left
leftDone = true;
}
}
else
{
scanIndexBelowThresholdLeft = -1;
}
var peakWidthMinutesBackward = scanList.SurveyScans[fullSICScanIndices[mzIndexWork, scanIndexObservedInFullSIC]].ScanTime -
scanList.SurveyScans[fullSICScanIndices[mzIndexWork, scanIndexStart]].ScanTime;
if (leftDone)
{
// Require a minimum distance of InitialPeakWidthScansMaximum data points to the left of scanIndexObservedInFullSIC and to the left of scanIndexMax
if (scanIndexObservedInFullSIC - scanIndexStart < sicOptions.SICPeakFinderOptions.InitialPeakWidthScansMaximum)
leftDone = false;
if (scanIndexMax - scanIndexStart < sicOptions.SICPeakFinderOptions.InitialPeakWidthScansMaximum)
leftDone = false;
// For custom SIC values, make sure the scan range has been satisfied
if (leftDone && customSICPeak)
{
if (peakWidthMinutesBackward < customSICScanToleranceMinutesHalfWidth)
{
leftDone = false;
}
}
}
if (!leftDone)
{
// ReSharper disable once ConditionIsAlwaysTrueOrFalse
if (scanIndexStart == 0)
{
leftDone = true;
}
else
{
scanIndexStart -= 1;
if (fullSICIntensities[mzIndexWork, scanIndexStart] > maximumIntensity)
{
maximumIntensity = fullSICIntensities[mzIndexWork, scanIndexStart];
scanIndexMax = scanIndexStart;
}
}
}
peakWidthMinutesBackward = scanList.SurveyScans[fullSICScanIndices[mzIndexWork, scanIndexObservedInFullSIC]].ScanTime -
scanList.SurveyScans[fullSICScanIndices[mzIndexWork, scanIndexStart]].ScanTime;
if (peakWidthMinutesBackward >= maxSICPeakWidthMinutesBackward)
{
leftDone = true;
}
}
}
catch (Exception ex)
{
ReportError("Error extending SIC to the left", ex, clsMASIC.eMasicErrorCodes.CreateSICsError);
}
try
{
// Extend the SIC to the right until the threshold is reached
if (scanIndexEnd < fullSICDataCount - 1 && !rightDone)
{
if (fullSICIntensities[mzIndexWork, scanIndexEnd] < sicOptions.SICPeakFinderOptions.IntensityThresholdAbsoluteMinimum ||
fullSICIntensities[mzIndexWork, scanIndexEnd] < sicOptions.SICPeakFinderOptions.IntensityThresholdFractionMax * maximumIntensity ||
fullSICIntensities[mzIndexWork, scanIndexEnd] < sicPeak.BaselineNoiseStats.NoiseLevel)
{
if (scanIndexBelowThresholdRight < 0)
{
scanIndexBelowThresholdRight = scanIndexEnd;
}
else if (scanIndexEnd >= scanIndexBelowThresholdRight + MINIMUM_NOISE_SCANS_TO_INCLUDE)
{
// We have now processed MINIMUM_NOISE_SCANS_TO_INCLUDE+1 scans that are below the thresholds
// Stop creating the SIC to the right
rightDone = true;
}
}
else
{
scanIndexBelowThresholdRight = -1;
}
var peakWidthMinutesForward = scanList.SurveyScans[fullSICScanIndices[mzIndexWork, scanIndexEnd]].ScanTime -
scanList.SurveyScans[fullSICScanIndices[mzIndexWork, scanIndexObservedInFullSIC]].ScanTime;
if (rightDone)
{
// Require a minimum distance of InitialPeakWidthScansMaximum data points to the right of scanIndexObservedInFullSIC and to the right of scanIndexMax
if (scanIndexEnd - scanIndexObservedInFullSIC < sicOptions.SICPeakFinderOptions.InitialPeakWidthScansMaximum)
rightDone = false;
if (scanIndexEnd - scanIndexMax < sicOptions.SICPeakFinderOptions.InitialPeakWidthScansMaximum)
rightDone = false;
// For custom SIC values, make sure the scan range has been satisfied
if (rightDone && customSICPeak)
{
if (peakWidthMinutesForward < customSICScanToleranceMinutesHalfWidth)
{
rightDone = false;
}
}
}
if (!rightDone)
{
if (scanIndexEnd == fullSICDataCount - 1)
{
rightDone = true;
}
else
{
scanIndexEnd += 1;
if (fullSICIntensities[mzIndexWork, scanIndexEnd] > maximumIntensity)
{
maximumIntensity = fullSICIntensities[mzIndexWork, scanIndexEnd];
scanIndexMax = scanIndexEnd;
}
}
}
peakWidthMinutesForward = scanList.SurveyScans[fullSICScanIndices[mzIndexWork, scanIndexEnd]].ScanTime -
scanList.SurveyScans[fullSICScanIndices[mzIndexWork, scanIndexObservedInFullSIC]].ScanTime;
if (peakWidthMinutesForward >= maxSICPeakWidthMinutesForward)
{
rightDone = true;
}
}
}
catch (Exception ex)
{
ReportError("Error extending SIC to the right", ex, clsMASIC.eMasicErrorCodes.CreateSICsError);
}
} // While Not LeftDone and Not RightDone
}
// Populate udtSICDetails with the data between scanIndexStart and scanIndexEnd
if (scanIndexStart < 0)
scanIndexStart = 0;
if (scanIndexEnd >= fullSICDataCount)
scanIndexEnd = fullSICDataCount - 1;
if (scanIndexEnd < scanIndexStart)
{
ReportError("Programming error: scanIndexEnd < scanIndexStart", clsMASIC.eMasicErrorCodes.FindSICPeaksError);
scanIndexEnd = scanIndexStart;
}
try
{
// Copy the scan index values from fullSICScanIndices to .SICScanIndices()
// Copy the intensity values from fullSICIntensities() to .SICData()
// Copy the mz values from fullSICMasses() to .SICMasses()
sicDetails.SICScanType = clsScanList.eScanTypeConstants.SurveyScan;
sicDetails.SICData.Clear();
sicPeak.IndexObserved = 0;
for (var scanIndex = scanIndexStart; scanIndex <= scanIndexEnd; scanIndex++)
{
if (fullSICScanIndices[mzIndexWork, scanIndex] >= 0)
{
sicDetails.AddData(scanList.SurveyScans[fullSICScanIndices[mzIndexWork, scanIndex]].ScanNumber,
fullSICIntensities[mzIndexWork, scanIndex],
fullSICMasses[mzIndexWork, scanIndex],
fullSICScanIndices[mzIndexWork, scanIndex]);
if (scanIndex == scanIndexObservedInFullSIC)
{
sicPeak.IndexObserved = sicDetails.SICDataCount - 1;
}
}
else
{
// This shouldn't happen
}
}
}
catch (Exception ex)
{
ReportError("Error populating .SICScanIndices, .SICData, and .SICMasses", ex, clsMASIC.eMasicErrorCodes.CreateSICsError);
}
return sicPeak;
}
private bool ProcessMZList(
clsScanList scanList,
clsSpectraCache spectraCache,
clsMASICOptions masicOptions,
clsDataOutput dataOutputHandler,
clsXMLResultsWriter xmlResultsWriter,
IReadOnlyList<clsMzBinInfo> mzBinList,
bool processSIMScans,
int simIndex,
ref int parentIonsProcessed)
{
// Step through the data in order of m/z, creating SICs for each grouping of m/z's within half of the SIC tolerance
// Note that mzBinList and parentIonIndices() are parallel arrays, with mzBinList() sorted on ascending m/z
const int MAX_RAW_DATA_MEMORY_USAGE_MB = 50;
int maxMZCountInChunk;
var mzSearchChunks = new List<clsMzSearchInfo>(mzBinList.Count);
bool[] parentIonUpdated;
try
{
// Determine the maximum number of m/z values to process simultaneously
// Limit the total memory usage to ~50 MB
// Each m/z value will require 12 bytes per scan
if (scanList.SurveyScans.Count > 0)
{
maxMZCountInChunk = (int)(MAX_RAW_DATA_MEMORY_USAGE_MB * 1024 * 1024 / (double)(scanList.SurveyScans.Count * 12));
}
else
{
maxMZCountInChunk = 1;
}
if (maxMZCountInChunk > mzBinList.Count)
{
maxMZCountInChunk = mzBinList.Count;
}
if (maxMZCountInChunk < 1)
maxMZCountInChunk = 1;
// Reserve room in parentIonUpdated
parentIonUpdated = new bool[mzBinList.Count];
}
catch (Exception ex)
{
ReportError("Error reserving memory for the m/z chunks", ex, clsMASIC.eMasicErrorCodes.CreateSICsError);
return false;
}
try
{
var dataAggregation = new clsDataAggregation();
RegisterEvents(dataAggregation);
var scanNumScanConverter = new clsScanNumScanTimeConversion();
RegisterEvents(scanNumScanConverter);
var parentIonIndices = (from item in mzBinList select item.ParentIonIndex).ToList();
var mzIndex = 0;
while (mzIndex < mzBinList.Count)
{
// ---------------------------------------------------------
// Find the next group of m/z values to use, starting with mzIndex
// ---------------------------------------------------------
// Initially set the MZIndexStart to mzIndex
// Look for adjacent m/z values within udtMZBinList(.MZIndexStart).MZToleranceDa / 2
// of the m/z value that starts this group
// Only group m/z values with the same udtMZBinList().MZTolerance and udtMZBinList().MZToleranceIsPPM values
var mzSearchChunk = new clsMzSearchInfo()
{
MZIndexStart = mzIndex,
MZTolerance = mzBinList[mzIndex].MZTolerance,
MZToleranceIsPPM = mzBinList[mzIndex].MZToleranceIsPPM
};
double mzToleranceDa;
if (mzSearchChunk.MZToleranceIsPPM)
{
mzToleranceDa = clsUtilities.PPMToMass(mzSearchChunk.MZTolerance, mzBinList[mzSearchChunk.MZIndexStart].MZ);
}
else
{
mzToleranceDa = mzSearchChunk.MZTolerance;
}
while (mzIndex < mzBinList.Count - 2 &&
Math.Abs(mzBinList[mzIndex + 1].MZTolerance - mzSearchChunk.MZTolerance) < double.Epsilon &&
mzBinList[mzIndex + 1].MZToleranceIsPPM == mzSearchChunk.MZToleranceIsPPM &&
mzBinList[mzIndex + 1].MZ - mzBinList[mzSearchChunk.MZIndexStart].MZ <= mzToleranceDa / 2)
mzIndex += 1;
mzSearchChunk.MZIndexEnd = mzIndex;
if (mzSearchChunk.MZIndexEnd == mzSearchChunk.MZIndexStart)
{
mzSearchChunk.MZIndexMidpoint = mzSearchChunk.MZIndexEnd;
mzSearchChunk.SearchMZ = mzBinList[mzSearchChunk.MZIndexStart].MZ;
}
// Determine the median m/z of the members in the m/z group
else if ((mzSearchChunk.MZIndexEnd - mzSearchChunk.MZIndexStart) % 2 == 0)
{
// Odd number of points; use the m/z value of the midpoint
mzSearchChunk.MZIndexMidpoint = mzSearchChunk.MZIndexStart + (int)Math.Round((mzSearchChunk.MZIndexEnd - mzSearchChunk.MZIndexStart) / (double)2);
mzSearchChunk.SearchMZ = mzBinList[mzSearchChunk.MZIndexMidpoint].MZ;
}
else
{
// Even number of points; average the values on either side of (.mzIndexEnd - .mzIndexStart / 2)
mzSearchChunk.MZIndexMidpoint = mzSearchChunk.MZIndexStart + (int)Math.Floor((mzSearchChunk.MZIndexEnd - mzSearchChunk.MZIndexStart) / 2.0);
mzSearchChunk.SearchMZ = (mzBinList[mzSearchChunk.MZIndexMidpoint].MZ + mzBinList[mzSearchChunk.MZIndexMidpoint + 1].MZ) / 2;
}
mzSearchChunks.Add(mzSearchChunk);
if (mzSearchChunks.Count >= maxMZCountInChunk || mzIndex == mzBinList.Count - 1)
{
// ---------------------------------------------------------
// Reached maxMZCountInChunk m/z value
// Process all of the m/z values in udtMZSearchChunk
// ---------------------------------------------------------
var mzSearchChunkProgressFraction = mzSearchChunks.Count / (double)mzBinList.Count;
var success = ProcessMzSearchChunk(
masicOptions,
scanList,
dataAggregation, dataOutputHandler, xmlResultsWriter,
spectraCache, scanNumScanConverter,
mzSearchChunks,
mzSearchChunkProgressFraction,
parentIonIndices,
processSIMScans,
simIndex,
parentIonUpdated,
ref parentIonsProcessed);
if (!success)
{
return false;
}
// Clear mzSearchChunks
mzSearchChunks.Clear();
}
if (masicOptions.AbortProcessing)
{
scanList.ProcessingIncomplete = true;
break;
}
mzIndex += 1;
}
return true;
}
catch (Exception ex)
{
ReportError("Error processing the m/z chunks to create the SIC data", ex, clsMASIC.eMasicErrorCodes.CreateSICsError);
return false;
}
}
private bool ProcessMzSearchChunk(
clsMASICOptions masicOptions,
clsScanList scanList,
clsDataAggregation dataAggregation,
clsDataOutput dataOutputHandler,
clsXMLResultsWriter xmlResultsWriter,
clsSpectraCache spectraCache,
clsScanNumScanTimeConversion scanNumScanConverter,
IReadOnlyList<clsMzSearchInfo> mzSearchChunk,
double mzSearchChunkProgressFraction,
IList<int> parentIonIndices,
bool processSIMScans,
int simIndex,
IList<bool> parentIonUpdated,
ref int parentIonsProcessed)
{
// The following are 2D arrays, ranging from 0 to mzSearchChunkCount-1 in the first dimension and 0 to .SurveyScans.Count - 1 in the second dimension
// We could have included these in udtMZSearchChunk but memory management is more efficient if I use 2D arrays for this data
// Reserve room in fullSICScanIndices for at most maxMZCountInChunk values and .SurveyScans.Count scans
// Count of the number of valid entries in the second dimension of the above 3 arrays
var fullSICDataCount = new int[mzSearchChunk.Count];
// Pointer into .SurveyScans
var fullSICScanIndices = new int[mzSearchChunk.Count, scanList.SurveyScans.Count];
var fullSICIntensities = new double[mzSearchChunk.Count, scanList.SurveyScans.Count];
var fullSICMasses = new double[mzSearchChunk.Count, scanList.SurveyScans.Count];
// The following is a 1D array, containing the SIC intensities for a single m/z group
var fullSICIntensities1D = new double[scanList.SurveyScans.Count];
// Initialize .MaximumIntensity and .ScanIndexMax
// Additionally, reset fullSICDataCount() and, for safety, set fullSICScanIndices() to -1
for (var mzIndexWork = 0; mzIndexWork < mzSearchChunk.Count; mzIndexWork++)
{
mzSearchChunk[mzIndexWork].ResetMaxIntensity();
fullSICDataCount[mzIndexWork] = 0;
for (var surveyScanIndex = 0; surveyScanIndex < scanList.SurveyScans.Count; surveyScanIndex++)
fullSICScanIndices[mzIndexWork, surveyScanIndex] = -1;
}
// ---------------------------------------------------------
// Step through scanList to obtain the scan numbers and intensity data for each .SearchMZ in udtMZSearchChunk
// We're stepping scan by scan since the process of loading a scan from disk is slower than the process of searching for each m/z in the scan
// ---------------------------------------------------------
for (var surveyScanIndex = 0; surveyScanIndex < scanList.SurveyScans.Count; surveyScanIndex++)
{
bool useScan;
if (processSIMScans)
{
if (scanList.SurveyScans[surveyScanIndex].SIMScan &&
scanList.SurveyScans[surveyScanIndex].SIMIndex == simIndex)
{
useScan = true;
}
else
{
useScan = false;
}
}
else
{
useScan = !scanList.SurveyScans[surveyScanIndex].SIMScan;
if (scanList.SurveyScans[surveyScanIndex].ZoomScan)
{
useScan = false;
}
}
if (!useScan)
{
continue;
}
if (!spectraCache.GetSpectrum(scanList.SurveyScans[surveyScanIndex].ScanNumber, out var spectrum, true))
{
SetLocalErrorCode(clsMASIC.eMasicErrorCodes.ErrorUncachingSpectrum);
return false;
}
for (var mzIndexWork = 0; mzIndexWork < mzSearchChunk.Count; mzIndexWork++)
{
var current = mzSearchChunk[mzIndexWork];
double mzToleranceDa;
if (current.MZToleranceIsPPM)
{
mzToleranceDa = clsUtilities.PPMToMass(current.MZTolerance, current.SearchMZ);
}
else
{
mzToleranceDa = current.MZTolerance;
}
var ionSum = dataAggregation.AggregateIonsInRange(spectrum,
current.SearchMZ, mzToleranceDa,
out _, out var closestMZ, false);
var dataIndex = fullSICDataCount[mzIndexWork];
fullSICScanIndices[mzIndexWork, dataIndex] = surveyScanIndex;
fullSICIntensities[mzIndexWork, dataIndex] = ionSum;
if (ionSum < float.Epsilon && masicOptions.SICOptions.ReplaceSICZeroesWithMinimumPositiveValueFromMSData)
{
fullSICIntensities[mzIndexWork, dataIndex] = scanList.SurveyScans[surveyScanIndex].MinimumPositiveIntensity;
}
fullSICMasses[mzIndexWork, dataIndex] = closestMZ;
if (ionSum > current.MaximumIntensity)
{
current.MaximumIntensity = ionSum;
current.ScanIndexMax = dataIndex;
}
fullSICDataCount[mzIndexWork] += 1;
}
if (surveyScanIndex % 100 == 0)
{
var subtaskPercentComplete = ComputeMzSearchChunkProgress(
parentIonsProcessed, scanList.ParentIons.Count,
surveyScanIndex, scanList.SurveyScans.Count, mzSearchChunkProgressFraction);
var progressMessage = "Loading raw SIC data: " + surveyScanIndex + " / " + scanList.SurveyScans.Count;
UpdateProgress(subtaskPercentComplete, progressMessage);
if (masicOptions.AbortProcessing)
{
scanList.ProcessingIncomplete = true;
return false;
}
}
}
UpdateProgress(CREATING_SICS);
if (masicOptions.AbortProcessing)
{
scanList.ProcessingIncomplete = true;
return false;
}
const int debugParentIonIndexToFind = 3139;
const float DebugMZToFind = 488.47F;
// ---------------------------------------------------------
// Compute the noise level in fullSICIntensities() for each m/z in udtMZSearchChunk
// Also, find the peaks for each m/z in udtMZSearchChunk and retain the largest peak found
// ---------------------------------------------------------
for (var mzIndexWork = 0; mzIndexWork < mzSearchChunk.Count; mzIndexWork++)
{
// Use this for debugging
if (Math.Abs(mzSearchChunk[mzIndexWork].SearchMZ - DebugMZToFind) < 0.1)
{
// ReSharper disable once UnusedVariable
var parentIonIndexPointer = mzSearchChunk[mzIndexWork].MZIndexStart;
}
// Copy the data for this m/z into fullSICIntensities1D()
for (var dataIndex = 0; dataIndex < fullSICDataCount[mzIndexWork]; dataIndex++)
fullSICIntensities1D[dataIndex] = fullSICIntensities[mzIndexWork, dataIndex];
// Compute the noise level; the noise level may change with increasing index number if the background is increasing for a given m/z
var success = mMASICPeakFinder.ComputeDualTrimmedNoiseLevelTTest(
fullSICIntensities1D, 0, fullSICDataCount[mzIndexWork] - 1,
masicOptions.SICOptions.SICPeakFinderOptions.SICBaselineNoiseOptions,
out var noiseStatSegments);
if (!success)
{
SetLocalErrorCode(clsMASIC.eMasicErrorCodes.FindSICPeaksError, true);
return false;
}
mzSearchChunk[mzIndexWork].BaselineNoiseStatSegments = noiseStatSegments;
// Compute the minimum potential peak area in the entire SIC, populating udtSICPotentialAreaStatsInFullSIC
mMASICPeakFinder.FindPotentialPeakArea(
fullSICDataCount[mzIndexWork],
fullSICIntensities1D,
out var potentialAreaStatsInFullSIC,
masicOptions.SICOptions.SICPeakFinderOptions);
var scanIndexObservedInFullSIC = mzSearchChunk[mzIndexWork].ScanIndexMax;
// Initialize sicDetails
var sicDetails = new clsSICDetails()
{
SICScanType = clsScanList.eScanTypeConstants.SurveyScan
};
// Populate sicDetails using the data centered around the highest intensity in fullSICIntensities
// Note that this function will update sicPeak.IndexObserved
var sicPeak = ExtractSICDetailsFromFullSIC(
mzIndexWork, mzSearchChunk[mzIndexWork].BaselineNoiseStatSegments,
fullSICDataCount[mzIndexWork], fullSICScanIndices, fullSICIntensities, fullSICMasses,
scanList, scanIndexObservedInFullSIC,
sicDetails,
masicOptions, scanNumScanConverter, false, 0);
UpdateSICStatsUsingLargestPeak(
sicDetails,
sicPeak,
masicOptions,
potentialAreaStatsInFullSIC,
scanList,
mzSearchChunk,
mzIndexWork,
parentIonIndices,
debugParentIonIndexToFind,
dataOutputHandler,
xmlResultsWriter,
parentIonUpdated,
ref parentIonsProcessed);
// --------------------------------------------------------
// Now step through the parent ions and process those that were not updated using sicPeak
// For each, search for the closest peak in SICIntensity
// --------------------------------------------------------
for (var parentIonIndexPointer = mzSearchChunk[mzIndexWork].MZIndexStart; parentIonIndexPointer <= mzSearchChunk[mzIndexWork].MZIndexEnd; parentIonIndexPointer++)
{
if (parentIonUpdated[parentIonIndexPointer])
continue;
if (parentIonIndices[parentIonIndexPointer] == debugParentIonIndexToFind)
{
// ReSharper disable once RedundantAssignment
scanIndexObservedInFullSIC = -1;
}
var currentParentIon = scanList.ParentIons[parentIonIndices[parentIonIndexPointer]];
// Clear udtSICPotentialAreaStatsForPeak
currentParentIon.SICStats.SICPotentialAreaStatsForPeak = new clsSICPotentialAreaStats();
// Record the index in the Full SIC that the parent ion mass was first observed
// Search for .SurveyScanIndex in fullSICScanIndices
scanIndexObservedInFullSIC = -1;
for (var dataIndex = 0; dataIndex < fullSICDataCount[mzIndexWork]; dataIndex++)
{
if (fullSICScanIndices[mzIndexWork, dataIndex] >= currentParentIon.SurveyScanIndex)
{
scanIndexObservedInFullSIC = dataIndex;
break;