Search in sources :

Example 11 with CandidateList

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

the class CandidateListWriterCSV method writeFile.

@Override
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 || candidateList.getNumberElements() == 0) {
        writeDefaultHeader(file);
        return false;
    }
    java.io.Writer writer = new java.io.OutputStreamWriter(new java.io.FileOutputStream(file), Charset.forName("UTF-8"));
    CSVPrinter csvFilePrinter = new CSVPrinter(writer, CSVFormat.EXCEL);
    java.util.List<Object> header = new java.util.ArrayList<Object>();
    for (int i = 0; i < candidateList.getNumberElements(); i++) {
        int countExplainedPeaks = 0;
        ICandidate scoredCandidate = candidateList.getElement(i);
        String origIdentifier = ((String) scoredCandidate.getProperty(VariableNames.IDENTIFIER_NAME)).replaceAll("\\|[0-9]+", "");
        if (settings != null)
            scoredCandidate.setUseSmiles((Boolean) settings.get(VariableNames.USE_SMILES_NAME));
        try {
            scoredCandidate.initialisePrecursorCandidate();
        } catch (Exception e) {
            continue;
        }
        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++;
            }
        }
        String peaksExplained = "";
        String sumFormulasOfFragmentsExplainedPeaks = "";
        if (scoredCandidate.getMatchList() != null) {
            for (int ii = 0; ii < scoredCandidate.getMatchList().getNumberElements(); ii++) {
                try {
                    double intensity = scoredCandidate.getMatchList().getElement(ii).getMatchedPeak().getIntensity();
                    peaksExplained += scoredCandidate.getMatchList().getElement(ii).getMatchedPeak().getMass() + "_" + intensity + ";";
                } catch (RelativeIntensityNotDefinedException e1) {
                    continue;
                }
                String formula = scoredCandidate.getMatchList().getElement(ii).getModifiedFormulaStringOfBestMatchedFragment(scoredCandidate.getPrecursorMolecule());
                sumFormulasOfFragmentsExplainedPeaks += scoredCandidate.getMatchList().getElement(ii).getMatchedPeak().getMass() + ":" + formula + ";";
            }
            if (sumFormulasOfFragmentsExplainedPeaks.length() != 0)
                sumFormulasOfFragmentsExplainedPeaks = sumFormulasOfFragmentsExplainedPeaks.substring(0, sumFormulasOfFragmentsExplainedPeaks.length() - 1);
            if (peaksExplained.length() != 0)
                peaksExplained = peaksExplained.substring(0, peaksExplained.length() - 1);
            if (peaksExplained.length() == 0)
                peaksExplained = "NA";
            if (sumFormulasOfFragmentsExplainedPeaks.length() == 0)
                sumFormulasOfFragmentsExplainedPeaks = "NA";
            scoredCandidate.setProperty(VariableNames.EXPLAINED_PEAKS_COLUMN, peaksExplained);
            scoredCandidate.setProperty(VariableNames.FORMULAS_OF_PEAKS_EXPLAINED_COLUMN, sumFormulasOfFragmentsExplainedPeaks);
            scoredCandidate.setProperty(VariableNames.NUMBER_PEAKS_USED_COLUMN, numberOfPeaksUsed);
            scoredCandidate.setProperty(VariableNames.NUMBER_EXPLAINED_PEAKS_COLUMN, countExplainedPeaks);
        }
        java.util.Enumeration<String> keys = scoredCandidate.getProperties().keys();
        if (i == 0) {
            while (keys.hasMoreElements()) {
                String key = keys.nextElement();
                header.add(key);
            }
            csvFilePrinter.printRecord(header);
        }
        java.util.List<Object> entries = new java.util.ArrayList<Object>();
        for (int ii = 0; ii < header.size(); ii++) {
            if (header.get(ii).equals(VariableNames.IDENTIFIER_NAME))
                entries.add(origIdentifier);
            else
                entries.add(checkEmptyProperty(scoredCandidate.getProperty((String) header.get(ii))));
        }
        csvFilePrinter.printRecord(entries);
    }
    writer.flush();
    writer.close();
    csvFilePrinter.close();
    return true;
}
Also used : MatchList(de.ipbhalle.metfraglib.list.MatchList) RelativeIntensityNotDefinedException(de.ipbhalle.metfraglib.exceptions.RelativeIntensityNotDefinedException) ICandidate(de.ipbhalle.metfraglib.interfaces.ICandidate) IOException(java.io.IOException) RelativeIntensityNotDefinedException(de.ipbhalle.metfraglib.exceptions.RelativeIntensityNotDefinedException) CSVPrinter(org.apache.commons.csv.CSVPrinter) SortedScoredCandidateList(de.ipbhalle.metfraglib.list.SortedScoredCandidateList) CandidateList(de.ipbhalle.metfraglib.list.CandidateList) ScoredCandidateList(de.ipbhalle.metfraglib.list.ScoredCandidateList) SortedScoredCandidateList(de.ipbhalle.metfraglib.list.SortedScoredCandidateList) ScoredCandidateList(de.ipbhalle.metfraglib.list.ScoredCandidateList) SortedScoredCandidateList(de.ipbhalle.metfraglib.list.SortedScoredCandidateList)

Example 12 with CandidateList

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

the class CandidateListWriterExtendedFragmentsXLS method writeFile.

public boolean writeFile(File xlsFile, 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;
    for (int i = 0; i < candidateList.getNumberElements(); i++) {
        int countExplainedPeaks = 0;
        ICandidate scoredCandidate = candidateList.getElement(i);
        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++;
            }
        }
        String peaksExplained = "";
        String sumFormulasOfFragmentsExplainedPeaks = "";
        if (scoredCandidate.getMatchList() != null) {
            for (int ii = 0; ii < scoredCandidate.getMatchList().getNumberElements(); ii++) {
                try {
                    double intensity = scoredCandidate.getMatchList().getElement(ii).getMatchedPeak().getIntensity();
                    peaksExplained += scoredCandidate.getMatchList().getElement(ii).getMatchedPeak().getMass() + "_" + intensity + ";";
                } catch (RelativeIntensityNotDefinedException e1) {
                    continue;
                }
                String formula = scoredCandidate.getMatchList().getElement(ii).getModifiedFormulaStringOfBestMatchedFragment(scoredCandidate.getPrecursorMolecule());
                sumFormulasOfFragmentsExplainedPeaks += scoredCandidate.getMatchList().getElement(ii).getMatchedPeak().getMass() + ":" + formula + ";";
            }
            if (sumFormulasOfFragmentsExplainedPeaks.length() != 0)
                sumFormulasOfFragmentsExplainedPeaks = sumFormulasOfFragmentsExplainedPeaks.substring(0, sumFormulasOfFragmentsExplainedPeaks.length() - 1);
            if (peaksExplained.length() != 0)
                peaksExplained = peaksExplained.substring(0, peaksExplained.length() - 1);
            if (peaksExplained.length() == 0)
                peaksExplained = "NA";
            if (sumFormulasOfFragmentsExplainedPeaks.length() == 0)
                sumFormulasOfFragmentsExplainedPeaks = "NA";
            scoredCandidate.setProperty("ExplPeaks", peaksExplained);
            scoredCandidate.setProperty("FormulasOfExplPeaks", sumFormulasOfFragmentsExplainedPeaks);
            scoredCandidate.setProperty("NumberPeaksUsed", numberOfPeaksUsed);
            scoredCandidate.setProperty("NoExplPeaks", countExplainedPeaks);
        }
    }
    boolean withImages = true;
    boolean withFragments = true;
    xlsFile.createNewFile();
    WritableWorkbook workbook = Workbook.createWorkbook(xlsFile);
    WritableSheet sheet1 = workbook.createSheet("MetFrag result list", 0);
    WritableFont arial10font = new WritableFont(WritableFont.ARIAL, 10);
    WritableCellFormat arial10format = new WritableCellFormat(arial10font);
    arial10font.setBoldStyle(WritableFont.BOLD);
    int numberCells = 0;
    java.util.Map<String, Integer> labels = new java.util.HashMap<String, Integer>();
    int columnWidthAdd = withImages || withFragments ? 3 : 0;
    int rowHeightAdd = withImages || withFragments ? 9 : 1;
    List<RenderedImage> molImages = null;
    List<List<RenderedImage>> molFragmentImages = null;
    if (withImages) {
        molImages = convertMoleculesToImages(candidateList);
        for (int i = 0; i < molImages.size(); i++) {
            File imageFile = File.createTempFile("file" + i, ".png", new File(Constants.OS_TEMP_DIR));
            imageFile.deleteOnExit();
            if (ImageIO.write(molImages.get(i), "png", imageFile)) {
                WritableImage wi = new WritableImage(0, (i * rowHeightAdd) + 1, columnWidthAdd, rowHeightAdd, imageFile);
                sheet1.addImage(wi);
            }
        }
    }
    if (withFragments) {
        molFragmentImages = convertMoleculesAndFragmentToImages(candidateList);
        WritableSheet sheet2 = workbook.createSheet("MetFrag fragment lists", 1);
        sheet2.addCell(new Label(0, 0, "Precursor", arial10format));
        sheet2.addCell(new Label(4, 0, "Identifier", arial10format));
        sheet2.addCell(new Label(5, 0, "Fragments", arial10format));
        for (int i = 0; i < molFragmentImages.size(); i++) {
            File imageFile = File.createTempFile("file" + i, ".png", new File(Constants.OS_TEMP_DIR));
            imageFile.deleteOnExit();
            if (ImageIO.write(molFragmentImages.get(i).get(0), "png", imageFile)) {
                WritableImage wi = new WritableImage(0, (i * rowHeightAdd) + 1, columnWidthAdd, rowHeightAdd, imageFile);
                sheet2.addImage(wi);
            }
            for (int k = molFragmentImages.get(i).size() - 1; k >= 1; k--) {
                File fragmentimageFile = File.createTempFile("file_" + i + "_" + k, ".png", new File(Constants.OS_TEMP_DIR));
                fragmentimageFile.deleteOnExit();
                if (ImageIO.write(molFragmentImages.get(i).get(k), "png", fragmentimageFile)) {
                    WritableImage wi = new WritableImage(((molFragmentImages.get(i).size() - k) * columnWidthAdd) + 2, (i * rowHeightAdd) + 1, columnWidthAdd, rowHeightAdd, fragmentimageFile);
                    sheet2.addImage(wi);
                }
            }
            sheet2.addCell(new Label(4, (i * rowHeightAdd) + 1, ((String) candidateList.getElement(i).getIdentifier()).replaceAll("\\|[0-9]+", "")));
        }
    }
    for (int i = 0; i < candidateList.getNumberElements(); i++) {
        java.util.Hashtable<String, Object> properties = candidateList.getElement(i).getProperties();
        Iterator<String> propNames = properties.keySet().iterator();
        while (propNames.hasNext()) {
            String propName = (String) propNames.next();
            if (!labels.containsKey(propName)) {
                labels.put(propName, Integer.valueOf(numberCells));
                sheet1.addCell(new Label(labels.get(propName) + columnWidthAdd, 0, propName, arial10format));
                numberCells++;
            }
            sheet1.addCell(new Label(labels.get(propName) + columnWidthAdd, (i * rowHeightAdd) + 1, String.valueOf(checkEmptyProperty(properties.get(propName)))));
        }
    }
    workbook.write();
    workbook.close();
    return true;
}
Also used : Label(jxl.write.Label) ICandidate(de.ipbhalle.metfraglib.interfaces.ICandidate) CandidateList(de.ipbhalle.metfraglib.list.CandidateList) ScoredCandidateList(de.ipbhalle.metfraglib.list.ScoredCandidateList) SortedScoredCandidateList(de.ipbhalle.metfraglib.list.SortedScoredCandidateList) MatchList(de.ipbhalle.metfraglib.list.MatchList) CandidateList(de.ipbhalle.metfraglib.list.CandidateList) ArrayList(java.util.ArrayList) ScoredCandidateList(de.ipbhalle.metfraglib.list.ScoredCandidateList) List(java.util.List) SortedScoredCandidateList(de.ipbhalle.metfraglib.list.SortedScoredCandidateList) IList(de.ipbhalle.metfraglib.interfaces.IList) ScoredCandidateList(de.ipbhalle.metfraglib.list.ScoredCandidateList) SortedScoredCandidateList(de.ipbhalle.metfraglib.list.SortedScoredCandidateList) MatchList(de.ipbhalle.metfraglib.list.MatchList) WritableFont(jxl.write.WritableFont) WritableSheet(jxl.write.WritableSheet) RelativeIntensityNotDefinedException(de.ipbhalle.metfraglib.exceptions.RelativeIntensityNotDefinedException) WritableCellFormat(jxl.write.WritableCellFormat) WritableWorkbook(jxl.write.WritableWorkbook) WritableImage(jxl.write.WritableImage) SortedScoredCandidateList(de.ipbhalle.metfraglib.list.SortedScoredCandidateList) RenderedImage(java.awt.image.RenderedImage) File(java.io.File)

Example 13 with CandidateList

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

the class CombinedMetFragProcess method initExternalProperties.

/**
 * @param path
 * @param candidateList
 * @return
 */
private boolean initExternalProperties(String path, CandidateList candidateList, String[] propertyValuesToScore) {
    Settings settings = new Settings();
    settings.set(VariableNames.LOCAL_DATABASE_PATH_NAME, path);
    LocalPropertyFileDatabase propertyDatabase = new LocalPropertyFileDatabase(settings);
    java.util.ArrayList<String> externalInChIKeys = new java.util.ArrayList<String>();
    java.util.ArrayList<String> externalPropertiesDefined = new java.util.ArrayList<String>();
    java.util.ArrayList<String> ids = null;
    try {
        ids = propertyDatabase.getCandidateIdentifiers();
    } catch (Exception e) {
        this.logger.error("Error: Problems reading ExternalPropertyFile: " + path);
        return false;
    }
    CandidateList externalCandidates = propertyDatabase.getCandidateByIdentifier(ids);
    for (int i = 0; i < externalCandidates.getNumberElements(); i++) {
        ICandidate externalCandidate = externalCandidates.getElement(i);
        if (!externalCandidate.getProperties().containsKey(VariableNames.INCHI_KEY_1_NAME) || externalCandidate.getProperty(VariableNames.INCHI_KEY_1_NAME) == null) {
            this.logger.error("Error: InChIKey1 field not defined for all candidate in ExternalPropertyFile: " + path);
            return false;
        }
        String externalInChIKey1 = (String) externalCandidate.getProperty(VariableNames.INCHI_KEY_1_NAME);
        if (externalInChIKeys.contains(externalInChIKey1)) {
            this.logger.error("Error: InChIKey1 " + externalInChIKey1 + " defined more than once in ExternalPropertyFile: " + path);
            return false;
        } else
            externalInChIKeys.add(externalInChIKey1);
        // try to set external values
        for (int j = 0; j < candidateList.getNumberElements(); j++) {
            ICandidate candidate = candidateList.getElement(j);
            String candidateInChIKey1 = (String) candidate.getProperty(VariableNames.INCHI_KEY_1_NAME);
            if (externalInChIKey1.equals(candidateInChIKey1)) {
                java.util.Enumeration<?> externalKeys = externalCandidate.getProperties().keys();
                while (externalKeys.hasMoreElements()) {
                    String currentKey = (String) externalKeys.nextElement();
                    for (int k = 0; k < propertyValuesToScore.length; k++) {
                        if (propertyValuesToScore[k].equals(currentKey)) {
                            if (!externalPropertiesDefined.contains(currentKey))
                                externalPropertiesDefined.add(currentKey);
                            Double value = null;
                            try {
                                value = (Double) externalCandidate.getProperty(currentKey);
                            } catch (Exception e1) {
                                try {
                                    value = Double.parseDouble((String) externalCandidate.getProperty(currentKey));
                                } catch (Exception e2) {
                                    this.logger.error("Error: Invalid value for candidate " + externalInChIKey1 + " for column " + currentKey + " in ExternalPropertyFile: " + path);
                                    return false;
                                }
                            }
                            candidate.setProperty(currentKey, value);
                        }
                    }
                }
            }
        }
    }
    // set property to zero (neutral element) in case not defined
    for (int i = 0; i < candidateList.getNumberElements(); i++) {
        ICandidate candidate = candidateList.getElement(i);
        for (int j = 0; j < externalPropertiesDefined.size(); j++) {
            if (!candidate.getProperties().containsKey(externalPropertiesDefined.get(j)) || candidate.getProperty(externalPropertiesDefined.get(j)) == null) {
                candidate.setProperty(externalPropertiesDefined.get(j), 0.0);
            }
        }
    }
    return true;
}
Also used : ScorePropertyNotDefinedException(de.ipbhalle.metfraglib.exceptions.ScorePropertyNotDefinedException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ICandidate(de.ipbhalle.metfraglib.interfaces.ICandidate) LocalPropertyFileDatabase(de.ipbhalle.metfraglib.database.LocalPropertyFileDatabase) SortedScoredCandidateList(de.ipbhalle.metfraglib.list.SortedScoredCandidateList) CandidateList(de.ipbhalle.metfraglib.list.CandidateList) ScoredCandidateList(de.ipbhalle.metfraglib.list.ScoredCandidateList) MetFragGlobalSettings(de.ipbhalle.metfraglib.settings.MetFragGlobalSettings) Settings(de.ipbhalle.metfraglib.settings.Settings) MetFragSingleProcessSettings(de.ipbhalle.metfraglib.settings.MetFragSingleProcessSettings)

Example 14 with CandidateList

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

the class MetFusionMoNASpectralSimilarityInitialiser method initScoreParameters.

@Override
public void initScoreParameters(Settings settings) throws Exception {
    /*
		 * 
		 */
    // initialise MoNA web service
    MoNARestWebService webService = new MoNARestWebService(settings);
    ((ProcessingStatus) settings.get(VariableNames.PROCESS_STATUS_OBJECT_NAME)).setProcessStatusString("Retrieving Results from MoNA");
    CandidateList candidatesFromMoNA = null;
    try {
        candidatesFromMoNA = webService.performSpectrumSimilaritySearch();
    } catch (Exception e) {
        settings.set(VariableNames.METFUSION_MONA_SPECTRAL_SIMILARITY_CANDIDATES_NAME, new CandidateList());
        e.printStackTrace();
        return;
    }
    for (int i = 0; i < candidatesFromMoNA.getNumberElements(); i++) {
        IBitFingerprint fingerprint = TanimotoSimilarity.calculateFingerPrint(candidatesFromMoNA.getElement(i).getAtomContainer());
        candidatesFromMoNA.getElement(i).setProperty("Fingerprint", fingerprint);
    }
    settings.set(VariableNames.METFUSION_MONA_SPECTRAL_SIMILARITY_CANDIDATES_NAME, candidatesFromMoNA);
}
Also used : IBitFingerprint(org.openscience.cdk.fingerprint.IBitFingerprint) MoNARestWebService(de.ipbhalle.metfraglib.functions.MoNARestWebService) CandidateList(de.ipbhalle.metfraglib.list.CandidateList) ProcessingStatus(de.ipbhalle.metfraglib.process.ProcessingStatus) IBitFingerprint(org.openscience.cdk.fingerprint.IBitFingerprint)

Example 15 with CandidateList

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

the class ExactMoNASpectralSimilarity method calculate.

/*
	 * (non-Javadoc)
	 * @see de.ipbhalle.metfraglib.interfaces.IScore#calculate()
	 */
public void calculate() {
    // thread save
    this.value = 0.0;
    /*
		 * previously calculated by ExactMoNASpectralSimilarityInitialiser
		 */
    CandidateList candidatesFromMoNA = (CandidateList) this.settings.get(VariableNames.EXACT_MONA_SPECTRAL_SIMILARITY_CANDIDATES_NAME);
    // beta = -9, gamma = 0.6
    try {
        String candidateInchikey = (String) this.candidate.getProperty(VariableNames.INCHI_KEY_1_NAME);
        for (int i = 0; i < candidatesFromMoNA.getNumberElements(); i++) {
            String currentInChIKey = (String) candidatesFromMoNA.getElement(i).getProperty(VariableNames.INCHI_KEY_1_NAME);
            if (candidateInchikey.equals(currentInChIKey)) {
                double score = (Double) candidatesFromMoNA.getElement(i).getProperty("score");
                if (score > this.value)
                    this.value = score;
            }
        }
    } catch (Exception e) {
        System.err.println("calculate ExactMoNASpectralSimilarity error");
        this.value = 0.0;
    }
    this.calculationFinished = true;
}
Also used : CandidateList(de.ipbhalle.metfraglib.list.CandidateList)

Aggregations

CandidateList (de.ipbhalle.metfraglib.list.CandidateList)80 ICandidate (de.ipbhalle.metfraglib.interfaces.ICandidate)43 MetFragGlobalSettings (de.ipbhalle.metfraglib.settings.MetFragGlobalSettings)22 SortedScoredCandidateList (de.ipbhalle.metfraglib.list.SortedScoredCandidateList)20 MultipleHeadersFoundInInputDatabaseException (de.ipbhalle.metfraglib.exceptions.MultipleHeadersFoundInInputDatabaseException)18 File (java.io.File)18 IOException (java.io.IOException)18 ArrayList (java.util.ArrayList)18 MatchList (de.ipbhalle.metfraglib.list.MatchList)17 ScoredCandidateList (de.ipbhalle.metfraglib.list.ScoredCandidateList)17 RelativeIntensityNotDefinedException (de.ipbhalle.metfraglib.exceptions.RelativeIntensityNotDefinedException)15 FileWriter (java.io.FileWriter)14 TopDownPrecursorCandidate (de.ipbhalle.metfraglib.candidate.TopDownPrecursorCandidate)12 LocalPSVDatabase (de.ipbhalle.metfraglib.database.LocalPSVDatabase)12 AtomTypeNotKnownFromInputListException (de.ipbhalle.metfraglib.exceptions.AtomTypeNotKnownFromInputListException)9 LocalCSVDatabase (de.ipbhalle.metfraglib.database.LocalCSVDatabase)7 Settings (de.ipbhalle.metfraglib.settings.Settings)7 SQLException (java.sql.SQLException)7 IDatabase (de.ipbhalle.metfraglib.interfaces.IDatabase)6 CombinedMetFragProcess (de.ipbhalle.metfraglib.process.CombinedMetFragProcess)6