public MsScan(int scanNumber, XRawFileIO reader)
        {
            ScanNumber = scanNumber;

            if (!reader.GetScanInfo(scanNumber, out var scanInfo))
            {
                ConsoleMsgUtils.ShowWarning("Scan {0} not found in {1}", scanNumber, Path.GetFileName(reader.RawFilePath));
                return;
            }

            // Get centroided data
            var dataPointCount = GetScanData(reader, scanInfo, out var mzList, out var intensityList);

            MsLevel    = scanInfo.MSLevel;
            PeaksCount = dataPointCount;

            switch (scanInfo.IonMode)
            {
            case IonModeConstants.Positive:
                Polarity = "+";
                break;

            case IonModeConstants.Negative:
                Polarity = "-";
                break;

            case IonModeConstants.Unknown:
                Polarity = string.Empty;
                break;
            }

            FilterLine = scanInfo.FilterText;
            ScanType   = GetScanType();

            RetentionTime = "PT" + Math.Round(scanInfo.RetentionTime * 60, 8) + "S";
            TotIonCurrent = scanInfo.TotalIonCurrent;

            string encodedPeaks;

            if (PeaksCount == 0)
            {
                LowMz             = 0;
                HighMz            = 0;
                BasePeakMz        = 0;
                BasePeakIntensity = 0;

                encodedPeaks = Base64EncodeMsData(mzList, intensityList);
            }
            else
            {
                LowMz             = mzList.Min();
                HighMz            = mzList.Max();
                BasePeakMz        = scanInfo.BasePeakMZ;
                BasePeakIntensity = scanInfo.BasePeakIntensity;

                encodedPeaks = Base64EncodeMsData(mzList, intensityList);
            }

            PeakData = new Peaks(32, "network", "m/z-int", "none", 0, encodedPeaks);
        }
Example #2
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        private static void Main()
        {
            // Start the main program running
            try
            {
                if (mMainProcess == null)
                {
                    mMainProcess = new MainProgram();
                    if (!mMainProcess.InitMgr())
                    {
                        PRISM.Logging.FileLogger.FlushPendingMessages();
                        return;
                    }
                    mMainProcess.DoDirectoryCreation();
                }
            }
            catch (Exception ex)
            {
                var errMsg = "Critical exception starting application: " + ex.Message;
                ConsoleMsgUtils.ShowWarning(errMsg + "; " + StackTraceFormatter.GetExceptionStackTrace(ex));
                ConsoleMsgUtils.ShowWarning("Exiting clsMainProcess.Main with error code = 1");
            }

            PRISM.Logging.FileLogger.FlushPendingMessages();
        }
Example #3
0
        private static int ProcessSQLiteDB(FileInfo fiSourceFile, string sourceTableName)
        {
            try
            {
                var runner = new Runner
                {
                    ShowProgressAtConsole = true
                };
                RegisterEvents(runner);

                var success = runner.ProcessSQLite(fiSourceFile.DirectoryName, fiSourceFile.Name, sourceTableName);

                if (success)
                {
                    Console.WriteLine();
                    Console.WriteLine("Processing complete");
                    ProgRunner.SleepMilliseconds(750);
                    return(0);
                }

                ConsoleMsgUtils.ShowWarning("Error computing protein parsimony: RunAlgorithm reports false");
                ProgRunner.SleepMilliseconds(1500);
                return(-3);
            }
            catch (Exception ex)
            {
                ConsoleMsgUtils.ShowError("Error computing protein parsimony", ex);
                ProgRunner.SleepMilliseconds(1500);
                return(-2);
            }
        }
Example #4
0
        private static void ShowGUI()
        {
            Application.EnableVisualStyles();
            Application.DoEvents();
            try
            {
                var handle = GetConsoleWindow();

                if (!mDebugMode)
                {
                    // Hide the console
                    ShowWindow(handle, SW_HIDE);
                }

                var objFormMain = new GUI()
                {
                    KeepDB = mKeepDB
                };

                objFormMain.ShowDialog();

                if (!mDebugMode)
                {
                    // Show the console
                    ShowWindow(handle, SW_SHOW);
                }
            }
            catch (Exception ex)
            {
                ConsoleMsgUtils.ShowWarning("Error in ShowGUI: " + ex.Message);
                ConsoleMsgUtils.ShowWarning(StackTraceFormatter.GetExceptionStackTraceMultiLine(ex));

                MessageBox.Show("Error in ShowGUI: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
Example #5
0
        private static void ShowWarning(string message)
        {
            Console.WriteLine();
            var msg = "Warning: " + message;

            ConsoleMsgUtils.ShowWarning(msg);
            mLogFile?.WriteLine(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\t" + msg);
        }
Example #6
0
 /// <summary>
 /// Validate the options
 /// </summary>
 /// <returns>True if all options are valid</returns>
 /// <remarks>This method is called from Program.cs</remarks>
 // ReSharper disable once UnusedMember.Global
 public bool Validate()
 {
     if (string.IsNullOrWhiteSpace(InputFilePathSpec))
     {
         ConsoleMsgUtils.ShowWarning("Error: Input file spec must be provided and non-empty, for example *.tsv");
         return(false);
     }
     return(true);
 }
Example #7
0
 private void WarnOnce(WriteWarnings code, string message)
 {
     if (warningTracker.Contains(code))
     {
         return;
     }
     warningTracker.Add(code);
     ConsoleMsgUtils.ShowWarning(string.Format("WARNING: {0}!", message));
 }
Example #8
0
 private static void PeptideHitResultsProcRunner_WarningEvent(string message)
 {
     if (message.StartsWith("Warning", StringComparison.OrdinalIgnoreCase))
     {
         ConsoleMsgUtils.ShowWarning(message);
     }
     else
     {
         ConsoleMsgUtils.ShowWarning("Warning: " + message);
     }
 }
Example #9
0
        private static void AssureDirectoryExists(DirectoryInfo directoryInfo)
        {
            if (directoryInfo == null || directoryInfo.Exists)
            {
                return;
            }

            ConsoleMsgUtils.ShowWarning("Creating missing directory: " + directoryInfo.FullName);
            directoryInfo.Create();
            Console.WriteLine();
        }
Example #10
0
        private void StoreKey(int linesRead, string sectionName, IDictionary <string, string> sectionInfo, string key, string value)
        {
            if (sectionInfo.ContainsKey(key))
            {
                ConsoleMsgUtils.ShowWarning(
                    "Line {0} has a duplicate key named {1} in section {2}; ignoring duplicate value {3}",
                    linesRead, key, sectionName, value);
            }

            sectionInfo.Add(key, value);
        }
Example #11
0
        private void Parse()
        {
            _rows.Clear();
            _data.Clear();
            _header.Clear();

            var headerParsed = false;

            using (var reader = new StreamReader(new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
            {
                while (!reader.EndOfStream)
                {
                    var line = reader.ReadLine();
                    if (string.IsNullOrWhiteSpace(line))
                    {
                        continue;
                    }

                    var token = line.Split(_delimeter);
                    if (!headerParsed)
                    {
                        for (var i = 0; i < token.Length; i++)
                        {
                            if (_data.ContainsKey(token[i]))
                            {
                                ConsoleMsgUtils.ShowWarning("Warning: header line has duplicate column names; ignoring duplicate " + token[i]);
                                continue;
                            }
                            _header.Add(i, token[i]);
                            _data[token[i]] = new List <string>();
                        }
                        headerParsed = true;
                        continue;
                    }

                    if (token.Length > _header.Count)
                    {
                        continue;
                    }

                    for (var i = 0; i < token.Length; i++)
                    {
                        if (!_header.ContainsKey(i))
                        {
                            continue;
                        }

                        _data[_header[i]].Add(token[i]);
                    }
                    _rows.Add(line);
                }
            }
        }
Example #12
0
        private bool ReadAnnoFile()
        {
            _offsetList   = new List <long>();
            _nameToLength = new Dictionary <string, int>();
            _names        = new Dictionary <long, string>();
            _descriptions = new Dictionary <long, string>();
            _nameToOffset = new Dictionary <string, long>();

            _duplicateNameCounts = new Dictionary <string, int>();

            using (var reader = new StreamReader(_annoFilePath))
            {
                string s;
                while ((s = reader.ReadLine()) != null)
                {
                    var token = s.Split(FastaDatabaseConstants.AnnotationDelimiter);
                    if (token.Length < 4)
                    {
                        break;
                    }
                    var offset = long.Parse(token[0]);
                    _offsetList.Add(offset);
                    var length = int.Parse(token[1]);
                    var name   = token[2];

                    if (_nameToLength.TryGetValue(name, out _))
                    {
                        ConsoleMsgUtils.ShowWarning(string.Format(
                                                        "Duplicate protein name, renaming {0} at offset {1} in {2} to avoid collisions",
                                                        name, offset, Path.GetFileName(_annoFilePath)));

                        if (_duplicateNameCounts.TryGetValue(name, out var duplicateSuffix))
                        {
                            duplicateSuffix++;
                            _duplicateNameCounts[name] = duplicateSuffix;
                        }
                        else
                        {
                            duplicateSuffix = 1;
                            _duplicateNameCounts.Add(name, duplicateSuffix);
                        }
                        name += "_Duplicate" + duplicateSuffix.ToString("00");
                    }

                    _nameToLength.Add(name, length);
                    _names.Add(offset, name);
                    _nameToOffset.Add(name, offset);
                    _descriptions.Add(offset, token[3]);
                }
            }

            return(true);
        }
Example #13
0
        /// <summary>
        /// Log a message to the local, generic log file
        /// </summary>
        /// <param name="logMessage"></param>
        /// <param name="localLogFilePath"></param>
        /// <remarks>Used to log errors and warnings when the standard log file (or database) cannot be written to</remarks>
        protected static void LogLocalMessage(LogMessage logMessage, string localLogFilePath = "FileLoggerErrors.txt")
        {
            switch (logMessage.LogLevel)
            {
            case LogLevels.DEBUG:
                ConsoleMsgUtils.ShowDebug(logMessage.Message);
                break;

            case LogLevels.WARN:
                ConsoleMsgUtils.ShowWarning(logMessage.Message);
                break;

            case LogLevels.ERROR:
            case LogLevels.FATAL:
                ConsoleMsgUtils.ShowError(logMessage.Message);
                break;

            default:
                Console.WriteLine(logMessage.Message);
                break;
            }

            if (string.IsNullOrWhiteSpace(localLogFilePath))
            {
                localLogFilePath = "FileLoggerErrors.txt";
            }

            try
            {
                var localLogFile = new FileInfo(localLogFilePath);
                localLogFilePath = localLogFile.FullName;

                using (var localLogWriter = new StreamWriter(new FileStream(localLogFile.FullName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)))
                {
                    localLogWriter.WriteLine(logMessage.GetFormattedMessage(TimestampFormat));
                }
            }
            catch (Exception ex)
            {
                if (!mLocalLogFileAccessError)
                {
                    mLocalLogFileAccessError = true;
                    ConsoleMsgUtils.ShowError("Error writing to the local log file: " + localLogFilePath);
                }

                ConsoleMsgUtils.ShowErrorCustom(
                    string.Format("Error writing '{0}' to the local log file: {1}", logMessage.GetFormattedMessage(TimestampFormat), ex),
                    false,
                    false);
            }
        }
Example #14
0
        /// <summary>
        /// Look for the mzML CacheInfo file
        /// If it exists, determine the path of the .mzML.gz file that it points to and verify that the file exists
        /// </summary>
        /// <param name="baseOutputFilePath"></param>
        /// <param name="cachedMzMLFile"></param>
        /// <param name="cacheInfoFileName"></param>
        /// <returns>True if the CacheInfo file was found and the .mzML.gz file was successfully retrieved; otherwise false</returns>
        private bool ResolveCachedMzMLFile(string baseOutputFilePath, out FileInfo cachedMzMLFile, out string cacheInfoFileName)
        {
            cacheInfoFileName = baseOutputFilePath + ".mzML.gz_CacheInfo.txt";

            try
            {
                var cacheInfoFile = new FileInfo(cacheInfoFileName);
                if (!cacheInfoFile.Exists)
                {
                    cachedMzMLFile = null;
                    return(false);
                }

                string cachedMzMLFilePath;

                using (var reader = new StreamReader(new FileStream(cacheInfoFile.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
                {
                    if (reader.EndOfStream)
                    {
                        cachedMzMLFilePath = string.Empty;
                    }
                    else
                    {
                        cachedMzMLFilePath = reader.ReadLine();
                    }
                }

                if (string.IsNullOrWhiteSpace(cachedMzMLFilePath))
                {
                    cachedMzMLFile = null;
                    return(false);
                }

                cachedMzMLFile = new FileInfo(cachedMzMLFilePath);
                if (cachedMzMLFile.Exists)
                {
                    return(true);
                }

                ConsoleMsgUtils.ShowWarning("Cached .mzML.gz file specified by {0} not found;\n" +
                                            "Cannot use: {1}", cacheInfoFile.Name, cachedMzMLFilePath);
                cachedMzMLFile = null;
                return(false);
            }
            catch (Exception ex)
            {
                ConsoleMsgUtils.ShowError("Error looking for the fixed mzML file using the CacheInfo file", ex);
                cachedMzMLFile = null;
                return(false);
            }
        }
Example #15
0
        /// <summary>
        /// Display a warning message at the console and write to the log file
        /// </summary>
        /// <param name="warningMessage">Warning message</param>
        /// <param name="logToDatabase">When true, log to the database (and to the file)</param>
        public static void LogWarning(string warningMessage, bool logToDatabase = false)
        {
            ConsoleMsgUtils.ShowWarning(warningMessage);

            try
            {
                var logType = logToDatabase ? LoggerTypes.LogDb : LoggerTypes.LogFile;
                WriteLog(logType, BaseLogger.LogLevels.WARN, warningMessage);
            }
            catch (Exception ex)
            {
                ErrorWritingToLog(warningMessage, ex);
            }
        }
Example #16
0
        public void TestGetParentScan(string mzXmlFileName, int startScan, int endScan, params int[] expectedParents)
        {
            var dataFile = FindInputFile(mzXmlFileName);

            var reader = new MzXMLFileAccessor();

            reader.OpenFile(dataFile.FullName);

            var i = 0;
            var validScanCount = 0;

            for (var scanNumber = startScan; scanNumber <= endScan; scanNumber++)
            {
                var validScan = reader.GetSpectrumByScanNumber(scanNumber, out var spectrumInfo);

                if (!validScan)
                {
                    ConsoleMsgUtils.ShowWarning("Invalid scan number: {0}", scanNumber);
                    i++;
                    continue;
                }

                validScanCount++;

                if (spectrumInfo is not SpectrumInfoMzXML mzXmlSpectrum)
                {
                    Assert.Fail("Input file is not a .mzXML file; cannot validate precursor scan numbers");
                    return;
                }

                Console.WriteLine("MS{0} scan {1,-4} has parent {2,-4}", spectrumInfo.MSLevel, scanNumber, mzXmlSpectrum.PrecursorScanNum);

                if (i < expectedParents.Length && expectedParents[i] != 0)
                {
                    Assert.AreEqual(
                        expectedParents[i], mzXmlSpectrum.PrecursorScanNum,
                        "Parent scan does not match expected value: {0}",
                        expectedParents[i]);
                }

                i++;
            }

            var percentValid = validScanCount / (double)(endScan - startScan + 1) * 100;

            Assert.Greater(percentValid, 90, "Over 10% of the spectra had invalid scan numbers");
        }
Example #17
0
        private static bool InvalidParameterFile(string parameterFilePath)
        {
            if (string.IsNullOrWhiteSpace(parameterFilePath))
            {
                return(false);
            }

            // Assure that the user did not provide an old-style XML-based parameter file
            var paramFile = new FileInfo(parameterFilePath);

            if (!paramFile.Extension.Equals(".xml", StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }

            using var paramFileReader = new StreamReader(new FileStream(paramFile.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));

            var linesRead = 0;

            while (!paramFileReader.EndOfStream && linesRead < 5)
            {
                var dataLine = paramFileReader.ReadLine();
                if (string.IsNullOrWhiteSpace(dataLine))
                {
                    continue;
                }

                linesRead++;

                var trimmedLine = dataLine.Trim();
                if (trimmedLine.StartsWith("<?xml", StringComparison.OrdinalIgnoreCase) ||
                    trimmedLine.StartsWith("<sections", StringComparison.OrdinalIgnoreCase))
                {
                    ConsoleMsgUtils.ShowWarning(
                        "PeptideHitResultsProcRunner v3.1 uses Key=Value parameter files\n" +
                        "{0} is an XML file\n" +
                        "For an example parameter file, see file PHRP_Options.conf at {1}",
                        paramFile.Name, "https://github.com/PNNL-Comp-Mass-Spec/PHRP/tree/master/Data");
                    ConsoleMsgUtils.ShowWarning("Aborting");
                    return(true);
                }
            }

            return(false);
        }
Example #18
0
        public bool Validate()
        {
            if (string.IsNullOrWhiteSpace(InputDataFilePath))
            {
                ConsoleMsgUtils.ShowError($"ERROR: Input path must be provided and non-empty; \"{InputDataFilePath}\" was provided.");
                return(false);
            }

            if (!string.IsNullOrWhiteSpace(MS2MzMinString))
            {
                if (MS2MzMinString.StartsWith("itraq", StringComparison.OrdinalIgnoreCase))
                {
                    MS2MzMin = clsMSFileInfoScanner.MINIMUM_MZ_THRESHOLD_ITRAQ;
                }
                else if (MS2MzMinString.StartsWith("tmt", StringComparison.OrdinalIgnoreCase))
                {
                    MS2MzMin = clsMSFileInfoScanner.MINIMUM_MZ_THRESHOLD_TMT;
                }
                else
                {
                    if (float.TryParse(MS2MzMinString, out var mzMin))
                    {
                        MS2MzMin = mzMin;
                    }
                    else
                    {
                        ConsoleMsgUtils.ShowWarning("Ignoring invalid m/z value for /MS2MzMin: " + MS2MzMinString);
                    }
                }
            }

            if (CheckFileIntegrity)
            {
                UseCacheFiles = true;
            }

            if (ScanStart > ScanEnd && ScanEnd != 0)
            {
                ConsoleMsgUtils.ShowError($"ERROR: When ScanStart and ScanEnd are both >0, ScanStart ({ScanStart}) cannot be greater than ScanEnd ({ScanEnd})!");
                return(false);
            }

            return(true);
        }
Example #19
0
        /// <summary>
        /// Process each file in the target folder
        /// </summary>
        /// <param name="targetDirectory"></param>
        /// <returns>0 if success, number of errors if a problem</returns>
        private int ProcessDirectory(string targetDirectory)
        {
            var fileEntries = Directory.GetFiles(targetDirectory);
            var errorCount  = 0;

            foreach (var fileName in fileEntries)
            {
                if ((MsRawFile(fileName) && !HasExistingPbfFile(fileName)) || MsPbfFile(fileName))
                {
                    var returnCode = ProcessFile(fileName);
                    if (returnCode != 0)
                    {
                        ConsoleMsgUtils.ShowWarning(string.Format("  error code {0} for {1}", returnCode, Path.GetFileName(fileName)));
                        errorCount++;
                    }
                }
            }

            return(errorCount);
        }
Example #20
0
        public IEnumerable <Spectrum> ReadAllSpectra()
        {
            for (var scanNum = _minLcScan; scanNum <= _maxLcScan; scanNum++)
            {
                Spectrum spec = null;
                try
                {
                    spec = ReadMassSpectrum(scanNum);
                }
                catch (System.Runtime.InteropServices.COMException /* ex*/)
                {
                    ConsoleMsgUtils.ShowWarning(string.Format("[Warning] Ignore corrupted spectrum Scan={0}", scanNum));
                }

                if (spec != null)
                {
                    yield return(spec);
                }
            }
        }
Example #21
0
        public override double GetMS2IsolationWidth(int scanNum)
        {
            try
            {
                if (!TryGetScanInfo(scanNum, out var scanInfo))
                {
                    return(0);
                }

                if (scanInfo.TryGetScanEvent("MS2 Isolation Width:", out var value, true))
                {
                    return(Convert.ToDouble(value));
                }

                return(0);
            }
            catch (Exception ex)
            {
                ConsoleMsgUtils.ShowWarning("Warning: Exception looking up the value for \"MS2 Isolation Width\" for scan " + scanNum + ": " + ex.Message);
                return(0);
            }
        }
Example #22
0
        /// <summary>
        /// Gets the appropriate IMassSpecDataReader for the supplied path.
        /// It is recommended that "NormalizeDatasetPath" be called prior to calling this function, and that the returned string be used instead of the original path
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        /// <remarks>It is recommended that "NormalizeDatasetPath" be called prior to calling this function, and that the returned string be used instead of the original path</remarks>
        public static IMassSpecDataReader GetMassSpecDataReader(string filePath)
        {
            filePath = NormalizeDatasetPath(filePath);
            var type = GetMassSpecDataType(filePath);
            IMassSpecDataReader reader = null;

            switch (type)
            {
            case MassSpecDataType.XCaliburRun:
                reader = new XCaliburReader(filePath);
                break;

            case MassSpecDataType.MzMLFile:
                reader = new MzMLReader(filePath);
                break;

            case MassSpecDataType.PbfFile:
                reader = new PbfLcMsRun(filePath);
                break;

            case MassSpecDataType.DeconvolutedPbfFile:
                reader = new DPbfLcMsRun(filePath);
                break;

            case MassSpecDataType.Unknown:
                if (_pwizAvailable)
                {
                    reader = new ProteoWizardReader(filePath);
                }
                else
                {
                    ConsoleMsgUtils.ShowWarning(string.Format("WARNING: Could not find a reader for file \"{0}\"." +
                                                              " Is MSFileReader and/or ProteoWizard installed?", filePath));
                }
                break;
            }

            return(reader);
        }
 private static void MASICResultsMerger_WarningEvent(string message)
 {
     ConsoleMsgUtils.ShowWarning(message);
 }
        private static void ProcessPackageConfigFile(FileSystemInfo packageConfigFile, string baseDirectoryPath, PackageUpdateOptions updateOptions)
        {
            try
            {
                // Open the packages.config file and look for XML like this:
                //
                //  <package id="PRISM-Library" version="2.5.10" targetFramework="net451" />

                var saveRequired = false;

                var doc = XDocument.Load(packageConfigFile.FullName);

                foreach (var packageRef in doc.Descendants().Where(p => p.Name.LocalName == "package"))
                {
                    if (!packageRef.HasAttributes)
                    {
                        continue;
                    }

                    var refName = (string)packageRef.Attribute("id");
                    if (refName == null)
                    {
                        // The package element does not have attribute id
                        continue;
                    }

                    if (!string.Equals(refName, updateOptions.NuGetPackageName, StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    if (!mVerboseLogging)
                    {
                        ShowProcessingFileMessage(packageConfigFile, baseDirectoryPath);
                    }

                    // Examine the version
                    var versionAttribute = packageRef.Attribute("version");
                    if (versionAttribute == null)
                    {
                        // The package element does not have attribute version
                        ConsoleMsgUtils.ShowWarning("package element has id=\"{0}\" but does not have version=\"x.y.z\": {1}",
                                                    updateOptions.NuGetPackageName, packageConfigFile.FullName);
                        continue;
                    }

                    // Found XML like this:
                    // <package id="PRISM-Library" version="2.5.10" targetFramework="net451" />

                    saveRequired = UpdateVersionAttributeIfRequired(versionAttribute, updateOptions);
                }

                if (updateOptions.Preview)
                {
                    return;
                }

                if (!saveRequired)
                {
                    return;
                }

                WriteXmlFile(packageConfigFile, doc);
            }
            catch (Exception ex)
            {
                ShowErrorMessage("Error processing file " + packageConfigFile.FullName + ": " + ex.Message);
            }
        }
Example #25
0
        // Ignore Spelling: Bryson, Conf

        private static int Main(string[] args)
        {
            var asmName        = typeof(Program).GetTypeInfo().Assembly.GetName();
            var exeName        = Path.GetFileName(Assembly.GetExecutingAssembly().Location); // Alternatively: System.AppDomain.CurrentDomain.FriendlyName
            var programVersion = typeof(Program).GetTypeInfo().Assembly.GetName().Version;
            var version        = $"version {programVersion.Major}.{programVersion.Minor}.{programVersion.Build}";

            var parser = new CommandLineParser <ConverterOptions>(asmName.Name, version)
            {
                ProgramInfo = "This program converts a .mzid file created by MS-GF+ into a tab-delimited text file.",

                ContactInfo = "Program written by Bryson Gibbons for the Department of Energy " + Environment.NewLine +
                              "(PNNL, Richland, WA)" + Environment.NewLine + Environment.NewLine +
                              string.Format(
                    "Version: {0}.{1}.{2} ({3})",
                    programVersion.Major, programVersion.Minor, programVersion.Build, ConverterOptions.PROGRAM_DATE) +
                              Environment.NewLine + Environment.NewLine +
                              "E-mail: [email protected] or [email protected]" + Environment.NewLine +
                              "Website: https://github.com/PNNL-Comp-Mass-Spec/ or https://panomics.pnnl.gov/ or https://www.pnnl.gov/integrative-omics",

                UsageExamples =
                {
                    exeName + " Results.mzid",
                    exeName + " Results.mzid -unroll",
                    exeName + " Results.mzid -unroll -showDecoy",
                }
            };

            parser.AddParamFileKey("Conf");

            var parseResults = parser.ParseArgs(args);
            var options      = parseResults.ParsedResults;

            if (!parseResults.Success)
            {
                Thread.Sleep(1500);
                return(-1);
            }

            if (!options.ValidateArgs(out var errorMessage))
            {
                parser.PrintHelp();

                Console.WriteLine();
                ConsoleMsgUtils.ShowWarning("Validation error:");
                ConsoleMsgUtils.ShowWarning(errorMessage);

                Thread.Sleep(1500);
                return(-1);
            }

            options.OutputSetOptions();

            try
            {
                var converter = new MzidToTsvConverter();
                converter.ConvertToTsv(options);

                Console.WriteLine();
                Console.WriteLine("Conversion finished!");
                Thread.Sleep(700);

                return(0);
            }
            catch (Exception ex)
            {
                ConsoleMsgUtils.ShowError("Conversion failed", ex);

                Thread.Sleep(1500);
                var errorCode = ex.Message.GetHashCode();
                if (errorCode == 0)
                {
                    return(-1);
                }
                return(errorCode);
            }
        }
        /// <summary>
        /// The main function to run the program
        /// </summary>
        /// <param name="args">Passed in arguments to the program</param>
        public static int Main(string[] args)
        {
            var asmName = typeof(Program).GetTypeInfo().Assembly.GetName();
            var exeName = Path.GetFileName(Assembly.GetExecutingAssembly().Location);       // Alternatively: System.AppDomain.CurrentDomain.FriendlyName
            var version = MetaboliteValidatorOptions.GetAppVersion();

            var parser = new CommandLineParser <MetaboliteValidatorOptions>(asmName.Name, version)
            {
                ProgramInfo = "This program reads metabolites in a .tsv file and pushes new information " + Environment.NewLine +
                              "to the git repository at https://github.com/PNNL-Comp-Mass-Spec/MetabolomicsCCS",

                ContactInfo = "Program written by Ryan Wilson and Matthew Monroe for the Department of Energy (PNNL, Richland, WA) in 2017" +
                              Environment.NewLine + Environment.NewLine +
                              "E-mail: [email protected] or [email protected]" + Environment.NewLine +
                              "Website: https://github.com/PNNL-Comp-Mass-Spec/ or https://panomics.pnnl.gov/ or https://www.pnnl.gov/integrative-omics",

                UsageExamples =
                {
                    exeName + " NewMetabolites.tsv",
                    exeName + " NewMetabolites.tsv -i",
                    exeName + " NewMetabolites.tsv -preview",
                    exeName + " NewMetabolites.tsv -user MyUsername -password *Dfw3gf"
                }
            };

            var result  = parser.ParseArgs(args);
            var options = result.ParsedResults;

            try
            {
                if (!result.Success)
                {
                    if (parser.CreateParamFileProvided)
                    {
                        return(0);
                    }

                    // Delay for 1500 msec in case the user double clicked this file from within Windows Explorer (or started the program via a shortcut)
                    Thread.Sleep(1500);
                    return(-1);
                }

                if (!options.ValidateArgs(out var errorMessage))
                {
                    parser.PrintHelp();

                    Console.WriteLine();
                    ConsoleMsgUtils.ShowWarning("Validation error:");
                    ConsoleMsgUtils.ShowWarning(errorMessage);

                    Thread.Sleep(1500);
                    return(-1);
                }

                options.OutputSetOptions();
            }
            catch (Exception e)
            {
                Console.WriteLine();
                Console.Write($"Error running {exeName}");
                Console.WriteLine(e.Message);
                Console.WriteLine($"See help with {exeName} --help");
                return(-1);
            }

            var program = new Program();

            var success = program.ProcessMetabolites(options);

            Console.WriteLine();

            if (success)
            {
                Console.WriteLine("Processing complete");
            }
            else
            {
                Console.WriteLine("Processing failed");
            }


            System.Threading.Thread.Sleep(1500);

            return(0);
        }
Example #27
0
 public void AddApplicationLogWarning(string message)
 {
     AddApplicationLog(message, false);
     ConsoleMsgUtils.ShowWarning(message);
 }
Example #28
0
        public static int Main(string[] args)
        {
            var exeName       = System.Reflection.Assembly.GetEntryAssembly()?.GetName().Name;
            var exePath       = PRISM.FileProcessor.ProcessFilesOrDirectoriesBase.GetAppPath();
            var cmdLineParser = new CommandLineParser <CommandLineOptions>(exeName, GetAppVersion());

            var scannerInfo = new clsMSFileInfoScanner();

            cmdLineParser.ProgramInfo = "This program will scan a series of MS data files (or data directories) and " +
                                        "extract the acquisition start and end times, number of spectra, and the " +
                                        "total size of the data, saving the values in the file " +
                                        clsMSFileInfoScanner.DefaultAcquisitionTimeFilename + ". " +
                                        "Supported file types are Thermo .RAW files, Agilent Ion Trap (.D directories), " +
                                        "Agilent or QStar/QTrap .WIFF files, MassLynx .Raw directories, Bruker 1 directories, " +
                                        "Bruker XMass analysis.baf files, .UIMF files (IMS), " +
                                        "zipped Bruker imaging datasets (with 0_R*.zip files), and " +
                                        "DeconTools _isos.csv files" + Environment.NewLine + Environment.NewLine +
                                        "Known file extensions: " + CollapseList(scannerInfo.GetKnownFileExtensionsList()) + Environment.NewLine +
                                        "Known directory extensions: " + CollapseList(scannerInfo.GetKnownDirectoryExtensionsList());
            cmdLineParser.ContactInfo = "Program written by Matthew Monroe for PNNL (Richland, WA) in 2005" + Environment.NewLine +
                                        "E-mail: [email protected] or [email protected]" + Environment.NewLine + "Website: https://omics.pnl.gov/ or https://panomics.pnnl.gov/";

            cmdLineParser.UsageExamples.Add("Program syntax:" + Environment.NewLine + Path.GetFileName(exePath) +
                                            " /I:InputFileNameOrDirectoryPath [/O:OutputDirectoryName]" +
                                            " [/P:ParamFilePath] [/S[:MaxLevel]] [/IE] [/L:LogFilePath]" +
                                            " [/LC[:MaxPointsToPlot]] [/NoTIC] [/LCGrad]" +
                                            " [/DI] [/SS] [/QS] [/CC]" +
                                            " [/MS2MzMin:MzValue] [/NoHash]" +
                                            " [/DST:DatasetStatsFileName]" +
                                            " [/ScanStart:0] [/ScanEnd:0] [/Debug]" +
                                            " [/C] [/M:nnn] [/H] [/QZ]" +
                                            " [/CF] [/R] [/Z]" +
                                            " [/PostToDMS] [/PythonPlot]");

            var result  = cmdLineParser.ParseArgs(args);
            var options = result.ParsedResults;

            if (!result.Success || !options.Validate())
            {
                // Delay for 750 msec in case the user double clicked this file from within Windows Explorer (or started the program via a shortcut)
                System.Threading.Thread.Sleep(750);
                return(-1);
            }

            mLastProgressTime = DateTime.UtcNow;

            try
            {
                var scanner = new clsMSFileInfoScanner();

                scanner.DebugEvent     += MSFileScanner_DebugEvent;
                scanner.ErrorEvent     += MSFileScanner_ErrorEvent;
                scanner.WarningEvent   += MSFileScanner_WarningEvent;
                scanner.StatusEvent    += MSFileScanner_MessageEvent;
                scanner.ProgressUpdate += MSFileScanner_ProgressUpdate;

                options.CopyToScanner(scanner);
                scanner.ShowCurrentProcessingOptions();

                bool processingError;

                int returnCode;
                if (options.RecurseDirectories)
                {
                    if (scanner.ProcessMSFilesAndRecurseDirectories(options.InputDataFilePath, options.OutputDirectoryName, options.MaxLevelsToRecurse))
                    {
                        returnCode      = 0;
                        processingError = false;
                    }
                    else
                    {
                        returnCode      = (int)scanner.ErrorCode;
                        processingError = true;
                    }
                }
                else
                {
                    if (scanner.ProcessMSFileOrDirectoryWildcard(options.InputDataFilePath, options.OutputDirectoryName, true))
                    {
                        returnCode      = 0;
                        processingError = false;
                    }
                    else
                    {
                        returnCode      = (int)scanner.ErrorCode;
                        processingError = true;
                    }
                }

                if (processingError)
                {
                    if (returnCode != 0)
                    {
                        ShowErrorMessage("Error while processing: " + scanner.GetErrorMessage());
                    }
                    else
                    {
                        ShowErrorMessage("Unknown error while processing (ProcessMSFileOrDirectoryWildcard returned false but the ErrorCode is 0)");
                    }

                    System.Threading.Thread.Sleep(1500);
                }
                else if (scanner.ErrorCode == iMSFileInfoScanner.eMSFileScannerErrorCodes.MS2MzMinValidationWarning)
                {
                    ConsoleMsgUtils.ShowWarning("MS2MzMin validation warning: " + scanner.MS2MzMinValidationMessage);
                }

                scanner.SaveCachedResults();

                return(returnCode);
            }
            catch (Exception ex)
            {
                ShowErrorMessage("Error occurred in modMain->Main", ex);
                return(-1);
            }
        }
Example #29
0
        /// <summary>
        /// Look for the file in a directory named Data, in a parent directory to the work directory
        /// If not found, look in remotePathToSearch
        /// </summary>
        /// <param name="fileOrDirectoryToFind"></param>
        /// <param name="isDirectory">True if looking for a directory, false if a file</param>
        /// <param name="remotePathToSearch">Remote directory to check if fileOrDirectoryToFind is not found locally</param>
        /// <param name="instrumentDataFileOrDirectory">Output: matching instrument data file, or null if not found</param>
        /// <returns></returns>
        public static bool FindInstrumentData(
            string fileOrDirectoryToFind,
            bool isDirectory,
            string remotePathToSearch,
            out FileSystemInfo instrumentDataFileOrDirectory)
        {
            string datasetType;

            if (isDirectory)
            {
                datasetType = "directory";
            }
            else
            {
                datasetType = "file";
            }

            try
            {
                var startingDirectory = new DirectoryInfo(".");
                var directoryToCheck  = new DirectoryInfo(".");

                while (true)
                {
                    var matchingDirectories = directoryToCheck.GetDirectories("Data");
                    if (matchingDirectories.Length > 0)
                    {
                        if (FindInstrumentData(fileOrDirectoryToFind, isDirectory, matchingDirectories[0], out instrumentDataFileOrDirectory))
                        {
                            return(true);
                        }

                        break;
                    }

                    if (directoryToCheck.Parent == null)
                    {
                        break;
                    }

                    directoryToCheck = directoryToCheck.Parent;
                }

                // Look in the unit test share
                var remoteShare = new DirectoryInfo(remotePathToSearch);
                if (remoteShare.Exists)
                {
                    if (FindInstrumentData(fileOrDirectoryToFind, isDirectory, remoteShare, out instrumentDataFileOrDirectory))
                    {
                        return(true);
                    }
                }

                ConsoleMsgUtils.ShowWarning("Could not find {0} {1} in a Data directory above {2}", datasetType, fileOrDirectoryToFind, startingDirectory.FullName);

                instrumentDataFileOrDirectory = null;
                return(false);
            }
            catch (Exception ex)
            {
                ConsoleMsgUtils.ShowError(ex, "Error looking for {0} {1}", datasetType, fileOrDirectoryToFind);

                instrumentDataFileOrDirectory = null;
                return(false);
            }
        }
Example #30
0
 private void ParentClass_WarningEvent(string message)
 {
     ConsoleMsgUtils.ShowWarning(message);
 }