Search in sources :

Example 1 with DefaultPeakList

use of de.ipbhalle.metfraglib.list.DefaultPeakList in project MetFragRelaunched by ipb-halle.

the class AutomatedLossFingerprintAnnotationScoreInitialiser method initScoreParameters.

@Override
public void initScoreParameters(Settings settings) throws Exception {
    if (!settings.containsKey(VariableNames.LOSS_TO_FINGERPRINT_GROUP_LIST_COLLECTION_NAME) || settings.get(VariableNames.LOSS_TO_FINGERPRINT_GROUP_LIST_COLLECTION_NAME) == null) {
        MassToFingerprintGroupListCollection lossToFingerprintGroupListCollection = new MassToFingerprintGroupListCollection();
        DefaultPeakList peakList = (DefaultPeakList) settings.get(VariableNames.PEAK_LIST_NAME);
        Double mzppm = (Double) settings.get(VariableNames.RELATIVE_MASS_DEVIATION_NAME);
        Double mzabs = (Double) settings.get(VariableNames.ABSOLUTE_MASS_DEVIATION_NAME);
        BufferedReader breader = null;
        java.io.InputStream is = null;
        if (settings.containsKey(VariableNames.FINGERPRINT_LOSS_ANNOTATION_FILE_NAME) && settings.get(VariableNames.FINGERPRINT_LOSS_ANNOTATION_FILE_NAME) != null) {
            breader = new BufferedReader(new FileReader(new File((String) settings.get(VariableNames.FINGERPRINT_LOSS_ANNOTATION_FILE_NAME))));
        } else {
            String filename = "loss_annotations_neg.txt";
            if ((Boolean) settings.get(VariableNames.IS_POSITIVE_ION_MODE_NAME))
                filename = "loss_annotations_pos.txt";
            is = AutomatedPeakFingerprintAnnotationScoreInitialiser.class.getResourceAsStream("/" + filename);
            breader = new java.io.BufferedReader(new java.io.InputStreamReader(is));
        }
        Double neutralPrecursorMass = (Double) settings.get(VariableNames.PRECURSOR_NEUTRAL_MASS_NAME);
        Double adductMass = Constants.getIonisationTypeMassCorrection(Constants.ADDUCT_NOMINAL_MASSES.indexOf((Integer) settings.get(VariableNames.PRECURSOR_ION_MODE_NAME)), (Boolean) settings.get(VariableNames.IS_POSITIVE_ION_MODE_NAME));
        java.util.ArrayList<Double> massDifferences = this.calculatePeakDifferences(peakList, neutralPrecursorMass, adductMass);
        java.util.ArrayList<Double> uniqueMassDifferences = this.calculateUniquePeakDifferences(massDifferences, mzppm, mzabs);
        java.util.LinkedList<Double> lossMassesFound = new java.util.LinkedList<Double>();
        String line = "";
        int numMatchedObservationsMerged = 0;
        java.util.HashMap<Double, MassToFingerprintGroupList> mergedFingerprintGroupLists = new java.util.HashMap<Double, MassToFingerprintGroupList>();
        this.setPseudoCountValues(settings);
        // first add non-matched masses with dummy fingerprint "0"
        // these masses are present in the first line of the annotation file: mass[:counts]
        String nonMatchedMassesString = breader.readLine().trim();
        int numNonMatchElements = 0;
        int numNonMatchOccurrences = 0;
        if (!nonMatchedMassesString.equals("NA")) {
            // masses are separated by ";"
            String[] tmp = nonMatchedMassesString.split(";");
            numNonMatchElements = tmp.length;
            for (int k = 0; k < tmp.length; k++) {
                // run over all masses
                // split by ":" to separate mass[:counts]
                String[] tmp2 = tmp[k].split("\\s+");
                int count = 1;
                // create mass value
                Double newMass = Double.parseDouble(tmp2[0]);
                // if count is present use count else use 1 (default)
                if (tmp2.length == 2)
                    count = Integer.parseInt(tmp2[1]);
                // save number non-matched occurences
                numNonMatchOccurrences += count;
                // check whether the newMass is also present in our found peak list losses
                Double matchedMass = this.containsMass(newMass, uniqueMassDifferences, mzabs, mzppm);
                // if not present and already larger than largest peak mass stop here
                if (matchedMass == null && newMass > peakList.getMaximumMassValue())
                    break;
                if (matchedMass != null) {
                    // if loss is present in our peak list add it to the annotation list
                    // prepare new element
                    FingerprintGroup group = new FingerprintGroup(1.0);
                    group.setNumberObserved(count);
                    group.setFingerprint("0");
                    if (mergedFingerprintGroupLists.containsKey(matchedMass)) {
                        // check if the mass was already inserted
                        MassToFingerprintGroupList currentGroupList = mergedFingerprintGroupLists.get(matchedMass);
                        FingerprintGroup curGroup = currentGroupList.getElementByFingerprint(group.getFingerprint());
                        // check if fingerprint was already inserted
                        if (// if not simply add it
                        curGroup == null)
                            // if not simply add it
                            currentGroupList.addElement(group);
                        else {
                            // if already present decrease number observed elements (as already observed)
                            numNonMatchElements--;
                            // adapt values
                            curGroup.setNumberObserved(curGroup.getNumberObserved() + group.getNumberObserved());
                            curGroup.setProbability(curGroup.getProbability() + group.getProbability());
                        }
                    } else {
                        // if mass not yet present simply add it
                        MassToFingerprintGroupList currentGroupList = new MassToFingerprintGroupList(matchedMass);
                        currentGroupList.addElement(group);
                        mergedFingerprintGroupLists.put(matchedMass, currentGroupList);
                    }
                }
            }
        }
        // now add loss-fingerprint assignments which were annotated in the training
        while ((line = breader.readLine()) != null) {
            line = line.trim();
            if (line.length() == 0)
                continue;
            if (line.startsWith("#"))
                continue;
            if (line.startsWith("SUMMARY")) {
                String[] tmp = line.split("\\s+");
                // sum overall occurrences
                settings.set(VariableNames.LOSS_FINGERPRINT_DENOMINATOR_COUNT_NAME, Double.parseDouble(tmp[2]) + numNonMatchOccurrences);
                // number different peak pairs matched
                settings.set(VariableNames.LOSS_FINGERPRINT_MATCHED_TUPLE_COUNT_NAME, Double.parseDouble(tmp[1]) - numMatchedObservationsMerged);
                // number different peak pairs non-matched
                settings.set(VariableNames.LOSS_FINGERPRINT_NON_MATCHED_TUPLE_COUNT_NAME, (double) numNonMatchElements);
                continue;
            }
            String[] tmp = line.split("\\s+");
            Double loss = Double.parseDouble(tmp[0]);
            // check whether the current loss in our annotation is also present in the peak list
            Double matchedMass = this.containsMass(loss, uniqueMassDifferences, mzabs, mzppm);
            if (matchedMass != null) {
                // if yes we need to consider it
                // create fingerprint groups from annotation entry
                FingerprintGroup[] groups = this.getFingerprintGroup(tmp);
                if (mergedFingerprintGroupLists.containsKey(matchedMass)) {
                    // check whether mass is already present
                    MassToFingerprintGroupList currentGroupList = mergedFingerprintGroupLists.get(matchedMass);
                    for (int i = 0; i < groups.length; i++) {
                        // check if fingerprint is already inserted
                        FingerprintGroup curGroup = currentGroupList.getElementByFingerprint(groups[i].getFingerprint());
                        if (// if not simply add it
                        curGroup == null)
                            // if not simply add it
                            currentGroupList.addElement(groups[i]);
                        else {
                            // otherwise increase the number of matched observations to adapt number of unique tupels
                            if (curGroup.getFingerprint().getSize() != 1)
                                numMatchedObservationsMerged++;
                            // adapt loss-fingerprint assignment values
                            curGroup.setNumberObserved(curGroup.getNumberObserved() + groups[i].getNumberObserved());
                            curGroup.setProbability(curGroup.getProbability() + groups[i].getProbability());
                        }
                    }
                } else {
                    // if mass not yet present simply add it
                    MassToFingerprintGroupList currentGroupList = new MassToFingerprintGroupList(matchedMass);
                    for (int i = 0; i < groups.length; i++) currentGroupList.addElement(groups[i]);
                    mergedFingerprintGroupLists.put(matchedMass, currentGroupList);
                }
            }
        }
        java.util.Iterator<Double> it = mergedFingerprintGroupLists.keySet().iterator();
        while (it.hasNext()) {
            lossToFingerprintGroupListCollection.addElementSorted(mergedFingerprintGroupLists.get(it.next()));
        }
        // store all mass differences (losses) found in the peak list
        for (int i = 0; i < massDifferences.size(); i++) {
            if (lossToFingerprintGroupListCollection.getElementByPeak(massDifferences.get(i), mzppm, mzabs) != null)
                lossMassesFound.add(massDifferences.get(i));
        }
        breader.close();
        settings.set(VariableNames.LOSS_MASSES_FOUND_PEAKLIST_NAME, lossMassesFound);
        settings.set(VariableNames.LOSS_TO_FINGERPRINT_GROUP_LIST_COLLECTION_NAME, lossToFingerprintGroupListCollection);
    }
}
Also used : MassToFingerprintsHashMap(de.ipbhalle.metfraglib.substructure.MassToFingerprintsHashMap) MassToFingerprintGroupListCollection(de.ipbhalle.metfraglib.substructure.MassToFingerprintGroupListCollection) DefaultPeakList(de.ipbhalle.metfraglib.list.DefaultPeakList) MassToFingerprintGroupList(de.ipbhalle.metfraglib.substructure.MassToFingerprintGroupList) FileReader(java.io.FileReader) FingerprintGroup(de.ipbhalle.metfraglib.substructure.FingerprintGroup) Fingerprint(de.ipbhalle.metfraglib.fingerprint.Fingerprint) BufferedReader(java.io.BufferedReader) BufferedReader(java.io.BufferedReader) File(java.io.File)

Example 2 with DefaultPeakList

use of de.ipbhalle.metfraglib.list.DefaultPeakList in project MetFragRelaunched by ipb-halle.

the class CombinedAutomatedAnnotationScoreInitialiser method initPeakParameters.

public void initPeakParameters(Settings settings) throws Exception {
    if (!settings.containsKey(VariableNames.PEAK_TO_SMARTS_GROUP_LIST_COLLECTION_NAME) || settings.get(VariableNames.PEAK_TO_SMARTS_GROUP_LIST_COLLECTION_NAME) == null) {
        PeakToSmartsGroupListCollection peakToSmartGroupListCollection = new PeakToSmartsGroupListCollection();
        String filename = (String) settings.get(VariableNames.SMARTS_PEAK_ANNOTATION_FILE_NAME);
        DefaultPeakList peakList = (DefaultPeakList) settings.get(VariableNames.PEAK_LIST_NAME);
        Double mzppm = (Double) settings.get(VariableNames.RELATIVE_MASS_DEVIATION_NAME);
        Double mzabs = (Double) settings.get(VariableNames.ABSOLUTE_MASS_DEVIATION_NAME);
        BufferedReader breader = new BufferedReader(new FileReader(new File(filename)));
        String line = "";
        while ((line = breader.readLine()) != null) {
            line = line.trim();
            if (line.length() == 0)
                continue;
            if (line.startsWith("#"))
                continue;
            String[] tmp = line.split("\\s+");
            Double peak = Double.parseDouble(tmp[0]);
            if (!peakList.containsMass(peak, mzppm, mzabs))
                continue;
            PeakToSmartsGroupList peakToSmartGroupList = new PeakToSmartsGroupList(peak);
            SmartsGroup smartsGroup = null;
            for (int i = 1; i < tmp.length; i++) {
                if (this.isDoubleValue(tmp[i])) {
                    if (smartsGroup != null)
                        peakToSmartGroupList.addElement(smartsGroup);
                    smartsGroup = new SmartsGroup(Double.parseDouble(tmp[i]));
                } else {
                    smartsGroup.addElement(tmp[i]);
                }
                if (i == (tmp.length - 1)) {
                    peakToSmartGroupList.addElement(smartsGroup);
                    peakToSmartGroupListCollection.addElement(peakToSmartGroupList);
                }
            }
        }
        breader.close();
        settings.set(VariableNames.PEAK_TO_SMARTS_GROUP_LIST_COLLECTION_NAME, peakToSmartGroupListCollection);
    }
}
Also used : PeakToSmartsGroupListCollection(de.ipbhalle.metfraglib.substructure.PeakToSmartsGroupListCollection) BufferedReader(java.io.BufferedReader) SmartsGroup(de.ipbhalle.metfraglib.substructure.SmartsGroup) FileReader(java.io.FileReader) DefaultPeakList(de.ipbhalle.metfraglib.list.DefaultPeakList) File(java.io.File) PeakToSmartsGroupList(de.ipbhalle.metfraglib.substructure.PeakToSmartsGroupList)

Example 3 with DefaultPeakList

use of de.ipbhalle.metfraglib.list.DefaultPeakList in project MetFragRelaunched by ipb-halle.

the class OfflineMetFusionSpectralSimilarityScore method main.

public static void main(String[] args) throws Exception {
    MetFragGlobalSettings settings = new MetFragGlobalSettings();
    settings.set(VariableNames.PEAK_LIST_STRING_NAME, "65.0381 17.51663\n" + "108.0472 18.403548\n" + "125.0479 26.16408\n" + "156.0125 47.006652\n" + "173.0383 100");
    settings.set(VariableNames.PRECURSOR_NEUTRAL_MASS_NAME, 172.0306);
    FilteredStringTandemMassPeakListReader peaklistreader = new FilteredStringTandemMassPeakListReader(settings);
    DefaultPeakList peaklist = peaklistreader.read();
    settings.set(VariableNames.PEAK_LIST_NAME, peaklist);
    PrecursorCandidate candidate = new PrecursorCandidate("InChI=1S/C6H8N2O2S/c7-5-1-3-6(4-2-5)11(8,9)10/h1-4H,7H2,(H2,8,9,10)", "Sulfanilamide");
    settings.set(VariableNames.CANDIDATE_NAME, candidate);
    OfflineMetFusionSpectralSimilarityScore score = new OfflineMetFusionSpectralSimilarityScore(settings);
    score.calculate();
    System.out.println(score.getValue());
}
Also used : MetFragGlobalSettings(de.ipbhalle.metfraglib.settings.MetFragGlobalSettings) FilteredStringTandemMassPeakListReader(de.ipbhalle.metfraglib.peaklistreader.FilteredStringTandemMassPeakListReader) DefaultPeakList(de.ipbhalle.metfraglib.list.DefaultPeakList) PrecursorCandidate(de.ipbhalle.metfraglib.candidate.PrecursorCandidate)

Example 4 with DefaultPeakList

use of de.ipbhalle.metfraglib.list.DefaultPeakList in project MetFragRelaunched by ipb-halle.

the class MoNARestWebService method performSpectrumSimilaritySearch.

public CandidateList performSpectrumSimilaritySearch() throws Exception {
    DefaultPeakList peaklist = (DefaultPeakList) this.settings.get(VariableNames.PEAK_LIST_NAME);
    String queryString = "{\"compound\":{},\"metadata\":[],\"tags\":[],\"match\":{\"spectra\":\"";
    for (int i = 0; i < peaklist.getNumberElements(); i++) {
        TandemMassPeak peak = (TandemMassPeak) peaklist.getElement(i);
        queryString += peak.getMass() + ":" + peak.getAbsoluteIntensity();
        if (i != (peaklist.getNumberElements() - 1))
            queryString += " ";
    }
    queryString += "\"}}";
    String result = performQuery(queryString, "http://mona.fiehnlab.ucdavis.edu/rest/spectra/search");
    JSONParser parser = new JSONParser();
    JSONArray jsonArray = (JSONArray) parser.parse(new java.io.InputStreamReader(IOUtils.toInputStream(result)));
    CandidateList spectralCandidates = new CandidateList();
    this.logger.info("Got " + jsonArray.size() + " results from MoNA.");
    java.util.ArrayList<String> inchikeys = new java.util.ArrayList<String>();
    java.util.ArrayList<Double> scores = new java.util.ArrayList<Double>();
    for (int i = 0; i < jsonArray.size(); i++) {
        try {
            JSONObject obj = (JSONObject) jsonArray.get(i);
            JSONObject compoundObject = (JSONObject) obj.get("chemicalCompound");
            JSONObject scoreObject = (JSONObject) obj.get("score");
            Double currentScore = (Double) scoreObject.get("score");
            String currentInChIKey1 = (String) compoundObject.get("inchiKey");
            // unique results by inchikey
            int index = inchikeys.indexOf(currentInChIKey1);
            if (index != -1) {
                double scoreAlreadyFound = scores.get(index);
                if (scoreAlreadyFound > currentScore)
                    continue;
                else {
                    spectralCandidates.removeElement(index);
                    scores.remove(index);
                    inchikeys.remove(index);
                }
            }
            ICandidate candidate = new PrecursorCandidate((String) compoundObject.get("inchi"), String.valueOf((Long) compoundObject.get("id")));
            candidate.setProperty(VariableNames.INCHI_KEY_NAME, (String) compoundObject.get("inchiKey"));
            candidate.setProperty(VariableNames.INCHI_KEY_1_NAME, ((String) compoundObject.get("inchiKey")).split("-")[0]);
            candidate.setProperty("scaledScore", scoreObject.get("scaledScore"));
            candidate.setProperty("score", currentScore);
            candidate.setProperty("relativeScore", scoreObject.get("relativeScore"));
            inchikeys.add(currentInChIKey1);
            scores.add(currentScore);
            spectralCandidates.addElement(candidate);
        } catch (Exception e) {
            System.err.println("performSpectrumSimilaritySearch MoNARestWebService error");
            spectralCandidates = new CandidateList();
            break;
        }
    }
    this.logger.info("After filtering " + spectralCandidates.getNumberElements() + " results left.");
    return spectralCandidates;
}
Also used : InputStreamReader(java.io.InputStreamReader) JSONArray(org.json.simple.JSONArray) DefaultPeakList(de.ipbhalle.metfraglib.list.DefaultPeakList) PrecursorCandidate(de.ipbhalle.metfraglib.candidate.PrecursorCandidate) ICandidate(de.ipbhalle.metfraglib.interfaces.ICandidate) ParseException(org.json.simple.parser.ParseException) IOException(java.io.IOException) JSONObject(org.json.simple.JSONObject) CandidateList(de.ipbhalle.metfraglib.list.CandidateList) JSONParser(org.json.simple.parser.JSONParser) TandemMassPeak(de.ipbhalle.metfraglib.peak.TandemMassPeak)

Example 5 with DefaultPeakList

use of de.ipbhalle.metfraglib.list.DefaultPeakList in project MetFragRelaunched by ipb-halle.

the class PeakListValidator method validate.

@Override
public void validate(FacesContext arg0, UIComponent arg1, Object value) throws ValidatorException {
    try {
        if (value == null)
            throw new Exception();
        String string = ((String) value).trim();
        if (string.length() == 0)
            throw new Exception();
        MetFragGlobalSettings settings = new MetFragGlobalSettings();
        settings.set(VariableNames.PEAK_LIST_STRING_NAME, string);
        settings.set(VariableNames.PRECURSOR_NEUTRAL_MASS_NAME, 0.0);
        DefaultPeakList peaklist = new StringTandemMassPeakListReader(settings).read();
        if (((TandemMassPeak) peaklist.getElement(peaklist.getNumberElements() - 1)).getMass() > 1000)
            throw new Exception();
    } catch (Exception e) {
        FacesMessage msg = new FacesMessage();
        msg.setDetail("Invalid peak list.");
        msg.setSummary("Invalid peak list.");
        msg.setSeverity(FacesMessage.SEVERITY_ERROR);
        throw new ValidatorException(msg);
    }
}
Also used : ValidatorException(javax.faces.validator.ValidatorException) MetFragGlobalSettings(de.ipbhalle.metfraglib.settings.MetFragGlobalSettings) DefaultPeakList(de.ipbhalle.metfraglib.list.DefaultPeakList) FacesMessage(javax.faces.application.FacesMessage) ValidatorException(javax.faces.validator.ValidatorException) StringTandemMassPeakListReader(de.ipbhalle.metfraglib.peaklistreader.StringTandemMassPeakListReader)

Aggregations

DefaultPeakList (de.ipbhalle.metfraglib.list.DefaultPeakList)18 BufferedReader (java.io.BufferedReader)6 File (java.io.File)6 FileReader (java.io.FileReader)6 MetFragGlobalSettings (de.ipbhalle.metfraglib.settings.MetFragGlobalSettings)5 IOException (java.io.IOException)5 Fingerprint (de.ipbhalle.metfraglib.fingerprint.Fingerprint)3 ICandidate (de.ipbhalle.metfraglib.interfaces.ICandidate)3 CandidateList (de.ipbhalle.metfraglib.list.CandidateList)3 StringTandemMassPeakListReader (de.ipbhalle.metfraglib.peaklistreader.StringTandemMassPeakListReader)3 MassToFingerprintGroupList (de.ipbhalle.metfraglib.substructure.MassToFingerprintGroupList)3 MassToFingerprintGroupListCollection (de.ipbhalle.metfraglib.substructure.MassToFingerprintGroupListCollection)3 MassToFingerprintsHashMap (de.ipbhalle.metfraglib.substructure.MassToFingerprintsHashMap)3 PeakToSmartsGroupList (de.ipbhalle.metfraglib.substructure.PeakToSmartsGroupList)3 PeakToSmartsGroupListCollection (de.ipbhalle.metfraglib.substructure.PeakToSmartsGroupListCollection)3 SmartsGroup (de.ipbhalle.metfraglib.substructure.SmartsGroup)3 InputStreamReader (java.io.InputStreamReader)3 JSONArray (org.json.simple.JSONArray)3 JSONObject (org.json.simple.JSONObject)3 JSONParser (org.json.simple.parser.JSONParser)3