Ejemplo n.º 1
0
 public static double GetRefIntensity(Peak[] peaks)
 {
     var intensities = peaks.Select(p => p.Intensity).ToArray();
     Array.Sort(intensities, 0, intensities.Length);
     var refIntensity = intensities[(int)(0.8750 * intensities.Length)];
     return refIntensity;
 }
Ejemplo n.º 2
0
        public double PearsonCorrelation(Peak[] spectrum1, Peak[] spectrum2,FilteredProteinMassBinning comparer)
        {
            
            var spec1Bar = 0d;
            var spec2Bar = 0d;

            spectrum1 = GuassianFilter(spectrum1, .5);
            spectrum2 = GuassianFilter(spectrum2, .5);
            var vectorLength = comparer.GetBinNumber(10000.0); 

            spec1Bar = spectrum1.Sum(x => x.Intensity)/vectorLength;
            spec2Bar = spectrum1.Sum(y => y.Intensity)/vectorLength;


            var intensityVector1 = ConvertToFullIntensityVector(spectrum1, vectorLength, comparer);
            var intensityVector2 = ConvertToFullIntensityVector(spectrum2, vectorLength, comparer);

            var cov = 0.0;
            var s1 = 0.0;
            var s2 = 0.0;

            for (var i = 0; i < vectorLength; i++)
            {
                var d1 = intensityVector1[i] - spec1Bar;
                var d2 = intensityVector2[i] - spec2Bar;
                cov += d1*d2;
                s1 += d1*d1;
                s2 += d2*d2;
            }

            if (s1 <= 0 || s2 <= 0) return 0;
            return cov < 0 ? 0f : cov/Math.Sqrt(s1*s2);
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Find intensity rank of ion in spectrum.
 /// </summary>
 /// <param name="ion">Ion to search for.</param>
 /// <param name="tolerance"></param>
 /// <returns>Intensity rank of ion. 1-based.</returns>
 public int RankIon(Ion ion, Tolerance tolerance)
 {
     var peak = _spectrum.FindPeak(ion.GetMonoIsotopicMz(), tolerance);
     int position;
     if (peak != null)
     {
         var searchPeak = new Peak(peak.Mz, peak.Intensity);
         position = Array.BinarySearch(Peaks, searchPeak, new IntensityComparer());
         position++;
     }
     else
     {
         position = -1;
     }
     return position;
 }
Ejemplo n.º 4
0
        public double RootMeanSquareDeviation(Peak[] spectrum1, Peak[] spectrum2, FilteredProteinMassBinning comparer)
        {

            spectrum1 = GuassianFilter(spectrum1, .5);
            spectrum2 = GuassianFilter(spectrum2, .5);
            var vectorLength = comparer.GetBinNumber(10000.0);
            var intensityVector1 = ConvertToFullIntensityVector(spectrum1, vectorLength, comparer);
            var intensityVector2 = ConvertToFullIntensityVector(spectrum2, vectorLength, comparer);
            var mean1 = spectrum1.Sum(p => p.Intensity)/spectrum1.Length;
            var mean2 = spectrum1.Sum(p => p.Intensity)/spectrum2.Length;

            var sum = 0d;
            for (int i = 0; i < vectorLength; i++)
            {
                var diff = intensityVector1[i] - intensityVector2[i];
                sum += diff*diff;
            }

            return Math.Sqrt(sum/vectorLength);
        }
Ejemplo n.º 5
0
        public double DotProduct(Peak[] spectrum1, Peak[] spectrum2, FilteredProteinMassBinning comparer)
        {

            spectrum1 = GuassianFilter(spectrum1,.5);
            spectrum2 = GuassianFilter(spectrum2,.5);
            var vectorLength = comparer.GetBinNumber(10000.0);
            var featureVector1 = ConvertToFullIntensityVector(spectrum1,vectorLength,comparer);
            var featureVector2 = ConvertToFullIntensityVector(spectrum2, vectorLength,comparer);

  
            var sum = 0d;
            for (int i = 0; i < vectorLength; i++)
            {
                sum += featureVector1[i]*featureVector2[i];
            }

            var norm1 = featureVector1.Sum(x => x*x);
            var norm2 = featureVector2.Sum(x => x * x);
            return sum/Math.Sqrt(norm1*norm2);
        }
Ejemplo n.º 6
0
        public DeconvolutedPeak(double mass, double intensity, int charge, double corr, double dist, Peak[] isotopePeaks = null) : base(mass, intensity)
        {
            Charge = charge;

            Corr = corr;
            Dist = dist;

            ObservedPeaks = isotopePeaks;
            //_isotopePeaks = new HashSet<Peak>();
            /*
            if (isotopePeaks == null)
            {
                SummedIntensity = intensity;
                return;
            }*/

            //SummedIntensity = 0;
            /*
            foreach (var peak in isotopePeaks.Where(peak => peak != null))
            {
                _isotopePeaks.Add(peak);
                SummedIntensity += peak.Intensity;
            }*/
        }
Ejemplo n.º 7
0
 public static double GetRefIntensity(Peak[] peaks)
 {
     return peaks.Sum(p => p.Intensity);
 }
Ejemplo n.º 8
0
 public override void Exclude(TimeSpan current_time, Peak precursor)
 {
     excluded_peaks[precursor] = current_time + exclusion_interval;
 }
    //        voronoiPresets.Add(new voronoiPresetData("Scattered Peaks", VoronoiType.Linear, 16, 8, 0.5f, 1.0f));
    //    voronoiPresets.Add(new voronoiPresetData("Rolling Hills", VoronoiType.Sine, 8, 8, 0.0f, 1.0f));
    //    voronoiPresets.Add(new voronoiPresetData("Jagged Mountains", VoronoiType.Linear, 32, 32, 0.5f, 1.0f));
    private float[,] generateVoronoi(ref float[,] heightMap, Vector2 arraySize, bool regenFlag)
    {
        int Tx = (int)arraySize.x;
        int Ty = (int)arraySize.y;
        // Create Voronoi set...
        ArrayList voronoiSet = new ArrayList();
        int i;
        int inc = 1;
        if (regenFlag)
            inc++;
        for (i = 0; i < voronoiCells; i += inc)
        {
            Peak newPeak = new Peak();
            int xCoord = (int)Mathf.Floor(UnityEngine.Random.value * Tx);
            int yCoord = (int)Mathf.Floor(UnityEngine.Random.value * Ty);
            float pointHeight = UnityEngine.Random.value;
            if (UnityEngine.Random.value > voronoiFeatures)
            {
                pointHeight = 0.0f;
            }
            newPeak.peakPoint = new Vector2(xCoord, yCoord);
            newPeak.peakHeight = pointHeight;
            voronoiSet.Add(newPeak);
        }
        int Mx;
        int My;
        float highestScore = 0.0f;
        for (My = 0; My < Ty; My += inc)
        {
            for (Mx = 0; Mx < Tx; Mx += inc)
            {
                ArrayList peakDistances = new ArrayList();
                try
                {
                    for (i = 0; i < voronoiCells; i += inc)
                    {
                        Peak peakI = (Peak)voronoiSet[i];
                        Vector2 peakPoint = peakI.peakPoint;
                        float distanceToPeak = Vector2.Distance(peakPoint, new Vector2(Mx, My));
                        PeakDistance newPeakDistance = new PeakDistance();
                        newPeakDistance.id = i;
                        newPeakDistance.dist = distanceToPeak;
                        peakDistances.Add(newPeakDistance);
                    }
                }
                catch (Exception) { }
                peakDistances.Sort();
                PeakDistance peakDistOne = (PeakDistance)peakDistances[0];
                PeakDistance peakDistTwo = (PeakDistance)peakDistances[1];
                int p1 = peakDistOne.id;
                float d1 = peakDistOne.dist;
                float d2 = peakDistTwo.dist;
                float scale = Mathf.Abs(d1 - d2) / ((Tx + Ty) / Mathf.Sqrt(voronoiCells));
                Peak peakOne = (Peak)voronoiSet[p1];
                float h1 = (float)peakOne.peakHeight;
                float hScore = h1 - Mathf.Abs(d1 / d2) * h1;
                float asRadians;
                switch (voronoiType)
                {
                    case VoronoiType.Linear:
                        // Nothing...
                        break;
                    case VoronoiType.Sine:
                        asRadians = hScore * Mathf.PI - Mathf.PI / 2;
                        hScore = 0.5f + Mathf.Sin(asRadians) / 2;
                        break;
                    case VoronoiType.Tangent:
                        asRadians = hScore * Mathf.PI / 2;
                        hScore = 0.5f + Mathf.Tan(asRadians) / 2;
                        break;
                }
                hScore = (hScore * scale * voronoiScale) + (hScore * (1.0f - voronoiScale));
                if (hScore < 0.0f)
                {
                    hScore = 0.0f;
                }
                else if (hScore > 1.0f)
                {
                    hScore = 1.0f;
                }
                heightMap[Mx, My] += hScore;
                if (hScore > highestScore)
                {
                    highestScore = hScore;
                }
                heightMap[Mx, My] = hScore + heightMap[Mx, My] < 1? heightMap[Mx, My] : 1;
                heightMap[Mx, My] *= mHeight;
            }

        }

        // Normalise...
        //for (My = 0; My < Ty; My++)
        //{
        //    for (Mx = 0; Mx < Tx; Mx++)
        //    {
        //        float normalisedHeight = heightMap[Mx, My] * (1.0f / highestScore);
        //        heightMap[Mx, My] = normalisedHeight;
        //    }
        //}
        return heightMap;
    }
Ejemplo n.º 10
0
 protected virtual void OnSelection(Peak v, IntensityInfo dp)
 {
     // No action
 }
Ejemplo n.º 11
0
 public Spectrum(ICollection<Peak> peaks, int scanNum)
 {
     Peaks = new Peak[peaks.Count];
     peaks.CopyTo(Peaks, 0);
     ScanNum = scanNum;
 }
Ejemplo n.º 12
0
 public abstract bool Is_Excluded(TimeSpan currentTime, Peak precursor);
Ejemplo n.º 13
0
        private void AddPeak(Dictionary <int, List <PeakEntry> > map, double maxPeakIntensity, string fileScan, Peak peak)
        {
            var mz = (int)(Math.Round(peak.Mz));

            List <PeakEntry> entries;

            if (!map.TryGetValue(mz, out entries))
            {
                entries = new List <PeakEntry>();
                map[mz] = entries;
            }

            var relativeIntensity = peak.Intensity / maxPeakIntensity;

            var       gap   = PrecursorUtils.ppm2mz(peak.Mz, options.ProductIonPPM);
            PeakEntry entry = new PeakEntry()
            {
                Ion    = new Peak(peak.Mz, peak.Intensity),
                FromMz = peak.Mz - gap,
                ToMz   = peak.Mz + gap
            };

            entry.Intensities.Add(new SourcePeak(fileScan, peak.Mz, relativeIntensity));
            entries.Add(entry);
        }
Ejemplo n.º 14
0
        //get pepSequence,source,scanID, write into a csv file.
        //have tons of information: theretical ion intensity, pep info, chargeLabel...
        public static void idpReader(string idpXMLFile, string mzMLFile, double TicCutoffPercentage, int z, int model)
        {
            //get the path and filename of output csv file:
            string fileName = Path.GetFileNameWithoutExtension(idpXMLFile);
            string filePath = Path.GetDirectoryName(idpXMLFile);
            string csvFile = Path.Combine(filePath, fileName) + "_" + z.ToString() + ".csv";

            IDPicker.Workspace workspace = new IDPicker.Workspace();
            Package.loadWorkspace(ref workspace, idpXMLFile);

            using (StreamWriter file = new StreamWriter(csvFile))
            {
                //TODO idOrIndex + "," + pepSequence + "," + pepBond + "," + AA + "," + bIons + "," + yIons;
                file.WriteLine("nativeID,pepSequence,bond,b1,b2,y1,y2");

                MSDataFile foo = new MSDataFile(mzMLFile);
                SpectrumList sl = foo.run.spectrumList;

                foreach (IDPicker.SourceGroupList.MapPair groupItr in workspace.groups)
                    foreach (IDPicker.SourceInfo source in groupItr.Value.getSources(true))
                        foreach (IDPicker.SpectrumList.MapPair sItr in source.spectra)
                        {

                            IDPicker.ResultInstance ri = sItr.Value.results[1];
                            IDPicker.VariantInfo vi = ri.info.peptides.Min;

                            string ss = vi.ToString() + "," + sItr.Value.id.source.name + "," + sItr.Value.nativeID;
                            bool boolCharge = sItr.Value.id.charge.Equals(z);
                            if (boolCharge)
                            {
                                string rawPepSequence = vi.ToString();
                                string pepSequence = vi.peptide.sequence;
                                int len = pepSequence.Length;

                                // Look up the index with nativeID
                                object idOrIndex = null;
                                if( sItr.Value.nativeID != null && sItr.Value.nativeID.Length > 0 )
                                    idOrIndex = sItr.Value.nativeID;
                                int spectrumIndex = sl.find(idOrIndex as string);
                                // Trust the local index, if the nativeID lookup fails
                                if( spectrumIndex >= sl.size() )
                                    spectrumIndex = sItr.Value.id.index;
                                // Bail of the loca index is larger than the spectrum list size
                                if( spectrumIndex >= sl.size() )
                                    throw new Exception( "Can't find spectrum associated with the index." );

                                //get base peak and TIC and converted to string
                                Spectrum spec1 = sl.spectrum(spectrumIndex, true);
                                MZIntensityPairList peaks = new MZIntensityPairList();
                                spec1.getMZIntensityPairs(ref peaks);
                                Set<Peak> peakList = new Set<Peak>();

                                //get base peak and TIC
                                double basePeakValue = 0;
                                double TICValue = 0;
                                CVParamList list = spec1.cvParams;
                                foreach (CVParam CVP in list)
                                {
                                    if (CVP.name == "base peak intensity")
                                    {
                                        basePeakValue = CVP.value;
                                    }
                                    if (CVP.name == "total ion current")
                                    {
                                        TICValue = CVP.value;
                                    }
                                }
                                string basePeak = basePeakValue.ToString();
                                string TIC = TICValue.ToString();

                                //very important. Surendra put them here
                                //to change those with modifications {} into a format
                                //that fragment method will accept.
                                string interpretation = vi.ToSimpleString();

                                Peptide peptide = new Peptide(interpretation, ModificationParsing.ModificationParsing_Auto, ModificationDelimiter.ModificationDelimiter_Brackets);

                                Fragmentation fragmentation = peptide.fragmentation(true, true);
                                //prepare the qualified peaklist
                                double intenThreshhold = 0;
                                int totalIntenClass = 0;

                                double[] intenArray = new double[peaks.Count];
                                //used during the foreach loop
                                int indexPeaks = 0;

                                //get all the peaks no matter how small they are
                                //then calculate the threshhold TIC
                                //test here
                                foreach (MZIntensityPair mzIntensity in peaks)
                                {
                                    //Peak p = new Peak(mzIntensity.mz, mzIntensity.intensity);
                                    //peakList.Add(p);
                                    intenArray[indexPeaks] = mzIntensity.intensity;
                                    indexPeaks++;
                                }
                                Array.Sort(intenArray);
                                Array.Reverse(intenArray, 0, peaks.Count);

                                //if currTIC>=cutoff, then break
                                double currTIC = 0;
                                double cutOffTIC = TicCutoffPercentage * TICValue;
                                foreach (double inten in intenArray)
                                {
                                    currTIC = currTIC + inten;
                                    if (currTIC < cutOffTIC)
                                    {
                                        intenThreshhold = inten;
                                        totalIntenClass++;
                                    }
                                    else break;
                                }

                                //then based on that, generate a new peaklist that contains only ABC peaks
                                //then calculate the intensity classes
                                foreach (MZIntensityPair mzIntensity in peaks)
                                {
                                    if (mzIntensity.intensity >= intenThreshhold)
                                    {
                                        //note 0 here. This is to tell people that the orbiorbi fragment charge is unknown.
                                        //the peaklist will be updated later.
                                        Peak p = new Peak(mzIntensity.mz, mzIntensity.intensity,0);
                                        peakList.Add(p);
                                    }
                                }
                                Console.WriteLine("nativeID: =============" + idOrIndex);
                                //update peaklist for charge states.
                                peakList = Package.chargeAssignment(peakList);
                                        //int ones = 0;
                                        //int twos = 0;
                                        //foreach (var peak in peakList)
                                        //{
                                        //    //Console.WriteLine(peak.fragmentCharge);
                                        //    if (peak.fragmentCharge == 1) ones++;
                                        //    else if (peak.fragmentCharge == 2) twos++;
                                        //}

                                        //Console.WriteLine("charge 1: " + ones);
                                        //Console.WriteLine("charge 2: " + twos);

                                //rowDic contains row information of each peptide bond
                                Dictionary<int, string> rowDic = new Dictionary<int, string>();
                                //intensityDic contains intensity information of fragment ions for each peptide bond
                                Dictionary<int, List<double>> intensityDic = new Dictionary<int, List<double>>();
                                //commonList contains the common intensities
                                List<double> duplicateList = new List<double>();

                                //call the method
                                List<double> completeIntensityList = new List<double>();
                                for (int k = 1; k < len; k++)
                                {
                                    List<double> intensityList = new List<double>();

                                    string bion = pepSequence.Substring(0, k);
                                    string yion = pepSequence.Substring(k, len - k);

                                    int NR = Package.parseAAResidues(bion, 'R');
                                    int NK = Package.parseAAResidues(bion, 'K');
                                    int NH = Package.parseAAResidues(bion, 'H');
                                    int NL = k;
                                    int CR = Package.parseAAResidues(yion, 'R');
                                    int CK = Package.parseAAResidues(yion, 'K');
                                    int CH = Package.parseAAResidues(yion, 'H');
                                    int CL = len - k;
                                    int pepBond = k;
                                    int NBasicAA = NR + NK + NH;
                                    int CBasicAA = CR + CK + CH;
                                    string AA = NR + "," + NK + "," + NH + "," + NL + "," + CR + "," + CK + "," + CH + "," + CL;

                                    double[] bCharge = new double[z + 1];
                                    double[] yCharge = new double[z + 1];
                                    //double[] bIntensity = new double[z + 1];
                                    //double[] yIntensity = new double[z + 1];
                                    //add variable for "real" charges

                                    if (model == 0) //naive model
                                    {
                                        int[] bFragmentCharge = new int[z + 1];
                                        int[] yFragmentCharge = new int[z + 1];
                                        //return the b ion charge 1 Intensity, if matched
                                        for (int i = 1; i < z; i++)
                                        {
                                            bCharge[i] = fragmentation.b(k, i);
                                            yCharge[i] = fragmentation.y(len - k, i);
                                            //change for ORBI-ORBI purposes.
                                            Peak bmatched = Package.findClose(peakList, bCharge[i], bCharge[i] * 30 * Math.Pow(10, -6));
                                            Peak ymatched = Package.findClose(peakList, yCharge[i], yCharge[i] * 30 * Math.Pow(10, -6));
                                            if (bmatched != null)
                                            {
                                                //bIntensity[i] = bmatched.rankOrIntensity;
                                                int fragmentCharge = bmatched.fragmentCharge;
                                                if (fragmentCharge == i)
                                                    bFragmentCharge[i] = 3;
                                                else bFragmentCharge[i] = 2;
                                                //intensityList.Add(bmatched.rankOrIntensity);
                                                //completeIntensityList.Add(bmatched.rankOrIntensity);
                                            }
                                            else bFragmentCharge[i] = 1;
                                            //else bIntensity[i] = 0;
                                            if (ymatched != null)
                                            {
                                                //yIntensity[i] = ymatched.rankOrIntensity;
                                                //yFragmentCharge[i] = ymatched.fragmentCharge;
                                                int fragmentCharge = ymatched.fragmentCharge;
                                                if (fragmentCharge == i)
                                                    yFragmentCharge[i] = 3;
                                                else yFragmentCharge[i] = 2;
                                                //intensityList.Add(ymatched.rankOrIntensity);
                                                //completeIntensityList.Add(ymatched.rankOrIntensity);
                                            }
                                            else yFragmentCharge[i] = 1;
                                            //else yIntensity[i] = 0;
                                        }
                                        string finalString = idOrIndex + "," + pepSequence + "," + pepBond + "," + bFragmentCharge[1] + "," + bFragmentCharge[2] + "," + yFragmentCharge[1] + "," + yFragmentCharge[2];
                                        file.WriteLine(finalString);
                                    }
                                    else if (model == 1) //my binary logistic regression basophile model
                                    {
                                        int b1=0, b2=0, y1=0, y2 = 0;
                                        double y1_logit = 0.1098112 * NR + 0.2085831 * NK + 0.1512109 * NH + 0.0460839 * NL
                                                        - 0.3872417 * CR - 0.3684911 * CK - 0.1634741 * CH - 0.1693931 * CL + 1.2632997;
                                        double y2_logit =-0.6345364 * NR - 0.3365917 * NK - 0.4577882 * NH - 0.1492703 * NL
                                                        + 0.7738133 * CR + 0.6036758 * CK + 0.5942542 * CH + 0.0701467 * CL + 0.0806280;
                                        double b1_logit = 0.0801432 * NR - 0.1088081 * NK - 0.1338220 * NH - 0.1413059 * NL
                                                        - 0.3157957 * CR - 0.2708274 * CK - 0.3703136 * CH + 0.0157418 * CL + 1.2124699;
                                        double b2_logit = 0.8606449 * NR + 0.2763119 * NK + 0.4969152 * NH + 0.0685712 * NL
                                                        - 1.3346995 * CR - 1.0977316 * CK - 1.0973677 * CH - 0.2028884 * CL + 1.9355980;
                                        if (b1_logit > -0.5)
                                        {
                                            double mz_b1 = fragmentation.b(k, 1);
                                            Peak matched = Package.findClose(peakList, mz_b1, mz_b1 * 30 * Math.Pow(10, -6));
                                            if (matched != null)
                                            {
                                                if (matched.fragmentCharge == 1) b1 = 3;
                                                else b1 = 2;
                                            }
                                            else b1 = 1;
                                        }
                                        else b1 = 0;
                                        if (b2_logit > 0)
                                        {
                                            double mz_b2 = fragmentation.b(k, 2);
                                            Peak matched = Package.findClose(peakList, mz_b2, mz_b2 * 30 * Math.Pow(10, -6));
                                            if (matched != null)
                                            {
                                                if (matched.fragmentCharge == 2) b2 = 3;
                                                else b2 = 2;
                                            }
                                            else b2 = 1;
                                        }
                                        else b2 = 0;
                                        if (y1_logit > -0.5)
                                        {
                                            double mz_y1 = fragmentation.y(len - k, 1);
                                            Peak matched = Package.findClose(peakList, mz_y1, mz_y1 * 30 * Math.Pow(10, -6));
                                            if (matched != null)
                                            {
                                                if (matched.fragmentCharge == 1) y1 = 3;
                                                else y1 = 2;
                                            }
                                            else y1 = 1;
                                        }
                                        else y1 = 0;
                                        if (y2_logit > -0.5)
                                        {
                                            double mz_y2 = fragmentation.y(len - k, 2);
                                            Peak matched = Package.findClose(peakList, mz_y2, mz_y2 * 30 * Math.Pow(10, -6));
                                            if (matched != null)
                                            {
                                                if (matched.fragmentCharge == 2) y2 = 3;
                                                else y2 = 2;
                                            }
                                            else y2 = 1;
                                        }
                                        else y2 = 0;
                                        string finalString = idOrIndex + "," + pepSequence + "," + pepBond + "," + b1 + "," + b2 + "," + y1 + "," + y2;
                                        file.WriteLine(finalString);
                                    }

                                    else if (model == 2) //Surendra's ordinal model
                                    {
                                        int b1 = 0, b2 = 0, y1 = 0, y2 = 0;
                                        double logit = NR * 0.9862 + NH * 0.8772 + NK * 0.7064 + NL * 0.4133
                                                     - CR * 1.1688 - CH * 0.3948 - CK * 0.6710 - CL * 0.4859;
                                        //charge Label = "1", generate b+,y++
                                        if (logit < -2.2502)
                                        {
                                            double mz_b1 = fragmentation.b(k, 1);
                                            Peak b1matched = Package.findClose(peakList, mz_b1, mz_b1 * 30 * Math.Pow(10, -6));
                                            if (b1matched != null)
                                            {
                                                if (b1matched.fragmentCharge == 1) b1 = 3;  //matched, charge agree
                                                else b1 = 2; //matched, charge does not agree
                                            }
                                            else b1 = 1; //unmatched, but predicted.

                                            double mz_y2 = fragmentation.y(len - k, 2);
                                            Peak y2matched = Package.findClose(peakList, mz_y2, mz_y2 * 30 * Math.Pow(10, -6));
                                            if (y2matched != null)
                                            {
                                                if (y2matched.fragmentCharge == 2) y2 = 3;  //matched, charge agree
                                                else y2 = 2; //matched, charge does not agree
                                            }
                                            else y2 = 1; //unmatched, but predicted.
                                        }
                                        //ambiLabel = "2", generate b+, y+, b++, y++
                                        else if (logit < 0.7872)
                                        {
                                            double mz_b1 = fragmentation.b(k, 1);
                                            Peak b1matched = Package.findClose(peakList, mz_b1, mz_b1 * 30 * Math.Pow(10, -6));
                                            if (b1matched != null)
                                            {
                                                if (b1matched.fragmentCharge == 1) b1 = 3;  //matched, charge agree
                                                else b1 = 2; //matched, charge does not agree
                                            }
                                            else b1 = 1; //unmatched, but predicted.

                                            double mz_y1 = fragmentation.y(len - k, 1);
                                            Peak y1matched = Package.findClose(peakList, mz_y1, mz_y1 * 30 * Math.Pow(10, -6));
                                            if (y1matched != null)
                                            {
                                                if (y1matched.fragmentCharge == 1) y1 = 3;  //matched, charge agree
                                                else y1 = 2; //matched, charge does not agree
                                            }
                                            else y1 = 1; //unmatched, but predicted.

                                            double mz_b2 = fragmentation.b(k, 2);
                                            Peak b2matched = Package.findClose(peakList, mz_b2, mz_b2 * 30 * Math.Pow(10, -6));
                                            if (b2matched != null)
                                            {
                                                if (b2matched.fragmentCharge == 2) b2 = 3;  //matched, charge agree
                                                else b2 = 2; //matched, charge does not agree
                                            }
                                            else b2 = 1; //unmatched, but predicted.

                                            double mz_y2 = fragmentation.y(len - k, 2);
                                            Peak y2matched = Package.findClose(peakList, mz_y2, mz_y2 * 30 * Math.Pow(10, -6));
                                            if (y2matched != null)
                                            {
                                                if (y2matched.fragmentCharge == 2) y2 = 3;  //matched, charge agree
                                                else y2 = 2; //matched, charge does not agree
                                            }
                                            else y2 = 1; //unmatched, but predicted.
                                        }
                                        //ambiLabel = "3", generate b++,y+
                                        else
                                        {
                                            double mz_b2 = fragmentation.b(k, 2);
                                            Peak b2matched = Package.findClose(peakList, mz_b2, mz_b2 * 30 * Math.Pow(10, -6));
                                            if (b2matched != null)
                                            {
                                                if (b2matched.fragmentCharge == 2) b2 = 3;  //matched, charge agree
                                                else b2 = 2; //matched, charge does not agree
                                            }
                                            else b2 = 1; //unmatched, but predicted.

                                            double mz_y1 = fragmentation.y(len - k, 1);
                                            Peak y1matched = Package.findClose(peakList, mz_y1, mz_y1 * 30 * Math.Pow(10, -6));
                                            if (y1matched != null)
                                            {
                                                if (y1matched.fragmentCharge == 1) y1 = 3;  //matched, charge agree
                                                else y1 = 2; //matched, charge does not agree
                                            }
                                            else y1 = 1; //unmatched, but predicted.
                                        }
                                        string finalString = idOrIndex + "," + pepSequence + "," + pepBond + "," + b1 + "," + b2 + "," + y1 + "," + y2;
                                        file.WriteLine(finalString);
                                    }

                                    //intensityDic.Add(pepBond, intensityList);

                                    //rowDic.Add(pepBond, finalString);
                                }//end for each peptide bond
                            }//end if z==3
                        }//end foreach peptide
            }//end using
        }
        public override IEnumerable <string> Process(string fileName)
        {
            System.Net.WebClient aWebClient = new System.Net.WebClient();
            aWebClient.Encoding = System.Text.Encoding.Default;
            string html = aWebClient.DownloadString(this.url);

            //string html = File.ReadAllText(fileName);
            Lexer lexer = new Lexer(html);

            Winista.Text.HtmlParser.Parser parser = new Winista.Text.HtmlParser.Parser(lexer);
            NodeList htmlNodes = parser.Parse(null);

            List <IsotopicAtom> atoms = new List <IsotopicAtom>();

            var          node = FindFirstNode(htmlNodes, "tbody");
            INode        nextNode;
            IsotopicAtom atom = null;

            while ((nextNode = FindFirstNode(node, "tr")) != null)
            {
                if (nextNode.Children != null)
                {
                    var tds = nextNode.Children.ExtractAllNodesThatMatch(new NameFilter("td"));
                    if (tds.Count == 1)
                    {
                        atom = null;
                    }

                    if (tds.Count >= 3 && tds[0].FirstChild != null)
                    {
                        var t1 = tds[0].FirstChild.GetText().Trim();
                        var t2 = tds[1].FirstChild.GetText().Trim();

                        if (Char.IsDigit(t1[0]) && Char.IsLetter(t2[0]))
                        {
                            atom = new IsotopicAtom();
                            atoms.Add(atom);

                            atom.Name = tds[1].FirstChild.GetText().Trim();
                            Peak p = new Peak();
                            p.Mz        = GetDouble(tds[3]);
                            p.Intensity = GetDouble(tds[4]);
                            atom.Isotopics.Add(p);
                        }
                        else if (atom != null)
                        {
                            var txt = tds[0].FirstChild.GetText().Trim();
                            if (txt.Length > 0 && Char.IsLetter(txt[0]))
                            {
                                tds.Remove(0);
                            }

                            Peak p = new Peak();
                            p.Mz        = GetDouble(tds[1]);
                            p.Intensity = GetDouble(tds[2]);
                            atom.Isotopics.Add(p);
                        }
                    }
                }

                node = nextNode.NextSibling;
                if (node == null)
                {
                    break;
                }
            }

            atoms.ForEach(m => m.Isotopics.RemoveAll(n => n.Intensity == 0.0));

            atoms.RemoveAll(m => m.Isotopics.Count == 0);

            var dic = atoms.ToDictionary(m => m.Name);

            var x = new IsotopicAtom();

            x.Name = "X";
            x.Isotopics.Add(new Peak(1, 0.9));
            x.Isotopics.Add(new Peak(2, 0.1));
            atoms.Insert(0, x);

            atoms.Add(AddHevayAtom("(H2)", "H", 1, dic));
            atoms.Add(AddHevayAtom("(C13)", "C", 1, dic));
            atoms.Add(AddHevayAtom("(N15)", "N", 1, dic));
            atoms.Add(AddHevayAtom("(O18)", "O", 2, dic));

            using (StreamWriter sw = new StreamWriter(fileName))
            {
                atoms.ForEach(m =>
                {
                    sw.WriteLine("{0}\t{1}", m.Name, m.Isotopics.Count);
                    m.Isotopics.ForEach(n => sw.WriteLine("{0:0.000000}\t{1:0.000000}", n.Mz, n.Intensity));
                    sw.WriteLine();
                });
            }
            return(new string[] { fileName });
        }
Ejemplo n.º 16
0
 /// <summary>
 /// CONSTRUCTOR
 /// </summary>
 public StylisedPeak(Peak peak)
 {
     this.Peak = peak;
 }
Ejemplo n.º 17
0
 /// <summary>
 /// Calculate the error in ppm of a peak and its theoretical M/Z
 /// </summary>
 /// <param name="peak">The peak to calculate the error for</param>
 /// <param name="theoMz">Theoretical M/Z</param>
 /// <returns>The error in ppm.</returns>
 public static double GetPeakPpmError(Peak peak, double theoMz)
 {
     // error = (observed - theo)/observed*10e6
     return((peak.Mz - theoMz) / peak.Mz * Math.Pow(10, 6));
 }
Ejemplo n.º 18
0
        public Tuple <int, int, int, int, string, string> GetLongestSequence(ProductSpectrum spectrum, Sequence sequence)
        {
            _spectrum     = spectrum;
            _sequence     = sequence;
            _baseIonTypes = _spectrum.ActivationMethod != ActivationMethod.ETD ? BaseIonTypesCid : BaseIonTypesEtd;

            var cleavages      = _sequence.GetInternalCleavages().ToArray();
            var prefixValueArr = new int[cleavages.Length];
            var suffixValueArr = new int[cleavages.Length];
            var prefixPeakArr  = new Peak[cleavages.Length];
            var suffixPeakArr  = new Peak[cleavages.Length];
            //var peakList = new double[_spectrum.Peaks.Length];

            int cleavageIndex = 0;

            /*
             * for (int i = 0; i < peakList.Length; i++)
             * {
             *  peakList[i] = _spectrum.Peaks[i].Intensity;
             * }*/

            //var rankings = ArrayUtil.GetRankings(peakList);

            foreach (var c in cleavages)
            {
                foreach (var baseIonType in _baseIonTypes)
                {
                    var fragmentComposition = baseIonType.IsPrefix
                                 ? c.PrefixComposition + baseIonType.OffsetComposition
                                 : c.SuffixComposition + baseIonType.OffsetComposition;
                    for (var charge = _minCharge; charge <= _maxCharge; charge++)
                    {
                        var ion = new Ion(fragmentComposition, charge);
                        if (_spectrum.GetCorrScore(ion, _tolerance, RelativeIsotopeIntensityThreshold) < .7)
                        {
                            continue;
                        }
                        if (baseIonType.IsPrefix)
                        {
                            prefixValueArr[cleavageIndex] = 1;
                        }
                        else
                        {
                            suffixValueArr[cleavageIndex] = 1;
                        }
                    }
                }
                cleavageIndex++;
            }

            var prefixSequenceArr = new int[_sequence.Count];
            var suffixSequenceArr = new int[_sequence.Count];

            prefixSequenceArr[0] = prefixValueArr[0];
            suffixSequenceArr[suffixSequenceArr.Length - 1] = suffixValueArr[suffixValueArr.Length - 1];

            for (int i = 1; i < prefixValueArr.Length; i++)
            {
                if (prefixValueArr[i] == 1 && prefixValueArr[i - 1] == 1)
                {
                    if (_sequence[i] is ModifiedAminoAcid)
                    {
                        continue;
                    }
                    prefixSequenceArr[i] = 1;
                }
            }

            for (int i = suffixValueArr.Length - 2; i >= 0; i--)
            {
                if (suffixValueArr[i] == 1 && suffixValueArr[i + 1] == 1)
                {
                    if (_sequence[i + 1] is ModifiedAminoAcid)
                    {
                        continue;
                    }
                    suffixSequenceArr[i + 1] = 1;
                }
            }



            var prefixSubString  = FindLongestSubstring(prefixSequenceArr);
            var prefixStartIndex = -1;
            var prefixEndIndex   = -1;
            //var prefixSequencePeaks = new List<Peak>();
            //var prefixPval = -1.0;
            var prefixSequence = "";

            if (prefixSubString != "")
            {
                var prefixIndex = string.Concat(prefixSequenceArr);
                prefixStartIndex = prefixIndex.IndexOf(prefixSubString) + 1;
                prefixEndIndex   = (prefixStartIndex == 1) ? 1 : prefixStartIndex + prefixSubString.Length - 1;
                //prefixSequencePeaks = GetPrefixSequencePeaks(prefixPeakArr, prefixStartIndex, prefixEndIndex);
                //var prefixRankSum = GetSequenceRankSum(prefixSequencePeaks, rankings, peakList);
                //prefixPval = FitScoreCalculator.GetRankSumPvalue(peakList.Length, prefixSequencePeaks.Count, prefixRankSum);
                prefixSequence = GetStringSubSequence(_sequence, prefixStartIndex, prefixEndIndex);
            }

            var suffixSubString  = FindLongestSubstring(suffixSequenceArr);
            var suffixStartIndex = -1;
            var suffixEndIndex   = -1;
            //var suffixSequencePeaks = new List<Peak>();
            //var suffixPval = -1.0;
            var suffixSequence = "";

            if (suffixSubString != "")
            {
                var suffixIndex = string.Concat(suffixSequenceArr);
                suffixStartIndex = suffixIndex.IndexOf(suffixSubString) + 1;
                suffixEndIndex   = (suffixStartIndex == 1) ? 1 : suffixStartIndex + suffixSubString.Length - 1;
                //suffixSequencePeaks = GetSuffixSequencePeaks(suffixPeakArr, suffixStartIndex, suffixEndIndex);
                //var suffixRankSum = GetSequenceRankSum(suffixSequencePeaks, rankings, peakList);
                //suffixPval = FitScoreCalculator.GetRankSumPvalue(peakList.Length, suffixSequencePeaks.Count, suffixRankSum);
                suffixSequence = GetStringSubSequence(_sequence, suffixStartIndex, suffixEndIndex);
            }

            return(new Tuple <int, int, int, int, string, string>(prefixStartIndex, prefixEndIndex, suffixStartIndex, suffixEndIndex, prefixSequence, suffixSequence));
        }
Ejemplo n.º 19
0
 public ChartSelectionEventArgs(Peak variable, IntensityInfo dataPoint, string seriesName)
 {
     this._peak       = variable;
     this._dataPoint  = dataPoint;
     this._seriesName = seriesName;
 }
Ejemplo n.º 20
0
        public Tuple<int, int, int, int, string, string> GetLongestSequence(ProductSpectrum spectrum, Sequence sequence)
        {
            _spectrum = spectrum;
            _sequence = sequence;
            _baseIonTypes = _spectrum.ActivationMethod != ActivationMethod.ETD ? BaseIonTypesCid : BaseIonTypesEtd;

            var cleavages = _sequence.GetInternalCleavages().ToArray();
            var prefixValueArr = new int[cleavages.Length];
            var suffixValueArr = new int[cleavages.Length];
            var prefixPeakArr = new Peak[cleavages.Length];
            var suffixPeakArr = new Peak[cleavages.Length];
            //var peakList = new double[_spectrum.Peaks.Length];

            int cleavageIndex = 0;

            /*
            for (int i = 0; i < peakList.Length; i++)
            {
                peakList[i] = _spectrum.Peaks[i].Intensity;
            }*/

            //var rankings = ArrayUtil.GetRankings(peakList);

            foreach (var c in cleavages)
            {
                foreach (var baseIonType in _baseIonTypes)
                {
                    var fragmentComposition = baseIonType.IsPrefix
                                 ? c.PrefixComposition + baseIonType.OffsetComposition
                                 : c.SuffixComposition + baseIonType.OffsetComposition;
                    for (var charge = _minCharge; charge <= _maxCharge; charge++)
                    {

                        var ion = new Ion(fragmentComposition, charge);
                        if (_spectrum.GetCorrScore(ion, _tolerance, RelativeIsotopeIntensityThreshold) < .7) continue;
                        if (baseIonType.IsPrefix) prefixValueArr[cleavageIndex] = 1;
                        else suffixValueArr[cleavageIndex] = 1;


                    }
                }
                cleavageIndex++;
            }

            var prefixSequenceArr = new int[_sequence.Count];
            var suffixSequenceArr = new int[_sequence.Count];
            prefixSequenceArr[0] = prefixValueArr[0];
            suffixSequenceArr[suffixSequenceArr.Length - 1] = suffixValueArr[suffixValueArr.Length - 1];

            for (int i = 1; i < prefixValueArr.Length; i++)
            {
                if (prefixValueArr[i] == 1 && prefixValueArr[i - 1] == 1)
                {
                    if (_sequence[i] is ModifiedAminoAcid) continue;
                    prefixSequenceArr[i] = 1;

                }
            }

            for (int i = suffixValueArr.Length - 2; i >= 0; i--)
            {
                if (suffixValueArr[i] == 1 && suffixValueArr[i + 1] == 1)
                {
                    if (_sequence[i + 1] is ModifiedAminoAcid) continue;
                    suffixSequenceArr[i + 1] = 1;
                }
            }



            var prefixSubString = FindLongestSubstring(prefixSequenceArr);
            var prefixStartIndex = -1;
            var prefixEndIndex = -1;
            //var prefixSequencePeaks = new List<Peak>();
            //var prefixPval = -1.0;
            var prefixSequence = "";
            if (prefixSubString != "")
            {
                var prefixIndex = string.Concat(prefixSequenceArr);
                prefixStartIndex = prefixIndex.IndexOf(prefixSubString) + 1;
                prefixEndIndex = (prefixStartIndex == 1) ? 1 : prefixStartIndex + prefixSubString.Length - 1;
                //prefixSequencePeaks = GetPrefixSequencePeaks(prefixPeakArr, prefixStartIndex, prefixEndIndex);
                //var prefixRankSum = GetSequenceRankSum(prefixSequencePeaks, rankings, peakList);
                //prefixPval = FitScoreCalculator.GetRankSumPvalue(peakList.Length, prefixSequencePeaks.Count, prefixRankSum);
                prefixSequence = GetStringSubSequence(_sequence, prefixStartIndex, prefixEndIndex);
            }

            var suffixSubString = FindLongestSubstring(suffixSequenceArr);
            var suffixStartIndex = -1;
            var suffixEndIndex = -1;
            //var suffixSequencePeaks = new List<Peak>();
            //var suffixPval = -1.0;
            var suffixSequence = "";

            if (suffixSubString != "")
            {
                var suffixIndex = string.Concat(suffixSequenceArr);
                suffixStartIndex = suffixIndex.IndexOf(suffixSubString) + 1;
                suffixEndIndex = (suffixStartIndex == 1) ? 1 : suffixStartIndex + suffixSubString.Length - 1;
                //suffixSequencePeaks = GetSuffixSequencePeaks(suffixPeakArr, suffixStartIndex, suffixEndIndex);
                //var suffixRankSum = GetSequenceRankSum(suffixSequencePeaks, rankings, peakList);
                //suffixPval = FitScoreCalculator.GetRankSumPvalue(peakList.Length, suffixSequencePeaks.Count, suffixRankSum);
                suffixSequence = GetStringSubSequence(_sequence, suffixStartIndex, suffixEndIndex);
            }

            return new Tuple<int, int, int, int, string, string>(prefixStartIndex, prefixEndIndex, suffixStartIndex, suffixEndIndex, prefixSequence, suffixSequence);
        }
Ejemplo n.º 21
0
        public override IEnumerable <string> Process(string targetPrefix)
        {
            var result = new List <string>();

            Dictionary <string, Dictionary <int, Dictionary <int, List <PeakEntry> > > > mode_maps     = new Dictionary <string, Dictionary <int, Dictionary <int, List <PeakEntry> > > >();
            Dictionary <string, Dictionary <int, Dictionary <int, List <PeakEntry> > > > mode_compmaps = new Dictionary <string, Dictionary <int, Dictionary <int, List <PeakEntry> > > >();
            Dictionary <int, int> scanCounts = new Dictionary <int, int>();

            foreach (var fileName in sourceFiles)
            {
                //var fileName = fileNames.Skip(2).First();
                Console.WriteLine(fileName);
                var name = Path.GetFileNameWithoutExtension(fileName);

                using (var reader = RawFileFactory.GetRawFileReader(fileName))
                {
                    var firstScan = reader.GetFirstSpectrumNumber();
                    var lastScan  = reader.GetLastSpectrumNumber();

                    for (int i = firstScan; i <= lastScan; i++)
                    {
                        Peak   precursor;
                        string mode;
                        if (reader.GetMsLevel(i) == 1)
                        {
                            precursor = new Peak(0.0, 0.0, FULLMS_CHARGE);
                            mode      = "hcd";
                        }
                        else
                        {
                            precursor = reader.GetPrecursorPeak(i);
                            mode      = reader.GetScanMode(i);
                        }

                        if (!scanCounts.ContainsKey(precursor.Charge))
                        {
                            scanCounts[precursor.Charge] = 1;
                        }
                        else
                        {
                            scanCounts[precursor.Charge] = scanCounts[precursor.Charge] + 1;
                        }

                        var pkl = reader.GetPeakList(i);
                        if (pkl.Count == 0)
                        {
                            continue;
                        }

                        pkl.ScanMode = mode;

                        Dictionary <int, Dictionary <int, List <PeakEntry> > > maps;
                        Dictionary <int, Dictionary <int, List <PeakEntry> > > compmaps;
                        if (!mode_maps.TryGetValue(pkl.ScanMode, out maps))
                        {
                            maps = new Dictionary <int, Dictionary <int, List <PeakEntry> > >();
                            mode_maps[pkl.ScanMode] = maps;
                        }

                        if (!mode_compmaps.TryGetValue(pkl.ScanMode, out compmaps))
                        {
                            compmaps = new Dictionary <int, Dictionary <int, List <PeakEntry> > >();
                            mode_compmaps[pkl.ScanMode] = compmaps;
                        }

                        if (!maps.ContainsKey(precursor.Charge))
                        {
                            maps[precursor.Charge]     = new Dictionary <int, List <PeakEntry> >();
                            compmaps[precursor.Charge] = new Dictionary <int, List <PeakEntry> >();
                        }

                        var map     = maps[precursor.Charge];
                        var compmap = compmaps[precursor.Charge];

                        var maxPeak      = pkl.FindMaxIntensityPeak();
                        var minIntensity = maxPeak.Intensity * options.MinRelativeIntensity;

                        double precursorMass = precursor.Charge > 0 ? PrecursorUtils.MzToMH(precursor.Mz, precursor.Charge, true) : 0.0;
                        var    filescan      = string.Format("{0}_{1}", name, i);
                        foreach (var peak in pkl)
                        {
                            if (peak.Intensity > minIntensity)
                            {
                                AddPeak(map, maxPeak.Intensity, filescan, peak);

                                if (precursor.Charge > 0)
                                {
                                    var peakMass = peak.Charge == 0 ? peak.Mz : PrecursorUtils.MzToMH(peak.Mz, peak.Charge, true);
                                    peakMass = precursorMass - peakMass;
                                    AddPeak(compmap, maxPeak.Intensity, filescan, new Peak(peakMass, peak.Intensity, peak.Charge));
                                }
                            }
                        }
                    }
                }
                //break;
            }

            targetPrefix = Path.GetFileName(targetPrefix);

            foreach (var mode in mode_maps.Keys)
            {
                var maps     = mode_maps[mode];
                var compmaps = mode_compmaps[mode];

                var keys = (from charge in maps.Keys
                            orderby charge
                            select charge).ToList();

                var resultFile1 = new FileInfo(string.Format("{0}/{1}.{2}.forward.ionfrequency",
                                                             options.TargetDirectory,
                                                             targetPrefix,
                                                             mode)).FullName;

                WriteMap(scanCounts, keys, resultFile1, maps, true);

                result.Add(resultFile1);

                var resultFile2 = new FileInfo(string.Format("{0}/{1}.{2}.backward.ionfrequency",
                                                             options.TargetDirectory,
                                                             targetPrefix,
                                                             mode)).FullName;

                WriteMap(scanCounts, keys, resultFile2, compmaps, false);

                result.Add(resultFile2);
            }

            return(result);
        }
Ejemplo n.º 22
0
 public override void Exclude(TimeSpan currentTime, Peak precursor)
 {
     mz_exclusion_intervals[precursor] = currentTime + exclusion_interval;
 }
Ejemplo n.º 23
0
 public Peak[] GuassianFilter(Peak[] spectrum, double std = 1)
 {
     var n = spectrum.Length;
     var newPeak = new Peak[n];
     for (var i = 0; i < n; i++)
     {
         var sum = 0d;
         for (var j = 0; j < n; j++)
         {
             var intensity = spectrum[j].Intensity;
             var massDiff = spectrum[j].Mz - spectrum[i].Mz;
             sum += intensity*Math.Exp(-(massDiff*massDiff)/(2*std*std));
         }
         newPeak[i] = new Peak(spectrum[i].Mz,sum/(n*2*std*std));
     }
     return newPeak;
 }
Ejemplo n.º 24
0
 public Spectrum(IList<double> mzArr, IList<double> intensityArr, int scanNum)
 {
     Peaks = new Peak[mzArr.Count];
     for(var i=0; i<mzArr.Count; i++) Peaks[i] = new Peak(mzArr[i], intensityArr[i]);
     ScanNum = scanNum;
 }
Ejemplo n.º 25
0
 public Peak[] RemovePeaks(double mass, Peak[] peakList)
 {
     return peakList.Where(p => p.Mz <= mass).ToArray();
 }
Ejemplo n.º 26
0
        public Peak[] GetAllIsotopePeaks(double monoIsotopeMass, int charge, IsotopomerEnvelope envelope, Tolerance tolerance, double relativeIntensityThreshold)
        {
            var mostAbundantIsotopeIndex = envelope.MostAbundantIsotopeIndex;
            var isotopomerEnvelope = envelope.Envolope;
            var mostAbundantIsotopeMz = Ion.GetIsotopeMz(monoIsotopeMass, charge, mostAbundantIsotopeIndex);
            var mostAbundantIsotopePeakIndex = FindPeakIndex(mostAbundantIsotopeMz, tolerance);
            if (mostAbundantIsotopePeakIndex < 0) return null;

            var observedPeaks = new Peak[isotopomerEnvelope.Length];
            observedPeaks[mostAbundantIsotopeIndex] = Peaks[mostAbundantIsotopePeakIndex];

            // go down
            var peakIndex = mostAbundantIsotopePeakIndex - 1;
            for (var isotopeIndex = mostAbundantIsotopeIndex - 1; isotopeIndex >= 0; isotopeIndex--)
            {
                if (isotopomerEnvelope[isotopeIndex] < relativeIntensityThreshold) break;
                var isotopeMz = Ion.GetIsotopeMz(monoIsotopeMass, charge, isotopeIndex);
                var tolTh = tolerance.GetToleranceAsTh(isotopeMz);
                var minMz = isotopeMz - tolTh;
                var maxMz = isotopeMz + tolTh;
                for (var i = peakIndex; i >= 0; i--)
                {
                    var peakMz = Peaks[i].Mz;
                    if (peakMz < minMz)
                    {
                        peakIndex = i;
                        break;
                    }
                    if (peakMz <= maxMz)    // find match, move to prev isotope
                    {
                        var peak = Peaks[i];
                        if (observedPeaks[isotopeIndex] == null ||
                            peak.Intensity > observedPeaks[isotopeIndex].Intensity)
                        {
                            observedPeaks[isotopeIndex] = peak;
                        }
                    }
                }
            }

            // go up
            peakIndex = mostAbundantIsotopePeakIndex + 1;
            for (var isotopeIndex = mostAbundantIsotopeIndex + 1; isotopeIndex < isotopomerEnvelope.Length; isotopeIndex++)
            {
                if (isotopomerEnvelope[isotopeIndex] < relativeIntensityThreshold) break;
                var isotopeMz = Ion.GetIsotopeMz(monoIsotopeMass, charge, isotopeIndex);
                var tolTh = tolerance.GetToleranceAsTh(isotopeMz);
                var minMz = isotopeMz - tolTh;
                var maxMz = isotopeMz + tolTh;
                for (var i = peakIndex; i < Peaks.Length; i++)
                {
                    var peakMz = Peaks[i].Mz;
                    if (peakMz > maxMz)
                    {
                        peakIndex = i;
                        break;
                    }
                    if (peakMz >= minMz)    // find match, move to prev isotope
                    {
                        var peak = Peaks[i];
                        if (observedPeaks[isotopeIndex] == null ||
                            peak.Intensity > observedPeaks[isotopeIndex].Intensity)
                        {
                            observedPeaks[isotopeIndex] = peak;
                        }
                    }
                }
            }
            return observedPeaks;
        }
Ejemplo n.º 27
0
 public abstract void Exclude(TimeSpan currentTime, Peak precursor);
Ejemplo n.º 28
0
        private static void GetNotes(int startIdx, int endIdx, IdolWave _wave, List<IdolWaveNote> result)
        {
            IdolWaveNote waveNote;
            //short[] waveShortBuffer = new short[bufferSize];
            //float timeLength = 0.4f;
            //short[] waveShortBuffer = new short[(int)(_wave.ByteRate / 2 * timeLength)];
            //byte[] waveByteBuffer = new byte[(int)(_wave.ByteRate / 2 * timeLength)];
            byte[] waveByteBuffer = new byte[bufferSize];

            int waveIdx = startIdx;
            int bufferIdx = 0;

            AudioFrame audioFrame = new AudioFrame(false);

            double MinFreq = 80;
            double MaxFreq = 800;

            int defaultIdx = -99;

            int batchNo = 0;
            while (waveIdx < endIdx)
            {
                batchNo++;
                bufferIdx = 0;

                /************************************************/

                //while (waveIdx < endIdx &&
                //        bufferIdx < waveShortBuffer.Length)
                //{
                //    waveShortBuffer[bufferIdx] = (Int16)swapByteOrder(BitConverter.ToUInt16(_wave.Data, waveIdx));

                //    waveIdx += _wave.NumChannels;
                //    bufferIdx++;
                //}

                //waveNote = IdolSoundAnalyzer.ProcessData(waveShortBuffer, _wave.SampleRate);

                //IdolSoundAnalyzer.FindClosestNote((int)Math.Round(waveNote.freq), out closestFreq, out waveNote.NoteIdx, out waveNote.NoteName);

                /************************************************/

                while (waveIdx < endIdx &&
                        bufferIdx < waveByteBuffer.Length)
                {
                    waveByteBuffer[bufferIdx] = _wave.Data[waveIdx];

                    waveIdx ++;
                    bufferIdx++;
                }

                audioFrame.ProcessMono(ref waveByteBuffer);

                int fftBufferLength = audioFrame._fftLeft.Length;

                int minSpectr = (int)(MinFreq * (fftBufferLength * 2) / _wave.SampleRate) + 1;
                int index = minSpectr;
                double max = audioFrame._fftLeft[index];
                int usefullMaxSpectr = Math.Min((fftBufferLength * 2),
                    (int)(MaxFreq * (fftBufferLength * 2) / _wave.SampleRate) + 1);

                List<Peak> peakList = new List<Peak>();
                double current = max;
                double last = max;
                double last2 = max;

                for (int i = index; i < usefullMaxSpectr; i++)
                {
                    last2 = last;
                    last = current;
                    current = audioFrame._fftLeft[i];

                    if (last > 51)
                    {
                        if (last > last2 && last > current)
                        {
                            Peak peak = new Peak();
                            peak.Index = i - 1;
                            peak.Freq = _wave.SampleRate * (i - 1) / (audioFrame._fftLeft.Length * 2);
                            peak.Amp = audioFrame._fftLeft[i - 1];
                            peakList.Add(peak);
                        }
                    }

                    if (max < audioFrame._fftLeft[i])
                    {
                        max = audioFrame._fftLeft[i]; index = i;
                    }
                }

                double freq = 0;
                if (peakList.Count > 0)
                {
                    int i = 0;
                    bool found = false;
                    while (i < peakList.Count && !found)
                    {
                        if (peakList[i].Amp >= 58)
                        {
                            index = peakList[i].Index;
                            found = true;
                        }
                        else i++;
                    }
                    if (!found)
                    {
                        index = peakList[0].Index;
                    }
                    else
                    {
                            for (int j = 0; j < i; j++)
                            {
                                double ratio = peakList[i].Freq / peakList[j].Freq;
                                if (ratio >= 1 && (ratio % 1.0f < 0.1f || ratio % 1.0f > 0.9f))
                                {
                                    index = peakList[j].Index;
                                    if (peakList[j].Freq == 93)
                                    {
                                        peakList[j].Freq *= 1;
                                    }
                                    break;
                                }
                            }
                    }
                }
                freq = _wave.SampleRate * index / (audioFrame._fftLeft.Length * 2);
                if (freq < MinFreq) freq = 0;

                waveNote = new IdolWaveNote();
                waveNote.freq = freq;
                waveNote.max = audioFrame._fftLeft[index];

                IdolSoundAnalyzer.FindClosestNote((int)Math.Round(waveNote.freq), out closestFreq, out waveNote.NoteIdx, out waveNote.NoteName);

                /************************************************/

                result.Add(waveNote);
            }
        }
Ejemplo n.º 29
0
    public void TestFindEnvelopeInList()
    {
      List<PeakList<Peak>> envelopes = pl.GetEnvelopes(20);
      Peak peak = new Peak(446.1185, 51638.0, 1);
      double mzTolerance = PrecursorUtils.ppm2mz(peak.Mz, 20);
      PeakList<Peak> actual = PeakList<Peak>.FindEnvelopeInList(envelopes, peak, mzTolerance);
      Assert.AreSame(envelopes[1], actual);

      Peak peak2 = new Peak(631.2642, 129351.8, 1);
      double mzTolerance2 = PrecursorUtils.ppm2mz(peak2.Mz, 20);
      PeakList<Peak> actual2 = PeakList<Peak>.FindEnvelopeInList(envelopes, peak2, mzTolerance2);
      Assert.AreSame(envelopes[4], actual2);

      Peak missPeak = new Peak(731.2642, 129351.8, 1);
      double missMzTolerance = PrecursorUtils.ppm2mz(missPeak.Mz, 20);
      PeakList<Peak> actualMiss = PeakList<Peak>.FindEnvelopeInList(envelopes, missPeak, missMzTolerance);
      Assert.AreSame(null, actualMiss);
    }
Ejemplo n.º 30
0
        // Select the best peak within +/- filteringWindowSize
        public static List<DeconvolutedPeak> GetDeconvolutedPeaks(
            Peak[] peaks, int minCharge, int maxCharge, 
            int isotopeOffsetTolerance, double filteringWindowSize,
            Tolerance tolerance, double corrScoreThreshold)
        {

            var monoIsotopePeakList = new List<DeconvolutedPeak>();
            for (var peakIndex = 0; peakIndex < peaks.Length; peakIndex++)
            {
                var peak = peaks[peakIndex];

                // Check whether peak has the maximum intensity within the window
                var isBest = true;

                var prevIndex = peakIndex - 1;
                while (prevIndex >= 0)
                {
                    var prevPeak = peaks[prevIndex];
                    if ((peak.Mz - prevPeak.Mz) > filteringWindowSize) break;
                    if (prevPeak.Intensity > peak.Intensity)
                    {
                        isBest = false;
                        break;
                    }
                    prevIndex--;
                }

                if (!isBest) continue;

                var nextIndex = peakIndex + 1;
                while (nextIndex < peaks.Length)
                {
                    var nextPeak = peaks[nextIndex];
                    if ((nextPeak.Mz - peak.Mz) > filteringWindowSize) break;
                    if (nextPeak.Intensity > peak.Intensity)
                    {
                        isBest = false;
                        break;
                    }
                    nextIndex++;
                }

                if (!isBest) continue;

                // peak has the maximum intensity, window = [prevIndex+1,nextIndex-1]

                var window = new Peak[nextIndex - prevIndex - 1];
                Array.Copy(peaks, prevIndex + 1, window, 0, window.Length);
                var windowSpectrum = new Spectrum(window, 1);
                var peakMz = peak.Mz;

                for (var charge = maxCharge; charge >= minCharge; charge--)
                {
                    var mass = peak.Mz * charge;
                    var mostAbundantIsotopeIndex = Averagine.GetIsotopomerEnvelope(mass).MostAbundantIsotopeIndex;

                    for (var isotopeIndex = mostAbundantIsotopeIndex - isotopeOffsetTolerance; isotopeIndex <= mostAbundantIsotopeIndex + isotopeOffsetTolerance; isotopeIndex++)
                    {
                        var monoIsotopeMass = Ion.GetMonoIsotopicMass(peakMz, charge, isotopeIndex);
                        var isotopomerEnvelope = Averagine.GetIsotopomerEnvelope(monoIsotopeMass);
                        var observedPeaks = windowSpectrum.GetAllIsotopePeaks(monoIsotopeMass, charge, isotopomerEnvelope, tolerance, 0.1);
                        if (observedPeaks == null) continue;

                        var envelop = isotopomerEnvelope.Envolope;
                        var observedIntensities = new double[observedPeaks.Length];

                        for (var i = 0; i < observedPeaks.Length; i++)
                        {
                            var observedPeak = observedPeaks[i];
                            observedIntensities[i] = observedPeak != null ? (float)observedPeak.Intensity : 0.0;
                        }

                        var sim = FitScoreCalculator.GetDistanceAndCorrelation(envelop, observedIntensities);
                        var bcDist = sim.Item1;
                        var corr = sim.Item2;

                        if (corr < corrScoreThreshold && bcDist > 0.03) continue;

                        // monoIsotopeMass is valid
                        var deconvPeak = new DeconvolutedPeak(monoIsotopeMass, observedIntensities[mostAbundantIsotopeIndex], charge, corr, bcDist, observedPeaks);
                        monoIsotopePeakList.Add(deconvPeak);
                    }
                }
            }

            monoIsotopePeakList.Sort();
            return monoIsotopePeakList;
        }
Ejemplo n.º 31
0
        private void PerformSelectionActions()
        {
            // Series are tagged with the variables they represent
            // When multiple series are selected they all have the same variable so no worries about using the first one
            Peak peak = this._chart.SelectedItem.SelectedSeries != null ? (Peak)this._chart.SelectedItem.SelectedSeries.Tag : null;

            // Points are tagged with the observation
            IntensityInfo dataPoint;

            if (this._chart.SelectedItem.DataPoint != null)
            {
                if (this._chart.SelectedItem.DataPoint.Tag is IntensityInfo)
                {
                    dataPoint = (IntensityInfo)this._chart.SelectedItem.DataPoint.Tag;
                }
                else if (this._chart.SelectedItem.DataPoint.Tag is IntensityInfo[])
                {
                    IntensityInfo[] dataPointArray = (IntensityInfo[])this._chart.SelectedItem.DataPoint.Tag;
                    dataPoint = dataPointArray != null ? dataPointArray[this._chart.SelectedItem.YIndex] : default(IntensityInfo);
                }
                else
                {
                    UiControls.Assert(false, "Unexpected data point format.");
                    dataPoint = null;
                }
            }
            else
            {
                // Clear selection
                dataPoint = null;
            }

            if (this.SelectionChanged != null)
            {
                string name;

                if (this._chart.SelectedItem.Series.Length != 0)
                {
                    // Select the first series names as all series are usually similar
                    name = this._chart.SelectedItem.Series[0].Name;

                    // Trim off everything after the | as this is just used so the chart doesn't complain
                    if (name.Contains("|"))
                    {
                        name = name.Substring(0, name.LastIndexOf('|')).Trim();
                    }
                }
                else
                {
                    name = null;
                }

                ChartSelectionEventArgs e = new ChartSelectionEventArgs(peak, dataPoint, name);
                this.SelectionChanged(this, e);
            }

            // Update text
            if (this._mnuSelectedPeak != null)
            {
                if (peak != null && this._chkShowPeak.Checked)
                {
                    this._mnuSelectedPeak.Text    = peak.DisplayName;
                    this._mnuSelectedPeak.Image   = UiControls.GetImage(((Visualisable)peak).Icon, true);
                    this._mnuSelectedPeak.Visible = true;
                }
                else
                {
                    this._mnuSelectedPeak.Visible = false;
                }

                if (dataPoint != null)
                {
                    if (dataPoint.Rep.HasValue && this._chkShowReplicate.Checked)
                    {
                        this._mnuSelectedReplicate.Text    = dataPoint.Rep.Value.ToString();
                        this._mnuSelectedReplicate.Visible = true;
                    }
                    else
                    {
                        this._mnuSelectedReplicate.Visible = false;
                    }

                    if (dataPoint.Time.HasValue && this._chkShowTime.Checked)
                    {
                        this._mnuSelectedTime.Text    = dataPoint.Time.Value.ToString();
                        this._mnuSelectedTime.Visible = true;
                    }
                    else
                    {
                        this._mnuSelectedTime.Visible = false;
                    }


                    if (this._chkShowIntensity.Checked)
                    {
                        this._mnuSelectedIntensity.Text    = dataPoint.Intensity.ToString();
                        this._mnuSelectedIntensity.Visible = true;
                    }
                    else
                    {
                        this._mnuSelectedIntensity.Visible = false;
                    }

                    if (dataPoint.Group != null && this._chkShowGroup.Checked)
                    {
                        this._mnuSelectedGroup.Text    = dataPoint.Group.DisplayName;
                        this._mnuSelectedGroup.Image   = UiControls.CreateExperimentalGroupImage(true, dataPoint.Group, false);
                        this._mnuSelectedGroup.Visible = true;
                    }
                    else
                    {
                        this._mnuSelectedGroup.Visible = false;
                    }

                    if (this._chkShowSeries.Checked && this._chart.SelectedItem.Series.Length != 0)
                    {
                        this._mnuSelectedSeries.Text    = this._chart.SelectedItem.Series[0].Name;
                        this._mnuSelectedSeries.Image   = this._chart.SelectedItem.Series[0].DrawLegendKey(this._menuBar.ImageScalingSize.Width, this._menuBar.ImageScalingSize.Height);
                        this._mnuSelectedSeries.Visible = true;
                    }
                    else
                    {
                        this._mnuSelectedSeries.Visible = false;
                    }
                }
                else
                {
                    this._mnuSelectedReplicate.Visible = false;
                    this._mnuSelectedTime.Visible      = false;
                    this._mnuSelectedIntensity.Visible = false;
                    this._mnuSelectedSeries.Visible    = false;
                    this._mnuSelectedGroup.Visible     = false;
                }
            }

            // Perform derived-class-specific actions
            this.OnSelection(peak, dataPoint);
        }
Ejemplo n.º 32
0
 public static double GetPeakPpmError(Peak peak, double theoMz)
 {
     return (peak.Mz - theoMz) / peak.Mz * Math.Pow(10, 6);
 }
Ejemplo n.º 33
0
 private Peak MakePeak(TracerFormula tracerFormula, double startTime, double endTime)
 {
     var result = new Peak
                      {
                          StartTime = startTime,
                          EndTime = endTime,
                          TotalArea = GetTracerChromatograms().GetArea(tracerFormula, startTime, endTime),
                          TracerPercent = PeptideFileAnalysis.TurnoverCalculator.GetTracerPercent(tracerFormula),
                          Background = GetTracerChromatograms().GetBackground(tracerFormula, startTime, endTime),
                      };
     return result;
 }
Ejemplo n.º 34
0
 private float[,] generateVoronoi(float[,] heightMap, Vector2 arraySize, GeneratorProgressDelegate generatorProgressDelegate)
 {
     int Tx = (int) arraySize.x;
     int Ty = (int) arraySize.y;
     // Create Voronoi set...
     ArrayList voronoiSet = new ArrayList();
     int i;
     for (i = 0; i < voronoiCells; i++) {
         Peak newPeak = new Peak();
         int xCoord = (int) Mathf.Floor(UnityEngine.Random.value * Tx);
         int yCoord = (int) Mathf.Floor(UnityEngine.Random.value * Ty);
         float pointHeight = UnityEngine.Random.value;
         if (UnityEngine.Random.value > voronoiFeatures) {
             pointHeight = 0.0f;
         }
         newPeak.peakPoint = new Vector2(xCoord, yCoord);
         newPeak.peakHeight = pointHeight;
         voronoiSet.Add(newPeak);
     }
     int Mx;
     int My;
     float highestScore = 0.0f;
     for (My = 0; My < Ty; My++) {
         for (Mx = 0; Mx < Tx; Mx++) {
             ArrayList peakDistances = new ArrayList();
             for (i = 0; i < voronoiCells; i++) {
                 Peak peakI = (Peak) voronoiSet[i];
                 Vector2 peakPoint = peakI.peakPoint;
                 float distanceToPeak = Vector2.Distance(peakPoint, new Vector2(Mx, My));
                 PeakDistance newPeakDistance = new PeakDistance();
                 newPeakDistance.id = i;
                 newPeakDistance.dist = distanceToPeak;
                 peakDistances.Add(newPeakDistance);
             }
             peakDistances.Sort();
             PeakDistance peakDistOne = (PeakDistance) peakDistances[0];
             PeakDistance peakDistTwo = (PeakDistance) peakDistances[1];
             int p1 = peakDistOne.id;
             float d1 = peakDistOne.dist;
             float d2 = peakDistTwo.dist;
             float scale = Mathf.Abs(d1 - d2) / ((Tx + Ty) / Mathf.Sqrt(voronoiCells));
             Peak peakOne = (Peak) voronoiSet[p1];
             float h1 = (float) peakOne.peakHeight;
             float hScore = h1 - Mathf.Abs(d1 / d2) * h1;
             float asRadians;
             switch (voronoiType) {
                 case VoronoiType.Linear:
                 // Nothing...
                 break;
                 case VoronoiType.Sine:
                 asRadians = hScore * Mathf.PI - Mathf.PI / 2;
                 hScore = 0.5f + Mathf.Sin(asRadians) / 2;
                 break;
                 case VoronoiType.Tangent:
                 asRadians = hScore * Mathf.PI / 2;
                 hScore = 0.5f + Mathf.Tan(asRadians) / 2;
                 break;
             }
             hScore = (hScore * scale * voronoiScale) + (hScore * (1.0f - voronoiScale));
             if (hScore < 0.0f) {
                 hScore = 0.0f;
             } else if (hScore > 1.0f) {
                 hScore = 1.0f;
             }
             heightMap[Mx, My] = hScore;
             if (hScore > highestScore) {
                 highestScore = hScore;
             }
         }
         // Show progress...
         float completePoints = My * Ty;
         float totalPoints = Tx * Ty;
         float percentComplete = completePoints / totalPoints;
         generatorProgressDelegate("Voronoi Generator", "Generating height map. Please wait.", percentComplete);
     }
     // Normalise...
     for (My = 0; My < Ty; My++) {
         for (Mx = 0; Mx < Tx; Mx++) {
             float normalisedHeight = heightMap[Mx, My] * (1.0f / highestScore);
             heightMap[Mx, My] = normalisedHeight;
         }
     }
     return heightMap;
 }
Ejemplo n.º 35
0
        public Peak[] GetAllIsotopePeaks(Spectrum spec, Ion ion, Tolerance tolerance, double relativeIntensityThreshold, out int[] peakIndexList)
        {
            var mostAbundantIsotopeIndex = ion.Composition.GetMostAbundantIsotopeZeroBasedIndex();
            var isotopomerEnvelope = ion.Composition.GetIsotopomerEnvelopeRelativeIntensities();

            peakIndexList = new int[isotopomerEnvelope.Length];

            var mostAbundantIsotopeMz = ion.GetIsotopeMz(mostAbundantIsotopeIndex);
            var mostAbundantIsotopeMatchedPeakIndex = spec.FindPeakIndex(mostAbundantIsotopeMz, tolerance);
            if (mostAbundantIsotopeMatchedPeakIndex < 0) return null;

            var observedPeaks = new Peak[isotopomerEnvelope.Length];
            observedPeaks[mostAbundantIsotopeIndex] = spec.Peaks[mostAbundantIsotopeMatchedPeakIndex];
            peakIndexList[mostAbundantIsotopeIndex] = mostAbundantIsotopeMatchedPeakIndex;

            // go down
            var peakIndex = mostAbundantIsotopeMatchedPeakIndex - 1;
            for (var isotopeIndex = mostAbundantIsotopeIndex - 1; isotopeIndex >= 0; isotopeIndex--)
            {
                if (isotopomerEnvelope[isotopeIndex] < relativeIntensityThreshold) break;
                var isotopeMz = ion.GetIsotopeMz(isotopeIndex);
                var tolTh = tolerance.GetToleranceAsTh(isotopeMz);
                var minMz = isotopeMz - tolTh;
                var maxMz = isotopeMz + tolTh;
                for (var i = peakIndex; i >= 0; i--)
                {
                    var peakMz = spec.Peaks[i].Mz;
                    if (peakMz < minMz)
                    {
                        peakIndex = i;
                        break;
                    }
                    if (peakMz <= maxMz)    // find match, move to prev isotope
                    {
                        var peak = spec.Peaks[i];
                        if (observedPeaks[isotopeIndex] == null ||
                            peak.Intensity > observedPeaks[isotopeIndex].Intensity)
                        {
                            observedPeaks[isotopeIndex] = peak;
                            peakIndexList[isotopeIndex] = i;
                        }
                    }
                }
            }

            // go up
            peakIndex = mostAbundantIsotopeMatchedPeakIndex + 1;
            for (var isotopeIndex = mostAbundantIsotopeIndex + 1; isotopeIndex < isotopomerEnvelope.Length; isotopeIndex++)
            {
                if (isotopomerEnvelope[isotopeIndex] < relativeIntensityThreshold) break;
                var isotopeMz = ion.GetIsotopeMz(isotopeIndex);
                var tolTh = tolerance.GetToleranceAsTh(isotopeMz);
                var minMz = isotopeMz - tolTh;
                var maxMz = isotopeMz + tolTh;
                for (var i = peakIndex; i < spec.Peaks.Length; i++)
                {
                    var peakMz = spec.Peaks[i].Mz;
                    if (peakMz > maxMz)
                    {
                        peakIndex = i;
                        break;
                    }
                    if (peakMz >= minMz)    // find match, move to prev isotope
                    {
                        var peak = spec.Peaks[i];
                        if (observedPeaks[isotopeIndex] == null ||
                            peak.Intensity > observedPeaks[isotopeIndex].Intensity)
                        {
                            observedPeaks[isotopeIndex] = peak;
                            peakIndexList[isotopeIndex] = i;
                        }
                    }
                }
            }

            return observedPeaks;
        }
Ejemplo n.º 36
0
 public DeconvolutedPeak(Peak mzPeak, int charge, double corr = 0, double dist = 0)
     : this(charge * (mzPeak.Mz - Constants.Proton), mzPeak.Intensity, charge, corr, dist)
 {
 }
Ejemplo n.º 37
0
        public override void Exclude(TimeSpan currentTime, Peak precursor)
        {
            double mz = precursor.Item1;

            mz_exclusion_intervals[precursor.Item1] = currentTime + exclusion_interval;
        }
Ejemplo n.º 38
0
        ///<summary>
        ///original code for grabbing the required ions
        ///get pepSequence,source,scanID, write into a csv file. 
        ///have tons of information: theretical ion intensity, pep info, chargeLabel...
        ///</summary>
        public static List<string> idpReader_original(string idpXMLFile, string mzMLFile, double TicCutoffPercentage, int z, List<string> pepList, List<string> output)
        {
            //get the path and filename of output csv file:
            string fileName = Path.GetFileNameWithoutExtension(idpXMLFile);
            string filePath = Path.GetDirectoryName(idpXMLFile);
            IDPicker.Workspace workspace = new IDPicker.Workspace();
            Package.loadWorkspace(ref workspace, idpXMLFile);

            MSDataFile foo = new MSDataFile(mzMLFile);
            SpectrumList sl = foo.run.spectrumList;

            foreach (IDPicker.SourceGroupList.MapPair groupItr in workspace.groups)
                foreach (IDPicker.SourceInfo source in groupItr.Value.getSources(true))
                    foreach (IDPicker.SpectrumList.MapPair sItr in source.spectra)
                    {

                        IDPicker.ResultInstance ri = sItr.Value.results[1];
                        IDPicker.VariantInfo vi = ri.info.peptides.Min;

                        string ss = vi.ToString() + "," + sItr.Value.id.source.name + "," + sItr.Value.nativeID;
                        bool boolCharge = sItr.Value.id.charge.Equals(z);
                        if (boolCharge)
                        {
                            string rawPepSequence = vi.ToString();
                            string pepSequence = vi.peptide.sequence;
                            int len = pepSequence.Length;

                            //make sure that the peptide is what we want
                            if (pepList.Contains(pepSequence))
                            {
                                // Look up the index with nativeID
                                object idOrIndex = null;
                                if (sItr.Value.nativeID != null && sItr.Value.nativeID.Length > 0)
                                    idOrIndex = sItr.Value.nativeID;
                                int spectrumIndex = sl.find(idOrIndex as string);
                                // Trust the local index, if the nativeID lookup fails
                                if (spectrumIndex >= sl.size())
                                    spectrumIndex = sItr.Value.id.index;
                                // Bail of the loca index is larger than the spectrum list size
                                if (spectrumIndex >= sl.size())
                                    throw new Exception("Can't find spectrum associated with the index.");

                                //Console.WriteLine(idOrIndex.ToString());
                                //get base peak and TIC and converted to string
                                Spectrum spec1 = sl.spectrum(spectrumIndex, true);
                                MZIntensityPairList peaks = new MZIntensityPairList();
                                spec1.getMZIntensityPairs(ref peaks);
                                Set<Peak> peakList = new Set<Peak>();

                                //get base peak and TIC
                                double basePeakValue = 0;
                                double TICValue = 0;
                                CVParamList list = spec1.cvParams;
                                foreach (CVParam CVP in list)
                                {
                                    if (CVP.name == "base peak intensity")
                                    {
                                        basePeakValue = CVP.value;
                                    }
                                    if (CVP.name == "total ion current")
                                    {
                                        TICValue = CVP.value;
                                    }
                                }
                                string basePeak = basePeakValue.ToString();
                                string TIC = TICValue.ToString();

                                //very important. Surendra put them here
                                //to change those with modifications {} into a format
                                //that fragment method will accept.
                                string interpretation = vi.ToSimpleString();

                                Peptide peptide = new Peptide(interpretation, ModificationParsing.ModificationParsing_Auto, ModificationDelimiter.ModificationDelimiter_Brackets);

                                Fragmentation fragmentation = peptide.fragmentation(true, true);
                                //prepare the qualified peaklist
                                double intenThreshhold = 0;
                                int totalIntenClass = 0;

                                double[] intenArray = new double[peaks.Count];
                                //used during the foreach loop
                                int indexPeaks = 0;

                                //get all the peaks no matter how small they are
                                //then calculate the threshhold TIC
                                //test here
                                foreach (MZIntensityPair mzIntensity in peaks)
                                {
                                    //Peak p = new Peak(mzIntensity.mz, mzIntensity.intensity);
                                    //peakList.Add(p);
                                    intenArray[indexPeaks] = mzIntensity.intensity;
                                    indexPeaks++;
                                }
                                Array.Sort(intenArray);
                                Array.Reverse(intenArray, 0, peaks.Count);

                                //if currTIC>=cutoff, then break
                                double currTIC = 0;
                                double cutOffTIC = TicCutoffPercentage * TICValue;
                                foreach (double inten in intenArray)
                                {
                                    currTIC = currTIC + inten;
                                    if (currTIC < cutOffTIC)
                                    {
                                        intenThreshhold = inten;
                                        totalIntenClass++;
                                    }
                                    else break;
                                }

                                //then based on that, generate a new peaklist that contains only ABC peaks
                                //then calculate the intensity classes
                                foreach (MZIntensityPair mzIntensity in peaks)
                                {
                                    if (mzIntensity.intensity >= intenThreshhold)
                                    {
                                        Peak p = new Peak(mzIntensity.mz, mzIntensity.intensity);
                                        peakList.Add(p);
                                    }
                                }

                                //rowDic contains row information of each peptide bond
                                Dictionary<int, string> rowDic = new Dictionary<int, string>();
                                //intensityDic contains intensity information of fragment ions for each peptide bond
                                Dictionary<int, List<double>> intensityDic = new Dictionary<int, List<double>>();
                                //commonList contains the common intensities
                                List<double> duplicateList = new List<double>();

                                //call the method
                                List<double> completeIntensityList = new List<double>();
                                for (int k = 1; k < len; k++)
                                {
                                    List<double> intensityList = new List<double>();

                                    string bion = pepSequence.Substring(0, k);
                                    string yion = pepSequence.Substring(k, len - k);

                                    int NR = Package.parseAAResidues(bion, 'R');
                                    int NK = Package.parseAAResidues(bion, 'K');
                                    int NH = Package.parseAAResidues(bion, 'H');
                                    int NL = k;
                                    int CR = Package.parseAAResidues(yion, 'R');
                                    int CK = Package.parseAAResidues(yion, 'K');
                                    int CH = Package.parseAAResidues(yion, 'H');
                                    int CL = len - k;
                                    int R = NR - CR;
                                    int K = NK - CK;
                                    int H = NH - CH;
                                    int L = NL - CL;
                                    int pepBond = k;
                                    int NBasicAA = NR + NK + NH;
                                    int CBasicAA = CR + CK + CH;
                                    string AA = NBasicAA + "," + CBasicAA + "," + NR + "," + NK + "," + NH + "," + NL + "," + CR + "," + CK + "," + CH + "," + CL + "," + R + "," + K + "," + H + "," + L;

                                    double[] bCharge = new double[z + 1];
                                    double[] yCharge = new double[z + 1];
                                    double[] bIntensity = new double[z + 1];
                                    double[] yIntensity = new double[z + 1];
                                    string bIonIntensity = "";
                                    string yIonIntensity = "";
                                    //to judge if the sum of intensities are 0
                                    //so to exclude the case with all "0s"
                                    double sumIntensity = 0;

                                    //return the b ion charge 1 Intensity, if matched
                                    for (int i = 1; i <= z; i++)
                                    {
                                        bCharge[i] = fragmentation.b(k, i);
                                        yCharge[i] = fragmentation.y(len - k, i);
                                        //change for Q-star purposes.
                                        Peak bmatched = Package.findClose(peakList, bCharge[i], 70 * bCharge[i] * Math.Pow(10, -6));
                                        Peak ymatched = Package.findClose(peakList, yCharge[i], 70 * yCharge[i] * Math.Pow(10, -6));
                                        if (bmatched != null)
                                        {
                                            bIntensity[i] = bmatched.rankOrIntensity;
                                            intensityList.Add(bmatched.rankOrIntensity);
                                            completeIntensityList.Add(bmatched.rankOrIntensity);
                                        }
                                        else bIntensity[i] = 0;
                                        if (ymatched != null)
                                        {
                                            yIntensity[i] = ymatched.rankOrIntensity;
                                            intensityList.Add(ymatched.rankOrIntensity);
                                            completeIntensityList.Add(ymatched.rankOrIntensity);
                                        }
                                        else yIntensity[i] = 0;

                                        sumIntensity = sumIntensity + bIntensity[i] + yIntensity[i];

                                        //record b/y ion intensity information into a string
                                        bIonIntensity = bIonIntensity + "," + bIntensity[i];
                                        yIonIntensity = yIonIntensity + "," + yIntensity[i];

                                    }

                                    intensityDic.Add(pepBond, intensityList);
                                    //to determine charge label, need to split by precursor charge
                                    //first need to make a metric to determine if all intensities are "0"

                                    if (z == 3)
                                    {
                                        if (sumIntensity != 0)
                                        {
                                            ////////////////////////////////////////////////
                                            //set the ambiguity label as follows:
                                            //-3: (0/+3) y3 only
                                            //-2: (0/+3, +1/+2) y3, b1y2
                                            //-1: (+1/+2): b1y2
                                            //0: (+1/+2, +2/+1): b1y2, b2y1
                                            //1: (+2/+1): b2y1
                                            //2: (+2/+1, +3/0): b2y1, b3
                                            //3: (+3/0): b3 only
                                            ////////////////////////////////////////////////

                                            double b1 = bIntensity[1];
                                            double b2 = bIntensity[2];
                                            double y1 = yIntensity[1];
                                            double y2 = yIntensity[2];
                                            double b3 = bIntensity[3];
                                            double y3 = yIntensity[3];
                                            double b1y2 = b1 + y2;
                                            double b2y1 = b2 + y1;
                                            string ambiguityLabel = "";
                                            //first part: set the intensity group: y3, b1y2, b2y1, b3
                                            //if one group was found, set the label
                                            //if two were found, but adjacent to each other, then ambiguity label is set
                                            if (y3 != 0 && (b1y2 + b2y1 + b3) == 0) ambiguityLabel = "-3";
                                            else if (y3 != 0 && b1y2 != 0 && (b2y1 + b3) == 0) ambiguityLabel = "-2";
                                            else if (b1y2 != 0 && (y3 + b2y1 + b3) == 0) ambiguityLabel = "-1";
                                            else if (b1y2 != 0 && b2y1 != 0 && (y3 + b3) == 0) ambiguityLabel = "0";
                                            else if (b2y1 != 0 && (y3 + b1y2 + b3) == 0) ambiguityLabel = "1";
                                            else if (b2y1 != 0 && b3 != 0 && (y3 + b1y2) == 0) ambiguityLabel = "2";
                                            else if (b3 != 0 && (y3 + b1y2 + b2y1) == 0) ambiguityLabel = "3";
                                            else ambiguityLabel = "error";

                                            string finalString = idOrIndex + "," + pepSequence + "," + basePeak + "," + TIC + bIonIntensity + yIonIntensity + "," + len + "," + pepBond + "," + AA + "," + ambiguityLabel;
                                            rowDic.Add(pepBond, finalString);
                                        }
                                    }
                                }//end for each peptide bond

                                //now we have: rowDic, intensityDic for each pep bond
                                //and we have: and completeIntensityList for each peptide
                                //the purpose of this is to remove such rows with duplicate matches
                                duplicateList = Package.findCommon(completeIntensityList);
                                foreach (int bond in rowDic.Keys)
                                {
                                    bool unique = true;
                                    foreach (double inten in duplicateList)
                                    {
                                        if (intensityDic[bond].Contains(inten))
                                        {
                                            unique = false;
                                            Console.WriteLine("kick");
                                            break;
                                        }
                                    }
                                    if (unique)
                                    {
                                        output.Add(rowDic[bond]);
                                    }
                                }
                            }//end of if peplist contains pepsequence
                        }//end if z==3
                    }//end foreach peptide
            return output;
        }
Ejemplo n.º 39
0
        public double[] ConvertToFullIntensityVector(Peak[] spectrum, int length, FilteredProteinMassBinning comparer)
        {
            var intensityVector = new double[length];
            Array.Clear(intensityVector,0,length);
            spectrum = RemovePeaks(10000.0, spectrum);

            for (var i = 0; i < spectrum.Length; i++)
            {
                var binNumber = comparer.GetBinNumber(spectrum[i].Mz);
                if (binNumber >= 0)
                {
                    intensityVector[binNumber - 1] = spectrum[i].Intensity;
                }
            }
            return intensityVector;
        }
Ejemplo n.º 40
0
 public double GetDistanceTo(Peak peak)
 {
     return Math.Max(Math.Abs(StartTime - peak.StartTime), Math.Abs(EndTime - peak.EndTime));
 }
Ejemplo n.º 41
0
    /// <summary>
    /// Subscribes to the spectrum visualiser's SpectrumChangedEvent,
    /// and spawns bubbles at peaks in the rendered spectrum.
    /// </summary>
    private void OnSpectrumBandsUpdate(object sender, SpectrumChangedEventArgs e)
    {
        // Get the spectrum band point positions from the event args.
        spectrumBandPoints = e.BandPoints;

        // Set the bubble spawn velocity, which is straight upwards at the specified speed.
        Vector3 spawnVelocity = new Vector3(0, options.spawnVelocityY, 0);

        // For each point, check if it is eligible to spawn a bubble and if so de-pool
        // a bubble at the required position with velocity spawnVelocity.
        // The aim is to create an effect where bubbles are spawned by peaks in the
        // rendered spectrum, at the time when each peak reaches its maximum height.
        for (int i = 1; i < spectrumBandPoints.Length - 1; i++)
        {
            // Is this point an eligible peak?
            if (oldSpectrumBandPoints != null && oldDirections != null && IsPeak(spectrumBandPoints, i))
            {
                // If so, create a new Peak instance at this point's previous position
                // which represents the peak's maximum height.
                Peak peak = new Peak(i, oldSpectrumBandPoints[i]);

                // If we aren't already aware of this peak (i.e. we haven't recently spawned
                // any bubbles from there) then we spawn the new bubble and add this peak to the list.
                if (!spectrumPeaks.Contains(peak) && activeBubbles.Count < options.maxBubbles)
                {
                    CreateBubble(oldSpectrumBandPoints[i], spawnVelocity);
                    spectrumPeaks.Add(peak);
                }
            }
        }

        // Check if any of our saved peaks (that have recently spawned a bubble)
        // are eligible to be removed, i.e. allowed to spawn more bubbles.
        for (int i = spectrumPeaks.Count - 1; i >= 0; i--)
        {
            if (IsNoLongerPeak(spectrumPeaks[i]))
            {
                spectrumPeaks.RemoveAt(i);
            }
        }

        if (oldSpectrumBandPoints == null)
        {
            // First update: create the arrays to hold the previous point locations
            // and the previous directions of change for each point. 
            oldSpectrumBandPoints = new Vector3[spectrumBandPoints.Length];
            oldDirections = new int[spectrumBandPoints.Length];
        } else
        {
            // Store the direction of change for each point. This will be used
            // to decide when a peak reaches its maximum amplitude.
            for (int i = 0; i < spectrumBandPoints.Length; i++)
            {
                oldDirections[i] = spectrumBandPoints[i].y > oldSpectrumBandPoints[i].y ? 1 : -1;
            }
        }
        spectrumBandPoints.CopyTo(oldSpectrumBandPoints, 0);
    }
Ejemplo n.º 42
0
        public static List<Peak> Sum(IList<Peak> peakList1, IList<Peak> peakList2,
            IComparer<Peak> comparer)
        {
            var count1 = peakList1.Count;
            var count2 = peakList2.Count;
            var index1 = 0;
            var index2 = 0;

            var sum = new List<Peak>();

            while (index1 < count1 && index2 < count2)
            {
                var p1 = peakList1[index1];
                var p2 = peakList2[index2];

                var comp = comparer.Compare(peakList1[index1], peakList2[index2]);
                if (comp < 0)
                {
                    sum.Add(p1);
                    ++index1;
                }
                else if (comp > 0)
                {
                    sum.Add(p2);
                    ++index2;
                }
                else
                {
                    peakList1[index1] = new Peak(p1.Mz, p1.Intensity + p2.Intensity);
                    ++index2;
                }
            }

            while (index1 < count1) sum.Add(peakList1[index1++]);
            while (index2 < count2) sum.Add(peakList2[index2++]);

            return sum;
        }
Ejemplo n.º 43
0
 private bool IsNoLongerPeak(Peak peak)
 {
     float currentHeight = spectrumBandPoints[peak.index].y - yOrigin;
     float peakHeight = peak.position.y - yOrigin;
     return currentHeight < options.newPeakHeightThreshold * peakHeight;
 }
Ejemplo n.º 44
0
        public static Tuple<double, double> GetDistCorr(Ion ion, Peak[] observedPeaks)
        {
            var isotopomerEnvelope = ion.Composition.GetIsotopomerEnvelopeRelativeIntensities();
            var envelope = isotopomerEnvelope;
            var observedIntensities = new double[envelope.Length];
            for (var i = 0; i < isotopomerEnvelope.Length; i++)
            {
                if (observedPeaks[i] != null) observedIntensities[i] = observedPeaks[i].Intensity;
            }

            return FitScoreCalculator.GetDistanceAndCorrelation(envelope, observedIntensities);
            //var bcDist = FitScoreCalculator.GetBhattacharyyaDistance(envelope, observedIntensities);
            //var corr = FitScoreCalculator.GetPearsonCorrelation(envelope, observedIntensities);
            //return new Tuple<double, double>(bcDist, corr);
        }
Ejemplo n.º 45
0
        private ScanSet createScanSetFromChromatogramPeak(Run run, Peak chromPeak)
        {
            var sigma      = chromPeak.Width / 2.35; //   width@half-height =  2.35σ   (Gaussian peak theory)
            var centerXVal = chromPeak.XValue;

            var leftMostScan  = (int)Math.Floor(centerXVal - sigma);
            var rightMostScan = (int)Math.Ceiling(centerXVal + sigma);
            var centerScan    = (int)Math.Round(centerXVal);

            centerScan    = run.GetClosestMSScan(centerScan, DeconTools.Backend.Globals.ScanSelectionMode.CLOSEST);
            leftMostScan  = run.GetClosestMSScan(leftMostScan, DeconTools.Backend.Globals.ScanSelectionMode.DESCENDING);
            rightMostScan = run.GetClosestMSScan(rightMostScan, DeconTools.Backend.Globals.ScanSelectionMode.ASCENDING);

            var scanIndexList = new List <int>();


            //the idea is to start at the center scan and add scans to the left and right.  It is easier to set a maximum number of scans to add this way.

            var maxScansToAddToTheLeft  = 0;
            var maxScansToAddToTheRight = 0;

            //add center scan
            scanIndexList.Add(centerScan);

            //add to the left of center
            var numScansAdded = 0;

            for (var i = (centerScan - 1); i >= leftMostScan; i--)
            {
                if (run.GetMSLevel(i) == 1)
                {
                    scanIndexList.Add(i);

                    numScansAdded++;
                    if (numScansAdded >= maxScansToAddToTheLeft)
                    {
                        break;
                    }
                }
            }

            //add to the right of center
            numScansAdded = 0;
            for (var i = (centerScan + 1); i <= rightMostScan; i++)
            {
                if (run.GetMSLevel(i) == 1)
                {
                    scanIndexList.Add(i);

                    numScansAdded++;
                    if (numScansAdded >= maxScansToAddToTheRight)
                    {
                        break;
                    }
                }
            }

            scanIndexList.Sort();

            //ScanSet scanSet = new ScanSet(centerScan, scanIndexList.ToArray());
            var scanSet = new ScanSet(centerScan);

            return(scanSet);
        }