コード例 #1
0
            public void Run(ProcessStartInfo psi, string stdin, IProgressMonitor progress, ref ProgressStatus status, TextWriter writer)
            {
                if (shouldCancel)
                {
                    status.Cancel();
                    progress.UpdateProgress(status = status.Cancel());
                    return;
                }

                if (!string.IsNullOrEmpty(stringToWriteToWriter))
                {
                    writer.WriteLine(stringToWriteToWriter);
                }
                status.ChangePercentComplete(100);
                progress.UpdateProgress(status);
            }
コード例 #2
0
        // ReSharper restore NonLocalizedString
        public static List<string> ConvertPilotFiles(IList<string> inputFiles, IProgressMonitor progress, ProgressStatus status)
        {
            string groupConverterExePath = null;
            var inputFilesPilotConverted = new List<string>();

            for (int index = 0; index < inputFiles.Count; index++)
            {
                string inputFile = inputFiles[index];
                if (!inputFile.EndsWith(BiblioSpecLiteBuilder.EXT_PILOT))
                {
                    inputFilesPilotConverted.Add(inputFile);
                    continue;
                }
                string outputFile = Path.ChangeExtension(inputFile, BiblioSpecLiteBuilder.EXT_PILOT_XML);
                // Avoid re-converting files that have already been converted
                if (File.Exists(outputFile))
                {
                    // Avoid duplication, in case the user accidentally adds both .group and .group.xml files
                    // for the same results
                    if (!inputFiles.Contains(outputFile))
                        inputFilesPilotConverted.Add(outputFile);
                    continue;
                }

                string message = string.Format(Resources.VendorIssueHelper_ConvertPilotFiles_Converting__0__to_xml, Path.GetFileName(inputFile));
                int percent = index * 100 / inputFiles.Count;
                progress.UpdateProgress(status = status.ChangeMessage(message).ChangePercentComplete(percent));

                if (groupConverterExePath == null)
                {
                    var key = Registry.LocalMachine.OpenSubKey(KEY_PROTEIN_PILOT, false);
                    if (key != null)
                    {
                        string proteinPilotCommandWithArgs = (string)key.GetValue(string.Empty);

                        var proteinPilotCommandWithArgsSplit =
                            proteinPilotCommandWithArgs.Split(new[] { "\" \"" }, StringSplitOptions.RemoveEmptyEntries);     // Remove " "%1" // Not L10N
                        string path = Path.GetDirectoryName(proteinPilotCommandWithArgsSplit[0].Trim(new[] { '\\', '\"' })); // Remove preceding "
                        if (path != null)
                        {
                            var groupFileExtractorPath = Path.Combine(path, EXE_GROUP_FILE_EXTRACTOR);
                            if (File.Exists(groupFileExtractorPath))
                            {
                                groupConverterExePath = groupFileExtractorPath;
                            }
                            else
                            {
                                var group2XmlPath = Path.Combine(path, EXE_GROUP2_XML);
                                if (File.Exists(group2XmlPath))
                                {
                                    groupConverterExePath = group2XmlPath;
                                }
                                else
                                {
                                    string errorMessage = string.Format(Resources.VendorIssueHelper_ConvertPilotFiles_Unable_to_find__0__or__1__in_directory__2____Please_reinstall_ProteinPilot_software_to_be_able_to_handle__group_files_,
                                        EXE_GROUP_FILE_EXTRACTOR, EXE_GROUP2_XML, path);
                                    throw new IOException(errorMessage);
                                }
                            }
                        }
                    }

                    if (groupConverterExePath == null)
                    {
                        throw new IOException(Resources.VendorIssueHelper_ConvertPilotFiles_ProteinPilot_software__trial_or_full_version__must_be_installed_to_convert___group__files_to_compatible___group_xml__files_);
                    }
                }

                // run group2xml
                // ReSharper disable NonLocalizedString
                var argv = new[]
                               {
                                   "XML",
                                   "\"" + inputFile + "\"",
                                   "\"" + outputFile + "\""
                               };
                // ReSharper restore NonLocalizedString

                var psi = new ProcessStartInfo(groupConverterExePath)
                              {
                                  CreateNoWindow = true,
                                  UseShellExecute = false,
                                  // Common directory includes the directory separator
                                  WorkingDirectory = Path.GetDirectoryName(groupConverterExePath) ?? string.Empty,
                                  Arguments = string.Join(" ", argv.ToArray()), // Not L10N
                                  RedirectStandardError = true,
                                  RedirectStandardOutput = true,
                              };

                var sbOut = new StringBuilder();
                var proc = new Process {StartInfo = psi};
                proc.Start();

                var reader = new ProcessStreamReader(proc);
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    if (progress.IsCanceled)
                    {
                        proc.Kill();
                        throw new LoadCanceledException(status.Cancel());
                    }

                    sbOut.AppendLine(line);
                }

                while (!proc.WaitForExit(200))
                {
                    if (progress.IsCanceled)
                    {
                        proc.Kill();
                        return inputFilesPilotConverted;
                    }
                }

                if (proc.ExitCode != 0)
                {
                    throw new IOException(TextUtil.LineSeparate(string.Format(Resources.VendorIssueHelper_ConvertPilotFiles_Failure_attempting_to_convert_file__0__to__group_xml_,
                                                        inputFile), string.Empty, sbOut.ToString()));
                }

                inputFilesPilotConverted.Add(outputFile);
            }
            progress.UpdateProgress(status.ChangePercentComplete(100));
            return inputFilesPilotConverted;
        }
コード例 #3
0
        private static void ConvertBrukerToMzml(string filePathBruker,
            string outputPath, IProgressMonitor monitor, ProgressStatus status)
        {
            // We use CompassXport, if it is installed, to convert a Bruker raw file to mzML.  This solves two
            // issues: the Bruker reader can't be called on any thread other than the main thread, and there
            // is no 64-bit version of the reader.  So we start CompassXport in its own 32-bit process,
            // and use it to convert the raw data to mzML in a temporary file, which we read back afterwards.
            var key = Registry.LocalMachine.OpenSubKey(KEY_COMPASSXPORT, false);
            string compassXportExe = (key != null) ? (string)key.GetValue(string.Empty) : null;
            if (compassXportExe == null)
                throw new IOException(Resources.VendorIssueHelper_ConvertBrukerToMzml_CompassXport_software_must_be_installed_to_import_Bruker_raw_data_files_);

            // CompassXport arguments
            // ReSharper disable NonLocalizedString
            var argv = new[]
                           {
                               "-a \"" + filePathBruker + "\"",     // input file (directory)
                               "-o \"" + outputPath + "\"",         // output file (directory)
                               "-mode 2",                           // mode 2 (mzML)
                               "-raw 0"                             // export line spectra (profile data is HUGE and SLOW!)
                           };
            // ReSharper restore NonLocalizedString

            // Start CompassXport in its own process.
            var psi = new ProcessStartInfo(compassXportExe)
            {
                CreateNoWindow = true,
                UseShellExecute = false,
                // Common directory includes the directory separator
                WorkingDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? string.Empty,
                Arguments = string.Join(" ", argv), // Not L10N
                RedirectStandardError = true,
                RedirectStandardOutput = true,
            };
            var proc = new Process { StartInfo = psi };
            proc.Start();

            // CompassXport starts by calculating a hash of the input file.  This takes a long time, and there is
            // no intermediate output during this time.  So we set the progress bar some fraction of the way and
            // let it sit there and animate while we wait for the start of spectra processing.
            const int hashPercent = 25; // percentage of import time allocated to calculating the input file hash

            int spectrumCount = 0;

            var sbOut = new StringBuilder();
            var reader = new ProcessStreamReader(proc);
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                if (monitor.IsCanceled)
                {
                    proc.Kill();
                    throw new LoadCanceledException(status.Cancel());
                }

                sbOut.AppendLine(line);
                line = line.Trim();

                // The main part of conversion starts with the hash calculation.
                if (line.StartsWith("Calculating hash")) // Not L10N
                {
                    status = status.ChangeMessage(Resources.VendorIssueHelper_ConvertBrukerToMzml_Calculating_hash_of_input_file)
                        .ChangePercentComplete(hashPercent);
                    monitor.UpdateProgress(status);
                    continue;
                }

                // Determine how many spectra will be converted so we can track progress.
                var match = Regex.Match(line, @"Converting (\d+) spectra"); // Not L10N
                if (match.Success)
                {
                    spectrumCount = int.Parse(match.Groups[1].Value);
                    continue;
                }

                // Update progress as each spectra batch is converted.
                match = Regex.Match(line, @"Spectrum \d+ - (\d+)"); // Not L10N
                if (match.Success)
                {
                    var spectrumEnd = int.Parse(match.Groups[1].Value);
                    var percentComplete = hashPercent + (100-hashPercent)*spectrumEnd/spectrumCount;
                    status = status.ChangeMessage(line).ChangePercentComplete(percentComplete);
                    monitor.UpdateProgress(status);
                }
            }

            while (!proc.WaitForExit(200))
            {
                if (monitor.IsCanceled)
                {
                    proc.Kill();
                    throw new LoadCanceledException(status.Cancel());
                }
            }

            if (proc.ExitCode != 0)
            {
                throw new IOException(TextUtil.LineSeparate(string.Format(Resources.VendorIssueHelper_ConvertBrukerToMzml_Failure_attempting_to_convert__0__to_mzML_using_CompassXport_,
                    filePathBruker), string.Empty, sbOut.ToString()));
            }
        }
コード例 #4
0
        public void Run(ProcessStartInfo psi, string stdin, IProgressMonitor progress, ref ProgressStatus status, TextWriter writer)
        {
            // Make sure required streams are redirected.
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardError = true;

            var proc = Process.Start(psi);
            if (proc == null)
                throw new IOException(string.Format("Failure starting {0} command.", psi.FileName)); // Not L10N
            if (stdin != null)
            {
                try
                {
                    proc.StandardInput.Write(stdin);
                }
                finally
                {
                    proc.StandardInput.Close();
                }
            }

            var reader = new ProcessStreamReader(proc);
            StringBuilder sbError = new StringBuilder();
            int percentLast = 0;
            string line;
            while ((line = reader.ReadLine(progress)) != null)
            {
                if (writer != null && !line.StartsWith(HideLinePrefix))
                    writer.WriteLine(line);

                if (progress == null || line.ToLowerInvariant().StartsWith("error")) // Not L10N
                {
                    sbError.AppendLine(line);
                }
                else // if (progress != null)
                {
                    if (progress.IsCanceled)
                    {
                        proc.Kill();
                        progress.UpdateProgress(status = status.Cancel());
                        return;
                    }

                    if (line.EndsWith("%")) // Not L10N
                    {
                        double percent;
                        string[] parts = line.Split(' ');
                        string percentPart = parts[parts.Length - 1];
                        if (double.TryParse(percentPart.Substring(0, percentPart.Length - 1), out percent))
                        {
                            percentLast = (int) percent;
                            status = status.ChangePercentComplete(percentLast);
                            if (percent >= 100 && status.SegmentCount > 0)
                                status = status.NextSegment();
                            progress.UpdateProgress(status);
                        }
                    }
                    else if (MessagePrefix == null || line.StartsWith(MessagePrefix))
                    {
                        // Remove prefix, if there is one.
                        if (MessagePrefix != null)
                            line = line.Substring(MessagePrefix.Length);

                        status = status.ChangeMessage(line);
                        progress.UpdateProgress(status);
                    }
                }
            }
            proc.WaitForExit();
            int exit = proc.ExitCode;
            if (exit != 0)
            {
                line = proc.StandardError.ReadLine();
                if (line != null)
                    sbError.AppendLine(line);
                if (sbError.Length == 0)
                    throw new IOException("Error occurred running process."); // Not L10N
                throw new IOException(sbError.ToString());
            }
            // Make to complete the status, if the process succeeded, but never
            // printed 100% to the console
            if (percentLast < 100)
            {
                status = status.ChangePercentComplete(100);
                if (status.SegmentCount > 0)
                    status = status.NextSegment();
                if (progress != null)
                    progress.UpdateProgress(status);
            }
        }
コード例 #5
0
            public void Run(ProcessStartInfo psi, string stdin, IProgressMonitor progress, ref ProgressStatus status, TextWriter writer)
            {
                if (shouldCancel)
                {
                    status.Cancel();
                    progress.UpdateProgress(status = status.Cancel());
                    return;
                }

                if (!string.IsNullOrEmpty(stringToWriteToWriter))
                    writer.WriteLine(stringToWriteToWriter);
                status.ChangePercentComplete(100);
                progress.UpdateProgress(status);
            }
コード例 #6
0
        protected override bool LoadBackground(IDocumentContainer container, SrmDocument document, SrmDocument docCurrent)
        {
            // Only allow one background proteome to load at a time.  This can
            // get tricky, if the user performs an undo and then a redo across
            // a change in background proteome.
            // Our first priority is doing the digestions, the second is accessing web
            // services to add missing protein metadata.
            lock (_lockLoadBackgroundProteome)
            {
                BackgroundProteome originalBackgroundProteome = GetBackgroundProteome(docCurrent);
                // Check to see whether the Digestion already exists but has not been queried yet.
                BackgroundProteome backgroundProteomeWithDigestions = new BackgroundProteome(originalBackgroundProteome, true);
                if (IsNotLoadedExplained(docCurrent, backgroundProteomeWithDigestions, true) == null)
                {
                    // digest is ready, and protein metdata is resolved
                    CompleteProcessing(container, backgroundProteomeWithDigestions);
                    return true;
                }
                // are we here to do the digest, or to resolve the protein metadata?
                bool getMetadata = (IsNotLoadedExplained(docCurrent, backgroundProteomeWithDigestions, false) == null) &&
                    backgroundProteomeWithDigestions.NeedsProteinMetadataSearch;

                string name = originalBackgroundProteome.Name;
                ProgressStatus progressStatus =
                    new ProgressStatus(string.Format(getMetadata?Resources.BackgroundProteomeManager_LoadBackground_Resolving_protein_details_for__0__proteome:Resources.BackgroundProteomeManager_LoadBackground_Digesting__0__proteome, name));
                try
                {
                    using (FileSaver fs = new FileSaver(originalBackgroundProteome.DatabasePath, StreamManager))
                    {
                        File.Copy(originalBackgroundProteome.DatabasePath, fs.SafeName, true);
                        var digestHelper = new DigestHelper(this, container, docCurrent, name, fs.SafeName, true);
                        bool success;
                        if (getMetadata)
                            success = digestHelper.LookupProteinMetadata(ref progressStatus);
                        else
                            success = (digestHelper.Digest(ref progressStatus) != null);

                        if (!success)
                        {
                            // Processing was canceled
                            EndProcessing(docCurrent);
                            UpdateProgress(progressStatus.Cancel());
                            return false;
                        }
                        using (var proteomeDb = ProteomeDb.OpenProteomeDb(originalBackgroundProteome.DatabasePath))
                        {
                            proteomeDb.DatabaseLock.AcquireWriterLock(int.MaxValue);
                            try
                            {
                                if (!fs.Commit())
                                {
                                    EndProcessing(docCurrent);
                                    throw new IOException(
                                        string.Format(
                                            Resources
                                                .BackgroundProteomeManager_LoadBackground_Unable_to_rename_temporary_file_to__0__,
                                            fs.RealName));
                                }
                            }
                            finally
                            {
                                proteomeDb.DatabaseLock.ReleaseWriterLock();
                            }
                        }

                        CompleteProcessing(container, new BackgroundProteome(originalBackgroundProteome, true));
                        UpdateProgress(progressStatus.Complete());
                        return true;
                    }
                }
                catch (Exception x)
                {
                    var message = new StringBuilder();
                    message.AppendLine(
                        string.Format(Resources.BackgroundProteomeManager_LoadBackground_Failed_updating_background_proteome__0__,
                                      name));
                    message.Append(x.Message);
                    UpdateProgress(progressStatus.ChangeErrorException(new IOException(message.ToString(), x)));
                    return false;
                }
            }
        }
コード例 #7
0
        private SrmDocument LookupProteinMetadata(SrmDocument docOrig, IProgressMonitor progressMonitor)
        {
            lock (_processedNodes)
            {
                // Check to make sure this operation was not canceled while this thread was
                // waiting to acquire the lock.  This also cleans up pending work.
                if (progressMonitor.IsCanceled)
                    return null;

                var progressStatus = new ProgressStatus(Resources.ProteinMetadataManager_LookupProteinMetadata_resolving_protein_details);
                int nResolved = 0;
                int nUnresolved = docOrig.PeptideGroups.Select(pg => pg.ProteinMetadata.NeedsSearch()).Count();

                if ((nUnresolved > 0) && !docOrig.Settings.PeptideSettings.BackgroundProteome.IsNone)
                {
                    // Do a quick check to see if background proteome already has the info
                    if (!docOrig.Settings.PeptideSettings.BackgroundProteome.NeedsProteinMetadataSearch)
                    {
                        try
                        {
                            using (var proteomeDb = docOrig.Settings.PeptideSettings.BackgroundProteome.OpenProteomeDb())
                            {
                                foreach (PeptideGroupDocNode nodePepGroup in docOrig.PeptideGroups)
                                {
                                    if (_processedNodes.ContainsKey(nodePepGroup.Id.GlobalIndex))
                                    {
                                        // We did this before we were interrupted
                                        progressMonitor.UpdateProgress(progressStatus = progressStatus.ChangePercentComplete(100 * nResolved++ / nUnresolved));
                                    }
                                    else if (nodePepGroup.ProteinMetadata.NeedsSearch())
                                    {
                                        var proteinMetadata = proteomeDb.GetProteinMetadataByName(nodePepGroup.Name);
                                        if ((proteinMetadata == null) && !Equals(nodePepGroup.Name, nodePepGroup.OriginalName))
                                            proteinMetadata = proteomeDb.GetProteinMetadataByName(nodePepGroup.OriginalName); // Original name might hit
                                        if ((proteinMetadata == null) && !String.IsNullOrEmpty(nodePepGroup.ProteinMetadata.Accession))
                                            proteinMetadata = proteomeDb.GetProteinMetadataByName(nodePepGroup.ProteinMetadata.Accession); // Parsed accession might hit
                                        if ((proteinMetadata != null) && !proteinMetadata.NeedsSearch())
                                        {
                                            // Background proteome has already resolved this
                                            _processedNodes.Add(nodePepGroup.Id.GlobalIndex, proteinMetadata);
                                            progressMonitor.UpdateProgress(
                                                progressStatus =
                                                    progressStatus.ChangePercentComplete(100*nResolved++/nUnresolved));
                                        }
                                    }
                                    if (progressMonitor.IsCanceled)
                                    {
                                        progressMonitor.UpdateProgress(progressStatus.Cancel());
                                        return null;
                                    }
                                }
                            }
                        }
                        // ReSharper disable once EmptyGeneralCatchClause
                        catch
                        {
                            // The protDB file is busy, or some other issue - just go directly to web
                        }
                    }
                }
                if (nResolved != nUnresolved)
                {
                    try
                    {
                        // Now go to the web for more protein metadata (or pretend to, depending on WebEnabledFastaImporter.DefaultWebAccessMode)
                        var docNodesWithUnresolvedProteinMetadata = new Dictionary<ProteinSearchInfo,PeptideGroupDocNode>();
                        var proteinsToSearch = new List<ProteinSearchInfo>();
                        foreach (PeptideGroupDocNode node in docOrig.PeptideGroups)
                        {
                            if (node.ProteinMetadata.NeedsSearch() && !_processedNodes.ContainsKey(node.Id.GlobalIndex)) // Did we already process this?
                            {
                                var proteinMetadata = node.ProteinMetadata;
                                if (proteinMetadata.WebSearchInfo.IsEmpty()) // Never even been hit with regex
                                {
                                    // Use Regexes to get some metadata, and a search term
                                    var parsedProteinMetaData = FastaImporter.ParseProteinMetaData(proteinMetadata);
                                    if ((parsedProteinMetaData == null) || Equals(parsedProteinMetaData.Merge(proteinMetadata),proteinMetadata.SetWebSearchCompleted()))
                                    {
                                        // That didn't parse well enough to make a search term, or didn't add any new info - just set it as searched so we don't keep trying
                                        _processedNodes.Add(node.Id.GlobalIndex, proteinMetadata.SetWebSearchCompleted());
                                        progressMonitor.UpdateProgress(progressStatus = progressStatus.ChangePercentComplete(100 * nResolved++ / nUnresolved));
                                        proteinMetadata = null;  // No search to be done
                                    }
                                    else
                                    {
                                        proteinMetadata = proteinMetadata.Merge(parsedProteinMetaData);  // Fill in any gaps with parsed info
                                    }
                                }
                                if (proteinMetadata != null)
                                {
                                    // We note the sequence length because it's useful in disambiguating search results
                                    proteinsToSearch.Add(new ProteinSearchInfo(new DbProteinName(null, proteinMetadata),
                                        node.PeptideGroup.Sequence == null ? 0 : node.PeptideGroup.Sequence.Length));
                                    docNodesWithUnresolvedProteinMetadata.Add(proteinsToSearch.Last(), node);
                                }
                            }
                        }
                        if (progressMonitor.IsCanceled)
                        {
                            progressMonitor.UpdateProgress(progressStatus.Cancel());
                            return null;
                        }
                        progressMonitor.UpdateProgress(progressStatus = progressStatus.ChangePercentComplete(100 * nResolved / nUnresolved));

                        // Now we actually hit the internet
                        if (proteinsToSearch.Any())
                        {
                            foreach (var result in FastaImporter.DoWebserviceLookup(proteinsToSearch, progressMonitor, false)) // Resolve them all, now
                            {
                                Debug.Assert(!result.GetProteinMetadata().NeedsSearch());
                                _processedNodes.Add(docNodesWithUnresolvedProteinMetadata[result].Id.GlobalIndex, result.GetProteinMetadata());
                                progressMonitor.UpdateProgress(progressStatus = progressStatus.ChangePercentComplete(100 * nResolved++ / nUnresolved));
                            }
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        progressMonitor.UpdateProgress(progressStatus.Cancel());
                        return null;
                    }

                }

                // And finally write back to the document
                var listProteins = new List<PeptideGroupDocNode>();
                foreach (PeptideGroupDocNode node in docOrig.MoleculeGroups)
                {
                    if (_processedNodes.ContainsKey(node.Id.GlobalIndex))
                    {
                        listProteins.Add(node.ChangeProteinMetadata(_processedNodes[node.Id.GlobalIndex]));
                    }
                    else
                    {
                        listProteins.Add(node);
                    }
                }
                var docNew = docOrig.ChangeChildrenChecked(listProteins.Cast<DocNode>().ToArray());
                progressMonitor.UpdateProgress(progressStatus.Complete());
                return (SrmDocument)docNew;
            }
        }
コード例 #8
0
        public void Run(ProcessStartInfo psi, string stdin, IProgressMonitor progress, ref ProgressStatus status)
        {
            // Make sure required streams are redirected.
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardError  = true;

            var proc = Process.Start(psi);

            if (proc == null)
            {
                throw new IOException(string.Format("Failure starting {0} command.", psi.FileName));
            }
            if (stdin != null)
            {
                try
                {
                    proc.StandardInput.Write(stdin);
                }
                finally
                {
                    proc.StandardInput.Close();
                }
            }

            var           reader      = new ProcessStreamReader(proc);
            StringBuilder sbError     = new StringBuilder();
            int           percentLast = 0;
            string        line;

            while ((line = reader.ReadLine()) != null)
            {
                if (progress == null || line.ToLower().StartsWith("error"))
                {
                    sbError.AppendLine(line);
                }
                else // if (progress != null)
                {
                    if (progress.IsCanceled)
                    {
                        proc.Kill();
                        progress.UpdateProgress(status = status.Cancel());
                        return;
                    }

                    if (line.EndsWith("%"))
                    {
                        double   percent;
                        string[] parts       = line.Split(' ');
                        string   percentPart = parts[parts.Length - 1];
                        if (double.TryParse(percentPart.Substring(0, percentPart.Length - 1), out percent))
                        {
                            percentLast = (int)percent;
                            status      = status.ChangePercentComplete(percentLast);
                            if (percent >= 100 && status.SegmentCount > 0)
                            {
                                status = status.NextSegment();
                            }
                            progress.UpdateProgress(status);
                        }
                    }
                    else if (MessagePrefix == null || line.StartsWith(MessagePrefix))
                    {
                        // Remove prefix, if there is one.
                        if (MessagePrefix != null)
                        {
                            line = line.Substring(MessagePrefix.Length);
                        }

                        status = status.ChangeMessage(line);
                        progress.UpdateProgress(status);
                    }
                }
            }
            proc.WaitForExit();
            int exit = proc.ExitCode;

            if (exit != 0)
            {
                line = proc.StandardError.ReadLine();
                if (line != null)
                {
                    sbError.AppendLine(line);
                }
                if (sbError.Length == 0)
                {
                    throw new IOException("Error occurred running process.");
                }
                throw new IOException(sbError.ToString());
            }
            // Make to complete the status, if the process succeeded, but never
            // printed 100% to the console
            else if (percentLast < 100)
            {
                status = status.ChangePercentComplete(100);
                if (status.SegmentCount > 0)
                {
                    status = status.NextSegment();
                }
                if (progress != null)
                {
                    progress.UpdateProgress(status);
                }
            }
        }
コード例 #9
0
 public static SrmDocument RecalculateAlignments(SrmDocument document, IProgressMonitor progressMonitor)
 {
     var newSources = ListAvailableRetentionTimeSources(document.Settings);
     var newResultsSources = ListSourcesForResults(document.Settings.MeasuredResults, newSources);
     var allLibraryRetentionTimes = ReadAllRetentionTimes(document, newSources);
     var newFileAlignments = new List<FileRetentionTimeAlignments>();
     var progressStatus = new ProgressStatus("Aligning retention times"); // Not L10N?  Will users see this?
     foreach (var retentionTimeSource in newResultsSources.Values)
     {
         progressStatus = progressStatus.ChangePercentComplete(100*newFileAlignments.Count/newResultsSources.Count);
         progressMonitor.UpdateProgress(progressStatus);
         try
         {
             var fileAlignments = CalculateFileRetentionTimeAlignments(retentionTimeSource.Name, allLibraryRetentionTimes, progressMonitor);
             newFileAlignments.Add(fileAlignments);
         }
         catch (OperationCanceledException)
         {
             progressMonitor.UpdateProgress(progressStatus.Cancel());
             return null;
         }
     }
     var newDocRt = new DocumentRetentionTimes(newSources.Values, newFileAlignments);
     var newDocument = document.ChangeSettings(document.Settings.ChangeDocumentRetentionTimes(newDocRt));
     Debug.Assert(IsLoaded(newDocument));
     progressMonitor.UpdateProgress(progressStatus.Complete());
     return newDocument;
 }
コード例 #10
0
ファイル: BiblioSpec.cs プロジェクト: lgatto/proteowizard
        // ReSharper restore UnusedMember.Local
        private bool Load(ILoadMonitor loader)
        {
            ProgressStatus status =
                new ProgressStatus(string.Format(Resources.BiblioSpecLibrary_Load_Loading__0__library,
                                                 Path.GetFileName(FilePath)));
            loader.UpdateProgress(status);

            long lenRead = 0;
            // AdlerChecksum checksum = new AdlerChecksum();

            try
            {
                // Use a buffered stream for initial read
                BufferedStream stream = new BufferedStream(CreateStream(loader), 32 * 1024);

                int countHeader = (int) LibHeaders.count*4;
                byte[] libHeader = new byte[countHeader];
                if (stream.Read(libHeader, 0, countHeader) != countHeader)
                    throw new InvalidDataException(Resources.BiblioSpecLibrary_Load_Data_truncation_in_library_header_File_may_be_corrupted);
                lenRead += countHeader;
                // Check the first byte of the primary version number to determine
                // whether the format is little- or big-endian.  Little-endian will
                // have the version number in this byte, while big-endian will have zero.
                if (libHeader[(int) LibHeaders.version1 * 4] == 0)
                    _bigEndian = true;

                int numSpectra = GetInt32(libHeader, (int) LibHeaders.num_spectra);
                var dictLibrary = new Dictionary<LibKey, BiblioSpectrumInfo>(numSpectra);
                var setSequences = new HashSet<LibSeqKey>();

                string revStr = string.Format("{0}.{1}", // Not L10N
                                              GetInt32(libHeader, (int) LibHeaders.version1),
                                              GetInt32(libHeader, (int) LibHeaders.version2));
                Revision = float.Parse(revStr, CultureInfo.InvariantCulture);

                // checksum.MakeForBuff(libHeader, AdlerChecksum.ADLER_START);

                countHeader = (int) SpectrumHeaders.count*4;
                byte[] specHeader = new byte[1024];
                byte[] specSequence = new byte[1024];
                for (int i = 0; i < numSpectra; i++)
                {
                    int percent = i * 100 / numSpectra;
                    if (status.PercentComplete != percent)
                    {
                        // Check for cancellation after each integer change in percent loaded.
                        if (loader.IsCanceled)
                        {
                            loader.UpdateProgress(status.Cancel());
                            return false;
                        }

                        // If not cancelled, update progress.
                        loader.UpdateProgress(status = status.ChangePercentComplete(percent));
                    }

                    // Read spectrum header
                    int bytesRead = stream.Read(specHeader, 0, countHeader);
                    if (bytesRead != countHeader)
                        throw new InvalidDataException(Resources.BiblioSpecLibrary_Load_Data_truncation_in_spectrum_header_File_may_be_corrupted);

                    // If this is the first header, and the sequence length is zero,
                    // then this is a Linux format library.  Switch to linux format,
                    // and start over.
                    if (i == 0 && GetInt32(specHeader, (int)SpectrumHeaders.seq_len) == 0)
                    {
                        _linuxFormat = true;
                        stream.Seek(lenRead, SeekOrigin.Begin);

                        // Re-ead spectrum header
                        countHeader = (int)SpectrumHeadersLinux.count * 4;
                        bytesRead = stream.Read(specHeader, 0, countHeader);
                        if (bytesRead != countHeader)
                            throw new InvalidDataException(Resources.BiblioSpecLibrary_Load_Data_truncation_in_spectrum_header_File_may_be_corrupted);
                    }

                    lenRead += bytesRead;

                    // checksum.MakeForBuff(specHeader, checksum.ChecksumValue);

                    int charge = GetInt32(specHeader, (int)SpectrumHeaders.charge);
                    if (charge > TransitionGroup.MAX_PRECURSOR_CHARGE)
                        throw new InvalidDataException(Resources.BiblioSpecLibrary_Load_Invalid_precursor_charge_found_File_may_be_corrupted);

                    int numPeaks = GetInt32(specHeader, (int)SpectrumHeaders.num_peaks);
                    int seqLength = GetInt32(specHeader, (_linuxFormat ?
                        (int)SpectrumHeadersLinux.seq_len : (int)SpectrumHeaders.seq_len));
                    int copies = GetInt32(specHeader, (_linuxFormat ?
                        (int)SpectrumHeadersLinux.copies : (int)SpectrumHeaders.copies));

                    // Read sequence information
                    int countSeq = (seqLength + 1)*2;
                    if (stream.Read(specSequence, 0, countSeq) != countSeq)
                        throw new InvalidDataException(Resources.BiblioSpecLibrary_Load_Data_truncation_in_spectrum_sequence_File_may_be_corrupted);

                    lenRead += countSeq;

                    // checksum.MakeForBuff(specSequence, checksum.ChecksumValue);

                    // Store in dictionary
                    if (IsUnmodified(specSequence, seqLength + 1, seqLength))
                    {
                        // These libraries should not have duplicates, but just in case.
                        // CONSIDER: Emit error about redundancy?
                        // These legacy libraries assume [+57.0] modified Cysteine
                        LibKey key = new LibKey(GetCModified(specSequence, ref seqLength), 0, seqLength, charge);
                        if (!dictLibrary.ContainsKey(key))
                            dictLibrary.Add(key, new BiblioSpectrumInfo((short)copies, (short)numPeaks, lenRead));
                        setSequences.Add(new LibSeqKey(key));
                    }

                    // Read over peaks
                    int countPeaks = 2*sizeof(Single)*numPeaks;
                    stream.Seek(countPeaks, SeekOrigin.Current);    // Skip spectrum
                    lenRead += countPeaks;

                    // checksum.MakeForBuff(specPeaks, checksum.ChecksumValue);
                }

                // Checksum = checksum.ChecksumValue;
                _dictLibrary = dictLibrary;
                _setSequences = setSequences;
                loader.UpdateProgress(status.Complete());
                return true;
            }
            catch (InvalidDataException x)
            {
                loader.UpdateProgress(status.ChangeErrorException(x));
                return false;
            }
            catch (IOException x)
            {
                loader.UpdateProgress(status.ChangeErrorException(x));
                return false;
            }
            catch (Exception x)
            {
                x = new Exception(string.Format(Resources.BiblioSpecLibrary_Load_Failed_loading_library__0__, FilePath), x);
                loader.UpdateProgress(status.ChangeErrorException(x));
                return false;
            }
            finally
            {
                if (ReadStream != null)
                {
                    // Close the read stream to ensure we never leak it.
                    // This only costs on extra open, the first time the
                    // active document tries to read.
                    try { ReadStream.CloseStream(); }
                    catch(IOException) {}
                }
            }
        }