public static void testSoftware(List <TheoreticalProtein> database) { string[] pepRead = File.ReadAllLines(@"C:\Users\Zach Rolfs\Desktop\Chemistry\Smith Research\Fusion Peptides\Neo\tests\testPepListInput.txt"); int nr = pepRead.Count(); List <PSM> realPSMs = new List <PSM>(); foreach (string s in pepRead) { string[] sArray = s.Split('\t'); PSM tempPSM = new PSM(sArray[0], Convert.ToInt16(sArray[1]), Convert.ToDouble(sArray[2])); } using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Zach Rolfs\Desktop\Chemistry\Smith Research\Fusion Peptides\Neo\Results\testPepListOutput.txt")) { /* AlternativeSequences altSeq = new AlternativeSequences(new Neo(), new System.ComponentModel.BackgroundWorker()); * altSeq.readProteins(database); * foreach (string str in pepRead) * { * if (altSeq.foundParent(str, ParentInfo.terminal.C,new FusionCandidate(str))) * { * file.WriteLine(str + '\t' + "1"); * } * else * { * file.WriteLine(str + '\t' + "0"); * } * }*/ } }
private void Button1_Click(object sender, EventArgs e) { if (OpenFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { Index = 0; Array.Resize(ref PSM_Surface, OpenFileDialog1.FileNames.Length); for (int i = 0; i <= OpenFileDialog1.FileNames.Length - 1; i++) { PSM_Surface[i] = new PSM(); if (OpenFileDialog1.FilterIndex == 1) { PSM_Surface[i].LoadPSM(OpenFileDialog1.FileNames[i], CheckBox1.Checked); } else if (OpenFileDialog1.FilterIndex == 2) { PSM_Surface[i].LoadPTC(OpenFileDialog1.FileNames[i], CheckBox1.Checked); } else if (OpenFileDialog1.FilterIndex == 3) { PSM_Surface[i].LoadPSF(OpenFileDialog1.FileNames[i], CheckBox1.Checked); } } Label1.Text = (Index + 1).ToString() + @"\" + PSM_Surface.Length.ToString(); GlControl1.Invalidate(); } }
//public PlotModel display_heatMap() //{ // var model = new PlotModel(); // model.Title = "Cos Similarity"; // var linearAxis1 = new LinearAxis(); // linearAxis1.Position = AxisPosition.Bottom; // model.Axes.Add(linearAxis1); // var linearAxis2 = new LinearAxis(); // model.Axes.Add(linearAxis2); // return model; //} public PlotModel display_heatMap() { var model = new PlotModel(); model.Title = "Cos Similarity"; var linearColorAxis1 = new LinearColorAxis(); linearColorAxis1.HighColor = OxyColors.Gray; linearColorAxis1.LowColor = OxyColors.Black; linearColorAxis1.Position = AxisPosition.Right; model.Axes.Add(linearColorAxis1); var linearAxis1 = new LinearAxis(); linearAxis1.Position = AxisPosition.Bottom; linearAxis1.Minimum = Min; linearAxis1.Maximum = Max; model.Axes.Add(linearAxis1); var linearAxis2 = new LinearAxis(); linearAxis2.Minimum = Min; linearAxis2.Maximum = Max; model.Axes.Add(linearAxis2); var heatMapSeries1 = new HeatMapSeries(); heatMapSeries1.X0 = 0; heatMapSeries1.X1 = 1.0; heatMapSeries1.Y0 = 0; heatMapSeries1.Y1 = 1.0; heatMapSeries1.Interpolate = false; heatMapSeries1.Data = new Double[Scores.Count, Scores.Count]; for (int i = 0; i < Scores.Count; ++i) { for (int j = 0; j < Scores.Count; ++j) { heatMapSeries1.Data[i, j] = Scores[i][j]; } } model.Series.Add(heatMapSeries1); heatMapSeries1.MouseDown += (s, e) => { DataPoint point = model.Axes[1].InverseTransform(e.Position.X, e.Position.Y, model.Axes[2]); int x_index = (int)((point.X - this.Min) / this.Width); int y_index = (int)((point.Y - this.Min) / this.Width); if (x_index < 0 || x_index >= Ncs.Count || y_index < 0 || y_index >= Ncs.Count) { return; } string title1 = Ncs[x_index].get_title(); string title2 = Ncs[y_index].get_title(); int psm1_index = (int)Psm_hash[title1]; int psm2_index = (int)Psm_hash[title2]; PSM psm1 = MainW.psms[psm1_index]; PSM psm2 = MainW.psms[psm2_index]; PlotModel model0 = display_TwoMS2(psm1, psm2); Model_Window mw = new Model_Window(model0, psm2.Title + "-" + psm1.Title); mw.Show(); }; return(model); }
private static string GetScore(PSM psm, string strScoreName, string strValueIfMissing) { if (!psm.TryGetScore(strScoreName, out var strScoreValue)) { strScoreValue = strValueIfMissing; } return(strScoreValue); }
public LocalizedHit(PSM psm, PeptideIsoform isoform, PeptideIsoform secondIsoform, int numSDFs, int sdfs, int sdfs2, double pvalue, double ascore) { PSM = psm; LocalizedIsoform = isoform; SecondBestPeptideIsoform = secondIsoform; NumberOfSiteDeterminingFragments = numSDFs; BestPeptideSDFCount = sdfs; SecondBestPeptideSDFCount = sdfs2; PValue = pvalue; AScore = ascore; MatchDifference = isoform.SpectralMatch.Matches - secondIsoform.SpectralMatch.Matches; }
public PlotModel display_TwoMS2(PSM psm1, PSM psm2) { Spectra spec1 = null, spec2 = null; Peptide pep1 = null, pep2 = null; MainW.parse_PSM(psm1, ref spec1, ref pep1); MainW.parse_PSM(psm2, ref spec2, ref pep2); PlotModel model = new PlotModel(); LinearAxis x_axis = new LinearAxis(); x_axis.Position = AxisPosition.Bottom; x_axis.Maximum = (spec1.Peaks.Last().Mass > spec2.Peaks.Last().Mass ? spec1.Peaks.Last().Mass : spec2.Peaks.Last().Mass) + 50; x_axis.Minimum = (spec1.Peaks[0].Mass < spec2.Peaks[0].Mass ? spec1.Peaks[0].Mass : spec2.Peaks[0].Mass) - 50; x_axis.AbsoluteMaximum = x_axis.Maximum; x_axis.AbsoluteMinimum = x_axis.Minimum; x_axis.PositionAtZeroCrossing = true; x_axis.TickStyle = TickStyle.Crossing; x_axis.IsAxisVisible = false; model.Axes.Add(x_axis); LinearAxis y_axis = new LinearAxis(); y_axis.Minimum = -100; y_axis.Maximum = 100; y_axis.IsPanEnabled = false; y_axis.IsZoomEnabled = false; y_axis.Title = psm2.Title + "-" + psm1.Title; model.Axes.Add(y_axis); LineSeries ls = new LineSeries(); ls.Color = OxyColors.Black; ls.LineStyle = LineStyle.Solid; ls.Points.Add(new DataPoint(x_axis.Minimum, 0)); ls.Points.Add(new DataPoint(x_axis.Maximum, 0)); model.Series.Add(ls); MainW.psm_help.Switch_PSM_Help(spec1, pep1); MainW.psm_help.Pep.Tag_Flag = int.Parse(psm1.Pep_flag); MainW.psm_help.Match_BY(); update_peaks(spec1, ref model); MainW.psm_help.Switch_PSM_Help(spec2, pep2); MainW.psm_help.Pep.Tag_Flag = int.Parse(psm2.Pep_flag); MainW.psm_help.Match_BY(); for (int i = 0; i < spec2.Peaks.Count; ++i) { spec2.Peaks[i].Intensity = -spec2.Peaks[i].Intensity; } update_peaks(spec2, ref model); return(model); }
private string GetScore(PSM currentPSM, string scoreColumnName, string alternativeName = "", string valueIfNotFound = "-1") { if (currentPSM.TryGetScore(scoreColumnName, out var value)) { return(value); } if (!string.IsNullOrEmpty(alternativeName) && currentPSM.TryGetScore(alternativeName, out var alternativeValue)) { return(alternativeValue); } return(valueIfNotFound); }
internal void AddReference(POI connectedEntity) { string value = PSM.ReadPropertyString(Owner, DriGraph.ConnectedEntities); //Avoid duplicate connections on con strings //Or filter the connections by their type //if (regex.IsMatch(value)) //{ // var matches = regex.Matches(value); // foreach (Match match in matches) // if (match.Groups["Handle"].Value == connectedEntity.Owner.Handle.ToString()) // //Do not add a reference if it already exists in the connection string // return; //} value += $"{(int)EndType}:{(int)connectedEntity.EndType}:{connectedEntity.Owner.Handle};"; PSM.WritePropertyString(DriGraph.ConnectedEntities, value); }
private static string GetCorrectedMassErrorPPM(PSM psm, out int intIsotopeError) { const double MASS_C13 = 1.00335483; double dblMassErrorPPM = 0; intIsotopeError = 0; if (double.TryParse(psm.MassErrorDa, out var dblDelM)) { // Examine dblDelM to determine which isotope was chosen if (dblDelM >= -0.5) { // This is the typical case while (dblDelM > 0.5) { dblDelM -= MASS_C13; intIsotopeError += 1; } } else { // This happens less often; but we'll still account for it // In this case, intCorrectionCount will be negative while (dblDelM < -0.5) { dblDelM += MASS_C13; intIsotopeError -= 1; } } dblMassErrorPPM = PeptideMassCalculator.MassToPPM(dblDelM, psm.PrecursorNeutralMass); } return(dblMassErrorPPM.ToString("0.0000")); }
static void ClientThreadProc(object obj) { System.Net.Sockets.Socket dllclientSock = null; byte[] buf = new byte[0x400 * 4]; try { dllclientSock = (System.Net.Sockets.Socket)obj; System.Net.Sockets.NetworkStream netstm = new System.Net.Sockets.NetworkStream(dllclientSock); for (bool run = true; run; ) { int ich = -1; try { ich = netstm.ReadByte(); } catch { } if (ich == -1) { break; } switch (ich) { case 'p': // Pin shared memory. { try { string smname = XContent.ReceiveXString(netstm, buf); IntPtr hf = INVALID_HANDLE_VALUE; IntPtr hmap = CreateFileMapping(hf, IntPtr.Zero, PAGE_READWRITE, 1, @"Global\" + smname); int lasterror = Marshal.GetLastWin32Error(); if (IntPtr.Zero == hmap) { if (8 == lasterror) { throw new Exception("Shared memory segment named '" + smname + "' cannot be allocated; CreateFileMapping failed with ERROR_NOT_ENOUGH_MEMORY", new OutOfMemoryException()); } throw new Exception("Shared memory segment named '" + smname + "' cannot be allocated; CreateFileMapping failed with GetLastWin32Error=" + lasterror); } if (ERROR_ALREADY_EXISTS != lasterror) { throw new Exception("Shared memory segment named '" + smname + "' not found"); } IntPtr ipview = MapViewOfFile(hmap, FILE_MAP_ALL_ACCESS, 0, 0, 0); if (IntPtr.Zero == ipview) { lasterror = Marshal.GetLastWin32Error(); CloseHandle(hmap); if (8 == lasterror) { throw new Exception("Shared memory segment named '" + smname + "' cannot be mapped into memory; MapViewOfFile failed with ERROR_NOT_ENOUGH_MEMORY", new OutOfMemoryException()); } throw new Exception("Shared memory segment named '" + smname + "' cannot be mapped into memory; MapViewOfFile failed with GetLastWin32Error=" + lasterror); } PSM psm; psm.hmap = hmap; psm.ipview = ipview; psm.name = smname; lock (pins) { pins.Add(psm); } netstm.WriteByte((byte)'+'); } catch(Exception e) { try { netstm.WriteByte((byte)'-'); XContent.SendXContent(netstm, e.ToString()); } catch { throw new Exception("Unable to report exception to caller (pin shared memory)", e); } } } break; case 'u': // Unpin shared memory. { try { string smname = XContent.ReceiveXString(netstm, buf); bool found = false; PSM psm = new PSM(); lock (pins) { int ipsm = IndexOfPSM_unlocked(smname); if (-1 != ipsm) { psm = pins[ipsm]; pins.RemoveAt(ipsm); found = true; } } if (found) { UnmapViewOfFile(psm.ipview); CloseHandle(psm.hmap); netstm.WriteByte((byte)'+'); } else { netstm.WriteByte((byte)'-'); XContent.SendXContent(netstm, "Cannot unpin; shared memory segment not pinned: " + smname); } } catch (Exception e) { try { netstm.WriteByte((byte)'-'); XContent.SendXContent(netstm, e.ToString()); } catch { throw new Exception("Unable to report exception to caller (unpin shared memory)", e); } } } break; case 'c': // Close. run = false; break; } } netstm.Close(); dllclientSock.Close(); } catch (Exception e) { XLog.errorlog("ClientThreadProc exception: " + e.ToString()); try { dllclientSock.Close(); } catch (Exception e2) { } } }
static void ClientThreadProc(object obj) { System.Net.Sockets.Socket dllclientSock = null; byte[] buf = new byte[0x400 * 4]; try { dllclientSock = (System.Net.Sockets.Socket)obj; System.Net.Sockets.NetworkStream netstm = new System.Net.Sockets.NetworkStream(dllclientSock); for (bool run = true; run;) { int ich = -1; try { ich = netstm.ReadByte(); } catch { } if (ich == -1) { break; } switch (ich) { case 'p': // Pin shared memory. { try { string smname = XContent.ReceiveXString(netstm, buf); IntPtr hf = INVALID_HANDLE_VALUE; IntPtr hmap = CreateFileMapping(hf, IntPtr.Zero, PAGE_READWRITE, 1, @"Global\" + smname); int lasterror = Marshal.GetLastWin32Error(); if (IntPtr.Zero == hmap) { if (8 == lasterror) { throw new Exception("Shared memory segment named '" + smname + "' cannot be allocated; CreateFileMapping failed with ERROR_NOT_ENOUGH_MEMORY", new OutOfMemoryException()); } throw new Exception("Shared memory segment named '" + smname + "' cannot be allocated; CreateFileMapping failed with GetLastWin32Error=" + lasterror); } if (ERROR_ALREADY_EXISTS != lasterror) { throw new Exception("Shared memory segment named '" + smname + "' not found"); } IntPtr ipview = MapViewOfFile(hmap, FILE_MAP_ALL_ACCESS, 0, 0, 0); if (IntPtr.Zero == ipview) { lasterror = Marshal.GetLastWin32Error(); CloseHandle(hmap); if (8 == lasterror) { throw new Exception("Shared memory segment named '" + smname + "' cannot be mapped into memory; MapViewOfFile failed with ERROR_NOT_ENOUGH_MEMORY", new OutOfMemoryException()); } throw new Exception("Shared memory segment named '" + smname + "' cannot be mapped into memory; MapViewOfFile failed with GetLastWin32Error=" + lasterror); } PSM psm; psm.hmap = hmap; psm.ipview = ipview; psm.name = smname; lock (pins) { pins.Add(psm); } netstm.WriteByte((byte)'+'); } catch (Exception e) { try { netstm.WriteByte((byte)'-'); XContent.SendXContent(netstm, e.ToString()); } catch { throw new Exception("Unable to report exception to caller (pin shared memory)", e); } } } break; case 'u': // Unpin shared memory. { try { string smname = XContent.ReceiveXString(netstm, buf); bool found = false; PSM psm = new PSM(); lock (pins) { int ipsm = IndexOfPSM_unlocked(smname); if (-1 != ipsm) { psm = pins[ipsm]; pins.RemoveAt(ipsm); found = true; } } if (found) { UnmapViewOfFile(psm.ipview); CloseHandle(psm.hmap); netstm.WriteByte((byte)'+'); } else { netstm.WriteByte((byte)'-'); XContent.SendXContent(netstm, "Cannot unpin; shared memory segment not pinned: " + smname); } } catch (Exception e) { try { netstm.WriteByte((byte)'-'); XContent.SendXContent(netstm, e.ToString()); } catch { throw new Exception("Unable to report exception to caller (unpin shared memory)", e); } } } break; case 'c': // Close. run = false; break; } } netstm.Close(); dllclientSock.Close(); } catch (Exception e) { XLog.errorlog("ClientThreadProc exception: " + e.ToString()); try { dllclientSock.Close(); } catch (Exception e2) { } } }
public void Read(IList<Modification> fixedModifications, int numberOfTopHits = 1, bool higherScoresAreBetter = false) { _data.Clear(); bool first = true; using (CsvReader reader = new CsvReader(new StreamReader(FilePath), true)) { string[] headers = reader.GetFieldHeaders(); HasPPMInfo = headers.Contains("Precursor Mass Error (ppm)"); while (reader.ReadNextRecord()) { if (first) { RawFileName = reader["Filename/id"].Split('.')[0]; first = false; } int scanNumber = int.Parse(reader["Spectrum number"]); PSM psm = new PSM(scanNumber) {Score = double.Parse(reader["E-value"])}; SortedMaxSizedContainer<PSM> peptides; if (!_data.TryGetValue(scanNumber, out peptides)) { peptides = new SortedMaxSizedContainer<PSM>(numberOfTopHits); _data.Add(scanNumber, peptides); } if (!peptides.Add(psm)) continue; psm.FileName = reader["Filename/id"]; psm.Charge = int.Parse(reader["Charge"]); psm.IsDecoy = reader["Defline"].StartsWith("DECOY_"); if (HasPPMInfo) psm.PrecursorMassError = double.Parse(reader["Precursor Mass Error (ppm)"]); psm.SetSequenceAndMods(reader["Peptide"].ToUpper(), fixedModifications, reader["Mods"]); } } PeptideSpectralMatches.Clear(); foreach (SortedMaxSizedContainer<PSM> set in _data.Values) { PeptideSpectralMatches.AddRange(set); } }
/// <summary> /// Loads all the unique peptide sequences (L / I ambiguous) from the OMSSA csv files /// supplied. Keeps track of all the psms for those peptides as well. /// </summary> /// <param name="csvFiles">The OMSSA .csv Files to read the PSMs from</param> /// <returns>A Dictionary of all unique peptide sequences with values of all the PSMs</returns> private Dictionary<string, Peptide> GetAllUniquePeptides(IEnumerable<CsvFile> csvFiles) { Log("Reading in unique peptides sequences from all .csv files..."); Dictionary<string, Peptide> peptides = new Dictionary<string, Peptide>(1 << 16); Proteases = new HashSet<Protease>(); int psmCount = 0; // Loop over each input file and read its contents foreach (CsvFile csvfile in csvFiles) { // Keep a list of all the proteases used Proteases.Add(Protease.GetProtease(csvfile.Protease)); // Counter for the number of PSMs loaded in this csvfile int csvPsmCount = 0; string sequenceString = "Peptide"; string pvalueString = "P-value"; bool proteomeDiscover = false; // Open up the csvfile and read its contents, skipping the header using (CsvReader reader = new CsvReader(new StreamReader(csvfile.FilePath), true)) { if (reader.GetFieldHeaders().Contains("XCorr")) { sequenceString = "Sequence"; pvalueString = "PEP"; proteomeDiscover = true; } // Read each line of the csv while (reader.ReadNextRecord()) { // Remove leucine / isoleucine ambiguity string leuSeq = reader[sequenceString].ToUpper().Replace('I', 'L'); double rt = 0; int specNum = 0; if (proteomeDiscover) { if (ProteinsPerMinute) rt = double.Parse(reader["RT [min]"]); } else { specNum = int.Parse(reader["Spectrum number"]); if (ProteinsPerMinute) rt = double.Parse(omssaRTRegex.Match(reader["Filename/id"]).Groups[1].Value); } double pvalue = double.Parse(reader[pvalueString]); // Create a new peptide spectral match PSM psm = new PSM(csvfile, specNum, rt, pvalue); // Add to the list of the all the unique peptides Peptide realPep; if (peptides.TryGetValue(leuSeq, out realPep)) // Faster than contains key since you only try to hash once { realPep.PSMs.Add(psm); } else { realPep = new Peptide(leuSeq); realPep.PSMs.Add(psm); peptides.Add(leuSeq, realPep); // Check to see if the peptide was the biggest or smallest if (leuSeq.Length < _smallestPeptide) { _smallestPeptide = leuSeq.Length; } if (leuSeq.Length > _largestPeptide) { _largestPeptide = leuSeq.Length; } } // General psm counters; csvPsmCount++; } } // Total psms loaded psmCount += csvPsmCount; Log("{0:N0} PSMs were loaded from {1}", csvPsmCount, csvfile); } Log("{0:N0} unique peptides were found from the {1:N0} PSMs loaded ({2:F1}%). (I/L ambiguity removed)", peptides.Count, psmCount, 100.0 * ((double)peptides.Count / psmCount)); return peptides; }
private bool CheckPsm( PSM psm ) { if( psm.Peptide == null ) return false; return CheckPsm( psm.passThreshold, psm.Rank, psm.Confidence, psm.Score, psm.ScoreType ); }
private void LoadRelations( SortedList<string,string> SortedAccession, SortedList<string,Peptide> SortedPeptides) { if( m_mzid.Data.DataCollection.AnalysisData.SpectrumIdentificationList.Length != 1 ) throw new ApplicationException( "Multiple spectrum identification lists not supported" ); SortedList<string,PeptideEvidenceType> SortedEvidences = new SortedList<string, PeptideEvidenceType>(); foreach( PeptideEvidenceType evidence in m_mzid.Data.SequenceCollection.PeptideEvidence ) SortedEvidences.Add( evidence.id, evidence ); int SpectrumID = 1; int PsmID = 1; double score; string type; Peptide.ConfidenceType confidence; foreach( SpectrumIdentificationResultType idres in m_mzid.Data.DataCollection.AnalysisData.SpectrumIdentificationList[0].SpectrumIdentificationResult ) { Spectrum spectrum = new Spectrum(); spectrum.ID = SpectrumID++; spectrum.File = idres.spectraData_ref; spectrum.SpectrumID = idres.spectrumID; spectrum.Psm = new List<PSM>(); Spectra.Add(spectrum); foreach( SpectrumIdentificationItemType item in idres.SpectrumIdentificationItem ) { //Console.Out.WriteLine(item.id); GetPsmScore( item, out score, out type, out confidence ); PSM psm = new PSM(); psm.ID = PsmID++; psm.Charge = item.chargeState; psm.Mz = item.experimentalMassToCharge; psm.Rank = item.rank; psm.Score = score; psm.ScoreType = type; psm.Confidence = confidence; psm.passThreshold = item.passThreshold; psm.Spectrum = spectrum; spectrum.Psm.Add(psm); if( item.PeptideEvidenceRef == null ) continue; foreach( PeptideEvidenceRefType evref in item.PeptideEvidenceRef ) { //Console.Out.WriteLine(evref.peptideEvidence_ref); PeptideEvidenceType evidence = SortedEvidences[evref.peptideEvidence_ref]; Peptide pep = SortedPeptides[evidence.peptide_ref]; if( pep.Sequence == null || pep.Sequence.Length == 0 ) { // ProCon 0.9.348 bug //Notify( "Skiped peptide with empty sequence: " + pep.DBRef ); continue; } pep.Decoy = evidence.isDecoy; psm.Peptide = pep; //pep.Psm.Add(psm); Protein prot = m_SortedProteins[SortedAccession[evidence.dBSequence_ref]]; if( pep.Proteins.Contains(prot) ) continue; prot.Peptides.Add( pep ); pep.Proteins.Add( prot ); } } } }