Search in sources :

Example 1 with IFragment

use of de.ipbhalle.metfraglib.interfaces.IFragment in project MetFragRelaunched by ipb-halle.

the class SimulateSpectrumHDX method generateDeuteratedSpectrumNegative.

/**
 * @param candidate
 * @return
 * @throws AtomTypeNotKnownFromInputListException
 * @throws Exception
 */
public static double[][] generateDeuteratedSpectrumNegative(ICandidate candidate, int method) throws AtomTypeNotKnownFromInputListException, Exception {
    int numberPositions = searchForDeuteriumExchangeablePositions((TopDownBitArrayPrecursor) candidate.getPrecursorMolecule()).length;
    HDTopDownBitArrayPrecursor preHDX = new HDTopDownBitArrayPrecursor(candidate.getImplicitHydrogenAtomContainer(), (byte) numberPositions);
    preHDX.preprocessPrecursor();
    MatchList matchList = candidate.getMatchList();
    double[][] spectrumHDX = null;
    if (method == 3)
        spectrumHDX = new double[matchList.getNumberElements() * 2][2];
    else
        spectrumHDX = new double[matchList.getNumberElements()][2];
    for (int i = 0; i < matchList.getNumberElements(); i++) {
        IFragment frag = matchList.getElement(i).getBestMatchedFragment();
        IPeak peak = matchList.getElement(i).getMatchedPeak();
        int[] setAtoms = ((DefaultBitArrayFragment) frag).getAtomsFastBitArray().getSetIndeces();
        int numberDeuteriums = 0;
        for (int k = 0; k < setAtoms.length; k++) {
            numberDeuteriums += preHDX.getNumberDeuteriumsConnectedToAtomIndex(0, setAtoms[k]);
        }
        spectrumHDX[i][1] = peak.getAbsoluteIntensity();
        // [M-D]-
        if (method == 1) {
            spectrumHDX[i][0] = peak.getMass() - (numberDeuteriums) * Constants.HYDROGEN_MASS + (numberDeuteriums) * Constants.getMonoisotopicMassOfAtom("D");
            spectrumHDX[i][0] += Constants.HYDROGEN_MASS - Constants.getMonoisotopicMassOfAtom("D");
        } else // [M]-
        if (method == 2) {
            spectrumHDX[i][0] = peak.getMass() - (numberDeuteriums) * Constants.HYDROGEN_MASS + (numberDeuteriums) * Constants.getMonoisotopicMassOfAtom("D");
        // nothing to do
        } else // [M]- [M-D]-
        if (method == 3) {
            spectrumHDX[i * 2][0] = peak.getMass() - (numberDeuteriums) * Constants.HYDROGEN_MASS + (numberDeuteriums) * Constants.getMonoisotopicMassOfAtom("D");
            spectrumHDX[(i * 2) + 1][0] = peak.getMass() - (numberDeuteriums) * Constants.HYDROGEN_MASS + (numberDeuteriums) * Constants.getMonoisotopicMassOfAtom("D");
            spectrumHDX[(i * 2) + 1][0] += Constants.HYDROGEN_MASS - Constants.getMonoisotopicMassOfAtom("D");
        } else // predict based on deuteriums
        if (method == 4) {
            spectrumHDX[i][0] = peak.getMass() - (numberDeuteriums) * Constants.HYDROGEN_MASS + (numberDeuteriums) * Constants.getMonoisotopicMassOfAtom("D");
            if (numberDeuteriums != 0)
                spectrumHDX[i][0] += Constants.HYDROGEN_MASS - Constants.getMonoisotopicMassOfAtom("D");
        } else // predict based on adduct
        if (method == 5) {
            byte adductTypeIndex = ((DefaultFragmentToPeakMatch) matchList.getElement(i)).getBestMatchedFragmentAdductTypeIndex();
            spectrumHDX[i][0] = peak.getMass() - (numberDeuteriums) * Constants.HYDROGEN_MASS + (numberDeuteriums) * Constants.getMonoisotopicMassOfAtom("D");
            if (adductTypeIndex == 1)
                spectrumHDX[i][0] += Constants.getMonoisotopicMassOfAtom("D") - Constants.HYDROGEN_MASS;
        }
    }
    return spectrumHDX;
}
Also used : DefaultFragmentToPeakMatch(de.ipbhalle.metfraglib.match.DefaultFragmentToPeakMatch) IPeak(de.ipbhalle.metfraglib.interfaces.IPeak) MatchList(de.ipbhalle.metfraglib.list.MatchList) IFragment(de.ipbhalle.metfraglib.interfaces.IFragment) TopDownBitArrayPrecursor(de.ipbhalle.metfraglib.precursor.TopDownBitArrayPrecursor) HDTopDownBitArrayPrecursor(de.ipbhalle.metfraglib.precursor.HDTopDownBitArrayPrecursor) HDTopDownBitArrayPrecursor(de.ipbhalle.metfraglib.precursor.HDTopDownBitArrayPrecursor)

Example 2 with IFragment

use of de.ipbhalle.metfraglib.interfaces.IFragment in project MetFragRelaunched by ipb-halle.

the class CandidateListWriterLossFragmentSmilesPSV method writeFile.

public boolean writeFile(File file, IList list, Settings settings) throws Exception {
    CandidateList candidateList = null;
    int numberOfPeaksUsed = 0;
    if (list instanceof ScoredCandidateList || list instanceof SortedScoredCandidateList) {
        candidateList = (ScoredCandidateList) list;
        numberOfPeaksUsed = ((ScoredCandidateList) list).getNumberPeaksUsed();
    }
    if (list instanceof CandidateList) {
        candidateList = (CandidateList) list;
    }
    if (candidateList == null)
        return false;
    StringBuilder heading = new StringBuilder();
    this.removeCandidateProperties(candidateList.getElement(0));
    java.util.Enumeration<String> keys = candidateList.getElement(0).getProperties().keys();
    if (keys.hasMoreElements()) {
        String key = keys.nextElement();
        heading.append(key);
    }
    while (keys.hasMoreElements()) {
        String key = keys.nextElement();
        heading.append("|");
        heading.append(key);
    }
    heading.append("|");
    heading.append("ExplPeaks");
    heading.append("|");
    heading.append("FormulasOfExplPeaks");
    heading.append("|");
    heading.append("FragmentFingerprintOfExplPeaks");
    heading.append("|");
    heading.append("NumberPeaksUsed");
    heading.append("|");
    heading.append("NoExplPeaks");
    heading.append("|");
    heading.append("LossFingerprintOfExplPeaks");
    java.io.BufferedWriter bwriter = new java.io.BufferedWriter(new FileWriter(file));
    bwriter.write(heading.toString());
    bwriter.newLine();
    Fingerprint fingerprint = new Fingerprint((String) settings.get(VariableNames.FINGERPRINT_TYPE_NAME));
    for (int i = 0; i < candidateList.getNumberElements(); i++) {
        StringBuilder line = new StringBuilder();
        int countExplainedPeaks = 0;
        ICandidate scoredCandidate = candidateList.getElement(i);
        this.removeCandidateProperties(scoredCandidate);
        if (settings != null)
            scoredCandidate.setUseSmiles((Boolean) settings.get(VariableNames.USE_SMILES_NAME));
        scoredCandidate.initialisePrecursorCandidate();
        if (scoredCandidate.getMatchList() != null) {
            MatchList matchList = scoredCandidate.getMatchList();
            for (int l = 0; l < matchList.getNumberElements(); l++) {
                try {
                    matchList.getElement(l).getMatchedPeak().getIntensity();
                } catch (RelativeIntensityNotDefinedException e1) {
                    continue;
                }
                countExplainedPeaks++;
            }
        }
        keys = scoredCandidate.getProperties().keys();
        if (keys.hasMoreElements()) {
            String key = keys.nextElement();
            line.append(scoredCandidate.getProperty(key));
        }
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            line.append("|");
            line.append(scoredCandidate.getProperty(key));
        }
        StringBuilder peaksExplained = new StringBuilder();
        StringBuilder sumFormulasOfFragmentsExplainedPeaks = new StringBuilder();
        StringBuilder fingerprintOfFragmentsExplainedPeaks = new StringBuilder();
        if (scoredCandidate.getMatchList() != null) {
            String[] matchedFormulas = new String[scoredCandidate.getMatchList().getNumberElements()];
            double[] correctedMasses = new double[scoredCandidate.getMatchList().getNumberElements()];
            for (int ii = 0; ii < scoredCandidate.getMatchList().getNumberElements(); ii++) {
                try {
                    double intensity = scoredCandidate.getMatchList().getElement(ii).getMatchedPeak().getIntensity();
                    peaksExplained.append(scoredCandidate.getMatchList().getElement(ii).getMatchedPeak().getMass());
                    peaksExplained.append("_");
                    peaksExplained.append(intensity);
                    peaksExplained.append(";");
                } catch (RelativeIntensityNotDefinedException e1) {
                    continue;
                }
                String formula = scoredCandidate.getMatchList().getElement(ii).getModifiedFormulaStringOfBestMatchedFragment(scoredCandidate.getPrecursorMolecule());
                double mass = scoredCandidate.getMatchList().getElement(ii).getMatchedPeak().getMass();
                if ((Boolean) settings.get(VariableNames.CORRECT_MASSES_FOR_FINGERPRINT_ANNOTATION_NAME)) {
                    matchedFormulas[ii] = formula;
                    correctedMasses[ii] = MathTools.round(calculateMassOfFormula(formula));
                    mass = correctedMasses[ii];
                }
                sumFormulasOfFragmentsExplainedPeaks.append(scoredCandidate.getMatchList().getElement(ii).getMatchedPeak().getMass());
                sumFormulasOfFragmentsExplainedPeaks.append(":");
                sumFormulasOfFragmentsExplainedPeaks.append(formula);
                sumFormulasOfFragmentsExplainedPeaks.append(";");
                // get fragment of explained peak
                IFragment frag = scoredCandidate.getMatchList().getElement(ii).getBestMatchedFragment();
                String fp = null;
                try {
                    IAtomContainer con = fingerprint.getNormalizedAtomContainer(scoredCandidate.getPrecursorMolecule(), frag);
                    fp = fingerprint.getNormalizedFingerprint(con);
                } catch (Exception e) {
                    continue;
                }
                fingerprintOfFragmentsExplainedPeaks.append(mass);
                fingerprintOfFragmentsExplainedPeaks.append(":");
                fingerprintOfFragmentsExplainedPeaks.append(fp);
                fingerprintOfFragmentsExplainedPeaks.append(";");
            }
            line.append("|");
            line.append(peaksExplained.length() == 0 ? "NA" : peaksExplained.substring(0, peaksExplained.length() - 1));
            line.append("|");
            line.append(sumFormulasOfFragmentsExplainedPeaks.length() == 0 ? "NA" : sumFormulasOfFragmentsExplainedPeaks.substring(0, sumFormulasOfFragmentsExplainedPeaks.length() - 1));
            line.append("|");
            line.append(fingerprintOfFragmentsExplainedPeaks.length() == 0 ? "NA" : fingerprintOfFragmentsExplainedPeaks.substring(0, fingerprintOfFragmentsExplainedPeaks.length() - 1));
            line.append("|");
            line.append(numberOfPeaksUsed);
            line.append("|");
            line.append(countExplainedPeaks);
            // add loss information
            if (settings != null) {
                String lossesFingerprints = createLossAnnotations(scoredCandidate.getPrecursorMolecule(), scoredCandidate.getMatchList(), settings, correctedMasses, fingerprint);
                line.append("|");
                line.append(lossesFingerprints);
            }
        }
        bwriter.write(line.toString());
        bwriter.newLine();
    }
    bwriter.close();
    return true;
}
Also used : Fingerprint(de.ipbhalle.metfraglib.fingerprint.Fingerprint) IAtomContainer(org.openscience.cdk.interfaces.IAtomContainer) MatchList(de.ipbhalle.metfraglib.list.MatchList) FileWriter(java.io.FileWriter) RelativeIntensityNotDefinedException(de.ipbhalle.metfraglib.exceptions.RelativeIntensityNotDefinedException) Fingerprint(de.ipbhalle.metfraglib.fingerprint.Fingerprint) ICandidate(de.ipbhalle.metfraglib.interfaces.ICandidate) AtomTypeNotKnownFromInputListException(de.ipbhalle.metfraglib.exceptions.AtomTypeNotKnownFromInputListException) RelativeIntensityNotDefinedException(de.ipbhalle.metfraglib.exceptions.RelativeIntensityNotDefinedException) SortedScoredCandidateList(de.ipbhalle.metfraglib.list.SortedScoredCandidateList) CandidateList(de.ipbhalle.metfraglib.list.CandidateList) ScoredCandidateList(de.ipbhalle.metfraglib.list.ScoredCandidateList) SortedScoredCandidateList(de.ipbhalle.metfraglib.list.SortedScoredCandidateList) IFragment(de.ipbhalle.metfraglib.interfaces.IFragment) ScoredCandidateList(de.ipbhalle.metfraglib.list.ScoredCandidateList) SortedScoredCandidateList(de.ipbhalle.metfraglib.list.SortedScoredCandidateList)

Example 3 with IFragment

use of de.ipbhalle.metfraglib.interfaces.IFragment in project MetFragRelaunched by ipb-halle.

the class AutomatedLossFingerprintAnnotationScoreInitialiser method postProcessScoreParameters.

public void postProcessScoreParameters(Settings settings) throws AtomTypeNotKnownFromInputListException, Exception {
    CombinedSingleCandidateMetFragProcess[] processes = (CombinedSingleCandidateMetFragProcess[]) settings.get(VariableNames.METFRAG_PROCESSES_NAME);
    // fingerprints not seen in training
    MassToFingerprintsHashMap lossMassToFingerprints = new MassToFingerprintsHashMap();
    MassToFingerprintGroupListCollection lossToFingerprintGroupListCollection = (MassToFingerprintGroupListCollection) settings.get(VariableNames.LOSS_TO_FINGERPRINT_GROUP_LIST_COLLECTION_NAME);
    Double mzppm = (Double) settings.get(VariableNames.RELATIVE_MASS_DEVIATION_NAME);
    Double mzabs = (Double) settings.get(VariableNames.ABSOLUTE_MASS_DEVIATION_NAME);
    int ionmode = (Integer) settings.get(VariableNames.PRECURSOR_ION_MODE_NAME);
    boolean ispositive = (Boolean) settings.get(VariableNames.IS_POSITIVE_ION_MODE_NAME);
    double adductMass = Constants.getIonisationTypeMassCorrection(Constants.ADDUCT_NOMINAL_MASSES.indexOf(ionmode), ispositive);
    double precursorMass = (Double) settings.get(VariableNames.PRECURSOR_NEUTRAL_MASS_NAME);
    double ionmass = MathTools.round(precursorMass + adductMass);
    Fingerprint fingerprint = new Fingerprint((String) settings.get(VariableNames.FINGERPRINT_TYPE_NAME));
    for (CombinedSingleCandidateMetFragProcess scmfp : processes) {
        /*
			 * check whether the single run was successful
			 */
        if (scmfp.wasSuccessful()) {
            ICandidate candidate = scmfp.getScoredPrecursorCandidates()[0];
            java.util.ArrayList<MassFingerprintMatch> lossMatchlist = new java.util.ArrayList<MassFingerprintMatch>();
            MatchList matchlist = candidate.getMatchList();
            if (matchlist != null) {
                candidate.initialisePrecursorCandidate();
                for (int i = 0; i < matchlist.getNumberElements(); i++) {
                    IMatch matchI = matchlist.getElement(i);
                    IFragment fragmentI = matchI.getBestMatchedFragment();
                    double peakMassI = matchI.getMatchedPeak().getMass();
                    for (int j = i + 1; j < matchlist.getNumberElements(); j++) {
                        IMatch matchJ = matchlist.getElement(j);
                        double peakMassJ = matchJ.getMatchedPeak().getMass();
                        IFragment fragmentJ = matchJ.getBestMatchedFragment();
                        if (fragmentJ.isRealSubStructure(fragmentI)) {
                            double diff = MathTools.round(peakMassJ - peakMassI);
                            MassToFingerprintGroupList matchingLossToFingerprintGroupList = lossToFingerprintGroupListCollection.getElementByPeak(diff, mzppm, mzabs);
                            if (matchingLossToFingerprintGroupList == null)
                                continue;
                            IFragment diffFragment = fragmentJ.getDifferenceFragment(candidate.getPrecursorMolecule(), fragmentI);
                            if (diffFragment == null)
                                continue;
                            IAtomContainer con = fingerprint.getNormalizedAtomContainer(candidate.getPrecursorMolecule(), diffFragment);
                            lossMatchlist.add(new MassFingerprintMatch(diff, fingerprint.getNormalizedFastBitArrayFingerprint(con)));
                        }
                    }
                    // do the same for the precursor ion
                    double diff = MathTools.round(ionmass - peakMassI);
                    MassToFingerprintGroupList matchingLossToFingerprintGroupList = lossToFingerprintGroupListCollection.getElementByPeak(diff, mzppm, mzabs);
                    if (matchingLossToFingerprintGroupList == null)
                        continue;
                    IFragment diffFragment = fragmentI.getDifferenceFragment(candidate.getPrecursorMolecule());
                    if (diffFragment == null)
                        continue;
                    IAtomContainer con = fingerprint.getNormalizedAtomContainer(candidate.getPrecursorMolecule(), diffFragment);
                    lossMatchlist.add(new MassFingerprintMatch(diff, fingerprint.getNormalizedFastBitArrayFingerprint(con)));
                }
            }
            // java.util.LinkedList<Double> nonExplainedLosses = this.getNonExplainedLoss(peakList, matchlist);
            for (int j = 0; j < lossMatchlist.size(); j++) {
                MassFingerprintMatch lossMatch = lossMatchlist.get(j);
                MassToFingerprintGroupList lossToFingerprintGroupList = lossToFingerprintGroupListCollection.getElementByPeak(lossMatch.getMass(), mzppm, mzabs);
                // if not loss not in our annotation list, there's no need to consider it
                if (lossToFingerprintGroupList == null)
                    continue;
                // lossMatch.setMass(lossToFingerprintGroupList.getPeakmz());
                FastBitArray currentFingerprint = lossMatch.getFingerprint();
                // check whether fingerprint was observed for current peak mass in the training data
                if (!lossToFingerprintGroupList.containsFingerprint(currentFingerprint)) {
                    // if not add the fingerprint to background by addFingerprint function
                    // addFingerprint checks also whether fingerprint was already added
                    lossMassToFingerprints.addFingerprint(lossMatch.getMass(), currentFingerprint);
                }
            }
            java.util.LinkedList<?> lossMassesFoundInPeakList = (java.util.LinkedList<?>) settings.get(VariableNames.LOSS_MASSES_FOUND_PEAKLIST_NAME);
            // important! now add all losses not assigned by that candidates
            // this is to equalize all loss match lists in length over all candidates
            this.addNonExplainedLosses(lossMassesFoundInPeakList, lossMatchlist);
            candidate.setProperty("LossMatchList", lossMatchlist);
        }
    }
    // alpha
    double alpha = (double) settings.get(VariableNames.LOSS_FINGERPRINT_ANNOTATION_ALPHA_VALUE_NAME);
    // beta
    double beta = (double) settings.get(VariableNames.LOSS_FINGERPRINT_ANNOTATION_BETA_VALUE_NAME);
    // f_s
    double f_seen_matched = (double) settings.get(VariableNames.LOSS_FINGERPRINT_MATCHED_TUPLE_COUNT_NAME);
    // f_s
    double f_seen_non_matched = (double) settings.get(VariableNames.LOSS_FINGERPRINT_NON_MATCHED_TUPLE_COUNT_NAME);
    // f_u
    double f_unseen_matched = lossMassToFingerprints.getOverallMatchedSize();
    // f_u
    double f_unseen_non_matched = lossMassToFingerprints.getOverallNonMatchedSize();
    // \sum_N
    double sumFingerprintFrequencies = (double) settings.get(VariableNames.LOSS_FINGERPRINT_DENOMINATOR_COUNT_NAME);
    // set value for denominator of P(f,m)
    double denominatorValue = sumFingerprintFrequencies + alpha * (f_seen_matched + f_unseen_matched) + beta * (f_seen_non_matched + f_unseen_non_matched);
    settings.set(VariableNames.LOSS_FINGERPRINT_DENOMINATOR_VALUE_NAME, denominatorValue);
    // P(f,m) F_u
    double alphaProbability = alpha / denominatorValue;
    // p(f,m) not annotated
    double betaProbability = beta / denominatorValue;
    for (int i = 0; i < lossToFingerprintGroupListCollection.getNumberElements(); i++) {
        MassToFingerprintGroupList groupList = lossToFingerprintGroupListCollection.getElement(i);
        // sum_f P(f,m)
        // calculate sum of MF_s (including the alpha count) and the joint probabilities
        // at this stage getProbability() returns the absolute counts from the annotation files
        double sum_f = 0.0;
        double sumFsProbabilities = 0.0;
        for (int ii = 0; ii < groupList.getNumberElements(); ii++) {
            // first calculate P(f,m)
            if (groupList.getElement(ii).getFingerprint().getSize() != 1)
                groupList.getElement(ii).setJointProbability((groupList.getElement(ii).getProbability() + alpha) / denominatorValue);
            else
                groupList.getElement(ii).setJointProbability((groupList.getElement(ii).getProbability() + beta) / denominatorValue);
            // sum_f P(f,m) -> for F_s
            sumFsProbabilities += groupList.getElement(ii).getJointProbability();
        }
        // calculate the sum of probabilities for un-observed fingerprints for the current mass
        double sumFuProbabilities = alphaProbability * lossMassToFingerprints.getSizeMatched(groupList.getPeakmz());
        // not needed as it's defined by fingerprint = "0"
        // sumFuProbabilities += betaProbability * lossMassToFingerprints.getSizeNonMatched(groupList.getPeakmz());
        sumFuProbabilities += betaProbability;
        sum_f += sumFsProbabilities;
        sum_f += sumFuProbabilities;
        for (int ii = 0; ii < groupList.getNumberElements(); ii++) {
            // second calculate P(f|m)
            groupList.getElement(ii).setConditionalProbability_sp(groupList.getElement(ii).getJointProbability() / sum_f);
        }
        groupList.setAlphaProb(alphaProbability / sum_f);
        groupList.setBetaProb(betaProbability / sum_f);
        groupList.setProbabilityToConditionalProbability_sp();
        groupList.calculateSumProbabilites();
    }
    return;
}
Also used : IMatch(de.ipbhalle.metfraglib.interfaces.IMatch) IAtomContainer(org.openscience.cdk.interfaces.IAtomContainer) MassToFingerprintGroupListCollection(de.ipbhalle.metfraglib.substructure.MassToFingerprintGroupListCollection) ICandidate(de.ipbhalle.metfraglib.interfaces.ICandidate) MassToFingerprintGroupList(de.ipbhalle.metfraglib.substructure.MassToFingerprintGroupList) FastBitArray(de.ipbhalle.metfraglib.FastBitArray) MassFingerprintMatch(de.ipbhalle.metfraglib.match.MassFingerprintMatch) Fingerprint(de.ipbhalle.metfraglib.fingerprint.Fingerprint) MatchList(de.ipbhalle.metfraglib.list.MatchList) CombinedSingleCandidateMetFragProcess(de.ipbhalle.metfraglib.process.CombinedSingleCandidateMetFragProcess) Fingerprint(de.ipbhalle.metfraglib.fingerprint.Fingerprint) MassToFingerprintsHashMap(de.ipbhalle.metfraglib.substructure.MassToFingerprintsHashMap) IFragment(de.ipbhalle.metfraglib.interfaces.IFragment)

Example 4 with IFragment

use of de.ipbhalle.metfraglib.interfaces.IFragment in project MetFragRelaunched by ipb-halle.

the class NewFragmenterLipidScore method calculateSingleMatch.

/**
 */
public Double[] calculateSingleMatch(IMatch currentMatch) {
    if (currentMatch instanceof HDFragmentMassToPeakMatch)
        return new Double[] { 0.0, null };
    FragmentList currentFragmentList = currentMatch.getMatchedFragmentList();
    double minimumEnergyPerMatch = (double) Integer.MAX_VALUE;
    double peakScore = 0.0;
    try {
        peakScore = Math.pow((currentMatch.getMatchedPeak().getMass() / this.measuredPrecursorMass) * 10.0, this.ALPHA) * Math.pow(currentMatch.getMatchedPeak().getIntensity(), this.BETA);
    } catch (RelativeIntensityNotDefinedException e) {
        e.printStackTrace();
    }
    int indexOfBestFragment = -1;
    double overallMatchScore = 0.0;
    for (int ii = 0; ii < currentFragmentList.getNumberElements(); ii++) {
        IFragment currentFragment = currentFragmentList.getElement(ii);
        /*
			 * check if current fragment is valid based on the tree depth
			 */
        // if(currentFragment.getTreeDepth() > this.maximumTreeDepth) continue;
        int[] brokenBondIndeces = ((AbstractTopDownBitArrayFragment) currentFragment).getBrokenBondsFastBitArray().getSetIndeces();
        double energyOfFragment = 0.0;
        for (int bondIndex : brokenBondIndeces) {
            energyOfFragment += this.bondEnergies[bondIndex];
        }
        energyOfFragment += Math.abs(currentMatch.getNumberOfOverallHydrogensDifferToPeakMass(ii)) * this.WEIGHT_HYDROGEN_PENALTY;
        /*
			 * assign optimal bondenergy and store best fragment
			 */
        overallMatchScore += peakScore / Math.pow(energyOfFragment, this.GAMMA);
        if (energyOfFragment < minimumEnergyPerMatch) {
            minimumEnergyPerMatch = energyOfFragment;
            indexOfBestFragment = ii;
        }
    /*
			if(((AbstractTopDownBitArrayFragment)currentFragment).getAtomsFastBitArray().toString().equals("111110001100010001")) {
				System.out.println(((AbstractTopDownBitArrayFragment)currentFragment).getAtomsFastBitArray().toString() + " " + 
						((AbstractTopDownBitArrayFragment)currentFragment).getBondsFastBitArray().toString() + " " + 
						((AbstractTopDownBitArrayFragment)currentFragment).getBrokenBondsFastBitArray().toString() + " " + currentFragment.getID()
						+ " " + energyOfFragment);
			}
			*/
    }
    this.calculationFinished = true;
    if (indexOfBestFragment != -1)
        currentMatch.initialiseBestMatchedFragment(indexOfBestFragment);
    return new Double[] { overallMatchScore, minimumEnergyPerMatch };
}
Also used : HDFragmentMassToPeakMatch(de.ipbhalle.metfraglib.match.HDFragmentMassToPeakMatch) FragmentList(de.ipbhalle.metfraglib.list.FragmentList) IFragment(de.ipbhalle.metfraglib.interfaces.IFragment) RelativeIntensityNotDefinedException(de.ipbhalle.metfraglib.exceptions.RelativeIntensityNotDefinedException)

Example 5 with IFragment

use of de.ipbhalle.metfraglib.interfaces.IFragment in project MetFragRelaunched by ipb-halle.

the class NewMergedPeakFragmenterScore method calculate.

public void calculate() {
    this.matchList = (MatchList) settings.get(VariableNames.MATCH_LIST_NAME);
    this.value = Double.valueOf(0);
    this.bestFragmentIndeces = new int[this.matchList.getNumberElements()];
    this.optimalValues = new double[this.matchList.getNumberElements()];
    for (int i = 0; i < this.matchList.getNumberElements(); i++) {
        DefaultFragmentToPeakMatch currentMatch = null;
        boolean isMatchOfQuerySpectrum = true;
        if (this.matchList.getElement(i) instanceof FragmentMassToPeakMatch)
            currentMatch = (FragmentMassToPeakMatch) this.matchList.getElement(i);
        else
            currentMatch = (FragmentFormulaToPeakMatch) this.matchList.getElement(i);
        double intensity = 0.0;
        try {
            intensity = currentMatch.getMatchedPeak().getIntensity();
        } catch (RelativeIntensityNotDefinedException e) {
            // if the match is not caused by a peak of the query spectrum
            isMatchOfQuerySpectrum = false;
            intensity = 0.0;
        }
        MergedTandemMassPeak matchedPeak = (MergedTandemMassPeak) currentMatch.getMatchedPeak();
        FragmentList currentFragmentList = currentMatch.getMatchedFragmentList();
        double minimumEnergyPerMatch = (double) Integer.MAX_VALUE;
        /*
			 * get all intensities of random spectra of this peak 
			 */
        java.util.ArrayList<Double> intensities = matchedPeak.getIntensities();
        java.util.ArrayList<Integer> spectraIDs = matchedPeak.getSpectraIDs();
        double peakScore = Math.pow((matchedPeak.getMass() / this.measuredPrecursorMass) * 10.0, this.ALPHA) * Math.pow(intensity, this.BETA);
        double[] peakScores = new double[intensities.size()];
        for (int k = 0; k < intensities.size(); k++) {
            peakScores[k] = Math.pow((matchedPeak.getMass() / this.measuredPrecursorMass) * 10.0, this.ALPHA) * Math.pow(intensities.get(k), this.BETA);
        }
        for (int ii = 0; ii < currentFragmentList.getNumberElements(); ii++) {
            IFragment currentFragment = currentFragmentList.getElement(ii);
            /*
				 * check if current fragment is valid based on the tree depth
				 */
            // if(currentFragment.getTreeDepth() > this.maximumTreeDepth) continue;
            int[] brokenBondIndeces = currentFragment.getBrokenBondIndeces();
            double energyOfFragment = 0.0;
            for (int bondIndex : brokenBondIndeces) {
                energyOfFragment += this.bondEnergies[bondIndex];
            }
            energyOfFragment += Math.abs(currentMatch.getNumberOfHydrogensDifferToPeakMass(ii)) * this.WEIGHT_HYDROGEN_PENALTY;
            /*
				 * assign optimal bondenergy and store best fragment
				 */
            if (energyOfFragment < minimumEnergyPerMatch) {
                minimumEnergyPerMatch = energyOfFragment;
                if (isMatchOfQuerySpectrum)
                    this.bestFragmentIndeces[i] = ii;
            }
        }
        if (isMatchOfQuerySpectrum) {
            currentMatch.initialiseBestMatchedFragment(this.bestFragmentIndeces[i]);
            this.value += peakScore / Math.pow(minimumEnergyPerMatch, this.GAMMA);
            this.optimalValues[i] = minimumEnergyPerMatch;
        }
        for (int k = 0; k < spectraIDs.size(); k++) {
            this.scoresRandomSpectra[spectraIDs.get(k)] += peakScores[k] / Math.pow(minimumEnergyPerMatch, this.GAMMA);
        }
    }
    int betterEqualScores = 0;
    for (int i = 0; i < this.scoresRandomSpectra.length; i++) {
        if (this.scoresRandomSpectra[i] >= this.value)
            betterEqualScores++;
    }
    this.scoredCandidate.setProperty("p-value", (double) betterEqualScores / (double) this.scoresRandomSpectra.length);
    this.calculationFinished = true;
}
Also used : DefaultFragmentToPeakMatch(de.ipbhalle.metfraglib.match.DefaultFragmentToPeakMatch) FragmentFormulaToPeakMatch(de.ipbhalle.metfraglib.match.FragmentFormulaToPeakMatch) FragmentMassToPeakMatch(de.ipbhalle.metfraglib.match.FragmentMassToPeakMatch) RelativeIntensityNotDefinedException(de.ipbhalle.metfraglib.exceptions.RelativeIntensityNotDefinedException) MergedTandemMassPeak(de.ipbhalle.metfraglib.peak.MergedTandemMassPeak) FragmentList(de.ipbhalle.metfraglib.list.FragmentList) IFragment(de.ipbhalle.metfraglib.interfaces.IFragment)

Aggregations

IFragment (de.ipbhalle.metfraglib.interfaces.IFragment)20 RelativeIntensityNotDefinedException (de.ipbhalle.metfraglib.exceptions.RelativeIntensityNotDefinedException)12 FragmentList (de.ipbhalle.metfraglib.list.FragmentList)8 MatchList (de.ipbhalle.metfraglib.list.MatchList)8 IMatch (de.ipbhalle.metfraglib.interfaces.IMatch)7 IAtomContainer (org.openscience.cdk.interfaces.IAtomContainer)7 ICandidate (de.ipbhalle.metfraglib.interfaces.ICandidate)5 DefaultFragmentToPeakMatch (de.ipbhalle.metfraglib.match.DefaultFragmentToPeakMatch)5 HDFragmentMassToPeakMatch (de.ipbhalle.metfraglib.match.HDFragmentMassToPeakMatch)5 AtomTypeNotKnownFromInputListException (de.ipbhalle.metfraglib.exceptions.AtomTypeNotKnownFromInputListException)4 Fingerprint (de.ipbhalle.metfraglib.fingerprint.Fingerprint)4 CandidateList (de.ipbhalle.metfraglib.list.CandidateList)3 ScoredCandidateList (de.ipbhalle.metfraglib.list.ScoredCandidateList)3 SortedScoredCandidateList (de.ipbhalle.metfraglib.list.SortedScoredCandidateList)3 FragmentFormulaToPeakMatch (de.ipbhalle.metfraglib.match.FragmentFormulaToPeakMatch)3 FragmentMassToPeakMatch (de.ipbhalle.metfraglib.match.FragmentMassToPeakMatch)3 FileWriter (java.io.FileWriter)3 FastBitArray (de.ipbhalle.metfraglib.FastBitArray)2 IPeak (de.ipbhalle.metfraglib.interfaces.IPeak)2 DefaultPeakList (de.ipbhalle.metfraglib.list.DefaultPeakList)2