Example #1
0
        public void WriteResults(string peaksOutputPath, string modPeptideOutputPath, string baseSeqPeptideOutputPath, string proteinOutputPath)
        {
            if (peaksOutputPath != null)
            {
                using (StreamWriter output = new StreamWriter(peaksOutputPath))
                {
                    output.WriteLine(ChromatographicPeak.TabSeparatedHeader);

                    foreach (var peak in Peaks.SelectMany(p => p.Value))
                    {
                        output.WriteLine(peak.ToString());
                    }
                }
            }

            if (modPeptideOutputPath != null)
            {
                using (StreamWriter output = new StreamWriter(modPeptideOutputPath))
                {
                    output.WriteLine(Peptide.TabSeparatedHeader(SpectraFiles));

                    foreach (var peptide in PeptideModifiedSequences.OrderBy(p => p.Key))
                    {
                        output.WriteLine(peptide.Value.ToString(SpectraFiles));
                    }
                }
            }

            if (baseSeqPeptideOutputPath != null)
            {
                using (StreamWriter output = new StreamWriter(baseSeqPeptideOutputPath))
                {
                    output.WriteLine(Peptide.TabSeparatedHeader(SpectraFiles));

                    foreach (var peptide in PeptideBaseSequences.OrderBy(p => p.Key))
                    {
                        output.WriteLine(peptide.Value.ToString(SpectraFiles));
                    }
                }
            }

            if (proteinOutputPath != null)
            {
                using (StreamWriter output = new StreamWriter(proteinOutputPath))
                {
                    output.WriteLine(ProteinGroup.TabSeparatedHeader(SpectraFiles));

                    foreach (var protein in ProteinGroups.OrderBy(p => p.Key))
                    {
                        output.WriteLine(protein.Value.ToString(SpectraFiles));
                    }
                }
            }
        }
Example #2
0
        public void MergeResultsWith(FlashLfqResults mergeFrom)
        {
            this.SpectraFiles.AddRange(mergeFrom.SpectraFiles);

            foreach (var pep in mergeFrom.PeptideModifiedSequences)
            {
                if (this.PeptideModifiedSequences.TryGetValue(pep.Key, out var peptide))
                {
                    Peptide mergeFromPep = pep.Value;
                    Peptide mergeToPep = peptide;

                    foreach (SpectraFileInfo file in mergeFrom.SpectraFiles)
                    {
                        mergeToPep.SetIntensity(file, mergeFromPep.GetIntensity(file));
                        mergeToPep.SetDetectionType(file, mergeFromPep.GetDetectionType(file));
                    }
                }
                else
                {
                    this.PeptideModifiedSequences.Add(pep.Key, pep.Value);
                }
            }

            foreach (var pg in mergeFrom.ProteinGroups)
            {
                if (this.ProteinGroups.TryGetValue(pg.Key, out var proteinGroup))
                {
                    ProteinGroup mergeFromPg = pg.Value;
                    ProteinGroup mergeToPg = proteinGroup;

                    foreach (SpectraFileInfo file in mergeFrom.SpectraFiles)
                    {
                        mergeToPg.SetIntensity(file, mergeFromPg.GetIntensity(file));
                    }
                }
                else
                {
                    this.ProteinGroups.Add(pg.Key, pg.Value);
                }
            }

            foreach (var fromPeaks in mergeFrom.Peaks)
            {
                if (this.Peaks.TryGetValue(fromPeaks.Key, out var toPeaks))
                {
                    toPeaks.AddRange(fromPeaks.Value);
                }
                else
                {
                    this.Peaks.Add(fromPeaks.Key, fromPeaks.Value);
                }
            }
        }
Example #3
0
        //If SILAC (Post-Quantification), compress the light/heavy protein group pairs into the same light protein group but different files
        //Create new files for each silac label and file so that "file 1" now becomes "file 1 (light)" and "file 1 (heavy)"
        //Change heavy residue into the light residue plus a string label ("PEPTIDEa" -> "PEPTIDEK(+8.014)")
        //This light to heavy conversion needs to happen for the flashLFQ peptides here, but can't for the psm peptides, which are constrained to the protein
        //i.e. pwsms currently don't have sequences; they have start/end residues and a protein sequence. We have to change the output sequences when they're created.
        public static void SilacConversionsPostQuantification(List <SilacLabel> allSilacLabels, SilacLabel startLabel, SilacLabel endLabel,
                                                              List <SpectraFileInfo> spectraFileInfo, List <ProteinGroup> proteinGroups, HashSet <DigestionParams> listOfDigestionParams, FlashLfqResults flashLfqResults,
                                                              List <PeptideSpectralMatch> allPsms, Dictionary <string, int> modsToWriteSelection, bool quantifyUnlabeledPeptides)
        {
            //do protein quant if we had any results
            //if no results, we still may need to edit the psms
            if (flashLfqResults != null) //can be null if no unambiguous psms were found
            {
                //after this point, we now have quantification values for the peptides, but they all belong to the same "unlabeled" protein and are in the same file
                //We can remove "labeled" peptides from each file and put them in a new file as "unlabeled".

                //MAKE NEW RAW FILES

                //update number of spectra files to include a new file for each label/condition
                Dictionary <SpectraFileInfo, List <SpectraFileInfo> > originalToLabeledFileInfoDictionary = CreateSilacRawFiles(flashLfqResults, allSilacLabels, startLabel, endLabel, quantifyUnlabeledPeptides, spectraFileInfo);

                //we have the files, now let's reassign the psms.
                //there are a few ways to do this, but we're going to generate the "base" peptide and assign to that

                //Get Dictionary of protein accessions to peptides
                Dictionary <string, List <FlashLFQ.Peptide> > unlabeledToPeptidesDictionary = GetDictionaryOfProteinAccessionsToPeptides(flashLfqResults.PeptideModifiedSequences.Values, allSilacLabels, startLabel, endLabel);

                //we now have a dictionary of unlabeledBaseSequence to the labeled peptides
                //Better SILAC results can be obtained by using the summed intensities from ms1 scans where all peaks were found, rather than the apex
                //foreach peptide, unlabeled peptide, get the isotopic envelope intensities for each labeled peptide in each file
                //save the intensities from ms1s that are shared. If no ms1s contains all the peaks, then just use the apex intensity (default)
                CalculateSilacIntensities(flashLfqResults.Peaks, unlabeledToPeptidesDictionary);


                //SPLIT THE FILES
                List <FlashLFQ.Peptide> updatedPeptides = new List <FlashLFQ.Peptide>();

                //split the heavy/light peptides into separate raw files, remove the heavy peptide
                if (startLabel != null || endLabel != null) //if turnover
                {
                    //foreach group, the labeled peptides should be split into their labeled files
                    //we're deleting the heavy results after we pull those results into a different file
                    foreach (SpectraFileInfo info in spectraFileInfo)
                    {
                        string          fullPathWithExtension    = info.FullFilePathWithExtension;
                        string[]        pathArray                = fullPathWithExtension.Split('.');
                        string          extension                = pathArray.Last();
                        string          filePathWithoutExtension = fullPathWithExtension.Substring(0, fullPathWithExtension.Length - extension.Length - 1); //-1 removes the '.'
                        SpectraFileInfo lightInfo                = new SpectraFileInfo(filePathWithoutExtension + "_Original." + extension, info.Condition, info.BiologicalReplicate, info.TechnicalReplicate, info.Fraction);
                        SpectraFileInfo heavyInfo                = new SpectraFileInfo(filePathWithoutExtension + "_NewlySynthesized." + extension, info.Condition + "_NewlySynthesized", info.BiologicalReplicate, info.TechnicalReplicate, info.Fraction);
                        originalToLabeledFileInfoDictionary[info] = new List <SpectraFileInfo> {
                            lightInfo, heavyInfo
                        };
                        flashLfqResults.SpectraFiles.Add(lightInfo);
                        flashLfqResults.SpectraFiles.Add(heavyInfo);
                    }

                    //This step converts the quantification intensities from light/heavy to original/newlySynthesized by splitting up the missed cleavage mixtures
                    foreach (KeyValuePair <string, List <FlashLFQ.Peptide> > kvp in unlabeledToPeptidesDictionary)
                    {
                        string unlabeledSequence         = kvp.Key; //this will be the key for the new quant entry
                        List <FlashLFQ.Peptide> peptides = kvp.Value;
                        if (peptides.Count != 1)                    //sometimes it's one if there is no label site on the peptide (e.g. label K, peptide is PEPTIDER)
                        {
                            //Missed cleavages can yield multiple peptides (e.g. 1 missed = LL, LH, HH; 2 missed = LLL, LLH, LHH, HHH; etc)
                            //Compress into 2 values: Light and Heavy
                            FlashLFQ.Peptide updatedPeptide = new FlashLFQ.Peptide(unlabeledSequence, unlabeledSequence, peptides[0].UseForProteinQuant, CleanPastProteinQuant(peptides[0].ProteinGroups)); //needed to keep protein info.
                            foreach (SpectraFileInfo info in spectraFileInfo)
                            {
                                int    maxNumberHeavyAminoAcids    = peptides.Count - 1;
                                double lightIntensity              = 0;
                                double heavyIntensity              = 0;
                                int    numUniquePeptidesQuantified = 0;
                                for (int numHeavyAminoAcids = 0; numHeavyAminoAcids < peptides.Count; numHeavyAminoAcids++)
                                {
                                    double totalIntensity = peptides[numHeavyAminoAcids].GetIntensity(info);
                                    if (totalIntensity > 0)
                                    {
                                        //prevent confidence of a ratio if only the HL (and not the LL or HH) is observed.
                                        //If LL or HH is observed (but not any other), the user knows the ratio is only from one peak.
                                        if (numHeavyAminoAcids == 0 || numHeavyAminoAcids == maxNumberHeavyAminoAcids)
                                        {
                                            numUniquePeptidesQuantified += 2;
                                        }
                                        else
                                        {
                                            numUniquePeptidesQuantified++;
                                        }
                                        double partHeavyIntensity = totalIntensity * numHeavyAminoAcids / maxNumberHeavyAminoAcids;
                                        lightIntensity += totalIntensity - partHeavyIntensity;
                                        heavyIntensity += partHeavyIntensity;
                                    }
                                }
                                //If only a mixed peptide with a missed cleavage was identified, reset the intensity values to zero so the user doesn't get a discreet, inaccurate measurement
                                if (numUniquePeptidesQuantified < 2)
                                {
                                    lightIntensity = 0;
                                    heavyIntensity = 0;
                                }

                                List <SpectraFileInfo> updatedInfo = originalToLabeledFileInfoDictionary[info];
                                SpectraFileInfo        startInfo   = updatedInfo[0];
                                SpectraFileInfo        endInfo     = updatedInfo[1];

                                updatedPeptide.SetIntensity(startInfo, lightIntensity);                           //assign the corrected light intensity
                                updatedPeptide.SetDetectionType(startInfo, peptides.First().GetDetectionType(info));
                                updatedPeptide.SetIntensity(endInfo, heavyIntensity);                             //assign the corrected heavy intensity to the heavy file
                                updatedPeptide.SetDetectionType(endInfo, peptides.Last().GetDetectionType(info)); //could include the mixed here if it really matters
                            }

                            //add the updated peptide to the list
                            updatedPeptides.Add(updatedPeptide);
                        }
                        else
                        {
                            updatedPeptides.Add(peptides[0]);
                        }
                    }
                }
                else //multiplex
                {
                    foreach (var kvp in unlabeledToPeptidesDictionary)
                    {
                        string unlabeledSequence         = kvp.Key;
                        List <FlashLFQ.Peptide> peptides = kvp.Value;
                        FlashLFQ.Peptide        representativePeptide = peptides[0];
                        FlashLFQ.Peptide        updatedPeptide        = new FlashLFQ.Peptide(unlabeledSequence, unlabeledSequence, representativePeptide.UseForProteinQuant, CleanPastProteinQuant(representativePeptide.ProteinGroups)); //needed to keep protein info.

                        //foreach original file
                        foreach (SpectraFileInfo info in spectraFileInfo)
                        {
                            List <SpectraFileInfo> filesForThisFile = originalToLabeledFileInfoDictionary[info];
                            for (int i = 0; i < peptides.Count; i++) //the files and the peptides can use the same index, because there should be a distinct file for each label/peptide
                            {
                                SpectraFileInfo  currentInfo    = filesForThisFile[i];
                                FlashLFQ.Peptide currentPeptide = peptides[i];
                                updatedPeptide.SetIntensity(currentInfo, currentPeptide.GetIntensity(info));
                                updatedPeptide.SetDetectionType(currentInfo, currentPeptide.GetDetectionType(info));
                            }
                        }
                        updatedPeptides.Add(updatedPeptide);
                    }
                }

                //Update peptides
                var peptideResults = flashLfqResults.PeptideModifiedSequences;
                peptideResults.Clear();
                foreach (FlashLFQ.Peptide peptide in updatedPeptides)
                {
                    peptideResults.Add(peptide.Sequence, peptide);
                }

                //Do protein quant
                flashLfqResults.CalculateProteinResultsMedianPolish(true);

                //update proteingroups to have all files for quantification
                if (proteinGroups != null)
                {
                    List <SpectraFileInfo> allInfo = originalToLabeledFileInfoDictionary.SelectMany(x => x.Value).ToList();
                    foreach (ProteinGroup proteinGroup in proteinGroups)
                    {
                        proteinGroup.FilesForQuantification = allInfo;
                        proteinGroup.IntensitiesByFile      = new Dictionary <SpectraFileInfo, double>();

                        foreach (var spectraFile in allInfo)
                        {
                            if (flashLfqResults.ProteinGroups.TryGetValue(proteinGroup.ProteinGroupName, out var flashLfqProteinGroup))
                            {
                                proteinGroup.IntensitiesByFile.Add(spectraFile, flashLfqProteinGroup.GetIntensity(spectraFile));
                            }
                            else
                            {
                                //needed for decoys/contaminants/proteins that aren't quantified
                                proteinGroup.IntensitiesByFile.Add(spectraFile, 0);
                            }
                        }
                    }
                }

                //Convert all lfqpeaks from heavy (a) to light (K+8.014) for output
                if (flashLfqResults != null) //can be null if nothing was quantified (all peptides are ambiguous)
                {
                    var lfqPeaks = flashLfqResults.Peaks;
                    List <SpectraFileInfo> peakKeys = lfqPeaks.Keys.ToList();

                    foreach (SpectraFileInfo key in peakKeys)
                    {
                        List <ChromatographicPeak> peaks = lfqPeaks[key];
                        for (int i = 0; i < peaks.Count; i++)
                        {
                            var peak = peaks[i];
                            //check if we're removing light peaks and if it's a light peak
                            if (peak.Identifications.Any(x => GetRelevantLabelFromBaseSequence(x.BaseSequence, allSilacLabels) != null)) //if no ids have any labels, remove them
                            {
                                List <Identification> updatedIds = new List <Identification>();
                                foreach (var id in peak.Identifications)
                                {
                                    string            baseSequence = id.BaseSequence;
                                    string            fullSequence = id.ModifiedSequence;
                                    List <SilacLabel> labels       = GetRelevantLabelsFromBaseSequenceForOutput(id.BaseSequence, allSilacLabels);
                                    if (labels != null)
                                    {
                                        foreach (SilacLabel label in labels)
                                        {
                                            baseSequence = GetSilacLightBaseSequence(baseSequence, label);
                                            fullSequence = GetSilacLightFullSequence(fullSequence, label);
                                        }
                                    }

                                    Identification updatedId = new Identification(
                                        id.FileInfo,
                                        baseSequence,
                                        fullSequence,
                                        id.MonoisotopicMass,
                                        id.Ms2RetentionTimeInMinutes,
                                        id.PrecursorChargeState,
                                        id.ProteinGroups.ToList(),
                                        id.OptionalChemicalFormula,
                                        id.UseForProteinQuant
                                        );
                                    updatedIds.Add(updatedId);
                                }
                                peak.Identifications.Clear();
                                peak.Identifications.AddRange(updatedIds);
                            }
                        }
                    }
                }
            }

            //convert all psms into human readable format
            for (int i = 0; i < allPsms.Count; i++)
            {
                allPsms[i].ResolveHeavySilacLabel(allSilacLabels, modsToWriteSelection);
            }
        }
Example #4
0
        public void WriteResults(string peaksOutputPath, string modPeptideOutputPath, string proteinOutputPath, string bayesianProteinQuantOutput, bool silent)
        {
            if (!silent)
            {
                Console.WriteLine("Writing output...");
            }

            if (peaksOutputPath != null)
            {
                using (StreamWriter output = new StreamWriter(peaksOutputPath))
                {
                    output.WriteLine(ChromatographicPeak.TabSeparatedHeader);

                    foreach (var peak in Peaks.SelectMany(p => p.Value)
                        .OrderBy(p => p.SpectraFileInfo.FilenameWithoutExtension)
                        .ThenByDescending(p => p.Intensity))
                    {
                        output.WriteLine(peak.ToString());
                    }
                }
            }

            if (modPeptideOutputPath != null)
            {
                using (StreamWriter output = new StreamWriter(modPeptideOutputPath))
                {
                    output.WriteLine(Peptide.TabSeparatedHeader(SpectraFiles));

                    foreach (var peptide in PeptideModifiedSequences.OrderBy(p => p.Key))
                    {
                        output.WriteLine(peptide.Value.ToString(SpectraFiles));
                    }
                }
            }

            if (proteinOutputPath != null)
            {
                using (StreamWriter output = new StreamWriter(proteinOutputPath))
                {
                    output.WriteLine(ProteinGroup.TabSeparatedHeader(SpectraFiles));

                    foreach (var protein in ProteinGroups.OrderBy(p => p.Key))
                    {
                        output.WriteLine(protein.Value.ToString(SpectraFiles));
                    }
                }
            }

            if (bayesianProteinQuantOutput != null)
            {
                StringBuilder header = new StringBuilder();
                StringBuilder[] proteinStringBuilders = new StringBuilder[ProteinGroups.Count];

                for (int i = 0; i < proteinStringBuilders.Length; i++)
                {
                    proteinStringBuilders[i] = new StringBuilder();
                }

                using (StreamWriter output = new StreamWriter(bayesianProteinQuantOutput))
                {
                    if (!ProteinGroups.Any())
                    {
                        return;
                    }

                    var firstProteinQuantResults = ProteinGroups.First().Value.ConditionToQuantificationResults;

                    if (!firstProteinQuantResults.Any())
                    {
                        return;
                    }

                    string tabSepHeader = null;

                    if (firstProteinQuantResults.First().Value is PairedProteinQuantResult)
                    {
                        tabSepHeader = PairedProteinQuantResult.TabSeparatedHeader();
                    }
                    else
                    {
                        tabSepHeader = UnpairedProteinQuantResult.TabSeparatedHeader();
                    }

                    foreach (var condition in firstProteinQuantResults.Keys)
                    {
                        header.Append(tabSepHeader);

                        int p = 0;

                        // sort by protein false discovery rate, then by number of measurements
                        foreach (var protein in ProteinGroups
                            .OrderByDescending(v => v.Value.ConditionToQuantificationResults[condition].IsStatisticallyValid)
                            .ThenByDescending(v => v.Value.ConditionToQuantificationResults[condition].BayesFactor)
                            .ThenByDescending(v => v.Value.ConditionToQuantificationResults[condition].Peptides.Count))
                        {
                            proteinStringBuilders[p].Append(
                                protein.Value.ConditionToQuantificationResults[condition].ToString());

                            p++;
                        }
                    }

                    output.WriteLine(header);

                    foreach (var proteinStringBuilder in proteinStringBuilders)
                    {
                        output.WriteLine(proteinStringBuilder);
                    }
                }
            }

            if (!silent)
            {
                Console.WriteLine("Finished writing output");
            }
        }
Example #5
0
        public void WriteResults(string peaksOutputPath, string modPeptideOutputPath, string proteinOutputPath, string bayesianProteinQuantOutput, bool silent)
        {
            if (!silent)
            {
                Console.WriteLine("Writing output...");
            }

            if (peaksOutputPath != null)
            {
                using (StreamWriter output = new StreamWriter(peaksOutputPath))
                {
                    output.WriteLine(ChromatographicPeak.TabSeparatedHeader);

                    foreach (var peak in Peaks.SelectMany(p => p.Value))
                    {
                        output.WriteLine(peak.ToString());
                    }
                }
            }

            if (modPeptideOutputPath != null)
            {
                using (StreamWriter output = new StreamWriter(modPeptideOutputPath))
                {
                    output.WriteLine(Peptide.TabSeparatedHeader(SpectraFiles));

                    foreach (var peptide in PeptideModifiedSequences.OrderBy(p => p.Key))
                    {
                        output.WriteLine(peptide.Value.ToString(SpectraFiles));
                    }
                }
            }

            if (proteinOutputPath != null)
            {
                using (StreamWriter output = new StreamWriter(proteinOutputPath))
                {
                    output.WriteLine(ProteinGroup.TabSeparatedHeader(SpectraFiles));

                    foreach (var protein in ProteinGroups.OrderBy(p => p.Key))
                    {
                        output.WriteLine(protein.Value.ToString(SpectraFiles));
                    }
                }
            }

            if (bayesianProteinQuantOutput != null)
            {
                StringBuilder   header = new StringBuilder();
                StringBuilder[] proteinStringBuilders = new StringBuilder[ProteinGroups.Count];

                for (int i = 0; i < proteinStringBuilders.Length; i++)
                {
                    proteinStringBuilders[i] = new StringBuilder();
                }

                using (StreamWriter output = new StreamWriter(bayesianProteinQuantOutput))
                {
                    if (!ProteinGroups.Any())
                    {
                        return;
                    }

                    var firstProteinQuantResults = ProteinGroups.First().Value.ConditionToQuantificationResults;

                    if (!firstProteinQuantResults.Any())
                    {
                        return;
                    }

                    foreach (var condition in firstProteinQuantResults.Keys)
                    {
                        header.Append(ProteinQuantificationEngineResult.TabSeparatedHeader());

                        int p = 0;

                        // sort by protein false discovery rate, then by number of fold-change measurements
                        foreach (var protein in ProteinGroups
                                 .OrderBy(v => v.Value.ConditionToQuantificationResults[condition].FalseDiscoveryRate)
                                 .ThenByDescending(v => v.Value.ConditionToQuantificationResults[condition].PeptideFoldChangeMeasurements.SelectMany(b => b.foldChanges).Count()))
                        {
                            proteinStringBuilders[p].Append(
                                protein.Value.ConditionToQuantificationResults[condition].ToString());

                            p++;
                        }
                    }

                    output.WriteLine(header);

                    foreach (var proteinStringBuilder in proteinStringBuilders)
                    {
                        output.WriteLine(proteinStringBuilder);
                    }
                }
            }

            if (!silent)
            {
                Console.WriteLine("Finished writing output");
            }
        }
        //If SILAC (Post-Quantification), compress the light/heavy protein group pairs into the same light protein group but different files
        //Create new files for each silac label and file so that "file 1" now becomes "file 1 (light)" and "file 1 (heavy)"
        //Change heavy residue into the light residue plus a string label ("PEPTIDEa" -> "PEPTIDEK(+8.014)")
        //This light to heavy conversion needs to happen for the flashLFQ peptides here, but can't for the psm peptides, which are constrained to the protein
        //i.e. pwsms currently don't have sequences; they have start/end residues and a protein sequence. We have to change the output sequences when they're created.
        public static void SilacConversionsPostQuantification(List <SilacLabel> silacLabels, List <SpectraFileInfo> spectraFileInfo, List <ProteinGroup> ProteinGroups,
                                                              HashSet <DigestionParams> ListOfDigestionParams, Dictionary <string, List <string> > silacProteinGroupMatcher, FlashLfqResults FlashLfqResults,
                                                              List <PeptideSpectralMatch> allPsms, Dictionary <string, int> ModsToWriteSelection, bool Integrate)
        {
            bool outputLightIntensities = ListOfDigestionParams.Any(x => x.GeneratehUnlabeledProteinsForSilac);


            //MAKE NEW RAW FILES
            //update number of spectra files to include a new file for each label*condition
            Dictionary <SpectraFileInfo, string>          fileToLabelDictionary  = new Dictionary <SpectraFileInfo, string>();          //figure out which file is which label, since some files will be only light and others only heavy. Key is file, value is the label string (label.MassDifference)
            Dictionary <SpectraFileInfo, SpectraFileInfo> labeledToUnlabeledFile = new Dictionary <SpectraFileInfo, SpectraFileInfo>(); //keep track of the heavy-to-light pairs. If multiple, looks like 3-1 and 2-1, but no 3-2 (only heavy to light, no heavy to heavy)
            List <SpectraFileInfo> silacSpectraFileInfo = new List <SpectraFileInfo>();                                                 //new files

            //foreach existing file
            foreach (SpectraFileInfo originalFile in spectraFileInfo)
            {
                //add the existing file as the light
                silacSpectraFileInfo.Add(originalFile);
                //foreach label, add a new file with the label
                foreach (SilacLabel label in silacLabels)
                {
                    SpectraFileInfo silacFile = GetHeavyFileInfo(originalFile, label);
                    silacSpectraFileInfo.Add(silacFile);
                    fileToLabelDictionary[silacFile]  = label.MassDifference;
                    labeledToUnlabeledFile[silacFile] = originalFile;
                }
            }


            //UPDATE PROTEIN GROUPS
            //remove the heavy protein groups so that there are only light ones
            //add the intensities of the heavy groups into the newly created heavy SpectraFileInfos
            HashSet <SpectraFileInfo> lightFilesToRemove = new HashSet <SpectraFileInfo>(); //this is only used when there user specified no unlabeled proteins

            if (ProteinGroups != null)                                                      //if we did parsimony
            {
                List <EngineLayer.ProteinGroup> silacProteinGroups = new List <EngineLayer.ProteinGroup>();
                //The light/unlabeled peptides/proteins were not searched if specified, but they were still quantified to keep track of the labels
                //we need to remove these unlabeled peptides/proteins before output
                //foreach protein group (which has its own quant for each file)
                foreach (EngineLayer.ProteinGroup proteinGroup in ProteinGroups)
                {
                    proteinGroup.FilesForQuantification = silacSpectraFileInfo;                                                    //update fileinfo for the group
                                                                                                                                   //grab the light groups. Using these light groups, find their heavy group pair(s), add them to the light group quant info, and then remove the heavy groups
                    if (silacProteinGroupMatcher.TryGetValue(proteinGroup.ProteinGroupName, out List <string> silacSubGroupNames)) //try to find the light protein groups. If it's not light, ignore it
                    {
                        //the out variable contains all the other heavy protein groups that were generated for this light protein group
                        //go through the files and see if any of them contain the same label. If not, put zeroes for those missing "files"
                        //If the user didn't specify to search light intensities, then don't output them
                        Dictionary <SpectraFileInfo, double> updatedIntensitiesByFile = proteinGroup.IntensitiesByFile; //light intensities
                        List <SpectraFileInfo> lightKeys = updatedIntensitiesByFile.Keys.ToList();

                        //go through all files (including "silac" files)
                        List <ProteinGroup> subGroup = ProteinGroups.Where(x => silacSubGroupNames.Contains(x.ProteinGroupName)).ToList(); //find the protein groups where the accession contains "light" accession of the current protein group
                        foreach (SpectraFileInfo fileInfo in silacSpectraFileInfo)                                                         //for every file (light and heavy)
                        {
                            //if it doesn't have a value, then it's a silac file (light missing values still have a value "0")
                            if (!updatedIntensitiesByFile.ContainsKey(fileInfo))
                            {
                                string       labelSignature = fileToLabelDictionary[fileInfo];                                                                 //a string associated with a silac label
                                ProteinGroup foundGroup     = subGroup.Where(x => x.Proteins.Any(y => y.Accession.Contains(labelSignature))).FirstOrDefault(); //get the protein groups containing this label
                                updatedIntensitiesByFile[fileInfo] = foundGroup == null ? 0 : foundGroup.IntensitiesByFile[labeledToUnlabeledFile[fileInfo]];  //update the intensity for that label in the light group
                            }
                            //else do nothing. The light version is already in the dictionary
                        }

                        //The light/unlabeled peptides/proteins were not searched if specified, but they were still quantified to keep track of the labels
                        //we need to remove these unlabeled peptides/proteins before output
                        if (!outputLightIntensities)
                        {
                            foreach (SpectraFileInfo info in lightKeys)
                            {
                                updatedIntensitiesByFile.Remove(info);
                                proteinGroup.FilesForQuantification.Remove(info);
                                lightFilesToRemove.Add(info);
                            }
                        }

                        silacProteinGroups.Add(proteinGroup);
                    }
                }

                //update
                ProteinGroups.Clear();
                ProteinGroups.AddRange(silacProteinGroups);
                //remove light files (if necessary)
                foreach (SpectraFileInfo info in lightFilesToRemove)
                {
                    FlashLfqResults.SpectraFiles.Remove(info);
                }

                //UPDATE FLASHLFQ PROTEINS
                if (FlashLfqResults != null)                                                                     //can be null if nothing was quantified (all peptides are ambiguous)
                {
                    Dictionary <string, FlashLFQ.ProteinGroup> flashLfqProteins = FlashLfqResults.ProteinGroups; //dictionary of protein group names to protein groups
                                                                                                                 //if the protein group is a heavy protein group, get rid of it. We already accounted for it above.
                    var keys = flashLfqProteins.Keys.ToList();
                    foreach (string key in keys)
                    {
                        if (silacLabels.Any(x => key.Contains(x.MassDifference)))
                        {
                            flashLfqProteins.Remove(key);
                        }
                    }
                }
            }

            ////UPDATE FLASHLFQ SPECTRA FILES
            if (FlashLfqResults != null)                                             //can be null if nothing was quantified (all peptides are ambiguous)
            {
                List <SpectraFileInfo> originalFiles = FlashLfqResults.SpectraFiles; //pass reference
                foreach (SpectraFileInfo info in silacSpectraFileInfo)
                {
                    if (!originalFiles.Contains(info))
                    {
                        originalFiles.Add(info);
                    }
                }
            }

            //UPDATE PEPTIDE INFO
            //convert all psm/peptide/proteingroup sequences from the heavy label to the light label for output
            //We can do this for all of the FlashLFQ peptides/peaks, because they use string sequences.
            //We are unable to do this for Parameters.AllPsms, because they store proteins and start/end residues instead
            //for Psms, we need to convert during the writing.
            for (int i = 0; i < allPsms.Count; i++)
            {
                allPsms[i].ResolveHeavySilacLabel(silacLabels, ModsToWriteSelection);
            }

            //Convert all lfqpeaks from heavy (a) to light (K+8.014) for output
            if (FlashLfqResults != null) //can be null if nothing was quantified (all peptides are ambiguous)
            {
                var lfqPeaks = FlashLfqResults.Peaks;
                List <SpectraFileInfo> peakKeys = lfqPeaks.Keys.ToList();

                foreach (SpectraFileInfo key in peakKeys)
                {
                    List <FlashLFQ.ChromatographicPeak> peaks = lfqPeaks[key];
                    for (int i = 0; i < peaks.Count; i++)
                    {
                        var peak = peaks[i];
                        List <Identification> identifications = new List <Identification>();
                        //check if we're removing light peaks and if it's a light peak
                        if (!outputLightIntensities && !peak.Identifications.Any(x => GetRelevantLabelFromBaseSequence(x.BaseSequence, silacLabels) != null)) //if no ids have any labels, remove them
                        {
                            peaks.RemoveAt(i);
                            i--;
                        }
                        else
                        {
                            foreach (var id in peak.Identifications)
                            {
                                SilacLabel label = GetRelevantLabelFromBaseSequence(id.BaseSequence, silacLabels);
                                HashSet <FlashLFQ.ProteinGroup> originalGroups = id.proteinGroups;
                                List <FlashLFQ.ProteinGroup>    updatedGroups  = new List <FlashLFQ.ProteinGroup>();
                                foreach (FlashLFQ.ProteinGroup group in originalGroups)
                                {
                                    string groupName = group.ProteinGroupName;
                                    if (label == null) //if light
                                    {
                                        updatedGroups.Add(group);
                                    }
                                    else
                                    {
                                        string labelString = "(" + label.OriginalAminoAcid + label.MassDifference;
                                        int    labelIndex  = groupName.IndexOf(labelString);
                                        if (labelIndex != -1) //labelIndex == 1 if a) 2+ peptides are required per protein or b) somebody broke parsimony
                                        {
                                            groupName = groupName.Substring(0, labelIndex);
                                            updatedGroups.Add(new FlashLFQ.ProteinGroup(groupName, group.GeneName, group.Organism));
                                        }
                                    }
                                }

                                Identification updatedId = new Identification(
                                    id.fileInfo,
                                    GetSilacLightBaseSequence(id.BaseSequence, label),
                                    GetSilacLightFullSequence(id.ModifiedSequence, label),
                                    id.monoisotopicMass,
                                    id.ms2RetentionTimeInMinutes,
                                    id.precursorChargeState,
                                    updatedGroups,
                                    id.OptionalChemicalFormula,
                                    id.UseForProteinQuant
                                    );
                                identifications.Add(updatedId);
                            }
                            FlashLFQ.ChromatographicPeak updatedPeak = new FlashLFQ.ChromatographicPeak(identifications.First(), peak.IsMbrPeak, peak.SpectraFileInfo);
                            for (int j = 1; j < identifications.Count; j++) //add all the original identification
                            {
                                updatedPeak.MergeFeatureWith(new FlashLFQ.ChromatographicPeak(identifications[j], peak.IsMbrPeak, peak.SpectraFileInfo), Integrate);
                            }
                            updatedPeak.IsotopicEnvelopes = peak.IsotopicEnvelopes;  //need to set isotopicEnevelopes, since the new identifications didn't have them.
                            updatedPeak.CalculateIntensityForThisFeature(Integrate); //needed to update info
                            peaks[i] = updatedPeak;
                        }
                    }
                }

                //convert all lfq peptides from heavy to light for output
                Dictionary <string, FlashLFQ.Peptide> lfqPwsms = FlashLfqResults.PeptideModifiedSequences;
                List <string> pwsmKeys = lfqPwsms.Keys.ToList();
                foreach (string key in pwsmKeys)
                {
                    FlashLFQ.Peptide currentPeptide = lfqPwsms[key];
                    SilacLabel       label          = GetRelevantLabelFromFullSequence(currentPeptide.Sequence, silacLabels);
                    if (label != null)                                                                                                                           //if it's a heavy peptide
                    {
                        lfqPwsms.Remove(key);                                                                                                                    //get rid of it
                                                                                                                                                                 //update the light version
                        string lightSequence = GetSilacLightFullSequence(currentPeptide.Sequence, label, false);                                                 //get the light sequence
                        List <SpectraFileInfo> heavyFiles = silacSpectraFileInfo.Where(x => x.FilenameWithoutExtension.Contains(label.MassDifference)).ToList(); //these are the heavy raw file names

                        //Find the light peptide (which has a value for the light datafile) and set the intensity for the heavy datafile from the current peptide
                        if (lfqPwsms.TryGetValue(lightSequence, out FlashLFQ.Peptide lightPeptide)) //this should always have a value, since we made replicas earlier, and yet it sometimes doesn't...
                        {
                            foreach (SpectraFileInfo heavyFile in heavyFiles)
                            {
                                SpectraFileInfo lightFile = labeledToUnlabeledFile[heavyFile];
                                lightPeptide.SetIntensity(heavyFile, currentPeptide.GetIntensity(lightFile));
                                lightPeptide.SetDetectionType(heavyFile, currentPeptide.GetDetectionType(lightFile));
                            }
                        }
                        else //if there's no light, create a new entry for the heavy
                        {
                            //new peptide
                            FlashLFQ.Peptide updatedPeptide = new FlashLFQ.Peptide(lightSequence, currentPeptide.UseForProteinQuant);
                            //update the heavy info, set the light values to zero
                            foreach (SpectraFileInfo info in heavyFiles)
                            {
                                updatedPeptide.SetIntensity(info, currentPeptide.GetIntensity(info));
                                updatedPeptide.SetDetectionType(info, currentPeptide.GetDetectionType(info));
                            }

                            //set the other values to zero
                            List <SpectraFileInfo> otherInfo = silacSpectraFileInfo.Where(x => !heavyFiles.Contains(x)).ToList();
                            foreach (SpectraFileInfo info in otherInfo)
                            {
                                updatedPeptide.SetIntensity(info, 0);
                                updatedPeptide.SetDetectionType(info, DetectionType.NotDetected);
                            }
                            HashSet <FlashLFQ.ProteinGroup> originalGroups = currentPeptide.proteinGroups;
                            HashSet <FlashLFQ.ProteinGroup> updatedGroups  = new HashSet <FlashLFQ.ProteinGroup>();
                            foreach (FlashLFQ.ProteinGroup group in originalGroups)
                            {
                                string groupName = group.ProteinGroupName;
                                groupName = groupName.Replace(label.MassDifference, "");
                                updatedGroups.Add(new FlashLFQ.ProteinGroup(groupName, group.GeneName, group.Organism));
                            }
                            updatedPeptide.proteinGroups      = updatedGroups;
                            lfqPwsms[updatedPeptide.Sequence] = updatedPeptide;
                        }
                    }
                }
            }
        }