-
Notifications
You must be signed in to change notification settings - Fork 4
/
Program.cs
624 lines (509 loc) · 24.1 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using MASIC.Options;
using PRISM;
using PRISM.Logging;
#if GUI
using System.Windows.Forms;
using ProgressFormNET;
#endif
namespace MASIC
{
// See clsMASIC for a program description
//
// -------------------------------------------------------------------------------
// 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
/// <summary>
/// Entry class for the GUI and console versions of MASIC
/// </summary>
public static class Program
{
// Ignore Spelling: bool, MASIC
/// <summary>
/// Program date
/// </summary>
public const string PROGRAM_DATE = "August 8, 2024";
private static string mInputFilePath;
private static string mOutputDirectoryPath; // Optional
private static string mParameterFilePath; // Optional
private static string mOutputDirectoryAlternatePath; // Optional
private static bool mRecreateDirectoryHierarchyInAlternatePath; // Optional
private static string mDatasetLookupFilePath; // Optional
private static int mDatasetID;
private static bool mRecurseDirectories;
private static int mMaxLevelsToRecurse;
private static bool mLogMessagesToFile;
private static string mLogFilePath = string.Empty;
private static string mLogDirectoryPath = string.Empty;
private static string mMASICStatusFilename = string.Empty;
private static bool mCreateParamFile;
private static string mExampleParamFilePath;
private static bool mQuietMode;
private static clsMASIC mMASIC;
#if GUI
private static frmProgress mProgressForm;
// Uncomment to test DPI scaling
//[System.Runtime.InteropServices.DllImport("user32.dll")]
//private static extern bool SetProcessDPIAware();
#endif
private static DateTime mLastSubtaskProgressTime;
private static DateTime mLastProgressReportTime;
private static int mLastProgressReportValue;
/// <summary>
/// Entry method
/// </summary>
/// <returns>0 if no error; error code if an error</returns>
[STAThread]
public static int Main()
{
#if GUI
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Uncomment to test DPI scaling
//if (Environment.OSVersion.Version.Major >= 6)
// SetProcessDPIAware();
#endif
var commandLineParser = new clsParseCommandLine();
mInputFilePath = string.Empty;
mOutputDirectoryPath = string.Empty;
mParameterFilePath = string.Empty;
mRecurseDirectories = false;
mMaxLevelsToRecurse = 0;
mQuietMode = false;
mLogMessagesToFile = false;
mLogFilePath = string.Empty;
mLastSubtaskProgressTime = DateTime.UtcNow;
try
{
var proceed = commandLineParser.ParseCommandLine() && SetOptionsUsingCommandLineParameters(commandLineParser);
if (commandLineParser.ParameterCount + commandLineParser.NonSwitchParameterCount == 0 && !commandLineParser.NeedToShowHelp)
{
#if GUI
ShowGUI();
#else
ShowProgramHelp();
#endif
return 0;
}
if (mCreateParamFile)
{
CreateExampleParameterFile();
return 0;
}
if (!proceed || commandLineParser.NeedToShowHelp || mInputFilePath.Length == 0)
{
ShowProgramHelp();
return -1;
}
var returnCode = ProcessFiles();
if (returnCode != 0)
{
AppUtils.SleepMilliseconds(1500);
}
return returnCode;
}
catch (Exception ex)
{
ShowErrorMessage("Error occurred in Program->Main: " + Environment.NewLine + ex.Message);
AppUtils.SleepMilliseconds(1500);
return -1;
}
#if GUI
finally
{
if (mProgressForm != null)
{
mProgressForm.HideForm();
mProgressForm = null;
}
}
#endif
}
private static void CreateExampleParameterFile()
{
var masicProcessor = new clsMASIC();
RegisterMasicEvents(masicProcessor);
masicProcessor.CreateExampleParameterFile(mExampleParamFilePath);
}
private static void DisplayProgressPercent(int percentComplete, bool addCarriageReturn)
{
if (addCarriageReturn)
{
Console.WriteLine();
}
if (percentComplete > 100)
percentComplete = 100;
Console.Write("Processing: " + percentComplete + "% ");
if (addCarriageReturn)
{
Console.WriteLine();
}
}
private static string GetAppVersion()
{
return AppUtils.GetAppVersion(PROGRAM_DATE);
}
private static int ProcessFiles()
{
mMASIC = new clsMASIC();
RegisterMasicEvents(mMASIC);
mMASIC.Options.DatasetLookupFilePath = mDatasetLookupFilePath;
mMASIC.Options.SICOptions.DatasetID = mDatasetID;
if (!string.IsNullOrEmpty(mMASICStatusFilename))
{
mMASIC.Options.MASICStatusFilename = mMASICStatusFilename;
}
mMASIC.LogMessagesToFile = mLogMessagesToFile;
mMASIC.LogFilePath = mLogFilePath;
mMASIC.LogDirectoryPath = mLogDirectoryPath;
if (!mQuietMode)
{
#if GUI
mProgressForm = new frmProgress();
mProgressForm.InitializeProgressForm("Parsing " + Path.GetFileName(mInputFilePath), 0, 100, false, true);
mProgressForm.InitializeSubtask(string.Empty, 0, 100, false);
mProgressForm.ResetKeyPressAbortProcess();
mProgressForm.Show();
Application.DoEvents();
#else
Console.WriteLine("Parsing " + Path.GetFileName(mInputFilePath));
#endif
}
if (mRecurseDirectories)
{
// This call will lead to calls to method ProcessFile in clsMASIC
if (mMASIC.ProcessFilesAndRecurseDirectories(
mInputFilePath, mOutputDirectoryPath,
mOutputDirectoryAlternatePath, mRecreateDirectoryHierarchyInAlternatePath,
mParameterFilePath, mMaxLevelsToRecurse))
{
return 0;
}
return (int)mMASIC.ErrorCode;
}
if (mMASIC.ProcessFilesWildcard(mInputFilePath, mOutputDirectoryPath, mParameterFilePath))
{
return 0;
}
var returnCode = (int)mMASIC.ErrorCode;
if (returnCode != 0)
{
Console.WriteLine("Error while processing: " + mMASIC.GetErrorMessage());
}
return returnCode;
}
private static void RegisterEvents(IEventNotifier sourceClass)
{
sourceClass.StatusEvent += StatusEventHandler;
sourceClass.DebugEvent += DebugEventHandler;
sourceClass.ErrorEvent += ErrorEventHandler;
sourceClass.WarningEvent += WarningEventHandler;
}
private static void RegisterMasicEvents(clsMASIC sourceClass)
{
RegisterEvents(sourceClass);
sourceClass.ProgressUpdate += ProgressUpdateHandler;
sourceClass.ProgressResetKeypressAbort += ProgressResetKeypressAbortHandler;
sourceClass.ProgressSubtaskChanged += ProgressSubtaskChangedHandler;
}
/// <summary>
/// Set options using command line arguments
/// </summary>
/// <param name="commandLineParser"></param>
/// <returns>True if no problems; otherwise, false</returns>
private static bool SetOptionsUsingCommandLineParameters(clsParseCommandLine commandLineParser)
{
var validParameters = new List<string> {
"I", "O", "P", "D", "S", "A", "R", "L", "Log", "SF", "LogDir", "LogFolder", "CreateParamFile", "Q"
};
try
{
// Make sure no invalid parameters are present
if (commandLineParser.InvalidParametersPresent(validParameters))
{
ShowErrorMessage("Invalid command line parameters",
(from item in commandLineParser.InvalidParameters(validParameters) select ("/" + item)).ToList());
return false;
}
// Query commandLineParser to see if various parameters are present
if (commandLineParser.RetrieveValueForParameter("I", out var inputFilePath))
{
mInputFilePath = inputFilePath;
}
else if (commandLineParser.NonSwitchParameterCount > 0)
{
// Treat the first non-switch parameter as the input file
mInputFilePath = commandLineParser.RetrieveNonSwitchParameter(0);
}
if (commandLineParser.RetrieveValueForParameter("O", out var outputDirectoryPath))
mOutputDirectoryPath = outputDirectoryPath;
if (commandLineParser.RetrieveValueForParameter("P", out var parameterFilePath))
mParameterFilePath = parameterFilePath;
if (commandLineParser.RetrieveValueForParameter("D", out var datasetIdOrLookupFile))
{
if (int.TryParse(datasetIdOrLookupFile, out var datasetId))
{
mDatasetID = datasetId;
}
else if (!string.IsNullOrWhiteSpace(datasetIdOrLookupFile))
{
// Assume the user specified a dataset number lookup file comma, space, or tab delimited file specifying the dataset number for each input file)
mDatasetLookupFilePath = datasetIdOrLookupFile;
mDatasetID = 0;
}
}
if (commandLineParser.RetrieveValueForParameter("S", out var recursionDepth))
{
mRecurseDirectories = true;
if (int.TryParse(recursionDepth, out var levelsToRecurse))
{
mMaxLevelsToRecurse = levelsToRecurse;
}
}
if (commandLineParser.RetrieveValueForParameter("A", out var alternateOutputDirectory))
mOutputDirectoryAlternatePath = alternateOutputDirectory;
if (commandLineParser.IsParameterPresent("R"))
mRecreateDirectoryHierarchyInAlternatePath = true;
var logFileName = string.Empty;
var logToFile = false;
if (commandLineParser.IsParameterPresent("L"))
{
logToFile = commandLineParser.RetrieveValueForParameter("L", out logFileName);
}
else if (commandLineParser.IsParameterPresent("Log"))
{
logToFile = commandLineParser.RetrieveValueForParameter("Log", out logFileName);
}
if (logToFile)
{
mLogMessagesToFile = true;
if (!string.IsNullOrEmpty(logFileName))
{
mLogFilePath = logFileName.Trim('"');
}
}
if (commandLineParser.RetrieveValueForParameter("SF", out var masicStatusFile))
{
mMASICStatusFilename = masicStatusFile;
}
if (commandLineParser.RetrieveValueForParameter("LogDir", out var logDirectoryPath))
{
mLogMessagesToFile = true;
if (!string.IsNullOrEmpty(logDirectoryPath))
{
mLogDirectoryPath = logDirectoryPath;
}
}
if (commandLineParser.RetrieveValueForParameter("LogFolder", out var logFolderPath))
{
mLogMessagesToFile = true;
if (!string.IsNullOrEmpty(logFolderPath))
{
mLogDirectoryPath = logFolderPath;
}
}
if (commandLineParser.RetrieveValueForParameter("CreateParamFile", out var exampleParamFilePath))
{
mCreateParamFile = true;
if (!string.IsNullOrEmpty(exampleParamFilePath))
{
mExampleParamFilePath = exampleParamFilePath;
}
}
if (commandLineParser.IsParameterPresent("Q"))
mQuietMode = true;
return true;
}
catch (Exception ex)
{
ShowErrorMessage("Error parsing the command line parameters: " + Environment.NewLine + ex.Message);
}
return false;
}
private static void ShowErrorMessage(string message, Exception ex = null)
{
ConsoleMsgUtils.ShowError(message, ex);
}
private static void ShowErrorMessage(string title, IEnumerable<string> errorMessages)
{
ConsoleMsgUtils.ShowErrors(title, errorMessages);
}
#if GUI
/// <summary>
/// Show the GUI
/// </summary>
public static void ShowGUI()
{
Application.EnableVisualStyles();
Application.DoEvents();
var mainWindow = new frmMain();
// The following call is needed because the .ShowDialog() call is inexplicably increasing the size of the form
mainWindow.SetHeightAdjustForce(mainWindow.Height);
mainWindow.ShowDialog();
}
#endif
private static void ShowProgramHelp()
{
try
{
Console.WriteLine(ConsoleMsgUtils.WrapParagraph(
"This program will read a Thermo .RAW file, .mzML file, .mzXML file, or Agilent LC/MSD .CDF/.MGF file combo " +
"and create a selected ion chromatogram (SIC) for each parent ion. " +
"It also supports extracting reporter ion intensities (e.g. iTRAQ or TMT), " +
"and additional metadata from mass spectrometer data files."));
Console.WriteLine();
Console.WriteLine("Program syntax:" + Environment.NewLine + Path.GetFileName(AppUtils.GetAppPath()));
Console.WriteLine(" /I:InputFilePath [/O:OutputDirectoryPath]");
Console.WriteLine(" [/P:ParamFilePath] [/D:DatasetID or DatasetLookupFilePath] ");
Console.WriteLine(" [/S:[MaxLevel]] [/A:AlternateOutputDirectoryPath] [/R]");
Console.WriteLine(" [/L:[LogFilePath]] [/LogDir:LogDirPath] [/SF:StatusFileName]");
Console.WriteLine(" [/CreateParamFile:FileName.xml] [/Q]");
Console.WriteLine();
Console.WriteLine("The input file path can contain the wildcard character *");
Console.WriteLine("It will typically point to an instrument data file (e.g. Thermo .raw file)");
Console.WriteLine();
Console.WriteLine(ConsoleMsgUtils.WrapParagraph(
// ReSharper disable once StringLiteralTypo
"If the input file name ends with _SICstats.txt, MASIC will create plots using existing results. " +
"If a _ReporterIons.txt file is also present, the Reporter Ion Observation Rate plots will also be made"));
Console.WriteLine();
Console.WriteLine(ConsoleMsgUtils.WrapParagraph(
"The output directory name is optional. " +
"If omitted, the output files will be created in the same directory as the input file. " +
"If included, a subdirectory will be created with the name OutputDirectoryName."));
Console.WriteLine();
Console.WriteLine(ConsoleMsgUtils.WrapParagraph(
"The parameter file switch /P is optional. " +
"If supplied, it should point to a valid MASIC XML parameter file. If omitted, defaults are used." +
"Create a parameter file for MASIC using the MASIC GUI. " +
"Alternatively, download a file from GitHub: https://github.com/PNNL-Comp-Mass-Spec/MASIC/tree/master/ExampleData/Parameter_Files"));
Console.WriteLine();
Console.WriteLine(ConsoleMsgUtils.WrapParagraph(
"The /D switch can be used to specify the Dataset ID of the input file; if omitted, 0 will be used"));
Console.WriteLine();
Console.WriteLine(ConsoleMsgUtils.WrapParagraph(
"Alternatively, a lookup file can be specified with the /D switch (useful if processing multiple files using * or /S). " +
"The lookup file is a comma, space, or tab delimited file with two columns:" + Environment.NewLine + "Dataset Name and Dataset ID"));
Console.WriteLine();
Console.WriteLine(ConsoleMsgUtils.WrapParagraph(
"Use /S to process all valid files in the input directory and subdirectories. " +
"Include a number after /S (like /S:2) to limit the level of subdirectories to examine."));
Console.WriteLine("When using /S, you can redirect the output of the results using /A.");
Console.WriteLine(ConsoleMsgUtils.WrapParagraph(
"When using /S, you can use /R to re-create the input directory hierarchy in the alternate output directory (if defined)."));
Console.WriteLine();
Console.WriteLine(ConsoleMsgUtils.WrapParagraph(
"Use /L or /Log to specify that a log file should be created. " +
"Use /L:LogFilePath to specify the name (or full path) for the log file."));
Console.WriteLine();
Console.WriteLine(ConsoleMsgUtils.WrapParagraph(
"Use /SF to specify the name to use for the MASIC Status file (default is " + MASICOptions.DEFAULT_MASIC_STATUS_FILE_NAME + ")."));
Console.WriteLine();
Console.WriteLine("Use /CreateParamFile to create an example parameter file named MASIC_ExampleSettings.xml");
Console.WriteLine("Include a colon and a filename to customize the filename");
Console.WriteLine();
Console.WriteLine("The optional /Q switch will prevent the progress window from being shown");
Console.WriteLine();
Console.WriteLine("Program written by Matthew Monroe for the Department of Energy (PNNL, Richland, WA)");
Console.WriteLine("Version: " + GetAppVersion());
Console.WriteLine();
Console.WriteLine("E-mail: [email protected] or [email protected]");
Console.WriteLine("Website: https://github.com/PNNL-Comp-Mass-Spec/ or https://www.pnnl.gov/integrative-omics");
Console.WriteLine();
// Delay for 750 msec in case the user double-clicked this file from within Windows Explorer (or started the program via a shortcut)
Thread.Sleep(750);
}
catch (Exception ex)
{
ShowErrorMessage("Error displaying the program syntax: " + ex.Message);
}
}
private static void ProgressUpdateHandler(string taskDescription, float percentComplete)
{
const int PROGRESS_DOT_INTERVAL_MSEC = 250;
#if GUI
const int PERCENT_REPORT_INTERVAL = 25;
if (mProgressForm != null)
{
mProgressForm.UpdateCurrentTask(mMASIC.ProgressStepDescription);
mProgressForm.UpdateProgressBar(percentComplete);
if (mProgressForm.KeyPressAbortProcess)
{
mMASIC.AbortProcessingNow();
}
Application.DoEvents();
return;
}
#else
const int PERCENT_REPORT_INTERVAL = 5;
#endif
if (percentComplete >= mLastProgressReportValue)
{
Console.WriteLine();
DisplayProgressPercent(mLastProgressReportValue, false);
Console.WriteLine();
mLastProgressReportValue += PERCENT_REPORT_INTERVAL;
mLastProgressReportTime = DateTime.UtcNow;
}
else if (DateTime.UtcNow.Subtract(mLastProgressReportTime).TotalMilliseconds > PROGRESS_DOT_INTERVAL_MSEC)
{
mLastProgressReportTime = DateTime.UtcNow;
Console.Write(".");
}
}
private static void ProgressResetKeypressAbortHandler()
{
#if GUI
mProgressForm?.ResetKeyPressAbortProcess();
#endif
}
private static void ProgressSubtaskChangedHandler()
{
#if GUI
if (mProgressForm != null)
{
mProgressForm.UpdateCurrentSubTask(mMASIC.SubtaskDescription);
mProgressForm.UpdateSubtaskProgressBar(mMASIC.SubtaskProgressPercentComplete);
if (mProgressForm.KeyPressAbortProcess)
{
mMASIC.AbortProcessingNow();
}
Application.DoEvents();
return;
}
#endif
if (DateTime.UtcNow.Subtract(mLastSubtaskProgressTime).TotalSeconds < 10)
return;
mLastSubtaskProgressTime = DateTime.UtcNow;
ConsoleMsgUtils.ShowDebug("{0}: {1}%", mMASIC.SubtaskDescription, mMASIC.SubtaskProgressPercentComplete);
}
private static void StatusEventHandler(string message)
{
Console.WriteLine(message);
}
private static void DebugEventHandler(string message)
{
ConsoleMsgUtils.ShowDebug(message);
}
private static void ErrorEventHandler(string message, Exception ex)
{
ShowErrorMessage(message, ex);
}
private static void WarningEventHandler(string message)
{
ConsoleMsgUtils.ShowWarning(message);
}
}
}