use of org.openscience.cdk.formula.MolecularFormulaGenerator in project mzmine2 by mzmine.
the class FormulaPredictionPeakListTask method run.
/**
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
setStatus(TaskStatus.PROCESSING);
totalRows = peakList.getNumberOfRows();
for (PeakListRow row : peakList.getRows()) {
if (row.getPeakIdentities().length > 0) {
continue;
}
this.searchedMass = (row.getAverageMZ() - ionType.getAddedMass()) * charge;
message = "Formula prediction for " + MZmineCore.getConfiguration().getMZFormat().format(searchedMass);
massRange = mzTolerance.getToleranceRange(searchedMass);
IChemObjectBuilder builder = SilentChemObjectBuilder.getInstance();
generator = new MolecularFormulaGenerator(builder, massRange.lowerEndpoint(), massRange.upperEndpoint(), elementCounts);
IMolecularFormula cdkFormula;
// create a map to store ResultFormula and relative mass deviation for sorting
Map<Double, String> possibleFormulas = new TreeMap<>();
while ((cdkFormula = generator.getNextFormula()) != null) {
if (isCanceled())
return;
// Mass is ok, so test other constraints
if (checkConstraints(cdkFormula, row) == true) {
String formula = MolecularFormulaManipulator.getString(cdkFormula);
// calc rel mass deviation
Double relMassDev = ((searchedMass - (FormulaUtils.calculateExactMass(formula))) / searchedMass) * 1000000;
// write to map
possibleFormulas.put(relMassDev, formula);
}
}
if (isCanceled())
return;
// create a map to store ResultFormula and relative mass deviation for sorting
Map<Double, String> possibleFormulasSorted = new TreeMap<>((Comparator<Double>) (o1, o2) -> Double.compare(Math.abs(o1), Math.abs(o2)));
possibleFormulasSorted.putAll(possibleFormulas);
// Add the new formula entry top results
int ctr = 0;
for (Map.Entry<Double, String> entry : possibleFormulasSorted.entrySet()) {
if (ctr < maxBestFormulasPerPeak) {
SimplePeakIdentity newIdentity = new SimplePeakIdentity(entry.getValue(), entry.getValue(), this.getClass().getName(), null, null);
row.addPeakIdentity(newIdentity, false);
ctr++;
}
}
if (isCanceled())
return;
finishedRows++;
}
if (isCanceled())
return;
logger.finest("Finished formula search for all the peaks");
setStatus(TaskStatus.FINISHED);
}
use of org.openscience.cdk.formula.MolecularFormulaGenerator in project mzmine2 by mzmine.
the class SingleRowPredictionTask method run.
/**
* @see java.lang.Runnable#run()
*/
public void run() {
setStatus(TaskStatus.PROCESSING);
resultWindow = new ResultWindow("Searching for " + MZmineCore.getConfiguration().getMZFormat().format(searchedMass), peakListRow, searchedMass, charge, this);
resultWindow.setVisible(true);
logger.finest("Starting search for formulas for " + massRange + " Da");
IsotopePattern detectedPattern = peakListRow.getBestIsotopePattern();
if ((checkIsotopes) && (detectedPattern == null)) {
final String msg = "Cannot calculate isotope pattern scores, because selected" + " peak does not have any isotopes. Have you run the isotope peak grouper?";
MZmineCore.getDesktop().displayMessage(resultWindow, msg);
}
IChemObjectBuilder builder = SilentChemObjectBuilder.getInstance();
generator = new MolecularFormulaGenerator(builder, massRange.lowerEndpoint(), massRange.upperEndpoint(), elementCounts);
IMolecularFormula cdkFormula;
while ((cdkFormula = generator.getNextFormula()) != null) {
if (isCanceled())
return;
// Mass is ok, so test other constraints
checkConstraints(cdkFormula);
}
if (isCanceled())
return;
logger.finest("Finished formula search for " + massRange + " m/z, found " + foundFormulas + " formulas");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
resultWindow.setTitle("Finished searching for " + MZmineCore.getConfiguration().getMZFormat().format(searchedMass) + " amu, " + foundFormulas + " formulas found");
}
});
setStatus(TaskStatus.FINISHED);
}
use of org.openscience.cdk.formula.MolecularFormulaGenerator in project mzmine2 by mzmine.
the class MSMSScoreCalculator method evaluateMSMS.
/**
* Returns a calculated similarity score of
*/
public static MSMSScore evaluateMSMS(IMolecularFormula parentFormula, Scan msmsScan, ParameterSet parameters) {
MZTolerance msmsTolerance = parameters.getParameter(MSMSScoreParameters.msmsTolerance).getValue();
String massListName = parameters.getParameter(MSMSScoreParameters.massList).getValue();
MassList massList = msmsScan.getMassList(massListName);
if (massList == null) {
throw new IllegalArgumentException("Scan #" + msmsScan.getScanNumber() + " does not have a mass list called '" + massListName + "'");
}
DataPoint[] msmsIons = massList.getDataPoints();
if (msmsIons == null) {
throw new IllegalArgumentException("Mass list " + massList + " does not contain data for scan #" + msmsScan.getScanNumber());
}
MolecularFormulaRange msmsElementRange = new MolecularFormulaRange();
for (IIsotope isotope : parentFormula.isotopes()) {
msmsElementRange.addIsotope(isotope, 0, parentFormula.getIsotopeCount(isotope));
}
int totalMSMSpeaks = 0, interpretedMSMSpeaks = 0;
Map<DataPoint, String> msmsAnnotations = new Hashtable<DataPoint, String>();
msmsCycle: for (DataPoint dp : msmsIons) {
// Check if this is an isotope
Range<Double> isotopeCheckRange = Range.closed(dp.getMZ() - 1.4, dp.getMZ() - 0.6);
for (DataPoint dpCheck : msmsIons) {
// isotope and we should ignore it
if (isotopeCheckRange.contains(dpCheck.getMZ()) && (dpCheck.getIntensity() > dp.getIntensity())) {
continue msmsCycle;
}
}
// If getPrecursorCharge() returns 0, it means charge is unknown. In
// that case let's assume charge 1
int precursorCharge = msmsScan.getPrecursorCharge();
if (precursorCharge == 0)
precursorCharge = 1;
// We don't know the charge of the fragment, so we will simply
// assume 1
double neutralLoss = msmsScan.getPrecursorMZ() * precursorCharge - dp.getMZ();
// good threshold
if (neutralLoss < 5) {
continue;
}
Range<Double> msmsTargetRange = msmsTolerance.getToleranceRange(neutralLoss);
IChemObjectBuilder builder = SilentChemObjectBuilder.getInstance();
MolecularFormulaGenerator msmsEngine = new MolecularFormulaGenerator(builder, msmsTargetRange.lowerEndpoint(), msmsTargetRange.upperEndpoint(), msmsElementRange);
IMolecularFormula formula = msmsEngine.getNextFormula();
if (formula != null) {
String formulaString = MolecularFormulaManipulator.getString(formula);
msmsAnnotations.put(dp, formulaString);
interpretedMSMSpeaks++;
}
totalMSMSpeaks++;
}
// If we did not evaluate any MS/MS peaks, we cannot calculate a score
if (totalMSMSpeaks == 0) {
return null;
}
double msmsScore = (double) interpretedMSMSpeaks / totalMSMSpeaks;
MSMSScore result = new MSMSScore(msmsScore, msmsAnnotations);
return result;
}
use of org.openscience.cdk.formula.MolecularFormulaGenerator in project mzmine2 by mzmine.
the class SpectraIdentificationSumFormulaTask method run.
/**
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
setStatus(TaskStatus.PROCESSING);
logger.finest("Starting search for formulas for " + massRange + " Da");
// create mass list for scan
DataPoint[] massList = null;
ArrayList<DataPoint> massListAnnotated = new ArrayList<>();
MassDetector massDetector = null;
ArrayList<String> allCompoundIDs = new ArrayList<>();
// Create a new mass list for MS/MS scan. Check if sprectrum is profile or centroid mode
if (currentScan.getSpectrumType() == MassSpectrumType.CENTROIDED) {
massDetector = new CentroidMassDetector();
CentroidMassDetectorParameters parameters = new CentroidMassDetectorParameters();
CentroidMassDetectorParameters.noiseLevel.setValue(noiseLevel);
massList = massDetector.getMassValues(currentScan.getDataPoints(), parameters);
} else {
massDetector = new ExactMassDetector();
ExactMassDetectorParameters parameters = new ExactMassDetectorParameters();
ExactMassDetectorParameters.noiseLevel.setValue(noiseLevel);
massList = massDetector.getMassValues(currentScan.getDataPoints(), parameters);
}
numItems = massList.length;
// loop through every peak in mass list
if (getStatus() != TaskStatus.PROCESSING) {
return;
}
IChemObjectBuilder builder = SilentChemObjectBuilder.getInstance();
for (int i = 0; i < massList.length; i++) {
massRange = mzTolerance.getToleranceRange((massList[i].getMZ() - ionType.getAddedMass()) / charge);
generator = new MolecularFormulaGenerator(builder, massRange.lowerEndpoint(), massRange.upperEndpoint(), elementCounts);
IMolecularFormula cdkFormula;
String annotation = "";
// create a map to store ResultFormula and relative mass deviation for sorting
Map<Double, String> possibleFormulas = new TreeMap<>();
while ((cdkFormula = generator.getNextFormula()) != null) {
if (isCanceled())
return;
// Mass is ok, so test other constraints
if (checkConstraints(cdkFormula) == true) {
String formula = MolecularFormulaManipulator.getString(cdkFormula);
// calc rel mass deviation
Double relMassDev = ((((//
massList[i].getMZ() - ionType.getAddedMass()) / //
charge) - (//
FormulaUtils.calculateExactMass(MolecularFormulaManipulator.getString(cdkFormula))) / charge) / ((//
massList[i].getMZ() - ionType.getAddedMass()) / charge)) * 1000000;
// write to map
possibleFormulas.put(relMassDev, formula);
}
}
Map<Double, String> treeMap = new TreeMap<>((Comparator<Double>) (o1, o2) -> Double.compare(Math.abs(o1), Math.abs(o2)));
treeMap.putAll(possibleFormulas);
// get top 3
int ctr = 0;
for (Map.Entry<Double, String> entry : treeMap.entrySet()) {
int number = ctr + 1;
if (ctr > 2)
break;
annotation = annotation + number + ". " + entry.getValue() + " Δ " + NumberFormat.getInstance().format(entry.getKey()) + " ppm; ";
ctr++;
if (isCanceled())
return;
}
if (annotation != "") {
allCompoundIDs.add(annotation);
massListAnnotated.add(massList[i]);
}
logger.finest("Finished formula search for " + massRange + " m/z, found " + foundFormulas + " formulas");
}
// new mass list
DataPoint[] annotatedMassList = new DataPoint[massListAnnotated.size()];
massListAnnotated.toArray(annotatedMassList);
String[] annotations = new String[annotatedMassList.length];
allCompoundIDs.toArray(annotations);
DataPointsDataSet detectedCompoundsDataset = new DataPointsDataSet("Detected compounds", annotatedMassList);
// Add label generator for the dataset
SpectraDatabaseSearchLabelGenerator labelGenerator = new SpectraDatabaseSearchLabelGenerator(annotations, spectraPlot);
spectraPlot.addDataSet(detectedCompoundsDataset, Color.orange, true, labelGenerator);
spectraPlot.getXYPlot().getRenderer().setSeriesItemLabelGenerator(spectraPlot.getXYPlot().getSeriesCount(), labelGenerator);
spectraPlot.getXYPlot().getRenderer().setDefaultPositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.TOP_LEFT, TextAnchor.BOTTOM_CENTER, 0.0), true);
setStatus(TaskStatus.FINISHED);
}
use of org.openscience.cdk.formula.MolecularFormulaGenerator in project mzmine2 by mzmine.
the class DPPSumFormulaPredictionTask method run.
@Override
public void run() {
if (!checkParameterSet() || !checkValues()) {
setStatus(TaskStatus.ERROR);
return;
}
if (getDataPoints().length == 0) {
logger.info("Data point/Spectra processing: 0 data points were passed to " + getTaskDescription() + " Please check the parameters.");
setStatus(TaskStatus.CANCELED);
return;
}
if (!(getDataPoints() instanceof ProcessedDataPoint[])) {
logger.info("Data point/Spectra processing: The array of data points passed to " + getTaskDescription() + " is not an instance of ProcessedDataPoint. Make sure to run mass detection first.");
setStatus(TaskStatus.CANCELED);
return;
}
setStatus(TaskStatus.PROCESSING);
List<ProcessedDataPoint> resultList = new ArrayList<>();
IChemObjectBuilder builder = SilentChemObjectBuilder.getInstance();
for (int i = 0; i < dataPoints.length; i++) {
if (isCanceled())
return;
if (dataPoints[i].getIntensity() < noiseLevel)
continue;
massRange = mzTolerance.getToleranceRange((dataPoints[i].getMZ() - ionType.getAddedMass()) / charge);
MolecularFormulaRange elCounts = DynamicParameterUtils.buildFormulaRangeOnIsotopePatternResults((ProcessedDataPoint) dataPoints[i], elementCounts);
generator = new MolecularFormulaGenerator(builder, massRange.lowerEndpoint(), massRange.upperEndpoint(), elCounts);
List<PredResult> formulas = generateFormulas((ProcessedDataPoint) dataPoints[i], massRange, charge, generator);
DPPSumFormulaResult[] results = genereateResults(formulas, numResults);
((ProcessedDataPoint) dataPoints[i]).addAllResults(results);
resultList.add((ProcessedDataPoint) dataPoints[i]);
currentIndex++;
}
// setResults((ProcessedDataPoint[]) dataPoints);
setResults(resultList.toArray(new ProcessedDataPoint[0]));
setStatus(TaskStatus.FINISHED);
}
Aggregations