use of net.sf.mzmine.datamodel.PeakIdentity in project mzmine2 by mzmine.
the class NistMsSearchTask method readSearchResults.
/**
* Reads the search results file for a given feature list row.
*
* @param row the row.
* @return a list of identities corresponding to the search results, or null if none is found.
* @throws IOException if and i/o problem occurs.
*/
private List<PeakIdentity> readSearchResults(final PeakListRow row) throws IOException {
// Search results.
List<PeakIdentity> hitList = null;
// Read the results file.
final BufferedReader reader = new BufferedReader(new FileReader(new File(nistMsSearchDir, SEARCH_RESULTS_FILE_NAME)));
try {
// Read results.
int lineCount = 1;
String line = reader.readLine();
while (line != null) {
// Match the line.
final Matcher scanMatcher = SEARCH_REGEX.matcher(line);
final Matcher hitMatcher = HIT_REGEX.matcher(line);
// Is this the start of a result block?
if (scanMatcher.matches()) {
// Is the row ID correct?
final int rowID = row.getID();
final int hitID = Integer.parseInt(scanMatcher.group(1));
if (rowID == hitID) {
// Create a new list for the hits.
hitList = new ArrayList<PeakIdentity>(1);
} else {
// Search results are for the wrong peak.
throw new IllegalArgumentException("Search results are for a different peak. Expected peak: " + rowID + " but found: " + hitID);
}
} else if (hitMatcher.matches()) {
if (hitList != null) {
// Do hit match factors exceed thresholds?
final String matchFactor = hitMatcher.group(3);
final String reverseMatchFactor = hitMatcher.group(4);
if (Integer.parseInt(matchFactor) >= minMatchFactor && Integer.parseInt(reverseMatchFactor) >= minReverseMatchFactor) {
// Extract identity from hit information.
final SimplePeakIdentity id = new SimplePeakIdentity(hitMatcher.group(1), hitMatcher.group(2), SEARCH_METHOD, hitMatcher.group(7), null);
id.setPropertyValue(MATCH_FACTOR_PROPERTY, matchFactor);
id.setPropertyValue(REVERSE_MATCH_FACTOR_PROPERTY, reverseMatchFactor);
id.setPropertyValue(CAS_PROPERTY, hitMatcher.group(5));
id.setPropertyValue(MOLECULAR_WEIGHT_PROPERTY, hitMatcher.group(6));
hitList.add(id);
}
} else {
throw new IOException("Didn't find start of results block before listing hits at line " + lineCount);
}
} else {
throw new IOException("Unrecognised results file text at line " + lineCount);
}
// Read the next line.
line = reader.readLine();
lineCount++;
}
} finally {
reader.close();
}
return hitList;
}
use of net.sf.mzmine.datamodel.PeakIdentity in project mzmine2 by mzmine.
the class NistMsSearchTask method writeSpectraFile.
/**
* Writes a search spectrum file for the given row and its neighbours.
*
* @param peakRow the row.
* @param neighbourRows its neighbouring rows.
* @return the file.
* @throws IOException if an i/o problem occurs.
*/
private File writeSpectraFile(final PeakListRow peakRow, final Collection<PeakListRow> neighbourRows) throws IOException {
final File spectraFile = File.createTempFile(SPECTRA_FILE_PREFIX, SPECTRA_FILE_SUFFIX);
spectraFile.deleteOnExit();
final BufferedWriter writer = new BufferedWriter(new FileWriter(spectraFile));
try {
LOG.finest("Writing spectra to file " + spectraFile);
// Write header.
final PeakIdentity identity = peakRow.getPreferredPeakIdentity();
final String name = SPECTRUM_NAME_PREFIX + peakRow.getID() + (identity == null ? "" : " (" + identity + ')') + " of " + peakList.getName();
writer.write("Name: " + name.substring(0, Math.min(SPECTRUM_NAME_MAX_LENGTH, name.length())));
writer.newLine();
writer.write("Num Peaks: " + neighbourRows.size());
writer.newLine();
for (final PeakListRow row : neighbourRows) {
final Feature peak = row.getBestPeak();
final int charge = peak.getCharge();
final double mass = (peak.getMZ() - ionType.getAddedMass()) * (charge == 0 ? 1.0 : (double) charge);
writer.write(mass + "\t" + peak.getHeight());
writer.newLine();
}
} finally {
// Close the open file.
writer.close();
}
return spectraFile;
}
use of net.sf.mzmine.datamodel.PeakIdentity in project mzmine2 by mzmine.
the class NistMsSearchTask method nistSearch.
/**
* Run the NIST search.
*
* @throws IOException if there are i/o problems.
*/
private void nistSearch() throws IOException {
// Waiting to get the SEMAPHORE: only one instance of NIST MS Search can
// run at a time.
setStatus(TaskStatus.WAITING);
synchronized (SEMAPHORE) {
File locatorFile2 = null;
try {
if (!isCanceled()) {
setStatus(TaskStatus.PROCESSING);
// Configure locator files.
final File locatorFile1 = new File(nistMsSearchDir, PRIMARY_LOCATOR_FILE_NAME);
locatorFile2 = getSecondLocatorFile(locatorFile1);
if (locatorFile2 == null) {
throw new IOException("Primary locator file " + locatorFile1 + " doesn't contain the name of a valid file.");
}
// Is MS Search already running?
if (locatorFile2.exists()) {
throw new IllegalStateException("NIST MS Search appears to be busy - please wait until it finishes its current task and then try again. Alternatively, try manually deleting the file " + locatorFile2);
}
}
// Single or multiple row search?
final PeakListRow[] peakListRows;
final Map<PeakListRow, Set<PeakListRow>> rowHoods;
if (peakListRow == null) {
peakListRows = peakList.getRows();
rowHoods = groupPeakRows();
} else {
peakListRows = new PeakListRow[] { peakListRow };
rowHoods = new HashMap<PeakListRow, Set<PeakListRow>>(1);
rowHoods.put(peakListRow, findPeakRowGroup());
}
// Reduce neighbourhoods to maximum number of peaks.
trimNeighbours(rowHoods);
// Store search results for each neighbourhood - to avoid repeat
// searches.
final int numRows = peakListRows.length;
final Map<Set<PeakListRow>, List<PeakIdentity>> rowIdentities = new HashMap<Set<PeakListRow>, List<PeakIdentity>>(numRows);
// Search command string.
final String command = nistMsSearchExe.getAbsolutePath() + ' ' + COMMAND_LINE_ARGS;
// Perform searches for each feature list row..
progress = 0;
progressMax = numRows;
for (final PeakListRow row : peakListRows) {
// Get the row's neighbours.
final Set<PeakListRow> neighbours = rowHoods.get(row);
// Has this neighbourhood's search been run already?
if (!rowIdentities.containsKey(neighbours)) {
if (!isCanceled()) {
// Write spectra file.
final File spectraFile = writeSpectraFile(row, neighbours);
// Write locator file.
writeSecondaryLocatorFile(locatorFile2, spectraFile);
// Run the search.
runNistMsSearch(command);
// Read the search results file and store the
// results.
rowIdentities.put(neighbours, readSearchResults(row));
}
}
// Get the search results.
final List<PeakIdentity> identities = rowIdentities.get(neighbours);
if (identities != null) {
// Add (copy of) identities to peak row.
int maxMatchFactor = -1;
for (final PeakIdentity identity : identities) {
// Copy the identity.
final PeakIdentity id = new SimplePeakIdentity((Hashtable<String, String>) identity.getAllProperties());
// Best match factor?
final boolean isPreferred;
final int matchFactor = Integer.parseInt(id.getPropertyValue(MATCH_FACTOR_PROPERTY));
if (matchFactor > maxMatchFactor) {
maxMatchFactor = matchFactor;
isPreferred = true;
} else {
isPreferred = false;
}
// Add peak identity.
row.addPeakIdentity(id, isPreferred);
}
// Notify the GUI about the change in the project
MZmineCore.getProjectManager().getCurrentProject().notifyObjectChanged(row, false);
}
progress++;
}
} finally {
// Clean up.
if (locatorFile2 != null) {
locatorFile2.delete();
}
}
}
}
use of net.sf.mzmine.datamodel.PeakIdentity in project mzmine2 by mzmine.
the class PeakListTablePopupMenu method actionPerformed.
@Override
public void actionPerformed(final ActionEvent e) {
final Object src = e.getSource();
if (deleteRowsItem.equals(src)) {
final int[] rowsToDelete = table.getSelectedRows();
final int[] unsortedIndexes = new int[rowsToDelete.length];
for (int i = rowsToDelete.length - 1; i >= 0; i--) {
unsortedIndexes[i] = table.convertRowIndexToModel(rowsToDelete[i]);
}
// sort row indexes and start removing from the last
Arrays.sort(unsortedIndexes);
// delete the rows starting from last
for (int i = unsortedIndexes.length - 1; i >= 0; i--) {
peakList.removeRow(unsortedIndexes[i]);
}
// Notify the GUI that peaklist contents have changed
updateTableGUI();
}
if (plotRowsItem.equals(src)) {
final int[] selectedTableRows = table.getSelectedRows();
final PeakListRow[] selectedRows = new PeakListRow[selectedTableRows.length];
for (int i = 0; i < selectedTableRows.length; i++) {
selectedRows[i] = getPeakListRow(table.convertRowIndexToModel(selectedTableRows[i]));
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
IntensityPlotModule.showIntensityPlot(MZmineCore.getProjectManager().getCurrentProject(), peakList, selectedRows);
}
});
}
if (showXICItem.equals(src) && allClickedPeakListRows.length != 0) {
// Map peaks to their identity labels.
final Map<Feature, String> labelsMap = new HashMap<Feature, String>(allClickedPeakListRows.length);
final RawDataFile selectedDataFile = clickedDataFile == null ? allClickedPeakListRows[0].getBestPeak().getDataFile() : clickedDataFile;
Range<Double> mzRange = null;
final List<Feature> selectedPeaks = new ArrayList<Feature>(allClickedPeakListRows.length);
for (final PeakListRow row : allClickedPeakListRows) {
for (final Feature peak : row.getPeaks()) {
if (mzRange == null) {
mzRange = peak.getRawDataPointsMZRange();
double upper = mzRange.upperEndpoint();
double lower = mzRange.lowerEndpoint();
if ((upper - lower) < 0.000001) {
// Workaround to make ultra narrow mzRanges (e.g. from imported mzTab peaklist),
// a more reasonable default for a HRAM instrument (~5ppm)
double fiveppm = (upper * 5E-6);
mzRange = Range.closed(lower - fiveppm, upper + fiveppm);
}
} else {
mzRange = mzRange.span(peak.getRawDataPointsMZRange());
}
}
final Feature filePeak = row.getPeak(selectedDataFile);
if (filePeak != null) {
selectedPeaks.add(filePeak);
// Label the peak with the row's preferred identity.
final PeakIdentity identity = row.getPreferredPeakIdentity();
if (identity != null) {
labelsMap.put(filePeak, identity.getName());
}
}
}
ScanSelection scanSelection = new ScanSelection(selectedDataFile.getDataRTRange(1), 1);
TICVisualizerModule.showNewTICVisualizerWindow(new RawDataFile[] { selectedDataFile }, selectedPeaks.toArray(new Feature[selectedPeaks.size()]), labelsMap, scanSelection, TICPlotType.BASEPEAK, mzRange);
}
if (showXICSetupItem.equals(src) && allClickedPeakListRows.length != 0) {
// Map peaks to their identity labels.
final Map<Feature, String> labelsMap = new HashMap<Feature, String>(allClickedPeakListRows.length);
final RawDataFile[] selectedDataFiles = clickedDataFile == null ? peakList.getRawDataFiles() : new RawDataFile[] { clickedDataFile };
Range<Double> mzRange = null;
final ArrayList<Feature> allClickedPeaks = new ArrayList<Feature>(allClickedPeakListRows.length);
final ArrayList<Feature> selectedClickedPeaks = new ArrayList<Feature>(allClickedPeakListRows.length);
for (final PeakListRow row : allClickedPeakListRows) {
// Label the peak with the row's preferred identity.
final PeakIdentity identity = row.getPreferredPeakIdentity();
for (final Feature peak : row.getPeaks()) {
allClickedPeaks.add(peak);
if (peak.getDataFile() == clickedDataFile) {
selectedClickedPeaks.add(peak);
}
if (mzRange == null) {
mzRange = peak.getRawDataPointsMZRange();
} else {
mzRange = mzRange.span(peak.getRawDataPointsMZRange());
}
if (identity != null) {
labelsMap.put(peak, identity.getName());
}
}
}
ScanSelection scanSelection = new ScanSelection(selectedDataFiles[0].getDataRTRange(1), 1);
TICVisualizerModule.setupNewTICVisualizer(MZmineCore.getProjectManager().getCurrentProject().getDataFiles(), selectedDataFiles, allClickedPeaks.toArray(new Feature[allClickedPeaks.size()]), selectedClickedPeaks.toArray(new Feature[selectedClickedPeaks.size()]), labelsMap, scanSelection, mzRange);
}
if (show2DItem.equals(src)) {
final Feature showPeak = getSelectedPeak();
if (showPeak != null) {
TwoDVisualizerModule.show2DVisualizerSetupDialog(showPeak.getDataFile(), getPeakMZRange(showPeak), getPeakRTRange(showPeak));
}
}
if (show3DItem.equals(src)) {
final Feature showPeak = getSelectedPeak();
if (showPeak != null) {
Fx3DVisualizerModule.setupNew3DVisualizer(showPeak.getDataFile(), getPeakMZRange(showPeak), getPeakRTRange(showPeak), showPeak);
}
}
if (manuallyDefineItem.equals(src)) {
// ManualPeakPickerModule.runManualDetection(clickedDataFile, clickedPeakListRow, peakList,
// table);
XICManualPickerModule.runManualDetection(clickedDataFile, clickedPeakListRow, peakList, table);
}
if (showSpectrumItem.equals(src)) {
final Feature showPeak = getSelectedPeak();
if (showPeak != null) {
SpectraVisualizerModule.showNewSpectrumWindow(showPeak.getDataFile(), showPeak.getRepresentativeScanNumber(), showPeak);
}
}
if (openCompoundIdUrl.equals(src)) {
if (clickedPeakListRow != null && clickedPeakListRow.getPreferredPeakIdentity() != null) {
String url = clickedPeakListRow.getPreferredPeakIdentity().getPropertyValue(PeakIdentity.PROPERTY_URL);
if (url != null && !url.isEmpty() && Desktop.isDesktopSupported()) {
try {
Desktop.getDesktop().browse(new URI(url));
} catch (IOException | URISyntaxException e1) {
}
}
}
}
if (showMSMSItem.equals(src)) {
if (allClickedPeakListRows != null && allClickedPeakListRows.length > 1) {
// show multi msms window of multiple rows
MultiMSMSWindow multi = new MultiMSMSWindow();
multi.setData(allClickedPeakListRows, peakList.getRawDataFiles(), clickedDataFile, true, SortingProperty.MZ, SortingDirection.Ascending);
multi.setVisible(true);
} else {
Feature showPeak = getSelectedPeakForMSMS();
if (showPeak != null) {
final int scanNumber = showPeak.getMostIntenseFragmentScanNumber();
if (scanNumber > 0) {
SpectraVisualizerModule.showNewSpectrumWindow(showPeak.getDataFile(), scanNumber);
} else {
MZmineCore.getDesktop().displayMessage(window, "There is no fragment for " + MZmineCore.getConfiguration().getMZFormat().format(showPeak.getMZ()) + " m/z in the current raw data.");
}
}
}
}
// mirror of the two best fragment scans
if (showMSMSMirrorItem.equals(src)) {
if (allClickedPeakListRows != null && allClickedPeakListRows.length == 2) {
PeakListRow a = allClickedPeakListRows[0];
PeakListRow b = allClickedPeakListRows[1];
Scan scan = a.getBestFragmentation();
Scan mirror = b.getBestFragmentation();
if (scan != null && mirror != null) {
// show mirror msms window of two rows
MirrorScanWindow mirrorWindow = new MirrorScanWindow();
mirrorWindow.setScans(scan, mirror);
mirrorWindow.setVisible(true);
}
}
}
// show spectral db matches
if (showSpectralDBResults.equals(src)) {
List<SpectralDBPeakIdentity> spectralID = Arrays.stream(clickedPeakListRow.getPeakIdentities()).filter(pi -> pi instanceof SpectralDBPeakIdentity).map(pi -> ((SpectralDBPeakIdentity) pi)).collect(Collectors.toList());
if (!spectralID.isEmpty()) {
SpectraIdentificationResultsWindow window = new SpectraIdentificationResultsWindow();
window.addMatches(spectralID);
window.setTitle("Matched " + spectralID.size() + " compounds for feature list row" + clickedPeakListRow.getID());
window.setVisible(true);
}
}
if (showAllMSMSItem.equals(src)) {
final Feature showPeak = getSelectedPeakForMSMS();
RawDataFile raw = clickedPeakListRow.getBestFragmentation().getDataFile();
if (showPeak != null && showPeak.getMostIntenseFragmentScanNumber() != 0)
raw = showPeak.getDataFile();
if (clickedPeakListRow.getBestFragmentation() != null) {
MultiSpectraVisualizerWindow multiSpectraWindow = new MultiSpectraVisualizerWindow(clickedPeakListRow, raw);
multiSpectraWindow.setVisible(true);
} else {
MZmineCore.getDesktop().displayMessage(window, "There is no fragment for " + MZmineCore.getConfiguration().getMZFormat().format(showPeak.getMZ()) + " m/z in the current raw data.");
}
}
if (showIsotopePatternItem.equals(src)) {
final Feature showPeak = getSelectedPeak();
if (showPeak != null && showPeak.getIsotopePattern() != null) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
SpectraVisualizerModule.showNewSpectrumWindow(showPeak.getDataFile(), showPeak.getRepresentativeScanNumber(), showPeak.getIsotopePattern());
}
});
}
}
if (formulaItem != null && formulaItem.equals(src)) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
FormulaPredictionModule.showSingleRowIdentificationDialog(clickedPeakListRow);
}
});
}
// peak.
if (siriusItem != null && siriusItem.equals(src)) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
SiriusProcessingModule.showSingleRowIdentificationDialog(clickedPeakListRow);
}
});
}
if (onlineDbSearchItem != null && onlineDbSearchItem.equals(src)) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
OnlineDBSearchModule.showSingleRowIdentificationDialog(clickedPeakListRow);
}
});
}
if (spectralDbSearchItem != null && spectralDbSearchItem.equals(src)) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
LocalSpectralDBSearchModule.showSelectedRowsIdentificationDialog(allClickedPeakListRows, table);
}
});
}
if (nistSearchItem != null && nistSearchItem.equals(src)) {
NistMsSearchModule.singleRowSearch(peakList, clickedPeakListRow);
}
if (addNewRowItem.equals(src)) {
// find maximum ID and add 1
int newID = 1;
for (final PeakListRow row : peakList.getRows()) {
if (row.getID() >= newID) {
newID = row.getID() + 1;
}
}
// create a new row
final PeakListRow newRow = new SimplePeakListRow(newID);
ManualPeakPickerModule.runManualDetection(peakList.getRawDataFiles(), newRow, peakList, table);
}
if (showPeakRowSummaryItem.equals(src)) {
PeakSummaryVisualizerModule.showNewPeakSummaryWindow(clickedPeakListRow);
}
if (exportIsotopesItem.equals(src)) {
IsotopePatternExportModule.exportIsotopePattern(clickedPeakListRow);
}
if (exportToSirius.equals(src)) {
// export all selected rows
SiriusExportModule.exportSingleRows(allClickedPeakListRows);
}
if (exportMSMSLibrary.equals(src)) {
// open window with all selected rows
MSMSLibrarySubmissionWindow libraryWindow = new MSMSLibrarySubmissionWindow();
libraryWindow.setData(allClickedPeakListRows, SortingProperty.MZ, SortingDirection.Ascending, true);
libraryWindow.setVisible(true);
}
if (exportMS1Library.equals(src)) {
// open window with all selected rows
MSMSLibrarySubmissionWindow libraryWindow = new MSMSLibrarySubmissionWindow();
libraryWindow.setData(allClickedPeakListRows, SortingProperty.MZ, SortingDirection.Ascending, false);
libraryWindow.setVisible(true);
}
if (exportMSMSItem.equals(src)) {
MSMSExportModule.exportMSMS(clickedPeakListRow);
}
if (clearIdsItem.equals(src)) {
// Delete identities of selected rows.
for (final PeakListRow row : allClickedPeakListRows) {
// Selected row index.
for (final PeakIdentity id : row.getPeakIdentities()) {
// Remove id.
row.removePeakIdentity(id);
}
}
// Update table GUI.
updateTableGUI();
}
if (copyIdsItem.equals(src) && allClickedPeakListRows.length > 0) {
final PeakIdentity id = allClickedPeakListRows[0].getPreferredPeakIdentity();
if (id != null) {
copiedId = (PeakIdentity) id.clone();
}
}
if (pasteIdsItem.equals(src) && copiedId != null) {
// Paste identity into selected rows.
for (final PeakListRow row : allClickedPeakListRows) {
row.setPreferredPeakIdentity((PeakIdentity) copiedId.clone());
}
// Update table GUI.
updateTableGUI();
}
}
use of net.sf.mzmine.datamodel.PeakIdentity in project mzmine2 by mzmine.
the class PeakListTable method getCellEditor.
public TableCellEditor getCellEditor(int row, int column) {
CommonColumnType commonColumn = pkTableModel.getCommonColumn(column);
if (commonColumn == CommonColumnType.IDENTITY) {
row = this.convertRowIndexToModel(row);
peakListRow = peakList.getRow(row);
PeakIdentity[] identities = peakListRow.getPeakIdentities();
PeakIdentity preferredIdentity = peakListRow.getPreferredPeakIdentity();
JComboBox<Object> combo;
if ((identities != null) && (identities.length > 0)) {
combo = new JComboBox<Object>(identities);
combo.addItem("-------------------------");
combo.addItem(REMOVE_IDENTITY);
combo.addItem(EDIT_IDENTITY);
} else {
combo = new JComboBox<Object>();
}
combo.setFont(comboFont);
combo.addItem(NEW_IDENTITY);
if (preferredIdentity != null) {
combo.setSelectedItem(preferredIdentity);
}
combo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox<?> combo = (JComboBox<?>) e.getSource();
Object item = combo.getSelectedItem();
if (item != null) {
if (item.toString() == NEW_IDENTITY) {
PeakIdentitySetupDialog dialog = new PeakIdentitySetupDialog(window, peakListRow);
dialog.setVisible(true);
return;
}
if (item.toString() == EDIT_IDENTITY) {
PeakIdentitySetupDialog dialog = new PeakIdentitySetupDialog(window, peakListRow, peakListRow.getPreferredPeakIdentity());
dialog.setVisible(true);
return;
}
if (item.toString() == REMOVE_IDENTITY) {
PeakIdentity identity = peakListRow.getPreferredPeakIdentity();
if (identity != null) {
peakListRow.removePeakIdentity(identity);
DefaultComboBoxModel<?> comboModel = (DefaultComboBoxModel<?>) combo.getModel();
comboModel.removeElement(identity);
}
return;
}
if (item instanceof PeakIdentity) {
peakListRow.setPreferredPeakIdentity((PeakIdentity) item);
return;
}
}
}
});
// Keep the reference to the editor
currentEditor = new DefaultCellEditor(combo);
return currentEditor;
}
return super.getCellEditor(row, column);
}
Aggregations