public void LoadProteins(List <QProtein> Proteins) { SQLiteCommand Select = new SQLiteCommand( "Select IPI, Desc, ipis, Name From Proteins Order by 1", con); SQLiteDataReader Reader = Select.ExecuteReader(); while (Reader.Read()) { QProtein Prot = new QProtein(); Prot.ipi = Reader[0].ToString(); Prot.Desc = Reader[1].ToString(); Prot.ipis = Utils.IPIStringtoList(Reader[2].ToString()); Prot.Name = Reader[3].ToString(); Prot.Peptides = new List <QPeptide>(); Proteins.Add(Prot); } }
abstract public ProteinPair GetProtPair(QProtein Prot, int Left, int Right);
public override ProteinPair GetProtPair(QProtein Prot, int Left, int Right) { return(null); }
//надеемся что они синхронизированы public double[] GetProtRatios(QProtein Prot, bool Errors) { double[,] MedianMatrix = new double[FileCount, FileCount]; double[,] SlopeMatrix = new double[FileCount, FileCount]; double[,] SlopeDeltas = new double[FileCount, FileCount]; int Index = GetProtIndex(Prot); for (int i = 0; i < FileCount; i++) { for (int j = 0; j < FileCount; j++) { MedianMatrix[i, j] = ProteinMedians[i, j, Index]; SlopeMatrix[i, j] = ProteinSlopes[i, j, Index]; SlopeDeltas[i, j] = ProteinDeltas[i, j, Index]; } } double[,] ErrorMatrix = null; double[,] FakeMatrix = null; double[] Res = SolveMatrix(MedianMatrix, ref FakeMatrix); if (!Errors) { return(Res); } double[] Slopes = SolveMatrix(SlopeMatrix, ref ErrorMatrix); double[] Errs = SolveMatrix(SlopeDeltas, ref FakeMatrix); double[] MErrs = new double[FileCount]; //обрабатываем матрицу ошибок матрицы for (int i = 0; i < FileCount; i++) { double AveX = 0.0; int Count = 0; for (int k = 0; k < FileCount; k++) { if (ErrorMatrix[i, k] != 0.0) { AveX += ErrorMatrix[i, k]; Count++; } } if (Count < 2) { MErrs[i] = 0.0; continue; } AveX = AveX / Count; double SumD = 0.0; for (int k = 0; k < FileCount; k++) { if (ErrorMatrix[i, k] != 0.0) //уточнить !! [i,k] или [k,i] { SumD += (ErrorMatrix[i, k] - AveX) * (ErrorMatrix[i, k] - AveX); } } MErrs[i] = (Math.Sqrt(SumD) / (Count - 1)) * alglib.studenttdistr.invstudenttdistribution(Count - 1, 0.833); } double[] ResErr = new double[FileCount * 3]; for (int i = 0; i < FileCount; i++) { ResErr[i] = Res[i]; } for (int i = 0; i < FileCount; i++) { ResErr[i + FileCount] = Slopes[i] * (1 + Errs[i] + MErrs[i]) - Res[i]; } for (int i = 0; i < FileCount; i++) { ResErr[i + FileCount + FileCount] = Res[i] - Slopes[i] * (1 - Errs[i] - MErrs[i]); } return(ResErr); }
public int GetProtIndex(QProtein Prot) { int Index = Proteins.BinarySearch(Prot, new QProtein.byIPI()); return(Index); }
static public void FillMSMSLists( ref List <QPeptide> Mascots, ref List <QPeptide> MSMSList, ref List <QProtein> Proteins, MascotParser mp) { Mascots = new List <QPeptide>(); MSMSList = new List <QPeptide>(); QPeptide data; int Best, i, j, k; SpectrabySeq comp = new SpectrabySeq(); mp.Spectra.Sort(comp); for (i = 0; i < mp.Spectra.Count; i++) { //если нет пептидов if (mp.Spectra[i].Peptides.Count == 0) { data = new QPeptide(mp, i); data.Case = "No peptides identified"; MSMSList.Add(data); continue; } //если у пептидов слишком маленький Score if (mp.Spectra[i].Peptides[0].Score < Convert.ToDouble(Settings.Default.MascotScore)) { data = new QPeptide(mp, i); data.Case = "Peptides identified under score limit"; MSMSList.Add(data); continue; } Best = i; if (Settings.Default.MascotScoreFiltering) { for (j = i + 1; j < mp.Spectra.Count; j++) { if (mp.Spectra[i].Peptides[0].Sequence != mp.Spectra[j].Peptides[0].Sequence) { break; } //определяем идентичность набора модификаций for (k = 0; k < mp.Spectra[i].Peptides[0].ModIndex.GetLength(0); k++) { if (mp.Spectra[i].Peptides[0].ModIndex[k] != mp.Spectra[j].Peptides[0].ModIndex[k]) { break; } } if (k < mp.Spectra[i].Peptides[0].ModIndex.GetLength(0) || mp.Spectra[i].Peptides[0].CModIndex != mp.Spectra[j].Peptides[0].CModIndex || mp.Spectra[i].Peptides[0].NModIndex != mp.Spectra[j].Peptides[0].NModIndex) { break; } //поиск лучшего по Score if (mp.Spectra[j].Peptides[0].Score > mp.Spectra[Best].Peptides[0].Score) { Best = j; } } //отмечаем нелучшие в списке всех MS/MS for (k = i; k < j; k++) { if (k != Best) { data = new QPeptide(mp, k); data.Case = string.Format("Not the best score ({0}) for peptide {1} (Max={2})", mp.Spectra[k].Peptides[0].Score, mp.Spectra[k].Peptides[0].Sequence, mp.Spectra[Best].Peptides[0].Score); MSMSList.Add(data); } } i = j - 1; } //только для лучшего по Score если пептид идентифицирован более одного раза data = new QPeptide(mp, Best); Mascots.Add(data); } //Фильтруем IPI //Спектр не может соответствовать нескольким IPI за исключением случая когда //набор спектров идентифицирующих один IPI является подмножеством (возможно полным) //спектров идентифицирующих другой IPI //собираем набор тех из них которые являются подмножествами других List <string> Processed = new List <string>(); //список в который откладываются List <string> ipiset = new List <string>(); //список всех IPI пептида кроме проверяемого List <string> NotDeps = new List <string>(); string[] dataexipis = null; foreach (QPeptide dataex in Mascots) //для каждого пептида { dataexipis = new string[dataex.IPIs.Count]; dataex.IPIs.CopyTo(dataexipis); foreach (string ipi in dataexipis) { if (!StringContains(ref Processed, ipi)) //если данный ipi еще не находится в списке обработанных { ipiset.Clear(); //составляем множество всех IPI пептида кроме проверяемого ipiset.AddRange(dataex.IPIs); StringRemove(ref ipiset, ipi); foreach (QPeptide chdata in Mascots) //составленный список будем соотносить с полным набором пептидов { if (dataex.MascotRT != chdata.MascotRT && StringContains(ref chdata.IPIs, ipi)) { //в этот момент мы установили что dataex и chdata имеют общий ipi foreach (string ipicheck in ipiset) { //здесь мы отбираем в Nodepts идентификаторы //которые не появляются вместе с ipi //отбор такого идентификатора в NoDepts означает что существует хотя бы один пептид // относящийся к ipi но не относящийся к этому идентификатору //и следовательно ipi не является зависимым от такого идентификатора if (!StringContains(ref chdata.IPIs, ipicheck) && !StringContains(ref NotDeps, ipicheck)) //если есть хотя бы один пептид с проверяемым IPI { NotDeps.Add(ipicheck); //не несущий какго-то из IPI начального списка //то целевой IPI не является зависимым от отсутствующего } } } } //если есть хотя бы один идентификатор который всегда встречается вместе с ipi //то в список Nodepts он никогда не попадет и неполнота списка Nodepts будет признаком //того что ipi зависит от другого идентификатора и должен быть исключен из списка //идентификаторов во всех пептидах if (ipiset.Count != NotDeps.Count) { foreach (QPeptide chdata in Mascots) { StringRemove(ref chdata.IPIs, ipi); } } else { Processed.Add(ipi); } NotDeps.Clear(); } } } iLog.RepProgress(50); //и теперь переносим только непротиворечивые List <QPeptide> OldMascots = Mascots; Mascots = new List <QPeptide>(); for (i = 0; i < OldMascots.Count; i++) { if (OldMascots[i].IPIs.Count == 1) { QPeptide remdata = OldMascots[i]; remdata.IPI = remdata.IPIs[0]; Mascots.Add(remdata); } else { string Mess = string.Format("This entry ambigously defined as part of {0} Proteins: ", OldMascots[i].IPIs.Count); for (j = 0; j < OldMascots[i].IPIs.Count; j++) { Mess = Mess + OldMascots[i].IPIs[j] + ", "; } Mess = Mess.Substring(0, Mess.Length - 2); OldMascots[i].Case = Mess; MSMSList.Add(OldMascots[i]); } } iLog.RepProgress(60); //теперь сортируем по белкам Mascots.Sort(new QPeptide.byIPIs()); //теперь фильтруем не набравшие достаточного количества пептидов iLog.RepProgress(70); QProtein Prot; Proteins = new List <QProtein>(); int Count = 0; string preIPI = ""; //!! здесь нет обработки последенего белка for (i = 0; i <= Mascots.Count; i++) { if (i < Mascots.Count && Mascots[i].IPI == preIPI) { Count++; } else { for (j = i - 1; i - j <= Count; j--) { QPeptide temp = Mascots[j]; temp.peptides = Count; Mascots[j] = temp; } if (Count >= Convert.ToInt32(Settings.Default.PeptperProt)) { Prot = new QProtein(); Prot.Peptides = new List <QPeptide>(); Prot.ipis = Mascots[i - 1].IPIs; Prot.ipi = Mascots[i - 1].IPI; Prot.Est = 0.0; for (j = i - 1; i - j <= Count; j--) { Prot.Peptides.Add(Mascots[j]); } //добываем из файла Маскот описания и имена белка for (j = 0; j < mp.Proteins.Count; j++) { if (mp.Proteins[j].Name == "\"" + Mascots[i - 1].IPI + "\"") { break; } } if (j < mp.Proteins.Count) { Prot.Name = mp.Proteins[j].Name; Prot.Desc = mp.Proteins[j].Descr; } else { Prot.Name = Prot.ipi; Prot.Desc = "This protein is not described in source .dat file. See initial FASTA file for protein description"; } Proteins.Add(Prot); } else { for (j = i - 1; i - j <= Count; j--) { Mascots[j].Case = string.Format("This entry belongs to \"{0}\" protein which have only {1} uniquely identified peptide(s)", Mascots[j].IPI, Count); MSMSList.Add(Mascots[j]); } } Count = 1; if (i < Mascots.Count) { preIPI = Mascots[i].IPI; } } } iLog.RepProgress(80); OldMascots = Mascots; Mascots = new List <QPeptide>(); for (i = 0; i < OldMascots.Count; i++) { if (OldMascots[i].peptides >= Convert.ToInt32(Settings.Default.PeptperProt)) { QPeptide remdata = OldMascots[i]; remdata.Case = string.Format("This entry belongs to \"{0}\" quntified protein", remdata.IPI); Mascots.Add(remdata); MSMSList.Add(remdata); } else { continue; } } iLog.RepProgress(90); //теперь сортируем по белкам и внутри них Mascots.Sort(new QPeptide.byMascotSN()); //и указываем теоретические отношения первых изотопов iLog.RepProgress(100); }
public override ProteinPair GetProtPair(QProtein Prot, int Left, int Right) { if (Right != RefNumber || Left > FileCount - 1) return null; QAlignment TargetAl = AlLine[Left]; for (int i = 0; i < TargetAl.Proteins.Count; i++ ){ if (TargetAl.Proteins[i].Protein == Prot){ return TargetAl.Proteins[i]; } } return null; }
public abstract ProteinPair GetProtPair(QProtein Prot, int Left, int Right);
//надеемся что они синхронизированы public double[] GetProtRatios(QProtein Prot,bool Errors) { double[,] MedianMatrix = new double[FileCount, FileCount]; double[,] SlopeMatrix = new double[FileCount, FileCount]; double[,] SlopeDeltas = new double[FileCount, FileCount]; int Index = GetProtIndex(Prot); for ( int i = 0 ; i < FileCount ; i++){ for ( int j = 0 ; j < FileCount ; j++){ MedianMatrix[i, j] = ProteinMedians[i,j,Index]; SlopeMatrix[i, j] = ProteinSlopes[i,j,Index]; SlopeDeltas[i, j] = ProteinDeltas[i,j,Index]; } } double[,] ErrorMatrix = null; double[,] FakeMatrix = null; double[] Res = SolveMatrix(MedianMatrix,ref FakeMatrix ); if (!Errors) return Res; double[] Slopes = SolveMatrix(SlopeMatrix,ref ErrorMatrix); double[] Errs = SolveMatrix(SlopeDeltas,ref FakeMatrix); double[] MErrs = new double[FileCount]; //обрабатываем матрицу ошибок матрицы for ( int i = 0 ; i < FileCount ; i++){ double AveX = 0.0; int Count = 0; for (int k = 0 ; k < FileCount ; k++){ if ( ErrorMatrix[i,k] != 0.0 ) { AveX += ErrorMatrix[i,k]; Count++; } } if (Count<2){ MErrs[i] = 0.0; continue; } AveX = AveX/Count; double SumD = 0.0; for (int k = 0 ; k < FileCount ; k++){ if ( ErrorMatrix[i,k] != 0.0 ) { //уточнить !! [i,k] или [k,i] SumD += (ErrorMatrix[i,k]-AveX)*(ErrorMatrix[i,k]-AveX); } } MErrs[i]= (Math.Sqrt(SumD)/(Count-1))*alglib.studenttdistr.invstudenttdistribution(Count-1,0.833); } double[] ResErr = new double[FileCount*3]; for (int i = 0 ; i < FileCount ; i++){ ResErr[i] = Res[i]; } for (int i = 0 ; i < FileCount ; i++){ ResErr[i+FileCount] = Slopes[i]*(1+Errs[i]+MErrs[i])-Res[i]; } for (int i = 0 ; i < FileCount ; i++){ ResErr[i+FileCount+FileCount] = Res[i]-Slopes[i]*(1-Errs[i]-MErrs[i]); } return ResErr; }
public override ProteinPair GetProtPair(QProtein Prot, int Left, int Right) { return null; }
public int GetProtIndex(QProtein Prot) { int Index=Proteins.BinarySearch(Prot, new QProtein.byIPI()); return Index; }
public void LoadProteins(List<QProtein> Proteins) { SQLiteCommand Select = new SQLiteCommand( "Select IPI, Desc, ipis, Name From Proteins Order by 1",con); SQLiteDataReader Reader = Select.ExecuteReader(); while(Reader.Read()){ QProtein Prot = new QProtein(); Prot.ipi = Reader[0].ToString(); Prot.Desc = Reader[1].ToString(); //Prot.ipis = Reader[2].ToString(); Prot.Name = Reader[3].ToString(); Prot.Peptides = new List<QPeptide>(); Proteins.Add(Prot); } }
static public bool FillMSMSLists( ref List <QPeptide> Mascots, ref List <QPeptide> MSMSList, ref List <QProtein> Proteins, StreamReader sr) { int LineCount = 0; //пока табов меньше пяти - это строки заголовка - отматываем их List <string> Tokens = new List <string>(); while (!sr.EndOfStream) { string str = sr.ReadLine(); LineCount++; Tokens = new List <string>(str.Split(new char[] { '\t' })); if (Tokens.Count > 3 && !Tokens.Contains("")) { break; } } if (sr.EndOfStream) { MessageBox.Show("Wrong text file format. No data found"); return(false); } //в верхний регистр и обрезать for (int i = 0; i < Tokens.Count; i++) { Tokens[i] = Tokens[i].ToUpper().Trim(); } //на выходе - заголовок таблицы int[] Indexes = new int[9]; //0 - SEQUENCE || ID - ID of feature Indexes[0] = Tokens.IndexOf("SEQUENCE") + Tokens.IndexOf("ID") + 1; //1 - MOD DESCR. || DESC - Description of feature (ID & Desc combines composite unique index of feature inside of group) – optional Indexes[1] = Tokens.IndexOf("MOD DESCR.") + Tokens.IndexOf("DESC") + 1; //2 - IPI || GROUP ID - ID of feature group (have to be unique) – if not defined – all the features will be treated separately Indexes[2] = Tokens.IndexOf("IPI") + Tokens.IndexOf("GROUP ID") + 1; //3 - IPI DESC || GROUP DESC - ID of feature group (have to be unique) – if not defined – all the features will be treated separately Indexes[3] = Tokens.IndexOf("IPI DESC") + Tokens.IndexOf("GROUP DESC") + 1; //4 - RT ORDER || ORDER - Average elution order (optional but desired) Indexes[4] = Tokens.IndexOf("RT ORDER") + Tokens.IndexOf("ORDER") + 1; //5 - RT APEX || RT - Elution time Indexes[5] = Tokens.IndexOf("RT APEX") + Tokens.IndexOf("RT") + 1; //6 - MZ MASCOT || MZ - Feature m/z Indexes[6] = Tokens.IndexOf("MZ MASCOT") + Tokens.IndexOf("MZ") + 1; //7 - CHARGE - Charge Indexes[7] = Tokens.IndexOf("CHARGE"); //8 - MASCOT SCORE || Score – optional Indexes[8] = Tokens.IndexOf("MASCOT SCORE") + Tokens.IndexOf("SCORE") + 1; //Check obligatory fields if (Indexes[0] < 0 || Indexes[5] < 0 || Indexes[6] < 0 || Indexes[7] < 0) { MessageBox.Show("File parsing error. Please, check input file for obligatory columns which are SEQUENCE|ID, RT APEX|RT, MZ MASCOT|MZ, CHARGE."); return(false); } Mascots = new List <QPeptide>(); int IPICount = 0; while (!sr.EndOfStream) { string str = sr.ReadLine(); LineCount++; Tokens = new List <string>(str.Split(new char[] { '\t' })); if (Tokens.Count <= 3) { continue; } try{ QPeptide P = new QPeptide(); P.MascotMZ = Convert.ToDouble(Tokens[Indexes[6]]); P.MascotRT = Convert.ToDouble(Tokens[Indexes[5]]); P.MascotScore = (Indexes[8] < 0)?Convert.ToDouble(Settings.Default.MascotScore):Convert.ToDouble(Tokens[Indexes[8]]); if (P.MascotScore < Convert.ToDouble(Settings.Default.MascotScore)) { continue; } P.MascotScan = (Indexes[4] < 0)?0:Convert.ToInt32(Tokens[Indexes[4]]); P.Charge = Convert.ToInt32(Tokens[Indexes[7]]); P.IPI = (Indexes[2] < 0)?(IPICount++).ToString():Tokens[Indexes[2]]; P.IPIs = new List <string>(); P.Sequence = Tokens[Indexes[0]]; P.ModDesk = (Indexes[1] < 0)?"":Tokens[Indexes[1]]; //временно помещаем описание белка в Case P.Case = (Indexes[3] < 0)?"":Tokens[Indexes[3]]; Mascots.Add(P); }catch (IndexOutOfRangeException e) { MessageBox.Show("File parsing error", "Check column consistency."); return(false); }catch { MessageBox.Show("File parsing error", "Check data format from string " + LineCount.ToString() + "."); return(false); } } Mascots.Sort(new QPeptide.byIPIs()); QProtein Prot; Proteins = new List <QProtein>(); //Теперь собираем белки string PrevIPI = ""; int PrevIPIInd = 0; for (int i = 0; i <= Mascots.Count; i++) { if (i == Mascots.Count || (Mascots[i].IPI != PrevIPI && PrevIPI != "")) { if (i - PrevIPIInd >= Convert.ToInt32(Settings.Default.PeptperProt)) { Prot = new QProtein(); Prot.ipi = PrevIPI; Prot.ipis = new List <string>(); Prot.Desc = Mascots[PrevIPIInd].Case; Prot.Peptides = new List <QPeptide>(); for (int j = PrevIPIInd; j < i; j++) { Mascots[j].PartOfProtein = Prot; Mascots[j].Case = ""; Prot.Peptides.Add(Mascots[j]); } Proteins.Add(Prot); } PrevIPIInd = i; } PrevIPI = i < Mascots.Count ? Mascots[i].IPI : ""; } //чистим Mascots от пептидов без белков и зодно ставим MascotOrder если его там не было if (Indexes[4] == -1) { Mascots.Sort(new QPeptide.byMascotRT()); } for (int i = Mascots.Count - 1; i >= 0; i--) { if (Indexes[4] == -1) { Mascots[i].MascotScan = i; } if (Mascots[i].PartOfProtein == null) { Mascots.RemoveAt(i); } } Mascots.Sort(new QPeptide.byIPIs()); MSMSList = Mascots; return(true); }