forked from compomics/ThermoRawFileParser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainClass.cs
992 lines (899 loc) · 39.8 KB
/
MainClass.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
using System;
using System.Reflection;
using System.IO;
using log4net;
using log4net.Core;
using Mono.Options;
using ThermoFisher.CommonCore.Data;
using System.Linq;
using ThermoRawFileParser.Query;
using ThermoRawFileParser.XIC;
using System.Globalization;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Data;
namespace ThermoRawFileParser
{
public static class MainClass
{
private static readonly ILog Log =
LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public const string Version = "1.4.2";
public static void Main(string[] args)
{
// Set Invariant culture as default for all further processing
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
// Introduce subcommand for xics and spectra query
if (args.Length > 0)
{
switch (args[0])
{
case "xic":
XicParametersParsing(args.Skip(1).ToArray()); // skip first command
break;
case "query":
SpectrumQueryParametersParsing(args.Skip(1).ToArray());
break;
default:
RegularParametersParsing(args);
break;
}
}
else
{
RegularParametersParsing(args);
}
}
private static void XicParametersParsing(string[] args)
{
XicParameters parameters = new XicParameters();
string singleFile = null;
string fileDirectory = null;
string outputFile = null;
string outputDirectory = null;
string logFormatString = null;
var optionSet = new OptionSet
{
{
"h|help", "Prints out the options.",
h => parameters.help = h != null
},
{
"i=|input=", "The raw file input (Required). Specify this or an input directory -d",
v => singleFile = v
},
{
"d=|input_directory=",
"The directory containing the raw files (Required). Specify this or an input file -i.",
v => fileDirectory = v
},
{
"j=|json=",
"The json input file (Required).",
v => parameters.jsonFilePath = v
},
{
"p|print_example",
"Show a json input file example.",
v => parameters.printJsonExample = v != null
},
{
"o=|output=",
"The output directory. Specify this or an output file. Specifying neither writes to the input directory.",
v => outputDirectory = v
},
{
"b=|output_file",
"The output file. Specify this or an output directory. Specifying neither writes to the input directory.",
v => outputFile = v
},
{
"6|base64",
"Encodes the content of the xic vectors as base 64 encoded string.",
v => parameters.base64 = v != null
},
{
"s|stdout",
"Pipes the output into standard output. Logging is being turned off.",
v => parameters.stdout = v != null
},
{
"w|warningsAreErrors", "Return non-zero exit code for warnings; default only for errors",
v => parameters.Vigilant = v != null
},
{
"l=|logging=", "Optional logging level: 0 for silent, 1 for verbose, 2 for default, 3 for warning, 4 for error; both numeric and text (case insensitive) value recognized.",
v => logFormatString = v
}
};
try
{
// parse the command line
var extra = optionSet.Parse(args);
if (!extra.IsNullOrEmpty())
{
throw new OptionException("unexpected extra arguments", null);
}
if (parameters.help)
{
ShowHelp("usage is:", null,
optionSet);
return;
}
if (parameters.printJsonExample)
{
var exampleJson =
"[\n {\n \"mz\":673.363,\n \"tolerance\":10,\n \"tolerance_unit\": \"ppm\",\n },\n {\n \"mz\":867.345,\n \"tolerance\": 0.02,\n \"tolerance_unit\": \"da\",\n \"rt_start\":87.56,\n \"rt_end\":99.56\n }\n]";
Console.WriteLine(exampleJson);
return;
}
if (singleFile != null && !File.Exists(singleFile))
{
throw new OptionException(
"specify a valid RAW file location",
"-i, --input");
}
if (fileDirectory != null && !Directory.Exists(fileDirectory))
{
throw new OptionException(
"specify a valid input directory",
"-d, --input_directory");
}
if (parameters.jsonFilePath == null)
{
throw new OptionException(
"specify an json input file. If you are not sure about the structure of the json file, use -p for printing an examplarily json input file",
"-j, --json");
}
if (parameters.jsonFilePath != null && !File.Exists(parameters.jsonFilePath))
{
throw new OptionException(
"specify a valid json file location",
"-j, --json");
}
if (outputDirectory != null && !Directory.Exists(outputDirectory))
{
throw new OptionException(
"specify a valid output location",
"-o, --output");
}
if ((singleFile == null && fileDirectory == null) || (singleFile != null && fileDirectory != null))
{
throw new OptionException(
"specify either an input file or an input directory",
"-i, --input xor -d, --input_directory");
}
if (outputFile != null && outputDirectory != null)
{
throw new OptionException(
"cannot use an output file and an output directory simultaneously",
"-b, --output_file; -o, --output");
}
if (singleFile != null)
{
parameters.rawFileList.Add(Path.GetFullPath(singleFile));
if (outputFile != null)
{
parameters.outputFileList.Add(Path.GetFullPath(outputFile));
}
else if (outputDirectory != null)
{
parameters.outputFileList.Add(Path.Combine(outputDirectory ?? throw new NoNullAllowedException("Output directory cannot be null"),
Path.GetFileNameWithoutExtension(singleFile) + ".json"));
}
else
{
parameters.outputFileList.Add(Path.Combine(Path.GetDirectoryName(Path.GetFullPath(singleFile)),
Path.GetFileNameWithoutExtension(singleFile) + ".json"));
}
}
else
{
if (outputFile != null)
{
throw new OptionException("Cannot use single output file to proceess a directory, use directory output instead", "-o, --output");
}
else if (outputDirectory != null)
{
outputDirectory = Path.GetFullPath(outputDirectory);
}
else
{
outputDirectory = Path.GetFullPath(fileDirectory);
}
var directoryInfo = new DirectoryInfo(Path.GetFullPath(fileDirectory));
var files = directoryInfo.GetFiles("*", SearchOption.TopDirectoryOnly)
.Where(f => f.Extension.ToLower() == ".raw").ToArray<FileInfo>();
foreach (var file in files)
{
parameters.rawFileList.Add(file.FullName);
parameters.outputFileList.Add(Path.Combine(outputDirectory ?? throw new NoNullAllowedException("Output directory cannot be null"),
Path.GetFileNameWithoutExtension(file.Name) + ".json"));
}
}
if (logFormatString != null)
{
parameters.LogFormat = (LogFormat)ParseToEnum(typeof(LogFormat), logFormatString, "-l, --logging");
}
if (parameters.stdout) parameters.LogFormat = LogFormat.SILENT; //switch off logging in stdout
}
catch (OptionException optionException)
{
ShowHelp("Error - usage is:", optionException,
optionSet);
}
catch (ArgumentNullException)
{
if (parameters.help)
{
ShowHelp("usage is:", null,
optionSet);
}
else
{
ShowHelp("Error - usage is:", null,
optionSet);
}
}
var exitCode = 1;
try
{
switch (parameters.LogFormat)
{
case LogFormat.VERBOSE:
((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root.Level =
Level.Debug;
((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository())
.RaiseConfigurationChanged(EventArgs.Empty);
break;
case LogFormat.SILENT:
((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root.Level =
Level.Off;
((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository())
.RaiseConfigurationChanged(EventArgs.Empty);
break;
case LogFormat.WARNING:
((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root.Level =
Level.Warn;
((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository())
.RaiseConfigurationChanged(EventArgs.Empty);
break;
case LogFormat.ERROR:
((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root.Level =
Level.Error;
((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository())
.RaiseConfigurationChanged(EventArgs.Empty);
break;
}
XicExecutor.Run(parameters);
Log.Info($"Processing completed {parameters.Errors} errors, {parameters.Warnings} warnings");
exitCode = parameters.Vigilant ? parameters.Errors + parameters.Warnings : parameters.Errors;
}
catch (Exception ex)
{
if (ex is RawFileParserException)
{
Log.Error(ex.Message);
}
else
{
Log.Error("An unexpected error occured:");
Log.Error(ex.ToString());
}
}
finally
{
Environment.Exit(exitCode);
}
}
private static void SpectrumQueryParametersParsing(string[] args)
{
string logFormatString = null;
QueryParameters parameters = new QueryParameters();
var optionSet = new OptionSet
{
{
"h|help", "Prints out the options.",
h => parameters.help = h != null
},
{
"i=|input=", "The raw file input (Required).",
v => parameters.rawFilePath = v
},
{
"n=|scans=",
"The scan numbers. e.g. \"1-5, 20, 25-30\"",
v => parameters.scans = v
},
{
"b=|output_file",
"The output file. Specifying none writes the output file to the input file parent directory.",
v => parameters.outputFile = v
},
{
"p|noPeakPicking",
"Don't use the peak picking provided by the native Thermo library. By default peak picking is enabled.",
v => parameters.noPeakPicking = v != null
},
{
"s|stdout",
"Pipes the output into standard output. Logging is being turned off",
v => parameters.stdout = v != null
},
{
"w|warningsAreErrors", "Return non-zero exit code for warnings; default only for errors",
v => parameters.Vigilant = v != null
},
{
"l=|logging=", "Optional logging level: 0 for silent, 1 for verbose, 2 for default, 3 for warning, 4 for error; both numeric and text (case insensitive) value recognized.",
v => logFormatString = v
}
};
try
{
// parse the command line
var extra = optionSet.Parse(args);
if (!extra.IsNullOrEmpty())
{
throw new OptionException("unexpected extra arguments", null);
}
if (parameters.help)
{
ShowHelp("usage is:", null,
optionSet);
return;
}
if (parameters.rawFilePath == null)
{
throw new OptionException(
"specify an input file",
"-i, --input ");
}
if (parameters.rawFilePath != null && !File.Exists(parameters.rawFilePath))
{
throw new OptionException(
"specify a valid RAW file location",
"-i, --input");
}
if (parameters.scans.IsNullOrEmpty())
{
throw new OptionException(
"specify a valid scan range",
"-s, --scans");
}
if (logFormatString != null)
{
parameters.LogFormat = (LogFormat)ParseToEnum(typeof(LogFormat), logFormatString, "-l, --logging");
}
if (parameters.stdout) parameters.LogFormat = LogFormat.SILENT; //switch off logging in stdout
}
catch (OptionException optionException)
{
ShowHelp("Error - usage is:", optionException,
optionSet);
}
catch (ArgumentNullException)
{
if (parameters.help)
{
ShowHelp("usage is:", null,
optionSet);
}
else
{
ShowHelp("Error - usage is:", null,
optionSet);
}
}
var exitCode = 1;
try
{
switch (parameters.LogFormat)
{
case LogFormat.VERBOSE:
((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root.Level =
Level.Debug;
((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository())
.RaiseConfigurationChanged(EventArgs.Empty);
break;
case LogFormat.SILENT:
((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root.Level =
Level.Off;
((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository())
.RaiseConfigurationChanged(EventArgs.Empty);
break;
case LogFormat.WARNING:
((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root.Level =
Level.Warn;
((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository())
.RaiseConfigurationChanged(EventArgs.Empty);
break;
case LogFormat.ERROR:
((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root.Level =
Level.Error;
((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository())
.RaiseConfigurationChanged(EventArgs.Empty);
break;
}
QueryExecutor.Run(parameters);
Log.Info($"Processing completed {parameters.Errors} errors, {parameters.Warnings} warnings");
exitCode = parameters.Vigilant ? parameters.Errors + parameters.Warnings : parameters.Errors;
}
catch (Exception ex)
{
if (ex is RawFileParserException)
{
Log.Error(ex.Message);
}
else
{
Log.Error("An unexpected error occured:");
Log.Error(ex.ToString());
}
}
finally
{
Environment.Exit(exitCode);
}
}
private static void RegularParametersParsing(string[] args)
{
var help = false;
var version = false;
string outputFormatString = null;
string metadataFormatString = null;
string logFormatString = null;
var parseInput = new ParseInput();
var optionSet = new OptionSet
{
{
"h|help", "Prints out the options.",
h => help = h != null
},
{
"version", "Prints out the version of the executable.",
v => version = v != null
},
{
"i=|input=", "The raw file input (Required). Specify this or an input directory -d.",
v => parseInput.RawFilePath = v
},
{
"d=|input_directory=",
"The directory containing the raw files (Required). Specify this or an input raw file -i.",
v => parseInput.RawDirectoryPath = v
},
{
"o=|output=",
"The output directory. Specify this or an output file -b. Specifying neither writes to the input directory.",
v => parseInput.OutputDirectory = v
},
{
"b=|output_file",
"The output file. Specify this or an output directory -o. Specifying neither writes to the input directory.",
v => parseInput.OutputFile = v
},
{
"s|stdout",
"Write to standard output. Cannot be combined with file or directory output. Implies silent logging, i.e. logging level 0",
v => parseInput.StdOut = v != null
},
{
"f=|format=",
"The spectra output format: 0 for MGF, 1 for mzML, 2 for indexed mzML, 3 for Parquet; both numeric and text (case insensitive) value recognized. Defaults to indexed mzML if no format is specified.",
v => outputFormatString = v
},
{
"m=|metadata=", "The metadata output format: 0 for JSON, 1 for TXT; both numeric and text (case insensitive) value recognized",
v => metadataFormatString = v
},
{
"c=|metadata_output_file",
"The metadata output file. By default the metadata file is written to the output directory.",
v => parseInput.MetadataOutputFile = v
},
{
"g|gzip", "GZip the output file.",
v => parseInput.Gzip = v != null
},
{
"p:|noPeakPicking:",
"Don't use the peak picking provided by the native Thermo library. By default peak picking is enabled. Optional argument allows disabling peak peaking only for selected MS levels and should be a comma-separated list of integers (1,2,3) and/or intervals (1-3), open-end intervals (1-) are allowed",
v => parseInput.NoPeakPicking = v is null ? ParseInput.AllLevels : ParseMsLevel(v)
},
{
"z|noZlibCompression",
"Don't use zlib compression for the m/z ratios and intensities. By default zlib compression is enabled.",
v => parseInput.NoZlibCompression = v != null
},
{
"a|allDetectors",
"Extract additional detector data: UV/PDA etc",
v => parseInput.AllDetectors = v != null
},
{
"l=|logging=", "Optional logging level: 0 for silent, 1 for verbose, 2 for default, 3 for warning, 4 for error; both numeric and text (case insensitive) value recognized.",
v => logFormatString = v
},
{
"e|ignoreInstrumentErrors", "Ignore missing properties by the instrument.",
v => parseInput.IgnoreInstrumentErrors = v != null
},
{
"x|excludeExceptionData", "Exclude reference and exception data",
v => parseInput.ExData = v != null
},
{
"L=|msLevel=",
"Select MS levels (MS1, MS2, etc) included in the output, should be a comma-separated list of integers (1,2,3) and/or intervals (1-3), open-end intervals (1-) are allowed",
v => parseInput.MsLevel = ParseMsLevel(v)
},
{
"P|mgfPrecursor",
"Include precursor scan number in MGF file TITLE",
v => parseInput.MgfPrecursor = v != null
},
{
"N|noiseData", "Include noise data in mzML output",
v => parseInput.NoiseData = v != null
},
{
"w|warningsAreErrors", "Return non-zero exit code for warnings; default only for errors",
v => parseInput.Vigilant = v != null
},
{
"u:|s3_url:",
"Optional property to write directly the data into S3 Storage.",
v => parseInput.S3Url = v
},
{
"k:|s3_accesskeyid:",
"Optional key for the S3 bucket to write the file output.",
v => parseInput.S3AccessKeyId = v
},
{
"t:|s3_secretaccesskey:",
"Optional key for the S3 bucket to write the file output.",
v => parseInput.S3SecretAccessKey = v
},
{
"n:|s3_bucketName:",
"S3 bucket name",
v => parseInput.BucketName = v
}
};
try
{
// parse the command line
var extra = optionSet.Parse(args);
if (!extra.IsNullOrEmpty())
{
throw new OptionException("Unexpected extra arguments", null);
}
if (help)
{
var helpMessage =
$"Usage is {Assembly.GetExecutingAssembly().GetName().Name}.exe [subcommand] [options]\noptional subcommands are xic|query (use [subcommand] -h for more info]):";
ShowHelp(helpMessage, null, optionSet);
return;
}
if (version)
{
Console.WriteLine(Version);
return;
}
if (parseInput.RawFilePath == null && parseInput.RawDirectoryPath == null)
{
throw new OptionException(
"specify an input file or an input directory",
"-i, --input or -d, --input_directory");
}
if (parseInput.RawFilePath != null)
{
if (parseInput.RawDirectoryPath != null)
{
throw new OptionException(
"specify an input file or an input directory, not both",
"-i, --input or -d, --input_directory");
}
if (!File.Exists(parseInput.RawFilePath))
{
throw new OptionException(
"specify a valid RAW file location",
"-i, --input");
}
}
if (parseInput.RawDirectoryPath != null && !Directory.Exists(parseInput.RawDirectoryPath))
{
throw new OptionException(
"specify a valid input directory",
"-d, --input_directory");
}
if (parseInput.StdOut && (parseInput.OutputFile != null || parseInput.OutputDirectory != null))
{
throw new OptionException(
"standard output cannot be combined with file or directory output",
"-s, --stdout");
}
if (parseInput.OutputFile == null && parseInput.OutputDirectory == null)
{
if (parseInput.RawFilePath != null)
{
parseInput.OutputDirectory = Path.GetDirectoryName(Path.GetFullPath(parseInput.RawFilePath));
}
else if (parseInput.RawDirectoryPath != null)
{
parseInput.OutputDirectory = parseInput.RawDirectoryPath;
}
}
if (parseInput.OutputFile != null)
{
if (parseInput.OutputDirectory == null)
{
parseInput.OutputDirectory = Path.GetDirectoryName(parseInput.OutputFile);
}
else
{
throw new OptionException(
"specify an output directory or an output file, not both",
"-o, --output or -b, --output_file");
}
if (Directory.Exists(parseInput.OutputFile))
{
throw new OptionException(
"specify a valid output file, not a directory",
"-b, --output_file");
}
if (parseInput.RawDirectoryPath != null)
{
throw new OptionException(
"when using an input directory, specify an output directory instead of an output file",
"-o, --output instead of -b, --output_file");
}
}
if (!parseInput.OutputDirectory.IsNullOrEmpty() && !Directory.Exists(parseInput.OutputDirectory))
{
throw new OptionException(
"specify a valid output directory",
"-o, --output");
}
if (metadataFormatString == null && outputFormatString == null)
{
parseInput.OutputFormat = OutputFormat.IndexMzML;
}
if (outputFormatString != null)
{
parseInput.OutputFormat = (OutputFormat)ParseToEnum(typeof(OutputFormat), outputFormatString, "-f, --format");
}
if (metadataFormatString != null)
{
parseInput.MetadataFormat = (MetadataFormat)ParseToEnum(typeof(MetadataFormat), metadataFormatString, "-m, --metadata");
}
if (parseInput.MetadataOutputFile != null && Directory.Exists(parseInput.MetadataOutputFile))
{
throw new OptionException(
"specify a valid metadata output file, not a directory",
"-c, --metadata_output_file");
}
if (parseInput.MetadataOutputFile != null && parseInput.MetadataFormat == MetadataFormat.NONE)
{
throw new OptionException("specify a metadata format (0 for JSON, 1 for TXT)",
"-m, --metadata");
}
if (parseInput.MetadataOutputFile != null && parseInput.RawDirectoryPath != null)
{
throw new OptionException(
"when using an input directory, specify an output directory instead of a metadata output file",
"-o, --output instead of -c, --metadata_output_file");
}
if (logFormatString != null)
{
parseInput.LogFormat = (LogFormat)ParseToEnum(typeof(LogFormat), logFormatString, "-l, --logging");
}
if (parseInput.StdOut)
{
parseInput.LogFormat = LogFormat.SILENT;
//use non-indexed mzML with stdout
if (parseInput.OutputFormat == OutputFormat.IndexMzML) parseInput.OutputFormat = OutputFormat.MzML;
}
if (parseInput.S3Url != null && parseInput.S3AccessKeyId != null &&
parseInput.S3SecretAccessKey != null && parseInput.BucketName != null)
if (Uri.IsWellFormedUriString(parseInput.S3Url, UriKind.Absolute))
{
parseInput.InitializeS3Bucket();
}
else
{
throw new RawFileParserException("Invalid S3 url: " + parseInput.S3Url);
}
}
catch (OptionException optionException)
{
ShowHelp("Error - usage is:", optionException,
optionSet);
}
catch (ArgumentNullException)
{
if (help)
{
ShowHelp("usage is:", null,
optionSet);
}
else
{
ShowHelp("Error - usage is:", null,
optionSet);
}
}
var exitCode = 1;
try
{
switch (parseInput.LogFormat)
{
case LogFormat.VERBOSE:
((log4net.Repository.Hierarchy.Hierarchy) LogManager.GetRepository()).Root.Level =
Level.Debug;
((log4net.Repository.Hierarchy.Hierarchy) LogManager.GetRepository())
.RaiseConfigurationChanged(EventArgs.Empty);
break;
case LogFormat.SILENT:
((log4net.Repository.Hierarchy.Hierarchy) LogManager.GetRepository()).Root.Level =
Level.Off;
((log4net.Repository.Hierarchy.Hierarchy) LogManager.GetRepository())
.RaiseConfigurationChanged(EventArgs.Empty);
break;
case LogFormat.WARNING:
((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root.Level =
Level.Warn;
((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository())
.RaiseConfigurationChanged(EventArgs.Empty);
break;
case LogFormat.ERROR:
((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root.Level =
Level.Error;
((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository())
.RaiseConfigurationChanged(EventArgs.Empty);
break;
}
RawFileParser.Parse(parseInput);
Log.Info($"Processing completed {parseInput.Errors} errors, {parseInput.Warnings} warnings");
exitCode = parseInput.Vigilant ? parseInput.Errors + parseInput.Warnings: parseInput.Errors;
}
catch (UnauthorizedAccessException ex)
{
Log.Error(!ex.Message.IsNullOrEmpty()
? ex.Message
: "Attempting to write to an unauthorized location.");
}
catch (Amazon.S3.AmazonS3Exception ex)
{
Log.Error(!ex.Message.IsNullOrEmpty()
? "An Amazon S3 exception occured: " + ex.Message
: "An Amazon S3 exception occured: " + ex);
}
catch (Exception ex)
{
if (ex is RawFileParserException)
{
Log.Error(ex.Message);
}
else
{
Log.Error("An unexpected error occured:");
Log.Error(ex.ToString());
}
}
finally
{
Environment.Exit(exitCode);
}
}
/// <summary>
/// Show the help message
/// </summary>
/// <param name="message">the help message</param>
/// <param name="optionException">the option exception, can be null</param>
/// <param name="optionSet">the option set object</param>
private static void ShowHelp(string message, OptionException optionException, OptionSet optionSet)
{
if (optionException != null)
{
if (!optionException.OptionName.IsNullOrEmpty())
{
Console.Error.Write(optionException.OptionName + ": ");
}
Console.Error.WriteLine(optionException.Message);
}
Console.Error.WriteLine(message);
optionSet.WriteOptionDescriptions(Console.Error);
Environment.Exit(-1);
}
private static string GetValidEnumLevels(Type enumType)
{
List<string> output = new List<string>();
foreach (int v in Enum.GetValues(enumType))
{
output.Add(String.Format("{0} ({1})", Enum.GetName(enumType, v), v));
}
return String.Join("\n", output);
}
private static int ParseToEnum(Type enumType, string formatString, string keyName)
{
if (int.TryParse(formatString, out var formatInt)) //can be parsed as int
{
if (Enum.IsDefined(enumType, formatInt))
{
return formatInt;
}
else
{
throw new OptionException(
String.Format("unknown format value, the following values recognized (case insensitive)\n{0}", GetValidEnumLevels(enumType)),
keyName);
}
}
else //try parse as a string
{
try
{
return (int)Enum.Parse(enumType, formatString, true);
}
catch (Exception)
{
throw new OptionException(
String.Format("unknown format value, the following values recognized (case insensitive)\n{0}", GetValidEnumLevels(enumType)),
keyName);
}
}
}
private static HashSet<int> ParseMsLevel(string inputString)
{
HashSet<int> result = new HashSet<int>();
Regex valid = new Regex(@"^[\d,\-\s]+$");
Regex interval = new Regex(@"^\s*(\d+)?\s*(-)?\s*(\d+)?\s*$");
if (!valid.IsMatch(inputString))
throw new OptionException("Invalid characters in msLevel key", "msLevel");
foreach (var piece in inputString.Split(new char[] {','}))
{
try
{
int start;
int end;
var intervalMatch = interval.Match(piece);
if (!intervalMatch.Success)
throw new OptionException();
if (intervalMatch.Groups[2].Success) //it is interval
{
if (intervalMatch.Groups[1].Success)
start = Math.Max(1, int.Parse(intervalMatch.Groups[1].Value));
else
start = 1;
if (intervalMatch.Groups[3].Success)
end = Math.Min(10, int.Parse(intervalMatch.Groups[3].Value));
else
end = 10;
}
else
{
if (intervalMatch.Groups[1].Success)
end = start = int.Parse(intervalMatch.Groups[1].Value);
else
throw new OptionException();
if (intervalMatch.Groups[3].Success)
throw new OptionException();
}
for (int l = start; l <= end; l++)
{
result.Add(l);
}
}
catch (Exception ex)
{
throw new OptionException(String.Format("Cannot parse part of msLevel input: '{0}'", piece),
"msLevel", ex);
}
}
return result;
}
}
}