Search in sources :

Example 11 with IsotopePattern

use of net.sf.mzmine.datamodel.IsotopePattern in project mzmine2 by mzmine.

the class SingleRowIdentificationTask method run.

/**
 * @see java.lang.Runnable#run()
 */
public void run() {
    setStatus(TaskStatus.PROCESSING);
    NumberFormat massFormater = MZmineCore.getConfiguration().getMZFormat();
    ResultWindow window = new ResultWindow(peakListRow, searchedMass, this);
    window.setTitle("Searching for " + massFormater.format(searchedMass) + " amu");
    window.setVisible(true);
    IsotopePattern detectedPattern = peakListRow.getBestIsotopePattern();
    if ((isotopeFilter) && (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(window, msg);
    }
    try {
        String[] compoundIDs = gateway.findCompounds(searchedMass, mzTolerance, numOfResults, db.getParameterSet());
        // Get the number of results
        numItems = compoundIDs.length;
        if (numItems == 0) {
            window.setTitle("Searching for " + massFormater.format(searchedMass) + " amu: no results found");
        }
        // Process each one of the result ID's.
        for (int i = 0; i < numItems; i++) {
            if (getStatus() != TaskStatus.PROCESSING) {
                return;
            }
            DBCompound compound = gateway.getCompound(compoundIDs[i], db.getParameterSet());
            // In case we failed to retrieve data, skip this compound
            if (compound == null)
                continue;
            String formula = compound.getPropertyValue(PeakIdentity.PROPERTY_FORMULA);
            if (formula != null) {
                // First modify the formula according to the ionization
                String adjustedFormula = FormulaUtils.ionizeFormula(formula, ionType, charge);
                logger.finest("Calculating isotope pattern for compound formula " + formula + " adjusted to " + adjustedFormula);
                // Generate IsotopePattern for this compound
                IsotopePattern compoundIsotopePattern = IsotopePatternCalculator.calculateIsotopePattern(adjustedFormula, 0.001, charge, ionType.getPolarity());
                compound.setIsotopePattern(compoundIsotopePattern);
                IsotopePattern rawDataIsotopePattern = peakListRow.getBestIsotopePattern();
                // If required, check isotope score
                if (isotopeFilter && (rawDataIsotopePattern != null) && (compoundIsotopePattern != null)) {
                    double score = IsotopePatternScoreCalculator.getSimilarityScore(rawDataIsotopePattern, compoundIsotopePattern, isotopeFilterParameters);
                    compound.setIsotopePatternScore(score);
                    double minimumScore = isotopeFilterParameters.getParameter(IsotopePatternScoreParameters.isotopePatternScoreThreshold).getValue();
                    if (score < minimumScore) {
                        finishedItems++;
                        continue;
                    }
                }
            }
            // Add compound to the list of possible candidate and
            // display it in window of results.
            window.addNewListItem(compound);
            // Update window title
            window.setTitle("Searching for " + massFormater.format(searchedMass) + " amu (" + (i + 1) + "/" + numItems + ")");
            finishedItems++;
        }
    } catch (Exception e) {
        e.printStackTrace();
        logger.log(Level.WARNING, "Could not connect to " + db, e);
        setStatus(TaskStatus.ERROR);
        setErrorMessage("Could not connect to " + db + ": " + ExceptionUtils.exceptionToString(e));
        return;
    }
    setStatus(TaskStatus.FINISHED);
}
Also used : IsotopePattern(net.sf.mzmine.datamodel.IsotopePattern) NumberFormat(java.text.NumberFormat)

Example 12 with IsotopePattern

use of net.sf.mzmine.datamodel.IsotopePattern in project mzmine2 by mzmine.

the class ADAP3AlignerTask method getComponent.

/**
 * Convert a {@link PeakListRow} with one {@link Feature} into {@link Component}.
 *
 * @param row an instance of {@link PeakListRow}. This parameter cannot be null.
 * @return an instance of {@link Component} or null if the row doesn't contain any peaks or isotope patterns.
 */
@Nullable
private Component getComponent(final PeakListRow row) {
    if (row.getNumberOfPeaks() == 0)
        return null;
    // Read Spectrum information
    NavigableMap<Double, Double> spectrum = new TreeMap<>();
    IsotopePattern pattern = row.getBestIsotopePattern();
    if (pattern == null)
        throw new IllegalArgumentException("ADAP Alignment requires mass " + "spectra (or isotopic patterns) of peaks. No spectra found.");
    for (DataPoint dataPoint : pattern.getDataPoints()) spectrum.put(dataPoint.getMZ(), dataPoint.getIntensity());
    // Read Chromatogram
    final Feature peak = row.getBestPeak();
    final RawDataFile dataFile = peak.getDataFile();
    NavigableMap<Double, Double> chromatogram = new TreeMap<>();
    for (final int scan : peak.getScanNumbers()) {
        final DataPoint dataPoint = peak.getDataPoint(scan);
        if (dataPoint != null)
            chromatogram.put(dataFile.getScan(scan).getRetentionTime(), dataPoint.getIntensity());
    }
    return new Component(null, new Peak(chromatogram, new PeakInfo().mzValue(peak.getMZ()).peakID(row.getID())), spectrum, null);
}
Also used : DataPoint(net.sf.mzmine.datamodel.DataPoint) RawDataFile(net.sf.mzmine.datamodel.RawDataFile) IsotopePattern(net.sf.mzmine.datamodel.IsotopePattern) Peak(dulab.adap.datamodel.Peak) TreeMap(java.util.TreeMap) Component(dulab.adap.datamodel.Component) ReferenceComponent(dulab.adap.datamodel.ReferenceComponent) Feature(net.sf.mzmine.datamodel.Feature) PeakInfo(dulab.adap.datamodel.PeakInfo) DataPoint(net.sf.mzmine.datamodel.DataPoint) Nullable(javax.annotation.Nullable)

Example 13 with IsotopePattern

use of net.sf.mzmine.datamodel.IsotopePattern in project mzmine2 by mzmine.

the class JoinAlignerTask method run.

/**
 * @see Runnable#run()
 */
@Override
public void run() {
    if ((mzWeight == 0) && (rtWeight == 0)) {
        setStatus(TaskStatus.ERROR);
        setErrorMessage("Cannot run alignment, all the weight parameters are zero");
        return;
    }
    setStatus(TaskStatus.PROCESSING);
    logger.info("Running join aligner");
    // twice, first for score calculation, second for actual alignment.
    for (int i = 0; i < peakLists.length; i++) {
        totalRows += peakLists[i].getNumberOfRows() * 2;
    }
    // Collect all data files
    Vector<RawDataFile> allDataFiles = new Vector<RawDataFile>();
    for (PeakList peakList : peakLists) {
        for (RawDataFile dataFile : peakList.getRawDataFiles()) {
            // Each data file can only have one column in aligned feature list
            if (allDataFiles.contains(dataFile)) {
                setStatus(TaskStatus.ERROR);
                setErrorMessage("Cannot run alignment, because file " + dataFile + " is present in multiple feature lists");
                return;
            }
            allDataFiles.add(dataFile);
        }
    }
    // Create a new aligned feature list
    alignedPeakList = new SimplePeakList(peakListName, allDataFiles.toArray(new RawDataFile[0]));
    // Iterate source feature lists
    for (PeakList peakList : peakLists) {
        // Create a sorted set of scores matching
        TreeSet<RowVsRowScore> scoreSet = new TreeSet<RowVsRowScore>();
        PeakListRow[] allRows = peakList.getRows();
        // Calculate scores for all possible alignments of this row
        for (PeakListRow row : allRows) {
            if (isCanceled())
                return;
            // Calculate limits for a row with which the row can be aligned
            Range<Double> mzRange = mzTolerance.getToleranceRange(row.getAverageMZ());
            Range<Double> rtRange = rtTolerance.getToleranceRange(row.getAverageRT());
            // Get all rows of the aligned peaklist within parameter limits
            PeakListRow[] candidateRows = alignedPeakList.getRowsInsideScanAndMZRange(rtRange, mzRange);
            // Calculate scores and store them
            for (PeakListRow candidate : candidateRows) {
                if (sameChargeRequired) {
                    if (!PeakUtils.compareChargeState(row, candidate))
                        continue;
                }
                if (sameIDRequired) {
                    if (!PeakUtils.compareIdentities(row, candidate))
                        continue;
                }
                if (compareIsotopePattern) {
                    IsotopePattern ip1 = row.getBestIsotopePattern();
                    IsotopePattern ip2 = candidate.getBestIsotopePattern();
                    if ((ip1 != null) && (ip2 != null)) {
                        ParameterSet isotopeParams = parameters.getParameter(JoinAlignerParameters.compareIsotopePattern).getEmbeddedParameters();
                        if (!IsotopePatternScoreCalculator.checkMatch(ip1, ip2, isotopeParams)) {
                            continue;
                        }
                    }
                }
                // compare the similarity of spectra mass lists on MS1 or MS2 level
                if (compareSpectraSimilarity) {
                    DataPoint[] rowDPs = null;
                    DataPoint[] candidateDPs = null;
                    SpectralSimilarity sim = null;
                    // get data points of mass list of the representative scans
                    if (msLevel == 1) {
                        rowDPs = row.getBestPeak().getRepresentativeScan().getMassList(massList).getDataPoints();
                        candidateDPs = candidate.getBestPeak().getRepresentativeScan().getMassList(massList).getDataPoints();
                    }
                    // get data points of mass list of the best fragmentation scans
                    if (msLevel == 2) {
                        if (row.getBestFragmentation() != null && candidate.getBestFragmentation() != null) {
                            rowDPs = row.getBestFragmentation().getMassList(massList).getDataPoints();
                            candidateDPs = candidate.getBestFragmentation().getMassList(massList).getDataPoints();
                        } else
                            continue;
                    }
                    // compare mass list data points of selected scans
                    if (rowDPs != null && candidateDPs != null) {
                        // calculate similarity using SimilarityFunction
                        sim = createSimilarity(rowDPs, candidateDPs);
                        // user set threshold
                        if (sim == null) {
                            continue;
                        }
                    }
                }
                RowVsRowScore score = new RowVsRowScore(row, candidate, RangeUtils.rangeLength(mzRange) / 2.0, mzWeight, RangeUtils.rangeLength(rtRange) / 2.0, rtWeight);
                scoreSet.add(score);
            }
            processedRows++;
        }
        // Create a table of mappings for best scores
        Hashtable<PeakListRow, PeakListRow> alignmentMapping = new Hashtable<PeakListRow, PeakListRow>();
        // Iterate scores by descending order
        Iterator<RowVsRowScore> scoreIterator = scoreSet.iterator();
        while (scoreIterator.hasNext()) {
            RowVsRowScore score = scoreIterator.next();
            // Check if the row is already mapped
            if (alignmentMapping.containsKey(score.getPeakListRow()))
                continue;
            // Check if the aligned row is already filled
            if (alignmentMapping.containsValue(score.getAlignedRow()))
                continue;
            alignmentMapping.put(score.getPeakListRow(), score.getAlignedRow());
        }
        // Align all rows using mapping
        for (PeakListRow row : allRows) {
            PeakListRow targetRow = alignmentMapping.get(row);
            // If we have no mapping for this row, add a new one
            if (targetRow == null) {
                targetRow = new SimplePeakListRow(newRowID);
                newRowID++;
                alignedPeakList.addRow(targetRow);
            }
            // Add all peaks from the original row to the aligned row
            for (RawDataFile file : row.getRawDataFiles()) {
                targetRow.addPeak(file, row.getPeak(file));
            }
            // Add all non-existing identities from the original row to the
            // aligned row
            PeakUtils.copyPeakListRowProperties(row, targetRow);
            processedRows++;
        }
    }
    // Next feature list
    // Add new aligned feature list to the project
    project.addPeakList(alignedPeakList);
    // Add task description to peakList
    alignedPeakList.addDescriptionOfAppliedTask(new SimplePeakListAppliedMethod("Join aligner", parameters));
    logger.info("Finished join aligner");
    setStatus(TaskStatus.FINISHED);
}
Also used : ParameterSet(net.sf.mzmine.parameters.ParameterSet) Hashtable(java.util.Hashtable) IsotopePattern(net.sf.mzmine.datamodel.IsotopePattern) SpectralSimilarity(net.sf.mzmine.util.scans.similarity.SpectralSimilarity) SimplePeakListAppliedMethod(net.sf.mzmine.datamodel.impl.SimplePeakListAppliedMethod) SimplePeakListRow(net.sf.mzmine.datamodel.impl.SimplePeakListRow) DataPoint(net.sf.mzmine.datamodel.DataPoint) SimplePeakListRow(net.sf.mzmine.datamodel.impl.SimplePeakListRow) PeakListRow(net.sf.mzmine.datamodel.PeakListRow) RawDataFile(net.sf.mzmine.datamodel.RawDataFile) DataPoint(net.sf.mzmine.datamodel.DataPoint) TreeSet(java.util.TreeSet) SimplePeakList(net.sf.mzmine.datamodel.impl.SimplePeakList) SimplePeakList(net.sf.mzmine.datamodel.impl.SimplePeakList) PeakList(net.sf.mzmine.datamodel.PeakList) Vector(java.util.Vector)

Example 14 with IsotopePattern

use of net.sf.mzmine.datamodel.IsotopePattern in project mzmine2 by mzmine.

the class RowsFilterTask method filterPeakListRows.

/**
 * Filter the feature list rows.
 *
 * @param peakList feature list to filter.
 * @return a new feature list with rows of the original feature list that pass the filtering.
 */
private PeakList filterPeakListRows(final PeakList peakList) {
    // Create new feature list.
    final PeakList newPeakList = new SimplePeakList(peakList.getName() + ' ' + parameters.getParameter(RowsFilterParameters.SUFFIX).getValue(), peakList.getRawDataFiles());
    // Copy previous applied methods.
    for (final PeakListAppliedMethod method : peakList.getAppliedMethods()) {
        newPeakList.addDescriptionOfAppliedTask(method);
    }
    // Add task description to peakList.
    newPeakList.addDescriptionOfAppliedTask(new SimplePeakListAppliedMethod(getTaskDescription(), parameters));
    // Get parameters.
    final boolean onlyIdentified = parameters.getParameter(RowsFilterParameters.HAS_IDENTITIES).getValue();
    final boolean filterByIdentityText = parameters.getParameter(RowsFilterParameters.IDENTITY_TEXT).getValue();
    final boolean filterByCommentText = parameters.getParameter(RowsFilterParameters.COMMENT_TEXT).getValue();
    final String groupingParameter = (String) parameters.getParameter(RowsFilterParameters.GROUPSPARAMETER).getValue();
    final boolean filterByMinPeakCount = parameters.getParameter(RowsFilterParameters.MIN_PEAK_COUNT).getValue();
    final boolean filterByMinIsotopePatternSize = parameters.getParameter(RowsFilterParameters.MIN_ISOTOPE_PATTERN_COUNT).getValue();
    final boolean filterByMzRange = parameters.getParameter(RowsFilterParameters.MZ_RANGE).getValue();
    final boolean filterByRtRange = parameters.getParameter(RowsFilterParameters.RT_RANGE).getValue();
    final boolean filterByDuration = parameters.getParameter(RowsFilterParameters.PEAK_DURATION).getValue();
    final boolean filterByFWHM = parameters.getParameter(RowsFilterParameters.FWHM).getValue();
    final boolean filterByCharge = parameters.getParameter(RowsFilterParameters.CHARGE).getValue();
    final boolean filterByKMD = parameters.getParameter(RowsFilterParameters.KENDRICK_MASS_DEFECT).getValue();
    final boolean filterByMS2 = parameters.getParameter(RowsFilterParameters.MS2_Filter).getValue();
    final String removeRowString = parameters.getParameter(RowsFilterParameters.REMOVE_ROW).getValue();
    Double minCount = parameters.getParameter(RowsFilterParameters.MIN_PEAK_COUNT).getEmbeddedParameter().getValue();
    final boolean renumber = parameters.getParameter(RowsFilterParameters.Reset_ID).getValue();
    int rowsCount = 0;
    boolean removeRow = false;
    if (removeRowString.equals(RowsFilterParameters.removeRowChoices[0]))
        removeRow = false;
    else
        removeRow = true;
    // Keep rows that don't match any criteria. Keep by default.
    boolean filterRowCriteriaFailed = false;
    // Handle < 1 values for minPeakCount
    if ((minCount == null) || (minCount < 1))
        minCount = 1.0;
    // Round value down to nearest hole number
    int intMinCount = minCount.intValue();
    // Filter rows.
    final PeakListRow[] rows = peakList.getRows();
    totalRows = rows.length;
    for (processedRows = 0; !isCanceled() && processedRows < totalRows; processedRows++) {
        filterRowCriteriaFailed = false;
        final PeakListRow row = rows[processedRows];
        final int peakCount = getPeakCount(row, groupingParameter);
        // Check number of peaks.
        if (filterByMinPeakCount) {
            if (peakCount < intMinCount)
                filterRowCriteriaFailed = true;
        }
        // Check identities.
        if (onlyIdentified) {
            if (row.getPreferredPeakIdentity() == null)
                filterRowCriteriaFailed = true;
        }
        // Check average m/z.
        if (filterByMzRange) {
            final Range<Double> mzRange = parameters.getParameter(RowsFilterParameters.MZ_RANGE).getEmbeddedParameter().getValue();
            if (!mzRange.contains(row.getAverageMZ()))
                filterRowCriteriaFailed = true;
        }
        // Check average RT.
        if (filterByRtRange) {
            final Range<Double> rtRange = parameters.getParameter(RowsFilterParameters.RT_RANGE).getEmbeddedParameter().getValue();
            if (!rtRange.contains(row.getAverageRT()))
                filterRowCriteriaFailed = true;
        }
        // Search peak identity text.
        if (filterByIdentityText) {
            if (row.getPreferredPeakIdentity() == null)
                filterRowCriteriaFailed = true;
            if (row.getPreferredPeakIdentity() != null) {
                final String searchText = parameters.getParameter(RowsFilterParameters.IDENTITY_TEXT).getEmbeddedParameter().getValue().toLowerCase().trim();
                int numFailedIdentities = 0;
                PeakIdentity[] identities = row.getPeakIdentities();
                for (int index = 0; !isCanceled() && index < identities.length; index++) {
                    String rowText = identities[index].getName().toLowerCase().trim();
                    if (!rowText.contains(searchText))
                        numFailedIdentities += 1;
                }
                if (numFailedIdentities == identities.length)
                    filterRowCriteriaFailed = true;
            }
        }
        // Search peak comment text.
        if (filterByCommentText) {
            if (row.getComment() == null)
                filterRowCriteriaFailed = true;
            if (row.getComment() != null) {
                final String searchText = parameters.getParameter(RowsFilterParameters.COMMENT_TEXT).getEmbeddedParameter().getValue().toLowerCase().trim();
                final String rowText = row.getComment().toLowerCase().trim();
                if (!rowText.contains(searchText))
                    filterRowCriteriaFailed = true;
            }
        }
        // Calculate average duration and isotope pattern count.
        int maxIsotopePatternSizeOnRow = 1;
        double avgDuration = 0.0;
        final Feature[] peaks = row.getPeaks();
        for (final Feature p : peaks) {
            final IsotopePattern pattern = p.getIsotopePattern();
            if (pattern != null && maxIsotopePatternSizeOnRow < pattern.getNumberOfDataPoints()) {
                maxIsotopePatternSizeOnRow = pattern.getNumberOfDataPoints();
            }
            avgDuration += RangeUtils.rangeLength(p.getRawDataPointsRTRange());
        }
        // Check isotope pattern count.
        if (filterByMinIsotopePatternSize) {
            final int minIsotopePatternSize = parameters.getParameter(RowsFilterParameters.MIN_ISOTOPE_PATTERN_COUNT).getEmbeddedParameter().getValue();
            if (maxIsotopePatternSizeOnRow < minIsotopePatternSize)
                filterRowCriteriaFailed = true;
        }
        // Check average duration.
        avgDuration /= peakCount;
        if (filterByDuration) {
            final Range<Double> durationRange = parameters.getParameter(RowsFilterParameters.PEAK_DURATION).getEmbeddedParameter().getValue();
            if (!durationRange.contains(avgDuration))
                filterRowCriteriaFailed = true;
        }
        // Filter by FWHM range
        if (filterByFWHM) {
            final Range<Double> FWHMRange = parameters.getParameter(RowsFilterParameters.FWHM).getEmbeddedParameter().getValue();
            // If any of the peaks fail the FWHM criteria,
            Double FWHM_value = row.getBestPeak().getFWHM();
            if (FWHM_value != null && !FWHMRange.contains(FWHM_value))
                filterRowCriteriaFailed = true;
        }
        // Filter by charge range
        if (filterByCharge) {
            final Range<Integer> chargeRange = parameters.getParameter(RowsFilterParameters.CHARGE).getEmbeddedParameter().getValue();
            int charge = row.getBestPeak().getCharge();
            if (charge == 0 || !chargeRange.contains(charge))
                filterRowCriteriaFailed = true;
        }
        // Filter by KMD or RKM range
        if (filterByKMD) {
            // get embedded parameters
            final Range<Double> rangeKMD = parameters.getParameter(RowsFilterParameters.KENDRICK_MASS_DEFECT).getEmbeddedParameters().getParameter(KendrickMassDefectFilterParameters.kendrickMassDefectRange).getValue();
            final String kendrickMassBase = parameters.getParameter(RowsFilterParameters.KENDRICK_MASS_DEFECT).getEmbeddedParameters().getParameter(KendrickMassDefectFilterParameters.kendrickMassBase).getValue();
            final double shift = parameters.getParameter(RowsFilterParameters.KENDRICK_MASS_DEFECT).getEmbeddedParameters().getParameter(KendrickMassDefectFilterParameters.shift).getValue();
            final int charge = parameters.getParameter(RowsFilterParameters.KENDRICK_MASS_DEFECT).getEmbeddedParameters().getParameter(KendrickMassDefectFilterParameters.charge).getValue();
            final int divisor = parameters.getParameter(RowsFilterParameters.KENDRICK_MASS_DEFECT).getEmbeddedParameters().getParameter(KendrickMassDefectFilterParameters.divisor).getValue();
            final boolean useRemainderOfKendrickMass = parameters.getParameter(RowsFilterParameters.KENDRICK_MASS_DEFECT).getEmbeddedParameters().getParameter(KendrickMassDefectFilterParameters.useRemainderOfKendrickMass).getValue();
            // get m/z
            Double valueMZ = row.getBestPeak().getMZ();
            // calc exact mass of Kendrick mass base
            double exactMassFormula = FormulaUtils.calculateExactMass(kendrickMassBase);
            // calc exact mass of Kendrick mass factor
            double kendrickMassFactor = Math.round(exactMassFormula / divisor) / (exactMassFormula / divisor);
            double defectOrRemainder = 0.0;
            if (!useRemainderOfKendrickMass) {
                // calc Kendrick mass defect
                defectOrRemainder = Math.ceil(charge * (valueMZ * kendrickMassFactor)) - charge * (valueMZ * kendrickMassFactor);
            } else {
                // calc Kendrick mass remainder
                defectOrRemainder = (charge * (divisor - Math.round(FormulaUtils.calculateExactMass(kendrickMassBase))) * valueMZ) / // 
                FormulaUtils.calculateExactMass(kendrickMassBase) - Math.floor((charge * (divisor - Math.round(FormulaUtils.calculateExactMass(kendrickMassBase))) * valueMZ) / FormulaUtils.calculateExactMass(kendrickMassBase));
            }
            // shift Kendrick mass defect or remainder of Kendrick mass
            double kendrickMassDefectShifted = defectOrRemainder + shift - Math.floor(defectOrRemainder + shift);
            // check if shifted Kendrick mass defect or remainder of Kendrick mass is in range
            if (!rangeKMD.contains(kendrickMassDefectShifted))
                filterRowCriteriaFailed = true;
        }
        // Check ms2 filter .
        if (filterByMS2) {
            // iterates the peaks
            int failCounts = 0;
            for (int i = 0; i < peakCount; i++) {
                if (row.getPeaks()[i].getMostIntenseFragmentScanNumber() < 1) {
                    failCounts++;
                // filterRowCriteriaFailed = true;
                // break;
                }
            }
            if (failCounts == peakCount) {
                filterRowCriteriaFailed = true;
            }
        }
        if (!filterRowCriteriaFailed && !removeRow) {
            // Only add the row if none of the criteria have failed.
            rowsCount++;
            PeakListRow resetRow = copyPeakRow(row);
            if (renumber) {
                resetRow.setID(rowsCount);
            }
            newPeakList.addRow(resetRow);
        }
        if (filterRowCriteriaFailed && removeRow) {
            // Only remove rows that match *all* of the criteria, so add
            // rows that fail any of the criteria.
            rowsCount++;
            PeakListRow resetRow = copyPeakRow(row);
            if (renumber) {
                resetRow.setID(rowsCount);
            }
            newPeakList.addRow(resetRow);
        }
    }
    return newPeakList;
}
Also used : SimplePeakListAppliedMethod(net.sf.mzmine.datamodel.impl.SimplePeakListAppliedMethod) PeakListAppliedMethod(net.sf.mzmine.datamodel.PeakList.PeakListAppliedMethod) IsotopePattern(net.sf.mzmine.datamodel.IsotopePattern) SimplePeakListAppliedMethod(net.sf.mzmine.datamodel.impl.SimplePeakListAppliedMethod) Feature(net.sf.mzmine.datamodel.Feature) SimpleFeature(net.sf.mzmine.datamodel.impl.SimpleFeature) PeakIdentity(net.sf.mzmine.datamodel.PeakIdentity) SimplePeakListRow(net.sf.mzmine.datamodel.impl.SimplePeakListRow) PeakListRow(net.sf.mzmine.datamodel.PeakListRow) SimplePeakList(net.sf.mzmine.datamodel.impl.SimplePeakList) SimplePeakList(net.sf.mzmine.datamodel.impl.SimplePeakList) PeakList(net.sf.mzmine.datamodel.PeakList)

Example 15 with IsotopePattern

use of net.sf.mzmine.datamodel.IsotopePattern in project mzmine2 by mzmine.

the class CameraSearchTask method groupPeaksByPCGroup.

/**
 * Uses PCGroup-field in PeakIdentity to group peaks and build spectrum
 *
 * @param peakList a PeakList object
 * @return a new PeakList object
 */
private PeakList groupPeaksByPCGroup(PeakList peakList) {
    // Create new feature list.
    final PeakList combinedPeakList = new SimplePeakList(peakList + " " + parameters.getParameter(CameraSearchParameters.SUFFIX).getValue(), peakList.getRawDataFiles());
    // Load previous applied methods.
    for (final PeakList.PeakListAppliedMethod method : peakList.getAppliedMethods()) {
        combinedPeakList.addDescriptionOfAppliedTask(method);
    }
    // Add task description to feature list.
    combinedPeakList.addDescriptionOfAppliedTask(new SimplePeakListAppliedMethod("Bioconductor CAMERA", parameters));
    // --------------------
    // Find unique PCGroups
    // --------------------
    Set<String> pcGroups = new HashSet<>();
    for (PeakListRow row : peakList.getRows()) {
        PeakIdentity identity = row.getPreferredPeakIdentity();
        if (identity == null)
            continue;
        String groupName = identity.getName();
        if (groupName == null || groupName.length() == 0)
            continue;
        pcGroups.add(groupName);
    }
    List<PeakListRow> groupRows = new ArrayList<>();
    // Set <String> groupNames = new HashSet <> ();
    Map<Double, Double> spectrum = new HashMap<>();
    List<PeakListRow> newPeakListRows = new ArrayList<>();
    for (String groupName : pcGroups) {
        // -----------------------------------------
        // Find all peaks belonging to isotopeGroups
        // -----------------------------------------
        groupRows.clear();
        // groupNames.clear();
        spectrum.clear();
        double maxIntensity = 0.0;
        PeakListRow groupRow = null;
        for (PeakListRow row : peakList.getRows()) {
            PeakIdentity identity = row.getPreferredPeakIdentity();
            if (identity == null)
                continue;
            String name = identity.getName();
            if (name.equals(groupName)) {
                double intensity = row.getAverageHeight();
                groupRows.add(row);
                // groupNames.add(name);
                spectrum.put(row.getAverageMZ(), intensity);
                if (intensity > maxIntensity) {
                    maxIntensity = intensity;
                    groupRow = row;
                }
            }
        }
        if (groupRow == null || spectrum.size() <= 1)
            continue;
        PeakIdentity identity = groupRow.getPreferredPeakIdentity();
        if (identity == null)
            continue;
        DataPoint[] dataPoints = new DataPoint[spectrum.size()];
        int count = 0;
        for (Entry<Double, Double> e : spectrum.entrySet()) dataPoints[count++] = new SimpleDataPoint(e.getKey(), e.getValue());
        IsotopePattern pattern = new SimpleIsotopePattern(dataPoints, IsotopePatternStatus.PREDICTED, "Spectrum");
        groupRow.getBestPeak().setIsotopePattern(pattern);
        // combinedPeakList.addRow(groupRow);
        newPeakListRows.add(groupRow);
    }
    // ------------------------------------
    // Sort new peak rows by retention time
    // ------------------------------------
    Collections.sort(newPeakListRows, new Comparator<PeakListRow>() {

        @Override
        public int compare(PeakListRow row1, PeakListRow row2) {
            double retTime1 = row1.getAverageRT();
            double retTime2 = row2.getAverageRT();
            return Double.compare(retTime1, retTime2);
        }
    });
    for (PeakListRow row : newPeakListRows) combinedPeakList.addRow(row);
    return combinedPeakList;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) IsotopePattern(net.sf.mzmine.datamodel.IsotopePattern) SimpleIsotopePattern(net.sf.mzmine.datamodel.impl.SimpleIsotopePattern) SimplePeakListAppliedMethod(net.sf.mzmine.datamodel.impl.SimplePeakListAppliedMethod) DataPoint(net.sf.mzmine.datamodel.DataPoint) SimpleDataPoint(net.sf.mzmine.datamodel.impl.SimpleDataPoint) SimplePeakIdentity(net.sf.mzmine.datamodel.impl.SimplePeakIdentity) PeakIdentity(net.sf.mzmine.datamodel.PeakIdentity) SimpleDataPoint(net.sf.mzmine.datamodel.impl.SimpleDataPoint) PeakListRow(net.sf.mzmine.datamodel.PeakListRow) DataPoint(net.sf.mzmine.datamodel.DataPoint) SimpleDataPoint(net.sf.mzmine.datamodel.impl.SimpleDataPoint) SimplePeakList(net.sf.mzmine.datamodel.impl.SimplePeakList) SimpleIsotopePattern(net.sf.mzmine.datamodel.impl.SimpleIsotopePattern) SimplePeakList(net.sf.mzmine.datamodel.impl.SimplePeakList) PeakList(net.sf.mzmine.datamodel.PeakList) HashSet(java.util.HashSet)

Aggregations

IsotopePattern (net.sf.mzmine.datamodel.IsotopePattern)31 DataPoint (net.sf.mzmine.datamodel.DataPoint)19 Feature (net.sf.mzmine.datamodel.Feature)14 RawDataFile (net.sf.mzmine.datamodel.RawDataFile)9 SimpleDataPoint (net.sf.mzmine.datamodel.impl.SimpleDataPoint)9 PeakListRow (net.sf.mzmine.datamodel.PeakListRow)8 ArrayList (java.util.ArrayList)7 SimpleIsotopePattern (net.sf.mzmine.datamodel.impl.SimpleIsotopePattern)7 PeakList (net.sf.mzmine.datamodel.PeakList)6 PeakIdentity (net.sf.mzmine.datamodel.PeakIdentity)5 SimplePeakList (net.sf.mzmine.datamodel.impl.SimplePeakList)5 SimplePeakListAppliedMethod (net.sf.mzmine.datamodel.impl.SimplePeakListAppliedMethod)4 ParameterSet (net.sf.mzmine.parameters.ParameterSet)4 HashMap (java.util.HashMap)3 SimplePeakIdentity (net.sf.mzmine.datamodel.impl.SimplePeakIdentity)3 SimplePeakListRow (net.sf.mzmine.datamodel.impl.SimplePeakListRow)3 ExitCode (net.sf.mzmine.util.ExitCode)3 Component (dulab.adap.datamodel.Component)2 Peak (dulab.adap.datamodel.Peak)2 PeakInfo (dulab.adap.datamodel.PeakInfo)2