use of net.sf.mzmine.datamodel.Feature in project mzmine2 by mzmine.
the class MetaboAnalystExportTask method exportPeakList.
private void exportPeakList(PeakList peakList, FileWriter writer) throws IOException {
final RawDataFile[] rawDataFiles = peakList.getRawDataFiles();
// Buffer for writing
StringBuffer line = new StringBuffer();
// Write sample (raw data file) names
line.append("\"Sample\"");
for (RawDataFile file : rawDataFiles) {
// Cancel?
if (isCanceled()) {
return;
}
line.append(fieldSeparator);
final String value = file.getName().replace('"', '\'');
line.append("\"");
line.append(value);
line.append("\"");
}
line.append("\n");
// Write grouping parameter values
line.append("\"");
line.append(groupParameter.getName().replace('"', '\''));
line.append("\"");
for (RawDataFile file : rawDataFiles) {
// Cancel?
if (isCanceled()) {
return;
}
line.append(fieldSeparator);
String value = String.valueOf(project.getParameterValue(groupParameter, file));
value = value.replace('"', '\'');
line.append("\"");
line.append(value);
line.append("\"");
}
line.append("\n");
writer.write(line.toString());
// Write data rows
for (PeakListRow peakListRow : peakList.getRows()) {
// Cancel?
if (isCanceled()) {
return;
}
// Reset the buffer
line.setLength(0);
final String rowName = generateUniquePeakListRowName(peakListRow);
line.append("\"" + rowName + "\"");
for (RawDataFile dataFile : rawDataFiles) {
line.append(fieldSeparator);
Feature peak = peakListRow.getPeak(dataFile);
if (peak != null) {
final double area = peak.getArea();
line.append(String.valueOf(area));
}
}
line.append("\n");
writer.write(line.toString());
processedRows++;
}
}
use of net.sf.mzmine.datamodel.Feature in project mzmine2 by mzmine.
the class MzTabExportTask method run.
public void run() {
setStatus(TaskStatus.PROCESSING);
// Shall export several files?
boolean substitute = fileName.getPath().contains(plNamePattern);
// Total number of rows
for (PeakList peakList : peakLists) {
totalRows += peakList.getNumberOfRows();
}
// Process feature lists
for (PeakList peakList : peakLists) {
File curFile = fileName;
try {
// Filename
if (substitute) {
// Cleanup from illegal filename characters
String cleanPlName = peakList.getName().replaceAll("[^a-zA-Z0-9.-]", "_");
// Substitute
String newFilename = fileName.getPath().replaceAll(Pattern.quote(plNamePattern), cleanPlName);
curFile = new File(newFilename);
}
// Open file
FileWriter writer;
try {
writer = new FileWriter(curFile);
} catch (Exception e) {
setStatus(TaskStatus.ERROR);
setErrorMessage("Could not open file " + curFile + " for writing.");
return;
}
// Metadata
Metadata mtd = new Metadata();
mtd.setMZTabMode(MZTabDescription.Mode.Summary);
mtd.setMZTabType(MZTabDescription.Type.Quantification);
mtd.setDescription(peakList.getName());
mtd.addSoftwareParam(1, new CVParam("MS", "MS:1002342", "MZmine", MZmineCore.getMZmineVersion()));
mtd.setSmallMoleculeQuantificationUnit(new CVParam("PRIDE", "PRIDE:0000330", "Arbitrary quantification unit", null));
mtd.addSmallMoleculeSearchEngineScoreParam(1, new CVParam("MS", "MS:1001153", "search engine specific score", null));
mtd.addFixedModParam(1, new CVParam("MS", "MS:1002453", "No fixed modifications searched", null));
mtd.addVariableModParam(1, new CVParam("MS", "MS:1002454", "No variable modifications searched", null));
// Create stable columns
MZTabColumnFactory factory = MZTabColumnFactory.getInstance(Section.Small_Molecule);
factory.addDefaultStableColumns();
// Add optional columns which have stable order
factory.addURIOptionalColumn();
factory.addBestSearchEngineScoreOptionalColumn(SmallMoleculeColumn.BEST_SEARCH_ENGINE_SCORE, 1);
final RawDataFile[] rawDataFiles = peakList.getRawDataFiles();
int fileCounter = 0;
for (RawDataFile file : rawDataFiles) {
fileCounter++;
/**
* TO DO: Add path to original imported raw file to MZmine and write it out here instead
*/
// MS run location
MsRun msRun = new MsRun(fileCounter);
msRun.setLocation(new URL("file:///" + file.getName()));
mtd.addMsRun(msRun);
mtd.addAssayMsRun(fileCounter, msRun);
// Add samples to study variable assay
for (UserParameter<?, ?> p : project.getParameters()) {
Assay assay = mtd.getAssayMap().get(fileCounter);
for (StudyVariable studyVariable : mtd.getStudyVariableMap().values()) {
if (studyVariable.getDescription().equals(String.valueOf(p) + ": " + String.valueOf(project.getParameterValue(p, file)))) {
mtd.addStudyVariableAssay(studyVariable.getId(), assay);
}
}
}
// Additional columns
factory.addAbundanceOptionalColumn(new Assay(fileCounter));
factory.addOptionalColumn(new Assay(fileCounter), "peak_mz", String.class);
factory.addOptionalColumn(new Assay(fileCounter), "peak_rt", String.class);
factory.addOptionalColumn(new Assay(fileCounter), "peak_height", String.class);
}
// Variable descriptions
int parameterCounter = 0;
for (UserParameter<?, ?> p : project.getParameters()) {
for (Object e : ((ComboParameter<?>) p).getChoices()) {
parameterCounter++;
mtd.addStudyVariableDescription(parameterCounter, String.valueOf(p) + ": " + String.valueOf(e));
StudyVariable studyVariable = new StudyVariable(parameterCounter);
factory.addAbundanceOptionalColumn(studyVariable);
}
}
// Write to file
BufferedWriter out = new BufferedWriter(writer);
out.write(mtd.toString());
out.write(newLine);
out.write(factory.toString());
out.write(newLine);
// Write data rows
for (PeakListRow peakListRow : peakList.getRows()) {
// Cancel?
if (isCanceled()) {
return;
}
PeakIdentity peakIdentity = peakListRow.getPreferredPeakIdentity();
if (exportall || peakIdentity != null) {
SmallMolecule sm = new SmallMolecule(factory, mtd);
if (peakIdentity != null) {
// Identity information
String identifier = escapeString(peakIdentity.getPropertyValue("ID"));
String database = peakIdentity.getPropertyValue("Identification method");
String formula = peakIdentity.getPropertyValue("Molecular formula");
String description = escapeString(peakIdentity.getPropertyValue("Name"));
String url = peakIdentity.getPropertyValue("URL");
if (identifier != null) {
sm.setIdentifier(identifier);
}
if (database != null) {
sm.setDatabase(database);
}
if (formula != null) {
sm.setChemicalFormula(formula);
}
if (description != null) {
sm.setDescription(description);
}
if (url != null) {
sm.setURI(url);
}
}
Double rowMZ = peakListRow.getAverageMZ();
int rowCharge = peakListRow.getRowCharge();
String rowRT = String.valueOf(peakListRow.getAverageRT());
if (rowMZ != null) {
sm.setExpMassToCharge(rowMZ);
}
if (rowCharge > 0) {
sm.setCharge(rowCharge);
}
if (rowRT != null) {
sm.setRetentionTime(rowRT);
}
int dataFileCount = 0;
for (RawDataFile dataFile : rawDataFiles) {
dataFileCount++;
Feature peak = peakListRow.getPeak(dataFile);
if (peak != null) {
String peakMZ = String.valueOf(peak.getMZ());
String peakRT = String.valueOf(String.valueOf(peak.getRT()));
String peakHeight = String.valueOf(peak.getHeight());
Double peakArea = peak.getArea();
sm.setOptionColumnValue(new Assay(dataFileCount), "peak_mz", peakMZ);
sm.setOptionColumnValue(new Assay(dataFileCount), "peak_rt", peakRT);
sm.setOptionColumnValue(new Assay(dataFileCount), "peak_height", peakHeight);
sm.setAbundanceColumnValue(new Assay(dataFileCount), peakArea);
}
}
out.write(sm.toString());
out.write(newLine);
}
}
out.flush();
out.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
setStatus(TaskStatus.ERROR);
setErrorMessage("Could not export feature list to file " + curFile + ": " + e.getMessage());
return;
}
}
if (getStatus() == TaskStatus.PROCESSING)
setStatus(TaskStatus.FINISHED);
}
use of net.sf.mzmine.datamodel.Feature in project mzmine2 by mzmine.
the class SmoothingTask method run.
@Override
public void run() {
setStatus(TaskStatus.PROCESSING);
try {
// Get filter weights.
final double[] filterWeights = SavitzkyGolayFilter.getNormalizedWeights(filterWidth);
// Create new feature list
newPeakList = new SimplePeakList(origPeakList + " " + suffix, origPeakList.getRawDataFiles());
// Process each row.
for (final PeakListRow row : origPeakList.getRows()) {
if (!isCanceled()) {
// Create a new peak-list row.
final int originalID = row.getID();
final PeakListRow newRow = new SimplePeakListRow(originalID);
// Process each peak.
for (final Feature peak : row.getPeaks()) {
if (!isCanceled()) {
// Copy original peak intensities.
final int[] scanNumbers = peak.getScanNumbers();
final int numScans = scanNumbers.length;
final double[] intensities = new double[numScans];
for (int i = 0; i < numScans; i++) {
final DataPoint dataPoint = peak.getDataPoint(scanNumbers[i]);
intensities[i] = dataPoint == null ? 0.0 : dataPoint.getIntensity();
}
// Smooth peak.
final double[] smoothed = convolve(intensities, filterWeights);
// Measure peak (max, ranges, area etc.)
final RawDataFile dataFile = peak.getDataFile();
final DataPoint[] newDataPoints = new DataPoint[numScans];
double maxIntensity = 0.0;
int maxScanNumber = -1;
DataPoint maxDataPoint = null;
Range<Double> intensityRange = null;
double area = 0.0;
for (int i = 0; i < numScans; i++) {
final int scanNumber = scanNumbers[i];
final DataPoint dataPoint = peak.getDataPoint(scanNumber);
final double intensity = smoothed[i];
if (dataPoint != null && intensity > 0.0) {
// Create a new data point.
final double mz = dataPoint.getMZ();
final double rt = dataFile.getScan(scanNumber).getRetentionTime();
final DataPoint newDataPoint = new SimpleDataPoint(mz, intensity);
newDataPoints[i] = newDataPoint;
// Track maximum intensity data point.
if (intensity > maxIntensity) {
maxIntensity = intensity;
maxScanNumber = scanNumber;
maxDataPoint = newDataPoint;
}
// Update ranges.
if (intensityRange == null) {
intensityRange = Range.singleton(intensity);
} else {
intensityRange = intensityRange.span(Range.singleton(intensity));
}
// Accumulate peak area.
if (i != 0) {
final DataPoint lastDP = newDataPoints[i - 1];
final double lastIntensity = lastDP == null ? 0.0 : lastDP.getIntensity();
final double lastRT = dataFile.getScan(scanNumbers[i - 1]).getRetentionTime();
area += (rt - lastRT) * 60d * (intensity + lastIntensity) / 2.0;
}
}
}
assert maxDataPoint != null;
if (!isCanceled() && maxScanNumber >= 0) {
// Create a new peak.
newRow.addPeak(dataFile, new SimpleFeature(dataFile, maxDataPoint.getMZ(), peak.getRT(), maxIntensity, area, scanNumbers, newDataPoints, peak.getFeatureStatus(), maxScanNumber, peak.getMostIntenseFragmentScanNumber(), peak.getAllMS2FragmentScanNumbers(), peak.getRawDataPointsRTRange(), peak.getRawDataPointsMZRange(), intensityRange));
}
}
}
newPeakList.addRow(newRow);
progress++;
}
}
// Finish up.
if (!isCanceled()) {
// Add new peak-list to the project.
project.addPeakList(newPeakList);
// Add quality parameters to peaks
QualityParameters.calculateQualityParameters(newPeakList);
// Remove the original peak-list if requested.
if (removeOriginal) {
project.removePeakList(origPeakList);
}
// Copy previously applied methods
for (final PeakListAppliedMethod method : origPeakList.getAppliedMethods()) {
newPeakList.addDescriptionOfAppliedTask(method);
}
// Add task description to peak-list.
newPeakList.addDescriptionOfAppliedTask(new SimplePeakListAppliedMethod("Peaks smoothed by Savitzky-Golay filter", parameters));
LOG.finest("Finished peak smoothing: " + progress + " rows processed");
setStatus(TaskStatus.FINISHED);
}
} catch (Throwable t) {
LOG.log(Level.SEVERE, "Smoothing error", t);
setErrorMessage(t.getMessage());
setStatus(TaskStatus.ERROR);
}
}
use of net.sf.mzmine.datamodel.Feature in project mzmine2 by mzmine.
the class PeakPreviewComboRenderer method getListCellRendererComponent.
public Component getListCellRendererComponent(JList<? extends PeakListRow> combo, PeakListRow value, int index, boolean isSelected, boolean cellHasFocus) {
PeakListRow row = (PeakListRow) value;
if (row == null)
return new JPanel();
Feature peak = row.getPeaks()[0];
String labelText = "#" + row.getID() + " " + MZmineCore.getConfiguration().getMZFormat().format(row.getAverageMZ()) + " m/z ";
JLabel textComponent = new JLabel(labelText);
textComponent.setFont(combo.getFont());
PeakXICComponent shapeComponent = new PeakXICComponent(peak);
shapeComponent.setBorder(null);
JPanel panel = new JPanel(new BorderLayout());
panel.setOpaque(true);
if (isSelected) {
panel.setBackground(combo.getSelectionBackground());
panel.setForeground(combo.getSelectionForeground());
} else {
panel.setBackground(combo.getBackground());
panel.setForeground(combo.getForeground());
}
panel.setEnabled(combo.isEnabled());
Border border = null;
if (cellHasFocus) {
if (isSelected) {
border = UIManager.getBorder("List.focusSelectedCellHighlightBorder");
}
if (border == null) {
border = UIManager.getBorder("List.focusCellHighlightBorder");
}
} else {
border = noFocusBorder;
}
panel.setBorder(border);
panel.add(textComponent, BorderLayout.WEST);
panel.add(shapeComponent, BorderLayout.CENTER);
return panel;
}
use of net.sf.mzmine.datamodel.Feature in project mzmine2 by mzmine.
the class PeakResolverSetupDialog method parametersChanged.
@Override
public void parametersChanged() {
if (preview != null && preview.isSelected()) {
final PeakListRow previewRow = (PeakListRow) comboPeak.getSelectedItem();
if (previewRow != null) {
LOG.finest("Loading new preview peak " + previewRow);
ticPlot.removeAllTICDataSets();
ticPlot.addTICDataset(new ChromatogramTICDataSet(previewRow.getPeaks()[0]));
// Auto-range to axes.
ticPlot.getXYPlot().getDomainAxis().setAutoRange(true);
ticPlot.getXYPlot().getDomainAxis().setAutoTickUnitSelection(true);
ticPlot.getXYPlot().getRangeAxis().setAutoRange(true);
ticPlot.getXYPlot().getRangeAxis().setAutoTickUnitSelection(true);
updateParameterSetFromComponents();
// If there is some illegal value, do not load the preview but
// just exit.
ArrayList<String> errors = new ArrayList<String>();
if (!parameterSet.checkParameterValues(errors)) {
LOG.fine("Illegal parameter value: " + errors);
return;
}
// Load the intensities and RTs into array.
final Feature previewPeak = previewRow.getPeaks()[0];
// Resolve peaks.
Feature[] resolvedPeaks = {};
RSessionWrapper rSession;
try {
if (peakResolver.getRequiresR()) {
// Check R availability, by trying to open the
// connection.
String[] reqPackages = peakResolver.getRequiredRPackages();
String[] reqPackagesVersions = peakResolver.getRequiredRPackagesVersions();
String callerFeatureName = peakResolver.getName();
REngineType rEngineType = peakResolver.getREngineType(parameters);
rSession = new RSessionWrapper(rEngineType, callerFeatureName, reqPackages, reqPackagesVersions);
rSession.open();
} else {
rSession = null;
}
CenterFunction mzCenterFunction = new CenterFunction(CenterMeasure.MEDIAN);
// preview doesn't show msms scans
// set it to be default searching range
resolvedPeaks = peakResolver.resolvePeaks(previewPeak, parameters, rSession, mzCenterFunction, 0, 0);
// Turn off R instance.
if (rSession != null)
rSession.close(false);
} catch (RSessionWrapperException e) {
throw new IllegalStateException(e.getMessage());
} catch (Throwable t) {
LOG.log(Level.SEVERE, "Peak deconvolution error", t);
MZmineCore.getDesktop().displayErrorMessage(this, t.toString());
}
// Add resolved peaks to TIC plot.
final int peakCount = Math.min(MAX_PEAKS, resolvedPeaks.length);
for (int i = 0; i < peakCount; i++) {
final XYDataset peakDataSet = new PeakDataSet(resolvedPeaks[i]);
ticPlot.addPeakDataset(peakDataSet);
}
// Check peak count.
if (resolvedPeaks.length > MAX_PEAKS) {
// MZmineCore.getDesktop().displayMessage(this,
// "Too many peaks detected, please adjust parameter values");
MZmineCore.getDesktop().displayMessage(this, "Too many peaks detected. Not all of the peaks might be displayed");
}
}
}
}
Aggregations