-
Notifications
You must be signed in to change notification settings - Fork 4
/
clsMASIC.cs
1766 lines (1455 loc) · 73.3 KB
/
clsMASIC.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
// This class will read an LC-MS/MS data file and create selected ion chromatograms
// for each of the parent ion masses chosen for fragmentation
// It will create several output files, including a BPI for the survey scan,
// a BPI for the fragmentation scans, an XML file containing the SIC data
// for each parent ion, and a "flat file" ready for import into the database
// containing summaries of the SIC data statistics
// Supported file types are Thermo .Raw files (LCQ, LTQ, LTQ-FT),
// Agilent Ion Trap (.MGF and .CDF files), and mzXML files
// -------------------------------------------------------------------------------
// Written by Matthew Monroe for the Department of Energy (PNNL, Richland, WA)
// Program started October 11, 2003
// Copyright 2005, Battelle Memorial Institute. All Rights Reserved.
// E-mail: [email protected] or [email protected]
// Website: https://github.com/PNNL-Comp-Mass-Spec/ or https://www.pnnl.gov/integrative-omics
// -------------------------------------------------------------------------------
//
// 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using MASIC.Data;
using MASIC.DataInput;
using MASIC.DataOutput;
using MASIC.DatasetStats;
using MASIC.Options;
using PRISM;
using PRISM.Logging;
namespace MASIC
{
/// <summary>
/// MASIC processing class
/// </summary>
public class clsMASIC : PRISM.FileProcessor.ProcessFilesBase
{
// Ignore Spelling: cls, Da, Keypress, MASIC, MSMS, OxyPlot, UnCache, uncaching
/// <summary>
/// Constructor
/// </summary>
public clsMASIC()
{
mFileDate = "June 7, 2022";
LocalErrorCode = MasicErrorCodes.NoError;
StatusMessage = string.Empty;
mProcessingStats = new ProcessingStats();
InitializeMemoryManagementOptions(mProcessingStats);
mMASICPeakFinder = new MASICPeakFinder.clsMASICPeakFinder();
RegisterEvents(mMASICPeakFinder);
Options = new MASICOptions(FileVersion, mMASICPeakFinder.ProgramVersion);
Options.InitializeVariables();
RegisterEvents(Options);
}
/// <summary>
/// Enabling this will result in SICs with less noise, which will hurt noise determination after finding the SICs
/// </summary>
public const bool DISCARD_LOW_INTENSITY_MS_DATA_ON_LOAD = false;
/// <summary>
/// Disabling this will slow down the correlation process (slightly)
/// </summary>
public const bool DISCARD_LOW_INTENSITY_MSMS_DATA_ON_LOAD = true;
private const int MINIMUM_STATUS_FILE_UPDATE_INTERVAL_SECONDS = 3;
/// <summary>
/// Processing steps
/// </summary>
public enum ProcessingStepConstants
{
/// <summary>
/// Starting a new analysis
/// </summary>
NewTask = 0,
/// <summary>
/// Reading the input file
/// </summary>
ReadDataFile = 1,
/// <summary>
/// Saving the base peak intensity chromatogram
/// </summary>
SaveBPI = 2,
/// <summary>
/// Creating selected ion chromatograms and finding peaks
/// </summary>
CreateSICsAndFindPeaks = 3,
/// <summary>
/// Finding similar parent ions
/// </summary>
FindSimilarParentIons = 4,
/// <summary>
/// Saving extended scan stats files
/// </summary>
SaveExtendedScanStatsFiles = 5,
/// <summary>
/// Saving the SIC stats files
/// </summary>
SaveSICStatsFlatFile = 6,
/// <summary>
/// Closing open file handles
/// </summary>
CloseOpenFileHandles = 7,
/// <summary>
/// Updating the XML file with optimal peak apex values
/// </summary>
UpdateXMLFileWithNewOptimalPeakApexValues = 8,
/// <summary>
/// Creating plots
/// </summary>
CreatePlots = 9,
/// <summary>
/// Processing canceled
/// </summary>
Cancelled = 99,
/// <summary>
/// Processing complete
/// </summary>
Complete = 100
}
/// <summary>
/// MASIC Error Codes
/// </summary>
public enum MasicErrorCodes
{
/// <summary>
/// No error
/// </summary>
NoError = 0,
/// <summary>
/// Invalid dataset lookup file path
/// </summary>
InvalidDatasetLookupFilePath = 1,
/// <summary>
/// Unknown file extension
/// </summary>
/// <remarks>
/// This error code matches the identical code in clsFilterMsMsSpectra
/// </remarks>
UnknownFileExtension = 2,
/// <summary>
/// Input file access error
/// </summary>
/// <remarks>
/// This error code matches the identical code in clsFilterMsMsSpectra
/// </remarks>
InputFileAccessError = 4,
/// <summary>
/// Invalid dataset ID
/// </summary>
InvalidDatasetID = 8,
/// <summary>
/// Error creating selected ion chromatograms
/// </summary>
CreateSICsError = 16,
/// <summary>
/// Error finding SIC peaks
/// </summary>
FindSICPeaksError = 32,
/// <summary>
/// Invalid custom SIC values
/// </summary>
InvalidCustomSICValues = 64,
/// <summary>
/// No parent ions were found in the input file
/// </summary>
NoParentIonsFoundInInputFile = 128,
/// <summary>
/// No survey scans were found in the input file
/// </summary>
NoSurveyScansFoundInInputFile = 256,
/// <summary>
/// Error finding similar parent ions
/// </summary>
FindSimilarParentIonsError = 512,
/// <summary>
/// Error reading the input file
/// </summary>
InputFileDataReadError = 1024,
/// <summary>
/// Error writing an output file
/// </summary>
OutputFileWriteError = 2048,
/// <summary>
/// File I/O permission error
/// </summary>
FileIOPermissionsError = 4096,
/// <summary>
/// Error creating the spectrum cache directory
/// </summary>
ErrorCreatingSpectrumCacheDirectory = 8192,
/// <summary>
/// Error caching a spectrum
/// </summary>
ErrorCachingSpectrum = 16384,
/// <summary>
/// Error uncaching a spectrum
/// </summary>
ErrorUncachingSpectrum = 32768,
/// <summary>
/// Error deleting cached spectrum files
/// </summary>
ErrorDeletingCachedSpectrumFiles = 65536,
/// <summary>
/// Unspecified error
/// </summary>
UnspecifiedError = -1
}
private bool mLoggedMASICVersion;
private readonly MASICPeakFinder.clsMASICPeakFinder mMASICPeakFinder;
private readonly ProcessingStats mProcessingStats;
/// <summary>
/// Use RaiseEvent MyBase.ProgressChanged when updating the overall progress
/// Use ProgressSubtaskChanged when updating the subtask progress
/// </summary>
public event ProgressSubtaskChangedEventHandler ProgressSubtaskChanged;
/// <summary>
/// Subtask changed event handler
/// </summary>
public delegate void ProgressSubtaskChangedEventHandler();
/// <summary>
/// Event to track that the user wants to abort processing
/// </summary>
public event ProgressResetKeypressAbortEventHandler ProgressResetKeypressAbort;
/// <summary>
/// Abort processing event handler
/// </summary>
public delegate void ProgressResetKeypressAbortEventHandler();
/// <summary>
/// Local error code
/// </summary>
public MasicErrorCodes LocalErrorCode { get; private set; }
/// <summary>
/// Returns the version of the MASIC peak finder DLL
/// </summary>
// ReSharper disable once UnusedMember.Global
public string MASICPeakFinderDllVersion => mMASICPeakFinder != null ? mMASICPeakFinder.ProgramVersion : string.Empty;
/// <summary>
/// Processing options
/// </summary>
public MASICOptions Options { get; }
/// <summary>
/// Current processing step
/// </summary>
public ProcessingStepConstants ProcessStep { get; private set; }
/// <summary>
/// Status message
/// </summary>
public string StatusMessage { get; private set; }
/// <summary>
/// Subtask progress percent complete
/// </summary>
/// <remarks>Value between 0 and 100</remarks>
public float SubtaskProgressPercentComplete { get; private set; }
/// <summary>
/// Subtask description
/// </summary>
public string SubtaskDescription { get; private set; } = string.Empty;
/// <summary>
/// Call this method to abort processing
/// </summary>
public override void AbortProcessingNow()
{
AbortProcessing = true;
Options.AbortProcessing = true;
}
/// <summary>
/// Create an example parameter file
/// </summary>
/// <param name="paramFilePath">File name or path; if an empty string, will use MASIC_ExampleSettings.xml</param>
public void CreateExampleParameterFile(string paramFilePath)
{
try
{
if (string.IsNullOrWhiteSpace(paramFilePath))
{
paramFilePath = "MASIC_ExampleSettings.xml";
}
var outputFile = new FileInfo(paramFilePath);
var action = outputFile.Exists ? "Overwriting " : "Creating ";
Console.WriteLine(action + PathUtils.CompactPathString(outputFile.FullName, 100));
Options.SaveParameterFileSettings(outputFile.FullName);
Console.WriteLine("... done");
}
catch (Exception ex)
{
LogErrors("CreateExampleParameterFile", "Error creating an example parameter file", ex, MasicErrorCodes.OutputFileWriteError);
}
}
private bool CreatePlots(string inputFilePath, string outputDirectoryPath)
{
bool success;
var inputFile = new FileInfo(inputFilePath);
if (inputFile.Name.EndsWith(DataOutput.DataOutput.SIC_STATS_FILE_SUFFIX, StringComparison.OrdinalIgnoreCase))
{
success = CreatePlots(inputFile, outputDirectoryPath);
}
else if (inputFilePath.EndsWith(DataOutput.DataOutput.SCAN_STATS_FILE_SUFFIX, StringComparison.OrdinalIgnoreCase))
{
// The user specified the Scan Stats file
// Auto-switch to the SIC stats file
var sicStatsFilePath = Utilities.ReplaceSuffix(inputFilePath, DataOutput.DataOutput.SCAN_STATS_FILE_SUFFIX, DataOutput.DataOutput.SIC_STATS_FILE_SUFFIX);
success = CreatePlots(new FileInfo(sicStatsFilePath), outputDirectoryPath);
}
else if (inputFilePath.EndsWith(DataOutput.DataOutput.REPORTER_IONS_FILE_SUFFIX, StringComparison.OrdinalIgnoreCase))
{
// The user specified the Reporter Ion data file
// Auto-switch to the SIC stats file
var sicStatsFilePath = Utilities.ReplaceSuffix(inputFilePath, DataOutput.DataOutput.REPORTER_IONS_FILE_SUFFIX, DataOutput.DataOutput.SIC_STATS_FILE_SUFFIX);
success = CreatePlots(new FileInfo(sicStatsFilePath), outputDirectoryPath);
}
else
{
StatusMessage = "Invalid input file path; cannot create plots using " + inputFilePath;
ShowErrorMessage(StatusMessage);
return false;
}
return success;
}
private bool CreatePlots(FileSystemInfo sicStatsFile, string outputDirectoryPath)
{
try
{
var statsPlotter = new StatsPlotter(Options);
RegisterEvents(statsPlotter);
var success = statsPlotter.ProcessFile(sicStatsFile.FullName, outputDirectoryPath);
if (!success)
{
SetLocalErrorCode(MasicErrorCodes.OutputFileWriteError);
}
return success;
}
catch (Exception ex)
{
LogErrors("CreatePlots", "Error summarizing stats and creating plots", ex, MasicErrorCodes.OutputFileWriteError);
return false;
}
}
private bool FindSICsAndWriteOutput(
string inputFilePathFull,
string outputDirectoryPath,
ScanList scanList,
SpectraCache spectraCache,
DataOutput.DataOutput dataOutputHandler,
ScanTracking scanTracking,
DatasetFileInfo datasetFileInfo,
ParentIonProcessing parentIonProcessor,
DataImport dataImporterBase)
{
var inputFileName = Path.GetFileName(inputFilePathFull);
try
{
var bpiWriter = new BPIWriter();
RegisterEvents(bpiWriter);
var xmlResultsWriter = new XMLResultsWriter(Options);
RegisterEvents(xmlResultsWriter);
// ---------------------------------------------------------
// Save the BPIs and TICs
// ---------------------------------------------------------
UpdateProcessingStep(ProcessingStepConstants.SaveBPI);
UpdateOverallProgress("Processing Data for " + inputFileName);
SetSubtaskProcessingStepPct(0, "Saving chromatograms to disk");
UpdatePeakMemoryUsage();
if (Options.SkipSICAndRawDataProcessing || !Options.ExportRawDataOnly)
{
LogMessage("FindSICsAndWriteOutput: Call SaveBPIs", MessageTypeConstants.Debug);
bpiWriter.SaveBPIs(scanList, spectraCache, inputFilePathFull, outputDirectoryPath);
}
// ---------------------------------------------------------
// Close the ScanStats file handle
// ---------------------------------------------------------
try
{
LogMessage("FindSICsAndWriteOutput: Close outputFileHandles.ScanStats");
dataOutputHandler.OutputFileHandles.CloseScanStats();
}
catch (Exception)
{
// Ignore errors here
}
// ---------------------------------------------------------
// Create the DatasetInfo XML file
// ---------------------------------------------------------
LogMessage("FindSICsAndWriteOutput: Create DatasetInfo File");
dataOutputHandler.CreateDatasetInfoFile(inputFileName, outputDirectoryPath, scanTracking, datasetFileInfo);
int similarParentIonUpdateCount;
if (Options.SkipSICAndRawDataProcessing)
{
LogMessage("FindSICsAndWriteOutput: Skipping SIC Processing");
SetDefaultPeakLocValues(scanList);
similarParentIonUpdateCount = 0;
}
else
{
var success = FindSICsWork(
inputFilePathFull,
outputDirectoryPath,
scanList,
spectraCache,
dataOutputHandler,
parentIonProcessor,
dataImporterBase,
bpiWriter,
xmlResultsWriter,
out similarParentIonUpdateCount);
if (!success)
return false;
}
if (Options.WriteExtendedStats && !Options.ExportRawDataOnly)
{
// ---------------------------------------------------------
// Save Extended Scan Stats Files
// ---------------------------------------------------------
UpdateProcessingStep(ProcessingStepConstants.SaveExtendedScanStatsFiles);
SetSubtaskProcessingStepPct(0);
UpdatePeakMemoryUsage();
LogMessage("FindSICsAndWriteOutput: Call SaveExtendedScanStatsFiles", MessageTypeConstants.Debug);
var extendedStatsWritten = dataOutputHandler.ExtendedStatsWriter.SaveExtendedScanStatsFiles(
scanList, inputFileName, outputDirectoryPath, Options.IncludeHeadersInExportFile);
if (!extendedStatsWritten)
{
SetLocalErrorCode(MasicErrorCodes.OutputFileWriteError, true);
return false;
}
}
// ---------------------------------------------------------
// Save SIC Stats Flat File
// ---------------------------------------------------------
UpdateProcessingStep(ProcessingStepConstants.SaveSICStatsFlatFile);
SetSubtaskProcessingStepPct(0);
UpdatePeakMemoryUsage();
string sicStatsFilePath;
if (!Options.ExportRawDataOnly)
{
var sicStatsWriter = new SICStatsWriter();
RegisterEvents(sicStatsWriter);
LogMessage("FindSICsAndWriteOutput: Call SaveSICStatsFlatFile", MessageTypeConstants.Debug);
var sicStatsWritten = sicStatsWriter.SaveSICStatsFlatFile(scanList, inputFileName, outputDirectoryPath, Options, dataOutputHandler);
if (!sicStatsWritten)
{
SetLocalErrorCode(MasicErrorCodes.OutputFileWriteError, true);
return false;
}
sicStatsFilePath = sicStatsWriter.SICStatsFilePath;
}
else
{
sicStatsFilePath = string.Empty;
}
UpdateProcessingStep(ProcessingStepConstants.CloseOpenFileHandles);
SetSubtaskProcessingStepPct(0);
UpdatePeakMemoryUsage();
if (!(Options.SkipSICAndRawDataProcessing || Options.ExportRawDataOnly))
{
// ---------------------------------------------------------
// Write processing stats to the XML output file
// ---------------------------------------------------------
LogMessage("FindSICsAndWriteOutput: Call FinalizeXMLFile", MessageTypeConstants.Debug);
var processingTimeSec = GetTotalProcessingTimeSec();
xmlResultsWriter.XMLOutputFileFinalize(
dataOutputHandler, scanList, spectraCache,
mProcessingStats, processingTimeSec);
}
// ---------------------------------------------------------
// Close any open output files
// ---------------------------------------------------------
dataOutputHandler.OutputFileHandles.CloseAll();
// ---------------------------------------------------------
// Save a text file containing the headers used in the text files
// ---------------------------------------------------------
if (!Options.IncludeHeadersInExportFile)
{
LogMessage("FindSICsAndWriteOutput: Call SaveHeaderGlossary", MessageTypeConstants.Debug);
dataOutputHandler.SaveHeaderGlossary(scanList, inputFileName, outputDirectoryPath);
}
if (!(Options.SkipSICAndRawDataProcessing || Options.ExportRawDataOnly) && similarParentIonUpdateCount > 0)
{
// ---------------------------------------------------------
// Reopen the XML file and update the entries for those ions in scanList that had their
// Optimal peak apex scan numbers updated
// ---------------------------------------------------------
UpdateProcessingStep(ProcessingStepConstants.UpdateXMLFileWithNewOptimalPeakApexValues);
SetSubtaskProcessingStepPct(0);
UpdatePeakMemoryUsage();
LogMessage("FindSICsAndWriteOutput: Call XmlOutputFileUpdateEntries", MessageTypeConstants.Debug);
xmlResultsWriter.XmlOutputFileUpdateEntries(scanList, inputFileName, outputDirectoryPath);
}
if (string.IsNullOrEmpty(sicStatsFilePath) || !Options.PlotOptions.CreatePlots || scanList.ParentIons.Count == 0)
{
return true;
}
UpdateProcessingStep(ProcessingStepConstants.CreatePlots);
SetSubtaskProcessingStepPct(0);
UpdateOverallProgress("Creating plots in " + outputDirectoryPath);
return CreatePlots(new FileInfo(sicStatsFilePath), outputDirectoryPath);
}
catch (Exception ex)
{
LogErrors("FindSICsAndWriteOutput", "Error saving results to: " + outputDirectoryPath, ex, MasicErrorCodes.OutputFileWriteError);
return false;
}
}
private bool FindSICsWork(
string inputFilePathFull,
string outputDirectoryPath,
ScanList scanList,
SpectraCache spectraCache,
DataOutput.DataOutput dataOutputHandler,
ParentIonProcessing parentIonProcessor,
DataImport dataImporterBase,
BPIWriter bpiWriter,
XMLResultsWriter xmlResultsWriter,
out int similarParentIonUpdateCount)
{
var inputFileName = Path.GetFileName(inputFilePathFull);
similarParentIonUpdateCount = 0;
// ---------------------------------------------------------
// Optionally, export the raw mass spectra data
// ---------------------------------------------------------
if (Options.RawDataExportOptions.ExportEnabled)
{
var rawDataExporter = new SpectrumDataWriter(bpiWriter, Options);
RegisterEvents(rawDataExporter);
rawDataExporter.ExportRawDataToDisk(scanList, spectraCache, inputFileName, outputDirectoryPath);
}
if (Options.ReporterIons.ReporterIonStatsEnabled)
{
// Look for Reporter Ions in the Fragmentation spectra
var reporterIonProcessor = new ReporterIonProcessor(Options);
RegisterEvents(reporterIonProcessor);
reporterIonProcessor.FindReporterIons(scanList, spectraCache, inputFilePathFull, outputDirectoryPath);
}
var mrmProcessor = new MRMProcessing(Options, dataOutputHandler);
RegisterEvents(mrmProcessor);
// ---------------------------------------------------------
// If MRM data is present, save the MRM values to disk
// ---------------------------------------------------------
if (scanList.MRMDataPresent)
{
mrmProcessor.ExportMRMDataToDisk(scanList, spectraCache, inputFileName, outputDirectoryPath);
}
if (!Options.ExportRawDataOnly)
{
// ---------------------------------------------------------
// Add the custom SIC values to scanList
// ---------------------------------------------------------
Options.CustomSICList.AddCustomSICValues(scanList, Options.SICOptions.SICTolerance,
Options.SICOptions.SICToleranceIsPPM, Options.CustomSICList.ScanOrAcqTimeTolerance);
// ---------------------------------------------------------
// Possibly create the Tab-separated SIC details output file
// ---------------------------------------------------------
if (Options.WriteDetailedSICDataFile)
{
var sicDetailsFileCreated = dataOutputHandler.InitializeSICDetailsTextFile(inputFilePathFull, outputDirectoryPath);
if (!sicDetailsFileCreated)
{
SetLocalErrorCode(MasicErrorCodes.OutputFileWriteError);
return false;
}
}
// ---------------------------------------------------------
// Create the XML output file
// ---------------------------------------------------------
var xmlWriterInitialized = xmlResultsWriter.XMLOutputFileInitialize(inputFilePathFull, outputDirectoryPath, dataOutputHandler, scanList,
spectraCache, Options.SICOptions, Options.BinningOptions);
if (!xmlWriterInitialized)
{
SetLocalErrorCode(MasicErrorCodes.OutputFileWriteError);
return false;
}
// ---------------------------------------------------------
// Create the selected ion chromatograms (SICs)
// For each one, find the peaks and make an entry to the XML output file
// ---------------------------------------------------------
UpdateProcessingStep(ProcessingStepConstants.CreateSICsAndFindPeaks);
SetSubtaskProcessingStepPct(0);
UpdatePeakMemoryUsage();
LogMessage("FindSICsWork: Call CreateParentIonSICs", MessageTypeConstants.Debug);
var sicProcessor = new SICProcessing(mMASICPeakFinder, mrmProcessor);
RegisterEvents(sicProcessor);
var parentIonSICsCreated = sicProcessor.CreateParentIonSICs(
scanList, spectraCache, Options, dataOutputHandler, sicProcessor, xmlResultsWriter);
if (!parentIonSICsCreated)
{
SetLocalErrorCode(MasicErrorCodes.CreateSICsError, true);
return false;
}
}
if (!(Options.SkipMSMSProcessing || Options.ExportRawDataOnly))
{
// ---------------------------------------------------------
// Find Similar Parent Ions
// ---------------------------------------------------------
UpdateProcessingStep(ProcessingStepConstants.FindSimilarParentIons);
SetSubtaskProcessingStepPct(0);
UpdatePeakMemoryUsage();
LogMessage("FindSICsWork: Call FindSimilarParentIons", MessageTypeConstants.Debug);
var foundSimilarParentIons = parentIonProcessor.FindSimilarParentIons(
scanList, spectraCache, Options, dataImporterBase, out similarParentIonUpdateCount);
if (!foundSimilarParentIons)
{
SetLocalErrorCode(MasicErrorCodes.FindSimilarParentIonsError, true);
return false;
}
}
return true;
}
/// <summary>
/// Get supported file extensions
/// </summary>
public override IList<string> GetDefaultExtensionsToParse()
{
return DataImport.GetDefaultExtensionsToParse();
}
/// <summary>
/// Get the error message, or an empty string if no error
/// </summary>
public override string GetErrorMessage()
{
if (ErrorCode is ProcessFilesErrorCodes.LocalizedError or ProcessFilesErrorCodes.NoError)
{
return LocalErrorCode switch
{
MasicErrorCodes.NoError => string.Empty,
MasicErrorCodes.InvalidDatasetLookupFilePath => "Invalid dataset lookup file path",
MasicErrorCodes.UnknownFileExtension => "Unknown file extension",
MasicErrorCodes.InputFileAccessError => "Input file access error",
MasicErrorCodes.InvalidDatasetID => "Invalid dataset number",
// ReSharper disable once StringLiteralTypo
MasicErrorCodes.CreateSICsError => "Create SIC's error",
MasicErrorCodes.FindSICPeaksError => "Error finding SIC peaks",
MasicErrorCodes.InvalidCustomSICValues => "Invalid custom SIC values",
MasicErrorCodes.NoParentIonsFoundInInputFile => "No parent ions were found in the input file (additionally, no custom SIC values were defined)",
MasicErrorCodes.NoSurveyScansFoundInInputFile => "No survey scans were found in the input file (do you have a Scan Range filter defined?)",
MasicErrorCodes.FindSimilarParentIonsError => "Find similar parent ions error",
MasicErrorCodes.InputFileDataReadError => "Error reading data from input file",
MasicErrorCodes.OutputFileWriteError => "Error writing data to output file",
MasicErrorCodes.FileIOPermissionsError => "File IO Permissions Error",
MasicErrorCodes.ErrorCreatingSpectrumCacheDirectory => "Error creating spectrum cache directory",
MasicErrorCodes.ErrorCachingSpectrum => "Error caching spectrum",
MasicErrorCodes.ErrorUncachingSpectrum => "Error uncaching spectrum",
MasicErrorCodes.ErrorDeletingCachedSpectrumFiles => "Error deleting cached spectrum files",
MasicErrorCodes.UnspecifiedError => "Unspecified localized error",
_ => "Unknown error state"
};
}
return GetBaseClassErrorMessage();
}
/// <summary>
/// Get the amount of free memory, in MB
/// </summary>
private float GetFreeMemoryMB()
{
return SystemInfo.GetFreeMemoryMB();
}
/// <summary>
/// Get the amount of memory used by this process
/// </summary>
private float GetProcessMemoryUsageMB()
{
// Obtain a handle to the current process
var currentProcess = Process.GetCurrentProcess();
// The WorkingSet is the total physical memory usage
return (float)(currentProcess.WorkingSet64 / 1024.0 / 1024);
}
/// <summary>
/// Get total processing time, in seconds
/// </summary>
private float GetTotalProcessingTimeSec()
{
var currentProcess = Process.GetCurrentProcess();
return (float)(currentProcess.TotalProcessorTime.TotalSeconds);
}
private void InitializeMemoryManagementOptions(ProcessingStats processingStats)
{
processingStats.PeakMemoryUsageMB = GetProcessMemoryUsageMB();
processingStats.TotalProcessingTimeAtStart = GetTotalProcessingTimeSec();
processingStats.CacheEventCount = 0;
processingStats.UnCacheEventCount = 0;
processingStats.FileLoadStartTime = DateTime.UtcNow;
processingStats.FileLoadEndTime = processingStats.FileLoadStartTime;
processingStats.ProcessingStartTime = processingStats.FileLoadStartTime;
processingStats.ProcessingEndTime = processingStats.FileLoadStartTime;
processingStats.MemoryUsageMBAtStart = processingStats.PeakMemoryUsageMB;
processingStats.MemoryUsageMBDuringLoad = processingStats.PeakMemoryUsageMB;
processingStats.MemoryUsageMBAtEnd = processingStats.PeakMemoryUsageMB;
}
private bool LoadData(
string inputFilePath,
string outputDirectoryPath,
DataOutput.DataOutput dataOutputHandler,
ParentIonProcessing parentIonProcessor,
ScanTracking scanTracking,
ScanList scanList,
SpectraCache spectraCache,
out DataImport dataImporterBase,
out DatasetFileInfo datasetFileInfo)
{
bool success;
datasetFileInfo = new DatasetFileInfo();
try
{
// ---------------------------------------------------------
// Define inputFileName (which is referenced several times below)
// ---------------------------------------------------------
var inputFileName = Path.GetFileName(inputFilePath);
// ---------------------------------------------------------
// Create the _ScanStats.txt file
// ---------------------------------------------------------
dataOutputHandler.OpenOutputFileHandles(inputFileName, outputDirectoryPath, Options.IncludeHeadersInExportFile);
// ---------------------------------------------------------
// Read the mass spectra from the input data file
// ---------------------------------------------------------
UpdateProcessingStep(ProcessingStepConstants.ReadDataFile);
SetSubtaskProcessingStepPct(0);
UpdatePeakMemoryUsage();
StatusMessage = string.Empty;
if (Options.SkipSICAndRawDataProcessing)
{
Options.ExportRawDataOnly = false;
}
var keepRawMSSpectra = !Options.SkipSICAndRawDataProcessing || Options.ExportRawDataOnly;
Options.SICOptions.ValidateSICOptions();
switch (Path.GetExtension(inputFileName).ToUpper())
{
case DataImport.THERMO_RAW_FILE_EXTENSION:
// Open the .Raw file and obtain the scan information
var dataImporter = new DataImportThermoRaw(Options, mMASICPeakFinder, parentIonProcessor, scanTracking);
RegisterDataImportEvents(dataImporter);
dataImporterBase = dataImporter;
success = dataImporter.ExtractScanInfoFromThermoDataFile(
inputFilePath,
scanList, spectraCache, dataOutputHandler,
keepRawMSSpectra,
!Options.SkipMSMSProcessing);
datasetFileInfo = dataImporter.DatasetFileInfo;
break;
case DataImport.MZ_ML_FILE_EXTENSION:
// Open the .mzML file and obtain the scan information
var dataImporterMzML = new DataImportMSXml(Options, mMASICPeakFinder, parentIonProcessor, scanTracking);
RegisterDataImportEvents(dataImporterMzML);
dataImporterBase = dataImporterMzML;
success = dataImporterMzML.ExtractScanInfoFromMzMLDataFile(
inputFilePath,
scanList, spectraCache, dataOutputHandler,
keepRawMSSpectra,
!Options.SkipMSMSProcessing);
datasetFileInfo = dataImporterMzML.DatasetFileInfo;
break;
case DataImport.MZ_XML_FILE_EXTENSION1:
case DataImport.MZ_XML_FILE_EXTENSION2:
// Open the .mzXML file and obtain the scan information
var dataImporterMzXML = new DataImportMSXml(Options, mMASICPeakFinder, parentIonProcessor, scanTracking);
RegisterDataImportEvents(dataImporterMzXML);
dataImporterBase = dataImporterMzXML;
success = dataImporterMzXML.ExtractScanInfoFromMzXMLDataFile(
inputFilePath,
scanList, spectraCache, dataOutputHandler,
keepRawMSSpectra,
!Options.SkipMSMSProcessing);
datasetFileInfo = dataImporterMzXML.DatasetFileInfo;
break;
case DataImport.MZ_DATA_FILE_EXTENSION1:
case DataImport.MZ_DATA_FILE_EXTENSION2:
// Open the .mzData file and obtain the scan information
var dataImporterMzData = new DataImportMSXml(Options, mMASICPeakFinder, parentIonProcessor, scanTracking);
RegisterDataImportEvents(dataImporterMzData);
dataImporterBase = dataImporterMzData;
success = dataImporterMzData.ExtractScanInfoFromMzDataFile(
inputFilePath,
scanList, spectraCache, dataOutputHandler,
keepRawMSSpectra, !Options.SkipMSMSProcessing);
datasetFileInfo = dataImporterMzData.DatasetFileInfo;
break;
case DataImport.AGILENT_MSMS_FILE_EXTENSION:
case DataImport.AGILENT_MS_FILE_EXTENSION:
// Open the .MGF and .CDF files to obtain the scan information
var dataImporterMGF = new DataImportMGFandCDF(Options, mMASICPeakFinder, parentIonProcessor, scanTracking);
RegisterDataImportEvents(dataImporterMGF);
dataImporterBase = dataImporterMGF;
success = dataImporterMGF.ExtractScanInfoFromMGFandCDF(
inputFilePath,
scanList, spectraCache, dataOutputHandler,
keepRawMSSpectra, !Options.SkipMSMSProcessing);
datasetFileInfo = dataImporterMGF.DatasetFileInfo;
break;
default:
StatusMessage = "Unknown file extension: " + Path.GetExtension(inputFilePath);
SetLocalErrorCode(MasicErrorCodes.UnknownFileExtension);
success = false;
// Instantiate this object to avoid a warning below about the object potentially not being initialized
// In reality, an Exit Try statement will be reached and the potentially problematic use will therefore not get encountered
datasetFileInfo = new DatasetFileInfo();
dataImporterBase = null;
break;
}
if (!success)
{
if (LocalErrorCode == MasicErrorCodes.NoParentIonsFoundInInputFile && string.IsNullOrWhiteSpace(StatusMessage))
{
StatusMessage = "None of the spectra in the input file was within the specified scan number and/or scan time range";
}
SetLocalErrorCode(MasicErrorCodes.InputFileAccessError, true);
}
}
catch (Exception ex)
{
success = false;
LogErrors("LoadData", "Error accessing input data file: " + inputFilePath, ex, MasicErrorCodes.InputFileDataReadError);
dataImporterBase = null;
}
scanList.SetListCapacityToCount();
GC.Collect();
GC.WaitForPendingFinalizers();
System.Threading.Thread.Sleep(50);
return success;
}
/// <summary>
/// Load settings from a parameter file
/// </summary>
/// <param name="parameterFilePath"></param>
/// <returns>True if success, false if an error</returns>
// ReSharper disable once UnusedMember.Global