diff --git a/pom.xml b/pom.xml index f3e4bd1..7e1d823 100644 --- a/pom.xml +++ b/pom.xml @@ -325,10 +325,10 @@ test - - com.compomics - utilities - 4.12.15 + + com.compomics + utilities + 5.1.17 commons-math @@ -370,13 +370,19 @@ ols-dialog no.uib - - jar - - - - jfree - jfreechart + + jar + + + + org.apache.logging.log4j + log4j-slf4j-impl + 2.25.4 + + + + jfree + jfreechart 1.0.13 diff --git a/src/log4j.properties b/src/log4j.properties deleted file mode 100644 index 35d8563..0000000 --- a/src/log4j.properties +++ /dev/null @@ -1,16 +0,0 @@ -# Log messages to stdout -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.Target=System.out -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%n%5p %d [%t] %c{1}:%L %m%n -log4j.appender.root=org.apache.log4j.FileAppender -log4j.appender.root.File=root.log -log4j.appender.root.layout=org.apache.log4j.PatternLayout -log4j.appender.root.layout.ConversionPattern=%n%5p %d [%t] %c{1}:%L %m%n - -# resources to the root file. -log4j.logger.resources = all - -# resources.mpa to the outputstream. -log4j.logger.resources.mpa = all, stdout -log4j.logger.org.apache.commons.configuration=error, stdout \ No newline at end of file diff --git a/src/main/java/com/compomics/denovogui/DeNovoGUIWrapper.java b/src/main/java/com/compomics/denovogui/DeNovoGUIWrapper.java index 7420b07..7edd2eb 100644 --- a/src/main/java/com/compomics/denovogui/DeNovoGUIWrapper.java +++ b/src/main/java/com/compomics/denovogui/DeNovoGUIWrapper.java @@ -4,7 +4,7 @@ import com.compomics.denovogui.util.Properties; import com.compomics.software.CompomicsWrapper; import com.compomics.software.settings.PathKey; -import com.compomics.software.settings.UtilitiesPathPreferences; +import com.compomics.software.settings.UtilitiesPathParameters; import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -89,7 +89,7 @@ protected String getJarFilePath() { * Sets the path configuration. */ private void setPathConfiguration() throws IOException { - File pathConfigurationFile = new File(getJarFilePath(), UtilitiesPathPreferences.configurationFileName); + File pathConfigurationFile = new File(getJarFilePath(), UtilitiesPathParameters.configurationFileName); if (pathConfigurationFile.exists()) { DeNovoGUIPathPreferences.loadPathPreferencesFromFile(pathConfigurationFile); } diff --git a/src/main/java/com/compomics/denovogui/DeNovoSequencingHandler.java b/src/main/java/com/compomics/denovogui/DeNovoSequencingHandler.java index b13c3cb..a05019c 100644 --- a/src/main/java/com/compomics/denovogui/DeNovoSequencingHandler.java +++ b/src/main/java/com/compomics/denovogui/DeNovoSequencingHandler.java @@ -1,22 +1,25 @@ package com.compomics.denovogui; - -import com.compomics.denovogui.execution.Job; -import com.compomics.denovogui.execution.jobs.DirecTagJob; -import com.compomics.denovogui.execution.jobs.NovorJob; -import com.compomics.denovogui.execution.jobs.PNovoJob; -import com.compomics.denovogui.execution.jobs.PepNovoJob; + +import com.compomics.denovogui.io.SpectrumFactory; + +import com.compomics.denovogui.execution.Job; +import com.compomics.denovogui.execution.jobs.DirecTagJob; +import com.compomics.denovogui.execution.jobs.InstaNovoJob; +import com.compomics.denovogui.execution.jobs.NovorJob; +import com.compomics.denovogui.execution.jobs.PNovoJob; +import com.compomics.denovogui.execution.jobs.PepNovoJob; import com.compomics.denovogui.io.FileProcessor; import com.compomics.denovogui.io.PepNovoModificationFile; import com.compomics.denovogui.util.Properties; import com.compomics.software.CompomicsWrapper; import com.compomics.util.exceptions.ExceptionHandler; -import com.compomics.util.experiment.biology.PTMFactory; +import com.compomics.util.experiment.biology.modifications.ModificationFactory; import com.compomics.util.experiment.identification.Advocate; -import com.compomics.util.experiment.identification.identification_parameters.SearchParameters; -import com.compomics.util.experiment.identification.identification_parameters.tool_specific.PepnovoParameters; -import com.compomics.util.experiment.massspectrometry.SpectrumFactory; +import com.compomics.util.parameters.identification.search.SearchParameters; +import com.compomics.util.parameters.identification.tool_specific.PepnovoParameters; +import com.compomics.util.experiment.mass_spectrometry.SpectrumProvider; import com.compomics.util.gui.waiting.waitinghandlers.WaitingHandlerCLIImpl; -import com.compomics.util.preferences.UtilitiesUserPreferences; +import com.compomics.util.parameters.UtilitiesUserParameters; import com.compomics.util.waiting.Duration; import com.compomics.util.waiting.WaitingHandler; import java.io.File; @@ -56,7 +59,11 @@ public class DeNovoSequencingHandler { /** * The Novor folder. */ - private File novorFolder; + private File novorFolder; + /** + * The InstaNovo folder. + */ + private File instaNovoFolder; /** * If true, PepNovo will be run. */ @@ -72,9 +79,21 @@ public class DeNovoSequencingHandler { /** * If true, Novor will be run. */ - private boolean enableNovor = false; - /** - * Default PTM selection. + private boolean enableNovor = false; + /** + * If true, InstaNovo will be run. + */ + private boolean enableInstaNovo = false; + /** + * If true, InstaNovo+ will be run. + */ + private boolean enableInstaNovoPlus = false; + /** + * If true, InstaNovo with refinement will be run. + */ + private boolean enableInstaNovoRefined = false; + /** + * Default Modification selection. */ public static final String DENOVOGUI_COMFIGURATION_FILE = "DeNovoGUI_configuration.txt"; /** @@ -116,7 +135,7 @@ public class DeNovoSequencingHandler { /** * The factory used to handle the modifications. */ - private PTMFactory ptmFactory = PTMFactory.getInstance(); + private ModificationFactory ptmFactory = ModificationFactory.getInstance(); /** * Constructor. @@ -126,12 +145,26 @@ public class DeNovoSequencingHandler { * @param pNovoFolder the pNovo folder * @param novorFolder the Novor folder */ - public DeNovoSequencingHandler(File pepNovoFolder, File direcTagFolder, File pNovoFolder, File novorFolder) { - this.pepNovoFolder = pepNovoFolder; - this.direcTagFolder = direcTagFolder; - this.pNovoFolder = pNovoFolder; - this.novorFolder = novorFolder; - } + public DeNovoSequencingHandler(File pepNovoFolder, File direcTagFolder, File pNovoFolder, File novorFolder) { + this(pepNovoFolder, direcTagFolder, pNovoFolder, novorFolder, null); + } + + /** + * Constructor. + * + * @param pepNovoFolder the PepNovo+ folder + * @param direcTagFolder the DirecTag folder + * @param pNovoFolder the pNovo folder + * @param novorFolder the Novor folder + * @param instaNovoFolder the InstaNovo folder + */ + public DeNovoSequencingHandler(File pepNovoFolder, File direcTagFolder, File pNovoFolder, File novorFolder, File instaNovoFolder) { + this.pepNovoFolder = pepNovoFolder; + this.direcTagFolder = direcTagFolder; + this.pNovoFolder = pNovoFolder; + this.novorFolder = novorFolder; + this.instaNovoFolder = instaNovoFolder; + } /** * Starts the sequencing for a list of files which will be processed @@ -157,14 +190,52 @@ public DeNovoSequencingHandler(File pepNovoFolder, File direcTagFolder, File pNo * @throws ClassNotFoundException thrown if the search parameters cannot be * processed from file */ - public void startSequencing(List spectrumFiles, SearchParameters searchParameters, File outputFolder, File searchParametersFile, String pepNovoExeTitle, String direcTagExeTitle, String pNovoExeTitle, String novorExeTitle, - boolean enablePepNovo, boolean enableDirecTag, boolean enablePNovo, boolean enableNovor, WaitingHandler waitingHandler, ExceptionHandler exceptionHandler) throws IOException, ClassNotFoundException { - - this.enablePepNovo = enablePepNovo; - this.enableDirecTag = enableDirecTag; - this.enablePNovo = enablePNovo; - this.enableNovor = enableNovor; - this.exceptionHandler = exceptionHandler; + public void startSequencing(List spectrumFiles, SearchParameters searchParameters, File outputFolder, File searchParametersFile, String pepNovoExeTitle, String direcTagExeTitle, String pNovoExeTitle, String novorExeTitle, + boolean enablePepNovo, boolean enableDirecTag, boolean enablePNovo, boolean enableNovor, WaitingHandler waitingHandler, ExceptionHandler exceptionHandler) throws IOException, ClassNotFoundException { + startSequencing(spectrumFiles, searchParameters, outputFolder, searchParametersFile, pepNovoExeTitle, direcTagExeTitle, pNovoExeTitle, novorExeTitle, + enablePepNovo, enableDirecTag, enablePNovo, enableNovor, false, false, false, waitingHandler, exceptionHandler); + } + + /** + * Starts the sequencing for a list of files which will be processed + * sequentially. + * + * @param spectrumFiles the spectrum files to process + * @param searchParameters the search parameters + * @param outputFolder the output folder + * @param searchParametersFile the file where to save the search parameters + * @param pepNovoExeTitle the name of the PepNovo+ executable + * @param direcTagExeTitle the name of the DirecTag executable + * @param pNovoExeTitle the name of the pNovo+ executable + * @param novorExeTitle the name of the Novor executable + * @param enablePepNovo run PepNovo? + * @param enableDirecTag run DirecTag? + * @param enablePNovo run pNovo? + * @param enableNovor run Novor? + * @param enableInstaNovo run InstaNovo? + * @param enableInstaNovoPlus run InstaNovo+? + * @param enableInstaNovoRefined run InstaNovo with refinement? + * @param waitingHandler the waiting handler + * @param exceptionHandler the exception handler to use when an exception is + * caught + * + * @throws IOException thrown if there is an IO issue + * @throws ClassNotFoundException thrown if the search parameters cannot be + * processed from file + */ + public void startSequencing(List spectrumFiles, SearchParameters searchParameters, File outputFolder, File searchParametersFile, String pepNovoExeTitle, String direcTagExeTitle, String pNovoExeTitle, String novorExeTitle, + boolean enablePepNovo, boolean enableDirecTag, boolean enablePNovo, boolean enableNovor, + boolean enableInstaNovo, boolean enableInstaNovoPlus, boolean enableInstaNovoRefined, + WaitingHandler waitingHandler, ExceptionHandler exceptionHandler) throws IOException, ClassNotFoundException { + + this.enablePepNovo = enablePepNovo; + this.enableDirecTag = enableDirecTag; + this.enablePNovo = enablePNovo; + this.enableNovor = enableNovor; + this.enableInstaNovo = enableInstaNovo; + this.enableInstaNovoPlus = enableInstaNovoPlus; + this.enableInstaNovoRefined = enableInstaNovoRefined; + this.exceptionHandler = exceptionHandler; int numberOfSpectrumFiles = spectrumFiles.size(); int primaryProgressCounterMax = 1; @@ -173,7 +244,7 @@ public void startSequencing(List spectrumFiles, SearchParameters searchPar // write the modification file try { File folder = new File(pepNovoFolder, "Models"); - PepNovoModificationFile.writeFile(folder, searchParameters.getPtmSettings()); + PepNovoModificationFile.writeFile(folder, searchParameters.getModificationParameters()); } catch (Exception e) { waitingHandler.appendReport("An error occurred while writing the modification file: " + e.getMessage(), true, true); exceptionHandler.catchException(e); @@ -187,9 +258,18 @@ public void startSequencing(List spectrumFiles, SearchParameters searchPar if (enablePNovo) { primaryProgressCounterMax += numberOfSpectrumFiles; } - if (enableNovor) { - primaryProgressCounterMax += numberOfSpectrumFiles; - } + if (enableNovor) { + primaryProgressCounterMax += numberOfSpectrumFiles; + } + if (enableInstaNovo) { + primaryProgressCounterMax += numberOfSpectrumFiles; + } + if (enableInstaNovoPlus) { + primaryProgressCounterMax += numberOfSpectrumFiles; + } + if (enableInstaNovoRefined) { + primaryProgressCounterMax += numberOfSpectrumFiles; + } waitingHandler.setMaxPrimaryProgressCounter(primaryProgressCounterMax); waitingHandler.increasePrimaryProgressCounter(); @@ -207,10 +287,10 @@ public void startSequencing(List spectrumFiles, SearchParameters searchPar // set this version as the default DeNovoGUI version if (!getJarFilePath().equalsIgnoreCase(".")) { - UtilitiesUserPreferences utilitiesUserPreferences = UtilitiesUserPreferences.loadUserPreferences(); + UtilitiesUserParameters utilitiesUserParameters = UtilitiesUserParameters.loadUserParameters(); String versionNumber = Properties.getVersion(); - utilitiesUserPreferences.setDeNovoGuiPath(new File(getJarFilePath(), "DeNovoGUI-" + versionNumber + ".jar").getAbsolutePath()); - UtilitiesUserPreferences.saveUserPreferences(utilitiesUserPreferences); + utilitiesUserParameters.setDeNovoGuiPath(new File(getJarFilePath(), "DeNovoGUI-" + versionNumber + ".jar").getAbsolutePath()); + UtilitiesUserParameters.saveUserParameters(utilitiesUserParameters); } Duration duration = new Duration(); @@ -241,7 +321,9 @@ public void startSequencing(List spectrumFiles, SearchParameters searchPar } // check if we have any output files - ArrayList resultFiles = FileProcessor.getAllResultFiles(outputFolder, spectrumFiles, enablePepNovo, enableDirecTag, enablePNovo, enableNovor); + ArrayList resultFiles = FileProcessor.getAllResultFiles(outputFolder, spectrumFiles, + enablePepNovo, enableDirecTag, enablePNovo, enableNovor, + enableInstaNovo, enableInstaNovoPlus, enableInstaNovoRefined); if (resultFiles.isEmpty()) { waitingHandler.appendReportEndLine(); @@ -271,10 +353,25 @@ private void startSequencing(File spectrumFile, SearchParameters searchParameter String direcTagExeTitle, String pNovoExeTitle, String novorExeTitle, WaitingHandler waitingHandler) throws IOException { try { - jobs = new ArrayDeque(); - - // Novor - if (enableNovor && !waitingHandler.isRunCanceled()) { + jobs = new ArrayDeque(); + + // InstaNovo + if (enableInstaNovo && !waitingHandler.isRunCanceled()) { + runInstaNovo(spectrumFile, searchParameters, outputFolder, waitingHandler, InstaNovoJob.Mode.transformer, "InstaNovo"); + } + + // InstaNovo+ + if (enableInstaNovoPlus && !waitingHandler.isRunCanceled()) { + runInstaNovo(spectrumFile, searchParameters, outputFolder, waitingHandler, InstaNovoJob.Mode.diffusion, "InstaNovo+"); + } + + // InstaNovo with refinement + if (enableInstaNovoRefined && !waitingHandler.isRunCanceled()) { + runInstaNovo(spectrumFile, searchParameters, outputFolder, waitingHandler, InstaNovoJob.Mode.refined, "InstaNovo with refinement"); + } + + // Novor + if (enableNovor && !waitingHandler.isRunCanceled()) { Duration algorithmDuration = new Duration(); algorithmDuration.start(); @@ -491,8 +588,54 @@ private void startSequencing(File spectrumFile, SearchParameters searchParameter exceptionHandler.catchException(ex); } catch (IOException ex) { exceptionHandler.catchException(ex); - } - } + } + } + + /** + * Runs an InstaNovo job. + * + * @param spectrumFile the spectrum file + * @param searchParameters the search parameters + * @param outputFolder the output folder + * @param waitingHandler the waiting handler + * @param mode the execution mode + * @param name the display name + */ + private void runInstaNovo(File spectrumFile, SearchParameters searchParameters, File outputFolder, WaitingHandler waitingHandler, + InstaNovoJob.Mode mode, String name) { + + Duration algorithmDuration = new Duration(); + algorithmDuration.start(); + + waitingHandler.appendReportEndLine(); + waitingHandler.appendReport("Sequencing " + spectrumFile.getName() + " using " + name + ".", true, true); + waitingHandler.appendReportEndLine(); + + threadExecutor = Executors.newFixedThreadPool(1); + InstaNovoJob instaNovoJob = new InstaNovoJob(instaNovoFolder, spectrumFile, outputFolder, searchParameters, mode, waitingHandler, exceptionHandler); + threadExecutor.submit(instaNovoJob); + jobs.add(instaNovoJob); + + threadExecutor.shutdown(); + + try { + threadExecutor.awaitTermination(12, TimeUnit.HOURS); + } catch (InterruptedException ex) { + if (!waitingHandler.isRunCanceled()) { + threadExecutor.shutdownNow(); + exceptionHandler.catchException(ex); + } + } + + if (!waitingHandler.isRunCanceled()) { + algorithmDuration.end(); + + waitingHandler.appendReportEndLine(); + waitingHandler.appendReport("Sequencing " + spectrumFile.getName() + " using " + name + " completed (" + algorithmDuration.toString() + ").", true, true); + waitingHandler.appendReportEndLine(); + waitingHandler.increasePrimaryProgressCounter(); + } + } /** * Cancels the sequencing process. @@ -635,9 +778,9 @@ public static void setUserModificationFile(String modificationFile) { */ public static String loadModifications(SearchParameters searchParameters) { String error = null; - ArrayList toCheck = PTMFactory.getInstance().loadBackedUpModifications(searchParameters, true); + ArrayList toCheck = ModificationFactory.getInstance().loadBackedUpModifications(searchParameters, true); if (!toCheck.isEmpty()) { - error = "The definition of the following PTM(s) seems to have changed and were overwritten:\n"; + error = "The definition of the following Modification(s) seems to have changed and were overwritten:\n"; for (int i = 0; i < toCheck.size(); i++) { if (i > 0) { if (i < toCheck.size() - 1) { @@ -648,7 +791,7 @@ public static String loadModifications(SearchParameters searchParameters) { } error += toCheck.get(i); } - error += ".\nPlease verify the definition of the PTM(s) in the modifications editor."; + error += ".\nPlease verify the definition of the Modification(s) in the modifications editor."; } return error; } diff --git a/src/main/java/com/compomics/denovogui/cmd/DeNovoCLI.java b/src/main/java/com/compomics/denovogui/cmd/DeNovoCLI.java index 632bf35..9e62bf2 100644 --- a/src/main/java/com/compomics/denovogui/cmd/DeNovoCLI.java +++ b/src/main/java/com/compomics/denovogui/cmd/DeNovoCLI.java @@ -1,18 +1,21 @@ package com.compomics.denovogui.cmd; - -import com.compomics.denovogui.DeNovoSequencingHandler; -import com.compomics.denovogui.preferences.DeNovoGUIPathPreferences; + +import com.compomics.denovogui.io.SpectrumFactory; + +import com.compomics.denovogui.DeNovoSequencingHandler; +import com.compomics.denovogui.execution.jobs.InstaNovoJob; +import com.compomics.denovogui.preferences.DeNovoGUIPathPreferences; import com.compomics.denovogui.util.Properties; import com.compomics.software.CompomicsWrapper; import com.compomics.software.settings.PathKey; -import com.compomics.software.settings.UtilitiesPathPreferences; +import com.compomics.software.settings.UtilitiesPathParameters; import com.compomics.util.Util; import com.compomics.util.exceptions.exception_handlers.CommandLineExceptionHandler; -import com.compomics.util.experiment.biology.*; -import com.compomics.util.experiment.identification.identification_parameters.SearchParameters; -import com.compomics.util.experiment.massspectrometry.SpectrumFactory; +import com.compomics.util.experiment.biology.enzymes.EnzymeFactory; +import com.compomics.util.parameters.identification.search.SearchParameters; +import com.compomics.util.experiment.mass_spectrometry.SpectrumProvider; import com.compomics.util.gui.waiting.waitinghandlers.WaitingHandlerCLIImpl; -import com.compomics.util.preferences.UtilitiesUserPreferences; +import com.compomics.util.parameters.UtilitiesUserParameters; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -56,7 +59,7 @@ public DeNovoCLI(String[] args) { Options lOptions = new Options(); DeNovoCLIParams.createOptionsCLI(lOptions); - BasicParser parser = new BasicParser(); + DefaultParser parser = new DefaultParser(); CommandLine line = parser.parse(lOptions, args); if (!DeNovoCLIInputBean.isValidStartup(line)) { @@ -122,15 +125,19 @@ public Object call() { boolean runPepNovo = deNovoCLIInputBean.enablePepNovo(); boolean runDirecTag = deNovoCLIInputBean.enableDirecTag(); - boolean runPNovo = deNovoCLIInputBean.enablePNovo(); - boolean runNovor = deNovoCLIInputBean.enableNovor(); - - File pepNovoExecutable = deNovoCLIInputBean.getPepNovoExecutable(); - File direcTagExecutable = deNovoCLIInputBean.getDirecTagExecutable(); - File pNovoExecutable = deNovoCLIInputBean.getPNovoExecutable(); - File novorExecutable = deNovoCLIInputBean.getNovorExecutable(); - File pepNovoFolder = null, direcTagFolder = null, pNovoFolder = null, novorFolder = null; - String pepNovoExecutableTitle = null, direcTagExecutableTitle = null, pNovoExecutableTitle = null, novorExecutableTitle = null; + boolean runPNovo = deNovoCLIInputBean.enablePNovo(); + boolean runNovor = deNovoCLIInputBean.enableNovor(); + boolean runInstaNovo = deNovoCLIInputBean.enableInstaNovo(); + boolean runInstaNovoPlus = deNovoCLIInputBean.enableInstaNovoPlus(); + boolean runInstaNovoRefine = deNovoCLIInputBean.enableInstaNovoRefine(); + + File pepNovoExecutable = deNovoCLIInputBean.getPepNovoExecutable(); + File direcTagExecutable = deNovoCLIInputBean.getDirecTagExecutable(); + File pNovoExecutable = deNovoCLIInputBean.getPNovoExecutable(); + File novorExecutable = deNovoCLIInputBean.getNovorExecutable(); + File instaNovoFolder = deNovoCLIInputBean.getInstaNovoFolder(); + File pepNovoFolder = null, direcTagFolder = null, pNovoFolder = null, novorFolder = null; + String pepNovoExecutableTitle = null, direcTagExecutableTitle = null, pNovoExecutableTitle = null, novorExecutableTitle = null; // OS check String osName = System.getProperty("os.name").toLowerCase(); @@ -262,15 +269,22 @@ public Object call() { } // check if the Novor folder is set - if (novorFolder == null && runNovor) { - waitingHandlerCLIImpl.appendReport("\nNovor location not set! Sequencing canceled.", false, true); - System.exit(1); - } - - if (!runPepNovo && !runDirecTag && !runPNovo && !runNovor) { - waitingHandlerCLIImpl.appendReport("\nNo sequencing algorithms selected! Sequencing canceled.", false, true); - System.exit(1); - } + if (novorFolder == null && runNovor) { + waitingHandlerCLIImpl.appendReport("\nNovor location not set! Sequencing canceled.", false, true); + System.exit(1); + } + + if ((runInstaNovo || runInstaNovoPlus || runInstaNovoRefine) + && instaNovoFolder != null + && !InstaNovoJob.getExecutable(instaNovoFolder).exists()) { + waitingHandlerCLIImpl.appendReport("\nInstaNovo executable not found in the selected InstaNovo folder! Sequencing canceled.", false, true); + System.exit(1); + } + + if (!runPepNovo && !runDirecTag && !runPNovo && !runNovor && !runInstaNovo && !runInstaNovoPlus && !runInstaNovoRefine) { + waitingHandlerCLIImpl.appendReport("\nNo sequencing algorithms selected! Sequencing canceled.", false, true); + System.exit(1); + } File searchParametersFile = deNovoCLIInputBean.getSearchParametersFile(); SearchParameters searchParameters = SearchParameters.getIdentificationParameters(searchParametersFile); @@ -301,18 +315,20 @@ public Object call() { waitingHandlerCLIImpl.appendReport("Done loading the spectra.", true, true); // incrementing the counter for a new DenovoGUI run - UtilitiesUserPreferences utilitiesUserPreferences = UtilitiesUserPreferences.loadUserPreferences(); - if (utilitiesUserPreferences.isAutoUpdate()) { + UtilitiesUserParameters utilitiesUserParameters = UtilitiesUserParameters.loadUserParameters(); + if (utilitiesUserParameters.isAutoUpdate()) { Util.sendGAUpdate("UA-36198780-4", "startrun-cl", "denovogui-" + Properties.getVersion()); } // start the sequencing - DeNovoSequencingHandler searchHandler = new DeNovoSequencingHandler(pepNovoFolder, direcTagFolder, pNovoFolder, novorFolder); - searchHandler.setNThreads(deNovoCLIInputBean.getNThreads()); - searchHandler.startSequencing(deNovoCLIInputBean.getSpectrumFiles(), - searchParameters, - deNovoCLIInputBean.getOutputFile(), searchParametersFile, pepNovoExecutableTitle, direcTagExecutableTitle, pNovoExecutableTitle, novorExecutableTitle, - runPepNovo, runDirecTag, runPNovo, runNovor, waitingHandlerCLIImpl, exceptionHandler); + DeNovoSequencingHandler searchHandler = new DeNovoSequencingHandler(pepNovoFolder, direcTagFolder, pNovoFolder, novorFolder, instaNovoFolder); + searchHandler.setNThreads(deNovoCLIInputBean.getNThreads()); + searchHandler.startSequencing(deNovoCLIInputBean.getSpectrumFiles(), + searchParameters, + deNovoCLIInputBean.getOutputFile(), searchParametersFile, pepNovoExecutableTitle, direcTagExecutableTitle, pNovoExecutableTitle, novorExecutableTitle, + runPepNovo, runDirecTag, runPNovo, runNovor, + runInstaNovo, runInstaNovoPlus, runInstaNovoRefine, + waitingHandlerCLIImpl, exceptionHandler); } catch (Exception e) { exceptionHandler.catchException(e); return 1; @@ -325,7 +341,7 @@ public Object call() { * Sets the path configuration. */ private void setPathConfiguration() throws IOException { - File pathConfigurationFile = new File(getJarFilePath(), UtilitiesPathPreferences.configurationFileName); + File pathConfigurationFile = new File(getJarFilePath(), UtilitiesPathParameters.configurationFileName); if (pathConfigurationFile.exists()) { DeNovoGUIPathPreferences.loadPathPreferencesFromFile(pathConfigurationFile); } diff --git a/src/main/java/com/compomics/denovogui/cmd/DeNovoCLIInputBean.java b/src/main/java/com/compomics/denovogui/cmd/DeNovoCLIInputBean.java index 2c0c7f6..f7116d3 100644 --- a/src/main/java/com/compomics/denovogui/cmd/DeNovoCLIInputBean.java +++ b/src/main/java/com/compomics/denovogui/cmd/DeNovoCLIInputBean.java @@ -2,8 +2,8 @@ import com.compomics.cli.identification_parameters.IdentificationParametersInputBean; import com.compomics.software.cli.CommandLineUtils; -import com.compomics.util.experiment.identification.identification_parameters.SearchParameters; -import com.compomics.util.preferences.IdentificationParameters; +import com.compomics.util.parameters.identification.search.SearchParameters; +import com.compomics.util.parameters.identification.IdentificationParameters; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; @@ -46,7 +46,19 @@ public class DeNovoCLIInputBean { /** * If true, Novor is enabled. */ - private boolean novorEnabled = false; + private boolean novorEnabled = false; + /** + * If true, InstaNovo is enabled. + */ + private boolean instaNovoEnabled = false; + /** + * If true, InstaNovo+ is enabled. + */ + private boolean instaNovoPlusEnabled = false; + /** + * If true, InstaNovo with refinement is enabled. + */ + private boolean instaNovoRefineEnabled = false; /** * The PepNovo executable. Full path. */ @@ -62,7 +74,11 @@ public class DeNovoCLIInputBean { /** * The Novor executable. Full path. */ - private File novorExecutable = null; + private File novorExecutable = null; + /** + * The InstaNovo checkout or installation folder. + */ + private File instaNovoFolder = null; /** * Number of threads to use. Defaults to the number of cores available. */ @@ -114,10 +130,22 @@ public DeNovoCLIInputBean(CommandLine aLine) throws FileNotFoundException, IOExc String pNovoOption = aLine.getOptionValue(DeNovoCLIParams.PNOVO.id); pNovoEnabled = pNovoOption.trim().equals("1"); } - if (aLine.hasOption(DeNovoCLIParams.NOVOR.id)) { - String novorOption = aLine.getOptionValue(DeNovoCLIParams.NOVOR.id); - novorEnabled = novorOption.trim().equals("1"); - } + if (aLine.hasOption(DeNovoCLIParams.NOVOR.id)) { + String novorOption = aLine.getOptionValue(DeNovoCLIParams.NOVOR.id); + novorEnabled = novorOption.trim().equals("1"); + } + if (aLine.hasOption(DeNovoCLIParams.INSTANOVO.id)) { + String instaNovoOption = aLine.getOptionValue(DeNovoCLIParams.INSTANOVO.id); + instaNovoEnabled = instaNovoOption.trim().equals("1"); + } + if (aLine.hasOption(DeNovoCLIParams.INSTANOVO_PLUS.id)) { + String instaNovoPlusOption = aLine.getOptionValue(DeNovoCLIParams.INSTANOVO_PLUS.id); + instaNovoPlusEnabled = instaNovoPlusOption.trim().equals("1"); + } + if (aLine.hasOption(DeNovoCLIParams.INSTANOVO_REFINE.id)) { + String instaNovoRefineOption = aLine.getOptionValue(DeNovoCLIParams.INSTANOVO_REFINE.id); + instaNovoRefineEnabled = instaNovoRefineOption.trim().equals("1"); + } // search engine folders if (aLine.hasOption(DeNovoCLIParams.PEPNOVO_LOCATION.id)) { @@ -132,10 +160,14 @@ public DeNovoCLIInputBean(CommandLine aLine) throws FileNotFoundException, IOExc String tempPNovoExecutable = aLine.getOptionValue(DeNovoCLIParams.PNOVO_LOCATION.id); this.pNovoExecutable = new File(tempPNovoExecutable); } - if (aLine.hasOption(DeNovoCLIParams.NOVOR_LOCATION.id)) { - String tempNovorExecutable = aLine.getOptionValue(DeNovoCLIParams.NOVOR_LOCATION.id); - this.novorExecutable = new File(tempNovorExecutable); - } + if (aLine.hasOption(DeNovoCLIParams.NOVOR_LOCATION.id)) { + String tempNovorExecutable = aLine.getOptionValue(DeNovoCLIParams.NOVOR_LOCATION.id); + this.novorExecutable = new File(tempNovorExecutable); + } + if (aLine.hasOption(DeNovoCLIParams.INSTANOVO_LOCATION.id)) { + String tempInstaNovoFolder = aLine.getOptionValue(DeNovoCLIParams.INSTANOVO_LOCATION.id); + this.instaNovoFolder = new File(tempInstaNovoFolder); + } // get the number of threads if (aLine.hasOption(DeNovoCLIParams.THREADS.id)) { @@ -223,9 +255,18 @@ public File getDirecTagExecutable() { * * @return the pNovo+ executable */ - public File getPNovoExecutable() { - return pNovoExecutable; - } + public File getPNovoExecutable() { + return pNovoExecutable; + } + + /** + * Returns the InstaNovo checkout or installation folder. Null if not set. + * + * @return the InstaNovo checkout or installation folder + */ + public File getInstaNovoFolder() { + return instaNovoFolder; + } /** * Returns if PepNovo+ is to be run or not. @@ -241,9 +282,36 @@ public boolean enablePepNovo() { * * @return if Novor is to be run or not */ - public boolean enableNovor() { - return novorEnabled; - } + public boolean enableNovor() { + return novorEnabled; + } + + /** + * Returns if InstaNovo is to be run or not. + * + * @return if InstaNovo is to be run or not + */ + public boolean enableInstaNovo() { + return instaNovoEnabled; + } + + /** + * Returns if InstaNovo+ is to be run or not. + * + * @return if InstaNovo+ is to be run or not + */ + public boolean enableInstaNovoPlus() { + return instaNovoPlusEnabled; + } + + /** + * Returns if InstaNovo with refinement is to be run or not. + * + * @return if InstaNovo with refinement is to be run or not + */ + public boolean enableInstaNovoRefine() { + return instaNovoRefineEnabled; + } /** * Returns if DirecTag is to be run or not. diff --git a/src/main/java/com/compomics/denovogui/cmd/DeNovoCLIParams.java b/src/main/java/com/compomics/denovogui/cmd/DeNovoCLIParams.java index c0e61da..88583a3 100644 --- a/src/main/java/com/compomics/denovogui/cmd/DeNovoCLIParams.java +++ b/src/main/java/com/compomics/denovogui/cmd/DeNovoCLIParams.java @@ -19,13 +19,17 @@ public enum DeNovoCLIParams { IDENTIFICATION_PARAMETERS("id_params", "A search parameters file. Can be generated from the GUI or using the IdentificationParametersCLI (see http://compomics.github.io/projects/compomics-utilities/wiki/identificationparameterscli.html for details).", false), THREADS("threads", "The number of threads to use for the processing. Default is the number of cores available.", false), PEPNOVO("pepnovo", "Turn the PepNovo+ sequencing on or off (1: on, 0: off, default is '1'). (At least one sequencing method has to be enabled.)", false), - DIRECT_TAG("directag", "Turn the DirecTag sequencing on or off (1: on, 0: off, default is '1'). (At least one sequencing method has to be enabled.)", false), - PNOVO("pnovo", "Turn the pNovo+ sequencing on or off (1: on, 0: off, default is '0'). (At least one sequencing method has to be enabled.)", false), - NOVOR("novor", "Turn the Novor sequencing on or off (1: on, 0: off, default is '0'). (At least one sequencing method has to be enabled.)", false), - PEPNOVO_LOCATION("pepnovo_folder", "The PepNovo+ executable, defaults to the OS dependent versions included with DeNovoGUI.", false), - DIRECTAG_LOCATION("directag_folder", "The DirecTag executable, defaults to the OS dependent versions included with DeNovoGUI.", false), - PNOVO_LOCATION("pnovo_folder", "The pNovo+ executable, defaults to the OS dependent versions included with DeNovoGUI.", false), - NOVOR_LOCATION("novor_folder", "The Novor executable, defaults to the OS dependent versions included with DeNovoGUI.", false); + DIRECT_TAG("directag", "Turn the DirecTag sequencing on or off (1: on, 0: off, default is '1'). (At least one sequencing method has to be enabled.)", false), + PNOVO("pnovo", "Turn the pNovo+ sequencing on or off (1: on, 0: off, default is '0'). (At least one sequencing method has to be enabled.)", false), + NOVOR("novor", "Turn the Novor sequencing on or off (1: on, 0: off, default is '0'). (At least one sequencing method has to be enabled.)", false), + INSTANOVO("instanovo", "Turn the InstaNovo sequencing on or off (1: on, 0: off, default is '0'). (At least one sequencing method has to be enabled.)", false), + INSTANOVO_PLUS("instanovo_plus", "Turn the InstaNovo+ sequencing on or off (1: on, 0: off, default is '0'). (At least one sequencing method has to be enabled.)", false), + INSTANOVO_REFINE("instanovo_refine", "Turn InstaNovo with refinement on or off (1: on, 0: off, default is '0'). Refinement uses InstaNovo+.", false), + PEPNOVO_LOCATION("pepnovo_folder", "The PepNovo+ executable, defaults to the OS dependent versions included with DeNovoGUI.", false), + DIRECTAG_LOCATION("directag_folder", "The DirecTag executable, defaults to the OS dependent versions included with DeNovoGUI.", false), + PNOVO_LOCATION("pnovo_folder", "The pNovo+ executable, defaults to the OS dependent versions included with DeNovoGUI.", false), + NOVOR_LOCATION("novor_folder", "The Novor executable, defaults to the OS dependent versions included with DeNovoGUI.", false), + INSTANOVO_LOCATION("instanovo_folder", "The InstaNovo checkout or installation folder. DeNovoGUI checks .venv/bin/instanovo, .venv/Scripts/instanovo(.exe), and instanovo(.exe) in this folder before falling back to PATH.", false); /** * Short Id for the CLI parameter. @@ -87,15 +91,19 @@ public static String getOptionsAsString() { output += "\n\nOptional Parameters:\n\n"; output += "-" + String.format(formatter, PEPNOVO.id) + " " + PEPNOVO.description + "\n"; output += "-" + String.format(formatter, DIRECT_TAG.id) + " " + DIRECT_TAG.description + "\n"; - output += "-" + String.format(formatter, PNOVO.id) + " " + PNOVO.description + "\n"; - output += "-" + String.format(formatter, NOVOR.id) + " " + NOVOR.description + "\n"; + output += "-" + String.format(formatter, PNOVO.id) + " " + PNOVO.description + "\n"; + output += "-" + String.format(formatter, NOVOR.id) + " " + NOVOR.description + "\n"; + output += "-" + String.format(formatter, INSTANOVO.id) + " " + INSTANOVO.description + "\n"; + output += "-" + String.format(formatter, INSTANOVO_PLUS.id) + " " + INSTANOVO_PLUS.description + "\n"; + output += "-" + String.format(formatter, INSTANOVO_REFINE.id) + " " + INSTANOVO_REFINE.description + "\n"; output += "\n\nOptional Advanced Parameters:\n\n"; output += "-" + String.format(formatter, PEPNOVO_LOCATION.id) + " " + PEPNOVO_LOCATION.description + "\n"; output += "-" + String.format(formatter, DIRECTAG_LOCATION.id) + " " + DIRECTAG_LOCATION.description + "\n"; - output += "-" + String.format(formatter, PNOVO_LOCATION.id) + " " + PNOVO_LOCATION.description + "\n"; - output += "-" + String.format(formatter, NOVOR_LOCATION.id) + " " + NOVOR_LOCATION.description + "\n"; - output += "-" + String.format(formatter, THREADS.id) + " " + THREADS.description + "\n"; + output += "-" + String.format(formatter, PNOVO_LOCATION.id) + " " + PNOVO_LOCATION.description + "\n"; + output += "-" + String.format(formatter, NOVOR_LOCATION.id) + " " + NOVOR_LOCATION.description + "\n"; + output += "-" + String.format(formatter, INSTANOVO_LOCATION.id) + " " + INSTANOVO_LOCATION.description + "\n"; + output += "-" + String.format(formatter, THREADS.id) + " " + THREADS.description + "\n"; output += "\n\nOptional Temporary Folder:\n\n"; output += "-" + String.format(formatter, PathSettingsCLIParams.ALL.id) + " " + PathSettingsCLIParams.ALL.description + "\n"; diff --git a/src/main/java/com/compomics/denovogui/cmd/DeNovoIdentificationParametersCLIParams.java b/src/main/java/com/compomics/denovogui/cmd/DeNovoIdentificationParametersCLIParams.java index b8b1333..5352fff 100644 --- a/src/main/java/com/compomics/denovogui/cmd/DeNovoIdentificationParametersCLIParams.java +++ b/src/main/java/com/compomics/denovogui/cmd/DeNovoIdentificationParametersCLIParams.java @@ -35,14 +35,13 @@ public static void createOptionsCLI(Options aOptions) { aOptions.addOption(IdentificationParametersCLIParams.MC.id, true, IdentificationParametersCLIParams.MC.description); aOptions.addOption(IdentificationParametersCLIParams.FI.id, true, IdentificationParametersCLIParams.FI.description); aOptions.addOption(IdentificationParametersCLIParams.RI.id, true, IdentificationParametersCLIParams.RI.description); - aOptions.addOption(IdentificationParametersCLIParams.DB.id, true, IdentificationParametersCLIParams.DB.description); aOptions.addOption(IdentificationParametersCLIParams.PEPNOVO_CORRECT_PREC_MASS.id, true, IdentificationParametersCLIParams.PEPNOVO_CORRECT_PREC_MASS.description); aOptions.addOption(IdentificationParametersCLIParams.PEPNOVO_DISCARD_SPECTRA.id, true, IdentificationParametersCLIParams.PEPNOVO_CORRECT_PREC_MASS.description); aOptions.addOption(IdentificationParametersCLIParams.PEPNOVO_FRAGMENTATION_MODEL.id, true, IdentificationParametersCLIParams.PEPNOVO_CORRECT_PREC_MASS.description); aOptions.addOption(IdentificationParametersCLIParams.PEPNOVO_GENERATE_BLAST.id, true, IdentificationParametersCLIParams.PEPNOVO_CORRECT_PREC_MASS.description); aOptions.addOption(IdentificationParametersCLIParams.PEPNOVO_HITLIST_LENGTH.id, true, IdentificationParametersCLIParams.PEPNOVO_CORRECT_PREC_MASS.description); - aOptions.addOption(IdentificationParametersCLIParams.PEPTNOVO_ESTIMATE_CHARGE.id, true, IdentificationParametersCLIParams.PEPNOVO_CORRECT_PREC_MASS.description); + aOptions.addOption(IdentificationParametersCLIParams.PEPNOVO_ESTIMATE_CHARGE.id, true, IdentificationParametersCLIParams.PEPNOVO_CORRECT_PREC_MASS.description); aOptions.addOption(IdentificationParametersCLIParams.DIRECTAG_ADJUST_PRECURSOR_MASS.id, true, IdentificationParametersCLIParams.DIRECTAG_ADJUST_PRECURSOR_MASS.description); aOptions.addOption(IdentificationParametersCLIParams.DIRECTAG_COMPLEMENT_MZ_TOLERANCE.id, true, IdentificationParametersCLIParams.DIRECTAG_COMPLEMENT_MZ_TOLERANCE.description); @@ -53,14 +52,14 @@ public static void createOptionsCLI(Options aOptions) { aOptions.addOption(IdentificationParametersCLIParams.DIRECTAG_ISOTOPE_MZ_TOLERANCE.id, true, IdentificationParametersCLIParams.DIRECTAG_ISOTOPE_MZ_TOLERANCE.description); aOptions.addOption(IdentificationParametersCLIParams.DIRECTAG_MAX_DYNAMIC_MODS.id, true, IdentificationParametersCLIParams.DIRECTAG_MAX_DYNAMIC_MODS.description); aOptions.addOption(IdentificationParametersCLIParams.DIRECTAG_MAX_PEAK_COUNT.id, true, IdentificationParametersCLIParams.DIRECTAG_MAX_PEAK_COUNT.description); - aOptions.addOption(IdentificationParametersCLIParams.DIRECTAG_MAX_PRECUSOR_ADJUSTMENT.id, true, IdentificationParametersCLIParams.DIRECTAG_MAX_PRECUSOR_ADJUSTMENT.description); + aOptions.addOption(IdentificationParametersCLIParams.DIRECTAG_MAX_PRECURSOR_ADJUSTMENT.id, true, IdentificationParametersCLIParams.DIRECTAG_MAX_PRECURSOR_ADJUSTMENT.description); aOptions.addOption(IdentificationParametersCLIParams.DIRECTAG_MAX_TAG_COUNT.id, true, IdentificationParametersCLIParams.DIRECTAG_MAX_TAG_COUNT.description); - aOptions.addOption(IdentificationParametersCLIParams.DIRECTAG_MIN_PRECUSOR_ADJUSTMENT.id, true, IdentificationParametersCLIParams.DIRECTAG_MIN_PRECUSOR_ADJUSTMENT.description); + aOptions.addOption(IdentificationParametersCLIParams.DIRECTAG_MIN_PRECURSOR_ADJUSTMENT.id, true, IdentificationParametersCLIParams.DIRECTAG_MIN_PRECURSOR_ADJUSTMENT.description); aOptions.addOption(IdentificationParametersCLIParams.DIRECTAG_MZ_FIDELITY_SCORE_WEIGHT.id, true, IdentificationParametersCLIParams.DIRECTAG_MZ_FIDELITY_SCORE_WEIGHT.description); aOptions.addOption(IdentificationParametersCLIParams.DIRECTAG_NUM_CHARGE_STATES.id, true, IdentificationParametersCLIParams.DIRECTAG_NUM_CHARGE_STATES.description); aOptions.addOption(IdentificationParametersCLIParams.DIRECTAG_NUM_INTENSITY_CLASSES.id, true, IdentificationParametersCLIParams.DIRECTAG_NUM_INTENSITY_CLASSES.description); aOptions.addOption(IdentificationParametersCLIParams.DIRECTAG_OUTPUT_SUFFIX.id, true, IdentificationParametersCLIParams.DIRECTAG_OUTPUT_SUFFIX.description); - aOptions.addOption(IdentificationParametersCLIParams.DIRECTAG_PRECUSOR_ADJUSTMENT_STEP.id, true, IdentificationParametersCLIParams.DIRECTAG_PRECUSOR_ADJUSTMENT_STEP.description); + aOptions.addOption(IdentificationParametersCLIParams.DIRECTAG_PRECURSOR_ADJUSTMENT_STEP.id, true, IdentificationParametersCLIParams.DIRECTAG_PRECURSOR_ADJUSTMENT_STEP.description); aOptions.addOption(IdentificationParametersCLIParams.DIRECTAG_TAG_LENGTH.id, true, IdentificationParametersCLIParams.DIRECTAG_TAG_LENGTH.description); aOptions.addOption(IdentificationParametersCLIParams.DIRECTAG_TIC_CUTOFF_PERCENTAGE.id, true, IdentificationParametersCLIParams.DIRECTAG_TIC_CUTOFF_PERCENTAGE.description); aOptions.addOption(IdentificationParametersCLIParams.DIRECTAG_USE_CHARGE_STATE_FROM_MS.id, true, IdentificationParametersCLIParams.DIRECTAG_USE_CHARGE_STATE_FROM_MS.description); @@ -102,7 +101,6 @@ public static String getOptionsAsString() { output += "-" + String.format(formatter, IdentificationParametersCLIParams.MC.id) + " " + IdentificationParametersCLIParams.MC.description + "\n"; output += "-" + String.format(formatter, IdentificationParametersCLIParams.FI.id) + " " + IdentificationParametersCLIParams.FI.description + "\n"; output += "-" + String.format(formatter, IdentificationParametersCLIParams.RI.id) + " " + IdentificationParametersCLIParams.RI.description + "\n"; - output += "-" + String.format(formatter, IdentificationParametersCLIParams.DB.id) + " " + IdentificationParametersCLIParams.DB.description + "\n"; output += "\n\nPepNovo+ Advanced Parameters:\n\n"; output += "-" + String.format(formatter, IdentificationParametersCLIParams.PEPNOVO_CORRECT_PREC_MASS.id) + " " + IdentificationParametersCLIParams.PEPNOVO_CORRECT_PREC_MASS.description + "\n"; @@ -110,7 +108,7 @@ public static String getOptionsAsString() { output += "-" + String.format(formatter, IdentificationParametersCLIParams.PEPNOVO_FRAGMENTATION_MODEL.id) + " " + IdentificationParametersCLIParams.PEPNOVO_FRAGMENTATION_MODEL.description + "\n"; output += "-" + String.format(formatter, IdentificationParametersCLIParams.PEPNOVO_GENERATE_BLAST.id) + " " + IdentificationParametersCLIParams.PEPNOVO_GENERATE_BLAST.description + "\n"; output += "-" + String.format(formatter, IdentificationParametersCLIParams.PEPNOVO_HITLIST_LENGTH.id) + " " + IdentificationParametersCLIParams.PEPNOVO_HITLIST_LENGTH.description + "\n"; - output += "-" + String.format(formatter, IdentificationParametersCLIParams.PEPTNOVO_ESTIMATE_CHARGE.id) + " " + IdentificationParametersCLIParams.PEPTNOVO_ESTIMATE_CHARGE.description + "\n"; + output += "-" + String.format(formatter, IdentificationParametersCLIParams.PEPNOVO_ESTIMATE_CHARGE.id) + " " + IdentificationParametersCLIParams.PEPNOVO_ESTIMATE_CHARGE.description + "\n"; output += "\n\nDirecTag Advanced Parameters:\n\n"; output += "-" + String.format(formatter, IdentificationParametersCLIParams.DIRECTAG_ADJUST_PRECURSOR_MASS.id) + " " + IdentificationParametersCLIParams.DIRECTAG_ADJUST_PRECURSOR_MASS.description + "\n"; @@ -122,14 +120,14 @@ public static String getOptionsAsString() { output += "-" + String.format(formatter, IdentificationParametersCLIParams.DIRECTAG_ISOTOPE_MZ_TOLERANCE.id) + " " + IdentificationParametersCLIParams.DIRECTAG_ISOTOPE_MZ_TOLERANCE.description + "\n"; output += "-" + String.format(formatter, IdentificationParametersCLIParams.DIRECTAG_MAX_DYNAMIC_MODS.id) + " " + IdentificationParametersCLIParams.DIRECTAG_MAX_DYNAMIC_MODS.description + "\n"; output += "-" + String.format(formatter, IdentificationParametersCLIParams.DIRECTAG_MAX_PEAK_COUNT.id) + " " + IdentificationParametersCLIParams.DIRECTAG_MAX_PEAK_COUNT.description + "\n"; - output += "-" + String.format(formatter, IdentificationParametersCLIParams.DIRECTAG_MAX_PRECUSOR_ADJUSTMENT.id) + " " + IdentificationParametersCLIParams.DIRECTAG_MAX_PRECUSOR_ADJUSTMENT.description + "\n"; + output += "-" + String.format(formatter, IdentificationParametersCLIParams.DIRECTAG_MAX_PRECURSOR_ADJUSTMENT.id) + " " + IdentificationParametersCLIParams.DIRECTAG_MAX_PRECURSOR_ADJUSTMENT.description + "\n"; output += "-" + String.format(formatter, IdentificationParametersCLIParams.DIRECTAG_MAX_TAG_COUNT.id) + " " + IdentificationParametersCLIParams.DIRECTAG_MAX_TAG_COUNT.description + "\n"; - output += "-" + String.format(formatter, IdentificationParametersCLIParams.DIRECTAG_MIN_PRECUSOR_ADJUSTMENT.id) + " " + IdentificationParametersCLIParams.DIRECTAG_MIN_PRECUSOR_ADJUSTMENT.description + "\n"; + output += "-" + String.format(formatter, IdentificationParametersCLIParams.DIRECTAG_MIN_PRECURSOR_ADJUSTMENT.id) + " " + IdentificationParametersCLIParams.DIRECTAG_MIN_PRECURSOR_ADJUSTMENT.description + "\n"; output += "-" + String.format(formatter, IdentificationParametersCLIParams.DIRECTAG_MZ_FIDELITY_SCORE_WEIGHT.id) + " " + IdentificationParametersCLIParams.DIRECTAG_MZ_FIDELITY_SCORE_WEIGHT.description + "\n"; output += "-" + String.format(formatter, IdentificationParametersCLIParams.DIRECTAG_NUM_CHARGE_STATES.id) + " " + IdentificationParametersCLIParams.DIRECTAG_NUM_CHARGE_STATES.description + "\n"; output += "-" + String.format(formatter, IdentificationParametersCLIParams.DIRECTAG_NUM_INTENSITY_CLASSES.id) + " " + IdentificationParametersCLIParams.DIRECTAG_NUM_INTENSITY_CLASSES.description + "\n"; output += "-" + String.format(formatter, IdentificationParametersCLIParams.DIRECTAG_OUTPUT_SUFFIX.id) + " " + IdentificationParametersCLIParams.DIRECTAG_OUTPUT_SUFFIX.description + "\n"; - output += "-" + String.format(formatter, IdentificationParametersCLIParams.DIRECTAG_PRECUSOR_ADJUSTMENT_STEP.id) + " " + IdentificationParametersCLIParams.DIRECTAG_PRECUSOR_ADJUSTMENT_STEP.description + "\n"; + output += "-" + String.format(formatter, IdentificationParametersCLIParams.DIRECTAG_PRECURSOR_ADJUSTMENT_STEP.id) + " " + IdentificationParametersCLIParams.DIRECTAG_PRECURSOR_ADJUSTMENT_STEP.description + "\n"; output += "-" + String.format(formatter, IdentificationParametersCLIParams.DIRECTAG_TAG_LENGTH.id) + " " + IdentificationParametersCLIParams.DIRECTAG_ADJUST_PRECURSOR_MASS.description + "\n"; output += "-" + String.format(formatter, IdentificationParametersCLIParams.DIRECTAG_TIC_CUTOFF_PERCENTAGE.id) + " " + IdentificationParametersCLIParams.DIRECTAG_TIC_CUTOFF_PERCENTAGE.description + "\n"; output += "-" + String.format(formatter, IdentificationParametersCLIParams.DIRECTAG_USE_CHARGE_STATE_FROM_MS.id) + " " + IdentificationParametersCLIParams.DIRECTAG_USE_CHARGE_STATE_FROM_MS.description + "\n"; diff --git a/src/main/java/com/compomics/denovogui/cmd/PathSettingsCLI.java b/src/main/java/com/compomics/denovogui/cmd/PathSettingsCLI.java index 7c2c132..1317560 100644 --- a/src/main/java/com/compomics/denovogui/cmd/PathSettingsCLI.java +++ b/src/main/java/com/compomics/denovogui/cmd/PathSettingsCLI.java @@ -2,14 +2,14 @@ import com.compomics.denovogui.DeNovoGUIWrapper; import com.compomics.denovogui.preferences.DeNovoGUIPathPreferences; -import com.compomics.software.settings.UtilitiesPathPreferences; +import com.compomics.software.settings.UtilitiesPathParameters; import com.compomics.util.gui.waiting.waitinghandlers.WaitingHandlerCLIImpl; import com.compomics.util.waiting.WaitingHandler; import java.io.File; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; -import org.apache.commons.cli.BasicParser; +import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; @@ -81,14 +81,14 @@ public void setPathSettings() { try { DeNovoGUIPathPreferences.DeNovoGUIPathKey denovoguiPathKey = DeNovoGUIPathPreferences.DeNovoGUIPathKey.getKeyFromId(id); if (denovoguiPathKey == null) { - UtilitiesPathPreferences.UtilitiesPathKey utilitiesPathKey = UtilitiesPathPreferences.UtilitiesPathKey.getKeyFromId(id); + UtilitiesPathParameters.UtilitiesPathKey utilitiesPathKey = UtilitiesPathParameters.UtilitiesPathKey.getKeyFromId(id); if (utilitiesPathKey == null) { System.out.println("Path id " + id + " not recognized."); } else { - UtilitiesPathPreferences.setPathPreference(utilitiesPathKey, pathInput.get(id)); + UtilitiesPathParameters.setPathParameter(utilitiesPathKey, pathInput.get(id)); } } else { - DeNovoGUIPathPreferences.setPathPreference(denovoguiPathKey, pathInput.get(id)); + DeNovoGUIPathPreferences.setPathParameter(denovoguiPathKey, pathInput.get(id)); } } catch (Exception e) { System.out.println("An error occurred when setting the path " + id + "."); @@ -98,7 +98,7 @@ public void setPathSettings() { } // Write path file preference - File destinationFile = new File(getJarFilePath(), UtilitiesPathPreferences.configurationFileName); + File destinationFile = new File(getJarFilePath(), UtilitiesPathParameters.configurationFileName); try { DeNovoGUIPathPreferences.writeConfigurationToFile(destinationFile); } catch (Exception e) { @@ -151,7 +151,7 @@ public static void main(String[] args) { try { Options lOptions = new Options(); PathSettingsCLIParams.createOptionsCLI(lOptions); - BasicParser parser = new BasicParser(); + DefaultParser parser = new DefaultParser(); CommandLine line = parser.parse(lOptions, args); if (args.length == 0) { @@ -237,7 +237,7 @@ public static String[] extractAndUpdatePathOptions(String[] args) throws ParseEx // update the paths if needed Options pathOptions = new Options(); PathSettingsCLIParams.createOptionsCLI(pathOptions); - BasicParser parser = new BasicParser(); + DefaultParser parser = new DefaultParser(); CommandLine line = parser.parse(pathOptions, pathSettingArgsAsList); PathSettingsCLIInputBean pathSettingsCLIInputBean = new PathSettingsCLIInputBean(line); PathSettingsCLI pathSettingsCLI = new PathSettingsCLI(pathSettingsCLIInputBean); diff --git a/src/main/java/com/compomics/denovogui/cmd/PathSettingsCLIInputBean.java b/src/main/java/com/compomics/denovogui/cmd/PathSettingsCLIInputBean.java index 01debe9..834d958 100644 --- a/src/main/java/com/compomics/denovogui/cmd/PathSettingsCLIInputBean.java +++ b/src/main/java/com/compomics/denovogui/cmd/PathSettingsCLIInputBean.java @@ -1,7 +1,7 @@ package com.compomics.denovogui.cmd; import com.compomics.denovogui.preferences.DeNovoGUIPathPreferences; -import com.compomics.software.settings.UtilitiesPathPreferences; +import com.compomics.software.settings.UtilitiesPathParameters; import java.io.File; import java.util.HashMap; import org.apache.commons.cli.CommandLine; @@ -47,7 +47,7 @@ public PathSettingsCLIInputBean(CommandLine aLine) { paths.put(id, aLine.getOptionValue(id)); } } - for (UtilitiesPathPreferences.UtilitiesPathKey utilitiesPathKey : UtilitiesPathPreferences.UtilitiesPathKey.values()) { + for (UtilitiesPathParameters.UtilitiesPathKey utilitiesPathKey : UtilitiesPathParameters.UtilitiesPathKey.values()) { String id = utilitiesPathKey.getId(); if (aLine.hasOption(id)) { paths.put(id, aLine.getOptionValue(id)); diff --git a/src/main/java/com/compomics/denovogui/cmd/PathSettingsCLIParams.java b/src/main/java/com/compomics/denovogui/cmd/PathSettingsCLIParams.java index e74f494..885f6e3 100644 --- a/src/main/java/com/compomics/denovogui/cmd/PathSettingsCLIParams.java +++ b/src/main/java/com/compomics/denovogui/cmd/PathSettingsCLIParams.java @@ -1,7 +1,7 @@ package com.compomics.denovogui.cmd; import com.compomics.denovogui.preferences.DeNovoGUIPathPreferences; -import com.compomics.software.settings.UtilitiesPathPreferences; +import com.compomics.software.settings.UtilitiesPathParameters; import java.util.ArrayList; import org.apache.commons.cli.Options; @@ -47,7 +47,7 @@ public static void createOptionsCLI(Options aOptions) { for (DeNovoGUIPathPreferences.DeNovoGUIPathKey denovoguiPathKey : DeNovoGUIPathPreferences.DeNovoGUIPathKey.values()) { aOptions.addOption(denovoguiPathKey.getId(), true, denovoguiPathKey.getDescription()); } - for (UtilitiesPathPreferences.UtilitiesPathKey utilitiesPathKey : UtilitiesPathPreferences.UtilitiesPathKey.values()) { + for (UtilitiesPathParameters.UtilitiesPathKey utilitiesPathKey : UtilitiesPathParameters.UtilitiesPathKey.values()) { aOptions.addOption(utilitiesPathKey.getId(), true, utilitiesPathKey.getDescription()); } } @@ -67,7 +67,7 @@ public static ArrayList getOptionIDs() { for (DeNovoGUIPathPreferences.DeNovoGUIPathKey denovoguiPathKey : DeNovoGUIPathPreferences.DeNovoGUIPathKey.values()) { options.add("-" + denovoguiPathKey.getId()); } - for (UtilitiesPathPreferences.UtilitiesPathKey utilitiesPathKey : UtilitiesPathPreferences.UtilitiesPathKey.values()) { + for (UtilitiesPathParameters.UtilitiesPathKey utilitiesPathKey : UtilitiesPathParameters.UtilitiesPathKey.values()) { options.add("-" + utilitiesPathKey.getId()); } @@ -94,7 +94,7 @@ public static String getOptionsAsString() { for (DeNovoGUIPathPreferences.DeNovoGUIPathKey denovoguiPathKey : DeNovoGUIPathPreferences.DeNovoGUIPathKey.values()) { output += "-" + String.format(formatter, denovoguiPathKey.getId()) + " " + denovoguiPathKey.getDescription() + System.getProperty("line.separator"); } - for (UtilitiesPathPreferences.UtilitiesPathKey utilitiesPathKey : UtilitiesPathPreferences.UtilitiesPathKey.values()) { + for (UtilitiesPathParameters.UtilitiesPathKey utilitiesPathKey : UtilitiesPathParameters.UtilitiesPathKey.values()) { output += "-" + String.format(formatter, utilitiesPathKey.getId()) + " " + utilitiesPathKey.getDescription() + System.getProperty("line.separator"); } diff --git a/src/main/java/com/compomics/denovogui/execution/Job.java b/src/main/java/com/compomics/denovogui/execution/Job.java index 811b491..89e6912 100644 --- a/src/main/java/com/compomics/denovogui/execution/Job.java +++ b/src/main/java/com/compomics/denovogui/execution/Job.java @@ -1,7 +1,9 @@ package com.compomics.denovogui.execution; + +import com.compomics.denovogui.io.SpectrumFactory; import com.compomics.util.exceptions.ExceptionHandler; -import com.compomics.util.experiment.massspectrometry.SpectrumFactory; +import com.compomics.util.experiment.mass_spectrometry.SpectrumProvider; import com.compomics.util.waiting.WaitingHandler; import java.io.BufferedWriter; import java.io.File; @@ -9,7 +11,8 @@ import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; /** * Abstract class of a job to be executed. Implements the interface Executable @@ -59,7 +62,7 @@ public abstract class Job implements Executable, Runnable { /** * Init the job logger. */ - protected static Logger log = Logger.getLogger(Job.class); + protected static Logger log = LogManager.getLogger(Job.class); /** * Waiting handler displaying feedback to the user. */ diff --git a/src/main/java/com/compomics/denovogui/execution/jobs/DirecTagJob.java b/src/main/java/com/compomics/denovogui/execution/jobs/DirecTagJob.java index 424fe81..4546e0d 100644 --- a/src/main/java/com/compomics/denovogui/execution/jobs/DirecTagJob.java +++ b/src/main/java/com/compomics/denovogui/execution/jobs/DirecTagJob.java @@ -4,12 +4,12 @@ import com.compomics.software.cli.CommandLineUtils; import com.compomics.util.Util; import com.compomics.util.exceptions.ExceptionHandler; -import com.compomics.util.experiment.biology.PTM; -import com.compomics.util.experiment.biology.PTMFactory; +import com.compomics.util.experiment.biology.modifications.Modification; +import com.compomics.util.experiment.biology.modifications.ModificationFactory; import com.compomics.util.experiment.identification.Advocate; -import com.compomics.util.experiment.identification.identification_parameters.SearchParameters; -import com.compomics.util.experiment.identification.identification_parameters.tool_specific.DirecTagParameters; -import com.compomics.util.preferences.IdentificationParameters; +import com.compomics.util.parameters.identification.search.SearchParameters; +import com.compomics.util.parameters.identification.tool_specific.DirecTagParameters; +import com.compomics.util.parameters.identification.IdentificationParameters; import com.compomics.util.waiting.WaitingHandler; import java.io.File; import java.util.ArrayList; @@ -37,7 +37,7 @@ public class DirecTagJob extends Job { /** * The post translational modifications factory. */ - private PTMFactory ptmFactory = PTMFactory.getInstance(); + private ModificationFactory ptmFactory = ModificationFactory.getInstance(); /** * The path to the executable. */ @@ -105,10 +105,10 @@ private void initJob() { // add fixed mods String fixedModsAsString = ""; - ArrayList fixedPtms = searchParameters.getPtmSettings().getFixedModifications(); + ArrayList fixedPtms = searchParameters.getModificationParameters().getFixedModifications(); for (String ptmName : fixedPtms) { - PTM ptm = ptmFactory.getPTM(ptmName); - if (ptm.getType() == PTM.MODAA) { + Modification ptm = ptmFactory.getModification(ptmName); + if (ptm.getType() == Modification.MODAA) { fixedModsAsString += getFixedPtmFormattedForDirecTag(ptmName); } } @@ -121,10 +121,10 @@ private void initJob() { // add variable mods ArrayList utilitiesPtms = new ArrayList(); String variableModsAsString = ""; - ArrayList variablePtms = searchParameters.getPtmSettings().getVariableModifications(); + ArrayList variablePtms = searchParameters.getModificationParameters().getVariableModifications(); for (String ptmName : variablePtms) { - PTM ptm = ptmFactory.getPTM(ptmName); - if (ptm.getType() == PTM.MODAA) { + Modification ptm = ptmFactory.getModification(ptmName); + if (ptm.getType() == Modification.MODAA) { variableModsAsString += getVariablePtmFormattedForDirecTag(ptmName, utilitiesPtms); } } @@ -286,15 +286,15 @@ public void run() { /** * Get the given modification as a string in the DirecTag format. * - * @param ptmName the utilities name of the PTM + * @param ptmName the utilities name of the Modification * @param utilitiesPtms the list of utilities PTMs, index is the index used - * in the DirecTag output (note that the same PTM may occur more than once - * in the list as multiple DirecTag PTM can map to the same utilities PTM) + * in the DirecTag output (note that the same Modification may occur more than once + * in the list as multiple DirecTag Modification can map to the same utilities Modification) * @return the given modification as a string in the DirecTag format */ private String getVariablePtmFormattedForDirecTag(String ptmName, ArrayList utilitiesPtms) { - PTM tempPtm = ptmFactory.getPTM(ptmName); + Modification tempPtm = ptmFactory.getModification(ptmName); String ptmAsString = ""; // get the targeted amino acids @@ -312,12 +312,12 @@ private String getVariablePtmFormattedForDirecTag(String ptmName, ArrayList getCommand() { + return new ArrayList(procCommands); + } + + @Override + public void run() { + + proc = null; + + try { + proc = procBuilder.start(); + setStatus(JobStatus.RUNNING); + } catch (IOException e) { + setStatus(JobStatus.ERROR); + setError(e.getMessage()); + waitingHandler.appendReport("Could not start " + getDescription() + "!", true, true); + waitingHandler.appendReportEndLine(); + waitingHandler.setRunCanceled(); + exceptionHandler.catchException(e); + return; + } + + Scanner scanner = new Scanner(proc.getInputStream()); + + try { + while (scanner.hasNextLine() && !waitingHandler.isRunCanceled()) { + waitingHandler.appendReport(scanner.nextLine(), false, true); + } + + int exitCode = proc.waitFor(); + + if (exitCode == 0 && !waitingHandler.isRunCanceled()) { + setStatus(JobStatus.FINISHED); + } else if (!waitingHandler.isRunCanceled()) { + String errorMessage = getDescription() + " exited with status " + exitCode + "."; + setStatus(JobStatus.ERROR); + setError(errorMessage); + waitingHandler.appendReport(errorMessage, true, true); + waitingHandler.setRunCanceled(); + } + } catch (InterruptedException e) { + if (!waitingHandler.isRunCanceled()) { + setStatus(JobStatus.ERROR); + setError(e.getMessage()); + exceptionHandler.catchException(e); + waitingHandler.setRunCanceled(); + } + } finally { + scanner.close(); + if (waitingHandler.isRunCanceled() && proc != null) { + proc.destroy(); + } + } + } + + @Override + public void cancel() { + if (proc != null) { + proc.destroy(); + log.info(">> De novo sequencing has been canceled."); + } + } + + @Override + public void writeCommand() { + System.out.println(System.getProperty("line.separator") + System.getProperty("line.separator") + getDescription() + " command: " + command + System.getProperty("line.separator")); + } +} diff --git a/src/main/java/com/compomics/denovogui/execution/jobs/NovorJob.java b/src/main/java/com/compomics/denovogui/execution/jobs/NovorJob.java index 5beb4b7..1f47aaa 100644 --- a/src/main/java/com/compomics/denovogui/execution/jobs/NovorJob.java +++ b/src/main/java/com/compomics/denovogui/execution/jobs/NovorJob.java @@ -4,13 +4,13 @@ import com.compomics.software.cli.CommandLineUtils; import com.compomics.software.CompomicsWrapper; import com.compomics.util.exceptions.ExceptionHandler; -import com.compomics.util.experiment.biology.PTM; -import com.compomics.util.experiment.biology.PTMFactory; +import com.compomics.util.experiment.biology.modifications.Modification; +import com.compomics.util.experiment.biology.modifications.ModificationFactory; import com.compomics.util.experiment.identification.Advocate; -import com.compomics.util.experiment.identification.identification_parameters.SearchParameters; -import com.compomics.util.experiment.identification.identification_parameters.tool_specific.NovorParameters; -import com.compomics.util.preferences.IdentificationParameters; -import com.compomics.util.preferences.UtilitiesUserPreferences; +import com.compomics.util.parameters.identification.search.SearchParameters; +import com.compomics.util.parameters.identification.tool_specific.NovorParameters; +import com.compomics.util.parameters.identification.IdentificationParameters; +import com.compomics.util.parameters.UtilitiesUserParameters; import com.compomics.util.waiting.WaitingHandler; import java.io.BufferedWriter; import java.io.File; @@ -65,10 +65,10 @@ public class NovorJob extends Job { /** * The post translational modifications factory. */ - private PTMFactory ptmFactory = PTMFactory.getInstance(); + private ModificationFactory ptmFactory = ModificationFactory.getInstance(); /** - * The Novor to utilities PTM map. Key: Novor PTM short name, element: - * utilities PTM name. + * The Novor to utilities Modification map. Key: Novor Modification short name, element: + * utilities Modification name. */ private HashMap novorPtmMap; @@ -104,9 +104,9 @@ private void initJob(boolean isCommandLine) { novorExecutable.setExecutable(true); // set java home - UtilitiesUserPreferences utilitiesUserPreferences = UtilitiesUserPreferences.loadUserPreferences(); + UtilitiesUserParameters utilitiesUserParameters = UtilitiesUserParameters.loadUserParameters(); CompomicsWrapper wrapper = new CompomicsWrapper(); - ArrayList javaHomeAndOptions = wrapper.getJavaHomeAndOptions(utilitiesUserPreferences.getDeNovoGuiPath()); + ArrayList javaHomeAndOptions = wrapper.getJavaHomeAndOptions(utilitiesUserParameters.getDeNovoGuiPath()); procCommands.add(javaHomeAndOptions.get(0)); // set java home // set java options @@ -248,12 +248,12 @@ private void createParameterFile() { novorPtmMap = new HashMap(); // variable modifications - if (!searchParameters.getPtmSettings().getVariableModifications().isEmpty()) { + if (!searchParameters.getModificationParameters().getVariableModifications().isEmpty()) { bufferedParameterWriter.write("# Variable modifications" + System.getProperty("line.separator")); String variableModsAsString = ""; - for (String variableModification : searchParameters.getPtmSettings().getVariableModifications()) { - PTM ptm = ptmFactory.getPTM(variableModification); + for (String variableModification : searchParameters.getModificationParameters().getVariableModifications()) { + Modification ptm = ptmFactory.getModification(variableModification); addModification(bufferedModsWriter, ptm); // update the modifications string @@ -269,12 +269,12 @@ private void createParameterFile() { } // fixed modifications - if (!searchParameters.getPtmSettings().getFixedModifications().isEmpty()) { + if (!searchParameters.getModificationParameters().getFixedModifications().isEmpty()) { bufferedParameterWriter.write("# Fixed modifications" + System.getProperty("line.separator")); String fixedModsAsString = ""; - for (String fixedModification : searchParameters.getPtmSettings().getFixedModifications()) { - PTM ptm = ptmFactory.getPTM(fixedModification); + for (String fixedModification : searchParameters.getModificationParameters().getFixedModifications()) { + Modification ptm = ptmFactory.getModification(fixedModification); addModification(bufferedModsWriter, ptm); // update the modifications string @@ -316,11 +316,11 @@ private void createParameterFile() { * Converts a modification to the Novor format. * * @param bufferedModsWriter the writer to add the modification to - * @param ptm the current PTM + * @param ptm the current Modification * @param modsAsString the current modifications as a string * @throws IOException thrown if an IOException occurs */ - private void addModification(BufferedWriter bufferedModsWriter, PTM ptm) throws IOException { + private void addModification(BufferedWriter bufferedModsWriter, Modification ptm) throws IOException { // modification id bufferedModsWriter.write(ptm.getName() + ", "); @@ -334,13 +334,13 @@ private void addModification(BufferedWriter bufferedModsWriter, PTM ptm) throws // the groups involved in the modification if (ptm.isNTerm()) { - if (ptm.getType() == PTM.MODNAA || ptm.getType() == PTM.MODNPAA) { + if (ptm.getType() == Modification.MODNAA || ptm.getType() == Modification.MODNPAA) { bufferedModsWriter.write("nr-, "); } else { bufferedModsWriter.write("n--, "); } } else if (ptm.isCTerm()) { - if (ptm.getType() == PTM.MODCAA || ptm.getType() == PTM.MODCPAA) { + if (ptm.getType() == Modification.MODCAA || ptm.getType() == Modification.MODCPAA) { bufferedModsWriter.write("-rc, "); } else { bufferedModsWriter.write("--c, "); diff --git a/src/main/java/com/compomics/denovogui/execution/jobs/PNovoJob.java b/src/main/java/com/compomics/denovogui/execution/jobs/PNovoJob.java index fccc2b6..959fe2d 100644 --- a/src/main/java/com/compomics/denovogui/execution/jobs/PNovoJob.java +++ b/src/main/java/com/compomics/denovogui/execution/jobs/PNovoJob.java @@ -2,14 +2,14 @@ import com.compomics.denovogui.execution.Job; import com.compomics.util.exceptions.ExceptionHandler; -import com.compomics.util.experiment.biology.AminoAcid; -import com.compomics.util.experiment.biology.Enzyme; -import com.compomics.util.experiment.biology.PTM; -import com.compomics.util.experiment.biology.PTMFactory; +import com.compomics.util.experiment.biology.aminoacids.AminoAcid; +import com.compomics.util.experiment.biology.enzymes.Enzyme; +import com.compomics.util.experiment.biology.modifications.Modification; +import com.compomics.util.experiment.biology.modifications.ModificationFactory; import com.compomics.util.experiment.identification.Advocate; -import com.compomics.util.experiment.identification.identification_parameters.SearchParameters; -import com.compomics.util.experiment.identification.identification_parameters.tool_specific.PNovoParameters; -import com.compomics.util.preferences.DigestionPreferences; +import com.compomics.util.parameters.identification.search.SearchParameters; +import com.compomics.util.parameters.identification.tool_specific.PNovoParameters; +import com.compomics.util.parameters.identification.search.DigestionParameters; import com.compomics.util.waiting.WaitingHandler; import java.io.BufferedWriter; import java.io.File; @@ -56,7 +56,7 @@ public class PNovoJob extends Job { /** * The post translational modifications factory. */ - private PTMFactory ptmFactory = PTMFactory.getInstance(); + private ModificationFactory ptmFactory = ModificationFactory.getInstance(); /** * The number of threads. */ @@ -217,7 +217,7 @@ private void createParameterFile() { int variableModCount = 0; // add the variable modifications - if (!searchParameters.getPtmSettings().getVariableModifications().isEmpty()) { + if (!searchParameters.getModificationParameters().getVariableModifications().isEmpty()) { br.write("#variable modifications" + System.getProperty("line.separator")); } @@ -226,14 +226,14 @@ private void createParameterFile() { HashMap modificationLetterToResidueMap = new HashMap(); // variable modifications targetting specific amino acids - if (!searchParameters.getPtmSettings().getVariableModifications().isEmpty()) { - for (String variableModification : searchParameters.getPtmSettings().getVariableModifications()) { - PTM ptm = ptmFactory.getPTM(variableModification); + if (!searchParameters.getModificationParameters().getVariableModifications().isEmpty()) { + for (String variableModification : searchParameters.getModificationParameters().getVariableModifications()) { + Modification ptm = ptmFactory.getModification(variableModification); if (!ptm.isCTerm() && !ptm.isNTerm() && ptm.getPattern() != null) { for (Character target : ptm.getPattern().getAminoAcidsAtTarget()) { if (variableModCount > variableModificationsCharacters.length) { - System.out.println("The number of variable PTM targets have to be smaller than " + variableModificationsCharacters.length + "!"); // @TODO: handle this better! + System.out.println("The number of variable Modification targets have to be smaller than " + variableModificationsCharacters.length + "!"); // @TODO: handle this better! break; } @@ -250,9 +250,9 @@ private void createParameterFile() { pNovoParameters.setPNovoPtmResiduesMap(modificationLetterToResidueMap); // variable modifications targetting the n or c term - if (!searchParameters.getPtmSettings().getVariableModifications().isEmpty()) { - for (String variableModification : searchParameters.getPtmSettings().getVariableModifications()) { - PTM ptm = ptmFactory.getPTM(variableModification); + if (!searchParameters.getModificationParameters().getVariableModifications().isEmpty()) { + for (String variableModification : searchParameters.getModificationParameters().getVariableModifications()) { + Modification ptm = ptmFactory.getModification(variableModification); if (ptm.isNTerm()) { br.write("n-term=" + ptm.getRoundedMass() + System.getProperty("line.separator")); } else if (ptm.isCTerm()) { @@ -264,11 +264,11 @@ private void createParameterFile() { } // add the fixed modifications - if (!searchParameters.getPtmSettings().getFixedModifications().isEmpty()) { + if (!searchParameters.getModificationParameters().getFixedModifications().isEmpty()) { br.write(System.getProperty("line.separator") + "#fixed modifications" + System.getProperty("line.separator")); - for (String fixedModification : searchParameters.getPtmSettings().getFixedModifications()) { - PTM ptm = ptmFactory.getPTM(fixedModification); + for (String fixedModification : searchParameters.getModificationParameters().getFixedModifications()) { + Modification ptm = ptmFactory.getModification(fixedModification); if (ptm.getPattern() != null) { for (Character target : ptm.getPattern().getAminoAcidsAtTarget()) { br.write(target + "=" + (AminoAcid.getAminoAcid(target).getMonoisotopicMass() + ptm.getRoundedMass()) + System.getProperty("line.separator")); @@ -296,8 +296,8 @@ private void createParameterFile() { br.write("ETDIONTYPE6=z 2 0 0 1.99129206512" + System.getProperty("line.separator")); // @TODO: should these be editable..? // set the enzyme - DigestionPreferences digestionPreferences = searchParameters.getDigestionPreferences(); - if (digestionPreferences.getCleavagePreference() == DigestionPreferences.CleavagePreference.enzyme) { + DigestionParameters digestionPreferences = searchParameters.getDigestionParameters(); + if (digestionPreferences.getCleavagePreference() == DigestionParameters.CleavagePreference.enzyme) { br.write("enzyme=" + getPNovoEnzyme(digestionPreferences.getEnzymes().get(0)) + System.getProperty("line.separator")); // @TODO: will this one ever be used? as an enzyme is not usually set? } diff --git a/src/main/java/com/compomics/denovogui/execution/jobs/PepNovoJob.java b/src/main/java/com/compomics/denovogui/execution/jobs/PepNovoJob.java index be67d83..5bb4000 100644 --- a/src/main/java/com/compomics/denovogui/execution/jobs/PepNovoJob.java +++ b/src/main/java/com/compomics/denovogui/execution/jobs/PepNovoJob.java @@ -5,9 +5,9 @@ import com.compomics.denovogui.io.PepNovoModificationFile; import com.compomics.util.exceptions.ExceptionHandler; import com.compomics.util.experiment.identification.Advocate; -import com.compomics.util.experiment.identification.identification_parameters.SearchParameters; -import com.compomics.util.experiment.identification.identification_parameters.tool_specific.PepnovoParameters; -import com.compomics.util.preferences.IdentificationParameters; +import com.compomics.util.parameters.identification.search.SearchParameters; +import com.compomics.util.parameters.identification.tool_specific.PepnovoParameters; +import com.compomics.util.parameters.identification.IdentificationParameters; import com.compomics.util.waiting.WaitingHandler; import java.io.File; import java.util.ArrayList; @@ -96,10 +96,10 @@ private void initJob() { procCommands.add(pepNovoParameters.getFragmentationModel()); // Add modifications - ArrayList modifications = searchParameters.getPtmSettings().getAllModifications(); + ArrayList modifications = searchParameters.getModificationParameters().getAllModifications(); if (!modifications.isEmpty()) { procCommands.add("-PTMs"); - procCommands.add(PepNovoModificationFile.getModsString(searchParameters.getPtmSettings().getAllModifications())); + procCommands.add(PepNovoModificationFile.getModsString(searchParameters.getModificationParameters().getAllModifications())); } // Add fragment tolerance diff --git a/src/main/java/com/compomics/denovogui/gui/AnnotationPreferencesDialog.java b/src/main/java/com/compomics/denovogui/gui/AnnotationPreferencesDialog.java index 178734b..16cdfe7 100644 --- a/src/main/java/com/compomics/denovogui/gui/AnnotationPreferencesDialog.java +++ b/src/main/java/com/compomics/denovogui/gui/AnnotationPreferencesDialog.java @@ -1,7 +1,7 @@ package com.compomics.denovogui.gui; import com.compomics.util.gui.error_handlers.HelpDialog; -import com.compomics.util.experiment.identification.spectrum_annotation.AnnotationSettings; +import com.compomics.util.experiment.identification.spectrum_annotation.AnnotationParameters; import java.awt.Toolkit; /** @@ -15,7 +15,7 @@ public class AnnotationPreferencesDialog extends javax.swing.JDialog { /** * The annotation preferences. */ - private AnnotationSettings annotationPreferences; + private AnnotationParameters annotationPreferences; /** * The ResultsFrame parent. */ diff --git a/src/main/java/com/compomics/denovogui/gui/DeNovoGUI.java b/src/main/java/com/compomics/denovogui/gui/DeNovoGUI.java index fbe232b..0bf5277 100644 --- a/src/main/java/com/compomics/denovogui/gui/DeNovoGUI.java +++ b/src/main/java/com/compomics/denovogui/gui/DeNovoGUI.java @@ -1,14 +1,18 @@ package com.compomics.denovogui.gui; - -import com.compomics.denovogui.DeNovoSequencingHandler; -import com.compomics.denovogui.DeNovoGUIWrapper; -import com.compomics.denovogui.execution.jobs.PepNovoJob; -import com.compomics.denovogui.util.Properties; + +import com.compomics.denovogui.io.SpectrumFactory; + +import com.compomics.denovogui.DeNovoSequencingHandler; +import com.compomics.denovogui.DeNovoGUIWrapper; +import com.compomics.denovogui.execution.jobs.InstaNovoJob; +import com.compomics.denovogui.execution.jobs.PepNovoJob; +import com.compomics.denovogui.util.InstaNovoSetup; +import com.compomics.denovogui.util.Properties; import com.compomics.software.cli.CommandLineUtils; import com.compomics.software.ToolFactory; -import com.compomics.util.experiment.biology.EnzymeFactory; -import com.compomics.util.experiment.biology.PTMFactory; -import com.compomics.util.experiment.identification.identification_parameters.SearchParameters; +import com.compomics.util.experiment.biology.enzymes.EnzymeFactory; +import com.compomics.util.experiment.biology.modifications.ModificationFactory; +import com.compomics.util.parameters.identification.search.SearchParameters; import com.compomics.denovogui.io.FileProcessor; import com.compomics.denovogui.preferences.DeNovoGUIPathPreferences; import com.compomics.denovogui.preferences.DeNovoGUIPathPreferences.DeNovoGUIPathKey; @@ -16,47 +20,54 @@ import com.compomics.software.CompomicsWrapper; import com.compomics.software.autoupdater.MavenJarFile; import com.compomics.software.dialogs.JavaHomeOrMemoryDialogParent; -import com.compomics.software.dialogs.JavaSettingsDialog; +import com.compomics.software.dialogs.JavaParametersDialog; import com.compomics.software.settings.PathKey; -import com.compomics.software.settings.UtilitiesPathPreferences; -import com.compomics.software.settings.gui.PathSettingsDialog; +import com.compomics.software.settings.UtilitiesPathParameters; +import com.compomics.software.settings.gui.PathParametersDialog; import com.compomics.util.Util; import com.compomics.util.exceptions.exception_handlers.FrameExceptionHandler; import com.compomics.util.exceptions.exception_handlers.WaitingDialogExceptionHandler; -import com.compomics.util.experiment.biology.PTM; +import com.compomics.util.experiment.biology.modifications.Modification; import com.compomics.util.experiment.identification.Advocate; -import com.compomics.util.experiment.identification.identification_parameters.tool_specific.DirecTagParameters; -import com.compomics.util.experiment.identification.identification_parameters.tool_specific.NovorParameters; -import com.compomics.util.experiment.identification.identification_parameters.tool_specific.PNovoParameters; -import com.compomics.util.experiment.identification.identification_parameters.tool_specific.PepnovoParameters; -import com.compomics.util.experiment.massspectrometry.SpectrumFactory; -import com.compomics.util.gui.PrivacySettingsDialog; +import com.compomics.util.parameters.identification.tool_specific.DirecTagParameters; +import com.compomics.util.parameters.identification.tool_specific.InstaNovoParameters; +import com.compomics.util.parameters.identification.tool_specific.InstaNovoPlusParameters; +import com.compomics.util.parameters.identification.tool_specific.NovorParameters; +import com.compomics.util.parameters.identification.tool_specific.PNovoParameters; +import com.compomics.util.parameters.identification.tool_specific.PepnovoParameters; +import com.compomics.util.experiment.mass_spectrometry.SpectrumProvider; +import com.compomics.util.gui.PrivacyParametersDialog; import com.compomics.util.gui.UtilitiesGUIDefaults; import com.compomics.util.gui.error_handlers.BugReport; import com.compomics.util.gui.error_handlers.HelpDialog; -import com.compomics.util.gui.parameters.identification_parameters.SearchSettingsDialog; -import com.compomics.util.gui.parameters.identification_parameters.algorithm_settings.DirecTagSettingsDialog; -import com.compomics.util.gui.parameters.identification_parameters.algorithm_settings.NovorSettingsDialog; -import com.compomics.util.gui.parameters.identification_parameters.algorithm_settings.PNovoSettingsDialog; -import com.compomics.util.gui.parameters.identification_parameters.algorithm_settings.PepNovoSettingsDialog; -import com.compomics.util.gui.ptm.ModificationsDialog; +import com.compomics.util.gui.parameters.identification.search.SearchParametersDialog; +import com.compomics.util.gui.parameters.identification.algorithm.DirecTagParametersDialog; +import com.compomics.util.gui.parameters.identification.algorithm.NovorParametersDialog; +import com.compomics.util.gui.parameters.identification.algorithm.PNovoParametersDialog; +import com.compomics.util.gui.parameters.identification.algorithm.PepNovoParametersDialog; +import com.compomics.util.gui.modification.ModificationsDialog; import com.compomics.util.gui.waiting.waitinghandlers.ProgressDialogX; import com.compomics.util.waiting.WaitingActionListener; import com.compomics.util.waiting.WaitingHandler; import com.compomics.util.gui.waiting.waitinghandlers.WaitingDialog; -import com.compomics.util.io.ConfigurationFile; -import com.compomics.util.preferences.DigestionPreferences; -import com.compomics.util.preferences.IdentificationParameters; -import com.compomics.util.preferences.LastSelectedFolder; -import com.compomics.util.preferences.SequenceMatchingPreferences; -import com.compomics.util.preferences.UtilitiesUserPreferences; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Toolkit; +import com.compomics.util.parameters.identification.search.DigestionParameters; +import com.compomics.util.parameters.identification.IdentificationParameters; +import com.compomics.util.io.file.LastSelectedFolder; +import com.compomics.util.parameters.identification.advanced.SequenceMatchingParameters; +import com.compomics.util.parameters.UtilitiesUserParameters; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.GraphicsEnvironment; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.Rectangle; +import java.awt.Toolkit; import java.io.BufferedReader; import java.io.BufferedWriter; -import java.io.File; -import java.io.FileNotFoundException; +import java.io.File; +import java.io.FileReader; +import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; @@ -70,17 +81,27 @@ import java.util.ArrayList; import java.util.Collections; import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Set; -import javax.swing.JFileChooser; -import javax.swing.JOptionPane; -import javax.swing.LookAndFeel; -import javax.swing.SwingWorker; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JFileChooser; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JSpinner; +import javax.swing.LookAndFeel; +import javax.swing.SpinnerNumberModel; +import javax.swing.SwingWorker; import javax.swing.UIDefaults; import javax.swing.UIManager; -import javax.swing.filechooser.FileFilter; -import net.jimmc.jshortcut.JShellLink; +import javax.swing.filechooser.FileFilter; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import net.jimmc.jshortcut.JShellLink; /** * The main DeNovoGUI frame. @@ -101,7 +122,7 @@ public class DeNovoGUI extends javax.swing.JFrame implements JavaHomeOrMemoryDia /** * The factory used to handle the modifications. */ - private PTMFactory ptmFactory; + private ModificationFactory ptmFactory; /** * The search handler. */ @@ -150,7 +171,11 @@ public class DeNovoGUI extends javax.swing.JFrame implements JavaHomeOrMemoryDia /** * The selected Novor folder. */ - private File novorFolder; + private File novorFolder; + /** + * The selected InstaNovo folder. + */ + private File instaNovoFolder; /** * Title of the PepNovo executable. */ @@ -211,15 +236,15 @@ public class DeNovoGUI extends javax.swing.JFrame implements JavaHomeOrMemoryDia * The implemented algorithms. The matches of these will be displayed only * and in this order. */ - public final static Advocate[] implementedAlgorithms = {Advocate.direcTag, Advocate.pepnovo, Advocate.pNovo, Advocate.novor}; + public final static Advocate[] implementedAlgorithms = {Advocate.direcTag, Advocate.pepnovo, Advocate.pNovo, Advocate.novor, Advocate.instanovo, Advocate.instanovoPlus, Advocate.instanovoRefined}; /** * The utilities user preferences. */ - private UtilitiesUserPreferences utilitiesUserPreferences = null; + private UtilitiesUserParameters utilitiesUserParameters = null; /** * The sequence matching preferences. */ - private SequenceMatchingPreferences sequenceMatchingPreferences; + private SequenceMatchingParameters sequenceMatchingPreferences; /** * Creates a new DeNovoGUI. @@ -249,11 +274,11 @@ public DeNovoGUI(ArrayList spectrumFiles, File searchParametersFile, File enzymeFactory = EnzymeFactory.getInstance(); spectrumFactory = SpectrumFactory.getInstance(); - ptmFactory = PTMFactory.getInstance(); + ptmFactory = ModificationFactory.getInstance(); // load the utilities user preferences try { - utilitiesUserPreferences = UtilitiesUserPreferences.loadUserPreferences(); + utilitiesUserParameters = UtilitiesUserParameters.loadUserParameters(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "An error occurred when reading the user preferences.", "File Error", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); @@ -261,7 +286,7 @@ public DeNovoGUI(ArrayList spectrumFiles, File searchParametersFile, File // check for new version boolean newVersion = false; - if (!getJarFilePath().equalsIgnoreCase(".") && utilitiesUserPreferences.isAutoUpdate()) { + if (!getJarFilePath().equalsIgnoreCase(".") && utilitiesUserParameters.isAutoUpdate()) { newVersion = checkForNewVersion(); } @@ -298,9 +323,9 @@ && new File(getJarFilePath() + "/resources/conf/firstRun").exists()) { // set this version as the default DeNovoGUI version if (!getJarFilePath().equalsIgnoreCase(".")) { String versionNumber = new com.compomics.denovogui.util.Properties().getVersion(); - UtilitiesUserPreferences utilitiesUserPreferences = UtilitiesUserPreferences.loadUserPreferences(); - utilitiesUserPreferences.setDeNovoGuiPath(new File(getJarFilePath(), "DeNovoGUI-" + versionNumber + ".jar").getAbsolutePath()); - UtilitiesUserPreferences.saveUserPreferences(utilitiesUserPreferences); + UtilitiesUserParameters utilitiesUserParameters = UtilitiesUserParameters.loadUserParameters(); + utilitiesUserParameters.setDeNovoGuiPath(new File(getJarFilePath(), "DeNovoGUI-" + versionNumber + ".jar").getAbsolutePath()); + UtilitiesUserParameters.saveUserParameters(utilitiesUserParameters); } // set the font color for the titlted borders, looks better than the default black @@ -395,7 +420,7 @@ && new File(getJarFilePath() + "/resources/conf/firstRun").exists()) { novorExecutable = "novor.jar"; } - deNovoSequencingHandler = new DeNovoSequencingHandler(pepNovoFolder, direcTagFolder, pNovoFolder, novorFolder); + deNovoSequencingHandler = new DeNovoSequencingHandler(pepNovoFolder, direcTagFolder, pNovoFolder, novorFolder, instaNovoFolder); setUpGUI(); @@ -406,7 +431,7 @@ && new File(getJarFilePath() + "/resources/conf/firstRun").exists()) { this.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/denovogui.png"))); // incrementing the counter for a new DenovoGUI run - if (utilitiesUserPreferences.isAutoUpdate()) { + if (utilitiesUserParameters.isAutoUpdate()) { Util.sendGAUpdate("UA-36198780-4", "toolstart", "denovogui-" + getVersion()); } @@ -417,10 +442,9 @@ && new File(getJarFilePath() + "/resources/conf/firstRun").exists()) { File folder = new File(getJarFilePath() + File.separator + "resources" + File.separator + "conf" + File.separator); File modUseFile = new File(folder, DeNovoSequencingHandler.DENOVOGUI_COMFIGURATION_FILE); - ConfigurationFile configFile = new ConfigurationFile(modUseFile); // @TODO: standardize the use of the ConfigurationFile - try { - modificationUse = SearchSettingsDialog.loadModificationsUse(configFile); - } catch (IOException e) { + try { + modificationUse = loadModificationsUse(modUseFile); + } catch (IOException e) { } @@ -445,7 +469,7 @@ && new File(getJarFilePath() + "/resources/conf/firstRun").exists()) { * Sets the path configuration. */ private void setPathConfiguration() throws IOException { - File pathConfigurationFile = new File(getJarFilePath(), UtilitiesPathPreferences.configurationFileName); + File pathConfigurationFile = new File(getJarFilePath(), UtilitiesPathParameters.configurationFileName); if (pathConfigurationFile.exists()) { DeNovoGUIPathPreferences.loadPathPreferencesFromFile(pathConfigurationFile); } @@ -454,9 +478,637 @@ private void setPathConfiguration() throws IOException { /** * Set up the GUI. */ - private void setUpGUI() { - // @TODO: should there be anything here? - } + private void setUpGUI() { + setUpInstaNovoControls(); + rebuildSearchEnginesPanel(); + fitMainFrameToContent(); + } + + /** + * Sets up the InstaNovo controls. + */ + private void setUpInstaNovoControls() { + + instaNovoCheckBox = new javax.swing.JCheckBox(); + instaNovoCheckBox.setSelected(true); + instaNovoCheckBox.setToolTipText("Enable InstaNovo"); + instaNovoCheckBox.setOpaque(false); + instaNovoCheckBox.addActionListener(evt -> { + if (instaNovoCheckBox.isSelected() && !ensureInstaNovoFolder()) { + instaNovoCheckBox.setSelected(false); + } + validateInput(false); + }); + + instaNovoPlusCheckBox = new javax.swing.JCheckBox(); + instaNovoPlusCheckBox.setSelected(true); + instaNovoPlusCheckBox.setToolTipText("Enable InstaNovo+"); + instaNovoPlusCheckBox.setOpaque(false); + instaNovoPlusCheckBox.addActionListener(evt -> { + if (instaNovoPlusCheckBox.isSelected() && !ensureInstaNovoFolder()) { + instaNovoPlusCheckBox.setSelected(false); + } + validateInput(false); + }); + + instaNovoRefineCheckBox = new javax.swing.JCheckBox(); + instaNovoRefineCheckBox.setSelected(true); + instaNovoRefineCheckBox.setToolTipText("Enable InstaNovo with refinement"); + instaNovoRefineCheckBox.setOpaque(false); + instaNovoRefineCheckBox.addActionListener(evt -> { + if (instaNovoRefineCheckBox.isSelected() && !ensureInstaNovoFolder()) { + instaNovoRefineCheckBox.setSelected(false); + } + validateInput(false); + }); + + instaNovoButton = new javax.swing.JButton("InstaNovo"); + setUpInstaNovoButton(instaNovoButton, "Enable InstaNovo"); + instaNovoButton.addActionListener(evt -> toggleInstaNovoCheckBox(instaNovoCheckBox)); + + instaNovoPlusButton = new javax.swing.JButton("InstaNovo+"); + setUpInstaNovoButton(instaNovoPlusButton, "Enable InstaNovo+"); + instaNovoPlusButton.addActionListener(evt -> toggleInstaNovoCheckBox(instaNovoPlusCheckBox)); + + instaNovoRefineButton = new javax.swing.JButton("Refinement"); + setUpInstaNovoButton(instaNovoRefineButton, "Enable InstaNovo with refinement"); + instaNovoRefineButton.addActionListener(evt -> toggleInstaNovoCheckBox(instaNovoRefineCheckBox)); + + instaNovoPlatformsButton = createAllPlatformsButton(); + instaNovoPlusPlatformsButton = createAllPlatformsButton(); + instaNovoRefinePlatformsButton = createAllPlatformsButton(); + + instaNovoLinkLabel = createInstaNovoLinkLabel("InstaNovo - De novo peptide sequencing with transformer based InstaNovo model"); + instaNovoPlusLinkLabel = createInstaNovoLinkLabel("InstaNovo+ - De novo peptide sequencing with diffusion based InstaNovo+ model"); + instaNovoRefineLinkLabel = createInstaNovoLinkLabel("InstaNovo with refinement - Refine InstaNovo predictions with InstaNovo+"); + + instaNovoSettingsJButton = createInstaNovoSettingsButton("Edit InstaNovo Advanced Settings"); + instaNovoSettingsJButton.addActionListener(evt -> editInstaNovoSettings(Advocate.instanovo, false, true, false)); + + instaNovoPlusSettingsJButton = createInstaNovoSettingsButton("Edit InstaNovo+ Advanced Settings"); + instaNovoPlusSettingsJButton.addActionListener(evt -> editInstaNovoSettings(Advocate.instanovoPlus, true, false, true)); + + instaNovoRefineSettingsJButton = createInstaNovoSettingsButton("Edit InstaNovo Refinement Advanced Settings"); + instaNovoRefineSettingsJButton.addActionListener(evt -> editInstaNovoSettings(Advocate.instanovoRefined, false, true, true)); + } + + /** + * Applies shared styling to an InstaNovo text button. + * + * @param button the button + * @param tooltip the tooltip + */ + private void setUpInstaNovoButton(javax.swing.JButton button, String tooltip) { + button.setToolTipText(tooltip); + button.setBorder(null); + button.setBorderPainted(false); + button.setContentAreaFilled(false); + button.setForeground(Color.BLACK); + button.setFont(button.getFont().deriveFont(java.awt.Font.BOLD | java.awt.Font.ITALIC, 18f)); + button.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); + button.setPreferredSize(new Dimension(101, 33)); + button.setMinimumSize(new Dimension(101, 33)); + } + + /** + * Creates an all-platforms button. + * + * @return the button + */ + private javax.swing.JButton createAllPlatformsButton() { + javax.swing.JButton button = new javax.swing.JButton(); + button.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/all_platforms_gray.png"))); + button.setToolTipText("\nSupported on Windows, Mac and Linux\n"); + button.setBorderPainted(false); + button.setContentAreaFilled(false); + return button; + } + + /** + * Creates an InstaNovo web link label. + * + * @param text the label text + * @return the label + */ + private javax.swing.JLabel createInstaNovoLinkLabel(String text) { + javax.swing.JLabel label = new javax.swing.JLabel("" + text + " - InstaNovo web page"); + label.setToolTipText("Open the InstaNovo web page"); + label.addMouseListener(new java.awt.event.MouseAdapter() { + public void mouseClicked(java.awt.event.MouseEvent evt) { + BareBonesBrowserLaunch.openURL("https://instadeepai.github.io/InstaNovo/"); + } + + public void mouseEntered(java.awt.event.MouseEvent evt) { + setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); + } + + public void mouseExited(java.awt.event.MouseEvent evt) { + setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); + } + }); + return label; + } + + /** + * Creates an InstaNovo settings button. + * + * @param tooltip the tooltip + * @return the button + */ + private javax.swing.JButton createInstaNovoSettingsButton(String tooltip) { + javax.swing.JButton button = new javax.swing.JButton(); + button.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/edit_gray.png"))); + button.setToolTipText(tooltip); + button.setBorder(null); + button.setBorderPainted(false); + button.setContentAreaFilled(false); + button.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/edit.png"))); + return button; + } + + /** + * Rebuilds the search engines panel with the added InstaNovo rows. + */ + private void rebuildSearchEnginesPanel() { + + searchEnginesPanel.removeAll(); + searchEnginesPanel.setLayout(new GridBagLayout()); + + int row = 0; + addSequencingMethodRow(row++, novorCheckBox, novorButton, novorPlatformsButton, novorLinkLabel, novorSettingsJButton); + addSequencingMethodRow(row++, instaNovoCheckBox, instaNovoButton, instaNovoPlatformsButton, instaNovoLinkLabel, instaNovoSettingsJButton); + addSequencingMethodRow(row++, instaNovoPlusCheckBox, instaNovoPlusButton, instaNovoPlusPlatformsButton, instaNovoPlusLinkLabel, instaNovoPlusSettingsJButton); + addSequencingMethodRow(row++, instaNovoRefineCheckBox, instaNovoRefineButton, instaNovoRefinePlatformsButton, instaNovoRefineLinkLabel, instaNovoRefineSettingsJButton); + addSequencingMethodRow(row++, direcTagCheckBox, direcTagButton, direcTagPlatformsButton, direcTagLinkLabel, directTagSettingsJButton); + addSequencingMethodRow(row++, pepNovoCheckBox, pepNovoButton, pepNovoPlatformsButton, pepNovoLinkLabel, pepNovoSettingsJButton); + addSequencingMethodRow(row, pNovoCheckBox, pNovoButton, pNovoPlatformsButton, pNovoLinkLabel, pNovoSettingsJButton); + searchEnginesPanel.revalidate(); + searchEnginesPanel.repaint(); + } + + /** + * Packs the frame after adding the dynamic InstaNovo rows and keeps it + * inside the usable desktop area. + */ + private void fitMainFrameToContent() { + + pack(); + + Rectangle screenBounds = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds(); + int width = Math.min(getWidth(), screenBounds.width); + int height = Math.min(getHeight(), screenBounds.height); + + if (width != getWidth() || height != getHeight()) { + setSize(width, height); + } + } + + /** + * Adds a row to the sequencing methods panel. + * + * @param row the row index + * @param checkBox the checkbox + * @param button the algorithm button + * @param platformsButton the platforms button + * @param linkLabel the link label + * @param settingsButton the settings button + */ + private void addSequencingMethodRow(int row, javax.swing.JCheckBox checkBox, javax.swing.JButton button, + javax.swing.JButton platformsButton, javax.swing.JLabel linkLabel, javax.swing.JButton settingsButton) { + + GridBagConstraints gbc = new GridBagConstraints(); + gbc.gridy = row; + gbc.insets = new Insets(2, 6, 2, 6); + gbc.anchor = GridBagConstraints.WEST; + + gbc.gridx = 0; + searchEnginesPanel.add(checkBox, gbc); + + gbc.gridx = 1; + gbc.fill = GridBagConstraints.HORIZONTAL; + gbc.weightx = 0.0; + searchEnginesPanel.add(button, gbc); + + gbc.gridx = 2; + gbc.fill = GridBagConstraints.NONE; + searchEnginesPanel.add(platformsButton, gbc); + + gbc.gridx = 3; + gbc.weightx = 1.0; + gbc.fill = GridBagConstraints.HORIZONTAL; + searchEnginesPanel.add(linkLabel, gbc); + + gbc.gridx = 4; + gbc.weightx = 0.0; + gbc.fill = GridBagConstraints.NONE; + searchEnginesPanel.add(settingsButton, gbc); + } + + /** + * Toggles an InstaNovo checkbox. + * + * @param checkBox the checkbox + */ + private void toggleInstaNovoCheckBox(javax.swing.JCheckBox checkBox) { + checkBox.setSelected(!checkBox.isSelected()); + if (checkBox.isSelected() && !ensureInstaNovoFolder()) { + checkBox.setSelected(false); + } + validateInput(false); + } + + /** + * Returns true if at least one InstaNovo workflow is selected. + * + * @return true if InstaNovo is selected + */ + private boolean isInstaNovoSelected() { + return instaNovoCheckBox.isSelected() || instaNovoPlusCheckBox.isSelected() || instaNovoRefineCheckBox.isSelected(); + } + + /** + * Returns true if the selected InstaNovo folder contains an executable. + * + * @return true if the InstaNovo folder is valid + */ + private boolean hasValidInstaNovoFolder() { + return instaNovoFolder != null && InstaNovoJob.getExecutable(instaNovoFolder).exists(); + } + + /** + * Updates the InstaNovo row state based on whether a source folder is needed. + */ + private void updateInstaNovoFolderState() { + boolean missingFolder = isInstaNovoSelected() && !hasValidInstaNovoFolder(); + String tooltip = missingFolder + ? "Install or select InstaNovo before starting" + : "InstaNovo folder configured"; + + instaNovoButton.setForeground(Color.BLACK); + instaNovoPlusButton.setForeground(Color.BLACK); + instaNovoRefineButton.setForeground(Color.BLACK); + + instaNovoCheckBox.setToolTipText(instaNovoCheckBox.isSelected() && missingFolder ? tooltip : "Enable InstaNovo"); + instaNovoPlusCheckBox.setToolTipText(instaNovoPlusCheckBox.isSelected() && missingFolder ? tooltip : "Enable InstaNovo+"); + instaNovoRefineCheckBox.setToolTipText(instaNovoRefineCheckBox.isSelected() && missingFolder ? tooltip : "Enable InstaNovo with refinement"); + + instaNovoSettingsJButton.setToolTipText(missingFolder ? "Install or select InstaNovo and edit InstaNovo Advanced Settings" : "Edit InstaNovo Advanced Settings"); + instaNovoPlusSettingsJButton.setToolTipText(missingFolder ? "Install or select InstaNovo and edit InstaNovo+ Advanced Settings" : "Edit InstaNovo+ Advanced Settings"); + instaNovoRefineSettingsJButton.setToolTipText(missingFolder ? "Install or select InstaNovo and edit InstaNovo Refinement Advanced Settings" : "Edit InstaNovo Refinement Advanced Settings"); + } + + /** + * Ensures that the InstaNovo folder is set. + * + * @return true if the folder is set and contains an executable + */ + private boolean ensureInstaNovoFolder() { + + if (hasValidInstaNovoFolder()) { + return true; + } + + Object[] options = {"Install InstaNovo", "Select Existing Folder", "Cancel"}; + int option = JOptionPane.showOptionDialog( + this, + "InstaNovo is required for the selected workflow.\n\n" + + "DeNovoGUI can install InstaNovo " + InstaNovoSetup.INSTANOVO_VERSION + " in a local virtual environment,\n" + + "or you can select an existing InstaNovo checkout or installation folder.", + "Install or Select InstaNovo", + JOptionPane.YES_NO_CANCEL_OPTION, + JOptionPane.QUESTION_MESSAGE, + null, + options, + options[0] + ); + + if (option == 0) { + return installInstaNovo(InstaNovoSetup.getDefaultInstallationFolder()); + } else if (option != 1) { + return false; + } + + return selectInstaNovoFolder(); + } + + /** + * Selects an existing InstaNovo folder. + * + * @return true if a valid folder was selected + */ + private boolean selectInstaNovoFolder() { + + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setDialogTitle("Select InstaNovo Folder"); + fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + fileChooser.setMultiSelectionEnabled(false); + + if (instaNovoFolder != null) { + fileChooser.setCurrentDirectory(instaNovoFolder); + } + + int option = fileChooser.showOpenDialog(this); + + if (option == JFileChooser.APPROVE_OPTION) { + File selectedFolder = fileChooser.getSelectedFile(); + if (InstaNovoJob.getExecutable(selectedFolder).exists()) { + instaNovoFolder = selectedFolder; + validateInput(false); + return true; + } + + JOptionPane.showMessageDialog( + this, + "Could not find the InstaNovo executable in the selected folder. Select the InstaNovo checkout or installation root.", + "InstaNovo Folder", + JOptionPane.WARNING_MESSAGE + ); + } + + return false; + } + + /** + * Installs InstaNovo in a local virtual environment. + * + * @param installationFolder the installation folder + * + * @return true if the installation succeeded + */ + private boolean installInstaNovo(File installationFolder) { + + int confirm = JOptionPane.showConfirmDialog( + this, + "Install InstaNovo " + InstaNovoSetup.INSTANOVO_VERSION + " into:\n" + + installationFolder.getAbsolutePath() + + "\n\n" + InstaNovoSetup.getInstallVariantDescription() + + "\n\nThis downloads uv if needed, a managed Python runtime, and Python dependencies.\n" + + "The InstaNovo model checkpoint will still be downloaded by InstaNovo on first use.", + "Install InstaNovo", + JOptionPane.OK_CANCEL_OPTION, + JOptionPane.QUESTION_MESSAGE + ); + + if (confirm != JOptionPane.OK_OPTION) { + return false; + } + + final ProgressDialogX installerDialog = new ProgressDialogX( + this, + Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/denovogui.png")), + Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/denovogui_orange.png")), + true + ); + installerDialog.setPrimaryProgressCounterIndeterminate(true); + installerDialog.setTitle("Installing InstaNovo. Please Wait..."); + + final boolean[] success = new boolean[]{false}; + final Exception[] exception = new Exception[]{null}; + + Thread installerThread = new Thread("InstallInstaNovoThread") { + @Override + public void run() { + try { + InstaNovoSetup.install(installationFolder, installerDialog); + success[0] = true; + } catch (Exception e) { + exception[0] = e; + } finally { + installerDialog.setRunFinished(); + } + } + }; + + installerThread.start(); + installerDialog.setVisible(true); + + if (!success[0]) { + JOptionPane.showMessageDialog( + this, + "Could not install InstaNovo.\n\n" + (exception[0] == null ? "The installation was canceled." : exception[0].getMessage()), + "InstaNovo Installation", + JOptionPane.WARNING_MESSAGE + ); + return false; + } + + if (!InstaNovoJob.getExecutable(installationFolder).exists()) { + JOptionPane.showMessageDialog( + this, + "InstaNovo was installed, but the executable could not be found in " + installationFolder + ".", + "InstaNovo Installation", + JOptionPane.WARNING_MESSAGE + ); + return false; + } + + instaNovoFolder = installationFolder; + validateInput(false); + + return true; + } + + /** + * Edits the InstaNovo parameters. + * + * @param advocate the advocate + * @param plusParameters whether to create InstaNovo+ parameters + * @param showInstaNovoModel show the InstaNovo model field + * @param showInstaNovoPlusModel show the InstaNovo+ model field + */ + private void editInstaNovoSettings(Advocate advocate, boolean plusParameters, boolean showInstaNovoModel, boolean showInstaNovoPlusModel) { + + if (!ensureInstaNovoFolder()) { + return; + } + + Object oldParameters = searchParameters.getIdentificationAlgorithmParameter(advocate.getIndex()); + InstaNovoParameters instaNovoParameters = oldParameters instanceof InstaNovoParameters + ? copyInstaNovoParameters((InstaNovoParameters) oldParameters, plusParameters) + : (plusParameters ? new InstaNovoPlusParameters() : new InstaNovoParameters()); + + HashMap> instaNovoModels = getInstaNovoModels(instaNovoFolder); + JComboBox instaNovoModelCmb = createInstaNovoModelComboBox(instaNovoModels.get("transformer"), instaNovoParameters.getInstaNovoModel()); + JComboBox instaNovoPlusModelCmb = createInstaNovoModelComboBox(instaNovoModels.get("diffusion"), instaNovoParameters.getInstaNovoPlusModel()); + + if ((showInstaNovoModel && instaNovoModelCmb.getItemCount() == 0) + || (showInstaNovoPlusModel && instaNovoPlusModelCmb.getItemCount() == 0)) { + + JOptionPane.showMessageDialog( + this, + "Could not read the InstaNovo model list from instanovo/models.json. Select the InstaNovo checkout root as the installation folder before editing advanced settings.", + "InstaNovo Model List", + JOptionPane.WARNING_MESSAGE + ); + return; + } + + javax.swing.JTextField configPathTxt = new javax.swing.JTextField(instaNovoParameters.getConfigFile() == null ? "" : instaNovoParameters.getConfigFile()); + JSpinner numberOfBeamsSpinner = new JSpinner(new SpinnerNumberModel(instaNovoParameters.getNumberOfBeams(), 1, 1000, 1)); + JComboBox beamSearchCombo = new JComboBox(new String[]{"Standard beam search", "Knapsack beam search"}); + beamSearchCombo.setSelectedIndex(instaNovoParameters.isUseKnapsack() ? 1 : 0); + JCheckBox saveAllPredictionsCheckBox = new JCheckBox("Save all beam predictions", instaNovoParameters.isSaveAllPredictions()); + JSpinner batchSizeSpinner = new JSpinner(new SpinnerNumberModel(instaNovoParameters.getBatchSize(), 1, 100000, 1)); + JCheckBox forceCpuCheckBox = new JCheckBox("Force CPU execution", instaNovoParameters.isForceCpu()); + + JPanel panel = new JPanel(new java.awt.GridLayout(0, 2, 5, 5)); + + if (showInstaNovoModel) { + panel.add(new JLabel("InstaNovo model")); + panel.add(instaNovoModelCmb); + } + + if (showInstaNovoPlusModel) { + panel.add(new JLabel("InstaNovo+ model")); + panel.add(instaNovoPlusModelCmb); + } + + panel.add(new JLabel("Number of beams")); + panel.add(numberOfBeamsSpinner); + panel.add(new JLabel("Beam search")); + panel.add(beamSearchCombo); + panel.add(new JLabel("Predictions")); + panel.add(saveAllPredictionsCheckBox); + panel.add(new JLabel("Batch size")); + panel.add(batchSizeSpinner); + panel.add(new JLabel("Config path")); + panel.add(configPathTxt); + panel.add(new JLabel("Device")); + panel.add(forceCpuCheckBox); + + int option = JOptionPane.showConfirmDialog( + this, + panel, + showInstaNovoModel && showInstaNovoPlusModel + ? "InstaNovo Refinement Advanced Settings" + : (plusParameters ? "InstaNovo+ Advanced Settings" : "InstaNovo Advanced Settings"), + JOptionPane.OK_CANCEL_OPTION, + JOptionPane.PLAIN_MESSAGE + ); + + if (option == JOptionPane.OK_OPTION) { + + if (showInstaNovoModel && instaNovoModelCmb.getSelectedItem() == null) { + JOptionPane.showMessageDialog(this, "The InstaNovo model cannot be empty.", "Input Error", JOptionPane.WARNING_MESSAGE); + return; + } + + if (showInstaNovoPlusModel && instaNovoPlusModelCmb.getSelectedItem() == null) { + JOptionPane.showMessageDialog(this, "The InstaNovo+ model cannot be empty.", "Input Error", JOptionPane.WARNING_MESSAGE); + return; + } + + if (showInstaNovoModel) { + instaNovoParameters.setInstaNovoModel(instaNovoModelCmb.getSelectedItem().toString()); + } + + if (showInstaNovoPlusModel) { + instaNovoParameters.setInstaNovoPlusModel(instaNovoPlusModelCmb.getSelectedItem().toString()); + } + + String configPath = configPathTxt.getText().trim(); + instaNovoParameters.setConfigFile(configPath.isEmpty() ? null : configPath); + instaNovoParameters.setNumberOfBeams((Integer) numberOfBeamsSpinner.getValue()); + instaNovoParameters.setUseKnapsack(beamSearchCombo.getSelectedIndex() == 1); + instaNovoParameters.setSaveAllPredictions(saveAllPredictionsCheckBox.isSelected()); + instaNovoParameters.setBatchSize((Integer) batchSizeSpinner.getValue()); + instaNovoParameters.setForceCpu(forceCpuCheckBox.isSelected()); + + searchParameters.setIdentificationAlgorithmParameter(advocate.getIndex(), instaNovoParameters); + validateInput(false); + } + } + + /** + * Creates a model combo box populated from the InstaNovo models file. + * + * @param models the available models + * @param selectedModel the selected model + * @return the model combo box + */ + private JComboBox createInstaNovoModelComboBox(ArrayList models, String selectedModel) { + + if (models == null) { + models = new ArrayList(); + } + + JComboBox comboBox = new JComboBox(models.toArray(new String[0])); + comboBox.setEditable(false); + + if (selectedModel != null && models.contains(selectedModel)) { + comboBox.setSelectedItem(selectedModel); + } + + return comboBox; + } + + /** + * Returns the available InstaNovo models. + * + * @param instaNovoLocation the InstaNovo installation folder + * @return the available model ids indexed by model type + */ + static HashMap> getInstaNovoModels(File instaNovoLocation) { + + HashMap> result = new HashMap>(); + + if (instaNovoLocation == null) { + return result; + } + + File modelsFile = InstaNovoSetup.getModelsFile(instaNovoLocation); + + if (modelsFile == null || !modelsFile.exists()) { + return result; + } + + try (FileReader reader = new FileReader(modelsFile)) { + + JsonObject modelsJson = JsonParser.parseReader(reader).getAsJsonObject(); + + for (Map.Entry modelTypeEntry : modelsJson.entrySet()) { + + JsonElement modelTypeElement = modelTypeEntry.getValue(); + + if (modelTypeElement.isJsonObject()) { + + ArrayList models = new ArrayList(); + + for (Map.Entry modelEntry : modelTypeElement.getAsJsonObject().entrySet()) { + models.add(modelEntry.getKey()); + } + + result.put(modelTypeEntry.getKey(), models); + } + } + } catch (Exception e) { + result.clear(); + } + + return result; + } + + /** + * Copies InstaNovo parameters. + * + * @param oldParameters the old parameters + * @param plusParameters whether to create InstaNovo+ parameters + * @return a copy of the parameters + */ + private InstaNovoParameters copyInstaNovoParameters(InstaNovoParameters oldParameters, boolean plusParameters) { + + InstaNovoParameters result = plusParameters ? new InstaNovoPlusParameters() : new InstaNovoParameters(); + result.setInstaNovoModel(oldParameters.getInstaNovoModel()); + result.setInstaNovoPlusModel(oldParameters.getInstaNovoPlusModel()); + result.setConfigFile(oldParameters.getConfigFile()); + result.setNumberOfBeams(oldParameters.getNumberOfBeams()); + result.setUseKnapsack(oldParameters.isUseKnapsack()); + result.setSaveAllPredictions(oldParameters.isSaveAllPredictions()); + result.setBatchSize(oldParameters.getBatchSize()); + result.setForceCpu(oldParameters.isForceCpu()); + + return result; + } /** * Set up the log file. @@ -1331,19 +1983,28 @@ private void algorithmLocationsMenuItemActionPerformed(java.awt.event.ActionEven * * @param evt */ - private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startButtonActionPerformed - - // no search parameters set, use the defaults - if (searchParameters == null) { - searchParameters = new SearchParameters(); - searchParameters.setDigestionPreferences(DigestionPreferences.getDefaultPreferences()); - } - - boolean validInput = true; + private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startButtonActionPerformed + + // no search parameters set, use the defaults + if (searchParameters == null) { + searchParameters = new SearchParameters(); + searchParameters.setDigestionParameters(DigestionParameters.getDefaultPreferences()); + } + + if (isInstaNovoSelected() && !hasValidInstaNovoFolder() && !ensureInstaNovoFolder()) { + validateInput(false); + return; + } + + if (!validateInput(true)) { + return; + } + + boolean validInput = true; // check if there are less than 10 ptms (variable and fixed) for novor if (novorCheckBox.isSelected()) { - if ((searchParameters.getPtmSettings().getFixedModifications().size() + searchParameters.getPtmSettings().getVariableModifications().size()) > 10) { + if ((searchParameters.getModificationParameters().getFixedModifications().size() + searchParameters.getModificationParameters().getVariableModifications().size()) > 10) { JOptionPane.showMessageDialog(this, "Maximum ten modifications are allowed when running Novor.\n" + "Please remove some of the modifications or disable Novor.", "Settings Error", JOptionPane.WARNING_MESSAGE); validInput = false; @@ -1352,8 +2013,8 @@ private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-F // check if all ptms are valid for pNovo+ if (pNovoCheckBox.isSelected()) { - for (String tempPtm : searchParameters.getPtmSettings().getAllModifications()) { - PTM currentPtm = ptmFactory.getPTM(tempPtm); + for (String tempPtm : searchParameters.getModificationParameters().getAllModifications()) { + Modification currentPtm = ptmFactory.getModification(tempPtm); if (currentPtm.isCTerm() || currentPtm.isNTerm()) { JOptionPane.showMessageDialog(this, "Terminal modifications are currently not supported for pNovo+.\n" + "Please remove \'" + tempPtm + "\' or disable pNovo+.", "Settings Error", JOptionPane.WARNING_MESSAGE); @@ -1365,8 +2026,8 @@ private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-F // check if all ptms are valid for DirecTag if (direcTagCheckBox.isSelected()) { boolean terminalPtmsSelected = false; - for (String tempPtm : searchParameters.getPtmSettings().getAllModifications()) { - PTM currentPtm = ptmFactory.getPTM(tempPtm); + for (String tempPtm : searchParameters.getModificationParameters().getAllModifications()) { + Modification currentPtm = ptmFactory.getModification(tempPtm); if (currentPtm.isCTerm() || currentPtm.isNTerm()) { terminalPtmsSelected = true; } @@ -1405,7 +2066,7 @@ private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-F } if (validInput) { - sequenceMatchingPreferences = SequenceMatchingPreferences.getDefaultSequenceMatching(); + sequenceMatchingPreferences = SequenceMatchingParameters.getDefaultSequenceMatching(); saveModificationUsage(); // save the ptms usage waitingDialog = new WaitingDialog(this, @@ -1426,7 +2087,7 @@ public void cancelPressed() { waitingDialog.setLocationRelativeTo(this); // incrementing the counter for a new DenovoGUI run - if (utilitiesUserPreferences.isAutoUpdate()) { + if (utilitiesUserParameters.isAutoUpdate()) { Util.sendGAUpdate("UA-36198780-4", "startrun-gui", "denovogui-" + getVersion()); } startSequencing(waitingDialog); @@ -1505,13 +2166,9 @@ private void pepNovoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN * @param evt */ private void clearSpectraButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearSpectraButtonActionPerformed - setSpectrumFiles(new ArrayList()); - spectrumFactory.clearFactory(); - try { - spectrumFactory.closeFiles(); - } catch (IOException e) { - catchException(e); - } + setSpectrumFiles(new ArrayList()); + spectrumFactory.clearFactory(); + spectrumFactory.closeFiles(); spectrumFilesTextField.setText(getSpectrumFiles().size() + " file(s) selected"); validateInput(false); }//GEN-LAST:event_clearSpectraButtonActionPerformed @@ -1629,7 +2286,7 @@ public String getDescription() { if (error != null) { JOptionPane.showMessageDialog(this, error, - "PTM Definition Changed", JOptionPane.WARNING_MESSAGE); + "Modification Definition Changed", JOptionPane.WARNING_MESSAGE); } parametersFile = file; @@ -1754,7 +2411,7 @@ private void deNovoGuiWebPageJLabelMouseExited(java.awt.event.MouseEvent evt) {/ */ private void openMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openMenuItemActionPerformed if (sequenceMatchingPreferences == null) { - sequenceMatchingPreferences = SequenceMatchingPreferences.getDefaultSequenceMatching(); + sequenceMatchingPreferences = SequenceMatchingParameters.getDefaultSequenceMatching(); } new ResultsFrame(this, null, searchParameters); }//GEN-LAST:event_openMenuItemActionPerformed @@ -1801,7 +2458,7 @@ public void run() { progressDialog.setRunFinished(); setVisible(false); if (sequenceMatchingPreferences == null) { - sequenceMatchingPreferences = SequenceMatchingPreferences.getDefaultSequenceMatching(); + sequenceMatchingPreferences = SequenceMatchingParameters.getDefaultSequenceMatching(); } new ResultsFrame(DeNovoGUI.this, outFiles, searchParameters); } catch (ClassNotFoundException e) { @@ -1905,16 +2562,16 @@ private void direcTagCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {// * @param evt */ private void javaSettingsJMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_javaSettingsJMenuItemActionPerformed - new JavaSettingsDialog(this, this, null, "DeNovoGUI", true); + new JavaParametersDialog(this, this, null, "DeNovoGUI", true); }//GEN-LAST:event_javaSettingsJMenuItemActionPerformed /** - * Open the PrivacySettingsDialog. + * Open the PrivacyParametersDialog. * * @param evt */ private void privacyMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_privacyMenuItemActionPerformed - new PrivacySettingsDialog(this, Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/denovogui.png"))); + new PrivacyParametersDialog(this, Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/denovogui.png"))); }//GEN-LAST:event_privacyMenuItemActionPerformed /** @@ -2003,7 +2660,7 @@ private void directTagSettingsJButtonMouseExited(java.awt.event.MouseEvent evt) */ private void directTagSettingsJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_directTagSettingsJButtonActionPerformed DirecTagParameters oldDirecTagParameters = (DirecTagParameters) searchParameters.getIdentificationAlgorithmParameter(Advocate.direcTag.getIndex()); - DirecTagSettingsDialog direcTagSettingsDialog = new DirecTagSettingsDialog(this, oldDirecTagParameters, true); + DirecTagParametersDialog direcTagSettingsDialog = new DirecTagParametersDialog(this, oldDirecTagParameters, true); boolean direcTagParametersSet = false; @@ -2027,7 +2684,7 @@ private void directTagSettingsJButtonActionPerformed(java.awt.event.ActionEvent if (error != null) { JOptionPane.showMessageDialog(this, error, - "PTM Definition Changed", JOptionPane.WARNING_MESSAGE); + "Modification Definition Changed", JOptionPane.WARNING_MESSAGE); } settingsFileJTextField.setText(parametersFile.getName()); direcTagParametersSet = true; @@ -2038,7 +2695,7 @@ private void directTagSettingsJButtonActionPerformed(java.awt.event.ActionEvent } break; case JOptionPane.CANCEL_OPTION: - direcTagSettingsDialog = new DirecTagSettingsDialog(this, newDirecTagParameters, true); + direcTagSettingsDialog = new DirecTagParametersDialog(this, newDirecTagParameters, true); break; case JOptionPane.NO_OPTION: direcTagParametersSet = true; @@ -2080,7 +2737,7 @@ private void pNovoSettingsJButtonMouseExited(java.awt.event.MouseEvent evt) {//G */ private void pNovoSettingsJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pNovoSettingsJButtonActionPerformed PNovoParameters oldPNovoParameters = (PNovoParameters) searchParameters.getAlgorithmSpecificParameters().get(Advocate.pNovo.getIndex()); - PNovoSettingsDialog pNovoSettingsDialog = new PNovoSettingsDialog(this, oldPNovoParameters, true); + PNovoParametersDialog pNovoSettingsDialog = new PNovoParametersDialog(this, oldPNovoParameters, true); pNovoSettingsDialog.dispose(); @@ -2106,7 +2763,7 @@ private void pNovoSettingsJButtonActionPerformed(java.awt.event.ActionEvent evt) if (error != null) { JOptionPane.showMessageDialog(this, error, - "PTM Definition Changed", JOptionPane.WARNING_MESSAGE); + "Modification Definition Changed", JOptionPane.WARNING_MESSAGE); } settingsFileJTextField.setText(parametersFile.getName()); pNovoParametersSet = true; @@ -2117,7 +2774,7 @@ private void pNovoSettingsJButtonActionPerformed(java.awt.event.ActionEvent evt) } break; case JOptionPane.CANCEL_OPTION: - pNovoSettingsDialog = new PNovoSettingsDialog(this, newPNovoParameters, true); + pNovoSettingsDialog = new PNovoParametersDialog(this, newPNovoParameters, true); break; case JOptionPane.NO_OPTION: pNovoParametersSet = true; @@ -2252,7 +2909,7 @@ private void resourceSettingsMenuItemActionPerformed(java.awt.event.ActionEvent */ private void novorSettingsJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_novorSettingsJButtonActionPerformed NovorParameters oldNovorParameters = (NovorParameters) searchParameters.getIdentificationAlgorithmParameter(Advocate.novor.getIndex()); - NovorSettingsDialog novorSettingsDialog = new NovorSettingsDialog(this, oldNovorParameters, true); + NovorParametersDialog novorSettingsDialog = new NovorParametersDialog(this, oldNovorParameters, true); boolean novorParametersSet = false; @@ -2276,7 +2933,7 @@ private void novorSettingsJButtonActionPerformed(java.awt.event.ActionEvent evt) if (error != null) { JOptionPane.showMessageDialog(this, error, - "PTM Definition Changed", JOptionPane.WARNING_MESSAGE); + "Modification Definition Changed", JOptionPane.WARNING_MESSAGE); } settingsFileJTextField.setText(parametersFile.getName()); novorParametersSet = true; @@ -2287,7 +2944,7 @@ private void novorSettingsJButtonActionPerformed(java.awt.event.ActionEvent evt) } break; case JOptionPane.CANCEL_OPTION: - novorSettingsDialog = new NovorSettingsDialog(this, newNovorParameters, true); + novorSettingsDialog = new NovorParametersDialog(this, newNovorParameters, true); break; case JOptionPane.NO_OPTION: novorParametersSet = true; @@ -2311,7 +2968,7 @@ private void novorSettingsJButtonActionPerformed(java.awt.event.ActionEvent evt) */ private void pepNovoSettingsJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pepNovoSettingsJButtonActionPerformed PepnovoParameters oldPepNovoParameters = (PepnovoParameters) searchParameters.getIdentificationAlgorithmParameter(Advocate.pepnovo.getIndex()); - PepNovoSettingsDialog pepNovoSettingsDialog = new PepNovoSettingsDialog(this, oldPepNovoParameters, true); + PepNovoParametersDialog pepNovoSettingsDialog = new PepNovoParametersDialog(this, oldPepNovoParameters, true); boolean pepNovoParametersSet = false; @@ -2335,7 +2992,7 @@ private void pepNovoSettingsJButtonActionPerformed(java.awt.event.ActionEvent ev if (error != null) { JOptionPane.showMessageDialog(this, error, - "PTM Definition Changed", JOptionPane.WARNING_MESSAGE); + "Modification Definition Changed", JOptionPane.WARNING_MESSAGE); } settingsFileJTextField.setText(parametersFile.getName()); pepNovoParametersSet = true; @@ -2346,7 +3003,7 @@ private void pepNovoSettingsJButtonActionPerformed(java.awt.event.ActionEvent ev } break; case JOptionPane.CANCEL_OPTION: - pepNovoSettingsDialog = new PepNovoSettingsDialog(this, newPepNovoParameters, true); + pepNovoSettingsDialog = new PepNovoParametersDialog(this, newPepNovoParameters, true); break; case JOptionPane.NO_OPTION: pepNovoParametersSet = true; @@ -2470,9 +3127,24 @@ public static void main(String args[]) { private javax.swing.JMenuItem loadExampleMenuItem; private javax.swing.JButton loadSettingsButton; private javax.swing.JMenuItem logReportMenu; - private javax.swing.JMenuBar menuBar; - private javax.swing.JMenuItem modsMenuItem; - private javax.swing.JButton novorButton; + private javax.swing.JMenuBar menuBar; + private javax.swing.JMenuItem modsMenuItem; + private javax.swing.JButton instaNovoButton; + private javax.swing.JCheckBox instaNovoCheckBox; + private javax.swing.JLabel instaNovoLinkLabel; + private javax.swing.JButton instaNovoPlatformsButton; + private javax.swing.JButton instaNovoSettingsJButton; + private javax.swing.JButton instaNovoPlusButton; + private javax.swing.JCheckBox instaNovoPlusCheckBox; + private javax.swing.JLabel instaNovoPlusLinkLabel; + private javax.swing.JButton instaNovoPlusPlatformsButton; + private javax.swing.JButton instaNovoPlusSettingsJButton; + private javax.swing.JButton instaNovoRefineButton; + private javax.swing.JCheckBox instaNovoRefineCheckBox; + private javax.swing.JLabel instaNovoRefineLinkLabel; + private javax.swing.JButton instaNovoRefinePlatformsButton; + private javax.swing.JButton instaNovoRefineSettingsJButton; + private javax.swing.JButton novorButton; private javax.swing.JCheckBox novorCheckBox; private javax.swing.JLabel novorLinkLabel; private javax.swing.JButton novorPlatformsButton; @@ -2508,9 +3180,9 @@ public static void main(String args[]) { */ public void startSequencing(WaitingHandler waitingHandler) { - int nThreads = deNovoSequencingHandler.getNThreads(); - deNovoSequencingHandler = new DeNovoSequencingHandler(pepNovoFolder, direcTagFolder, pNovoFolder, novorFolder); - deNovoSequencingHandler.setNThreads(nThreads); // @TODO: find a better fix!! + int nThreads = deNovoSequencingHandler.getNThreads(); + deNovoSequencingHandler = new DeNovoSequencingHandler(pepNovoFolder, direcTagFolder, pNovoFolder, novorFolder, instaNovoFolder); + deNovoSequencingHandler.setNThreads(nThreads); // @TODO: find a better fix!! sequencingWorker = new SequencingWorker(waitingHandler, true); sequencingWorker.execute(); @@ -2563,8 +3235,8 @@ public void restart() { } @Override - public UtilitiesUserPreferences getUtilitiesUserPreferences() { - return utilitiesUserPreferences; + public UtilitiesUserParameters getUtilitiesUserParameters() { + return utilitiesUserParameters; } @SuppressWarnings("rawtypes") @@ -2606,12 +3278,14 @@ protected Object doInBackground() throws Exception { waitingHandler.appendReportEndLine(); try { - waitingHandler.appendReport("Loading the spectra.", true, true); - loadSpectra(spectrumFiles, waitingHandler); - waitingHandler.appendReport("Done loading the spectra.", true, true); - waitingHandler.appendReportEndLine(); - deNovoSequencingHandler.startSequencing(spectrumFiles, searchParameters, outputFolder, parametersFile, pepNovoExecutable, direcTagExecutable, pNovoExecutable, novorExecutable, - pepNovoCheckBox.isSelected(), direcTagCheckBox.isSelected(), pNovoCheckBox.isSelected(), novorCheckBox.isSelected(), waitingHandler, exceptionHandler); + waitingHandler.appendReport("Loading the spectra.", true, true); + loadSpectra(spectrumFiles, waitingHandler); + waitingHandler.appendReport("Done loading the spectra.", true, true); + waitingHandler.appendReportEndLine(); + deNovoSequencingHandler.startSequencing(spectrumFiles, searchParameters, outputFolder, parametersFile, pepNovoExecutable, direcTagExecutable, pNovoExecutable, novorExecutable, + pepNovoCheckBox.isSelected(), direcTagCheckBox.isSelected(), pNovoCheckBox.isSelected(), novorCheckBox.isSelected(), + instaNovoCheckBox.isSelected(), instaNovoPlusCheckBox.isSelected(), instaNovoRefineCheckBox.isSelected(), + waitingHandler, exceptionHandler); } catch (Exception e) { workerExceptionHandler.catchException(e); } @@ -2651,10 +3325,11 @@ protected void done() { } // check if there are any output files to open - ArrayList resultFiles = FileProcessor.getAllResultFiles( - outputFolder, spectrumFiles, - pepNovoCheckBox.isSelected(), direcTagCheckBox.isSelected(), - pNovoCheckBox.isSelected(), novorCheckBox.isSelected()); + ArrayList resultFiles = FileProcessor.getAllResultFiles( + outputFolder, spectrumFiles, + pepNovoCheckBox.isSelected(), direcTagCheckBox.isSelected(), + pNovoCheckBox.isSelected(), novorCheckBox.isSelected(), + instaNovoCheckBox.isSelected(), instaNovoPlusCheckBox.isSelected(), instaNovoRefineCheckBox.isSelected()); if (resultFiles.isEmpty()) { waitingHandler.appendReportEndLine(); @@ -2690,7 +3365,7 @@ private void displayResults(ArrayList resultFiles) throws Exception { setVisible(false); if (sequenceMatchingPreferences == null) { - sequenceMatchingPreferences = SequenceMatchingPreferences.getDefaultSequenceMatching(); + sequenceMatchingPreferences = SequenceMatchingParameters.getDefaultSequenceMatching(); } new ResultsFrame(this, resultFiles, searchParameters); } @@ -2734,7 +3409,7 @@ private void addShortcutAtDeskTop() { jarFilePath = jarFilePath.substring(1); } - //utilitiesUserPreferences.setDeNovoPath(jarFilePath); // @TODO: add this method to utilities + //utilitiesUserParameters.setDeNovoPath(jarFilePath); // @TODO: add this method to utilities String iconFileLocation = jarFilePath + "\\resources\\denovogui.ico"; String jarFileLocation = jarFilePath + "\\DeNovoGUI-" + new Properties().getVersion() + ".jar"; @@ -2760,7 +3435,7 @@ private void addShortcutAtDeskTop() { public LastSelectedFolder getLastSelectedFolder() { if (lastSelectedFolder == null) { lastSelectedFolder = new LastSelectedFolder(); - utilitiesUserPreferences.setLastSelectedFolder(lastSelectedFolder); + utilitiesUserParameters.setLastSelectedFolder(lastSelectedFolder); } return lastSelectedFolder; } @@ -3106,7 +3781,7 @@ public boolean checkPNovoFolder(File deNovoFolder) { public void setIdentificationParameters(File parametersFile) { if (parametersFile == null) { searchParameters = new SearchParameters(); - searchParameters.setDigestionPreferences(DigestionPreferences.getDefaultPreferences()); + searchParameters.setDigestionParameters(DigestionParameters.getDefaultPreferences()); setDefaultParameters(); // label the configs as default } else { try { @@ -3115,7 +3790,7 @@ public void setIdentificationParameters(File parametersFile) { if (error != null) { JOptionPane.showMessageDialog(this, error, - "PTM Definition Changed", JOptionPane.WARNING_MESSAGE); + "Modification Definition Changed", JOptionPane.WARNING_MESSAGE); } settingsFileJTextField.setText(parametersFile.getName()); } catch (Exception e) { @@ -3125,11 +3800,11 @@ public void setIdentificationParameters(File parametersFile) { e.printStackTrace(); setDefaultParameters(); // label the configs as default searchParameters = new SearchParameters(); - searchParameters.setDigestionPreferences(DigestionPreferences.getDefaultPreferences()); + searchParameters.setDigestionParameters(DigestionParameters.getDefaultPreferences()); setDefaultParameters(); // label the configs as default } } - sequenceMatchingPreferences = SequenceMatchingPreferences.getDefaultSequenceMatching(); + sequenceMatchingPreferences = SequenceMatchingParameters.getDefaultSequenceMatching(); validateInput(false); } @@ -3139,53 +3814,65 @@ public void setIdentificationParameters(File parametersFile) { * @param showMessage if true an error messages are shown to the users * @return a boolean indicating if the input is valid. */ - private boolean validateInput(boolean showMessage) { - - boolean valid = true; - - if (!pepNovoCheckBox.isSelected() && !direcTagCheckBox.isSelected() && !pNovoCheckBox.isSelected() && !novorCheckBox.isSelected()) { - if (showMessage && valid) { - JOptionPane.showMessageDialog(this, "You need to select at least one sequencing method.", "No Sequencing Methods Selected", JOptionPane.WARNING_MESSAGE); - } - valid = false; - } - - if (spectrumFiles.isEmpty()) { - if (showMessage && valid) { - JOptionPane.showMessageDialog(this, "You need to select at least one spectrum file.", "Spectra Files Not Found", JOptionPane.WARNING_MESSAGE); - } - spectraFilesLabel.setForeground(Color.RED); - spectraFilesLabel.setToolTipText("Please select at least one spectrum file"); - valid = false; - } else { - spectraFilesLabel.setToolTipText(null); - spectraFilesLabel.setForeground(Color.BLACK); - } + private boolean validateInput(boolean showMessage) { + + boolean valid = true; + String startButtonToolTip = "Click here to start sequencing"; + + if (!pepNovoCheckBox.isSelected() && !direcTagCheckBox.isSelected() && !pNovoCheckBox.isSelected() && !novorCheckBox.isSelected() + && !instaNovoCheckBox.isSelected() && !instaNovoPlusCheckBox.isSelected() && !instaNovoRefineCheckBox.isSelected()) { + if (showMessage && valid) { + JOptionPane.showMessageDialog(this, "You need to select at least one sequencing method.", "No Sequencing Methods Selected", JOptionPane.WARNING_MESSAGE); + } + startButtonToolTip = "Select at least one sequencing method"; + valid = false; + } + + if (isInstaNovoSelected() && !hasValidInstaNovoFolder()) { + startButtonToolTip = "Install or select InstaNovo before prediction starts"; + } + updateInstaNovoFolderState(); + + if (spectrumFiles.isEmpty()) { + if (showMessage && valid) { + JOptionPane.showMessageDialog(this, "You need to select at least one spectrum file.", "Spectra Files Not Found", JOptionPane.WARNING_MESSAGE); + } + spectraFilesLabel.setForeground(Color.RED); + spectraFilesLabel.setToolTipText("Please select at least one spectrum file"); + startButtonToolTip = "Select at least one spectrum file"; + valid = false; + } else { + spectraFilesLabel.setToolTipText(null); + spectraFilesLabel.setForeground(Color.BLACK); + } // validate the search parameters - if (!validateParametersInput(showMessage)) { - valid = false; - } + if (!validateParametersInput(showMessage)) { + startButtonToolTip = "Check the de novo settings"; + valid = false; + } // validate the output folder if (outputFolderTextField.getText() == null || outputFolderTextField.getText().trim().equals("")) { - if (showMessage && valid) { - JOptionPane.showMessageDialog(this, "You need to specify an output folder.", "Output Folder Not Found", JOptionPane.WARNING_MESSAGE); - } - resultFolderLbl.setForeground(Color.RED); - resultFolderLbl.setToolTipText("Please select an output folder"); - valid = false; - } else if (!new File(outputFolderTextField.getText()).exists()) { - int value = JOptionPane.showConfirmDialog(this, "The selected output folder does not exist. Do you want to create it?", "Folder Not Found", JOptionPane.YES_NO_OPTION); + if (showMessage && valid) { + JOptionPane.showMessageDialog(this, "You need to specify an output folder.", "Output Folder Not Found", JOptionPane.WARNING_MESSAGE); + } + resultFolderLbl.setForeground(Color.RED); + resultFolderLbl.setToolTipText("Please select an output folder"); + startButtonToolTip = "Select an output folder"; + valid = false; + } else if (!new File(outputFolderTextField.getText()).exists()) { + int value = JOptionPane.showConfirmDialog(this, "The selected output folder does not exist. Do you want to create it?", "Folder Not Found", JOptionPane.YES_NO_OPTION); if (value == JOptionPane.YES_OPTION) { boolean success = new File(outputFolderTextField.getText()).mkdir(); if (!success) { - JOptionPane.showMessageDialog(this, "Failed to create the output folder. Please create it manually and re-select it.", "File Error", JOptionPane.ERROR_MESSAGE); - valid = false; - } else { - resultFolderLbl.setForeground(Color.BLACK); + JOptionPane.showMessageDialog(this, "Failed to create the output folder. Please create it manually and re-select it.", "File Error", JOptionPane.ERROR_MESSAGE); + startButtonToolTip = "Select an existing output folder"; + valid = false; + } else { + resultFolderLbl.setForeground(Color.BLACK); resultFolderLbl.setToolTipText(null); } } @@ -3194,16 +3881,18 @@ private boolean validateInput(boolean showMessage) { resultFolderLbl.setToolTipText(null); } - if (searchParameters == null) { - configurationFileLbl.setForeground(Color.RED); - configurationFileLbl.setToolTipText("Please check the settings"); - } else { - // @TODO: do we need to check more?? - } - - startButton.setEnabled(valid); - return valid; - } + if (searchParameters == null) { + configurationFileLbl.setForeground(Color.RED); + configurationFileLbl.setToolTipText("Please check the settings"); + startButtonToolTip = "Check the de novo settings"; + } else { + // @TODO: do we need to check more?? + } + + startButton.setEnabled(valid); + startButton.setToolTipText(startButtonToolTip); + return valid; + } /** * Inspects the parameters validity. @@ -3258,33 +3947,85 @@ private void catchException(Exception e) { } /** - * This method saves PTM usage in the conf folder. + * This method saves Modification usage in the conf folder. */ - private void saveModificationUsage() { + private void saveModificationUsage() { File folder = new File(getJarFilePath() + File.separator + "resources" + File.separator + "conf" + File.separator); if (!folder.exists()) { JOptionPane.showMessageDialog(this, new String[]{"Unable to find folder: '" + folder.getAbsolutePath() + "'!", - "Could not save PTM usage."}, "Folder Not Found", JOptionPane.WARNING_MESSAGE); + "Could not save Modification usage."}, "Folder Not Found", JOptionPane.WARNING_MESSAGE); } else { File output = new File(folder, DeNovoSequencingHandler.DENOVOGUI_COMFIGURATION_FILE); try { BufferedWriter bw = new BufferedWriter(new FileWriter(output)); bw.write("Modification use:" + System.getProperty("line.separator")); - bw.write(SearchSettingsDialog.getModificationUseAsString(modificationUse) + System.getProperty("line.separator")); + bw.write(getModificationUseAsString(modificationUse) + System.getProperty("line.separator")); bw.flush(); bw.close(); } catch (IOException ioe) { ioe.printStackTrace(); JOptionPane.showMessageDialog(this, new String[]{"Unable to write file: '" + ioe.getMessage() + "'!", - "Could not save PTM usage."}, "File Error", JOptionPane.WARNING_MESSAGE); - } - } - } - - /** - * Returns the tips of the day. + "Could not save Modification usage."}, "File Error", JOptionPane.WARNING_MESSAGE); + } + } + } + + /** + * Loads the saved modification usage. + * + * @param modUseFile the modification usage file + * + * @return the saved modification usage + * + * @throws IOException if the file cannot be read + */ + private static ArrayList loadModificationsUse(File modUseFile) throws IOException { + + ArrayList result = new ArrayList(); + + if (!modUseFile.exists()) { + return result; + } + + java.io.BufferedReader br = new java.io.BufferedReader(new java.io.FileReader(modUseFile)); + + try { + String line; + + while ((line = br.readLine()) != null) { + line = line.trim(); + + if (!line.isEmpty() && !line.endsWith(":")) { + for (String modification : line.split(",")) { + String trimmed = modification.trim(); + if (!trimmed.isEmpty()) { + result.add(trimmed); + } + } + } + } + } finally { + br.close(); + } + + return result; + } + + /** + * Returns the modification usage as a comma-separated string. + * + * @param modificationUse the modification usage + * + * @return the modification usage as a comma-separated string + */ + private static String getModificationUseAsString(ArrayList modificationUse) { + return String.join(", ", modificationUse); + } + + /** + * Returns the tips of the day. * * @return the tips of the day in an ArrayList */ @@ -3321,20 +4062,21 @@ public ArrayList getTips() { * * @return the best score for this algorithm */ - public static double getBestScore(Advocate advocate, Set scores) { - double bestScore = 0.0; - for (double score : scores) { - if (advocate == Advocate.direcTag) { - if (bestScore == 0.0 || score < bestScore) { - bestScore = score; - } - } else if (advocate == Advocate.pepnovo || advocate == Advocate.pNovo || advocate == Advocate.novor) { - if (score > bestScore) { - bestScore = score; - } - } else { - throw new IllegalArgumentException("Best score selection not implemented for algorithm " + advocate + "."); - } + public static double getBestScore(Advocate advocate, Set scores) { + double bestScore = 0.0; + for (double score : scores) { + if (advocate == Advocate.direcTag) { + if (bestScore == 0.0 || score < bestScore) { + bestScore = score; + } + } else if (advocate == Advocate.pepnovo || advocate == Advocate.pNovo || advocate == Advocate.novor + || advocate == Advocate.instanovo || advocate == Advocate.instanovoPlus || advocate == Advocate.instanovoRefined) { + if (bestScore == 0.0 || score > bestScore) { + bestScore = score; + } + } else { + throw new IllegalArgumentException("Best score selection not implemented for algorithm " + advocate + "."); + } } return bestScore; } @@ -3348,8 +4090,9 @@ public static double getBestScore(Advocate advocate, Set scores) { public static void sortScores(Advocate advocate, ArrayList scores) { if (advocate == Advocate.direcTag) { Collections.sort(scores); - } else if (advocate == Advocate.pepnovo || advocate == Advocate.pNovo || advocate == Advocate.novor) { - Collections.sort(scores, Collections.reverseOrder()); + } else if (advocate == Advocate.pepnovo || advocate == Advocate.pNovo || advocate == Advocate.novor + || advocate == Advocate.instanovo || advocate == Advocate.instanovoPlus || advocate == Advocate.instanovoRefined) { + Collections.sort(scores, Collections.reverseOrder()); } else { throw new IllegalArgumentException("Sorting order not implemented for algorithm " + advocate + "."); } @@ -3373,11 +4116,7 @@ public boolean checkForNewVersion() { MavenJarFile oldMavenJarFile = new MavenJarFile(jarFile.toURI()); - URL jarRepository = new URL( - "https", - "genesis.ugent.be", - "/archiva/repository/maven2/" - ); + URL jarRepository = java.net.URI.create("https://genesis.ugent.be/archiva/repository/maven2/").toURL(); return CompomicsWrapper.checkForNewDeployedVersion( "DeNovoGUI", @@ -3411,7 +4150,7 @@ public boolean checkForNewVersion() { * * @return the sequence matching preferences */ - public SequenceMatchingPreferences getSequenceMatchingPreferences() { + public SequenceMatchingParameters getSequenceMatchingParameters() { return sequenceMatchingPreferences; } @@ -3420,7 +4159,7 @@ public SequenceMatchingPreferences getSequenceMatchingPreferences() { * * @param sequenceMatchingPreferences the sequence matching preferences */ - public void setSequenceMatchingPreferences(SequenceMatchingPreferences sequenceMatchingPreferences) { + public void setSequenceMatchingParameters(SequenceMatchingParameters sequenceMatchingPreferences) { this.sequenceMatchingPreferences = sequenceMatchingPreferences; } @@ -3431,22 +4170,22 @@ public void editPathSettings() { try { HashMap pathSettings = new HashMap(); for (DeNovoGUIPathKey deNovoGUIPathKey : DeNovoGUIPathKey.values()) { - pathSettings.put(deNovoGUIPathKey, DeNovoGUIPathPreferences.getPathPreference(deNovoGUIPathKey)); + pathSettings.put(deNovoGUIPathKey, DeNovoGUIPathPreferences.getPathParameter(deNovoGUIPathKey)); } - for (UtilitiesPathPreferences.UtilitiesPathKey utilitiesPathKey : UtilitiesPathPreferences.UtilitiesPathKey.values()) { - pathSettings.put(utilitiesPathKey, UtilitiesPathPreferences.getPathPreference(utilitiesPathKey)); + for (UtilitiesPathParameters.UtilitiesPathKey utilitiesPathKey : UtilitiesPathParameters.UtilitiesPathKey.values()) { + pathSettings.put(utilitiesPathKey, UtilitiesPathParameters.getPathParameter(utilitiesPathKey)); } - PathSettingsDialog pathSettingsDialog = new PathSettingsDialog(this, "DeNovoGUI", pathSettings); + PathParametersDialog pathSettingsDialog = new PathParametersDialog(this, "DeNovoGUI", pathSettings); if (!pathSettingsDialog.isCanceled()) { HashMap newSettings = pathSettingsDialog.getKeyToPathMap(); for (PathKey pathKey : pathSettings.keySet()) { String newPath = newSettings.get(pathKey); if (!pathSettings.get(pathKey).equals(newPath)) { - DeNovoGUIPathPreferences.setPathPreference(pathKey, newPath); + DeNovoGUIPathPreferences.setPathParameter(pathKey, newPath); } } // write path file preference - File destinationFile = new File(getJarFilePath(), UtilitiesPathPreferences.configurationFileName); + File destinationFile = new File(getJarFilePath(), UtilitiesPathParameters.configurationFileName); try { DeNovoGUIPathPreferences.writeConfigurationToFile(destinationFile); restart(); @@ -3505,7 +4244,7 @@ public boolean checkSearchParameters(SearchParameters tempSearchParameters) { if (error != null) { JOptionPane.showMessageDialog(this, error, - "PTM Definition Changed", JOptionPane.WARNING_MESSAGE); + "Modification Definition Changed", JOptionPane.WARNING_MESSAGE); } settingsFileJTextField.setText(parametersFile.getName()); return true; diff --git a/src/main/java/com/compomics/denovogui/gui/FindPanel.java b/src/main/java/com/compomics/denovogui/gui/FindPanel.java index 3a1330e..f0ec33f 100644 --- a/src/main/java/com/compomics/denovogui/gui/FindPanel.java +++ b/src/main/java/com/compomics/denovogui/gui/FindPanel.java @@ -1,11 +1,13 @@ package com.compomics.denovogui.gui; + +import com.compomics.denovogui.io.SpectrumFactory; import com.compomics.util.experiment.identification.Advocate; import com.compomics.util.experiment.identification.SpectrumIdentificationAssumption; import com.compomics.util.experiment.identification.spectrum_assumptions.PeptideAssumption; import com.compomics.util.experiment.identification.spectrum_assumptions.TagAssumption; -import com.compomics.util.experiment.massspectrometry.Spectrum; -import com.compomics.util.experiment.massspectrometry.SpectrumFactory; +import com.compomics.util.experiment.mass_spectrometry.spectra.Spectrum; +import com.compomics.util.experiment.mass_spectrometry.SpectrumProvider; import java.awt.Color; import java.awt.event.KeyEvent; import java.util.ArrayList; diff --git a/src/main/java/com/compomics/denovogui/gui/ProteinMappingDialog.java b/src/main/java/com/compomics/denovogui/gui/ProteinMappingDialog.java index 9a63de5..e0bf9d0 100644 --- a/src/main/java/com/compomics/denovogui/gui/ProteinMappingDialog.java +++ b/src/main/java/com/compomics/denovogui/gui/ProteinMappingDialog.java @@ -1,10 +1,11 @@ package com.compomics.denovogui.gui; -import com.compomics.util.experiment.biology.PTMFactory; +import com.compomics.util.experiment.biology.modifications.ModificationFactory; +import com.compomics.util.experiment.io.biology.protein.FastaParameters; import com.compomics.util.experiment.identification.protein_sequences.SequenceFactory; -import com.compomics.util.gui.ptm.ModificationsDialog; -import com.compomics.util.experiment.identification.identification_parameters.PtmSettings; -import com.compomics.util.protein_sequences_manager.gui.SequenceDbDetailsDialog; +import com.compomics.util.gui.modification.ModificationsDialog; +import com.compomics.util.parameters.identification.search.ModificationParameters; +import com.compomics.util.gui.parameters.identification.search.SequenceDbDetailsDialog; import java.awt.Color; import java.awt.event.MouseEvent; import java.io.IOException; @@ -35,7 +36,7 @@ public class ProteinMappingDialog extends javax.swing.JDialog{ /** * The post translational modifications factory. */ - private PTMFactory ptmFactory = PTMFactory.getInstance(); + private ModificationFactory ptmFactory = ModificationFactory.getInstance(); /** * The parent result frame. */ @@ -64,7 +65,7 @@ public class ProteinMappingDialog extends javax.swing.JDialog{ * @param modificationProfile the modification profile used for the * identification */ - public ProteinMappingDialog(ResultsFrame resultFrame, PtmSettings modificationProfile) { + public ProteinMappingDialog(ResultsFrame resultFrame, ModificationParameters modificationProfile) { super(resultFrame, true); this.resultsFrame = resultFrame; if (modificationProfile != null) { @@ -170,7 +171,7 @@ public boolean isCellEditable(int rowIndex, int columnIndex) { ((DefaultTableModel) modificationsTable.getModel()).addRow( new Object[]{ptmFactory.getColor(mod), mod, - ptmFactory.getPTM(mod).getMass(), + ptmFactory.getModification(mod).getMass(), variableModifications.contains(mod), fixedModifications.contains(mod)}); } @@ -182,11 +183,11 @@ public boolean isCellEditable(int rowIndex, int columnIndex) { double minMass = Double.MAX_VALUE; for (String ptm : ptmFactory.getPTMs()) { - if (ptmFactory.getPTM(ptm).getMass() > maxMass) { - maxMass = ptmFactory.getPTM(ptm).getMass(); + if (ptmFactory.getModification(ptm).getMass() > maxMass) { + maxMass = ptmFactory.getModification(ptm).getMass(); } - if (ptmFactory.getPTM(ptm).getMass() < minMass) { - minMass = ptmFactory.getPTM(ptm).getMass(); + if (ptmFactory.getModification(ptm).getMass() < minMass) { + minMass = ptmFactory.getModification(ptm).getMass(); } } @@ -491,8 +492,15 @@ private void editDatabaseSettingsActionPerformed(java.awt.event.ActionEvent evt) } } - SequenceDbDetailsDialog sequenceDbDetailsDialog = new SequenceDbDetailsDialog(resultsFrame, - resultsFrame.getDeNovoGUI().getLastSelectedFolder(), true, resultsFrame.getNormalIcon(), resultsFrame.getWaitingIcon()); + SequenceDbDetailsDialog sequenceDbDetailsDialog = new SequenceDbDetailsDialog( + resultsFrame, + "FASTA Database", + new FastaParameters(), + resultsFrame.getDeNovoGUI().getLastSelectedFolder(), + true, + resultsFrame.getNormalIcon(), + resultsFrame.getWaitingIcon() + ); boolean success = sequenceDbDetailsDialog.selectDB(true); if (success) { diff --git a/src/main/java/com/compomics/denovogui/gui/ResultsFrame.java b/src/main/java/com/compomics/denovogui/gui/ResultsFrame.java index 73d7778..904c3f3 100644 --- a/src/main/java/com/compomics/denovogui/gui/ResultsFrame.java +++ b/src/main/java/com/compomics/denovogui/gui/ResultsFrame.java @@ -1,4 +1,6 @@ package com.compomics.denovogui.gui; + +import com.compomics.denovogui.io.SpectrumFactory; import com.compomics.denovogui.DeNovoGUIWrapper; import com.compomics.denovogui.gui.tablemodels.AssumptionsTableModel; @@ -7,53 +9,45 @@ import com.compomics.denovogui.io.TextExporter; import com.compomics.denovogui.util.BareBonesBrowserLaunch; import com.compomics.util.Util; -import com.compomics.util.db.DerbyUtil; -import com.compomics.util.db.ObjectsCache; +import com.compomics.util.db.object.ObjectsCache; +import com.compomics.util.db.object.ObjectsDB; import com.compomics.util.exceptions.exception_handlers.FrameExceptionHandler; -import com.compomics.util.experiment.MsExperiment; -import com.compomics.util.experiment.ProteomicAnalysis; -import com.compomics.util.experiment.SampleAnalysisSet; -import com.compomics.util.experiment.biology.AminoAcid; -import com.compomics.util.experiment.biology.AminoAcidPattern; -import com.compomics.util.experiment.biology.AminoAcidSequence; -import com.compomics.util.experiment.biology.Ion; -import com.compomics.util.experiment.biology.IonFactory; -import com.compomics.util.experiment.biology.NeutralLoss; -import com.compomics.util.experiment.biology.PTM; -import com.compomics.util.experiment.biology.PTMFactory; -import com.compomics.util.experiment.biology.Peptide; -import com.compomics.util.experiment.biology.Sample; -import com.compomics.util.experiment.biology.ions.ReporterIon; -import com.compomics.util.experiment.biology.ions.TagFragmentIon; +import com.compomics.util.experiment.biology.aminoacids.AminoAcid; +import com.compomics.util.experiment.biology.aminoacids.sequence.AminoAcidPattern; +import com.compomics.util.experiment.biology.aminoacids.sequence.AminoAcidSequence; +import com.compomics.util.experiment.biology.ions.Ion; +import com.compomics.util.experiment.biology.ions.IonFactory; +import com.compomics.util.experiment.biology.ions.NeutralLoss; +import com.compomics.util.experiment.biology.modifications.Modification; +import com.compomics.util.experiment.biology.modifications.ModificationFactory; +import com.compomics.util.experiment.biology.proteins.Peptide; +import com.compomics.util.experiment.biology.ions.impl.ReporterIon; +import com.compomics.util.experiment.biology.ions.impl.TagFragmentIon; import com.compomics.util.experiment.identification.Advocate; import com.compomics.util.experiment.identification.Identification; -import com.compomics.util.experiment.identification.IdentificationMethod; import com.compomics.util.experiment.identification.spectrum_assumptions.PeptideAssumption; -import com.compomics.util.experiment.identification.identification_parameters.SearchParameters; +import com.compomics.util.parameters.identification.search.SearchParameters; import com.compomics.util.experiment.identification.protein_sequences.SequenceFactory; import com.compomics.util.experiment.identification.spectrum_annotation.SpectrumAnnotator; import com.compomics.util.experiment.identification.SpectrumIdentificationAssumption; import com.compomics.util.experiment.identification.spectrum_assumptions.TagAssumption; -import com.compomics.util.experiment.identification.identification_parameters.tool_specific.PepnovoParameters; -import com.compomics.util.experiment.identification.identifications.Ms2Identification; +import com.compomics.util.parameters.identification.tool_specific.PepnovoParameters; import com.compomics.util.experiment.identification.matches.IonMatch; import com.compomics.util.experiment.identification.matches.ModificationMatch; import com.compomics.util.experiment.identification.matches.SpectrumMatch; import com.compomics.util.experiment.identification.matches_iterators.PsmIterator; -import com.compomics.util.experiment.identification.protein_inference.proteintree.ProteinTree; import com.compomics.util.experiment.identification.spectrum_annotation.spectrum_annotators.TagSpectrumAnnotator; import com.compomics.util.experiment.identification.amino_acid_tags.Tag; import com.compomics.util.experiment.identification.amino_acid_tags.TagComponent; -import com.compomics.util.experiment.identification.amino_acid_tags.matchers.TagMatcher; -import com.compomics.util.experiment.biology.MassGap; -import com.compomics.util.experiment.biology.ions.PeptideFragmentIon; -import com.compomics.util.experiment.io.identifications.IdfileReader; -import com.compomics.util.experiment.io.identifications.IdfileReaderFactory; -import com.compomics.util.experiment.massspectrometry.MSnSpectrum; -import com.compomics.util.experiment.massspectrometry.Precursor; -import com.compomics.util.experiment.massspectrometry.Spectrum; -import com.compomics.util.experiment.massspectrometry.SpectrumFactory; -import com.compomics.util.experiment.refinementparameters.PepnovoAssumptionDetails; +import com.compomics.util.experiment.identification.amino_acid_tags.MassGap; +import com.compomics.util.experiment.biology.ions.impl.PeptideFragmentIon; +import com.compomics.util.experiment.io.identification.IdfileReader; +import com.compomics.util.experiment.io.identification.IdfileReaderFactory; +import com.compomics.util.experiment.mass_spectrometry.spectra.Spectrum; +import com.compomics.util.experiment.mass_spectrometry.spectra.Precursor; +import com.compomics.util.experiment.mass_spectrometry.spectra.Spectrum; +import com.compomics.util.experiment.mass_spectrometry.SpectrumProvider; +import com.compomics.util.experiment.refinement_parameters.PepnovoAssumptionDetails; import com.compomics.util.gui.JOptionEditorPane; import com.compomics.util.gui.error_handlers.BugReport; import com.compomics.util.gui.error_handlers.HelpDialog; @@ -62,16 +56,13 @@ import com.compomics.util.gui.spectrum.SpectrumPanel; import com.compomics.util.waiting.WaitingHandler; import com.compomics.util.gui.waiting.waitinghandlers.ProgressDialogX; -import com.compomics.util.experiment.identification.spectrum_annotation.AnnotationSettings; -import com.compomics.util.experiment.identification.identification_parameters.PtmSettings; -import com.compomics.util.experiment.identification.protein_inference.PeptideMapper; -import com.compomics.util.experiment.identification.protein_inference.PeptideMapperType; -import com.compomics.util.experiment.identification.protein_inference.PeptideProteinMapping; -import com.compomics.util.preferences.SequenceMatchingPreferences; -import com.compomics.util.experiment.identification.spectrum_annotation.SpecificAnnotationSettings; +import com.compomics.util.experiment.identification.spectrum_annotation.AnnotationParameters; +import com.compomics.util.parameters.identification.search.ModificationParameters; +import com.compomics.util.parameters.identification.advanced.SequenceMatchingParameters; +import com.compomics.util.experiment.identification.spectrum_annotation.SpecificAnnotationParameters; import com.compomics.util.experiment.identification.spectrum_annotation.spectrum_annotators.PeptideSpectrumAnnotator; -import com.compomics.util.preferences.PeptideVariantsPreferences; -import com.compomics.util.preferences.UtilitiesUserPreferences; +import com.compomics.util.parameters.identification.advanced.PeptideVariantsParameters; +import com.compomics.util.parameters.UtilitiesUserParameters; import java.awt.Color; import java.awt.Component; import static java.awt.Frame.MAXIMIZED_BOTH; @@ -84,13 +75,14 @@ import java.io.File; import java.io.FileWriter; import java.io.IOException; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import javax.swing.Box; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import javax.swing.Box; import javax.swing.DefaultComboBoxModel; import javax.swing.ImageIcon; import javax.swing.JCheckBoxMenuItem; @@ -112,7 +104,6 @@ import no.uib.jsparklines.renderers.JSparklinesIntegerColorTableCellRenderer; import no.uib.jsparklines.renderers.JSparklinesIntervalChartTableCellRenderer; import org.jfree.chart.plot.PlotOrientation; -import uk.ac.ebi.jmzml.xml.io.MzMLUnmarshallerException; /** * Frame for showing the results of de novo sequencing. @@ -136,11 +127,11 @@ public class ResultsFrame extends javax.swing.JFrame { /** * The annotation preferences. */ - private AnnotationSettings annotationPreferences = new AnnotationSettings(); + private AnnotationParameters annotationPreferences = new AnnotationParameters(); /** * The specific annotation preferences. */ - private SpecificAnnotationSettings specificAnnotationPreferences; + private SpecificAnnotationParameters specificAnnotationPreferences; /** * The charge menus. */ @@ -150,9 +141,9 @@ public class ResultsFrame extends javax.swing.JFrame { */ private HashMap lossMenus = new HashMap(); /** - * The compomics PTM factory. + * The compomics Modification factory. */ - private PTMFactory ptmFactory = PTMFactory.getInstance(); + private ModificationFactory ptmFactory = ModificationFactory.getInstance(); /** * The query spectra table column header tooltips. */ @@ -221,10 +212,22 @@ public class ResultsFrame extends javax.swing.JFrame { * The minimal Novor score. */ private double minNovorScore = Double.MAX_VALUE; - /** - * The maximal Novor score. - */ - private double maxNovorScore = Double.MIN_VALUE; + /** + * The maximal Novor score. + */ + private double maxNovorScore = Double.MIN_VALUE; + /** + * The maximal InstaNovo score. + */ + private double maxInstaNovoScore = Double.MIN_VALUE; + /** + * The maximal InstaNovo+ score. + */ + private double maxInstaNovoPlusScore = Double.MIN_VALUE; + /** + * The maximal InstaNovo with refinement score. + */ + private double maxInstaNovoRefinedScore = Double.MIN_VALUE; /** * The maximal n gap. */ @@ -363,9 +366,12 @@ private void setUpGUI() { querySpectraTableToolTips.add("Number of Peaks"); querySpectraTableToolTips.add("Max PepNovo+ Score"); querySpectraTableToolTips.add("Min DirecTag E-Value"); - querySpectraTableToolTips.add("Max pNovo+ Score"); - querySpectraTableToolTips.add("Max Novor Score"); - querySpectraTableToolTips.add("De Novo Solution"); + querySpectraTableToolTips.add("Max pNovo+ Score"); + querySpectraTableToolTips.add("Max Novor Score"); + querySpectraTableToolTips.add("Max InstaNovo Score"); + querySpectraTableToolTips.add("Max InstaNovo+ Score"); + querySpectraTableToolTips.add("Max InstaNovo with refinement Score"); + querySpectraTableToolTips.add("De Novo Solution"); deNovoPeptidesTableToolTips = new ArrayList(); deNovoPeptidesTableToolTips.add(null); @@ -378,9 +384,12 @@ private void setUpGUI() { deNovoPeptidesTableToolTips.add("PepNovo+ Rank Score"); deNovoPeptidesTableToolTips.add("PepNovo+ Score"); deNovoPeptidesTableToolTips.add("DirecTag E-Value"); - deNovoPeptidesTableToolTips.add("pNovo+ Score"); - deNovoPeptidesTableToolTips.add("Novor Score"); - deNovoPeptidesTableToolTips.add("BLAST Sequence"); + deNovoPeptidesTableToolTips.add("pNovo+ Score"); + deNovoPeptidesTableToolTips.add("Novor Score"); + deNovoPeptidesTableToolTips.add("InstaNovo Score"); + deNovoPeptidesTableToolTips.add("InstaNovo+ Score"); + deNovoPeptidesTableToolTips.add("InstaNovo with refinement Score"); + deNovoPeptidesTableToolTips.add("BLAST Sequence"); // set the title this.setTitle("DeNovoGUI " + deNovoGUI.getVersion()); @@ -449,8 +458,14 @@ private void setSpectrumTableProperties() { ((JSparklinesBarChartTableCellRenderer) querySpectraTable.getColumn("Score (D)").getCellRenderer()).showNumberAndChart(true, labelWidth); querySpectraTable.getColumn("Score (p)").setCellRenderer(new JSparklinesBarChartTableCellRenderer(PlotOrientation.HORIZONTAL, maxPNovoScore, sparklineColor)); ((JSparklinesBarChartTableCellRenderer) querySpectraTable.getColumn("Score (p)").getCellRenderer()).showNumberAndChart(true, labelWidth); - querySpectraTable.getColumn("Score (N)").setCellRenderer(new JSparklinesBarChartTableCellRenderer(PlotOrientation.HORIZONTAL, maxNovorScore, sparklineColor)); - ((JSparklinesBarChartTableCellRenderer) querySpectraTable.getColumn("Score (N)").getCellRenderer()).showNumberAndChart(true, labelWidth); + querySpectraTable.getColumn("Score (N)").setCellRenderer(new JSparklinesBarChartTableCellRenderer(PlotOrientation.HORIZONTAL, maxNovorScore, sparklineColor)); + ((JSparklinesBarChartTableCellRenderer) querySpectraTable.getColumn("Score (N)").getCellRenderer()).showNumberAndChart(true, labelWidth); + querySpectraTable.getColumn("Score (I)").setCellRenderer(new JSparklinesBarChartTableCellRenderer(PlotOrientation.HORIZONTAL, maxInstaNovoScore, sparklineColor)); + ((JSparklinesBarChartTableCellRenderer) querySpectraTable.getColumn("Score (I)").getCellRenderer()).showNumberAndChart(true, labelWidth); + querySpectraTable.getColumn("Score (I+)").setCellRenderer(new JSparklinesBarChartTableCellRenderer(PlotOrientation.HORIZONTAL, maxInstaNovoPlusScore, sparklineColor)); + ((JSparklinesBarChartTableCellRenderer) querySpectraTable.getColumn("Score (I+)").getCellRenderer()).showNumberAndChart(true, labelWidth); + querySpectraTable.getColumn("Score (Ir)").setCellRenderer(new JSparklinesBarChartTableCellRenderer(PlotOrientation.HORIZONTAL, maxInstaNovoRefinedScore, sparklineColor)); + ((JSparklinesBarChartTableCellRenderer) querySpectraTable.getColumn("Score (Ir)").getCellRenderer()).showNumberAndChart(true, labelWidth); // make sure that the user is made aware that the tool is doing something during sorting of the query table querySpectraTable.getRowSorter().addRowSorterListener(new RowSorterListener() { @@ -501,8 +516,14 @@ private void setAssumptionsTableProperties() { ((JSparklinesBarChartTableCellRenderer) deNovoMatchesTable.getColumn("Score (P)").getCellRenderer()).showNumberAndChart(true, labelWidth); deNovoMatchesTable.getColumn("Score (p)").setCellRenderer(new JSparklinesBarChartTableCellRenderer(PlotOrientation.HORIZONTAL, maxPNovoScore, sparklineColor)); ((JSparklinesBarChartTableCellRenderer) deNovoMatchesTable.getColumn("Score (p)").getCellRenderer()).showNumberAndChart(true, labelWidth); - deNovoMatchesTable.getColumn("Score (N)").setCellRenderer(new JSparklinesBarChartTableCellRenderer(PlotOrientation.HORIZONTAL, maxNovorScore, sparklineColor)); - ((JSparklinesBarChartTableCellRenderer) deNovoMatchesTable.getColumn("Score (N)").getCellRenderer()).showNumberAndChart(true, labelWidth); + deNovoMatchesTable.getColumn("Score (N)").setCellRenderer(new JSparklinesBarChartTableCellRenderer(PlotOrientation.HORIZONTAL, maxNovorScore, sparklineColor)); + ((JSparklinesBarChartTableCellRenderer) deNovoMatchesTable.getColumn("Score (N)").getCellRenderer()).showNumberAndChart(true, labelWidth); + deNovoMatchesTable.getColumn("Score (I)").setCellRenderer(new JSparklinesBarChartTableCellRenderer(PlotOrientation.HORIZONTAL, maxInstaNovoScore, sparklineColor)); + ((JSparklinesBarChartTableCellRenderer) deNovoMatchesTable.getColumn("Score (I)").getCellRenderer()).showNumberAndChart(true, labelWidth); + deNovoMatchesTable.getColumn("Score (I+)").setCellRenderer(new JSparklinesBarChartTableCellRenderer(PlotOrientation.HORIZONTAL, maxInstaNovoPlusScore, sparklineColor)); + ((JSparklinesBarChartTableCellRenderer) deNovoMatchesTable.getColumn("Score (I+)").getCellRenderer()).showNumberAndChart(true, labelWidth); + deNovoMatchesTable.getColumn("Score (Ir)").setCellRenderer(new JSparklinesBarChartTableCellRenderer(PlotOrientation.HORIZONTAL, maxInstaNovoRefinedScore, sparklineColor)); + ((JSparklinesBarChartTableCellRenderer) deNovoMatchesTable.getColumn("Score (Ir)").getCellRenderer()).showNumberAndChart(true, labelWidth); deNovoMatchesTable.getColumn("N-Gap").setCellRenderer(new JSparklinesBarChartTableCellRenderer(PlotOrientation.HORIZONTAL, maxNGap, sparklineColor)); ((JSparklinesBarChartTableCellRenderer) deNovoMatchesTable.getColumn("N-Gap").getCellRenderer()).showNumberAndChart(true, labelWidth); deNovoMatchesTable.getColumn("C-Gap").setCellRenderer(new JSparklinesBarChartTableCellRenderer(PlotOrientation.HORIZONTAL, maxCGap, sparklineColor)); @@ -516,11 +537,24 @@ private void setAssumptionsTableProperties() { null, "Click to BLAST tag sequence", null)); - deNovoMatchesTable.getColumn("SA").setCellRenderer(new JSparklinesIntegerColorTableCellRenderer(Color.LIGHT_GRAY, Advocate.getAdvocateColorMap(), Advocate.getAdvocateToolTipMap())); - } - - /** - * Returns a reference to the main DeNovoGUI frame. + deNovoMatchesTable.getColumn("SA").setCellRenderer(new JSparklinesIntegerColorTableCellRenderer(Color.LIGHT_GRAY, Advocate.getAdvocateColorMap(), Advocate.getAdvocateToolTipMap())); + } + + /** + * Sets a table model and rebuilds the visible columns from the model. + * + * @param table the table + * @param tableModel the table model + */ + private void setTableModel(JTable table, TableModel tableModel) { + table.setAutoCreateColumnsFromModel(true); + table.setModel(tableModel); + table.createDefaultColumnsFromModel(); + table.setAutoCreateRowSorter(true); + } + + /** + * Returns a reference to the main DeNovoGUI frame. * * @return a reference to the main DeNovoGUI frame. */ @@ -600,15 +634,21 @@ private void initComponents() { querySpectraPanel = new javax.swing.JPanel(); querySpectraTableScrollPane = new javax.swing.JScrollPane(); querySpectraTable = new JTable() { - protected JTableHeader createDefaultTableHeader() { - return new JTableHeader(columnModel) { - public String getToolTipText(MouseEvent e) { - java.awt.Point p = e.getPoint(); - int index = columnModel.getColumnIndexAtX(p.x); - int realIndex = columnModel.getColumn(index).getModelIndex(); - String tip = (String) querySpectraTableToolTips.get(realIndex); - return tip; - } + protected JTableHeader createDefaultTableHeader() { + return new JTableHeader(columnModel) { + public String getToolTipText(MouseEvent e) { + java.awt.Point p = e.getPoint(); + int index = columnModel.getColumnIndexAtX(p.x); + if (index < 0 || index >= columnModel.getColumnCount()) { + return null; + } + int realIndex = columnModel.getColumn(index).getModelIndex(); + if (realIndex < 0 || realIndex >= querySpectraTableToolTips.size()) { + return null; + } + String tip = (String) querySpectraTableToolTips.get(realIndex); + return tip; + } }; } }; @@ -617,15 +657,21 @@ public String getToolTipText(MouseEvent e) { deNovoMatchesPanel = new javax.swing.JPanel(); deNovoPeptidesTableScrollPane = new javax.swing.JScrollPane(); deNovoMatchesTable = new JTable() { - protected JTableHeader createDefaultTableHeader() { - return new JTableHeader(columnModel) { - public String getToolTipText(MouseEvent e) { - java.awt.Point p = e.getPoint(); - int index = columnModel.getColumnIndexAtX(p.x); - int realIndex = columnModel.getColumn(index).getModelIndex(); - String tip = (String) deNovoPeptidesTableToolTips.get(realIndex); - return tip; - } + protected JTableHeader createDefaultTableHeader() { + return new JTableHeader(columnModel) { + public String getToolTipText(MouseEvent e) { + java.awt.Point p = e.getPoint(); + int index = columnModel.getColumnIndexAtX(p.x); + if (index < 0 || index >= columnModel.getColumnCount()) { + return null; + } + int realIndex = columnModel.getColumn(index).getModelIndex(); + if (realIndex < 0 || realIndex >= deNovoPeptidesTableToolTips.size()) { + return null; + } + String tip = (String) deNovoPeptidesTableToolTips.get(realIndex); + return tip; + } }; } }; @@ -965,7 +1011,7 @@ public void windowClosing(java.awt.event.WindowEvent evt) { querySpectraPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Query Spectra")); querySpectraPanel.setOpaque(false); - querySpectraTable.setModel(new SpectrumTableModel()); + setTableModel(querySpectraTable, new SpectrumTableModel()); querySpectraTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); querySpectraTable.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { @@ -1019,7 +1065,7 @@ public void actionPerformed(java.awt.event.ActionEvent evt) { deNovoMatchesPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("De Novo Matches")); deNovoMatchesPanel.setOpaque(false); - deNovoMatchesTable.setModel(new com.compomics.denovogui.gui.tablemodels.AssumptionsTableModel()); + setTableModel(deNovoMatchesTable, new com.compomics.denovogui.gui.tablemodels.AssumptionsTableModel()); deNovoMatchesTable.setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); deNovoMatchesTable.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { @@ -1736,7 +1782,7 @@ private void exportPeptideMatchesMenuItemActionPerformed(java.awt.event.ActionEv JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) != JOptionPane.YES_OPTION; final ProteinMappingDialog mappingDialog; if (needMapping) { - mappingDialog = new ProteinMappingDialog(this, searchParameters.getPtmSettings()); + mappingDialog = new ProteinMappingDialog(this, searchParameters.getModificationParameters()); if (mappingDialog.isCanceled() || sequenceFactory.getCurrentFastaFile() == null) { return; } @@ -1768,8 +1814,7 @@ public void run() { try { boolean peptideFound = true; if (needMapping) { - SequenceMatchingPreferences sequenceMatchingPreferences = new SequenceMatchingPreferences(); //@TODO add dialog - sequenceMatchingPreferences.setPeptideMapperType(PeptideMapperType.fm_index); + SequenceMatchingParameters sequenceMatchingPreferences = new SequenceMatchingParameters(); //@TODO add dialog peptideFound = matchInProteins(sequenceMatchingPreferences, mappingDialog.getFixedModifications(), mappingDialog.getVariableModifications(), progressDialog, exportSettingsDialog.getThreshold(), exportSettingsDialog.isGreaterThenThreshold(), exportSettingsDialog.getNumberOfPeptides()); } @@ -1952,186 +1997,13 @@ private void relatedIonsCheckMenuActionPerformed(java.awt.event.ActionEvent evt) * @throws SQLException exception thrown whenever an error occurs while * interacting with the back-end database */ - private boolean matchInProteins(SequenceMatchingPreferences sequenceMatchingPreferences, ArrayList fixedModifications, ArrayList variableModifications, WaitingHandler waitingHandler, - Double scoreThreshold, boolean greaterThan, Integer aNumberOfMatches) throws IOException, ClassNotFoundException, InterruptedException, SQLException { - - double threshold = 0; - if (scoreThreshold != null) { - threshold = scoreThreshold; - } - int numberOfMatches = 10; - if (aNumberOfMatches != null) { - numberOfMatches = aNumberOfMatches; - } - - waitingHandler.setWaitingText("Importing FASTA File (Step 1 of 2). Please Wait..."); - waitingHandler.setSecondaryProgressCounterIndeterminate(false); - - if (waitingHandler.isRunCanceled()) { - return false; - } - - waitingHandler.resetSecondaryProgressCounter(); - waitingHandler.setSecondaryProgressCounterIndeterminate(true); - - UtilitiesUserPreferences userPreferences = UtilitiesUserPreferences.loadUserPreferences(); - int memoryPreference = userPreferences.getMemoryPreference(); - int nSequences = sequenceFactory.getNSequences(); - int cacheSizeInMb = nSequences * 112 / 1048576; // 112 is the size taken by one protein - if (!sequenceFactory.isDefaultReversed() || cacheSizeInMb < memoryPreference / 4) { - nSequences = sequenceFactory.getNSequences(); - sequenceFactory.setDecoyInMemory(true); - } else { - nSequences = sequenceFactory.getNTargetSequences(); - sequenceFactory.setDecoyInMemory(false); - } - long availableCachSize = 1048576l * memoryPreference / 112; // 112 is the size taken by one protein - availableCachSize *= 0.8; - if (availableCachSize > nSequences) { - availableCachSize = nSequences; - } else { - waitingHandler.appendReport("Warning: DeNovoGUI cannot load your FASTA file into memory. This will slow down the processing. " - + "Note that using large large databases also increases the number of false positives. " - + "Try to either (i) use a smaller database, (ii) increase the memory provided to DeNovoGUI, or (iii) improve the reading speed by using an SSD disc. " - + "(See also http://compomics.github.io/projects/compomics-utilities/wiki/proteininference.html.)", true, true); - - } - int cacheSize = (int) availableCachSize; - sequenceFactory.setnCache(cacheSize); - - PeptideMapper peptideMapper; - try { - peptideMapper = sequenceFactory.getDefaultPeptideMapper(sequenceMatchingPreferences, searchParameters, PeptideVariantsPreferences.getNoVariantPreferences(), waitingHandler, exceptionHandler); - } catch (SQLException e) { - waitingHandler.appendReport("Database " + sequenceFactory.getCurrentFastaFile().getName() + " could not be accessed, make sure that the file is not used by another program.", true, true); - e.printStackTrace(); - waitingHandler.setRunCanceled(); - return false; - } - int treeKeyLength = 0; - if (sequenceMatchingPreferences.getPeptideMapperType() == PeptideMapperType.tree) { - treeKeyLength = ((ProteinTree) peptideMapper).getInitialTagSize(); - } - - waitingHandler.setWaitingText("Mapping Tags (Step 2 of 2). Please Wait..."); - waitingHandler.resetSecondaryProgressCounter(); - waitingHandler.setSecondaryProgressCounterIndeterminate(false); - int total = identification.getSpectrumIdentificationSize(); - waitingHandler.setMaxSecondaryProgressCounter(total); - ((SpectrumTableModel) querySpectraTable.getModel()).setUpdate(false); // @TODO: remove when the objectDB is stable - TagMatcher tagMatcher = new TagMatcher(fixedModifications, variableModifications, deNovoGUI.getSequenceMatchingPreferences()); - - int progress = 0; - boolean peptideFound = false; - for (String spectrumFile : identification.getOrderedSpectrumFileNames()) { - - PsmIterator psmIterator = identification.getPsmIterator(spectrumFile, true, waitingHandler); - SpectrumMatch spectrumMatch; - - while ((spectrumMatch = psmIterator.next()) != null) { - - String spectrumKey = spectrumMatch.getKey(); - HashMap>> allAssumptions = identification.getAssumptions(spectrumKey); - - for (Advocate advocate : DeNovoGUI.implementedAlgorithms) { - - int advocateIndex = advocate.getIndex(); - HashMap> assumptionsMap = allAssumptions.get(advocateIndex); - - if (assumptionsMap != null) { - ArrayList scores = new ArrayList(assumptionsMap.keySet()); - if (advocate.getIndex() == Advocate.pepnovo.getIndex() - || advocate.getIndex() == Advocate.pNovo.getIndex() - || advocate.getIndex() == Advocate.novor.getIndex()) { - Collections.sort(scores, Collections.reverseOrder()); - } else { - Collections.sort(scores); - } - - for (int i = 0; i < scores.size() && i < numberOfMatches; i++) { - - double score = scores.get(i); - ArrayList tempAssumptions = assumptionsMap.get(score); - ArrayList denovoAssumptions = new ArrayList(tempAssumptions); - - for (SpectrumIdentificationAssumption assumption : denovoAssumptions) { - - boolean passesThreshold; - - if (greaterThan) { - passesThreshold = assumption.getScore() >= threshold; - } else { // less than - passesThreshold = assumption.getScore() <= threshold; - } - - if (passesThreshold) { - if (assumption instanceof TagAssumption) { - TagAssumption tagAssumption = (TagAssumption) assumption; - int longestAminoAcidSequence = tagAssumption.getTag().getLongestAminoAcidSequence().length(); - if (longestAminoAcidSequence >= treeKeyLength) { - ArrayList proteinMapping = peptideMapper.getProteinMapping( - tagAssumption.getTag(), tagMatcher, deNovoGUI.getSequenceMatchingPreferences(), searchParameters.getFragmentIonAccuracy()); - for (Peptide peptide : PeptideProteinMapping.getPeptides(proteinMapping, deNovoGUI.getSequenceMatchingPreferences())) { - if (!peptideFound) { - peptideFound = true; - } - PeptideAssumption peptideAssumption = new PeptideAssumption(peptide, tagAssumption.getRank(), - advocateIndex, assumption.getIdentificationCharge(), score, assumption.getIdentificationFile()); - peptideAssumption.addUrParam(tagAssumption); - tempAssumptions.add(peptideAssumption); - } - } - } else if (assumption instanceof PeptideAssumption) { - if (!peptideFound) { - peptideFound = true; - } - PeptideAssumption peptideAssumption = (PeptideAssumption) assumption; - ArrayList proteinMapping = peptideMapper.getProteinMapping( - peptideAssumption.getPeptide().getSequence(), deNovoGUI.getSequenceMatchingPreferences()); - HashSet proteins = new HashSet(proteinMapping.size()); - for (PeptideProteinMapping peptideProteinMapping : proteinMapping) { - proteins.add(peptideProteinMapping.getProteinAccession()); - } - ArrayList sortedProteinList = new ArrayList(proteins); - Collections.sort(sortedProteinList); - peptideAssumption.getPeptide().setParentProteins(sortedProteinList); - } else { - throw new UnsupportedOperationException("Peptide mapping not supported for assumption of type " + assumption.getClass() + "."); - } - } - } - } - } - } - - identification.updateAssumptions(spectrumKey, allAssumptions); - - // free memory if needed - if (memoryUsed() > 0.8 && !objectsCache.isEmpty()) { - objectsCache.reduceMemoryConsumption(0.5, null); - } - waitingHandler.increaseSecondaryProgressCounter(); - waitingHandler.setWaitingText("Mapping Tags (Step 2 of 2, Spectrum " + ++progress + " of " + total + "). Please Wait..."); - - if (waitingHandler.isRunCanceled()) { - break; - } - } - - if (waitingHandler.isRunCanceled()) { - break; - } - } - - if (waitingHandler.isRunCanceled()) { - return false; - } - - ((SpectrumTableModel) querySpectraTable.getModel()).setUpdate(true); //@TODO: remove when the objectDB is stable - waitingHandler.setRunFinished(); - - return peptideFound; - } + private boolean matchInProteins(SequenceMatchingParameters sequenceMatchingPreferences, ArrayList fixedModifications, ArrayList variableModifications, WaitingHandler waitingHandler, + Double scoreThreshold, boolean greaterThan, Integer aNumberOfMatches) throws IOException, ClassNotFoundException, InterruptedException, SQLException { + + waitingHandler.appendReport("Protein database mapping is not available with the Utilities 5 migration.", true, true); + return false; + } + /** * Returns the share of memory being used. @@ -2181,8 +2053,8 @@ private void displayResults() { progressDialog.setTitle("Updating Display. Please Wait..."); TableModel tableModel = new SpectrumTableModel(getSelectedSpectrumFile(), identification, orderedSpectrumTitles); - querySpectraTable.setModel(tableModel); - setSpectrumTableProperties(); + setTableModel(querySpectraTable, tableModel); + setSpectrumTableProperties(); ((DefaultTableModel) querySpectraTable.getModel()).fireTableDataChanged(); @@ -2409,10 +2281,10 @@ public void updateAssumptionsTable(int selectedPsmRow) { } } - TableModel tableModel = new AssumptionsTableModel(assumptions, searchParameters.getPtmSettings(), !fixedPtmsCheckBoxMenuItem.isSelected()); - deNovoMatchesTable.setModel(tableModel); - - ((DefaultTableModel) deNovoMatchesTable.getModel()).fireTableDataChanged(); + TableModel tableModel = new AssumptionsTableModel(assumptions, searchParameters.getModificationParameters(), !fixedPtmsCheckBoxMenuItem.isSelected()); + setTableModel(deNovoMatchesTable, tableModel); + + ((DefaultTableModel) deNovoMatchesTable.getModel()).fireTableDataChanged(); setAssumptionsTableProperties(); if (deNovoMatchesTable.getRowCount() > 0) { @@ -2464,7 +2336,7 @@ public void updateSpectrum() { int maxPrecursorCharge = 1; ArrayList allModifications = new ArrayList(); - MSnSpectrum currentSpectrum = (MSnSpectrum) spectrumFactory.getSpectrum(spectrumKey); + Spectrum currentSpectrum = (Spectrum) spectrumFactory.getSpectrum(spectrumKey); // add the data to the spectrum panel Precursor precursor = currentSpectrum.getPrecursor(); @@ -2503,20 +2375,39 @@ public void updateSpectrum() { for (int i = 0; i < deNovoMatchesTable.getSelectedRowCount(); i++) { SpectrumIdentificationAssumption assumption = assumptions.get(deNovoMatchesTable.convertRowIndexToModel(deNovoMatchesTable.getSelectedRows()[i])); - specificAnnotationPreferences = annotationPreferences.getSpecificAnnotationPreferences(spectrumKey, assumption, SequenceMatchingPreferences.defaultStringMatching, SequenceMatchingPreferences.defaultStringMatching); + specificAnnotationPreferences = annotationPreferences.getSpecificAnnotationPreferences(spectrumKey, assumption, SequenceMatchingParameters.defaultStringMatching, SequenceMatchingParameters.defaultStringMatching); updateAnnotationPreferences(); - ArrayList annotations; - if (assumption instanceof TagAssumption) { - TagAssumption tagAssumption = (TagAssumption) assumption; - annotations = tagSpectrumAnnotator.getSpectrumAnnotation(annotationPreferences, specificAnnotationPreferences, currentSpectrum, tagAssumption.getTag()); - } else if (assumption instanceof PeptideAssumption) { - PeptideAssumption peptideAssumption = (PeptideAssumption) assumption; - annotations = peptideSpectrumAnnotator.getSpectrumAnnotation(annotationPreferences, specificAnnotationPreferences, currentSpectrum, peptideAssumption.getPeptide()); + ArrayList annotations; + if (assumption instanceof TagAssumption) { + TagAssumption tagAssumption = (TagAssumption) assumption; + annotations = new ArrayList(Arrays.asList(tagSpectrumAnnotator.getSpectrumAnnotation( + annotationPreferences, + searchParameters.getModificationParameters(), + SequenceMatchingParameters.defaultStringMatching, + specificAnnotationPreferences, + getSelectedSpectrumFile(), + getSelectedSpectrumTitle(), + currentSpectrum, + tagAssumption.getTag() + ))); + } else if (assumption instanceof PeptideAssumption) { + PeptideAssumption peptideAssumption = (PeptideAssumption) assumption; + annotations = new ArrayList(Arrays.asList(peptideSpectrumAnnotator.getSpectrumAnnotation( + annotationPreferences, + specificAnnotationPreferences, + getSelectedSpectrumFile(), + getSelectedSpectrumTitle(), + currentSpectrum, + peptideAssumption.getPeptide(), + searchParameters.getModificationParameters(), + null, + SequenceMatchingParameters.defaultStringMatching + ))); } else { throw new UnsupportedOperationException("Operation not supported for assumption of type " + assumption.getClass() + "."); } if (i == 0) { - spectrumPanel.setAnnotations(SpectrumAnnotator.getSpectrumAnnotation(annotations)); + spectrumPanel.setAnnotations(SpectrumAnnotator.getSpectrumAnnotation(annotations.toArray(new IonMatch[0]))); // convert the amino acid scores to alpha levels ArrayList alphaValues = null; @@ -2547,7 +2438,7 @@ public void updateSpectrum() { throw new UnsupportedOperationException("Operation not supported for assumption of type " + assumption.getClass() + "."); } } else { - spectrumPanel.setAnnotationsMirrored(SpectrumAnnotator.getSpectrumAnnotation(annotations)); + spectrumPanel.setAnnotationsMirrored(SpectrumAnnotator.getSpectrumAnnotation(annotations.toArray(new IonMatch[0]))); // convert the amino acid scores to alpha levels ArrayList alphaValues = null; @@ -2611,7 +2502,7 @@ public void updateSpectrum() { modifiedSequence += " vs. "; } - modifiedSequence += tag.getTaggedModifiedSequence(deNovoGUI.getSearchParameters().getPtmSettings(), false, false, true, false); + modifiedSequence += tag.getTaggedModifiedSequence(deNovoGUI.getSearchParameters().getModificationParameters(), false, false, true, false); } else if (assumption instanceof PeptideAssumption) { PeptideAssumption peptideAssumption = (PeptideAssumption) assumption; @@ -2626,14 +2517,14 @@ public void updateSpectrum() { modifiedSequence += " vs. "; } - modifiedSequence += peptide.getTaggedModifiedSequence(deNovoGUI.getSearchParameters().getPtmSettings(), false, false, true, false); + modifiedSequence += peptide.getTaggedModifiedSequence(deNovoGUI.getSearchParameters().getModificationParameters(), false, false, true, false); } else { throw new UnsupportedOperationException("Operation not supported for assumption of type " + assumption.getClass() + "."); } // Update max precursor charge - if (assumption.getIdentificationCharge().value > maxPrecursorCharge) { - maxPrecursorCharge = assumption.getIdentificationCharge().value; + if (assumption.getIdentificationCharge() > maxPrecursorCharge) { + maxPrecursorCharge = assumption.getIdentificationCharge(); } } @@ -2845,13 +2736,16 @@ public void updateAnnotationMenus(int precursorCharge, ArrayList neutralLosses = new HashMap(); // add the general neutral losses - for (NeutralLoss neutralLoss : IonFactory.getInstance().getDefaultNeutralLosses()) { - neutralLosses.put(neutralLoss.name, neutralLoss); - } + for (String neutralLossName : IonFactory.getDefaultNeutralLosses()) { + NeutralLoss neutralLoss = NeutralLoss.getNeutralLoss(neutralLossName); + if (neutralLoss != null) { + neutralLosses.put(neutralLoss.name, neutralLoss); + } + } // add the sequence specific neutral losses for (ModificationMatch modMatch : modificationMatches) { - PTM ptm = ptmFactory.getPTM(modMatch.getTheoreticPtm()); + Modification ptm = ptmFactory.getModification(modMatch.getTheoreticPtm()); for (NeutralLoss neutralLoss : ptm.getNeutralLosses()) { neutralLosses.put(neutralLoss.name, neutralLoss); } @@ -2922,7 +2816,7 @@ public void actionPerformed(java.awt.event.ActionEvent evt) { ArrayList selectedCharges; if (specificAnnotationPreferences != null) { - selectedCharges = specificAnnotationPreferences.getSelectedCharges(); + selectedCharges = new ArrayList(specificAnnotationPreferences.getSelectedCharges()); } else { selectedCharges = new ArrayList(); selectedCharges.add(1); @@ -3046,7 +2940,7 @@ public ArrayList getReporterIons() { ArrayList reporterIonsSubtypes = new ArrayList(); for (String mod : modifications) { - PTM ptm = ptmFactory.getPTM(mod); + Modification ptm = ptmFactory.getModification(mod); for (ReporterIon reporterIon : ptm.getReporterIons()) { int subType = reporterIon.getSubType(); if (!reporterIonsSubtypes.contains(subType)) { @@ -3090,19 +2984,13 @@ public String getSpectrumAsMgf() { StringBuilder spectraAsMgf = new StringBuilder(); try { - MSnSpectrum currentSpectrum = (MSnSpectrum) spectrumFactory.getSpectrum(spectrumKey); + Spectrum currentSpectrum = (Spectrum) spectrumFactory.getSpectrum(spectrumKey); spectraAsMgf.append(currentSpectrum.asMgf()); return spectraAsMgf.toString(); - } catch (IOException e) { - e.printStackTrace(); - JOptionPane.showMessageDialog(this, "An error occurred when reading the spectrum.", "File Error", JOptionPane.ERROR_MESSAGE); - } catch (IllegalArgumentException e) { - e.printStackTrace(); - JOptionPane.showMessageDialog(this, "An error occurred when reading the spectrum.", "File Error", JOptionPane.ERROR_MESSAGE); - } catch (MzMLUnmarshallerException e) { - e.printStackTrace(); - JOptionPane.showMessageDialog(this, "An error occurred when reading the spectrum.", "File Error", JOptionPane.ERROR_MESSAGE); - } + } catch (IllegalArgumentException e) { + e.printStackTrace(); + JOptionPane.showMessageDialog(this, "An error occurred when reading the spectrum.", "File Error", JOptionPane.ERROR_MESSAGE); + } } return null; @@ -3143,7 +3031,7 @@ public String getPeptideModificationTooltipAsHtml(Peptide peptide) { ptmConfidence = "not confident"; } - String temp = AminoAcidSequence.getTaggedResidue(aminoAcid, ptmName, searchParameters.getPtmSettings(), 1, true, true) + ": " + ptmName + " (" + ptmConfidence + ")
"; + String temp = AminoAcidSequence.getTaggedResidue(aminoAcid, ptmName, searchParameters.getModificationParameters(), 1, true, true) + ": " + ptmName + " (" + ptmConfidence + ")
"; if (!alreadyAnnotated.contains(temp)) { tooltip += temp; alreadyAnnotated.add(temp); @@ -3183,7 +3071,7 @@ public String getTagModificationTooltipAsHtml(Tag tag) { String affectedResidue = aminoAcidPattern.asSequence(site - 1); String modName = modificationMatch.getTheoreticPtm(); if (modificationMatch.isVariable() || (!modificationMatch.isVariable() && fixedPtmsCheckBoxMenuItem.isSelected())) { - Color ptmColor = deNovoGUI.getSearchParameters().getPtmSettings().getColor(modName); + Color ptmColor = new Color(deNovoGUI.getSearchParameters().getModificationParameters().getColor(modName)); if (!modificationMatch.isVariable()) { tooltip += "" + affectedResidue @@ -3210,7 +3098,7 @@ public String getTagModificationTooltipAsHtml(Tag tag) { if (modificationMatch.isVariable() || (!modificationMatch.isVariable() && fixedPtmsCheckBoxMenuItem.isSelected())) { char affectedResidue = aminoAcidSequence.charAt(site - 1); String modName = modificationMatch.getTheoreticPtm(); - Color ptmColor = deNovoGUI.getSearchParameters().getPtmSettings().getColor(modName); + Color ptmColor = new Color(deNovoGUI.getSearchParameters().getModificationParameters().getColor(modName)); if (!modificationMatch.isVariable()) { tooltip += "" + affectedResidue @@ -3258,40 +3146,28 @@ public String getTagModificationTooltipAsHtml(Tag tag) { */ public Identification importDeNovoResults(ArrayList resultFiles, SearchParameters searchParameters, WaitingHandler waitingHandler) throws Exception { - // @TODO: let the user reference his project - String projectReference = "DeNovoGUI"; - String sampleReference = "sample reference"; - int replicateNumber = 0; - String identificationReference = Identification.getDefaultReference(projectReference, sampleReference, replicateNumber); - MsExperiment experiment = new MsExperiment(projectReference); - Sample sample = new Sample(sampleReference); - SampleAnalysisSet analysisSet = new SampleAnalysisSet(sample, new ProteomicAnalysis(replicateNumber)); - experiment.addAnalysisSet(sample, analysisSet); - ProteomicAnalysis analysis = experiment.getAnalysisSet(sample).getProteomicAnalysis(replicateNumber); - analysis.addIdentificationResults(IdentificationMethod.MS2_IDENTIFICATION, new Ms2Identification(identificationReference)); - - // The identification object - Identification tempIdentification = analysis.getIdentification(IdentificationMethod.MS2_IDENTIFICATION); - - // The cache used whenever the identification becomes too big - String dbFolder = getCacheDirectory(getJarFilePath()).getAbsolutePath(); - objectsCache.setAutomatedMemoryManagement(true); - try { - tempIdentification.establishConnection(dbFolder, true, objectsCache); - } catch (Exception e) { - JOptionPane.showMessageDialog(ResultsFrame.this, "An error occurred while creating the identification database. " - + "Please make sure that no other instance of DeNovoGUI is running.", "Database Connection error", JOptionPane.WARNING_MESSAGE); - e.printStackTrace(); - return null; - } + // The cache used whenever the identification becomes too big + String dbFolder = getCacheDirectory(getJarFilePath()).getAbsolutePath(); + ObjectsDB objectsDB = new ObjectsDB(dbFolder, "DeNovoGUI", true); + Identification tempIdentification = new Identification(objectsDB); + objectsCache = objectsDB.getObjectsCache(); + objectsCache.setAutomatedMemoryManagement(true); numAdvocatesLoaded = 0; boolean pepNovoDataLoaded = false; - boolean direcTagDataLoaded = false; - boolean pNovoDataLoaded = false; - boolean novorDataLoaded = false; - - for (int i = 0; i < resultFiles.size(); i++) { + boolean direcTagDataLoaded = false; + boolean pNovoDataLoaded = false; + boolean novorDataLoaded = false; + boolean instaNovoDataLoaded = false; + boolean instaNovoPlusDataLoaded = false; + boolean instaNovoRefinedDataLoaded = false; + SequenceMatchingParameters sequenceMatchingParameters = deNovoGUI.getSequenceMatchingParameters(); + if (sequenceMatchingParameters == null) { + sequenceMatchingParameters = SequenceMatchingParameters.getDefaultSequenceMatching(); + deNovoGUI.setSequenceMatchingParameters(sequenceMatchingParameters); + } + + for (int i = 0; i < resultFiles.size(); i++) { File resultFile = resultFiles.get(i); @@ -3306,8 +3182,14 @@ public Identification importDeNovoResults(ArrayList resultFiles, SearchPar if (idfileReader != null) { - LinkedList spectrumMatches = idfileReader.getAllSpectrumMatches(waitingHandler, searchParameters); - progressDialog.setPrimaryProgressCounterIndeterminate(true); + ArrayList spectrumMatches = idfileReader.getAllSpectrumMatches( + spectrumFactory.getSpectrumProvider(), + waitingHandler, + searchParameters, + sequenceMatchingParameters, + true + ); + progressDialog.setPrimaryProgressCounterIndeterminate(true); // remap the ptms and set GUI min/max values for (SpectrumMatch spectrumMatch : spectrumMatches) { @@ -3322,9 +3204,15 @@ public Identification importDeNovoResults(ArrayList resultFiles, SearchPar direcTagDataLoaded = true; } else if (advocate == Advocate.pNovo.getIndex()) { pNovoDataLoaded = true; - } else if (advocate == Advocate.novor.getIndex()) { - novorDataLoaded = true; - } + } else if (advocate == Advocate.novor.getIndex()) { + novorDataLoaded = true; + } else if (advocate == Advocate.instanovo.getIndex()) { + instaNovoDataLoaded = true; + } else if (advocate == Advocate.instanovoPlus.getIndex()) { + instaNovoPlusDataLoaded = true; + } else if (advocate == Advocate.instanovoRefined.getIndex()) { + instaNovoRefinedDataLoaded = true; + } HashMap> tempAssumptions = assumptionsMap.get(advocate); @@ -3337,7 +3225,7 @@ public Identification importDeNovoResults(ArrayList resultFiles, SearchPar Tag tag = tagAssumption.getTag(); // add the fixed PTMs - ptmFactory.checkFixedModifications(searchParameters.getPtmSettings(), tag, deNovoGUI.getSequenceMatchingPreferences()); + ptmFactory.addFixedModifications(searchParameters.getModificationParameters(), tag, deNovoGUI.getSequenceMatchingParameters()); // rename the variable modifications for (TagComponent tagComponent : tag.getContent()) { @@ -3353,21 +3241,25 @@ public Identification importDeNovoResults(ArrayList resultFiles, SearchPar PepnovoParameters pepnovoParameters = (PepnovoParameters) searchParameters.getIdentificationAlgorithmParameter(advocate); String utilitiesPtmName = pepnovoParameters.getUtilitiesPtmName(pepnovoPtmName); if (utilitiesPtmName == null) { - throw new IllegalArgumentException("PepNovo PTM " + pepnovoPtmName + " not recognized in spectrum " + spectrumMatch.getKey() + "."); + throw new IllegalArgumentException("PepNovo Modification " + pepnovoPtmName + " not recognized in spectrum " + spectrumMatch.getKey() + "."); } modificationMatch.setTheoreticPtm(utilitiesPtmName); } else if (advocate == Advocate.direcTag.getIndex()) { // already mapped } else if (advocate == Advocate.pNovo.getIndex()) { // already mapped - } else if (advocate == Advocate.novor.getIndex()) { - // already mapped - } else { + } else if (advocate == Advocate.novor.getIndex()) { + // already mapped + } else if (advocate == Advocate.instanovo.getIndex() + || advocate == Advocate.instanovoPlus.getIndex() + || advocate == Advocate.instanovoRefined.getIndex()) { + // already mapped + } else { Advocate notImplemented = Advocate.getAdvocate(advocate); if (notImplemented == null) { throw new IllegalArgumentException("Advocate of id " + advocate + " not recognized."); } - throw new IllegalArgumentException("PTM mapping not implemented for " + Advocate.getAdvocate(advocate).getName() + "."); + throw new IllegalArgumentException("Modification mapping not implemented for " + Advocate.getAdvocate(advocate).getName() + "."); } } } @@ -3384,21 +3276,25 @@ public Identification importDeNovoResults(ArrayList resultFiles, SearchPar PepnovoParameters pepnovoParameters = (PepnovoParameters) searchParameters.getIdentificationAlgorithmParameter(advocate); String utilitiesPtmName = pepnovoParameters.getUtilitiesPtmName(pepnovoPtmName); if (utilitiesPtmName == null) { - throw new IllegalArgumentException("PepNovo PTM " + pepnovoPtmName + " not recognized in spectrum " + spectrumMatch.getKey() + "."); + throw new IllegalArgumentException("PepNovo Modification " + pepnovoPtmName + " not recognized in spectrum " + spectrumMatch.getKey() + "."); } modificationMatch.setTheoreticPtm(utilitiesPtmName); } else if (advocate == Advocate.direcTag.getIndex()) { // already mapped } else if (advocate == Advocate.pNovo.getIndex()) { // already mapped - } else if (advocate == Advocate.novor.getIndex()) { - // already mapped - } else { + } else if (advocate == Advocate.novor.getIndex()) { + // already mapped + } else if (advocate == Advocate.instanovo.getIndex() + || advocate == Advocate.instanovoPlus.getIndex() + || advocate == Advocate.instanovoRefined.getIndex()) { + // already mapped + } else { Advocate notImplemented = Advocate.getAdvocate(advocate); if (notImplemented == null) { throw new IllegalArgumentException("Advocate of id " + advocate + " not recognized."); } - throw new IllegalArgumentException("PTM mapping not implemented for " + Advocate.getAdvocate(advocate).getName() + "."); + throw new IllegalArgumentException("Modification mapping not implemented for " + Advocate.getAdvocate(advocate).getName() + "."); } } } @@ -3415,8 +3311,8 @@ public Identification importDeNovoResults(ArrayList resultFiles, SearchPar if (mz > maxIdentificationMz) { maxIdentificationMz = mz; } - if (tagAssumption.getIdentificationCharge().value > maxIdentificationCharge) { - maxIdentificationCharge = tagAssumption.getIdentificationCharge().value; + if (tagAssumption.getIdentificationCharge() > maxIdentificationCharge) { + maxIdentificationCharge = tagAssumption.getIdentificationCharge(); } double nGap = tag.getNTerminalGap(); if (nGap > maxNGap) { @@ -3454,30 +3350,62 @@ public Identification importDeNovoResults(ArrayList resultFiles, SearchPar if (score < minPNovoScore) { minPNovoScore = score; } - } else if (advocate == Advocate.novor.getIndex()) { - if (score > maxNovorScore) { - maxNovorScore = score; - } - if (score < minNovorScore) { - minNovorScore = score; - } - } else { + } else if (advocate == Advocate.novor.getIndex()) { + if (score > maxNovorScore) { + maxNovorScore = score; + } + if (score < minNovorScore) { + minNovorScore = score; + } + } else if (advocate == Advocate.instanovo.getIndex()) { + if (score > maxInstaNovoScore) { + maxInstaNovoScore = score; + } + } else if (advocate == Advocate.instanovoPlus.getIndex()) { + if (score > maxInstaNovoPlusScore) { + maxInstaNovoPlusScore = score; + } + } else if (advocate == Advocate.instanovoRefined.getIndex()) { + if (score > maxInstaNovoRefinedScore) { + maxInstaNovoRefinedScore = score; + } + } else { Advocate notImplemented = Advocate.getAdvocate(advocate); if (notImplemented == null) { throw new IllegalArgumentException("Advocate of id " + advocate + " not recognized."); } throw new IllegalArgumentException("Unsupported advocate " + Advocate.getAdvocate(advocate).getName() + "."); } - } else if (assumption instanceof PeptideAssumption) { - //@TODO: implement other algorithms? - if (advocate == Advocate.novor.getIndex()) { - if (score > maxNovorScore) { - maxNovorScore = score; - } - if (score < minNovorScore) { - minNovorScore = score; - } - } else { + } else if (assumption instanceof PeptideAssumption) { + + PeptideAssumption peptideAssumption = (PeptideAssumption) assumption; + peptideAssumption.getPeptide().estimateTheoreticMass( + searchParameters.getModificationParameters(), + null, + SequenceMatchingParameters.DEFAULT_STRING_MATCHING + ); + + //@TODO: implement other algorithms? + if (advocate == Advocate.novor.getIndex()) { + if (score > maxNovorScore) { + maxNovorScore = score; + } + if (score < minNovorScore) { + minNovorScore = score; + } + } else if (advocate == Advocate.instanovo.getIndex()) { + if (score > maxInstaNovoScore) { + maxInstaNovoScore = score; + } + } else if (advocate == Advocate.instanovoPlus.getIndex()) { + if (score > maxInstaNovoPlusScore) { + maxInstaNovoPlusScore = score; + } + } else if (advocate == Advocate.instanovoRefined.getIndex()) { + if (score > maxInstaNovoRefinedScore) { + maxInstaNovoRefinedScore = score; + } + } else { Advocate notImplemented = Advocate.getAdvocate(advocate); if (notImplemented == null) { throw new IllegalArgumentException("Advocate of id " + advocate + " not recognized."); @@ -3492,8 +3420,8 @@ public Identification importDeNovoResults(ArrayList resultFiles, SearchPar } } - // put the matches in the identification object - tempIdentification.addSpectrumMatches(spectrumMatches); + // put the matches in the identification object + addOrMergeSpectrumMatches(tempIdentification, spectrumMatches); idfileReader.close(); @@ -3516,18 +3444,100 @@ public Identification importDeNovoResults(ArrayList resultFiles, SearchPar if (pNovoDataLoaded) { numberOfAdvocateLoaded++; } - if (novorDataLoaded) { - numberOfAdvocateLoaded++; - } - - numAdvocatesLoaded = numberOfAdvocateLoaded; - - return tempIdentification; - } - - /** - * Close the DB connection and empty the temp folder. - */ + if (novorDataLoaded) { + numberOfAdvocateLoaded++; + } + if (instaNovoDataLoaded) { + numberOfAdvocateLoaded++; + } + if (instaNovoPlusDataLoaded) { + numberOfAdvocateLoaded++; + } + if (instaNovoRefinedDataLoaded) { + numberOfAdvocateLoaded++; + } + + numAdvocatesLoaded = numberOfAdvocateLoaded; + + return tempIdentification; + } + + /** + * Adds imported spectrum matches while preserving assumptions already + * imported for the same spectra by another de novo algorithm. + * + * @param identification the identification object + * @param spectrumMatches the imported spectrum matches + */ + private void addOrMergeSpectrumMatches( + Identification identification, + ArrayList spectrumMatches + ) { + + HashMap newMatches = new HashMap<>(); + + for (SpectrumMatch spectrumMatch : spectrumMatches) { + + long key = spectrumMatch.getKey(); + + if (newMatches.containsKey(key)) { + + SpectrumMatch existingMatch = (SpectrumMatch) newMatches.get(key); + mergeSpectrumMatchAssumptions(existingMatch, spectrumMatch); + + } else if (identification.contains(key)) { + + SpectrumMatch existingMatch = identification.getSpectrumMatch(key); + mergeSpectrumMatchAssumptions(existingMatch, spectrumMatch); + identification.updateObject(key, existingMatch); + + } else { + + newMatches.put(key, spectrumMatch); + + } + } + + if (!newMatches.isEmpty()) { + + identification.addSpectrumMatches(newMatches, null, false); + + } + } + + /** + * Adds all assumptions from the imported match to the existing match. + * + * @param existingMatch the match already present in the identification + * @param importedMatch the match imported from a result file + */ + private void mergeSpectrumMatchAssumptions( + SpectrumMatch existingMatch, + SpectrumMatch importedMatch + ) { + + HashMap>> assumptionsMap + = importedMatch.getAssumptionsMap(); + + for (Map.Entry>> advocateEntry + : assumptionsMap.entrySet()) { + + int advocate = advocateEntry.getKey(); + + for (ArrayList assumptions : advocateEntry.getValue().values()) { + + for (SpectrumIdentificationAssumption assumption : assumptions) { + + existingMatch.addHit(advocate, assumption, false); + + } + } + } + } + + /** + * Close the DB connection and empty the temp folder. + */ private void closeConnectionsAndEmptyTempFolder() { if (identification != null) { @@ -3554,9 +3564,8 @@ private void closeConnectionsAndEmptyTempFolder() { // @Override // public void run() { try { - identification.close(); - DerbyUtil.closeConnection(); - File matchFolder = getCacheDirectory(getJarFilePath()); + identification.close(); + File matchFolder = getCacheDirectory(getJarFilePath()); File[] tempFiles = matchFolder.listFiles(); if (tempFiles != null) { @@ -3605,7 +3614,7 @@ public void run() { * @return the modifications found in this project */ public ArrayList getFoundModifications() { - return searchParameters.getPtmSettings().getAllModifications(); + return searchParameters.getModificationParameters().getAllModifications(); } /** @@ -3613,7 +3622,7 @@ public ArrayList getFoundModifications() { * * @return the annotation preferences */ - public AnnotationSettings getAnnotationPreferences() { + public AnnotationParameters getAnnotationPreferences() { return annotationPreferences; } @@ -3622,7 +3631,7 @@ public AnnotationSettings getAnnotationPreferences() { * * @param annotationPreferences the annotation preferences */ - public void setAnnotationPreferences(AnnotationSettings annotationPreferences) { + public void setAnnotationPreferences(AnnotationParameters annotationPreferences) { this.annotationPreferences = annotationPreferences; } @@ -3667,13 +3676,13 @@ public HashMap getCurrentMassDeltas() { // knownMassDeltas.put(4d, "18O"); // @TODO: should this be added to neutral losses?? // knownMassDeltas.put(44d, "PEG"); // @TODO: should this be added to neutral losses?? // add the modifications - PtmSettings modificationProfile = searchParameters.getPtmSettings(); + ModificationParameters modificationProfile = searchParameters.getModificationParameters(); ArrayList modificationList = modificationProfile.getAllModifications(); Collections.sort(modificationList); // iterate the modifications list and add the non-terminal modifications for (String modification : modificationList) { - PTM ptm = ptmFactory.getPTM(modification); + Modification ptm = ptmFactory.getModification(modification); if (ptm != null) { @@ -3681,7 +3690,7 @@ public HashMap getCurrentMassDeltas() { AminoAcidPattern ptmPattern = ptm.getPattern(); double mass = ptm.getMass(); - if (ptm.getType() == PTM.MODAA && ptmPattern != null) { + if (ptm.getType() == Modification.MODAA && ptmPattern != null) { for (Character aa : ptmPattern.getAminoAcidsAtTarget()) { if (!knownMassDeltas.containsValue(aa + "<" + shortName + ">")) { AminoAcid aminoAcid = AminoAcid.getAminoAcid(aa); @@ -3691,7 +3700,7 @@ public HashMap getCurrentMassDeltas() { } } } else { - System.out.println("Error: PTM not found: " + modification); + System.out.println("Error: Modification not found: " + modification); } } diff --git a/src/main/java/com/compomics/denovogui/gui/SelectResultsDialog.java b/src/main/java/com/compomics/denovogui/gui/SelectResultsDialog.java index ac95dd8..7074c7c 100644 --- a/src/main/java/com/compomics/denovogui/gui/SelectResultsDialog.java +++ b/src/main/java/com/compomics/denovogui/gui/SelectResultsDialog.java @@ -2,8 +2,8 @@ import com.compomics.denovogui.io.FileProcessor; import com.compomics.util.Util; -import com.compomics.util.experiment.identification.identification_parameters.SearchParameters; -import com.compomics.util.gui.filehandling.FileSelectionDialog; +import com.compomics.util.parameters.identification.search.SearchParameters; +import com.compomics.util.gui.file_handling.FileSelectionDialog; import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -307,19 +307,22 @@ public boolean accept(File myFile) { return false; } - return myFile.getName().toLowerCase().endsWith(".out") - || myFile.getName().toLowerCase().endsWith(".tags") - || myFile.getName().toLowerCase().endsWith(".pnovo.txt") - || myFile.getName().toLowerCase().endsWith(".novor.csv") - || myFile.getName().toLowerCase().endsWith(".mzid") - || myFile.isDirectory(); + return myFile.getName().toLowerCase().endsWith(".out") + || myFile.getName().toLowerCase().endsWith(".tags") + || myFile.getName().toLowerCase().endsWith(".pnovo.txt") + || myFile.getName().toLowerCase().endsWith(".novor.csv") + || myFile.getName().toLowerCase().endsWith(".instanovo.csv") + || myFile.getName().toLowerCase().endsWith(".instanovoplus.csv") + || myFile.getName().toLowerCase().endsWith(".instanovo.refined.csv") + || myFile.getName().toLowerCase().endsWith(".mzid") + || myFile.isDirectory(); } @Override public String getDescription() { - return "Supported formats: DirecTag (.tags), PepNovo+ (.out), pNovo+ (.pnovo.txt) and Novor (.novor.csv)"; - } - }; + return "Supported formats: DirecTag (.tags), PepNovo+ (.out), pNovo+ (.pnovo.txt), Novor (.novor.csv), InstaNovo (.instanovo.csv), InstaNovo+ (.instanovoplus.csv) and InstaNovo with refinement (.instanovo.refined.csv)"; + } + }; fileChooser.setFileFilter(filter); diff --git a/src/main/java/com/compomics/denovogui/gui/SettingsDialog.java b/src/main/java/com/compomics/denovogui/gui/SettingsDialog.java index 04ce972..b460c9c 100644 --- a/src/main/java/com/compomics/denovogui/gui/SettingsDialog.java +++ b/src/main/java/com/compomics/denovogui/gui/SettingsDialog.java @@ -1,13 +1,13 @@ package com.compomics.denovogui.gui; -import com.compomics.util.experiment.biology.EnzymeFactory; -import com.compomics.util.experiment.biology.PTM; -import com.compomics.util.experiment.biology.PTMFactory; -import com.compomics.util.experiment.identification.identification_parameters.SearchParameters; +import com.compomics.util.experiment.biology.enzymes.EnzymeFactory; +import com.compomics.util.experiment.biology.modifications.Modification; +import com.compomics.util.experiment.biology.modifications.ModificationFactory; +import com.compomics.util.parameters.identification.search.SearchParameters; import com.compomics.util.gui.error_handlers.HelpDialog; -import com.compomics.util.gui.ptm.ModificationsDialog; -import com.compomics.util.experiment.identification.identification_parameters.PtmSettings; -import com.compomics.util.preferences.DigestionPreferences; +import com.compomics.util.gui.modification.ModificationsDialog; +import com.compomics.util.parameters.identification.search.ModificationParameters; +import com.compomics.util.parameters.identification.search.DigestionParameters; import java.awt.Color; import java.awt.Toolkit; import java.awt.event.MouseEvent; @@ -39,7 +39,7 @@ public class SettingsDialog extends javax.swing.JDialog { /** * The factory used to handle the modifications. */ - private PTMFactory ptmFactory = PTMFactory.getInstance(); + private ModificationFactory ptmFactory = ModificationFactory.getInstance(); /** * The compomics enzyme factory. */ @@ -58,7 +58,7 @@ public class SettingsDialog extends javax.swing.JDialog { */ private int keyPressedCounter = 0; /** - * The current PTM search string. + * The current Modification search string. */ private String currentPtmSearchString = ""; /** @@ -186,7 +186,7 @@ private void insertData() { // add the modifications ArrayList missingPtms = new ArrayList(); - PtmSettings modificationProfile = searchParameters.getPtmSettings(); + ModificationParameters modificationProfile = searchParameters.getModificationParameters(); if (modificationProfile != null) { ArrayList fixedMods = modificationProfile.getFixedModifications(); @@ -226,7 +226,7 @@ private void insertData() { fixedModel.getDataVector().removeAllElements(); for (String fixedMod : fixedMods) { - ((DefaultTableModel) fixedModsTable.getModel()).addRow(new Object[]{searchParameters.getPtmSettings().getColor(fixedMod), fixedMod, ptmFactory.getPTM(fixedMod).getMass()}); + ((DefaultTableModel) fixedModsTable.getModel()).addRow(new Object[]{searchParameters.getModificationParameters().getColor(fixedMod), fixedMod, ptmFactory.getModification(fixedMod).getMass()}); } ((DefaultTableModel) fixedModsTable.getModel()).fireTableDataChanged(); fixedModsTable.repaint(); @@ -269,7 +269,7 @@ private void insertData() { variableModel.getDataVector().removeAllElements(); for (String variableMod : variableMods) { ((DefaultTableModel) variableModsTable.getModel()).addRow( - new Object[]{searchParameters.getPtmSettings().getColor(variableMod), variableMod, ptmFactory.getPTM(variableMod).getMass()}); + new Object[]{searchParameters.getModificationParameters().getColor(variableMod), variableMod, ptmFactory.getModification(variableMod).getMass()}); } ((DefaultTableModel) variableModsTable.getModel()).fireTableDataChanged(); variableModsTable.repaint(); @@ -886,7 +886,7 @@ private void addFixedModificationActionPerformed(java.awt.event.ActionEvent evt) fixedModel.getDataVector().removeAllElements(); for (String fixedMod : fixedModifications) { - ((DefaultTableModel) fixedModsTable.getModel()).addRow(new Object[]{searchParameters.getPtmSettings().getColor(fixedMod), fixedMod, ptmFactory.getPTM(fixedMod).getMass()}); + ((DefaultTableModel) fixedModsTable.getModel()).addRow(new Object[]{searchParameters.getModificationParameters().getColor(fixedMod), fixedMod, ptmFactory.getModification(fixedMod).getMass()}); } ((DefaultTableModel) fixedModsTable.getModel()).fireTableDataChanged(); @@ -925,7 +925,7 @@ private void removeFixedModificationActionPerformed(java.awt.event.ActionEvent e fixedModel.getDataVector().removeAllElements(); for (String fixedMod : fixedModifications) { - ((DefaultTableModel) fixedModsTable.getModel()).addRow(new Object[]{searchParameters.getPtmSettings().getColor(fixedMod), fixedMod, ptmFactory.getPTM(fixedMod).getMass()}); + ((DefaultTableModel) fixedModsTable.getModel()).addRow(new Object[]{searchParameters.getModificationParameters().getColor(fixedMod), fixedMod, ptmFactory.getModification(fixedMod).getMass()}); } ((DefaultTableModel) fixedModsTable.getModel()).fireTableDataChanged(); fixedModsTable.repaint(); @@ -944,7 +944,7 @@ private void fixedModsTableMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIR }//GEN-LAST:event_fixedModsTableMouseExited /** - * Change the color of a fixed PTM. + * Change the color of a fixed Modification. * * @param evt */ @@ -957,7 +957,7 @@ private void fixedModsTableMouseReleased(java.awt.event.MouseEvent evt) {//GEN-F Color newColor = JColorChooser.showDialog(this, "Pick a Color", (Color) fixedModsTable.getValueAt(row, column)); if (newColor != null) { - searchParameters.getPtmSettings().setColor((String) fixedModsTable.getValueAt(row, 1), newColor); + searchParameters.getModificationParameters().setColor((String) fixedModsTable.getValueAt(row, 1), newColor); fixedModsTable.setValueAt(newColor, row, 0); ((DefaultTableModel) fixedModsTable.getModel()).fireTableDataChanged(); fixedModsTable.repaint(); @@ -979,7 +979,7 @@ private void fixedModsTableMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRS if (row != -1) { String ptmName = (String) fixedModsTable.getValueAt(row, fixedModsTable.getColumn("Name").getModelIndex()); - PTM ptm = ptmFactory.getPTM(ptmName); + Modification ptm = ptmFactory.getModification(ptmName); fixedModsTable.setToolTipText(ptm.getHtmlTooltip()); if (column == fixedModsTable.getColumn(" ").getModelIndex()) { @@ -1030,7 +1030,7 @@ private void addVariableModificationActionPerformed(java.awt.event.ActionEvent e variableModel.getDataVector().removeAllElements(); for (String variabledMod : variableModifications) { - ((DefaultTableModel) variableModsTable.getModel()).addRow(new Object[]{searchParameters.getPtmSettings().getColor(variabledMod), variabledMod, ptmFactory.getPTM(variabledMod).getMass()}); + ((DefaultTableModel) variableModsTable.getModel()).addRow(new Object[]{searchParameters.getModificationParameters().getColor(variabledMod), variabledMod, ptmFactory.getModification(variabledMod).getMass()}); } ((DefaultTableModel) variableModsTable.getModel()).fireTableDataChanged(); variableModsTable.repaint(); @@ -1074,7 +1074,7 @@ private void removeVariableModificationActionPerformed(java.awt.event.ActionEven variableModel.getDataVector().removeAllElements(); for (String variabledMod : variableModifications) { - ((DefaultTableModel) variableModsTable.getModel()).addRow(new Object[]{searchParameters.getPtmSettings().getColor(variabledMod), variabledMod, ptmFactory.getPTM(variabledMod).getMass()}); + ((DefaultTableModel) variableModsTable.getModel()).addRow(new Object[]{searchParameters.getModificationParameters().getColor(variabledMod), variabledMod, ptmFactory.getModification(variabledMod).getMass()}); } ((DefaultTableModel) variableModsTable.getModel()).fireTableDataChanged(); variableModsTable.repaint(); @@ -1093,7 +1093,7 @@ private void variableModsTableMouseExited(java.awt.event.MouseEvent evt) {//GEN- }//GEN-LAST:event_variableModsTableMouseExited /** - * Change the color of a fixed PTM. + * Change the color of a fixed Modification. * * @param evt */ @@ -1106,7 +1106,7 @@ private void variableModsTableMouseReleased(java.awt.event.MouseEvent evt) {//GE Color newColor = JColorChooser.showDialog(this, "Pick a Color", (Color) variableModsTable.getValueAt(row, column)); if (newColor != null) { - searchParameters.getPtmSettings().setColor((String) variableModsTable.getValueAt(row, 1), newColor); + searchParameters.getModificationParameters().setColor((String) variableModsTable.getValueAt(row, 1), newColor); variableModsTable.setValueAt(newColor, row, 0); ((DefaultTableModel) variableModsTable.getModel()).fireTableDataChanged(); variableModsTable.repaint(); @@ -1128,7 +1128,7 @@ private void variableModsTableMouseMoved(java.awt.event.MouseEvent evt) {//GEN-F if (row != -1) { String ptmName = (String) variableModsTable.getValueAt(row, variableModsTable.getColumn("Name").getModelIndex()); - PTM ptm = ptmFactory.getPTM(ptmName); + Modification ptm = ptmFactory.getModification(ptmName); variableModsTable.setToolTipText(ptm.getHtmlTooltip()); if (column == variableModsTable.getColumn(" ").getModelIndex()) { @@ -1161,7 +1161,7 @@ private void modificationsListComboActionPerformed(java.awt.event.ActionEvent ev }//GEN-LAST:event_modificationsListComboActionPerformed /** - * Opens a file chooser where the color for the PTM can be changed. + * Opens a file chooser where the color for the Modification can be changed. * * @param evt */ @@ -1237,7 +1237,7 @@ private void modificationsTableMouseMoved(java.awt.event.MouseEvent evt) {//GEN- if (row != -1) { String ptmName = (String) modificationsTable.getValueAt(row, modificationsTable.getColumn("Name").getModelIndex()); - PTM ptm = ptmFactory.getPTM(ptmName); + Modification ptm = ptmFactory.getModification(ptmName); modificationsTable.setToolTipText(ptm.getHtmlTooltip()); if (column == modificationsTable.getColumn(" ").getModelIndex()) { @@ -1311,7 +1311,7 @@ private void openDialogHelpJButtonActionPerformed(java.awt.event.ActionEvent evt }//GEN-LAST:event_openDialogHelpJButtonActionPerformed /** - * Jump to the row with the PTM starting with the typed letters. + * Jump to the row with the Modification starting with the typed letters. * * @param evt */ @@ -1415,8 +1415,8 @@ public SearchParameters getSearchParametersFromGUI() { SearchParameters tempSearchParameters = new SearchParameters(searchParameters); // set the digestion preferences - DigestionPreferences digestionPreferences = DigestionPreferences.getDefaultPreferences(); - searchParameters.setDigestionPreferences(digestionPreferences); + DigestionParameters digestionPreferences = DigestionParameters.getDefaultPreferences(); + searchParameters.setDigestionParameters(digestionPreferences); // general parameters double fragmentIonTolerance = (Double) fragmentMassToleranceSpinner.getValue(); @@ -1435,16 +1435,16 @@ public SearchParameters getSearchParametersFromGUI() { } // set the modifications - PtmSettings modificationProfile = new PtmSettings(); + ModificationParameters modificationProfile = new ModificationParameters(); for (int i = 0; i < fixedModsTable.getRowCount(); i++) { String modName = (String) fixedModsTable.getValueAt(i, 1); - modificationProfile.addFixedModification(ptmFactory.getPTM(modName)); + modificationProfile.addFixedModification(ptmFactory.getModification(modName)); modificationProfile.setColor(modName, (Color) fixedModsTable.getValueAt(i, 0)); } for (int i = 0; i < variableModsTable.getRowCount(); i++) { String modName = (String) variableModsTable.getValueAt(i, 1); - modificationProfile.addVariableModification(ptmFactory.getPTM(modName)); + modificationProfile.addVariableModification(ptmFactory.getModification(modName)); modificationProfile.setColor(modName, (Color) variableModsTable.getValueAt(i, 0)); } tempSearchParameters.setPtmSettings(modificationProfile); @@ -1547,7 +1547,7 @@ public boolean isCellEditable(int rowIndex, int columnIndex) { } for (String mod : allModificationsAsArray) { - ((DefaultTableModel) modificationsTable.getModel()).addRow(new Object[]{ptmFactory.getColor(mod), mod, ptmFactory.getPTM(mod).getMass(), deNovoGUI.getModificationUse().contains(mod)}); + ((DefaultTableModel) modificationsTable.getModel()).addRow(new Object[]{ptmFactory.getColor(mod), mod, ptmFactory.getModification(mod).getMass(), deNovoGUI.getModificationUse().contains(mod)}); } ((DefaultTableModel) modificationsTable.getModel()).fireTableDataChanged(); modificationsTable.repaint(); @@ -1557,11 +1557,11 @@ public boolean isCellEditable(int rowIndex, int columnIndex) { double minMass = Double.MAX_VALUE; for (String ptm : ptmFactory.getPTMs()) { - if (ptmFactory.getPTM(ptm).getMass() > maxMass) { - maxMass = ptmFactory.getPTM(ptm).getMass(); + if (ptmFactory.getModification(ptm).getMass() > maxMass) { + maxMass = ptmFactory.getModification(ptm).getMass(); } - if (ptmFactory.getPTM(ptm).getMass() < minMass) { - minMass = ptmFactory.getPTM(ptm).getMass(); + if (ptmFactory.getModification(ptm).getMass() < minMass) { + minMass = ptmFactory.getModification(ptm).getMass(); } } @@ -1585,7 +1585,7 @@ public boolean isCellEditable(int rowIndex, int columnIndex) { } /** - * Enable/disable the add/remove PTM buttons. + * Enable/disable the add/remove Modification buttons. */ private void enableAddRemoveButtons() { removeVariableModification.setEnabled(variableModsTable.getSelectedRow() != -1); diff --git a/src/main/java/com/compomics/denovogui/gui/tablemodels/AssumptionsTableModel.java b/src/main/java/com/compomics/denovogui/gui/tablemodels/AssumptionsTableModel.java index 898cda0..68e440c 100644 --- a/src/main/java/com/compomics/denovogui/gui/tablemodels/AssumptionsTableModel.java +++ b/src/main/java/com/compomics/denovogui/gui/tablemodels/AssumptionsTableModel.java @@ -1,11 +1,11 @@ package com.compomics.denovogui.gui.tablemodels; -import com.compomics.util.experiment.biology.Peptide; +import com.compomics.util.experiment.biology.proteins.Peptide; import com.compomics.util.experiment.identification.Advocate; import com.compomics.util.experiment.identification.SpectrumIdentificationAssumption; import com.compomics.util.experiment.identification.spectrum_assumptions.TagAssumption; -import com.compomics.util.experiment.refinementparameters.PepnovoAssumptionDetails; -import com.compomics.util.experiment.identification.identification_parameters.PtmSettings; +import com.compomics.util.experiment.refinement_parameters.PepnovoAssumptionDetails; +import com.compomics.util.parameters.identification.search.ModificationParameters; import com.compomics.util.experiment.identification.spectrum_assumptions.PeptideAssumption; import java.util.ArrayList; import java.util.logging.Level; @@ -27,7 +27,7 @@ public class AssumptionsTableModel extends DefaultTableModel { /** * The modification profile of the search. */ - private PtmSettings modificationProfile = null; + private ModificationParameters modificationProfile = null; /** * If true, the fixed PTMs are indicated in the peptide sequences. */ @@ -47,7 +47,7 @@ public AssumptionsTableModel() { * @param excludeAllFixedPtms are fixed PTMs are to be indicated in the * table */ - public AssumptionsTableModel(ArrayList assumptions, PtmSettings modificationProfile, boolean excludeAllFixedPtms) { + public AssumptionsTableModel(ArrayList assumptions, ModificationParameters modificationProfile, boolean excludeAllFixedPtms) { this.assumptions = assumptions; this.modificationProfile = modificationProfile; this.excludeAllFixedPtms = excludeAllFixedPtms; @@ -71,9 +71,9 @@ public int getRowCount() { return assumptions.size(); } - @Override - public int getColumnCount() { - return 13; + @Override + public int getColumnCount() { + return 16; } @Override @@ -99,12 +99,18 @@ public String getColumnName(int column) { return "Score (P)"; case 9: return "Score (D)"; - case 10: - return "Score (p)"; - case 11: - return "Score (N)"; - case 12: - return " "; + case 10: + return "Score (p)"; + case 11: + return "Score (N)"; + case 12: + return "Score (I)"; + case 13: + return "Score (I+)"; + case 14: + return "Score (Ir)"; + case 15: + return " "; default: return ""; } @@ -132,15 +138,11 @@ public Object getValueAt(int row, int column) { if (assumption instanceof TagAssumption) { TagAssumption tagAssumption = (TagAssumption) assumption; return tagAssumption.getTheoreticMz(true, true); - } else { - try { - return assumption.getTheoreticMz(); - } catch (InterruptedException ex) { - return null; - } - } + } else { + return assumption.getTheoreticMz(); + } case 4: - return assumption.getIdentificationCharge().value; + return assumption.getIdentificationCharge(); case 5: if (assumption instanceof TagAssumption) { TagAssumption tagAssumption = (TagAssumption) assumption; @@ -177,13 +179,28 @@ public Object getValueAt(int row, int column) { return assumption.getScore(); } return null; - case 11: - if (assumption.getAdvocate() == Advocate.novor.getIndex()) { - return assumption.getScore(); - } - return null; - case 12: - return true; + case 11: + if (assumption.getAdvocate() == Advocate.novor.getIndex()) { + return assumption.getScore(); + } + return null; + case 12: + if (assumption.getAdvocate() == Advocate.instanovo.getIndex()) { + return assumption.getScore(); + } + return null; + case 13: + if (assumption.getAdvocate() == Advocate.instanovoPlus.getIndex()) { + return assumption.getScore(); + } + return null; + case 14: + if (assumption.getAdvocate() == Advocate.instanovoRefined.getIndex()) { + return assumption.getScore(); + } + return null; + case 15: + return true; default: return ""; } @@ -203,12 +220,15 @@ public Class getColumnClass(int columnIndex) { case 6: case 7: case 8: - case 9: - case 10: - case 11: - return Double.class; - case 12: - return Boolean.class; + case 9: + case 10: + case 11: + case 12: + case 13: + case 14: + return Double.class; + case 15: + return Boolean.class; default: return null; } diff --git a/src/main/java/com/compomics/denovogui/gui/tablemodels/SpectrumTableModel.java b/src/main/java/com/compomics/denovogui/gui/tablemodels/SpectrumTableModel.java index 2b0b3cf..959ec89 100644 --- a/src/main/java/com/compomics/denovogui/gui/tablemodels/SpectrumTableModel.java +++ b/src/main/java/com/compomics/denovogui/gui/tablemodels/SpectrumTableModel.java @@ -1,12 +1,14 @@ package com.compomics.denovogui.gui.tablemodels; + +import com.compomics.denovogui.io.SpectrumFactory; import com.compomics.util.experiment.identification.Advocate; import com.compomics.util.experiment.identification.Identification; import com.compomics.util.experiment.identification.SpectrumIdentificationAssumption; -import com.compomics.util.experiment.massspectrometry.MSnSpectrum; -import com.compomics.util.experiment.massspectrometry.Precursor; -import com.compomics.util.experiment.massspectrometry.Spectrum; -import com.compomics.util.experiment.massspectrometry.SpectrumFactory; +import com.compomics.util.experiment.mass_spectrometry.spectra.Spectrum; +import com.compomics.util.experiment.mass_spectrometry.spectra.Precursor; +import com.compomics.util.experiment.mass_spectrometry.spectra.Spectrum; +import com.compomics.util.experiment.mass_spectrometry.SpectrumProvider; import java.util.ArrayList; import java.util.HashMap; import javax.swing.table.DefaultTableModel; @@ -72,9 +74,9 @@ public int getRowCount() { return spectrumFactory.getNSpectra(spectrumFile); } - @Override - public int getColumnCount() { - return 13; + @Override + public int getColumnCount() { + return 16; } @Override @@ -100,12 +102,18 @@ public String getColumnName(int column) { return "Score (P)"; case 9: return "Score (D)"; - case 10: - return "Score (p)"; - case 11: - return "Score (N)"; - case 12: - return " "; + case 10: + return "Score (p)"; + case 11: + return "Score (N)"; + case 12: + return "Score (I)"; + case 13: + return "Score (I+)"; + case 14: + return "Score (Ir)"; + case 15: + return " "; default: return ""; } @@ -173,8 +181,8 @@ public Object getValueAt(int row, int column) { } case 7: try { - MSnSpectrum spectrum = (MSnSpectrum) spectrumFactory.getSpectrum(spectrumFile, spectrumTitle); - return spectrum.getPeakList().size(); + Spectrum spectrum = (Spectrum) spectrumFactory.getSpectrum(spectrumFile, spectrumTitle); + return spectrum.getNPeaks(); } catch (Exception e) { e.printStackTrace(); return null; @@ -242,34 +250,52 @@ public Object getValueAt(int row, int column) { e.printStackTrace(); return null; } - case 11: - try { - String spectrumKey = Spectrum.getSpectrumKey(spectrumFile, spectrumTitle); - if (update && identification.matchExists(spectrumKey)) { - HashMap>> allAssumptions = identification.getAssumptions(spectrumKey); - HashMap> hitMap = allAssumptions.get(Advocate.novor.getIndex()); - if (hitMap != null) { - double bestScore = 0; - for (double score : hitMap.keySet()) { - if (score > bestScore) { - bestScore = score; - } - } - return bestScore; - } - } - return null; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - case 12: - String spectrumKey = Spectrum.getSpectrumKey(spectrumFile, spectrumTitle); - return identification.matchExists(spectrumKey); - default: - return null; - } - } + case 11: + return getBestScore(spectrumTitle, Advocate.novor.getIndex()); + case 12: + return getBestScore(spectrumTitle, Advocate.instanovo.getIndex()); + case 13: + return getBestScore(spectrumTitle, Advocate.instanovoPlus.getIndex()); + case 14: + return getBestScore(spectrumTitle, Advocate.instanovoRefined.getIndex()); + case 15: + String spectrumKey = Spectrum.getSpectrumKey(spectrumFile, spectrumTitle); + return identification.matchExists(spectrumKey); + default: + return null; + } + } + + /** + * Returns the best score for the given advocate and spectrum. + * + * @param spectrumTitle the spectrum title + * @param advocateIndex the advocate index + * + * @return the best score, or null if no score was found + */ + private Double getBestScore(String spectrumTitle, int advocateIndex) { + try { + String spectrumKey = Spectrum.getSpectrumKey(spectrumFile, spectrumTitle); + if (update && identification.matchExists(spectrumKey)) { + HashMap>> allAssumptions = identification.getAssumptions(spectrumKey); + HashMap> hitMap = allAssumptions.get(advocateIndex); + if (hitMap != null) { + double bestScore = 0; + for (double score : hitMap.keySet()) { + if (bestScore == 0 || score > bestScore) { + bestScore = score; + } + } + return bestScore; + } + } + return null; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } @Override public Class getColumnClass(int columnIndex) { @@ -285,12 +311,15 @@ public Class getColumnClass(int columnIndex) { case 5: case 6: case 8: - case 9: - case 10: - case 11: - return Double.class; - case 12: - return Boolean.class; + case 9: + case 10: + case 11: + case 12: + case 13: + case 14: + return Double.class; + case 15: + return Boolean.class; default: return null; } diff --git a/src/main/java/com/compomics/denovogui/io/FileProcessor.java b/src/main/java/com/compomics/denovogui/io/FileProcessor.java index d7988be..ee5d306 100644 --- a/src/main/java/com/compomics/denovogui/io/FileProcessor.java +++ b/src/main/java/com/compomics/denovogui/io/FileProcessor.java @@ -229,10 +229,49 @@ public static File getPNovoResultFile(File outFolder, File spectrumFile) { * @param spectrumFile the spectrum file * @return the corresponding out file */ - public static File getNovorResultFile(File outFolder, File spectrumFile) { - String mgfName = spectrumFile.getName().substring(0, spectrumFile.getName().lastIndexOf(".")); - return new File(outFolder, mgfName + ".novor.csv"); - } + public static File getNovorResultFile(File outFolder, File spectrumFile) { + String mgfName = spectrumFile.getName().substring(0, spectrumFile.getName().lastIndexOf(".")); + return new File(outFolder, mgfName + ".novor.csv"); + } + + /** + * Returns the InstaNovo result file corresponding to the given spectrum + * file and output folder. + * + * @param outFolder the output folder + * @param spectrumFile the spectrum file + * @return the corresponding result file + */ + public static File getInstaNovoResultFile(File outFolder, File spectrumFile) { + String mgfName = spectrumFile.getName().substring(0, spectrumFile.getName().lastIndexOf(".")); + return new File(outFolder, mgfName + ".instanovo.csv"); + } + + /** + * Returns the InstaNovo+ result file corresponding to the given spectrum + * file and output folder. + * + * @param outFolder the output folder + * @param spectrumFile the spectrum file + * @return the corresponding result file + */ + public static File getInstaNovoPlusResultFile(File outFolder, File spectrumFile) { + String mgfName = spectrumFile.getName().substring(0, spectrumFile.getName().lastIndexOf(".")); + return new File(outFolder, mgfName + ".instanovoplus.csv"); + } + + /** + * Returns the InstaNovo with refinement result file corresponding to the + * given spectrum file and output folder. + * + * @param outFolder the output folder + * @param spectrumFile the spectrum file + * @return the corresponding result file + */ + public static File getInstaNovoRefinedResultFile(File outFolder, File spectrumFile) { + String mgfName = spectrumFile.getName().substring(0, spectrumFile.getName().lastIndexOf(".")); + return new File(outFolder, mgfName + ".instanovo.refined.csv"); + } /** * Returns the DirectTag result file corresponding to the given spectrum @@ -260,12 +299,21 @@ public static File getMgfFile(File outFile) throws IllegalArgumentException { if (fileName.endsWith(".out")) { String mgfName = fileName.substring(0, fileName.lastIndexOf(".")); return new File(outFile.getParent(), mgfName); - } else if (fileName.endsWith(".tags")) { - String mgfName = fileName.substring(0, fileName.lastIndexOf(".")); - return new File(outFile.getParent(), mgfName + ".mgf"); - } - throw new IllegalArgumentException("Output file " + fileName + " format not recognized."); - } + } else if (fileName.endsWith(".tags")) { + String mgfName = fileName.substring(0, fileName.lastIndexOf(".")); + return new File(outFile.getParent(), mgfName + ".mgf"); + } else if (fileName.endsWith(".instanovo.refined.csv")) { + String mgfName = fileName.substring(0, fileName.length() - ".instanovo.refined.csv".length()); + return new File(outFile.getParent(), mgfName + ".mgf"); + } else if (fileName.endsWith(".instanovoplus.csv")) { + String mgfName = fileName.substring(0, fileName.length() - ".instanovoplus.csv".length()); + return new File(outFile.getParent(), mgfName + ".mgf"); + } else if (fileName.endsWith(".instanovo.csv")) { + String mgfName = fileName.substring(0, fileName.length() - ".instanovo.csv".length()); + return new File(outFile.getParent(), mgfName + ".mgf"); + } + throw new IllegalArgumentException("Output file " + fileName + " format not recognized."); + } /** * Returns a list of PepNovo out files expected from a list of spectrum @@ -332,16 +380,73 @@ public static ArrayList getPNovoResultFiles(File outFolder, List spe * @param spectrumFiles list of spectrum files * @return expected list of out files */ - public static ArrayList getNovorResultFiles(File outFolder, List spectrumFiles) { - ArrayList outFiles = new ArrayList(); - for (File file : spectrumFiles) { - File tempFile = getNovorResultFile(outFolder, file); - if (tempFile.exists()) { + public static ArrayList getNovorResultFiles(File outFolder, List spectrumFiles) { + ArrayList outFiles = new ArrayList(); + for (File file : spectrumFiles) { + File tempFile = getNovorResultFile(outFolder, file); + if (tempFile.exists()) { outFiles.add(tempFile); } - } - return outFiles; - } + } + return outFiles; + } + + /** + * Returns a list of InstaNovo result files expected from a list of spectrum + * files. + * + * @param outFolder the output folder + * @param spectrumFiles list of spectrum files + * @return expected list of result files + */ + public static ArrayList getInstaNovoResultFiles(File outFolder, List spectrumFiles) { + ArrayList outFiles = new ArrayList(); + for (File file : spectrumFiles) { + File tempFile = getInstaNovoResultFile(outFolder, file); + if (tempFile.exists()) { + outFiles.add(tempFile); + } + } + return outFiles; + } + + /** + * Returns a list of InstaNovo+ result files expected from a list of + * spectrum files. + * + * @param outFolder the output folder + * @param spectrumFiles list of spectrum files + * @return expected list of result files + */ + public static ArrayList getInstaNovoPlusResultFiles(File outFolder, List spectrumFiles) { + ArrayList outFiles = new ArrayList(); + for (File file : spectrumFiles) { + File tempFile = getInstaNovoPlusResultFile(outFolder, file); + if (tempFile.exists()) { + outFiles.add(tempFile); + } + } + return outFiles; + } + + /** + * Returns a list of InstaNovo with refinement result files expected from a + * list of spectrum files. + * + * @param outFolder the output folder + * @param spectrumFiles list of spectrum files + * @return expected list of result files + */ + public static ArrayList getInstaNovoRefinedResultFiles(File outFolder, List spectrumFiles) { + ArrayList outFiles = new ArrayList(); + for (File file : spectrumFiles) { + File tempFile = getInstaNovoRefinedResultFile(outFolder, file); + if (tempFile.exists()) { + outFiles.add(tempFile); + } + } + return outFiles; + } /** * Returns a list of result files expected from a list of spectrum files. @@ -350,9 +455,9 @@ public static ArrayList getNovorResultFiles(File outFolder, List spe * @param spectrumFiles list of spectrum files * @return expected list of out files */ - public static ArrayList getAllResultFiles(File resultsFolder, List spectrumFiles) { - return getAllResultFiles(resultsFolder, spectrumFiles, true, true, true, true); - } + public static ArrayList getAllResultFiles(File resultsFolder, List spectrumFiles) { + return getAllResultFiles(resultsFolder, spectrumFiles, true, true, true, true, true, true, true); + } /** * Returns a list of result files expected from a list of spectrum files. @@ -365,21 +470,50 @@ public static ArrayList getAllResultFiles(File resultsFolder, List s * @param novor add Novor files * @return expected list of out files */ - public static ArrayList getAllResultFiles(File resultsFolder, List spectrumFiles, - boolean pepNovo, boolean direcTag, boolean pNovo, boolean novor) { - ArrayList resultFiles = new ArrayList(); - if (pepNovo) { - resultFiles.addAll(getOutFiles(resultsFolder, spectrumFiles)); - } + public static ArrayList getAllResultFiles(File resultsFolder, List spectrumFiles, + boolean pepNovo, boolean direcTag, boolean pNovo, boolean novor) { + return getAllResultFiles(resultsFolder, spectrumFiles, pepNovo, direcTag, pNovo, novor, false, false, false); + } + + /** + * Returns a list of result files expected from a list of spectrum files. + * + * @param resultsFolder the results folder + * @param spectrumFiles list of spectrum files + * @param pepNovo add PepNovo files + * @param direcTag add DirecTag files + * @param pNovo add pNovo files + * @param novor add Novor files + * @param instaNovo add InstaNovo files + * @param instaNovoPlus add InstaNovo+ files + * @param instaNovoRefined add InstaNovo with refinement files + * @return expected list of out files + */ + public static ArrayList getAllResultFiles(File resultsFolder, List spectrumFiles, + boolean pepNovo, boolean direcTag, boolean pNovo, boolean novor, + boolean instaNovo, boolean instaNovoPlus, boolean instaNovoRefined) { + ArrayList resultFiles = new ArrayList(); + if (pepNovo) { + resultFiles.addAll(getOutFiles(resultsFolder, spectrumFiles)); + } if (direcTag) { resultFiles.addAll(getTagsFiles(resultsFolder, spectrumFiles)); } if (pNovo) { resultFiles.addAll(getPNovoResultFiles(resultsFolder, spectrumFiles)); } - if (novor) { - resultFiles.addAll(getNovorResultFiles(resultsFolder, spectrumFiles)); - } - return resultFiles; - } -} + if (novor) { + resultFiles.addAll(getNovorResultFiles(resultsFolder, spectrumFiles)); + } + if (instaNovo) { + resultFiles.addAll(getInstaNovoResultFiles(resultsFolder, spectrumFiles)); + } + if (instaNovoPlus) { + resultFiles.addAll(getInstaNovoPlusResultFiles(resultsFolder, spectrumFiles)); + } + if (instaNovoRefined) { + resultFiles.addAll(getInstaNovoRefinedResultFiles(resultsFolder, spectrumFiles)); + } + return resultFiles; + } +} diff --git a/src/main/java/com/compomics/denovogui/io/PepNovoModificationFile.java b/src/main/java/com/compomics/denovogui/io/PepNovoModificationFile.java index b131629..bf8c8c1 100644 --- a/src/main/java/com/compomics/denovogui/io/PepNovoModificationFile.java +++ b/src/main/java/com/compomics/denovogui/io/PepNovoModificationFile.java @@ -1,8 +1,8 @@ package com.compomics.denovogui.io; -import com.compomics.util.experiment.biology.PTM; -import com.compomics.util.experiment.biology.PTMFactory; -import com.compomics.util.experiment.identification.identification_parameters.PtmSettings; +import com.compomics.util.experiment.biology.modifications.Modification; +import com.compomics.util.experiment.biology.modifications.ModificationFactory; +import com.compomics.util.parameters.identification.search.ModificationParameters; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; @@ -35,11 +35,11 @@ public class PepNovoModificationFile { */ private static final String SPACE = " "; /** - * Fixed PTM type. + * Fixed Modification type. */ private static final String FIXED_PTM = "FIXED"; /** - * Variable PTM type. + * Variable Modification type. */ private static final String VARIABLE_PTM = "OPTIONAL"; /** @@ -67,11 +67,11 @@ public class PepNovoModificationFile { * @param modificationProfile the modification profile of the search * @throws java.io.IOException thrown if the file access fails */ - public static void writeFile(File filePath, PtmSettings modificationProfile) throws IOException { + public static void writeFile(File filePath, ModificationParameters modificationProfile) throws IOException { // Init the buffered writer. BufferedWriter writer = new BufferedWriter(new FileWriter(new File(filePath, name))); - // PTM file header + // Modification file header writer.append(getHeader()); writer.newLine(); @@ -91,7 +91,7 @@ public static void writeFile(File filePath, PtmSettings modificationProfile) thr } /** - * Writes the lines corresponding to the given PTM name. + * Writes the lines corresponding to the given Modification name. * * @param writer the writer used to write * @param mod the name of the modifications of interest @@ -101,9 +101,9 @@ public static void writeFile(File filePath, PtmSettings modificationProfile) thr */ private static void writePtmLine(BufferedWriter writer, String mod, String variable) throws IOException { - // Get the PTMFactory - PTMFactory ptmFactory = PTMFactory.getInstance(); - PTM ptm = ptmFactory.getPTM(mod); + // Get the ModificationFactory + ModificationFactory ptmFactory = ModificationFactory.getInstance(); + Modification ptm = ptmFactory.getModification(mod); double ptmMass = ptm.getRoundedMass(); if (ptmMass > maxMassOffsetValue) { @@ -120,8 +120,8 @@ private static void writePtmLine(BufferedWriter writer, String mod, String varia variable = VARIABLE_PTM; // PepNovo+ does not support fixed PTMs at the terminals... } - if (ptmFactory.getPTM(mod).getType() == PTM.MODN || ptmFactory.getPTM(mod).getType() == PTM.MODNAA - || ptmFactory.getPTM(mod).getType() == PTM.MODNP || ptmFactory.getPTM(mod).getType() == PTM.MODNPAA) { + if (ptmFactory.getModification(mod).getType() == Modification.MODN || ptmFactory.getModification(mod).getType() == Modification.MODNAA + || ptmFactory.getModification(mod).getType() == Modification.MODNP || ptmFactory.getModification(mod).getType() == Modification.MODNPAA) { writer.append("N_TERM" + SEP); writer.append(ptmMass + SPACE); writer.append(variable + SPACE); @@ -130,8 +130,8 @@ private static void writePtmLine(BufferedWriter writer, String mod, String varia modIdMap.put(ptm.getName(), "^" + connector + Long.toString(Math.round(ptmMass))); writer.append(ptm.getName().toUpperCase()); writer.newLine(); - } else if (ptmFactory.getPTM(mod).getType() == PTM.MODC || ptmFactory.getPTM(mod).getType() == PTM.MODCAA - || ptmFactory.getPTM(mod).getType() == PTM.MODCP || ptmFactory.getPTM(mod).getType() == PTM.MODCPAA) { + } else if (ptmFactory.getModification(mod).getType() == Modification.MODC || ptmFactory.getModification(mod).getType() == Modification.MODCAA + || ptmFactory.getModification(mod).getType() == Modification.MODCP || ptmFactory.getModification(mod).getType() == Modification.MODCPAA) { writer.append("C_TERM" + SEP); writer.append(ptmMass + SPACE); writer.append(variable + SPACE); @@ -145,16 +145,16 @@ private static void writePtmLine(BufferedWriter writer, String mod, String varia for (Character residue : ptm.getPattern().getAminoAcidsAtTarget()) { - if (ptmFactory.getPTM(mod).getType() == PTM.MODN || ptmFactory.getPTM(mod).getType() == PTM.MODNAA - || ptmFactory.getPTM(mod).getType() == PTM.MODNP || ptmFactory.getPTM(mod).getType() == PTM.MODNPAA) { + if (ptmFactory.getModification(mod).getType() == Modification.MODN || ptmFactory.getModification(mod).getType() == Modification.MODNAA + || ptmFactory.getModification(mod).getType() == Modification.MODNP || ptmFactory.getModification(mod).getType() == Modification.MODNPAA) { writer.append(residue + SEP); writer.append(ptmMass + SPACE); writer.append(variable + SPACE); writer.append("+1" + SPACE); writer.append(residue + connector + Long.toString(Math.round(ptmMass)) + SPACE); modIdMap.put(ptm.getName(), residue + connector + Long.toString(Math.round(ptmMass))); - } else if (ptmFactory.getPTM(mod).getType() == PTM.MODC || ptmFactory.getPTM(mod).getType() == PTM.MODCAA - || ptmFactory.getPTM(mod).getType() == PTM.MODCP || ptmFactory.getPTM(mod).getType() == PTM.MODCPAA) { + } else if (ptmFactory.getModification(mod).getType() == Modification.MODC || ptmFactory.getModification(mod).getType() == Modification.MODCAA + || ptmFactory.getModification(mod).getType() == Modification.MODCP || ptmFactory.getModification(mod).getType() == Modification.MODCPAA) { writer.append(residue + SEP); writer.append(ptmMass + SPACE); writer.append(variable + SPACE); @@ -183,7 +183,7 @@ private static void writePtmLine(BufferedWriter writer, String mod, String varia private static void fillModIdMap() { modIdMap = new HashMap(); - PTMFactory ptmFactory = PTMFactory.getInstance(); + ModificationFactory ptmFactory = ModificationFactory.getInstance(); List mods = new ArrayList(); mods.addAll(ptmFactory.getDefaultModifications()); mods.addAll(ptmFactory.getUserModifications()); @@ -192,7 +192,7 @@ private static void fillModIdMap() { // Write the modifications for (String mod : mods) { - PTM ptm = ptmFactory.getPTM(mod); + Modification ptm = ptmFactory.getModification(mod); double ptmMass = ptm.getRoundedMass(); if (ptmMass > 0) { @@ -202,20 +202,20 @@ private static void fillModIdMap() { } if (ptm.getPattern() == null || ptm.getPattern().getAminoAcidsAtTarget().isEmpty()) { - if (ptmFactory.getPTM(mod).getType() == PTM.MODN || ptmFactory.getPTM(mod).getType() == PTM.MODNAA - || ptmFactory.getPTM(mod).getType() == PTM.MODNP || ptmFactory.getPTM(mod).getType() == PTM.MODNPAA) { + if (ptmFactory.getModification(mod).getType() == Modification.MODN || ptmFactory.getModification(mod).getType() == Modification.MODNAA + || ptmFactory.getModification(mod).getType() == Modification.MODNP || ptmFactory.getModification(mod).getType() == Modification.MODNPAA) { modIdMap.put(ptm.getName(), "^" + connector + Long.toString(Math.round(ptmMass))); - } else if (ptmFactory.getPTM(mod).getType() == PTM.MODC || ptmFactory.getPTM(mod).getType() == PTM.MODCAA - || ptmFactory.getPTM(mod).getType() == PTM.MODCP || ptmFactory.getPTM(mod).getType() == PTM.MODCPAA) { + } else if (ptmFactory.getModification(mod).getType() == Modification.MODC || ptmFactory.getModification(mod).getType() == Modification.MODCAA + || ptmFactory.getModification(mod).getType() == Modification.MODCP || ptmFactory.getModification(mod).getType() == Modification.MODCPAA) { modIdMap.put(ptm.getName(), "$" + connector + Long.toString(Math.round(ptmMass))); } } else { - for (Character residue : ptmFactory.getPTM(mod).getPattern().getAminoAcidsAtTarget()) { - if (ptmFactory.getPTM(mod).getType() == PTM.MODN || ptmFactory.getPTM(mod).getType() == PTM.MODNAA - || ptmFactory.getPTM(mod).getType() == PTM.MODNP || ptmFactory.getPTM(mod).getType() == PTM.MODNPAA) { + for (Character residue : ptmFactory.getModification(mod).getPattern().getAminoAcidsAtTarget()) { + if (ptmFactory.getModification(mod).getType() == Modification.MODN || ptmFactory.getModification(mod).getType() == Modification.MODNAA + || ptmFactory.getModification(mod).getType() == Modification.MODNP || ptmFactory.getModification(mod).getType() == Modification.MODNPAA) { modIdMap.put(ptm.getName(), residue + connector + Long.toString(Math.round(ptmMass))); - } else if (ptmFactory.getPTM(mod).getType() == PTM.MODC || ptmFactory.getPTM(mod).getType() == PTM.MODCAA - || ptmFactory.getPTM(mod).getType() == PTM.MODCP || ptmFactory.getPTM(mod).getType() == PTM.MODCPAA) { + } else if (ptmFactory.getModification(mod).getType() == Modification.MODC || ptmFactory.getModification(mod).getType() == Modification.MODCAA + || ptmFactory.getModification(mod).getType() == Modification.MODCP || ptmFactory.getModification(mod).getType() == Modification.MODCPAA) { modIdMap.put(ptm.getName(), residue + connector + Long.toString(Math.round(ptmMass))); } else { modIdMap.put(ptm.getName(), residue + connector + Long.toString(Math.round(ptmMass))); @@ -231,7 +231,7 @@ private static void fillModIdMap() { * @return The header string. */ private static String getHeader() { - return "#AA offset type locations symbol PTM name"; + return "#AA offset type locations symbol Modification name"; } /** diff --git a/src/main/java/com/compomics/denovogui/io/SpectrumFactory.java b/src/main/java/com/compomics/denovogui/io/SpectrumFactory.java new file mode 100644 index 0000000..3c73177 --- /dev/null +++ b/src/main/java/com/compomics/denovogui/io/SpectrumFactory.java @@ -0,0 +1,291 @@ +package com.compomics.denovogui.io; + +import com.compomics.util.experiment.io.mass_spectrometry.MsFileHandler; +import com.compomics.util.experiment.mass_spectrometry.SpectrumProvider; +import com.compomics.util.experiment.mass_spectrometry.spectra.Precursor; +import com.compomics.util.experiment.mass_spectrometry.spectra.Spectrum; +import com.compomics.util.io.IoUtil; +import com.compomics.util.waiting.WaitingHandler; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; + +/** + * Compatibility wrapper around the Utilities 5 spectrum provider. + */ +public class SpectrumFactory { + + /** + * The singleton instance. + */ + private static final SpectrumFactory instance = new SpectrumFactory(); + /** + * The spectrum provider. + */ + private MsFileHandler msFileHandler = new MsFileHandler(); + /** + * File names indexed by the Utilities file name without extension. + */ + private final HashMap registeredFiles = new HashMap<>(); + + /** + * Returns the singleton instance. + * + * @return the singleton instance + */ + public static SpectrumFactory getInstance() { + return instance; + } + + /** + * Clears all registered spectra. + */ + public void clearFactory() { + closeFiles(); + msFileHandler = new MsFileHandler(); + registeredFiles.clear(); + } + + /** + * Registers spectra from the given file. + * + * @param spectrumFile the spectrum file + * @param waitingHandler the waiting handler + * + * @throws IOException if the file cannot be read + */ + public void addSpectra(File spectrumFile, WaitingHandler waitingHandler) throws IOException { + msFileHandler.register(spectrumFile, waitingHandler); + registeredFiles.put(IoUtil.removeExtension(spectrumFile.getName()), spectrumFile); + } + + /** + * Closes the registered spectrum files. + */ + public void closeFiles() { + msFileHandler.close(); + } + public void close() { + closeFiles(); + } + + public SpectrumProvider getSpectrumProvider() { + return msFileHandler; + } + + /** + * Returns the registered spectrum file names. + * + * @return the registered spectrum file names + */ + public ArrayList getMgfFileNames() { + return new ArrayList<>(Arrays.asList(msFileHandler.getOrderedFileNamesWithoutExtensions())); + } + + /** + * Returns all spectrum titles for the given spectrum file. + * + * @param spectrumFile the spectrum file + * + * @return all spectrum titles + */ + public ArrayList getSpectrumTitles(String spectrumFile) { + String fileName = IoUtil.removeExtension(new File(spectrumFile).getName()); + return new ArrayList<>(Arrays.asList(msFileHandler.getSpectrumTitles(fileName))); + } + + /** + * Returns the number of spectra in all files. + * + * @return the number of spectra + */ + public int getNSpectra() { + return getMgfFileNames().stream().mapToInt(this::getNSpectra).sum(); + } + + /** + * Returns the number of spectra in a file. + * + * @param spectrumFile the spectrum file + * + * @return the number of spectra + */ + public int getNSpectra(String spectrumFile) { + return getSpectrumTitles(spectrumFile).size(); + } + + /** + * Returns the precursor for the given spectrum key. + * + * @param spectrumKey the spectrum key + * + * @return the precursor + */ + public Precursor getPrecursor(String spectrumKey) { + return getPrecursor(Spectrum.getSpectrumFile(spectrumKey), Spectrum.getSpectrumTitle(spectrumKey)); + } + + /** + * Returns the precursor for the given spectrum. + * + * @param spectrumFile the spectrum file + * @param spectrumTitle the spectrum title + * + * @return the precursor + */ + public Precursor getPrecursor(String spectrumFile, String spectrumTitle) { + String fileName = IoUtil.removeExtension(new File(spectrumFile).getName()); + return msFileHandler.getPrecursor(fileName, spectrumTitle); + } + + /** + * Returns the spectrum for the given spectrum key. + * + * @param spectrumKey the spectrum key + * + * @return the spectrum + */ + public Spectrum getSpectrum(String spectrumKey) { + return getSpectrum(Spectrum.getSpectrumFile(spectrumKey), Spectrum.getSpectrumTitle(spectrumKey)); + } + + /** + * Returns the spectrum. + * + * @param spectrumFile the spectrum file + * @param spectrumTitle the spectrum title + * + * @return the spectrum + */ + public Spectrum getSpectrum(String spectrumFile, String spectrumTitle) { + String fileName = IoUtil.removeExtension(new File(spectrumFile).getName()); + return msFileHandler.getSpectrum(fileName, spectrumTitle); + } + public ArrayList getPostcursorSpectrumTitles(String fileNameWithoutExtension, String spectrumTitle) { + return msFileHandler.getPostcursorSpectrumTitles(fileNameWithoutExtension, spectrumTitle); + } + public double getPrecursorMz(String fileNameWithoutExtension, String spectrumTitle) { + return msFileHandler.getPrecursorMz(fileNameWithoutExtension, spectrumTitle); + } + public double getPrecursorRt(String fileNameWithoutExtension, String spectrumTitle) { + return msFileHandler.getPrecursorRt(fileNameWithoutExtension, spectrumTitle); + } + public int getSpectrumLevel(String fileNameWithoutExtension, String spectrumTitle) { + return msFileHandler.getSpectrumLevel(fileNameWithoutExtension, spectrumTitle); + } + public double[][] getPeaks(String fileNameWithoutExtension, String spectrumTitle) { + return msFileHandler.getPeaks(fileNameWithoutExtension, spectrumTitle); + } + public double getMinPrecMz(String fileNameWithoutExtension) { + return msFileHandler.getMinPrecMz(fileNameWithoutExtension); + } + public double getMaxPrecMz(String fileNameWithoutExtension) { + return msFileHandler.getMaxPrecMz(fileNameWithoutExtension); + } + public double getMaxPrecInt(String fileNameWithoutExtension) { + return msFileHandler.getMaxPrecInt(fileNameWithoutExtension); + } + public double getMaxPrecRT(String fileNameWithoutExtension) { + return msFileHandler.getMaxPrecRT(fileNameWithoutExtension); + } + public double getMinPrecMz() { + return msFileHandler.getMinPrecMz(); + } + public String[] getOrderedFileNamesWithoutExtensions() { + return msFileHandler.getOrderedFileNamesWithoutExtensions(); + } + public HashMap getFilePaths() { + return msFileHandler.getFilePaths(); + } + public HashMap getCmsFilePaths() { + return msFileHandler.getCmsFilePaths(); + } + + /** + * Returns true if the spectrum is loaded. + * + * @param spectrumKey the spectrum key + * + * @return true if the spectrum is loaded + */ + public boolean spectrumLoaded(String spectrumKey) { + return getSpectrum(spectrumKey) != null; + } + + /** + * Returns the maximum precursor m/z. + * + * @return the maximum precursor m/z + */ + public Double getMaxMz() { + return msFileHandler.getMaxPrecMz(); + } + + /** + * Returns the maximum charge. + * + * @return the maximum charge + */ + public Integer getMaxCharge() { + int maxCharge = 0; + for (String fileName : getMgfFileNames()) { + for (String spectrumTitle : getSpectrumTitles(fileName)) { + Precursor precursor = getPrecursor(fileName, spectrumTitle); + for (int charge : precursor.possibleCharges) { + maxCharge = Math.max(maxCharge, Math.abs(charge)); + } + } + } + return maxCharge; + } + + /** + * Returns the maximum intensity. + * + * @return the maximum intensity + */ + public Double getMaxIntensity() { + return msFileHandler.getMaxPrecInt(); + } + + /** + * Returns the maximum retention time. + * + * @return the maximum retention time + */ + public Double getMaxRT() { + return msFileHandler.getMaxPrecRT(); + } + + /** + * Returns the minimum retention time. + * + * @return the minimum retention time + */ + public Double getMinRT() { + double minRt = Double.MAX_VALUE; + for (String fileName : getMgfFileNames()) { + for (String spectrumTitle : getSpectrumTitles(fileName)) { + minRt = Math.min(minRt, getPrecursor(fileName, spectrumTitle).rt); + } + } + return minRt == Double.MAX_VALUE ? 0.0 : minRt; + } + + /** + * Returns the maximum number of peaks. + * + * @return the maximum number of peaks + */ + public Integer getMaxPeakCount() { + int maxPeakCount = 0; + for (String fileName : getMgfFileNames()) { + for (String spectrumTitle : getSpectrumTitles(fileName)) { + maxPeakCount = Math.max(maxPeakCount, getSpectrum(fileName, spectrumTitle).getNPeaks()); + } + } + return maxPeakCount; + } +} diff --git a/src/main/java/com/compomics/denovogui/io/TextExporter.java b/src/main/java/com/compomics/denovogui/io/TextExporter.java index f601016..ae9c40b 100644 --- a/src/main/java/com/compomics/denovogui/io/TextExporter.java +++ b/src/main/java/com/compomics/denovogui/io/TextExporter.java @@ -1,18 +1,20 @@ package com.compomics.denovogui.io; + +import com.compomics.denovogui.io.SpectrumFactory; -import com.compomics.util.experiment.biology.Peptide; +import com.compomics.util.experiment.biology.proteins.Peptide; import com.compomics.util.experiment.identification.Advocate; import com.compomics.util.experiment.identification.Identification; import com.compomics.util.experiment.identification.spectrum_assumptions.PeptideAssumption; -import com.compomics.util.experiment.identification.identification_parameters.SearchParameters; +import com.compomics.util.parameters.identification.search.SearchParameters; import com.compomics.util.experiment.identification.SpectrumIdentificationAssumption; import com.compomics.util.experiment.identification.spectrum_assumptions.TagAssumption; import com.compomics.util.experiment.identification.matches.ModificationMatch; import com.compomics.util.experiment.identification.amino_acid_tags.Tag; -import com.compomics.util.experiment.massspectrometry.Precursor; -import com.compomics.util.experiment.massspectrometry.Spectrum; -import com.compomics.util.experiment.massspectrometry.SpectrumFactory; -import com.compomics.util.experiment.refinementparameters.PepnovoAssumptionDetails; +import com.compomics.util.experiment.mass_spectrometry.spectra.Precursor; +import com.compomics.util.experiment.mass_spectrometry.spectra.Spectrum; +import com.compomics.util.experiment.mass_spectrometry.SpectrumProvider; +import com.compomics.util.experiment.refinement_parameters.PepnovoAssumptionDetails; import com.compomics.util.waiting.WaitingHandler; import java.io.BufferedWriter; import java.io.File; @@ -22,7 +24,6 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; -import uk.ac.ebi.jmzml.xml.io.MzMLUnmarshallerException; /** * This class allows exporting the results in a text file. @@ -58,13 +59,13 @@ public class TextExporter { * @throws IOException thrown if an IO exception occurs * @throws SQLException thrown if an SQL exception occurs * @throws ClassNotFoundException thrown if a ClassNotFoundException occurs - * @throws MzMLUnmarshallerException thrown if a precursor cannot be + * @throws IOException thrown if a precursor cannot be * extracted from a spectrum * @throws InterruptedException thrown if the process is interrupted */ public static void exportPeptides(File destinationFile, Identification identification, SearchParameters searchParameters, WaitingHandler waitingHandler, Double scoreThreshold, boolean greaterThan, Integer aNumberOfMatches) - throws IOException, SQLException, ClassNotFoundException, MzMLUnmarshallerException, InterruptedException { + throws IOException, SQLException, ClassNotFoundException, InterruptedException { FileWriter f = new FileWriter(destinationFile); @@ -84,7 +85,8 @@ public static void exportPeptides(File destinationFile, Identification identific b.write("File Name" + SEPARATOR + "Spectrum Title" + SEPARATOR + "Retention Time (s)" + SEPARATOR + "Measured m/z" + SEPARATOR + "Measured Charge" + SEPARATOR + "Rank" + SEPARATOR + "Protein(s)" + SEPARATOR + "Peptide" + SEPARATOR + "Peptide Variable Modifications" + SEPARATOR + "Modified Sequence" + SEPARATOR + "Tag" + SEPARATOR + "Longest Amino Acid Sequence" + SEPARATOR + "Tag Variable Modifications" + SEPARATOR + "Modified tag sequence" + SEPARATOR - + "PepNovo RankScore" + SEPARATOR + "PepNovo Score" + SEPARATOR + "DirecTag E-value" + SEPARATOR + "pNovo+ Score" + SEPARATOR + "Novor Score" + SEPARATOR + + "PepNovo RankScore" + SEPARATOR + "PepNovo Score" + SEPARATOR + "DirecTag E-value" + SEPARATOR + "pNovo+ Score" + SEPARATOR + + "Novor Score" + SEPARATOR + "InstaNovo Score" + SEPARATOR + "InstaNovo+ Score" + SEPARATOR + "InstaNovo with refinement Score" + SEPARATOR + "N-Gap" + SEPARATOR + "C-Gap" + SEPARATOR + "Theoretic m/z" + SEPARATOR + "Identification Charge" + SEPARATOR + "Tag Mass Error (Da)" + SEPARATOR + "Tag Mass Error (ppm)" + SEPARATOR + "Peptide Mass Error (Da)" + SEPARATOR + "Peptide Mass Error (ppm)" + SEPARATOR + "Isotope"); b.newLine(); @@ -161,66 +163,30 @@ public static void exportPeptides(File destinationFile, Identification identific b.write(peptide.getSequence() + SEPARATOR); b.write(getPeptideModificationsAsString(peptide) + SEPARATOR); - b.write(peptide.getTaggedModifiedSequence(searchParameters.getPtmSettings(), false, false, true, false) + SEPARATOR); + b.write(peptide.getTaggedModifiedSequence(searchParameters.getModificationParameters(), false, false, true, false) + SEPARATOR); // tag section if any - TagAssumption tagAssumption = new TagAssumption(); - tagAssumption = (TagAssumption) peptideAssumption.getUrParam(tagAssumption); + TagAssumption tagAssumption = null; if (tagAssumption != null) { Tag tag = tagAssumption.getTag(); b.write(tag.asSequence() + SEPARATOR); b.write(tag.getLongestAminoAcidSequence() + SEPARATOR); b.write(Tag.getTagModificationsAsString(tag) + SEPARATOR); - b.write(tag.getTaggedModifiedSequence(searchParameters.getPtmSettings(), false, false, true, false) + SEPARATOR); - if (tagAssumption.getAdvocate() == Advocate.pepnovo.getIndex()) { - PepnovoAssumptionDetails pepnovoAssumptionDetails = new PepnovoAssumptionDetails(); - pepnovoAssumptionDetails = (PepnovoAssumptionDetails) tagAssumption.getUrParam(pepnovoAssumptionDetails); - b.write(pepnovoAssumptionDetails.getRankScore() + SEPARATOR); - b.write(tagAssumption.getScore() + SEPARATOR + SEPARATOR + SEPARATOR + SEPARATOR); - } else if (tagAssumption.getAdvocate() == Advocate.direcTag.getIndex()) { - b.write(SEPARATOR + SEPARATOR + tagAssumption.getScore() + SEPARATOR + SEPARATOR + SEPARATOR); - } else if (tagAssumption.getAdvocate() == Advocate.pNovo.getIndex()) { - b.write(SEPARATOR + SEPARATOR + SEPARATOR + tagAssumption.getScore() + SEPARATOR + SEPARATOR); - } else if (tagAssumption.getAdvocate() == Advocate.novor.getIndex()) { - b.write(SEPARATOR + SEPARATOR + SEPARATOR + SEPARATOR + tagAssumption.getScore() + SEPARATOR); - } + b.write(tag.getTaggedModifiedSequence(searchParameters.getModificationParameters(), false, false, true, false) + SEPARATOR); + writeScoreColumns(b, tagAssumption); b.write(tag.getNTerminalGap() + SEPARATOR); b.write(tag.getCTerminalGap() + SEPARATOR); b.write(tag.getMass() + SEPARATOR); - b.write(tagAssumption.getIdentificationCharge().value + SEPARATOR); + b.write(tagAssumption.getIdentificationCharge() + SEPARATOR); double massDeviation = tagAssumption.getDeltaMass(precursor.getMz(), false, searchParameters.getMinIsotopicCorrection(), searchParameters.getMaxIsotopicCorrection()); b.write(massDeviation + SEPARATOR); massDeviation = tagAssumption.getDeltaMass(precursor.getMz(), true, searchParameters.getMinIsotopicCorrection(), searchParameters.getMaxIsotopicCorrection()); b.write(massDeviation + SEPARATOR); - } else if (peptideAssumption.getAdvocate() == Advocate.novor.getIndex()) { - b.write(SEPARATOR); - b.write(SEPARATOR); - b.write(SEPARATOR); - b.write(SEPARATOR); - b.write(SEPARATOR + SEPARATOR + SEPARATOR + SEPARATOR + peptideAssumption.getScore() + SEPARATOR); - b.write(SEPARATOR); - b.write(SEPARATOR); - b.write(SEPARATOR); - b.write(SEPARATOR); - b.write(SEPARATOR); - b.write(SEPARATOR); - } else { - b.write(SEPARATOR); - b.write(SEPARATOR); - b.write(SEPARATOR); - b.write(SEPARATOR); - b.write(SEPARATOR); - b.write(SEPARATOR); - b.write(SEPARATOR); - b.write(SEPARATOR); - b.write(SEPARATOR); - b.write(SEPARATOR); - b.write(SEPARATOR); - b.write(SEPARATOR); - b.write(SEPARATOR); - b.write(SEPARATOR); - b.write(SEPARATOR); - } + } else { + writeEmptyColumns(b, 4); + writeScoreColumns(b, peptideAssumption); + writeEmptyColumns(b, 6); + } Double massDeviation = peptideAssumption.getDeltaMass(precursor.getMz(), false, searchParameters.getMinIsotopicCorrection(), searchParameters.getMaxIsotopicCorrection()); b.write(massDeviation + SEPARATOR); massDeviation = peptideAssumption.getDeltaMass(precursor.getMz(), true, searchParameters.getMinIsotopicCorrection(), searchParameters.getMaxIsotopicCorrection()); @@ -263,13 +229,13 @@ public static void exportPeptides(File destinationFile, Identification identific * @throws IOException thrown if an IO exception occurs * @throws SQLException thrown if an SQL exception occurs * @throws ClassNotFoundException thrown if a ClassNotFoundException occurs - * @throws MzMLUnmarshallerException thrown if a precursor cannot be + * @throws IOException thrown if a precursor cannot be * extracted from a spectrum * @throws InterruptedException thrown if the process is interrupted */ public static void exportTags(File destinationFile, Identification identification, SearchParameters searchParameters, WaitingHandler waitingHandler, Double scoreThreshold, boolean greaterThan, Integer aNumberOfMatches) - throws IOException, SQLException, ClassNotFoundException, MzMLUnmarshallerException, InterruptedException { + throws IOException, SQLException, ClassNotFoundException, InterruptedException { FileWriter f = new FileWriter(destinationFile); @@ -288,7 +254,8 @@ public static void exportTags(File destinationFile, Identification identificatio try { b.write("File Name" + SEPARATOR + "Spectrum Title" + SEPARATOR + "Retention Time (s)" + SEPARATOR + "Measured m/z" + SEPARATOR + "Measured Charge" + SEPARATOR + "Rank" + SEPARATOR + "Tag" + SEPARATOR + "Longest AminoAcid sequence" + SEPARATOR + "Variable Modifications" + SEPARATOR + "Modified Sequence" + SEPARATOR - + "PepNovo RankScore" + SEPARATOR + "PepNovo Score" + SEPARATOR + "DirecTag E-value" + SEPARATOR + "pNovo+ Score" + SEPARATOR + "Novor Score" + SEPARATOR + + "PepNovo RankScore" + SEPARATOR + "PepNovo Score" + SEPARATOR + "DirecTag E-value" + SEPARATOR + "pNovo+ Score" + SEPARATOR + + "Novor Score" + SEPARATOR + "InstaNovo Score" + SEPARATOR + "InstaNovo+ Score" + SEPARATOR + "InstaNovo with refinement Score" + SEPARATOR + "N-Gap" + SEPARATOR + "C-Gap" + SEPARATOR + "Theoretic m/z" + SEPARATOR + "Identification Charge"); b.newLine(); @@ -384,20 +351,80 @@ public static void exportTags(File destinationFile, Identification identificatio * @throws java.lang.InterruptedException exception thrown if a thread is * interrupted */ - public static void writeTagExportLine(BufferedWriter b, SpectrumIdentificationAssumption assumption, SearchParameters searchParameters) throws IOException, InterruptedException { - if (assumption instanceof TagAssumption) { - TagAssumption tagAssumption = (TagAssumption) assumption; - writeTagExportLine(b, tagAssumption, searchParameters); + public static void writeTagExportLine(BufferedWriter b, SpectrumIdentificationAssumption assumption, SearchParameters searchParameters) throws IOException, InterruptedException { + if (assumption instanceof TagAssumption) { + TagAssumption tagAssumption = (TagAssumption) assumption; + writeTagExportLine(b, tagAssumption, searchParameters); } else if (assumption instanceof PeptideAssumption) { PeptideAssumption peptideAssumption = (PeptideAssumption) assumption; writeTagExportLine(b, peptideAssumption, searchParameters); } else { throw new UnsupportedOperationException("Export not implemented for assumption of type " + assumption.getClass() + "."); - } - } - - /** - * Writes the details on the given peptide assumption to the given writer in + } + } + + /** + * Writes the score columns for the given assumption. + * + * @param b the writer + * @param assumption the assumption + * + * @throws IOException exception thrown whenever an error occurred while + * writing + */ + private static void writeScoreColumns(BufferedWriter b, SpectrumIdentificationAssumption assumption) throws IOException { + int advocate = assumption.getAdvocate(); + if (advocate == Advocate.pepnovo.getIndex()) { + PepnovoAssumptionDetails pepnovoAssumptionDetails = new PepnovoAssumptionDetails(); + pepnovoAssumptionDetails = (PepnovoAssumptionDetails) assumption.getUrParam(pepnovoAssumptionDetails); + b.write(pepnovoAssumptionDetails.getRankScore() + SEPARATOR); + b.write(assumption.getScore() + SEPARATOR); + writeEmptyColumns(b, 6); + } else if (advocate == Advocate.direcTag.getIndex()) { + writeEmptyColumns(b, 2); + b.write(assumption.getScore() + SEPARATOR); + writeEmptyColumns(b, 5); + } else if (advocate == Advocate.pNovo.getIndex()) { + writeEmptyColumns(b, 3); + b.write(assumption.getScore() + SEPARATOR); + writeEmptyColumns(b, 4); + } else if (advocate == Advocate.novor.getIndex()) { + writeEmptyColumns(b, 4); + b.write(assumption.getScore() + SEPARATOR); + writeEmptyColumns(b, 3); + } else if (advocate == Advocate.instanovo.getIndex()) { + writeEmptyColumns(b, 5); + b.write(assumption.getScore() + SEPARATOR); + writeEmptyColumns(b, 2); + } else if (advocate == Advocate.instanovoPlus.getIndex()) { + writeEmptyColumns(b, 6); + b.write(assumption.getScore() + SEPARATOR); + writeEmptyColumns(b, 1); + } else if (advocate == Advocate.instanovoRefined.getIndex()) { + writeEmptyColumns(b, 7); + b.write(assumption.getScore() + SEPARATOR); + } else { + writeEmptyColumns(b, 8); + } + } + + /** + * Writes empty tab-separated columns. + * + * @param b the writer + * @param nColumns the number of columns + * + * @throws IOException exception thrown whenever an error occurred while + * writing + */ + private static void writeEmptyColumns(BufferedWriter b, int nColumns) throws IOException { + for (int i = 0; i < nColumns; i++) { + b.write(SEPARATOR); + } + } + + /** + * Writes the details on the given peptide assumption to the given writer in * the form of a tag export. * * @param b the writer @@ -412,26 +439,15 @@ public static void writeTagExportLine(BufferedWriter b, SpectrumIdentificationAs public static void writeTagExportLine(BufferedWriter b, PeptideAssumption peptideAssumption, SearchParameters searchParameters) throws IOException, InterruptedException { Peptide peptide = peptideAssumption.getPeptide(); - b.write(peptide.getSequence() + SEPARATOR); - b.write(peptide.getSequence() + SEPARATOR); - b.write(Peptide.getPeptideModificationsAsString(peptide, true) + SEPARATOR); - b.write(peptide.getTaggedModifiedSequence(searchParameters.getPtmSettings(), false, false, true, false) + SEPARATOR); - if (peptideAssumption.getAdvocate() == Advocate.pepnovo.getIndex()) { - PepnovoAssumptionDetails pepnovoAssumptionDetails = new PepnovoAssumptionDetails(); - pepnovoAssumptionDetails = (PepnovoAssumptionDetails) peptideAssumption.getUrParam(pepnovoAssumptionDetails); - b.write(pepnovoAssumptionDetails.getRankScore() + SEPARATOR); - b.write(peptideAssumption.getScore() + SEPARATOR + SEPARATOR + SEPARATOR + SEPARATOR); - } else if (peptideAssumption.getAdvocate() == Advocate.direcTag.getIndex()) { - b.write(SEPARATOR + SEPARATOR + peptideAssumption.getScore() + SEPARATOR + SEPARATOR + SEPARATOR); - } else if (peptideAssumption.getAdvocate() == Advocate.pNovo.getIndex()) { - b.write(SEPARATOR + SEPARATOR + SEPARATOR + peptideAssumption.getScore() + SEPARATOR + SEPARATOR); - } else if (peptideAssumption.getAdvocate() == Advocate.novor.getIndex()) { - b.write(SEPARATOR + SEPARATOR + SEPARATOR + SEPARATOR + peptideAssumption.getScore() + SEPARATOR); - } - b.write(0 + SEPARATOR); - b.write(0 + SEPARATOR); - b.write(peptide.getMass() + SEPARATOR); - b.write(peptideAssumption.getIdentificationCharge().value + SEPARATOR); + b.write(peptide.getSequence() + SEPARATOR); + b.write(peptide.getSequence() + SEPARATOR); + b.write(Peptide.getPeptideModificationsAsString(peptide, true) + SEPARATOR); + b.write(peptide.getTaggedModifiedSequence(searchParameters.getModificationParameters(), false, false, true, false) + SEPARATOR); + writeScoreColumns(b, peptideAssumption); + b.write(0 + SEPARATOR); + b.write(0 + SEPARATOR); + b.write(peptide.getMass() + SEPARATOR); + b.write(peptideAssumption.getIdentificationCharge() + SEPARATOR); } /** @@ -449,25 +465,14 @@ public static void writeTagExportLine(BufferedWriter b, TagAssumption tagAssumpt Tag tag = tagAssumption.getTag(); b.write(tag.asSequence() + SEPARATOR); - b.write(tag.getLongestAminoAcidSequence() + SEPARATOR); - b.write(Tag.getTagModificationsAsString(tag) + SEPARATOR); - b.write(tag.getTaggedModifiedSequence(searchParameters.getPtmSettings(), false, false, true, false) + SEPARATOR); - if (tagAssumption.getAdvocate() == Advocate.pepnovo.getIndex()) { - PepnovoAssumptionDetails pepnovoAssumptionDetails = new PepnovoAssumptionDetails(); - pepnovoAssumptionDetails = (PepnovoAssumptionDetails) tagAssumption.getUrParam(pepnovoAssumptionDetails); - b.write(pepnovoAssumptionDetails.getRankScore() + SEPARATOR); - b.write(tagAssumption.getScore() + SEPARATOR + SEPARATOR + SEPARATOR + SEPARATOR); - } else if (tagAssumption.getAdvocate() == Advocate.direcTag.getIndex()) { - b.write(SEPARATOR + SEPARATOR + tagAssumption.getScore() + SEPARATOR + SEPARATOR + SEPARATOR); - } else if (tagAssumption.getAdvocate() == Advocate.pNovo.getIndex()) { - b.write(SEPARATOR + SEPARATOR + SEPARATOR + tagAssumption.getScore() + SEPARATOR + SEPARATOR); - } else if (tagAssumption.getAdvocate() == Advocate.novor.getIndex()) { - b.write(SEPARATOR + SEPARATOR + SEPARATOR + SEPARATOR + tagAssumption.getScore() + SEPARATOR); - } - b.write(tag.getNTerminalGap() + SEPARATOR); + b.write(tag.getLongestAminoAcidSequence() + SEPARATOR); + b.write(Tag.getTagModificationsAsString(tag) + SEPARATOR); + b.write(tag.getTaggedModifiedSequence(searchParameters.getModificationParameters(), false, false, true, false) + SEPARATOR); + writeScoreColumns(b, tagAssumption); + b.write(tag.getNTerminalGap() + SEPARATOR); b.write(tag.getCTerminalGap() + SEPARATOR); b.write(tag.getMass() + SEPARATOR); - b.write(tagAssumption.getIdentificationCharge().value + SEPARATOR); + b.write(tagAssumption.getIdentificationCharge() + SEPARATOR); } /** @@ -487,12 +492,12 @@ public static void writeTagExportLine(BufferedWriter b, TagAssumption tagAssumpt * @throws IOException thrown if an IO exception occurs * @throws SQLException thrown if an SQL exception occurs * @throws ClassNotFoundException thrown if a ClassNotFoundException occurs - * @throws MzMLUnmarshallerException thrown if a precursor cannot be + * @throws IOException thrown if a precursor cannot be * extracted from a spectrum * @throws InterruptedException thrown if the process is interrupted */ public static void exportBlastPSMs(File destinationFile, Identification identification, SearchParameters searchParameters, WaitingHandler waitingHandler, - Double scoreThreshold, boolean greaterThan, Integer aNumberOfMatches) throws IOException, SQLException, ClassNotFoundException, MzMLUnmarshallerException, InterruptedException { + Double scoreThreshold, boolean greaterThan, Integer aNumberOfMatches) throws IOException, SQLException, ClassNotFoundException, InterruptedException { FileWriter f = new FileWriter(destinationFile); double threshold = 0; diff --git a/src/main/java/com/compomics/denovogui/preferences/DeNovoGUIPathPreferences.java b/src/main/java/com/compomics/denovogui/preferences/DeNovoGUIPathPreferences.java index 49069d6..985c03c 100644 --- a/src/main/java/com/compomics/denovogui/preferences/DeNovoGUIPathPreferences.java +++ b/src/main/java/com/compomics/denovogui/preferences/DeNovoGUIPathPreferences.java @@ -2,7 +2,7 @@ import com.compomics.denovogui.gui.ResultsFrame; import com.compomics.software.settings.PathKey; -import com.compomics.software.settings.UtilitiesPathPreferences; +import com.compomics.software.settings.UtilitiesPathParameters; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; @@ -106,7 +106,7 @@ public static void loadPathPreferencesFromFile(File inputFile) throws FileNotFou while ((line = br.readLine()) != null) { line = line.trim(); if (!line.equals("") && !line.startsWith("#")) { - loadPathPreferenceFromLine(line); + loadPathParameterFromLine(line); } } } finally { @@ -120,17 +120,17 @@ public static void loadPathPreferencesFromFile(File inputFile) throws FileNotFou * @param line the line where to read the path from * @throws FileNotFoundException thrown if the file cannot be found */ - public static void loadPathPreferenceFromLine(String line) throws FileNotFoundException { - String id = UtilitiesPathPreferences.getPathID(line); + public static void loadPathParameterFromLine(String line) throws FileNotFoundException { + String id = UtilitiesPathParameters.getPathID(line); if (id.equals("")) { throw new IllegalArgumentException("Impossible to parse path in " + line + "."); } DeNovoGUIPathKey denovoguiPathKey = DeNovoGUIPathKey.getKeyFromId(id); if (denovoguiPathKey == null) { - UtilitiesPathPreferences.loadPathPreferenceFromLine(line); + UtilitiesPathParameters.loadPathParameterFromLine(line); } else { - String path = UtilitiesPathPreferences.getPath(line); - if (!path.equals(UtilitiesPathPreferences.defaultPath)) { + String path = UtilitiesPathParameters.getPath(line); + if (!path.equals(UtilitiesPathParameters.defaultPath)) { File file = new File(path); if (!file.exists()) { throw new FileNotFoundException("File " + path + " not found."); @@ -138,7 +138,7 @@ public static void loadPathPreferenceFromLine(String line) throws FileNotFoundEx if (denovoguiPathKey.isDirectory && !file.isDirectory()) { throw new FileNotFoundException("Found a file when expecting a directory for " + denovoguiPathKey.id + "."); } - setPathPreference(denovoguiPathKey, path); + setPathParameter(denovoguiPathKey, path); } } } @@ -152,7 +152,7 @@ public static void loadPathPreferenceFromLine(String line) throws FileNotFoundEx * * @throws FileNotFoundException thrown if an FileNotFoundException occurs */ - public static String getPathPreference(DeNovoGUIPathKey deNovoGuiPathKey) throws IOException { + public static String getPathParameter(DeNovoGUIPathKey deNovoGuiPathKey) throws IOException { switch (deNovoGuiPathKey) { case matchesDirectory: return ResultsFrame.getCacheDirectoryParent(); @@ -167,7 +167,7 @@ public static String getPathPreference(DeNovoGUIPathKey deNovoGuiPathKey) throws * @param deNovoGuiPathKey the key of the path * @param path the path to be set */ - public static void setPathPreference(DeNovoGUIPathKey deNovoGuiPathKey, String path) { + public static void setPathParameter(DeNovoGUIPathKey deNovoGuiPathKey, String path) { switch (deNovoGuiPathKey) { case matchesDirectory: ResultsFrame.setCacheDirectoryParent(path); @@ -185,13 +185,13 @@ public static void setPathPreference(DeNovoGUIPathKey deNovoGuiPathKey, String p * * @throws FileNotFoundException thrown if an FileNotFoundException occurs */ - public static void setPathPreference(PathKey pathKey, String path) throws IOException { + public static void setPathParameter(PathKey pathKey, String path) throws IOException { if (pathKey instanceof DeNovoGUIPathKey) { DeNovoGUIPathKey peptideShakerPathKey = (DeNovoGUIPathKey) pathKey; - DeNovoGUIPathPreferences.setPathPreference(peptideShakerPathKey, path); - } else if (pathKey instanceof UtilitiesPathPreferences.UtilitiesPathKey) { - UtilitiesPathPreferences.UtilitiesPathKey utilitiesPathKey = (UtilitiesPathPreferences.UtilitiesPathKey) pathKey; - UtilitiesPathPreferences.setPathPreference(utilitiesPathKey, path); + DeNovoGUIPathPreferences.setPathParameter(peptideShakerPathKey, path); + } else if (pathKey instanceof UtilitiesPathParameters.UtilitiesPathKey) { + UtilitiesPathParameters.UtilitiesPathKey utilitiesPathKey = (UtilitiesPathParameters.UtilitiesPathKey) pathKey; + UtilitiesPathParameters.setPathParameter(utilitiesPathKey, path); } else { throw new UnsupportedOperationException("Path " + pathKey.getId() + " not implemented."); } @@ -214,9 +214,9 @@ public static void setAllPathsIn(String path) throws FileNotFoundException { if (!newFile.exists()) { throw new FileNotFoundException(newFile.getAbsolutePath() + " could not be created."); } - setPathPreference(denovoguiPathKey, newFile.getAbsolutePath()); + setPathParameter(denovoguiPathKey, newFile.getAbsolutePath()); } - UtilitiesPathPreferences.setAllPathsIn(path); + UtilitiesPathParameters.setAllPathsIn(path); } /** @@ -248,7 +248,7 @@ public static void writeConfigurationToFile(BufferedWriter bw) throws IOExceptio for (DeNovoGUIPathKey pathKey : DeNovoGUIPathKey.values()) { writePathToFile(bw, pathKey); } - UtilitiesPathPreferences.writeConfigurationToFile(bw); + UtilitiesPathParameters.writeConfigurationToFile(bw); } /** @@ -260,12 +260,12 @@ public static void writeConfigurationToFile(BufferedWriter bw) throws IOExceptio * @throws IOException thrown if there are issues writing */ public static void writePathToFile(BufferedWriter bw, DeNovoGUIPathKey pathKey) throws IOException { - bw.write(pathKey.id + UtilitiesPathPreferences.separator); + bw.write(pathKey.id + UtilitiesPathParameters.separator); switch (pathKey) { case matchesDirectory: String toWrite = ResultsFrame.getCacheDirectoryParent(); if (toWrite == null) { - toWrite = UtilitiesPathPreferences.defaultPath; + toWrite = UtilitiesPathParameters.defaultPath; } bw.write(toWrite); break; @@ -288,12 +288,12 @@ public static void writePathToFile(BufferedWriter bw, DeNovoGUIPathKey pathKey) public static ArrayList getErrorKeys() throws IOException { ArrayList result = new ArrayList(); for (DeNovoGUIPathKey deNovoGUIPathKey : DeNovoGUIPathKey.values()) { - String folder = DeNovoGUIPathPreferences.getPathPreference(deNovoGUIPathKey); - if (folder != null && !UtilitiesPathPreferences.testPath(folder)) { + String folder = DeNovoGUIPathPreferences.getPathParameter(deNovoGUIPathKey); + if (folder != null && !UtilitiesPathParameters.testPath(folder)) { result.add(deNovoGUIPathKey); } } - result.addAll(UtilitiesPathPreferences.getErrorKeys()); + result.addAll(UtilitiesPathParameters.getErrorKeys()); return result; } } diff --git a/src/main/java/com/compomics/denovogui/util/InstaNovoSetup.java b/src/main/java/com/compomics/denovogui/util/InstaNovoSetup.java new file mode 100644 index 0000000..344eebf --- /dev/null +++ b/src/main/java/com/compomics/denovogui/util/InstaNovoSetup.java @@ -0,0 +1,493 @@ +package com.compomics.denovogui.util; + +import com.compomics.util.waiting.WaitingHandler; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.Scanner; + +/** + * Helper methods for installing and locating InstaNovo. + * + * @author CompOmics + */ +public class InstaNovoSetup { + + /** + * The supported InstaNovo version. + */ + public static final String INSTANOVO_VERSION = "1.2.2"; + /** + * The CPU package specification. + */ + private static final String INSTANOVO_CPU_PACKAGE = "instanovo[cpu]==" + INSTANOVO_VERSION; + /** + * The CUDA package specification. + */ + private static final String INSTANOVO_CUDA_PACKAGE = "instanovo[cu126]==" + INSTANOVO_VERSION; + /** + * The PyTorch CPU wheel index. + */ + private static final String PYTORCH_CPU_INDEX = "https://download.pytorch.org/whl/cpu"; + /** + * The PyTorch CUDA 12.6 wheel index. + */ + private static final String PYTORCH_CUDA_INDEX = "https://download.pytorch.org/whl/cu126"; + + /** + * Returns the default shared CompOmics InstaNovo installation folder. + * + * @return the default installation folder + */ + public static File getDefaultInstallationFolder() { + + return new File(getCompOmicsDataFolder(), "tools" + File.separator + "instanovo" + File.separator + INSTANOVO_VERSION); + } + + /** + * Returns the platform-specific CompOmics data folder. + * + * @return the CompOmics data folder + */ + private static File getCompOmicsDataFolder() { + + String userHome = System.getProperty("user.home"); + + if (isWindows()) { + + String localAppData = System.getenv("LOCALAPPDATA"); + + if (localAppData != null && !localAppData.trim().isEmpty()) { + return new File(localAppData, "CompOmics"); + } + + return new File(userHome, "AppData" + File.separator + "Local" + File.separator + "CompOmics"); + } + + if (isMacOs()) { + return new File(userHome, "Library" + File.separator + "Application Support" + File.separator + "CompOmics"); + } + + String xdgDataHome = System.getenv("XDG_DATA_HOME"); + + if (xdgDataHome != null && !xdgDataHome.trim().isEmpty() && new File(xdgDataHome).isAbsolute()) { + return new File(xdgDataHome, "compomics"); + } + + return new File(userHome, ".local" + File.separator + "share" + File.separator + "compomics"); + } + + /** + * Installs uv if needed and creates an InstaNovo virtual environment. + * + * @param installationFolder the installation folder + * @param waitingHandler the waiting handler + * + * @throws IOException thrown if a command fails + * @throws InterruptedException thrown if interrupted + */ + public static void install(File installationFolder, WaitingHandler waitingHandler) throws IOException, InterruptedException { + + if (!installationFolder.exists() && !installationFolder.mkdirs()) { + throw new IOException("Could not create " + installationFolder + "."); + } + + File uvExecutable = ensureUv(waitingHandler); + boolean cudaInstall = isCudaGpuDetected(); + String instaNovoPackage = cudaInstall ? INSTANOVO_CUDA_PACKAGE : INSTANOVO_CPU_PACKAGE; + String pytorchIndex = cudaInstall ? PYTORCH_CUDA_INDEX : PYTORCH_CPU_INDEX; + + append(waitingHandler, "Creating the InstaNovo Python environment in " + installationFolder + "."); + runCommand( + Arrays.asList(uvExecutable.getAbsolutePath(), "venv", "--python", "3.12", "--clear"), + installationFolder, + waitingHandler + ); + + append(waitingHandler, "Installing " + instaNovoPackage + (cudaInstall ? " with CUDA PyTorch wheels." : " with CPU PyTorch wheels.")); + runCommand( + Arrays.asList( + uvExecutable.getAbsolutePath(), + "pip", + "install", + instaNovoPackage, + "--extra-index-url", + pytorchIndex, + "--index-strategy", + "unsafe-best-match" + ), + installationFolder, + waitingHandler + ); + } + + /** + * Returns a description of the install variant selected for this machine. + * + * @return the install variant description + */ + public static String getInstallVariantDescription() { + + if (isCudaGpuDetected()) { + return "GPU installation: InstaNovo " + INSTANOVO_VERSION + " with CUDA 12.6 PyTorch wheels."; + } + + if (isAppleSiliconMac()) { + return "macOS installation: InstaNovo " + INSTANOVO_VERSION + " with PyTorch wheels that can use Apple Silicon MPS when available."; + } + + if (isMacOs()) { + return "CPU fallback installation: CUDA is not available on macOS and no Apple Silicon GPU was detected. Prediction will be very slow."; + } + + return "CPU fallback installation: no NVIDIA/CUDA GPU was detected. Prediction will be very slow."; + } + + /** + * Returns true if an NVIDIA/CUDA-capable GPU is detected. + * + * @return true if a CUDA GPU is detected + */ + public static boolean isCudaGpuDetected() { + + if (isMacOs()) { + return false; + } + + String cudaPath = System.getenv("CUDA_PATH"); + String cudaHome = System.getenv("CUDA_HOME"); + + return commandSucceeds("nvidia-smi") + || new File("/proc/driver/nvidia/version").exists() + || findOnPath("nvcc") != null + || new File("/usr/local/cuda/bin/nvcc").exists() + || new File("/usr/local/cuda-12.6/bin/nvcc").exists() + || cudaPath != null && new File(cudaPath, "bin" + File.separator + "nvcc.exe").exists() + || cudaHome != null && new File(cudaHome, "bin" + File.separator + "nvcc.exe").exists() + || new File("C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA").exists() + || new File("C:\\Windows\\System32\\nvidia-smi.exe").exists(); + } + + /** + * Returns the InstaNovo models file from either a checkout root or a virtual + * environment installation. + * + * @param instaNovoLocation the InstaNovo location + * + * @return the models file, or null if not found + */ + public static File getModelsFile(File instaNovoLocation) { + + if (instaNovoLocation == null) { + return null; + } + + ArrayList candidates = new ArrayList(); + candidates.add(new File(instaNovoLocation, "instanovo" + File.separator + "models.json")); + candidates.add(new File(instaNovoLocation, ".venv" + File.separator + "Lib" + File.separator + "site-packages" + File.separator + "instanovo" + File.separator + "models.json")); + + File unixSitePackages = new File(instaNovoLocation, ".venv" + File.separator + "lib"); + + if (unixSitePackages.exists()) { + + File[] pythonFolders = unixSitePackages.listFiles(); + + if (pythonFolders != null) { + for (File pythonFolder : pythonFolders) { + candidates.add(new File(pythonFolder, "site-packages" + File.separator + "instanovo" + File.separator + "models.json")); + } + } + } + + for (File candidate : candidates) { + if (candidate.exists()) { + return candidate; + } + } + + return null; + } + + /** + * Ensures that uv is available. + * + * @param waitingHandler the waiting handler + * + * @return the uv executable + * + * @throws IOException thrown if uv cannot be installed + * @throws InterruptedException thrown if interrupted + */ + private static File ensureUv(WaitingHandler waitingHandler) throws IOException, InterruptedException { + + File uvExecutable = findUvExecutable(); + + if (uvExecutable != null) { + append(waitingHandler, "Using uv at " + uvExecutable + "."); + return uvExecutable; + } + + append(waitingHandler, "uv was not found. Installing uv with the official standalone installer."); + runCommand(getUvInstallCommand(), null, waitingHandler); + + uvExecutable = findUvExecutable(); + + if (uvExecutable == null) { + throw new IOException("uv was installed, but the uv executable could not be found. Restart the application or install uv manually."); + } + + return uvExecutable; + } + + /** + * Finds uv on PATH or in the default standalone installer location. + * + * @return the uv executable, or null if not found + */ + private static File findUvExecutable() { + + String executableName = isWindows() ? "uv.exe" : "uv"; + File pathExecutable = findOnPath(executableName); + + if (pathExecutable != null) { + return pathExecutable; + } + + String userHome = System.getProperty("user.home"); + String localAppData = System.getenv("LOCALAPPDATA"); + + ArrayList candidates = new ArrayList(); + candidates.add(new File(userHome, ".local" + File.separator + "bin" + File.separator + executableName)); + + if (localAppData != null) { + candidates.add(new File(localAppData, "uv" + File.separator + "uv.exe")); + candidates.add(new File(localAppData, "Programs" + File.separator + "uv" + File.separator + "uv.exe")); + } + + for (File candidate : candidates) { + if (candidate.exists()) { + candidate.setExecutable(true); + return candidate; + } + } + + return null; + } + + /** + * Finds an executable on PATH. + * + * @param executableName the executable name + * + * @return the executable, or null if not found + */ + private static File findOnPath(String executableName) { + + String path = System.getenv("PATH"); + + if (path == null) { + return null; + } + + String[] pathEntries = path.split(File.pathSeparator); + + for (String pathEntry : pathEntries) { + File candidate = new File(pathEntry, executableName); + if (candidate.exists()) { + candidate.setExecutable(true); + return candidate; + } + } + + return null; + } + + /** + * Returns the uv standalone installer command. + * + * @return the command + */ + private static List getUvInstallCommand() { + + if (isWindows()) { + return Arrays.asList( + "powershell", + "-ExecutionPolicy", + "ByPass", + "-c", + "$env:UV_NO_MODIFY_PATH='1'; irm https://astral.sh/uv/install.ps1 | iex" + ); + } + + return Arrays.asList( + "sh", + "-c", + "if command -v curl >/dev/null 2>&1; then curl -LsSf https://astral.sh/uv/install.sh | env UV_NO_MODIFY_PATH=1 sh; " + + "elif command -v wget >/dev/null 2>&1; then wget -qO- https://astral.sh/uv/install.sh | env UV_NO_MODIFY_PATH=1 sh; " + + "else echo 'Installing uv requires curl or wget.' >&2; exit 1; fi" + ); + } + + /** + * Runs a command. + * + * @param command the command + * @param workingDirectory the working directory + * @param waitingHandler the waiting handler + * + * @throws IOException thrown if the command fails + * @throws InterruptedException thrown if interrupted + */ + private static void runCommand(List command, File workingDirectory, WaitingHandler waitingHandler) throws IOException, InterruptedException { + + append(waitingHandler, "Running: " + join(command)); + + ProcessBuilder processBuilder = new ProcessBuilder(command); + processBuilder.redirectErrorStream(true); + + if (workingDirectory != null) { + processBuilder.directory(workingDirectory); + } + + Process process = processBuilder.start(); + + Scanner scanner = new Scanner(process.getInputStream()); + LinkedList recentOutput = new LinkedList(); + + while (scanner.hasNextLine()) { + + if (waitingHandler != null && waitingHandler.isRunCanceled()) { + process.destroy(); + throw new InterruptedException("InstaNovo installation canceled."); + } + + String line = scanner.nextLine(); + recentOutput.add(line); + + while (recentOutput.size() > 20) { + recentOutput.removeFirst(); + } + + append(waitingHandler, line); + } + + int exitCode = process.waitFor(); + + if (exitCode != 0) { + throw new IOException("Command exited with status " + exitCode + ": " + join(command) + getRecentOutput(recentOutput)); + } + } + + /** + * Returns the recent command output for error reporting. + * + * @param recentOutput the recent output lines + * + * @return the recent command output + */ + private static String getRecentOutput(LinkedList recentOutput) { + + if (recentOutput.isEmpty()) { + return ""; + } + + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("\n\nLast command output:"); + + for (String line : recentOutput) { + stringBuilder.append("\n").append(line); + } + + return stringBuilder.toString(); + } + + /** + * Appends text to the waiting handler. + * + * @param waitingHandler the waiting handler + * @param text the text + */ + private static void append(WaitingHandler waitingHandler, String text) { + + if (waitingHandler != null) { + if (waitingHandler.isReport()) { + waitingHandler.appendReport(text, true, true); + } else { + waitingHandler.setWaitingText(text); + } + } + } + + /** + * Joins a command line for display. + * + * @param command the command + * + * @return the display string + */ + private static String join(List command) { + + StringBuilder stringBuilder = new StringBuilder(); + + for (String part : command) { + + if (stringBuilder.length() > 0) { + stringBuilder.append(' '); + } + + stringBuilder.append(part); + } + + return stringBuilder.toString(); + } + + /** + * Returns true on Windows. + * + * @return true on Windows + */ + private static boolean isWindows() { + return System.getProperty("os.name").toLowerCase().contains("win"); + } + + /** + * Returns true on macOS. + * + * @return true on macOS + */ + private static boolean isMacOs() { + return System.getProperty("os.name").toLowerCase().contains("mac"); + } + + /** + * Returns true on Apple Silicon macOS. + * + * @return true on Apple Silicon macOS + */ + private static boolean isAppleSiliconMac() { + + String architecture = System.getProperty("os.arch").toLowerCase(); + + return isMacOs() && (architecture.contains("aarch64") || architecture.contains("arm64")); + } + + /** + * Returns true if running a command succeeds. + * + * @param command the command + * + * @return true if the command succeeds + */ + private static boolean commandSucceeds(String command) { + + try { + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + return process.waitFor() == 0; + } catch (Exception e) { + return false; + } + } +} diff --git a/src/main/java/com/compomics/util/experiment/identification/protein_sequences/SequenceFactory.java b/src/main/java/com/compomics/util/experiment/identification/protein_sequences/SequenceFactory.java new file mode 100644 index 0000000..58ec73f --- /dev/null +++ b/src/main/java/com/compomics/util/experiment/identification/protein_sequences/SequenceFactory.java @@ -0,0 +1,87 @@ +package com.compomics.util.experiment.identification.protein_sequences; + +import java.io.File; + +/** + * Minimal DeNovoGUI compatibility facade for the removed Utilities 4 sequence + * factory. + */ +public class SequenceFactory { + + /** + * The singleton instance. + */ + private static final SequenceFactory instance = new SequenceFactory(); + /** + * The selected FASTA file. + */ + private File currentFastaFile; + + /** + * Returns the singleton instance. + * + * @return the singleton instance + */ + public static SequenceFactory getInstance() { + return instance; + } + + /** + * Clears the selected FASTA file. + */ + public void clearFactory() { + currentFastaFile = null; + } + + /** + * Returns the currently selected FASTA file. + * + * @return the currently selected FASTA file + */ + public File getCurrentFastaFile() { + return currentFastaFile; + } + + /** + * Returns the number of loaded sequences. + * + * @return the number of loaded sequences + */ + public int getNSequences() { + return currentFastaFile == null ? 0 : 1; + } + + /** + * Returns the number of target sequences. + * + * @return the number of target sequences + */ + public int getNTargetSequences() { + return getNSequences(); + } + + /** + * Indicates whether decoys are reversed by default. + * + * @return true + */ + public boolean isDefaultReversed() { + return true; + } + + /** + * Legacy compatibility method. + * + * @param decoyInMemory ignored + */ + public void setDecoyInMemory(boolean decoyInMemory) { + } + + /** + * Legacy compatibility method. + * + * @param cacheSize ignored + */ + public void setnCache(int cacheSize) { + } +} diff --git a/src/test/java/com/compomics/denovogui/execution/jobs/InstaNovoJobTest.java b/src/test/java/com/compomics/denovogui/execution/jobs/InstaNovoJobTest.java new file mode 100644 index 0000000..70fe6e2 --- /dev/null +++ b/src/test/java/com/compomics/denovogui/execution/jobs/InstaNovoJobTest.java @@ -0,0 +1,124 @@ +package com.compomics.denovogui.execution.jobs; + +import com.compomics.denovogui.io.FileProcessor; +import com.compomics.util.exceptions.exception_handlers.CommandLineExceptionHandler; +import com.compomics.util.experiment.identification.Advocate; +import com.compomics.util.gui.waiting.waitinghandlers.WaitingHandlerCLIImpl; +import com.compomics.util.parameters.identification.search.SearchParameters; +import com.compomics.util.parameters.identification.tool_specific.InstaNovoParameters; +import java.io.File; +import java.util.List; +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +/** + * Tests for InstaNovo job setup. + * + * @author CompOmics + */ +public class InstaNovoJobTest { + + /** + * Temporary folder. + */ + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + /** + * Tests Unix virtual environment executable resolution. + */ + @Test + public void testUnixVirtualEnvironmentExecutableResolution() throws Exception { + + File instaNovoFolder = temporaryFolder.newFolder("InstaNovo"); + File executable = new File(instaNovoFolder, ".venv/bin/instanovo"); + Assert.assertTrue(executable.getParentFile().mkdirs()); + Assert.assertTrue(executable.createNewFile()); + + Assert.assertEquals(executable, InstaNovoJob.getExecutable(instaNovoFolder)); + } + + /** + * Tests Windows virtual environment executable resolution. + */ + @Test + public void testWindowsVirtualEnvironmentExecutableResolution() throws Exception { + + File instaNovoFolder = temporaryFolder.newFolder("InstaNovo"); + File executable = new File(instaNovoFolder, ".venv/Scripts/instanovo.exe"); + Assert.assertTrue(executable.getParentFile().mkdirs()); + Assert.assertTrue(executable.createNewFile()); + + Assert.assertEquals(executable, InstaNovoJob.getExecutable(instaNovoFolder)); + } + + /** + * Tests result file naming. + */ + @Test + public void testResultFileNaming() throws Exception { + + File outputFolder = temporaryFolder.newFolder("output"); + File spectrumFile = temporaryFolder.newFile("sample.mgf"); + + Assert.assertEquals(new File(outputFolder, "sample.instanovo.csv"), FileProcessor.getInstaNovoResultFile(outputFolder, spectrumFile)); + Assert.assertEquals(new File(outputFolder, "sample.instanovoplus.csv"), FileProcessor.getInstaNovoPlusResultFile(outputFolder, spectrumFile)); + Assert.assertEquals(new File(outputFolder, "sample.instanovo.refined.csv"), FileProcessor.getInstaNovoRefinedResultFile(outputFolder, spectrumFile)); + } + + /** + * Tests refined command construction. + */ + @Test + public void testRefinedCommandConstruction() throws Exception { + + File instaNovoFolder = temporaryFolder.newFolder("InstaNovo"); + File executable = new File(instaNovoFolder, ".venv/bin/instanovo"); + Assert.assertTrue(executable.getParentFile().mkdirs()); + Assert.assertTrue(executable.createNewFile()); + + File spectrumFile = temporaryFolder.newFile("sample.mgf"); + File outputFolder = temporaryFolder.newFolder("output"); + + InstaNovoParameters parameters = new InstaNovoParameters(); + parameters.setInstaNovoModel("instanovo-v1.2.0"); + parameters.setInstaNovoPlusModel("instanovoplus-v1.1.0"); + parameters.setNumberOfBeams(7); + parameters.setUseKnapsack(true); + parameters.setSaveAllPredictions(true); + parameters.setBatchSize(8); + parameters.setForceCpu(true); + + SearchParameters searchParameters = new SearchParameters(); + searchParameters.setIdentificationAlgorithmParameter(Advocate.instanovo.getIndex(), parameters); + + InstaNovoJob job = new InstaNovoJob( + instaNovoFolder, + spectrumFile, + outputFolder, + searchParameters, + InstaNovoJob.Mode.refined, + new WaitingHandlerCLIImpl(), + new CommandLineExceptionHandler() + ); + + List command = job.getCommand(); + + Assert.assertEquals(executable.getPath(), command.get(0)); + Assert.assertTrue(command.contains("predict")); + Assert.assertTrue(command.contains("--with-refinement")); + Assert.assertTrue(command.contains("--instanovo-model")); + Assert.assertTrue(command.contains("instanovo-v1.2.0")); + Assert.assertTrue(command.contains("--instanovo-plus-model")); + Assert.assertTrue(command.contains("instanovoplus-v1.1.0")); + Assert.assertTrue(command.contains("num_beams=7")); + Assert.assertTrue(command.contains("use_knapsack=true")); + Assert.assertTrue(command.contains("save_all_predictions=true")); + Assert.assertTrue(command.contains("batch_size=8")); + Assert.assertTrue(command.contains("force_cpu=true")); + Assert.assertTrue(command.contains("log_interval=1")); + Assert.assertTrue(command.contains(FileProcessor.getInstaNovoRefinedResultFile(outputFolder, spectrumFile).getAbsolutePath())); + } +}