public IEnumerable <DigestedPeptide> Digest(Protein protein) { if (string.IsNullOrEmpty(protein.Sequence)) { yield break; } FastaSequence fastaSequence; try { fastaSequence = new FastaSequence("name", "description", new List <ProteinMetadata>(), protein.Sequence); // Not L10N } catch (InvalidDataException) { // It's possible that the peptide sequence in the fasta file was bogus, in which case we just don't digest it. yield break; } DigestSettings digestSettings = new DigestSettings(6, false); foreach (var digest in _enzyme.Digest(fastaSequence, digestSettings)) { var digestedPeptide = new DigestedPeptide { Index = digest.Begin ?? 0, Sequence = digest.Sequence }; yield return(digestedPeptide); } }
public void ProteinListTest() { // Too few columns const char sep = TextUtil.SEPARATOR_TSV; AssertEx.ThrowsException <LineColNumberedIoException>(() => FastaImporter.ToFasta("PROT1\nPROT2\nPROT2", sep)); // Invalid sequence string invalidSeq = PROTEINLIST_CLIPBOARD_TEXT.Replace("MDAL", "***"); AssertEx.ThrowsException <LineColNumberedIoException>(() => FastaImporter.ToFasta(invalidSeq, sep)); string fastaText = FastaImporter.ToFasta(PROTEINLIST_CLIPBOARD_TEXT, sep); var reader = new StringReader(fastaText); int countProt = 0; string line; while ((line = reader.ReadLine()) != null) { if (line.StartsWith(">")) { countProt++; } else { Assert.IsTrue(FastaSequence.IsExSequence(line.Trim('*'))); } } Assert.AreEqual(3, countProt); }
// creates dictionary of a protein to a list of peptides that match private void FindProteinMatchesWithFasta(Stream fastaFile) { var proteinAssociations = new List <KeyValuePair <FastaSequence, List <PeptideDocNode> > >(); var peptidesForMatching = ListPeptidesForMatching(); using (var reader = new StreamReader(fastaFile)) { foreach (var seq in FastaData.ParseFastaFile(reader)) { var fasta = new FastaSequence(seq.Name, null, null, seq.Sequence); var matches = new List <PeptideDocNode>(); foreach (var peptide in peptidesForMatching) { // TODO(yuval): does digest matter? if (fasta.Sequence.IndexOf(peptide.Peptide.Target.Sequence, StringComparison.Ordinal) < 0) { continue; } matches.Add(peptide); } if (matches.Count > 0) { proteinAssociations.Add(new KeyValuePair <FastaSequence, List <PeptideDocNode> >(fasta, matches)); } } } SetCheckBoxListItems(proteinAssociations, Resources.AssociateProteinsDlg_FindProteinMatchesWithFasta_No_matches_were_found_using_the_imported_fasta_file_); }
private static ExitCodes ProgramExecution() { var testSeqChromosome = new Chromosome("chrTestSeq", "TestSeq", null, null, 1, 0); var chromosomes = new List <IChromosome> { testSeqChromosome }; Console.Write("- creating FASTA sequence... "); var fastaSequence = new FastaSequence(testSeqChromosome, "NNATGTTTCCACTTTCTCCTCATTAGANNNTAACGAATGGGTGATTTCCCTAN"); Console.WriteLine($"- sequence length: {fastaSequence.Bases.Length:N0}"); Console.Write("- applying 2-bit compression... "); var referenceSequence = CreateReferenceSequence(fastaSequence); Console.WriteLine("finished."); Console.Write("- creating reference sequence file... "); CreateReferenceSequenceFile(GenomeAssembly.GRCh37, chromosomes, referenceSequence); long fileSize = new FileInfo(_outputCompressedPath).Length; Console.WriteLine($"{fileSize:N0} bytes"); return(ExitCodes.Success); }
public IEnumerable <DigestedPeptide> DigestSequence(string proteinSequence, int maxMissedCleavages, int?maxPeptideSequenceLength) { if (string.IsNullOrEmpty(proteinSequence)) { yield break; } FastaSequence fastaSequence; try { fastaSequence = new FastaSequence(@"name", @"description", new List <ProteinMetadata>(), proteinSequence); } catch (InvalidDataException) { // It's possible that the peptide sequence in the fasta file was bogus, in which case we just don't digest it. yield break; } var digestSettings = new DigestSettings(maxMissedCleavages, false); foreach (var digest in _enzyme.Digest(fastaSequence, digestSettings, maxPeptideSequenceLength)) { var digestedPeptide = new DigestedPeptide { Index = digest.Begin ?? 0, Sequence = digest.Target.Sequence }; yield return(digestedPeptide); } }
private static bool LooksLikeCrosslinkSequence(string str) { if (string.IsNullOrEmpty(str)) { return(false); } return(FastaSequence.StripModifications(str).IndexOf('-') >= 0); }
public static bool ValidateRow(object[] columns, IWin32Window parent, int lineNumber, bool postiveTime) { if (columns.Length != 2) { MessageDlg.Show(parent, string.Format(Resources.PeptideGridViewDriver_ValidateRow_The_pasted_text_must_have_two_columns_)); return(false); } string seq = columns[COLUMN_SEQUENCE] as string; string time = columns[COLUMN_TIME] as string; string message = null; if (string.IsNullOrWhiteSpace(seq)) { message = string.Format(Resources.PeptideGridViewDriver_ValidateRow_Missing_peptide_sequence_on_line__0_, lineNumber); } else if (!FastaSequence.IsExSequence(seq)) { message = string.Format(Resources.PeptideGridViewDriver_ValidateRow_The_text__0__is_not_a_valid_peptide_sequence_on_line__1_, seq, lineNumber); } else { try { columns[COLUMN_SEQUENCE] = SequenceMassCalc.NormalizeModifiedSequence(seq); } catch (Exception x) { message = x.Message; } if (message == null) { double dTime; if (string.IsNullOrWhiteSpace(time)) { message = string.Format(Resources.PeptideGridViewDriver_ValidateRow_Missing_value_on_line__0_, lineNumber); } else if (!double.TryParse(time, out dTime)) { message = string.Format(Resources.PeptideGridViewDriver_ValidateRow_Invalid_decimal_number_format__0__on_line__1_, time, lineNumber); } else if (postiveTime && dTime <= 0) { message = string.Format(Resources.PeptideGridViewDriver_ValidateRow_The_time__0__must_be_greater_than_zero_on_line__1_, time, lineNumber); } else { return(true); } } } MessageDlg.Show(parent, message); return(false); }
// find matches using the background proteome public void UseBackgroundProteome() { if (_parent.Document.Settings.PeptideSettings.BackgroundProteome.Equals(BackgroundProteome.NONE)) { MessageDlg.Show(this, Resources.AssociateProteinsDlg_UseBackgroundProteome_No_background_proteome_defined); return; } _isFasta = false; _fileName = _parent.Document.Settings.PeptideSettings.BackgroundProteome.DatabasePath; checkBoxListMatches.Items.Clear(); BackgroundProteome proteome = _parent.Document.Settings.PeptideSettings.BackgroundProteome; var proteinAssociations = new List <KeyValuePair <FastaSequence, List <PeptideDocNode> > >(); var peptidesForMatching = ListPeptidesForMatching(); IDictionary <String, List <Protein> > proteinsWithSequences = null; using (var longWaitDlg = new LongWaitDlg()) { longWaitDlg.PerformWork(this, 1000, longWaitBroker => { using (var proteomeDb = proteome.OpenProteomeDb(longWaitBroker.CancellationToken)) { proteinsWithSequences = proteomeDb.GetDigestion() .GetProteinsWithSequences(peptidesForMatching.Select(pep => pep.Peptide.Target.Sequence)); } }); } if (proteinsWithSequences == null) { return; } HashSet <String> processedProteinSequence = new HashSet <string>(); foreach (var entry in proteinsWithSequences) { foreach (var protein in entry.Value) { if (!processedProteinSequence.Add(protein.Sequence)) { continue; } var matches = peptidesForMatching.Where(pep => protein.Sequence.Contains(pep.Peptide.Target.Sequence)).ToList(); if (matches.Count == 0) { continue; } FastaSequence fastaSequence = proteome.MakeFastaSequence(protein); if (fastaSequence != null) { proteinAssociations.Add(new KeyValuePair <FastaSequence, List <PeptideDocNode> >(fastaSequence, matches)); } } } SetCheckBoxListItems(proteinAssociations, Resources.AssociateProteinsDlg_UseBackgroundProteome_No_matches_were_found_using_the_background_proteome_); }
public IEnumerable <Peptide> Digest(FastaSequence fastaSeq, DigestSettings settings) { Regex regex = new Regex(Regex); int begin = 0; int len = fastaSeq.Sequence.Length; while (begin < len) { int end = begin; int endFirst = begin; int missed = 0; do { string sequence = fastaSeq.Sequence; Match m = regex.Match(sequence, end); end = (m.Success ? m.Index + 1 : len); // Save the end of the first cleavage if (missed == 0) { endFirst = end; } // Deal with 'ragged ends', or cleavages one amino acid apart // i.e. KR, RR, etc. for trypsin if (settings.ExcludeRaggedEnds && end < len) { Match mNext = regex.Match(sequence, end); if (mNext.Success && mNext.Index == end) { // If there are no missed cleavages, then move the // begin index to the next cleavage point that is // not part of a run. if (missed == 0) { endFirst = GetDiscontiguousCleavageIndex(regex, mNext, sequence); } break; } } // Single amino acid peptides have no fragment ions. int count = end - begin; if (count > 1 && sequence.IndexOfAny(new[] { '*', '-' }, begin, count) == -1) // Not L10N { yield return(new Peptide(fastaSeq, sequence.Substring(begin, end - begin), begin, end, missed)); } // Increment missed cleavages for next loop. missed++; }while (end < len && missed <= settings.MaxMissedCleavages); begin = endFirst; } }
/// <summary> /// Serializes the contents of a single <see cref="PeptideGroupDocNode"/> /// to XML. /// </summary> /// <param name="writer">The XML writer</param> /// <param name="node">The peptide group document node</param> private void WritePeptideGroupXml(XmlWriter writer, PeptideGroupDocNode node) { // save the identity info if (node.PeptideGroup.Name != null) { writer.WriteAttributeString(ATTR.name, node.PeptideGroup.Name); } if (node.PeptideGroup.Description != null) { writer.WriteAttributeString(ATTR.description, node.PeptideGroup.Description); } // save any overrides if ((node.ProteinMetadataOverrides.Name != null) && !Equals(node.ProteinMetadataOverrides.Name, node.PeptideGroup.Name)) { writer.WriteAttributeString(ATTR.label_name, node.ProteinMetadataOverrides.Name); } if ((node.ProteinMetadataOverrides.Description != null) && !Equals(node.ProteinMetadataOverrides.Description, node.PeptideGroup.Description)) { writer.WriteAttributeString(ATTR.label_description, node.ProteinMetadataOverrides.Description); } WriteProteinMetadataXML(writer, node.ProteinMetadataOverrides, true); // write the protein metadata, skipping the name and description we already wrote writer.WriteAttribute(ATTR.auto_manage_children, node.AutoManageChildren, true); writer.WriteAttribute(ATTR.decoy, node.IsDecoy); writer.WriteAttributeNullable(ATTR.decoy_match_proportion, node.ProportionDecoysMatch); // Write child elements WriteAnnotations(writer, node.Annotations); FastaSequence seq = node.PeptideGroup as FastaSequence; if (seq != null) { if (seq.Alternatives.Count > 0) { writer.WriteStartElement(EL.alternatives); foreach (ProteinMetadata alt in seq.Alternatives) { writer.WriteStartElement(EL.alternative_protein); WriteProteinMetadataXML(writer, alt, false); // don't skip name and description writer.WriteEndElement(); } writer.WriteEndElement(); } writer.WriteStartElement(EL.sequence); writer.WriteString(FormatProteinSequence(seq.Sequence)); writer.WriteEndElement(); } foreach (PeptideDocNode nodePeptide in node.Children) { WritePeptideXml(writer, nodePeptide); } }
public static string ValidateSequence(Target sequence) { if (sequence.IsEmpty || !sequence.IsProteomic) { return(Resources.MeasuredPeptide_ValidateSequence_A_modified_peptide_sequence_is_required_for_each_entry); } if (!FastaSequence.IsExSequence(sequence.Sequence)) { return(string.Format(Resources.MeasuredPeptide_ValidateSequence_The_sequence__0__is_not_a_valid_modified_peptide_sequence, sequence)); } return(null); }
public static string ValidateSequence(string sequence) { if (sequence == null) { return(Resources.ValidatingIonMobilityPeptide_ValidateSequence_A_modified_peptide_sequence_is_required_for_each_entry_); } if (!FastaSequence.IsExSequence(sequence)) { return(string.Format(Resources.ValidatingIonMobilityPeptide_ValidateSequence_The_sequence__0__is_not_a_valid_modified_peptide_sequence_, sequence)); } return(null); }
public static string ValidateSequence(string sequenceText) { if (string.IsNullOrWhiteSpace(sequenceText)) { return(Resources.LibraryGridViewDriver_ValidateSequence_Sequence_cannot_be_empty_); } if (!FastaSequence.IsExSequence(Transition.StripChargeIndicators(sequenceText, TransitionGroup.MIN_PRECURSOR_CHARGE, TransitionGroup.MAX_PRECURSOR_CHARGE))) { return(string.Format(Resources.EditOptimizationLibraryDlg_ValidateOptimizationList_The_value__0__is_not_a_valid_modified_peptide_sequence_, sequenceText)); } return(null); }
private bool ValidatePeptideList(IEnumerable <ValidatingIonMobilityPeptide> peptideList, string tableName) { foreach (ValidatingIonMobilityPeptide peptide in peptideList) { string seqModified = peptide.PeptideModSeq; // CONSIDER: Select the peptide row if (!FastaSequence.IsExSequence(seqModified)) { MessageDlg.Show(this, string.Format(Resources.EditIonMobilityLibraryDlg_ValidatePeptideList_The_value__0__is_not_a_valid_modified_peptide_sequence_, seqModified)); return(false); } } return(true); }
private static bool IsNotRagged(PeptideDocNode nodePeptide) { Peptide peptide = nodePeptide.Peptide; FastaSequence fastaSeq = peptide.FastaSequence; if (fastaSeq == null) { return(true); } int begin = peptide.Begin ?? 0; return((begin < 2 || "KR".IndexOf(fastaSeq.Sequence[begin - 2]) == -1) && "KR".IndexOf(peptide.NextAA) == -1); }
private static void CheckChrYPadding(IEnumerable <FastaSequence> fastaSequences) { FastaSequence chrY = fastaSequences.FirstOrDefault(s => s.Chromosome.UcscName == "chrY"); if (chrY == null) { return; } int numN = CountNs(chrY.Bases); if (numN > 33720001) { throw new InvalidDataException($"Found a large number of Ns ({numN}) in the Y chromosome. Are you sure the PAR region is unmasked?"); } }
public static string ValidateMeasuredDriftTimeCellValues(string[] values) { int tempInt; double tempDouble; if (values.Count() < 3) { return(Resources.MeasuredDriftTimeTable_ValidateMeasuredDriftTimeCellValues_The_pasted_text_must_have_three_columns_); } // Parse sequence var sequence = values[EditDriftTimePredictorDlg.COLUMN_SEQUENCE]; if (string.IsNullOrEmpty(sequence)) { return(Resources.MeasuredDriftTimeTable_ValidateMeasuredDriftTimeCellValues_A_modified_peptide_sequence_is_required_for_each_entry_); } if (!FastaSequence.IsExSequence(sequence)) { return(string.Format(Resources.MeasuredDriftTimeTable_ValidateMeasuredDriftTimeCellValues_The_sequence__0__is_not_a_valid_modified_peptide_sequence_, sequence)); } try { values[EditDriftTimePredictorDlg.COLUMN_SEQUENCE] = SequenceMassCalc.NormalizeModifiedSequence(sequence); } catch (Exception x) { return(x.Message); } // Parse charge if ((!int.TryParse(values[EditDriftTimePredictorDlg.COLUMN_CHARGE].Trim(), out tempInt)) || ValidateCharge(tempInt) != null) { return(string.Format(Resources.EditDriftTimePredictorDlg_ValidateCharge_The_entry__0__is_not_a_valid_charge__Precursor_charges_must_be_integer_values_between_1_and__1__, values[EditDriftTimePredictorDlg.COLUMN_CHARGE].Trim(), TransitionGroup.MAX_PRECURSOR_CHARGE)); } // Parse drift time if (!double.TryParse(values[EditDriftTimePredictorDlg.COLUMN_DRIFT_TIME_MSEC].Trim(), out tempDouble)) { return(string.Format(Resources.MeasuredDriftTimeTable_ValidateMeasuredDriftTimeCellValues_The_value__0__is_not_a_valid_drift_time_, values[EditDriftTimePredictorDlg.COLUMN_DRIFT_TIME_MSEC].Trim())); } return(null); }
protected override void WriteTransition(TextWriter writer, XmlFastaSequence sequence, XmlPeptide peptide, XmlTransition transition) { char separator = TextUtil.GetCsvSeparator(_cultureInfo); writer.Write(transition.PrecursorMz.ToString(_cultureInfo)); writer.Write(separator); writer.Write(transition.ProductMz.ToString(_cultureInfo)); writer.Write(separator); if (MethodType == ExportMethodType.Standard) { writer.Write(Math.Round(DwellTime, 2).ToString(_cultureInfo)); } else { if (!peptide.PredictedRetentionTime.HasValue) { throw new InvalidOperationException(Resources.XmlThermoMassListExporter_WriteTransition_Attempt_to_write_scheduling_parameters_failed); } writer.Write(peptide.PredictedRetentionTime.Value.ToString(_cultureInfo)); } writer.Write(separator); // Write special ID for ABI software var fastaSequence = new FastaSequence(sequence.Name, sequence.Description, null, peptide.Sequence); var newPeptide = new Peptide(fastaSequence, peptide.Sequence, 0, peptide.Sequence.Length, peptide.MissedCleavages); var nodePep = new PeptideDocNode(newPeptide); string modifiedPepSequence = AbiMassListExporter.GetSequenceWithModsString(nodePep, _document.Settings); // Not L10N; string extPeptideId = string.Format("{0}.{1}.{2}.{3}", // Not L10N sequence.Name, modifiedPepSequence, GetTransitionName(transition), "light"); // Not L10N : file format writer.WriteDsvField(extPeptideId, separator); writer.Write(separator); writer.Write(Math.Round(transition.DeclusteringPotential ?? 0, 1).ToString(_cultureInfo)); writer.Write(separator); writer.Write(Math.Round(transition.CollisionEnergy, 1).ToString(_cultureInfo)); writer.WriteLine(); }
private void VerifyReportFile(string fileName, int rowCount, IList <string> columnNames, bool invariantFormat = false) { var formatProvider = invariantFormat ? CultureInfo.InvariantCulture : CultureInfo.CurrentCulture; string[] lines = File.ReadAllLines(fileName); Assert.AreEqual(rowCount, lines.Length - 1); string[] columnHeaderNames = lines[0].ParseCsvFields(); Assert.IsTrue(ArrayUtil.EqualsDeep(columnNames, columnHeaderNames)); for (int i = 1; i < lines.Length; i++) { string[] values = lines[i].ParseCsvFields(); for (int j = 0; j < columnHeaderNames.Length; j++) { string columnName = columnNames[j]; string value = values[j]; if (columnName.Equals("PeptideSequence")) { Assert.IsTrue(FastaSequence.IsSequence(value) || (TestSmallMolecules && value.StartsWith("zzz"))); } else if (columnName.StartsWith("Cv")) { Assert.IsTrue(TestSmallMolecules || value.EndsWith("%")); Assert.IsTrue(TestSmallMolecules || double.Parse(value.Substring(0, value.Length - 1), NumberStyles.Float, formatProvider) > 0); } else if (!columnName.Equals("ProteinName")) { double valueParsed; if (!double.TryParse(value, NumberStyles.Float, formatProvider, out valueParsed)) { if (!(TestSmallMolecules && value == TextUtil.EXCEL_NA)) { Assert.Fail("Failed parsing {0} as a double", value); } } else { Assert.IsTrue(valueParsed > 0); } } } } }
protected override void WriteTransition(TextWriter writer, XmlFastaSequence sequence, XmlPeptide peptide, XmlTransition transition) { char separator = TextUtil.GetCsvSeparator(_cultureInfo); writer.Write(transition.PrecursorMz.ToString(_cultureInfo)); writer.Write(separator); writer.Write(transition.ProductMz.ToString(_cultureInfo)); writer.Write(separator); if (MethodType == ExportMethodType.Standard) writer.Write(Math.Round(DwellTime, 2).ToString(_cultureInfo)); else { if (!peptide.PredictedRetentionTime.HasValue) throw new InvalidOperationException(Resources.XmlThermoMassListExporter_WriteTransition_Attempt_to_write_scheduling_parameters_failed); writer.Write(peptide.PredictedRetentionTime.Value.ToString(_cultureInfo)); } writer.Write(separator); // Write special ID for ABI software var fastaSequence = new FastaSequence(sequence.Name, sequence.Description, null, peptide.Sequence); var newPeptide = new Peptide(fastaSequence, peptide.Sequence, 0, peptide.Sequence.Length, peptide.MissedCleavages); var nodePep = new PeptideDocNode(newPeptide); string modifiedPepSequence = AbiMassListExporter.GetSequenceWithModsString(nodePep, _document.Settings); // Not L10N; string extPeptideId = string.Format("{0}.{1}.{2}.{3}", // Not L10N sequence.Name, modifiedPepSequence, GetTransitionName(transition), "light"); // Not L10N : file format writer.WriteDsvField(extPeptideId, separator); writer.Write(separator); writer.Write(Math.Round(transition.DeclusteringPotential ?? 0, 1).ToString(_cultureInfo)); writer.Write(separator); writer.Write(Math.Round(transition.CollisionEnergy, 1).ToString(_cultureInfo)); writer.WriteLine(); }
public void TestIsValidProteinSequenceChar() { // We only check the first 256 characters because the whole character range takes too long // to throw that many exceptions. for (int chValue = 1; chValue <= 256; chValue++) { char ch = (char)chValue; var sequence = new string(ch, 1); bool exceptionExpected; try { FastaSequence.ValidateSequence(sequence); exceptionExpected = false; } catch { exceptionExpected = true; } Assert.AreEqual(!exceptionExpected, WebEnabledFastaImporter.IsValidProteinSequenceChar(ch)); } }
private DbRefSpectra RefSpectrumFromPeaks(SpectrumMzInfo spectrum) { var peaksInfo = spectrum.SpectrumPeaks; var refSpectra = new DbRefSpectra { PeptideSeq = FastaSequence.StripModifications(spectrum.Key.Sequence), PrecursorMZ = spectrum.PrecursorMz, PrecursorCharge = spectrum.Key.Charge, PeptideModSeq = spectrum.Key.Sequence, Copies = 1, NumPeaks = (ushort)peaksInfo.Peaks.Length }; refSpectra.Peaks = new DbRefSpectraPeaks { RefSpectra = refSpectra, PeakIntensity = IntensitiesToBytes(peaksInfo.Peaks), PeakMZ = MZsToBytes(peaksInfo.Peaks) }; ModsFromModifiedSequence(refSpectra); return(refSpectra); }
public static CrosslinkLibraryKey ParseCrosslinkLibraryKey(string str, int charge) { List <PeptideLibraryKey> peptideSequences = new List <PeptideLibraryKey>(); List <CrosslinkLibraryKey.Crosslink> crosslinks = new List <CrosslinkLibraryKey.Crosslink>(); bool inCrosslinkers = false; int ich = 0; foreach (var token in Tokenize(str)) { if (token.StartsWith(@"[") && token.EndsWith(@"]")) { inCrosslinkers = true; } if (inCrosslinkers) { crosslinks.Add(ParseCrosslink(token, ich)); } else { string sequence = token; if (sequence.EndsWith(@"-")) { sequence = sequence.Substring(sequence.Length - 1); } if (!FastaSequence.IsExSequence(sequence)) { throw CommonException.Create(new ParseExceptionDetail(Resources.CrosslinkSequenceParser_ParseCrosslinkLibraryKey_Invalid_peptide_sequence, ich)); } peptideSequences.Add(new PeptideLibraryKey(sequence, 0)); } ich += token.Length; } return(new CrosslinkLibraryKey(peptideSequences, crosslinks, charge)); }
public void TestSerializePeptides() { var srmDocument = new SrmDocument(SrmSettingsList.GetDefault()); string strProteinSequence = string.Join(string.Empty, "MSLSSKLSVQDLDLKDKRVFIRVDFNVPLDGKKITSNQRIVAALPTIKYVLEHHPRYVVL", "ASHLGRPNGERNEKYSLAPVAKELQSLLGKDVTFLNDCVGPEVEAAVKASAPGSVILLEN", "LRYHIEEEGSRKVDGQKVKASKEDVQKFRHELSSLADVYINDAFGTAHRAHSSMVGFDLP", "QRAAGFLLEKELKYFGKALENPTRPFLAILGGAKVADKIQLIDNLLDKVDSIIIGGGMAF", "TFKKVLENTEIGDSIFDKAGAEIVPKLMEKAKAKGVEVVLPVDFIIADAFSADANTKTVT", "DKEGIPAGWQGLDNGPESRKLFAATVAKAKTIVWNGPPGVFEFEKFAAGTKALLDEVVKS", "SAAGNTVIIGGGDTATVAKKYGVTDKISHVSTGGGASLELLEGKELPGVAFLSEKK"); var fastaSequence = new FastaSequence("YCR012W", "PGK1", null, strProteinSequence); var peptideGroup = new PeptideGroupDocNode(fastaSequence, fastaSequence.Name, fastaSequence.Description, new PeptideDocNode[0]); Assert.AreEqual(true, peptideGroup.AutoManageChildren); peptideGroup = peptideGroup.ChangeSettings(srmDocument.Settings, SrmSettingsDiff.ALL); srmDocument = (SrmDocument)srmDocument.ChangeChildren(new DocNode[] { peptideGroup }); Assert.AreNotEqual(0, srmDocument.PeptideCount); Assert.AreNotEqual(0, srmDocument.MoleculeTransitionCount); Assert.IsFalse(CompactFormatOption.NEVER.UseCompactFormat(srmDocument)); Assert.IsTrue(CompactFormatOption.ALWAYS.UseCompactFormat(srmDocument)); VerifyRoundTrips(srmDocument); VerifyRoundTrips(AddSmallMolecules(srmDocument)); }
private bool TryMakePeptide(out Peptide peptide) { peptide = null; if (cbxLooplink.Checked) { return(true); } var messageBoxHelper = new MessageBoxHelper(this); var peptideSequence = tbxPeptideSequence.Text.Trim(); if (string.IsNullOrEmpty(peptideSequence)) { messageBoxHelper.ShowTextBoxError(tbxPeptideSequence, Resources.PasteDlg_ListPeptideSequences_The_peptide_sequence_cannot_be_blank); return(false); } if (!FastaSequence.IsExSequence(peptideSequence)) { messageBoxHelper.ShowTextBoxError(tbxPeptideSequence, Resources.PasteDlg_ListPeptideSequences_This_peptide_sequence_contains_invalid_characters); return(false); } peptide = new Peptide(peptideSequence); return(true); }
public IEnumerable<DigestedPeptide> Digest(Protein protein) { if (string.IsNullOrEmpty(protein.Sequence)) { yield break; } FastaSequence fastaSequence; try { fastaSequence = new FastaSequence("name", "description", new List<ProteinMetadata>(), protein.Sequence); // Not L10N } catch (InvalidDataException) { // It's possible that the peptide sequence in the fasta file was bogus, in which case we just don't digest it. yield break; } DigestSettings digestSettings = new DigestSettings(6, false); foreach (var digest in _enzyme.Digest(fastaSequence, digestSettings)) { var digestedPeptide = new DigestedPeptide { Index = digest.Begin ?? 0, Sequence = digest.Sequence }; yield return digestedPeptide; } }
public void OkDialog() { var reader = new StringReader(PeptidesText); var invalidLines = new List <string>(); var notFoundLines = new List <string>(); var acceptedPeptides = new List <LibraryKey>(); var peptideSequences = GetPeptideSequences(); string line; while ((line = reader.ReadLine()) != null) { line = line.Trim(); if (string.IsNullOrEmpty(line)) { continue; } int foundAt; var charge = Transition.GetChargeFromIndicator(line, TransitionGroup.MIN_PRECURSOR_CHARGE, TransitionGroup.MAX_PRECURSOR_CHARGE, out foundAt); if (!charge.IsEmpty) { line = line.Substring(0, foundAt); } Target target; try { // CONSIDER(bspratt) small molecule equivalent? if (!FastaSequence.IsExSequence(line)) { invalidLines.Add(line); continue; } line = SequenceMassCalc.NormalizeModifiedSequence(line); target = new Target(line); } catch (Exception) { invalidLines.Add(line); continue; } if (!peptideSequences.ContainsKey(target)) { notFoundLines.Add(line); } else { acceptedPeptides.Add(new LibKey(target, charge).LibraryKey); } } if (invalidLines.Count > 0) { if (invalidLines.Count == 1) { MessageDlg.Show(this, string.Format(Resources.RefineListDlg_OkDialog_The_sequence__0__is_not_a_valid_peptide, invalidLines[0])); } else { MessageDlg.Show(this, TextUtil.LineSeparate(Resources.RefineListDlg_OkDialog_The_following_sequences_are_not_valid_peptides, string.Empty, TextUtil.LineSeparate(invalidLines))); } return; } if (acceptedPeptides.Count == 0) { MessageDlg.Show(this, Resources.RefineListDlg_OkDialog_None_of_the_specified_peptides_are_in_the_document); return; } if (notFoundLines.Count > 0) { string message; if (notFoundLines.Count == 1) { message = string.Format(Resources.RefineListDlg_OkDialog_The_peptide__0__is_not_in_the_document_Do_you_want_to_continue, notFoundLines[0]); } else if (notFoundLines.Count < 15) { message = TextUtil.LineSeparate(Resources.RefineListDlg_OkDialog_The_following_peptides_are_not_in_the_document, string.Empty, TextUtil.LineSeparate(notFoundLines), string.Empty, Resources.RefineListDlg_OkDialog_Do_you_want_to_continue); } else { message = string.Format(Resources.RefineListDlg_OkDialog_Of_the_specified__0__peptides__1__are_not_in_the_document_Do_you_want_to_continue, notFoundLines.Count + acceptedPeptides.Count, notFoundLines.Count); } if (MultiButtonMsgDlg.Show(this, message, MultiButtonMsgDlg.BUTTON_OK) != DialogResult.OK) { return; } } AcceptedPeptides = acceptedPeptides.ToArray(); DialogResult = DialogResult.OK; }
public static string ValidateMeasuredDriftTimeCellValues(string[] values) { Adduct tempAdduct; double tempDouble; if (values.Length < 3) { return(Resources.MeasuredDriftTimeTable_ValidateMeasuredDriftTimeCellValues_The_pasted_text_must_have_three_columns_); } // Parse sequence var sequence = values[EditDriftTimePredictorDlg.COLUMN_SEQUENCE]; if (string.IsNullOrEmpty(sequence)) { return(Resources.MeasuredDriftTimeTable_ValidateMeasuredDriftTimeCellValues_A_modified_peptide_sequence_is_required_for_each_entry_); } if (!FastaSequence.IsExSequence(sequence)) { return(string.Format(Resources.MeasuredDriftTimeTable_ValidateMeasuredDriftTimeCellValues_The_sequence__0__is_not_a_valid_modified_peptide_sequence_, sequence)); } try { values[EditDriftTimePredictorDlg.COLUMN_SEQUENCE] = SequenceMassCalc.NormalizeModifiedSequence(sequence); } catch (Exception x) { return(x.Message); } // Parse charge if ((!Adduct.TryParse(values[EditDriftTimePredictorDlg.COLUMN_CHARGE].Trim(), out tempAdduct)) || ValidateCharge(tempAdduct) != null) { return(string.Format(Resources.EditDriftTimePredictorDlg_ValidateCharge_The_entry__0__is_not_a_valid_charge__Precursor_charges_must_be_integer_values_between_1_and__1__, values[EditDriftTimePredictorDlg.COLUMN_CHARGE].Trim(), TransitionGroup.MAX_PRECURSOR_CHARGE)); } // Parse drift time if (!double.TryParse(values[EditDriftTimePredictorDlg.COLUMN_ION_MOBILITY].Trim(), out tempDouble)) { return(string.Format(Resources.MeasuredDriftTimeTable_ValidateMeasuredDriftTimeCellValues_The_value__0__is_not_a_valid_drift_time_, values[EditDriftTimePredictorDlg.COLUMN_ION_MOBILITY].Trim())); } if (values.Length > EditDriftTimePredictorDlg.COLUMN_CCS) { // Parse CCS, if any if (!string.IsNullOrEmpty(values[EditDriftTimePredictorDlg.COLUMN_CCS]) && !double.TryParse(values[EditDriftTimePredictorDlg.COLUMN_CCS].Trim(), out tempDouble)) { return(string.Format(Resources.MeasuredDriftTimeTable_ValidateMeasuredDriftTimeCellValues_The_value__0__is_not_a_valid_collisional_cross_section_, values[EditDriftTimePredictorDlg.COLUMN_CCS].Trim())); } } if (values.Length > EditDriftTimePredictorDlg.COLUMN_HIGH_ENERGY_OFFSET) { // Parse high energy offset, if any if (!string.IsNullOrEmpty(values[EditDriftTimePredictorDlg.COLUMN_HIGH_ENERGY_OFFSET]) && !double.TryParse(values[EditDriftTimePredictorDlg.COLUMN_HIGH_ENERGY_OFFSET].Trim(), out tempDouble)) { return(string.Format(Resources.MeasuredDriftTimeTable_ValidateMeasuredDriftTimeCellValues_The_value__0__is_not_a_valid_high_energy_offset_, values[EditDriftTimePredictorDlg.COLUMN_HIGH_ENERGY_OFFSET].Trim())); } } return(null); }
protected override DataObject GetNodeData() { FastaSequence fastaSeq = DocNode.Id as FastaSequence; if (fastaSeq == null) { return(base.GetNodeData()); } DataObject data = new DataObject(); string fastaText = fastaSeq.FastaFileText; // If protein has been renamed in the UI if (!Equals(DocNode.Name, fastaSeq.Name)) { int oldNameLen = (fastaSeq.Name != null ? fastaSeq.Name.Length : 0); fastaText = @">" + DocNode.Name + fastaText.Substring(oldNameLen + 1); } data.SetData(DataFormats.Text, fastaText); var sb = new StringBuilder(); sb.Append(@"<b>").Append(DocNode.Name).Append(@"</b> "); sb.Append(@"<i>"); if (string.IsNullOrEmpty(DocNode.Description)) // CONSIDER bspratt - a more complete set of data here, maybe - accession etc { sb.AppendLine(@"<br/>"); } else { foreach (string desc in Descriptions) { sb.Append(desc).AppendLine(@"<br/>"); } } sb.Append(@"</i>"); using (var peptides = GetChoices(true).GetEnumerator()) { HashSet <DocNode> peptidesChosen = new HashSet <DocNode>(Chosen); PeptideDocNode nodePep = (PeptideDocNode)(peptides.MoveNext() ? peptides.Current : null); bool chosen = (nodePep != null && peptidesChosen.Contains(nodePep)); bool inPeptide = false; string aa = fastaSeq.Sequence; for (int i = 0; i < aa.Length; i++) { if (nodePep != null) { while (nodePep != null && i >= nodePep.Peptide.End) { nodePep = (PeptideDocNode)(peptides.MoveNext() ? peptides.Current : null); if (nodePep != null) { bool chosenNew = peptidesChosen.Contains(nodePep); // Need a new font tag, if the chosen state is changing if (chosenNew != chosen) { sb.Append(@"</font>"); inPeptide = false; } chosen = chosenNew; } } if (nodePep != null && i >= nodePep.Peptide.Begin) { if (!inPeptide) { sb.Append(chosen // ReSharper disable LocalizableElement ? "<font style=\"font-weight: bold; color: blue\">" : "<font style=\"font-weight: bold\">"); // ReSharper restore LocalizableElement inPeptide = true; } } else if (inPeptide) { sb.Append(@"</font>"); inPeptide = false; } } sb.Append(aa[i]); } if (inPeptide) { sb.Append(@"</font>"); } } data.SetData(DataFormats.Html, HtmlFragment.ClipBoardText(sb.ToString())); var transitionListExporter = new AbiMassListExporter(Document, DocNode); transitionListExporter.Export(null); data.SetData(DataFormats.CommaSeparatedValue, transitionListExporter.MemoryOutput[AbstractMassListExporter.MEMORY_KEY_ROOT].ToString()); return(data); }
public override Size RenderTip(Graphics g, Size sizeMax, bool draw) { var sizeInitial = base.RenderTip(g, sizeMax, draw); if (ShowAnnotationTipOnly) { return(sizeInitial); } g.TranslateTransform(0, sizeInitial.Height); FastaSequence fastaSeq = DocNode.Id as FastaSequence; var tableDetails = new TableDesc(); using (RenderTools rt = new RenderTools()) { SizeF sizeX80 = g.MeasureString(X80, rt.FontNormal); float widthLine = sizeX80.Width; float heightLine = sizeX80.Height; float heightMax = sizeMax.Height; tableDetails.AddDetailRow(Resources.PeptideGroupTreeNode_RenderTip_Name, DocNode.Name, rt); // If current name isn't the original, show that. if (DocNode.PeptideGroup.Name != null && !Equals(DocNode.Name, DocNode.PeptideGroup.Name)) { tableDetails.AddDetailRow(Resources.PeptideGroupTreeNode_RenderTip_Original_Name, DocNode.OriginalName, rt); } if (!String.IsNullOrEmpty(DocNode.ProteinMetadata.Accession)) { tableDetails.AddDetailRow(Resources.PeptideGroupTreeNode_RenderTip_Accession, DocNode.ProteinMetadata.Accession, rt); } if (!String.IsNullOrEmpty(DocNode.ProteinMetadata.PreferredName)) { tableDetails.AddDetailRow(Resources.PeptideGroupTreeNode_RenderTip_Preferred_Name, DocNode.ProteinMetadata.PreferredName, rt); } if (!String.IsNullOrEmpty(DocNode.ProteinMetadata.Gene)) { tableDetails.AddDetailRow(Resources.PeptideGroupTreeNode_RenderTip_Gene, DocNode.ProteinMetadata.Gene, rt); } if (!String.IsNullOrEmpty(DocNode.ProteinMetadata.Species)) { tableDetails.AddDetailRow(Resources.PeptideGroupTreeNode_RenderTip_Species, DocNode.ProteinMetadata.Species, rt); } if (!String.IsNullOrEmpty(DocNode.ProteinMetadata.DisplaySearchHistory())) { tableDetails.AddDetailRow(Resources.PeptideGroupTreeNode_RenderTip_Searched, DocNode.ProteinMetadata.DisplaySearchHistory(), rt); } if (!String.IsNullOrEmpty(DocNode.ProteinMetadata.Description)) { tableDetails.AddDetailRowLineWrap(g, Resources.PeptideGroupTreeNode_RenderTip_Description, DocNode.ProteinMetadata.Description, rt); } if (DocNode.PeptideGroup.Description != null && !Equals(DocNode.Description, DocNode.PeptideGroup.Description)) { tableDetails.AddDetailRow(Resources.PeptideGroupTreeNode_RenderTip_Original_Description, DocNode.OriginalDescription, rt); } SizeF sizeDetails = tableDetails.CalcDimensions(g); sizeDetails.Height += TableDesc.TABLE_SPACING; // Spacing between details and fragments float heightTotal = sizeDetails.Height; widthLine = Math.Max(widthLine, sizeDetails.Width); if (draw) { tableDetails.Draw(g); } if (fastaSeq != null) { IList <DocNode> peptidesChoices = GetChoices(true).ToArray(); HashSet <DocNode> peptidesChosen = new HashSet <DocNode>(Chosen); // Make sure all chosen peptides get listed HashSet <DocNode> setChoices = new HashSet <DocNode>(peptidesChoices); setChoices.UnionWith(peptidesChosen); var arrayChoices = setChoices.ToArray(); Array.Sort(arrayChoices, (choice1, choice2) => PeptideFromChoice(choice1).Order - PeptideFromChoice(choice2).Order); peptidesChoices = arrayChoices; // Get the selected peptide, if there is one PeptideTreeNode nodePepTree = SequenceTree.GetNodeOfType <PeptideTreeNode>(); Peptide peptideSelected = (nodePepTree != null ? nodePepTree.DocNode.Peptide : null); int i = 0; string aa = fastaSeq.Sequence; const bool peptideList = false; while (i < aa.Length) { // If this is not the last possible line, just render it. if (heightTotal + heightLine * 2 <= heightMax) { i = RenderAALine(aa, peptideList, i, false, draw, peptidesChoices, peptidesChosen, peptideSelected, g, rt, heightTotal, widthLine); heightTotal += heightLine; } // If not drawing, then this is the last possible line, and // it will have content. else if (!draw) { heightTotal += heightLine; break; } // Otherwise, measure first, and then re-render, with an elipsis // if the full sequence cannot be shown. else { RenderAALine(aa, peptideList, i, false, false, peptidesChoices, peptidesChosen, peptideSelected, g, rt, heightTotal, widthLine); RenderAALine(aa, peptideList, i, i < aa.Length, true, peptidesChoices, peptidesChosen, peptideSelected, g, rt, heightTotal, widthLine); heightTotal += heightLine; break; } } } return(TipSize(Math.Max(widthLine, sizeInitial.Width), heightTotal + sizeInitial.Height)); } }
public IEnumerable<Peptide> Digest(FastaSequence fastaSeq, DigestSettings settings) { Regex regex = new Regex(Regex); int begin = 0; int len = fastaSeq.Sequence.Length; while (begin < len) { int end = begin; int endFirst = begin; int missed = 0; do { string sequence = fastaSeq.Sequence; Match m = regex.Match(sequence, end); end = (m.Success ? m.Index + 1 : len); // Save the end of the first cleavage if (missed == 0) endFirst = end; // Deal with 'ragged ends', or cleavages one amino acid apart // i.e. KR, RR, etc. for trypsin if (settings.ExcludeRaggedEnds && end < len) { Match mNext = regex.Match(sequence, end); if (mNext.Success && mNext.Index == end) { // If there are no missed cleavages, then move the // begin index to the next cleavage point that is // not part of a run. if (missed == 0) endFirst = GetDiscontiguousCleavageIndex(regex, mNext, sequence); break; } } // Single amino acid peptides have no fragment ions. int count = end - begin; if (count > 1 && sequence.IndexOfAny(new[] { '*', '-' }, begin, count) == -1) // Not L10N { yield return new Peptide(fastaSeq, sequence.Substring(begin, end - begin), begin, end, missed); } // Increment missed cleavages for next loop. missed++; } while (end < len && missed <= settings.MaxMissedCleavages); begin = endFirst; } }
private static Creation.ReferenceSequence CreateReferenceSequence(FastaSequence fastaSequence, List <Band> cytogeneticBands) { Band[] bands = cytogeneticBands.ToArray(); (byte[] buffer, MaskedEntry[] maskedEntries) = TwoBitCompressor.Compress(fastaSequence.Bases); return(new Creation.ReferenceSequence(buffer, maskedEntries, bands, _beginPosition - 1, fastaSequence.Bases.Length)); }
protected override void DoTest() { RunUI(() => SkylineWindow.OpenFile(TestFilesDir.GetTestPath("CE_Vantage_15mTorr_scheduled_mini_withMod.sky"))); WaitForGraphs(); RunUI(() => { SequenceTree sequenceTree = SkylineWindow.SequenceTree; // Test single node copy. sequenceTree.ExpandAll(); sequenceTree.KeysOverride = Keys.None; sequenceTree.SelectedNode = sequenceTree.Nodes[0]; SkylineWindow.Copy(); CheckCopiedNodes(0, 1); // Test multiple selection copy. sequenceTree.KeysOverride = Keys.Shift; sequenceTree.SelectedNode = sequenceTree.Nodes[1]; SkylineWindow.Copy(); // Test multiple selection disjoint, reverse order copy. CheckCopiedNodes(0, 1); Assert.AreSame(sequenceTree, SkylineWindow.SequenceTree); sequenceTree.KeysOverride = Keys.None; sequenceTree.SelectedNode = sequenceTree.Nodes[1].Nodes[0]; sequenceTree.KeysOverride = Keys.Control; sequenceTree.SelectedNode = sequenceTree.Nodes[0].Nodes[0]; SkylineWindow.Copy(); // After copying in reverse order, reselect the nodes in sorted order so we don't have to // sort them in the test code. sequenceTree.KeysOverride = Keys.None; sequenceTree.SelectedNode = sequenceTree.Nodes[0]; sequenceTree.SelectedNode = sequenceTree.Nodes[0].Nodes[0]; sequenceTree.KeysOverride = Keys.Control; sequenceTree.SelectedNode = sequenceTree.Nodes[1].Nodes[0]; Assert.AreSame(sequenceTree, SkylineWindow.SequenceTree); CheckCopiedNodes(1, 2); // Test no space between parent and descendents if immediate child is not selected. sequenceTree.KeysOverride = Keys.None; sequenceTree.SelectedNode = sequenceTree.Nodes[0]; sequenceTree.KeysOverride = Keys.Control; sequenceTree.SelectedNode = sequenceTree.Nodes[0].Nodes[0].Nodes[0].Nodes[0]; sequenceTree.SelectedNode = sequenceTree.Nodes[0].Nodes[0].Nodes[0].Nodes[2]; SkylineWindow.Copy(); CheckCopiedNodes(0, 1); // Test paste menu item enabled, copy menu item disabled when dummy node is selected. sequenceTree.KeysOverride = Keys.None; sequenceTree.SelectedNode = sequenceTree.Nodes[SkylineWindow.SequenceTree.Nodes.Count - 1]; Assert.IsFalse(SkylineWindow.CopyMenuItemEnabled(), "Copy menu should not be enabled"); Assert.IsTrue(SkylineWindow.PasteMenuItemEnabled()); // Test FASTA sequence copy HTML formatting sequenceTree.SelectedNode = sequenceTree.Nodes[0]; SkylineWindow.Copy(); string clipboardHtml = GetClipboardHtml(); Assert.AreEqual(4, Regex.Matches(clipboardHtml, "<font style=\"font-weight: bold").Count); Assert.AreEqual(4, Regex.Matches(clipboardHtml, "</font>").Count); Assert.AreEqual(1, Regex.Matches(clipboardHtml, "color: blue").Count); sequenceTree.SelectedNode = sequenceTree.Nodes[1]; SkylineWindow.Copy(); clipboardHtml = GetClipboardHtml(); Assert.AreEqual(19, Regex.Matches(clipboardHtml, "<font style=\"font-weight: bold").Count); Assert.AreEqual(19, Regex.Matches(clipboardHtml, "</font>").Count); Assert.AreEqual(2, Regex.Matches(clipboardHtml, "color: blue").Count); sequenceTree.SelectedNode = sequenceTree.Nodes[2]; SkylineWindow.Copy(); clipboardHtml = GetClipboardHtml(); Assert.AreEqual(18, Regex.Matches(clipboardHtml, "<font style=\"font-weight: bold").Count); Assert.AreEqual(18, Regex.Matches(clipboardHtml, "</font>").Count); Assert.AreEqual(2, Regex.Matches(clipboardHtml, "color: blue").Count); // Test clipboard HTML contains formatting for modified peptides. sequenceTree.SelectedNode = sequenceTree.Nodes[3].Nodes[0]; SkylineWindow.Copy(); clipboardHtml = GetClipboardHtml(); Assert.IsTrue(clipboardHtml.Contains("font") && clipboardHtml.Contains("color")); }); // Paste a protein list var document = WaitForProteinMetadataBackgroundLoaderCompletedUI(); RunUI(() => { SetClipboardText(PROTEINLIST_CLIPBOARD_TEXT); SkylineWindow.Paste(); }); var docPaste = WaitForDocumentChange(document); Assert.AreEqual(document.PeptideGroupCount + 3, docPaste.PeptideGroupCount); Assert.AreEqual("P23978", docPaste.PeptideGroups.Last().ProteinMetadata.Accession); // Did builtin IPI conversion work? // Paste an invalid protein list RunDlg <MessageDlg>(() => { SetClipboardText(PROTEINLIST_CLIPBOARD_TEXT.Replace("MDAL", "***")); SkylineWindow.Paste(); }, msgDlg => msgDlg.OkDialog()); Assert.AreSame(docPaste, WaitForProteinMetadataBackgroundLoaderCompletedUI()); // Test border case where protein/peptide/transition list contains a blank line // Should give generic error, not crash RunDlg <MessageDlg>(() => { SetClipboardText(PROTEIN_LIST_BAD_FORMAT); SkylineWindow.Paste(); }, msgDlg => { Assert.AreEqual(msgDlg.Message, Resources.CopyPasteTest_DoTest_Could_not_read_the_pasted_transition_list___Transition_list_must_be_in_separated_columns_and_cannot_contain_blank_lines_); msgDlg.OkDialog(); }); // Paste peptides const int precursorCharge = 2; List <Tuple <string, int> > peptidePaste = new List <Tuple <string, int> > { new Tuple <string, int>("FVEGLPINDFSR", 3), new Tuple <string, int>("FVEGLPINDFSR", 2), new Tuple <string, int>("FVEGLPINDFSR", 0), new Tuple <string, int>("DLNELQALIEAHFENR", 0), new Tuple <string, int>(string.Format("C[+{0:F01}]QPLELAGLGFAELQDLC[+{1:F01}]R", 57.0, 57.0), 3), new Tuple <string, int>("PEPTIDER", 5), new Tuple <string, int>("PEPTIDER", 15) }; var peptidePasteSb = new StringBuilder(); foreach (var pep in peptidePaste) { peptidePasteSb.AppendLine(pep.Item1 + Transition.GetChargeIndicator(pep.Item2)); } RunUI(() => { SkylineWindow.NewDocument(true); document = SkylineWindow.Document; document = document.ChangeSettings(document.Settings.ChangeTransitionFilter(f => f.ChangePrecursorCharges(new[] { precursorCharge }))); SetClipboardText(peptidePasteSb.ToString()); SkylineWindow.Paste(); }); document = WaitForDocumentChange(document); Assert.AreEqual(peptidePaste.Count, document.PeptideTransitionGroupCount); for (int i = 0; i < document.PeptideTransitionGroupCount; i++) { TransitionGroupDocNode transition = document.PeptideTransitionGroups.ElementAt(i); string seq = transition.TransitionGroup.Peptide.Sequence; int charge = transition.PrecursorCharge; Assert.AreEqual(FastaSequence.StripModifications(peptidePaste[i].Item1), seq); var pastedCharge = peptidePaste[i].Item2; Assert.AreEqual(pastedCharge != 0 ? pastedCharge : precursorCharge, charge); } // Undo paste RunUI(() => SkylineWindow.Undo()); document = WaitForDocumentChange(document); // Change precursor charges int[] precursorCharges = { 2, 3, 4 }; RunUI(() => SkylineWindow.ModifyDocument("Change precursor charges", doc => doc.ChangeSettings((document.Settings.ChangeTransitionFilter(f => f.ChangePrecursorCharges(precursorCharges)))))); document = WaitForDocumentChange(document); // Re-paste in peptides RunUI(() => SkylineWindow.Paste()); document = WaitForDocumentChange(document); int curTransitionGroup = 0; foreach (var peptide in peptidePaste) { if (peptide.Item2 > 0) { // Pasted peptides with a charge indicator should have a single precursor with the specified charge state TransitionGroupDocNode group = document.PeptideTransitionGroups.ElementAt(curTransitionGroup++); string seq = group.TransitionGroup.Peptide.Sequence; int charge = group.PrecursorCharge; Assert.AreEqual(FastaSequence.StripModifications(peptide.Item1), seq); var pastedCharge = peptide.Item2; Assert.AreEqual(pastedCharge, charge); } else { // Pasted peptides with no charge indicator should have a precursor for every charge state in transition filter settings for (int j = 0; j < precursorCharges.Count(); j++) { TransitionGroupDocNode group = document.PeptideTransitionGroups.ElementAt(curTransitionGroup++); string seq = group.TransitionGroup.Peptide.Sequence; int charge = group.PrecursorCharge; Assert.AreEqual(FastaSequence.StripModifications(peptide.Item1), seq); Assert.AreEqual(precursorCharges[j], charge); } } } Assert.AreEqual(curTransitionGroup, document.PeptideTransitionGroupCount); }