forked from thermofisherlsms/RawFileReader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
1248 lines (1057 loc) · 53.8 KB
/
Program.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
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Program.cs" company="Thermo Fisher Scientific">
// Copyright © Thermo Fisher Scientific. All rights reserved.
// </copyright>
// This source file contains the code for the console application that demonstrates who to
// read our RAW files using the RAWFileReader .Net library. This example uses only a fraction
// of the functions available in the RawFileReader library. Please consult the RawFileReader
// documentation for a complete list of methods available.
//
// This code has been compiled and tested using Visual Studio 2013 Update 5, Visual Studio
// 2015 Update 3, Visual Studio 2017 Update 2, Visual Studio 2019, and Visual Studio 2022, Visual
// Studio MAC, and MonoDevelop. Additional tools used include Resharper 2017.1. This application
// has been tested with .Net Framework 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, and 4.8.
//
// Questions about the program can be directed to [email protected]
// --------------------------------------------------------------------------------------------------------------------
namespace RawFileReaderDotNetExample
{
// These are the libraries necessary to read the Thermo RAW files. The Interfaces
// library contains the extension for accessing the scan averaging and background
// subtraction methods.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.ExceptionServices;
using ThermoFisher.CommonCore.Data;
using ThermoFisher.CommonCore.Data.Business;
using ThermoFisher.CommonCore.Data.FilterEnums;
using ThermoFisher.CommonCore.Data.Interfaces;
using ThermoFisher.CommonCore.MassPrecisionEstimator;
using ThermoFisher.CommonCore.RawFileReader;
/// <summary>
/// The object used to store the inclusion/exclusion list items.
/// </summary>
public class InclusionListItem : IComparable<InclusionListItem>
{
/// <summary>
/// Gets or sets the mass value for the inclusion/exclusion item.
/// </summary>
public double Mass { get; set; }
/// <summary>
/// Gets or sets the acquisition parameter for the inclusion/exclusion item. This
/// could be an intensity threshold or an isolation window based upon the instrument.
/// </summary>
public double Threshold { get; set; }
/// <summary>
/// Gets or sets the scan number for the inclusion/exclusion item.
/// </summary>
public int ScanNumber { get; set; }
/// <summary>
/// Gets or sets the descriptor for the inclusion/exclusion item.
/// </summary>
public string Descriptor { get; set; }
/// <summary>
/// Gets or sets the if the item is an exclusion item.
/// </summary>
public bool IsExclusionItem { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="InclusionListItem"/> class.
/// </summary>
public InclusionListItem()
{
Mass = 0.0;
ScanNumber = 0;
Threshold = 0.0;
Descriptor = string.Empty;
IsExclusionItem = false;
}
/// <summary>
/// The compare to method for the inclusion item class.
/// </summary>
/// <param name="other">
/// The other InclusionItem object to compare against this object.
/// </param>
/// <returns>
/// The <see cref="int"/>.
/// </returns>
public int CompareTo(InclusionListItem other)
{
// Compare the descriptors
int result = string.CompareOrdinal(Descriptor, other.Descriptor);
if (result != 0)
{
return result;
}
// Compare the mass values
result = Mass.CompareTo(other.Mass);
if (result != 0)
{
return result;
}
// Compare the threshold values
result = Threshold.CompareTo(other.Threshold);
if (result != 0)
{
return result;
}
// Compare the scan number values
result = ScanNumber.CompareTo(other.ScanNumber);
if (result != 0)
{
return result;
}
return result;
}
}
/// <summary>
/// A C# example program showing how to use RAWFileReader. More information on the RAWFileReader methods used
/// in this example and the other methods available in RAWFileReader can be found in the RAWFileReader user
/// documentation, that is installed with the RAWFileReader software.
/// This program has been tested with RAWFileReader 4.0.22 Changes maybe necessary with other versions
/// of RAWFileReader.
/// </summary>
internal static class Program
{
/// <summary>
/// The main routine for this example program. This example program only shows how to use the RawFileReader library
/// in a single-threaded application but our documentation for RawFileReader describes how to use it in a multi-threaded
/// application.
/// </summary>
/// <param name="args">The command line arguments for this program. The RAW file name should be passed as the first argument</param>
private static void Main(string[] args)
{
// This local variables controls if certain operations are performed. Change any of them to true to read and output that
// information section from the RAW file.
bool analyzeScans = false;
bool averageScans = false;
bool calculateMassPrecision = false;
bool centroidScan = false;
bool createSequenceListFile = false;
bool getChromatogram = false;
bool getInclusionExclusionList = false;
bool getStatusLog = false;
bool getTrailerExtra = false;
bool readAllScans = false;
bool readAnalog = false;
bool readMassChromatogram = true;
bool readScanInformation = false;
bool readSpectrum = false;
// Get the memory used at the beginning of processing
Process processBefore = Process.GetCurrentProcess();
long memoryBefore = processBefore.PrivateMemorySize64 / 1024;
try
{
// Check to see if the RAW file name was supplied as an argument to the program
string filename = string.Empty;
if (args.Length > 0)
{
filename = args[0];
}
if (string.IsNullOrEmpty(filename))
{
Console.WriteLine("No RAW file specified!");
return;
}
// Check to see if the specified RAW file exists
if (!File.Exists(filename))
{
Console.WriteLine(@"The file doesn't exist in the specified location - " + filename);
return;
}
// Create the IRawDataPlus object for accessing the RAW file
var rawFile = RawFileReaderAdapter.FileFactory(filename);
if (!rawFile.IsOpen || rawFile.IsError)
{
Console.WriteLine("Unable to access the RAW file using the RawFileReader class!");
return;
}
// Check for any errors in the RAW file
if (rawFile.IsError)
{
Console.WriteLine("Error opening ({0}) - {1}", rawFile.FileError, filename);
return;
}
// Check if the RAW file is being acquired
if (rawFile.InAcquisition)
{
Console.WriteLine("RAW file still being acquired - " + filename);
return;
}
// Get the number of instruments (controllers) present in the RAW file and set the
// selected instrument to the MS instrument, first instance of it
Console.WriteLine("The RAW file has data from {0} instruments" + rawFile.InstrumentCount);
rawFile.SelectInstrument(Device.MS, 1);
// Get the first and last scan from the RAW file
int firstScanNumber = rawFile.RunHeaderEx.FirstSpectrum;
int lastScanNumber = rawFile.RunHeaderEx.LastSpectrum;
// Get the start and end time from the RAW file
double startTime = rawFile.RunHeaderEx.StartTime;
double endTime = rawFile.RunHeaderEx.EndTime;
// Print some OS and other information
Console.WriteLine("System Information:");
Console.WriteLine(" OS Version: " + Environment.OSVersion);
Console.WriteLine(" 64 bit OS: " + Environment.Is64BitOperatingSystem);
Console.WriteLine(" Computer: " + Environment.MachineName);
Console.WriteLine(" # Cores: " + Environment.ProcessorCount);
Console.WriteLine(" Date: " + DateTime.Now);
Console.WriteLine();
// Get some information from the header portions of the RAW file and display that information.
// The information is general information pertaining to the RAW file.
Console.WriteLine("General File Information:");
Console.WriteLine(" RAW file: " + rawFile.FileName);
Console.WriteLine(" RAW file version: " + rawFile.FileHeader.Revision);
Console.WriteLine(" Creation date: " + rawFile.FileHeader.CreationDate);
Console.WriteLine(" Operator: " + rawFile.FileHeader.WhoCreatedId);
Console.WriteLine(" Number of instruments: " + rawFile.InstrumentCount);
Console.WriteLine(" Description: " + rawFile.FileHeader.FileDescription);
Console.WriteLine(" Instrument model: " + rawFile.GetInstrumentData().Model);
Console.WriteLine(" Instrument name: " + rawFile.GetInstrumentData().Name);
Console.WriteLine(" Serial number: " + rawFile.GetInstrumentData().SerialNumber);
Console.WriteLine(" Software version: " + rawFile.GetInstrumentData().SoftwareVersion);
Console.WriteLine(" Firmware version: " + rawFile.GetInstrumentData().HardwareVersion);
Console.WriteLine(" Units: " + rawFile.GetInstrumentData().Units);
Console.WriteLine(" Mass resolution: {0:F3} ", rawFile.RunHeaderEx.MassResolution);
Console.WriteLine(" Number of scans: {0}", rawFile.RunHeaderEx.SpectraCount);
Console.WriteLine(" Scan range: {0} - {1}", firstScanNumber, lastScanNumber);
Console.WriteLine(" Time range: {0:F2} - {1:F2}", startTime, endTime);
Console.WriteLine(" Mass range: {0:F4} - {1:F4}", rawFile.RunHeaderEx.LowMass, rawFile.RunHeaderEx.HighMass);
Console.WriteLine();
// Get information related to the sample that was processed
Console.WriteLine("Sample Information:");
Console.WriteLine(" Sample name: " + rawFile.SampleInformation.SampleName);
Console.WriteLine(" Sample id: " + rawFile.SampleInformation.SampleId);
Console.WriteLine(" Sample type: " + rawFile.SampleInformation.SampleType);
Console.WriteLine(" Sample comment: " + rawFile.SampleInformation.Comment);
Console.WriteLine(" Sample vial: " + rawFile.SampleInformation.Vial);
Console.WriteLine(" Sample volume: " + rawFile.SampleInformation.SampleVolume);
Console.WriteLine(" Sample injection volume: " + rawFile.SampleInformation.InjectionVolume);
Console.WriteLine(" Sample row number: " + rawFile.SampleInformation.RowNumber);
Console.WriteLine(" Sample dilution factor: " + rawFile.SampleInformation.DilutionFactor);
Console.WriteLine();
// Read the first instrument method (most likely for the MS portion of the instrument).
// NOTE: This method reads the instrument methods from the RAW file but the underlying code
// uses some Microsoft code that hasn't been ported to Linux or MacOS. Therefore this
// method won't work on those platforms therefore the check for Windows.
if (Environment.OSVersion.ToString().Contains("Windows"))
{
var deviceNames = rawFile.GetAllInstrumentNamesFromInstrumentMethod();
foreach (var device in deviceNames)
{
Console.WriteLine("Instrument method: " + device);
}
Console.WriteLine();
}
// Display all of the trailer extra data fields present in the RAW file
if (getTrailerExtra)
{
ListTrailerExtraFields(rawFile);
}
// Get the status log items
if (getStatusLog)
{
ListStatusLog(rawFile, firstScanNumber, lastScanNumber);
}
// Get the inclusion/exclusion list
if (getInclusionExclusionList)
{
var inclusionList = GetInclusionExclusionList(rawFile, 1e-5);
// Output the saved inclusion/exclusion list
int count = 0;
foreach (var item in inclusionList)
{
Console.WriteLine(" {0} - {1}, {2:F4}, {3:F0}, {4}", ++count, item.Descriptor, item.Mass, item.Threshold, item.ScanNumber);
}
Console.WriteLine();
}
// Get the number of filters present in the RAW file
int numberFilters = rawFile.GetFilters().Count;
// Get the scan filter for the first and last spectrum in the RAW file
var firstFilter = rawFile.GetFilterForScanNumber(firstScanNumber);
var lastFilter = rawFile.GetFilterForScanNumber(lastScanNumber);
Console.WriteLine("Filter Information:");
Console.WriteLine(" Scan filter (first scan): " + firstFilter.ToString());
Console.WriteLine(" Scan filter (last scan): " + lastFilter.ToString());
Console.WriteLine(" Total number of filters:" + numberFilters);
Console.WriteLine();
// Get the BasePeak chromatogram for the MS data
if (getChromatogram)
{
GetChromatogram(rawFile, firstScanNumber, lastScanNumber, true);
}
// Read the scan information for each scan in the RAW file
if (readScanInformation)
{
ReadScanInformation(rawFile, firstScanNumber, lastScanNumber, true);
}
// Get a spectrum from the RAW file.
if (readSpectrum)
{
GetSpectrum(rawFile, firstScanNumber, false);
}
// Get a average spectrum from the RAW file for the first 15 scans in the file.
if (averageScans)
{
GetAverageSpectrum(rawFile, 1, 15, true);
}
// Read each spectrum
if (readAllScans)
{
ReadAllSpectra(rawFile, firstScanNumber, lastScanNumber, true);
}
// Calculate the mass precision for a spectrum
if (calculateMassPrecision)
{
CalculateMassPrecision(rawFile, 1);
}
// Check all of the scans for out of order data. This method isn't enabled by
// default because it is very, very time consuming. If you would like to
// call this method change the value of _analyzeScans to true.
if (analyzeScans)
{
AnalyzeAllScans(rawFile, firstScanNumber, lastScanNumber);
}
// Create a sequence list file
if (createSequenceListFile)
{
CreateSequenceListFile("X:\\test.sld");
}
// Find the analog device for the given signal and output the chromatographic data for that device
if (readAnalog)
{
ReadAnalogSignal(rawFile, "Pump_Pressure");
}
// Find the mass chromatographic data for that device
if (readMassChromatogram)
{
ReadMassChromatogram(rawFile);
}
// Centroid the specified scan
if (centroidScan)
{
CentroidScan(rawFile, 100, true);
}
// Close (dispose) the RAW file
Console.WriteLine();
Console.WriteLine("Closing " + filename);
rawFile.Dispose();
}
catch (Exception ex)
{
Console.WriteLine("Error accessing RAWFileReader library! - " + ex.Message);
}
// Get the memory used at the end of processing
Process processAfter = Process.GetCurrentProcess();
long memoryAfter = processAfter.PrivateMemorySize64 / 1024;
Console.WriteLine();
Console.WriteLine("Memory Usage:");
Console.WriteLine(" Before {0} kb, After {1} kb, Extra {2} kb", memoryBefore, memoryAfter, memoryAfter - memoryBefore);
}
/// <summary>
/// Reads all of the scans in the RAW and looks for out of order data
/// </summary>
/// <param name="rawFile">
/// The RAW file being read
/// </param>
/// <param name="firstScanNumber">
/// The first scan in the RAW file
/// </param>
/// <param name="lastScanNumber">
/// the last scan in the RAW file
/// </param>
private static void AnalyzeAllScans(IRawDataPlus rawFile, int firstScanNumber, int lastScanNumber)
{
// Test the preferred (normal) data and centroid (high resolution/label) data
int failedCentroid = 0;
int failedPreferred = 0;
for (int scanNumber = firstScanNumber; scanNumber <= lastScanNumber; scanNumber++)
{
// Test the scan dependents methods
// var origDependents = rawFile.GetScanDependents(scanNumber, 2);
// Get each scan from the RAW file
var scan = Scan.FromFile(rawFile, scanNumber);
// Check to see if the RAW file contains label (high-res) data and if it is present
// then look for any data that is out of order
if (scan.HasCentroidStream)
{
if (scan.CentroidScan.Length > 0)
{
double currentMass = scan.CentroidScan.Masses[0];
for (int index = 1; index < scan.CentroidScan.Length; index++)
{
if (scan.CentroidScan.Masses[index] > currentMass)
{
currentMass = scan.CentroidScan.Masses[index];
}
else
{
if (failedCentroid == 0)
{
Console.WriteLine("First failure: Failed in scan data at: Scan: " + scanNumber + " Mass: "
+ currentMass.ToString("F4"));
}
failedCentroid++;
}
}
}
}
// Check the normal (non-label) data in the RAW file for any out-of-order data
if (scan.PreferredMasses.Length > 0)
{
double currentMass = scan.PreferredMasses[0];
for (int index = 1; index < scan.PreferredMasses.Length; index++)
{
if (scan.PreferredMasses[index] > currentMass)
{
currentMass = scan.PreferredMasses[index];
}
else
{
if (failedPreferred == 0)
{
Console.WriteLine("First failure: Failed in scan data at: Scan: " + scanNumber + " Mass: "
+ currentMass.ToString("F2"));
}
failedPreferred++;
}
}
}
}
// Display a message indicating if any of the scans had data that was "out of order"
if (failedPreferred == 0 && failedCentroid == 0)
{
Console.WriteLine();
Console.WriteLine("Analysis completed: No out of order data found");
}
else
{
Console.WriteLine();
Console.WriteLine("Analysis completed: Preferred data failed: " + failedPreferred + " Centroid data failed: " + failedCentroid);
}
}
/// <summary>
/// Calculates the mass precision for a spectrum.
/// </summary>
/// <param name="rawFile">
/// The RAW file being read
/// </param>
/// <param name="scanNumber">
/// The scan to process
/// </param>
private static void CalculateMassPrecision(IRawDataPlus rawFile, int scanNumber)
{
// Get the scan from the RAW file
var scan = Scan.FromFile(rawFile, scanNumber);
// Get the scan event and from the scan event get the analyzer type for this scan
var scanEvent = rawFile.GetScanEventForScanNumber(scanNumber);
// Get the trailer extra data to get the ion time for this file
LogEntry logEntry = rawFile.GetTrailerExtraInformation(scanNumber);
var trailerHeadings = new List<string>();
var trailerValues = new List<string>();
for (var i = 0; i < logEntry.Length; i++)
{
trailerHeadings.Add(logEntry.Labels[i]);
trailerValues.Add(logEntry.Values[i]);
}
// Create the mass precision estimate object
IPrecisionEstimate precisionEstimate = new PrecisionEstimate();
// Get the ion time from the trailer extra data values
var ionTime = precisionEstimate.GetIonTime(scanEvent.MassAnalyzer, scan, trailerHeadings, trailerValues);
// Calculate the mass precision for the scan
var listResults = precisionEstimate.GetMassPrecisionEstimate(scan, scanEvent.MassAnalyzer, ionTime, rawFile.RunHeader.MassResolution);
// Output the mass precision results
if (listResults.Count > 0)
{
Console.WriteLine("Mass Precision Results:");
foreach (var result in listResults)
{
Console.WriteLine("Mass {0:F5}, mmu = {1:F3}, ppm = {2:F2}", result.Mass, result.MassAccuracyInMmu, result.MassAccuracyInPpm);
}
}
}
/// <summary>
/// Centroids the specified scan from the RAW file
/// </summary>
/// <param name="rawFile">
/// The RAW file being read
/// </param>
/// <param name="scanNumber">
/// The scan to consider for the centroiding operation
/// </param>
/// <param name="outputData">
/// The output data flag.
/// </param>
private static void CentroidScan(IRawDataPlus rawFile, int scanNumber, bool outputData)
{
// Get the scan from the RAW file
var scan = Scan.FromFile(rawFile, scanNumber);
// Centroid the scan
var centroidedScan = Scan.ToCentroid(scan);
// See if the returned scan object has a centroid stream
if (centroidedScan.HasCentroidStream)
{
Console.WriteLine("Average spectrum ({0} points)", centroidedScan.CentroidScan.Length);
// Print the spectral data (mass, intensity values)
if (outputData)
{
for (int i = 0; i < centroidedScan.CentroidScan.Length; i++)
{
Console.WriteLine(" {0:F4} {1:F0}", centroidedScan.CentroidScan.Masses[0], centroidedScan.CentroidScan.Intensities[i]);
}
}
}
}
/// <summary>
/// Creates a sequence list file
/// </summary>
/// <param name="filename">
/// The name of the sequence list file
/// </param>
private static void CreateSequenceListFile(string filename)
{
// Create the sequence file writer object
var seqFileWriter = SequenceFileWriterFactory.CreateSequenceFileWriter(filename, false);
// Set some of the header values
var fileHeader = new FileHeader
{
FileDescription = "Test Sequence List File",
WhoCreatedId = "me",
WhoCreatedLogon = "you"
};
seqFileWriter.UpdateFileHeader(fileHeader);
// Write a couple of samples to the list
seqFileWriter.Samples.Add(new SampleInformation() { Comment = "Greyhounds", SampleId = "Casper", SampleName = "Casper_1", Vial = "1", Path = "X:\\Junk", RawFileName = "run_1" });
seqFileWriter.Samples.Add(new SampleInformation() { Comment = "Greyhounds", SampleId = "Wendy", SampleName = "Wendy_1", Vial = "2", Path = "X:\\Junk", RawFileName = "run_2" });
seqFileWriter.Samples.Add(new SampleInformation() { Comment = "Greyhounds", SampleId = "Pete", SampleName = "Pete_1", Vial = "3", Path = "X:\\Junk", RawFileName = "run_3" });
seqFileWriter.Samples.Add(new SampleInformation() { Comment = "Greyhounds", SampleId = "Jack", SampleName = "Jack_1", Vial = "4", Path = "X:\\Junk", RawFileName = "run_4" });
// Save the sequence file and then dispose of the file
seqFileWriter.Save();
// Get the sequence writer info object
var info = seqFileWriter.Info;
info.ColumnWidth[0] = 100;
seqFileWriter.Info = info;
// Close/dispose of the file
seqFileWriter.Dispose();
}
/// <summary>
/// Gets the average spectrum from the RAW file.
/// </summary>
/// <param name="rawFile">
/// The RAW file being read
/// </param>
/// <param name="firstScanNumber">
/// The first scan to consider for the averaged spectrum
/// </param>
/// <param name="lastScanNumber">
/// The last scan to consider for the averaged spectrum
/// </param>
/// <param name="outputData">
/// The output data flag.
/// </param>
private static void GetAverageSpectrum(IRawDataPlus rawFile, int firstScanNumber, int lastScanNumber, bool outputData)
{
// Create the mass options object that will be used when averaging the scans
var options = rawFile.DefaultMassOptions();
options.ToleranceUnits = ToleranceUnits.ppm;
options.Tolerance = 5.0;
// Get the scan filter for the first scan. This scan filter will be used to located
// scans within the given scan range of the same type
var scanFilter = rawFile.GetFilterForScanNumber(firstScanNumber);
// Get the average mass spectrum for the provided scan range. In addition to getting the
// average scan using a scan range, the library also provides a similar method that takes
// a time range.
var averageScan = rawFile.AverageScansInScanRange(firstScanNumber, lastScanNumber, scanFilter, options);
if (averageScan.HasCentroidStream)
{
Console.WriteLine("Average spectrum ({0} points)", averageScan.CentroidScan.Length);
// Print the spectral data (mass, intensity values)
if (outputData)
{
for (int i = 0; i < averageScan.CentroidScan.Length; i++)
{
Console.WriteLine(" {0:F4} {1:F0}", averageScan.CentroidScan.Masses[0], averageScan.CentroidScan.Intensities[i]);
}
}
}
// This example uses a different method to get the same average spectrum that was calculated in the
// previous portion of this method. Instead of passing the start and end scan, a list of scans will
// be passed to the GetAveragedMassSpectrum function.
List<int> scans = new List<int>(new[] { 1, 6, 7, 9, 11, 12, 14 });
averageScan = rawFile.AverageScans(scans, options);
if (averageScan.HasCentroidStream)
{
Console.WriteLine("Average spectrum ({0} points)", averageScan.CentroidScan.Length);
// Print the spectral data (mass, intensity values)
if (outputData)
{
for (int i = 0; i < averageScan.CentroidScan.Length; i++)
{
Console.WriteLine(" {0:F4} {1:F0}", averageScan.CentroidScan.Masses[0], averageScan.CentroidScan.Intensities[i]);
}
}
}
Console.WriteLine();
}
/// <summary>
/// Reads the base peak chromatogram for the RAW file
/// </summary>
/// <param name="rawFile">
/// The RAW file being read
/// </param>
/// <param name="startScan">
/// Start scan for the chromatogram
/// </param>
/// <param name="endScan">
/// End scan for the chromatogram
/// </param>
/// <param name="outputData">
/// The output data flag.
/// </param>
private static void GetChromatogram(IRawDataPlus rawFile, int startScan, int endScan, bool outputData)
{
// Define the settings for getting the Base Peak chromatogram
ChromatogramTraceSettings settings = new ChromatogramTraceSettings(TraceType.BasePeak);
// Get the chromatogram from the RAW file.
var data = rawFile.GetChromatogramData(new IChromatogramSettings[] { settings }, startScan, endScan);
// Split the data into the chromatograms
var trace = ChromatogramSignal.FromChromatogramData(data);
if (trace[0].Length > 0)
{
// Print the chromatogram data (time, intensity values)
Console.WriteLine("Base Peak chromatogram ({0} points)", trace[0].Length);
if (outputData)
{
for (int i = 0; i < trace[0].Length; i++)
{
Console.WriteLine(" {0} - {1:F3}, {2:F0}", i, trace[0].Times[i], trace[0].Intensities[i]);
}
}
}
Console.WriteLine();
}
/// <summary>
/// Reads the inclusion/exclusion list from the mass spectrometer method in the RAW file
/// </summary>
/// <param name="rawFile">
/// The RAW file being read
/// </param>
/// <param name="massTolerance">
/// The mass tolerance used when associating an inclusion list item with a spectrum
/// </param>
/// <returns>
/// The <see cref="List"/>.
/// </returns>
private static List<InclusionListItem> GetInclusionExclusionList(IRawDataPlus rawFile, double massTolerance)
{
// Select the MS instrument
rawFile.SelectInstrument(Device.MS, 1);
// Get the instrument method item(s) and look for the inclusion/exclusion list
// which will be flagged by the "Mass List Table"
List<string> inclusionStrings = new List<string>();
for (int i = 0; i < rawFile.InstrumentMethodsCount; i++)
{
var methodText = rawFile.GetInstrumentMethod(i);
if (methodText.Contains("Mass List Table"))
{
bool saveLine = false;
var splitMethod = methodText.Split(new[] { "\n" }, StringSplitOptions.None);
foreach (var line in splitMethod)
{
if (line.Contains("Mass List Table"))
{
saveLine = true;
}
if (line.Contains("End Mass List Table"))
{
saveLine = false;
continue;
}
if (saveLine && !line.Contains("Mass List Table"))
{
inclusionStrings.Add(line);
}
}
}
}
// Create the inclusion/exclusion list
List<InclusionListItem> inclusionList = new List<InclusionListItem>();
// Convert each line from the inclusion/exclusion mass table into InclusionListItem objects
// and add them to the inclusion/exclusion list.
foreach (var line in inclusionStrings)
{
// Skip the title line
if (line.Contains("CompoundName"))
{
continue;
}
// Split the line into its separate fields
var fields = line.Split(new[] { "|" }, StringSplitOptions.None);
if (fields.Length == 4)
{
InclusionListItem inclusionItem = new InclusionListItem() { Descriptor = fields[0] };
inclusionItem.Mass = Convert.ToDouble(fields[1]);
inclusionItem.Threshold = Convert.ToDouble(fields[2]);
inclusionList.Add(inclusionItem);
}
}
// Get the actual scan number for each mass in the inclusion list
for (int scan = rawFile.RunHeaderEx.FirstSpectrum; scan <= rawFile.RunHeaderEx.LastSpectrum; scan++)
{
// Get the scan filter and event for this scan number
var scanFilter = rawFile.GetFilterForScanNumber(scan);
var scanEvent = rawFile.GetScanEventForScanNumber(scan);
// Only consider MS2 scans when looking for the spectrum corr3e
if (scanFilter.MSOrder == MSOrderType.Ms2)
{
// Get the reaction information in order to get the precursor mass for this spectrum
var reaction = scanEvent.GetReaction(0);
double precursorMass = reaction.PrecursorMass;
double tolerance = precursorMass * massTolerance;
// Find the inclusion list item matching this precursor mass
foreach (var item in inclusionList)
{
if (item.Mass >= (precursorMass - tolerance) && (item.Mass <= (precursorMass + tolerance)))
{
item.ScanNumber = scan;
break;
}
}
}
}
return inclusionList;
}
/// <summary>
/// Gets the spectrum from the RAW file.
/// </summary>
/// <param name="rawFile">
/// The RAW file being read
/// </param>
/// <param name="scanNumber">
/// The scan number being read
/// </param>
/// <param name="scanFilter">
/// The scan filter for that scan
/// </param>
/// <param name="outputData">
/// The output data flag.
/// </param>
private static void GetSpectrum(IRawDataPlus rawFile, int scanNumber, bool outputData)
{
// Get the scan statistics from the RAW file for this scan number
var scanStatistics = rawFile.GetScanStatsForScanNumber(scanNumber);
// Check to see if the scan has centroid data or profile data. Depending upon the
// type of data, different methods will be used to read the data. While the ReadAllSpectra
// method demonstrates reading the data using the Scan.FromFile method, generating the
// Scan object takes more time and memory to do, so that method isn't optimum.
if (scanStatistics.IsCentroidScan && scanStatistics.SpectrumPacketType == SpectrumPacketType.FtCentroid)
{
// Get the centroid (label) data from the RAW file for this scan
var centroidStream = rawFile.GetCentroidStream(scanNumber, false);
Console.WriteLine("Spectrum (centroid/label) {0} - {1} points", scanNumber, centroidStream.Length);
// Print the spectral data (mass, intensity, charge values). Not all of the information in the high resolution centroid
// (label data) object is reported in this example. Please check the documentation for more information about what is
// available in high resolution centroid (label) data.
if (outputData)
{
for (int i = 0; i < centroidStream.Length; i++)
{
Console.WriteLine(" {0} - {1:F4}, {2:F0}, {3:F0}", i, centroidStream.Masses[i], centroidStream.Intensities[i], centroidStream.Charges[i]);
}
}
Console.WriteLine();
}
else
{
// Get the segmented (low res and profile) scan data
var segmentedScan = rawFile.GetSegmentedScanFromScanNumber(scanNumber, scanStatistics);
Console.WriteLine("Spectrum (normal data) {0} - {1} points", scanNumber, segmentedScan.Positions.Length);
// Print the spectral data (mass, intensity values)
if (outputData)
{
for (int i = 0; i < segmentedScan.Positions.Length; i++)
{
Console.WriteLine(" {0} - {1:F4}, {2:F0}", i, segmentedScan.Positions[i], segmentedScan.Intensities[i]);
}
}
Console.WriteLine();
}
}
/// <summary>
/// Reads and reports the trailer extra data fields present in the RAW file.
/// </summary>
/// <param name="rawFile">
/// The RAW file
/// </param>
private static void ListTrailerExtraFields(IRawDataPlus rawFile)
{
// Get the Trailer Extra data fields present in the RAW file
var trailerFields = rawFile.GetTrailerExtraHeaderInformation();
// Display each value
int i = 0;
Console.WriteLine("Trailer Extra Data Information:");
foreach (var field in trailerFields)
{
Console.WriteLine(" Field {0} = {1} storing data of type {2}", i, field.Label, field.DataType);
i++;
}
Console.WriteLine();
}
/// <summary>
/// Reads and reports the status log data fields present in the RAW file.
/// </summary>
/// <param name="rawFile">
/// The RAW file
/// </param>
/// <param name="startScan">
/// Start scan for the chromatogram
/// </param>
/// <param name="endScan">
/// End scan for the chromatogram
/// </param>
private static void ListStatusLog(IRawDataPlus rawFile, int startScan, int endScan)
{
// Get the status log header information
var statusLog = rawFile.GetStatusLogHeaderInformation();
// Display each value that is part of the status log. They are stored as label/data type pairs
int i = 0;
Console.WriteLine("Status Log Information:");
foreach (var field in statusLog)
{
if (!field.Label.IsNullOrEmpty() && field.DataType != GenericDataTypes.NULL)
{
Console.WriteLine(" Field {0} = {1} storing data of type {2}", i, field.Label, field.DataType);
}
i++;
}
Console.WriteLine();
// Display the value for item 10 in the status log for each scan
Console.WriteLine("Status Information for item 10:");
for (int scan = startScan; scan < endScan; scan++)
{
// Get the status log for this scan
var time = rawFile.RetentionTimeFromScanNumber(scan);
var logEntry = rawFile.GetStatusLogForRetentionTime(time);
// Print the values for one item
Console.WriteLine(" Scan {0} = {1}", scan, logEntry.Values[10]);
}
Console.WriteLine();
}
/// <summary>
/// Read all spectra in the RAW file.
/// </summary>