private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var fileInfo = new FileInfo(pbPreview.ImageLocation);
            if (!fileInfo.Exists) return;

            var saver = new FileSaver();
            saver.Save(pbPreview.ImageLocation, InitialDirectory);
        }
Пример #2
0
 protected ChromCacheWriter(string cachePath, ILoadMonitor loader, ProgressStatus status,
     Action<ChromatogramCache, Exception> completed)
 {
     CachePath = cachePath;
     _fs = new FileSaver(CachePath);
     _fsScans = new FileSaver(CachePath + ChromatogramCache.SCANS_EXT, true);
     _fsPeaks = new FileSaver(CachePath + ChromatogramCache.PEAKS_EXT, true);
     _fsScores = new FileSaver(CachePath + ChromatogramCache.SCORES_EXT, true);
     _loader = loader;
     _status = status;
     _completed = completed;
 }
Пример #3
0
 public void ReportToCsv(ReportSpec reportSpec, SrmDocument doc, string fileName, CultureInfo cultureInfo)
 {
     Report report = Report.Load(reportSpec);
     using (var saver = new FileSaver(fileName))
     using (var writer = new StreamWriter(saver.SafeName))
     using (var database = new Database(doc.Settings))
     {
         database.AddSrmDocument(doc);
         var resultSet = report.Execute(database);
         char separator = TextUtil.GetCsvSeparator(cultureInfo);
         ResultSet.WriteReportHelper(resultSet, separator, writer, cultureInfo);
         writer.Flush();
         writer.Close();
         saver.Commit();
     }
 }
Пример #4
0
        public override bool Apply(Request request)
        {
            if (request.Response == null)
                return false;
            if ((request.Flags ["save"] || request.Response.Flags ["save"]) == false)
                return false;

            //Intercept data connection
            FileSaver save = new FileSaver (request, this, request.Response.Stream);
            lock (savings) {
                savings.Add (save);
            }
            request.Response.Stream = save;

            return true;
        }
Пример #5
0
 public void RunConversion(IEnumerable<string> individualInput, string combinedOutput)
 {
     using (var fs = new FileSaver(combinedOutput))
     using (var writer = new StreamWriter(fs.SafeName))
     {
         bool first = true;
         var fields = new List<string>();
         int currentFileCount = 0;
         foreach (var inputFile in individualInput)
         {
             using (var reader = new StreamReader(inputFile))
             {
                 fields = TranscribeAndModifyFile(writer, reader, fields, first, currentFileCount);
             }
             first = false;
             ++currentFileCount;
         }
         writer.Close();
         fs.Commit();
     }
 }
Пример #6
0
        public static void Main(string[] args)
        {
            int port = 50400;

            FileSaver fs = null;

            // read from parameters
            try {
                FileSaver.RootMapping mapping = new FileSaver.RootMapping ();
                mapping.domain = args[0];
                mapping.localRootPath = args[1];

                if (args.Length >= 3)
                    port = int.Parse(args[2]);

                fs = new FileSaver (port);
                fs.AddRoot(mapping);
            }
            catch (IndexOutOfRangeException)
            {
                Console.Error.WriteLine ("Bad arguments");
                Console.WriteLine ("Usage:\nHttpFileSaver domain path/to/www/root [port-number]");
                return;
            }
            catch(Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
                Console.WriteLine("Usage:\nHttpFileSaver domain path/to/www/root [port-number]");
                return;
            }

            fs.NewMessage += (sender, e) => Console.Write(e.message);

            Console.WriteLine ("Starting listening on port {0}", port);
            fs.Start();
        }
Пример #7
0
        private bool ValidateBuilder(bool validateInputFiles)
        {
            string name;

            if (!_helper.ValidateNameTextBox(textName, out name))
            {
                return(false);
            }

            string outputPath = textPath.Text;

            if (string.IsNullOrEmpty(outputPath))
            {
                _helper.ShowTextBoxError(textPath, Resources.BuildLibraryDlg_ValidateBuilder_You_must_specify_an_output_file_path, outputPath);
                return(false);
            }
            if (Directory.Exists(outputPath))
            {
                _helper.ShowTextBoxError(textPath, Resources.BuildLibraryDlg_ValidateBuilder_The_output_path__0__is_a_directory_You_must_specify_a_file_path, outputPath);
                return(false);
            }
            string outputDir = Path.GetDirectoryName(outputPath);

            if (string.IsNullOrEmpty(outputDir) || !Directory.Exists(outputDir))
            {
                _helper.ShowTextBoxError(textPath, Resources.BuildLibraryDlg_ValidateBuilder_The_directory__0__does_not_exist, outputDir);
                return(false);
            }
            if (!outputPath.EndsWith(BiblioSpecLiteSpec.EXT))
            {
                outputPath += BiblioSpecLiteSpec.EXT;
            }
            try
            {
                using (var sfLib = new FileSaver(outputPath))
                {
                    if (!sfLib.CanSave(this))
                    {
                        textPath.Focus();
                        textPath.SelectAll();
                        return(false);
                    }
                }
            }
            catch (UnauthorizedAccessException)
            {
                _helper.ShowTextBoxError(textPath, TextUtil.LineSeparate(Resources.BuildLibraryDlg_ValidateBuilder_Access_violation_attempting_to_write_to__0__,
                                                                         Resources.BuildLibraryDlg_ValidateBuilder_Please_check_that_you_have_write_access_to_this_folder_), outputDir);
                return(false);
            }
            catch (IOException)
            {
                _helper.ShowTextBoxError(textPath, TextUtil.LineSeparate(Resources.BuildLibraryDlg_ValidateBuilder_Failure_attempting_to_create_a_file_in__0__,
                                                                         Resources.BuildLibraryDlg_ValidateBuilder_Please_check_that_you_have_write_access_to_this_folder_), outputDir);
                return(false);
            }

            double cutOffScore;

            if (!_helper.ValidateDecimalTextBox(textCutoff, 0, 1.0, out cutOffScore))
            {
                return(false);
            }
            Settings.Default.LibraryResultCutOff = cutOffScore;

            var libraryBuildAction = LibraryBuildAction;

            if (validateInputFiles)
            {
                var inputFilesChosen = new List <string>();
                foreach (int i in listInputFiles.CheckedIndices)
                {
                    inputFilesChosen.Add(_inputFileNames[i]);
                }

                List <Target> targetPeptidesChosen = null;
                if (cbFilter.Checked)
                {
                    targetPeptidesChosen = new List <Target>();
                    var doc = _documentUiContainer.Document;
                    foreach (PeptideDocNode nodePep in doc.Peptides)
                    {
                        // Add light modified sequences
                        targetPeptidesChosen.Add(nodePep.ModifiedTarget);
                        // Add heavy modified sequences
                        foreach (var nodeGroup in nodePep.TransitionGroups)
                        {
                            if (nodeGroup.TransitionGroup.LabelType.IsLight)
                            {
                                continue;
                            }
                            targetPeptidesChosen.Add(doc.Settings.GetModifiedSequence(nodePep.Peptide.Target,
                                                                                      nodeGroup.TransitionGroup.LabelType,
                                                                                      nodePep.ExplicitMods,
                                                                                      SequenceModFormatType.lib_precision));
                        }
                    }
                }

                if (prositDataSourceRadioButton.Checked)
                {
                    // TODO: Need to figure out a better way to do this, use PrositPeptidePrecursorPair?
                    var doc                  = _documentUiContainer.DocumentUI;
                    var peptides             = doc.Peptides.Where(pep => !pep.IsDecoy).ToArray();
                    var precursorCount       = peptides.Sum(pep => pep.TransitionGroupCount);
                    var peptidesPerPrecursor = new PeptideDocNode[precursorCount];
                    var precursors           = new TransitionGroupDocNode[precursorCount];
                    int index                = 0;

                    for (var i = 0; i < peptides.Length; ++i)
                    {
                        var groups = peptides[i].TransitionGroups.ToArray();
                        Array.Copy(Enumerable.Repeat(peptides[i], groups.Length).ToArray(), 0, peptidesPerPrecursor, index,
                                   groups.Length);
                        Array.Copy(groups, 0, precursors, index, groups.Length);
                        index += groups.Length;
                    }

                    try
                    {
                        PrositUIHelpers.CheckPrositSettings(this, _skylineWindow);
                        // Still construct the library builder, otherwise a user might configure Prosit
                        // incorrectly, causing the build to silently fail
                        Builder = new PrositLibraryBuilder(doc, name, outputPath, () => true, IrtStandard,
                                                           peptidesPerPrecursor, precursors, NCE);
                    }
                    catch (Exception ex)
                    {
                        _helper.ShowTextBoxError(this, ex.Message);
                        return(false);
                    }
                }
                else
                {
                    Builder = new BiblioSpecLiteBuilder(name, outputPath, inputFilesChosen, targetPeptidesChosen)
                    {
                        Action = libraryBuildAction,
                        IncludeAmbiguousMatches = cbIncludeAmbiguousMatches.Checked,
                        KeepRedundant           = LibraryKeepRedundant,
                        CutOffScore             = cutOffScore,
                        Id                    = Helpers.MakeId(textName.Text),
                        IrtStandard           = _driverStandards.SelectedItem,
                        PreferEmbeddedSpectra = PreferEmbeddedSpectra
                    };
                }
            }
            return(true);
        }
Пример #8
0
        public bool BuildLibrary(IProgressMonitor progress)
        {
            _ambiguousMatches = null;
            IProgressStatus status = new ProgressStatus(Resources.BiblioSpecLiteBuilder_BuildLibrary_Preparing_to_build_library);

            progress.UpdateProgress(status);
            if (InputFiles.Any(f => f.EndsWith(EXT_PILOT)))
            {
                try
                {
                    InputFiles = VendorIssueHelper.ConvertPilotFiles(InputFiles, progress, status);
                    if (progress.IsCanceled)
                    {
                        return(false);
                    }
                }
                catch (Exception x)
                {
                    progress.UpdateProgress(status.ChangeErrorException(x));
                    return(false);
                }
            }

            string message = string.Format(Resources.BiblioSpecLiteBuilder_BuildLibrary_Building__0__library,
                                           Path.GetFileName(OutputPath));

            progress.UpdateProgress(status = status.ChangeMessage(message));
            string redundantLibrary = BiblioSpecLiteSpec.GetRedundantName(OutputPath);
            var    blibBuilder      = new BlibBuild(redundantLibrary, InputFiles, TargetSequences)
            {
                IncludeAmbiguousMatches = IncludeAmbiguousMatches,
                CutOffScore             = CutOffScore,
                Id = Id,
                PreferEmbeddedSpectra = PreferEmbeddedSpectra,
                DebugMode             = DebugMode,
            };

            bool retry = true;

            do
            {
                try
                {
                    if (!blibBuilder.BuildLibrary(Action, progress, ref status,
                                                  out _buildCommandArgs, out _buildOutput, out _ambiguousMatches))
                    {
                        return(false);
                    }

                    retry = false;
                }
                catch (IOException x)
                {
                    if (IsLibraryMissingExternalSpectraError(x, out string spectrumFilename, out string resultsFilepath))
                    {
                        // replace the relative path to the results file (e.g. msms.txt) with the absolute path
                        string fullResultsFilepath = InputFiles.SingleOrDefault(o => o.EndsWith(resultsFilepath)) ??
                                                     throw new InvalidDataException(@"no results filepath from BiblioSpec error message", x);

                        // TODO: this will break if BiblioSpec output is translated to other languages
                        string messageWithFullFilepath =
                            x.Message.Replace(@"search results file '" + resultsFilepath,
                                              @"search results file '" + fullResultsFilepath);

                        var response =
                            progress.UpdateProgress(
                                status.ChangeErrorException(new IOException(messageWithFullFilepath, x)));
                        if (response == UpdateProgressResponse.cancel)
                        {
                            return(false);
                        }
                        else if (response == UpdateProgressResponse.normal)
                        {
                            blibBuilder.PreferEmbeddedSpectra = true;
                        }
                        continue;
                    }

                    progress.UpdateProgress(status.ChangeErrorException(x));
                    return(false);
                }
                catch (Exception x)
                {
                    Console.WriteLine(x.Message);
                    progress.UpdateProgress(status.ChangeErrorException(
                                                new Exception(string.Format(Resources.BiblioSpecLiteBuilder_BuildLibrary_Failed_trying_to_build_the_redundant_library__0__,
                                                                            redundantLibrary))));
                    return(false);
                }
            } while (retry);

            var blibFilter = new BlibFilter();

            status = new ProgressStatus(message);
            progress.UpdateProgress(status);
            // Write the non-redundant library to a temporary file first
            try
            {
                using (var saver = new FileSaver(OutputPath))
                {
                    if (!blibFilter.Filter(redundantLibrary, saver.SafeName, progress, ref status))
                    {
                        return(false);
                    }

                    saver.Commit();
                }
            }
            catch (IOException x)
            {
                progress.UpdateProgress(status.ChangeErrorException(x));
                return(false);
            }
            catch
            {
                progress.UpdateProgress(status.ChangeErrorException(
                                            new Exception(string.Format(Resources.BiblioSpecLiteBuilder_BuildLibrary_Failed_trying_to_build_the_library__0__,
                                                                        OutputPath))));
                return(false);
            }
            finally
            {
                if (!KeepRedundant)
                {
                    FileEx.SafeDelete(redundantLibrary, true);
                }
            }

            return(true);
        }
        private BackgroundProteome Load(IDocumentContainer container, PeptideSettings settings, SrmDocument docCurrent, bool isBackgroundLoad)
        {
            // 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.
            // There may also be a load initiation by the Peptide Settings dialog as foreground task,
            // it takes priority over the background task.
            lock (_lockLoadBackgroundProteome)
            {
                BackgroundProteome originalBackgroundProteome = settings.BackgroundProteome;
                // Check to see whether the Digestion already exists but has not been queried yet.
                BackgroundProteome backgroundProteomeWithDigestions = new BackgroundProteome(originalBackgroundProteome, true);
                if (IsNotLoadedExplained(settings, backgroundProteomeWithDigestions, true) == null)
                {
                    // digest is ready, and protein metdata is resolved
                    CompleteProcessing(container, backgroundProteomeWithDigestions);
                    return(originalBackgroundProteome); // No change needed
                }
                // are we here to do the digest, or to resolve the protein metadata?
                var  needsProteinMetadataSearch = backgroundProteomeWithDigestions.NeedsProteinMetadataSearch;
                bool getMetadata = (IsNotLoadedExplained(settings, backgroundProteomeWithDigestions, false) == null) &&
                                   needsProteinMetadataSearch;

                string          name           = originalBackgroundProteome.Name;
                IProgressStatus progressStatus =
                    new ProgressStatus(string.Format(getMetadata?Resources.BackgroundProteomeManager_LoadBackground_Resolving_protein_details_for__0__proteome:Resources.BackgroundProteomeManager_LoadBackground_Digesting__0__proteome, name));
                try
                {
                    // The transaction commit for writing the digestion info can be very lengthy, avoid lock timeouts
                    // by doing that work in a tempfile that no other thread knows aboout
                    using (FileSaver fs = new FileSaver(originalBackgroundProteome.DatabasePath, StreamManager))
                    {
                        File.Copy(originalBackgroundProteome.DatabasePath, fs.SafeName, true);
                        var digestHelper = new DigestHelper(this, container, docCurrent, settings, name, fs.SafeName, true);

                        bool success;
                        if (getMetadata)
                        {
                            success = digestHelper.LookupProteinMetadata(ref progressStatus);
                        }
                        else
                        {
                            success = digestHelper.Digest(ref progressStatus, true); // Delay indexing until we copy the file back
                        }
                        if (digestHelper.IsCanceled || !success)
                        {
                            // Processing was canceled
                            if (docCurrent != null)
                            {
                                EndProcessing(docCurrent);
                            }
                            UpdateProgress(progressStatus.Cancel());
                            return(null);
                        }
                        using (var proteomeDb = ProteomeDb.OpenProteomeDb(originalBackgroundProteome.DatabasePath))
                        {
                            proteomeDb.DatabaseLock.AcquireWriterLock(int.MaxValue); // Wait for any existing readers to complete, prevent any new ones
                            try
                            {
                                if (File.GetLastWriteTime(fs.RealName) <= File.GetLastWriteTime(fs.SafeName)) // Don't overwrite if foreground task has already updated
                                {
                                    proteomeDb.CloseDbConnection();                                           // Get rid of any file handles
                                    if (!fs.Commit())
                                    {
                                        if (docCurrent != null)
                                        {
                                            EndProcessing(docCurrent);
                                        }
                                        throw new IOException(string.Format(Resources.BackgroundProteomeManager_LoadBackground_Unable_to_rename_temporary_file_to__0__,
                                                                            fs.RealName));
                                    }
                                }
                            }
                            finally
                            {
                                proteomeDb.DatabaseLock.ReleaseWriterLock();
                            }
                        }

                        var proteomeWithDigestions = new BackgroundProteome(originalBackgroundProteome, true);
                        using (var proteomeDb = proteomeWithDigestions.OpenProteomeDb())
                        {
                            proteomeDb.AnalyzeDb(); // Now it's safe to start this potentially lengthy indexing operation
                        }
                        CompleteProcessing(container, proteomeWithDigestions);
                        UpdateProgress(progressStatus.Complete());
                        return(proteomeWithDigestions);
                    }
                }
                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(null);
                }
            }
        }
Пример #10
0
        /// <summary>
        /// Test only method for creating a <see cref="BiblioSpecLibrary"/> file
        /// from another loaded <see cref="Library"/>.  Should this move into test project?
        /// </summary>
        /// <param name="streamManager">Provides access to the file system</param>
        /// <param name="path">Path to write to</param>
        /// <param name="library">The loaded library to use as a data source</param>
        public static void Write(IStreamManager streamManager, string path, Library library)
        {
            using (FileSaver fs = new FileSaver(path, streamManager))
                using (Stream outStream = streamManager.CreateStream(fs.SafeName, FileMode.Create, true))
                {
                    outStream.Write(BitConverter.GetBytes(library.SpectrumCount), 0, sizeof(int)); // num_spectra
                    outStream.Write(BitConverter.GetBytes(0), 0, sizeof(int));                     // filtered
                    outStream.Write(BitConverter.GetBytes(1), 0, sizeof(int));                     // version1
                    outStream.Write(BitConverter.GetBytes(1), 0, sizeof(int));                     // version2
                    outStream.Write(BitConverter.GetBytes(0), 0, sizeof(int));                     // next_id

                    SequenceMassCalc calc = new SequenceMassCalc(MassType.Monoisotopic);

                    byte[] seqBuffer = new byte[1024];

                    int scanNum = 1;

                    foreach (var key in library.Keys)
                    {
                        SpectrumPeaksInfo peaksInfo;
                        if (!library.TryLoadSpectrum(key, out peaksInfo))
                        {
                            continue;
                        }

                        var sequence = key.Target.Sequence;
                        // Only works for unmodified sequence
                        Debug.Assert(!key.IsModified);
                        var   precursorMH = calc.GetPrecursorMass(sequence);
                        int   charge      = key.Charge;
                        float precursorMz = (float)SequenceMassCalc.GetMZ(precursorMH, charge);

                        outStream.Write(BitConverter.GetBytes(scanNum), 0, sizeof(int));                // scan_num
                        outStream.Write(BitConverter.GetBytes(2), 0, sizeof(int));                      // scan_type
                        outStream.Write(BitConverter.GetBytes(precursorMz), 0, sizeof(float));          // pre_mz
                        outStream.Write(BitConverter.GetBytes(charge), 0, sizeof(int));                 // scan_type
                        outStream.Write(BitConverter.GetBytes(0f), 0, sizeof(int));                     // r_time
                        outStream.Write(BitConverter.GetBytes(peaksInfo.Peaks.Length), 0, sizeof(int)); // num_peaks
                        outStream.Write(BitConverter.GetBytes(0), 0, sizeof(int));                      // 32-bit peak_ptr
                        outStream.Write(BitConverter.GetBytes(sequence.Length), 0, sizeof(int));        // seq_len
                        outStream.Write(BitConverter.GetBytes(0), 0, sizeof(int));                      // annot
                        outStream.Write(BitConverter.GetBytes(scanNum), 0, sizeof(int));                // copies (bogus value for ranking)
                        outStream.Write(BitConverter.GetBytes(0), 0, sizeof(int));                      // lib_id
                        scanNum++;

                        // Sequence
                        int len = sequence.Length;
                        seqBuffer[len] = 0;
                        Encoding.UTF8.GetBytes(sequence, 0, len, seqBuffer, 0);
                        outStream.Write(seqBuffer, 0, len + 1);
                        // Modifications
                        const string zeros = "000000000000000000000000000000000000000000000000000";
                        Encoding.UTF8.GetBytes(zeros.Substring(0, len), 0, len, seqBuffer, 0);
                        outStream.Write(seqBuffer, 0, len + 1);
                        // Peaks
                        foreach (var mi in peaksInfo.Peaks)
                        {
                            outStream.Write(BitConverter.GetBytes((float)mi.Mz), 0, sizeof(float));
                            outStream.Write(BitConverter.GetBytes(mi.Intensity), 0, sizeof(float));
                        }
                    }

                    streamManager.Finish(outStream);
                    fs.Commit();
                }
        }
Пример #11
0
        public static void SaveDocument(SrmDocument doc, string outFile, TextWriter outText)
        {
            // Make sure the containing directory is created
            string dirPath = Path.GetDirectoryName(outFile);
            if (dirPath != null)
                Directory.CreateDirectory(dirPath);

            var progressMonitor = new CommandProgressMonitor(outText, new ProgressStatus(string.Empty));
            using (var saver = new FileSaver(outFile))
            {
                saver.CheckException();

                using (var writer = new XmlWriterWithProgress(saver.SafeName, outFile, Encoding.UTF8, doc.MoleculeTransitionCount, progressMonitor))
                {
                    XmlSerializer ser = new XmlSerializer(typeof(SrmDocument));
                    ser.Serialize(writer, doc);

                    writer.Flush();
                    writer.Close();
                    saver.Commit();

                    var settings = doc.Settings;
                    if (settings.HasResults)
                    {
                        if (settings.MeasuredResults.IsLoaded)
                        {
                            FileStreamManager fsm = FileStreamManager.Default;
                            settings.MeasuredResults.OptimizeCache(outFile, fsm);

                            //don't worry about updating the document with the results of optimization
                            //as is done in SkylineFiles
                        }
                    }
                    else
                    {
                        string cachePath = ChromatogramCache.FinalPathForName(outFile, null);
                        FileEx.SafeDelete(cachePath, true);
                    }
                }
            }
        }
Пример #12
0
 public void WriteChromatograms(string filePath, 
     IProgressMonitor progressMonitor,
     IList<string> filesToExport,
     CultureInfo cultureInfo,
     IList<ChromExtractor> chromExtractors,
     IList<ChromSource> chromSources)
 {
     var chromExporter = new ChromatogramExporter(Document);
     using (var saver = new FileSaver(filePath))
     using (var writer = new StreamWriter(saver.SafeName))
     {
         chromExporter.Export(writer, progressMonitor, filesToExport, cultureInfo, chromExtractors, chromSources);
         writer.Close();
         saver.Commit();
     }
 }
Пример #13
0
 public void RunConversion(string rtFile, string scoreFile, string qValueFile, string combinedFile)
 {
     using (var rtReader = new StreamReader(rtFile))
     using (var scoreReader = new StreamReader(scoreFile))
     using (var qValueReader = new StreamReader(qValueFile))
     using (var fs = new FileSaver(combinedFile))
     using (var writer = new StreamWriter(fs.SafeName))
     {
         var rtPeakData = ImportFile(rtReader);
         var scorePeakData = ImportFile(scoreReader);
         var qValuePeakData = ImportFile(qValueReader);
         int nPeaks = rtPeakData.Count;
         Assert.AreEqual(nPeaks, scorePeakData.Count);
         Assert.AreEqual(nPeaks, qValuePeakData.Count);
         WriteHeader(writer);
         for (int i = 0; i < nPeaks; ++i)
         {
             string file = rtPeakData[i].SimplifiedFile;
             string modifiedSequence = rtPeakData[i].ModifiedSequence;
             bool decoy = rtPeakData[i].Decoy;
             Assert.AreEqual(decoy, scorePeakData[i].Decoy);
             Assert.AreEqual(decoy, qValuePeakData[i].Decoy);
             Assert.AreEqual(modifiedSequence, scorePeakData[i].ModifiedSequence);
             Assert.AreEqual(modifiedSequence, qValuePeakData[i].ModifiedSequence);
             double rt = rtPeakData[i].DataValue;
             double score = scorePeakData[i].DataValue;
             double qValue = qValuePeakData[i].DataValue;
             WriteLine(writer, CultureInfo.CurrentCulture, file, modifiedSequence, rt, score, qValue, decoy);
         }
         writer.Close();
         fs.Commit();
     }
 }
Пример #14
0
        private void HangarReset(string HangarDir, bool FixMarket)
        {
            String[] subdirectoryEntries = Directory.GetDirectories(HangarDir);
            foreach (string subdir in subdirectoryEntries)
            {
                string FolderName = new DirectoryInfo(subdir).Name;


                //Main.Debug(FolderName);
                ulong SteamID;
                try
                {
                    SteamID = Convert.ToUInt64(FolderName);
                }
                catch
                {
                    continue;
                    //Not a valid steam dir;
                }


                PlayerInfo Data = new PlayerInfo();
                try
                {
                    Data = JsonConvert.DeserializeObject <PlayerInfo>(File.ReadAllText(Path.Combine(subdir, "PlayerInfo.json")));

                    if (Data == null || Data.Grids == null || Data.Grids.Count == 0)
                    {
                        continue;
                    }



                    var ext = new List <string> {
                        "sbc"
                    };
                    var myFiles = Directory.GetFiles(subdir, "*.sbc", SearchOption.AllDirectories);

                    List <GridStamp> NewGrids = new List <GridStamp>();
                    NewGrids = Data.Grids;
                    for (int i = 0; i < Data.Grids.Count(); i++)
                    {
                        if (!myFiles.Any(x => Path.GetFileNameWithoutExtension(x) == Data.Grids[i].GridName))
                        {
                            Hangar.Debug("Removing grid: " + NewGrids[i].GridName + "! It doesnt exist in the folder!!");
                            NewGrids.RemoveAt(i);
                        }
                    }



                    Data.Grids = NewGrids;
                    FileSaver.Save(Path.Combine(subdir, "PlayerInfo.json"), Data);
                }
                catch (Exception e)
                {
                    //Main.Debug("Unable File IO exception!", e, Main.ErrorType.Warn);
                    //File is prob null/missing
                    continue;
                }
            }



            if (FixMarket)
            {
                for (int i = 0; i < GridMarket.GridList.Count(); i++)
                {
                    //Removes any item with steamID of 0
                    if (GridMarket.GridList[i].Steamid == 0)
                    {
                        Hangar.Debug("Removing " + GridMarket.GridList[i].Name + " from the market. Has SteamID of 0");
                        GridMarket.GridList.RemoveAt(i);
                    }
                }
            }
        }
Пример #15
0
        void OpenFromUrl()
        {
            OpenFromUrlCommand = new CommandBase((parameter, command) =>
            {
                var form   = new OpenFromUrlDialog();
                form.Owner = Model.Window;
                var result = form.ShowDialog();

                if (result == null || !result.Value || string.IsNullOrEmpty(form.Url))
                {
                    return;
                }

                var url = form.Url;
                bool fixupImageLinks = form.FixupImageLinks;

                var fs = new FileSaver();
                url    = fs.ParseMarkdownUrl(url);

                string markdown;
                try
                {
                    markdown = HttpUtils.HttpRequestString(url);
                }
                catch (System.Net.WebException ex)
                {
                    Model.Window.ShowStatus($"Can't open from url: {ex.Message}", 6000, FontAwesomeIcon.Warning,
                                            Colors.Firebrick);
                    return;
                }

                if (string.IsNullOrEmpty(markdown))
                {
                    Model.Window.ShowStatus($"No content found at URL: {url}", 6000, FontAwesomeIcon.Warning,
                                            Colors.Firebrick);
                    return;
                }

                if (fixupImageLinks && url.EndsWith(".md", StringComparison.CurrentCultureIgnoreCase))
                {
                    var uri         = new Uri(url);
                    string basePath =
                        $"{uri.Scheme}://{uri.Authority}{string.Join("", uri.Segments.Take(uri.Segments.Length - 1))}";


                    var reg = new Regex("!\\[.*?]\\(.*?\\)");

                    var matches = reg.Matches(markdown);
                    foreach (Match match in matches)
                    {
                        var link    = match.Value;
                        var linkUrl = StringUtils.ExtractString(link, "](", ")");

                        if (linkUrl.StartsWith("http"))
                        {
                            continue;
                        }

                        var text = StringUtils.ExtractString(link, "![", "](");
                        linkUrl  = basePath + linkUrl;

                        var newLink = $"![text]({linkUrl})";
                        markdown    = markdown.Replace(link, newLink);
                    }

                    reg = new Regex("<img src=\\\".*?/>");

                    matches = reg.Matches(markdown);
                    foreach (Match match in matches)
                    {
                        var link    = match.Value;
                        var linkUrl = StringUtils.ExtractString(link, " src=\"", "\"");

                        if (linkUrl.StartsWith("http"))
                        {
                            continue;
                        }

                        string newLink = basePath + linkUrl;
                        newLink        = link.Replace(linkUrl, newLink);

                        markdown = markdown.Replace(link, newLink);
                    }
                }

                var tab = Model.Window.OpenTab("untitled");
                ((MarkdownDocumentEditor)tab.Tag).MarkdownDocument.CurrentText = markdown;
                Model.Window.PreviewMarkdownAsync();
            }, (p, c) => true);
        }
Пример #16
0
        //AutoSellsGrids (HotPile of s***e)
        private void AutoSellWorker(Hangar Plugin)
        {
            String[] subdirectoryEntries = Directory.GetDirectories(Plugin.Config.FolderDirectory);
            foreach (string subdir in subdirectoryEntries)
            {
                string FolderName = new DirectoryInfo(subdir).Name;

                //Path.GetDirectoryName(subdir+"\\");

                if (FolderName == "PublicOffers")
                {
                    continue;
                }

                //Main.Debug(FolderName);
                ulong SteamID;
                try
                {
                    SteamID = Convert.ToUInt64(FolderName);
                }
                catch
                {
                    continue;
                    //Not a valid steam dir;
                }


                //Check playerlast logon
                //MyPlayer.PlayerId CurrentPlayer = MySession.Static.Players.GetAllPlayers().First(x => x.SteamId == SteamID);
                MyIdentity identity;
                DateTime   LastLogin;
                try
                {
                    string playername = MySession.Static.Players.TryGetIdentityNameFromSteamId(SteamID);
                    identity = MySession.Static.Players.GetAllIdentities().First(x => x.DisplayName == playername);

                    //Main.Debug(identity.DisplayName);


                    //MyPlayer.PlayerId PlayerID = MySession.Static.Players.GetAllPlayers().First(x => x.SteamId == SteamID);
                    //CurrentPlayer = MySession.Static.Players.GetPlayerById(0);
                    LastLogin = identity.LastLoginTime;
                    if (LastLogin.AddDays(Plugin.Config.SellAFKDayAmount) < DateTime.Now)
                    {
                        Hangar.Debug("Grids will be auto sold by auction!");
                    }
                    else
                    {
                        //Main.Debug(LastLogin.AddDays(MaxDayCount).ToString());
                        continue;
                    }
                }
                catch
                {
                    //Perhaps players was removed? Should we delete thy folder? Nah. WE SHALL SELL
                    continue;
                }


                PlayerInfo Data = new PlayerInfo();
                try
                {
                    Data = JsonConvert.DeserializeObject <PlayerInfo>(File.ReadAllText(Path.Combine(subdir, "PlayerInfo.json")));

                    if (Data == null || Data.Grids == null || Data.Grids.Count == 0)
                    {
                        //Delete folder
                        Directory.Delete(subdir);
                        continue;
                    }
                }
                catch (Exception p)
                {
                    //Main.Debug("Unable File IO exception!", e, Main.ErrorType.Warn);
                    //File is prob null/missing
                    continue;
                }


                foreach (GridStamp grid in Data.Grids)
                {
                    //
                    if (grid.GridForSale == true)
                    {
                        //This grid could be for sale somewhere else. We need to remove it

                        try
                        {
                            int index = GridMarket.GridList.FindIndex(x => x.Name == grid.GridName);
                            CrossServerMessage message = new CrossServerMessage();
                            message.Type = CrossServer.MessageType.RemoveItem;
                            message.List.Add(GridMarket.GridList[index]);

                            //Send all servers that we removed an item
                            Servers.Update(message);

                            GridMarket.GridList.RemoveAt(index);
                            grid.GridForSale = false;
                        }
                        catch
                        {
                            //Could be a bugged grid?
                            grid.GridForSale = false;
                        }
                    }

                    string Description = "Sold by server due to inactivity at a discounted price! Originial owner: " + identity.DisplayName;


                    long Price = (long)grid.MarketValue;
                    if (grid.MarketValue == 0)
                    {
                        Price = grid.NumberofBlocks * grid.GridPCU;
                    }

                    grid.MarketValue = Price;

                    Price            = Price / 2;
                    grid.GridForSale = true;

                    if (!SellOnMarket(subdir, grid, Data, identity, Price, Description))
                    {
                        Hangar.Debug("Unkown error on grid sell! Grid doesnt exist! (Dont manually delete files!)");
                        return;
                    }
                }

                FileSaver.Save(Path.Combine(subdir, "PlayerInfo.json"), Data);
                //File.WriteAllText(Path.Combine(subdir, "PlayerInfo.json"), JsonConvert.SerializeObject(Data));
            }
        }
        public bool BuildLibrary(IProgressMonitor progress)
        {
            _ambiguousMatches = null;
            ProgressStatus status = new ProgressStatus(Resources.BiblioSpecLiteBuilder_BuildLibrary_Preparing_to_build_library);

            progress.UpdateProgress(status);
            if (InputFiles.Any(f => f.EndsWith(EXT_PILOT)))
            {
                try
                {
                    InputFiles = VendorIssueHelper.ConvertPilotFiles(InputFiles, progress, status);
                    if (progress.IsCanceled)
                    {
                        return(false);
                    }
                }
                catch (Exception x)
                {
                    progress.UpdateProgress(status.ChangeErrorException(x));
                    return(false);
                }
            }

            string message = string.Format(Resources.BiblioSpecLiteBuilder_BuildLibrary_Building__0__library,
                                           Path.GetFileName(OutputPath));

            progress.UpdateProgress(status = status.ChangeMessage(message));
            string redundantLibrary = BiblioSpecLiteSpec.GetRedundantName(OutputPath);
            var    blibBuilder      = new BlibBuild(redundantLibrary, InputFiles, TargetSequences)
            {
                Authority = Authority,
                IncludeAmbiguousMatches = IncludeAmbiguousMatches,
                CutOffScore             = CutOffScore,
                Id = Id,
            };

            try
            {
                if (!blibBuilder.BuildLibrary(Action, progress, ref status, out _ambiguousMatches))
                {
                    return(false);
                }
            }
            catch (IOException x)
            {
                progress.UpdateProgress(status.ChangeErrorException(x));
                return(false);
            }
            catch (Exception x)
            {
                Console.WriteLine(x.Message);
                progress.UpdateProgress(status.ChangeErrorException(
                                            new Exception(string.Format(Resources.BiblioSpecLiteBuilder_BuildLibrary_Failed_trying_to_build_the_redundant_library__0__,
                                                                        redundantLibrary))));
                return(false);
            }
            var blibFilter = new BlibFilter();

            status = new ProgressStatus(message);
            progress.UpdateProgress(status);
            // Write the non-redundant library to a temporary file first
            try
            {
                using (var saver = new FileSaver(OutputPath))
                {
                    if (!blibFilter.Filter(redundantLibrary, saver.SafeName, progress, ref status))
                    {
                        return(false);
                    }
                    saver.Commit();
                }
            }
            catch (IOException x)
            {
                progress.UpdateProgress(status.ChangeErrorException(x));
                return(false);
            }
            catch
            {
                progress.UpdateProgress(status.ChangeErrorException(
                                            new Exception(string.Format(Resources.BiblioSpecLiteBuilder_BuildLibrary_Failed_trying_to_build_the_library__0__,
                                                                        OutputPath))));
                return(false);
            }
            finally
            {
                if (!KeepRedundant)
                {
                    FileEx.SafeDelete(redundantLibrary, true);
                }
            }

            return(true);
        }
    void LoadTree(string namePath)
    {
        string path = pathRoot + namePath + ".skilltree";

        LoadNodes(FileSaver.JsonToSkillTree(path), namePath);
    }
Пример #19
0
        public async Task <ActionResult> Existing(ExistingFormViewModel exitingViewModel)
        {
            #region validate input

            if (!ModelState.IsValid)
            {
                TempData["error"] = ModelState.ToErrors();

                if (!string.IsNullOrEmpty(exitingViewModel.BlmPointId))
                {
                    return(RedirectToAction("Existing", new
                    {
                        blmid = exitingViewModel.BlmPointId
                    }));
                }

                return(RedirectToRoute("", new
                {
                    Controller = "Home",
                    Action = "Index"
                }));
            }

            #endregion

            var re = new Regex(".pdf$", RegexOptions.IgnoreCase);
            if (exitingViewModel.MonumentForm == null ||
                exitingViewModel.MonumentForm.ContentLength <= 0 ||
                !re.IsMatch(exitingViewModel.MonumentForm.FileName))
            {
                TempData["error"] = "Please upload a PDF.";

                return(RedirectToAction("Existing", new
                {
                    blmid = exitingViewModel.BlmPointId
                }));
            }

            var  connection = new SqlConnection(ConfigurationManager.ConnectionStrings["PLSS"].ConnectionString);
            User user;
            try
            {
                await connection.OpenAsync();

                user = CommandExecutor.ExecuteCommand(new GetUserCommand(connection, User.Identity.Name));

                if (user == null)
                {
                    TempData["error"] = "You must log in to submit corner information";

                    return(RedirectToRoute("", new
                    {
                        Controller = "Home",
                        Action = "Index"
                    }));
                }
            }
            catch (Exception ex)
            {
                Log.LogException(LogLevel.Fatal, "problem getting user", ex);
                throw;
            }
            finally
            {
                connection.Close();
                connection.Dispose();
            }

            byte[] pdfBytes;
            using (var binaryReader = new BinaryReader(exitingViewModel.MonumentForm.InputStream))
            {
                pdfBytes = binaryReader.ReadBytes(exitingViewModel.MonumentForm.ContentLength);
            }

            var path = Path.Combine("UserCommittedTieSheets",
                                    user.Name,
                                    DateTime.Now.ToShortDateString().Replace("/", "-"),
                                    exitingViewModel.BlmPointId).Replace(@"\", "/") + ".pdf";
            var actualPath = Path.Combine(Config.Global.Get <string>("SharePath"), path);

            Log.Info($"Writing PDF to: {actualPath}");
            var success = FileSaver.SaveFile(actualPath, pdfBytes);

            if (!success)
            {
                //show error and redirect to page
                TempData["error"] = "There was a problem uploading your document. Please try again.";

                return(RedirectToRoute("", new
                {
                    Controller = "Home",
                    Action = "Index"
                }));
            }

            Log.Info("Sending admin notification email");

            CommandExecutor.ExecuteCommand(new UserSubmittedEmailCommand(
                                               new UserSubmittedEmailCommand.MailTemplate(App.AdminEmails,
                                                                                          new[] { user.UserName },
                                                                                          user.Name,
                                                                                          exitingViewModel.BlmPointId,
                                                                                          DateTime.Now.ToShortDateString(),
                                                                                          actualPath)));

#if RELEASE
            var          apikey   = Config.Global.Get <string>("prodKey");
            const string referrer = "http://plss.utah.gov/";
#endif
#if STAGE
            var          apikey   = Config.Global.Get <string>("stageKey");
            const string referrer = "http://test.mapserv.utah.gov/plss";
#endif
#if DEBUG
            var          apikey   = Config.Global.Get <string>("devKey");
            const string referrer = "http://localhost";
#endif
            Log.Info("Getting county from api with referrer {0} and api key {1}", referrer, apikey);
            //find what county the point is in
            string countyName;
            try
            {
                var client  = new RestClient("http://api.mapserv.utah.gov/api/v1/");
                var request = new RestRequest("search/{layer}/{returnValues}", Method.GET);

                request.AddUrlSegment("layer", "SGID10.CADASTRE.PLSSPoint_AGRC");
                request.AddUrlSegment("returnValues", "xcoord, ycoord");
                request.AddParameter("predicate", $"pointid = '{exitingViewModel.BlmPointId}'");
                request.AddParameter("attributeStyle", "lower");
                request.AddParameter("apiKey", apikey);

                request.AddHeader("Referer", referrer);

                var response = client.Execute <SearchApiContainer>(request);

                if (response.Data == null)
                {
                    Log.Warn($"problem querying webservice for blm point id {client.BuildUri(request)}. {response.ErrorMessage}");

                    TempData["message"] = "Monument saved successfully but the county contact was not notfied.";

                    return(RedirectToRoute("", new
                    {
                        Controller = "Home",
                        Action = "Index"
                    }));
                }

                if (response.Data.result == null)
                {
                    Log.Warn($"problem querying webservice for blm point id {client.BuildUri(request)}. {response.Content}");

                    TempData["message"] = "Monument saved successfully but the county contact was not notfied.";

                    return(RedirectToRoute("", new
                    {
                        Controller = "Home",
                        Action = "Index"
                    }));
                }

                var searchApiResult = response.Data.result.FirstOrDefault();

                if (searchApiResult == null)
                {
                    Log.Warn($"problem querying webservice for blm point id {client.BuildUri(request)}. {response.Content}");

                    TempData["message"] = "Monument saved successfully but the county contact was not notfied.";

                    return(RedirectToRoute("", new
                    {
                        Controller = "Home",
                        Action = "Index"
                    }));
                }

                var xcoord = searchApiResult.attributes["xcoord"];
                var ycoord = searchApiResult.attributes["ycoord"];

                request = new RestRequest("search/{layer}/{returnValues}");
                request.AddUrlSegment("layer", "SGID10.BOUNDARIES.Counties");
                request.AddUrlSegment("returnValues", "NAME");
                request.AddParameter("attributeStyle", "lower");

                request.AddParameter("geometry", $"point:[{xcoord},{ycoord}]");

                request.AddParameter("spatialReference", "4326");
                request.AddParameter("apiKey", apikey);

                request.AddHeader("Referer", referrer);

                var county = client.Execute <SearchApiContainer>(request);

                if (county.Data == null)
                {
                    Log.Warn($"problem querying webservice forcounty {client.BuildUri(request)}. {county.ErrorMessage}");

                    TempData["message"] = "Monument saved successfully but the county contact was not notfied.";

                    return(RedirectToRoute("", new
                    {
                        Controller = "Home",
                        Action = "Index"
                    }));
                }

                if (county.Data.result == null)
                {
                    Log.Warn($"problem querying webservice for county {client.BuildUri(request)}. {county.Content}");

                    TempData["message"] = "Monument saved successfully but the county contact was not notfied.";

                    return(RedirectToRoute("", new
                    {
                        Controller = "Home",
                        Action = "Index"
                    }));
                }

                var countResult = county.Data.result.FirstOrDefault();
                if (countResult == null)
                {
                    Log.Warn($"problem querying webservice for county {client.BuildUri(request)}");

                    TempData["message"] = "Monument saved successfully but the county contact was not notfied.";

                    return(RedirectToRoute("", new
                    {
                        Controller = "Home",
                        Action = "Index"
                    }));
                }

                countyName = countResult.attributes["name"].ToUpper();
                Log.Info("County: {0}", countyName);
            }
            catch (Exception ex)
            {
                Log.LogException(LogLevel.Fatal, $"problem uploading pdf for {exitingViewModel}", ex);

                TempData["message"] = "Monument saved successfully but the county contact was not notfied.";

                return(RedirectToRoute("", new
                {
                    Controller = "Home",
                    Action = "Index"
                }));
            }

            //get the county contact for that submission
            CountyContact contact;
            using (connection = new SqlConnection(ConfigurationManager.ConnectionStrings["PLSS"].ConnectionString))
            {
                await connection.OpenAsync();

                contact = connection.Query <CountyContact>(
                    "Select FullName, Email from Lookup_CountyContacts where County = @countyName",
                    new
                {
                    countyName
                }).SingleOrDefault();

                if (contact == null)
                {
                    Log.Warn("problem finding a county contact for {0}", countyName);

                    TempData["message"] = "Monument saved successfully but the county contact was not notfied.";

                    return(RedirectToRoute("", new
                    {
                        Controller = "Home",
                        Action = "Index"
                    }));
                }
            }

            //send county contact an email with link to pdf or attachment
            var file = new FileInfo(actualPath);
            Log.Info("Sending county contact email to: {0}", contact.Email);
            CommandExecutor.ExecuteCommand(new NotifyCountyEmailCommand(
                                               new NotifyCountyEmailCommand.MailTemplate(new[] { contact.Email },
                                                                                         App.AdminEmails,
                                                                                         contact.FullName,
                                                                                         user.Name,
                                                                                         exitingViewModel.BlmPointId,
                                                                                         countyName,
                                                                                         pdfBytes,
                                                                                         file.Name)));


            TempData["message"] = "Monument saved successfully.";
            Log.Info("Monument was saved successfully");

            return(RedirectToRoute("", new
            {
                Controller = "Home",
                Action = "Index"
            }));
        }
Пример #20
0
        public void MinimizeToFile(string targetFile)
        {
            var targetSkydFile = ChromatogramCache.FinalPathForName(targetFile, null);
            using (var skydSaver = new FileSaver(targetSkydFile))
            using (var scansSaver = new FileSaver(targetSkydFile + ChromatogramCache.SCANS_EXT, true))
            using (var peaksSaver = new FileSaver(targetSkydFile + ChromatogramCache.PEAKS_EXT, true))
            using (var scoreSaver = new FileSaver(targetSkydFile + ChromatogramCache.SCORES_EXT, true))
            {
                skydSaver.Stream = File.OpenWrite(skydSaver.SafeName);
                using (var longWaitDlg = new LongWaitDlg(DocumentUIContainer))
                {
                    longWaitDlg.PerformWork(this, 1000,
                                            longWaitBroker =>
                                                {
                                                    longWaitBroker.Message = Resources.MinimizeResultsDlg_MinimizeToFile_Saving_new_cache_file;
                                                    try
                                                    {
                                                        using (var backgroundWorker =
                                                            new BackgroundWorker(this, longWaitBroker))
                                                        {
                                                            backgroundWorker.RunBackground(skydSaver.Stream,
                                                                scansSaver.FileStream, peaksSaver.FileStream, scoreSaver.FileStream);
                                                        }
                                                    }
                                                    catch (ObjectDisposedException)
                                                    {
                                                        if (!longWaitBroker.IsCanceled)
                                                        {
                                                            throw;
                                                        }
                                                    }
                                                });

                    if (longWaitDlg.IsCanceled)
                    {
                        return;
                    }
                }

                var skylineWindow = (SkylineWindow) DocumentUIContainer;
                if (!skylineWindow.SaveDocument(targetFile, false))
                {
                    return;
                }
                try
                {
                    var measuredResults = DocumentUIContainer.Document.Settings.MeasuredResults.CommitCacheFile(skydSaver);
                    SrmDocument docOrig, docNew;
                    do
                    {
                        docOrig = DocumentUIContainer.Document;
                        docNew = docOrig.ChangeMeasuredResults(measuredResults);
                    } while (!DocumentUIContainer.SetDocument(docNew, docOrig));
                }
                catch (Exception x)
                {
                    var message = TextUtil.LineSeparate(
                        string.Format(Resources.MinimizeResultsDlg_MinimizeToFile_An_unexpected_error_occurred_while_saving_the_data_cache_file__0__,
                                                targetFile),
                        x.Message);
                    MessageDlg.ShowWithException(this, message, x);
                    return;
                }
                skylineWindow.InvalidateChromatogramGraphs();
            }
            DialogResult = DialogResult.OK;
        }
Пример #21
0
        /// <summary>
        /// Saves the database to a new directory with only the ions used
        /// in a given document.
        /// </summary>
        /// <param name="pathDestDir">The directory to save to</param>
        /// <param name="document">The document for which ions are to be kept</param>
        /// <param name="smallMoleculeConversionMap">Used for changing charge,modifedSeq to adduct,molecule in small molecule conversion</param>
        /// <param name="loadedDatabase">Returns in-memory representation of the revised ion mobility table</param>
        /// <returns>The full path to the file saved</returns>
        public string PersistMinimized(string pathDestDir,
                                       SrmDocument document, IDictionary <LibKey, LibKey> smallMoleculeConversionMap, out IonMobilityDb loadedDatabase)
        {
            RequireUsable();

            var fname = Path.GetFileName(FilePath);

            if (smallMoleculeConversionMap != null && fname != null &&
                !fname.Contains(BiblioSpecLiteSpec.DotConvertedToSmallMolecules))
            {
                fname = fname.Replace(IonMobilityDb.EXT, BiblioSpecLiteSpec.DotConvertedToSmallMolecules + IonMobilityDb.EXT);
            }

            fname = fname ?? string.Empty; // Keeps ReSharper from complaining about possible null
            string persistPath = Path.Combine(pathDestDir, fname);

            using (var fs = new FileSaver(persistPath))
            {
                var libraryName          = fname.Replace(IonMobilityDb.EXT, String.Empty);
                var ionMobilityDbMinimal = IonMobilityDb.CreateIonMobilityDb(fs.SafeName, libraryName, true);

                // Calculate the minimal set of peptides needed for this document
                var dbPrecursors         = _database.DictLibrary.LibKeys;
                var persistIonMobilities = new List <PrecursorIonMobilities>();

                var dictPrecursors = dbPrecursors.ToDictionary(p => p.LibraryKey);
                foreach (var pair in document.MoleculePrecursorPairs)
                {
                    var test =
                        new PrecursorIonMobilities(pair.NodePep.ModifiedTarget, pair.NodeGroup.PrecursorAdduct, 0, 0, 0, eIonMobilityUnits.none);
                    var key = test.Precursor;
                    if (dictPrecursors.TryGetValue(key, out var dbPrecursor))
                    {
                        if (smallMoleculeConversionMap != null)
                        {
                            // We are in the midst of converting a document to small molecules for test purposes
                            LibKey smallMolInfo;
                            if (smallMoleculeConversionMap.TryGetValue(new LibKey(pair.NodePep.ModifiedSequence, pair.NodeGroup.PrecursorCharge), out smallMolInfo))
                            {
                                var precursorAdduct         = smallMolInfo.Adduct;
                                var smallMoleculeAttributes = smallMolInfo.SmallMoleculeLibraryAttributes;
                                dbPrecursor = new LibKey(smallMoleculeAttributes, precursorAdduct);
                            }
                            else
                            {
                                // Not being converted
                                Assume.IsTrue(pair.NodeGroup.Peptide.IsDecoy);
                                continue;
                            }
                        }
                        persistIonMobilities.Add(new PrecursorIonMobilities(dbPrecursor, test.IonMobilities));
                        // Only add once
                        dictPrecursors.Remove(key);
                    }
                }

                loadedDatabase = ionMobilityDbMinimal.UpdateIonMobilities(persistIonMobilities);
                fs.Commit();
            }

            return(persistPath);
        }
Пример #22
0
        public void MinimizeToFile(string targetFile)
        {
            var targetSkydFile = ChromatogramCache.FinalPathForName(targetFile, null);

            using (var skydSaver = new FileSaver(targetSkydFile))
                using (var scansSaver = new FileSaver(targetSkydFile + ChromatogramCache.SCANS_EXT, true))
                    using (var peaksSaver = new FileSaver(targetSkydFile + ChromatogramCache.PEAKS_EXT, true))
                        using (var scoreSaver = new FileSaver(targetSkydFile + ChromatogramCache.SCORES_EXT, true))
                        {
                            skydSaver.Stream = File.OpenWrite(skydSaver.SafeName);
                            using (var longWaitDlg = new LongWaitDlg(DocumentUIContainer))
                            {
                                longWaitDlg.PerformWork(this, 1000,
                                                        longWaitBroker =>
                                {
                                    longWaitBroker.Message = Resources.MinimizeResultsDlg_MinimizeToFile_Saving_new_cache_file;
                                    try
                                    {
                                        using (var backgroundWorker =
                                                   new BackgroundWorker(this, longWaitBroker))
                                        {
                                            backgroundWorker.RunBackground(skydSaver.Stream,
                                                                           scansSaver.FileStream, peaksSaver.FileStream, scoreSaver.FileStream);
                                        }
                                    }
                                    catch (ObjectDisposedException)
                                    {
                                        if (!longWaitBroker.IsCanceled)
                                        {
                                            throw;
                                        }
                                    }
                                });

                                if (longWaitDlg.IsCanceled)
                                {
                                    return;
                                }
                            }

                            var skylineWindow = (SkylineWindow)DocumentUIContainer;
                            if (!skylineWindow.SaveDocument(targetFile, false))
                            {
                                return;
                            }
                            try
                            {
                                var         measuredResults = DocumentUIContainer.Document.Settings.MeasuredResults.CommitCacheFile(skydSaver);
                                SrmDocument docOrig, docNew;
                                do
                                {
                                    docOrig = DocumentUIContainer.Document;
                                    docNew  = docOrig.ChangeMeasuredResults(measuredResults);
                                } while (!DocumentUIContainer.SetDocument(docNew, docOrig));
                            }
                            catch (Exception x)
                            {
                                var message = TextUtil.LineSeparate(
                                    string.Format(Resources.MinimizeResultsDlg_MinimizeToFile_An_unexpected_error_occurred_while_saving_the_data_cache_file__0__,
                                                  targetFile),
                                    x.Message);
                                MessageDlg.ShowWithException(this, message, x);
                                return;
                            }
                            skylineWindow.InvalidateChromatogramGraphs();
                        }
            DialogResult = DialogResult.OK;
        }
Пример #23
0
        /// <summary>
        /// Saves the database to a new directory with only the optimizations used
        /// in a given document.
        /// </summary>
        /// <param name="pathDestDir">The directory to save to</param>
        /// <param name="document">The document for which peptides are to be kept</param>
        /// <returns>The full path to the file saved</returns>
        public string PersistMinimized(string pathDestDir, SrmDocument document)
        {
            RequireUsable();

            string persistPath = Path.Combine(pathDestDir, Path.GetFileName(PersistencePath) ?? string.Empty);  // ReSharper
            using (var fs = new FileSaver(persistPath))
            {
                var optDbMinimal = OptimizationDb.CreateOptimizationDb(fs.SafeName);

                // Calculate the minimal set of optimizations needed for this document
                var persistOptimizations = new List<DbOptimization>();
                var dictOptimizations = _database.GetOptimizations().ToDictionary(opt => opt.Key);
                foreach (PeptideGroupDocNode seq in document.MoleculeGroups)
                {
                    // Skip peptide groups with no transitions
                    if (seq.TransitionCount == 0)
                        continue;
                    foreach (PeptideDocNode peptide in seq.Children)
                    {
                        foreach (TransitionGroupDocNode group in peptide.Children)
                        {
                            string modSeq = document.Settings.GetSourceTextId(peptide);
                            int charge = group.PrecursorCharge;
                            foreach (TransitionDocNode transition in group.Children)
                            {
                                foreach (var optType in Enum.GetValues(typeof(OptimizationType)).Cast<OptimizationType>())
                                {
                                    var optimizationKey = new OptimizationKey(optType, modSeq, charge, transition.FragmentIonName, transition.Transition.Charge);
                                    DbOptimization dbOptimization;
                                    if (dictOptimizations.TryGetValue(optimizationKey, out dbOptimization))
                                    {
                                        persistOptimizations.Add(new DbOptimization(dbOptimization.Key, dbOptimization.Value));
                                        // Only add once
                                        dictOptimizations.Remove(optimizationKey);
                                    }
                                }
                            }
                        }
                    }
                }

                optDbMinimal.UpdateOptimizations(persistOptimizations, new DbOptimization[0]);
                fs.Commit();
            }

            return persistPath;
        }
 private static void SaveChrom(SrmDocument docResults,
     string fileToSave,
     IList<string> fileNames,
     CultureInfo cultureInfo,
     IList<ChromExtractor> extractors,
     IList<ChromSource> sources)
 {
     var chromExporter = new ChromatogramExporter(docResults);
     using (var saver = new FileSaver(fileToSave))
     using (var writer = new StreamWriter(saver.SafeName))
     {
         chromExporter.Export(writer, null, fileNames, cultureInfo, extractors, sources);
         writer.Flush();
         writer.Close();
         saver.Commit();
     }
 }
Пример #25
0
        public static OptimizationDb ConvertFromOldFormat(string path, IProgressMonitor loadMonitor, ProgressStatus status, SrmDocument document)
        {
            // Try to open assuming old format (Id, PeptideModSeq, Charge, Mz, Value, Type)
            var precursors = new Dictionary<string, HashSet<int>>(); // PeptideModSeq -> charges
            var optimizations = new List<Tuple<DbOptimization, double>>(); // DbOptimization, product m/z
            int maxCharge = 1;
            using (SQLiteConnection connection = new SQLiteConnection("Data Source = " + path)) // Not L10N
            using (SQLiteCommand command = new SQLiteCommand(connection))
            {
                connection.Open();
                command.CommandText = "SELECT PeptideModSeq, Charge, Mz, Value, Type FROM OptimizationLibrary"; // Not L10N
                using (SQLiteDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var type = (OptimizationType)reader["Type"]; // Not L10N
                        var modifiedSequence = reader["PeptideModSeq"].ToString(); // Not L10N
                        var charge = (int)reader["Charge"]; // Not L10N
                        var productMz = (double)reader["Mz"]; // Not L10N
                        var value = (double)reader["Value"]; // Not L10N
                        optimizations.Add(new Tuple<DbOptimization, double>(new DbOptimization(type, modifiedSequence, charge, string.Empty, -1, value), productMz));

                        if (!precursors.ContainsKey(modifiedSequence))
                        {
                            precursors[modifiedSequence] = new HashSet<int>();
                        }
                        precursors[modifiedSequence].Add(charge);
                        if (charge > maxCharge)
                        {
                            maxCharge = charge;
                        }
                    }
                }
            }

            var peptideList = (from precursor in precursors
                               from charge in precursor.Value
                               select string.Format("{0}{1}", precursor.Key, Transition.GetChargeIndicator(charge)) // Not L10N
                               ).ToList();

            var newDoc = new SrmDocument(document != null ? document.Settings : SrmSettingsList.GetDefault());
            newDoc = newDoc.ChangeSettings(newDoc.Settings
                .ChangePeptideLibraries(libs => libs.ChangePick(PeptidePick.filter))
                .ChangeTransitionFilter(filter =>
                    filter.ChangeFragmentRangeFirstName("ion 1") // Not L10N
                          .ChangeFragmentRangeLastName("last ion") // Not L10N
                          .ChangeProductCharges(Enumerable.Range(1, maxCharge).ToList())
                          .ChangeIonTypes(new []{ IonType.y, IonType.b }))
                .ChangeTransitionLibraries(libs => libs.ChangePick(TransitionLibraryPick.none))
                );
            var matcher = new ModificationMatcher { FormatProvider = NumberFormatInfo.InvariantInfo };
            matcher.CreateMatches(newDoc.Settings, peptideList, Settings.Default.StaticModList, Settings.Default.HeavyModList);
            FastaImporter importer = new FastaImporter(newDoc, matcher);
            string text = string.Format(">>{0}\r\n{1}", newDoc.GetPeptideGroupId(true), TextUtil.LineSeparate(peptideList)); // Not L10N
            PeptideGroupDocNode imported = importer.Import(new StringReader(text), null, Helpers.CountLinesInString(text)).First();

            int optimizationsUpdated = 0;
            foreach (PeptideDocNode nodePep in imported.Children)
            {
                string sequence = newDoc.Settings.GetSourceTextId(nodePep);
                foreach (var nodeGroup in nodePep.TransitionGroups)
                {
                    int charge = nodeGroup.PrecursorCharge;
                    foreach (var nodeTran in nodeGroup.Transitions)
                    {
                        double productMz = nodeTran.Mz;
                        foreach (var optimization in optimizations.Where(opt =>
                            string.IsNullOrEmpty(opt.Item1.FragmentIon) &&
                            opt.Item1.ProductCharge == -1 &&
                            opt.Item1.PeptideModSeq == sequence &&
                            opt.Item1.Charge == charge &&
                            Math.Abs(opt.Item2 - productMz) < 0.00001))
                        {
                            optimization.Item1.FragmentIon = nodeTran.FragmentIonName;
                            optimization.Item1.ProductCharge = nodeTran.Transition.Charge;
                            ++optimizationsUpdated;
                        }
                    }
                }
            }

            if (optimizations.Count > optimizationsUpdated)
            {
                throw new OptimizationsOpeningException(string.Format(Resources.OptimizationDb_ConvertFromOldFormat_Failed_to_convert__0__optimizations_to_new_format_,
                                                                      optimizations.Count - optimizationsUpdated));
            }

            using (var fs = new FileSaver(path))
            {
                OptimizationDb db = CreateOptimizationDb(fs.SafeName);
                db.UpdateOptimizations(optimizations.Select(opt => opt.Item1).ToArray(), new DbOptimization[0]);
                fs.Commit();

                if (loadMonitor != null)
                    loadMonitor.UpdateProgress(status.ChangePercentComplete(100));
                return GetOptimizationDb(fs.RealName, null, null);
            }
        }
Пример #26
0
        /// <summary>
        /// Post a report to a website, without exception handling.  
        /// </summary>        
        /// <param name="link">Web URL to post report to</param>
        /// <param name="postData">Report text</param>
        public static void PostToLink(string link, string postData)
        {
            string filePath = Path.GetTempFileName() + ".html"; // Not L10N

            string javaScript = string.Format(

            @"<script type=""text/javascript"">
            function submitForm()
            {{
            document.getElementById(""my_form"").submit();
            }}
            window.onload = submitForm;
            </script>
            <form id=""my_form"" action=""{0}"" method=""post"" style=""visibility: hidden;"">
            <textarea name=""SkylineReport"">{1}</textarea>
            </form>", // Not L10N

                link, WebUtility.HtmlEncode(postData));

            try
            {
                using (var saver = new FileSaver(filePath))
                {
                    using (var writer = new StreamWriter(saver.SafeName))
                    {
                        writer.Write(javaScript);
                        writer.Flush();
                        writer.Close();
                    }

                    saver.Commit();
                }
            }
            catch (Exception)
            {
                throw new IOException(Resources.WebHelpers_PostToLink_Failure_saving_temporary_post_data_to_disk_);
            }

            try
            {
                // CONSIDER: User could have a configuration that opens html documents
                //           with a text editor. This would defeat the redirection and post.
                Process.Start(filePath);
            }
            catch(Exception)
            {
                throw new WebToolException(Resources.Could_not_open_web_Browser_to_show_link_, link);
            }

            DeleteTempHelper d = new DeleteTempHelper(filePath);
            Thread t = new Thread(d.DeletePath);
            t.Start();
        }
Пример #27
0
        /// <summary>
        /// Test only method for creating a <see cref="XHunterLibrary"/> file
        /// from another loaded <see cref="Library"/>.  Should this move into test project?
        /// </summary>
        /// <param name="streamManager">Provides access to the file system</param>
        /// <param name="path">Path to write to</param>
        /// <param name="library">The loaded library to use as a data source</param>
        /// <param name="lowIntensity">True to use 20 lowest intensity peaks for bad spectrum</param>
        public static void Write(IStreamManager streamManager, string path, Library library, bool lowIntensity)
        {
            using (FileSaver fs = new FileSaver(path, streamManager))
                using (Stream outStream = streamManager.CreateStream(fs.SafeName, FileMode.Create, true))
                {
                    outStream.Write(BitConverter.GetBytes(0), 0, sizeof(int));
                    outStream.Write(BitConverter.GetBytes(library.SpectrumCount), 0, sizeof(int));

                    byte[]       header     = new byte[256 - 8];
                    const string headerText = @"HLF v=2 s=test.hlf d=2009.02.04"; // Not L10N
                    Encoding.UTF8.GetBytes(headerText, 0, headerText.Length, header, 0);

                    outStream.Write(header, 0, header.Length);

                    SequenceMassCalc calc = new SequenceMassCalc(MassType.Monoisotopic);

                    byte[] seqBuffer = new byte[1024];

                    foreach (var key in library.Keys)
                    {
                        SpectrumPeaksInfo peaksInfo;
                        if (!library.TryLoadSpectrum(key, out peaksInfo))
                        {
                            continue;
                        }

                        // Fake X! Hunter filtering by choosing just the to 20 peaks
                        SpectrumPeaksInfo.MI[] peaks = peaksInfo.Peaks.ToArray();
                        // Sort by intensity
                        if (lowIntensity)
                        {
                            Array.Sort(peaks, (p1, p2) => Comparer.Default.Compare(p1.Intensity, p2.Intensity)); // ascending
                        }
                        else
                        {
                            Array.Sort(peaks, (p1, p2) => Comparer.Default.Compare(p2.Intensity, p1.Intensity)); // descending
                        }
                        float maxI = peaks.Length == 0 ? 0 : peaks[0].Intensity;
                        // Take 20 most intense peaks
                        SpectrumPeaksInfo.MI[] peaksFiltered = new SpectrumPeaksInfo.MI[Math.Min(20, peaks.Length)];
                        Array.Copy(peaks, peaksFiltered, peaksFiltered.Length);
                        // Resort by m/z (ineffient, but this is test code)
                        Array.Sort(peaksFiltered, (p1, p2) => Comparer.Default.Compare(p1.Mz, p2.Mz));

                        double totalI    = 0;
                        byte[] peakBytes = new byte[(sizeof(byte) + sizeof(float)) * peaksFiltered.Length];
                        for (int i = 0; i < peaksFiltered.Length; i++)
                        {
                            var mi = peaksFiltered[i];

                            // Calculate the X! Hunter processed intensity value
                            float intensity = 100f * mi.Intensity / maxI;
                            totalI += intensity;

                            // Fill the peaks buffer
                            peakBytes[i] = (byte)(int)intensity;
                            Array.Copy(BitConverter.GetBytes((float)mi.Mz), 0, peakBytes, peaksFiltered.Length + i * 4, sizeof(float));
                        }

                        string sequence = key.Sequence;
                        // Only works for unmodified sequence
                        Debug.Assert(!key.IsModified);
                        double precursorMH = calc.GetPrecursorMass(sequence);
                        outStream.Write(BitConverter.GetBytes(precursorMH), 0, sizeof(double));
                        outStream.Write(BitConverter.GetBytes(key.Charge), 0, sizeof(int));
                        // Value rounded for consistent serialization round-tripping
                        float i2 = (float)Math.Round(Math.Sqrt(totalI), 4);
                        outStream.Write(BitConverter.GetBytes(i2), 0, sizeof(float));
                        outStream.Write(BitConverter.GetBytes(0.0001f), 0, sizeof(float));
                        outStream.Write(BitConverter.GetBytes(sequence.Length), 0, sizeof(int));

                        // Sequence
                        Encoding.UTF8.GetBytes(sequence, 0, sequence.Length, seqBuffer, 0);
                        outStream.Write(seqBuffer, 0, sequence.Length);

                        // Peaks
                        outStream.Write(BitConverter.GetBytes(peaksFiltered.Length), 0, sizeof(int));
                        outStream.Write(peakBytes, 0, peakBytes.Length);

                        // Modifications
                        outStream.Write(BitConverter.GetBytes(0), 0, sizeof(int));
                        // Homologs
                        outStream.Write(BitConverter.GetBytes(0), 0, sizeof(int));
                    }

                    streamManager.Finish(outStream);
                    fs.Commit();
                }
        }
Пример #28
0
 private void btnExport_Click(object sender, EventArgs e)
 {
     string strReferenceFile = (string) comboBoxReferenceFile.SelectedItem;
     string strSaveFileName = string.Empty;
     if (!string.IsNullOrEmpty(_documentFilePath))
     {
         strSaveFileName = Path.GetFileNameWithoutExtension(_documentFilePath);
     }
     if (!string.IsNullOrEmpty(strReferenceFile))
     {
         strSaveFileName += Path.GetFileNameWithoutExtension(strReferenceFile);
     }
     strSaveFileName += ".ChorusRequest.xml"; // Not L10N
     strSaveFileName = strSaveFileName.Replace(' ', '_');
     using (var saveFileDialog = new SaveFileDialog { FileName = strSaveFileName})
     {
         if (saveFileDialog.ShowDialog(this) != DialogResult.OK || string.IsNullOrEmpty(saveFileDialog.FileName))
         {
             return;
         }
         SpectrumFilter spectrumFilterData = new SpectrumFilter(Document, MsDataFileUri.Parse(strReferenceFile), null);
         using (var saver = new FileSaver(saveFileDialog.FileName))
         {
             if (!saver.CanSave(this))
             {
                 return;
             }
             using (var stream = new StreamWriter(saver.SafeName))
             {
                 var xmlSerializer = new XmlSerializer(typeof(Model.Results.RemoteApi.GeneratedCode.ChromatogramRequestDocument));
                 xmlSerializer.Serialize(stream, spectrumFilterData.ToChromatogramRequestDocument());
             }
             saver.Commit();
         }
     }
     Close();
 }
Пример #29
0
        protected override void DoTest()
        {
            string outDir       = Path.Combine(TestContext.TestDir, "PerfPeakTest");
            string resultsTable = Path.Combine(outDir, "results.txt");

            Directory.CreateDirectory(outDir); // In case it doesn't already exists
            File.Delete(resultsTable);         // In case it does already exist
            var none      = new string[0];
            var openSwath = new List <string> {
                "OpenSwath.csv"
            };
            var spectronaut = new List <string> {
                "Spectronaut.csv"
            };
            var peakView = new List <string> {
                "PeakView.txt"
            };
            var peakViewSpectronaut          = spectronaut.Concat(peakView).ToList();
            var peakViewOpenSwath            = openSwath.Concat(peakView).ToList();
            var peakViewSpectronautOpenSwath = peakViewSpectronaut.Concat(openSwath).ToList();
            var decoysAndSecond = MODEL_NAMES;
            var secondOnly      = MODEL_NAMES.Take(3).ToList();

            int i = 0;

            using (var fs = new FileSaver(resultsTable))
                using (var resultsWriter = new StreamWriter(fs.SafeName))
                {
                    WriteHeader(resultsWriter);
                    // Overlap 10 mz
                    AnalyzeDirectory(i++, none, outDir, decoysAndSecond, resultsWriter);
                    // Overlap 20 mz
                    AnalyzeDirectory(i++, none, outDir, decoysAndSecond, resultsWriter);
                    // Schilling Ack
                    AnalyzeDirectory(i++, peakView, outDir, decoysAndSecond, resultsWriter, new List <int> {
                        1
                    });
                    // Schilling Mito
                    AnalyzeDirectory(i++, peakView, outDir, decoysAndSecond, resultsWriter, new List <int> {
                        1
                    });
                    // Reiter sPRG
                    AnalyzeDirectory(i++, spectronaut, outDir, decoysAndSecond, resultsWriter, new List <int> {
                        0
                    });
                    // Ludwig sPRG
                    AnalyzeDirectory(i++, none, outDir, decoysAndSecond, resultsWriter, new List <int> {
                        1
                    });
                    // Hasmik Swath Heavy only
                    AnalyzeDirectory(i++, peakViewSpectronautOpenSwath, outDir, decoysAndSecond, resultsWriter, new List <int> {
                        1, 1, 1
                    });
                    // Hasmik Qe Heavy only
                    AnalyzeDirectory(i++, spectronaut, outDir, decoysAndSecond, resultsWriter, new List <int> {
                        1
                    });
                    // Hasmik SWATH
                    AnalyzeDirectory(i++, peakViewSpectronautOpenSwath, outDir, decoysAndSecond, resultsWriter, new List <int> {
                        1, 1, 1
                    });
                    // Hasmik QE
                    AnalyzeDirectory(i++, spectronaut, outDir, decoysAndSecond, resultsWriter, new List <int> {
                        1
                    });
                    // Hasmik Swath Light only
                    AnalyzeDirectory(i++, peakViewSpectronaut, outDir, decoysAndSecond, resultsWriter, new List <int> {
                        0, 1
                    });
                    // Hasmik Qe Light only
                    AnalyzeDirectory(i++, spectronaut, outDir, decoysAndSecond, resultsWriter, new List <int> {
                        1
                    });
                    // OpenSwath_Water
                    AnalyzeDirectory(i++, peakViewOpenSwath, outDir, decoysAndSecond, resultsWriter, new List <int> {
                        2, 1
                    });
                    // OpenSwath_Yeast
                    AnalyzeDirectory(i++, peakViewOpenSwath, outDir, decoysAndSecond, resultsWriter, new List <int> {
                        1, 1
                    });
                    // OpenSwath_Human
                    AnalyzeDirectory(i++, peakViewOpenSwath, outDir, decoysAndSecond, resultsWriter, new List <int> {
                        2, 1
                    });
                    // Olga SRM Course vantage
                    AnalyzeDirectory(i++, none, outDir, decoysAndSecond, resultsWriter);
                    // Olga SRM Course
                    AnalyzeDirectory(i++, none, outDir, decoysAndSecond, resultsWriter);
                    // Heart Failure
                    AnalyzeDirectory(i++, none, outDir, secondOnly, resultsWriter);
                    // Ovarian cancer
                    AnalyzeDirectory(i++, none, outDir, secondOnly, resultsWriter);
                    // mProphet Gold
                    AnalyzeDirectory(i++, none, outDir, decoysAndSecond, resultsWriter);
                    // MikeB high (DDA dilution top 12 runs)
                    AnalyzeDirectory(i++, none, outDir, secondOnly, resultsWriter);
                    // Schilling DDA (DDA dilution 15 runs)
                    AnalyzeDirectory(i++, none, outDir, secondOnly, resultsWriter);
                    // Held DIA
                    AnalyzeDirectory(i++, peakView, outDir, decoysAndSecond, resultsWriter, new List <int> {
                        4
                    });
                    resultsWriter.Close();
                    fs.Commit();
                }
        }
Пример #30
0
        private bool ValidateBuilder(bool validateInputFiles)
        {
            string name;
            if (!_helper.ValidateNameTextBox(textName, out name))
                return false;

            string outputPath = textPath.Text;
            if (string.IsNullOrEmpty(outputPath))
            {
                _helper.ShowTextBoxError(textPath, Resources.BuildLibraryDlg_ValidateBuilder_You_must_specify_an_output_file_path, outputPath);
                return false;
            }
            if (Directory.Exists(outputPath))
            {
                _helper.ShowTextBoxError(textPath, Resources.BuildLibraryDlg_ValidateBuilder_The_output_path__0__is_a_directory_You_must_specify_a_file_path, outputPath);
                return false;
            }
            string outputDir = Path.GetDirectoryName(outputPath);
            if (string.IsNullOrEmpty(outputDir) || !Directory.Exists(outputDir))
            {
                _helper.ShowTextBoxError(textPath, Resources.BuildLibraryDlg_ValidateBuilder_The_directory__0__does_not_exist, outputDir);
                return false;
            }
            if (!outputPath.EndsWith(BiblioSpecLiteSpec.EXT))
                outputPath += BiblioSpecLiteSpec.EXT;
            try
            {
                using (var sfLib = new FileSaver(outputPath))
                {
                    if (!sfLib.CanSave(this))
                    {
                        textPath.Focus();
                        textPath.SelectAll();
                        return false;
                    }
                }
            }
            catch (UnauthorizedAccessException)
            {
                _helper.ShowTextBoxError(textPath, TextUtil.LineSeparate(Resources.BuildLibraryDlg_ValidateBuilder_Access_violation_attempting_to_write_to__0__,
                                                                         Resources.BuildLibraryDlg_ValidateBuilder_Please_check_that_you_have_write_access_to_this_folder_), outputDir);
                return false;
            }
            catch (IOException)
            {
                _helper.ShowTextBoxError(textPath, TextUtil.LineSeparate(Resources.BuildLibraryDlg_ValidateBuilder_Failure_attempting_to_create_a_file_in__0__,
                                                                         Resources.BuildLibraryDlg_ValidateBuilder_Please_check_that_you_have_write_access_to_this_folder_), outputDir);
                return false;
            }

            double cutOffScore;
            if (!_helper.ValidateDecimalTextBox(textCutoff, 0, 1.0, out cutOffScore))
                return false;
            Settings.Default.LibraryResultCutOff = cutOffScore;

            var libraryBuildAction = LibraryBuildAction;
            string authority = null;
            string id = null;
            if (libraryBuildAction == LibraryBuildAction.Create)
            {
                authority = LibraryAuthority;
                if (Uri.CheckHostName(authority) != UriHostNameType.Dns)
                {
                    _helper.ShowTextBoxError(textAuthority, Resources.BuildLibraryDlg_ValidateBuilder_The_lab_authority_name__0__is_not_valid_This_should_look_like_an_internet_server_address_e_g_mylab_myu_edu_and_be_unlikely_to_be_used_by_any_other_lab_but_need_not_refer_to_an_actual_server,
                                             authority);
                    return false;
                }
                Settings.Default.LibraryAuthority = authority;

                id = textID.Text;
                if (!Regex.IsMatch(id, @"\w[0-9A-Za-z_\-]*")) // Not L10N: Easier to keep IDs restricted to these values.
                {
                    _helper.ShowTextBoxError(textID, Resources.BuildLibraryDlg_ValidateBuilder_The_library_identifier__0__is_not_valid_Identifiers_start_with_a_letter_number_or_underscore_and_contain_only_letters_numbers_underscores_and_dashes, id);
                    return false;
                }
            }

            if (validateInputFiles)
            {
                var inputFilesChosen = new List<string>();
                foreach (int i in listInputFiles.CheckedIndices)
                {
                    inputFilesChosen.Add(_inputFileNames[i]);
                }

                List<string> targetPeptidesChosen = null;
                if (cbFilter.Checked)
                {
                    targetPeptidesChosen = new List<string>();
                    var doc = _documentUiContainer.Document;
                    foreach (PeptideDocNode nodePep in doc.Peptides)
                    {
                        // Add light modified sequences
                        targetPeptidesChosen.Add(nodePep.ModifiedSequence);
                        // Add heavy modified sequences
                        foreach (var nodeGroup in nodePep.TransitionGroups)
                        {
                            if (nodeGroup.TransitionGroup.LabelType.IsLight)
                                continue;
                            targetPeptidesChosen.Add(doc.Settings.GetModifiedSequence(nodePep.Peptide.Sequence,
                                                                                      nodeGroup.TransitionGroup.LabelType,
                                                                                      nodePep.ExplicitMods));
                        }
                    }
                }

                _builder = new BiblioSpecLiteBuilder(name, outputPath, inputFilesChosen, targetPeptidesChosen)
                              {
                                  Action = libraryBuildAction,
                                  IncludeAmbiguousMatches = cbIncludeAmbiguousMatches.Checked,
                                  KeepRedundant = LibraryKeepRedundant,
                                  CutOffScore = cutOffScore,
                                  Authority = authority,
                                  Id = id
                              };
            }
            return true;
        }
        private void ImageBox_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                var imageBox = (PictureBox)sender;
                var fileInfo = new FileInfo(imageBox.ImageLocation);
                if (!fileInfo.Exists) return;

                var saver = new FileSaver();
                saver.Save(imageBox.ImageLocation, InitialDirectory);
            }
        }
Пример #32
0
 private void CopyFile(string source, FileSaver destSaver)
 {
     // Copy the specified file to the new name using a FileSaver
     destSaver.CheckException();
     File.Copy(source, destSaver.SafeName, true);
 }
        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);
                }
            }
        }
Пример #34
0
        private void SaveDocumentLibraryAs(string newDocFilePath)
        {
            string oldDocLibFile = BiblioSpecLiteSpec.GetLibraryFileName(DocumentFilePath);
            string oldRedundantDocLibFile = BiblioSpecLiteSpec.GetRedundantName(oldDocLibFile);
            // If the document has a document-specific library, and the files for it
            // exist on disk
            var document = Document;
            if (document.Settings.PeptideSettings.Libraries.HasDocumentLibrary
                && File.Exists(oldDocLibFile))
            {
                string newDocLibFile = BiblioSpecLiteSpec.GetLibraryFileName(newDocFilePath);
                using (var saverLib = new FileSaver(newDocLibFile))
                {
                    FileSaver saverRedundant = null;
                    if (File.Exists(oldRedundantDocLibFile))
                    {
                        string newRedundantDocLibFile = BiblioSpecLiteSpec.GetRedundantName(newDocFilePath);
                        saverRedundant = new FileSaver(newRedundantDocLibFile);
                    }
                    using (saverRedundant)
                    {
                        CopyFile(oldDocLibFile, saverLib);
                        if (saverRedundant != null)
                        {
                            CopyFile(oldRedundantDocLibFile, saverRedundant);
                        }
                        saverLib.Commit();
                        if (saverRedundant != null)
                        {
                            saverRedundant.Commit();
                        }
                    }
                }

                // Update the document library settings to point to the new library.
                SrmDocument docOriginal, docNew;
                do
                {
                    docOriginal = Document;
                    docNew = docOriginal.ChangeSettingsNoDiff(docOriginal.Settings.ChangePeptideLibraries(libraries =>
                        libraries.ChangeDocumentLibraryPath(newDocFilePath)));
                }
                while (!SetDocument(docNew, docOriginal));
            }
        }
Пример #35
0
        public async Task <ActionResult> New(CornerViewModel cornerViewModel)
        {
            #region validate input

            if (!ModelState.IsValid)
            {
                TempData["error"] = ModelState.ToErrors();

                return(RedirectToRoute("", new
                {
                    Controller = "Home",
                    Action = "Index"
                }));
            }

            #endregion

            if (Request.Form["submitType"] == "preview")
            {
                Log.Info("Showing preview for {0}", cornerViewModel.BlmPointId);

                return(await Preview(cornerViewModel));
            }

            var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["PLSS"].ConnectionString);
            try
            {
                await connection.OpenAsync();

                var user = CommandExecutor.ExecuteCommand(new GetUserCommand(connection, User.Identity.Name));

                if (user == null)
                {
                    Log.Info("Could not find user {0} redirecting to home.", User.Identity.Name);

                    TempData["error"] = "You must log in to submit a corner";

                    return(RedirectToRoute("", new
                    {
                        Controller = "Home",
                        Action = "Index"
                    }));
                }

                Log.Info("Submitting tiesheet for {0}", user.Name);

                cornerViewModel.User = user;

                var corner = new Corner(cornerViewModel);

                var grid       = new Grid(cornerViewModel.Grid);
                var coordinate = new Coordinate(cornerViewModel.Coordinate);
                var formInfo   = new FormInfo(user.Name, corner.BlmPointId);
                var photos     = new Photo(cornerViewModel);

                corner.CoordinateId = coordinate.CoordinateId;
                corner.GridId       = grid.GridId;
                corner.FormInfoId   = formInfo.FormInfoId;
                corner.PhotoId      = photos.PhotoId;

                var gInserts = connection.Execute(Grid.InsertString, grid);
                Debug.Assert(gInserts == 1, "inserted into grid successfully");
                var cInserts = connection.Execute(Coordinate.InsertString, coordinate);
                Debug.Assert(cInserts == 1, "inserted into coords successfully");
                var fInserts = connection.Execute(FormInfo.InsertString, formInfo);
                Debug.Assert(fInserts == 1, "inserted into form successfully");
                var pInserts = connection.Execute(Photo.InsertString, photos);
                Debug.Assert(pInserts == 1, "inserted into photo successfully");
                var cornInserts = connection.Execute(Corner.InsertString, corner);
                Debug.Assert(cornInserts == 1, "inserted into corners successfully");

                var model      = new TieSheetPdfModel(cornerViewModel, corner, photos);
                var pdfService = new PlssPdfService("Assets\\pdf");
                var pdf        = pdfService.HydratePdfForm("MonumentStatusTemplate.pdf", model);
#if DEBUG
                pdf.FlattenFormFields();
#endif
                Log.Info("finished created database models");

                var actualPath = Path.Combine(Config.Global.Get <string>("SharePath"), formInfo.Path);
                Log.Info($"Writing PDF to: {actualPath}");
                var success = FileSaver.SaveFile(actualPath, pdf.GetPDFAsByteArray());

                if (!success)
                {
                    Log.Fatal($"problem saving pdf for {cornerViewModel}");

                    //do nothing, email will get sent about issue and we'll rebuild pdf form later.
                    Log.Info("Sending failed notification email to {0}", string.Join(", ", App.AdminEmails));

                    CommandExecutor.ExecuteCommand(new UserSubmitionFailedEmailCommand(
                                                       new UserSubmitionFailedEmailCommand.MailTemplate(App.AdminEmails,
                                                                                                        new[]
                    {
                        user.
                        UserName
                    },
                                                                                                        user.Name,
                                                                                                        model.BlmPointId,
                                                                                                        model.
                                                                                                        CollectionDate)));
                }
                else
                {
                    CommandExecutor.ExecuteCommand(new UserSubmittedEmailCommand(
                                                       new UserSubmittedEmailCommand.MailTemplate(App.AdminEmails,
                                                                                                  new[] { user.UserName },
                                                                                                  user.Name,
                                                                                                  model.BlmPointId,
                                                                                                  model.CollectionDate,
                                                                                                  actualPath)));
                }

                Log.Info("updating forminfoes table path: {0}", actualPath, success);

                var cUpdate = connection.Execute(
                    "update FormInfoes set " +
                    "path = @actualpath, " +
                    "uploadedSuccessfully = @success " +
                    "where forminfoid = @FormInfoId", new
                {
                    actualPath,
                    formInfo.FormInfoId,
                    success
                });
                Debug.Assert(cUpdate == 1, "updated form infos correctly");
            }
            catch (Exception ex)
            {
                Log.LogException(LogLevel.Fatal, $"problem saving new corner for {cornerViewModel}", ex);

                TempData["error"] = ex.Message;

                return(RedirectToRoute("", new
                {
                    Controller = "Home",
                    Action = "Index"
                }));
            }
            finally
            {
                connection.Close();
                connection.Dispose();
            }

            return(RedirectToRoute("", new
            {
                Controller = "Home",
                Action = "Index"
            }));
        }
Пример #36
0
 private void SaveLayout(string fileName)
 {
     using (var saverUser = new FileSaver(GetViewFile(fileName)))
     {
         if (saverUser.CanSave())
         {
             dockPanel.SaveAsXml(saverUser.SafeName);
             saverUser.Commit();
         }
     }
 }
Пример #37
0
        private bool ExportReport(string fileName, char separator)
        {
            try
            {
                using (var saver = new FileSaver(fileName))
                {
                    if (!saver.CanSave(this))
                        return false;

                    using (var writer = new StreamWriter(saver.SafeName))
                    {
                        Report report = GetReport();
                        bool success = false;

                        using (var longWait = new LongWaitDlg { Text = Resources.ExportReportDlg_ExportReport_Generating_Report })
                        {
                            longWait.PerformWork(this, 1500, broker =>
                            {
                                var status = new ProgressStatus(Resources.ExportReportDlg_GetDatabase_Analyzing_document);
                                broker.UpdateProgress(status);
                                Database database = EnsureDatabase(broker, 80, ref status);
                                if (broker.IsCanceled)
                                    return;
                                broker.UpdateProgress(status = status.ChangeMessage(Resources.ExportReportDlg_ExportReport_Building_report));
                                ResultSet resultSet = report.Execute(database);
                                if (broker.IsCanceled)
                                    return;
                                broker.UpdateProgress(status = status.ChangePercentComplete(95)
                                    .ChangeMessage(Resources.ExportReportDlg_ExportReport_Writing_report));

                                ResultSet.WriteReportHelper(resultSet, separator, writer, CultureInfo);

                                writer.Flush();
                                writer.Close();

                                if (broker.IsCanceled)
                                    return;
                                broker.UpdateProgress(status.Complete());

                                saver.Commit();
                                success = true;
                            });
                        }

                        return success;
                    }
                }
            }
            catch (Exception x)
            {
                MessageDlg.ShowWithException(this, string.Format(Resources.ExportReportDlg_ExportReport_Failed_exporting_to, fileName, GetExceptionDisplayMessage(x)), x);
                return false;
            }
        }
Пример #38
0
        public bool SaveDocument(String fileName, bool includingCacheFile = true)
        {
            if (string.IsNullOrEmpty(DocumentUI.Settings.DataSettings.DocumentGuid) ||
                !Equals(DocumentFilePath, fileName))
            {
                SrmDocument docOriginal;
                SrmDocument docNew;
                do
                {
                    docOriginal = Document;
                    docNew =
                        docOriginal.ChangeSettings(
                            docOriginal.Settings.ChangeDataSettings(
                                docOriginal.Settings.DataSettings.ChangeDocumentGuid()));
                } while (!SetDocument(docNew, docOriginal));
            }

            SrmDocument document = Document;

            try
            {
                using (var saver = new FileSaver(fileName))
                {
                    saver.CheckException();

                    using (var longWaitDlg = new LongWaitDlg(this)
                        {
                            Text = Resources.SkylineWindow_SaveDocument_Saving___,
                            Message = Path.GetFileName(fileName)
                        })
                    {
                        longWaitDlg.PerformWork(this, 800, progressMonitor =>
                        {
                            using (var writer = new XmlWriterWithProgress(saver.SafeName, fileName, Encoding.UTF8,
                                document.MoleculeTransitionCount, progressMonitor)
                            {
                                Formatting = Formatting.Indented
                            })
                            {
                                XmlSerializer ser = new XmlSerializer(typeof(SrmDocument));
                                ser.Serialize(writer, document);

                                writer.Flush();
                                writer.Close();

                                // If the user has chosen "Save As", and the document has a
                                // document specific spectral library, copy this library to
                                // the new name.
                                if (!Equals(DocumentFilePath, fileName))
                                    SaveDocumentLibraryAs(fileName);

                                saver.Commit();
                            }
                        });

                        // Sometimes this catches a cancellation that doesn't throw an OperationCanceledException.
                        if (longWaitDlg.IsCanceled)
                            return false;
                    }
                }
            }
            catch (OperationCanceledException)
            {
                return false;
            }
            catch (Exception ex)
            {
                var message = TextUtil.LineSeparate(string.Format(Resources.SkylineWindow_SaveDocument_Failed_writing_to__0__, fileName), ex.Message);
                MessageBox.Show(message);
                return false;
            }

            DocumentFilePath = fileName;
            _savedVersion = document.UserRevisionIndex;
            SetActiveFile(fileName);

            // Make sure settings lists contain correct values for this document.
            document.Settings.UpdateLists(DocumentFilePath);

            try
            {
                SaveLayout(fileName);

                // CONSIDER: Is this really optional?
                if (includingCacheFile)
                {
                    using (var longWaitDlg = new LongWaitDlg(this)
                    {
                        Text = Resources.SkylineWindow_SaveDocument_Optimizing_data_file___,
                        Message = Path.GetFileName(fileName)
                    })
                    {
                        longWaitDlg.PerformWork(this, 800, () =>
                            OptimizeCache(fileName, longWaitDlg));
                    }
                }
            }

            // We allow silent failures because it is OK for the cache to remain unoptimized
            // or the layout to not be saved.  These aren't critical as long as the document
            // was saved correctly.
            catch (UnauthorizedAccessException) {}
            catch (IOException) {}
            catch (OperationCanceledException) {}
            catch (TargetInvocationException) {}

            return true;
        }
Пример #39
0
        private void Save(ZipFile zip)
        {
            CountEntries = zip.Entries.Count;

            using (var saver = new FileSaver(SharedPath))
            {
                zip.SaveProgress += SrmDocumentSharing_SaveProgress;
                zip.Save(saver.SafeName);
                ProgressMonitor.UpdateProgress(_progressStatus.Complete());
                saver.Commit();
            }
        }
Пример #40
0
 /// <summary>
 /// test the corretness of the generated home
 /// Method: print the homes information to file
 /// Plot files in matlab to see the trend of energy consumption and harvesting energy
 /// </summary>
 public void testHomeSettings()
 {
     this.Homes = Util.HomeGenerator.GenerateHome(this.Config);
     FileSaver.SaveHomeListToFile(this.Homes);
 }
Пример #41
0
        protected override void DoTest()
        {
            string outDir = Path.Combine(TestContext.TestDir, "PerfPeakTest");
            string resultsTable = Path.Combine(outDir, "results.txt");
            Directory.CreateDirectory(outDir); // In case it doesn't already exists
            File.Delete(resultsTable); // In case it does already exist
            var none = new string[0];
            var openSwath = new List<string> { "OpenSwath.csv" };
            var spectronaut = new List<string> { "Spectronaut.csv" };
            var peakView = new List<string> { "PeakView.txt" };
            var peakViewSpectronaut = spectronaut.Concat(peakView).ToList();
            var peakViewOpenSwath = openSwath.Concat(peakView).ToList();
            var peakViewSpectronautOpenSwath = peakViewSpectronaut.Concat(openSwath).ToList();
            var decoysAndSecond = MODEL_NAMES;
            var secondOnly = MODEL_NAMES.Take(3).ToList();

            int i = 0;
            using (var fs = new FileSaver(resultsTable))
            using (var resultsWriter = new StreamWriter(fs.SafeName))
            {
                WriteHeader(resultsWriter);
                // Overlap 10 mz
                AnalyzeDirectory(i++, none, outDir, decoysAndSecond, resultsWriter);
                // Overlap 20 mz
                AnalyzeDirectory(i++, none, outDir, decoysAndSecond, resultsWriter);
                // Schilling Ack
                AnalyzeDirectory(i++, peakView, outDir, decoysAndSecond, resultsWriter, new List<int> { 1 });
                // Schilling Mito
                AnalyzeDirectory(i++, peakView, outDir, decoysAndSecond, resultsWriter, new List<int> { 1 });
                // Reiter sPRG
                AnalyzeDirectory(i++, spectronaut, outDir, decoysAndSecond, resultsWriter, new List<int> { 0 });
                // Ludwig sPRG
                AnalyzeDirectory(i++, none, outDir, decoysAndSecond, resultsWriter, new List<int> { 1 });
                // Hasmik Swath Heavy only
                AnalyzeDirectory(i++, peakViewSpectronautOpenSwath, outDir, decoysAndSecond, resultsWriter, new List<int> { 1, 1, 1 });
                // Hasmik Qe Heavy only
                AnalyzeDirectory(i++, spectronaut, outDir, decoysAndSecond, resultsWriter, new List<int> { 1 });
                // Hasmik SWATH
                AnalyzeDirectory(i++, peakViewSpectronautOpenSwath, outDir, decoysAndSecond, resultsWriter, new List<int> { 1, 1, 1 });
                // Hasmik QE
                AnalyzeDirectory(i++, spectronaut, outDir, decoysAndSecond, resultsWriter, new List<int> { 1 });
                // Hasmik Swath Light only
                AnalyzeDirectory(i++, peakViewSpectronaut, outDir, decoysAndSecond, resultsWriter, new List<int> { 0, 1 });
                // Hasmik Qe Light only
                AnalyzeDirectory(i++, spectronaut, outDir, decoysAndSecond, resultsWriter, new List<int> { 1 });
                // OpenSwath_Water
                AnalyzeDirectory(i++, peakViewOpenSwath, outDir, decoysAndSecond, resultsWriter, new List<int> { 2, 1 });
                // OpenSwath_Yeast
                AnalyzeDirectory(i++, peakViewOpenSwath, outDir, decoysAndSecond, resultsWriter, new List<int> { 1, 1 });
                // OpenSwath_Human
                AnalyzeDirectory(i++, peakViewOpenSwath, outDir, decoysAndSecond, resultsWriter, new List<int> { 2, 1 });
                // Olga SRM Course vantage
                AnalyzeDirectory(i++, none, outDir, decoysAndSecond, resultsWriter);
                // Olga SRM Course
                AnalyzeDirectory(i++, none, outDir, decoysAndSecond, resultsWriter);
                // Heart Failure
                AnalyzeDirectory(i++, none, outDir, secondOnly, resultsWriter);
                // Ovarian cancer
                AnalyzeDirectory(i++, none, outDir, secondOnly, resultsWriter);
                // mProphet Gold
                AnalyzeDirectory(i++, none, outDir, decoysAndSecond, resultsWriter);
                // MikeB high (DDA dilution top 12 runs)
                AnalyzeDirectory(i++, none, outDir, secondOnly, resultsWriter);
                // Schilling DDA (DDA dilution 15 runs)
                AnalyzeDirectory(i++, none, outDir, secondOnly, resultsWriter);
                // Held DIA
                AnalyzeDirectory(i++, peakView, outDir, decoysAndSecond, resultsWriter, new List<int> { 4 });
                resultsWriter.Close();
                fs.Commit();
            }

        }
Пример #42
0
        private bool ExportReport(string fileName, char separator)
        {
            try
            {
                using (var saver = new FileSaver(fileName))
                {
                    if (!saver.CanSave(this))
                    {
                        return(false);
                    }

                    using (var writer = new StreamWriter(saver.SafeName))
                    {
                        Report report  = GetReport();
                        bool   success = false;

                        using (var longWait = new LongWaitDlg {
                            Text = Resources.ExportReportDlg_ExportReport_Generating_Report
                        })
                        {
                            longWait.PerformWork(this, 1500, broker =>
                            {
                                var status = new ProgressStatus(Resources.ExportReportDlg_GetDatabase_Analyzing_document);
                                broker.UpdateProgress(status);
                                Database database = EnsureDatabase(broker, 80, ref status);
                                if (broker.IsCanceled)
                                {
                                    return;
                                }
                                broker.UpdateProgress(status = status.ChangeMessage(Resources.ExportReportDlg_ExportReport_Building_report));
                                ResultSet resultSet          = report.Execute(database);
                                if (broker.IsCanceled)
                                {
                                    return;
                                }
                                broker.UpdateProgress(status = status.ChangePercentComplete(95)
                                                               .ChangeMessage(Resources.ExportReportDlg_ExportReport_Writing_report));

                                ResultSet.WriteReportHelper(resultSet, separator, writer, CultureInfo);

                                writer.Flush();
                                writer.Close();

                                if (broker.IsCanceled)
                                {
                                    return;
                                }
                                broker.UpdateProgress(status.Complete());

                                saver.Commit();
                                success = true;
                            });
                        }

                        return(success);
                    }
                }
            }
            catch (Exception x)
            {
                MessageDlg.ShowWithException(this, string.Format(Resources.ExportReportDlg_ExportReport_Failed_exporting_to, fileName, GetExceptionDisplayMessage(x)), x);
                return(false);
            }
        }
        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;
                }
            }
        }
Пример #44
0
        // ReSharper restore UnusedMember.Local

        private bool CreateCache(ILoadMonitor loader, ProgressStatus status, int percent)
        {
            var sm = loader.StreamManager;

            BufferedStream stream = new BufferedStream(CreateStream(loader), 32 * 1024);

            int    version = 1;
            string id = string.Empty, revision = string.Empty;
            int    size = ReadSize(stream);
            int    i;

            if (size == 0)
            {
                version = 2;
                size    = ReadSize(stream);

                const int countLibHeader = 256 - 8;
                byte[]    libHeader      = new byte[countLibHeader];
                if (stream.Read(libHeader, 0, libHeader.Length) != libHeader.Length)
                {
                    throw new InvalidDataException(Resources.XHunterLibrary_CreateCache_Data_truncation_in_library_header_File_may_be_corrupted);
                }

                for (i = 0; i < libHeader.Length; i++)
                {
                    if (libHeader[i] == 0)
                    {
                        break;
                    }
                }

                string header = Encoding.UTF8.GetString(libHeader, 0, i);
                Match  match  = REGEX_HEADER.Match(header);
                if (match.Success)
                {
                    version  = int.Parse(match.Groups[1].Value);
                    id       = match.Groups[2].Value;
                    revision = match.Groups[3].Value;
                }
            }
            var setLibKeys     = new Dictionary <LibKey, bool>(size);
            var setSequences   = new Dictionary <LibSeqKey, bool>(size);
            var libraryEntries = new List <XHunterSpectrumInfo>(size);

            const int countHeader = ((int)SpectrumHeaders2.count) * sizeof(int);

            byte[] specHeader   = new byte[1024];
            byte[] specSequence = new byte[1024];
            i = 0;

            while (stream.Read(specHeader, 0, countHeader) == countHeader)
            {
                int percentComplete = (i++ *percent / size);
                if (status.PercentComplete != percentComplete)
                {
                    // 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(percentComplete));
                }

                int charge = (version == 1
                                  ? GetInt32(specHeader, ((int)SpectrumHeaders1.charge))
                                  : GetInt32(specHeader, ((int)SpectrumHeaders2.charge)));

                float i2 = (version == 1
                                ? GetSingle(specHeader, ((int)SpectrumHeaders1.i2))
                                : GetSingle(specHeader, ((int)SpectrumHeaders2.i2)));
                int seqLength = (version == 1
                                     ? GetInt32(specHeader, ((int)SpectrumHeaders1.seq_len))
                                     : GetInt32(specHeader, ((int)SpectrumHeaders2.seq_len)));

                float expect = (version == 1 ? 0.001f : GetSingle(specHeader, (int)SpectrumHeaders2.expect));


                // Read sequence information
                ReadComplete(stream, specSequence, seqLength);
                specSequence[seqLength] = 0;

                short numPeaks = (short)ReadSize(stream);

                // Save spectrum location
                long location = stream.Position;

                // Read over spectrum
                int countPeaks = (sizeof(byte) + sizeof(float)) * numPeaks;
                stream.Seek(countPeaks, SeekOrigin.Current); // Skip spectrum

                // Read modifications
                int numMods = ReadSize(stream);

                byte[] sequence = specSequence;

                if (numMods > 0)
                {
                    StringBuilder sb = new StringBuilder();

                    ReadComplete(stream, specHeader, (4 + sizeof(double)) * numMods);
                    int    iLast    = 0;
                    double modTotal = 0;
                    for (int j = 0; j < numMods; j++)
                    {
                        int    iPos = GetInt32(specHeader, j * 3);
                        double mod  = BitConverter.ToDouble(specHeader, (j * 3 + 1) * 4);

                        // X! Hunter allows multiple modifications on the same
                        // residue.  So, they need to be totaled, and assigned to a
                        // single residue to allow them to match Skyline modification
                        // settings.
                        if (iPos > iLast)
                        {
                            if (modTotal != 0)
                            {
                                sb.Append(SequenceMassCalc.GetModDiffDescription(modTotal));
                            }
                            sb.Append(Encoding.UTF8.GetString(specSequence, iLast, iPos - iLast));

                            modTotal = 0;
                        }
                        modTotal += mod;
                        iLast     = iPos;
                    }
                    if (modTotal != 0)
                    {
                        sb.Append(SequenceMassCalc.GetModDiffDescription(modTotal));
                    }
                    sb.Append(Encoding.UTF8.GetString(specSequence, iLast, seqLength - iLast));
                    sequence  = Encoding.UTF8.GetBytes(sb.ToString());
                    seqLength = sb.Length;
                }

                // Skip over homologs (list of protein IDs and start positions from a FASTA
                // file used to generate the library)
                int numHomologs = ReadSize(stream);
                for (int j = 0; j < numHomologs; j++)
                {
                    stream.Seek(ReadSize(stream) + 4, SeekOrigin.Current);
                }

                // These libraries should not have duplicates, but just in case.
                // Apparently, GPM libraries do contain redundancies, as we found
                // when a revision lost this test.
                var key = new LibKey(sequence, 0, seqLength, charge);
                if (!setLibKeys.ContainsKey(key))
                {
                    setLibKeys.Add(key, true);
                    libraryEntries.Add(new XHunterSpectrumInfo(key, i2, expect, numPeaks, location));
                }
            }

            libraryEntries.Sort(CompareSpectrumInfo);

            using (FileSaver fs = new FileSaver(CachePath, sm))
                using (Stream outStream = sm.CreateStream(fs.SafeName, FileMode.Create, true))
                {
                    foreach (var info in libraryEntries)
                    {
                        LibSeqKey seqKey = new LibSeqKey(info.Key);
                        if (setSequences.ContainsKey(seqKey))
                        {
                            outStream.Write(BitConverter.GetBytes(0), 0, sizeof(int));
                            outStream.Write(BitConverter.GetBytes(-1), 0, sizeof(int));
                        }
                        else
                        {
                            // If it is unique, it will need to be added at cache load time.
                            setSequences.Add(seqKey, true);
                            outStream.Write(BitConverter.GetBytes(seqKey.GetHashCode()), 0, sizeof(int));
                            outStream.Write(BitConverter.GetBytes(seqKey.Length), 0, sizeof(int));
                        }
                        outStream.Write(BitConverter.GetBytes(info.Key.Charge), 0, sizeof(int));
                        outStream.Write(BitConverter.GetBytes(info.ProcessedIntensity), 0, sizeof(float));
                        outStream.Write(BitConverter.GetBytes(info.Location), 0, sizeof(long));
                        outStream.Write(BitConverter.GetBytes(info.NumPeaks), 0, sizeof(int));
                        outStream.Write(BitConverter.GetBytes(info.Expect), 0, sizeof(float));
                        info.Key.WriteSequence(outStream);
                    }

                    byte[] revisionBytes = Encoding.UTF8.GetBytes(revision);
                    outStream.Write(revisionBytes, 0, revisionBytes.Length);
                    byte[] idBytes = Encoding.UTF8.GetBytes(id);
                    outStream.Write(idBytes, 0, idBytes.Length);
                    outStream.Write(BitConverter.GetBytes(revisionBytes.Length), 0, sizeof(int));
                    outStream.Write(BitConverter.GetBytes(idBytes.Length), 0, sizeof(int));
                    outStream.Write(BitConverter.GetBytes(FORMAT_VERSION_CACHE), 0, sizeof(int));
                    outStream.Write(BitConverter.GetBytes(libraryEntries.Count), 0, sizeof(int));
                    outStream.Write(BitConverter.GetBytes((long)0), 0, sizeof(long));

                    sm.Finish(outStream);
                    fs.Commit();
                    sm.SetCache(FilePath, CachePath);
                }

            loader.UpdateProgress(status.Complete());

            return(true);
        }
Пример #45
0
        /// <summary>
        /// Saves the database to a new directory with only the standards and peptides used
        /// in a given document.
        /// </summary>
        /// <param name="pathDestDir">The directory to save to</param>
        /// <param name="document">The document for which peptides are to be kept</param>
        /// <returns>The full path to the file saved</returns>
        public override string PersistMinimized(string pathDestDir, SrmDocument document)
        {
            RequireUsable();

            string persistPath = Path.Combine(pathDestDir, Path.GetFileName(PersistencePath) ?? string.Empty);  // ReSharper
            using (var fs = new FileSaver(persistPath))
            {
                var irtDbMinimal = IrtDb.CreateIrtDb(fs.SafeName);

                // Calculate the minimal set of peptides needed for this document
                var dbPeptides = _database.GetPeptides().ToList();
                var persistPeptides = dbPeptides.Where(pep => pep.Standard).Select(NewPeptide).ToList();
                var dictPeptides = dbPeptides.Where(pep => !pep.Standard).ToDictionary(pep => pep.PeptideModSeq);
                foreach (var nodePep in document.Peptides)
                {
                    string modifiedSeq = document.Settings.GetSourceTextId(nodePep);
                    DbIrtPeptide dbPeptide;
                    if (dictPeptides.TryGetValue(modifiedSeq, out dbPeptide))
                    {
                        persistPeptides.Add(NewPeptide(dbPeptide));
                        // Only add once
                        dictPeptides.Remove(modifiedSeq);
                    }
                }

                irtDbMinimal.AddPeptides(persistPeptides);
                fs.Commit();
            }

            return persistPath;
        }
        private void GenerateFiles(List<CrudGenCSharp> cSharpFiles)
        {
            //output the files
            FileSaver fs = new FileSaver();
            foreach (CrudGenCSharp cs in cSharpFiles)
            {
                //output BL and DL
                if (u.UserSettings.ResultsToFile)
                {
                    fs.SaveFile(u.UserSettings.OutputDirectory + cs.ClassName + ".cs", cs.CrudObject, u.UserSettings.ResultFileOverwrite);
                    fs.SaveFile(u.UserSettings.OutputDirectory + cs.ClassName + "Data.cs", cs.CrudData, u.UserSettings.ResultFileOverwrite);
                }
                else
                {
                    txtC_BL.Text += cs.CrudObject;
                    txtC_DL.Text += cs.CrudData;
                }
            }

            if (u.UserSettings.ResultsToFile)
            {
                //save DataReaderExtensions
                fs.SaveFile(u.UserSettings.OutputDirectory + "DataReaderExtensions.cs", CrudGenCSharp.GetDataReaderExtensions(), true);
                //save the Data Layer
                fs.SaveFile(u.UserSettings.OutputDirectory + "DataAccessLayer.cs", CrudGenCSharp.GetDataAccessLayer(), true);
            }
            else
            {
                txtC_DAL.Text = CrudGenCSharp.GetDataAccessLayer();
                txtC_DAL.Text +="\r\n\r\n\\\\\\\\\\\\\\********************************"
                    + CrudGenCSharp.GetDataReaderExtensions();
            }
        }
Пример #47
0
        private void ExportLiveReport(string reportName, string reportFile, char reportColSeparator, bool reportInvariant)
        {
            var viewContext = DocumentGridViewContext.CreateDocumentGridViewContext(_doc, reportInvariant
                ? DataSchemaLocalizer.INVARIANT
                : SkylineDataSchema.GetLocalizedSchemaLocalizer());
            var viewInfo = viewContext.GetViewInfo(PersistedViews.MainGroup.Id.ViewName(reportName));
            if (null == viewInfo)
            {
                _out.WriteLine(Resources.CommandLine_ExportLiveReport_Error__The_report__0__does_not_exist__If_it_has_spaces_in_its_name__use__double_quotes__around_the_entire_list_of_command_parameters_, reportName);
                return;
            }
            _out.WriteLine(Resources.CommandLine_ExportLiveReport_Exporting_report__0____, reportName);

            try
            {
                using (var saver = new FileSaver(reportFile))
                {
                    if (!saver.CanSave())
                    {
                        _out.WriteLine(Resources.CommandLine_ExportLiveReport_Error__The_report__0__could_not_be_saved_to__1__, reportName, reportFile);
                        _out.WriteLine(Resources.CommandLine_ExportLiveReport_Check_to_make_sure_it_is_not_read_only_);
                    }

                    var status = new ProgressStatus(string.Empty);
                    IProgressMonitor broker = new CommandProgressMonitor(_out, status);

                    using (var writer = new StreamWriter(saver.SafeName))
                    {
                        viewContext.Export(broker, ref status, viewInfo, writer,
                            new DsvWriter(reportInvariant ? CultureInfo.InvariantCulture : LocalizationHelper.CurrentCulture, reportColSeparator));
                    }

                    broker.UpdateProgress(status.Complete());
                    saver.Commit();
                    _out.WriteLine(Resources.CommandLine_ExportLiveReport_Report__0__exported_successfully_to__1__, reportName, reportFile);
                }
            }
            catch (Exception x)
            {
                _out.WriteLine(Resources.CommandLine_ExportLiveReport_Error__Failure_attempting_to_save__0__report_to__1__, reportName, reportFile);
                _out.WriteLine(x.Message);
            }
        }
Пример #48
0
 public RecipesController(CookBookContext context, FileSaver fileSaver)
 {
     _context   = context;
     _fileSaver = fileSaver;
 }
Пример #49
0
        public void ExportChromatograms(string chromatogramsFile, bool precursors, bool products, bool basePeaks, bool tics)
        {
            _out.WriteLine(Resources.CommandLine_ExportChromatograms_Exporting_chromatograms_file__0____, chromatogramsFile);

            var chromExtractors = new List<ChromExtractor>();
            if (tics)
                chromExtractors.Add(ChromExtractor.summed);
            if (basePeaks)
                chromExtractors.Add(ChromExtractor.base_peak);

            var chromSources = new List<ChromSource>();
            if (precursors)
                chromSources.Add(ChromSource.ms1);
            if (products)
                chromSources.Add(ChromSource.fragment);

            if (chromExtractors.Count == 0 && chromSources.Count == 0)
            {
                _out.WriteLine(Resources.CommandLine_ExportChromatograms_Error__At_least_one_chromatogram_type_must_be_selected);
                return;
            }

            var filesToExport = Document.Settings.HasResults
                ? Document.Settings.MeasuredResults.MSDataFilePaths.Select(f => f.GetFileName()).ToList()
                : new List<string>();
            if (filesToExport.Count == 0)
            {
                _out.WriteLine(Resources.CommandLine_ExportChromatograms_Error__The_document_must_have_imported_results);
                return;
            }

            try
            {
                var chromExporter = new ChromatogramExporter(Document);
                using (var saver = new FileSaver(chromatogramsFile))
                using (var writer = new StreamWriter(saver.SafeName))
                {
                    var status = new ProgressStatus(string.Empty);
                    IProgressMonitor broker = new CommandProgressMonitor(_out, status);
                    chromExporter.Export(writer, broker, filesToExport, LocalizationHelper.CurrentCulture, chromExtractors, chromSources);
                    writer.Close();
                    broker.UpdateProgress(status.Complete());
                    saver.Commit();
                    _out.WriteLine(Resources.CommandLine_ExportChromatograms_Chromatograms_file__0__exported_successfully_, chromatogramsFile);
                }
            }
            catch (Exception x)
            {
                _out.WriteLine(Resources.CommandLine_ExportChromatograms_Error__Failure_attempting_to_save_chromatograms_file__0_, chromatogramsFile);
                _out.WriteLine(x.Message);
            }
        }
Пример #50
0
        private bool ValidateBuilder(bool validateInputFiles)
        {
            string name;

            if (!_helper.ValidateNameTextBox(textName, out name))
            {
                return(false);
            }

            string outputPath = textPath.Text;

            if (string.IsNullOrEmpty(outputPath))
            {
                _helper.ShowTextBoxError(textPath, Resources.BuildLibraryDlg_ValidateBuilder_You_must_specify_an_output_file_path, outputPath);
                return(false);
            }
            if (Directory.Exists(outputPath))
            {
                _helper.ShowTextBoxError(textPath, Resources.BuildLibraryDlg_ValidateBuilder_The_output_path__0__is_a_directory_You_must_specify_a_file_path, outputPath);
                return(false);
            }
            string outputDir = Path.GetDirectoryName(outputPath);

            if (string.IsNullOrEmpty(outputDir) || !Directory.Exists(outputDir))
            {
                _helper.ShowTextBoxError(textPath, Resources.BuildLibraryDlg_ValidateBuilder_The_directory__0__does_not_exist, outputDir);
                return(false);
            }
            if (!outputPath.EndsWith(BiblioSpecLiteSpec.EXT))
            {
                outputPath += BiblioSpecLiteSpec.EXT;
            }
            try
            {
                using (var sfLib = new FileSaver(outputPath))
                {
                    if (!sfLib.CanSave(this))
                    {
                        textPath.Focus();
                        textPath.SelectAll();
                        return(false);
                    }
                }
            }
            catch (UnauthorizedAccessException)
            {
                _helper.ShowTextBoxError(textPath, TextUtil.LineSeparate(Resources.BuildLibraryDlg_ValidateBuilder_Access_violation_attempting_to_write_to__0__,
                                                                         Resources.BuildLibraryDlg_ValidateBuilder_Please_check_that_you_have_write_access_to_this_folder_), outputDir);
                return(false);
            }
            catch (IOException)
            {
                _helper.ShowTextBoxError(textPath, TextUtil.LineSeparate(Resources.BuildLibraryDlg_ValidateBuilder_Failure_attempting_to_create_a_file_in__0__,
                                                                         Resources.BuildLibraryDlg_ValidateBuilder_Please_check_that_you_have_write_access_to_this_folder_), outputDir);
                return(false);
            }

            double cutOffScore;

            if (!_helper.ValidateDecimalTextBox(textCutoff, 0, 1.0, out cutOffScore))
            {
                return(false);
            }
            Settings.Default.LibraryResultCutOff = cutOffScore;

            var libraryBuildAction = LibraryBuildAction;

            if (validateInputFiles)
            {
                var inputFilesChosen = new List <string>();
                foreach (int i in listInputFiles.CheckedIndices)
                {
                    inputFilesChosen.Add(_inputFileNames[i]);
                }

                List <Target> targetPeptidesChosen = null;
                if (cbFilter.Checked)
                {
                    targetPeptidesChosen = new List <Target>();
                    var doc = _documentUiContainer.Document;
                    foreach (PeptideDocNode nodePep in doc.Peptides)
                    {
                        // Add light modified sequences
                        targetPeptidesChosen.Add(nodePep.ModifiedTarget);
                        // Add heavy modified sequences
                        foreach (var nodeGroup in nodePep.TransitionGroups)
                        {
                            if (nodeGroup.TransitionGroup.LabelType.IsLight)
                            {
                                continue;
                            }
                            targetPeptidesChosen.Add(doc.Settings.GetModifiedSequence(nodePep.Peptide.Target,
                                                                                      nodeGroup.TransitionGroup.LabelType,
                                                                                      nodePep.ExplicitMods));
                        }
                    }
                }

                _builder = new BiblioSpecLiteBuilder(name, outputPath, inputFilesChosen, targetPeptidesChosen)
                {
                    Action = libraryBuildAction,
                    IncludeAmbiguousMatches = cbIncludeAmbiguousMatches.Checked,
                    KeepRedundant           = LibraryKeepRedundant,
                    CutOffScore             = cutOffScore,
                    Id                    = Helpers.MakeId(textName.Text),
                    IrtStandard           = _driverStandards.SelectedItem,
                    PreferEmbeddedSpectra = PreferEmbeddedSpectra
                };
            }
            return(true);
        }
Пример #51
0
    // Update is called once per frame
    public override IEnumerator Evolve()
    {
        // Start by randomly generating the initial population.
        for (int i = 0; i < populationSize; i++)
        {
            m_population.Add(RandomGenome());
        }
        // Randomly generate the first best genome.
        bestGenome = RandomGenome();

        // First, process the initial population differently.
        feedbackText.SetText("Generation " + 0 + " out of " + generations + "...");
        Debug.Log("Starting simulation step of initial population...");
        // Start simulation and wait until done.
        simulationDone = false;
        StartCoroutine(Simulate(m_population));
        yield return(new WaitUntil(() => simulationDone));

        Debug.Log("Simulation step of initial population complete!");

        // Assign fitness to each genome according to nondomination principle.
        SortFitnessByNondomination(m_population);
        CalculateCrowdingDistance(m_population);

        // Initial "next population" processing.
        while (m_childPop.Count < m_population.Count)
        {
            Genome parent0, parent1;
            parent0 = BinaryCrowdedTournamentSelect(m_population);
            parent1 = BinaryCrowdedTournamentSelect(m_population);

            // Combine parents to retrieve two children
            Genome child0, child1;
            Combine(out child0, out child1, parent0, parent1);

            Mutate(child0.RootNode);
            Mutate(child1.RootNode);
            m_childPop.Add(child0);
            m_childPop.Add(child1);
        }

        //Debug.Log("Evolving rest of generations...");
        // Run general algorithm for remaining -th generations. (index 1 and forward
        for (int i = 1; i < generations; i++)
        {
            feedbackText.SetText("Generation " + i + " out of " + generations + "...");

            //Debug.Log("Starting simulation step of generation " + i);
            // Start simulation and wait until done.
            simulationDone = false;
            StartCoroutine(Simulate(m_childPop));
            yield return(new WaitUntil(() => simulationDone));

            //Debug.Log("Simulation step complete!");

            // First, create new generation as a combination of the last and the one before that.
            List <Genome> combinedGenomes = new List <Genome>();
            combinedGenomes.AddRange(m_population);
            combinedGenomes.AddRange(m_childPop);

            List <Genome> nextPopCandidates = new List <Genome>();
            // Sort according to nondomination and return list of fronts
            List <List <Genome> > fronts = GetFrontsByNondomination(combinedGenomes);
            int frontIndex = 0;

            // Create set of potential genome candidats
            while (nextPopCandidates.Count + fronts[frontIndex].Count <= populationSize)
            {
                // Calculate crowding distance for the front and add it to the population.
                CalculateCrowdingDistance(fronts[frontIndex]);
                nextPopCandidates.AddRange(fronts[frontIndex]);

                frontIndex++;
            }

            //Debug.Log(fronts[0].Count);
            // Retrieve the best genome from front 0, used for simulation
            Genome bestBack = BestFromFront(fronts[0]);
            bestGenome          = bestBack.GenomeCopy();
            bestGenome.RootNode = StaticMethods.DeepCopy <N_Root>(bestBack.RootNode);

            // Sort the front that didn't fit
            SortCrowdedComparison(fronts[frontIndex]);
            int fillingIndex = 0;
            // Complete the population by adding from the sorted front
            while (nextPopCandidates.Count < populationSize)
            {
                nextPopCandidates.Add(fronts[frontIndex][fillingIndex]);
                fillingIndex++;
            }

            // Push child back to pop and create new child using nextpop made from child and pop
            m_population = m_childPop;
            m_childPop   = new List <Genome>();

            // Finally, create the childpop for next generation.
            while (m_childPop.Count < populationSize)
            {
                Genome parent0, parent1;
                parent0 = BinaryCrowdedTournamentSelect(nextPopCandidates);
                parent1 = BinaryCrowdedTournamentSelect(nextPopCandidates);

                // Combine parents to retrieve two children
                Genome child0, child1;
                Combine(out child0, out child1, parent0, parent1);

                Mutate(child0.RootNode);
                Mutate(child1.RootNode);
                m_childPop.Add(child0);
                m_childPop.Add(child1);
            }
        }
        // Save the final best tree.
        FileSaver.GetInstance().SaveTree(bestGenome.RootNode, "multiEvolved");
        feedbackText.SetText("Multi evolution complete!");
        buttonCanvas.SetActive(true);

        yield return(null);
    }
        public ActionResult UploadFile(int?entityId)  // optionally receive values specified with Html helper
        {
            // here we can send in some extra info to be included with the delete url
            var statuses = new List <ViewDataUploadFileResult>();

            for (var i = 0; i < Request.Files.Count; i++)
            {
                var st = FileSaver.StoreFile(x =>
                {
                    x.File = Request.Files[i];
                    //note how we are adding an additional value to be posted with delete request
                    //and giving it the same value posted with upload
                    x.DeleteUrl        = Url.Action("DeleteFile", new { entityId = entityId });
                    x.StorageDirectory = Server.MapPath("~/Content/uploads");
                    x.UrlPrefix        = "/Content/uploads";// this is used to generate the relative url of the file


                    //overriding defaults
                    x.FileName        = Request.Files[i].FileName; // default is filename suffixed with filetimestamp
                    x.ThrowExceptions = true;                      //default is false, if false exception message is set in error property
                });

                statuses.Add(st);
            }

            //statuses contains all the uploaded files details (if error occurs then check error property is not null or empty)
            //todo: add additional code to generate thumbnail for videos, associate files with entities etc

            //adding thumbnail url for jquery file upload javascript plugin
            statuses.ForEach(x => x.thumbnailUrl = x.url + "?width=80&height=80"); // uses ImageResizer httpmodule to resize images from this url

            //setting custom download url instead of direct url to file which is default
            statuses.ForEach(x => x.url = Url.Action("DownloadFile", new { fileUrl = x.url, mimetype = x.type }));


            //server side error generation, generate some random error if entity id is 13
            if (entityId == 13)
            {
                var rnd = new Random();
                statuses.ForEach(x =>
                {
                    //setting the error property removes the deleteUrl, thumbnailUrl and url property values
                    x.error = rnd.Next(0, 2) > 0 ? "We do not have any entity with unlucky Id : '13'" : String.Format("Your file size is {0} bytes which is un-acceptable", x.size);
                    //delete file by using FullPath property
                    if (System.IO.File.Exists(x.FullPath))
                    {
                        System.IO.File.Delete(x.FullPath);
                    }
                });
            }

            var viewresult = Json(new { files = statuses });

            //for IE8 which does not accept application/json
            if (Request.Headers["Accept"] != null && !Request.Headers["Accept"].Contains("application/json"))
            {
                viewresult.ContentType = "text/plain";
            }

            return(viewresult);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            try { CheckIfAllRequiredFilledAreEntered(); }
            catch(Exception ex) {MessageBox.Show(ex.Message);return;}

            if (string.IsNullOrEmpty(u.ConnectionString))
            {
                MessageBox.Show("The connectionstring is empty");
                return;
            }
            string server = this.txtServer.Text, database = this.txtDatabase.Text, userName = this.txtUser.Text, passWord = this.txtPassword.Text;
            bool dropIfExists = u.UserSettings.SprocDropIfExists ;
            DataTable dt = GetColumns();
            List<CrudGenSPROC> sprocs = CrudGenSPROC.ParseDataTable(dt);
            string errors = "";
            SuccessLog = new StringBuilder();
            ErrorLog = new StringBuilder();

            foreach (CrudGenSPROC sp in sprocs) {
                sp.Author = this.txtAuthor.Text;
                sp.IsActive = this.txtIsActive.Text;

                string errorLine = "";

                if (u.UserSettings.SprocCreate)
                    errorLine += Execute(sp.GenerateCreate(dropIfExists), "Create");
                if (u.UserSettings.SprocDelete)
                    errorLine += Execute(sp.GenerateDelete(dropIfExists), "Delete");
                if (u.UserSettings.SprocUpdate)
                    errorLine += Execute(sp.GenerateUpdate(dropIfExists), "Update");
                if (u.UserSettings.SprocRetrieveAll)
                    errorLine += Execute(sp.GenerateSelectAll(dropIfExists), "ReadAll");
                if (u.UserSettings.SprocRetrieveByID)
                    errorLine += Execute(sp.GenerateSelectById(dropIfExists), "ReadById");
                if (u.UserSettings.ReadByIDIfUserIdColumnExists)
                    errorLine += Execute(sp.GenerateSelectByUserId(dropIfExists), "ReadByUserId");
                if (this.chkDeactivate.Checked)
                    errorLine += Execute(sp.GenerateDeactiveate(dropIfExists), "Deactivate");

                if (errorLine.Length > 0) {
                    if (errors.Length > 0)
                        errors = errors + Environment.NewLine;
                    errors = errors + sp.TableName + "-" + errorLine.Remove(errorLine.Length-2);//remove ", "
                }
            }

            if (u.UserSettings.ResultsToFile) {
                this.txtSuccessLog.Text = "Files created in " + u.UserSettings.OutputDirectory + Environment.NewLine ;
                this.txtSuccessLog.Text += "  -  See file name: " + "InstallCRUD_SPROCs.sql" + Environment.NewLine;
                FileSaver fs = new FileSaver();
                fs.SaveFile(u.UserSettings.OutputDirectory + "InstallCRUD_SPROCs.sql", SuccessLog.ToString(), u.UserSettings.ResultFileOverwrite );
            }
            else
            {
                this.txtSuccessLog.Text = SuccessLog.ToString();
                this.txtErrorLog.Text = ErrorLog.ToString();
            }
            if (errors.Length > 0)
                MessageBox.Show("The following procedures were not able to be generated:" + Environment.NewLine + errors);
            else
            {
                MessageBox.Show("SUCCESS");
            }
            ErrorLog = null;
            SuccessLog = null;
        }
Пример #54
0
        public static OptimizationDb ConvertFromOldFormat(string path, IProgressMonitor loadMonitor, ProgressStatus status, SrmDocument document)
        {
            // Try to open assuming old format (Id, PeptideModSeq, Charge, Mz, Value, Type)
            var precursors    = new Dictionary <string, HashSet <int> >();    // PeptideModSeq -> charges
            var optimizations = new List <Tuple <DbOptimization, double> >(); // DbOptimization, product m/z
            int maxCharge     = 1;

            using (SQLiteConnection connection = new SQLiteConnection("Data Source = " + path)) // Not L10N
                using (SQLiteCommand command = new SQLiteCommand(connection))
                {
                    connection.Open();
                    command.CommandText = "SELECT PeptideModSeq, Charge, Mz, Value, Type FROM OptimizationLibrary"; // Not L10N
                    using (SQLiteDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var type             = (OptimizationType)reader["Type"];   // Not L10N
                            var modifiedSequence = reader["PeptideModSeq"].ToString(); // Not L10N
                            var charge           = (int)reader["Charge"];              // Not L10N
                            var productMz        = (double)reader["Mz"];               // Not L10N
                            var value            = (double)reader["Value"];            // Not L10N
                            optimizations.Add(new Tuple <DbOptimization, double>(new DbOptimization(type, modifiedSequence, charge, string.Empty, -1, value), productMz));

                            if (!precursors.ContainsKey(modifiedSequence))
                            {
                                precursors[modifiedSequence] = new HashSet <int>();
                            }
                            precursors[modifiedSequence].Add(charge);
                            if (charge > maxCharge)
                            {
                                maxCharge = charge;
                            }
                        }
                    }
                }

            var peptideList = (from precursor in precursors
                               from charge in precursor.Value
                               select string.Format("{0}{1}", precursor.Key, Transition.GetChargeIndicator(charge)) // Not L10N
                               ).ToList();

            var newDoc = new SrmDocument(document != null ? document.Settings : SrmSettingsList.GetDefault());

            newDoc = newDoc.ChangeSettings(newDoc.Settings
                                           .ChangePeptideLibraries(libs => libs.ChangePick(PeptidePick.filter))
                                           .ChangeTransitionFilter(filter =>
                                                                   filter.ChangeFragmentRangeFirstName("ion 1") // Not L10N
                                                                   .ChangeFragmentRangeLastName("last ion")     // Not L10N
                                                                   .ChangeProductCharges(Enumerable.Range(1, maxCharge).ToList())
                                                                   .ChangeIonTypes(new [] { IonType.y, IonType.b }))
                                           .ChangeTransitionLibraries(libs => libs.ChangePick(TransitionLibraryPick.none))
                                           );
            var matcher = new ModificationMatcher {
                FormatProvider = NumberFormatInfo.InvariantInfo
            };

            matcher.CreateMatches(newDoc.Settings, peptideList, Settings.Default.StaticModList, Settings.Default.HeavyModList);
            FastaImporter       importer = new FastaImporter(newDoc, matcher);
            string              text     = string.Format(">>{0}\r\n{1}", newDoc.GetPeptideGroupId(true), TextUtil.LineSeparate(peptideList)); // Not L10N
            PeptideGroupDocNode imported = importer.Import(new StringReader(text), null, Helpers.CountLinesInString(text)).First();

            int optimizationsUpdated = 0;

            foreach (PeptideDocNode nodePep in imported.Children)
            {
                string sequence = newDoc.Settings.GetSourceTextId(nodePep);
                foreach (var nodeGroup in nodePep.TransitionGroups)
                {
                    int charge = nodeGroup.PrecursorCharge;
                    foreach (var nodeTran in nodeGroup.Transitions)
                    {
                        double productMz = nodeTran.Mz;
                        foreach (var optimization in optimizations.Where(opt =>
                                                                         string.IsNullOrEmpty(opt.Item1.FragmentIon) &&
                                                                         opt.Item1.ProductCharge == -1 &&
                                                                         opt.Item1.PeptideModSeq == sequence &&
                                                                         opt.Item1.Charge == charge &&
                                                                         Math.Abs(opt.Item2 - productMz) < 0.00001))
                        {
                            optimization.Item1.FragmentIon   = nodeTran.FragmentIonName;
                            optimization.Item1.ProductCharge = nodeTran.Transition.Charge;
                            ++optimizationsUpdated;
                        }
                    }
                }
            }

            if (optimizations.Count > optimizationsUpdated)
            {
                throw new OptimizationsOpeningException(string.Format(Resources.OptimizationDb_ConvertFromOldFormat_Failed_to_convert__0__optimizations_to_new_format_,
                                                                      optimizations.Count - optimizationsUpdated));
            }

            using (var fs = new FileSaver(path))
            {
                OptimizationDb db = CreateOptimizationDb(fs.SafeName);
                db.UpdateOptimizations(optimizations.Select(opt => opt.Item1).ToArray(), new DbOptimization[0]);
                fs.Commit();

                if (loadMonitor != null)
                {
                    loadMonitor.UpdateProgress(status.ChangePercentComplete(100));
                }
                return(GetOptimizationDb(fs.RealName, null, null));
            }
        }