Search in sources :

Example 6 with MZTolerance

use of net.sf.mzmine.parameters.parametertypes.tolerances.MZTolerance in project mzmine2 by mzmine.

the class KovatsIndexExtractionDialog method setMzRangeByAlkane.

private void setMzRangeByAlkane(int diff) {
    if (currentAlkane == null) {
        currentAlkane = KovatsIndex.C4;
    } else {
        int index = currentAlkane.ordinal() + diff;
        index = Math.min(Math.max(index, 0), KovatsIndex.values().length);
        currentAlkane = KovatsIndex.values()[index];
    }
    String formula = currentAlkane.getFormula(cbCurrentAlkaneSubH.isSelected());
    lbCurrentAlkane.setText(formula);
    // set mz
    Range<Double> mzRange = MzRangeFormulaCalculatorModule.getMzRangeFromFormula(formula, IonizationType.POSITIVE, new MZTolerance(0.75, 0), 1);
    ((MZRangeComponent) getComponentForParameter(KovatsIndexExtractionParameters.mzRange)).setValue(mzRange);
}
Also used : MZTolerance(net.sf.mzmine.parameters.parametertypes.tolerances.MZTolerance) MZRangeComponent(net.sf.mzmine.parameters.parametertypes.ranges.MZRangeComponent)

Example 7 with MZTolerance

use of net.sf.mzmine.parameters.parametertypes.tolerances.MZTolerance in project mzmine2 by mzmine.

the class MsMsSpectraMergeModule method merge.

/**
 * Merge a scan into a merged spectrum.
 *
 * @param orderedByMz peaks from merged spectrum, sorted by ascending m/z
 * @param orderedByInt peaks from scan, sorted by descending intensity
 * @return a merged spectrum. Might be the original one if no new peaks were added.
 */
private static MergedDataPoint[] merge(MergedDataPoint[] orderedByMz, DataPoint[] orderedByInt, MzMergeMode mzMergeMode, IntensityMergeMode intensityMergeMode, MZTolerance expectedPPM) {
    // we assume a rather large deviation as signal peaks should be contained in more than one
    // measurement
    expectedPPM = new MZTolerance(expectedPPM.getMzTolerance() * 4, expectedPPM.getPpmTolerance() * 4);
    final List<MergedDataPoint> append = new ArrayList<>();
    for (int k = 0; k < orderedByInt.length; ++k) {
        final DataPoint peak = orderedByInt[k];
        final double dev = expectedPPM.getMzToleranceForMass(peak.getMZ());
        final double lb = peak.getMZ() - dev, ub = peak.getMZ() + dev;
        int mz1 = Arrays.binarySearch(orderedByMz, peak, Comparator.comparingDouble(DataPoint::getMZ));
        if (mz1 < 0) {
            mz1 = -(mz1 + 1);
        }
        int mz0 = mz1 - 1;
        while (mz1 < orderedByMz.length && orderedByMz[mz1].getMZ() <= ub) ++mz1;
        --mz1;
        while (mz0 >= 0 && orderedByMz[mz0].getMZ() >= lb) --mz0;
        ++mz0;
        if (mz0 <= mz1) {
            // merge!
            int mostIntense = mz0;
            double bestScore = Double.NEGATIVE_INFINITY;
            for (int i = mz0; i <= mz1; ++i) {
                final double massDiff = orderedByMz[i].getMZ() - peak.getMZ();
                final double score = Erf.erfc(3 * massDiff) / (dev * Math.sqrt(2)) * orderedByMz[i].getIntensity();
                if (score > bestScore) {
                    bestScore = score;
                    mostIntense = i;
                }
            }
            orderedByMz[mostIntense] = orderedByMz[mostIntense].merge(peak, mzMergeMode, intensityMergeMode);
        } else {
            // append
            append.add(new MergedDataPoint(mzMergeMode, intensityMergeMode, peak));
        }
    }
    if (append.size() > 0) {
        int offset = orderedByMz.length;
        orderedByMz = Arrays.copyOf(orderedByMz, orderedByMz.length + append.size());
        for (MergedDataPoint p : append) {
            orderedByMz[offset++] = p;
        }
        ScanUtils.sortDataPointsByMz(orderedByMz);
    }
    return orderedByMz;
}
Also used : MZTolerance(net.sf.mzmine.parameters.parametertypes.tolerances.MZTolerance) DataPoint(net.sf.mzmine.datamodel.DataPoint) ArrayList(java.util.ArrayList) DataPoint(net.sf.mzmine.datamodel.DataPoint)

Example 8 with MZTolerance

use of net.sf.mzmine.parameters.parametertypes.tolerances.MZTolerance in project mzmine2 by mzmine.

the class MsMsSpectraMergeModule method mergeAcrossFragmentSpectra.

/**
 * Internal method that merges a list of spectra into one.
 *
 * @param fragmentMergedSpectra list of spectra with meta information
 * @return merged spectrum
 */
protected MergedSpectrum mergeAcrossFragmentSpectra(ParameterSet parameters, List<MergedSpectrum> fragmentMergedSpectra) {
    if (fragmentMergedSpectra.isEmpty())
        return MergedSpectrum.empty();
    int totalNumberOfScans = 0;
    for (MergedSpectrum s : fragmentMergedSpectra) totalNumberOfScans += s.totalNumberOfScans();
    final double[] scores = new double[fragmentMergedSpectra.size()];
    for (int k = 0; k < fragmentMergedSpectra.size(); ++k) {
        scores[k] = fragmentMergedSpectra.get(k).bestFragmentScanScore;
    }
    int scansRemovedDueToLowQuality = 0;
    final double bestScore = Arrays.stream(scores).max().getAsDouble();
    // only pick fragment scans with decent quality
    final List<MergedSpectrum> selectedScans = new ArrayList<>();
    MergedSpectrum bestOne = null;
    for (int k = 0; k < fragmentMergedSpectra.size(); ++k) {
        if (scores[k] >= bestScore / 5d) {
            if (scores[k] >= bestScore)
                bestOne = fragmentMergedSpectra.get(k);
            selectedScans.add(fragmentMergedSpectra.get(k));
        } else {
            scansRemovedDueToLowQuality += fragmentMergedSpectra.get(k).totalNumberOfScans();
        }
    }
    Collections.sort(selectedScans, Comparator.comparingInt(u -> u.scanIds[0]));
    int bestIndex = 0;
    for (int k = 0; k < selectedScans.size(); ++k) {
        if (selectedScans.get(k) == bestOne)
            bestIndex = k;
    }
    final List<MergedSpectrum> toMerge = new ArrayList<>();
    toMerge.add(bestOne);
    for (int i = 1; i < selectedScans.size(); ++i) {
        int k = bestIndex - i;
        if (k >= 0)
            toMerge.add(selectedScans.get(k));
        k = bestIndex + i;
        if (k < selectedScans.size())
            toMerge.add(selectedScans.get(k));
    }
    if (toMerge.size() == 1) {
        toMerge.get(0).removedScansByLowQuality = scansRemovedDueToLowQuality;
        return toMerge.get(0);
    }
    /*
     * merge every scan if its cosine is above the cosine threshold
     */
    final double cosineThreshold = parameters.getParameter(MsMsSpectraMergeParameters.COSINE_PARAMETER).getValue();
    final MZTolerance massTolerance = parameters.getParameter(MsMsSpectraMergeParameters.MASS_ACCURACY).getValue();
    final MzMergeMode mzMergeMode = parameters.getParameter(MsMsSpectraMergeParameters.MZ_MERGE_MODE).getValue();
    final IntensityMergeMode intensityMergeMode = parameters.getParameter(MsMsSpectraMergeParameters.INTENSITY_MERGE_MODE).getValue();
    MergedSpectrum initial = bestOne;
    final double lowestMassToConsider = Math.min(50d, initial.precursorMz - 50d);
    final DataPoint[] initialMostIntense = ScanUtils.extractMostIntensePeaksAcrossMassRange(initial.data, Range.closed(lowestMassToConsider, lowestMassToConsider + 100), 6);
    final Range<Double> cosineRange = Range.closed(lowestMassToConsider, initial.precursorMz - 20);
    double lowestIntensityToConsider;
    {
        Optional<MergedDataPoint> max = Arrays.stream(initial.data).filter(x -> cosineRange.contains(x.getMZ())).max(Comparator.comparingDouble(u -> u.intensity));
        if (!max.isPresent()) {
            // no peak beside precursor ion
            return MergedSpectrum.empty(totalNumberOfScans);
        }
        MergedDataPoint basePeak = max.get();
        lowestIntensityToConsider = basePeak.sources[0].getIntensity();
        for (DataPoint p : basePeak.sources) {
            lowestIntensityToConsider = Math.max(p.getIntensity(), lowestIntensityToConsider);
        }
        lowestIntensityToConsider = lowestIntensityToConsider * 0.01;
    }
    final double initialCosine = ScanUtils.probabilityProductUnnormalized(initialMostIntense, initialMostIntense, massTolerance, lowestIntensityToConsider, cosineRange);
    for (int k = 1; k < toMerge.size(); ++k) {
        MergedSpectrum scan = toMerge.get(k);
        DataPoint[] dataPoints = scan.data;
        final DataPoint[] mostIntense = ScanUtils.extractMostIntensePeaksAcrossMassRange(dataPoints, Range.closed(50d, 150d), 6);
        final double norm = ScanUtils.probabilityProductUnnormalized(mostIntense, mostIntense, massTolerance, lowestIntensityToConsider, cosineRange);
        final double cosine = ScanUtils.probabilityProductUnnormalized(initialMostIntense, mostIntense, massTolerance, lowestIntensityToConsider, cosineRange) / Math.sqrt(norm * initialCosine);
        if (cosine >= cosineThreshold) {
            initial = merge(initial, scan, mzMergeMode, intensityMergeMode, massTolerance);
        } else {
            initial.removedScansByLowCosine += scan.totalNumberOfScans();
        }
    }
    initial.removedScansByLowQuality = scansRemovedDueToLowQuality;
    return initial;
}
Also used : Scan(net.sf.mzmine.datamodel.Scan) MZTolerance(net.sf.mzmine.parameters.parametertypes.tolerances.MZTolerance) Arrays(java.util.Arrays) LoggerFactory(org.slf4j.LoggerFactory) Range(com.google.common.collect.Range) RawDataFile(net.sf.mzmine.datamodel.RawDataFile) Collectors(java.util.stream.Collectors) DataPoint(net.sf.mzmine.datamodel.DataPoint) ArrayList(java.util.ArrayList) MassList(net.sf.mzmine.datamodel.MassList) PeakListRow(net.sf.mzmine.datamodel.PeakListRow) ScanUtils(net.sf.mzmine.util.scans.ScanUtils) HashSet(java.util.HashSet) List(java.util.List) Feature(net.sf.mzmine.datamodel.Feature) MZmineModule(net.sf.mzmine.modules.MZmineModule) ParameterSet(net.sf.mzmine.parameters.ParameterSet) Optional(java.util.Optional) Comparator(java.util.Comparator) Erf(org.apache.commons.math3.special.Erf) Collections(java.util.Collections) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) MZTolerance(net.sf.mzmine.parameters.parametertypes.tolerances.MZTolerance) Optional(java.util.Optional) ArrayList(java.util.ArrayList) DataPoint(net.sf.mzmine.datamodel.DataPoint) DataPoint(net.sf.mzmine.datamodel.DataPoint)

Example 9 with MZTolerance

use of net.sf.mzmine.parameters.parametertypes.tolerances.MZTolerance in project mzmine2 by mzmine.

the class MsMsVisualizerWindow method actionPerformed.

/**
 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
 */
public void actionPerformed(ActionEvent event) {
    String command = event.getActionCommand();
    if (command.equals("SHOW_SPECTRUM")) {
        CursorPosition pos = getCursorPosition();
        if (pos != null) {
            SpectraVisualizerModule.showNewSpectrumWindow(pos.getDataFile(), pos.getScanNumber());
        }
    }
    if (command.equals("SETUP_AXES")) {
        AxesSetupDialog dialog = new AxesSetupDialog(this, IDAPlot.getXYPlot());
        dialog.setVisible(true);
    }
    if (command.equals("SHOW_DATA_POINTS")) {
        IDAPlot.switchDataPointsVisible();
    }
    if (command.equals("SWITCH_TOOLTIPS")) {
        if (tooltipMode) {
            IDAPlot.showPeaksTooltips(false);
            toolBar.setTooltipButton(false);
            tooltipMode = false;
        } else {
            IDAPlot.showPeaksTooltips(true);
            toolBar.setTooltipButton(true);
            tooltipMode = true;
        }
    }
    if (command.equals("FIND_SPECTRA")) {
        // Parameters
        final DoubleParameter inputMZ = new DoubleParameter("Ion m/z", "m/z value of ion to search for.");
        final MZToleranceParameter inputMZTolerance = new MZToleranceParameter();
        final DoubleParameter inputIntensity = new DoubleParameter("Min. ion intensity", "Only ions with intensities above this value will be searched for.");
        final BooleanParameter inputNL = new BooleanParameter("Neutral Loss", "If selected, the ion to be searched for will be a neutral loss ion.\nIn this case, only ions above the min. intensity will be examined.", false);
        final ComboParameter<Colors> inputColors = new ComboParameter<Colors>("Color", "The color which the data points will be marked with.", Colors.values());
        Parameter<?>[] parameters = new Parameter<?>[5];
        parameters[0] = inputMZ;
        parameters[1] = inputMZTolerance;
        parameters[2] = inputIntensity;
        parameters[3] = inputNL;
        parameters[4] = inputColors;
        final ParameterSet parametersSearch = new SimpleParameterSet(parameters);
        ExitCode exitCode = parametersSearch.showSetupDialog(this, true);
        if (exitCode != ExitCode.OK)
            return;
        double searchMZ = parametersSearch.getParameter(inputMZ).getValue();
        MZTolerance searchMZTolerance = parametersSearch.getParameter(inputMZTolerance).getValue();
        double minIntensity = parametersSearch.getParameter(inputIntensity).getValue();
        boolean neutralLoss = parametersSearch.getParameter(inputNL).getValue();
        Color highligtColor = Color.red;
        ;
        if (parametersSearch.getParameter(inputColors).getValue().equals(Colors.green)) {
            highligtColor = Color.green;
        }
        if (parametersSearch.getParameter(inputColors).getValue().equals(Colors.blue)) {
            highligtColor = Color.blue;
        }
        // Find and highlight spectra with specific ion
        dataset.highlightSpectra(searchMZ, searchMZTolerance, minIntensity, neutralLoss, highligtColor);
        // Add legend entry
        LegendItemCollection chartLegend = IDAPlot.getXYPlot().getLegendItems();
        chartLegend.add(new LegendItem("Ion: " + searchMZ, "", "MS/MS spectra which contain the " + searchMZ + " ion\nTolerance: " + searchMZTolerance.toString() + "\nMin intensity: " + minIntensity, "", new Ellipse2D.Double(0, 0, 7, 7), highligtColor));
        IDAPlot.getXYPlot().setFixedLegendItems(chartLegend);
    }
}
Also used : ParameterSet(net.sf.mzmine.parameters.ParameterSet) SimpleParameterSet(net.sf.mzmine.parameters.impl.SimpleParameterSet) MZTolerance(net.sf.mzmine.parameters.parametertypes.tolerances.MZTolerance) DoubleParameter(net.sf.mzmine.parameters.parametertypes.DoubleParameter) MZToleranceParameter(net.sf.mzmine.parameters.parametertypes.tolerances.MZToleranceParameter) SimpleParameterSet(net.sf.mzmine.parameters.impl.SimpleParameterSet) LegendItemCollection(org.jfree.chart.LegendItemCollection) ExitCode(net.sf.mzmine.util.ExitCode) Color(java.awt.Color) BooleanParameter(net.sf.mzmine.parameters.parametertypes.BooleanParameter) AxesSetupDialog(net.sf.mzmine.util.dialogs.AxesSetupDialog) ComboParameter(net.sf.mzmine.parameters.parametertypes.ComboParameter) LegendItem(org.jfree.chart.LegendItem) Parameter(net.sf.mzmine.parameters.Parameter) WindowSettingsParameter(net.sf.mzmine.parameters.parametertypes.WindowSettingsParameter) DoubleParameter(net.sf.mzmine.parameters.parametertypes.DoubleParameter) ComboParameter(net.sf.mzmine.parameters.parametertypes.ComboParameter) BooleanParameter(net.sf.mzmine.parameters.parametertypes.BooleanParameter) MZToleranceParameter(net.sf.mzmine.parameters.parametertypes.tolerances.MZToleranceParameter) CursorPosition(net.sf.mzmine.modules.visualization.tic.CursorPosition)

Example 10 with MZTolerance

use of net.sf.mzmine.parameters.parametertypes.tolerances.MZTolerance in project mzmine2 by mzmine.

the class IsotopePatternScoreCalculator method getSimilarityScore.

/**
 * Returns a calculated similarity score of two isotope patterns in the range of 0 (not similar at
 * all) to 1 (100% same).
 */
public static double getSimilarityScore(IsotopePattern ip1, IsotopePattern ip2, ParameterSet parameters) {
    assert ip1 != null;
    assert ip2 != null;
    MZTolerance mzTolerance = parameters.getParameter(IsotopePatternScoreParameters.mzTolerance).getValue();
    assert mzTolerance != null;
    final double patternIntensity = Math.max(ip1.getHighestDataPoint().getIntensity(), ip2.getHighestDataPoint().getIntensity());
    final double noiseIntensity = parameters.getParameter(IsotopePatternScoreParameters.isotopeNoiseLevel).getValue();
    // Normalize the isotopes to intensity 0..1
    IsotopePattern nip1 = IsotopePatternCalculator.normalizeIsotopePattern(ip1);
    IsotopePattern nip2 = IsotopePatternCalculator.normalizeIsotopePattern(ip2);
    // Merge the data points from both isotope patterns into a single array.
    // Data points from first pattern will have positive intensities, data
    // points from second pattern will have negative intensities.
    ArrayList<DataPoint> mergedDataPoints = new ArrayList<DataPoint>();
    for (DataPoint dp : nip1.getDataPoints()) {
        if (dp.getIntensity() * patternIntensity < noiseIntensity)
            continue;
        mergedDataPoints.add(dp);
    }
    for (DataPoint dp : nip2.getDataPoints()) {
        if (dp.getIntensity() * patternIntensity < noiseIntensity)
            continue;
        DataPoint negativeDP = new SimpleDataPoint(dp.getMZ(), dp.getIntensity() * -1);
        mergedDataPoints.add(negativeDP);
    }
    DataPoint[] mergedDPArray = mergedDataPoints.toArray(new DataPoint[0]);
    // Sort the merged data points by m/z
    Arrays.sort(mergedDPArray, new DataPointSorter(SortingProperty.MZ, SortingDirection.Ascending));
    // tolerance
    for (int i = 0; i < mergedDPArray.length - 1; i++) {
        Range<Double> toleranceRange = mzTolerance.getToleranceRange(mergedDPArray[i].getMZ());
        if (!toleranceRange.contains(mergedDPArray[i + 1].getMZ()))
            continue;
        double summedIntensity = mergedDPArray[i].getIntensity() + mergedDPArray[i + 1].getIntensity();
        double newMZ = mergedDPArray[i + 1].getMZ();
        // Update the next data point and remove the current one
        mergedDPArray[i + 1] = new SimpleDataPoint(newMZ, summedIntensity);
        mergedDPArray[i] = null;
    }
    // Calculate the resulting score. Ideal score is 1, in case the final
    // data point array is empty.
    double result = 1;
    for (DataPoint dp : mergedDPArray) {
        if (dp == null)
            continue;
        double remainingIntensity = Math.abs(dp.getIntensity());
        // intensity may be over 1
        if (remainingIntensity > 1)
            remainingIntensity = 1;
        // Decrease the score with each remaining peak
        result *= 1 - remainingIntensity;
    }
    return result;
}
Also used : MZTolerance(net.sf.mzmine.parameters.parametertypes.tolerances.MZTolerance) SimpleDataPoint(net.sf.mzmine.datamodel.impl.SimpleDataPoint) SimpleDataPoint(net.sf.mzmine.datamodel.impl.SimpleDataPoint) DataPoint(net.sf.mzmine.datamodel.DataPoint) ArrayList(java.util.ArrayList) DataPointSorter(net.sf.mzmine.util.DataPointSorter) IsotopePattern(net.sf.mzmine.datamodel.IsotopePattern) SimpleDataPoint(net.sf.mzmine.datamodel.impl.SimpleDataPoint) DataPoint(net.sf.mzmine.datamodel.DataPoint)

Aggregations

MZTolerance (net.sf.mzmine.parameters.parametertypes.tolerances.MZTolerance)12 ArrayList (java.util.ArrayList)6 DataPoint (net.sf.mzmine.datamodel.DataPoint)6 Nullable (javax.annotation.Nullable)3 MassList (net.sf.mzmine.datamodel.MassList)3 ParameterSet (net.sf.mzmine.parameters.ParameterSet)3 Range (com.google.common.collect.Range)2 PeakListRow (net.sf.mzmine.datamodel.PeakListRow)2 Scan (net.sf.mzmine.datamodel.Scan)2 DataPointSorter (net.sf.mzmine.util.DataPointSorter)2 ExitCode (net.sf.mzmine.util.ExitCode)2 Color (java.awt.Color)1 Arrays (java.util.Arrays)1 Collections (java.util.Collections)1 Comparator (java.util.Comparator)1 HashSet (java.util.HashSet)1 Hashtable (java.util.Hashtable)1 List (java.util.List)1 Optional (java.util.Optional)1 Vector (java.util.Vector)1