From b1c99f7ff9c05dd3fa41084211f4fc385f952895 Mon Sep 17 00:00:00 2001 From: Genet Abay Date: Tue, 10 Apr 2018 13:54:19 +0200 Subject: [PATCH] spectrum title removed from key and mzml file added --- .../coss/Controller/ConfigSpecReaders.java | 153 +++++++++ .../coss/Controller/MainFrameController.java | 274 ++++++++------- .../compomics/coss/Controller/Validation.java | 14 +- .../com/compomics/coss/Model/ConfigData.java | 2 - .../java/com/compomics/coss/View/MainGUI.java | 187 ++++++----- .../compomics/coss/View/SearchCommandPnl.java | 16 +- .../coss/View/ValidationCommandPanel.java | 34 +- .../coss/View/ValidationHistogramPanel.java | 186 ++++++----- .../java/com/compomics/matching/Cascade.java | 308 ----------------- .../java/com/compomics/matching/Matching.java | 2 +- .../com/compomics/matching/UseMsRoben.java | 311 +++++++++++------- src/main/resources/config.properties | 4 +- 12 files changed, 738 insertions(+), 753 deletions(-) create mode 100644 src/main/java/com/compomics/coss/Controller/ConfigSpecReaders.java delete mode 100644 src/main/java/com/compomics/matching/Cascade.java diff --git a/src/main/java/com/compomics/coss/Controller/ConfigSpecReaders.java b/src/main/java/com/compomics/coss/Controller/ConfigSpecReaders.java new file mode 100644 index 0000000..b47cd44 --- /dev/null +++ b/src/main/java/com/compomics/coss/Controller/ConfigSpecReaders.java @@ -0,0 +1,153 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.compomics.coss.Controller; + +import com.compomics.ms2io.IndexKey; +import com.compomics.ms2io.Indexer; +import java.io.File; +import java.io.IOException; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import com.compomics.coss.Model.*; +import com.compomics.ms2io.MgfReader; +import com.compomics.ms2io.MspReader; +import com.compomics.ms2io.SpectraReader; +import java.util.concurrent.ExecutionException; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + *This class generate index file for both experimental and library spectra and + * configures spectrum reader object to read them + * @author Genet + */ +public class ConfigSpecReaders { + + private final File fileExperimnt; + private final File fileLibrary; + private boolean isCanceled; + + public ConfigSpecReaders(File expFile, File libFile) { + this.fileExperimnt = expFile; + this.fileLibrary = libFile; + isCanceled=false; + } + + public void cancelConfig(boolean cncl){ + isCanceled=cncl; + + } + + public boolean readFile(ConfigData cfData) { + + try { + ExecutorService executors = Executors.newFixedThreadPool(2); + Future[] fut = new Future[2]; + + //Generate Index for experimental spectrum + InputHandler ipHandler = new InputHandler(this.fileExperimnt, "spectrum"); + fut[0] = executors.submit(ipHandler); + + + //generating index for library spectrum if it doesn't exist and read if it does. + // String libname = this.fileLibrary.getName().substring(0, this.fileLibrary.getName().lastIndexOf(".")); + // File lib_indxfile = new File(this.fileLibrary.getParent(), libname + ".idx"); + // if(!lib_indxfile.exists()){ + ipHandler = new InputHandler(this.fileLibrary, "spectrum" ); + +// } +// +// else{ +// ipHandler = new InputHandler(this.fileLibrary, "index" ); +// +// } + fut[1] = executors.submit(ipHandler); + executors.shutdown(); + + cfData.setExpSpectraIndex((List) fut[0].get()); + cfData.setSpectralLibraryIndex((List) fut[1].get()); + + //sort library spectrum + Collections.sort(cfData.getSpectraLibraryIndex()); + + + + + //reader for experimental spectrum file + if (cfData.getExperimentalSpecFile().getName().endsWith("mgf")) { + SpectraReader rd = new MgfReader(cfData.getExperimentalSpecFile(), cfData.getExpSpectraIndex()); + cfData.setExpSpecReader(rd); + + } else if (cfData.getExperimentalSpecFile().getName().endsWith("msp")) { + SpectraReader rd = new MspReader(cfData.getExperimentalSpecFile(), cfData.getExpSpectraIndex()); + cfData.setExpSpecReader(rd); + + } + + //reader for spectral library file + if (cfData.getSpecLibraryFile().getName().endsWith("mgf")) { + SpectraReader rd = new MgfReader(cfData.getSpecLibraryFile(), cfData.getSpectraLibraryIndex()); + cfData.setLibSpecReader(rd); + + } else if (cfData.getSpecLibraryFile().getName().endsWith("msp")) { + SpectraReader rd = new MspReader(cfData.getSpecLibraryFile(), cfData.getSpectraLibraryIndex()); + cfData.setLibSpecReader(rd); + } + + + + + + + } catch (InterruptedException ex) { + Logger.getLogger(ConfigSpecReaders.class.getName()).log(Level.SEVERE, null, ex); + } catch (ExecutionException ex) { + Logger.getLogger(ConfigSpecReaders.class.getName()).log(Level.SEVERE, null, ex); + } + + return true; + } + + private class InputHandler implements Callable> { + + private final File file; + private final String aboutFile; + + public InputHandler(File file, String aboutFile) { + this.file = file; + this.aboutFile=aboutFile; + } + + + + @Override + public List call() throws Exception { + List indxList = null; + + try { + if (this.aboutFile.equals("spectrum")) { + Indexer giExp = new Indexer(this.file); + indxList = giExp.generate(); + } + else if(this.aboutFile.equals("index")){ + Indexer indxer = new Indexer(); + indxList = indxer.readFromFile(this.file); + } + + } catch (IOException e) { + e.printStackTrace(); + } + + return indxList; + } + + } + +} diff --git a/src/main/java/com/compomics/coss/Controller/MainFrameController.java b/src/main/java/com/compomics/coss/Controller/MainFrameController.java index 467cf5d..db28f28 100644 --- a/src/main/java/com/compomics/coss/Controller/MainFrameController.java +++ b/src/main/java/com/compomics/coss/Controller/MainFrameController.java @@ -6,7 +6,6 @@ import java.util.List; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; -import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTextArea; @@ -17,7 +16,8 @@ import org.apache.log4j.Priority; import com.compomics.coss.Model.ConfigHolder; import com.compomics.coss.View.*; -import com.compomics.matching.Cascade; +//import com.compomics.matching.Cascade; +import javax.swing.JFileChooser; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; @@ -25,17 +25,13 @@ import javax.swing.SwingUtilities; import com.compomics.matching.Matching; import com.compomics.matching.UseMsRoben; -import java.awt.Color; import java.awt.Toolkit; import javax.swing.DefaultComboBoxModel; import javax.swing.SpinnerNumberModel; import javax.swing.table.DefaultTableModel; -//import org.jfree.util.Log; import com.compomics.ms2io.*; import java.awt.BorderLayout; import java.util.Collections; -import java.util.Map; -import java.util.TreeMap; /** * Controller class for GUI @@ -52,16 +48,13 @@ public class MainFrameController implements UpdateListener { private MainGUI mainView; private SettingPanel settingsPnl; private ResultPanel resultPnl; - private ValidationHistogramPanel valdHistPnl; private TargetDB_View targetView; - private SearchCommandPnl srchCmdPnl; - private ValidationCommandPanel valdtCmdPnl; // private ConfigHolder config = new ConfigHolder(); Matching matching; - private static List> resultTarget=null; - private static List> resultDecoy=null; - private static List> resultMerged=null; + private static List> resultTarget = null; + private static List> resultDecoy = null; + private static List> resultMerged = null; int cutoff_index; ConfigData configData; public boolean cencelled = false; @@ -75,24 +68,22 @@ public class MainFrameController implements UpdateListener { private int targSpectrumNum, resultNumber; private boolean isValidation; + private boolean isReaderReady; + /** * Initialize objects, variables and components. */ // public void init() { + isReaderReady = false; String libPath = ConfigHolder.getInstance().getString("spectra.library.path"); settingsPnl = new SettingPanel(this, new File(libPath)); resultPnl = new ResultPanel(this); - targetView = new TargetDB_View(this); - - srchCmdPnl=new SearchCommandPnl(this); - valdtCmdPnl=new ValidationCommandPanel(this); - - mainView = new MainGUI(settingsPnl, resultPnl, targetView,this); - mainView.pnlCommands.setLayout(new BorderLayout()); - mainView.pnlCommands.add(srchCmdPnl); + targetView = new TargetDB_View(this); + mainView = new MainGUI(settingsPnl, resultPnl, targetView, this); + mainView.pnlCommands.setLayout(new BorderLayout()); configData = new ConfigData(); // add gui appender LogTextAreaAppender logTextAreaAppender = new LogTextAreaAppender(); @@ -121,8 +112,6 @@ public void init() { //cmbModel = new DefaultComboBoxModel(); //settingsPnl.cboSpectraLibrary.setModel(cmbModel); - srchCmdPnl.prgProgress.setStringPainted(true); - srchCmdPnl.prgProgress.setForeground(Color.BLUE); spectrumDisplay(0); rasterDisplay(); @@ -132,22 +121,6 @@ public void init() { }// - public void cmdViewDisplay(int a){ - if(a==0){ - mainView.pnlCommands.removeAll(); - mainView.pnlCommands.add(srchCmdPnl); - - } - else{ - mainView.pnlCommands.removeAll(); - mainView.pnlCommands.add(valdtCmdPnl, BorderLayout.EAST); - if(valdHistPnl!=null) - mainView.pnlCommands.add(valdHistPnl, BorderLayout.CENTER); - - } - - } - /** * Show the view of this controller. */ @@ -177,7 +150,40 @@ public void stopSearch() { */ public void startSearch() { - //check for input validation and display if one or more infalid value found +// //check for input validation and display if one or more infalid value found +// List validationMessages = validateInput(); +// if (!validationMessages.isEmpty()) { +// StringBuilder message = new StringBuilder(); +// for (String validationMessage : validationMessages) { +// message.append(validationMessage).append(System.lineSeparator()); +// } +// showMessageDialog("Validation errors", message.toString(), JOptionPane.WARNING_MESSAGE); +// } else { + if (this.isReaderReady) { + + this.cencelled = false; + + isValidation = false; + matching = new UseMsRoben(this, configData.getExpSpecReader(), configData.getExpSpectraIndex(), configData.getLibSpecReader(), "target"); + + mainView.setProgressValue(0); + SwingWorkerThread workerThread = new SwingWorkerThread(); + workerThread.execute(); + + } else { + LOG.info("Spectrum reader is not ready"); + } + + try { + + } catch (Exception ex) { + java.util.logging.Logger.getLogger(com.compomics.main.ProjectMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } + + } + + public void configReader() { + List validationMessages = validateInput(); if (!validationMessages.isEmpty()) { StringBuilder message = new StringBuilder(); @@ -186,32 +192,37 @@ public void startSearch() { } showMessageDialog("Validation errors", message.toString(), JOptionPane.WARNING_MESSAGE); } else { + ReadInputData(); - readSpectra(); - this.cencelled = false; this.isBussy = true; + mainView.searchBtnActive(false); - isValidation = false; - matching = new UseMsRoben(this, configData.getExpSpecReader(), configData.getExpSpectraIndex(), configData.getLibSpecReader(), "target"); - srchCmdPnl.prgProgress.setValue(0); - SwingWorkerThread workerThread = new SwingWorkerThread(); - workerThread.execute(); + SwingReadThread readThread = new SwingReadThread(); + readThread.execute(); } - try { + } + + private File readDecoyFile() { + File decoyDB = null; + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setCurrentDirectory(new File("C:/pandyDS/")); + int result = fileChooser.showOpenDialog(mainView); + if (result == JFileChooser.APPROVE_OPTION) { + decoyDB = fileChooser.getSelectedFile(); - } catch (Exception ex) { - java.util.logging.Logger.getLogger(com.compomics.main.ProjectMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } + return decoyDB; } /** * start search against decoy database */ - private void validateResult(File decoydbFile) { + public void validateResult() { + File decoydbFile = readDecoyFile(); SpectraReader rdDecoy = null; List decoyindxList = null; try { @@ -234,7 +245,7 @@ private void validateResult(File decoydbFile) { isValidation = true; matching = new UseMsRoben(this, configData.getExpSpecReader(), configData.getExpSpectraIndex(), rdDecoy, "decoy"); - srchCmdPnl.prgProgress.setValue(0); + mainView.setProgressValue(0); SwingWorkerThread workerThread = new SwingWorkerThread(); workerThread.execute(); @@ -256,81 +267,6 @@ private void ReadInputData() { } - /** - * Initiates spectra reading from the specified directory, draws the target - * spectra and display information of the spectra - */ - private void readSpectra() { - - try { - Map mp = new TreeMap(); - mp.put(1, 1); - mp.put(2, 2); - mp.put(3, 1); - - LOG.info("Reading Data ...."); - srchCmdPnl.btnStartSearch.setEnabled(false); - //Read target and librart spectra - - // List experimentalSpectra; - Indexer giExp = new Indexer(configData.getExperimentalSpecFile()); - List indxList = giExp.generate(); - //Collections.sort(indxList); - configData.setExpSpectraIndex(indxList); - - //Read spectra library - String libname = configData.getSpecLibraryFile().getName().substring(0, configData.getSpecLibraryFile().getName().lastIndexOf(".")); - File lib_indxfile = new File(configData.getSpecLibraryFile().getParent(), libname + ".idx"); - - List indxList2; - if (lib_indxfile.exists()) { - - Indexer indxer = new Indexer(); - indxList2 = indxer.readFromFile(lib_indxfile); - - } else { - - Indexer gi = new Indexer(configData.getSpecLibraryFile()); - indxList2 = gi.generate(); - Collections.sort(indxList2); - gi.saveIndex2File(lib_indxfile); - - } - configData.setSpectralLibraryIndex(indxList2); - - //reader for experimental spectrum file - if (configData.getExperimentalSpecFile().getName().endsWith("mgf")) { - SpectraReader rd = new MgfReader(configData.getExperimentalSpecFile(), configData.getExpSpectraIndex()); - configData.setExpSpecReader(rd); - - } else if (configData.getExperimentalSpecFile().getName().endsWith("msp")) { - SpectraReader rd = new MspReader(configData.getExperimentalSpecFile(), configData.getExpSpectraIndex()); - configData.setExpSpecReader(rd); - - } - - //reader for spectral library file - if (configData.getSpecLibraryFile().getName().endsWith("mgf")) { - SpectraReader rd = new MgfReader(configData.getSpecLibraryFile(), configData.getSpectraLibraryIndex()); - configData.setLibSpecReader(rd); - - } else if (configData.getSpecLibraryFile().getName().endsWith("msp")) { - SpectraReader rd = new MspReader(configData.getSpecLibraryFile(), configData.getSpectraLibraryIndex()); - configData.setLibSpecReader(rd); - } - - //Displaying info and visualization of experimental spectrum - int expSpecSize = configData.getExpSpectraIndex().size(); - spnModel.setMaximum(expSpecSize); - targetView.txtTotalSpec.setText("/" + Integer.toString(expSpecSize)); - updateInputInfo(); - spectrumDisplay(0); - rasterDisplay(); - } catch (Exception ex) { - java.util.logging.Logger.getLogger(MainFrameController.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); - } - } - /** * Read input configData from file and put on GUI */ @@ -565,7 +501,6 @@ public void fillBestmatchTable(int target) { public void fillBestmatchTable() { //ArrayList singleResult = resultTarget.get(target); - int a = 0; Object[][] rows = new Object[10][8]; @@ -573,7 +508,7 @@ public void fillBestmatchTable() { if (!res.isEmpty()) { Long pos = res.get(0).getSpecPosition(); - + rows[a][0] = a + 1; rows[a][1] = "ID" + Integer.toString(a); rows[a][2] = res.get(0).getTitle(); @@ -604,8 +539,8 @@ public void updateprogressbar(double percent) { final double PERCENT = percent; SwingUtilities.invokeLater(() -> { int v = (int) (100 * PERCENT); - srchCmdPnl.prgProgress.setValue(v); - srchCmdPnl.prgProgress.setString(Integer.toString(v) + "%"); + mainView.setProgressValue(v); + mainView.setProgressValue(Integer.toString(v) + "%"); }); } @@ -794,12 +729,15 @@ private class SwingWorkerThread extends SwingWorker { @Override protected Void doInBackground() throws Exception { + isBussy = true; + mainView.searchBtnActive(false); + matching.InpArgs(Integer.toString(configData.getMsRobinOption()), Integer.toString(configData.getIntensityOption()), Double.toString(configData.getfragTol())); if (!isValidation) { - resultTarget = matching.compare(LOG); + resultTarget = matching.dispatcher(LOG); cutoff_index = resultTarget.size() - 1; } else { - resultDecoy = matching.compare(LOG); + resultDecoy = matching.dispatcher(LOG); Validation validation = new Validation(); resultMerged = validation.compareNmerge(resultTarget, resultDecoy); cutoff_index = validation.validate(resultTarget, 0.01); @@ -811,25 +749,30 @@ protected Void doInBackground() throws Exception { @Override protected void done() { + try { if (cencelled) { LOG.info("Process Cancelled."); - srchCmdPnl.prgProgress.setValue(0); - srchCmdPnl.prgProgress.setString(Integer.toString(0) + "%"); + mainView.setProgressValue(0); + mainView.setProgressValue(Integer.toString(0) + "%"); } else { LOG.info("Spectrum Similarity Comparison Completed"); - srchCmdPnl.prgProgress.setValue(100); - srchCmdPnl.prgProgress.setString(Integer.toString(100) + "%"); + mainView.setProgressValue(100); + mainView.setProgressValue(Integer.toString(100) + "%"); - if (resultTarget != null && resultTarget.size() > 0) { + if (resultTarget != null) { //validationPnl=new ValidationHistogramPanel(resultTarget, resultDecoy); fillExpSpectraTable(); fillBestmatchTable(0); displayResult(); + if (resultDecoy != null) { + mainView.setResults(resultTarget, resultDecoy); + + } } else { LOG.info("No comparison result."); @@ -838,7 +781,62 @@ protected void done() { } isBussy = false; - srchCmdPnl.btnStartSearch.setEnabled(true); + mainView.searchBtnActive(true); + get(); + + } catch (InterruptedException | ExecutionException ex) { + LOG.error(ex.getMessage(), ex); + showMessageDialog("Unexpected error", ex.getMessage(), JOptionPane.ERROR_MESSAGE); + } catch (CancellationException ex) { + LOG.info("the spectrum similarity score pipeline run was cancelled"); + } finally { + + } + } + + } + + /** + * swing thread to start the search and it runs on background + */ + private class SwingReadThread extends SwingWorker { + + @Override + protected Void doInBackground() throws Exception { + + // isBussy = true; + mainView.readerBtnActive(false); + mainView.searchBtnActive(false); + + LOG.info("Configuring Spectrum Reader ...."); + ConfigSpecReaders cfReader = new ConfigSpecReaders(configData.getExperimentalSpecFile(), configData.getSpecLibraryFile()); + cfReader.readFile(configData); + return null; + } + + @Override + protected void done() { + + try { + + LOG.info("Spectrum Reader Config Completed"); + if (configData.getExpSpectraIndex() != null && configData.getSpectraLibraryIndex() != null) { + + int expSpecSize = configData.getExpSpectraIndex().size(); + spnModel.setMaximum(expSpecSize); + targetView.txtTotalSpec.setText("/" + Integer.toString(expSpecSize)); + updateInputInfo(); + spectrumDisplay(0); + // rasterDisplay(); + + } else { + LOG.info("Null Spectrum Index"); + } + + isReaderReady=true; + isBussy = false; + mainView.readerBtnActive(true); + mainView.searchBtnActive(true); get(); } catch (InterruptedException | ExecutionException ex) { diff --git a/src/main/java/com/compomics/coss/Controller/Validation.java b/src/main/java/com/compomics/coss/Controller/Validation.java index 6e3276f..f31d282 100644 --- a/src/main/java/com/compomics/coss/Controller/Validation.java +++ b/src/main/java/com/compomics/coss/Controller/Validation.java @@ -29,14 +29,18 @@ public List> compareNmerge(List rTarget : targetResult) { + ArrayList rDecoy = decoyResult.get(c++); - if (rTarget.get(0).compareTo(rDecoy.get(0)) < 0) { + if(!rTarget.isEmpty() && !rDecoy.isEmpty()){ + if (rTarget.get(0).compareTo(rDecoy.get(0)) < 0) { validatedResult.add(rDecoy); - - } - else{ - validatedResult.add(rTarget); + + } + else{ + validatedResult.add(rTarget); + } + } diff --git a/src/main/java/com/compomics/coss/Model/ConfigData.java b/src/main/java/com/compomics/coss/Model/ConfigData.java index 94d329d..dc2698f 100644 --- a/src/main/java/com/compomics/coss/Model/ConfigData.java +++ b/src/main/java/com/compomics/coss/Model/ConfigData.java @@ -26,8 +26,6 @@ public class ConfigData { int intensityOption; int maxPrecursorCharge; - - /** * constructor diff --git a/src/main/java/com/compomics/coss/View/MainGUI.java b/src/main/java/com/compomics/coss/View/MainGUI.java index e3e7ecc..067caf0 100644 --- a/src/main/java/com/compomics/coss/View/MainGUI.java +++ b/src/main/java/com/compomics/coss/View/MainGUI.java @@ -1,8 +1,10 @@ package com.compomics.coss.View; - import com.compomics.coss.Controller.MainFrameController; +import com.compomics.coss.Model.ComparisonResult; import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; @@ -10,6 +12,8 @@ import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; +import java.util.ArrayList; +import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ImageIcon; @@ -30,53 +34,51 @@ import javax.swing.WindowConstants; import javax.swing.event.ChangeEvent; - /** - *Main GUI of the project + * Main GUI of the project + * * @author Genet */ public class MainGUI extends JFrame { - - SettingPanel settings; - ResultPanel result; - MainFrameController control; - TargetDB_View pnlTargView; - - /** - * constructor of the class - * @param settings setting panel to be added on the main GUI - * @param result result panel to be added on the main GUI + SettingPanel settings; + ResultPanel result; + MainFrameController control; + TargetDB_View pnlTargView; + + /** + * constructor of the class + * + * @param settings setting panel to be added on the main GUI + * @param result result panel to be added on the main GUI * @param targetView - * @param controler controller class responsible for coordinating the process - */ + * @param controler controller class responsible for coordinating the + * process + */ public MainGUI(SettingPanel settings, ResultPanel result, TargetDB_View targetView, MainFrameController controler) { super("COSS"); - this.control=controler; - this.settings=settings; - this.result=result; - this.pnlTargView=targetView; + this.control = controler; + this.settings = settings; + this.result = result; + this.pnlTargView = targetView; initComponents(); } - // /** * Initialize components of the GUI */ - @SuppressWarnings("unchecked") private void initComponents() { setName("test view"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - + //icon images ImageIcon iconSetting = new ImageIcon("settingIcon.png"); - + //Initialize components - menuBar = new JMenuBar(); - + JMenu fileMenu = new JMenu("File"); JMenu editMenu = new JMenu("Edit"); JMenu settingMenu = new JMenu("Setting"); @@ -86,7 +88,7 @@ private void initComponents() { fileMenu.setMnemonic(KeyEvent.VK_F); editMenu.setMnemonic(KeyEvent.VK_E); helpMenu.setMnemonic(KeyEvent.VK_F1); - + menuBar.add(fileMenu); menuBar.add(editMenu); menuBar.add(settingMenu); @@ -100,7 +102,7 @@ private void initComponents() { paste = new JMenuItem("Paste", KeyEvent.VK_P); about = new JMenuItem("About", KeyEvent.VK_A); JMenuItem configSystem = new JMenuItem("Configure Library", KeyEvent.VK_L); - + fileMenu.add(open); fileMenu.add(save); fileMenu.add(exit); @@ -108,7 +110,7 @@ private void initComponents() { editMenu.add(paste); helpMenu.add(about); settingMenu.add(configSystem); - + pnlsetting = new JPanel(new FlowLayout(FlowLayout.LEFT)); pnlsetting.setLayout(new BorderLayout()); @@ -118,17 +120,15 @@ private void initComponents() { pnlCommands = new JPanel(new FlowLayout(FlowLayout.LEFT)); pnlCommands.setLayout(new BorderLayout()); - - pnlLog = new JPanel(new FlowLayout(FlowLayout.LEFT)); pnlLog.setLayout(new BorderLayout()); - + txtlog = new JTextArea(); - scrLogArea=new JScrollPane(); + scrLogArea = new JScrollPane(); txtlog.setColumns(20); txtlog.setRows(5); scrLogArea.setViewportView(txtlog); - + //this.setSize(dmnsn); this.setExtendedState(JFrame.MAXIMIZED_BOTH); tab = new JTabbedPane(JTabbedPane.TOP, JTabbedPane.WRAP_TAB_LAYOUT); @@ -137,20 +137,24 @@ private void initComponents() { tab.addTab("Result", new JScrollPane(pnlresult)); //tab.setSize(WIDTH, WIDTH); - - //the upper split panel holding main tabed panels and the info panel - JPanel pnlUpper=new JPanel(); + srchCmdPnl = new SearchCommandPnl(control); + valdtCmdPnl = new ValidationCommandPanel(control); + valdHistPnl=new ValidationHistogramPanel(null, null); + srchCmdPnl.prgProgress.setStringPainted(true); + srchCmdPnl.prgProgress.setForeground(Color.BLUE); + pnlCommands.add(srchCmdPnl); + + //the upper split panel holding main tabed panels and the info panel + JPanel pnlUpper = new JPanel(); pnlUpper.setLayout(new GridLayout(1, 2)); pnlUpper.add(tab); pnlUpper.add(pnlTargView); - - JPanel pnlLower=new JPanel(); + JPanel pnlLower = new JPanel(); pnlLower.setLayout(new GridLayout(1, 2)); pnlLower.add(pnlCommands); pnlLower.add(pnlLog); - - + //SettingPanel settings = new SettingPanel(); pnlsetting.add(settings); @@ -159,7 +163,6 @@ private void initComponents() { pnlLog.add(scrLogArea); - //Control Events //main window listener for window closing setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); @@ -169,13 +172,13 @@ public void windowClosing(final WindowEvent we ) { //System.exit(0); - int selectionOption=JOptionPane.showConfirmDialog(null, + int selectionOption = JOptionPane.showConfirmDialog(null, "Are you sure to close this window?", "Really Closing?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (selectionOption == JOptionPane.YES_OPTION) { - if(control.isBussy){ + if (control.isBussy) { control.stopSearch(); } @@ -185,8 +188,7 @@ public void windowClosing(final WindowEvent we } } ); - - + save.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { try { @@ -199,24 +201,25 @@ public void actionPerformed(ActionEvent ev) { exit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { - int selectionOption=JOptionPane.showConfirmDialog(null, + int selectionOption = JOptionPane.showConfirmDialog(null, "Are you sure to close this window?", "Really Closing?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (selectionOption == JOptionPane.YES_OPTION) { - if(control.isBussy) + if (control.isBussy) { control.stopSearch(); + } System.exit(0); } } }); - configSystem.addActionListener(new ActionListener() { + configSystem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //control.chooseLibraryFile(); - // frmNewLibrary.setVisible(true); + // frmNewLibrary.setVisible(true); } } @@ -226,30 +229,69 @@ public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof JTabbedPane) { JTabbedPane pane = (JTabbedPane) e.getSource(); int ind = pane.getSelectedIndex(); - control.cmdViewDisplay(ind); - - } + if (ind == 0) { + pnlCommands.removeAll(); + pnlCommands.add(srchCmdPnl); + pnlCommands.revalidate(); + pnlCommands.repaint(); + + } else { + pnlCommands.removeAll(); + pnlCommands.add(valdtCmdPnl, BorderLayout.EAST); + //if (valdHistPnl != null) { + pnlCommands.add(valdHistPnl, BorderLayout.CENTER); + // } + + pnlCommands.revalidate(); + pnlCommands.repaint(); + + } + + } }); - - - - setJMenuBar(menuBar); - BorderLayout layout=new BorderLayout(); + BorderLayout layout = new BorderLayout(); getContentPane().setLayout(layout); - add (new JScrollPane(pnlUpper), BorderLayout.CENTER); + add(new JScrollPane(pnlUpper), BorderLayout.CENTER); add(new JScrollPane(pnlLower), BorderLayout.SOUTH); - - - - + pack(); - + } // + public void setResults(List> resT, List> resD) { + valdHistPnl = new ValidationHistogramPanel(resT, resD); + //valdHistPnl.setPreferredSize(new Dimension(300,200)); + valdHistPnl.revalidate(); + valdHistPnl.repaint(); + + } + + public void setProgressValue(int v) { + srchCmdPnl.prgProgress.setValue(v); + } + + public void setProgressValue(String s) { + srchCmdPnl.prgProgress.setString(s); + } + public void searchBtnActive(boolean b) { + srchCmdPnl.btnStartSearch.setEnabled(b); + } + + public void readerBtnActive(boolean b) { + srchCmdPnl.btnConfigReader.setEnabled(b); + } + + + + + private ValidationHistogramPanel valdHistPnl; + private SearchCommandPnl srchCmdPnl; + private ValidationCommandPanel valdtCmdPnl; + private JMenuBar menuBar; private JMenuItem open; private JMenuItem save; @@ -257,27 +299,14 @@ public void actionPerformed(ActionEvent e) { private JMenuItem copy; private JMenuItem paste; private JMenuItem about; - private JTabbedPane tab; + private JTabbedPane tab; public JPanel pnlsetting; public JPanel pnlresult; - + public JPanel pnlCommands; private JPanel pnlLog; - public JTextArea txtlog; private JScrollPane scrLogArea; - - - private void changeControlView(int selectedIndex) { - - - - } - - - - - - + } diff --git a/src/main/java/com/compomics/coss/View/SearchCommandPnl.java b/src/main/java/com/compomics/coss/View/SearchCommandPnl.java index 940d1cd..e28faaa 100644 --- a/src/main/java/com/compomics/coss/View/SearchCommandPnl.java +++ b/src/main/java/com/compomics/coss/View/SearchCommandPnl.java @@ -29,15 +29,28 @@ public SearchCommandPnl(MainFrameController control) { private void init(){ - + btnConfigReader=new JButton("Config Spec. Reader"); btnStartSearch=new JButton("Start Searching"); JButton btnCancel=new JButton("Cancel"); prgProgress=new JProgressBar(0, 100); JPanel innerControlPanel=new JPanel(new FlowLayout()); + innerControlPanel.add(btnConfigReader); innerControlPanel.add(btnStartSearch); innerControlPanel.add(btnCancel); + //start search button listenr + btnConfigReader.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + + + control.configReader(); + + } + } + ); + //start search button listenr btnStartSearch.addActionListener(new ActionListener() { @Override @@ -70,6 +83,7 @@ public void actionPerformed(ActionEvent ev) { } public JButton btnStartSearch; + public JButton btnConfigReader; public JProgressBar prgProgress; diff --git a/src/main/java/com/compomics/coss/View/ValidationCommandPanel.java b/src/main/java/com/compomics/coss/View/ValidationCommandPanel.java index ee58207..7c0a8f4 100644 --- a/src/main/java/com/compomics/coss/View/ValidationCommandPanel.java +++ b/src/main/java/com/compomics/coss/View/ValidationCommandPanel.java @@ -6,6 +6,8 @@ package com.compomics.coss.View; import com.compomics.coss.Controller.MainFrameController; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; @@ -37,12 +39,9 @@ private void init(){ JComboBox cmbFdr=new JComboBox(fdr); cmbFdr.setSelectedIndex(0); - JLabel lblVaidResul=new JLabel("No. of Valid Result"); - JTextField txtValidResult=new JTextField(Integer.toString(0)); - txtValidResult.setEditable(false); - JButton btnValidate=new JButton("Validate Result"); - // JPanel pnlValdninnerControl = new JPanel(new FlowLayout()); + JButton btnValidate=new JButton("Validate Result"); + javax.swing.GroupLayout pnlValdninnerControlLayout = new javax.swing.GroupLayout(this); setLayout(pnlValdninnerControlLayout); pnlValdninnerControlLayout.setHorizontalGroup( @@ -54,14 +53,13 @@ private void init(){ .addComponent(lblFdr) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(cmbFdr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) - .addContainerGap(38, Short.MAX_VALUE)) + .addContainerGap(38, 38)) .addGroup(pnlValdninnerControlLayout.createSequentialGroup() .addGroup(pnlValdninnerControlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(btnValidate) .addGroup(pnlValdninnerControlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(lblVaidResul, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE) - .addComponent(txtValidResult, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) - .addGap(0, 0, Short.MAX_VALUE)))) + )) + .addGap(0, 0, 10)))) ); pnlValdninnerControlLayout.setVerticalGroup( pnlValdninnerControlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) @@ -70,17 +68,23 @@ private void init(){ .addGroup(pnlValdninnerControlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblFdr) .addComponent(cmbFdr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(lblVaidResul) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(txtValidResult, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnValidate) - .addGap(119, 119, 119)) + .addGap(5, 5, 5) + ) ); - + btnValidate.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + + + control.validateResult(); + + } + } + ); } diff --git a/src/main/java/com/compomics/coss/View/ValidationHistogramPanel.java b/src/main/java/com/compomics/coss/View/ValidationHistogramPanel.java index 7d315ab..ff1865b 100644 --- a/src/main/java/com/compomics/coss/View/ValidationHistogramPanel.java +++ b/src/main/java/com/compomics/coss/View/ValidationHistogramPanel.java @@ -7,6 +7,7 @@ import com.compomics.coss.Controller.MainFrameController; import com.compomics.coss.Model.ComparisonResult; +import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; @@ -31,21 +32,52 @@ public class ValidationHistogramPanel extends JPanel { public ValidationHistogramPanel(List> resultTarget, List> resultDecoy) { this.histTarget = new TreeMap<>(); this.histDecoy = new TreeMap<>(); - if(resultTarget!=null || resultDecoy!=null){ + if(resultTarget!=null && resultDecoy!=null){ - resultDecoy.stream().map((rt) -> rt.get(0).getScore()).map((score) -> { - histDecoy.computeIfPresent(score, (k, v) -> v + 1); - return score; - }).forEach((score) -> { - histDecoy.putIfAbsent(score, 1); - }); - - resultTarget.stream().map((rt) -> rt.get(0).getScore()).map((score) -> { - histTarget.computeIfPresent(score, (k, v) -> v + 1); - return score; - }).forEach((score) -> { - histTarget.putIfAbsent(score, 1); - }); + for(ArrayList resT: resultTarget){ + if(!resT.isEmpty()) + { + double score=resT.get(0).getScore(); + + if(histTarget.containsKey(score)){ + int val=histTarget.get(score)+1; + histTarget.replace(score, val); + } + histTarget.put(score, 1); + } + + + + } + + for(ArrayList resD: resultDecoy){ + + if(!resD.isEmpty()) + { + double score=resD.get(0).getScore(); + if(histDecoy.containsKey(score)){ + int val=histDecoy.get(score)+1; + histDecoy.replace(score, val); + } + histDecoy.put(score, 1); + } + + + } + +// resultDecoy.stream().map((rt) -> rt.get(0).getScore()).map((score) -> { +// histDecoy.computeIfPresent(score, (k, v) -> v + 1); +// return score; +// }).forEach((score) -> { +// histDecoy.putIfAbsent(score, 1); +// }); +// +// resultTarget.stream().map((rt) -> rt.get(0).getScore()).map((score) -> { +// histTarget.computeIfPresent(score, (k, v) -> v + 1); +// return score; +// }).forEach((score) -> { +// histTarget.putIfAbsent(score, 1); +// }); } init(); } @@ -62,25 +94,26 @@ private void init() { public void paint(Graphics g) { super.paint(g); - + Graphics2D g2 = (Graphics2D) g; + drawCoordinate(g2); if(!this.histDecoy.isEmpty()|| !this.histTarget.isEmpty()){ - Graphics2D g2 = (Graphics2D) g; - drawDistribution(); - drawCoordinate(g2); + image=(Image)tempImage; + image = image.getScaledInstance(this.getWidth()-35, this.getHeight()-15, Image.SCALE_DEFAULT); if (image != null) { - g.drawImage(image, 51, 10, null); - } - - if (image == null ) { - g.drawString("Couldn't get scores", this.getWidth() / 2 - 10, this.getHeight() / 2 - 10); + g.drawImage(image, 24, 0, null); } + g2.dispose(); } + if (image == null ) { + g.drawString("Result not provided", this.getWidth() / 2 - 10, this.getHeight() / 2 - 10); + } + } /** @@ -96,18 +129,22 @@ public void paint(Graphics g) { private void drawDistribution() { double maxScoreT = histTarget.lastEntry().getKey(); - double maxScoreD = histDecoy.lastEntry().getKey(); - int maxHitT=histTarget.lastEntry().getValue(); - int maxHitD=histDecoy.lastEntry().getValue(); + double maxScoreD=0; + if(!histDecoy.isEmpty()){ + maxScoreD = histDecoy.lastEntry().getKey(); + } + + // int maxHitT=histTarget.lastEntry().getValue(); + //int maxHitD=histDecoy.lastEntry().getValue(); double maxScore = maxScoreT > maxScoreD ? maxScoreT : maxScoreD; - int maxHit= maxHitT>maxHitD? maxHitT : maxHitD; + //int maxHit= maxHitT>maxHitD? maxHitT : maxHitD; //int len = this.histDecoy.size(); int w =(int)Math.ceil(maxScore)+5; - int h =maxHit+5; + int h = this.getHeight()-15;// 50;//maxHit+5; tempImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g = tempImage.createGraphics(); @@ -121,22 +158,35 @@ private void drawDistribution() { int yPos; //drawing target db scores with green color - g.setColor(Color.green); - for (Map.Entry entry : histTarget.entrySet()) { - xPos = entry.getKey().intValue(); - yPos = h - entry.getValue(); - - g.drawLine(xPos, h, xPos, yPos); - } + + if(!histTarget.isEmpty()){ + g.setColor(Color.blue); + g.setStroke(new BasicStroke(3)); + for (Map.Entry entry : histTarget.entrySet()) { + xPos = entry.getKey().intValue(); + yPos = h - entry.getValue()*50; + + g.drawLine(xPos, h, xPos, yPos); + } + + } + //draing decoy scores with red color - g.setColor(Color.red); - for (Map.Entry entry : histDecoy.entrySet()) { - xPos = entry.getKey().intValue(); - yPos = h - entry.getValue(); - - g.drawLine(xPos, h, xPos, yPos); + if(!histDecoy.isEmpty()){ + g.setColor(Color.red); + g.setStroke(new BasicStroke()); + for (Map.Entry entry : histDecoy.entrySet()) { + xPos = entry.getKey().intValue(); + yPos = h - entry.getValue()*4; + + g.drawLine(xPos, h, xPos, yPos); + } + } + + + g.dispose(); } @@ -147,26 +197,15 @@ private void drawDistribution() { * @param g2 graphical object of the panel */ private void drawCoordinate(Graphics2D g2) { + +//int picWidth = this.getWidth() - 50; // 50 pixels for left(50) and right(10) margin + int picHeight = this.getHeight() - 15;// 50 pixels for top(10) and bottom(50) margin -// int y; -// int x; -// int xStep; -// int yStep; -// -// double mzPoint = 0; -// int currentX = 0; - - //int picWidth = this.getWidth() - 50; // 50 pixels for left(50) and right(10) margin - int picHeight = this.getHeight() - 50;// 50 pixels for top(10) and bottom(50) margin - - int picLeft = 40;// left margin, 40 pixels - int picRight = this.getWidth() - 10;// right margin,10 pixels - int picTop = 10; // top margin, 10 pixels - int picBottom = this.getHeight() - 40; //lower coordinate position of the picture - int picMid = picHeight / 2 + picTop;//Mid coordinate position of the picture - -// xStep = picWidth / 10; //divide the pcture in 10 steps horizontally -// yStep = picHeight / 5; //divide the picture in 5 steps vertically + int picLeft = 23; + int picRight = this.getWidth() - 10; + int picTop = 0; + int picBottom = this.getHeight() - 15; + int picMid = picHeight / 2 + picTop; //DrawCoordinate(this.getHeight()-10, this.getWidth()-10, 20, 20, new Point(10, 10), grph); g2.setColor(Color.black); @@ -174,33 +213,10 @@ private void drawCoordinate(Graphics2D g2) { g2.drawLine(picLeft - 1, picTop, picLeft - 1, picBottom + 1); g2.drawString("Hits", 0, picMid); - //g2.drawString("(%)", 0, picMid + 10); - //draw horizontal coordinate line, measurements and lable g2.drawLine(picLeft - 1, picBottom + 1, picRight, picBottom + 1); -// for (x = picLeft - 1; x <= picRight; x += xStep) { -// -// g2.drawLine(x, picBottom, x, picBottom + 5);// horizontal ticks -// mzPoint = currentX * xMap; -// mzPoint = Precision.round(mzPoint, 2); -// g2.drawString(Double.toString(mzPoint), x - 10, picBottom + 17); //10(string size) + 2(gap with ticks) + 5(bottompic pos) = 17 pixels -// currentX += xStep; -// } - g2.drawString("Score", (this.getWidth() / 2) - 5, this.getHeight() - 17); - -// //vertical ticks of the coordinate -// int currentY = 0; -// //int intensityPoint = 0; -// // double percentage=100/(double)picHeight; -// -// for (y = picBottom + 1; y >= picTop; y -= yStep) { -// -// g2.drawLine(picLeft - 1, y, picLeft - 6, y); -// //intensityPoint =(int)( currentY * percentage); -// g2.drawString(Integer.toString(currentY), 20, y + 3); -// currentY += 20; -// -// } + + g2.drawString("Score", (this.getWidth() / 2) - 5, this.getHeight() - 3); } diff --git a/src/main/java/com/compomics/matching/Cascade.java b/src/main/java/com/compomics/matching/Cascade.java deleted file mode 100644 index a1b3775..0000000 --- a/src/main/java/com/compomics/matching/Cascade.java +++ /dev/null @@ -1,308 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package com.compomics.matching; - -import com.compomics.coss.Controller.UpdateListener; -import com.compomics.coss.Model.ComparisonResult; -import com.compomics.featureExtraction.Peaks; -import com.compomics.featureExtraction.Features; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.logging.Level; -import org.apache.log4j.Logger; -import com.compomics.preprocessing.Filter; -//import com.compomics.preprocessing.HighPass; -import com.compomics.featureExtraction.Wavelet; -import com.compomics.ms2io.IndexKey; -import com.compomics.ms2io.Spectrum; -import com.compomics.ms2io.SpectraReader; -import java.util.Arrays; -import java.util.Map; - -/** - * - * @author Genet - */ -public class Cascade extends Matching { - - UpdateListener listener; - - boolean cancelled = false; - - public Cascade(UpdateListener listener) { - this.listener = listener; - } - - @Override - public void InpArgs(String... args) { - - } - - @Override - public void stopMatching() { - cancelled = true; - } - - @Override - public List> compare(SpectraReader rdExperiment, List expIndex, SpectraReader rdLibrary, List libIndex,org.apache.log4j.Logger log) { - - int specNum = 1; - List> simResult = new ArrayList<>(); - - ExecutorService executor = Executors.newFixedThreadPool(4); - List futureList = new ArrayList<>(); - - int specPos = 1; - int taskCompleted = 0; - double lenA = expIndex.size(); - //double lenB = specb.size(); - -// for (Spectrum sp1 : speca) { -// -// if (cancelled) { -// executor.shutdownNow(); -// return null; -// } -//// Cascade.DoMatching dm = new Cascade.DoMatching(specPos, sp1, specb); -// Future future = executor.submit(dm); -// futureList.add(future); -// specPos++; -// -// } - - for (Future> f : futureList) { - try { - - if (cancelled) { - executor.shutdownNow(); - return null; - } - - simResult.add(f.get()); - taskCompleted++; - this.listener.updateprogressbar((double) taskCompleted / lenA); - log.info("Matching Spectrum Number " + specNum + " Completed"); - specNum++; - - } catch (InterruptedException ex) { - java.util.logging.Logger.getLogger(UseMsRoben.class.getName()).log(Level.SEVERE, "IterruptedExeption", ex + "Interrrupted Exception"); - } catch (ExecutionException ex) { - java.util.logging.Logger.getLogger(UseMsRoben.class.getName()).log(Level.SEVERE, "Execution Exception", ex + " from useMsRobin"); - } - } - - executor.shutdown(); - return simResult; - } - - private class DoMatching implements Callable { - - public DoMatching() { - // this.sp1 = sa; - //this.sb = sb; - // this.specPos = specpos; - } - - //MSnSpectrum sp1; - // ArrayList sb; - int specPos; - double intensity_part = 0, probability_part = 0; - Features flt = new Wavelet(); - - @Override - public int[] call() throws Exception { - -// InnerIteratorSync iteratorSpectra = new InnerIteratorSync(sb.iterator()); - //the first 6 values stores scores and the last 6 values corresponds to lib. spec. indexes at which the score calculated - int max = Integer.MAX_VALUE; - int[] topScores = {max, max, max, max, max, max, max, max, max, max, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - int pos = 0; - - double[] mzVal2; - - double[] feature2; - - // double[] mzVal1 = sp1.getMzValuesAsArray(); - double[] peaks1=new double[10]; - int[] peaks2; - // Peaks.findPeaks(mzVal1, peaks1, 10); - //Arrays.sort(mzVal1); - - //double[] peaks1 = PickPeaks(mzVal1).stream().mapToDouble(d -> d).toArray();// sp1.getIntensityValuesAsArray(); - double[] feature1 = flt.getFeatures(peaks1); - - //while (iteratorSpectra.iter.hasNext()) { - - // MSnSpectrum sp2 = (MSnSpectrum) iteratorSpectra.iter.next(); - - - // topNpeaks2=new DivideAndTopNPeaks(sp2, 10, 10); - - //mzVal2 = sp2.getMzValuesAsArray(); - //Arrays.sort(mzVal2); - //peaks2 = PickPeaks(mzVal2).stream().mapToDouble(d -> d).toArray();//sp2.getIntensityValuesAsArray(); - //double[] testD=new{6, 12, 15, 15, 14, 12, 120, 116}; - //feature1=flt.getFeatures(testD); - // feature2 = flt.getFeatures(mzVal2); - - // int coorIndx = 0;// xCorrelation(mzVal1, mzVal2, len1, len2); - - //double distScore =eclDistance(feature1, feature2, 10); - -// for (int i = 0; i < 10; i++) { -// if (distScore < topScores[i]) { -// for (int j = 9; j > i; j--) { -// topScores[j] = topScores[j - 1]; -// topScores[j + 10] = topScores[j + 9]; -// } -// topScores[i] = (int) distScore; -// topScores[i + 10] = pos; -// break; -// } -// -// } - pos++; - - // } - - return topScores; - } - - private List PickPeaks(double[] values) { - - List peaks = new ArrayList<>(); - int len = values.length; - - for (int i = 0; i < len - 2; i++) { - if ((values[i + 1] - values[i]) * (values[i + 2] - values[i + 1]) <= 0) { // changed sign? - peaks.add(values[i+1]); - } - } - -// List peaks = new ArrayList<>(); -// double previous = 0; -// double previousSlope = 0; -// int len=values.length; -// -// for (int i=0;i { - - private Iterator iter = null; - - public InnerIteratorSync(Iterator aIterator) { - iter = aIterator; - } - - public synchronized T next() { - T result = null; - if (iter.hasNext()) { - result = iter.next(); - } - return result; - } - } - - private int xCorrelation(double[] mz1, double[] mz2, int len1, int len2) { - int xCoorIndx = 0; - double min = 0; - double sum; - double diff = 0; - - if (len1 >= len2) { - - for (int i = 0; i < len1; i++) { - sum = 0; - for (int j = 0; j < len2 && j + i < len1; j++) { - diff = mz1[i + j] - mz2[j]; - - sum += (diff * diff); - } - if (min > sum) { - min = sum; - xCoorIndx = i; - } - } - } else { - for (int i = 0; i < len2; i++) { - sum = 0; - for (int j = 0; j < len1 && j + i < len2; j++) { - diff = mz2[i + j] - mz1[j]; - - sum += (diff * diff); - } - if (min > sum) { - min = sum; - xCoorIndx = i; - } - } - } - - return xCoorIndx; - } - - private double eclDistance(double[] feature1, double[] feature2, int len) { - double dist = 0; - - double diff = 0; - - for (int i = 0; i < len; i++) { - - diff = feature1[i] - feature2[i]; - - dist += diff * diff; - } - dist = Math.sqrt(dist); - return dist; - } - -// private int simulatedannealing(double startTemp, double coolingRate) { -// -// double state=0; -// // Solution x = createRandomSolution(); -// double t= startTemp; -// -// while(state>0) { -// double f = calculatedist(targ, libcurrent); -// double newf=calculatedist(targ, libnext); -// -// -// -// if (newFf< f) { -// double p = PR(); // no idea what you're talking about here -// if (p > UR(0, 1)) { // likewise -// // then do nothing -// } else { -// x = mutatedX; -// } -// ti = t * coolingRate; -// } -// } -// return x; -// return 0; -// } - } - -} diff --git a/src/main/java/com/compomics/matching/Matching.java b/src/main/java/com/compomics/matching/Matching.java index 72cdb26..e16d226 100644 --- a/src/main/java/com/compomics/matching/Matching.java +++ b/src/main/java/com/compomics/matching/Matching.java @@ -17,7 +17,7 @@ public abstract class Matching { public abstract void InpArgs(java.lang.String ... args); - public abstract List > compare(org.apache.log4j.Logger log); + public abstract List > dispatcher(org.apache.log4j.Logger log); public abstract void stopMatching(); diff --git a/src/main/java/com/compomics/matching/UseMsRoben.java b/src/main/java/com/compomics/matching/UseMsRoben.java index 1cb1ff2..d97df2a 100644 --- a/src/main/java/com/compomics/matching/UseMsRoben.java +++ b/src/main/java/com/compomics/matching/UseMsRoben.java @@ -1,5 +1,6 @@ package com.compomics.matching; + import com.compomics.featureExtraction.DivideAndTopNPeaks; import com.compomics.featureExtraction.TopNPeaks; import java.util.ArrayList; @@ -18,8 +19,9 @@ import com.compomics.ms2io.IndexKey; import java.util.Collections; + /** - * + * * * @author Genet */ @@ -28,25 +30,28 @@ public class UseMsRoben extends Matching { //private final double msRobinScore = 0; private final double massWindow = 100; + boolean stillReading; UpdateListener listener; SpectraReader rdExperiment; SpectraReader rdLibrary; List expIndex; String resultType; - + int MsRobinOption; int IntensityOption; double fragTolerance; boolean cancelled = false; + int TaskCompleted; public UseMsRoben(UpdateListener lstner, SpectraReader rdExperiment, List expIndex, SpectraReader rdLibrary, String resultType) { this.listener = lstner; - this.rdExperiment=rdExperiment; - this.rdLibrary=rdLibrary; - this.resultType=resultType; - this.expIndex=expIndex; + this.rdExperiment = rdExperiment; + this.rdLibrary = rdLibrary; + this.resultType = resultType; + this.expIndex = expIndex; cancelled = false; + this.TaskCompleted = 0; } @Override @@ -59,144 +64,215 @@ public void InpArgs(String... args) { @Override public void stopMatching() { - //executor.shutdownNow(); + cancelled = true; } @Override - public List> compare(org.apache.log4j.Logger log) { - // specA = spa;, libIndex - - - - int specNum = 1; + public List> dispatcher(org.apache.log4j.Logger log) { + List> simResult = new ArrayList<>(); + try { - ExecutorService executor = Executors.newFixedThreadPool(4); - List futureList = new ArrayList<>(); + this.stillReading = true; + ArrayBlockingQueue expspec = new ArrayBlockingQueue<>(10, true); + ArrayBlockingQueue> libSelected = new ArrayBlockingQueue<>(10, true); + TheData data = new TheData(expspec, libSelected); - int taskCompleted = 0; - double numTasks = expIndex.size(); - Spectrum expSpec; - for(int a=0;a>> future = executor.submit(match1); + + future1.get(); + simResult = future.get(); + executor.shutdown(); + + } catch (InterruptedException ex) { + Logger.getLogger(UseMsRoben.class.getName()).log(Level.SEVERE, null, ex); + } catch (ExecutionException ex) { + Logger.getLogger(UseMsRoben.class.getName()).log(Level.SEVERE, null, ex); } - for (Future> f : futureList) { + return simResult; + } + + /** + * This class creates and holds blocking queues for experimental spectrum + * and selected library spectrum based on precursor mass. The comparison is + * done between experimental spectrum against corresponding spectra at the + * same location in their respective queue. + * + */ + private class TheData { + + private BlockingQueue expSpec = null; + private BlockingQueue> selectedLibSpec = null; + + public TheData(ArrayBlockingQueue expS, ArrayBlockingQueue> libS) { + + this.expSpec = expS; + this.selectedLibSpec = libS; + + } + + private void putExpSpec(Spectrum s) throws InterruptedException { + this.expSpec.put(s); + } + + private void putLibSpec(ArrayList s) throws InterruptedException { + this.selectedLibSpec.put(s); + } + + private Spectrum pollExpSpec() throws InterruptedException { + return this.expSpec.poll(1, TimeUnit.SECONDS); + } + + private ArrayList pollLibSpec() throws InterruptedException { + return this.selectedLibSpec.poll(1, TimeUnit.SECONDS); + } + + } + + /** + * this class puts spectra that are going to be compared into queue as it is + * blocking Queue it blocks until there is free space. + */ + private class DataProducer implements Runnable { //procucer thread + + TheData data; + + public DataProducer(TheData data) { + this.data = data; + + } + + @Override + public void run() { try { + double numTasks = expIndex.size(); + Spectrum expSpec; + for (int a = 0; a < numTasks; a++) { - if (cancelled) { - executor.shutdownNow(); - return null; - } + expSpec = rdExperiment.readAt(expIndex.get(a).getPos()); + double mass = expSpec.getPCMass(); + double da_error = (10 * mass) / 1000000.0; + ArrayList libSpec = rdLibrary.readPart(mass, da_error); + + data.putExpSpec(expSpec); + data.putLibSpec(libSpec); - simResult.add(f.get()); - taskCompleted++; - this.listener.updateprogressbar((double) taskCompleted / numTasks); - log.info("Matching Spectrum Number " + specNum + " Completed"); - specNum++; + } + } catch (Exception e) { + System.out.println(e.toString()); - } catch (InterruptedException ex) { - Logger.getLogger(UseMsRoben.class.getName()).log(Level.SEVERE, "IterruptedExeption", ex + "Interrrupted Exception"); - } catch (ExecutionException ex) { - Logger.getLogger(UseMsRoben.class.getName()).log(Level.SEVERE, "Execution Exception", ex + " from useMsRobin"); + } finally { + stillReading = false; } - } - executor.shutdown(); - return simResult; + } } - private class DoMatching implements Callable > { - - Spectrum sp1; - ArrayList sb; - String resType=""; - - public DoMatching(Spectrum sa, ArrayList sb, String restype) { - this.sp1 = sa; - this.sb = sb; - - + private class DoMatching implements Callable>> { + + String resType = ""; + TheData data; + final String threadName; + org.apache.log4j.Logger log; + + public DoMatching(TheData data, String restype, String matcherName, org.apache.log4j.Logger log) { + this.data = data; + this.resType = restype; + this.threadName = matcherName; + this.log = log; + } - - double intensity_part = 0, probability_part = 0; @Override - public ArrayList call() throws Exception { - - InnerIteratorSync iteratorSpectra = new InnerIteratorSync(sb.iterator()); - - //the first 6 values stores scores and the last 6 values corresponds to lib. spec. indexes at which the score calculated - // double[][] topScores = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - - - ArrayList compResult=new ArrayList<>(); - - - while (iteratorSpectra.iter.hasNext()) { - ComparisonResult res=new ComparisonResult(); - Spectrum sp2 = (Spectrum) iteratorSpectra.iter.next(); - //DoMatching dm = new DoMatching(sp1, sp2); - - //Computing all topN scores omited as the all 10 picks score more than the others - topN changed by 10 - //for (int topN = 1; topN < 11; topN++) { - TopNPeaks filterA = new DivideAndTopNPeaks(sp1, 10, massWindow); - TopNPeaks filterB = new DivideAndTopNPeaks(sp2, 10, massWindow); - double probability = (double) 10 / (double) massWindow; - ArrayList fP_spectrumA = filterA.getFilteredPeaks(), - fP_spectrumB = filterB.getFilteredPeaks(); - double[] results = new double[4]; - if (fP_spectrumB.size() < fP_spectrumA.size()) { - results = prepareData(fP_spectrumA, fP_spectrumB); - } else { - results = prepareData(fP_spectrumB, fP_spectrumA); + public List> call() { + + List> simResult = new ArrayList<>(); + + while (stillReading || (!data.expSpec.isEmpty() && !data.selectedLibSpec.isEmpty())) { + + ArrayList compResult = new ArrayList<>(); + Spectrum sp1 = new Spectrum(); + ArrayList sb = new ArrayList(); + + try { + + if(data.expSpec.isEmpty() || data.selectedLibSpec.isEmpty()) + continue; + + sp1 = data.pollExpSpec(); + sb = data.pollLibSpec(); + } catch (InterruptedException ex) { + Logger.getLogger(UseMsRoben.class.getName()).log(Level.SEVERE, null, ex); + } + + InnerIteratorSync iteratorSpectra = new InnerIteratorSync(sb.iterator()); + + while (iteratorSpectra.iter.hasNext()) { + Spectrum sp2 = (Spectrum) iteratorSpectra.iter.next(); + ComparisonResult res = new ComparisonResult(); + try { + + //Computing all topN scores omited as the all 10 picks score more than the others - topN changed by 10 + //for (int topN = 1; topN < 11; topN++) { + TopNPeaks filterA = new DivideAndTopNPeaks(sp1, 10, massWindow); + TopNPeaks filterB = new DivideAndTopNPeaks(sp2, 10, massWindow); + double probability = (double) 10 / (double) massWindow; + ArrayList fP_spectrumA = filterA.getFilteredPeaks(), + fP_spectrumB = filterB.getFilteredPeaks(); + double[] results = new double[4]; + if (fP_spectrumB.size() < fP_spectrumA.size()) { + results = prepareData(fP_spectrumA, fP_spectrumB); + } else { + results = prepareData(fP_spectrumB, fP_spectrumA); + } + int totalN = (int) results[0], + n = (int) results[1]; + double tmp_intensity_part = results[2]; + MSRobin object = new MSRobin(probability, totalN, n, tmp_intensity_part, MsRobinOption); + double score = object.getScore(); + Precision.round(score, 2); + res.setCharge(sp2.getCharge()); + res.setPrecMass(sp2.getPCMass()); + res.setScanNum(sp2.getScanNumber()); + res.setScore(score); + res.setTitle(sp2.getTitle()); + res.setSpecPosition(sp2.getIndex().getPos()); + res.setResultType(this.resType); + compResult.add(res); + intensity_part = object.getIntensity_part(); + probability_part = object.getProbability_part(); + } catch (Exception ex) { + Logger.getLogger(UseMsRoben.class.getName()).log(Level.SEVERE, null, ex); + } + + } + + TaskCompleted++; + log.info("Number of match completed " + Integer.toString(TaskCompleted)); + Collections.sort(compResult, Collections.reverseOrder()); + //only top 5 scores returned + if (compResult.size() > 5) { + compResult.subList(5, compResult.size()).clear(); } - int totalN = (int) results[0], - n = (int) results[1]; - double tmp_intensity_part = results[2]; - - MSRobin object = new MSRobin(probability, totalN, n, tmp_intensity_part, MsRobinOption); - double score = object.getScore(); - Precision.round(score, 2); - - res.setCharge(sp2.getCharge()); - res.setPrecMass(sp2.getPCMass()); - res.setScanNum(sp2.getScanNumber()); - res.setScore(score); - res.setTitle(sp2.getTitle()); - res.setSpecPosition(sp2.getIndex().getPos()); - res.setResultType(this.resType); - - compResult.add(res); - - intensity_part = object.getIntensity_part(); - probability_part = object.getProbability_part(); - + + simResult.add(compResult); + compResult.clear(); } - - Collections.sort(compResult, Collections.reverseOrder()); - //only top 5 scores returned - if(compResult.size()> 5) - compResult.subList(5, compResult.size()).clear(); - return compResult; + return simResult; } public double getIntensity_part() { @@ -233,7 +309,7 @@ public synchronized T next() { } private double[] prepareData(ArrayList filteredExpMS2_1, ArrayList filteredExpMS2_2) { - + double[] results = new double[4]; HashSet mPeaks_2 = new HashSet(); //matched peaks from filteredExpMS2_2 double intensities_1 = 0, @@ -327,3 +403,4 @@ private double calculateIntensityPart(double alpha_alpha, double beta_beta, doub } } + diff --git a/src/main/resources/config.properties b/src/main/resources/config.properties index 634abd6..8c37db6 100644 --- a/src/main/resources/config.properties +++ b/src/main/resources/config.properties @@ -4,8 +4,8 @@ coss.version = 1.0 ###### User Imput Parameters ###### ############################## -target.spectra.path = D:/testData/SpecA.msp -#C:/pandyDS/Adult_Lung_bRP_Velos_12_f12-medium.mgf +target.spectra.path = C:/pandyDS/Adult_Lung_bRP_Velos_12_f12-medium.mgf +# D:/testData/SpecA.msp # D:/testData/SpecA.msp # D:/testData/SpecA.mgf #Adult_Lung_bRP_Velos_12_f12-medium.mgf