file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
ShowHowToCiteCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/show/ShowHowToCiteCommand.java | /*
* ShowHowToCiteCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.show;
import jloda.swing.commands.ICommand;
import jloda.swing.util.Message;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* how to cite
* Daniel Huson, 6.2010
*/
public class ShowHowToCiteCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "show window=howToCite;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
Message.show(getViewer().getFrame(),
"Please cite:\n" +
"D.H. Huson et al (2016) MEGAN Community Edition - Interactive exploration and 2 analysis of large-scale microbiome sequencing data,\n" +
"PLoS Computational Biology 12(6): e1004957. doi:10.1371/journal. pcbi.1004957\n");
}
public void actionPerformed(ActionEvent event) {
executeImmediately(getSyntax());
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "How to Cite...";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Help16.gif");
}
public String getDescription() {
return "Show how to cite the program";
}
public boolean isCritical() {
return false;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,303 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowPropertiesCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/show/ShowPropertiesCommand.java | /*
* ShowPropertiesCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.show;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.viewer.PropertiesWindow;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ShowPropertiesCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "show window=properties;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
new PropertiesWindow(getViewer().getFrame(), getDoc());
}
public void actionPerformed(ActionEvent event) {
executeImmediately(getSyntax());
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Properties...";
}
public String getDescription() {
return "Show document properties";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Properties16.gif");
}
public boolean isCritical() {
return false;
}
}
| 1,924 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowInspectorCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/show/ShowInspectorCommand.java | /*
* ShowInspectorCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.show;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.core.Director;
import megan.inspector.InspectorWindow;
import megan.util.WindowUtilities;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ShowInspectorCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "show window=inspector;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
final Director dir = getDir();
InspectorWindow inspectorWindow = (InspectorWindow) dir.getViewerByClass(InspectorWindow.class);
if (inspectorWindow == null) {
inspectorWindow = (InspectorWindow) dir.addViewer(new InspectorWindow(dir));
}
WindowUtilities.toFront(inspectorWindow.getFrame());
}
public void actionPerformed(ActionEvent event) {
executeImmediately(getSyntax());
}
public boolean isApplicable() {
return getDoc().getMeganFile().hasDataConnector();
}
public String getName() {
return "Inspector Window...";
}
public String getDescription() {
return "Open inspector window";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Inspector16.gif");
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,372 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowSamplesViewerCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/show/ShowSamplesViewerCommand.java | /*
* ShowSamplesViewerCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.show;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.samplesviewer.SamplesViewer;
import megan.util.WindowUtilities;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class ShowSamplesViewerCommand extends megan.commands.CommandBase implements ICommand {
public String getSyntax() {
return "show window=samplesViewer;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
SamplesViewer samplesViewer = (SamplesViewer) getDir().getViewerByClass(SamplesViewer.class);
if (samplesViewer == null) {
samplesViewer = new SamplesViewer(getDir());
getDir().addViewer(samplesViewer);
}
WindowUtilities.toFront(samplesViewer.getFrame());
}
public void actionPerformed(ActionEvent event) {
SamplesViewer samplesViewer = (SamplesViewer) getDir().getViewerByClass(SamplesViewer.class);
if (samplesViewer == null)
execute(getSyntax());
else // already exists, just need to bring to the front
executeImmediately(getSyntax());
}
public boolean isApplicable() {
return getDir().getDocument().getNumberOfSamples() > 0;
}
public static final String NAME = "Samples Viewer...";
public String getName() {
return NAME;
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Table16.gif");
}
public String getDescription() {
return "Opens the Samples Viewer";
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_Y, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
}
| 2,734 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowCheckForUpdateCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/show/ShowCheckForUpdateCommand.java | /*
* ShowCheckForUpdateCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.show;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.director.IDirector;
import jloda.swing.director.ProjectManager;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.main.CheckForUpdate;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* show the message window
* Daniel Huson, 6.2010
*/
public class ShowCheckForUpdateCommand extends CommandBase implements ICommand {
private final static String NAME = "Check For Updates...";
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Check for updates";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Refresh16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
CheckForUpdate.apply();
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
execute(getSyntax());
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
for (IDirector dir : ProjectManager.getProjects()) {
if (dir.getDirty())
return false;
}
return true;
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "checkForUpdate;";
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 3,339 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CompareCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/show/CompareCommand.java | /*
* CompareCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.show;
import jloda.swing.commands.ICommand;
import jloda.swing.director.ProjectManager;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.RecursiveFileLister;
import jloda.swing.util.ResourceManager;
import jloda.util.CanceledException;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import jloda.util.progress.ProgressListener;
import megan.commands.CommandBase;
import megan.core.Director;
import megan.core.Document;
import megan.core.MeganFile;
import megan.dialogs.compare.CompareWindow;
import megan.dialogs.compare.Comparer;
import megan.main.MeganProperties;
import megan.util.MeganFileFilter;
import megan.util.MeganizedDAAFileFilter;
import megan.util.RMAFileFilter;
import megan.viewer.MainViewer;
import megan.viewer.gui.NodeDrawer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
public class CompareCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "compare mode={" + StringUtils.toString(Comparer.COMPARISON_MODE.values(), "|") + "}" +
" readAssignmentMode={" + StringUtils.toString(Document.ReadAssignmentMode.values(), "|") + "}" +
" [keep1={false|true}] [ignoreUnassigned={false|true}] [pid=<number> ...] [meganFile=<filename> ...];";
}
public void apply(NexusStreamParser np) throws Exception {
final Director dir = getDir();
final Document doc = dir.getDocument();
final ProgressListener progress = doc.getProgressListener();
if (!doc.neverOpenedReads)
throw new Exception("Internal error: document already used");
doc.neverOpenedReads = false;
np.matchIgnoreCase("compare");
final Comparer comparer = new Comparer();
if (np.peekMatchIgnoreCase("mode")) {
np.matchIgnoreCase("mode=");
comparer.setMode(np.getWordMatchesIgnoringCase(StringUtils.toString(Comparer.COMPARISON_MODE.values(), " ")));
}
Document.ReadAssignmentMode readAssignmentMode = Document.ReadAssignmentMode.readCount;
if (np.peekMatchIgnoreCase("readAssignmentMode")) {
np.matchIgnoreCase("readAssignmentMode=");
readAssignmentMode = Document.ReadAssignmentMode.valueOfIgnoreCase(np.getWordMatchesIgnoringCase(StringUtils.toString(Document.ReadAssignmentMode.values(), " ")));
}
if (np.peekMatchIgnoreCase("keep1")) {
np.matchIgnoreCase("keep1=");
comparer.setKeep1(np.getBoolean());
}
if (np.peekMatchIgnoreCase("ignoreUnassigned")) {
np.matchIgnoreCase("ignoreUnassigned=");
comparer.setIgnoreUnassigned(np.getBoolean());
}
final java.util.List<Director> toDelete = new LinkedList<>();
try {
if (np.peekMatchIgnoreCase("pid")) {
np.matchIgnoreCase("pid=");
do {
int pid = np.getInt();
Director newDir = (Director) ProjectManager.getProject(pid);
if (newDir == null)
throw new IOException("No such project id: " + pid);
if (newDir.getDocument().getNumberOfReads() == 0)
throw new IOException("No reads found in file: '" + newDir.getDocument().getMeganFile().getFileName() + "' (id=" + pid + ")");
comparer.addDirector(newDir);
if (np.peekMatchIgnoreCase(",")) // for backward compatibility
np.matchAnyTokenIgnoreCase(",");
} while (!np.peekMatchAnyTokenIgnoreCase("; meganFile"));
}
if (np.peekMatchIgnoreCase("meganFile")) {
np.matchIgnoreCase("meganFile=");
final ArrayList<String> files = new ArrayList<>();
do {
String fileName = np.getWordRespectCase();
if (fileName.contains("::")) {
files.add(fileName);
} else {
files.addAll(RecursiveFileLister.apply(fileName, new MeganFileFilter(), new RMAFileFilter(), MeganizedDAAFileFilter.getInstance()));
}
if (np.peekMatchIgnoreCase(","))
np.matchAnyTokenIgnoreCase(","); // for backward compatibility
} while (!np.peekMatchIgnoreCase(";"));
np.matchIgnoreCase(";");
progress.setProgress(0);
progress.setMaximum(files.size());
for (String fileName : files) {
progress.setTasks("Comparison", "Loading files");
final Director newDir = Director.newProject(false, true);
newDir.executeImmediately("open file='" + fileName + "' readOnly=true;update;", newDir.getMainViewer().getCommandManager());
if (newDir.getDocument().getNumberOfReads() == 0) {
throw new IOException("No reads found in file: '" + fileName + "'");
}
comparer.addDirector(newDir);
toDelete.add(newDir);
progress.incrementProgress();
}
}
doc.getMeganFile().setFileName(ProjectManager.getUniqueName("Comparison.megan"));
doc.clearReads();
doc.setReadAssignmentMode(readAssignmentMode);
comparer.computeComparison(doc.getSampleAttributeTable(), doc.getDataTable(), progress);
doc.setNumberReads(doc.getDataTable().getTotalReads());
doc.processReadHits();
doc.setTopPercent(100);
doc.setMinScore(0);
doc.setMinSupportPercent(0);
doc.setMinSupport(1);
doc.setMaxExpected(10000);
doc.getActiveViewers().addAll(doc.getDataTable().getClassification2Class2Counts().keySet());
doc.setDirty(true);
doc.getMeganFile().setFileType(MeganFile.Type.MEGAN_SUMMARY_FILE);
final MainViewer mainViewer = dir.getMainViewer();
if (mainViewer != null) {
if (mainViewer.isVisible()) {
mainViewer.getNodeDrawer().setStyle(ProgramProperties.get(MeganProperties.COMPARISON_STYLE, ""), NodeDrawer.Style.BarChart);
mainViewer.collapseToDefault();
mainViewer.setDoReInduce(true);
mainViewer.setDoReset(true);
mainViewer.setVisible(true);
doc.loadColorTableFromDataTable();
}
}
} finally {
for (Director aDir : toDelete) {
aDir.close();
}
}
}
/**
* display the dialog and then execute the command entered, if any
*
*/
public void actionPerformed(ActionEvent event) {
final Director newDir = Director.newProject();
boolean ok = false;
final CompareWindow compareWindow = new CompareWindow(newDir.getMainViewer().getFrame(), newDir, null);
if (!compareWindow.isCanceled()) {
final String command = compareWindow.getCommand();
if (command != null) {
newDir.execute(command, newDir.getCommandManager());
ok = true;
}
}
if (!ok) {
try {
newDir.close();
} catch (CanceledException e) {
e.printStackTrace();
}
ProjectManager.removeProject(newDir);
}
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Compare...";
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_M, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
public String getDescription() {
return "Open compare dialog to produce a comparison of multiple datasets";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/New16.gif");
}
public boolean isCritical() {
return true;
}
}
| 9,041 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowTimeSeriesViewerCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/show/ShowTimeSeriesViewerCommand.java | /*
* ShowTimeSeriesViewerCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.show;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.Basic;
import jloda.util.parse.NexusStreamParser;
import megan.core.Director;
import megan.timeseriesviewer.TimeSeriesViewer;
import megan.util.WindowUtilities;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ShowTimeSeriesViewerCommand extends megan.commands.CommandBase implements ICommand {
public String getSyntax() {
return "show window=timeSeriesViewer;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
TimeSeriesViewer viewer = (TimeSeriesViewer) getDir().getViewerByClass(TimeSeriesViewer.class);
if (viewer == null) {
try {
viewer = new TimeSeriesViewer(getViewer().getFrame(), getDir());
getDir().addViewer(viewer);
WindowUtilities.toFront(viewer.getFrame());
} catch (Exception e) {
Basic.caught(e);
}
} else {
viewer.updateView(Director.ALL);
WindowUtilities.toFront(viewer.getFrame());
}
}
public void actionPerformed(ActionEvent event) {
execute(getSyntax());
}
public boolean isApplicable() {
return getDir().getDocument().getNumberOfSamples() > 0 && getViewer() instanceof ClassificationViewer;
}
public String getName() {
return "Time Series Viewer...";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("TimeSeries16.gif");
}
public String getDescription() {
return "Opens the Time Series Viewer";
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,704 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowLRInspectorCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/show/ShowLRInspectorCommand.java | /*
* ShowLRInspectorCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.show;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.Pair;
import jloda.util.parse.NexusStreamParser;
import megan.core.Director;
import megan.dialogs.lrinspector.LRInspectorViewer;
import megan.util.WindowUtilities;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* show long read inspector command
* Daniel Huson, 2.2107
*/
public class ShowLRInspectorCommand extends CommandBase implements ICommand {
private static final Map<Pair<String, Integer>, LRInspectorViewer> classification2viewer = new HashMap<>();
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("show window=longReadInspector");
final boolean alwaysNew;
if (np.peekMatchIgnoreCase("alwaysNew")) {
np.matchIgnoreCase("alwaysNew=");
alwaysNew = np.getBoolean();
} else
alwaysNew = false;
np.matchIgnoreCase(";");
if (getViewer() instanceof ClassificationViewer) {
final Director dir = (Director) getDir();
final ClassificationViewer parentViewer = (ClassificationViewer) getViewer();
final String classification = parentViewer.getClassName();
final Collection<Integer> classIds = parentViewer.getSelectedNodeIds();
if (classIds.size() > 0) {
if (classIds.size() >= 5 && JOptionPane.showConfirmDialog(parentViewer.getFrame(), "Do you really want to open " + classIds.size() +
" windows?", "Confirmation - MEGAN", JOptionPane.YES_NO_CANCEL_OPTION) != JOptionPane.YES_OPTION)
return;
for (Integer classId : classIds) {
final Pair<String, Integer> pair = new Pair<>(dir.getID() + "." + classification, classId);
LRInspectorViewer viewer = classification2viewer.get(pair);
if (viewer != null) {
if (dir.getViewers().contains(viewer)) {
WindowUtilities.toFront(viewer);
} else {
classification2viewer.remove(pair);
viewer = null;
}
}
if (alwaysNew || viewer == null) {
viewer = new LRInspectorViewer(parentViewer.getFrame(), parentViewer, classId);
viewer.setRunOnDestroy(() -> classification2viewer.keySet().remove(pair));
classification2viewer.put(pair, viewer);
dir.addViewer(viewer);
}
}
}
}
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "show window=longReadInspector [alwaysNew={false|true}];";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
executeImmediately("show window=longReadInspector" + ((ev.getModifiers() & ActionEvent.SHIFT_MASK) == 0 ? ";" : " alwaysNew=false;"));
}
private static final String NAME = "Inspect Long Reads...";
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Show visual long read inspector";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("Inspector16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_I, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | java.awt.event.InputEvent.SHIFT_DOWN_MASK);
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return getViewer() instanceof ClassificationViewer && ((ClassificationViewer) getViewer()).getDocument().getMeganFile().hasDataConnector()
&& ((ClassificationViewer) getViewer()).getSelectedNodes().size() > 0;
}
}
| 5,758 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowLegendCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/show/ShowLegendCommand.java | /*
* ShowLegendCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.show;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.director.IDirector;
import jloda.swing.director.IViewerWithLegend;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* show legend
* Daniel Huson, 3.2013
*/
public class ShowLegendCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
return getViewer() instanceof IViewerWithLegend &&
(((IViewerWithLegend) getViewer()).getShowLegend().equals("horizontal")
|| ((IViewerWithLegend) getViewer()).getShowLegend().equals("vertical"));
}
public String getSyntax() {
return "show legend={horizontal|vertical|none};";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("show legend=");
String which = np.getWordMatchesIgnoringCase("horizontal vertical none");
np.matchIgnoreCase(";");
if (getViewer() instanceof IViewerWithLegend) {
IViewerWithLegend viewer = (IViewerWithLegend) getViewer();
viewer.setShowLegend(which);
if (getViewer() != null) {
getViewer().updateView(IDirector.ENABLE_STATE);
}
}
}
public void actionPerformed(ActionEvent event) {
if (getViewer() instanceof IViewerWithLegend) {
String legend = ((IViewerWithLegend) getViewer()).getShowLegend();
switch (legend) {
case "none" -> executeImmediately("show legend=horizontal;");
case "horizontal" -> executeImmediately("show legend=vertical;");
case "vertical" -> executeImmediately("show legend=none;");
}
}
}
public boolean isApplicable() {
return getDir().getDocument().getNumberOfSamples() > 1 && getViewer() instanceof IViewerWithLegend;
}
public String getName() {
return "Show Legend";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Legend16.gif");
}
public String getDescription() {
return "Show horizontal or vertical legend, or hide";
}
public boolean isCritical() {
return false;
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_J, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | java.awt.event.InputEvent.SHIFT_DOWN_MASK);
}
}
| 3,414 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowReanalyzeDialogCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/show/ShowReanalyzeDialogCommand.java | /*
* ShowReanalyzeDialogCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.show;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.CommandManager;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.core.Director;
import megan.dialogs.reanalyze.ReanalyzeDialog;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* meganize DAA files command
* Daniel Huson, 3.2016
*/
public class ShowReanalyzeDialogCommand extends CommandBase implements ICommand {
public ShowReanalyzeDialogCommand() {
}
public ShowReanalyzeDialogCommand(CommandManager commandManager) {
super(commandManager);
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "show window=Reanalyze;";
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
final ReanalyzeDialog dialog = new ReanalyzeDialog(getViewer().getFrame(), (Director) getDir());
final String command = dialog.showAndGetCommand();
if (command != null)
execute(command);
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
executeImmediately(getSyntax());
}
public static final String NAME = "Reanalyze Files...";
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Show the 'renalyze files' dialog";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Refresh16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return ((Director) getDir()).getDocument().neverOpenedReads;
}
}
| 3,494 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowExtractReadsDialogCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/show/ShowExtractReadsDialogCommand.java | /*
* ShowExtractReadsDialogCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.show;
import jloda.swing.commands.ICommand;
import jloda.swing.director.IDirectableViewer;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.core.ClassificationType;
import megan.core.Director;
import megan.dialogs.extractor.ExtractReadsViewer;
import megan.util.WindowUtilities;
import megan.viewer.ClassificationViewer;
import megan.viewer.MainViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.IOException;
public class ShowExtractReadsDialogCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "show window=ExtractReads;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
final Director dir = getDir();
ExtractReadsViewer extractReadsViewer = (ExtractReadsViewer) dir.getViewerByClass(ExtractReadsViewer.class);
final IDirectableViewer viewer = getViewer();
if (extractReadsViewer == null)
extractReadsViewer = (ExtractReadsViewer) dir.addViewer(new ExtractReadsViewer(viewer.getFrame(), dir));
if (viewer instanceof MainViewer)
extractReadsViewer.setMode(ClassificationType.Taxonomy.toString());
else if (viewer instanceof ClassificationViewer)
extractReadsViewer.setMode(getViewer().getClassName());
else {
throw new IOException("Invalid viewer");
}
WindowUtilities.toFront(extractReadsViewer);
}
public void actionPerformed(ActionEvent event) {
execute(getSyntax());
}
public boolean isApplicable() {
return getViewer() != null && getViewer() instanceof ClassificationViewer
&& getDir().getDocument().getMeganFile().hasDataConnector();
}
private final static String NAME = "Extract Reads...";
public String getName() {
return NAME;
}
public String getDescription() {
return "Extract reads for the selected nodes";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Extractor16.gif");
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 3,143 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowMainViewerCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/show/ShowMainViewerCommand.java | /*
* ShowMainViewerCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.show;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.util.WindowUtilities;
import megan.viewer.MainViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ShowMainViewerCommand extends megan.commands.CommandBase implements ICommand {
public String getSyntax() {
return "show window=mainViewer;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
if (ProgramProperties.isUseGUI()) {
final MainViewer viewer = (MainViewer) getDir().getViewerByClass(MainViewer.class);
WindowUtilities.toFront(viewer.getFrame());
}
}
public void actionPerformed(ActionEvent event) {
executeImmediately(getSyntax());
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Main Viewer...";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("TaxonomyViewer16.gif");
}
public String getDescription() {
return "Brings the main viewer to the front";
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,202 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowMatchesHistogramCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/show/ShowMatchesHistogramCommand.java | /*
* ShowMatchesHistogramCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.show;
import jloda.swing.commands.ICommand;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.core.ClassificationType;
import megan.core.Document;
import megan.data.IConnector;
import megan.data.IMatchBlock;
import megan.data.IReadBlock;
import megan.data.IReadBlockIterator;
import megan.viewer.MainViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* shows the histogram of matches for a given node
* Daniel Huson, 11.2010
*/
public class ShowMatchesHistogramCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("show histogram taxonId=");
int taxId = np.getInt();
np.matchIgnoreCase(";");
Document doc = getDir().getDocument();
int[] values = computeHistogram(taxId, doc);
System.err.println("Histogram for taxonId=" + taxId + ":");
for (int value : values) {
System.err.println(value);
}
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "show histogram taxonId=<num>;";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
int taxId = ((MainViewer) getViewer()).getSelectedNodeIds().iterator().next();
String command = "show histogram taxonId=" + taxId + ";";
execute(command);
}
/**
* compute the histogram associated with a given class
*
* @return histogram of counts of matches to different sequences
*/
private int[] computeHistogram(int classId, Document doc) throws IOException {
IConnector connector = doc.getConnector();
Map<String, Integer> matched2count = new HashMap<>();
try (IReadBlockIterator it = connector.getReadsIterator(ClassificationType.Taxonomy.toString(), classId, doc.getMinScore(), doc.getMaxExpected(), false, true)) {
while (it.hasNext()) {
final IReadBlock readBlock = it.next();
for (int i = 0; i < readBlock.getNumberOfAvailableMatchBlocks(); i++) {
IMatchBlock matchBlock = readBlock.getMatchBlock(i);
if (matchBlock.getBitScore() >= doc.getMinScore() && matchBlock.getExpected() <= doc.getMaxExpected() &&
(matchBlock.getPercentIdentity() == 0 || matchBlock.getPercentIdentity() >= doc.getMinPercentIdentity())) {
String firstLine = matchBlock.getText().split("\n")[0];
matched2count.merge(firstLine, 1, Integer::sum);
}
}
}
}
int[] values = new int[matched2count.size()];
int i = 0;
for (Integer count : matched2count.values()) {
values[i++] = count;
}
Arrays.sort(values);
return values;
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Show Matches Histogram";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Shows the distribution of matches for a given taxon";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return ((MainViewer) getViewer()).getSelectedNodeIds().size() == 1;
}
}
| 5,199 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowChartCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/show/ShowChartCommand.java | /*
* ShowChartCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.show;
import jloda.swing.commands.ICommand;
import jloda.swing.util.PopupMenu;
import jloda.swing.util.ResourceManager;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.chart.AttributesChart;
import megan.chart.FViewerChart;
import megan.chart.MetadataChart;
import megan.chart.TaxaChart;
import megan.chart.data.ChartCommandHelper;
import megan.chart.drawers.BarChartDrawer;
import megan.chart.drawers.DrawerManager;
import megan.chart.gui.ChartViewer;
import megan.classification.Classification;
import megan.classification.ClassificationManager;
import megan.commands.CommandBase;
import megan.core.Director;
import megan.util.WindowUtilities;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.IOException;
/**
* show chart command
* Daniel Huson, 6.2012
*/
public class ShowChartCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "show chart drawer={" + StringUtils.toString(DrawerManager.getAllSupportedChartDrawers(), ",") + "} data={" + StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), "|") + "|attributes|metadata};";
}
public void apply(NexusStreamParser np) throws Exception {
final Director dir = getDir();
np.matchIgnoreCase("show chart drawer=");
final String drawerType = np.getWordMatchesRespectingCase(StringUtils.toString(DrawerManager.getAllSupportedChartDrawers(), " "));
np.matchIgnoreCase("data=");
final String data = np.getWordMatchesRespectingCase(StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), " ") + " attributes metadata");
np.matchIgnoreCase(";");
ChartViewer chartViewer = null;
if (data.equalsIgnoreCase(Classification.Taxonomy) || data.equalsIgnoreCase("taxa")) // taxa for legacy
{
chartViewer = (TaxaChart) dir.getViewerByClass(TaxaChart.class);
if (chartViewer == null) {
chartViewer = new TaxaChart(dir);
getDir().addViewer(chartViewer);
if (drawerType.equals(BarChartDrawer.NAME) && getDir().getDocument().getNumberOfSamples() > 1)
chartViewer.setTranspose(true);
chartViewer.chooseDrawer(drawerType);
} else {
chartViewer.sync();
chartViewer.chooseDrawer(drawerType);
chartViewer.updateView(Director.ALL);
}
} else if (data.equalsIgnoreCase("attributes")) {
chartViewer = (AttributesChart) dir.getViewerByClass(AttributesChart.class);
if (chartViewer == null) {
chartViewer = new AttributesChart(dir);
getDir().addViewer(chartViewer);
chartViewer.chooseDrawer(drawerType);
} else {
chartViewer.sync();
chartViewer.chooseDrawer(drawerType);
chartViewer.updateView(Director.ALL);
}
} else if (data.equalsIgnoreCase("metadata")) {
chartViewer = (MetadataChart) dir.getViewerByClass(AttributesChart.class);
if (chartViewer == null) {
chartViewer = new MetadataChart(dir, dir.getMainViewer());
getDir().addViewer(chartViewer);
chartViewer.chooseDrawer(drawerType);
} else {
chartViewer.sync();
chartViewer.chooseDrawer(drawerType);
chartViewer.updateView(Director.ALL);
}
} else if (ClassificationManager.getAllSupportedClassifications().contains(data.toUpperCase())) {
chartViewer = (FViewerChart) dir.getViewerByClassName(FViewerChart.getClassName(data));
if (chartViewer == null) {
ClassificationViewer classificationViewer = (ClassificationViewer) dir.getViewerByClassName(ClassificationViewer.getClassName(data));
if (classificationViewer == null)
throw new IOException(data + " viewer must be open for " + data + " chart to operate");
chartViewer = new FViewerChart(dir, classificationViewer);
getDir().addViewer(chartViewer);
if (getDir().getDocument().getNumberOfSamples() == 1)
chartViewer.setTranspose(true);
chartViewer.chooseDrawer(drawerType);
} else {
chartViewer.sync();
chartViewer.chooseDrawer(drawerType);
chartViewer.updateView(Director.ALL);
}
}
WindowUtilities.toFront(chartViewer);
}
public boolean isCritical() {
return true;
}
public void actionPerformed(ActionEvent event) {
final JPopupMenu popupMenu = new PopupMenu(this, ChartCommandHelper.getOpenChartMenuString(), getCommandManager());
final Point location = MouseInfo.getPointerInfo().getLocation();
SwingUtilities.convertPointFromScreen(location, getViewer().getFrame());
popupMenu.show(getViewer().getFrame(), location.x, location.y);
}
public boolean isApplicable() {
return getDir().getDocument().getNumberOfReads() > 0 && getViewer() instanceof ClassificationViewer;
}
public String getName() {
return "Chart...";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("BarChart16.gif");
}
public String getDescription() {
return "Show chart";
}
}
| 6,390 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowRemoteBrowserCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/show/ShowRemoteBrowserCommand.java | /*
* ShowRemoteBrowserCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.show;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.ms.clientdialog.RemoteServiceBrowser;
import megan.ms.clientdialog.service.RemoteServiceManager;
import megan.util.WindowUtilities;
import megan.viewer.MainViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
public class ShowRemoteBrowserCommand extends CommandBase implements ICommand {
private static RemoteServiceBrowser remoteServiceBrowser;
public String getSyntax() {
return "show window=RemoteBrowser;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
if (remoteServiceBrowser == null) {
RemoteServiceManager.ensureCredentialsHaveBeenLoadedFromProperties();
RemoteServiceManager.ensureDefaultService();
remoteServiceBrowser = new RemoteServiceBrowser(MainViewer.getLastActiveFrame());
}
WindowUtilities.toFront(remoteServiceBrowser.getFrame());
}
public void actionPerformed(ActionEvent event) {
executeImmediately(getSyntax());
}
public boolean isApplicable() {
return true;
}
private final static String NAME = "Open From Server...";
public String getName() {
return NAME;
}
public String getDescription() {
return "Open browser for remote files";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Open16.gif");
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_O, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | InputEvent.SHIFT_DOWN_MASK);
}
}
| 2,750 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowReadLengthDistributionCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/show/ShowReadLengthDistributionCommand.java | /*
* ShowReadLengthDistributionCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.show;
import jloda.swing.commands.ICommand;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.dialogs.reads.ReadLengthDistribution;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ShowReadLengthDistributionCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "show window=readLengthDistribution;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
ClassificationViewer viewer = (ClassificationViewer) getViewer();
if (viewer.getSelectedNodes().size() > 0) {
final int classId = viewer.getSelectedNodeIds().iterator().next();
ReadLengthDistribution readLengthDistribution = new ReadLengthDistribution(viewer, classId);
readLengthDistribution.show();
}
}
public void actionPerformed(ActionEvent event) {
execute(getSyntax());
}
public boolean isApplicable() {
return getViewer() != null && getViewer() instanceof ClassificationViewer
&& ((ClassificationViewer) getViewer()).getSelectedNodes().size() == 1;
}
private final static String NAME = "Show Read Length Distribution...";
public String getName() {
return NAME;
}
public String getDescription() {
return "Show read length distribution";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,512 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowMessageWindowCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/show/ShowMessageWindowCommand.java | /*
* ShowMessageWindowCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.show;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.core.Director;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* show the message window
* Daniel Huson, 6.2010
*/
public class ShowMessageWindowCommand extends CommandBase implements ICommand {
private final static String NAME = "Message Window...";
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Open the message window";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/History16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
Director.showMessageWindow();
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
executeImmediately(getSyntax());
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return false;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "show window=message;";
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 3,134 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowClusterWindowCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/show/ShowClusterWindowCommand.java | /*
* ShowClusterWindowCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.show;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.clusteranalysis.TaxonomyClusterViewer;
import megan.commands.CommandBase;
import megan.core.Director;
import megan.viewer.ClassificationViewer;
import megan.viewer.MainViewer;
import megan.viewer.ViewerBase;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ShowClusterWindowCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "show window=clusterViewer;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
final Director dir = getDir();
if (getViewer() instanceof MainViewer) {
ClusterViewer viewer = (ClusterViewer) dir.getViewerByClass(TaxonomyClusterViewer.class);
if (viewer == null) {
viewer = new TaxonomyClusterViewer((MainViewer) getViewer());
if (ClusterViewer.clusterViewerAddOn != null)
ClusterViewer.clusterViewerAddOn.accept(viewer);
dir.addViewer(viewer);
}
viewer.getFrame().toFront();
} else if (getViewer() instanceof ClassificationViewer) {
final String name = getViewer().getClassName().toUpperCase() + "ClusterViewer";
ClusterViewer viewer = (ClusterViewer) dir.getViewerByClassName(name);
if (viewer == null) {
viewer = new ClusterViewer(dir, (ClassificationViewer) getViewer(), getViewer().getClassName());
if (ClusterViewer.clusterViewerAddOn != null)
ClusterViewer.clusterViewerAddOn.accept(viewer);
dir.addViewer(viewer);
}
viewer.toFront();
}
}
public void actionPerformed(ActionEvent event) {
if (getViewer() instanceof ViewerBase && ((ViewerBase) getViewer()).getSelectedNodes().size() == 0)
executeImmediately("select nodes=leaves;");
executeImmediately(getSyntax());
}
public boolean isApplicable() {
return getDir().getDocument().getNumberOfSamples() >= 4 && getViewer() instanceof ClassificationViewer;
}
public String getName() {
return "Cluster Analysis...";
}
public String getDescription() {
return "Open a cluster analysis window";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Network16.gif");
}
public boolean isCritical() {
return true;
}
}
| 3,461 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowFormatterCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/show/ShowFormatterCommand.java | /*
* ShowFormatterCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.show;
import jloda.swing.commands.ICommand;
import jloda.swing.director.IDirectableViewer;
import jloda.swing.format.Formatter;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.commands.CommandBase;
import megan.util.FormatterUtils;
import megan.util.WindowUtilities;
import megan.viewer.ViewerBase;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class ShowFormatterCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "show window=formatter;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
Formatter formatter;
IDirectableViewer viewer = getViewer();
if (!(viewer instanceof ClusterViewer))
formatter = FormatterUtils.getFormatter((ViewerBase) getViewer(), getDir());
else
formatter = FormatterUtils.getFormatter(((ClusterViewer) viewer).getGraphView(), getDir());
WindowUtilities.toFront(formatter.getFrame());
}
public void actionPerformed(ActionEvent event) {
executeImmediately(getSyntax());
}
public boolean isApplicable() {
return getViewer() != null && (getViewer() instanceof ViewerBase || getViewer() instanceof ClusterViewer);
}
public String getName() {
return "Format...";
}
public String getDescription() {
return "Format nodes and edges";
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_J, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Preferences16.gif");
}
public boolean isCritical() {
return true;
}
}
| 2,735 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowMeganizeDialogCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/show/ShowMeganizeDialogCommand.java | /*
* ShowMeganizeDialogCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.show;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.CommandManager;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.core.Director;
import megan.dialogs.meganize.MeganizeDAADialog;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
/**
* meganize DAA files command
* Daniel Huson, 3.2016
*/
public class ShowMeganizeDialogCommand extends CommandBase implements ICommand {
public ShowMeganizeDialogCommand() {
}
public ShowMeganizeDialogCommand(CommandManager commandManager) {
super(commandManager);
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "show window=MeganizeDAA;";
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
final MeganizeDAADialog dialog = new MeganizeDAADialog(getViewer().getFrame(), (Director) getDir());
final String command = dialog.showAndGetCommand();
if (command != null)
execute(command);
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
executeImmediately(getSyntax());
}
public static final String NAME = "Meganize DAA File...";
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Show the 'meganize DAA file' dialog";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Import16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_D, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | InputEvent.SHIFT_DOWN_MASK);
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
}
| 3,656 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowChartAttributesCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/show/ShowChartAttributesCommand.java | /*
* ShowChartAttributesCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.show;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.core.Director;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ShowChartAttributesCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void actionPerformed(ActionEvent event) {
execute("show chart drawer=BarChart data=attributes;");
}
public boolean isApplicable() {
return ((Director) getDir()).getDocument().getNumberOfReads() > 0 && getViewer() instanceof ClassificationViewer;
}
public String getName() {
return "Chart Microbial Attributes...";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("AttributesChart16.gif");
}
public String getDescription() {
return "Chart microbial attributes";
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
}
| 2,377 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowGroupsViewerCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/show/ShowGroupsViewerCommand.java | /*
* ShowGroupsViewerCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.show;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.Basic;
import jloda.util.parse.NexusStreamParser;
import megan.core.Director;
import megan.groups.GroupsViewer;
import megan.util.WindowUtilities;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ShowGroupsViewerCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "show window=groups;";
}
public void actionPerformed(ActionEvent event) {
execute(getSyntax());
}
public boolean isApplicable() {
return ((Director) getDir()).getDocument().getNumberOfReads() > 0 && getViewer() instanceof ClassificationViewer;
}
public String getName() {
return "Groups Viewer...";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("JoinNodes16.gif");
}
public String getDescription() {
return "Show groups viewer";
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
GroupsViewer groupsViewer = (GroupsViewer) getDir().getViewerByClass(GroupsViewer.class);
if (groupsViewer == null) {
try {
groupsViewer = new GroupsViewer((Director) getDir(), getViewer().getFrame());
getDir().addViewer(groupsViewer);
WindowUtilities.toFront(groupsViewer.getFrame());
} catch (Exception e) {
Basic.caught(e);
}
} else {
groupsViewer.updateView(Director.ENABLE_STATE);
WindowUtilities.toFront(groupsViewer.getFrame());
}
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
}
| 3,075 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowComparisonPlotCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/show/ShowComparisonPlotCommand.java | /*
* ShowComparisonPlotCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.show;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.chart.ComparisonPlot;
import megan.chart.gui.ChartViewer;
import megan.classification.Classification;
import megan.classification.ClassificationManager;
import megan.commands.CommandBase;
import megan.core.Director;
import megan.util.WindowUtilities;
import megan.viewer.ClassificationViewer;
import megan.viewer.MainViewer;
import megan.viewer.ViewerBase;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.IOException;
public class ShowComparisonPlotCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "show comparisonPlot [data={" + StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), "|") + "]};";
}
public void apply(NexusStreamParser np) throws Exception {
Director dir = getDir();
ChartViewer chartViewer;
np.matchIgnoreCase("show comparisonPlot");
String data = "taxonomy";
if (np.peekMatchIgnoreCase("data")) {
np.matchIgnoreCase("data=");
data = np.getWordMatchesIgnoringCase(StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), " "));
}
np.matchIgnoreCase(";");
chartViewer = (ComparisonPlot) dir.getViewerByClassName(ComparisonPlot.getClassName(data));
if (chartViewer == null) {
ClassificationViewer classificationViewer = (ClassificationViewer) dir.getViewerByClassName(ClassificationViewer.getClassName(data));
if (classificationViewer == null)
throw new IOException("Viewer must be open for chart to operate");
chartViewer = new ComparisonPlot(dir, classificationViewer);
getDir().addViewer(chartViewer);
} else {
chartViewer.sync();
}
WindowUtilities.toFront(chartViewer);
}
public void actionPerformed(ActionEvent event) {
if (getViewer() instanceof ViewerBase && ((ViewerBase) getViewer()).getSelectedNodes().size() == 0)
executeImmediately("select nodes=leaves;");
if (getViewer() instanceof MainViewer) {
execute("show comparisonPlot data=" + Classification.Taxonomy + ";");
} else if (getViewer() instanceof ClassificationViewer) {
execute("show comparisonPlot data=" + getViewer().getClassName() + ";");
}
}
public boolean isApplicable() {
return getDir().getDocument().getNumberOfSamples() > 1 && getViewer() instanceof ClassificationViewer;
}
public String getName() {
return "Comparison Plot...";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Plot2D16.gif");
}
public String getDescription() {
return "Plot pairwise comparison of assignments to classes";
}
public boolean isCritical() {
return true;
}
}
| 3,852 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ColorByPositionCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/color/ColorByPositionCommand.java | /*
* ColorByPositionCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.color;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.core.Director;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ColorByPositionCommand extends CommandBase implements ICheckBoxCommand {
@Override
public boolean isSelected() {
return ((Director) getDir()).getDocument().getChartColorManager().isColorByPosition();
}
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
execute("set colorBy=position;");
}
public boolean isApplicable() {
return true;
}
public static final String NAME = "Color Classes By Position";
public String getName() {
return NAME;
}
public String getDescription() {
return "Color classes by their position in the chart";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,117 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetColorTableCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/color/SetColorTableCommand.java | /*
* SetColorTableCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.color;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.director.IUsesHeatMapColors;
import jloda.swing.util.ColorTableManager;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.chart.commands.ColorByRankCommand;
import megan.core.Director;
import megan.core.Document;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
/**
* sets the color table
* Daniel Huson, 1.2016
*/
public class SetColorTableCommand extends CommandBase implements ICommand {
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "set colorTable={name} [heatMap={false|true}]";
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Colors...";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Set colors";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("ColorTable16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set colorTable=");
String name = np.getWordMatchesRespectingCase(ColorTableManager.getNames());
boolean isHeatMap;
if (np.peekMatchIgnoreCase("heatMap")) {
np.matchIgnoreCase("heatMap=");
isHeatMap = np.getBoolean();
} else
isHeatMap = false;
np.matchIgnoreCase(";");
final Document doc = ((Director) getDir()).getDocument();
if (isHeatMap) {
doc.getChartColorManager().setHeatMapTable(name);
ColorTableManager.setDefaultColorTableHeatMap(name);
} else {
doc.getChartColorManager().setColorTable(name);
ColorTableManager.setDefaultColorTable(name);
}
ColorByLabelCommand.updateColors(doc);
doc.setDirty(true);
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
final String[] choices = ColorTableManager.getNamesOrdered();
final boolean isHeatMap = (getViewer() instanceof IUsesHeatMapColors) && ((IUsesHeatMapColors) getViewer()).useHeatMapColors();
final Document doc = ((Director) getDir()).getDocument();
final String current = isHeatMap ? doc.getChartColorManager().getHeatMapTable().getName() : doc.getChartColorManager().getColorTable().getName();
final JPopupMenu popMenu = new JPopupMenu();
for (final String name : choices) {
JCheckBoxMenuItem checkBoxMenuItem = new JCheckBoxMenuItem();
checkBoxMenuItem.setAction(new AbstractAction(name) {
public void actionPerformed(ActionEvent e) {
if (doc.getChartColorManager().hasChangedColors()) {
switch (JOptionPane.showConfirmDialog(getViewer().getFrame(), "Clear all individually set colors?", "Question", JOptionPane.YES_NO_CANCEL_OPTION)) {
case JOptionPane.YES_OPTION:
doc.getChartColorManager().clearChangedColors();
break;
case JOptionPane.NO_OPTION:
break;
default:
return; // canceled
}
}
execute("set colorTable='" + name + "'" + (isHeatMap ? " heatMap=true;" : ";"));
}
});
checkBoxMenuItem.setSelected(name.equals(current));
checkBoxMenuItem.setIcon(ColorTableManager.getColorTable(name).makeIcon());
popMenu.add(checkBoxMenuItem);
}
popMenu.addSeparator();
{
final JMenuItem item = getViewer().getCommandManager().getJMenuItem(ColorByLabelCommand.NAME);
if (item != null) {
item.setEnabled(!isHeatMap);
popMenu.add(item);
}
}
{
final JMenuItem item = getViewer().getCommandManager().getJMenuItem(ColorByPositionCommand.NAME);
if (item != null) {
item.setEnabled(!isHeatMap);
popMenu.add(item);
}
}
{
final JMenuItem item = getViewer().getCommandManager().getJMenuItem(ColorSamplesByAttributeCommand.ALT_NAME);
if (item != null) {
popMenu.addSeparator();
item.setEnabled(!isHeatMap);
popMenu.add(item);
}
}
{
final JMenuItem item = getViewer().getCommandManager().getJMenuItem(ColorByRankCommand.NAME);
if (item != null) {
popMenu.addSeparator();
item.setEnabled(!isHeatMap);
popMenu.add(item);
}
}
popMenu.addSeparator();
{
final JMenuItem item = getViewer().getCommandManager().getJMenuItem(UseProgramColorsCommand.NAME);
if (item != null) {
popMenu.add(item);
}
}
final Point location = MouseInfo.getPointerInfo().getLocation();
SwingUtilities.convertPointFromScreen(location, getViewer().getFrame());
popMenu.show(getViewer().getFrame(), location.x, location.y);
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
}
| 7,141 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ClearSetColorsCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/color/ClearSetColorsCommand.java | /*
* ClearSetColorsCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.color;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.util.parse.NexusStreamParser;
import megan.core.Director;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ClearSetColorsCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "clearSetColors;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
((Director) getDir()).getDocument().getChartColorManager().clearChangedColors();
}
public void actionPerformed(ActionEvent event) {
if (JOptionPane.showConfirmDialog(getViewer().getFrame(), "This will discard all individually set colors, proceed?", "Question", JOptionPane.YES_NO_CANCEL_OPTION)
!= JOptionPane.YES_OPTION)
return; // answered no or cancle
execute(getSyntax());
}
public boolean isApplicable() {
return ((Director) getDir()).getDocument().getChartColorManager().hasChangedColors();
}
private static final String NAME = "Clear Set Colors";
public String getName() {
return NAME;
}
public String getDescription() {
return "Clear all individually set colors";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,411 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ColorSamplesByAttributeCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/color/ColorSamplesByAttributeCommand.java | /*
* ColorSamplesByAttributeCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.color;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.core.Director;
import megan.core.Document;
import megan.samplesviewer.SamplesViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ColorSamplesByAttributeCommand extends CommandBase implements ICheckBoxCommand {
@Override
public boolean isSelected() {
return ((Director) getDir()).getDocument().getSampleAttributeTable().isSomeSampleColored();
}
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
if (isSelected()) { // erase all sample colors
final Document doc = ((Director) getDir()).getDocument();
for (String sample : doc.getSampleNames()) {
doc.getSampleAttributeTable().putSampleColor(sample, null);
}
execute("set colorBy=position;");
} else if (getViewer() instanceof SamplesViewer) {
final SamplesViewer viewer = ((SamplesViewer) getViewer());
viewer.getFrame().toFront();
final String attribute = viewer.getSamplesTableView().getASelectedAttribute();
if (attribute != null)
execute("colorBy attribute='" + attribute + "';");
} else
execute("show window=samplesViewer;");
}
public boolean isApplicable() {
return getViewer() instanceof SamplesViewer && isSelected();
}
public static final String ALT_NAME = "Color Samples By Attributes CBOX";
public String getAltName() {
return ALT_NAME;
}
public String getName() {
return "Color Samples By Attributes";
}
public String getDescription() {
return "Determine whether to color samples by attributes";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 3,068 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
UseProgramColorsCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/color/UseProgramColorsCommand.java | /*
* UseProgramColorsCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.color;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.core.Director;
import megan.core.Document;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class UseProgramColorsCommand extends CommandBase implements ICheckBoxCommand {
@Override
public boolean isSelected() {
return ((Director) getDir()).getDocument().getChartColorManager().isUsingProgramColors();
}
public String getSyntax() {
return "set useProgramColors={false|true};";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set useProgramColors=");
boolean use = np.getBoolean();
np.matchIgnoreCase(";");
final Document doc = ((Director) getDir()).getDocument();
if (doc.getChartColorManager().isUsingProgramColors() != use)
doc.setupChartColorManager(use);
}
public void actionPerformed(ActionEvent event) {
execute("set useProgramColors=" + (!isSelected()) + ";");
}
public boolean isApplicable() {
return true;
}
public static final String NAME = "Use Program Color Table";
public String getName() {
return NAME;
}
public String getDescription() {
return "Use program color table rather than document specific one";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,541 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetAttributeColorCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/color/SetAttributeColorCommand.java | /*
* SetAttributeColorCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.color;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ColorUtilsSwing;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.chart.ChartColorManager;
import megan.core.Director;
import megan.core.Document;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* set color by attribute
* Daniel Huson, 7.2012
*/
public class SetAttributeColorCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set color=");
Color color = ColorUtilsSwing.convert(np.getColor());
np.matchIgnoreCase("attribute=");
final String attribute = np.getLabelRespectCase();
np.matchIgnoreCase("state=");
final String state = np.getLabelRespectCase();
if (attribute != null && state != null) {
final Document doc = ((Director) getDir()).getDocument();
final ChartColorManager chartColorManager = doc.getChartColorManager();
chartColorManager.setAttributeStateColor(attribute, state, color);
for (String sample : doc.getSampleNames()) {
chartColorManager.setSampleColor(sample, chartColorManager.getAttributeStateColor(attribute, doc.getSampleAttributeTable().get(sample, attribute)));
}
doc.setDirty(true);
((Director) getDir()).updateView(Director.ALL);
}
np.matchIgnoreCase(";");
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "set color=<color> attribute=<name> state=<name>;";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
}
public String getName() {
return null;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Set the color for an attribute value";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("YellowSquare16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_K, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
}
| 3,872 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ColorByLabelCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/color/ColorByLabelCommand.java | /*
* ColorByLabelCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.color;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.chart.ChartColorManager;
import megan.core.Director;
import megan.core.Document;
import megan.core.SampleAttributeTable;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.List;
public class ColorByLabelCommand extends CommandBase implements ICheckBoxCommand {
@Override
public boolean isSelected() {
return !((Director) getDir()).getDocument().getChartColorManager().isColorByPosition();
}
public String getSyntax() {
return "set colorBy={label|position};";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set colorBy=");
final boolean byPosition = (np.getWordMatchesRespectingCase("label position").equalsIgnoreCase("position"));
np.matchIgnoreCase(";");
final Document doc = ((Director) getDir()).getDocument();
final boolean oldByPosition = doc.getChartColorManager().isColorByPosition();
doc.getChartColorManager().setColorByPosition(byPosition);
updateColors(doc);
if (oldByPosition != byPosition)
doc.setDirty(true);
}
public static void updateColors (Document doc) {
final boolean byPosition=doc.getChartColorManager().isColorByPosition();
final List<String> samples=doc.getSampleNames();
final ChartColorManager colorTableManager=doc.getChartColorManager();
colorTableManager.clearChangedColors();
for (int i = 0; i < doc.getNumberOfSamples(); i++) {
doc.getSampleAttributeTable().put(samples.get(i), SampleAttributeTable.HiddenAttribute.Color, null);
}
if(byPosition)
colorTableManager.setSampleColorPositions(samples);
}
public void actionPerformed(ActionEvent event) {
execute("set colorBy=label;");
}
public boolean isApplicable() {
return true;
}
public static final String NAME = "Color Classes By Label";
public String getName() {
return NAME;
}
public String getDescription() {
return "Color classes by their labels (same label always gets same color)";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 3,411 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SelectInvertCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/select/SelectInvertCommand.java | /*
* SelectInvertCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.select;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* * selection command
* * Daniel Huson, 11.2010
*/
public class SelectInvertCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
execute("select nodes=invert;");
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Invert";
}
public String getDescription() {
return "Invert selection";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Empty16.gif");
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,034 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SelectLeavesBelowCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/select/SelectLeavesBelowCommand.java | /*
* SelectLeavesBelowCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.select;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.util.parse.NexusStreamParser;
import megan.viewer.ViewerBase;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* * selection command
* * Daniel Huson, 11.2010
*/
public class SelectLeavesBelowCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
execute("select nodes=leavesBelow;");
}
public boolean isApplicable() {
return getViewer() != null && ((ViewerBase) getViewer()).getSelectedNodes().size() > 0;
}
public String getName() {
return "Leaves Below";
}
public String getDescription() {
return "Select all leaves below currently selected nodes";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,119 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SelectInternalNodesCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/select/SelectInternalNodesCommand.java | /*
* SelectInternalNodesCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.select;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* * selection command
* * Daniel Huson, 11.2010
*/
public class SelectInternalNodesCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void actionPerformed(ActionEvent event) {
execute("select nodes=internal;");
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "All Internal Nodes";
}
public String getDescription() {
return "Select all internal nodes";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Empty16.gif");
}
public boolean isCritical() {
return true;
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,071 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SelectNodesByNameCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/select/SelectNodesByNameCommand.java | /*
* SelectNodesByNameCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.select;
import jloda.swing.commands.ICommand;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.viewer.ViewerBase;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.HashSet;
import java.util.Set;
/**
* select by name
* Daniel Huson, 2.2011
*/
public class SelectNodesByNameCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "select name=<name> <name> ... [state={true|false}];";
}
public void apply(NexusStreamParser np) throws Exception {
ViewerBase viewer = (ViewerBase) getViewer();
np.matchIgnoreCase("select");
np.matchIgnoreCase("name=");
Set<String> names = new HashSet<>();
while (!np.peekMatchAnyTokenIgnoreCase("state ;")) {
names.add(np.getWordRespectCase());
}
boolean state = true;
if (np.peekMatchIgnoreCase("state")) {
np.matchIgnoreCase("state=");
state = np.getBoolean();
}
np.matchRespectCase(";");
viewer.selectNodesByLabels(names, state);
viewer.repaint();
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
String result = JOptionPane.showInputDialog(getViewer().getFrame(), "Enter name", "Select Node", JOptionPane.QUESTION_MESSAGE);
if (result != null)
execute("select name=" + result + ";");
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Select By Name...";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Select the named nodes";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
ViewerBase viewer = (ViewerBase) getViewer();
return viewer.getGraph().getNumberOfNodes() > 0;
}
}
| 3,335 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SelectNodesAboveCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/select/SelectNodesAboveCommand.java | /*
* SelectNodesAboveCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.select;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.util.parse.NexusStreamParser;
import megan.viewer.ViewerBase;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* * selection command
* * Daniel Huson, 11.2010
*/
public class SelectNodesAboveCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
execute("select nodes=nodesAbove;");
}
public boolean isApplicable() {
return getViewer() != null && ((ViewerBase) getViewer()).getSelectedNodes().size() > 0;
}
public String getName() {
return "Nodes Above";
}
public String getDescription() {
return "Select all nodes above the currently selected nodes";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,118 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SelectAllNodesCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/select/SelectAllNodesCommand.java | /*
* SelectAllNodesCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.select;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.director.ProjectManager;
import jloda.swing.util.ResourceManager;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.groups.GroupsViewer;
import megan.viewer.ClassificationViewer;
import megan.viewer.ViewerBase;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* * selection command
* * Daniel Huson, 11.2010
*/
public class SelectAllNodesCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "select nodes={all|none|leaves|internal|previous|subtree|leavesBelow|nodesAbove|intermediate|invert}";
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("select nodes=");
String what = np.getWordMatchesIgnoringCase("all none leaves internal previous subTree leavesBelow subLeaves nodesAbove intermediate invert positiveAssigned");
np.matchRespectCase(";");
final ViewerBase viewer;
if (getViewer() instanceof ViewerBase)
viewer = (ViewerBase) getViewer();
else if (getViewer() instanceof ClusterViewer && ((ClusterViewer) getViewer()).getGraphView() instanceof ViewerBase)
viewer = (ViewerBase) ((ClusterViewer) getViewer()).getGraphView();
else if (getViewer() instanceof ClusterViewer && ((ClusterViewer) getViewer()).getTabbedIndex() == ClusterViewer.MATRIX_TAB_INDEX && what.equalsIgnoreCase("previous")) {
((ClusterViewer) getViewer()).getMatrixTab().selectByLabels(ProjectManager.getPreviouslySelectedNodeLabels());
return;
} else if (getViewer() instanceof GroupsViewer) {
switch (what.toLowerCase()) {
case "previous" -> ((GroupsViewer) getViewer()).selectFromPrevious(ProjectManager.getPreviouslySelectedNodeLabels());
case "all" -> ((GroupsViewer) getViewer()).getGroupsPanel().selectAll();
case "none" -> ((GroupsViewer) getViewer()).getGroupsPanel().selectNone();
}
return;
} else
return;
if (what.equalsIgnoreCase("all"))
viewer.selectAllNodes(true);
else if (what.equals("none"))
viewer.selectAllNodes(false);
else if (what.equals("leaves"))
viewer.selectAllLeaves();
else if (what.equals("internal"))
viewer.selectAllInternal();
else if (what.equals("previous"))
viewer.selectNodesByLabels(ProjectManager.getPreviouslySelectedNodeLabels(), true);
else if (what.equalsIgnoreCase("subTree"))
viewer.selectSubTreeNodes();
else if (what.equals("subLeaves") || what.equals("leavesBelow"))
viewer.selectLeavesBelow();
else if (what.equals("nodesAbove"))
viewer.selectNodesAbove();
else if (what.equals("intermediate"))
viewer.selectAllIntermediateNodes();
else if (what.equals("invert"))
viewer.invertNodeSelection();
else if (what.equals("positiveAssigned")) {
if (viewer instanceof ClassificationViewer)
((ClassificationViewer) viewer).selectNodesPositiveAssigned();
else
NotificationsInSwing.showWarning("select nodes=" + what + ": not implemented for this type of viewer");
}
System.err.println("Number of nodes selected: " + viewer.getNumberSelectedNodes());
viewer.repaint();
}
public void actionPerformed(ActionEvent event) {
executeImmediately("select nodes=all;");
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "All Nodes";
}
public String getDescription() {
return "Select nodes";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Empty16.gif");
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
}
| 5,202 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SelectNodesByIdsCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/select/SelectNodesByIdsCommand.java | /*
* SelectNodesByIdsCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.select;
import jloda.graph.Node;
import jloda.swing.commands.ICommand;
import jloda.util.NumberUtils;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.viewer.ViewerBase;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.HashSet;
import java.util.Set;
/**
* select by name
* Daniel Huson, 2.2011
*/
public class SelectNodesByIdsCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "select id=<number> ...;";
}
public void apply(NexusStreamParser np) throws Exception {
ViewerBase viewer = ((ViewerBase) getViewer());
np.matchIgnoreCase("select id=");
Set<Integer> ids = new HashSet<>();
while (!np.peekMatchAnyTokenIgnoreCase(";")) {
ids.add(NumberUtils.parseInt(np.getWordRespectCase()));
}
np.matchRespectCase(";");
Set<Node> nodes = new HashSet<>();
for (Integer id : ids) {
if (id != null) {
Set<Node> add = viewer.getNodes(id);
if (add != null && add.size() > 0)
nodes.addAll(add);
}
}
viewer.getSelectedNodes().addAll(nodes);
viewer.repaint();
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
String result = JOptionPane.showInputDialog(getViewer().getFrame(), "Enter Id", "Select Node by Id", JOptionPane.QUESTION_MESSAGE);
if (result != null)
execute("select id=" + result + ";");
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Select By Id...";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Select the nodes for the given ids";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
ViewerBase viewer = (ViewerBase) getViewer();
return viewer.getGraph().getNumberOfNodes() > 0;
}
}
| 3,445 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SelectFromPreviousWindowCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/select/SelectFromPreviousWindowCommand.java | /*
* SelectFromPreviousWindowCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.select;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* * selection command
* * Daniel Huson, 11.2010
*/
public class SelectFromPreviousWindowCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
execute("select nodes=previous;");
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "From Previous Window";
}
public String getDescription() {
return "Select from previous window";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Empty16.gif");
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_P, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
}
| 2,147 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SelectNoneCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/select/SelectNoneCommand.java | /*
* SelectNoneCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.select;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* * selection command
* * Daniel Huson, 11.2010
*/
public class SelectNoneCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
execute("select nodes=none;");
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "None";
}
public String getDescription() {
return "Deselect all nodes";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Empty16.gif");
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,028 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SelectSubtreeCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/select/SelectSubtreeCommand.java | /*
* SelectSubtreeCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.select;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.viewer.ViewerBase;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* * selection command
* * Daniel Huson, 11.2010
*/
public class SelectSubtreeCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
execute("select nodes=subTree;");
}
public boolean isApplicable() {
return getViewer() != null && ((ViewerBase) getViewer()).getSelectedNodes().size() > 0;
}
public String getName() {
return "Subtree";
}
public String getDescription() {
return "Select subtree";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Empty16.gif");
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,143 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SelectLeavesCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/select/SelectLeavesCommand.java | /*
* SelectLeavesCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.select;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* * selection command
* * Daniel Huson, 11.2010
*/
public class SelectLeavesCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
executeImmediately("select nodes=leaves;");
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "All Leaves";
}
public String getDescription() {
return "Select all leaves (except Not Assigned, No Hits and Low Complexity)";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Empty16.gif");
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_L, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
}
| 2,134 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SelectIntermediateNodesCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/select/SelectIntermediateNodesCommand.java | /*
* SelectIntermediateNodesCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.select;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.util.parse.NexusStreamParser;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* * selection command
* * Daniel Huson, 11.2010
*/
public class SelectIntermediateNodesCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
executeImmediately("select nodes=intermediate;");
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "All Intermediate Nodes";
}
public String getDescription() {
return "Select all intermediate nodes";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,027 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExportAlignmentsCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/export/ExportAlignmentsCommand.java | /*
* ExportAlignmentsCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.export;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.NumberUtils;
import jloda.util.Pair;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentExporter;
import megan.classification.Classification;
import megan.classification.ClassificationManager;
import megan.commands.CommandBase;
import megan.core.ClassificationType;
import megan.core.Document;
import megan.viewer.ClassificationViewer;
import megan.viewer.MainViewer;
import megan.viewer.TaxonomyData;
import megan.viewer.ViewerBase;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
/**
* export all alignments for the selected nodes
*/
public class ExportAlignmentsCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "export what=alignment file=<filename> data={" + StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), "|") + "}" +
" classId={number[,number...]|selected} [asConsensus={false|true}]\n" +
"\t[useEachReadOnlyOnce={true|false}] [useEachReferenceOnlyOnce={true|false}] [includeInsertions={true|false}]\n" +
"\t[refSeqOnly={false|true}] [contractGaps={false|true}] [translateCDNA={false|true}] [minReads={number}] [minLength={number}] [minCoverage={number}];";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("export what=alignment file=");
String fileName = np.getWordFileNamePunctuation();
np.matchIgnoreCase("data=");
String classificationName = np.getWordMatchesRespectingCase(StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), " "));
np.matchIgnoreCase("classId=");
boolean useSelected = false;
Set<Integer> classIds = new HashSet<>();
if (np.peekMatchIgnoreCase("selected")) {
np.matchIgnoreCase("selected");
useSelected = true;
} else {
while (true) {
classIds.add(np.getInt());
if (!np.peekMatchIgnoreCase(","))
break;
np.matchIgnoreCase(",");
}
}
boolean asConsensus = false;
if (np.peekMatchIgnoreCase("asConsensus")) {
np.matchIgnoreCase("asConsensus=");
asConsensus = np.getBoolean();
ProgramProperties.put("ExAlignmentAsConsensus", asConsensus);
}
boolean useEachReadOnlyOnce = true;
if (np.peekMatchIgnoreCase("useEachReadOnlyOnce")) {
np.matchIgnoreCase("useEachReadOnlyOnce=");
useEachReadOnlyOnce = np.getBoolean();
ProgramProperties.put("ExAlignmentUseEachReadOnce", useEachReadOnlyOnce);
}
boolean useEachReferenceOnlyOnce = false;
if (np.peekMatchIgnoreCase("useEachReferenceOnlyOnce")) {
np.matchIgnoreCase("useEachReferenceOnlyOnce=");
useEachReferenceOnlyOnce = np.getBoolean();
ProgramProperties.put("ExAlignmentUseEachRefOnce", useEachReferenceOnlyOnce);
}
/*
boolean includeInsertions = true;
if (np.peekMatchIgnoreCase("includeInsertions")) {
np.matchIgnoreCase("includeInsertions=");
includeInsertions = np.getBoolean();
}
*/
boolean refSeqOnly = false;
if (np.peekMatchIgnoreCase("refSeqOnly")) {
np.matchIgnoreCase("refSeqOnly=");
refSeqOnly = np.getBoolean();
ProgramProperties.put("ExAlignmentUseRefSeqOnly", refSeqOnly);
}
/*
boolean contractGaps = false;
if (np.peekMatchIgnoreCase("contractGaps")) {
np.matchIgnoreCase("contractGaps=");
contractGaps = np.getBoolean();
}
*/
boolean blastXAsProtein = false;
if (np.peekMatchIgnoreCase("translateCDNA")) {
np.matchIgnoreCase("translateCDNA=");
blastXAsProtein = np.getBoolean();
ProgramProperties.put("ExAlignmentTranslateCDNA", blastXAsProtein);
}
int minReads = 0;
if (np.peekMatchIgnoreCase("minReads")) {
np.matchIgnoreCase("minReads=");
minReads = np.getInt(0, 1000000);
ProgramProperties.put("ExAlignmentMinReads", minReads);
}
int minLength = 0;
if (np.peekMatchIgnoreCase("minLength")) {
np.matchIgnoreCase("minLength=");
minLength = np.getInt(0, 1000000000);
ProgramProperties.put("ExAlignmentMinLength", minLength);
}
double minCoverage = 0;
if (np.peekMatchIgnoreCase("minCoverage")) {
np.matchIgnoreCase("minCoverage=");
minCoverage = np.getDouble(0, 1000000);
ProgramProperties.put("ExAlignmentMinCoverage", (float) minCoverage);
}
np.matchIgnoreCase(";");
if (useSelected) {
if (classificationName.equals(ClassificationType.Taxonomy.toString())) {
MainViewer mainViewer = getDir().getMainViewer();
classIds.addAll(mainViewer.getSelectedNodeIds());
} else {
ClassificationViewer viewer = (ClassificationViewer) getDir().getViewerByClassName(classificationName);
if (viewer != null) {
classIds.addAll(viewer.getSelectedNodeIds());
}
}
}
int totalReads = 0;
int totalFiles = 0;
if (classIds.size() > 0) {
final Document doc = getDir().getDocument();
doc.getProgressListener().setTasks("Alignment export", "");
AlignmentExporter alignmentExporter = new AlignmentExporter(doc, getViewer().getFrame());
alignmentExporter.setUseEachReferenceOnlyOnce(useEachReferenceOnlyOnce);
Classification classification = (classificationName.equals(Classification.Taxonomy) ? null : ClassificationManager.get(classificationName, true));
for (Integer classId : classIds) {
final String className;
if (getViewer() instanceof MainViewer) {
className = TaxonomyData.getName2IdMap().get(classId);
} else if (classification != null) {
className = classification.getName2IdMap().get(classId);
} else
className = "Unknown";
alignmentExporter.loadData(classificationName, classId, className, refSeqOnly, doc.getProgressListener());
Pair<Integer, Integer> numberOfReadsAndFiles = alignmentExporter.exportToFiles(totalFiles, fileName,
useEachReadOnlyOnce, blastXAsProtein, asConsensus, minReads, minLength, minCoverage,
doc.getProgressListener());
totalReads += numberOfReadsAndFiles.getFirst();
totalFiles = numberOfReadsAndFiles.getSecond();
}
doc.getProgressListener().close();
NotificationsInSwing.showInformation(getViewer().getFrame(), "Wrote " + totalReads + " sequences to " + totalFiles + " files");
}
System.err.println("Export Alignments: done");
}
public void actionPerformed(ActionEvent event) {
final String classificationName;
if (getViewer() instanceof MainViewer)
classificationName = ClassificationType.Taxonomy.toString();
else if (getViewer() instanceof ClassificationViewer) {
ClassificationViewer viewer = (ClassificationViewer) getViewer();
classificationName = viewer.getClassName();
} else
return;
final JDialog dialog = new JDialog(getViewer().getFrame());
dialog.setModal(true);
dialog.setLocationRelativeTo(getViewer().getFrame());
dialog.setSize(500, 400);
dialog.setTitle("Export Alignments for " + classificationName + " - " + ProgramProperties.getProgramName());
final JTextField outDirectory = new JTextField();
outDirectory.setText(ProgramProperties.get("ExAlignmentDir", System.getProperty("user.home")));
final JTextField outFileTemplate = new JTextField();
outFileTemplate.setText(ProgramProperties.get("ExAlignmentFile", "alignment-%c-%r.fasta"));
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JPanel topMiddlePanel = new JPanel();
topMiddlePanel.setLayout(new BoxLayout(topMiddlePanel, BoxLayout.Y_AXIS));
JPanel middlePanel = new JPanel();
middlePanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Output files"));
middlePanel.setLayout(new BoxLayout(middlePanel, BoxLayout.Y_AXIS));
JPanel m1 = new JPanel();
m1.setLayout(new BorderLayout());
m1.add(new JLabel("Directory:"), BorderLayout.WEST);
m1.add(outDirectory, BorderLayout.CENTER);
outDirectory.setToolTipText("Set directory for files to be written to");
m1.add(new JButton(new AbstractAction("Browse...") {
public void actionPerformed(ActionEvent actionEvent) {
File file = chooseDirectory(actionEvent, outDirectory.getText());
if (file != null)
outDirectory.setText(file.getPath());
}
}), BorderLayout.EAST);
middlePanel.add(m1);
JPanel m2 = new JPanel();
m2.setLayout(new BorderLayout());
m2.add(new JLabel("File name:"), BorderLayout.WEST);
m2.add(outFileTemplate, BorderLayout.CENTER);
outFileTemplate.setToolTipText("Set name of file to save to. A %c is replaced by node name, %r by reference name and %n by file number.");
middlePanel.add(m2);
JPanel buttons = new JPanel();
buttons.setLayout(new BoxLayout(buttons, BoxLayout.Y_AXIS));
final JCheckBox useEachReadOnlyOnce = new JCheckBox(new AbstractAction("Use Each Read Only Once") {
public void actionPerformed(ActionEvent actionEvent) {
}
});
useEachReadOnlyOnce.setSelected(ProgramProperties.get("ExAlignmentUseEachReadOnce", true));
useEachReadOnlyOnce.setToolTipText("Allow each read only to occur in one alignment, the deepest one containing it");
buttons.add(useEachReadOnlyOnce);
final JCheckBox useEachReferenceOnlyOnce = new JCheckBox(new AbstractAction("Use Each Reference Only Once") {
public void actionPerformed(ActionEvent actionEvent) {
}
});
useEachReferenceOnlyOnce.setSelected(ProgramProperties.get("ExAlignmentUseEachRefOnce", true));
useEachReferenceOnlyOnce.setToolTipText("Allow each reference sequence to appear only once (and not for multiple nodes)");
buttons.add(useEachReferenceOnlyOnce);
/*
final JCheckBox includeInsertions = new JCheckBox(new AbstractAction("Include Insertions") {
public void actionPerformed(ActionEvent actionEvent) {
}
});
includeInsertions.setSelected(true);
includeInsertions.setToolTipText("Include insertions into the reference sequence in alignment");
buttons.add(includeInsertions);
*/
final JCheckBox refSeqOnly = new JCheckBox(new AbstractAction("Use Only Matches to RefSeqs") {
public void actionPerformed(ActionEvent actionEvent) {
}
});
refSeqOnly.setSelected(ProgramProperties.get("ExAlignmentUseRefSeqOnly", false));
refSeqOnly.setToolTipText("Only alignment to reference sequences that have a refSeq id");
buttons.add(refSeqOnly);
/*
final JCheckBox contractGaps = new JCheckBox(new AbstractAction("Contract Gaps") {
public void actionPerformed(ActionEvent actionEvent) {
}
});
contractGaps.setSelected(false);
contractGaps.setToolTipText("Contract runs of gaps and replace by length in square brackets");
buttons.add(contractGaps);
*/
final JCheckBox cDNAAsProteins = new JCheckBox(new AbstractAction("Translate cDNA as proteins") {
public void actionPerformed(ActionEvent actionEvent) {
}
});
cDNAAsProteins.setSelected(ProgramProperties.get("ExAlignmentTranslateCDNA", false));
cDNAAsProteins.setToolTipText("Translate cDNA sequences to proteins");
buttons.add(cDNAAsProteins);
final JCheckBox asConsensus = new JCheckBox(new AbstractAction("As Consensus") {
public void actionPerformed(ActionEvent actionEvent) {
}
});
asConsensus.setSelected(ProgramProperties.get("ExAlignmentAsConsensus", false));
asConsensus.setToolTipText("Save consensus ");
buttons.add(asConsensus);
buttons.add(Box.createVerticalStrut(20));
final JPanel numbersPanel = new JPanel();
numbersPanel.setLayout(new GridLayout(3, 4));
buttons.add(numbersPanel);
final JTextField minReadsField = new JTextField(6);
minReadsField.setMaximumSize(new Dimension(100, 20));
minReadsField.setText("" + ProgramProperties.get("ExAlignmentMinReads", 1));
numbersPanel.add(newSingleLine(Box.createHorizontalGlue(), new JLabel("Minimum reads: ")));
numbersPanel.add(newSingleLine(minReadsField, Box.createHorizontalGlue()));
minReadsField.setToolTipText("Discard all alignments that do not have the specify minimum number of reads");
final JTextField minLengthField = new JTextField(6);
minLengthField.setMaximumSize(new Dimension(100, 20));
minLengthField.setText("" + ProgramProperties.get("ExAlignmentMinLength", 1));
numbersPanel.add(newSingleLine(Box.createHorizontalGlue(), new JLabel("Minimum length: ")));
numbersPanel.add(newSingleLine(minLengthField, Box.createHorizontalGlue()));
minLengthField.setToolTipText("Discard all alignments that do not have the specify minimum length");
final JTextField minCoverageField = new JTextField(6);
minCoverageField.setMaximumSize(new Dimension(100, 20));
minCoverageField.setText("" + (float) (ProgramProperties.get("ExAlignmentMinCoverage", 1.0)));
numbersPanel.add(newSingleLine(Box.createHorizontalGlue(), new JLabel("Minimum Coverage: ")));
numbersPanel.add(newSingleLine(minCoverageField, Box.createHorizontalGlue()));
minCoverageField.setToolTipText("Discard all alignments that do not have the specify minimum coverage");
middlePanel.add(buttons);
topMiddlePanel.add(middlePanel);
mainPanel.add(topMiddlePanel, BorderLayout.NORTH);
JPanel bottomPanel = new JPanel();
bottomPanel.setBorder(BorderFactory.createEtchedBorder());
bottomPanel.setLayout(new BorderLayout());
JPanel b1 = new JPanel();
b1.add(new JButton(new AbstractAction("Cancel") {
public void actionPerformed(ActionEvent actionEvent) {
dialog.setVisible(false);
}
}));
b1.setLayout(new BoxLayout(b1, BoxLayout.X_AXIS));
JButton applyButton = new JButton(new AbstractAction("Apply") {
public void actionPerformed(ActionEvent actionEvent) {
dialog.setVisible(false);
String fileName = (new File(outDirectory.getText().trim(), outFileTemplate.getText().trim())).getPath();
if (fileName.length() > 0) {
String command = "export what=alignment file='" + fileName + "'";
command += " data=" + classificationName;
command += " classId=selected";
command += " asConsensus=" + asConsensus.isSelected();
command += " useEachReadOnlyOnce=" + useEachReadOnlyOnce.isSelected();
command += " useEachReferenceOnlyOnce=" + useEachReferenceOnlyOnce.isSelected();
// command += " includeInsertions=" + includeInsertions.isSelected();
command += " refSeqOnly=" + refSeqOnly.isSelected();
// command += " contractGaps=" + contractGaps.isSelected();
command += " translateCDNA=" + cDNAAsProteins.isSelected();
{
final String text = minReadsField.getText();
if (NumberUtils.isInteger(text) && NumberUtils.parseInt(text) > 0)
command += " minReads=" + text;
}
{
final String text = minLengthField.getText();
if (NumberUtils.isInteger(text) && NumberUtils.parseInt(text) > 0)
command += " minLength=" + text;
}
{
final String text = minCoverageField.getText();
if (NumberUtils.isDouble(text) && NumberUtils.parseDouble(text) > 0)
command += " minCoverage=" + text;
}
command += ";";
ProgramProperties.put("ExAlignmentDir", outDirectory.getText().trim());
ProgramProperties.put("ExAlignmentFile", outFileTemplate.getText().trim());
execute(command);
}
}
});
b1.add(applyButton);
dialog.getRootPane().setDefaultButton(applyButton);
bottomPanel.add(b1, BorderLayout.EAST);
mainPanel.add(bottomPanel, BorderLayout.SOUTH);
dialog.getContentPane().setLayout(new BorderLayout());
dialog.getContentPane().add(mainPanel, BorderLayout.CENTER);
dialog.validate();
dialog.setVisible(true);
}
private static JPanel newSingleLine(Component left, Component right) {
final JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(left);
panel.add(right);
return panel;
}
/**
* choose the directory for export of files
*
* @return directory
*/
private File chooseDirectory(ActionEvent event, String fileName) {
File file = null;
if (ProgramProperties.isMacOS() && (event != null && (event.getModifiers() & ActionEvent.SHIFT_MASK) == 0)) {
//Use native file dialog on mac
java.awt.FileDialog dialog = new java.awt.FileDialog(getViewer().getFrame(), "Open output directory", java.awt.FileDialog.LOAD);
dialog.setFilenameFilter((dir, name) -> true);
if (fileName != null) {
dialog.setDirectory(fileName);
//dialog.setFile(fileName);
}
System.setProperty("apple.awt.fileDialogForDirectories", "true");
dialog.setVisible(true);
System.setProperty("apple.awt.fileDialogForDirectories", "false");
if (dialog.getFile() != null) {
file = new File(dialog.getDirectory(), dialog.getFile());
}
} else {
JFileChooser chooser = new JFileChooser(fileName);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (fileName != null)
chooser.setSelectedFile(new File(fileName));
chooser.setAcceptAllFileFilterUsed(true);
int result = chooser.showOpenDialog(getViewer().getFrame());
if (result == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
}
}
if (file != null) {
if (!file.isDirectory())
file = file.getParentFile();
}
return file;
}
public boolean isApplicable() {
return getViewer() instanceof ViewerBase && getDir().getDocument().getMeganFile().hasDataConnector() && ((ViewerBase) getViewer()).getSelectedNodes().size() > 0;
}
private static final String NAME = "Alignments...";
public String getName() {
return NAME;
}
public KeyStroke getAcceleratorKey() {
return null;
}
public String getDescription() {
return "Calculate and export alignments for all selected leaves";
}
public boolean isCritical() {
return true;
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Export16.gif");
}
}
| 21,473 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExportBIOMCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/export/ExportBIOMCommand.java | /*
* ExportBIOMCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.export;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ChooseFileDialog;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.Basic;
import jloda.util.FileUtils;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.biom.biom1.Biom1ExportFViewer;
import megan.biom.biom1.Biom1ExportTaxonomy;
import megan.classification.Classification;
import megan.classification.ClassificationManager;
import megan.commands.CommandBase;
import megan.core.Director;
import megan.core.Document;
import megan.util.BiomFileFilter;
import megan.viewer.ClassificationViewer;
import megan.viewer.MainViewer;
import megan.viewer.ViewerBase;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
/**
* export BIOM 1.0 format
* Daniel Huson, 2012
*/
public class ExportBIOMCommand extends CommandBase implements ICommand {
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("export format=biom");
Director dir = getDir();
Document doc = dir.getDocument();
np.matchIgnoreCase("data=");
String data = np.getWordMatchesIgnoringCase(StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), " "));
np.matchIgnoreCase("file=");
String outputFile = np.getAbsoluteFileName();
boolean officialRanksOnly = true;
if (np.peekMatchIgnoreCase("officialRanksOnly")) {
np.matchIgnoreCase("officialRanksOnly=");
officialRanksOnly = np.getBoolean();
}
np.matchIgnoreCase(";");
if (data.equalsIgnoreCase(Classification.Taxonomy)) {
try {
int numberOfRows = Biom1ExportTaxonomy.apply(dir, new File(outputFile), officialRanksOnly, doc.getProgressListener());
NotificationsInSwing.showInformation(getViewer().getFrame(), String.format("Exported %,d rows in BIOM1 format", numberOfRows));
} catch (Throwable th) {
Basic.caught(th);
}
} else {
int numberOfRows = Biom1ExportFViewer.apply(getDir(), data, new File(outputFile), doc.getProgressListener());
NotificationsInSwing.showInformation(getViewer().getFrame(), String.format("Exported %,d rows in BIOM1 format", numberOfRows));
}
}
public boolean isApplicable() {
return getDoc().getNumberOfReads() > 0 && getViewer() instanceof ViewerBase
&& ((ViewerBase) getViewer()).getSelectedNodes().size() > 0;
}
public boolean isCritical() {
return true;
}
public String getSyntax() {
return "export format=biom data={" + StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), "|") + "} file=<filename> [officialRanksOnly={true|false}];";
}
public void actionPerformed(ActionEvent event) {
final Director dir = getDir();
boolean officialRanksOnly = false;
String choice;
if (getViewer() instanceof MainViewer) {
choice = Classification.Taxonomy;
switch (JOptionPane.showConfirmDialog(getViewer().getFrame(), "Export taxa at offical ranks only (KPCOFGS)?", "Setup biom export", JOptionPane.YES_NO_CANCEL_OPTION)) {
case JOptionPane.CANCEL_OPTION:
return;
case JOptionPane.YES_OPTION:
officialRanksOnly = true;
}
} else if (getViewer() instanceof ClassificationViewer)
choice = getViewer().getClassName();
else
return;
String name = FileUtils.replaceFileSuffix(dir.getDocument().getTitle(), "-" + choice + ".biom");
File lastOpenFile = new File(name);
String lastDir = ProgramProperties.get("BiomDirectory", "");
if (lastDir.length() > 0) {
lastOpenFile = new File(lastDir, name);
}
File file = ChooseFileDialog.chooseFileToSave(getViewer().getFrame(), lastOpenFile, new BiomFileFilter(BiomFileFilter.Version.V1), new BiomFileFilter(BiomFileFilter.Version.V1), event,
"Save as BIOM 1.0.0 file (JSON format)", ".txt");
if (file != null) {
if (getViewer() instanceof ViewerBase && ((ViewerBase) getViewer()).getSelectedNodes().size() == 0)
executeImmediately("select nodes=leaves;");
ProgramProperties.put("BiomDirectory", file.getParent());
execute("export format=biom data=" + choice + " file='" + file.getPath() + "'" + (choice.equals(Classification.Taxonomy) ? " officialRanksOnly=" + officialRanksOnly + ";" : ";"));
}
}
public String getName() {
return "BIOM1 Format...";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Export16.gif");
}
public String getDescription() {
return "Export data in BIOM 1.0.0 (JSON) format (see http://biom-format.org/documentation/format_versions/biom-1.0.html)";
}
}
| 5,900 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExportTreeCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/export/ExportTreeCommand.java | /*
* ExportTreeCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.export;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ChooseFileDialog;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.swing.util.TextFileFilter;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.FileUtils;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.dialogs.export.ExportTree;
import megan.viewer.ViewerBase;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class ExportTreeCommand extends CommandBase implements ICommand {
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("export what=tree");
np.matchIgnoreCase("file=");
String outputFile = np.getAbsoluteFileName();
var simplify = false;
if (np.peekMatchIgnoreCase("simplify")) {
np.matchIgnoreCase("simplify=");
simplify = np.getBoolean();
}
var showInternalLabels = true;
if (np.peekMatchIgnoreCase("showInternalLabels")) {
np.matchIgnoreCase("showInternalLabels=");
showInternalLabels = np.getBoolean();
}
var showUnassigned = true;
if (np.peekMatchIgnoreCase("showUnassigned")) {
np.matchIgnoreCase("showUnassigned=");
showUnassigned = np.getBoolean();
}
var useIds = false;
if (np.peekMatchIgnoreCase("useIds")) {
np.matchIgnoreCase("useIds=");
useIds = np.getBoolean();
}
np.matchIgnoreCase(";");
if (getViewer() instanceof ViewerBase) {
var viewer = (ViewerBase) getViewer();
try(var w = new BufferedWriter(new FileWriter(outputFile))) {
var count=ExportTree.apply(viewer, w, useIds,showInternalLabels, showUnassigned, simplify);
if(count==0)
NotificationsInSwing.showWarning("Export tree failed: Empty tree");
else
NotificationsInSwing.showInformation("Export tree: %,d nodes".formatted(count));
}
} else
System.err.println("Invalid command");
}
public boolean isApplicable() {
return getViewer() instanceof ViewerBase && ((ViewerBase) getViewer()).getSelectedNodes().size() > 0;
}
public boolean isCritical() {
return true;
}
public String getSyntax() {
return "export what=tree file=<filename> [simplify={false|true}] [showInternalLabels={true|false}] [showUassigned={true|false}] [useIds={false|true}];";
}
public void actionPerformed(ActionEvent event) {
var dir = getDir();
var name = FileUtils.replaceFileSuffix(dir.getDocument().getTitle(), ".tre");
var lastOpenFile = new File(name);
var lastDir = ProgramProperties.get("TreeDirectory", "");
if (lastDir.length() > 0) {
lastOpenFile = new File(lastDir, name);
}
var file = ChooseFileDialog.chooseFileToSave(getViewer().getFrame(), lastOpenFile, new TextFileFilter(), new TextFileFilter(), event, "Save as tree", ".txt");
if (file != null) {
execute("export what=tree file='" + file.getPath() + "' showInternalLabels=true showUnassigned=true useIds=false;");
ProgramProperties.put("TreeDirectory", file.getParent());
}
}
public String getName() {
return "Tree...";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Export16.gif");
}
public String getDescription() {
return "Export induced tree (in Newick format)";
}
}
| 4,543 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExportReadsToLengthAndCoverageCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/export/ExportReadsToLengthAndCoverageCommand.java | /*
* ExportReadsToLengthAndCoverageCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.export;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ChooseFileDialog;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.swing.util.TextFileFilter;
import jloda.util.FileUtils;
import jloda.util.parse.NexusStreamParser;
import megan.core.Director;
import megan.core.Document;
import megan.dialogs.export.ExportReads2LengthAndAlignmentCoverage;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
/**
* export reads in length and amount covered
* Daniel Huson, 3.2017
*/
public class ExportReadsToLengthAndCoverageCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("export what=lengthAndCovered file=");
final String fileName = np.getWordFileNamePunctuation();
np.matchIgnoreCase(";");
if (getViewer() instanceof ClassificationViewer) {
final ClassificationViewer viewer = (ClassificationViewer) getViewer();
final Document doc = viewer.getDocument();
System.err.println("Writing file: " + fileName);
int lines = ExportReads2LengthAndAlignmentCoverage.apply(viewer, new File(fileName), doc.getProgressListener());
System.err.println("done (" + lines + ")");
}
}
public String getSyntax() {
return "export what=lengthAndCovered file=<file-name>";
}
public void actionPerformed(ActionEvent event) {
final Director dir = (Director) getDir();
String name = FileUtils.replaceFileSuffix(dir.getDocument().getTitle(), ".txt");
String lastGFFFile = ProgramProperties.get("lastExportFile", "");
File lastOpenFile = new File((new File(lastGFFFile)).getParent(), name);
final File file = ChooseFileDialog.chooseFileToSave(getViewer().getFrame(), lastOpenFile, new TextFileFilter(), new TextFileFilter(), event, "Save read length and covered bases", ".txt");
if (file != null) {
ProgramProperties.put("lastExportFile", file.getPath());
execute("export what=lengthAndCovered file='" + file.getPath() + "';");
}
}
public boolean isApplicable() {
return getViewer() instanceof ClassificationViewer && ((ClassificationViewer) getViewer()).getNumberSelectedNodes() > 0;
}
private static final String NAME = "Export Read Lengths and Coverage...";
public String getName() {
return NAME;
}
public String getDescription() {
return "Export length and number of bases covered for all selected reads";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Export16.gif");
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 3,866 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExportStampProfileCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/export/ExportStampProfileCommand.java | /*
* ExportStampProfileCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.export;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ChooseFileDialog;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.FileUtils;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.classification.Classification;
import megan.classification.ClassificationManager;
import megan.commands.CommandBase;
import megan.core.Director;
import megan.core.Document;
import megan.util.ExportStamp;
import megan.util.StampFileFilter;
import megan.viewer.MainViewer;
import megan.viewer.ViewerBase;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
/**
* export as STAMP profile
* Daniel Huson, 1.2016
*/
public class ExportStampProfileCommand extends CommandBase implements ICommand {
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("export format=stamp");
Director dir = getDir();
Document doc = dir.getDocument();
np.matchIgnoreCase("data=");
String data = np.getWordMatchesIgnoringCase(StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), " "));
np.matchIgnoreCase("file=");
String outputFile = np.getAbsoluteFileName();
boolean allLevels = false;
if (np.peekMatchIgnoreCase("allLevels")) {
np.matchIgnoreCase("allLevels=");
allLevels = np.getBoolean();
}
np.matchIgnoreCase(";");
final int numberOfRows = ExportStamp.apply(getDir(), data, new File(outputFile), allLevels, doc.getProgressListener());
NotificationsInSwing.showInformation(getViewer().getFrame(), String.format("Exported %,d rows in STAMP profile format", numberOfRows));
}
public boolean isApplicable() {
return getDoc().getNumberOfReads() > 0 && getViewer() instanceof ViewerBase
&& ((ViewerBase) getViewer()).getSelectedNodes().size() > 0;
}
public boolean isCritical() {
return true;
}
public String getSyntax() {
return "export format=stamp data={" + StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), "|") + "} file=<filename>;";
}
public void actionPerformed(ActionEvent event) {
if (!(getViewer() instanceof ViewerBase))
return;
final ViewerBase viewer = (ViewerBase) getViewer();
final Director dir = getDir();
final String choice;
if (viewer instanceof MainViewer)
choice = Classification.Taxonomy;
else
choice = (getViewer()).getClassName();
boolean allLevels = false;
switch (JOptionPane.showConfirmDialog(viewer.getFrame(), "Export all levels above selected nodes as well?", "Export to STAMP option", JOptionPane.YES_NO_CANCEL_OPTION)) {
case JOptionPane.CANCEL_OPTION:
return;
case JOptionPane.YES_OPTION:
allLevels = true;
}
String name = FileUtils.replaceFileSuffix(dir.getDocument().getTitle(), "-" + choice + ".spf");
File lastOpenFile = new File(name);
String lastDir = ProgramProperties.get("StampDirectory", "");
if (lastDir.length() > 0) {
lastOpenFile = new File(lastDir, name);
}
final File file = ChooseFileDialog.chooseFileToSave(getViewer().getFrame(), lastOpenFile, new StampFileFilter(), new StampFileFilter(), event, "Save as STAMP profile file", ".spf");
if (file != null) {
if (viewer.getSelectedNodes().size() == 0)
executeImmediately("select nodes=leaves;");
ProgramProperties.put("StampDirectory", file.getParent());
execute("export format=stamp data=" + choice + " file='" + file.getPath() + "' allLevels=" + allLevels + ";");
}
}
public static String NAME="STAMP Format...";
public String getName() {
return NAME;
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Export16.gif");
}
public String getDescription() {
return "Export selected nodes as a STAMP profile file (.spf)";
}
}
| 5,063 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExportCSVCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/export/ExportCSVCommand.java | /*
* ExportCSVCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.export;
import jloda.swing.commands.ICommand;
import jloda.swing.director.IDirectableViewer;
import jloda.swing.util.*;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.FileUtils;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.classification.Classification;
import megan.commands.CommandBase;
import megan.core.Director;
import megan.core.Document;
import megan.dialogs.export.CSVExporter;
import megan.viewer.ClassificationViewer;
import megan.viewer.ViewerBase;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.List;
import java.util.Objects;
public class ExportCSVCommand extends CommandBase implements ICommand {
private static final String EXPORT_CHOICE = "CSVExportChoice";
private static final String COUNT_CHOICE = "CSVCount";
private static final String SEPARATOR_CHOICE = "CSVSeparator";
public enum Choice {assigned, summarized}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("export what=csv");
final Director dir = getDir();
final IDirectableViewer viewer = getViewer();
final Document doc = dir.getDocument();
final String classificationName;
if (viewer instanceof ClassificationViewer)
classificationName = viewer.getClassName();
else
classificationName = Classification.Taxonomy;
final List<String> formats = CSVExporter.getFormats(classificationName, doc);
np.matchIgnoreCase("format=");
final String format = np.getWordMatchesIgnoringCase(StringUtils.toString(formats, " "));
char separator = '\t';
if (np.peekMatchIgnoreCase("separator")) {
np.matchIgnoreCase("separator=");
if (np.getWordMatchesIgnoringCase("comma tab").equalsIgnoreCase("comma"))
separator = ',';
}
boolean reportSummarized = false;
if (np.peekMatchIgnoreCase("counts")) {
np.matchIgnoreCase("counts=");
if (np.getWordMatchesIgnoringCase(StringUtils.toString(Choice.values(), " ")).equalsIgnoreCase(Choice.summarized.toString()))
reportSummarized = true;
}
np.matchIgnoreCase("file=");
String outputFile = np.getAbsoluteFileName();
np.matchIgnoreCase(";");
int count = CSVExporter.apply(dir, doc.getProgressListener(), new File(outputFile), format, separator, reportSummarized);
NotificationsInSwing.showInformation(getViewer().getFrame(), "Wrote " + count + " line(s) to file: " + outputFile);
}
public boolean isApplicable() {
return getViewer() instanceof ViewerBase && ((ViewerBase) getViewer()).getSelectedNodes().size() > 0;
}
public boolean isCritical() {
return true;
}
public String getSyntax() {
return "export what=CSV format={format} [separator={comma|tab}] [counts={assigned|summarized}] file=<filename>;";
}
public void actionPerformed(ActionEvent event) {
final Director dir = getDir();
final String[] choice = showChoices(getViewer().getFrame(), dir.getDocument(), getViewer().getClassName());
if (choice == null)
return;
final String formatName = choice[0];
final String countChoice = choice[1];
final String separator = choice[2];
final String name = FileUtils.replaceFileSuffix(dir.getDocument().getTitle(), "-ex.txt");
File lastOpenFile = new File(name);
final String lastDir = ProgramProperties.get("CSVDirectory", "");
if (lastDir.length() > 0) {
lastOpenFile = new File(lastDir, name);
}
final File file = ChooseFileDialog.chooseFileToSave(getViewer().getFrame(), lastOpenFile, new TextFileFilter(), new TextFileFilter(), event, "Save as CSV (delimiter-separated values)", ".txt");
if (file != null) {
final String cmd = ("export what=CSV format=" + formatName + " separator=" + separator
+ (countChoice == null ? "" : " counts=" + countChoice) + " file='" + file.getPath() + "';");
execute(cmd);
ProgramProperties.put("CSVDirectory", file.getParent());
}
}
public String getName() {
return "Text (CSV) Format...";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Export16.gif");
}
public String getDescription() {
return "Export assignments of reads to nodes to a CSV (comma or tab-separated value) file";
}
/**
* show the choices dialog
*
* @return choices or null
*/
private static String[] showChoices(Component parent, Document doc, String classification) {
final boolean doTaxonomy = classification.equalsIgnoreCase(Classification.Taxonomy);
final List<String> formats = CSVExporter.getFormats(classification, doc);
final JLabel label0 = new JLabel("Choose data to export: ");
label0.setToolTipText("Choose data to export");
final RememberingComboBox choice0 = new RememberingComboBox();
choice0.setEditable(false);
choice0.addItems(formats);
choice0.setToolTipText("Choose data to export");
if (choice0.getItemCount() > 0)
choice0.setSelectedItem(ProgramProperties.get(EXPORT_CHOICE, choice0.getItemAt(0)));
final JLabel label1 = new JLabel("Choose count to use: ");
label1.setToolTipText("Choose count to use, summarized or assigned");
final RememberingComboBox choice1 = new RememberingComboBox();
choice1.setEditable(false);
choice1.addItem(Choice.assigned.toString());
choice1.addItem(Choice.summarized.toString());
choice1.setToolTipText("Choose count to use, summarized or assigned");
if (choice1.getItemCount() > 0)
choice1.setSelectedItem(ProgramProperties.get(COUNT_CHOICE, choice1.getItemAt(0)));
final JLabel label2 = new JLabel("Choose separator to use: ");
label2.setToolTipText("Choose separator to use");
final RememberingComboBox choice2 = new RememberingComboBox();
choice2.setEditable(false);
choice2.addItem("tab");
choice2.addItem("comma");
choice2.setToolTipText("Choose separator to use");
if (choice2.getItemCount() > 0)
choice2.setSelectedItem(ProgramProperties.get(SEPARATOR_CHOICE, choice2.getItemAt(0)));
final JPanel myPanel = new JPanel();
myPanel.setLayout(new GridLayout((doTaxonomy ? 3 : 2), 2));
myPanel.add(label0);
myPanel.add(choice0);
if (doTaxonomy) {
myPanel.add(label1);
myPanel.add(choice1);
}
myPanel.add(label2);
myPanel.add(choice2);
final int result = JOptionPane.showConfirmDialog(parent, myPanel, "MEGAN - Export to CSV", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
ProgramProperties.getProgramIcon());
if (result == JOptionPane.OK_OPTION) {
ProgramProperties.put(EXPORT_CHOICE, Objects.requireNonNull(choice0.getSelectedItem()).toString());
ProgramProperties.put(COUNT_CHOICE, Objects.requireNonNull(choice1.getSelectedItem()).toString());
ProgramProperties.put(SEPARATOR_CHOICE, Objects.requireNonNull(choice2.getSelectedItem()).toString());
return new String[]{choice0.getCurrentText(false), choice1.getCurrentText(false), choice2.getCurrentText(false)};
}
return null;
}
}
| 8,413 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExportCSVForAllLevelsCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/export/ExportCSVForAllLevelsCommand.java | /*
* ExportCSVForAllLevelsCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.export;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.core.ClassificationType;
import megan.core.DataTable;
import megan.viewer.TaxonomicLevels;
import megan.viewer.TaxonomyData;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class ExportCSVForAllLevelsCommand extends CommandBase implements ICommand {
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("export taxonname_count");
char separator = '\t';
if (np.peekMatchIgnoreCase("separator")) {
np.matchIgnoreCase("separator=");
if (np.getWordMatchesIgnoringCase("comma tab").equalsIgnoreCase("comma"))
separator = ',';
}
np.matchIgnoreCase("folder=");
String outputFile = np.getAbsoluteFileName().trim();
np.matchIgnoreCase("file=");
String rmaFile = np.getAbsoluteFileName();
np.matchIgnoreCase(";");
DataTable table = new DataTable();
BufferedReader reader = new BufferedReader(new FileReader(rmaFile));
table.read(reader, false);
reader.close();
List<String> levels = TaxonomicLevels.getAllNames();
for (String level : levels) {
try (BufferedWriter w = new BufferedWriter(new FileWriter(outputFile + "/" + new File(rmaFile).getName() + "." + level + ".txt"))) {
Map<Integer, float[]> tab = table.getClass2Counts(ClassificationType.Taxonomy.toString());
for (Entry<Integer, float[]> taxid2count : tab.entrySet()) {
Integer taxId = taxid2count.getKey();
float count = taxid2count.getValue()[0];
if (TaxonomyData.getTaxonomicRank(taxId) != TaxonomicLevels.getId(level)) {
continue;
}
if (count == 0) {
continue;
}
w.write("\"" + TaxonomyData.getName2IdMap().get(taxId) + "\"");
w.write(separator + "" + count);
w.write("\n");
}
}
}
}
public boolean isApplicable() {
return getDoc().getNumberOfReads() > 0;
}
public boolean isCritical() {
return true;
}
public String getSyntax() {
return "export taxonname_count separator={comma|tab} folder=<foldername>";
}
public void actionPerformed(ActionEvent event) {
}
public String getName() {
return "Export Taxon_Path Format...";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Export16.gif");
}
public String getDescription() {
return "Export assignments";
}
}
| 3,787 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExportTaxonParentMappingCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/export/ExportTaxonParentMappingCommand.java | /*
* ExportTaxonParentMappingCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.export;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ChooseFileDialog;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.swing.util.TextFileFilter;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.Single;
import jloda.util.parse.NexusStreamParser;
import megan.core.Director;
import megan.viewer.TaxonomyData;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
* exports the parent to node mapping
* Daniel Huson. 7.2021
*/
public class ExportTaxonParentMappingCommand extends CommandBase implements ICommand {
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("export what=taxonParentMap file=");
var file = np.getWordFileNamePunctuation();
boolean top;
if (np.peekMatchIgnoreCase("toTop")) {
np.matchIgnoreCase("toTop=");
top = np.getBoolean();
} else
top = true;
boolean names;
if(np.peekMatchIgnoreCase("names")) {
np.matchIgnoreCase("names=");
names=np.getBoolean();
}
else
names=false;
np.matchIgnoreCase(";");
var exception=new Single<Exception>();
var progress=((Director)getDir()).getDocument().getProgressListener();
progress.setTasks("Export","Taxon-parent mapping");
progress.setProgress(0);
progress.setMaximum(TaxonomyData.getTree().getNumberOfNodes());
try(var writer=new BufferedWriter(new FileWriter(file))) {
var root=TaxonomyData.getTree().getRoot();
var cellularOrganisms=131567;
var topNode=new Single<>(root);
TaxonomyData.getTree().preorderTraversal(v -> {
if (exception.isNull() && v.getParent() != null) {
try {
progress.incrementProgress();
var id = (int) v.getInfo();
int other;
if (top) {
if (v.getParent() == root || (int) v.getParent().getInfo() == cellularOrganisms)
topNode.set(v);
other = (int) topNode.get().getInfo();
} else {
other = (int) v.getParent().getInfo();
}
if(names)
writer.write(String.format("%s\t%s%n", TaxonomyData.getName2IdMap().get(id), TaxonomyData.getName2IdMap().get(other)));
writer.write(String.format("%d\t%d%n", id, other));
}
catch(IOException ex) {
exception.setIfCurrentValueIsNull(ex);
}
}
} );
progress.reportTaskCompleted();
}
catch(IOException ex) {
exception.setIfCurrentValueIsNull(ex);
}
if(exception.isNotNull()) {
NotificationsInSwing.showError("Write failed: "+exception.get().getMessage());
}
}
@Override
public String getSyntax() {
return "export what=taxonParentMap file=<output-file> [toTop={false|true}] [names={false|true}];";
}
@Override
public void actionPerformed(ActionEvent ev) {
var lastOpenFile = new File(ProgramProperties.get("TaxonParentFile","taxon-parent.txt"));
var file = ChooseFileDialog.chooseFileToSave(getViewer().getFrame(), lastOpenFile, new TextFileFilter(), new TextFileFilter(), ev, "Save", ".txt");
if (file != null) {
execute("export what=taxonParentMap file='" + file.getPath() + "' toTop=true names=false;");
ProgramProperties.put("TaxonParentFile", file);
}
}
@Override
public String getName() {
return "Taxon-Parent Mapping...";
}
@Override
public String getDescription() {
return "Export taxonomy as node-to-parent mapping";
}
@Override
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Export16.gif");
}
@Override
public KeyStroke getAcceleratorKey() {
return null;
}
@Override
public boolean isCritical() {
return true;
}
@Override
public boolean isApplicable() {
return true;
}
}
| 5,203 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExportSummaryCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/export/ExportSummaryCommand.java | /*
* ExportSummaryCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.export;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ChooseFileDialog;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.util.FileUtils;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.core.Director;
import megan.main.MeganProperties;
import megan.util.MeganFileFilter;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
public class ExportSummaryCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
// no need to implement, never called
}
public void actionPerformed(ActionEvent event) {
Director dir = getDir();
if (dir.getDocument().getMeganFile().hasDataConnector()) {
final File savedFile = ProgramProperties.getFile(MeganProperties.SAVEFILE);
final File directory = (savedFile != null ? savedFile.getParentFile() : null);
final File lastOpenFile = FileUtils.replaceFileSuffix(new File(directory, dir.getTitle()), ".megan");
final File file = ChooseFileDialog.chooseFileToSave(getViewer().getFrame(), lastOpenFile, new MeganFileFilter(), new MeganFileFilter(), event, "Save MEGAN summary file", ".megan");
if (file != null) {
ProgramProperties.put(MeganProperties.SAVEFILE, file);
String cmd;
cmd = ("save file='" + file.getPath() + "' summary=true;");
execute(cmd);
}
}
}
// if in ask to save summary, modify event source to tell calling method can see that user has canceled
void replyUserHasCanceledInAskToSavesummary(ActionEvent event) {
((Boolean[]) event.getSource())[0] = true;
}
public boolean isApplicable() {
return getDoc().getNumberOfReads() > 0 && getDoc().getMeganFile().hasDataConnector();
}
public String getName() {
return "MEGAN Summary File...";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Export16.gif");
}
public String getDescription() {
return "Export as summary file";
}
public boolean isCritical() {
return true;
}
}
| 3,104 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExportImageCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/export/ExportImageCommand.java | /*
* ExportImageCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.export;
import jloda.fx.util.IHasJavaFXStageAndRoot;
import jloda.swing.commands.ICommand;
import jloda.swing.director.IDirectableViewer;
import jloda.swing.export.*;
import jloda.swing.graphview.GraphView;
import jloda.swing.graphview.NodeView;
import jloda.swing.util.IViewerWithJComponent;
import jloda.swing.util.ResourceManager;
import jloda.util.Basic;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import megan.clusteranalysis.ClusterViewer;
import megan.commands.CommandBase;
import megan.core.Document;
import megan.util.JPanelWithFXStageAndRoot;
import megan.viewer.ViewerBase;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class ExportImageCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "exportImage file=<filename> [descriptionFile=<filename>] [format={bmp|eps|gif|jpg|pdf|png|svg}] [replace={false|true}]\n" +
"\t[visibleOnly]={false|true}] [textAsShapes={false|true}] [title=<string>];";
}
public void apply(NexusStreamParser np) throws Exception {
if (getViewer() != null) {
final IDirectableViewer viewer = getViewer();
np.matchIgnoreCase("exportImage file=");
String cname = np.getWordFileNamePunctuation();
if (cname == null)
throw new IOException("exportImage: Must specify FILE=filename");
String nodeLabelDescriptionFile = null;
if (np.peekMatchIgnoreCase("descriptionFile")) {
np.matchIgnoreCase("descriptionFile=");
nodeLabelDescriptionFile = np.getAbsoluteFileName();
}
java.util.List<String> tokens;
try {
np.pushPunctuationCharacters("=;"); // filename punctuation
tokens = np.getTokensRespectCase(null, ";");
} finally {
np.popPunctuationCharacters();
}
String format = np.findIgnoreCase(tokens, "format=", "svg gif png jpg pdf eps bmp file-suffix", "file-suffix");
boolean visibleOnly = np.findIgnoreCase(tokens, "visibleOnly=", "true false", "false").equals("true");
boolean text2shapes = np.findIgnoreCase(tokens, "textAsShapes=", "true false", "false").equals("true");
String title = np.findIgnoreCase(tokens, "title=", null, "none");
boolean replace = np.findIgnoreCase(tokens, "replace=", "true false", "false").equals("true");
np.checkFindDone(tokens);
File file = new File(cname);
if (!replace && file.exists())
throw new IOException("File exists: " + cname + ", use REPLACE=true to overwrite");
try {
final ExportGraphicType graphicsType;
if (format.equalsIgnoreCase("eps")) {
graphicsType = new EPSExportType();
((EPSExportType) graphicsType).setDrawTextAsOutlines(!text2shapes);
} else if (format.equalsIgnoreCase("png"))
graphicsType = new PNGExportType();
else if (format.equalsIgnoreCase("pdf"))
graphicsType = new PDFExportType();
else if (format.equalsIgnoreCase("svg"))
graphicsType = new SVGExportType();
else if (format.equalsIgnoreCase("gif"))
graphicsType = new GIFExportType();
else if (format.equalsIgnoreCase("bmp"))
graphicsType = new RenderedExportType();
else if (format.equalsIgnoreCase("jpg") || format.equalsIgnoreCase("jpeg"))
graphicsType = new JPGExportType();
else
throw new IOException("Unsupported graphics format: " + format);
JPanel panel;
JScrollPane scrollPane = null;
if (viewer instanceof ViewerBase) {
panel = ((ViewerBase) viewer).getPanel();
scrollPane = ((ViewerBase) viewer).getScrollPane();
} else if (viewer instanceof ChartViewer) {
panel = ((ChartViewer) viewer).getContentPanel();
scrollPane = ((ChartViewer) viewer).getScrollPane();
} else if (viewer instanceof ClusterViewer) {
panel = ((ClusterViewer) viewer).getPanel();
GraphView graphView = ((ClusterViewer) viewer).getGraphView();
if (graphView != null)
scrollPane = graphView.getScrollPane();
} else if (viewer instanceof IHasJavaFXStageAndRoot) {
final IHasJavaFXStageAndRoot component = (IHasJavaFXStageAndRoot) viewer;
panel = new JPanelWithFXStageAndRoot(component.getJavaFXRoot(), component.getJavaFXStage()) {
@Override
public void paint(Graphics g) {
if (viewer instanceof IViewerWithJComponent)
((IViewerWithJComponent) viewer).getComponent().paint(g);
}
};
} else if (viewer instanceof IViewerWithJComponent) {
final JComponent component = ((IViewerWithJComponent) viewer).getComponent();
System.err.println("Size: " + component.getSize());
panel = new JPanel() {
public void paint(Graphics gc) {
component.paint(gc);
}
};
panel.setSize(component.getSize());
} else {
final JFrame frame = viewer.getFrame();
panel = new JPanel() {
public void paint(Graphics gc) {
frame.paint(gc);
}
};
panel.setSize(frame.getContentPane().getSize());
}
if (!visibleOnly && scrollPane != null) { // need to adjust bounds and color background
if (!panel.getBounds().contains(scrollPane.getBounds())) {
final JPanel fpanel = panel;
final JScrollPane fScrollPane = scrollPane;
panel = new JPanel() {
@Override
public void paint(Graphics g) {
Rectangle rectangle = new Rectangle(getBounds());
final Point apt = fScrollPane.getViewport().getViewPosition();
rectangle.x += apt.x;
rectangle.y += apt.y;
g.setColor(Color.WHITE);
((Graphics2D) g).fill(rectangle);
fpanel.paint(g);
}
};
panel.setBounds(fpanel.getBounds().x, fpanel.getBounds().y, Math.max(fpanel.getBounds().width, scrollPane.getBounds().width),
Math.max(fpanel.getBounds().height, scrollPane.getBounds().height));
}
}
ensureReasonableBounds(panel);
ensureReasonableBounds(scrollPane);
NodeView.descriptionWriter = null;
if (nodeLabelDescriptionFile != null) {
try {
NodeView.descriptionWriter = new FileWriter(nodeLabelDescriptionFile);
} catch (Exception ex) {
Basic.caught(ex);
}
}
try {
/* todo: find out why no printer is found...
if(graphicsType instanceof PDFExportType && panel instanceof IHasJavaFXStageAndRoot) {
JavaFX2PDF javaFX2PDF = new JavaFX2PDF(((IHasJavaFXStageAndRoot) panel).getJavaFXRoot(), ((IHasJavaFXStageAndRoot) panel).getJavaFXStage());
javaFX2PDF.print();
}
else
*/
graphicsType.writeToFile(file, panel, scrollPane, !visibleOnly);
} finally {
if (NodeView.descriptionWriter != null) {
NodeView.descriptionWriter.close();
NodeView.descriptionWriter = null;
}
}
System.err.println("Exported image to file: " + file);
} catch (Exception ex) {
throw new IOException(ex);
}
} else {
np.matchWordIgnoreCase("exportImage");
throw new IOException("ExportImage not implemented for this type of window: " + (Basic.getShortName(getParent().getClass())));
}
}
/**
* if width or height unreasonably big (>100000) or small (<=0), sets to 1000
*
*/
private static void ensureReasonableBounds(JPanel panel) {
panel.setSize(new Dimension((panel.getWidth() <= 0 || panel.getWidth() > 100000 ? 1000 : panel.getWidth()), (panel.getHeight() <= 0 || panel.getHeight() > 100000 ? 1000 : panel.getHeight())));
}
/**
* if width or height unreasonably big or small, sets to 1000
*
*/
private void ensureReasonableBounds(JScrollPane panel) {
if (panel != null) {
panel.setSize(new Dimension((panel.getWidth() <= 0 || panel.getWidth() > 100000 ? 1000 : panel.getWidth()), (panel.getHeight() <= 0 || panel.getHeight() > 100000 ? 1000 : panel.getHeight())));
final JViewport viewPort = panel.getViewport();
viewPort.setExtentSize(new Dimension((int) (viewPort.getExtentSize().getWidth() <= 0 || viewPort.getExtentSize().getWidth() > 100000 ? 1000 : viewPort.getExtentSize().getWidth()),
(int) (viewPort.getExtentSize().getHeight() <= 0 || viewPort.getExtentSize().getHeight() > 100000 ? 1000 : viewPort.getExtentSize().getHeight())));
}
}
public void actionPerformed(ActionEvent event) {
final IDirectableViewer viewer = getViewer();
// setup a good default name: the file name plus .eps:
String fileName = "Untitled";
Document doc = getDir().getDocument();
if (doc.getMeganFile().getFileName() != null)
fileName = doc.getMeganFile().getFileName();
final boolean allowWhole = (viewer instanceof ViewerBase || viewer instanceof ChartViewer || (viewer instanceof ClusterViewer && ((ClusterViewer) viewer).isSwingPanel()));
final ExportImageDialog saveImageDialog = new ExportImageDialog(viewer.getFrame(), fileName, true, allowWhole, true, event);
final String command = saveImageDialog.displayDialog();
if (command != null)
executeImmediately(command);
}
public boolean isApplicable() {
return getViewer() != null;
}
public String getName() {
return "Export Image...";
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_E, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
public String getDescription() {
return "Export content of window to an image file";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Export16.gif");
}
public boolean isCritical() {
return true;
}
}
| 12,509 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExportMetaDataCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/export/ExportMetaDataCommand.java | /*
* ExportMetaDataCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.export;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ChooseFileDialog;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.swing.util.TextFileFilter;
import jloda.util.FileUtils;
import jloda.util.parse.NexusStreamParser;
import megan.core.Director;
import megan.core.Document;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
public class ExportMetaDataCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "export metaData=<file> [format={metaDataMapping}];";
}
public void apply(NexusStreamParser np) throws Exception {
Director dir = (Director) getDir();
Document doc = dir.getDocument();
np.matchIgnoreCase("export metaData=");
String fileName = np.getAbsoluteFileName();
String format = "metaDataMapping";
if (np.peekMatchIgnoreCase("format")) {
np.matchIgnoreCase("format=");
format = np.getWordMatchesIgnoringCase("metaDataMapping");
}
np.matchIgnoreCase(";");
Writer w = new FileWriter(fileName);
doc.getSampleAttributeTable().write(w, false, false);
w.close();
}
public void actionPerformed(ActionEvent event) {
String name = ((Director) getDir()).getDocument().getMeganFile().getName();
File lastOpenFile = ProgramProperties.getFile("MetaDataFilePath");
if (lastOpenFile != null) {
lastOpenFile = new File(lastOpenFile.getParent(), FileUtils.replaceFileSuffix(name, "-metadata.txt"));
} else
lastOpenFile = new File(FileUtils.replaceFileSuffix(name, "-metadata.txt"));
File file = ChooseFileDialog.chooseFileToSave(getViewer().getFrame(), lastOpenFile, new TextFileFilter(), new TextFileFilter(), event, "Export metadata mapping file");
if (file != null) {
execute("export metadata='" + file.getPath() + "';");
ProgramProperties.put("MetaDataFilePath", file.getPath());
}
}
public boolean isApplicable() {
Director dir = (Director) getDir();
Document doc = dir.getDocument();
return doc.getNumberOfSamples() > 0;
}
public String getName() {
return "Metadata...";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Export16.gif");
}
public String getDescription() {
return "Export a metadata mapping file (as defined in http://qiime.org/documentation/file_formats.html)";
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 3,613 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExportMatchSignaturesCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/export/ExportMatchSignaturesCommand.java | /*
* ExportMatchSignaturesCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.export;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ChooseFileDialog;
import jloda.swing.util.FastaFileFilter;
import jloda.swing.util.ResourceManager;
import jloda.util.FileUtils;
import jloda.util.NumberUtils;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.core.Director;
import megan.core.Document;
import megan.dialogs.export.MatchSignaturesExporter;
import megan.viewer.TaxonomicLevels;
import megan.viewer.TaxonomyData;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
public class ExportMatchSignaturesCommand extends CommandBase implements ICommand {
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("export what=matchPatterns");
final Document doc = getDir().getDocument();
np.matchIgnoreCase("taxon=");
String label = np.getWordRespectCase();
int taxonId;
if (NumberUtils.isInteger(label))
taxonId = NumberUtils.parseInt(label);
else
taxonId = TaxonomyData.getName2IdMap().get(label);
np.matchIgnoreCase("rank=");
String rank = np.getWordMatchesRespectingCase(StringUtils.toString(TaxonomicLevels.getAllNames(), " "));
np.matchIgnoreCase("file=");
String outputFile = np.getAbsoluteFileName();
np.matchIgnoreCase(";");
MatchSignaturesExporter.export(doc.getConnector(), taxonId, rank, doc.getMinScore(), doc.getMaxExpected(), doc.getMinPercentIdentity(), doc.getTopPercent(), outputFile, doc.getProgressListener());
}
public boolean isApplicable() {
return getDoc().getMeganFile().hasDataConnector() && getDir().getMainViewer().getSelectedNodeIds().size() == 1;
}
public boolean isCritical() {
return true;
}
public String getSyntax() {
return "export what=matchPatterns taxon=<id or name> rank=<name> file=<filename>;";
}
public void actionPerformed(ActionEvent event) {
Director dir = getDir();
if (!isApplicable())
return;
int taxon = getDir().getMainViewer().getSelectedNodeIds().iterator().next();
String name = FileUtils.replaceFileSuffix(dir.getDocument().getTitle(), "-ex.txt");
File lastOpenFile = new File(name);
File file = ChooseFileDialog.chooseFileToSave(getViewer().getFrame(), lastOpenFile, new FastaFileFilter(), new FastaFileFilter(), event, "Save all READs to file", ".fasta");
if (file != null) {
String cmd;
cmd = ("export what=matchPatterns taxon=" + taxon + " rank=Genus file='" + file.getPath() + "';");
execute(cmd);
}
}
public String getName() {
return "Match Signatures...";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Export16.gif");
}
public String getDescription() {
return "Export all match signatures for the select node";
}
}
| 3,753 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExportReadsToGFFCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/export/ExportReadsToGFFCommand.java | /*
* ExportReadsToGFFCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.export;
import jloda.seq.BlastMode;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.message.MessageWindow;
import jloda.swing.util.ChooseFileDialog;
import jloda.swing.util.Message;
import jloda.swing.util.ResourceManager;
import jloda.swing.util.TextFileFilter;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.*;
import jloda.util.parse.NexusStreamParser;
import megan.classification.Classification;
import megan.classification.ClassificationManager;
import megan.core.Director;
import megan.core.Document;
import megan.dialogs.export.ExportAlignedReads2GFF3Format;
import megan.dialogs.lrinspector.LRInspectorViewer;
import megan.main.Version;
import megan.viewer.ClassificationViewer;
import megan.viewer.MainViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.File;
/**
* export reads in GFF format
* Daniel Huson, 3.2017
*/
public class ExportReadsToGFFCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "export what=GFF file=<file-name> [classification={all|" + StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), "|") + "] [excludeIncompatible={false|true}] [excludeDominated={true|false}]";
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("export what=GFF file=");
final String fileName = np.getWordFileNamePunctuation();
final String classification;
if (np.peekMatchIgnoreCase("classification")) {
np.matchIgnoreCase("classification=");
classification = np.getWordMatchesIgnoringCase("all " + StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), " "));
} else
classification = "all";
final boolean excludeIncompatible;
if (np.peekMatchIgnoreCase("excludeIncompatible")) {
np.matchIgnoreCase("excludeIncompatible=");
excludeIncompatible = np.getBoolean();
} else
excludeIncompatible = false;
final boolean excludeDominated;
if (np.peekMatchIgnoreCase("excludeDominated")) {
np.matchIgnoreCase("excludeDominated=");
excludeDominated = np.getBoolean();
} else
excludeDominated = true;
np.matchIgnoreCase(";");
if (getViewer() instanceof final ClassificationViewer viewer) {
final Document doc = viewer.getDocument();
final Pair<Long, Long> counts = ExportAlignedReads2GFF3Format.apply(viewer, new File(fileName), classification, excludeIncompatible, excludeDominated, doc.getProgressListener());
NotificationsInSwing.showInformation(viewer.getFrame(), "Number of reads exported: " + counts.getFirst() + ", alignments exported: " + counts.getSecond());
} else if (getViewer() instanceof final LRInspectorViewer viewer) {
final Document doc = viewer.getDir().getDocument();
final Pair<Long, Long> counts = ExportAlignedReads2GFF3Format.apply(viewer, new File(fileName), classification, excludeIncompatible, excludeDominated, doc.getProgressListener());
NotificationsInSwing.showInformation(viewer.getFrame(), "Number of reads exported: " + counts.getFirst() + ", alignments exported: " + counts.getSecond());
}
}
public void actionPerformed(ActionEvent event) {
final boolean canExport;
final boolean canExcludeIncompatible;
{
if (getViewer() instanceof MainViewer) {
canExcludeIncompatible = true;
canExport = (((MainViewer) getViewer()).getNumberSelectedNodes() > 0);
} else if (getViewer() instanceof ClassificationViewer) {
canExcludeIncompatible = false;
canExport = (((ClassificationViewer) getViewer()).getNumberSelectedNodes() > 0);
} else if (getViewer() instanceof final LRInspectorViewer viewer) {
canExcludeIncompatible = viewer.getClassificationName().equals(Classification.Taxonomy) && viewer.someSelectedItemHasTaxonLabelsShowing();
canExport=viewer.someSelectedItemHasAnyLabelsShowing();
} else {
canExcludeIncompatible = false;
canExport = false;
}
}
if(!canExport) {
NotificationsInSwing.showWarning("To export in GFF format, select reads(s) and activate classifications in Layout menu");
return;
}
final Triplet<Boolean, Boolean, String> options = getOptions(getViewer().getFrame(), canExport, canExcludeIncompatible);
if (options != null) {
String name = FileUtils.replaceFileSuffix(((Director) getDir()).getDocument().getTitle(), "-" + ExportAlignedReads2GFF3Format.getShortName(options.getThird()) + ".gff");
String lastGFFFile = ProgramProperties.get("lastGFFFile", "");
File lastOpenFile = new File((new File(lastGFFFile)).getParent(), name);
final File file = ChooseFileDialog.chooseFileToSave(getViewer().getFrame(), lastOpenFile, new TextFileFilter(".gff"), new TextFileFilter(".gff"), event, "Save read annotations to file", ".gff");
if (file != null) {
ProgramProperties.put("lastGFFFile", file.getPath());
execute("export what=GFF file='" + file.getPath() + "'" + (options.getThird() != null ? " classification=" + options.getThird() : "") +
(options.getFirst() ? " excludeIncompatible=true" : "") + (options.getSecond() ? " excludeDominated=true" : "") + ";");
}
}
}
/**
* gets options from user
*
* @return options
*/
private Triplet<Boolean, Boolean, String> getOptions(JFrame frame, boolean canExport, boolean canExcludeIncompatible) {
final JDialog dialog = new JDialog();
{
dialog.setModal(true);
dialog.setTitle("Export in GFF3 Format - " + Version.NAME);
dialog.setIconImages(jloda.swing.util.ProgramProperties.getProgramIconImages());
dialog.setLocationRelativeTo(frame);
dialog.setSize(500, 160);
dialog.getContentPane().setLayout(new BorderLayout());
}
final JPanel topPane = new JPanel();
{
topPane.setLayout(new BoxLayout(topPane, BoxLayout.X_AXIS));
topPane.setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 5));
topPane.add(new JLabel("Select export options:"));
dialog.getContentPane().add(topPane, BorderLayout.NORTH);
}
final JPanel middlePanel = new JPanel();
{
middlePanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(2, 4, 2, 4),
BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(), BorderFactory.createEmptyBorder(4, 4, 4, 4))));
middlePanel.setLayout(new BoxLayout(middlePanel, BoxLayout.Y_AXIS));
dialog.getContentPane().add(middlePanel, BorderLayout.CENTER);
}
final JComboBox<String> classificationCBox = new JComboBox<>();
{
classificationCBox.setEditable(false);
classificationCBox.addItem("All");
for (String classification : ClassificationManager.getAllSupportedClassifications())
classificationCBox.addItem(classification);
classificationCBox.setSelectedItem(ProgramProperties.get("GFFExportClassification", "All"));
final JPanel aLine = new JPanel();
aLine.setLayout(new BoxLayout(aLine, BoxLayout.X_AXIS));
aLine.setMaximumSize(new Dimension(256, 60));
aLine.add(new JLabel("Classification:"));
aLine.add(classificationCBox);
classificationCBox.setToolTipText("Choose classification to export. Use 'all' to export all alignments.");
middlePanel.add(aLine);
}
final JCheckBox excludeIncompatible = new JCheckBox("Exclude taxonomically incompatible genes");
final JCheckBox excludeDominated = new JCheckBox("Exclude dominated genes");
{
excludeIncompatible.setToolTipText("Don't report a gene if its taxon is incompatible with the taxon assigned to the read.");
excludeIncompatible.setEnabled(canExport && canExcludeIncompatible);
excludeIncompatible.setSelected(ProgramProperties.get("GFFExportExcludeIncompatible", false));
excludeDominated.setToolTipText("Don't report any genes that are dominated by better ones.");
excludeDominated.setEnabled(canExport);
excludeDominated.setSelected(ProgramProperties.get("GFFExportExcludeDominated", true));
middlePanel.add(excludeIncompatible);
middlePanel.add(excludeDominated);
}
final JPanel bottomPanel = new JPanel();
{
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.X_AXIS));
bottomPanel.add(Box.createHorizontalGlue());
if (!canExport) {
bottomPanel.add(new JLabel("Nothing to export."));
}
bottomPanel.add(Box.createHorizontalGlue());
dialog.getContentPane().add(bottomPanel, BorderLayout.SOUTH);
}
final JButton cancel = new JButton(new AbstractAction("Cancel") {
@Override
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
}
});
bottomPanel.add(cancel);
final Single<Triplet<Boolean, Boolean, String>> result = new Single<>(null);
final JButton apply = new JButton(new AbstractAction("Apply") {
@Override
public void actionPerformed(ActionEvent e) {
ProgramProperties.put("GFFExportClassification", (String) classificationCBox.getSelectedItem());
ProgramProperties.put("GFFExportExcludeIncompatible", excludeIncompatible.isSelected());
ProgramProperties.put("GFFExportExcludeDominated", excludeDominated.isSelected());
result.set(new Triplet<>(excludeIncompatible.isSelected(), excludeDominated.isSelected(), (String) classificationCBox.getSelectedItem()));
dialog.setVisible(false);
}
});
apply.setEnabled(canExport);
bottomPanel.add(apply);
dialog.setVisible(true);
return result.get();
}
public boolean isApplicable() {
if (((Director) getDir()).getDocument().getBlastMode() == BlastMode.BlastX) {
if (getViewer() instanceof final ClassificationViewer viewer) {
return viewer.getDocument().isLongReads() && viewer.getNumberSelectedNodes() > 0;
} else if (getViewer() instanceof LRInspectorViewer) {
return ((LRInspectorViewer) getViewer()).getNumberOfSelectedItems() > 0;
}
}
return false;
}
private static final String NAME = "Annotations in GFF Format...";
public String getName() {
return NAME;
}
public String getDescription() {
return "Export selected long reads and their aligned genes in GFF3 format";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Export16.gif");
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 12,426 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExportMatchesCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/export/ExportMatchesCommand.java | /*
* ExportMatchesCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.export;
import jloda.swing.commands.ICommand;
import jloda.swing.util.BlastFileFilter;
import jloda.swing.util.ChooseFileDialog;
import jloda.swing.util.ResourceManager;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.FileUtils;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.classification.Classification;
import megan.classification.ClassificationManager;
import megan.commands.CommandBase;
import megan.core.ClassificationType;
import megan.core.Director;
import megan.core.Document;
import megan.dialogs.export.MatchesExporter;
import megan.viewer.ClassificationViewer;
import megan.viewer.MainViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
public class ExportMatchesCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "export what=matches [data={" + StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), "|") + "}] file=<filename>;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("export what=matches");
Director dir = getDir();
MainViewer mainViewer = dir.getMainViewer();
Document doc = dir.getDocument();
String classificationName = ClassificationType.Taxonomy.toString();
if (np.peekMatchIgnoreCase("data")) {
np.matchIgnoreCase("data=");
classificationName = np.getWordMatchesRespectingCase(StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), " "));
}
Set<Integer> classIds = new HashSet<>();
if (classificationName.equals(Classification.Taxonomy))
classIds.addAll(mainViewer.getSelectedNodeIds());
else {
ClassificationViewer viewer = (ClassificationViewer) getDir().getViewerByClassName(classificationName);
if (viewer != null) {
final Classification classification = ClassificationManager.get(classificationName, true);
for (Integer id : viewer.getSelectedNodeIds()) {
Set<Integer> ids = classification.getFullTree().getAllDescendants(id);
classIds.addAll(ids);
}
}
}
np.matchIgnoreCase("file=");
String outputFile = np.getAbsoluteFileName();
np.matchIgnoreCase(";");
long count;
if (classIds.size() == 0)
count = MatchesExporter.exportAll(doc.getBlastMode(), doc.getConnector(), outputFile, doc.getProgressListener());
else
count = MatchesExporter.export(classificationName, classIds, doc.getBlastMode(), doc.getConnector(), outputFile, doc.getProgressListener());
NotificationsInSwing.showInformation(getViewer().getFrame(), "Wrote " + count + " matches to file: " + outputFile);
}
public boolean isApplicable() {
return getDoc().getMeganFile().hasDataConnector();
}
public boolean isCritical() {
return true;
}
public void actionPerformed(ActionEvent event) {
Director dir = getDir();
if (!dir.getDocument().getMeganFile().hasDataConnector())
return;
String name = FileUtils.replaceFileSuffix(dir.getDocument().getTitle(), "-ex.blast");
File lastOpenFile = new File(name);
File file = ChooseFileDialog.chooseFileToSave(getViewer().getFrame(), lastOpenFile, new BlastFileFilter(), new BlastFileFilter(), event, "Save all BLAST matches to file", ".blast");
String data;
if (getViewer() instanceof MainViewer) {
data = Classification.Taxonomy;
} else if (getViewer() instanceof ClassificationViewer) {
data = getViewer().getClassName();
} else
return;
if (file != null) {
String cmd;
cmd = ("export what=matches data=" + data + " file='" + file.getPath() + "';");
execute(cmd);
}
}
public String getName() {
return "Matches...";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Export16.gif");
}
public String getDescription() {
return "Export all matches to a file in BLAST text format (or only those for selected nodes, if any selected)";
}
}
| 5,190 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExportLegendCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/export/ExportLegendCommand.java | /*
* ExportLegendCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.export;
import jloda.swing.commands.ICommand;
import jloda.swing.director.IDirectableViewer;
import jloda.swing.director.IViewerWithLegend;
import jloda.swing.export.*;
import jloda.swing.util.ResourceManager;
import jloda.util.FileUtils;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.core.Document;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
public class ExportLegendCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "exportLegend file=<filename> [format={bmp|eps|gif|jpg|pdf|png|svg}]" +
" [replace={false|true}] [textAsShapes={false|true}];";
}
public void apply(NexusStreamParser np) throws Exception {
IDirectableViewer viewer = getViewer();
np.matchIgnoreCase("exportLegend file=");
String cname = np.getWordFileNamePunctuation();
if (cname == null)
throw new IOException("exportimage: Must specify FILE=filename");
String nodeLabelDescriptionFile = null;
if (np.peekMatchIgnoreCase("descriptionFile")) {
np.matchIgnoreCase("descriptionFile=");
nodeLabelDescriptionFile = np.getAbsoluteFileName();
}
java.util.List<String> tokens;
try {
np.pushPunctuationCharacters("=;"); // filename punctuation
tokens = np.getTokensRespectCase(null, ";");
} finally {
np.popPunctuationCharacters();
}
String format = np.findIgnoreCase(tokens, "format=", "svg gif png jpg pdf eps bmp file-suffix", "file-suffix");
boolean visibleOnly = np.findIgnoreCase(tokens, "visibleOnly=", "true false", "false").equals("true");
boolean text2shapes = np.findIgnoreCase(tokens, "textasShapes=", "true false", "false").equals("true");
String title = np.findIgnoreCase(tokens, "title=", null, "none");
boolean replace = np.findIgnoreCase(tokens, "replace=", "true false", "false").equals("true");
np.checkFindDone(tokens);
File file = new File(cname);
if (!replace && file.exists())
throw new IOException("File exists: " + cname + ", use REPLACE=true to overwrite");
try {
ExportGraphicType graphicsType;
if (format.equalsIgnoreCase("eps")) {
graphicsType = new EPSExportType();
((EPSExportType) graphicsType).setDrawTextAsOutlines(!text2shapes);
} else if (format.equalsIgnoreCase("png"))
graphicsType = new PNGExportType();
else if (format.equalsIgnoreCase("pdf"))
graphicsType = new PDFExportType();
else if (format.equalsIgnoreCase("svg"))
graphicsType = new SVGExportType();
else if (format.equalsIgnoreCase("gif"))
graphicsType = new GIFExportType();
else if (format.equalsIgnoreCase("bmp"))
graphicsType = new RenderedExportType();
else if (format.equalsIgnoreCase("jpg") || format.equalsIgnoreCase("jpeg"))
graphicsType = new JPGExportType();
else
throw new IOException("Unsupported graphics format: " + format);
if (viewer instanceof IViewerWithLegend)
graphicsType.writeToFile(file, ((IViewerWithLegend) viewer).getLegendPanel(), ((IViewerWithLegend) viewer).getLegendScrollPane(), true);
else
throw new IOException("Export legend: not imported for this type of viewer");
System.err.println("Exported legend image to file: " + file);
} catch (Exception ex) {
throw new IOException(ex);
}
}
public void actionPerformed(ActionEvent event) {
IDirectableViewer viewer = getViewer();
// setup a good default name: the file name plus .eps:
String fileName = "Untitled";
Document doc = getDir().getDocument();
if (doc.getMeganFile().getFileName() != null)
fileName = doc.getMeganFile().getFileName();
fileName = FileUtils.replaceFileSuffix(fileName, "-legend.pdf");
ExportImageDialog saveImageDialog;
if (viewer instanceof IViewerWithLegend) {
saveImageDialog = new ExportImageDialog(viewer.getFrame(), fileName, false, true, true, event);
String command = saveImageDialog.displayDialog();
if (command != null) {
command = command.replaceAll("(?i)exportimage", "exportLegend");
execute(command);
}
}
}
public boolean isApplicable() {
return getViewer() != null && getViewer() instanceof IViewerWithLegend && !((IViewerWithLegend) getViewer()).getShowLegend().equals("none");
}
public String getName() {
return "Export Legend...";
}
public KeyStroke getAcceleratorKey() {
return null;
}
public String getDescription() {
return "Export content of legend window";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Export16.gif");
}
public boolean isCritical() {
return true;
}
}
| 6,067 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExportIndividualSamplesCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/export/ExportIndividualSamplesCommand.java | /*
* ExportIndividualSamplesCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.export;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ChooseFileDialog;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.FileUtils;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.core.Document;
import megan.core.MeganFile;
import megan.main.MeganProperties;
import megan.util.MeganFileFilter;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Collections;
public class ExportIndividualSamplesCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "extract directory=<target-directory> replace={true|false};";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("extract directory=");
final String directory = np.getWordFileNamePunctuation();
final boolean replace;
if (np.peekMatchIgnoreCase("replace")) {
np.matchIgnoreCase("replace=");
replace = np.getBoolean();
} else
replace = true;
np.matchIgnoreCase(";");
for (String name : getDoc().getSampleNames()) {
final File file = new File(directory, name + ".megan");
if (!replace && file.exists()) {
NotificationsInSwing.showWarning("File exists: " + file + ", won't replace");
} else {
try (Writer w = new BufferedWriter(new FileWriter(file))) {
Document newDocument = new Document();
newDocument.getMeganFile().setFile(file.getPath(), MeganFile.Type.MEGAN_SUMMARY_FILE);
newDocument.extractSamples(Collections.singleton(name), getDoc());
newDocument.setNumberReads(newDocument.getDataTable().getTotalReads());
System.err.println("Number of reads: " + newDocument.getNumberOfReads());
newDocument.processReadHits();
newDocument.setTopPercent(100);
newDocument.setMinScore(0);
newDocument.setMaxExpected(10000);
newDocument.setMinSupport(1);
newDocument.getDataTable().setParameters(newDocument.getParameterString());
newDocument.getDataTable().write(w);
newDocument.getSampleAttributeTable().write(w, false, true);
}
}
}
}
public void actionPerformed(ActionEvent event) {
if (getDoc().getMeganFile().hasDataConnector()) {
final File savedFile = ProgramProperties.getFile(MeganProperties.SAVEFILE);
final File directory = (savedFile != null ? savedFile.getParentFile() : null);
final File lastOpenFile = FileUtils.replaceFileSuffix(new File(directory, getDoc().getSampleNames().get(0)), ".megan");
final File file = ChooseFileDialog.chooseFileToSave(getViewer().getFrame(), lastOpenFile, new MeganFileFilter(), new MeganFileFilter(), event, "Extract MEGAN files", ".megan");
if (file != null) {
ProgramProperties.put(MeganProperties.SAVEFILE, file);
execute("extract directory='" + file.getParent() + "' replace=true;");
}
}
}
public boolean isApplicable() {
return getDoc().getNumberOfReads() > 0 && getDoc().getMeganFile().hasDataConnector();
}
public String getName() {
return "All Individual Samples...";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Export16.gif");
}
public String getDescription() {
return "Extract and export all contained samples as individual files";
}
public boolean isCritical() {
return true;
}
}
| 4,768 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExportReadsCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/export/ExportReadsCommand.java | /*
* ExportReadsCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.export;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ChooseFileDialog;
import jloda.swing.util.FastaFileFilter;
import jloda.swing.util.ResourceManager;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.FileUtils;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.classification.Classification;
import megan.classification.ClassificationManager;
import megan.commands.CommandBase;
import megan.core.ClassificationType;
import megan.core.Director;
import megan.core.Document;
import megan.dialogs.export.ReadsExporter;
import megan.dialogs.lrinspector.LRInspectorViewer;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
public class ExportReadsCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "export what=reads [data={" + StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), "|") + "}] file=<filename>;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("export what=reads");
final String data;
if (np.peekMatchIgnoreCase("data")) {
np.matchIgnoreCase("data=");
data = np.getWordMatchesRespectingCase(StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), " "));
} else
data = Classification.Taxonomy;
np.matchIgnoreCase("file=");
String outputFile = np.getAbsoluteFileName();
np.matchIgnoreCase(";");
final Director dir = getDir();
final Document doc = dir.getDocument();
long count;
if (getViewer() instanceof ClassificationViewer) {
final ClassificationViewer classificationViewer = (ClassificationViewer) dir.getViewerByClassName(data);
final Set<Integer> classIds = new HashSet<>();
if (classificationViewer != null)
classIds.addAll(classificationViewer.getSelectedNodeIds());
if (classIds.size() == 0)
count = ReadsExporter.exportAll(doc.getConnector(), outputFile, doc.getProgressListener());
else
count = ReadsExporter.export(data, classIds, doc.getConnector(), outputFile, doc.getProgressListener());
} else if (getViewer() instanceof LRInspectorViewer) {
count = ((LRInspectorViewer) getViewer()).exportSelectedReads(outputFile, doc.getProgressListener());
} else
count = 0;
NotificationsInSwing.showInformation(getViewer().getFrame(), "Wrote " + count + " reads to file: " + outputFile);
}
public boolean isApplicable() {
return getDoc().getMeganFile().hasDataConnector();
}
public boolean isCritical() {
return true;
}
public void actionPerformed(ActionEvent event) {
Director dir = getDir();
if (!dir.getDocument().getMeganFile().hasDataConnector())
return;
String name = FileUtils.replaceFileSuffix(dir.getDocument().getTitle(), "-ex.fasta");
File lastOpenFile = new File(name);
final File file = ChooseFileDialog.chooseFileToSave(getViewer().getFrame(), lastOpenFile, new FastaFileFilter(), new FastaFileFilter(), event, "Save all READs to file", ".fasta");
final String data;
if (getViewer() instanceof ClassificationViewer)
data = getViewer().getClassName();
else
data = ClassificationType.Taxonomy.toString();
if (file != null) {
execute("export what=reads data=" + data + " file='" + file.getPath() + "';");
}
}
public String getName() {
return "Reads...";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Export16.gif");
}
public String getDescription() {
return "Export reads to a text file";
}
}
| 4,800 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ComputeRareBiomeCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/algorithms/ComputeRareBiomeCommand.java | /*
* ComputeRareBiomeCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.algorithms;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.TwoInputOptionsPanel;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.NumberUtils;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.samplesviewer.SamplesViewer;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.Collection;
/**
* compute rea biome
* Daniel Huson, 2.2013
*/
public class ComputeRareBiomeCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
final Collection<String> samples;
if (getViewer() instanceof SamplesViewer)
samples = ((SamplesViewer) getViewer()).getSamplesTableView().getSelectedSamples();
else if (getViewer() instanceof ClassificationViewer)
samples = ((ClassificationViewer) getViewer()).getDocument().getSampleNames();
else
return;
if (samples.size() > 1) {
float sampleThresholdPercent = (float) ProgramProperties.get("RareBiomeSampleThreshold", 10.0);
float classThresholdPercent = (float) ProgramProperties.get("RareBiomeClassThreshold", 1.0);
final String[] result = TwoInputOptionsPanel.show(getViewer().getFrame(), "MEGAN - Setup Compute Rare Biome", "Sample threshold (%)", "" + sampleThresholdPercent,
"Maximum percent of samples in which class is present",
"Class threshold (%)", "" + classThresholdPercent, "Percentage of assigned reads in sample that class must achieve to be considered present in that sample");
if (result != null) {
if (NumberUtils.isFloat(result[0]) && NumberUtils.isFloat(result[1])) {
sampleThresholdPercent = NumberUtils.parseFloat(result[0]);
ProgramProperties.put("RareBiomeSampleThreshold", sampleThresholdPercent);
classThresholdPercent = NumberUtils.parseFloat(result[1]);
ProgramProperties.put("RareBiomeClassThreshold", classThresholdPercent);
execute("compute biome=rare classThreshold=" + result[1] + " sampleThreshold=" + result[0] + " samples='" + StringUtils.toString(samples, "' '") + "';");
} else
NotificationsInSwing.showError(getViewer().getFrame(), "Failed to parse values: " + StringUtils.toString(result, " "));
}
}
}
public boolean isApplicable() {
return getViewer() instanceof ClassificationViewer || getViewer() instanceof SamplesViewer && ((SamplesViewer) getViewer()).getSamplesTableView().getCountSelectedSamples() > 1;
}
public boolean isCritical() {
return true;
}
public String getName() {
return "Compute Rare Biome...";
}
public ImageIcon getIcon() {
return null;
}
public String getDescription() {
return "Determine taxa and functions that appear in a minority of samples";
}
}
| 3,976 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ReanalyzeFilesCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/algorithms/ReanalyzeFilesCommand.java | /*
* ReanalyzeFilesCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.algorithms;
import jloda.swing.commands.ICommand;
import jloda.swing.director.IDirector;
import jloda.swing.director.ProjectManager;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import jloda.util.progress.ProgressListener;
import jloda.util.progress.ProgressPercentage;
import megan.classification.ClassificationManager;
import megan.commands.CommandBase;
import megan.core.Director;
import megan.core.Document;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* reanalyze a set of files
* Daniel Huson, 12.2019
*/
public class ReanalyzeFilesCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "reanalyzeFiles file=<name> [,<name>...] [minSupportPercent=<number>] [minSupport=<number>] [minScore=<number>] [maxExpected=<number>] [minPercentIdentity=<number>]\n" +
"\t[topPercent=<number>] [minSupportPercent=<num>] [minSupport=<num>]\n" +
"\t[lcaAlgorithm={" + StringUtils.toString(Document.LCAAlgorithm.values(), "|") + "}] [lcaCoveragePercent=<number>] [minPercentReadToCover=<number>] [minPercentReferenceToCover=<number>]" +
" [minComplexity=<number>] [longReads={false|true}] [pairedReads={false|true}] [useIdentityFilter={false|true}]\n" +
"\t[useContaminantFilter={false|true}] [loadContaminantFile=<filename>]\n" +
"\t[readAssignmentMode={" + StringUtils.toString(Document.ReadAssignmentMode.values(), "|") + "} [fNames={" + StringUtils.toString(ClassificationManager.getAllSupportedClassificationsExcludingNCBITaxonomy(), "|") + "|*}];";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("reanalyzeFiles file=");
final ArrayList<String> files = new ArrayList<>();
files.add(np.getWordFileNamePunctuation());
while (np.peekMatchAnyTokenIgnoreCase(",")) {
np.matchIgnoreCase(",");
files.add(np.getWordFileNamePunctuation());
}
final ProgressListener progress = (getDoc() != null ? getDoc().getProgressListener() : new ProgressPercentage());
progress.setMaximum(files.size());
progress.setProgress(0);
final List<String> tokens = np.getTokensRespectCase(null, ";");
final String fNames = np.findIgnoreCase(tokens, "fName=", null, "*");
final boolean allFNames = (fNames.equals("*"));
final String recomputeParameters = StringUtils.toString(tokens, " ").replaceAll("fNames\\s*=.*", "");
for (String file : files) {
progress.setTasks("Reanalyzing", file);
{
final Director openDir = findOpenDirector(file);
if (openDir != null) {
NotificationsInSwing.showWarning("File '" + file + "' is currently open, cannot reanalyze open files");
continue;
}
}
NotificationsInSwing.showInformation("Reanalyzing file: " + file);
final Director dir = Director.newProject(false, true);
try {
final Document doc = dir.getDocument();
doc.setOpenDAAFileOnlyIfMeganized(false);
doc.getMeganFile().setFileFromExistingFile(file, false);
final String fNamesToUse = (allFNames ? StringUtils.toString(StringUtils.remove(doc.getConnector().getAllClassificationNames(), "Taxonomy"), " ") : fNames).trim();
final String recomputeCommand = "recompute " + recomputeParameters + (fNamesToUse.length() > 0 ? " fNames = " + fNamesToUse : "") + ";";
dir.getDocument().setProgressListener(getDoc().getProgressListener());
dir.executeImmediately(recomputeCommand, dir.getMainViewer().getCommandManager());
} finally {
dir.close();
}
progress.incrementProgress();
}
//getDir().close();
}
public void actionPerformed(ActionEvent event) {
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Reanalyze Files";
}
public String getDescription() {
return "Reanalyze files";
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return null;
}
public ImageIcon getIcon() {
return null;
}
/**
* get directory if this file is currently open
*
* @return directory
*/
private Director findOpenDirector(String daaFile) {
final File file = new File(daaFile);
if (file.isFile()) {
for (IDirector dir : ProjectManager.getProjects()) {
File aFile = new File(((Director) dir).getDocument().getMeganFile().getFileName());
if (aFile.isFile() && aFile.equals(file))
return (Director) dir;
}
}
return null;
}
}
| 5,856 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
RemoveLowAbundancesCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/algorithms/RemoveLowAbundancesCommand.java | /*
* RemoveLowAbundancesCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.algorithms;
import jloda.graph.Node;
import jloda.swing.commands.ICommand;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.*;
import jloda.util.parse.NexusStreamParser;
import jloda.util.progress.ProgressListener;
import megan.classification.Classification;
import megan.classification.ClassificationManager;
import megan.commands.CommandBase;
import megan.core.Director;
import megan.core.Document;
import megan.core.MeganFile;
import megan.main.MeganProperties;
import megan.samplesviewer.SamplesViewer;
import megan.viewer.ClassificationViewer;
import megan.viewer.TaxonomyData;
import megan.viewer.gui.NodeDrawer;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* compute robust biome
* Daniel Huson, 22022
*/
public class RemoveLowAbundancesCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "compute minAbundance=<threshold> samples=<name name...>;";
}
public void apply(NexusStreamParser np) throws Exception {
final var dir = getDir();
final var doc = dir.getDocument();
np.matchIgnoreCase("compute minAbundance=");
var threshold = (float) np.getDouble(0, 100);
final var legalSampleNames = "'" + StringUtils.toString(doc.getSampleNames(), "' '") + "' ALL";
final var selectedSamples = new ArrayList<String>();
np.matchIgnoreCase("samples=");
while (!np.peekMatchIgnoreCase(";")) {
selectedSamples.add(np.getWordMatchesRespectingCase(legalSampleNames));
}
np.matchIgnoreCase(";");
if (selectedSamples.contains("ALL")) {
selectedSamples.addAll(doc.getSampleNames());
}
System.err.println("Number of samples: " + selectedSamples.size());
var newDir = Director.newProject(false);
if (dir.getMainViewer() != null) {
newDir.getMainViewer().getFrame().setVisible(true);
newDir.getMainViewer().setDoReInduce(true);
newDir.getMainViewer().setDoReset(true);
}
final var newDocument = newDir.getDocument();
final var tarClassification2class2counts = new HashMap<String, Map<Integer, float[]>>();
var sampleSizes = removeLowAbundance(doc, selectedSamples, threshold, tarClassification2class2counts, doc.getProgressListener());
if (tarClassification2class2counts.size() > 0) {
for (var s = 0; s < selectedSamples.size(); s++) {
newDocument.getDataTable().addSample(selectedSamples.get(s), sampleSizes[s], doc.getDataTable().getBlastMode(), s, tarClassification2class2counts);
}
newDocument.getSampleAttributeTable().addTable(doc.getSampleAttributeTable().extractTable(selectedSamples), false, true);
newDocument.setNumberReads(newDocument.getDataTable().getTotalReads());
var fileName = FileUtils.replaceFileSuffix(doc.getMeganFile().getFileName(), "-min-" + threshold + ".megan");
newDocument.getMeganFile().setFile(fileName, MeganFile.Type.MEGAN_SUMMARY_FILE);
System.err.printf("Total number of reads: %,d%n", newDocument.getNumberOfReads());
newDocument.processReadHits();
newDocument.setTopPercent(100);
newDocument.setMinScore(0);
newDocument.setMaxExpected(10000);
newDocument.setMinSupport(1);
newDocument.setMinSupportPercent(0);
newDocument.setDirty(true);
for (var classificationName : newDocument.getDataTable().getClassification2Class2Counts().keySet()) {
newDocument.getActiveViewers().add(classificationName);
}
newDocument.getSampleAttributeTable().addTable(doc.getSampleAttributeTable().mergeSamples(selectedSamples, newDocument.getSampleNames().get(0)), false, true);
if (newDocument.getNumberOfSamples() > 1) {
newDir.getMainViewer().getNodeDrawer().setStyle(ProgramProperties.get(MeganProperties.COMPARISON_STYLE, ""), NodeDrawer.Style.PieChart);
}
NotificationsInSwing.showInformation("Filtered dataset has %,d reads".formatted(newDocument.getNumberOfReads()));
newDir.execute("update reprocess=true reinduce=true;", newDir.getMainViewer().getCommandManager());
}
}
public void actionPerformed(ActionEvent event) {
final Collection<String> samples;
if (getViewer() instanceof SamplesViewer)
samples = ((SamplesViewer) getViewer()).getSamplesTableView().getSelectedSamples();
else if (getViewer() instanceof ClassificationViewer)
samples = ((ClassificationViewer) getViewer()).getDocument().getSampleNames();
else
return;
if (samples.size() > 1) {
float classThresholdPercent = (float) ProgramProperties.get("LowAbundanceThreshold", 1.0);
var result = JOptionPane.showInputDialog(getViewer().getFrame(), "Minimum abundance threshold (%):", "MEGAN - Remove low abundance nodes", JOptionPane.QUESTION_MESSAGE, null, null, classThresholdPercent);
if (result instanceof String string && NumberUtils.isFloat(string)) {
classThresholdPercent = NumberUtils.parseFloat(string);
ProgramProperties.put("LowAbundanceThreshold", classThresholdPercent);
execute("compute minAbundance=" + result + " samples='" + StringUtils.toString(samples, "' '") + "';");
} else
NotificationsInSwing.showError(getViewer().getFrame(), "Failed to parse value: " + result);
}
}
public boolean isApplicable() {
return getViewer() instanceof ClassificationViewer || getViewer() instanceof SamplesViewer && ((SamplesViewer) getViewer()).getSamplesTableView().getCountSelectedSamples() > 1;
}
public boolean isCritical() {
return true;
}
public String getName() {
return "Remove Low Abundances...";
}
public ImageIcon getIcon() {
return null;
}
public String getDescription() {
return "Remove taxa and functions whose abundance lie below a given percentage of assigned reads for all samples";
}
/**
* compute a new comparison in which low abundance items have been removed
*
* @param srcDoc
* @param samplesToUse
* @param threshold
* @param tarClassification2class2counts
* @param progress
* @return low abundance version
* @throws CanceledException
*/
private int[] removeLowAbundance(Document srcDoc, ArrayList<String> samplesToUse, float threshold, HashMap<String, Map<Integer, float[]>> tarClassification2class2counts, ProgressListener progress) throws CanceledException {
var numberInputSamples = srcDoc.getNumberOfSamples();
var numberOutputSamples = samplesToUse.size();
final var sampleIds = srcDoc.getDataTable().getSampleIds(samplesToUse);
var input2outputId = new int[sampleIds.cardinality()];
var outId = 0;
for (var inId : BitSetUtils.members(sampleIds)) {
input2outputId[inId] = outId++;
}
final var sizes = new int[numberOutputSamples];
if (numberOutputSamples > 0) {
var dataTable = srcDoc.getDataTable();
for (var classificationName : dataTable.getClassification2Class2Counts().keySet()) {
final var srcClass2counts = srcDoc.getDataTable().getClass2Counts(classificationName);
final Node root;
if (classificationName.equals(Classification.Taxonomy))
root = TaxonomyData.getTree().getRoot();
else {
root = ClassificationManager.get(classificationName, true).getFullTree().getRoot();
}
final int[] detectionThresholds = ComputeCoreOrRareBiome.computeDetectionThreshold(classificationName, numberInputSamples, srcClass2counts, threshold);
var tarClass2counts = new HashMap<Integer, float[]>();
if (true) {
var coreClass2counts = new HashMap<Integer, float[]>();
ComputeCoreOrRareBiome.computeCoreBiomeRec(sampleIds, false, srcDoc.getNumberOfSamples(), 0, detectionThresholds, root, srcClass2counts, coreClass2counts, progress);
for (var classId : coreClass2counts.keySet()) {
var value = coreClass2counts.get(classId)[0];
if (value > 0) {
var srcCounts = srcClass2counts.get(classId);
var tarCounts = new float[numberOutputSamples];
var outS = 0;
for (var inS : BitSetUtils.members(sampleIds)) {
tarCounts[outS++] = srcCounts[inS];
}
tarClass2counts.put(classId, tarCounts);
}
}
} else {
for (var s : BitSetUtils.members(sampleIds)) {
var tmpClass2counts = new HashMap<Integer, float[]>();
ComputeCoreOrRareBiome.computeCoreBiomeRec(BitSetUtils.asBitSet(s), false, srcDoc.getNumberOfSamples(), 0, detectionThresholds, root, srcClass2counts, tmpClass2counts, progress);
for (var classId : tmpClass2counts.keySet()) {
var value = tmpClass2counts.get(classId)[0];
var array = tarClass2counts.computeIfAbsent(classId, a -> new float[numberOutputSamples]);
array[input2outputId[s]] = value;
}
}
}
tarClassification2class2counts.put(classificationName, tarClass2counts);
if (classificationName.equals(Classification.Taxonomy)) {
for (var counts : tarClass2counts.values()) {
for (var i = 0; i < counts.length; i++) {
sizes[i] += counts[i];
}
}
}
}
}
return sizes;
}
}
| 9,714 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ComputeTotalBiomeCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/algorithms/ComputeTotalBiomeCommand.java | /*
* ComputeTotalBiomeCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.algorithms;
import jloda.swing.commands.ICommand;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.samplesviewer.SamplesViewer;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.Collection;
/**
* compute biome
* Daniel Huson, 2.2013
*/
public class ComputeTotalBiomeCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
final Collection<String> samples;
if (getViewer() instanceof SamplesViewer)
samples = ((SamplesViewer) getViewer()).getSamplesTableView().getSelectedSamples();
else if (getViewer() instanceof ClassificationViewer)
samples = ((ClassificationViewer) getViewer()).getDocument().getSampleNames();
else
return;
if (samples.size() > 1) {
execute("compute biome=total samples='" + StringUtils.toString(samples, "' '") + "';");
}
}
public boolean isApplicable() {
return getViewer() instanceof ClassificationViewer || getViewer() instanceof SamplesViewer && ((SamplesViewer) getViewer()).getSamplesTableView().getCountSelectedSamples() > 1;
}
public boolean isCritical() {
return true;
}
public String getName() {
return "Compute Total Biome...";
}
public ImageIcon getIcon() {
return null;
}
public String getDescription() {
return "Determine total (union) taxonomic and functional content";
}
}
| 2,538 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
RecomputeCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/algorithms/RecomputeCommand.java | /*
* RecomputeCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.algorithms;
import jloda.swing.commands.ICommand;
import jloda.swing.director.IDirectableViewer;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.Basic;
import jloda.util.CanceledException;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.classification.Classification;
import megan.classification.ClassificationManager;
import megan.commands.CommandBase;
import megan.core.ContaminantManager;
import megan.core.Document;
import megan.dialogs.lrinspector.LRInspectorViewer;
import megan.inspector.InspectorWindow;
import megan.viewer.MainViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
/**
* rerun LCA algorithm
* Daniel Huson, 2010?
*/
public class RecomputeCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "recompute [minScore=<number>] [maxExpected=<number>] [minPercentIdentity=<number>] [topPercent=<number>] [minSupportPercent=<number>] [minSupport=<number>]\n" +
"\t[lcaAlgorithm={" + StringUtils.toString(Document.LCAAlgorithm.values(), "|") + "}] [lcaCoveragePercent=<number>] [minPercentReadToCover=<number>] [minPercentReferenceToCover=<number>]" +
" [minComplexity=<number>] [longReads={false|true}] [pairedReads={false|true}] [useIdentityFilter={false|true}]\n" +
"\t[useContaminantFilter={false|true}] [loadContaminantFile=<filename>]\n" +
"\t[readAssignmentMode={" + StringUtils.toString(Document.ReadAssignmentMode.values(), "|") + "} [fNames={" + StringUtils.toString(ClassificationManager.getAllSupportedClassificationsExcludingNCBITaxonomy(), "|") + "];";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("recompute");
if (np.peekMatchIgnoreCase("minScore")) {
np.matchIgnoreCase("minScore=");
getDoc().setMinScore((float) np.getDouble(0, Float.MAX_VALUE));
}
if (np.peekMatchIgnoreCase("maxExpected")) {
np.matchIgnoreCase("maxExpected=");
getDoc().setMaxExpected((float) np.getDouble(0, Float.MAX_VALUE));
}
if (np.peekMatchIgnoreCase("minPercentIdentity")) {
np.matchIgnoreCase("minPercentIdentity=");
getDoc().setMinPercentIdentity((float) np.getDouble(0, 100));
}
if (np.peekMatchIgnoreCase("topPercent")) {
np.matchIgnoreCase("topPercent=");
getDoc().setTopPercent((float) np.getDouble(0, Float.MAX_VALUE));
}
if (np.peekMatchIgnoreCase("minSupportPercent")) {
np.matchIgnoreCase("minSupportPercent=");
getDoc().setMinSupportPercent((float) np.getDouble(0, 100));
}
if (np.peekMatchIgnoreCase("minSupport")) {
np.matchIgnoreCase("minSupport=");
getDoc().setMinSupport(np.getInt(1, Integer.MAX_VALUE));
}
if (np.peekMatchIgnoreCase("weightedLCA")) { // legacy
np.matchIgnoreCase("weightedLCA=");
getDoc().setLcaAlgorithm(Document.LCAAlgorithm.weighted);
} else if (np.peekMatchIgnoreCase("lcaAlgorithm")) {
np.matchIgnoreCase("lcaAlgorithm=");
getDoc().setLcaAlgorithm(Document.LCAAlgorithm.valueOfIgnoreCase(np.getWordRespectCase()));
}
if (np.peekMatchAnyTokenIgnoreCase("lcaCoveragePercent weightedLCAPercent")) {
np.matchAnyTokenIgnoreCase("lcaCoveragePercent weightedLCAPercent");
np.matchIgnoreCase("=");
getDoc().setLcaCoveragePercent((float) np.getDouble(1, 100));
}
if (np.peekMatchIgnoreCase("minPercentReadToCover")) {
np.matchIgnoreCase("minPercentReadToCover=");
getDoc().setMinPercentReadToCover((float) np.getDouble(0, 100));
}
if (np.peekMatchIgnoreCase("minPercentReferenceToCover")) {
np.matchIgnoreCase("minPercentReferenceToCover=");
getDoc().setMinPercentReferenceToCover((float) np.getDouble(0, 100));
}
if (np.peekMatchIgnoreCase("minComplexity")) {
np.matchIgnoreCase("minComplexity=");
getDoc().setMinComplexity((float) np.getDouble(-1.0, 1.0));
}
if (np.peekMatchIgnoreCase("minReadLength")) {
np.matchIgnoreCase("minReadLength=");
getDoc().setMinReadLength(np.getInt(0,Integer.MAX_VALUE));
}
if (np.peekMatchIgnoreCase("longReads")) {
np.matchIgnoreCase("longReads=");
getDoc().setLongReads(np.getBoolean());
}
if (np.peekMatchIgnoreCase("pairedReads")) {
np.matchIgnoreCase("pairedReads=");
getDoc().setPairedReads(np.getBoolean());
}
if (np.peekMatchIgnoreCase("useIdentityFilter")) {
np.matchIgnoreCase("useIdentityFilter=");
getDoc().setUseIdentityFilter(np.getBoolean());
}
if (np.peekMatchIgnoreCase("useContaminantFilter")) {
np.matchIgnoreCase("useContaminantFilter=");
getDoc().setUseContaminantFilter(np.getBoolean());
} else
getDoc().setUseContaminantFilter(false);
if (np.peekMatchIgnoreCase("loadContaminantFile")) {
np.matchIgnoreCase("loadContaminantFile=");
final String fileName = np.getWordFileNamePunctuation();
final ContaminantManager contaminantManager = new ContaminantManager();
System.err.println("Loading contaminant file: " + fileName);
contaminantManager.read(fileName);
System.err.println("Contaminants: " + contaminantManager.inputSize());
getDoc().getDataTable().setContaminants(contaminantManager.getTaxonIdsString());
getDoc().setUseContaminantFilter(true);
}
if (np.peekMatchIgnoreCase("readAssignmentMode")) {
np.matchIgnoreCase("readAssignmentMode=");
getDoc().setReadAssignmentMode(Document.ReadAssignmentMode.valueOfIgnoreCase(np.getWordMatchesIgnoringCase(StringUtils.toString(Document.ReadAssignmentMode.values(), " "))));
}
if (np.peekMatchIgnoreCase("fNames")) {
getDoc().getActiveViewers().clear();
getDoc().getActiveViewers().add(Classification.Taxonomy);
np.matchIgnoreCase("fNames=");
while (!np.peekMatchIgnoreCase(";")) {
final String cName = np.getWordRespectCase();
if (ClassificationManager.getAllSupportedClassificationsExcludingNCBITaxonomy().contains(cName))
getDoc().getActiveViewers().add(cName);
else
System.err.println("Warning: Unknown classification: " + cName);
}
}
np.matchIgnoreCase(";");
final InspectorWindow inspectorWindow = (InspectorWindow) getDir().getViewerByClass(InspectorWindow.class);
if (inspectorWindow != null && inspectorWindow.getDataTree().getRowCount() > 1) {
SwingUtilities.invokeLater(inspectorWindow::clear);
}
final ArrayList<LRInspectorViewer> toClose = new ArrayList<>();
for (IDirectableViewer viewer : getDir().getViewers()) {
if (viewer instanceof LRInspectorViewer)
toClose.add((LRInspectorViewer) viewer);
}
for (final IDirectableViewer viewer : toClose) {
SwingUtilities.invokeLater(() -> {
try {
viewer.destroyView();
} catch (CanceledException e) {
Basic.caught(e);
}
});
}
getDoc().processReadHits();
getDoc().setDirty(true);
if (getViewer() instanceof MainViewer)
((MainViewer) getViewer()).setDoReInduce(true);
NotificationsInSwing.showInformation(String.format("Classified %,d reads", +getDoc().getNumberOfReads()));
}
public void actionPerformed(ActionEvent event) {
}
public boolean isApplicable() {
Document doc = getDoc();
return !doc.getMeganFile().isReadOnly() && doc.getMeganFile().hasDataConnector() && !doc.getMeganFile().isMeganSummaryFile();
}
public String getName() {
return null;
}
public String getDescription() {
return "Rerun the LCA analysis with different parameters";
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return null;
}
public ImageIcon getIcon() {
return null;
}
}
| 9,336 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ComputeCoreBiomeCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/algorithms/ComputeCoreBiomeCommand.java | /*
* ComputeCoreBiomeCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.algorithms;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.TwoInputOptionsPanel;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.NumberUtils;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.samplesviewer.SamplesViewer;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.Collection;
/**
* compute biome
* Daniel Huson, 2.2013, 7.2016
*/
public class ComputeCoreBiomeCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public boolean isCritical() {
return true;
}
public void actionPerformed(ActionEvent event) {
final Collection<String> samples;
if (getViewer() instanceof SamplesViewer)
samples = ((SamplesViewer) getViewer()).getSamplesTableView().getSelectedSamples();
else if (getViewer() instanceof ClassificationViewer)
samples = ((ClassificationViewer) getViewer()).getDocument().getSampleNames();
else
return;
if (samples.size() > 1) {
float sampleThresholdPercent = (float) ProgramProperties.get("CoreBiomeSampleThreshold", 50.0);
float classThresholdPercent = (float) ProgramProperties.get("CoreBiomeClassThreshold", 1.0);
final String[] result = TwoInputOptionsPanel.show(getViewer().getFrame(), "MEGAN - Setup Compute Core Biome", "Sample threshold (%)", "" + sampleThresholdPercent,
"Minimum percent of samples in which class must be present",
"Class threshold (%)", "" + classThresholdPercent, "Percentage of assigned reads in sample that class must achieve to be considered present in that sample");
if (result != null) {
if (NumberUtils.isFloat(result[0]) && NumberUtils.isFloat(result[1])) {
sampleThresholdPercent = NumberUtils.parseFloat(result[0]);
ProgramProperties.put("CoreBiomeSampleThreshold", sampleThresholdPercent);
classThresholdPercent = NumberUtils.parseFloat(result[1]);
ProgramProperties.put("CoreBiomeClassThreshold", classThresholdPercent);
execute("compute biome=core classThreshold=" + result[1] + " sampleThreshold=" + result[0] + " samples='" + StringUtils.toString(samples, "' '") + "';");
} else
NotificationsInSwing.showError(getViewer().getFrame(), "Failed to parse values: " + StringUtils.toString(result, " "));
}
}
}
public boolean isApplicable() {
return (getViewer() instanceof ClassificationViewer && ((ClassificationViewer) getViewer()).getDocument().getNumberOfSamples() > 1) || (getViewer() instanceof SamplesViewer && ((SamplesViewer) getViewer()).getSamplesTableView().getCountSelectedSamples() > 1);
}
public String getName() {
return "Compute Core Biome...";
}
public ImageIcon getIcon() {
return null;
}
public String getDescription() {
return "Determine taxa and functions that appear in a majority of the samples";
}
}
| 4,071 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ComputeCoreOrRareBiome.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/algorithms/ComputeCoreOrRareBiome.java | /*
* ComputeCoreOrRareBiome.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.algorithms;
import jloda.graph.Edge;
import jloda.graph.Node;
import jloda.util.CanceledException;
import jloda.util.progress.ProgressListener;
import megan.classification.Classification;
import megan.classification.ClassificationManager;
import megan.core.ClassificationType;
import megan.core.DataTable;
import megan.core.Document;
import megan.viewer.TaxonomyData;
import java.util.BitSet;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* computes the core or rare biome for a set of samples
* Reads summarized by a node are used to decide whether to keep node, reads assigned to node are used as counts
* Daniel Huson, 2.2013
*/
public class ComputeCoreOrRareBiome {
/**
* computes core biome for a given threshold
*
* @param asUpperBound if true, keep rare taxa in which the sample threshold is an upper bound
* @param samplesThreshold number of samples that must contain a taxon so that it appears in the output, or max, if asUpperBound is true
* @return sampleSize
*/
public static int apply(Document srcDoc, Collection<String> samplesToUse, boolean asUpperBound, int samplesThreshold,
float taxonDetectionThresholdPercent, Map<String, Map<Integer, float[]>> tarClassification2class2counts, ProgressListener progress) throws CanceledException {
final BitSet sampleIds = srcDoc.getDataTable().getSampleIds(samplesToUse);
int size = 0;
if (sampleIds.cardinality() > 0) {
DataTable dataTable = srcDoc.getDataTable();
for (String classificationName : dataTable.getClassification2Class2Counts().keySet()) {
final Map<Integer, float[]> srcClass2counts = srcDoc.getDataTable().getClass2Counts(classificationName);
final Node root;
if (classificationName.equals(Classification.Taxonomy))
root = TaxonomyData.getTree().getRoot();
else {
root = ClassificationManager.get(classificationName, true).getFullTree().getRoot();
}
final Map<Integer, float[]> tarClass2counts = new HashMap<>();
tarClassification2class2counts.put(classificationName, tarClass2counts);
final int[] detectionThreshold = computeDetectionThreshold(classificationName, srcDoc.getNumberOfSamples(), srcClass2counts, taxonDetectionThresholdPercent);
computeCoreBiomeRec(sampleIds, asUpperBound, srcDoc.getNumberOfSamples(), samplesThreshold, detectionThreshold, root, srcClass2counts, tarClass2counts, progress);
// System.err.println(classificationName + ": " + tarClassification2class2counts.size());
}
final Map<Integer, float[]> taxId2counts = tarClassification2class2counts.get(ClassificationType.Taxonomy.toString());
if (taxId2counts != null) {
for (Integer taxId : taxId2counts.keySet()) {
if (taxId >= 0) {
float[] values = taxId2counts.get(taxId);
size += values[0];
}
}
}
if (size == 0) {
for (String classificationName : dataTable.getClassification2Class2Counts().keySet()) {
if (!classificationName.equals(ClassificationType.Taxonomy.toString())) {
final Map<Integer, float[]> id2counts = tarClassification2class2counts.get(classificationName);
if (id2counts != null) {
for (Integer ids : id2counts.keySet()) {
final float[] values = id2counts.get(ids);
if (ids >= 0)
size += values[0];
}
if (size > 0)
break;
}
}
}
}
}
return size;
}
/**
* determines the number of counts necessary for a taxon to be considered detected, for each sample
*
* @return thresholds
*/
static int[] computeDetectionThreshold(String classificationName, int numberOfSamples, Map<Integer, float[]> srcClass2counts, float detectionThresholdPercent) {
final int[] array = new int[numberOfSamples];
if (detectionThresholdPercent > 0) {
for (Integer id : srcClass2counts.keySet()) {
if (id > 0) {
final float[] counts = srcClass2counts.get(id);
if (counts != null) {
for (int i = 0; i < counts.length; i++) {
array[i] += counts[i];
}
}
}
}
for (int i = 0; i < array.length; i++) {
array[i] *= detectionThresholdPercent / 100.0;
}
System.err.println("Read detection thresholds for " + classificationName + ":");
for (float value : array) {
System.err.printf(" %,12.0f", value);
}
System.err.println();
}
for (int i = 0; i < array.length; i++) { // need at least 1 to detect
array[i] = Math.max(1, array[i]);
}
return array;
}
/**
* recursively compute the core biome
*
*/
static float[] computeCoreBiomeRec(BitSet sampleIds, boolean asUpperBound, int numberOfSamples, int samplesThreshold, int[] detectionThreshold,
Node v, Map<Integer, float[]> srcClass2counts, Map<Integer, float[]> tarClass2counts, ProgressListener progress) throws CanceledException {
final float[] summarized = new float[numberOfSamples];
final int classId = (Integer) v.getInfo();
if (classId == -1 || classId == -2 || classId == -3)
return summarized; // ignore unassigned etc
final float[] countsV = srcClass2counts.get(classId);
if (countsV != null) {
for (int i = 0; i < countsV.length; i++) {
if (sampleIds.get(i))
summarized[i] = countsV[i];
}
}
for (Edge e = v.getFirstOutEdge(); e != null; e = v.getNextOutEdge(e)) {
final Node w = e.getTarget();
final float[] countsBelow = computeCoreBiomeRec(sampleIds, asUpperBound, numberOfSamples, samplesThreshold, detectionThreshold, w, srcClass2counts, tarClass2counts, progress);
for (int i = 0; i < numberOfSamples; i++) {
if (sampleIds.get(i)) {
summarized[i] += countsBelow[i];
}
}
}
int numberOfSamplesWithClass = 0;
int value = 0;
for (int i = 0; i < numberOfSamples; i++) {
if (sampleIds.get(i)) {
if (summarized[i] >= detectionThreshold[i])
numberOfSamplesWithClass++;
if (countsV != null && i < countsV.length && sampleIds.get(i))
value += countsV[i];
}
}
if (countsV != null && numberOfSamplesWithClass > 0 && ((!asUpperBound && numberOfSamplesWithClass >= samplesThreshold) || (asUpperBound && numberOfSamplesWithClass <= samplesThreshold))) {
tarClass2counts.put(classId, new float[]{value});
}
progress.checkForCancel();
return summarized;
}
}
| 8,408 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ComputeBiomeCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/algorithms/ComputeBiomeCommand.java | /*
* ComputeBiomeCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.algorithms;
import jloda.seq.BlastMode;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ProgramProperties;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.FileUtils;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.core.Director;
import megan.core.Document;
import megan.core.MeganFile;
import megan.main.MeganProperties;
import megan.viewer.gui.NodeDrawer;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* compute biome
* Daniel Huson, 2.2013
*/
public class ComputeBiomeCommand extends CommandBase implements ICommand {
private Director newDir;
public String getSyntax() {
return "compute biome={core|total|rare} [classThreshold=<percentage>] [sampleThreshold=<percentage>] samples=<name name...>;";
}
public void apply(NexusStreamParser np) throws Exception {
final Director dir = getDir();
final Document doc = dir.getDocument();
np.matchIgnoreCase("compute biome=");
final String what = np.getWordMatchesIgnoringCase("core total rare");
final float classThreshold;
if (np.peekMatchIgnoreCase("classThreshold")) {
np.matchIgnoreCase("classThreshold=");
classThreshold = (float) np.getDouble(0, 100);
} else
classThreshold = 1;
final float samplesThreshold;
if (np.peekMatchIgnoreCase("sampleThreshold")) {
np.matchIgnoreCase("sampleThreshold=");
samplesThreshold = (float) np.getDouble(0, 100);
} else
samplesThreshold = 50;
final String legalSampleNames = "'" + StringUtils.toString(doc.getSampleNames(), "' '") + "' ALL";
final Set<String> selectedSamples = new HashSet<>();
np.matchIgnoreCase("samples=");
while (!np.peekMatchIgnoreCase(";")) {
selectedSamples.add(np.getWordMatchesRespectingCase(legalSampleNames));
}
np.matchIgnoreCase(";");
if (selectedSamples.contains("ALL")) {
selectedSamples.addAll(doc.getSampleNames());
}
System.err.println("Number of samples: " + selectedSamples.size());
newDir = Director.newProject(false);
if (dir.getMainViewer() != null) {
newDir.getMainViewer().getFrame().setVisible(true);
newDir.getMainViewer().setDoReInduce(true);
newDir.getMainViewer().setDoReset(true);
}
final Document newDocument = newDir.getDocument();
final Map<String, Map<Integer, float[]>> classification2class2counts = new HashMap<>();
int sampleSize = 0;
String title = null;
if (what.equalsIgnoreCase("core")) {
int minSamplesToHave = (int) Math.ceil((samplesThreshold / 100.0) * selectedSamples.size());
sampleSize = ComputeCoreOrRareBiome.apply(doc, selectedSamples, false, minSamplesToHave, classThreshold, classification2class2counts, doc.getProgressListener());
title = "CoreBiome-%s-%s".formatted(StringUtils.removeTrailingZerosAfterDot(samplesThreshold), StringUtils.removeTrailingZerosAfterDot(classThreshold));
} else if (what.equalsIgnoreCase("rare")) {
int minSamplesNotToHave = (int) Math.ceil((samplesThreshold / 100.0) * selectedSamples.size());
sampleSize = ComputeCoreOrRareBiome.apply(doc, selectedSamples, true, minSamplesNotToHave, classThreshold, classification2class2counts, doc.getProgressListener());
title = "RareBiome-%s-%s".formatted(StringUtils.removeTrailingZerosAfterDot(samplesThreshold), StringUtils.removeTrailingZerosAfterDot(classThreshold));
} else if (what.equalsIgnoreCase("total")) {
sampleSize = ComputeCoreOrRareBiome.apply(doc, selectedSamples, false, 0, classThreshold, classification2class2counts, doc.getProgressListener());
title = "TotalBiome";
}
if (classification2class2counts.size() > 0) {
newDocument.addSample(title, sampleSize, 0, BlastMode.Unknown, classification2class2counts);
newDocument.setNumberReads(newDocument.getDataTable().getTotalReads());
String fileName = FileUtils.replaceFileSuffix(doc.getMeganFile().getFileName(), "-" + title + ".megan");
newDocument.getMeganFile().setFile(fileName, MeganFile.Type.MEGAN_SUMMARY_FILE);
System.err.println("Number of reads: " + newDocument.getNumberOfReads());
newDocument.processReadHits();
newDocument.setTopPercent(100);
newDocument.setMinScore(0);
newDocument.setMaxExpected(10000);
newDocument.setMinSupport(1);
newDocument.setMinSupportPercent(0);
newDocument.setDirty(true);
for (String classificationName : newDocument.getDataTable().getClassification2Class2Counts().keySet()) {
newDocument.getActiveViewers().add(classificationName);
}
newDocument.getSampleAttributeTable().addTable(doc.getSampleAttributeTable().mergeSamples(selectedSamples, newDocument.getSampleNames().get(0)), false, true);
if (newDocument.getNumberOfSamples() > 1) {
newDir.getMainViewer().getNodeDrawer().setStyle(ProgramProperties.get(MeganProperties.COMPARISON_STYLE, ""), NodeDrawer.Style.PieChart);
}
NotificationsInSwing.showInformation(String.format(StringUtils.capitalizeFirstLetter(what) + " biome has %,d reads", newDocument.getNumberOfReads()));
newDir.execute("update reprocess=true reinduce=true;", newDir.getMainViewer().getCommandManager());
}
}
public boolean isApplicable() {
return false;
}
public boolean isCritical() {
return true;
}
public void actionPerformed(ActionEvent event) {
}
public String getName() {
return "Compute Core Biome...";
}
public ImageIcon getIcon() {
return null;
}
public String getDescription() {
return "Compute the core biome for a set of samples";
}
/**
* gets the new director created by running this command
*
* @return new dir
*/
public Director getNewDir() {
return newDir;
}
}
| 7,189 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetFirstWordIsAccessionCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/preferences/SetFirstWordIsAccessionCommand.java | /*
* SetFirstWordIsAccessionCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.preferences;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.classification.IdParser;
import megan.commands.CommandBase;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class SetFirstWordIsAccessionCommand extends CommandBase implements ICheckBoxCommand {
@Override
public boolean isSelected() {
return ProgramProperties.get(IdParser.PROPERTIES_FIRST_WORD_IS_ACCESSION, true);
}
public String getSyntax() {
return "set firstWordIsAccession={true|false};";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set firstWordIsAccession=");
boolean state = np.getBoolean();
np.matchIgnoreCase(";");
ProgramProperties.put(IdParser.PROPERTIES_FIRST_WORD_IS_ACCESSION, state);
}
public void actionPerformed(ActionEvent event) {
executeImmediately("set firstWordIsAccession=" + (!isSelected()) + ";");
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "First Word Is Accession";
}
public String getDescription() {
return "Parse first word of reference header-line as accession number in accordance with 2016 NCBI formatting";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Preferences16.gif");
}
public boolean isCritical() {
return true;
}
}
| 2,403 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
FullScreenModeCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/preferences/FullScreenModeCommand.java | /*
* FullScreenModeCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.preferences;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
public class FullScreenModeCommand extends CommandBase implements ICheckBoxCommand {
private static final GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[0];
@Override
public boolean isSelected() {
return isApplicable() && device.getFullScreenWindow() == getViewer().getFrame();
}
public String getSyntax() {
return "set fullScreen={false|true};";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set fullScreen=");
boolean state = np.getBoolean();
np.matchIgnoreCase(";");
JFrame frame = (state ? getViewer().getFrame() : null);
device.setFullScreenWindow(frame);
}
public void actionPerformed(ActionEvent event) {
executeImmediately("set fullScreen=" + (!isSelected()) + ";");
}
public boolean isApplicable() {
return getViewer() != null && device.isFullScreenSupported();
}
public String getName() {
return "Full Screen Mode";
}
public String getDescription() {
return "Full Screen Mode";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("FullScreen16.gif");
}
public boolean isCritical() {
return false;
}
}
| 2,392 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowNotificationsCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/preferences/ShowNotificationsCommand.java | /*
* ShowNotificationsCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.preferences;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
public class ShowNotificationsCommand extends CommandBase implements ICheckBoxCommand {
private static final GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[0];
@Override
public boolean isSelected() {
return NotificationsInSwing.isShowNotifications();
}
public String getSyntax() {
return "set showNotifications={true|false};";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set showNotifications=");
boolean state = np.getBoolean();
np.matchIgnoreCase(";");
NotificationsInSwing.setShowNotifications(state);
}
public void actionPerformed(ActionEvent event) {
executeImmediately("set showNotifications=" + (!NotificationsInSwing.isShowNotifications()) + ";");
}
public boolean isApplicable() {
return getViewer() != null && device.isFullScreenSupported();
}
public String getName() {
return "Show Notifications";
}
public String getDescription() {
return "Show notifications";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Preferences16.gif");
}
public boolean isCritical() {
return false;
}
}
| 2,428 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetAccessionTagsCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/preferences/SetAccessionTagsCommand.java | /*
* SetAccessionTagsCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.preferences;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.classification.IdParser;
import megan.commands.CommandBase;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class SetAccessionTagsCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "set accessionTags=<word ...>;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set accessionTags=");
String[] tags = np.getWordRespectCase().split("\\s+");
np.matchIgnoreCase(";");
ProgramProperties.put(IdParser.PROPERTIES_ACCESSION_TAGS, tags);
}
public void actionPerformed(ActionEvent event) {
String[] tags = ProgramProperties.get(IdParser.PROPERTIES_ACCESSION_TAGS, IdParser.ACCESSION_TAGS);
String result = JOptionPane.showInputDialog(getViewer().getFrame(), "Enter tag(s) for identifying accession numbers (separated by spaces):", StringUtils.toString(tags, " "));
if (result != null)
executeImmediately("set accessionTags='" + result + "';");
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Set Accession Tags";
}
public String getDescription() {
return "Set tags used to identify accession numbers";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Preferences16.gif");
}
public boolean isCritical() {
return true;
}
}
| 2,489 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ZoomToFullCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/zoom/ZoomToFullCommand.java | /*
* ZoomToFullCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.zoom;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.viewer.ViewerBase;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* zoom to full
* Daniel Huson, 2005
*/
public class ZoomToFullCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "zoom what={fit|full|selection}";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("zoom what=");
final String what = np.getWordMatchesIgnoringCase("fit full selected");
np.matchIgnoreCase(";");
if (getViewer() instanceof ViewerBase) {
final ViewerBase viewer = (ViewerBase) getViewer();
if (what.equalsIgnoreCase("fit")) {
viewer.fitGraphToWindow();
//viewer.trans.setScaleY(0.14); // no idea why this was here...
} else if (what.equalsIgnoreCase("full")) {
viewer.fitGraphToWindow();
viewer.trans.setScaleY(1);
} else { // selection
viewer.zoomToSelection();
}
}
}
public void actionPerformed(ActionEvent event) {
executeImmediately("zoom what=full;");
}
public String getName() {
return "Fully Expand";
}
public String getDescription() {
return "Expand tree";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/AlignJustifyVertical16.gif");
}
public boolean isApplicable() {
return getViewer() instanceof ViewerBase;
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,753 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ZoomToSelectionCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/zoom/ZoomToSelectionCommand.java | /*
* ZoomToSelectionCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.zoom;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.viewer.ViewerBase;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* zoom to selection
* Daniel Huson, 2005
*/
public class ZoomToSelectionCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
@Override
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
executeImmediately("zoom what=selected;");
}
public boolean isApplicable() {
return getViewer() instanceof ViewerBase && ((ViewerBase) getViewer()).getSelectedNodes().size() > 0;
}
public String getName() {
return "Zoom To Selection";
}
public String getDescription() {
return "Zoom to the selection";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/AlignCenter16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
@Override
public boolean isCritical() {
return true;
}
}
| 2,140 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ZoomToFitCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/zoom/ZoomToFitCommand.java | /*
* ZoomToFitCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.zoom;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.viewer.ViewerBase;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* zoom to fit
* Daniel Huson, 2005
*/
public class ZoomToFitCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
@Override
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
executeImmediately("zoom what=fit;");
}
public String getName() {
return "Fully Contract";
}
public String getDescription() {
return "Contract tree vertically";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/AlignJustifyHorizontal16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
@Override
public boolean isCritical() {
return true;
}
@Override
public boolean isApplicable() {
return getViewer() instanceof ViewerBase;
}
}
| 2,082 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
RunBlastOnNCBICommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/additional/RunBlastOnNCBICommand.java | /*
* RunBlastOnNCBICommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.additional;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import jloda.seq.FastAFileIterator;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.director.IDirector;
import jloda.swing.util.ChooseFileDialog;
import jloda.swing.util.ProgressDialog;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.*;
import jloda.util.parse.NexusStreamParser;
import megan.blastclient.BlastService;
import megan.blastclient.RemoteBlastClient;
import megan.blastclient.RemoteBlastDialog;
import megan.core.Director;
import megan.core.Document;
import megan.importblast.ImportBlastDialog;
import megan.util.IReadsProvider;
import megan.util.MeganFileFilter;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
/**
* analyse a sequence on NCBI
* Daniel Huson, 3/2017
*/
public class RunBlastOnNCBICommand extends CommandBase implements ICommand {
private static BlastService blastService;
private static boolean serviceIsRunning = false;
public String getSyntax() {
return "remoteBlastNCBI readsFile=<file-name> [longReads={false|true}] [blastMode={blastn|blastx|blastp}] [blastDB={nr|<name>}];";
}
/**
* apply the command
*/
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("remoteBlastNCBI readsFile=");
final File readsFile = new File(np.getWordFileNamePunctuation());
final boolean longReads;
if (np.peekMatchIgnoreCase("longReads")) {
np.matchIgnoreCase("longReads=");
longReads = np.getBoolean();
} else
longReads = false;
final String blastMode;
if (np.peekMatchIgnoreCase("blastMode")) {
np.matchIgnoreCase("blastMode=");
blastMode = np.getWordMatchesIgnoringCase(StringUtils.toString(RemoteBlastClient.BlastProgram.values(), " "));
} else
blastMode = "blastn";
final String blastDB;
if (np.peekMatchIgnoreCase("blastDB")) {
np.matchIgnoreCase("blastDB=");
blastDB = np.getWordMatchesIgnoringCase(StringUtils.toString(RemoteBlastClient.getDatabaseNames(blastMode), " "));
} else
blastDB = "nr";
np.matchIgnoreCase(";");
getDir().notifyLockInput();
if (blastService == null) {
blastService = new BlastService();
}
if (serviceIsRunning && ProgramProperties.isUseGUI()) {
if (JOptionPane.showConfirmDialog(getViewer().getFrame(), "A remote BLAST is currently running, kill it?", "Kill current remote job?", JOptionPane.YES_NO_CANCEL_OPTION) != JOptionPane.YES_OPTION) {
getDir().executeImmediately("close what=current;", ((Director) getDir()).getCommandManager());
return;
}
}
blastService.setProgram(RemoteBlastClient.BlastProgram.valueOf(blastMode));
final ArrayList<Pair<String, String>> queries = new ArrayList<>();
try (FastAFileIterator it = new FastAFileIterator(readsFile.getPath())) {
while (it.hasNext()) {
queries.add(it.next());
}
}
blastService.setQueries(queries);
blastService.setDatabase(blastDB);
final Document doc = ((Director) getDir()).getDocument();
doc.setProgressListener(new ProgressDialog("Blasting at NCBI", "Running", getViewer().getFrame()));
doc.getProgressListener().setMaximum(1000);
final ChangeListener<Number> progressChangeListener = (observable, oldValue, newValue) -> {
try {
if (doc.getProgressListener() != null)
doc.getProgressListener().setProgress(Math.round(1000 * newValue.doubleValue()));
} catch (CanceledException e) {
blastService.cancel();
}
};
final ChangeListener<String> messageChangeListener = (observable, oldValue, newValue) -> {
System.err.println(newValue);
if (doc.getProgressListener() != null)
doc.getProgressListener().setSubtask(newValue);
};
// if user cancels progress listener, cancels service
final Thread thread = new Thread(() -> {
while (serviceIsRunning) {
if (doc.getProgressListener().isUserCancelled()) {
Platform.runLater(() -> {
if (blastService.isRunning())
blastService.cancel();
});
}
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {
}
}
});
thread.start();
Platform.runLater(() -> {
blastService.setOnRunning(event -> SwingUtilities.invokeLater(() -> {
serviceIsRunning = true;
getCommandManager().updateEnableState(NAME);
}));
blastService.messageProperty().addListener(messageChangeListener);
blastService.progressProperty().addListener(progressChangeListener);
blastService.restart();
blastService.setOnSucceeded(event -> {
blastService.progressProperty().removeListener(progressChangeListener);
blastService.messageProperty().removeListener(messageChangeListener);
final String result = blastService.getValue();
SwingUtilities.invokeLater(() -> {
try {
if (result != null && result.length() > 0) {
try {
final File blastFile = ChooseFileDialog.chooseFileToSave(getViewer().getFrame(), FileUtils.replaceFileSuffix(readsFile, "." + blastMode), new MeganFileFilter(), new MeganFileFilter(), null, "Save BLAST file", "." + blastMode);
if (blastFile != null) {
try (BufferedWriter w = new BufferedWriter(new FileWriter(blastFile))) {
w.write(result);
}
System.err.println("Alignments written to: " + blastFile.getPath());
if (ProgramProperties.isUseGUI()) {
final int result1 = JOptionPane.showConfirmDialog(null, "Import remotely BLASTED file into MEGAN?", "Import - MEGAN", JOptionPane.YES_NO_CANCEL_OPTION);
getDir().notifyUnlockInput();
if (result1 == JOptionPane.YES_OPTION) {
final ImportBlastDialog importBlastDialog = new ImportBlastDialog(getViewer().getFrame(), (Director) getDir(), "Import Blast File");
importBlastDialog.getBlastFileNameField().setText(blastFile.getPath());
importBlastDialog.getReadFileNameField().setText(readsFile.getPath());
importBlastDialog.setLongReads(longReads);
importBlastDialog.getMeganFileNameField().setText(FileUtils.replaceFileSuffix(blastFile.getPath(), "-" + blastMode + ".rma6"));
importBlastDialog.updateView(IDirector.ALL);
final String command = importBlastDialog.showAndGetCommand();
if (command != null) {
getDir().notifyUnlockInput();
getDir().execute(command, getViewer().getCommandManager());
}
}
}
}
} catch (Exception ex) {
NotificationsInSwing.showError("Create RMA file failed: " + ex.getMessage());
getDir().notifyUnlockInput();
getDir().executeImmediately("close what=current;", ((Director) getDir()).getCommandManager());
}
} else {
NotificationsInSwing.showInformation("No hits found");
getDir().notifyUnlockInput();
getDir().executeImmediately("close what=current;", ((Director) getDir()).getCommandManager());
}
} finally {
serviceIsRunning = false;
if (doc.getProgressListener() != null)
doc.getProgressListener().close();
}
});
});
blastService.setOnFailed(event -> {
blastService.progressProperty().removeListener(progressChangeListener);
blastService.messageProperty().removeListener(messageChangeListener);
NotificationsInSwing.showError("Remote blast failed: " + blastService.getException());
SwingUtilities.invokeLater(() -> {
try {
doc.getProgressListener().close();
getDir().notifyUnlockInput();
getDir().executeImmediately("close what=current;", ((Director) getDir()).getCommandManager());
} finally {
serviceIsRunning = false;
}
});
});
blastService.setOnCancelled(event -> {
blastService.progressProperty().removeListener(progressChangeListener);
blastService.messageProperty().removeListener(messageChangeListener);
if (serviceIsRunning)
NotificationsInSwing.showWarning("Remote blast canceled");
SwingUtilities.invokeLater(() -> {
if (serviceIsRunning) {
try {
getDir().notifyUnlockInput();
getDir().executeImmediately("close what=current;", ((Director) getDir()).getCommandManager());
} finally {
serviceIsRunning = false;
if (doc.getProgressListener() != null)
doc.getProgressListener().close();
}
}
});
});
});
}
public void actionPerformed(ActionEvent event) {
if (isApplicable()) {
final IReadsProvider readProvider = ((IReadsProvider) getViewer());
if (readProvider.isReadsAvailable()) {
final Pair<String, String> first = readProvider.getReads(1).iterator().next();
final String commandString = RemoteBlastDialog.apply(getViewer(), (Director) getDir(), readProvider, null, StringUtils.toCleanName(first.getFirst()));
if (commandString != null) {
final Director newDir = Director.newProject();
newDir.getMainViewer().getFrame().setVisible(true);
newDir.getMainViewer().setDoReInduce(true);
newDir.getMainViewer().setDoReset(true);
newDir.executeImmediately(commandString, newDir.getMainViewer().getCommandManager());
getCommandManager().updateEnableState(NAME);
}
}
}
}
public boolean isApplicable() {
return getViewer() instanceof IReadsProvider && (blastService == null || !serviceIsRunning) && ((IReadsProvider) getViewer()).isReadsAvailable();
}
private static final String NAME = "BLAST on NCBI...";
public String getName() {
return NAME;
}
public String getDescription() {
return "Remotely BLAST sequence on NCBI website";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
@Override
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_B, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
}
| 13,241 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ProjectAssignmentsToRankCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/additional/ProjectAssignmentsToRankCommand.java | /*
* ProjectAssignmentsToRankCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.additional;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.FileUtils;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.algorithms.NaiveProjectionProfile;
import megan.classification.ClassificationManager;
import megan.core.Director;
import megan.core.Document;
import megan.core.MeganFile;
import megan.core.SampleAttributeTable;
import megan.main.MeganProperties;
import megan.util.CallBack;
import megan.util.PopupChoice;
import megan.viewer.ClassificationViewer;
import megan.viewer.TaxonomicLevels;
import megan.viewer.gui.NodeDrawer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class ProjectAssignmentsToRankCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "project rank={" + StringUtils.toString(TaxonomicLevels.getAllMajorRanks(), "|") + "} [minPercent={number}];";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("project rank=");
final String rank = np.getWordMatchesRespectingCase(StringUtils.toString(TaxonomicLevels.getAllNames(), " "));
final float minPercent;
if (np.peekMatchIgnoreCase("minPercent")) {
np.matchIgnoreCase("minPercent=");
minPercent = (float) np.getDouble(0, 100);
} else
minPercent = 0f;
np.matchIgnoreCase(";");
final Document doc = ((Director) getDir()).getDocument();
final int numberOfSamples = doc.getNumberOfSamples();
final String[] sampleNames = doc.getSampleNamesAsArray();
final String fileName = FileUtils.replaceFileSuffix(doc.getMeganFile().getFileName(), "-" + rank + "-projection.megan");
final SampleAttributeTable sampleAttributeTable = doc.getSampleAttributeTable().copy();
final long numberOfReads = doc.getNumberOfReads();
final int[] sampleSizes = new int[numberOfSamples];
for (int s = 0; s < numberOfSamples; s++) {
sampleSizes[s] = Math.round(doc.getDataTable().getSampleSizes()[s]);
}
final Director newDir;
final Document newDocument;
if (ProgramProperties.isUseGUI()) {
newDir = Director.newProject(false);
newDir.getMainViewer().setDoReInduce(true);
newDir.getMainViewer().setDoReset(true);
newDocument = newDir.getDocument();
newDocument.setReadAssignmentMode(doc.getReadAssignmentMode());
} else {
newDir = (Director) getDir();
newDocument = doc;
newDocument.clearReads();
newDocument.getSampleAttributeTable().clear();
}
newDocument.getMeganFile().setFile(fileName, MeganFile.Type.MEGAN_SUMMARY_FILE);
newDocument.setNumberReads(numberOfReads);
Map<String, Map<Integer, float[]>> classification2class2counts = new HashMap<>();
{
var viewers = new ArrayList<ClassificationViewer>();
viewers.add(((Director) getDir()).getMainViewer());
if (doc.getClassificationNames().contains("GTDB")) {
for (var viewer : ((Director) getDir()).getViewers()) {
if (viewer instanceof ClassificationViewer && viewer.getClassName().equals("GTDB")) {
viewers.add((ClassificationViewer) viewer);
break;
}
}
if (viewers.size() < 2) {
System.err.println("Document has GTDB classification, open GTDB viewer to ensure that it gets projected, too");
}
}
for (var viewer : viewers) {
final Map<Integer, float[]> taxonMap = NaiveProjectionProfile.compute(viewer, rank, minPercent);
final Map<Integer, float[]>[] sample2taxonMap = sortBySample(numberOfSamples, taxonMap);
for (int s = 0; s < numberOfSamples; s++) {
classification2class2counts.put(viewer.getClassName(), sample2taxonMap[s]);
// float sampleSize = computeSize(sample2taxonMap[s]);
newDocument.addSample(sampleNames[s], sampleSizes[s], 0, doc.getBlastMode(), classification2class2counts);
}
}
}
System.err.printf("Number of reads: %,d%n",newDocument.getNumberOfReads());
newDocument.processReadHits();
newDocument.setTopPercent(100);
newDocument.setMinScore(0);
newDocument.setMaxExpected(10000);
newDocument.setMinSupportPercent(0);
newDocument.setMinSupport(1);
newDocument.setDirty(true);
newDocument.getDataTable().setParameters(doc.getDataTable().getParameters());
newDocument.getActiveViewers().addAll(newDocument.getDataTable().getClassification2Class2Counts().keySet());
newDocument.getSampleAttributeTable().addTable(sampleAttributeTable, true, true);
NotificationsInSwing.showInformation(String.format("Computed taxonomic profile for %,d reads", newDocument.getNumberOfReads()));
if (ProgramProperties.isUseGUI() && newDocument.getNumberOfReads() == 0) {
newDocument.setDirty(false);
newDir.close();
} else {
newDir.getMainViewer().getFrame().setVisible(true);
if (newDocument.getNumberOfSamples() > 1) {
newDir.getMainViewer().getNodeDrawer().setStyle(ProgramProperties.get(MeganProperties.COMPARISON_STYLE, ""), NodeDrawer.Style.PieChart);
}
newDir.execute("update reprocess=true reInduce=true;collapse rank=" + rank + ";", newDir.getMainViewer().getCommandManager());
}
}
/**
* compute the size of the classification
*
* @return size
*/
private float computeSize(Map<Integer, float[]> integerMap) {
float size = 0;
for (Integer taxonId : integerMap.keySet()) {
size += integerMap.get(taxonId)[0];
}
return size;
}
/**
* split into single sample tables
*
* @return single sample tables
*/
private Map<Integer, float[]>[] sortBySample(int numberOfSamples, Map<Integer, float[]> taxonMap) {
Map<Integer, float[]>[] sample2TaxonMap = new HashMap[numberOfSamples];
for (int i = 0; i < numberOfSamples; i++) {
sample2TaxonMap[i] = new HashMap<>();
}
for (Integer taxId : taxonMap.keySet()) {
float[] counts = taxonMap.get(taxId);
for (int i = 0; i < numberOfSamples; i++) {
sample2TaxonMap[i].put(taxId, new float[]{counts[i]});
}
}
return sample2TaxonMap;
}
public void actionPerformed(ActionEvent event) {
final String[] ranks = TaxonomicLevels.getAllMajorRanks().toArray(new String[0]);
PopupChoice<String> popupChoice = new PopupChoice<>(ranks, null, new CallBack<>() {
@Override
public void call(String choice) {
execute("collapse rank='" + choice + "';project rank='" + choice + "' minPercent=0;");
}
});
popupChoice.showAtCurrentMouseLocation(getViewer().getFrame());
}
public boolean isApplicable() {
return ClassificationManager.isTaxonomy(getViewer().getClassName()) && ((Director) getDir()).getDocument().getNumberOfReads() > 0;
}
public String getName() {
return "Project Assignments To Rank...";
}
public String getDescription() {
return "Projects all taxonomic assignments onto a given rank";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/New16.gif");
}
public boolean isCritical() {
return true;
}
@Override
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_R, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
}
| 9,050 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ComputeMatepairLCARanksCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/additional/ComputeMatepairLCARanksCommand.java | /*
* ComputeMatepairLCARanksCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.additional;
import jloda.graph.Node;
import jloda.swing.commands.ICommand;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.viewer.TaxonomicLevels;
import megan.viewer.TaxonomyData;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.HashSet;
public class ComputeMatepairLCARanksCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "mpAnalyzer what={lca-ranks|compare} infile=<filename> outfile=<filename>;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("mpAnalyzer what=");
String what = np.getWordMatchesIgnoringCase("lca-ranks compare");
np.matchIgnoreCase("infile=");
String infile = np.getWordFileNamePunctuation();
np.matchIgnoreCase("outfile=");
String outfile = np.getWordFileNamePunctuation();
np.matchIgnoreCase(";");
int lines = 0;
int warnings = 0;
try (BufferedReader r = new BufferedReader(new FileReader(infile))) {
BufferedWriter w = new BufferedWriter(new FileWriter(outfile));
try {
String aLine;
while ((aLine = r.readLine()) != null) {
String[] tokens = aLine.split("\t");
if (tokens.length != 3) {
if (warnings < 10)
System.err.println("Skipping line: " + aLine);
else if (warnings == 10)
System.err.println("...");
warnings++;
continue;
}
if (tokens[0].equals("ReadID"))
continue;
if (what.charAt(0) == 'l') { // lca-ranks
int taxId1 = TaxonomyData.getName2IdMap().get(tokens[1].trim());
int taxId2 = TaxonomyData.getName2IdMap().get(tokens[2].trim());
if (taxId1 <= 0 || taxId2 <= 0) {
w.write("NA\n");
lines++;
} else {
HashSet<Integer> taxIds = new HashSet<>();
taxIds.add(taxId1);
taxIds.add(taxId2);
Integer taxId = TaxonomyData.getLCA(taxIds, false);
int level = 0;
while (level == 0) {
level = TaxonomyData.getTaxonomicRank(taxId);
if (level == 0) {
Node v = TaxonomyData.getTree().getANode(taxId);
if (v == null || v.getInDegree() == 0)
break;
v = v.getFirstInEdge().getSource();
taxId = (Integer) v.getInfo();
}
}
if (level != 0)
w.write(TaxonomicLevels.getName(level) + "\n");
else
w.write("NA\n");
lines++;
}
} else // compare
{
String readId = tokens[0].trim();
String taxonName1 = tokens[1].trim();
String taxonName2 = tokens[2].trim();
int taxId1 = TaxonomyData.getName2IdMap().get(taxonName1);
int taxId2 = TaxonomyData.getName2IdMap().get(taxonName2);
if (taxId1 <= 0 || taxId2 <= 0) {
w.write(readId + "\tNA\tNA\n");
lines++;
} else {
HashSet<Integer> taxIds = new HashSet<>();
taxIds.add(taxId1);
taxIds.add(taxId2);
int taxId = TaxonomyData.getLCA(taxIds, true);
if (taxId == taxId1 || taxId == taxId2) {
w.write(readId + "\t" + TaxonomyData.getName2IdMap().get(taxId) + "\t" + TaxonomyData.getName2IdMap().get(taxId) + "\n");
} else {
w.write(readId + "\t" + taxonName1 + "\t" + taxonName2 + "\n");
}
lines++;
}
}
}
} finally {
w.flush();
w.close();
System.err.println("lines wrote: " + lines);
}
}
}
public void actionPerformed(ActionEvent event) {
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "MP-Compute";
}
public String getDescription() {
return "Compute the rank at which the LCA is found for each mate-pair, or preprocess comparison";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return false;
}
}
| 6,241 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SplitByAttributeCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/additional/SplitByAttributeCommand.java | /*
* SplitByAttributeCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.additional;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.FileUtils;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.core.Director;
import megan.core.Document;
import megan.core.SampleAttributeTable;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* * split by command
* * Daniel Huson, 11.2020
*/
public class SplitByAttributeCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "splitBy attribute=<name> [samples=<names>];";
}
/**
* parses the given command and executes it
*/
public void apply(NexusStreamParser np) throws Exception {
final Document doc = ((Director) getDir()).getDocument();
np.matchIgnoreCase("splitBy attribute=");
String attribute = np.getWordRespectCase();
final ArrayList<String> srcSamples = new ArrayList<>();
if (np.peekMatchIgnoreCase("samples")) {
srcSamples.addAll(np.getTokensRespectCase("samples=", ";"));
} else {
srcSamples.addAll(doc.getSampleNames());
np.matchIgnoreCase(";");
}
final Map<String, List<String>> tarSample2SrcSamples = new HashMap<>();
for (String sample : srcSamples) {
final Object obj = doc.getSampleAttributeTable().get(sample, attribute);
if (obj != null) {
final String value = StringUtils.toCleanName(obj.toString());
if (value.length() > 0) {
final String tarSample =attribute.equals(SampleAttributeTable.SAMPLE_ID) ? value : attribute + "-" + value;
tarSample2SrcSamples.computeIfAbsent(tarSample, k -> new ArrayList<>());
tarSample2SrcSamples.get(tarSample).add(sample);
}
}
}
final List<String> commands=new ArrayList<>();
if (tarSample2SrcSamples.size() > 0) {
for(String tarName:tarSample2SrcSamples.keySet()) {
final String fileName = FileUtils.replaceFileSuffix(FileUtils.getFileNameWithoutPath(doc.getMeganFile().getFileName()), "-" + tarName + ".megan");
final List<String> samples = tarSample2SrcSamples.get(tarName);
if(samples.size()>0)
commands.add(String.format("extract samples='%s' file='%s';", StringUtils.toString(samples, "' '"), fileName));
}
}
executeImmediately(StringUtils.toString(commands, "\n"));
}
public void actionPerformed(ActionEvent event) {
}
public boolean isApplicable() {
return true;
}
public String getName() {
return null;
}
public String getDescription() {
return "Splits samples by this attribute and show in new documents";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Compare16.gif");
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 4,021 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
OpenDecontamCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/additional/OpenDecontamCommand.java | /*
* OpenDecontamCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.additional;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.util.parse.NexusStreamParser;
import megan.core.Director;
import megan.fx.dialogs.decontam.DecontamDialog;
import megan.util.WindowUtilities;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* open the decontam viewer
* Daniel Huson, 8/2020
*/
public class OpenDecontamCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "open decontam;";
}
/**
* apply the command
*/
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
final Director dir = (Director) getDir();
DecontamDialog viewer = (DecontamDialog) dir.getViewerByClass(DecontamDialog.class);
if (viewer == null) {
viewer = new DecontamDialog(getViewer().getFrame(), dir);
dir.addViewer(viewer);
} else {
WindowUtilities.toFront(viewer);
}
}
public boolean isApplicable() {
return ((Director) getDir()).getDocument().getNumberOfReads() > 0;
}
@Override
public void actionPerformed(ActionEvent ev) {
execute(getSyntax());
}
private static final String NAME = "Decontam...";
public String getName() {
return NAME;
}
public String getDescription() {
return "Open the Decontam dialog";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
@Override
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,485 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CompareByAttributeCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/additional/CompareByAttributeCommand.java | /*
* CompareByAttributeCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.additional;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.FileUtils;
import jloda.util.parse.NexusStreamParser;
import megan.commands.algorithms.ComputeCoreOrRareBiome;
import megan.core.*;
import megan.dialogs.compare.Comparer;
import megan.main.MeganProperties;
import megan.viewer.gui.NodeDrawer;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* * compare by command
* * Daniel Huson, 9.2015
*/
public class CompareByAttributeCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "compareBy attribute=<name> [mode={relative|absolute}] [samples=<names>];";
}
/**
* parses the given command and executes it
*/
public void apply(NexusStreamParser np) throws Exception {
final Document doc = ((Director) getDir()).getDocument();
np.matchIgnoreCase("compareBy attribute=");
String attribute = np.getWordRespectCase();
final Comparer.COMPARISON_MODE mode;
if (np.peekMatchIgnoreCase("mode")) {
np.matchIgnoreCase("mode=");
mode = Comparer.COMPARISON_MODE.valueOfIgnoreCase(np.getWordMatchesIgnoringCase("relative absolute"));
} else
mode = Comparer.COMPARISON_MODE.ABSOLUTE;
final ArrayList<String> srcSamples = new ArrayList<>();
if (np.peekMatchIgnoreCase("samples")) {
srcSamples.addAll(np.getTokensRespectCase("samples=", ";"));
} else {
srcSamples.addAll(doc.getSampleNames());
np.matchIgnoreCase(";");
}
final Map<String, List<String>> tarSample2SrcSamples = new HashMap<>();
final List<String> tarSamples = new ArrayList<>();
final Map<String, Object> tarSample2Value = new HashMap<>();
for (String sample : srcSamples) {
final Object obj = doc.getSampleAttributeTable().get(sample, attribute);
if (obj != null) {
final String value = obj.toString().trim();
if (value.length() > 0) {
final String tarSample = (attribute.equals(SampleAttributeTable.SAMPLE_ID) ? value : attribute + ":" + value);
if (tarSample2SrcSamples.get(tarSample) == null) {
tarSamples.add(tarSample);
tarSample2SrcSamples.put(tarSample, new ArrayList<>());
}
tarSample2SrcSamples.get(tarSample).add(sample);
tarSample2Value.put(tarSample, value);
}
}
}
if (tarSample2SrcSamples.size() > 0) {
final String fileName = FileUtils.replaceFileSuffix(doc.getMeganFile().getFileName(), "-" + attribute + ".megan");
final Director newDir = Director.newProject(false);
final Document newDocument = newDir.getDocument();
newDocument.getMeganFile().setFile(fileName, MeganFile.Type.MEGAN_SUMMARY_FILE);
doc.getProgressListener().setMaximum(srcSamples.size());
doc.getProgressListener().setProgress(0);
for (String tarSample : tarSamples) {
doc.getProgressListener().setTasks("Comparing samples", tarSample);
final List<String> samples = tarSample2SrcSamples.get(tarSample);
Map<String, Map<Integer, float[]>> classification2class2counts = new HashMap<>();
final int sampleSize = ComputeCoreOrRareBiome.apply(doc, samples, false, 0, 0, classification2class2counts, doc.getProgressListener());
if (classification2class2counts.size() > 0) {
newDocument.addSample(tarSample, sampleSize, 0, doc.getBlastMode(), classification2class2counts);
}
doc.getProgressListener().incrementProgress();
}
// normalize:
if (mode == Comparer.COMPARISON_MODE.RELATIVE) {
float newSize = Float.MAX_VALUE;
float maxSize = 0;
for (String tarSample : tarSamples) {
newSize = Math.min(newSize, newDocument.getNumberOfReads(tarSample));
maxSize = Math.max(maxSize, newDocument.getNumberOfReads(tarSample));
}
if (newSize < maxSize) {
double[] factor = new double[tarSamples.size()];
for (int i = 0; i < tarSamples.size(); i++) {
String tarSample = tarSamples.get(i);
factor[i] = (newSize > 0 ? (double) newSize / (double) newDocument.getNumberOfReads(tarSample) : 0);
}
final DataTable dataTable = newDocument.getDataTable();
for (String classificationName : dataTable.getClassification2Class2Counts().keySet()) {
Map<Integer, float[]> class2counts = dataTable.getClass2Counts(classificationName);
for (Integer classId : class2counts.keySet()) {
float[] counts = class2counts.get(classId);
for (int i = 0; i < counts.length; i++) {
counts[i] = (int) Math.round(factor[i] * counts[i]);
}
}
}
}
newDocument.getDataTable().setParameters("mode=" + Comparer.COMPARISON_MODE.RELATIVE + " normalizedTo=" + newSize);
} else
newDocument.getDataTable().setParameters("mode=" + Comparer.COMPARISON_MODE.ABSOLUTE);
newDocument.getSampleAttributeTable().addAttribute(attribute, tarSample2Value, true);
newDocument.setNumberReads(newDocument.getDataTable().getTotalReads());
newDocument.setDirty(true);
if (newDocument.getNumberOfSamples() > 1) {
newDir.getMainViewer().getNodeDrawer().setStyle(ProgramProperties.get(MeganProperties.COMPARISON_STYLE, ""), NodeDrawer.Style.PieChart);
}
NotificationsInSwing.showInformation(String.format("Wrote %,d reads to file '%s'", newDocument.getNumberOfReads(), fileName));
newDir.getMainViewer().getFrame().setVisible(true);
newDir.getMainViewer().setDoReInduce(true);
newDir.getMainViewer().setDoReset(true);
newDir.execute("update reprocess=true reinduce=true;", newDir.getMainViewer().getCommandManager());
}
}
public void actionPerformed(ActionEvent event) {
}
public boolean isApplicable() {
return true;
}
public String getName() {
return null;
}
public String getDescription() {
return "Aggregate samples by this attribute and show comparison in new document";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Compare16.gif");
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 8,114 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExportGeneCentricAssemblyCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/additional/ExportGeneCentricAssemblyCommand.java | /*
* ExportGeneCentricAssemblyCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.additional;
import jloda.fx.util.ProgramExecutorService;
import jloda.seq.BlastMode;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ChooseFileDialog;
import jloda.swing.util.FastaFileFilter;
import jloda.swing.util.ResourceManager;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.*;
import jloda.util.parse.NexusStreamParser;
import jloda.util.progress.ProgressListener;
import jloda.util.progress.ProgressPercentage;
import megan.alignment.AlignmentViewer;
import megan.assembly.ReadAssembler;
import megan.assembly.ReadDataCollector;
import megan.assembly.alignment.AlignmentAssembler;
import megan.blastclient.RemoteBlastDialog;
import megan.commands.CommandBase;
import megan.core.Director;
import megan.core.Document;
import megan.data.ReadBlockIteratorMaxCount;
import megan.viewer.ClassificationViewer;
import megan.viewer.ViewerBase;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.*;
import java.util.HashSet;
import java.util.Set;
/**
* assemble all reads associated with a selected node
* Daniel Huson, 5.2015
*/
public class ExportGeneCentricAssemblyCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "export assembly file=<name> [minOverlap=<number>] [minReads=<number>] [minLength=<number>] [minAvCoverage=<number>] [minPercentIdentity=<number>] [maxNumberOfReads=<number>] [showGraph={false|true}];";
}
// nt minReads, double minCoverage, int minLength,
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("export assembly");
np.matchIgnoreCase("file=");
final String outputFile = np.getWordFileNamePunctuation();
final int minOverlap;
if (np.peekMatchIgnoreCase("minOverlap")) {
np.matchIgnoreCase("minOverlap=");
minOverlap = np.getInt(1, 1000000);
} else
minOverlap = 20;
final int minReads;
if (np.peekMatchIgnoreCase("minReads")) {
np.matchIgnoreCase("minReads=");
minReads = np.getInt(1, 1000000);
} else minReads = 2;
final int minLength;
if (np.peekMatchIgnoreCase("minLength")) {
np.matchIgnoreCase("minLength=");
minLength = np.getInt(1, 1000000);
} else
minLength = 0;
final float minAvCoverage;
if (np.peekMatchIgnoreCase("minAvCoverage") || np.peekMatchIgnoreCase("minCoverage")) { // allow minCoverage for legacy
np.matchAnyTokenIgnoreCase("minAvCoverage minCoverage");
np.matchIgnoreCase("=");
minAvCoverage = (float) np.getDouble(0, 1000000);
} else
minAvCoverage = 0;
final boolean doOverlapContigs;
if (np.peekMatchIgnoreCase("doOverlapContigs")) {
np.matchIgnoreCase("doOverlapContigs=");
doOverlapContigs = np.getBoolean();
} else
doOverlapContigs = true;
final int minContigOverlap;
if (np.peekMatchIgnoreCase("minContigOverlap")) {
np.matchIgnoreCase("minContigOverlap=");
minContigOverlap = np.getInt(1, 1000000);
} else
minContigOverlap = 20;
final float maxPercentIdentity;
if (np.peekMatchIgnoreCase("minPercentIdentity")) {
np.matchIgnoreCase("minPercentIdentity=");
maxPercentIdentity = (float) np.getDouble(0, 100);
} else
maxPercentIdentity = 100;
final int maxNumberOfReads;
if (np.peekMatchIgnoreCase("maxNumberOfReads")) {
np.matchIgnoreCase("maxNumberOfReads=");
maxNumberOfReads = np.getInt(-1, Integer.MAX_VALUE);
} else
maxNumberOfReads = -1;
final boolean showGraph;
if (np.peekMatchIgnoreCase("showGraph")) {
np.matchIgnoreCase("showGraph=");
showGraph = np.getBoolean();
} else
showGraph = false;
np.matchIgnoreCase(";");
// test whether we can write the output file:
try (FileWriter w = new FileWriter(outputFile)) {
w.write("");
}
final Director dir = getDir();
final Document doc = dir.getDocument();
if (doc.getNumberOfReads() == 0 || doc.getMeganFile().isMeganSummaryFile())
throw new IOException("No reads available for assembly");
final ProgressListener progress = (ProgramProperties.isUseGUI() ? doc.getProgressListener() : new ProgressPercentage());
progress.setTasks("Gene-centric assembly", "Initializing");
String message = "";
if (getViewer() instanceof final AlignmentViewer viewer) {
final var alignmentAssembler = new AlignmentAssembler();
alignmentAssembler.computeOverlapGraph(minOverlap, viewer.getAlignment(), progress);
var count = alignmentAssembler.computeContigs(0, minReads, minAvCoverage, minLength, false, progress);
System.err.printf("Number of contigs:%6d%n", count);
if (doOverlapContigs) {
final int numberOfThreads = ProgramExecutorService.getNumberOfCoresToUse();
count = ReadAssembler.mergeOverlappingContigs(numberOfThreads, progress, maxPercentIdentity, minContigOverlap, alignmentAssembler.getContigs(), true);
System.err.printf("Remaining contigs:%6d%n", count);
}
try (Writer w = new BufferedWriter(new FileWriter(outputFile))) {
alignmentAssembler.writeContigs(w, progress);
System.err.println("Contigs written to: " + outputFile);
message += "Wrote " + count + " contigs\n";
}
if (ProgramProperties.isUseGUI()) {
if (JOptionPane.showConfirmDialog(null, "BLAST contigs on NCBI?", "Remote BLAST - MEGAN", JOptionPane.YES_NO_CANCEL_OPTION) == JOptionPane.YES_OPTION) {
final String commandString = RemoteBlastDialog.apply(getViewer(), getDir(), null, outputFile, "contig");
if (commandString != null) {
final Director newDir = Director.newProject();
newDir.getMainViewer().getFrame().setVisible(true);
newDir.getMainViewer().setDoReInduce(true);
newDir.getMainViewer().setDoReset(true);
newDir.executeImmediately(commandString, newDir.getMainViewer().getCommandManager());
}
}
}
if (showGraph)
alignmentAssembler.showOverlapGraph(dir, dir.getDocument().getProgressListener());
} else {
final ViewerBase viewer = (ViewerBase) getViewer();
if (viewer.getSelectedNodeIds().size() > 0) {
final ReadAssembler readAssembler = new ReadAssembler(true);
final var it0 = doc.getConnector().getReadsIteratorForListOfClassIds(viewer.getClassName(), viewer.getSelectedNodeIds(), 0, 10, true, true);
try (var it = (maxNumberOfReads > 0 ? new ReadBlockIteratorMaxCount(it0, maxNumberOfReads) : it0)) {
final var label = viewer.getClassName() + ". Id(s): " + StringUtils.toString(viewer.getSelectedNodeIds(), ", ");
final var readData = ReadDataCollector.apply(it, progress);
readAssembler.computeOverlapGraph(label, minOverlap, readData, progress);
var count = readAssembler.computeContigs(minReads, minAvCoverage, minLength, progress);
System.err.printf("Number of contigs:%6d%n", count);
if (count == 0) {
message = "Could not assemble reads, 0 contigs created.";
} else {
if (doOverlapContigs) {
final int numberOfThreads = ProgramExecutorService.getNumberOfCoresToUse();
count = ReadAssembler.mergeOverlappingContigs(numberOfThreads, progress, maxPercentIdentity, minContigOverlap, readAssembler.getContigs(), true);
System.err.printf("Remaining contigs:%6d%n", count);
}
if (ProgramProperties.get("verbose-assembly", false)) {
for (Pair<String, String> contig : readAssembler.getContigs()) {
System.err.println(contig.getFirst());
}
}
try (Writer w = new BufferedWriter(new FileWriter(outputFile))) {
readAssembler.writeContigs(w, progress);
System.err.println("Contigs written to: " + outputFile);
readAssembler.reportContigStats();
message += "Wrote " + count + " contigs\n";
}
if (showGraph)
readAssembler.showOverlapGraph(dir, progress);
if (ProgramProperties.isUseGUI()) {
if (JOptionPane.showConfirmDialog(null, "BLAST contigs on NCBI?", "Remote BLAST - MEGAN", JOptionPane.YES_NO_CANCEL_OPTION) == JOptionPane.YES_OPTION) {
final String commandString = RemoteBlastDialog.apply(getViewer(), getDir(), null, outputFile, "contig");
if (commandString != null) {
final Director newDir = Director.newProject();
newDir.getMainViewer().setDoReInduce(true);
newDir.getMainViewer().setDoReset(true);
newDir.executeImmediately(commandString, newDir.getMainViewer().getCommandManager());
}
}
}
}
}
} else {
NotificationsInSwing.showWarning(getViewer().getFrame(), "Nothing selected");
}
}
if (message.length() > 0)
NotificationsInSwing.showInformation(getViewer().getFrame(), message);
}
public void actionPerformed(final ActionEvent event) {
final Single<Boolean> askedToOverwrite = new Single<>(false);
final Document doc = getDir().getDocument();
final String classificationName = getViewer().getClassName();
final JDialog dialog = new JDialog(getViewer().getFrame());
dialog.setModal(true);
dialog.setLocationRelativeTo(getViewer().getFrame());
dialog.setSize(400, 400);
dialog.getContentPane().setLayout(new BorderLayout());
final JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
dialog.getContentPane().add(mainPanel, BorderLayout.CENTER);
dialog.setTitle("Assembly for " + classificationName + " - " + ProgramProperties.getProgramName());
final JPanel middlePanel = new JPanel();
middlePanel.setLayout(new BoxLayout(middlePanel, BoxLayout.Y_AXIS));
{
final String message;
if (getViewer() instanceof AlignmentViewer)
message = "Run 'gene-centric assembly' on current alignment";
else
message = "Run 'gene-centric assembly' on selected node(s)";
final JPanel messagePanel = newSingleLine(new JLabel(message), Box.createHorizontalGlue());
messagePanel.setBorder(BorderFactory.createEmptyBorder(4, 6, 4, 6));
middlePanel.add(messagePanel);
}
File lastOpenFile = ProgramProperties.getFile("AssemblyFile");
String fileName = FileUtils.replaceFileSuffix(doc.getMeganFile().getName(), "");
String addOn = null;
if (getViewer() instanceof AlignmentViewer) {
addOn = StringUtils.toCleanName(((AlignmentViewer) getViewer()).getAlignment().getName()).replaceAll("[_]+", "_");
} else if (getViewer() instanceof ViewerBase) {
addOn = getViewer().getClassName().toLowerCase();
final Set<String> labels = new HashSet<>(((ViewerBase) getViewer()).getSelectedNodeLabels(false));
if (labels.size() == 1)
addOn += "-" + StringUtils.toCleanName(labels.iterator().next()).replaceAll("[_]+", "_");
}
if (addOn != null) {
final File file = new File(fileName);
final String name = file.getName();
fileName = FileUtils.getFilePath(file.getParent(), FileUtils.replaceFileSuffix(name, "-" + addOn));
}
if (lastOpenFile != null) {
fileName = new File(lastOpenFile.getParent(), fileName).getPath();
}
fileName += "-contigs.fasta";
final JTextField outfile = new JTextField();
outfile.setText(fileName);
final JPanel m1 = new JPanel();
m1.setLayout(new BorderLayout());
m1.setBorder(BorderFactory.createEmptyBorder(2, 4, 20, 4));
m1.add(new JLabel("Output file:"), BorderLayout.WEST);
m1.add(outfile, BorderLayout.CENTER);
outfile.setToolTipText("Set file to save to");
m1.add(new JButton(new AbstractAction("Browse...") {
public void actionPerformed(ActionEvent actionEvent) {
File file = ChooseFileDialog.chooseFileToSave(getViewer().getFrame(), new File(outfile.getText()), new FastaFileFilter(), new FastaFileFilter(), event, "Save assembly file", ".fasta");
if (file != null) {
askedToOverwrite.set(true);
outfile.setText(file.getPath());
}
}
}), BorderLayout.EAST);
middlePanel.add(m1);
final JPanel parametersPanel = new JPanel();
parametersPanel.setLayout(new BoxLayout(parametersPanel, BoxLayout.Y_AXIS));
mainPanel.add(parametersPanel, BorderLayout.CENTER);
final JPanel firstPanel = new JPanel();
firstPanel.setBorder(BorderFactory.createTitledBorder("Read overlapping: "));
firstPanel.setLayout(new GridLayout(4, 2));
parametersPanel.add(firstPanel);
final JTextField minOverlapTextField = new JTextField(6);
minOverlapTextField.setMaximumSize(new Dimension(100, 20));
minOverlapTextField.setText("" + ProgramProperties.get("AssemblyMinOverlap", 20));
firstPanel.add(newSingleLine(Box.createHorizontalGlue(), new JLabel("Mininum overlap: ")));
firstPanel.add(newSingleLine(minOverlapTextField, Box.createHorizontalGlue()));
minOverlapTextField.setToolTipText("Minimum length of exact overlap between two reads");
final JTextField minReadsTextField = new JTextField(6);
minReadsTextField.setMaximumSize(new Dimension(100, 20));
minReadsTextField.setText("" + ProgramProperties.get("AssemblyMinReads", 5));
firstPanel.add(newSingleLine(Box.createHorizontalGlue(), new JLabel("Minimum reads: ")));
firstPanel.add(newSingleLine(minReadsTextField, Box.createHorizontalGlue()));
minReadsTextField.setToolTipText("Minimum number of reads in a contig");
final JTextField minLengthTextField = new JTextField(6);
minLengthTextField.setMaximumSize(new Dimension(100, 20));
minLengthTextField.setText("" + ProgramProperties.get("AssemblyMinLength", 200));
firstPanel.add(newSingleLine(Box.createHorizontalGlue(), new JLabel("Minimum length: ")));
firstPanel.add(newSingleLine(minLengthTextField, Box.createHorizontalGlue()));
minLengthTextField.setToolTipText("Minimum contig length");
final JTextField minAvCoverageTextField = new JTextField(6);
minAvCoverageTextField.setMaximumSize(new Dimension(100, 20));
minAvCoverageTextField.setText("" + ProgramProperties.get("AssemblyMinAvCoverage", 2));
firstPanel.add(newSingleLine(Box.createHorizontalGlue(), new JLabel("Min average coverage: ")));
firstPanel.add(newSingleLine(minAvCoverageTextField, Box.createHorizontalGlue()));
minAvCoverageTextField.setToolTipText("Minimum average coverage of a contig");
final JPanel secondPanel = new JPanel();
secondPanel.setBorder(BorderFactory.createTitledBorder("Contig overlapping: "));
secondPanel.setLayout(new GridLayout(3, 2));
parametersPanel.add(secondPanel);
final JCheckBox doContigOverlappingCBOX = new JCheckBox();
doContigOverlappingCBOX.setToolTipText("Perform all pairwise alignments of contigs to detect overlaps");
doContigOverlappingCBOX.setSelected(ProgramProperties.get("AssemblyDoOverlapContigs", true));
secondPanel.add(newSingleLine(Box.createHorizontalGlue(), new JLabel("Contig Overlapping:")));
secondPanel.add(newSingleLine(doContigOverlappingCBOX, Box.createHorizontalGlue()));
final JTextField minContigOverlapTextField = new JTextField(6);
minContigOverlapTextField.setMaximumSize(new Dimension(100, 20));
minContigOverlapTextField.setText("" + ProgramProperties.get("AssemblyMinContigOverlap", 20));
secondPanel.add(newSingleLine(Box.createHorizontalGlue(), new JLabel("Min contig overlap:")));
secondPanel.add(newSingleLine(minContigOverlapTextField, Box.createHorizontalGlue()));
minContigOverlapTextField.setToolTipText("Minimum length overlap between two contigs");
final JTextField minPercentIdentityTextField = new JTextField(6);
minPercentIdentityTextField.setMaximumSize(new Dimension(100, 20));
minPercentIdentityTextField.setText("" + ProgramProperties.get("AssemblyMinPercentIdentity", 99));
secondPanel.add(newSingleLine(Box.createHorizontalGlue(), new JLabel("Min percent identity:")));
secondPanel.add(newSingleLine(minPercentIdentityTextField, Box.createHorizontalGlue()));
minPercentIdentityTextField.setToolTipText("Minimum percent identity to overlap two contigs");
middlePanel.add(parametersPanel);
mainPanel.add(middlePanel, BorderLayout.NORTH);
JPanel bottomPanel = new JPanel();
bottomPanel.setBorder(BorderFactory.createEtchedBorder());
bottomPanel.setLayout(new BorderLayout());
JPanel b1 = new JPanel();
b1.setLayout(new BoxLayout(b1, BoxLayout.X_AXIS));
b1.add(new JButton(new AbstractAction("Cancel") {
public void actionPerformed(ActionEvent actionEvent) {
dialog.setVisible(false);
}
}));
final JButton applyButton = new JButton(new AbstractAction("Apply") {
public void actionPerformed(ActionEvent actionEvent) {
String fileName = (new File(outfile.getText().trim())).getPath();
if (fileName.length() > 0) {
if (FileUtils.getFileSuffix(fileName) == null)
fileName = FileUtils.replaceFileSuffix(fileName, ".fasta");
if (!askedToOverwrite.get() && (new File(fileName)).exists()) {
switch (JOptionPane.showConfirmDialog(getViewer().getFrame(), "File already exists, do you want to replace it?", "File exists", JOptionPane.YES_NO_CANCEL_OPTION)) {
case JOptionPane.CANCEL_OPTION: // close and abort
dialog.setVisible(false);
return;
case JOptionPane.NO_OPTION: // don't close
return;
default: // close and continue
}
}
dialog.setVisible(false);
ProgramProperties.put("AssemblyFile", fileName);
ProgramProperties.put("AssemblyMinOverlap", minOverlapTextField.getText());
ProgramProperties.put("AssemblyMinReads", minReadsTextField.getText());
ProgramProperties.put("AssemblyMinLength", minLengthTextField.getText());
ProgramProperties.put("AssemblyMinAvCoverage", minAvCoverageTextField.getText());
ProgramProperties.put("AssemblyDoOverlapContigs", doContigOverlappingCBOX.isSelected());
ProgramProperties.put("AssemblyMinContigOverlap", minContigOverlapTextField.getText());
ProgramProperties.put("AssemblyMinPercentIdentity", minPercentIdentityTextField.getText());
final String command = "export assembly file='" + fileName + "'"
+ " minOverlap=" + minOverlapTextField.getText()
+ " minReads=" + minReadsTextField.getText()
+ " minLength=" + minLengthTextField.getText()
+ " minAvCoverage=" + minAvCoverageTextField.getText()
+ " doOverlapContigs=" + doContigOverlappingCBOX.isSelected()
+ " minContigOverlap=" + minContigOverlapTextField.getText()
+ " minPercentIdentity=" + minPercentIdentityTextField.getText()
+ " showGraph=false;";
execute(command);
}
}
});
b1.add(applyButton);
dialog.getRootPane().setDefaultButton(applyButton);
bottomPanel.add(b1, BorderLayout.EAST);
mainPanel.add(bottomPanel, BorderLayout.SOUTH);
dialog.getContentPane().setLayout(new BorderLayout());
dialog.getContentPane().add(mainPanel, BorderLayout.CENTER);
dialog.validate();
outfile.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
applyButton.setEnabled(outfile.getText().trim().length() > 0);
}
@Override
public void removeUpdate(DocumentEvent e) {
insertUpdate(e);
}
@Override
public void changedUpdate(DocumentEvent e) {
insertUpdate(e);
}
});
dialog.setVisible(true);
}
private static JPanel newSingleLine(Component left, Component right) {
final JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(left);
panel.add(right);
return panel;
}
public boolean isApplicable() {
final Document doc = getDir().getDocument();
return (getViewer() instanceof AlignmentViewer && ((AlignmentViewer) getViewer()).getAlignment().getLength() > 0) ||
(getViewer() instanceof ClassificationViewer && ((ClassificationViewer) getViewer()).getNumberSelectedNodes() > 0 && doc.getMeganFile().hasDataConnector() && doc.getBlastMode().equals(BlastMode.BlastX));
}
public String getName() {
return "Gene-Centric Assembly...";
}
public String getDescription() {
return "Compute and export 'gene-centric' assembly of reads for all selected nodes.\n" +
"Huson et al, Protein-alignment-guided assembly of orthologous gene families from microbiome sequencing reads. J. Microbiome, 2017";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Export16.gif");
}
public boolean isCritical() {
return true;
}
}
| 24,181 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExportOverlapGraphCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/additional/ExportOverlapGraphCommand.java | /*
* ExportOverlapGraphCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.additional;
import jloda.seq.BlastMode;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ChooseFileDialog;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.swing.util.TextFileFilter;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.FileUtils;
import jloda.util.Pair;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.assembly.ReadAssembler;
import megan.assembly.ReadData;
import megan.assembly.ReadDataCollector;
import megan.commands.CommandBase;
import megan.core.Director;
import megan.core.Document;
import megan.data.IReadBlockIterator;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.List;
/**
* assemble all reads associated with a selected node
* Daniel Huson, 5.2015
*/
public class ExportOverlapGraphCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "export overlapGraph file=<name> [minOverlap=<number>] [showGraph={false|true}];";
}
// nt minReads, double minCoverage, int minLength,
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("export overlapGraph file=");
final String overlapGraphFile = np.getWordFileNamePunctuation();
final int minOverlap;
if (np.peekMatchIgnoreCase("minOverlap")) {
np.matchIgnoreCase("minOverlap=");
minOverlap = np.getInt(1, 1000000);
} else
minOverlap = ProgramProperties.get("AssemblyMinOverlap", 20);
boolean showGraph = false;
if (np.peekMatchIgnoreCase("showGraph")) {
np.matchIgnoreCase("showGraph=");
showGraph = np.getBoolean();
}
np.matchIgnoreCase(";");
final Director dir = getDir();
final Document doc = dir.getDocument();
final ClassificationViewer viewer = (ClassificationViewer) getViewer();
String message = "";
if (viewer.getSelectedNodeIds().size() > 0) {
final ReadAssembler readAssembler = new ReadAssembler(true);
try (IReadBlockIterator it = doc.getConnector().getReadsIteratorForListOfClassIds(viewer.getClassName(), viewer.getSelectedNodeIds(), 0, 10, true, true)) {
final String label = viewer.getClassName() + ". Id(s): " + StringUtils.toString(viewer.getSelectedNodeIds(), ", ");
final List<ReadData> readData = ReadDataCollector.apply(it, doc.getProgressListener());
readAssembler.computeOverlapGraph(label, minOverlap, readData, doc.getProgressListener());
if (overlapGraphFile != null) {
try (final Writer w = new BufferedWriter(new FileWriter(overlapGraphFile))) {
Pair<Integer, Integer> counts = readAssembler.writeOverlapGraph(w);
System.err.println("Graph written to: " + overlapGraphFile);
message = "Wrote " + counts.getFirst() + " nodes and " + counts.getSecond() + " edges";
}
}
if (showGraph)
readAssembler.showOverlapGraph(dir, doc.getProgressListener());
}
} else
message = "Nothing selected";
if (message.length() > 0) {
NotificationsInSwing.showInformation(getViewer().getFrame(), message);
}
}
public void actionPerformed(ActionEvent event) {
final Document doc = getDir().getDocument();
File lastOpenFile = ProgramProperties.getFile("OverlapGraphFile");
String fileName = doc.getMeganFile().getName();
if (fileName == null)
fileName = "Untitled";
else
fileName = StringUtils.toCleanName(fileName);
if (lastOpenFile != null) {
fileName = new File(lastOpenFile.getParent(), fileName).getPath();
}
fileName = FileUtils.replaceFileSuffix(fileName, "-overlap.gml");
File file = ChooseFileDialog.chooseFileToSave(getViewer().getFrame(), new File(fileName), new TextFileFilter(".gml"), new TextFileFilter(".gml"), event, "Save overlap graph", ".gml");
if (file != null) {
if (FileUtils.getFileSuffix(file.getName()) == null)
file = FileUtils.replaceFileSuffix(file, ".gml");
ProgramProperties.put("OverlapGraphFile", file);
execute("export overlapGraph file='" + file.getPath() + "' minOverlap=" + ProgramProperties.get("AssemblyMinOverlap", 20) + " showGraph=false;");
}
}
public boolean isApplicable() {
final Document doc = getDir().getDocument();
return getViewer() instanceof ClassificationViewer && ((ClassificationViewer) getViewer()).getNumberSelectedNodes() > 0 && doc.getMeganFile().hasDataConnector() && doc.getBlastMode().equals(BlastMode.BlastX);
}
public String getName() {
return "Overlap Graph...";
}
public String getDescription() {
return "Build and export the overlap graph for selected nodes";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Export16.gif");
}
public boolean isCritical() {
return true;
}
}
| 6,147 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CorrelateClassToAttributeCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/additional/CorrelateClassToAttributeCommand.java | /*
* CorrelateClassToAttributeCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.additional;
import jloda.graph.Node;
import jloda.graph.NodeData;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ProgramProperties;
import jloda.util.NumberUtils;
import jloda.util.parse.NexusStreamParser;
import megan.classification.ClassificationManager;
import megan.classification.data.Name2IdMap;
import megan.commands.CommandBase;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
public class CorrelateClassToAttributeCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "correlate class={name|number ...} classification={name} attribute={name} ;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("correlate class=");
ArrayList<String> labels = new ArrayList<>();
while (!np.peekMatchIgnoreCase("classification")) {
labels.add(np.getWordRespectCase());
}
np.matchIgnoreCase("classification=");
String classificationName = np.getWordRespectCase();
np.matchIgnoreCase("attribute=");
String attribute = np.getWordRespectCase();
np.matchIgnoreCase(";");
final ClassificationViewer viewer = (ClassificationViewer) getDir().getViewerByClassName(classificationName);
final Name2IdMap name2IdMap = ClassificationManager.get(classificationName, false).getName2IdMap();
final String[] sampleNames = getDoc().getSampleNamesAsArray();
final int n = sampleNames.length;
for (String label : labels) {
final int id = (NumberUtils.isInteger(label) ? NumberUtils.parseInt(label) : name2IdMap.get(label));
final String name = (NumberUtils.isInteger(label) ? name2IdMap.get(id) : label);
if (id != 0) {
final Node v = viewer.getANode(id);
final NodeData nodeData = (NodeData) v.getData();
final float[] x = (v.getOutDegree() == 0 ? nodeData.getSummarized() : nodeData.getAssigned());
final double[] y = new double[n];
for (int i = 0; i < n; i++) {
Object obj = getDoc().getSampleAttributeTable().get(sampleNames[i], attribute);
if (obj instanceof Number)
y[i] = ((Number) obj).doubleValue();
else
throw new IOException("Attribute '" + attribute + "': has non-numerical value: " + obj);
}
System.out.println("Sample\t'" + name + "'\t'" + attribute + "':");
for (int i = 0; i < n; i++) {
System.err.printf("%s\t%f\t%f%n", sampleNames[i], x[i], y[i]);
}
System.err.println("Correlation coefficient: " + computeCorrelationCoefficient(x, y, n));
}
}
}
/**
* computes the correlation coefficient
*
*/
private double computeCorrelationCoefficient(float[] x, double[] y, int n) {
double sumX = 0;
double sumY = 0;
double sumXY = 0;
double sumX2 = 0;
double sumY2 = 0;
for (int i = 0; i < n; i++) {
sumX += x[i];
sumY += y[i];
sumXY += x[i] * y[i];
sumX2 += x[i] * x[i];
sumY2 += y[i] * y[i];
}
final double bottom = Math.sqrt((n * sumX2 - sumX * sumX) * (n * sumY2 - sumY * sumY));
if (bottom == 0)
return 0;
final double top = n * sumXY - sumX * sumY;
return top / bottom;
}
public void actionPerformed(ActionEvent event) {
final Collection<String> list = getDoc().getSampleAttributeTable().getNumericalAttributes();
final ClassificationViewer viewer = (ClassificationViewer) getViewer();
final Collection<Integer> ids = viewer.getSelectedNodeIds();
if (ids.size() > 0 && list.size() > 0) {
final String[] choices = list.toArray(new String[0]);
String choice = ProgramProperties.get("CorrelateToAttribute", choices[0]);
if (!list.contains(choice))
choice = choices[0];
choice = (String) JOptionPane.showInputDialog(getViewer().getFrame(), "Choose attribute to correlate to:",
"Compute Correlation Coefficient", JOptionPane.QUESTION_MESSAGE, ProgramProperties.getProgramIcon(), choices, choice);
if (choice != null) {
ProgramProperties.put("CorrelateToAttribute", choice);
StringBuilder buf = new StringBuilder();
buf.append("correlate class=");
for (Integer id : ids) {
buf.append(" ").append(id);
}
buf.append(" classification='").append(viewer.getClassName()).append("' attribute='").append(choice).append("';");
executeImmediately("show window=message;");
execute(buf.toString());
}
}
}
public boolean isApplicable() {
return getViewer() instanceof ClassificationViewer && ((ClassificationViewer) getViewer()).getNumberSelectedNodes() > 0 && getDoc().getNumberOfSamples() > 0 && getDoc().getSampleAttributeTable().getNumberOfAttributes() > 0;
}
public String getName() {
return "Correlate To Attributes...";
}
public String getDescription() {
return "Correlate assigned (or summarized) counts for nodes with a selected attribute";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
}
| 6,554 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
PasteCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/clipboard/PasteCommand.java | /*
* PasteCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.clipboard;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import javax.swing.*;
import javax.swing.text.DefaultEditorKit;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class PasteCommand extends ClipboardBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
Action action = findAction(DefaultEditorKit.pasteAction);
if (action != null)
action.actionPerformed(event);
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Paste";
}
public String getDescription() {
return "Paste";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Paste16.gif");
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_V, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
}
| 2,013 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CopyEdgeLabelCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/clipboard/CopyEdgeLabelCommand.java | /*
* CopyEdgeLabelCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.clipboard;
import jloda.graph.Edge;
import jloda.swing.commands.ICommand;
import jloda.swing.graphview.GraphView;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
public class CopyEdgeLabelCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
GraphView viewer = (GraphView) getViewer();
StringBuilder buf = new StringBuilder();
boolean first = true;
for (Edge e : viewer.getSelectedEdges()) {
String label = viewer.getLabel(e);
if (label != null) {
if (first)
first = false;
else
buf.append(" ");
buf.append(label);
}
}
if (buf.toString().length() > 0) {
StringSelection selection = new StringSelection(buf.toString());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, null);
}
}
public boolean isApplicable() {
return ((GraphView) getViewer()).getSelectedEdges().size() > 0;
}
public String getName() {
return "Copy Edge Label";
}
public String getDescription() {
return "Copy the edge label";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Copy16.gif");
}
public boolean isCritical() {
return false;
}
}
| 2,539 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ClipboardBase.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/clipboard/ClipboardBase.java | /*
* ClipboardBase.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.clipboard;
import jloda.swing.util.ResourceManager;
import megan.commands.CommandBase;
import javax.swing.*;
import javax.swing.text.DefaultEditorKit;
import java.awt.*;
import java.awt.event.KeyEvent;
/**
* base for cut, copy and paste
* Daniel Huson, 11.2010
*/
public abstract class ClipboardBase extends CommandBase {
// need an instance to get default textComponent Actions
static private DefaultEditorKit kit;
/**
* find the action
*
* @return action
*/
static protected Action findAction(String name) {
if (kit == null)
kit = new DefaultEditorKit();
Action[] actions = kit.getActions();
for (int i = 0; i < kit.getActions().length; i++) {
Action action = actions[i];
if (action.getValue(AbstractAction.NAME).equals(name))
return action;
}
return null;
}
static public Action getCutDefaultKit() {
Action action = findAction(DefaultEditorKit.cutAction);
if (action == null)
return null;
action.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_X,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()));
action.putValue(Action.SHORT_DESCRIPTION, "Cut");
action.putValue(AbstractAction.SMALL_ICON, ResourceManager.getIcon("sun/Cut16.gif"));
return action;
}
static public Action getCopyDefaultKit() {
Action action = findAction(DefaultEditorKit.copyAction);
if (action == null)
return null;
action.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()));
action.putValue(Action.SHORT_DESCRIPTION, "Copy");
action.putValue(AbstractAction.SMALL_ICON, ResourceManager.getIcon("sun/Copy16.gif"));
return action;
}
static public Action getPasteDefaultKit() {
Action action = findAction(DefaultEditorKit.pasteAction);
if (action == null)
return null;
action.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_V, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()));
action.putValue(Action.SHORT_DESCRIPTION, "Paste");
action.putValue(AbstractAction.SMALL_ICON, ResourceManager.getIcon("sun/Paste16.gif"));
return action;
}
static public Action getSelectAllDefaultEditorKit() {
Action action = findAction(DefaultEditorKit.selectAllAction);
if (action == null)
return null;
action.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()));
action.putValue(Action.SHORT_DESCRIPTION, "Select All");
return action;
}
}
| 3,664 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CopyCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/clipboard/CopyCommand.java | /*
* CopyCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.clipboard;
import jloda.swing.commands.ICommand;
import jloda.swing.director.IDirectableViewer;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.viewer.ViewerBase;
import javax.swing.*;
import javax.swing.text.DefaultEditorKit;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class CopyCommand extends ClipboardBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
IDirectableViewer viewer = getViewer();
if (viewer instanceof ViewerBase) {
ViewerBase graphView = (ViewerBase) viewer;
if (graphView.getSelectedNodes().size() > 0) {
StringBuilder buf = new StringBuilder();
boolean first = true;
for (String label : graphView.getSelectedNodeLabels(true)) {
if (label != null) {
if (first)
first = false;
else
buf.append("\n");
buf.append(label);
}
}
if (buf.toString().length() > 0) {
StringSelection selection = new StringSelection(buf.toString());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, null);
return;
}
}
}
Action action = findAction(DefaultEditorKit.copyAction);
if (action != null)
action.actionPerformed(event);
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Copy";
}
public String getDescription() {
return "Copy";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Copy16.gif");
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
}
| 3,093 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CutCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/clipboard/CutCommand.java | /*
* CutCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.clipboard;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import javax.swing.*;
import javax.swing.text.DefaultEditorKit;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class CutCommand extends ClipboardBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
Action action = findAction(DefaultEditorKit.cutAction);
if (action != null)
action.actionPerformed(event);
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Cut";
}
public String getDescription() {
return "Cut";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Cut16.gif");
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_X, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
}
| 2,001 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CopyNodeLabelCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/clipboard/CopyNodeLabelCommand.java | /*
* CopyNodeLabelCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.clipboard;
import jloda.swing.commands.ICommand;
import jloda.swing.graphview.GraphView;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.viewer.ViewerBase;
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
public class CopyNodeLabelCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
ViewerBase viewer = (ViewerBase) getViewer();
StringBuilder buf = new StringBuilder();
boolean first = true;
for (String label : viewer.getSelectedNodeLabels(true)) {
if (label != null) {
if (first)
first = false;
else
buf.append(" ");
buf.append(label);
}
}
if (buf.toString().length() > 0) {
StringSelection selection = new StringSelection(buf.toString());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, null);
}
}
public boolean isApplicable() {
return getViewer() instanceof GraphView && ((GraphView) getViewer()).getSelectedNodes().size() > 0;
}
public String getName() {
return "Copy Node Label";
}
public String getDescription() {
return "Copy the node label";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Copy16.gif");
}
public boolean isCritical() {
return false;
}
}
| 2,553 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
FindCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/find/FindCommand.java | /*
* FindCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.find;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.director.IViewerWithFindToolBar;
import jloda.swing.util.ResourceManager;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.parse.NexusStreamParser;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* Open the Find dialog
* Daniel Huson, 7 2010
*/
public class FindCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
return getViewer() instanceof IViewerWithFindToolBar && ((IViewerWithFindToolBar) getViewer()).isShowFindToolBar();
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Find...";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Open the find toolbar";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Find16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_F, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("show findToolbar=");
boolean show = np.getBoolean();
np.matchIgnoreCase(";");
if (getViewer() instanceof IViewerWithFindToolBar) {
IViewerWithFindToolBar viewer = (IViewerWithFindToolBar) getViewer();
if (show) {
if (!viewer.getSearchManager().getFindDialogAsToolBar().isEnabled())
viewer.setShowFindToolBar(true);
else
viewer.getSearchManager().getFindDialogAsToolBar().setEnabled(true); // refocus
} else
viewer.setShowFindToolBar(false);
} else {
NotificationsInSwing.showWarning(getViewer().getFrame(), "Find not implemented for this type of window");
}
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "show findToolbar={true|false};";
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return getViewer() instanceof IViewerWithFindToolBar;
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
execute("show findToolbar=true;");
}
}
| 4,034 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
FindAgainCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/find/FindAgainCommand.java | /*
* FindAgainCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.find;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.director.IViewerWithFindToolBar;
import jloda.swing.find.SearchManager;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* Find again
* Daniel Huson, 7 2010
*/
public class FindAgainCommand extends CommandBase implements ICommand {
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Find Again";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Find the next occurrence";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/FindAgain16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_G, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return getViewer() instanceof IViewerWithFindToolBar && ((IViewerWithFindToolBar) getViewer()).isShowFindToolBar();
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
SearchManager searchManager = ((IViewerWithFindToolBar) getViewer()).getSearchManager();
if (searchManager != null)
searchManager.applyFindNext();
}
}
| 3,238 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
DrawCirclesCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/compare/DrawCirclesCommand.java | /*
* DrawCirclesCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.compare;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.viewer.ViewerBase;
import megan.viewer.gui.NodeDrawer;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class DrawCirclesCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
ViewerBase viewer = (ViewerBase) getViewer();
return viewer != null && viewer.getNodeDrawer().getStyle() == NodeDrawer.Style.Circle;
}
public String getSyntax() {
return null;
}
public void actionPerformed(ActionEvent event) {
execute("set nodeDrawer=" + NodeDrawer.Style.Circle + ";");
}
public String getName() {
return "Draw Circles";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Circle16.gif");
}
public String getDescription() {
return "Draw data as circles";
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return getDoc().getNumberOfReads() > 0;
}
/**
* parses the given command and executes it
*/
public void apply(NexusStreamParser np) {
}
}
| 2,420 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
DrawMetersCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/compare/DrawMetersCommand.java | /*
* DrawMetersCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.compare;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.viewer.ViewerBase;
import megan.viewer.gui.NodeDrawer;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class DrawMetersCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
ViewerBase viewer = (ViewerBase) getViewer();
return viewer != null && viewer.getNodeDrawer().getStyle() == NodeDrawer.Style.BarChart;
}
public String getSyntax() {
return null;
}
public void actionPerformed(ActionEvent event) {
execute("set nodeDrawer=" + NodeDrawer.Style.BarChart + ";");
}
public String getName() {
return "Draw Bars";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Meters16.gif");
}
public String getDescription() {
return "Draw nodes as bars";
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return getDoc().getNumberOfReads() > 0;
}
/**
* parses the given command and executes it
*/
public void apply(NexusStreamParser np) {
}
}
| 2,416 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
DrawPieChartsCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/compare/DrawPieChartsCommand.java | /*
* DrawPieChartsCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.compare;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.core.Document;
import megan.main.MeganProperties;
import megan.viewer.ViewerBase;
import megan.viewer.gui.NodeDrawer;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class DrawPieChartsCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
ViewerBase viewer = (ViewerBase) getViewer();
return viewer != null && viewer.getNodeDrawer().getStyle() == NodeDrawer.Style.PieChart;
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set nodeDrawer=");
final ViewerBase viewer = (ViewerBase) getViewer();
final Document doc = getDoc();
final String style = np.getWordMatchesIgnoringCase(StringUtils.toString(NodeDrawer.Style.values(), " "));
np.matchIgnoreCase(";");
viewer.getNodeDrawer().setStyle(style, NodeDrawer.Style.Circle);
viewer.getLegendPanel().setStyle(viewer.getNodeDrawer().getStyle());
doc.setDirty(true);
if (doc.getNumberOfSamples() > 1)
ProgramProperties.put(MeganProperties.COMPARISON_STYLE, style);
viewer.repaint();
}
public String getSyntax() {
return "set nodeDrawer={" + StringUtils.toString(NodeDrawer.ScaleBy.values(), "|") + "};";
}
public void actionPerformed(ActionEvent event) {
execute("set nodeDrawer=" + NodeDrawer.Style.PieChart + ";");
}
public String getName() {
return "Draw Pies";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("PieChart16.gif");
}
public String getDescription() {
return "Draw data as pie charts";
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return getDoc().getNumberOfReads() > 0;
}
}
| 3,205 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
DrawHeatMapCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/compare/DrawHeatMapCommand.java | /*
* DrawHeatMapCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.compare;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.viewer.ViewerBase;
import megan.viewer.gui.NodeDrawer;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class DrawHeatMapCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
ViewerBase viewer = (ViewerBase) getViewer();
return viewer != null && viewer.getNodeDrawer().getStyle() == NodeDrawer.Style.HeatMap;
}
public String getSyntax() {
return null;
}
public void actionPerformed(ActionEvent event) {
execute("set nodeDrawer=" + NodeDrawer.Style.HeatMap + ";");
}
public String getName() {
return "Draw Heatmaps";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("HeatMap16.gif");
}
public String getDescription() {
return "Draw data as heat maps";
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return getDoc().getNumberOfReads() > 0;
}
/**
* parses the given command and executes it
*/
public void apply(NexusStreamParser np) {
}
}
| 2,424 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
DrawCoxCombsCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/compare/DrawCoxCombsCommand.java | /*
* DrawCoxCombsCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.compare;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.core.Director;
import megan.viewer.ViewerBase;
import megan.viewer.gui.NodeDrawer;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class DrawCoxCombsCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
ViewerBase viewer = (ViewerBase) getViewer();
return viewer != null && viewer.getNodeDrawer().getStyle() == NodeDrawer.Style.CoxComb;
}
public String getSyntax() {
return null;
}
public void actionPerformed(ActionEvent event) {
execute("set nodeDrawer=" + NodeDrawer.Style.CoxComb + ";");
}
public String getName() {
return "Draw Coxcombs";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Coxcomb16.gif");
}
public String getDescription() {
return "Draw data as coxcombs";
}
public boolean isApplicable() {
return ((Director) getDir()).getDocument().getNumberOfReads() > 0 && ((Director) getDir()).getDocument().getNumberOfSamples() > 1;
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
}
| 2,591 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
UseDefaultTaxonomyFileCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/load/UseDefaultTaxonomyFileCommand.java | /*
* UseDefaultTaxonomyFileCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.load;
import jloda.swing.commands.ICommand;
import jloda.swing.director.ProjectManager;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.core.Director;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* load command
* Daniel Huson, 11.2010
*/
public class UseDefaultTaxonomyFileCommand extends CommandBase implements ICommand {
public static final String NAME="Use Default NCBI Taxonomy";
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Open default NCBI taxonomy";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
execute("load taxonomyFile=ncbi.tre mapfile=ncbi.map;collapse level=2;");
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return ProjectManager.getNumberOfProjects() == 1 && ((Director) ProjectManager.getProjects().get(0)).getDocument().getNumberOfSamples() == 0;
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
}
| 2,997 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
LoadAlternativeTaxonomyFileCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/load/LoadAlternativeTaxonomyFileCommand.java | /*
* LoadAlternativeTaxonomyFileCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.load;
import jloda.swing.commands.ICommand;
import jloda.swing.director.ProjectManager;
import jloda.swing.util.ChooseFileDialog;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.swing.util.TextFileFilter;
import jloda.util.FileUtils;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.core.Director;
import megan.main.MeganProperties;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
/**
* load command
* Daniel Huson, 11.2010
*/
public class LoadAlternativeTaxonomyFileCommand extends CommandBase implements ICommand {
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Use Alternative Taxonomy...";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Open alternative taxonomy.tre and taxonomy.map files";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Open16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
File lastOpenFile = ProgramProperties.getFile(MeganProperties.TAXONOMYFILE);
getDir().notifyLockInput();
File file = ChooseFileDialog.chooseFileToOpen(getViewer().getFrame(), lastOpenFile, new TextFileFilter("tre"), new TextFileFilter("tre"), ev, "Open Tree File");
getDir().notifyUnlockInput();
if (file != null && file.exists() && file.canRead()) {
ProgramProperties.put(MeganProperties.TAXONOMYFILE, file.getAbsolutePath());
String mappingFile = FileUtils.replaceFileSuffix(file.getPath(), ".map");
if (!(new File(mappingFile)).exists()) {
mappingFile = null;
}
StringBuilder buf = new StringBuilder();
buf.append("load taxonomyFile='").append(file.getPath()).append("'");
if (mappingFile != null)
buf.append(" mapFile='").append(mappingFile).append("';");
else
buf.append(";");
buf.append("collapse level=2;");
execute(buf.toString());
}
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return ProjectManager.getNumberOfProjects() == 1 && ((Director) ProjectManager.getProjects().get(0)).getDocument().getNumberOfSamples() == 0;
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
}
| 4,251 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
AddClassificationCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/load/AddClassificationCommand.java | /*
* AddClassificationCommand.java Copyright (C) 2022. Daniel H. Huson
*
* No usage, copying or distribution without explicit permission.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
*/
package megan.commands.load;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.CommandManager;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ChooseFileDialog;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.swing.util.TextFileFilter;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.FileUtils;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.main.MeganProperties;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
/**
* add classification command
* Daniel Huson, 4.2021
*/
public class AddClassificationCommand extends CommandBase implements ICommand {
public AddClassificationCommand() {
}
/**
* constructor
*/
public AddClassificationCommand(CommandManager commandManager) {
super(commandManager);
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("addClassification file=");
var treeFileName = np.getWordFileNamePunctuation();
np.matchWordIgnoreCase(";");
if (!(treeFileName.endsWith(".tre")))
throw new IOException("addClassification: file must have suffix .tre");
if (!FileUtils.fileExistsAndIsNonEmpty(treeFileName))
throw new IOException("addClassification: specified .tre file does not exist or is empty");
var mapFile = FileUtils.replaceFileSuffixKeepGZ(treeFileName, ".map");
if (!FileUtils.fileExistsAndIsNonEmpty(mapFile))
throw new IOException("addClassification: corresponding .map file does not exist or is empty");
var addedClassificationFiles = Arrays.asList(ProgramProperties.get(MeganProperties.ADDITION_CLASSIFICATION_FILES, new String[0]));
var treeFile = new File(treeFileName);
var found = false;
for (var other : addedClassificationFiles) {
if (treeFile.equals(new File(other))) {
found = true;
NotificationsInSwing.showWarning("Classification has already been added, no action will be taken");
break;
}
}
if (!found) {
addedClassificationFiles = new ArrayList<>(addedClassificationFiles);
addedClassificationFiles.add(0, treeFileName);
ProgramProperties.put(MeganProperties.ADDITION_CLASSIFICATION_FILES, addedClassificationFiles.toArray(new String[0]));
System.err.println("All added classification files: " + StringUtils.toString(addedClassificationFiles, ", "));
NotificationsInSwing.showInformation("Classification file has been added, restart MEGAN to use");
}
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Add Classification...";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Adds a classification to MEGAN";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Import16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
var addedClassificationFiles = Arrays.asList(ProgramProperties.get(MeganProperties.ADDITION_CLASSIFICATION_FILES, new String[0]));
var lastOpenFile = (addedClassificationFiles.size() > 0 ? new File(addedClassificationFiles.get(0)) : null);
File file = ChooseFileDialog.chooseFileToOpen(getViewer().getFrame(), lastOpenFile, new TextFileFilter("tre", false), new TextFileFilter("tre", false), ev, "Open Classification Tree File");
if (file != null) {
executeImmediately("addClassification file='" + file.getPath() + "';");
}
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "addClassification file=<file-name>;";
}
}
| 4,762 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
LoadTaxonomyFileCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/load/LoadTaxonomyFileCommand.java | /*
* LoadTaxonomyFileCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.commands.load;
import jloda.graph.Node;
import jloda.swing.commands.ICommand;
import jloda.swing.director.ProjectManager;
import jloda.swing.util.ChooseFileDialog;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.swing.util.TextFileFilter;
import jloda.util.FileUtils;
import jloda.util.parse.NexusStreamParser;
import megan.classification.Classification;
import megan.classification.ClassificationManager;
import megan.commands.CommandBase;
import megan.core.Director;
import megan.core.Document;
import megan.main.MeganProperties;
import megan.viewer.TaxonomyData;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
/**
* load command
* Daniel Huson, 11.2010
*/
public class LoadTaxonomyFileCommand extends CommandBase implements ICommand {
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Load Taxonomy...";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Load taxonomy.tre and taxonomy.map files";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Open16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("load taxonomyFile=");
String treeFile = np.getWordFileNamePunctuation();
String mapFile = null;
if (np.peekMatchAnyTokenIgnoreCase("mapFile")) {
np.matchIgnoreCase("mapFile=");
mapFile = np.getWordFileNamePunctuation();
}
np.matchIgnoreCase(";");
if (mapFile == null)
mapFile = FileUtils.replaceFileSuffix(treeFile, ".map");
final Classification classification = ClassificationManager.load(Classification.Taxonomy, treeFile, mapFile, getDoc().getProgressListener());
TaxonomyData.ensureDisabledTaxaInitialized();
Node v = classification.getFullTree().getRoot();
if (v != null && (Integer) v.getInfo() == 0) {
v.setInfo(1);
classification.getFullTree().addId2Node(0, null);
classification.getFullTree().addId2Node(1, v);
classification.getIdMapper().getName2IdMap().put("Root", 1);
}
ProgramProperties.put(MeganProperties.TAXONOMYFILE, treeFile);
Document.loadVersionInfo("Taxonomy", treeFile);
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
File lastOpenFile = ProgramProperties.getFile(MeganProperties.TAXONOMYFILE);
getDir().notifyLockInput();
File file = ChooseFileDialog.chooseFileToOpen(getViewer().getFrame(), lastOpenFile, new TextFileFilter("tre"), new TextFileFilter("tre"), ev, "Open Tree File");
getDir().notifyUnlockInput();
if (file != null && file.exists() && file.canRead()) {
ProgramProperties.put(MeganProperties.TAXONOMYFILE, file.getAbsolutePath());
String mappingFile = FileUtils.replaceFileSuffix(file.getPath(), ".map");
if (!(new File(mappingFile)).exists()) {
mappingFile = null;
}
StringBuilder buf = new StringBuilder();
buf.append("load taxonomyFile='").append(file.getPath()).append("'");
if (mappingFile != null)
buf.append(" mapFile='").append(mappingFile).append("';");
else
buf.append(";");
buf.append("collapse level=2;");
execute(buf.toString());
}
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return ProjectManager.getNumberOfProjects() == 1 && ((Director) ProjectManager.getProjects().get(0)).getDocument().getNumberOfSamples() == 0;
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "load taxonomyFile=<filename> [mapFile=<filename>];";
}
}
| 5,559 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.