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
AddFilesCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/dialogs/compare/commands/AddFilesCommand.java
/* * AddFilesCommand.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.dialogs.compare.commands; import jloda.swing.commands.ICommand; import jloda.swing.director.IDirector; 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.dialogs.compare.CompareWindow; import megan.main.MeganProperties; import megan.util.MeganAndRMAFileFilter; import megan.util.MeganizedDAAFileFilter; import javax.swing.*; import java.awt.event.ActionEvent; import java.io.File; import java.util.Collection; /** * the add files command * Daniel Huson, 9.2105 */ public class AddFilesCommand extends CommandBase implements ICommand { /** * constructor */ public AddFilesCommand() { } /** * constructor * */ public AddFilesCommand(IDirector dir) { setDir(dir); } /** * get the name to be used as a menu label * * @return name */ public String getName() { return NAME; } public static final String NAME = "Add Files..."; /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Add files for comparison"; } /** * 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("add file="); final String fileName = np.getAbsoluteFileName(); np.matchIgnoreCase(";"); FileUtils.checkFileReadableNonEmpty(fileName); CompareWindow viewer = (CompareWindow) getParent(); viewer.addFile(fileName); } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { File lastOpenFile = ProgramProperties.getFile(MeganProperties.MEGANFILE); MeganAndRMAFileFilter meganAndRMAFileFilter = new MeganAndRMAFileFilter(); meganAndRMAFileFilter.setAllowGZipped(true); meganAndRMAFileFilter.setAllowZipped(true); meganAndRMAFileFilter.add(MeganizedDAAFileFilter.getInstance()); getDir().notifyLockInput(); CompareWindow viewer = (CompareWindow) getParent(); Collection<File> files; try { files = ChooseFileDialog.chooseFilesToOpen(viewer, lastOpenFile, meganAndRMAFileFilter, meganAndRMAFileFilter, ev, "Add MEGAN file"); } finally { getDir().notifyUnlockInput(); } if (files.size() > 0) { StringBuilder buf = new StringBuilder(); for (File file : files) { if (file != null && file.exists() && file.canRead()) { ProgramProperties.put(MeganProperties.MEGANFILE, file.getAbsolutePath()); buf.append("add file='").append(file.getPath()).append("';"); } } 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 true; } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "add file=<filename>;"; } }
4,792
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetAbsoluteModeCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/dialogs/compare/commands/SetAbsoluteModeCommand.java
/* * SetAbsoluteModeCommand.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.dialogs.compare.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICheckBoxCommand; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.dialogs.compare.CompareWindow; import megan.dialogs.compare.Comparer; import javax.swing.*; import java.awt.event.ActionEvent; /** * command * Daniel Huson, 11.2010 */ public class SetAbsoluteModeCommand extends CommandBase implements ICheckBoxCommand { public boolean isSelected() { CompareWindow viewer = (CompareWindow) getParent(); return viewer != null && viewer.getMode().equals(Comparer.COMPARISON_MODE.ABSOLUTE); } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set mode="); String mode = np.getLabelRespectCase(); np.matchIgnoreCase(";"); CompareWindow viewer = (CompareWindow) getParent(); viewer.setMode(Comparer.COMPARISON_MODE.valueOfIgnoreCase(mode)); } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "set mode={" + StringUtils.toString(Comparer.COMPARISON_MODE.values(), "|") + "};"; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { executeImmediately("set mode=" + (Comparer.COMPARISON_MODE.ABSOLUTE) + ";"); CompareWindow viewer = (CompareWindow) getParent(); viewer.getCommandManager().updateEnableState(); } final public static String NAME = "Use Absolute Counts"; /** * 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 "Set comparison mode"; } /** * 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() { CompareWindow viewer = (CompareWindow) getParent(); return viewer != null; } }
3,659
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetKeep1Command.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/dialogs/compare/commands/SetKeep1Command.java
/* * SetKeep1Command.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.dialogs.compare.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICheckBoxCommand; import jloda.util.parse.NexusStreamParser; import megan.dialogs.compare.CompareWindow; import megan.dialogs.compare.Comparer; import javax.swing.*; import java.awt.event.ActionEvent; /** * command * Daniel Huson, 2.2016 */ public class SetKeep1Command extends CommandBase implements ICheckBoxCommand { public boolean isSelected() { CompareWindow viewer = (CompareWindow) getParent(); return viewer != null && viewer.isKeep1(); } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set keep1="); boolean value = np.getBoolean(); np.matchIgnoreCase(";"); CompareWindow viewer = (CompareWindow) getParent(); viewer.setKeep1(value); } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "set keep1={false|true};"; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { executeImmediately("set keep1=" + (!isSelected()) + ";"); } final public static String NAME = "Keep at least 1 read"; /** * 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 "Always keep at least one read when normalizing"; } /** * 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() { final CompareWindow viewer = (CompareWindow) getParent(); return viewer != null && viewer.getMode() == Comparer.COMPARISON_MODE.RELATIVE; } }
3,428
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetIgnoreNoHitsCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/dialogs/compare/commands/SetIgnoreNoHitsCommand.java
/* * SetIgnoreNoHitsCommand.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.dialogs.compare.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICheckBoxCommand; import jloda.util.parse.NexusStreamParser; import megan.dialogs.compare.CompareWindow; import javax.swing.*; import java.awt.event.ActionEvent; /** * command * Daniel Huson, 11.2010 */ public class SetIgnoreNoHitsCommand extends CommandBase implements ICheckBoxCommand { public boolean isSelected() { CompareWindow viewer = (CompareWindow) getParent(); return viewer != null && viewer.isIgnoreNoHits(); } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set ignoreUnassigned="); boolean value = np.getBoolean(); np.matchIgnoreCase(";"); CompareWindow viewer = (CompareWindow) getParent(); viewer.setIgnoreNoHits(value); } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "set ignoreUnassigned={true|false};"; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { executeImmediately("set ignoreUnassigned=" + (!isSelected()) + ";"); } final public static String NAME = "Ignore all unassigned reads"; /** * 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 "Ignore all reads placed on the no-hits, not-assigned or low-complexity node"; } /** * 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() { CompareWindow viewer = (CompareWindow) getParent(); return viewer != null; } }
3,424
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/dialogs/compare/commands/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.dialogs.compare.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.util.parse.NexusStreamParser; import megan.dialogs.compare.CompareWindow; import javax.swing.*; import java.awt.event.ActionEvent; /** * command * Daniel Huson, 11.2010 */ public class SelectNoneCommand extends CommandBase implements ICommand { /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase(getSyntax()); CompareWindow viewer = (CompareWindow) getParent(); viewer.getJList().clearSelection(); } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "select datasets=none;"; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { executeImmediately(getSyntax()); } public static final String NAME = "Select None"; public String getName() { return NAME; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Deselect all datasets"; } /** * 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() { CompareWindow viewer = (CompareWindow) getParent(); return viewer != null && viewer.getJList().getSelectedValuesList().size() >= 1; } }
3,005
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SelectAllCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/dialogs/compare/commands/SelectAllCommand.java
/* * SelectAllCommand.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.dialogs.compare.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.util.parse.NexusStreamParser; import megan.dialogs.compare.CompareWindow; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; /** * command * Daniel Huson, 11.2010 */ public class SelectAllCommand extends CommandBase implements ICommand { /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase(getSyntax()); CompareWindow viewer = (CompareWindow) getParent(); viewer.getJList().setSelectionInterval(0, viewer.getListModel().getSize() - 1); viewer.getJList().setSelectionInterval(0, viewer.getListModel().getSize() - 1); } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "select datasets=all;"; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { executeImmediately(getSyntax()); } public static final String NAME = "Select All"; public String getName() { return NAME; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Select all datasets"; } /** * 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 KeyStroke.getKeyStroke(KeyEvent.VK_A, 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 getParent() != null; } }
3,159
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetNormalizedModeCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/dialogs/compare/commands/SetNormalizedModeCommand.java
/* * SetNormalizedModeCommand.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.dialogs.compare.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICheckBoxCommand; import jloda.util.parse.NexusStreamParser; import megan.dialogs.compare.CompareWindow; import megan.dialogs.compare.Comparer; import javax.swing.*; import java.awt.event.ActionEvent; /** * command * Daniel Huson, 11.2010 */ public class SetNormalizedModeCommand extends CommandBase implements ICheckBoxCommand { public boolean isSelected() { CompareWindow viewer = (CompareWindow) getParent(); return viewer != null && viewer.getMode().equals(Comparer.COMPARISON_MODE.RELATIVE); } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) { } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return null; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { executeImmediately("set mode=" + (Comparer.COMPARISON_MODE.RELATIVE) + ";"); CompareWindow viewer = (CompareWindow) getParent(); viewer.getCommandManager().updateEnableState(); } final public static String NAME = "Use Normalized Counts"; /** * 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 "Normalize the counts for samples to equal the smallest count"; } /** * 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() { CompareWindow viewer = (CompareWindow) getParent(); return viewer != null; } }
3,329
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
CancelCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/dialogs/compare/commands/CancelCommand.java
/* * CancelCommand.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.dialogs.compare.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.util.parse.NexusStreamParser; import megan.dialogs.compare.CompareWindow; import javax.swing.*; import java.awt.event.ActionEvent; /** * command * Daniel Huson, 11.2010 */ public class CancelCommand extends CommandBase implements ICommand { /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase(getSyntax()); CompareWindow viewer = (CompareWindow) getParent(); viewer.setVisible(false); } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "cancel;"; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { executeImmediately(getSyntax()); } public static final String NAME = "Cancel"; public String getName() { return NAME; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Cancel and close this dialog"; } /** * 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() { CompareWindow viewer = (CompareWindow) getParent(); return viewer != null; } }
2,917
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ApplyCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/dialogs/compare/commands/ApplyCommand.java
/* * ApplyCommand.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.dialogs.compare.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.util.parse.NexusStreamParser; import megan.core.Document; import megan.dialogs.compare.CompareWindow; import megan.dialogs.compare.Comparer; import megan.dialogs.compare.MyListItem; import javax.swing.*; import java.awt.event.ActionEvent; /** * command * Daniel Huson, 11.2010 */ public class ApplyCommand extends CommandBase implements ICommand { /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase(getSyntax()); CompareWindow viewer = (CompareWindow) getParent(); viewer.setCanceled(false); viewer.setVisible(false); } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "apply;"; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { executeImmediately(getSyntax()); } public static final String NAME = "Apply"; public String getName() { return NAME; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Create the comparison in a new window"; } /** * 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() { if (getParent() != null && getParent() instanceof CompareWindow) { final CompareWindow viewer = (CompareWindow) getParent(); if (viewer.getJList().getSelectedValuesList().size() >= 1) { if (viewer.getMode() == Comparer.COMPARISON_MODE.RELATIVE) return true; Document.ReadAssignmentMode readAssignmentMode = null; for (Object obj : viewer.getJList().getSelectedValuesList()) { final MyListItem myListItem = (MyListItem) obj; if (readAssignmentMode == null) readAssignmentMode = myListItem.getReadAssignmentMode(); else if (readAssignmentMode != myListItem.getReadAssignmentMode()) return false; } return true; } } return false; } }
3,869
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
IdMapper.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/IdMapper.java
/* * IdMapper.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.classification; import jloda.swing.util.ProgramProperties; import jloda.util.Basic; import jloda.util.progress.ProgressListener; import jloda.util.progress.ProgressSilent; import megan.accessiondb.AccessAccessionAdapter; import megan.classification.data.*; import megan.main.MeganProperties; import java.io.IOException; import java.util.*; /** * tracks mapping files for a named type of classification * <p> * Daniel Huson, 4.2015 */ public class IdMapper { static public final int NOHITS_ID = -1; static public final String NOHITS_LABEL = "No hits"; static public final int UNASSIGNED_ID = -2; static public final String UNASSIGNED_LABEL = "Not assigned"; static public final int LOW_COMPLEXITY_ID = -3; static public final String LOW_COMPLEXITY_LABEL = "Low complexity"; static public final int UNCLASSIFIED_ID = -4; static public final String UNCLASSIFIED_LABEL = "Unclassified"; static public final int CONTAMINANTS_ID = -6; // -5 used by KEGG static public final String CONTAMINANTS_LABEL = "Contaminants"; public static IString2IntegerMapFactory accessionMapFactory = new Accession2IdMapFactory(); public enum MapType {Accession, Synonyms, MeganMapDB} private final String cName; private final EnumMap<MapType, String> map2Filename = new EnumMap<>(MapType.class); private final EnumSet<MapType> loadedMaps = EnumSet.noneOf(MapType.class); private final EnumSet<MapType> activeMaps = EnumSet.noneOf(MapType.class); final ClassificationFullTree fullTree; private final Name2IdMap name2IdMap; private boolean useTextParsing; private final Set<Integer> disabledIds = new HashSet<>(); private IString2IntegerMap accessionMap = null; private String2IntegerMap synonymsMap = null; private final IdParser.Algorithm algorithm; /** * constructor * */ public IdMapper(String name, ClassificationFullTree fullTree, Name2IdMap name2IdMap) { this.cName = name; this.fullTree = fullTree; this.name2IdMap = name2IdMap; algorithm = (Arrays.asList(ProgramProperties.get(MeganProperties.TAXONOMIC_CLASSIFICATIONS, new String[]{"Taxonomy", "GTDB"})).contains(name) ? IdParser.Algorithm.LCA : IdParser.Algorithm.First_Hit); } /** * create tags for parsing header line * * @return short tag */ public static String[] createTags(String cName) { String shortTag = Classification.createShortTag(cName); String longTag = cName.toLowerCase() + "|"; if (shortTag.equals(longTag)) return new String[]{shortTag}; else return new String[]{shortTag, longTag}; } /** * load the named file of the given map type * */ public void loadMappingFile(String fileName, MapType mapType, boolean reload, ProgressListener progress) throws IOException { switch (mapType) { case Accession -> { if (accessionMap == null || reload) { if (accessionMap != null) { closeAccessionMap(); } this.accessionMap = accessionMapFactory.create(name2IdMap, fileName, progress); loadedMaps.add(mapType); activeMaps.add(mapType); map2Filename.put(mapType, fileName); } } case Synonyms -> { if (synonymsMap == null || reload) { if (synonymsMap != null) { synonymsMap.close(); } final String2IntegerMap synonymsMap = new String2IntegerMap(); synonymsMap.loadFile(name2IdMap, fileName, progress); this.synonymsMap = synonymsMap; loadedMaps.add(mapType); activeMaps.add(mapType); map2Filename.put(mapType, fileName); } } case MeganMapDB -> { if (accessionMap == null || reload) { if (accessionMap != null) { closeAccessionMap(); } try { this.accessionMap = new AccessAccessionAdapter(fileName, cName); loadedMaps.add(mapType); activeMaps.add(mapType); map2Filename.put(mapType, fileName); } catch (Exception e) { throw new IOException(e); } } } } } /** * is the named parsing method loaded * * @return true, if loaded */ public boolean isLoaded(MapType mapType) { return loadedMaps.contains(mapType); } public boolean isActiveMap(MapType mapType) { return activeMaps.contains(mapType); } public void setActiveMap(MapType mapType, boolean state) { if (state) activeMaps.add(mapType); else activeMaps.remove(mapType); } public void setUseTextParsing(boolean useTextParsing) { this.useTextParsing = useTextParsing; } public boolean isUseTextParsing() { return useTextParsing; } /** * creates a new id parser for this mapper * */ public IdParser createIdParser() { // the follow code ensures that we use multiple accesses to the sqlite mapping database if (accessionMap instanceof AccessAccessionAdapter) { final IdMapper copy = new IdMapper(cName, fullTree, name2IdMap); copy.setActiveMap(MapType.MeganMapDB, true); copy.setUseTextParsing(isUseTextParsing()); try { copy.loadMappingFile(((AccessAccessionAdapter) accessionMap).getMappingDBFile(), MapType.MeganMapDB, false, new ProgressSilent()); } catch (IOException e) { Basic.caught(e); } final IdParser idParser = new IdParser(copy); idParser.setAlgorithm(algorithm); return idParser; } else { final IdParser idParser = new IdParser(this); idParser.setAlgorithm(algorithm); return idParser; } } /** * get a id from an accession * * @return KO id or null */ public Integer getIdFromAccession(String accession) throws IOException { if (isLoaded(MapType.Accession) || isLoaded(MapType.MeganMapDB)) { return getAccessionMap().get(accession); } return null; } public String getMappingFile(MapType mapType) { return map2Filename.get(mapType); } public IString2IntegerMap getAccessionMap() { return accessionMap; } public String2IntegerMap getSynonymsMap() { return synonymsMap; } public boolean hasActiveAndLoaded() { return activeMaps.size() > 0 && loadedMaps.size() > 0; } public String getCName() { return cName; } public String[] getIdTags() { if (ProgramProperties.get(cName + "ParseIds", false)) { return ProgramProperties.get(cName + "Tags", createTags(cName)); // user can override tags using program property } else return new String[0]; } public Name2IdMap getName2IdMap() { return name2IdMap; } public Set<Integer> getDisabledIds() { return disabledIds; } private void closeAccessionMap() { if (accessionMap != null) { try { accessionMap.close(); } catch (IOException e) { Basic.caught(e); } } accessionMap = null; } public boolean isDisabled(int id) { return disabledIds.size() > 0 && disabledIds.contains(id); } }
8,674
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Classification.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/Classification.java
/* * Classification.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.classification; import jloda.swing.window.NotificationsInSwing; import jloda.util.Basic; import jloda.util.FileUtils; import jloda.util.StringUtils; import jloda.util.progress.ProgressListener; import megan.classification.data.ClassificationFullTree; import megan.classification.data.Name2IdMap; import megan.core.Document; import megan.viewer.MainViewer; import megan.viewer.TaxonomyData; import java.util.ArrayList; import java.util.Map; /** * data structures needed for parsing and representing a classification * Daniel Huson, 4.2015 */ public class Classification { public static final String Taxonomy = "Taxonomy"; private final String cName; private final ClassificationFullTree fullTree; private final Name2IdMap name2IdMap; private final IdMapper idMapper; /** * constructor * */ public Classification(String cName) { this.cName = cName; name2IdMap = new Name2IdMap(); fullTree = new ClassificationFullTree(cName, name2IdMap); fullTree.setRoot(fullTree.newNode(-1)); this.idMapper = new IdMapper(cName, fullTree, name2IdMap); if (cName.equals(Taxonomy)) { TaxonomyData.setTaxonomyClassification(this); } } /** * load the data * */ public void load(String treeFile, String mapFile, ProgressListener progress) { progress.setCancelable(false); try { progress.setSubtask("Loading " + mapFile); progress.setMaximum(2); progress.setProgress(0); Document.loadVersionInfo(cName + " tree", FileUtils.replaceFileSuffix(treeFile, ".info")); name2IdMap.loadFromFile(mapFile); progress.setProgress(1); progress.setSubtask("Loading " + treeFile); if (cName.equals(Classification.Taxonomy)) { if (name2IdMap.get(3554) != null && name2IdMap.get(3554).equals("Beta")) name2IdMap.put("Beta <vulgaris>", 3554); // this is the cause of many false positives } fullTree.loadFromFile(treeFile); progress.setProgress(2); } catch (Exception e) { Basic.caught(e); NotificationsInSwing.showError(MainViewer.getLastActiveFrame(), "Failed to open files: " + treeFile + " and " + mapFile + ": " + e.getMessage()); } finally { progress.setCancelable(true); } } /** * get classification name * * @return name */ public String getName() { return cName; } /** * get mapper * */ public IdMapper getIdMapper() { return idMapper; } public ClassificationFullTree getFullTree() { return fullTree; } public Name2IdMap getName2IdMap() { return name2IdMap; } public Map<Integer, Integer> getId2Rank() { return name2IdMap.getId2Rank(); } public Map<Integer, String> getId2ToolTip() { return name2IdMap.getId2ToolTip(); } /** * create short tag for writing header line * * @return short tag */ public static String createShortTag(String cName) { if (cName.equalsIgnoreCase(Taxonomy)) return "tax|"; else if (cName.equalsIgnoreCase("interpro2go")) return "IPR|"; else if (cName.equalsIgnoreCase("eggnog")) return "cog|"; else return cName.toLowerCase() + "|"; } public String getPath(int id) { return getPath(id, "|"); } public String getPath(int id, String separator) { var node = getFullTree().getANode(id); var list = new ArrayList<String>(); while (node != null) { list.add(0, idMapper.getName2IdMap().get((int) node.getInfo())); node = node.getParent(); } return StringUtils.toString(list, separator); } }
4,604
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
IdParser.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/IdParser.java
/* * IdParser.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.classification; import jloda.swing.util.ProgramProperties; import jloda.util.NumberUtils; import jloda.util.StringUtils; import megan.classification.data.Name2IdMap; import megan.classification.util.MultiWords; import megan.classification.util.TaggedValueIterator; import java.io.IOException; import java.util.*; /** * this class does the work of parsing ids based on the given idMapper * Daniel Huson, 4.2015, 3.2016 */ public class IdParser { public static final String[] ACCESSION_TAGS = new String[]{"gb|", "ref|"}; public static final String REFSEQ_TAG = "ref|"; public static final String PROPERTIES_FIRST_WORD_IS_ACCESSION = "FirstWordIsAccession"; public static final String PROPERTIES_ACCESSION_TAGS = "AccessionTags"; public enum Algorithm {First_Hit, Majority, LCA} private final IdMapper idMapper; private boolean useTextParsing; private Algorithm algorithm = Algorithm.First_Hit; private final Set<Integer> disabledIds = new HashSet<>(); private final Map<Integer, Integer> id2count = new HashMap<>(); private final Set<Integer> ids = new HashSet<>(); private final Set<Integer> disabled = new HashSet<>(); private final boolean isTaxonomy; private final MultiWords multiWords; private final Map<Integer, int[]> id2segment = new HashMap<>(); private final TaggedValueIterator taggedIds; private final TaggedValueIterator accTaggedIds; private int maxWarnings = 10; /** * constructor * */ public IdParser(IdMapper idMapper) { this.idMapper = idMapper; this.useTextParsing = idMapper.isUseTextParsing(); disabledIds.addAll(idMapper.getDisabledIds()); isTaxonomy = idMapper.getCName().equals(Classification.Taxonomy); multiWords = new MultiWords(); final boolean accessionOrDB = (idMapper.isActiveMap(IdMapper.MapType.Accession) && idMapper.isLoaded(IdMapper.MapType.Accession)) || (idMapper.isActiveMap(IdMapper.MapType.MeganMapDB) && idMapper.isLoaded(IdMapper.MapType.MeganMapDB)); taggedIds = new TaggedValueIterator(false, true, idMapper.getIdTags()); accTaggedIds = new TaggedValueIterator(ProgramProperties.get(PROPERTIES_FIRST_WORD_IS_ACCESSION, true), accessionOrDB, ProgramProperties.get(PROPERTIES_ACCESSION_TAGS, ACCESSION_TAGS)); } /** * Attempt to determine Id from header line. * * @return ID or 0 */ public int getIdFromHeaderLine(String headerString) throws IOException { if (headerString == null) return 0; ids.clear(); disabled.clear(); headerString = headerString.trim(); // look for ID tag: if (taggedIds.isEnabled()) { taggedIds.restart(headerString); for (String label : taggedIds) { try { int id = NumberUtils.parseInt(label); if (id != 0) { if (disabledIds.contains(id)) disabled.add(id); else { switch (algorithm) { default: case First_Hit: return id; case LCA: ids.add(id); break; case Majority: id2count.put(id,id2count.getOrDefault(id,0)+1); break; } } } } catch (NumberFormatException ex) { if (maxWarnings > 0) { System.err.println("parseInt() failed: " + label); maxWarnings--; } } } } // if synonyms file given, try to find occurrence of synonym if (idMapper.isActiveMap(IdMapper.MapType.Synonyms) && idMapper.isLoaded(IdMapper.MapType.Synonyms)) { final int countLabels = multiWords.compute(headerString); for (int i = 0; i < countLabels; i++) { final String label = multiWords.getWord(i); Integer id = idMapper.getSynonymsMap().get(label); if (id != null && id != 0) { if (disabledIds.contains(id)) disabled.add(id); else { switch (algorithm) { default: case First_Hit: return id; case LCA: ids.add(id); break; case Majority: id2count.put(id,id2count.getOrDefault(id,0)+1); break; } } } } } // Look for accession mapping if (accTaggedIds.isEnabled()) { accTaggedIds.restart(headerString); for (String label : accTaggedIds) { final int id = idMapper.getAccessionMap().get(label); if (id > 0) { if (disabledIds.contains(id)) disabled.add(id); else { switch (algorithm) { default: case First_Hit: return id; case LCA: ids.add(id); break; case Majority: id2count.put(id,id2count.getOrDefault(id,0)+1); break; } } } } } // if text parsing is allowed and no ids have been found yet: if (isTaxonomy && useTextParsing && ids.size() == 0 && disabled.size() == 0) { // parse taxonomic path in which taxa are separated by ; final int countSemiColons = StringUtils.countOccurrences(headerString, ';'); if (countSemiColons > 0 && countSemiColons >= (headerString.length() / 32)) // assume is taxonomy path e.g. Bacteria;Proteobacteria; { // find last legal name int taxId = 0; String[] tokens = headerString.split(";"); for (String token : tokens) { token = token.trim(); final int newTaxId = idMapper.getName2IdMap().get(token); if (newTaxId != 0 && (taxId == 0 || idMapper.fullTree.isDescendant(taxId, newTaxId))) { taxId = newTaxId; } } if (taxId != 0) return taxId; } for (int left = headerString.indexOf('['); left != -1; left = headerString.indexOf('[', left + 1)) { try { Integer id = null; final int right = headerString.indexOf(']', left + 1); if (right > left) { if (idMapper.isActiveMap(IdMapper.MapType.Synonyms) && idMapper.isLoaded(IdMapper.MapType.Synonyms)) { id = idMapper.getSynonymsMap().get(headerString.substring(left + 1, right)); } if (id == null) { id = idMapper.getName2IdMap().get(headerString.substring(left + 1, right)); } if (id != 0) { if (disabledIds.contains(id)) disabled.add(id); else { switch (algorithm) { default: case First_Hit: return id; case LCA: ids.add(id); break; case Majority: id2count.put(id,id2count.getOrDefault(id,0)+1); break; } } } } } catch (Exception ignored) { } } // Name simply as text { id2segment.clear(); int countLabels = multiWords.compute(headerString, 5, 120); for (int i = 0; i < countLabels; i++) { final String label = multiWords.getWord(i); final int id = idMapper.getName2IdMap().get(label); if (id != 0 && !id2segment.containsKey(id)) { boolean overlaps = false; int[] pair = multiWords.getPair(i); for (int[] previousPair : id2segment.values()) { // make sure this doesn't overlap some other segment already used for an id if (pair[0] >= previousPair[0] && pair[0] <= previousPair[1] || pair[1] >= previousPair[0] && pair[1] <= previousPair[1]) { overlaps = true; break; } } if (!overlaps) { if (disabledIds.contains(id)) disabled.add(id); else { switch (algorithm) { default: case First_Hit: return id; case LCA: ids.add(id); break; case Majority: id2count.put(id,id2count.getOrDefault(id,0)+1); break; } } id2segment.put(id, pair); } } } } } // compute final result: if (ids.size() == 1) return ids.iterator().next(); // only one id or must be algorithm==Algorithm.First_Hit if (ids.size() > 0) { // must be algorithm==LCA return idMapper.fullTree.getLCA(ids); } else if (id2count.size() > 0) { // and has ids.size()==0, must be Algorithm.Majority var best=0; var bestCount=0; for(var id:id2count.keySet()) { if(id2count.get(id)>bestCount) best=id; } return best; } else if (disabled.size() > 0) { // only have disabled ids, return one of them if (disabled.size() == 1) return disabled.iterator().next(); return switch (algorithm) { case Majority, First_Hit -> disabled.iterator().next(); case LCA -> idMapper.fullTree.getLCA(disabled); }; } return 0; } /** * compute assignment for a list of IDs using specified algorithm * @param ids the list * @return id computed using specified algorithm */ public int processMultipleIds(Collection<Integer> ids) { // compute final result: if(ids.size()==0) return 0; else if (ids.size() == 1 || algorithm==Algorithm.First_Hit) return ids.iterator().next(); else if(algorithm==Algorithm.LCA) { return idMapper.fullTree.getLCA(ids); } else if(algorithm==Algorithm.Majority){ id2count.clear(); for(var id:ids) { id2count.put(id,id2count.getOrDefault(id,0)+1); } var best=0; var bestCount=0; for(var id:id2count.keySet()) { var count=id2count.get(id); if(count>bestCount) { best = id; bestCount=count; } } return best; } return 0; } /** * get the name of the classification * * @return name */ public String getCName() { return idMapper.getCName(); } public Algorithm getAlgorithm() { return algorithm; } public void setAlgorithm(Algorithm algorithm) { this.algorithm = algorithm; } public boolean isUseTextParsing() { return useTextParsing; } public void setUseTextParsing(boolean useTextParsing) { this.useTextParsing = useTextParsing; } public Name2IdMap getName2IdMap() { return idMapper.getName2IdMap(); } }
13,940
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ClassificationManager.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/ClassificationManager.java
/* * ClassificationManager.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.classification; import jloda.util.FileUtils; import jloda.util.StringUtils; import jloda.util.progress.ProgressListener; import jloda.util.progress.ProgressSilent; import java.io.IOException; import java.util.*; /** * manages classification data * Daniel Huson, 4.2015 */ public class ClassificationManager { private static final Set<String> allSupportedClassifications = new TreeSet<>(); private static final Set<String> allSupportedClassificationsExcludingNCBITaxonomy = new TreeSet<>(); private static final Map<String, Classification> name2classification = new TreeMap<>(); private static final ArrayList<String> defaultClassificationsList = new ArrayList<>(); private static final ArrayList<String> defaultClassificationsListExcludingNCBITaxonomy = new ArrayList<>(); private static final Map<String, String> additionalClassificationName2TreeFile = new HashMap<>(); private static final Map<String, String> additionalClassificationName2MapFile = new HashMap<>(); private static String meganMapDBFile; private static boolean useFastAccessionMappingMode; static { defaultClassificationsListExcludingNCBITaxonomy.add("GTDB"); defaultClassificationsListExcludingNCBITaxonomy.add("INTERPRO2GO"); defaultClassificationsListExcludingNCBITaxonomy.add("EGGNOG"); defaultClassificationsListExcludingNCBITaxonomy.add("SEED"); defaultClassificationsListExcludingNCBITaxonomy.add("KEGG"); defaultClassificationsListExcludingNCBITaxonomy.add("EC"); defaultClassificationsListExcludingNCBITaxonomy.add("PGPT"); allSupportedClassificationsExcludingNCBITaxonomy.addAll(defaultClassificationsListExcludingNCBITaxonomy); defaultClassificationsList.addAll(defaultClassificationsListExcludingNCBITaxonomy); defaultClassificationsList.add(Classification.Taxonomy); allSupportedClassifications.addAll(defaultClassificationsList); } /** * gets the named classification, loading the tree and mapping, if necessary * There is one static classification object per name * * @param load - create standard file names and load the files * @return classification */ public static Classification get(String name, boolean load) { Classification classification = name2classification.get(name); if (classification == null) { synchronized (name2classification) { classification = name2classification.get(name); if (classification == null) { if (load) { final String treeFile; if (name.equals(Classification.Taxonomy)) treeFile = "ncbi.tre"; else if (additionalClassificationName2TreeFile.containsKey(name)) treeFile = additionalClassificationName2TreeFile.get(name); else treeFile = name.toLowerCase() + ".tre"; final String mapFile; if (name.equals(Classification.Taxonomy)) mapFile = "ncbi.map"; else if (additionalClassificationName2MapFile.containsKey(name)) mapFile = additionalClassificationName2MapFile.get(name); else mapFile = name.toLowerCase() + ".map"; classification = load(name, treeFile, mapFile, new ProgressSilent()); } else { classification = new Classification(name); } name2classification.put(name, classification); } } } return classification; } /** * loads the named files and setups up the given classification (if not already present) * * @return classification */ public static Classification load(String name, String treeFile, String mapFile, ProgressListener progress) { synchronized (name2classification) { Classification classification = name2classification.get(name); if (classification == null) { classification = new Classification(name); name2classification.put(name, classification); } classification.load(treeFile, mapFile, progress); return classification; } } /** * ensure that the tree and mapping for the named classification are loaded * */ public static void ensureTreeIsLoaded(String name) { get(name, true); } public static Set<String> getAllSupportedClassifications() { return allSupportedClassifications; } public static Set<String> getAllSupportedClassificationsExcludingNCBITaxonomy() { return allSupportedClassificationsExcludingNCBITaxonomy; } public static ArrayList<String> getDefaultClassificationsList() { return defaultClassificationsList; } public static ArrayList<String> getDefaultClassificationsListExcludingNCBITaxonomy() { return defaultClassificationsListExcludingNCBITaxonomy; } public static String getIconFileName(String classificationName) { return StringUtils.capitalizeFirstLetter(classificationName.toLowerCase()) + "Viewer16.gif"; } public static boolean isActiveMapper(String name, IdMapper.MapType mapType) { return name2classification.get(name) != null && get(name, true).getIdMapper().isActiveMap(mapType); } public static void setActiveMapper(String name, IdMapper.MapType mapType, boolean active) { if (active || name2classification.get(name) != null) get(name, true).getIdMapper().setActiveMap(mapType, active); } public static boolean hasTaxonomicRanks(String classificationName) { return name2classification.get(classificationName).getId2Rank().size() > 1; } /** * is the named parsing method loaded * * @return true, if loaded */ public static boolean isLoaded(String name, IdMapper.MapType mapType) { return name2classification.get(name) != null && get(name, true).getIdMapper().isLoaded(mapType); } public static String getMapFileKey(String name, IdMapper.MapType mapType) { return name + mapType.toString() + "FileLocation"; } public static String getWindowGeometryKey(String name) { return name + "WindowGeometry"; } public static boolean isTaxonomy(String name) { return hasTaxonomicRanks(name); // todo: need to enforce that all labels are unique } public static String getMeganMapDBFile() { return meganMapDBFile; } public static void setMeganMapDBFile(String meganMapDBFile) throws IOException { if (meganMapDBFile != null && !FileUtils.fileExistsAndIsNonEmpty(meganMapDBFile)) throw new IOException("File not found or not readable: " + meganMapDBFile); ClassificationManager.meganMapDBFile = meganMapDBFile; if (meganMapDBFile != null) setUseFastAccessionMappingMode(true); } public static boolean canUseMeganMapDBFile() { return getMeganMapDBFile() != null && isUseFastAccessionMappingMode(); } public static boolean isUseFastAccessionMappingMode() { return useFastAccessionMappingMode; } public static void setUseFastAccessionMappingMode(boolean useFastAccessionMappingMode) { ClassificationManager.useFastAccessionMappingMode = useFastAccessionMappingMode; } public static Map<String, String> getAdditionalClassificationName2TreeFile() { return additionalClassificationName2TreeFile; } public static Map<String, String> getAdditionalClassificationName2MapFile() { return additionalClassificationName2MapFile; } }
8,736
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ClassificationFullTree.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/data/ClassificationFullTree.java
/* * ClassificationFullTree.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.classification.data; import jloda.graph.Edge; import jloda.graph.Node; import jloda.graph.NodeData; import jloda.graph.NodeSet; import jloda.phylo.PhyloTree; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.util.FileUtils; import jloda.util.NumberUtils; import megan.algorithms.LCAAddressing; import megan.classification.Classification; import megan.classification.ClassificationManager; import megan.classification.IdMapper; import megan.viewer.TaxonomyData; import java.io.*; import java.util.*; import static megan.main.MeganProperties.DISABLED_TAXA; /** * the classification full tree * Daniel Huson, 4.2010, 4.2015 */ public class ClassificationFullTree extends PhyloTree { private final Name2IdMap name2IdMap; private final Map<Integer, Set<Node>> id2Nodes = new HashMap<>(); // maps each id to all equivalent nodes private final Map<Integer, Node> id2Node = new HashMap<>(); //maps each id to a node private final Map<Integer, String> id2Address = new HashMap<>(); private final Map<String, Integer> address2Id = new HashMap<>(); private final NodeData emptyData = new NodeData(new float[0], new float[0]); /** * constructor * */ public ClassificationFullTree(String cName, Name2IdMap name2IdMap) { this.name2IdMap = name2IdMap; this.setName(cName); setAllowMultiLabeledNodes(true); } public void clear() { super.clear(); id2Node.clear(); id2Nodes.clear(); id2Address.clear(); address2Id.clear(); } /** * load the tree from a file * */ public void loadFromFile(String fileName) throws IOException { clear(); System.err.print("Loading " + FileUtils.getFileNameWithoutPath(fileName) + ": "); try (var r = new BufferedReader(new InputStreamReader(ResourceManager.getFileAsStream(fileName)))) { read(r); } for (var v = getFirstNode(); v != null; v = v.getNext()) { if (NumberUtils.isInteger(getLabel(v))) { int id = Integer.parseInt(getLabel(v)); setInfo(v, id); addId2Node(id, v); if (v.getInDegree() > 1) System.err.println("Reticulate node: " + id); } else throw new IOException("Node has illegal label: " + getLabel(v)); } if (id2Node.get(IdMapper.NOHITS_ID) == null) { var v = newNode(); addId2Node(IdMapper.NOHITS_ID, v); name2IdMap.put(IdMapper.NOHITS_LABEL, IdMapper.NOHITS_ID); name2IdMap.setRank(IdMapper.NOHITS_ID, 0); newEdge(getRoot(), v); } setInfo(getANode(IdMapper.NOHITS_ID), IdMapper.NOHITS_ID); if (id2Node.get(IdMapper.UNASSIGNED_ID) == null) { var v = newNode(); addId2Node(IdMapper.UNASSIGNED_ID, v); name2IdMap.put(IdMapper.UNASSIGNED_LABEL, IdMapper.UNASSIGNED_ID); name2IdMap.setRank(IdMapper.UNASSIGNED_ID, 0); newEdge(getRoot(), v); } setInfo(getANode(IdMapper.UNASSIGNED_ID), IdMapper.UNASSIGNED_ID); if (id2Node.get(IdMapper.LOW_COMPLEXITY_ID) == null) { var v = newNode(); addId2Node(IdMapper.LOW_COMPLEXITY_ID, v); name2IdMap.put(IdMapper.LOW_COMPLEXITY_LABEL, IdMapper.LOW_COMPLEXITY_ID); name2IdMap.setRank(IdMapper.LOW_COMPLEXITY_ID, 0); newEdge(getRoot(), v); } setInfo(getANode(IdMapper.LOW_COMPLEXITY_ID), IdMapper.LOW_COMPLEXITY_ID); if (id2Node.get(IdMapper.CONTAMINANTS_ID) == null) { var v = newNode(); addId2Node(IdMapper.CONTAMINANTS_ID, v); name2IdMap.put(IdMapper.CONTAMINANTS_LABEL, IdMapper.CONTAMINANTS_ID); name2IdMap.setRank(IdMapper.CONTAMINANTS_ID, 0); newEdge(getRoot(), v); } setInfo(getANode(IdMapper.CONTAMINANTS_ID), IdMapper.CONTAMINANTS_ID); if (getName().equals(Classification.Taxonomy)) { // fix Domains: int taxId = name2IdMap.get("Bacteria"); if (taxId > 0) name2IdMap.setRank(taxId, 127); taxId = name2IdMap.get("Archaea"); if (taxId > 0) name2IdMap.setRank(taxId, 127); taxId = name2IdMap.get("Eukaryota"); if (taxId > 0) name2IdMap.setRank(taxId, 127); // disable taxa for (int t : ProgramProperties.get(DISABLED_TAXA, new int[0])) { TaxonomyData.getDisabledTaxa().add(t); } } LCAAddressing.computeAddresses(this, id2Address, address2Id); System.err.printf("%,9d%n", getNumberOfNodes()); } /** * add all ids that many be missing from the tree to the tree */ private void addMissingToTree(String unclassifiedNodeLabel, int unclassifiedNodeId, String labelFormat, final int maxId) { // add additional nodes for ids that are not found in the tree: Node unclassified = null; for (int id = 1; id <= maxId; id++) { if (!containsId(id)) { if (unclassified == null) { unclassified = newNode(); Edge before = null; for (Edge e = getRoot().getFirstOutEdge(); e != null; e = getRoot().getNextOutEdge(e)) { Node w = e.getTarget(); Integer wid = (Integer) w.getInfo(); if (wid < 0) { before = e; break; } } if (before != null) // insert unclassified edge before the no hits etc nodes newEdge(getRoot(), before, unclassified, null, Edge.BEFORE, Edge.AFTER, null); else newEdge(getRoot(), unclassified); unclassified.setInfo(unclassifiedNodeId); addId2Node(unclassifiedNodeId, unclassified); name2IdMap.put(unclassifiedNodeLabel, unclassifiedNodeId); } Node v = newNode(id); newEdge(unclassified, v); name2IdMap.put(String.format(labelFormat, id), id); addId2Node(id, v); } } } /** * save to file * */ public void saveToFile(String fileName) throws IOException { System.err.println("Saving tree to file: " + fileName); try (BufferedWriter w = new BufferedWriter(new FileWriter(fileName))) { write(w, false); w.write(";\n"); } System.err.println("done (" + getNumberOfNodes() + " nodes)"); } /** * extract the induced tree * */ public void extractInducedTree(Map<Integer, NodeData> id2data, Set<Integer> collapsedIds, PhyloTree targetTree, Map<Integer, Set<Node>> targetId2Nodes) { final Map<Integer, Float> id2count = new HashMap<>(); for (Integer id : id2data.keySet()) { id2count.put(id, id2data.get(id).getCountAssigned()); } final NodeSet keep = new NodeSet(this); labelToKeepRec(getRoot(), id2count.keySet(), keep); targetTree.clear(); final Node rootCpy = targetTree.newNode(); Map<Node, Node> node2cpy = new HashMap<>(); // used in context of reticulate nodes, currently not supported targetTree.setRoot(rootCpy); rootCpy.setInfo(getRoot().getInfo()); node2cpy.put(getRoot(), rootCpy); final int rootId = (Integer) getRoot().getInfo(); final NodeData rootData = id2data.get(rootId); rootCpy.setData(rootData != null ? rootData : emptyData); induceRec(getRoot(), rootCpy, targetTree, keep, collapsedIds, id2data, node2cpy); targetId2Nodes.clear(); for (Node v = targetTree.getFirstNode(); v != null; v = v.getNext()) { int id = (Integer) v.getInfo(); Set<Node> nodes = targetId2Nodes.computeIfAbsent(id, k -> new HashSet<>()); nodes.add(v); if (v.getInDegree() > 1) System.err.println("Reticulate node: " + id + " (currently not supported)"); } if (false) System.err.printf("Induced tree has %,d of %,d nodes%n", +keep.size(), getNumberOfNodes()); if (collapsedIds.size() > 0) { // ensure that set of collapsed ids is only as large as necessary for given data final Set<Integer> notNeeded = new HashSet<>(); for (Node v = targetTree.getFirstNode(); v != null; v = targetTree.getNextNode(v)) { Integer id = (Integer) v.getInfo(); if (!collapsedIds.contains(id)) notNeeded.add(id); } if (notNeeded.size() > 0) { collapsedIds.removeAll(notNeeded); } } } /** * label all nodes in tree that we must keep in induced tree * * @return true, if node v is to be kept */ private boolean labelToKeepRec(Node v, Set<Integer> ids, NodeSet keep) { boolean hasBelow = false; int id = (Integer) v.getInfo(); if (ids.size() == 0 || ids.contains(id)) hasBelow = true; for (Edge e = v.getFirstOutEdge(); e != null; e = v.getNextOutEdge(e)) { Node w = e.getTarget(); if (labelToKeepRec(w, ids, keep)) hasBelow = true; } if (hasBelow) keep.add(v); return hasBelow; } /** * induce the tree * * @param stopIds don't induce below these ids */ private void induceRec(Node v, Node vCpy, PhyloTree treeCpy, NodeSet keep, Set<Integer> stopIds, Map<Integer, NodeData> id2data, Map<Node, Node> node2copy) { for (Edge e = v.getFirstOutEdge(); e != null; e = v.getNextOutEdge(e)) { Node w = e.getTarget(); if (keep.contains(w)) { int id = (Integer) w.getInfo(); Node wCpy = null; if (node2copy != null) wCpy = node2copy.get(w); if (wCpy == null) { wCpy = treeCpy.newNode(); if (node2copy != null) node2copy.put(w, wCpy); wCpy.setInfo(id); } NodeData nodeData = id2data.get(id); wCpy.setData(Objects.requireNonNullElseGet(nodeData, () -> new NodeData(new float[0], new float[0]))); treeCpy.newEdge(vCpy, wCpy); if (wCpy.getInDegree() > 1) { for (Edge f = wCpy.getFirstInEdge(); f != null; f = wCpy.getNextInEdge(f)) treeCpy.setReticulate(f, true); } if (!stopIds.contains(w.getInfo())) induceRec(w, wCpy, treeCpy, keep, stopIds, id2data, node2copy); } } } /** * modify the given set of collapsedIds so that the toUncollapse ids are uncollapsed * */ public void uncollapse(Set<Integer> toUncollapse, Set<Integer> collapsedIds) { Set<Integer> newCollapsed = new HashSet<>(); for (Node v = getFirstNode(); v != null; v = v.getNext()) { int vId = (Integer) v.getInfo(); if (toUncollapse.contains(vId) && collapsedIds.contains(vId)) { for (Edge e = v.getFirstOutEdge(); e != null; e = v.getNextOutEdge(e)) { Node w = e.getTarget(); newCollapsed.add((Integer) w.getInfo()); } } } collapsedIds.removeAll(toUncollapse); collapsedIds.addAll(newCollapsed); } /** * computes the id2data map * */ public void computeId2Data(int numberOfDatasets, Map<Integer, float[]> id2counts, Map<Integer, NodeData> id2data) { id2data.clear(); if (id2counts != null) { if (ClassificationManager.isTaxonomy(getName())) computeTaxonomyId2DataRec(numberOfDatasets, getRoot(), id2counts, id2data); else computeId2DataRec(numberOfDatasets, getRoot(), id2counts, new HashMap<>(), id2data); } } /** * recursively computes the classification-id 2 assigned and classification-id 2 summarized maps. * Use this when classification contains same leaves more than once * * @return set of classification-ids on or below node v */ private Set<Integer> computeId2DataRec(int numberOfDataSets, Node v, Map<Integer, float[]> id2counts, Map<Integer, Set<Integer>> id2idsBelow, Map<Integer, NodeData> id2data) { final int id = (Integer) v.getInfo(); final Set<Integer> idsBelow = new HashSet<>(); id2idsBelow.put(id, idsBelow); idsBelow.add(id); for (Edge e = v.getFirstOutEdge(); e != null; e = v.getNextOutEdge(e)) { Node w = e.getTarget(); final Set<Integer> allBelow = computeId2DataRec(numberOfDataSets, w, id2counts, id2idsBelow, id2data); idsBelow.addAll(allBelow); } float[] assigned = new float[numberOfDataSets]; float[] summarized = new float[numberOfDataSets]; long total = 0; final float[] counts = id2counts.get(id); if (counts != null) { int top = Math.min(assigned.length, counts.length); for (int i = 0; i < top; i++) { assigned[i] = counts[i]; total += counts[i]; } } for (Integer below : id2idsBelow.get(id)) { float[] countBelow = id2counts.get(below); if (countBelow != null) { int top = Math.min(summarized.length, countBelow.length); for (int i = 0; i < top; i++) { summarized[i] += countBelow[i]; total += countBelow[i]; } } } if (total > 0) id2data.put(id, new NodeData(assigned, summarized)); return idsBelow; } public Set<Integer> getIds() { return id2Node.keySet(); } /** * recursively computes the taxon-id 2 assigned and taxon-id 2 summarized maps * */ private void computeTaxonomyId2DataRec(int numberOfDataSets, Node v, Map<Integer, float[]> id2counts, Map<Integer, NodeData> id2data) { int taxonomyId = (Integer) v.getInfo(); // first process all children for (Edge e = v.getFirstOutEdge(); e != null; e = v.getNextOutEdge(e)) { Node w = e.getTarget(); computeTaxonomyId2DataRec(numberOfDataSets, w, id2counts, id2data); } // set up assigned: float[] assigned = new float[numberOfDataSets]; float[] summarized = new float[numberOfDataSets]; long total = 0; float[] counts = id2counts.get(taxonomyId); if (counts != null) { int top = Math.min(assigned.length, counts.length); for (int i = 0; i < top; i++) { assigned[i] = counts[i]; summarized[i] = counts[i]; total += counts[i]; } } // setup summarized: for (Edge e = v.getFirstOutEdge(); e != null; e = v.getNextOutEdge(e)) { Node w = e.getTarget(); int wId = (Integer) w.getInfo(); NodeData dataW = id2data.get(wId); if (dataW != null) { float[] below = dataW.getSummarized(); int top = Math.min(summarized.length, below.length); for (int i = 0; i < top; i++) { summarized[i] += below[i]; total += below[i]; } } } if (total > 0) id2data.put(taxonomyId, new NodeData(assigned, summarized)); } /** * get all descendants of a id (including the id itself * * @return all descendant ids */ public Set<Integer> getAllDescendants(int id) { final Set<Integer> set = new HashSet<>(); set.add(id); return getAllDescendants(set); } /** * does the node contain this id * * @return true, if id is contained */ private boolean containsId(int id) { return id2Node.containsKey(id); } /** * get all descendants of a set of f ids (including the ids themselves * * @return ids and all descendants */ public Set<Integer> getAllDescendants(Set<Integer> ids) { final Set<Integer> set = new HashSet<>(ids); getAllDescendantsRec(getRoot(), false, set); return set; } /** * recursively add all descendants to a set * */ private void getAllDescendantsRec(Node v, boolean add, Set<Integer> set) { if (!add && set.contains(v.getInfo())) add = true; else if (add) set.add((Integer) v.getInfo()); for (Edge e = v.getFirstOutEdge(); e != null; e = v.getNextOutEdge(e)) { getAllDescendantsRec(e.getTarget(), add, set); } } /** * get all parents for a given id. There can be more than one parent because an id can appear on more than one node * * @return all ids of all parents */ public Set<Integer> getAllParents(int classId) { final Set<Integer> set = new HashSet<>(); for (Node v : getNodes(classId)) { if (v.getInDegree() > 0) { final Node w = v.getFirstInEdge().getSource(); set.add((Integer) w.getInfo()); } } return set; } /** * returns the child of classV that is above classW * * @return child of classV that is above classW, or 0, if not found */ public int getChildAbove(int classV, int classW) { if (classV == classW) return classV; final Node v = getANode(classV); if (v != null) { for (Node w : getNodes(classW)) { while (w.getInDegree() > 0) { final Node u = w.getFirstInEdge().getSource(); if (u == v) return (int) w.getInfo(); else w = u; } } } return 0; } /** * gets all nodes associated with a given f id * * @return nodes */ public Set<Node> getNodes(int id) { Set<Node> set = id2Nodes.get(id); if (set == null) { set = new HashSet<>(); id2Nodes.put(id, set); Node v = id2Node.get(id); // there is only one node associated with this id, make a set and save it for repeated use if (v != null) { set.add(v); } } return set; } /** * get a node associated with this id * * @return a node */ public Node getANode(int id) { return id2Node.get(id); } public void clearId2Node(int id) { id2Nodes.remove(id); id2Node.remove(id); } public void addId2Node(int id, Node v) { if (id2Node.get(id) == null) { id2Node.put(id, v); } else if (id2Nodes.get(id) == null) { final Set<Node> set = new HashSet<>(); set.add(id2Node.get(id)); set.add(v); id2Nodes.put(id, set); } else id2Nodes.get(id).add(v); } /** * gets the LCA of a set of ids * * @return LCA */ public Integer getLCA(Collection<Integer> ids) { final var addresses = new HashSet<String>(); for (var id : ids) { var address = id2Address.get(id); if (address != null) addresses.add(address); } var prefix = LCAAddressing.getCommonPrefix(addresses, true); return address2Id.get(prefix); } /** * is the class below a descendant of the class above? * * @return true, if idAbove an ancestor of idBelow */ public boolean isDescendant(Integer idAbove, Integer idBelow) { String addressAbove = id2Address.get(idAbove); String addressBelow = id2Address.get(idBelow); if (addressAbove != null && addressBelow != null) return id2Address.get(idBelow).startsWith(id2Address.get(idAbove)); else { Set<Node> nodesAbove = id2Nodes.get(idAbove); Set<Node> nodesBelow = id2Nodes.get(idBelow); if (nodesAbove != null && nodesBelow != null) { for (Node w : nodesBelow) { while (true) { if (nodesAbove.contains(w)) return true; if (w.getInDegree() == 0) break; w = w.getFirstInEdge().getSource(); } } } return false; } } /** * gets the address for an id * * @return address */ public String getAddress(int id) { return id2Address.get(id); } /** * gets the id for an address * * @return id */ public int getAddress2Id(String address) { var id = address2Id.get(address); return Objects.requireNonNullElse(id, 0); } /** * get all nodes at the given level (i.e. distance from root) * * @return set of nodes */ public Set<Integer> getAllAtLevel(int level) { var result = new HashSet<Integer>(); getAllAtLevelRec(getRoot(), 0, level, result); return result; } /** * recursively does the work * */ private void getAllAtLevelRec(Node v, int current, int level, Set<Integer> result) { if (current == level) { result.add((Integer) v.getInfo()); } else { for (var e = v.getFirstOutEdge(); e != null; e = v.getNextOutEdge(e)) { getAllAtLevelRec(e.getTarget(), current + 1, level, result); } } } /** * gets all nodes of given rank * * @param closure if true, compute closure * @return result */ public Set<Integer> getNodeIdsAtGivenRank(Integer rank, boolean closure) { Set<Integer> result = new HashSet<>(); getNodesAtGivenRankRec(getRoot(), rank, result, closure); return result; } /** * recursively does the work * * @return true, if node found below */ private boolean getNodesAtGivenRankRec(final Node v, final Integer rank, final Set<Integer> result, final boolean closure) { if (name2IdMap.getRank((Integer) v.getInfo()) == rank) { result.add((Integer) v.getInfo()); return true; } // are some, but not all, of the children not involved? If so, add those to the result (to collapse them) int noneBelowCount = 0; final Node[] noneBelow = new Node[v.getOutDegree()]; for (Edge e = v.getFirstOutEdge(); e != null; e = v.getNextOutEdge(e)) { if (!getNodesAtGivenRankRec(e.getTarget(), rank, result, closure)) noneBelow[noneBelowCount++] = e.getTarget(); } if (closure && noneBelowCount > 0 && noneBelowCount < noneBelow.length) { for (int i = 0; i < noneBelowCount; i++) result.add((Integer) noneBelow[i].getInfo()); } return noneBelowCount < noneBelow.length; } }
24,489
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
IString2IntegerMap.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/data/IString2IntegerMap.java
/* * IString2IntegerMap.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.classification.data; import java.io.Closeable; import java.io.IOException; /** * String to integer map * Created by huson on 7/15/16. */ public interface IString2IntegerMap extends Closeable { /** * get a value * * @return value or 0 */ int get(String key) throws IOException; /** * return the number of entries * * @return size */ int size(); }
1,237
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
IString2IntegerMapFactory.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/data/IString2IntegerMapFactory.java
/* * IString2IntegerMapFactory.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.classification.data; import jloda.util.progress.ProgressListener; import megan.data.IName2IdMap; import java.io.IOException; /** * factory for creating string-2-integer mappings * Created by huson on August 2017 */ public interface IString2IntegerMapFactory { /** * create a string to integer map from the named file * * @param label2id option mapping of labels to ids * @param fileName file * @param progress progress listner * @return map or null */ IString2IntegerMap create(IName2IdMap label2id, String fileName, ProgressListener progress) throws IOException; }
1,451
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Accession2IdMapFactory.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/data/Accession2IdMapFactory.java
/* * Accession2IdMapFactory.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.classification.data; import jloda.swing.window.NotificationsInSwing; import jloda.util.progress.ProgressListener; import megan.data.IName2IdMap; import java.io.IOException; /** * factory for creating Accession to ID mappings * Created by huson on 7/15/16. */ public class Accession2IdMapFactory implements IString2IntegerMapFactory { /** * create an accession to integer map from the named file * * @param label2id option mapping of labels to ids * @param fileName file * @param progress progress listener * @return map or null */ @Override public IString2IntegerMap create(IName2IdMap label2id, String fileName, ProgressListener progress) throws IOException { if (String2IntegerFileBasedABinMap.isTableFile(fileName)) return new String2IntegerFileBasedABinMap(fileName); else if (String2IntegerFileBasedABinMap.isIncompatibleTableFile(fileName)) { NotificationsInSwing.showError("Incompatible mapping file (UE?): " + fileName); throw new IOException("Incompatible mapping file (UE?): " + fileName); } else return new Accession2IdMap(label2id, fileName, progress); } }
2,031
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ClassificationCommandHelper.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/data/ClassificationCommandHelper.java
/* * ClassificationCommandHelper.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.classification.data; import jloda.swing.commands.ICommand; import megan.classification.ClassificationManager; import megan.classification.IdMapper; import megan.classification.commandtemplates.*; import java.util.Collection; import java.util.LinkedList; import java.util.List; /** * generates open viewer commands * Daniel Huson, 4.2015 */ public class ClassificationCommandHelper { /** * gets the menu string for opening all registered viewers * * @return menu string */ public static String getOpenViewerMenuString() { final StringBuilder buf = new StringBuilder(); for (String name : ClassificationManager.getDefaultClassificationsListExcludingNCBITaxonomy()) { buf.append((new OpenFViewerCommand(name)).getName()).append(";"); if(name.equals("GTDB")) buf.append("|;"); } var first=true; for (String name : ClassificationManager.getAllSupportedClassificationsExcludingNCBITaxonomy()) { if (!ClassificationManager.getDefaultClassificationsListExcludingNCBITaxonomy().contains(name)) { if(first) { buf.append("|;"); first = false; } buf.append((new OpenFViewerCommand(name)).getName()).append(";"); } } return buf.toString(); } /** * get commands needed by all viewers * * @return list of globally used commands */ public static Collection<ICommand> getGlobalCommands() { final List<ICommand> commands = new LinkedList<>(); for (String name : ClassificationManager.getAllSupportedClassifications()) { commands.add(new OpenFViewerCommand(name)); } commands.add(new SetUseMapTypeCommand()); commands.add(new SetAnalyseCommand()); commands.add(new LoadMappingFileCommand()); commands.add(new SetUseIdParsingCommand()); commands.add(new SetUseLCACommand()); return commands; } /** * get all commands needed by the import blast dialog * * @return import blast commands */ public static Collection<ICommand> getImportBlastCommands(Collection<String> cNames) { final List<ICommand> commands = new LinkedList<>(); for (String cName : cNames) { commands.add(new SetAnalyse4ViewerCommand(cName)); commands.add(new SetUseMapType4ViewerCommand(cName, IdMapper.MapType.Accession)); commands.add(new LoadMappingFile4ViewerCommand(cNames, cName, IdMapper.MapType.Accession)); commands.add(new SetUseMapType4ViewerCommand(cName, IdMapper.MapType.MeganMapDB)); commands.add(new LoadMappingFile4ViewerCommand(cNames, cName, IdMapper.MapType.MeganMapDB)); commands.add(new SetUseMapType4ViewerCommand(cName, IdMapper.MapType.Synonyms)); commands.add(new LoadMappingFile4ViewerCommand(cNames, cName, IdMapper.MapType.Synonyms)); commands.add(new SetUseIdParsing4ViewerCommand(cName)); commands.add(new SetUseLCA4ViewerCommand(cName)); } return commands; } }
4,014
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SyncDataTableAndClassificationViewer.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/data/SyncDataTableAndClassificationViewer.java
/* * SyncDataTableAndClassificationViewer.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.classification.data; import jloda.graph.Edge; import jloda.graph.Node; import jloda.graph.NotOwnerException; import jloda.util.Pair; import megan.core.DataTable; import megan.viewer.ClassificationViewer; import java.io.IOException; import java.util.HashSet; import java.util.Set; /** * sync between summary and functional viewer * Daniel Huson, 4.2015 */ public class SyncDataTableAndClassificationViewer { /** * sync collapsed nodes * */ public static void syncCollapsedFromSummary2Viewer(final DataTable table, final ClassificationViewer classificationViewer) { final String classificationName = classificationViewer.getClassName(); // Sync collapsed nodes: if (table.getCollapsed(classificationName) != null && table.getCollapsed(classificationName).size() > 0) { classificationViewer.getCollapsedIds().clear(); classificationViewer.getCollapsedIds().addAll(table.getCollapsed(classificationName)); } } /** * sync the formatting (and collapsed nodes) from the summary to the fviewer viewer * */ public static void syncFormattingFromSummary2Viewer(DataTable table, ClassificationViewer classificationViewer) { final String classificationName = classificationViewer.getClassName(); boolean changed = false; // can't use nexus parser here because it swallows the ' quotes String nodeFormats = table.getNodeFormats(classificationName); // System.err.println("Node Format: "+nodeFormats); if (nodeFormats != null) { int state = 0; int idA = 0, idB = 0; int formatA = 0; for (int pos = 0; pos < nodeFormats.length(); pos++) { char ch = nodeFormats.charAt(pos); switch (state) { case 0: // skipping spaces before class id if (!Character.isSpaceChar(ch)) { state++; idA = pos; } break; case 1: // scanning class id idB = pos; if (ch == ':') state++; break; case 2: // skipping spaces before start of format if (!Character.isSpaceChar(ch)) { state++; formatA = pos; } break; case 3: // scanning format if (ch == ';') { int formatB = pos; if (idA < idB && formatA < formatB) { Integer taxId = Integer.parseInt(nodeFormats.substring(idA, idB).trim()); classificationViewer.getDirtyNodeIds().add(taxId); String format = nodeFormats.substring(formatA, formatB + 1).trim(); // System.err.println("got: <"+taxId+">: <"+format+">"); for (Node v : classificationViewer.getNodes(taxId)) { try { classificationViewer.getNV(v).read(format); changed = true; } catch (IOException ignored) { } } } state = 0; } break; } } } String edgeFormats = table.getEdgeFormats(classificationName); //System.err.println("Edge Format: "+edgeFormats); if (edgeFormats != null) { int state = 0; int id1A = 0, id1B = 0; int id2A = 0, id2B = 0; int formatA = 0; for (int pos = 0; pos < edgeFormats.length(); pos++) { char ch = edgeFormats.charAt(pos); switch (state) { case 0: // skipping spaces before class id1 if (!Character.isSpaceChar(ch)) { state++; id1A = pos; } break; case 1: // scaning class id id1B = pos; if (ch == ',') state++; break; case 2: // skipping spaces before class id2 if (!Character.isSpaceChar(ch)) { state++; id2A = pos; } break; case 3: // scaning class id id2B = pos; if (ch == ':') state++; break; case 4: // skipping spaces before start of format if (!Character.isSpaceChar(ch)) { state++; formatA = pos; } break; case 5: // scanning format if (ch == ';') { int formatB = pos; if (id1A < id1B && id2A < id2B && formatA < formatB) { Integer taxId1 = Integer.parseInt(edgeFormats.substring(id1A, id1B).trim()); Integer taxId2 = Integer.parseInt(edgeFormats.substring(id2A, id2B).trim()); classificationViewer.getDirtyEdgeIds().add(new Pair<>(taxId1, taxId2)); String format = edgeFormats.substring(formatA, formatB + 1).trim(); for (Node v : classificationViewer.getNodes(taxId1)) { for (Node w : classificationViewer.getNodes(taxId2)) { Edge e = v.getCommonEdge(w); try { if (e != null) { classificationViewer.getEV(e).read(format); changed = true; } } catch (IOException ignored) { } } } } state = 0; } break; } } } } /** * sync formatting (and collapsed nodes) from fviewer viewer to summary * */ static public void syncFormattingFromViewer2Summary(ClassificationViewer classificationViewer, DataTable table) { final String classificationName = classificationViewer.getClassName(); if (classificationViewer.getDirtyNodeIds().size() > 0) { StringBuilder buf = new StringBuilder(); for (Integer fviewerId : classificationViewer.getDirtyNodeIds()) { try { Node v = classificationViewer.getANode(fviewerId); if (v != null) { String format = classificationViewer.getNV(v).toString(false); buf.append(fviewerId).append(":").append(format); } } catch (NotOwnerException ignored) { } } table.setNodeFormats(classificationName, buf.toString()); } else table.setNodeFormats(classificationName, null); if (classificationViewer.getDirtyEdgeIds().size() > 0) { StringBuilder buf = new StringBuilder(); for (Pair<Integer, Integer> pair : classificationViewer.getDirtyEdgeIds()) { Edge e = null; Set<Node> nodes = classificationViewer.getNodes(pair.getFirst()); if (nodes != null) { for (Node v : nodes) { for (Node w : classificationViewer.getNodes(pair.getSecond())) { e = v.getCommonEdge(w); if (e != null) break; } if (e != null) break; } } if (e != null) { String format = classificationViewer.getEV(e).toString(false); buf.append(pair.getFirst()).append(",").append(pair.getSecond()).append(":").append(format); } } table.setEdgeFormats(classificationName, buf.toString()); } else table.setEdgeFormats(classificationName, null); table.setNodeStyle(classificationName, classificationViewer.getNodeDrawer().getStyle().toString()); // Sync collapsed nodes: Set<Integer> collapsed = new HashSet<>(classificationViewer.getCollapsedIds()); if (collapsed.size() == 0) collapsed.add(-1); // collapsed must contain atleast one element, otherwise will be ignored table.setCollapsed(classificationName, collapsed); } }
10,335
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ILong2IntegerMap.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/data/ILong2IntegerMap.java
/* * ILong2IntegerMap.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.classification.data; import java.io.Closeable; import java.io.IOException; /** * long to integer map * Created by huson on 7/15/16. */ public interface ILong2IntegerMap extends Closeable { /** * get a value * * @return value or 0 */ int get(long index) throws IOException; }
1,135
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
String2IntegerFileBasedABinMap.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/data/String2IntegerFileBasedABinMap.java
/* * String2IntegerFileBasedABinMap.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.classification.data; import jloda.thirdparty.MurmurHash3; import jloda.util.StringUtils; import megan.io.ByteFileGetterMappedMemory; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; /** * a disk-based string-to-int hash table * Daniel Huson, 3.2016 */ public class String2IntegerFileBasedABinMap implements IString2IntegerMap, Closeable { public static String MAGIC_NUMBER = "SI1"; // not final public static String MAGIC_NUMBERX = "SIX"; // not final private final ByteFileGetterMappedMemory dataByteBuffer; private final long indexStartPos; private final long dataStartPos; private final boolean extended; // no extended uses four bytes to address table, extended uses 8 bytes private final int size; private final int mask; private final int cacheBits = 20; private final int cacheSize = (1 << cacheBits); private final byte[][] cacheKeys = new byte[cacheSize][]; private final int[] cacheValues = new int[cacheSize]; /** * constructor * */ public String2IntegerFileBasedABinMap(String fileName) throws IOException { try (RandomAccessFile raf = new RandomAccessFile(fileName, "r")) { { final byte[] magicNumber = new byte[3]; raf.read(magicNumber); if (StringUtils.toString(magicNumber).equals(MAGIC_NUMBER)) extended = false; // old version that uses int to address data else if (StringUtils.toString(magicNumber).equals(MAGIC_NUMBERX)) { extended = true; // uses long to address data } else throw new IOException("File has wrong magic number"); final byte bits = (byte) raf.read(); // yes, read a single byte if (bits <= 0 || bits >= 30) throw new IOException("Bits out of range: " + bits); mask = (1 << bits) - 1; indexStartPos = magicNumber.length + 1; // header consists of 4 bytes: 3 for magic number plus mask byte } dataStartPos = indexStartPos + (long) (extended ? 8 : 4) * (mask + 1); // This is where the data begins. dataByteBuffer = new ByteFileGetterMappedMemory(new File(fileName)); size = dataByteBuffer.getInt(dataByteBuffer.limit() - 4); if (size < 0) throw new IOException("Bad size: " + size); /* for(int i=8;i< dataStartPos && i<128;i+=8) { System.err.println("buf: "+i + " -> " + dataByteBuffer.getLong(i)); raf.seek(i); System.err.println("raf: "+i + " -> " + raf.readLong()); } */ } } /** * is this an appropriate file? * * @return true, if is table file */ public static boolean isTableFile(String fileName) { try { try (RandomAccessFile raf = new RandomAccessFile(fileName, "r")) { final byte[] magicNumber = new byte[3]; raf.read(magicNumber); return StringUtils.toString(magicNumber).equals(MAGIC_NUMBER) || StringUtils.toString(magicNumber).equals(MAGIC_NUMBERX); } } catch (Exception ex) { return false; } } /** * is this an appropriate file? * * @return true, if is table file */ public static boolean isIncompatibleTableFile(String fileName) { try { try (RandomAccessFile raf = new RandomAccessFile(fileName, "r")) { final byte[] magicNumber = new byte[3]; raf.read(magicNumber); return StringUtils.toString(magicNumber).equals(MAGIC_NUMBER.toLowerCase()) || StringUtils.toString(magicNumber).equals(MAGIC_NUMBERX.toLowerCase()); } } catch (Exception ex) { return false; } } public int size() { return size; } /** * get the value for a key */ public int get(String keyString) throws IOException { byte[] key = keyString.getBytes(); final int keyHash = computeHash(key, mask); long dataOffset = extended ? dataByteBuffer.getLong(8L * keyHash + indexStartPos) : dataByteBuffer.getInt(4L * keyHash + indexStartPos); if (dataOffset == 0) return 0; // cache: final int cacheIndex = (keyHash & cacheBits); synchronized (cacheKeys) { final byte[] cacheKey = cacheKeys[cacheIndex]; if (cacheKey != null && equal(key, cacheKey)) return cacheValues[cacheIndex]; } if (dataOffset < 0) { // need to expand, should only happen when extended==false dataOffset = (long) Integer.MAX_VALUE + (dataOffset & (Integer.MAX_VALUE)) + 1; } dataOffset += dataStartPos; while (true) { final int numberOfBytes = readAndCompareBytes0Terminated(key, key.length, dataOffset, dataByteBuffer); if (numberOfBytes == 0) break; else if (numberOfBytes < 0) // negative means not a match to the query dataOffset += -numberOfBytes + 5; // add 1 for terminating 0, and 4 for value else { // matches query dataOffset += numberOfBytes + 1; // add 1 for terminating 0 final int value = dataByteBuffer.getInt(dataOffset); // cache: synchronized (cacheKeys) { cacheKeys[cacheIndex] = key; cacheValues[cacheIndex] = value; } return value; } } return 0; } /** * equal keys? * * @return true if the same */ private boolean equal(byte[] key1, byte[] key2) { if (key1.length != key2.length) return false; else { for (int i = 0; i < key1.length; i++) { if (key1[i] != key2[i]) return false; } return true; } } @Override public void close() { dataByteBuffer.close(); } /** * compute the hash value for a given key * * @return hash */ public static int computeHash(byte[] key, int mask) { return Math.abs(MurmurHash3.murmurhash3x8632(key, 0, key.length, 666) & mask); } /** * read and compare 0-terminated bytes, * * @return number of bytes read excluding termining 0, if match, or -number of bytes read, if no match */ private int readAndCompareBytes0Terminated(byte[] key, int keyLength, long pos, ByteFileGetterMappedMemory byteBuffer) { int i = 0; boolean equal = true; // byte[] got=new byte[10000]; while (true) { final byte b = (byte) byteBuffer.get(pos++); //got[i]=b; if (b == 0) break; if (i < keyLength) { if (equal && b != key[i]) { equal = false; } } i++; } //System.err.println("Looking for: "+ Basic.toString(key,0,keyLength)+", got: "+Basic.toString(got,0,i)); return (equal && i == keyLength) ? i : -i; // negative means no match } }
8,113
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Name2IdMap.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/data/Name2IdMap.java
/* * Name2IdMap.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.classification.data; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.util.FileUtils; import jloda.util.NumberUtils; import jloda.util.StringUtils; import megan.data.IName2IdMap; import java.io.*; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * maintains a mapping between names and ids * Daniel Huson, 4.2015 */ public class Name2IdMap implements IName2IdMap { private final Map<String, Integer> name2id; private final Map<Integer, String> id2name; private final Map<Integer, String> id2toolTip; private final Map<Integer, Integer> id2rank; private final boolean allowUnderscoresInLookups; /** * constructor */ public Name2IdMap() { this(100000); } /** * constructor */ public Name2IdMap(int approximateSize) { name2id = new HashMap<>(approximateSize, 0.99f); id2name = new HashMap<>(approximateSize, 0.99f); id2toolTip = new HashMap<>(approximateSize, 0.99f); id2rank = new HashMap<>(approximateSize, 0.99f); allowUnderscoresInLookups = ProgramProperties.get("allow-underscores-in-lookup", true); } /** * get ids to names map * * @return id2names */ public Map<Integer, String> getId2Name() { return id2name; } /** * get the id for a name * * @return id or 0 */ public int get(String name) { Integer result = name2id.get(name); if (result != null) return result; else if (allowUnderscoresInLookups) { result = name2id.get(name.replaceAll("_", " ")); if (result != null) return result; } return 0; } /** * get name for id * * @return name or null */ public String get(int id) { return id2name.get(id); } /** * remove an id from the map * */ public void remove(int id) { String name = id2name.get(id); if (name != null) name2id.remove(name); id2name.remove(id); } /** * put a name and id * */ public void put(String name, int id) { name2id.put(name, id); id2name.put(id, name); } /** * get the set of ids * * @return id set */ public Collection<Integer> getIds() { return name2id.values(); } /** * get the set of names * * @return names */ public Collection<String> getNames() { return name2id.keySet(); } /** * gets the size of the mapping * * @return size */ public int size() { return name2id.size(); } /** * load from file */ public void loadFromFile(String fileName) throws IOException { System.err.print("Loading " + FileUtils.getFileNameWithoutPath(fileName) + ": "); try (BufferedReader r = new BufferedReader(new InputStreamReader(ResourceManager.getFileAsStream(fileName)))) { String aLine; while ((aLine = r.readLine()) != null) { if (!aLine.isEmpty() && !aLine.startsWith("#")) { String[] tokens = StringUtils.split(aLine, '\t'); if (tokens.length >= 2) { if (tokens[0].trim().isEmpty()) continue; // Silva has such lines... int id = Integer.parseInt(tokens[0]); String name = tokens[1]; name2id.put(name, id); id2name.put(id, name); boolean hasToolTip = tokens.length > 2 && tokens[tokens.length - 1].startsWith("\""); int tokensLengthWithoutToolTip = (hasToolTip ? tokens.length - 1 : tokens.length); Integer rank = null; if (tokensLengthWithoutToolTip == 3 && NumberUtils.isInteger(tokens[2])) { // just level rank = Integer.parseInt(tokens[2]); } else if (tokensLengthWithoutToolTip == 4) { // genome size, level rank = Integer.parseInt(tokens[3]); } if (hasToolTip) { String quotedToolTip = tokens[tokens.length - 1]; id2toolTip.put(id, quotedToolTip.substring(1, quotedToolTip.length() - 1)); } if (rank != null) id2rank.put(id, rank); } } } } catch (NullPointerException ex) { throw new IOException("not found: " + fileName); } System.err.printf("%,9d%n", id2name.size()); } /** * save mapping to file * */ public void saveMappingToFile(String fileName) throws IOException { System.err.println("Writing name2id map to file: " + fileName); try (Writer w = new FileWriter(fileName)) { writeMapping(w); } System.err.println("Done (" + id2name.size() + " entries)"); } /** * write the new mapping * */ public void writeMapping(Writer w) throws IOException { w.write("# Mapping file, generated " + (new Date()) + "\n"); for (Integer key : id2name.keySet()) { w.write(key + "\t" + id2name.get(key).replaceAll("\\s+", " ") + "\n"); } } /** * get the rank of an item * * @return rank */ public int getRank(int id) { Integer rank = id2rank.get(id); return rank == null ? 0 : rank; } /** * put the rank of an id * */ public void setRank(int id, int rank) { id2rank.put(id, rank); } public Map<Integer, Integer> getId2Rank() { return id2rank; } /** * gets the tooltip map * * @return tooltip map */ public Map<Integer, String> getId2ToolTip() { return id2toolTip; } }
6,931
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
IntIntMap.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/data/IntIntMap.java
/* * IntIntMap.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.classification.data; import megan.classification.util.Tools; import java.io.*; /** * optimized int to int map, see http://java-performance.info/implementing-world-fastest-java-int-to-int-hash-map/ */ public class IntIntMap { private static final int NO_VALUE = 0; private static final int FREE_KEY = 0; private static final int MAGIC_NUMBER = 123456789; /** * Do we have 'free' key in the map? */ private boolean m_hasFreeKey; /** * Value of 'free' key */ private int m_freeValue; /** * Fill factor, must be between (0 and 1) */ private final float m_fillFactor; /** * We will resize a map once it reaches this size */ private int m_threshold; /** * Current map size */ private int m_size; /** * Mask to calculate the original position */ private int m_mask; private int m_mask2; /** * Keys and values */ private int[] m_data; /** * constructor * */ public IntIntMap(final int size, final float fillFactor) { if (fillFactor <= 0 || fillFactor >= 1) throw new IllegalArgumentException("FillFactor must be in (0, 1)"); if (size <= 0) throw new IllegalArgumentException("Size must be positive!"); final int capacity = Tools.arraySize(size, fillFactor); m_mask = capacity - 1; m_mask2 = capacity * 2 - 1; m_fillFactor = fillFactor; m_data = new int[capacity * 2]; m_threshold = (int) (capacity * fillFactor); } /** * get value * * @return get value */ public int get(final int key) { int ptr = (Tools.phiMix(key) & m_mask) << 1; if (key == FREE_KEY) return m_hasFreeKey ? m_freeValue : NO_VALUE; int k = m_data[ptr]; if (k == FREE_KEY) return NO_VALUE; //end of chain already if (k == key) //we check FREE prior to this call return m_data[ptr + 1]; while (true) { ptr = (ptr + 2) & m_mask2; //that's next index k = m_data[ptr]; if (k == FREE_KEY) return NO_VALUE; if (k == key) return m_data[ptr + 1]; } } /** * put value * */ public void put(final int key, final int value) { if (key == FREE_KEY) { final int ret = m_freeValue; if (!m_hasFreeKey) ++m_size; m_hasFreeKey = true; m_freeValue = value; return; } int ptr = (Tools.phiMix(key) & m_mask) << 1; int k = m_data[ptr]; if (k == FREE_KEY) //end of chain already { m_data[ptr] = key; m_data[ptr + 1] = value; if (m_size >= m_threshold) rehash(m_data.length * 2); //size is set inside else ++m_size; return; } else if (k == key) //we check FREE prior to this call { final int ret = m_data[ptr + 1]; m_data[ptr + 1] = value; return; } while (true) { ptr = (ptr + 2) & m_mask2; //that's next index calculation k = m_data[ptr]; if (k == FREE_KEY) { m_data[ptr] = key; m_data[ptr + 1] = value; if (m_size >= m_threshold) rehash(m_data.length * 2); //size is set inside else ++m_size; return; } else if (k == key) { final int ret = m_data[ptr + 1]; m_data[ptr + 1] = value; return; } } } /** * remove a key * */ public int remove(final int key) { if (key == FREE_KEY) { if (!m_hasFreeKey) return NO_VALUE; m_hasFreeKey = false; --m_size; return m_freeValue; //value is not cleaned } int ptr = (Tools.phiMix(key) & m_mask) << 1; int k = m_data[ptr]; if (k == key) //we check FREE prior to this call { final int res = m_data[ptr + 1]; shiftKeys(ptr); --m_size; return res; } else if (k == FREE_KEY) return NO_VALUE; //end of chain already while (true) { ptr = (ptr + 2) & m_mask2; //that's next index calculation k = m_data[ptr]; if (k == key) { final int res = m_data[ptr + 1]; shiftKeys(ptr); --m_size; return res; } else if (k == FREE_KEY) return NO_VALUE; } } /** * get size * * @return size */ public int size() { return m_size; } private void shiftKeys(int pos) { // Shift entries with the same hash. int last, slot; int k; final int[] data = this.m_data; while (true) { pos = ((last = pos) + 2) & m_mask2; while (true) { if ((k = data[pos]) == FREE_KEY) { data[last] = FREE_KEY; return; } slot = (Tools.phiMix(k) & m_mask) << 1; //calculate the starting slot for the current key if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; pos = (pos + 2) & m_mask2; //go to the next entry } data[last] = k; data[last + 1] = data[pos + 1]; } } private void rehash(final int newCapacity) { m_threshold = (int) (newCapacity / 2 * m_fillFactor); m_mask = newCapacity / 2 - 1; m_mask2 = newCapacity - 1; final int oldCapacity = m_data.length; final int[] oldData = m_data; m_data = new int[newCapacity]; m_size = m_hasFreeKey ? 1 : 0; for (int i = 0; i < oldCapacity; i += 2) { final int oldKey = oldData[i]; if (oldKey != FREE_KEY) put(oldKey, oldData[i + 1]); } } // private int getStartIdx( final int key ) // { // return ( Tools.phiMix( key ) & m_mask) << 1; // } /** * construct from input stream * */ public IntIntMap(InputStream inputStream) throws IOException { try (DataInputStream ins = new DataInputStream(inputStream)) { int magicNumber = ins.readInt(); if (magicNumber != MAGIC_NUMBER) throw new IOException("Wrong file type"); m_hasFreeKey = ins.readBoolean(); m_freeValue = ins.readInt(); m_fillFactor = ins.readFloat(); m_threshold = ins.readInt(); m_size = ins.readInt(); m_mask = ins.readInt(); m_mask2 = ins.readInt(); final int m_data_length = ins.readInt(); m_data = new int[m_data_length]; for (int i = 0; i < m_data_length; i++) m_data[i] = ins.readInt(); } } /** * save to file * */ public void save(File file, boolean append) throws IOException { try (DataOutputStream outs = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file, append)))) { outs.writeInt(MAGIC_NUMBER); outs.writeBoolean(m_hasFreeKey); outs.writeInt(m_freeValue); outs.writeFloat(m_fillFactor); outs.writeInt(m_threshold); outs.writeInt(m_size); outs.writeInt(m_mask); outs.writeInt(m_mask2); outs.writeInt(m_data.length); for (int a : m_data) outs.writeInt(a); } } }
8,659
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
String2IntegerMap.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/data/String2IntegerMap.java
/* * String2IntegerMap.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.classification.data; import jloda.util.CanceledException; import jloda.util.FileLineIterator; import jloda.util.NumberUtils; import jloda.util.progress.ProgressListener; import megan.data.IName2IdMap; import java.io.BufferedWriter; import java.io.Closeable; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; /** * a loadable string to integer map. Integers may have a prefix * Daniel Huson, 7.2016 */ public class String2IntegerMap extends HashMap<String, Integer> implements Closeable { /** * load a file of synonyms * */ public void loadFile(IName2IdMap label2id, String fileName, ProgressListener progressListener) throws IOException, CanceledException { System.err.println("Loading map from file: " + fileName); try (FileLineIterator it = new FileLineIterator(fileName)) { it.setSkipCommentLines(true); it.setSkipEmptyLines(true); progressListener.setProgress(0); progressListener.setMaximum(it.getMaximumProgress()); while (it.hasNext()) { String aLine = it.next(); String[] tokens = aLine.split("\t"); if (tokens.length >= 2) { final int id; if (NumberUtils.isInteger(tokens[1])) { id = NumberUtils.parseInt(tokens[1]); } else { id = label2id.get(tokens[1]); } if (id != 0) put(tokens[0], id); else System.err.println("Line " + it.getLineNumber() + ": invalid id: " + tokens[1]); } else { throw new IOException("Loading synonyms-to-id file, line: " + it.getLineNumber() + ": expected two entries separated by a tab, got: <" + aLine + ">"); } progressListener.setProgress(it.getProgress()); } } finally { System.err.println("Lines loaded: " + size()); } } /** * save to a file * */ public void save(String fileName) throws IOException { try (BufferedWriter w = new BufferedWriter(new FileWriter(fileName), 1000000)) { for (String key : keySet()) { Integer value = get(key); if (value != null) w.write(key + "\t" + value + "\n"); } } } /** * has the table been loaded * */ public boolean isLoaded() { return size() > 0; } @Override public void close() { clear(); } }
3,337
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ILong2IntegerMapFactory.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/data/ILong2IntegerMapFactory.java
/* * ILong2IntegerMapFactory.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.classification.data; import jloda.util.CanceledException; import jloda.util.progress.ProgressListener; import megan.data.IName2IdMap; import java.io.IOException; /** * factory for creating long-2-integer mappings * Created by huson on 7/15/16. */ public interface ILong2IntegerMapFactory { /** * create a long to integer map from the named file * * @param label2id option mapping of labels to ids * @param fileName file * @param progress progress listner * @return map or null */ ILong2IntegerMap create(IName2IdMap label2id, String fileName, ProgressListener progress) throws IOException, CanceledException; }
1,494
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Long2IntegerBinMap.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/data/Long2IntegerBinMap.java
/* * Long2IntegerBinMap.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.classification.data; import jloda.util.FileUtils; import megan.io.IIntGetter; import megan.io.IntFileGetterMappedMemory; import megan.io.IntFileGetterRandomAccess; import java.io.*; /** * long to integer mapping in binary file format * Daniel Huson, 4.2010, 4.2015 */ class Long2IntegerBinMap implements ILong2IntegerMap, Closeable { private static final int MAGIC_NUMBER = 666; // write this as first number so that we can recognize file private IIntGetter reader; /** * open a bin file * */ public Long2IntegerBinMap(String fileName) throws IOException{ FileUtils.checkFileReadableNonEmpty(fileName); var file = new File(fileName); if (!isBinFile(fileName)) throw new IOException("Wrong magic number: " + file); try { reader = new IntFileGetterMappedMemory(file); } catch (IOException ex) { // on 32-bit machine, memory mapping will fail... use Random access System.err.println("Opening file: " + file); reader = new IntFileGetterRandomAccess(file); } } /** * lookup an id from a gi * * @return id or 0 */ public int get(long key) throws IOException { if (key >= 0 && key < reader.limit()) return reader.get(key); else return 0; } @Override public void close() { reader.close(); } /** * does this look like a valid bin file? * * @return true, if this looks like a valid bin file */ public static boolean isBinFile(String fileName) { try (var dis = new DataInputStream(new FileInputStream(fileName))) { var firstInt = dis.readInt(); return firstInt == 0 || firstInt == MAGIC_NUMBER; } catch (Exception e) { return false; } } }
2,680
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Long2IntegerFileBasedMap.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/data/Long2IntegerFileBasedMap.java
/* * Long2IntegerFileBasedMap.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.classification.data; import jloda.util.CanceledException; import jloda.util.FileLineIterator; import jloda.util.NumberUtils; import jloda.util.progress.ProgressListener; import jloda.util.progress.ProgressPercentage; import megan.data.IName2IdMap; import megan.io.OutputWriter; import java.io.Closeable; import java.io.File; import java.io.IOException; /** * long to integer mapping that can be loaded from and saved to a file * Daniel Huson, 4.2010, 4.2015 */ public class Long2IntegerFileBasedMap implements ILong2IntegerMap, Closeable { public static final int MAGIC_NUMBER = 666; // write this as first number so that we can recognize file private final static int BITS = 10; // 2^10=1024 private final static int SIZE = (1 << BITS); private final static int MASK = (SIZE - 1); private final IntIntMap[] maps; /** * constructor * */ public Long2IntegerFileBasedMap(final IName2IdMap label2id, final String fileName, final ProgressListener progress) throws IOException, CanceledException { maps = new IntIntMap[SIZE]; for (int i = 0; i < maps.length; i++) { maps[i] = new IntIntMap(2 ^ 20, 0.9f); // 2^20=1048576 } final File file = new File(fileName); System.err.println("Loading file: " + file.getName()); int totalIn = 0; int totalSkipped = -100; // allow ourselves 100 skips more than totalIn before we give up... try (final FileLineIterator it = new FileLineIterator(file)) { progress.setTasks("Loading file", file.getName()); progress.setProgress(0); progress.setMaximum(it.getMaximumProgress()); while (it.hasNext()) { String[] tokens = it.next().split("\t"); if (tokens[0].length() > 0 && tokens[0].charAt(0) != '#' && tokens.length == 2) { long giNumber = NumberUtils.parseLong(tokens[0]); if (giNumber > 0) { if (NumberUtils.isInteger(tokens[1])) { int id = NumberUtils.parseInt(tokens[1]); if (id != 0) { put(giNumber, id); totalIn++; } } else if (label2id != null) { int id = label2id.get(tokens[1]); if (id != 0) { put(giNumber, id); totalIn++; } } } } else { if (totalSkipped++ > totalIn) throw new IOException("Failed to parse too many lines, is this really a .map or .bin file? " + fileName); } progress.setProgress(it.getProgress()); } } if (progress instanceof ProgressPercentage) progress.reportTaskCompleted(); System.err.printf("Entries: %,10d%n", totalIn); } /** * add a value to the map maintained in memory * */ private void put(long key, int value) { maps[(int) (key & MASK)].put((int) (key >>> BITS), value); } /** * lookup an id from a gi * * @return id or 0 */ public int get(long key) { if (key <= 0) return 0; synchronized (maps) { final int whichArray = (int) (key & MASK); final int index = (int) (key >>> BITS); return maps[whichArray].get(index); } } @Override public void close() { } /** * converts the named dmp file to a bin file * */ public static void writeToBinFile(File dmpFile, File binFile) throws IOException { System.err.println("Converting " + dmpFile.getName() + " to " + binFile.getName() + "..."); long totalOut = 0; try (final FileLineIterator it = new FileLineIterator(dmpFile, true); OutputWriter outs = new OutputWriter(binFile)) { System.err.println("Writing file: " + binFile); outs.writeInt(MAGIC_NUMBER); long lastGi = 0; int lineNo = 0; while (it.hasNext()) { String aLine = it.next(); lineNo++; final int pos = aLine.indexOf('\t'); final String giString = aLine.substring(0, pos); final int dotPos = giString.indexOf('.'); final long gi = Long.parseLong(dotPos > 0 ? giString.substring(0, dotPos) : giString); if (gi >= 0) { final int taxId = Integer.parseInt(aLine.substring(pos + 1)); if (gi <= lastGi) throw new IOException("Error, line: " + lineNo + ": GIs out of order: " + gi + " after " + lastGi); // fill in missing Gis final int missing = (int) (gi - 1 - lastGi); for (int i = 0; i < missing; i++) outs.writeInt(0); outs.writeInt(taxId); totalOut++; lastGi = gi; } } } System.err.println("done (" + totalOut + " entries)"); } }
6,157
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
GI2IdMapFactory.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/data/GI2IdMapFactory.java
/* * GI2IdMapFactory.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.classification.data; import jloda.swing.window.NotificationsInSwing; import jloda.util.CanceledException; import jloda.util.progress.ProgressListener; import jloda.util.progress.ProgressPercentage; import megan.data.IName2IdMap; import java.io.File; import java.io.IOException; /** * factory for creating GI to ID mappings * Created by huson on 7/15/16. */ public class GI2IdMapFactory implements ILong2IntegerMapFactory { /** * create a long to integer map from the named file * * @param label2id option mapping of labels to ids * @param fileName file * @param progress progress listner * @return map or null */ @Override public ILong2IntegerMap create(IName2IdMap label2id, String fileName, ProgressListener progress) throws IOException, CanceledException { final String name = (new File(fileName)).getName(); if (name.equals("gi_taxid-March2015X.bin") || name.equals("gi2kegg-Nov2015X.bin") || name.equals("gi2tax-Feb2016.bin") || name.equals("gi2tax-Feb2016X.bin")) NotificationsInSwing.showWarning("The mapping file '" + name + "' is known to contain errors, please use latest file from the MEGAN6 download page"); if (Long2IntegerBinMap.isBinFile(fileName)) return new Long2IntegerBinMap(fileName); else return new Long2IntegerFileBasedMap(label2id, fileName, progress != null ? progress : new ProgressPercentage()); } }
2,279
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Accession2IdMap.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/data/Accession2IdMap.java
/* * Accession2IdMap.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.classification.data; import jloda.util.FileLineIterator; import jloda.util.NumberUtils; import jloda.util.StringUtils; import jloda.util.progress.ProgressListener; import megan.data.IName2IdMap; import java.io.Closeable; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * maps accession strings to ids * Daniel Huson, 3.2016 */ public class Accession2IdMap implements IString2IntegerMap, Closeable { private final Map<String, Integer> map; /** * constructor * */ public Accession2IdMap(final IName2IdMap label2id, final String fileName, final ProgressListener progress) throws IOException { map = new HashMap<>(200000000); try (FileLineIterator it = new FileLineIterator(fileName)) { progress.setSubtask("Loading file: " + fileName); progress.setMaximum(it.getMaximumProgress()); while (it.hasNext()) { String[] tokens = StringUtils.split(it.next(), '\t'); if (tokens.length == 2) { if (NumberUtils.isInteger(tokens[1])) { int id = NumberUtils.parseInt(tokens[1]); if (id != 0) { map.put(tokens[0], id); } } else if (label2id != null) { int id = label2id.get(tokens[1]); if (id != 0) { map.put(tokens[0], id); } } } progress.setProgress(it.getProgress()); } } } public int size() { return map.size(); } @Override public void close() { map.clear(); } public int get(String accession) { final var result = map.get(accession); return Objects.requireNonNullElse(result, 0); } public Map<String, Integer> getMap() { return map; } }
2,810
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetAnalyseCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/commandtemplates/SetAnalyseCommand.java
/* * SetAnalyseCommand.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.classification.commandtemplates; import jloda.swing.commands.CommandBase; 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.ClassificationManager; import javax.swing.*; import java.awt.event.ActionEvent; /** * Turns use of named functional viewer on or off * Daniel Huson, 4.2015 */ public class SetAnalyseCommand extends CommandBase implements ICommand { public String getSyntax() { return "use cViewer=<name> state={true|false};"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("use cViewer="); String cName = np.getWordMatchesRespectingCase(StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), " ")); np.matchIgnoreCase("state="); boolean select = np.getBoolean(); np.matchIgnoreCase(";"); ProgramProperties.put("Use" + cName, select); } public void actionPerformed(ActionEvent event) { } public boolean isApplicable() { return true; } public String getName() { return null; } public String getDescription() { return "Determine whether to perform a specific functional analysis"; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Preferences16.gif"); } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
2,424
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
OpenFViewerCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/commandtemplates/OpenFViewerCommand.java
/* * OpenFViewerCommand.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.classification.commandtemplates; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.util.Basic; import jloda.util.parse.NexusStreamParser; import megan.classification.ClassificationManager; import megan.core.Director; import megan.core.Document; import megan.viewer.ClassificationViewer; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.image.BufferedImage; /** * Command for opening a named function viewer * These commands are added to the global list of commands. They are not generated by reflection. * Daniel Huson, 4.2015 */ public class OpenFViewerCommand extends CommandBase implements ICommand { private final String cName; /** * constructor * */ public OpenFViewerCommand(String cName) { this.cName = cName; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase(getSyntax()); final boolean firstOpen; final ClassificationViewer classificationViewer; if (((Director) getDir()).getViewerByClassName(cName) != null) { classificationViewer = (ClassificationViewer) ((Director) getDir()).getViewerByClassName(cName); firstOpen = false; } else { try { classificationViewer = new ClassificationViewer((Director) getDir(), ClassificationManager.get(cName, true), true); getDir().addViewer(classificationViewer); firstOpen = true; } catch (Exception e) { Basic.caught(e); return; } } SwingUtilities.invokeLater(() -> { classificationViewer.getFrame().setVisible(true); classificationViewer.getFrame().setState(JFrame.NORMAL); classificationViewer.getFrame().toFront(); classificationViewer.updateView(Director.ALL); // aim of this is to prevent windowing opening blank: if (firstOpen) { final Timer timer = new Timer(600, e -> SwingUtilities.invokeLater(() -> classificationViewer.getDir().execute("zoom what=fit;", classificationViewer.getCommandManager()))); timer.setRepeats(false); timer.start(); } }); } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "open viewer=" + cName + ";"; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { execute(getSyntax()); } /** * get the name to be used as a menu label * * @return name */ @Override public String getName() { return "Open " + cName + " Viewer..."; } /** * get description to be used as a tooltip * * @return description */ @Override public String getDescription() { return "Open " + cName + " viewer"; } /** * get icon to be used in menu or button * * @return icon */ @Override public ImageIcon getIcon() { final String iconFile = ClassificationManager.getIconFileName(cName); if (ResourceManager.getImage(iconFile) == null && ResourceManager.getIcon(iconFile, false) == null) { // no icon file found, build an icon.... ResourceManager.getIconMap().put(iconFile, new MyImageIcon(iconFile)); } return ResourceManager.getIcon(iconFile); } /** * icon to represent classification */ static class MyImageIcon extends ImageIcon { /** * construct icon * */ MyImageIcon(String label) { final BufferedImage image = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB); Graphics2D g = image.createGraphics(); g.setColor((new JButton()).getBackground()); g.fillRect(0, 0, 16, 16); g.setFont(new Font(Font.SERIF, Font.PLAIN, 15)); g.setColor(Color.GRAY); g.drawString(label.substring(0, 1).toUpperCase(), 1, 13); g.dispose(); setImage(image); } } /** * gets the accelerator key to be used in menu * * @return accelerator key */ @Override 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 */ @Override public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ @Override public boolean isApplicable() { if (ProgramProperties.get("enable-open-empty-fviewer", false)) return true; final Document doc = ((Director) getDir()).getDocument(); return doc.getActiveViewers().contains(cName); } }
6,056
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
LoadMappingFile4ViewerCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/commandtemplates/LoadMappingFile4ViewerCommand.java
/* * LoadMappingFile4ViewerCommand.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.classification.commandtemplates; 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.parse.NexusStreamParser; import megan.accessiondb.AccessAccessionMappingDatabase; import megan.classification.ClassificationManager; import megan.classification.IdMapper; import megan.importblast.ImportBlastDialog; import javax.swing.*; import java.awt.event.ActionEvent; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; /** * loads a mapping file for the given fViewer and mapType * Daniel Huson, 3.2014 */ public class LoadMappingFile4ViewerCommand extends CommandBase implements ICommand { private final Collection<String> cNames; final private String cName; final private IdMapper.MapType mapType; public LoadMappingFile4ViewerCommand(Collection<String> cNames, String cName, IdMapper.MapType mapType) { this.cNames = cNames; this.cName = cName; this.mapType = mapType; } /** * commandline syntax * */ @Override public String getSyntax() { return null; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) { } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { final File lastOpenFile = ProgramProperties.getFile(ClassificationManager.getMapFileKey(cName, mapType)); getDir().notifyLockInput(); ImportBlastDialog dialog = (ImportBlastDialog) getParent(); final ArrayList<String> suffixes = new ArrayList<>(Arrays.asList("map", "map.gz")); if (mapType == IdMapper.MapType.Accession) { suffixes.add("abin"); } else if (mapType == IdMapper.MapType.MeganMapDB) { suffixes.add("db"); } final File file = ChooseFileDialog.chooseFileToOpen(dialog, lastOpenFile, new TextFileFilter(suffixes.toArray(new String[0]), false), new TextFileFilter(suffixes.toArray(new String[0]), true), ev, "Open " + mapType + " File"); getDir().notifyUnlockInput(); if (file != null) { if (file.exists() && file.canRead()) { if (mapType != IdMapper.MapType.MeganMapDB) { ProgramProperties.put(ClassificationManager.getMapFileKey(cName, mapType), file); execute("load mapFile='" + file.getPath() + "' mapType=" + mapType + " cName=" + cName + ";"); } else { try { ClassificationManager.setMeganMapDBFile(file.toString()); ClassificationManager.setUseFastAccessionMappingMode(true); } catch (IOException e) { NotificationsInSwing.showError("Load MEGAN mapping db failed: " + e.getMessage()); return; } final Collection<String> supportedClassifications = AccessAccessionMappingDatabase.getContainedClassificationsIfDBExists(file.getPath()); for (String name : cNames) { if (supportedClassifications.contains(name)) { ProgramProperties.put(ClassificationManager.getMapFileKey(name, mapType), file); executeImmediately("load mapFile='" + file.getPath() + "' mapType=" + mapType + " cName=" + name + ";"); } executeImmediately("use cViewer=" + name + " state=" + supportedClassifications.contains(name) + ";"); } execute("update;"); } } else NotificationsInSwing.showError(getViewer().getFrame(), "Failed to open 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; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Open16.gif"); } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return !ClassificationManager.isUseFastAccessionMappingMode() || mapType == IdMapper.MapType.MeganMapDB; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } public static String getAltName(String cName, IdMapper.MapType mapType) { return "Load " + mapType + " mapping file for " + cName; } public String getAltName() { return getAltName(cName, mapType); } public static String getName(String cName, IdMapper.MapType mapType) { return "Load " + mapType + " mapping file"; } /** * get the name to be used as a menu label * * @return name */ public String getName() { return getName(cName, mapType); } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { if (mapType == IdMapper.MapType.MeganMapDB) return "Load a MEGAN mapping DB file to map to " + cName + " ids"; else return "Load a file that maps " + mapType + " ids to " + cName + " ids"; } }
6,706
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetUseLCA4ViewerCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/commandtemplates/SetUseLCA4ViewerCommand.java
/* * SetUseLCA4ViewerCommand.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.classification.commandtemplates; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICheckBoxCommand; import jloda.swing.util.ProgramProperties; import jloda.util.parse.NexusStreamParser; import megan.main.MeganProperties; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.Arrays; /** * use LCS for the given fViewer and mapType * Daniel Huson, 10.2015 */ public class SetUseLCA4ViewerCommand extends CommandBase implements ICheckBoxCommand { final private String cName; public SetUseLCA4ViewerCommand(String cName) { this.cName = cName; } public boolean isSelected() { return Arrays.asList(ProgramProperties.get(MeganProperties.TAXONOMIC_CLASSIFICATIONS, new String[]{"Taxonomy", "GTDB"})).contains(cName); } /** * commandline syntax * */ @Override public String getSyntax() { 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("set useLCA=" + (!isSelected()) + " cName=" + cName + ";"); } /** * 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 icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { 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 true; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } public static String getAltName(String cName) { return "Use LCA For " + cName; } public String getAltName() { return getAltName(cName); } /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Use LCA"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Use LCA algorithm for analyzing " + cName + " content. This option is not recommended for functional binning; stick to the default 'best hit'."; } }
3,449
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetUseMapType4ViewerCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/commandtemplates/SetUseMapType4ViewerCommand.java
/* * SetUseMapType4ViewerCommand.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.classification.commandtemplates; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICheckBoxCommand; import jloda.util.parse.NexusStreamParser; import megan.classification.ClassificationManager; import megan.classification.IdMapper; import javax.swing.*; import java.awt.event.ActionEvent; /** * Set maptype to use for specific fViewer * Daniel Huson, 4.2015 */ public class SetUseMapType4ViewerCommand extends CommandBase implements ICheckBoxCommand { final private String cName; final private IdMapper.MapType mapType; /** * constructor * */ public SetUseMapType4ViewerCommand(String cName, IdMapper.MapType mapType) { this.cName = cName; this.mapType = mapType; } /** * is selected? */ @Override public boolean isSelected() { if (ClassificationManager.isUseFastAccessionMappingMode() && mapType == IdMapper.MapType.MeganMapDB) return ClassificationManager.canUseMeganMapDBFile(); else return ClassificationManager.isActiveMapper(cName, mapType); } public String getSyntax() { return null; } public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { executeImmediately("use mapType=" + mapType + " cName=" + cName + " state=" + (!isSelected()) + ";"); } public boolean isApplicable() { return ClassificationManager.isLoaded(cName, mapType) && !ClassificationManager.isUseFastAccessionMappingMode(); } public static String getAltName(String cName, IdMapper.MapType mapType) { return "Use " + mapType + " For " + cName; } public String getAltName() { return getAltName(cName, mapType); } public String getName() { return "Use " + mapType; } public String getDescription() { return "Use " + mapType + " map to identify classes when parsing " + cName + " data"; } public ImageIcon getIcon() { return null; } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
2,999
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetAnalyse4ViewerCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/commandtemplates/SetAnalyse4ViewerCommand.java
/* * SetAnalyse4ViewerCommand.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.classification.commandtemplates; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICheckBoxCommand; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import javax.swing.*; import java.awt.event.ActionEvent; /** * Turns use of named functional viewer on or off * Daniel Huson, 4.2015 */ public class SetAnalyse4ViewerCommand extends CommandBase implements ICheckBoxCommand { private final String cName; public SetAnalyse4ViewerCommand(String cName) { this.cName = cName; } public boolean isSelected() { return ProgramProperties.get("Use" + cName, false); } public String getSyntax() { return null; } public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { executeImmediately("use cViewer=" + cName + " state=" + (!isSelected()) + ";"); } public boolean isApplicable() { return true; } public static String getName(String cName) { return "Analyze " + cName + " content"; // use Analyze not Analyse to differ from old commands } public String getName() { return getName(cName); } public String getDescription() { return "Analyse the " + cName + " content of the sample"; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Preferences16.gif"); } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
2,435
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
LoadMappingFileCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/commandtemplates/LoadMappingFileCommand.java
/* * LoadMappingFileCommand.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.classification.commandtemplates; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ProgressDialog; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import jloda.util.progress.ProgressListener; import jloda.util.progress.ProgressPercentage; import megan.classification.Classification; import megan.classification.ClassificationManager; import megan.classification.IdMapper; import megan.importblast.ImportBlastDialog; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; /** * loads a mapping file for the given fViewer and mapType * Daniel Huson, 3.2014 */ public class LoadMappingFileCommand extends CommandBase implements ICommand { /** * commandline syntax */ @Override public String getSyntax() { return "load mapFile=<filename> mapType=<" + StringUtils.toString(IdMapper.MapType.values(), "|") + "> cName=<" + StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), "|") + "> [parseTaxonNames={false|true}];"; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("load mapFile="); final String fileName = np.getWordFileNamePunctuation(); np.matchIgnoreCase("mapType="); final IdMapper.MapType mapType = IdMapper.MapType.valueOf(np.getWordMatchesRespectingCase(StringUtils.toString(IdMapper.MapType.values(), " "))); np.matchIgnoreCase("cName="); final String cName = np.getWordMatchesRespectingCase(StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), " ")); final boolean parseTaxonName; if (np.peekMatchIgnoreCase("parseTaxonNames")) { np.matchIgnoreCase("parseTaxonNames="); parseTaxonName = np.getBoolean(); if (parseTaxonName) { if (!cName.equals(Classification.Taxonomy)) System.err.println("Warning: load mapFile: cName=" + cName + " is not Taxonomy, ignoring 'parseTaxonNames=true'"); } } else parseTaxonName = false; np.matchIgnoreCase(";"); final Classification classification = ClassificationManager.get(cName, true); classification.getIdMapper().setUseTextParsing(parseTaxonName); ProgressListener progressListener; if (ProgramProperties.isUseGUI()) progressListener = new ProgressDialog("Loading file", "", (Component) getParent()); else progressListener = new ProgressPercentage(); try { final IdMapper mapper = classification.getIdMapper(); mapper.loadMappingFile(fileName, mapType, true, progressListener); } finally { progressListener.close(); } if (getParent() instanceof ImportBlastDialog) { ((ImportBlastDialog) getParent()).getCommandManager().execute("use cViewer=" + cName + " state=true;"); } ProgramProperties.put(ClassificationManager.getMapFileKey(cName, mapType), fileName); } /** * action to be performed */ public void actionPerformed(ActionEvent ev) { } /** * 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 icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { 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 true; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Load Mapping File"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Loads a mapping file"; } }
4,753
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetUseIdParsing4ViewerCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/commandtemplates/SetUseIdParsing4ViewerCommand.java
/* * SetUseIdParsing4ViewerCommand.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.classification.commandtemplates; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICheckBoxCommand; import jloda.swing.director.IDirectableViewer; import jloda.swing.util.ProgramProperties; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.classification.ClassificationManager; import megan.classification.IdMapper; import javax.swing.*; import java.awt.event.ActionEvent; /** * use Id parsing for the given fViewer and mapType * Daniel Huson, 10.2015 */ public class SetUseIdParsing4ViewerCommand extends CommandBase implements ICheckBoxCommand { final private String cName; public SetUseIdParsing4ViewerCommand(String cName) { this.cName = cName; } public boolean isSelected() { return ProgramProperties.get(cName + "ParseIds", false); } /** * commandline syntax * */ @Override public String getSyntax() { return null; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) { } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { if (isSelected()) execute("set idParsing=false cName=" + cName + ";"); else { String idTags = StringUtils.toString(ProgramProperties.get(cName + "Tags", IdMapper.createTags(cName)), " "); final JFrame frame = ((getParent() instanceof IDirectableViewer) ? ((IDirectableViewer) getParent()).getFrame() : null); idTags = JOptionPane.showInputDialog(frame, "Enter tag(s) used to identify ids (separated by spaces):", idTags); if (idTags != null) execute("set idParsing=true cName=" + cName + " prefix='" + idTags + "';"); else execute("set idParsing=false cName=" + cName + ";"); } } /** * 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 icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { 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 !ClassificationManager.isUseFastAccessionMappingMode(); } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } public static String getAltName(String cName) { return "Use Id parsing for " + cName; } public String getAltName() { return getAltName(cName); } /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Use Id parsing"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Parse class ids directly from header line using tags"; } }
4,083
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetUseLCACommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/commandtemplates/SetUseLCACommand.java
/* * SetUseLCACommand.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.classification.commandtemplates; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ProgramProperties; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.classification.ClassificationManager; import megan.classification.IdMapper; import megan.importblast.ImportBlastDialog; import megan.main.MeganProperties; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * Set whether to use LCA for specific fViewer * Daniel Huson, 1.2016 */ public class SetUseLCACommand extends CommandBase implements ICommand { public String getSyntax() { return "set useLCA={true|false} cName=<name>;"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set useLCA="); boolean useLCA = np.getBoolean(); np.matchIgnoreCase("cName="); final String cName = np.getWordMatchesRespectingCase(StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), " ")); np.matchIgnoreCase(";"); final Set<String> set = new HashSet<>(Arrays.asList(ProgramProperties.get(MeganProperties.TAXONOMIC_CLASSIFICATIONS, new String[]{"Taxonomy", "GTDB"}))); if (useLCA) set.add(cName); else set.remove(cName); ProgramProperties.put(MeganProperties.TAXONOMIC_CLASSIFICATIONS, set.toArray(new String[0])); if (getParent() instanceof ImportBlastDialog) { final IdMapper mapper = ClassificationManager.get(cName, true).getIdMapper(); ((ImportBlastDialog) getParent()).getCommandManager().execute("use cViewer=" + cName + " state=" + mapper.hasActiveAndLoaded() + ";"); } } public void actionPerformed(ActionEvent event) { } public boolean isApplicable() { return true; } public String getName() { return null; } public String getDescription() { return "Set whether to use the LCA algorithm for assignment (alternative: best hit)"; } public ImageIcon getIcon() { return null; } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
3,145
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetUseIdParsingCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/commandtemplates/SetUseIdParsingCommand.java
/* * SetUseIdParsingCommand.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.classification.commandtemplates; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ProgramProperties; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.classification.ClassificationManager; import javax.swing.*; import java.awt.event.ActionEvent; /** * Set use id parsing * Daniel Huson, 10.2015 */ public class SetUseIdParsingCommand extends CommandBase implements ICommand { public String getSyntax() { return "set idParsing={true|false} cName=<name> [prefix=<prefix prefix ...>];"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set idParsing="); boolean useIdParsing = np.getBoolean(); np.matchIgnoreCase("cName="); final String cName = np.getWordMatchesRespectingCase(StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), " ")); ProgramProperties.put(cName + "ParseIds", useIdParsing); if (np.peekMatchIgnoreCase("prefix")) { np.matchIgnoreCase("prefix="); String prefix = np.getWordRespectCase(); if (!prefix.equals(";")) { ProgramProperties.put(cName + "Tags", prefix.split("\\s+")); np.matchIgnoreCase(";"); } } } public void actionPerformed(ActionEvent event) { } public boolean isApplicable() { return true; } public String getName() { return null; } public String getDescription() { return "Set ID prefixes and use ID parsing"; } public ImageIcon getIcon() { return null; } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
2,646
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetUseMapTypeCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/commandtemplates/SetUseMapTypeCommand.java
/* * SetUseMapTypeCommand.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.classification.commandtemplates; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.classification.ClassificationManager; import megan.classification.IdMapper; import megan.importblast.ImportBlastDialog; import javax.swing.*; import java.awt.event.ActionEvent; /** * Set map type to use for specific viewer * Daniel Huson, 4.2015 */ public class SetUseMapTypeCommand extends CommandBase implements ICommand { public String getSyntax() { return "use mapType=<mapType> cName=<name> state=<true|false>;"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("use mapType="); final IdMapper.MapType mapType = IdMapper.MapType.valueOf(np.getWordMatchesRespectingCase(StringUtils.toString(IdMapper.MapType.values(), " "))); np.matchIgnoreCase("cName="); final String cName = np.getWordMatchesRespectingCase(StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), " ")); np.matchIgnoreCase("state="); final boolean state = np.getBoolean(); np.matchIgnoreCase(";"); ClassificationManager.setActiveMapper(cName, mapType, state); if (getParent() instanceof ImportBlastDialog) { ((ImportBlastDialog) getParent()).getCommandManager().execute("use cViewer=" + cName + " state=" + ClassificationManager.get(cName, true).getIdMapper().hasActiveAndLoaded() + ";"); } } public void actionPerformed(ActionEvent event) { } public boolean isApplicable() { return true; } public String getName() { return null; } public String getDescription() { return "Set activity state of map type"; } public ImageIcon getIcon() { return null; } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
2,831
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Tools.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/util/Tools.java
/* * Tools.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.classification.util; /** * Common methods */ public class Tools { /** * Return the least power of two greater than or equalOverShorterOfBoth to the specified value. * <p/> * <p>Note that this function will return 1 when the argument is 0. * * @param x a long integer smaller than or equalOverShorterOfBoth to 2<sup>62</sup>. * @return the least power of two greater than or equalOverShorterOfBoth to the specified value. */ private static long nextPowerOfTwo(long x) { if (x == 0) return 1; x--; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return (x | x >> 32) + 1; } /** * Returns the least power of two smaller than or equalOverShorterOfBoth to 2<sup>30</sup> and larger than or equalOverShorterOfBoth to <code>Math.ceil( expected / f )</code>. * * @param expected the expected number of elements in a hash table. * @param f the load factor. * @return the minimum possible size for a backing array. * @throws IllegalArgumentException if the necessary size is larger than 2<sup>30</sup>. */ public static int arraySize(final int expected, final float f) { final long s = Math.max(2, nextPowerOfTwo((long) Math.ceil(expected / f))); if (s > (1 << 30)) throw new IllegalArgumentException("Too large (" + expected + " expected elements with load factor " + f + ")"); return (int) s; } //taken from FastUtil private static final int INT_PHI = 0x9E3779B9; public static int phiMix(final int x) { final int h = x * INT_PHI; return h ^ (h >> 16); } }
2,522
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
MultiWords.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/util/MultiWords.java
/* * MultiWords.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.classification.util; import java.util.Arrays; /** * some additional utils for parsing taxon names and similar * Daniel Huson, 1.2009 */ public class MultiWords { private final static int DEFAULT_MIN_LENGTH = 2; private final static int DEFAULT_MAX_LENGTH = 128; private int[][] pairs; private int[] starts; private int[] ends; private String line; public MultiWords() { pairs = new int[DEFAULT_MAX_LENGTH][2]; starts = new int[DEFAULT_MAX_LENGTH]; ends = new int[DEFAULT_MAX_LENGTH]; } /** * gets all the sets of one or more consecutive words, in decreasing order of length. * Assumes minimum length is 2 and maximum length is 80 * * @return sets of one or more consecutive words */ public int compute(String str) { return compute(str, DEFAULT_MIN_LENGTH, DEFAULT_MAX_LENGTH); } /** * gets all the sets of one or more consecutive words, in decreasing order of length * * @return sets of one or more consecutive words */ public int compute(String line, int minLength, int maxLength) { this.line = line; int countStarts = 0; int countEnds = 0; for (int i = 0; i < line.length(); i++) { if ((i == 0 || !Character.isLetterOrDigit(line.charAt(i - 1))) && (Character.isLetterOrDigit(line.charAt(i)))) { if (countStarts == starts.length) starts = grow(starts); starts[countStarts++] = i; } if ((i == line.length() - 1 || !Character.isLetterOrDigit(line.charAt(i + 1))) && (Character.isLetterOrDigit(line.charAt(i)))) { if (countEnds == ends.length) ends = grow(ends); ends[countEnds++] = i + 1; } if (line.charAt(i) == ')' || line.charAt(i) == ']' || line.charAt(i) == '}') { if (countEnds == ends.length) ends = grow(ends); ends[countEnds++] = i + 1; } } int count = 0; for (int i = 0; i < countStarts; i++) { int start = starts[i]; for (int j = 0; j < countEnds; j++) { int end = ends[j]; if (end - start >= minLength && end - start <= maxLength) { if (count == pairs.length) { pairs = grow(pairs); } pairs[count][0] = start; pairs[count++][1] = end; } } } Arrays.sort(pairs, 0, count, (a, b) -> { int aLen = a[1] - a[0]; int bLen = b[1] - b[0]; if (aLen > bLen) return -1; else if (aLen < bLen) return 1; // have same length and start, must be equalOverShorterOfBoth return Integer.compare(a[0], b[0]); }); return count; } /** * get the i-th pair * * @return pair */ public int[] getPair(int i) { return pairs[i]; } /** * get the i-th word * * @return word */ public String getWord(int i) { return line.substring(pairs[i][0], pairs[i][1]); } private static int[] grow(final int[] array) { final int[] result = new int[Math.max(10, 2 * array.length)]; System.arraycopy(array, 0, result, 0, array.length); return result; } private static int[][] grow(final int[][] array) { final int[][] result = new int[Math.max(10, 2 * array.length)][2]; System.arraycopy(array, 0, result, 0, array.length); return result; } }
4,550
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
TaggedValueIterator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/classification/util/TaggedValueIterator.java
/* * TaggedValueIterator.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.classification.util; import jloda.util.FileLineIterator; import jloda.util.StringUtils; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.NoSuchElementException; /** * iterator over all values following an occurrence of tag in aLine. * Created by huson on 7/21/16. */ public class TaggedValueIterator implements Iterator<String>, java.lang.Iterable<String> { private String aLine; private final String[] tags; private int tagPos; private final boolean attemptFirstWord; private boolean attemptWordsAfterSOH; private boolean enabled; private String nextResult; /** * iterator over all values following an occurrence of tag in aLine. * Example: aLine= gi|4444|gi|5555 and tag=gi| with return 4444 and then 5555 * Value consists of letters, digits or underscore * */ public TaggedValueIterator(final boolean attemptFirstWord, final boolean enabled, final String... tags) { this(null, attemptFirstWord, enabled, tags); } /** * iterator over all values following an occurrence of tag in aLine. * Example: aLine= gi|4444|gi|5555 and tag=gi| with return 4444 and then 5555 * Value consists of letters, digits or underscore * * @param attemptFirstWord if true, attempts to parse the first word in a fasta header string as a value */ public TaggedValueIterator(final String aLine, final boolean attemptFirstWord, final String... tags) { this(aLine, attemptFirstWord, true, tags); } /** * iterator over all values following an occurrence of tag in aLine. * Example: aLine= gi|4444|gi|5555 and tag=gi| with return 4444 and then 5555 * Value consists of letters, digits or underscore * * @param attemptFirstWord if true, attempts to parse the first word in a fasta header string as a value */ public TaggedValueIterator(final String aLine, final boolean attemptFirstWord, final boolean enabled, final String... tags) { this.attemptFirstWord = attemptFirstWord; this.attemptWordsAfterSOH = attemptFirstWord; this.enabled = enabled; this.tags = tags; if (aLine != null) restart(aLine); } public TaggedValueIterator iterator() { return this; } /** * restart the iterator with a new string * */ public TaggedValueIterator restart(String aLine) { this.aLine = aLine; tagPos = 0; nextResult = getNextResult(); if (attemptFirstWord) { var a = 0; while (a < aLine.length()) { if (aLine.charAt(a) == '>' || aLine.charAt(a) == '@' || Character.isWhitespace(aLine.charAt(a))) a++; else break; } var b = a + 1; while (b < aLine.length() && (Character.isLetterOrDigit(aLine.charAt(b)) || aLine.charAt(b) == '_')) { // while(b <aLine.length() && (Character.isLetterOrDigit(aLine.charAt(b)) || aLine.charAt(b) == '_')) { b++; } if (b - a > 4) { nextResult = aLine.substring(a, b); } tagPos = b; } return this; } @Override public boolean hasNext() { return nextResult != null; } @Override public String next() { if (nextResult == null) throw new NoSuchElementException(); final var result = nextResult; nextResult = getNextResult(); return result; } @Override public void remove() { } /** * gets the next result * * @return next result or null */ private String getNextResult() { loop: while (tagPos < aLine.length()) { if (attemptWordsAfterSOH && aLine.charAt(tagPos) == 1) { tagPos++; break; } for (var tag : tags) { if (match(aLine, tagPos, tag)) { tagPos += tag.length(); break loop; } } tagPos++; } if (tagPos >= aLine.length()) return null; var b = tagPos + 1; while (b < aLine.length() && (Character.isLetterOrDigit(aLine.charAt(b)) || aLine.charAt(b) == '_')) { //while(b <aLine.length() && (Character.isLetterOrDigit(aLine.charAt(b)) || aLine.charAt(b) == '_')) { b++; } var result = aLine.substring(tagPos, b); tagPos = b; return result; } /** * does the query match the string starting at the offset * * @return true, if string starts with query at offset */ private static boolean match(final String string, final int offset, final String query) { if (string.length() - offset < query.length()) return false; for (var i = 0; i < query.length(); i++) { if (string.charAt(offset + i) != query.charAt(i)) return false; } return true; } /** * gets the first element or null * * @return first or null */ public String getFirst() { if (hasNext()) return next(); else return null; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public ArrayList<String> getAll() { var result = new ArrayList<String>(); while (iterator().hasNext()) result.add(iterator().next()); return result; } public void getAll(ArrayList<String> target) { target.clear(); while (iterator().hasNext()) target.add(iterator().next()); } public boolean isAttemptWordsAfterSOH() { return attemptWordsAfterSOH; } public void setAttemptWordsAfterSOH(boolean attemptWordsAfterSOH) { this.attemptWordsAfterSOH = attemptWordsAfterSOH; } public static void main(String[] args) throws IOException { var file = "/Users/huson/classify/ncbi/latest-ncbi/nr.gz"; var count = 0; try (var it = new FileLineIterator(file, true)) { while (it.hasNext()) { var line = it.next(); if (line.startsWith(">")) { var tit = new TaggedValueIterator(line, true, true); System.err.println(line); System.err.println("Accessions: " + StringUtils.toString(tit.getAll(), " ")); if (count++ == 10) break; } } } } }
7,573
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SamplesViewer.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/SamplesViewer.java
/* * SamplesViewer.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.samplesviewer; import javafx.application.Platform; import jloda.swing.director.IDirectableViewer; import jloda.swing.director.IViewerWithFindToolBar; import jloda.swing.director.ProjectManager; import jloda.swing.find.FindToolBar; import jloda.swing.find.SearchManager; import jloda.swing.util.ProgramProperties; import jloda.swing.util.StatusBar; import jloda.swing.util.ToolBar; import jloda.swing.window.MenuBar; import jloda.swing.window.MenuConfiguration; import megan.core.Director; import megan.core.Document; import megan.core.SampleAttributeTable; import megan.core.SelectionSet; import megan.dialogs.input.InputDialog; import megan.fx.CommandManagerFX; import megan.main.MeganProperties; import megan.samplesviewer.commands.PasteCommand; import megan.viewer.MainViewer; import javax.swing.*; import java.awt.*; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Viewer for working with metadata * Daniel Huson, 9.2012 */ public class SamplesViewer implements IDirectableViewer, IViewerWithFindToolBar { private boolean uptodate = true; private boolean locked = false; private final JFrame frame; private final JPanel mainPanel; private final StatusBar statusbar; private final Director dir; private final Document doc; private final SelectionSet.SelectionListener selectionListener; private boolean showFindToolBar = false; private boolean showReplaceToolBar = false; private final SearchManager searchManager; private final CommandManagerFX commandManager; private final MenuBar menuBar; private final Set<String> needToReselectSamples = new HashSet<>(); private final SamplesTableView sampleTableView; /** * constructor * */ public SamplesViewer(final Director dir) { this.dir = dir; this.doc = dir.getDocument(); frame = new JFrame("Sample viewer"); frame.getContentPane().setLayout(new BorderLayout()); frame.setLocationRelativeTo(dir.getMainViewer().getFrame()); final int[] geometry = ProgramProperties.get("SampleViewerGeometry", new int[]{100, 100, 800, 600}); frame.setSize(geometry[2], geometry[3]); statusbar = new StatusBar(); this.commandManager = new CommandManagerFX(dir, this, new String[]{"megan.commands", "megan.samplesviewer.commands"}, !ProgramProperties.isUseGUI()); String toolBarConfig = megan.samplesviewer.GUIConfiguration.getToolBarConfiguration(); JToolBar toolBar = new ToolBar(this, toolBarConfig, commandManager); frame.getContentPane().add(toolBar, BorderLayout.NORTH); mainPanel = new JPanel(); mainPanel.setLayout(new BorderLayout()); frame.getContentPane().add(mainPanel, BorderLayout.CENTER); sampleTableView = new SamplesTableView(this); mainPanel.add(sampleTableView.getPanel()); frame.getContentPane().add(statusbar, BorderLayout.SOUTH); MenuConfiguration menuConfig = GUIConfiguration.getMenuConfiguration(); TableViewSearcher tableViewSearcher = new TableViewSearcher(sampleTableView.getTableView()); searchManager = new SearchManager(dir, this, tableViewSearcher, false, true); this.menuBar = new MenuBar(this, menuConfig, getCommandManager()); frame.setJMenuBar(menuBar); MeganProperties.addPropertiesListListener(menuBar.getRecentFilesListener()); MeganProperties.notifyListChange(ProgramProperties.RECENTFILES); ProjectManager.addAnotherWindowWithWindowMenu(dir, menuBar.getWindowMenu()); frame.setIconImages(ProgramProperties.getProgramIconImages()); setWindowTitle(); // add window listeners frame.addComponentListener(new ComponentAdapter() { public void componentMoved(ComponentEvent e) { componentResized(e); } public void componentResized(ComponentEvent event) { if ((event.getID() == ComponentEvent.COMPONENT_RESIZED || event.getID() == ComponentEvent.COMPONENT_MOVED) && (getFrame().getExtendedState() & JFrame.MAXIMIZED_HORIZ) == 0 && (getFrame().getExtendedState() & JFrame.MAXIMIZED_VERT) == 0) { ProgramProperties.put("SampleViewerGeometry", new int[]{frame.getLocation().x, frame.getLocation().y, frame.getSize().width, frame.getSize().height}); } } }); getFrame().addWindowListener(new WindowAdapter() { public void windowActivated(WindowEvent event) { MainViewer.setLastActiveFrame(frame); commandManager.updateEnableState(PasteCommand.ALT_NAME); final InputDialog inputDialog = InputDialog.getInstance(); if (inputDialog != null) { inputDialog.setViewer(dir, SamplesViewer.this); } } public void windowDeactivated(WindowEvent event) { List<String> list = new ArrayList<>(); list.addAll(sampleTableView.getSelectedAttributes()); list.addAll(sampleTableView.getSelectedSamples()); if (list.size() != 0) { ProjectManager.getPreviouslySelectedNodeLabels().clear(); ProjectManager.getPreviouslySelectedNodeLabels().addAll(list); } } public void windowClosing(WindowEvent e) { if (dir.getDocument().getProgressListener() != null) dir.getDocument().getProgressListener().setUserCancelled(true); if (MainViewer.getLastActiveFrame() == frame) MainViewer.setLastActiveFrame(null); } }); selectionListener = (labels, selected) -> Platform.runLater(() -> sampleTableView.selectSamples(labels, selected)); doc.getSampleSelection().addSampleSelectionListener(selectionListener); frame.setVisible(true); } /** * is viewer uptodate? * * @return uptodate */ public boolean isUptoDate() { return uptodate; } /** * return the frame associated with the viewer * * @return frame */ public JFrame getFrame() { return frame; } /** * gets the title * * @return title */ public String getTitle() { return getFrame().getTitle(); } /** * gets the associated command manager * * @return command manager */ public CommandManagerFX getCommandManager() { return commandManager; } public Director getDir() { return dir; } /** * ask view to rescan itself * * @param what what should be updated? Possible values: Director.ALL or Director.TITLE */ public void updateView(final String what) { // if (!SwingUtilities.isEventDispatchThread() && !Platform.isFxApplicationThread()) // System.err.println("updateView(): not in Swing or FX thread!"); if (what.equals(Director.ALL)) { sampleTableView.syncFromDocumentToView(); } final FindToolBar findToolBar = searchManager.getFindDialogAsToolBar(); if (findToolBar.isClosing()) { showFindToolBar = false; showReplaceToolBar = false; findToolBar.setClosing(false); } if (!findToolBar.isEnabled() && showFindToolBar) { mainPanel.add(findToolBar, BorderLayout.NORTH); findToolBar.setEnabled(true); if (showReplaceToolBar) findToolBar.setShowReplaceBar(true); frame.getContentPane().validate(); } else if (findToolBar.isEnabled() && !showFindToolBar) { mainPanel.remove(findToolBar); findToolBar.setEnabled(false); frame.getContentPane().validate(); } if (findToolBar.isEnabled()) { findToolBar.clearMessage(); searchManager.updateView(Director.ENABLE_STATE); if (findToolBar.isShowReplaceBar() != showReplaceToolBar) findToolBar.setShowReplaceBar(showReplaceToolBar); } if (!doc.isDirty() && sampleTableView.isDirty()) doc.setDirty(true); getCommandManager().updateEnableStateSwingItems(); javafx.application.Platform.runLater(() -> getCommandManager().updateEnableStateFXItems()); setWindowTitle(); frame.setCursor(Cursor.getDefaultCursor()); updateStatusBar(); } /** * ask view to prevent user input */ public void lockUserInput() { locked = true; statusbar.setText1(""); statusbar.setText2("Busy..."); frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); getCommandManager().setEnableCritical(false); searchManager.getFindDialogAsToolBar().setEnableCritical(false); sampleTableView.lockUserInput(); menuBar.setEnableRecentFileMenuItems(false); } /** * ask view to allow user input */ public void unlockUserInput() { sampleTableView.unlockUserInput(); getCommandManager().setEnableCritical(true); frame.setCursor(Cursor.getDefaultCursor()); searchManager.getFindDialogAsToolBar().setEnableCritical(true); frame.setCursor(Cursor.getDefaultCursor()); updateStatusBar(); menuBar.setEnableRecentFileMenuItems(true); locked = false; } /** * rescan the status bar */ private void updateStatusBar() { SampleAttributeTable sampleAttributeTable = doc.getSampleAttributeTable(); String message = "Samples=" + sampleAttributeTable.getNumberOfSamples(); message += " Attributes=" + sampleAttributeTable.getNumberOfUnhiddenAttributes(); if (getSamplesTableView().getCountSelectedSamples() > 0 || getSamplesTableView().getCountSelectedAttributes() > 0) { message += " (Selection: " + getSamplesTableView().getCountSelectedSamples() + " samples, " + getSamplesTableView().getCountSelectedAttributes() + " attributes)"; } statusbar.setText2(message); } /** * is viewer currently locked? * * @return true, if locked */ public boolean isLocked() { return locked; } /** * ask view to destroy itself */ public void destroyView() { locked = true; ProgramProperties.put("SampleViewerGeometry", new int[]{frame.getLocation().x, frame.getLocation().y, frame.getSize().width, frame.getSize().height}); frame.setVisible(false); searchManager.getFindDialogAsToolBar().close(); doc.getSampleSelection().removeSampleSelectionListener(selectionListener); MeganProperties.removePropertiesListListener(menuBar.getRecentFilesListener()); frame.setVisible(false); dir.removeViewer(this); //frame.dispose(); } /** * set uptodate state * */ public void setUptoDate(boolean flag) { uptodate = flag; } public boolean isShowFindToolBar() { return showFindToolBar; } public void setShowFindToolBar(boolean show) { showFindToolBar = show; } public boolean isShowReplaceToolBar() { return showReplaceToolBar; } public void setShowReplaceToolBar(boolean showReplaceToolBar) { this.showReplaceToolBar = showReplaceToolBar; if (showReplaceToolBar) showFindToolBar = true; } public SearchManager getSearchManager() { return searchManager; } /** * get name for this type of viewer * * @return name */ public String getClassName() { return "SamplesViewer"; } /** * sets the title of the window */ public void setWindowTitle() { String newTitle = "SamplesViewer - " + dir.getDocument().getTitle(); if (doc.getMeganFile().isMeganServerFile()) newTitle += " (remote file)"; if (doc.getMeganFile().isReadOnly()) newTitle += " (read-only)"; else if (doc.isDirty()) newTitle += "*"; if (dir.getID() == 1) newTitle += " - " + ProgramProperties.getProgramVersion(); else newTitle += " - [" + dir.getID() + "] - " + ProgramProperties.getProgramVersion(); if (!getTitle().equals(newTitle)) { frame.setTitle(newTitle); ProjectManager.updateWindowMenus(); } } public SampleAttributeTable getSampleAttributeTable() { return dir.getDocument().getSampleAttributeTable(); } public Document getDocument() { return dir.getDocument(); } public Set<String> getNeedToReselectSamples() { return needToReselectSamples; } public SamplesTableView getSamplesTableView() { return sampleTableView; } /** * execute a command * */ public void execute(String command) { dir.execute(command, getCommandManager()); } /** * execute a command * */ public void executeImmediately(String command) { dir.executeImmediately(command, getCommandManager()); } }
14,316
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
TableViewSearcher.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/TableViewSearcher.java
/* * TableViewSearcher.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.samplesviewer; import javafx.application.Platform; import javafx.scene.control.TableColumn; import javafx.scene.control.TablePosition; import jloda.fx.control.table.MyTableView; import jloda.swing.find.IObjectSearcher; import jloda.util.Basic; import jloda.util.Pair; import javax.swing.*; import java.awt.*; import java.util.Collection; import java.util.HashSet; import java.util.Set; /** * Class for finding labels in a SpreadsheetView * Daniel Huson, 9.2015 */ public class TableViewSearcher implements IObjectSearcher { private final String name; private final MyTableView table; private final Frame frame; private final Pair<Integer, Integer> current = new Pair<>(-1, -1); // row, col private final Set<Pair<Integer, Integer>> toSelect; private final Set<Pair<Integer, Integer>> toDeselect; private static final String SEARCHER_NAME = "TableSearcher"; private final Set<Pair<Integer, Integer>> selected; /** * constructor * */ public TableViewSearcher(MyTableView table) { this(null, SEARCHER_NAME, table); } /** * constructor * */ public TableViewSearcher(Frame frame, MyTableView table) { this(frame, SEARCHER_NAME, table); } /** * constructor * * @param */ public TableViewSearcher(Frame frame, String name, MyTableView table) { this.frame = frame; this.name = name; this.table = table; toSelect = new HashSet<>(); toDeselect = new HashSet<>(); selected = new HashSet<>(); } /** * get the parent component * * @return parent */ public Component getParent() { return frame; } /** * get the name for this type of search * * @return name */ public String getName() { return name; } /** * goto the first object */ public boolean gotoFirst() { current.setFirst(0); current.setSecond(0); return isCurrentSet(); } /** * goto the next object */ public boolean gotoNext() { if (isCurrentSet()) { current.setFirst(current.getFirst() + 1); if (current.getFirst() >= table.getRowCount()) { current.setFirst(0); current.setSecond(current.getSecond() + 1); } } else gotoFirst(); return isCurrentSet(); } /** * goto the last object */ public boolean gotoLast() { current.setFirst(table.getRowCount() - 1); current.setSecond(table.getColCount() - 1); return isCurrentSet(); } /** * goto the previous object */ public boolean gotoPrevious() { if (isCurrentSet()) { if (current.getSecond() > 0) current.setSecond(current.getSecond() - 1); else if (current.getFirst() > 0) { current.setFirst(current.getFirst() - 1); current.setSecond(table.getColCount() - 1); } else { current.setFirst(-1); current.setSecond(-1); } } else gotoLast(); return isCurrentSet(); } /** * is the current object selected? * * @return true, if selected */ public boolean isCurrentSelected() { return isCurrentSet() && selected.contains(current); } /** * set selection state of current object * */ public void setCurrentSelected(boolean select) { if (select) toSelect.add(new Pair<>(current.getFirst(), current.getSecond())); else toDeselect.add(new Pair<>(current.getFirst(), current.getSecond())); } /** * set select state of all objects * */ public void selectAll(boolean select) { if (select) { table.getSelectionModel().selectAll(); } else { table.getSelectionModel().clearSelection(); } } /** * get the label of the current object * * @return label */ public String getCurrentLabel() { try { if (isCurrentSet()) return table.getValue(current.getFirst(), current.getSecond()); } catch (Exception ex) { Basic.caught(ex); } return null; } /** * set the label of the current object * */ public void setCurrentLabel(final String newLabel) { final Pair<Integer, Integer> cell = new Pair<>(current.getFirst(), current.getSecond()); final Runnable runnable = () -> table.setValue(cell.getFirst(), cell.getSecond(), newLabel); if (Platform.isFxApplicationThread()) runnable.run(); else Platform.runLater(runnable); } /** * is a global find possible? * * @return true, if there is at least one object */ public boolean isGlobalFindable() { return table.getRowCount() > 0; } /** * is a selection find possible * * @return true, if at least one object is selected */ public boolean isSelectionFindable() { return selected.size() > 0; //table.getSelectionModel().getSelectedCells().size()>0; } /** * is the current object set? * * @return true, if set */ public boolean isCurrentSet() { return current.getFirst() >= 0 && current.getFirst() < table.getRowCount() && current.getSecond() >= 0 && current.getSecond() < table.getColCount(); } /** * something has been changed or selected, update view */ public void updateView() { Platform.runLater(() -> { Pair<Integer, Integer> first = null; final Set<Pair<Integer, Integer>> selection = new HashSet<>(); for (Object obj : table.getSelectionModel().getSelectedCells()) { TablePosition pos = (TablePosition) obj; selection.add(new Pair<>(pos.getRow(), pos.getColumn())); } for (Pair<Integer, Integer> pair : toDeselect) { selection.remove(pair); } for (Pair<Integer, Integer> pair : toSelect) { selection.add(pair); if (first == null) first = pair; } table.getSelectionModel().clearSelection(); for (Pair<Integer, Integer> pair : selection) { final TableColumn<MyTableView.MyTableRow, ?> column = table.getCol(pair.getSecond()); table.getSelectionModel().select(pair.getFirst(), column); } if (first != null) { table.scrollToRow(first.getFirst()); } toSelect.clear(); toDeselect.clear(); }); } /** * does this searcher support find all? * * @return true, if find all supported */ public boolean canFindAll() { return true; } /** * how many objects are there? * * @return number of objects or -1 */ public int numberOfObjects() { return table.getRowCount() * table.getColCount(); } @Override public Collection<AbstractButton> getAdditionalButtons() { return null; } public Set<Pair<Integer, Integer>> getSelected() { return selected; } }
8,224
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
GUIConfiguration.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/GUIConfiguration.java
/* * GUIConfiguration.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.samplesviewer; import jloda.swing.window.MenuConfiguration; import megan.classification.data.ClassificationCommandHelper; /** * configuration for menu and toolbar * Daniel Huson, 7.2010 */ class GUIConfiguration { /** * get the menu configuration * * @return menu configuration */ public static MenuConfiguration getMenuConfiguration() { MenuConfiguration menuConfig = new MenuConfiguration(); menuConfig.defineMenuBar("File;Edit;Attributes;Samples;Layout;Window;Help;"); menuConfig.defineMenu("File", "New...;|;Open...;@Open Recent;|;Open From Server...;|;Compare...;|;Import From BLAST...;@Import;Meganize DAA File...;|;Save As...;|;" + "Export Image...;Export Legend...;@Export;|;Page Setup...;Print...;|;Properties...;|;Close;|;Quit;"); menuConfig.defineMenu("Open Recent", ";"); menuConfig.defineMenu("Export", "Text (CSV) Format...;BIOM1 Format...;STAMP Format...;|;Metadata...;|;Reads...;Matches...;Alignments...;|;All Individual Samples...;MEGAN Summary File...;"); menuConfig.defineMenu("Import", "Import Text (CSV) Format...;Import BIOM Format...;|;Import Metadata...;"); menuConfig.defineMenu("Edit", "Samples Viewer Cut;Samples Viewer Copy;Samples Viewer Paste;Samples Viewer Paste By Attribute;|;" + "Select All;Select None;Select Similar;From Previous Window;|;Select Comment-Like;Select Numerical;Select Uninformative;|;" + "Find...;Find Again;Replace...;|;Colors...;"); menuConfig.defineMenu("Attributes", "List Attribute Summary...;|;New Column...;Delete Column(s)...;|;Use to Color Samples;Use to Shape Samples;Use to Label Samples;Use to Group Samples;|;" + "Expand...;"); menuConfig.defineMenu("Samples", "Rename Sample...;|;Move Up;Move Down;|;Extract Samples...;|;Compute Total Biome...;Compute Core Biome...;Compute Rare Biome...;|;Remove Low Abundances...;|;Compare Relative...;Compare Absolute...;Split By Attribute...;|;Label by Samples;|;Open RMA File...;"); menuConfig.defineMenu("Layout", "Squeeze Wide Columns;"); menuConfig.defineMenu("Window", "Close All Other Windows...;|;Reset Window Location;Set Window Size...;|;Message Window...;|;" + "Inspector Window...;|;Main Viewer...;" + ClassificationCommandHelper.getOpenViewerMenuString() + "|;Samples Viewer...;Groups Viewer...;|;"); menuConfig.defineMenu("Help", "About...;How to Cite...;|;Community Website...;Reference Manual...;|;Check For Updates...;"); return menuConfig; } /** * gets the toolbar configuration * * @return toolbar configuration */ public static String getToolBarConfiguration() { return "Open...;|;Find...;|;Colors...;|;Group Nodes;Ungroup All;|;Main Viewer...;" + ClassificationCommandHelper.getOpenViewerMenuString(); } /** * gets the column header configuration * * @return configuration */ public static String getAttributeColumnHeaderPopupConfiguration() { //return "Rename Attribute...;|;Sort Increasing;Sort Decreasing;|;Move Left;Move Right;|;New Column...;Delete Column(s)...;|;Hide;Unhide;|;Use to Color Samples;Use to Shape Samples;Use to Label Samples;Use to Group Samples;|;Expand...;|;Compare Relative...;Compare Absolute...;"; return "Use to Color Samples;Use to Shape Samples;Use to Label Samples;Use to Group Samples;|;Expand...;|;Compare Relative...;Compare Absolute...;"; } public static String getSampleRowHeaderPopupConfiguration() { return "Move Up;Move Down;|;Rename Sample...;|;Open RMA File...;|;Set Shape...;Set Color...;"; // we add the color menu item after these } /** * gets main popup configuration * * @return configuration */ public static String getMainPopupConfiguration() { return "|;Select All;Select None;Select Similar;From Previous Window;"; } }
4,810
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SamplesTableView.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/SamplesTableView.java
/* * SamplesTableView.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.samplesviewer; import javafx.application.Platform; import javafx.beans.InvalidationListener; import javafx.embed.swing.JFXPanel; import javafx.geometry.Insets; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.TableColumn; import javafx.scene.control.TablePosition; import javafx.scene.input.Clipboard; import javafx.scene.layout.BorderPane; import jloda.fx.control.table.MyTableView; import jloda.swing.director.IDirector; import jloda.util.Basic; import jloda.util.Pair; import jloda.util.StringUtils; import jloda.util.Triplet; import jloda.util.progress.ProgressSilent; import megan.core.Director; import megan.core.Document; import megan.core.SampleAttributeTable; import megan.fx.PopupMenuFX; import megan.util.GraphicsUtilities; import javax.swing.*; import java.io.IOException; import java.io.StringWriter; import java.util.*; public class SamplesTableView { private static final Set<String> seenFXExceptions = new HashSet<>(); private static final Thread.UncaughtExceptionHandler fxExceptionHandler = (t, e) -> { if (!seenFXExceptions.contains(e.getMessage())) { seenFXExceptions.add(e.getMessage()); System.err.println("FX Exception: " + e.getMessage()); } }; private final SamplesViewer samplesViewer; private final JFXPanel jFXPanel = new JFXPanel(); private MyTableView tableView; private int selectedSamplesCount = 0; private int selectedAttributesCount = 0; private boolean initialized = false; private long initialUpdate = Long.MAX_VALUE; private final Object lock = new Object(); /** * constructor */ public SamplesTableView(SamplesViewer samplesViewer) { this.samplesViewer = samplesViewer; Platform.runLater(() -> initFxLater(jFXPanel)); } /** * get the panel * * @return panel */ public JFXPanel getPanel() { for (int count = 0; count < 100; count++) { if (initialized) break; try { Thread.sleep(10); } catch (InterruptedException e) { Basic.caught(e); } } return jFXPanel; } public List<String> getSelectedSamples() { if (tableView != null) return new ArrayList<>(tableView.getSelectedRows()); else return new ArrayList<>(); } public List<String> getSelectedAttributes() { if (tableView != null) return new ArrayList<>(tableView.getSelectedCols()); else return new ArrayList<>(); } public void lockUserInput() { if (tableView != null) { ensureFXThread(() -> tableView.setEditable(false)); } } public void unlockUserInput() { if (tableView != null) ensureFXThread(() -> tableView.setEditable(true)); } /** * create the main node * * @return panel */ private Node createMainNode() { tableView = new MyTableView(); tableView.setAllowRenameCol(true); //tableView.setAllowReorderRow(true); // todo: throws expections tableView.getUnrenameableCols().add(SampleAttributeTable.SAMPLE_ID); tableView.setAllowDeleteCol(true); tableView.getUndeleteableCols().add(SampleAttributeTable.SAMPLE_ID); tableView.updateProperty().addListener((c, o, n) -> { if (n.longValue() > initialUpdate) { SwingUtilities.invokeLater(() -> { syncFromViewToDocument(); if (!samplesViewer.getDocument().isDirty()) { samplesViewer.getDocument().setDirty(true); //samplesViewer.getDir().notifyUpdateViewer(IDirector.TITLE); } samplesViewer.getDir().notifyUpdateViewer(IDirector.ALL); }); } }); tableView.setAllowAddCol(true); tableView.setAdditionColHeaderMenuItems((col) -> { //tableView.getSelectionModel().clearSelection(); //tableView.selectColumn(col,true); return (new PopupMenuFX(GUIConfiguration.getAttributeColumnHeaderPopupConfiguration(), samplesViewer.getCommandManager())).getItems(); }); tableView.setAdditionRowHeaderMenuItems((rows) -> { tableView.selectRows(rows, true); return (new PopupMenuFX(GUIConfiguration.getSampleRowHeaderPopupConfiguration(), samplesViewer.getCommandManager())).getItems(); }); tableView.getSelectionModel().getSelectedCells().addListener((InvalidationListener) (e) -> { updateNumberOfSelectedRowsAndCols(); SwingUtilities.invokeLater(() -> samplesViewer.updateView(Director.ENABLE_STATE)); }); tableView.getSelectedRows().addListener((InvalidationListener) (e) -> { updateNumberOfSelectedRowsAndCols(); SwingUtilities.invokeLater(() -> samplesViewer.updateView(Director.ENABLE_STATE)); }); initialUpdate = Long.MAX_VALUE; return tableView; } /** * initialize JavaFX * */ private void initFxLater(JFXPanel jfxPanel) { if (!initialized) { if (Thread.getDefaultUncaughtExceptionHandler() != fxExceptionHandler) Thread.setDefaultUncaughtExceptionHandler(fxExceptionHandler); synchronized (lock) { if (!initialized) { try { final BorderPane rootNode = new BorderPane(); jfxPanel.setScene(new Scene(rootNode, 600, 600)); final Node main = createMainNode(); rootNode.setCenter(main); BorderPane.setMargin(main, new Insets(3, 3, 3, 3)); // String css = NotificationsInSwing.getControlStylesheetURL(); // if (css != null) // jfxPanel.getScene().getStylesheets().add(css); } finally { initialized = true; } } } } } public MyTableView getTableView() { return tableView; } public void copyToClipboard() { if (tableView != null) ensureFXThread(() -> tableView.copyToClipboard()); } /** * paste into table */ public void pasteClipboard() { final Clipboard clipboard = Clipboard.getSystemClipboard(); final String contents = clipboard.getString().trim().replaceAll("\r\n", "\n").replaceAll("\r", "\n"); final String[] lines = contents.split("\n"); paste(lines); } /** * pastes lines into table * */ private void paste(String[] lines) { if (tableView != null) { ensureFXThread(() -> { if (lines.length > 0 && tableView.getSelectedCells().size() > 0) { final Set<Pair<Integer, Integer>> selectedPairs = new HashSet<>(); final BitSet rows = new BitSet(); final BitSet cols = new BitSet(); for (var position : tableView.getSelectedCells()) { final int row = position.getRow(); final int col = position.getColumn(); selectedPairs.add(new Pair<>(row, col)); rows.set(row); cols.set(col); } int row = rows.nextSetBit(0); for (String line : lines) { int col = cols.nextSetBit(1); String[] values = line.trim().split("\t"); for (String value : values) { value = value.trim(); // move to next col that is selected in this row: while (col != -1 && !selectedPairs.contains(new Pair<>(row, col))) col = cols.nextSetBit(col + 1); if (col != -1) { tableView.setValue(row, col, value); col = cols.nextSetBit(col + 1); } else break; } row = rows.nextSetBit(row + 1); if (row == -1) break; } } }); } } /** * pastes lines into table guided by an attribute * */ public void pasteClipboardByAttribute(String attribute) { if (tableView != null && tableView.getSelectedCells().size() > 0) { ensureFXThread(() -> { final Clipboard clipboard = Clipboard.getSystemClipboard(); final BitSet rows = new BitSet(); for (TablePosition position : tableView.getSelectedCells()) { rows.set(position.getRow()); } String contents = clipboard.getString().trim().replaceAll("\r\n", "\n").replaceAll("\r", "\n"); String[] lines = contents.split("\n"); if (lines.length > 0) { final int guideCol = tableView.getColIndex(attribute); final Map<String, String> attributeValue2Line = new HashMap<>(); int inputLineNumber = 0; String[] toPaste = new String[tableView.getSelectedRows().size()]; int expandedLineNumber = 0; for (int row = rows.nextSetBit(1); row != -1; row = rows.nextSetBit(row + 1)) { String value = tableView.getValue(row, guideCol); if (!attributeValue2Line.containsKey(value)) { if (inputLineNumber == lines.length) break; toPaste[expandedLineNumber++] = lines[inputLineNumber]; attributeValue2Line.put(value, lines[inputLineNumber++]); } else { if (expandedLineNumber == toPaste.length) break; toPaste[expandedLineNumber++] = attributeValue2Line.get(value); } } if (attributeValue2Line.size() != lines.length) { System.err.println("Mismatch between number of lines pasted (" + lines.length + ") and number of attribute values (" + attributeValue2Line.size() + ")"); return; } paste(toPaste); } }); } } /** * add a new column * */ public void addNewColumn(final int index, String name) { ensureFXThread(() -> tableView.addCol(index, name)); } /** * delete columns */ public void deleteColumns(final String... attributes) { if (tableView != null) ensureFXThread(() -> { for (String col : attributes) { tableView.deleteCol(col); } }); } /** * select cells for an attribute and value * */ public void selectCellsByValue(final String attribute, final String value) { if (tableView != null) ensureFXThread(() -> tableView.selectByValue(attribute, value)); } private void updateNumberOfSelectedRowsAndCols() { selectedSamplesCount = getSelectedSamples().size(); selectedAttributesCount = getSelectedAttributes().size(); } public int getCountSelectedSamples() { return selectedSamplesCount; } public int getCountSelectedAttributes() { return selectedAttributesCount; } public void syncFromViewToDocument() { // System.err.println("Syncing to document (update: "+tableView.getUpdate()+")"); final SampleAttributeTable sampleAttributeTable = samplesViewer.getSampleAttributeTable(); if (sampleAttributeTable.getSampleOrder().size() != tableView.getRowNames().size()) throw new RuntimeException("Table size mismatch"); sampleAttributeTable.getSampleOrder().clear(); sampleAttributeTable.getSampleOrder().addAll(tableView.getRowNames()); try { samplesViewer.getDocument().reorderSamples(sampleAttributeTable.getSampleOrder()); } catch (IOException e) { Basic.caught(e); } final ArrayList<String> toDelete = new ArrayList<>(); for (String attribute : sampleAttributeTable.getAttributeOrder()) { if (!sampleAttributeTable.isSecretAttribute(attribute)) toDelete.add(attribute); } for (String attribute : toDelete) sampleAttributeTable.removeAttribute(attribute); final List<String> secretAttributes = new ArrayList<>(sampleAttributeTable.getAttributeOrder()); sampleAttributeTable.getAttributeOrder().removeAll(secretAttributes); // will put these back at the end of the list for (String attribute : tableView.getColNames()) { final Map<String, Object> sampleValueMap = new HashMap<>(); for (String sample : tableView.getRowNames()) sampleValueMap.put(sample, tableView.getValue(sample, attribute)); sampleAttributeTable.addAttribute(attribute, sampleValueMap, false, false); } sampleAttributeTable.getAttributeOrder().addAll(secretAttributes); final StringWriter w = new StringWriter(); try { sampleAttributeTable.write(w, false, true); } catch (IOException e) { Basic.caught(e); } initialUpdate = tableView.getUpdate(); //System.err.println("Doc: "+w.toString()); if (false) SwingUtilities.invokeLater(() -> samplesViewer.getDocument().getDir().notifyUpdateViewer(IDirector.ALL)); } public void syncFromDocumentToView() { if (tableView != null) { ensureFXThread(() -> { initialUpdate = Long.MAX_VALUE; //System.err.println("Syncing to view"); final SampleAttributeTable sampleAttributeTable = samplesViewer.getSampleAttributeTable(); final ArrayList<String> samples = sampleAttributeTable.getSampleOrder(); final ArrayList<String> userAttributes = sampleAttributeTable.getUnhiddenAttributes(); tableView.pausePostingUpdates(); try { tableView.createRowsAndCols(samples, userAttributes); for (int row = 0; row < samples.size(); row++) { final String sample = samples.get(row); for (int col = 0; col < userAttributes.size(); col++) { final String attribute = userAttributes.get(col); final Object value = sampleAttributeTable.get(sample, attribute); tableView.setValue(row, col, value != null ? value.toString() : "?"); } tableView.setRowGraphic(sample, GraphicsUtilities.makeSampleIconFX(samplesViewer.getDocument(), sample, true, true, 16)); } } finally { initialUpdate = tableView.getUpdate() + 1; tableView.resumePostingUpdates(); } }); } } public String getASelectedAttribute() { if (getCountSelectedAttributes() > 0) return getSelectedAttributes().get(0); else return null; } public String getASelectedSample() { if (getCountSelectedSamples() > 0) return getSelectedSamples().get(0); else return null; } public void renameRow(String sampleName, String newName) { if (tableView != null) { Platform.runLater(() -> tableView.renameRow(sampleName, newName)); } } public void clear() { if (tableView != null) { ensureFXThread(() -> tableView.clear()); } } public int getAttributeCount() { if (tableView != null) return tableView.getColCount(); else return 0; } public TableColumn<MyTableView.MyTableRow, ?> getAttribute(int index) { if (tableView != null) return tableView.getCol(index); else return null; } public ArrayList<String> getAttributes() { if (tableView != null) return tableView.getColNames(); else return new ArrayList<>(); } public ArrayList<String> getSamples() { if (tableView != null) return tableView.getRowNames(); else return new ArrayList<>(); } public int getSampleCount() { if (tableView != null) return tableView.getRowCount(); else return 0; } public void selectAll(boolean select) { if (tableView != null) { ensureFXThread(() -> { if (select) tableView.getSelectionModel().selectAll(); else tableView.getSelectionModel().clearSelection(); }); } } public void selectSample(String sample, boolean select) { if (tableView != null) { ensureFXThread(() -> tableView.selectRow(sample, select)); } } public void selectSamples(Collection<String> samples, boolean select) { if (tableView != null) { ensureFXThread(() -> tableView.selectRowHeaders(samples, select)); } } public void selectByValue(String attribute, Object value) { if (tableView != null) { ensureFXThread(() -> tableView.selectByValue(attribute, value.toString())); } } public void selectAttribute(String attribute, boolean select) { if (tableView != null) { ensureFXThread(() -> tableView.selectCol(attribute, select)); } } public void scrollToSample(String sample) { if (tableView != null) { ensureFXThread(() -> { if (sample == null) tableView.scrollToRow(0); else tableView.scrollToRow(sample); }); } } public boolean isDirty() { if (tableView != null) return tableView.getUpdate() > initialUpdate; else return false; } public Triplet<String, String, String> getSingleSelectedCell() { if (tableView != null) return tableView.getSingleSelectedCell(); else return null; } public int getUpdate() { if (tableView != null) return tableView.getRowCount(); else return 0; } private static void ensureFXThread(Runnable runnable) { if (Platform.isFxApplicationThread()) runnable.run(); else Platform.runLater(runnable); } public void moveSamples(boolean up, Collection<String> samples) { Platform.runLater(() -> { final Document doc = samplesViewer.getDocument(); SwingUtilities.invokeLater(() -> { try { doc.getSampleAttributeTable().moveSamples(up, samples); doc.setProgressListener(new ProgressSilent()); doc.reorderSamples(doc.getSampleAttributeTable().getSampleOrder()); samplesViewer.getDir().executeImmediately("update reinduce=true;" + "select samples name='" + StringUtils.toString(samples, "' '") + "';", samplesViewer.getCommandManager()); selectSamples(samples, true); doc.getDir().notifyUpdateViewer(IDirector.ALL); } catch (Exception e) { Basic.caught(e); } }); }); } public ArrayList<Integer> getSelectedSamplesIndices() { if (tableView != null) return tableView.getSelectedRowIndices(); else return new ArrayList<>(); } }
21,270
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ApplyOrderToViewersCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/ApplyOrderToViewersCommand.java
/* * ApplyOrderToViewersCommand.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.samplesviewer.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.util.parse.NexusStreamParser; import megan.core.Document; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.LinkedList; /** * * reorder samples in viewer * * Daniel Huson, 9.2012 */ public class ApplyOrderToViewersCommand extends CommandBase implements ICommand { public String getSyntax() { return "reorder samples[=<name>...];"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("reorder samples"); LinkedList<String> newOrder = new LinkedList<>(); if (np.peekMatchIgnoreCase("=")) { np.matchIgnoreCase("="); while (!np.peekMatchIgnoreCase(";")) { newOrder.add(np.getWordRespectCase()); } } else { final SamplesViewer viewer = (SamplesViewer) getViewer(); newOrder.addAll(viewer.getSamplesTableView().getSamples()); } np.matchIgnoreCase(";"); final SamplesViewer viewer = (SamplesViewer) getViewer(); Document doc = viewer.getDocument(); doc.reorderSamples(newOrder); } public void actionPerformed(ActionEvent event) { } public boolean isApplicable() { final SamplesViewer viewer = (SamplesViewer) getViewer(); return viewer != null && viewer.getDocument().getNumberOfSamples() > 0 && !viewer.getSampleAttributeTable().getSampleOrder().equals(viewer.getDocument().getSampleNames()); } public String getName() { return null; } public String getDescription() { return "Reorder samples in all viewers as specified"; } public ImageIcon getIcon() { return null; } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
2,825
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
CompareByAttributeRelativeCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/CompareByAttributeRelativeCommand.java
/* * CompareByAttributeRelativeCommand.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.samplesviewer.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.dialogs.compare.Comparer; import megan.samplesviewer.SamplesTableView; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.event.ActionEvent; /** * * compare by command * * Daniel Huson, 9.2015 */ public class CompareByAttributeRelativeCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } /** * parses the given command and executes it */ public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { final SamplesViewer viewer = ((SamplesViewer) getViewer()); final String attribute = viewer.getSamplesTableView().getASelectedAttribute(); final SamplesTableView samplesTable = ((SamplesViewer) getViewer()).getSamplesTableView(); if (attribute != null && samplesTable.getCountSelectedSamples() > 0) { execute("compareBy attribute='" + attribute + "' mode=" + Comparer.COMPARISON_MODE.RELATIVE.toString().toLowerCase() + " samples='" + StringUtils.toString(samplesTable.getSelectedSamples(), "' '") + "';"); } } public boolean isApplicable() { return getViewer() instanceof SamplesViewer && ((SamplesViewer) getViewer()).getSamplesTableView().getCountSelectedAttributes() == 1; } public String getName() { return "Compare Relative..."; } 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; } }
2,815
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
PasteByAttributeCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/PasteByAttributeCommand.java
/* * PasteByAttributeCommand.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.samplesviewer.commands; import javafx.application.Platform; import javafx.scene.control.ChoiceDialog; import jloda.swing.commands.ICommand; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.commands.clipboard.ClipboardBase; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.Optional; public class PasteByAttributeCommand extends ClipboardBase implements ICommand { public String getSyntax() { return null; } public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { Platform.runLater(() -> { SamplesViewer samplesViewer = (SamplesViewer) getViewer(); final java.util.List<String> list = getDoc().getSampleAttributeTable().getUnhiddenAttributes(); if (list.size() > 0) { String choice = ProgramProperties.get("PasteByAttribute", list.get(0)); if (!list.contains(choice)) choice = list.get(0); final ChoiceDialog<String> dialog = new ChoiceDialog<>(choice, list); dialog.setTitle("Paste By Attribute"); dialog.setHeaderText("Select an attribute to guide paste"); Optional<String> result = dialog.showAndWait(); if (result.isPresent()) { final String selected = result.get(); ProgramProperties.put("PasteByAttribute", selected); samplesViewer.getSamplesTableView().pasteClipboardByAttribute(selected); samplesViewer.getSamplesTableView().syncFromViewToDocument(); samplesViewer.getCommandManager().updateEnableStateFXItems(); if (!samplesViewer.getDocument().isDirty() && samplesViewer.getSamplesTableView().isDirty()) { samplesViewer.getDocument().setDirty(true); samplesViewer.setWindowTitle(); } } } }); } public boolean isApplicable() { return getViewer() instanceof SamplesViewer && ((SamplesViewer) getViewer()).getSamplesTableView().getCountSelectedAttributes() > 0; } private static final String ALT_NAME = "Samples Viewer Paste By Attribute"; public String getAltName() { return ALT_NAME; } public String getName() { return "Paste By Attribute..."; } public String getDescription() { return "Paste values guided by values of a selected attribute." + "E.g. if you have multiple samples per Subject and you want to add an Age to each sample given by one value per Subject, then paste by 'Subject'"; } 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() | java.awt.event.InputEvent.SHIFT_DOWN_MASK); } }
4,076
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SelectUniformativeCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/SelectUniformativeCommand.java
/* * SelectUniformativeCommand.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.samplesviewer.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.util.parse.NexusStreamParser; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.event.ActionEvent; /** * * select numerical attributes * * Daniel Huson, 4.2017 */ public class SelectUniformativeCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } public void actionPerformed(ActionEvent event) { executeImmediately("select uninformative;"); } public boolean isApplicable() { return getViewer() instanceof SamplesViewer; } public String getName() { return "Select Uninformative"; } public String getDescription() { return "Select all uninformative attributes that have only 1 state or 1 state for each sample"; } public ImageIcon getIcon() { return null; } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } /** * parses the given command and executes it */ public void apply(NexusStreamParser np) { } }
2,036
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ShowReplaceCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/ShowReplaceCommand.java
/* * ShowReplaceCommand.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.samplesviewer.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICheckBoxCommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; /** * Open the replace dialog * Daniel Huson, 9 2016 */ public class ShowReplaceCommand extends CommandBase implements ICheckBoxCommand { public boolean isSelected() { return getViewer() instanceof SamplesViewer && ((SamplesViewer) getViewer()).isShowReplaceToolBar(); } /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Replace..."; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Open the replace toolbar"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Replace16.gif"); } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_R, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()); } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("show replaceToolbar="); boolean show = np.getBoolean(); np.matchIgnoreCase(";"); final SamplesViewer samplesViewer = (SamplesViewer) getViewer(); samplesViewer.setShowReplaceToolBar(show); } /** * 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; } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "show replaceToolbar={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 SamplesViewer; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { execute("show replaceToolbar=" + !isSelected() + ";"); } }
3,496
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ExtractSamplesCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/ExtractSamplesCommand.java
/* * ExtractSamplesCommand.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.samplesviewer.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.List; /** * * duplicate command * * Daniel Huson, 9.2012 */ public class ExtractSamplesCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } /** * parses the given command and executes it */ public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { SamplesViewer viewer = (SamplesViewer) getViewer(); List<String> samples = viewer.getSamplesTableView().getSelectedSamples(); if (samples.size() > 0) { execute("extract samples='" + StringUtils.toString(samples, "' '") + "';"); } } public boolean isApplicable() { return getViewer() instanceof SamplesViewer && ((SamplesViewer) getViewer()).getSamplesTableView().getCountSelectedSamples() > 0; } public String getName() { return "Extract Samples..."; } public String getDescription() { return "Extract selected samples to a new document"; } public ImageIcon getIcon() { return null; } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
2,325
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/samplesviewer/commands/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.samplesviewer.commands; import javafx.application.Platform; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.commands.clipboard.ClipboardBase; import megan.samplesviewer.SamplesViewer; import javax.swing.*; 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) { Platform.runLater(() -> { SamplesViewer samplesViewer = (SamplesViewer) getViewer(); samplesViewer.getSamplesTableView().pasteClipboard(); samplesViewer.getSamplesTableView().syncFromViewToDocument(); samplesViewer.getCommandManager().updateEnableStateFXItems(); if (!samplesViewer.getDocument().isDirty() && samplesViewer.getSamplesTableView().getUpdate() > 0) { samplesViewer.getDocument().setDirty(true); samplesViewer.setWindowTitle(); } }); } public boolean isApplicable() { return getViewer() instanceof SamplesViewer && ((SamplesViewer) getViewer()).getSamplesTableView().getCountSelectedAttributes() > 0; } public static final String ALT_NAME = "Samples Viewer Paste"; public String getAltName() { return ALT_NAME; } 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,782
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SelectCommentLikeCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/SelectCommentLikeCommand.java
/* * SelectCommentLikeCommand.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.samplesviewer.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.util.parse.NexusStreamParser; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.event.ActionEvent; /** * * select comment like attributes * * Daniel Huson, 4.2017 */ public class SelectCommentLikeCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } public void actionPerformed(ActionEvent event) { executeImmediately("select commentLike;"); } public boolean isApplicable() { return getViewer() instanceof SamplesViewer; } public String getName() { return "Select Comment-Like"; } public String getDescription() { return "Select all attributes that look like comments"; } public ImageIcon getIcon() { return null; } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } /** * parses the given command and executes it */ public void apply(NexusStreamParser np) { } }
1,994
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SelectSimilarCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/SelectSimilarCommand.java
/* * SelectSimilarCommand.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.samplesviewer.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.util.Triplet; import jloda.util.parse.NexusStreamParser; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.event.ActionEvent; /** * * selection command * * Daniel Huson, 11.2010 */ public class SelectSimilarCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { final SamplesViewer viewer = (SamplesViewer) getViewer(); final Triplet<String, String, String> selectedCell = viewer.getSamplesTableView().getSingleSelectedCell(); if (selectedCell != null) { executeImmediately("select similar name='" + selectedCell.getSecond() + "' value='" + selectedCell.getThird() + "';"); } } public boolean isApplicable() { return getViewer() instanceof SamplesViewer && ((SamplesViewer) getViewer()).getSamplesTableView().getCountSelectedAttributes() == 1; } public String getName() { return "Select Similar"; } public String getDescription() { return "Deselect all"; } public ImageIcon getIcon() { return null; } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
2,298
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SelectNumericalCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/SelectNumericalCommand.java
/* * SelectNumericalCommand.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.samplesviewer.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.util.parse.NexusStreamParser; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.event.ActionEvent; /** * * select numerical attributes * * Daniel Huson, 4.2017 */ public class SelectNumericalCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } public void actionPerformed(ActionEvent event) { executeImmediately("select numerical;"); } public boolean isApplicable() { return getViewer() instanceof SamplesViewer; } public String getName() { return "Select Numerical"; } public String getDescription() { return "Select all numerical attributes"; } public ImageIcon getIcon() { return null; } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } /** * parses the given command and executes it */ public void apply(NexusStreamParser np) { } }
1,968
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/samplesviewer/commands/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.samplesviewer.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.util.parse.NexusStreamParser; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; /** * * selection command * * Daniel Huson, 11.2010 */ public class SelectNoneCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } public void actionPerformed(ActionEvent event) { executeImmediately("select none;"); } public boolean isApplicable() { return getViewer() instanceof SamplesViewer && ((SamplesViewer) getViewer()).getSamplesTableView().getCountSelectedAttributes() > 0; } public String getName() { return "Select None"; } public String getDescription() { return "Deselect all"; } public ImageIcon getIcon() { return null; } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | java.awt.event.InputEvent.SHIFT_DOWN_MASK); } /** * parses the given command and executes it */ public void apply(NexusStreamParser np) { } }
2,192
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SelectFromPreviousCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/SelectFromPreviousCommand.java
/* * SelectFromPreviousCommand.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.samplesviewer.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.director.ProjectManager; 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 SelectFromPreviousCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } public void actionPerformed(ActionEvent event) { executeImmediately("select fromPrevious;"); } public boolean isApplicable() { return ProjectManager.getPreviouslySelectedNodeLabels().size() > 0; } public String getName() { return "From Previous Window"; } public String getDescription() { return "Select from previous window"; } public ImageIcon getIcon() { return null; } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_P, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()); } /** * parses the given command and executes it */ public void apply(NexusStreamParser np) { } }
2,133
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/samplesviewer/commands/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.samplesviewer.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.samplesviewer.SamplesTableView; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.event.ActionEvent; /** * * split by command * * Daniel Huson, 11.2020 */ public class SplitByAttributeCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } /** * parses the given command and executes it */ public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { final SamplesViewer viewer = ((SamplesViewer) getViewer()); final String attribute = viewer.getSamplesTableView().getASelectedAttribute(); final SamplesTableView samplesTable = ((SamplesViewer) getViewer()).getSamplesTableView(); if (attribute != null && samplesTable.getCountSelectedSamples() > 0) { execute("splitBy attribute='" + attribute + "' samples='" + StringUtils.toString(samplesTable.getSelectedSamples(), "' '") + "';"); } } public boolean isApplicable() { return getViewer() instanceof SamplesViewer && ((SamplesViewer) getViewer()).getSamplesTableView().getCountSelectedAttributes() == 1; } public String getName() { return "Split By Attribute..."; } public String getDescription() { return "Split samples into multiple documents based on values of the selected attribute"; } public ImageIcon getIcon() { return ResourceManager.getIcon("Compare16.gif"); } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
2,687
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/samplesviewer/commands/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.samplesviewer.commands; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.commands.clipboard.ClipboardBase; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.*; 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) { ((SamplesViewer) getViewer()).getSamplesTableView().copyToClipboard(); } public boolean isApplicable() { SamplesViewer sampleViewer = (SamplesViewer) getViewer(); return sampleViewer != null && sampleViewer.getSamplesTableView().getCountSelectedAttributes() > 0; } public String getAltName() { return "Samples Viewer Copy"; } 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()); } }
2,232
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SelectAllCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/SelectAllCommand.java
/* * SelectAllCommand.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.samplesviewer.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.director.ProjectManager; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.Collection; import java.util.HashSet; import java.util.Set; /** * * selection command * * Daniel Huson, 11.2010 */ public class SelectAllCommand extends CommandBase implements ICommand { private static final String[] legalOptions = {"all", "none", "similar", "commentLike", "numerical", "uninformative", "romPrevious", "samples"}; public String getSyntax() { return "select {" + StringUtils.toString(legalOptions, "|") + "} [name=<string>] [value=<string>];"; } /** * parses the given command and executes it */ public void apply(final NexusStreamParser np) throws Exception { np.matchIgnoreCase("select"); final String what = np.getWordMatchesIgnoringCase(legalOptions); final String name; final String value; final java.util.List<String> samples; if (what.equalsIgnoreCase("similar")) { np.matchIgnoreCase("name="); name = np.getWordRespectCase(); if (np.peekMatchIgnoreCase("value=")) { np.matchIgnoreCase("value="); value = np.getWordRespectCase(); } else value = null; samples = null; np.matchIgnoreCase(";"); } else if (what.equalsIgnoreCase("samples")) { name = null; value = null; samples = np.getTokensRespectCase("name=", ";"); } else { name = null; value = null; samples = null; np.matchIgnoreCase(";"); } final SamplesViewer viewer = (SamplesViewer) getViewer(); switch (what) { case "samples" -> { if (samples != null) { viewer.getSamplesTableView().selectSamples(samples, true); System.err.println("Selected " + samples.size() + " rows"); } } case "all" -> viewer.getSamplesTableView().selectAll(true); case "none" -> viewer.getSamplesTableView().selectAll(false); case "commentLike" -> { int count = 0; for (String attribute : viewer.getSamplesTableView().getAttributes()) { int min = Integer.MAX_VALUE; int max = 0; for (String sample : viewer.getSamplesTableView().getSamples()) { final Object value1 = viewer.getSampleAttributeTable().get(sample, attribute); if (value1 != null) { String string = value1.toString().trim(); if (string.length() > 0) { min = Math.min(min, string.length()); max = Math.max(max, string.length()); } } } if (max - min > 100) { viewer.getSamplesTableView().selectAttribute(attribute, true); count++; } } if (count > 0) System.err.println("Selected " + count + " columns"); } case "numerical" -> { int count = 0; final Collection<String> numericalAttributes = viewer.getSampleAttributeTable().getNumericalAttributes(); for (String attribute : viewer.getSamplesTableView().getAttributes()) { if (numericalAttributes.contains(attribute)) { viewer.getSamplesTableView().selectAttribute(attribute, true); count++; } } if (count > 0) System.err.println("Selected " + count + " columns"); } case "uninformative" -> { int count = 0; for (String attribute : viewer.getSamplesTableView().getAttributes()) { final Set<String> values = new HashSet<>(); for (String sample : viewer.getSamplesTableView().getSamples()) { Object value1 = viewer.getSampleAttributeTable().get(sample, attribute); if (value1 != null) { String string = value1.toString().trim(); if (string.length() > 0) { values.add(string); } } } if (values.size() <= 1 || values.size() == viewer.getSamplesTableView().getSampleCount()) { viewer.getSamplesTableView().selectAttribute(attribute, true); count++; } } if (count > 0) System.err.println("Selected " + count + " columns"); } case "similar" -> viewer.getSamplesTableView().selectByValue(name, value); case "fromPrevious" -> { String row1 = null; for (String sample : viewer.getSamplesTableView().getSamples()) { if (ProjectManager.getPreviouslySelectedNodeLabels().contains(sample)) { viewer.getSamplesTableView().selectSample(sample, true); row1 = sample; } } if (row1 != null) { viewer.getSamplesTableView().scrollToSample(row1); } String col1 = null; for (String attribute : viewer.getSamplesTableView().getAttributes()) { if (ProjectManager.getPreviouslySelectedNodeLabels().contains(attribute)) { viewer.getSamplesTableView().selectAttribute(attribute, true); col1 = attribute; } } if (row1 == null && col1 != null) { viewer.getSamplesTableView().scrollToSample(null); } } } } public void actionPerformed(ActionEvent event) { executeImmediately("select all;"); } public boolean isApplicable() { return getViewer() instanceof SamplesViewer; } public String getName() { return "Select All"; } public String getDescription() { return "Selection"; } public ImageIcon getIcon() { return null; } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()); } }
7,868
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SqueezeWidthColumnsCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/SqueezeWidthColumnsCommand.java
/* * SqueezeWidthColumnsCommand.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.samplesviewer.commands; import javafx.application.Platform; import javafx.scene.control.TableColumn; import jloda.fx.control.table.MyTableView; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.util.parse.NexusStreamParser; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; /** * * reorder samples in viewer * * Daniel Huson, 9.2012 */ public class SqueezeWidthColumnsCommand extends CommandBase implements ICommand { public String getSyntax() { return "squeeze above=<number> to=<number>;"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("squeeze above="); final int threshold = np.getInt(1, 10000); np.matchIgnoreCase("to="); final int size = np.getInt(1, threshold); np.matchIgnoreCase(";"); Platform.runLater(() -> { final SamplesViewer viewer = (SamplesViewer) getViewer(); for (int col = 0; col < viewer.getSamplesTableView().getAttributeCount(); col++) { final TableColumn<MyTableView.MyTableRow, ?> column = viewer.getSamplesTableView().getAttribute(col); if (column != null && column.getWidth() > threshold) column.setPrefWidth(size); } }); } public void actionPerformed(ActionEvent event) { executeImmediately("squeeze above=150 to=80;"); } public boolean isApplicable() { final SamplesViewer viewer = (SamplesViewer) getViewer(); return viewer != null && viewer.getDocument().getNumberOfSamples() > 0; } public String getName() { return "Squeeze Wide Columns"; } public String getDescription() { return "Squeeze wide columns to narrow width"; } public ImageIcon getIcon() { return null; } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_K, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()); } }
3,005
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ListAttributeSummaryCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/ListAttributeSummaryCommand.java
/* * ListAttributeSummaryCommand.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.samplesviewer.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.Pair; import jloda.util.Statistics; import jloda.util.parse.NexusStreamParser; import megan.core.Director; import megan.core.Document; import megan.core.SampleAttributeTable; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * list a report over all attributes * * @author Daniel Huson, 3.2017 */ public class ListAttributeSummaryCommand extends CommandBase implements ICommand { /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("list attributes="); final String what = np.getWordMatchesIgnoringCase(" all selected"); np.matchIgnoreCase(";"); final Collection<String> activeSamples; final Collection<String> activeAttributes; if (what.equalsIgnoreCase("selected")) { if (getViewer() instanceof SamplesViewer) { final SamplesViewer samplesViewer = (SamplesViewer) getViewer(); activeSamples = samplesViewer.getSamplesTableView().getSelectedSamples(); activeAttributes = samplesViewer.getSamplesTableView().getSelectedAttributes(); } else return; } else { final Document doc = ((Director) getDir()).getDocument(); activeSamples = doc.getSampleNames(); activeAttributes = doc.getSampleAttributeTable().getUnhiddenAttributes(); } final Document doc = ((Director) getDir()).getDocument(); final SampleAttributeTable sampleAttributeTable = doc.getSampleAttributeTable(); final Collection<String> numericalAttributes = sampleAttributeTable.getNumericalAttributes(); System.err.println("Active samples: " + activeSamples.size()); System.err.println("Active attributes: " + activeAttributes.size()); for (String attribute : activeAttributes) { if (numericalAttributes.contains(attribute)) { ArrayList<Number> numbers = new ArrayList<>(activeSamples.size()); for (String sample : activeSamples) { Object value = sampleAttributeTable.get(sample, attribute); if (value instanceof Number) numbers.add((Number) value); } final Statistics statistics = new Statistics(numbers); System.out.printf("%s: m=%.1f sd=%.1f (%.1f - %.1f)%n", attribute, statistics.getMean(), statistics.getStdDev(), statistics.getMin(), statistics.getMax()); } else { final Map<String, Integer> value2count = new HashMap<>(); for (String sample : activeSamples) { Object value = sampleAttributeTable.get(sample, attribute); if (value != null) { String string = value.toString().trim(); if (string.length() > 0) { value2count.merge(string, 1, Integer::sum); } } } ArrayList<Pair<Integer, String>> list = new ArrayList<>(value2count.size()); for (Map.Entry<String, Integer> entry : value2count.entrySet()) { list.add(new Pair<>(entry.getValue(), entry.getKey())); } if (list.size() > 0) { list.sort((a, b) -> { if (a.getFirst() > b.getFirst()) return -1; else if (a.getFirst() < b.getFirst()) return 1; else return a.getSecond().compareTo(b.getSecond()); }); System.out.printf("%s:%n", attribute); Pair<Integer, String> first = list.get(0); if (first.getFirst() == 1) { System.out.printf("\t(Singleton: %.1f %%)%n", 100 * ((double) list.size() / (double) activeSamples.size())); if (list.size() < activeSamples.size()) System.out.printf("\t(Rest: %.1f %%)%n", 100 * ((double) (activeSamples.size() - list.size()) / (double) activeSamples.size())); } else { int count = 0; double sum = 0; for (Pair<Integer, String> pair : list) { double percent = Math.max(0, Math.min(100, 100 * ((double) pair.getFirst() / (double) activeSamples.size()))); System.out.printf("\t%s: %.1f %%%n", pair.getSecond(), percent); sum += percent; if (++count == 20) { if (count < list.size()) System.out.printf("\t(Rest: %d items, %.1f %%)%n", (list.size() - count), Math.max(0, 100 - sum)); break; } } } } } } } public String getSyntax() { return "list attributes={all|selected};"; } public void actionPerformed(ActionEvent event) { if (getViewer() instanceof SamplesViewer) { final SamplesViewer samplesViewer = (SamplesViewer) getViewer(); if (samplesViewer.getSamplesTableView().getSelectedSamples().size() > 0 || samplesViewer.getSamplesTableView().getSelectedAttributes().size() > 0) executeImmediately("show window=message;list attributes=selected;"); else executeImmediately("show window=message;list attributes=all;"); } } public boolean isApplicable() { return true; } public String getName() { return "List Summary..."; } public String getAltName() { return "List Attribute Summary..."; } public String getDescription() { return "List summary of attributes"; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/History16.gif"); } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
7,471
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DeleteColumnCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/DeleteColumnCommand.java
/* * DeleteColumnCommand.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.samplesviewer.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.fx.Dialogs; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.Collection; import java.util.HashSet; import java.util.Set; /** * * delete command * * Daniel Huson, 9.2015 */ public class DeleteColumnCommand extends CommandBase implements ICommand { public String getSyntax() { return "delete attribute=<name> [<name>...];"; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("delete attribute="); Set<String> attributes = new HashSet<>(); while (!np.peekMatchIgnoreCase(";")) { String attribute = np.getWordRespectCase(); attributes.add(attribute); } np.matchIgnoreCase(";"); if (attributes.size() > 0) { final SamplesViewer viewer = ((SamplesViewer) getViewer()); viewer.getSamplesTableView().deleteColumns(attributes.toArray(new String[0])); } } public void actionPerformed(ActionEvent event) { final SamplesViewer viewer = ((SamplesViewer) getViewer()); final Collection<String> attributes = viewer.getSamplesTableView().getSelectedAttributes(); if (attributes.size() > 0) { final String message = "Confirm delete column '" + attributes.iterator().next() + "'" + (attributes.size() > 1 ? " (and " + (attributes.size() - 1) + " others)" : ""); if (Dialogs.showConfirmation(getViewer().getFrame(), "Confirm delete", message)) { final StringBuilder buf = new StringBuilder(); buf.append("delete attribute="); for (String attributeName : attributes) { buf.append(" '").append(attributeName).append("'"); } buf.append(";"); executeImmediately(buf.toString()); } } } public boolean isApplicable() { final SamplesViewer samplesViewer = ((SamplesViewer) getViewer()); return samplesViewer != null && samplesViewer.getSamplesTableView().getCountSelectedAttributes() > 0; } public String getName() { return "Delete Column(s)..."; } public String getDescription() { return "Delete selected columns"; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/ColumnDelete16.gif"); } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()); } }
3,774
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/samplesviewer/commands/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.samplesviewer.commands; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.commands.clipboard.ClipboardBase; import javax.swing.*; 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) { System.err.println("Not implemented"); } public boolean isApplicable() { return false; } public String getAltName() { return "Samples Viewer Cut"; } 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,000
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
CompareByAttributeAbsoluteCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/CompareByAttributeAbsoluteCommand.java
/* * CompareByAttributeAbsoluteCommand.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.samplesviewer.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.dialogs.compare.Comparer; import megan.samplesviewer.SamplesTableView; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.event.ActionEvent; /** * * compare by command * * Daniel Huson, 9.2105 */ public class CompareByAttributeAbsoluteCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } /** * parses the given command and executes it */ public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { final SamplesViewer viewer = ((SamplesViewer) getViewer()); final String attribute = viewer.getSamplesTableView().getASelectedAttribute(); final SamplesTableView samplesTable = ((SamplesViewer) getViewer()).getSamplesTableView(); if (attribute != null && samplesTable.getCountSelectedSamples() > 0) { execute("compareBy attribute='" + attribute + "' mode=" + Comparer.COMPARISON_MODE.ABSOLUTE.toString().toLowerCase() + " samples='" + StringUtils.toString(samplesTable.getSelectedSamples(), "' '") + "';"); } } public boolean isApplicable() { return getViewer() instanceof SamplesViewer && ((SamplesViewer) getViewer()).getSamplesTableView().getCountSelectedAttributes() == 1; } public String getName() { return "Compare Absolute..."; } public String getDescription() { return "Aggregate samples by this attribute and show absolute comparison in new document"; } public ImageIcon getIcon() { return ResourceManager.getIcon("Compare16.gif"); } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
2,825
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
LabelSamplesBySamplesCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/samples/LabelSamplesBySamplesCommand.java
/* * LabelSamplesBySamplesCommand.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.samplesviewer.commands.samples; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.core.SampleAttributeTable; import javax.swing.*; import java.awt.event.ActionEvent; /** * label by command * Daniel Huson, 9.2105 */ public class LabelSamplesBySamplesCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } /** * parses the given command and executes it */ public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { execute("labelBy attribute='" + SampleAttributeTable.SAMPLE_ID + "' samples=all;"); } public boolean isApplicable() { return true; } public String getName() { return "Label by Samples"; } public String getDescription() { return "Label samples by there names"; } public ImageIcon getIcon() { return ResourceManager.getIcon("Labels16.gif"); } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
2,057
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
OpenOriginalFileCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/samples/OpenOriginalFileCommand.java
/* * OpenOriginalFileCommand.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.samplesviewer.commands.samples; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.core.MeganFile; import megan.core.SampleAttributeTable; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.event.ActionEvent; /** * * open original file * * Daniel Huson, 10.2015 */ public class OpenOriginalFileCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } /** * parses the given command and executes it */ public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { final SamplesViewer viewer = (SamplesViewer) getViewer(); if (viewer.getDocument().getMeganFile().isMeganSummaryFile()) { if (viewer.getSamplesTableView().getCountSelectedSamples() > 0) { StringBuilder buf = new StringBuilder(); for (String sample : viewer.getSamplesTableView().getSelectedSamples()) { Object source = viewer.getDocument().getSampleAttributeTable().get(sample, SampleAttributeTable.HiddenAttribute.Source.toString()); if (source != null) { buf.append("open file='").append(source).append("';"); } } String command = buf.toString(); if (command.length() > 0) execute(command); } } } public boolean isApplicable() { if (getViewer() instanceof SamplesViewer) { final SamplesViewer viewer = (SamplesViewer) getViewer(); if (viewer.getDocument().getMeganFile().isMeganSummaryFile()) { if (viewer.getSamplesTableView().getCountSelectedSamples() > 0) { for (String sample : viewer.getSamplesTableView().getSelectedSamples()) { Object source = viewer.getDocument().getSampleAttributeTable().get(sample, SampleAttributeTable.HiddenAttribute.Source.toString()); if (source != null) { final MeganFile meganFile = new MeganFile(); meganFile.setFileFromExistingFile(source.toString(), true); try { meganFile.checkFileOkToRead(); return true; } catch (Exception ex) { // ignore } } } } } } return false; } public String getName() { return "Open RMA File..."; } public String getDescription() { return "Open the original RMA file"; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Open16.gif"); } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
3,956
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetSampleShapeCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/samples/SetSampleShapeCommand.java
/* * SetSampleShapeCommand.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.samplesviewer.commands.samples; import javafx.application.Platform; import javafx.scene.control.ChoiceDialog; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.NodeShape; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.Collection; import java.util.Optional; /** * set sample node shape * Daniel Huson, 3.2013 */ public class SetSampleShapeCommand extends CommandBase implements ICommand { /** * apply */ public void apply(NexusStreamParser np) { } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { 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; } public boolean isApplicable() { return true; } /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Set Shape..."; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Set the sample shape"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("BlueTriangle16.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) { final SamplesViewer viewer = (SamplesViewer) getViewer(); final Collection<String> selected = viewer.getSamplesTableView().getSelectedSamples(); if (selected.size() > 0) { String sample = selected.iterator().next(); String shapeLabel = viewer.getSampleAttributeTable().getSampleShape(sample); NodeShape nodeShape = NodeShape.valueOfIgnoreCase(shapeLabel); if (nodeShape == null) nodeShape = NodeShape.Oval; final NodeShape nodeShape1 = nodeShape; Runnable runnable = () -> { final ChoiceDialog<NodeShape> dialog = new ChoiceDialog<>(nodeShape1, NodeShape.values()); dialog.setTitle("MEGAN choice"); dialog.setHeaderText("Choose shape to represent sample(s)"); dialog.setContentText("Shape:"); final Optional<NodeShape> result = dialog.showAndWait(); result.ifPresent(shape -> execute("set nodeShape=" + shape + " sample='" + StringUtils.toString(selected, "' '") + "';")); }; if (Platform.isFxApplicationThread()) runnable.run(); else Platform.runLater(runnable); } } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
4,190
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetSampleColorCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/samples/SetSampleColorCommand.java
/* * SetSampleColorCommand.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.samplesviewer.commands.samples; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ChooseColorDialog; import jloda.swing.util.ColorUtilsSwing; import jloda.swing.util.ResourceManager; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.core.Director; import megan.core.Document; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.util.Collection; import java.util.LinkedList; import java.util.List; /** * draw sample node color * Daniel Huson, 11.2019 */ public class SetSampleColorCommand extends CommandBase implements ICommand { /** * apply */ public void apply(NexusStreamParser np) throws Exception { final Document doc = ((Director) getDir()).getDocument(); np.matchIgnoreCase("set nodeColor="); Color color = null; if (np.peekMatchIgnoreCase("null")) np.matchIgnoreCase("null"); else color = ColorUtilsSwing.convert(np.getColor()); final List<String> samples = new LinkedList<>(); if (np.peekMatchIgnoreCase("sample=")) { np.matchIgnoreCase("sample="); while (!np.peekMatchIgnoreCase(";")) { samples.add(np.getWordRespectCase()); } } np.matchIgnoreCase(";"); if (samples.size() == 0) samples.addAll(doc.getSampleSelection().getAll()); if (samples.size() > 0) { for (String sample : samples) { doc.getSampleAttributeTable().putSampleColor(sample, color); } ((Director) getDir()).getDocument().setDirty(true); } } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { 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; } public boolean isApplicable() { return true; } /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Set Color..."; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Set the sample color"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("YellowSquare16.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) { final SamplesViewer viewer = (SamplesViewer) getViewer(); final Collection<String> selected = viewer.getSamplesTableView().getSelectedSamples(); if (selected.size() > 0) { Color color = ChooseColorDialog.showChooseColorDialog(getViewer().getFrame(), "Choose sample color", null); if (color != null) execute("set nodeColor=" + color.getRed() + " " + color.getGreen() + " " + color.getBlue() + " sample='" + StringUtils.toString(selected, "' '") + "';"); } } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
4,504
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
MoveSamplesUpCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/samples/MoveSamplesUpCommand.java
/* * MoveSamplesUpCommand.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.samplesviewer.commands.samples; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.Collection; import java.util.HashSet; import java.util.Set; /** * * delete command * * Daniel Huson, 9.2015 */ public class MoveSamplesUpCommand extends CommandBase implements ICommand { public String getSyntax() { return "move sample=<name> [<name>...] direction={up|down};"; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("move sample="); Set<String> samples = new HashSet<>(); while (!np.peekMatchIgnoreCase("direction")) { String attribute = np.getWordRespectCase(); samples.add(attribute); } np.matchIgnoreCase("direction="); String direction = np.getWordMatchesIgnoringCase("up down"); np.matchIgnoreCase(";"); if (samples.size() > 0) { final SamplesViewer viewer = ((SamplesViewer) getViewer()); viewer.getSamplesTableView().moveSamples(direction.equalsIgnoreCase("up"), samples); } } public void actionPerformed(ActionEvent event) { final SamplesViewer viewer = ((SamplesViewer) getViewer()); final Collection<String> samples = viewer.getSamplesTableView().getSelectedSamples(); if (samples.size() > 0) { final StringBuilder buf = new StringBuilder(); buf.append("move sample="); for (String attributeName : samples) { buf.append(" '").append(attributeName).append("'"); } buf.append(" direction=up;"); executeImmediately(buf.toString()); } } public boolean isApplicable() { return getViewer() instanceof SamplesViewer && ((SamplesViewer) getViewer()).getSamplesTableView().getCountSelectedSamples() > 0 && !((SamplesViewer) getViewer()).getSamplesTableView().getSelectedSamplesIndices().contains(0); } public String getName() { return "Move Up"; } public String getDescription() { return "Move selected samples"; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Up16.gif"); } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_U, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()); } }
3,582
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
RenameSampleCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/samples/RenameSampleCommand.java
/* * RenameSampleCommand.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.samplesviewer.commands.samples; import javafx.application.Platform; import javafx.scene.control.TextInputDialog; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.util.parse.NexusStreamParser; import megan.core.Director; import megan.core.SampleAttributeTable; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.Optional; /** * * rename command * * Daniel Huson, 9.2012 */ public class RenameSampleCommand extends CommandBase implements ICommand { public String getSyntax() { return "rename sample=<name> newName=<name>;"; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("rename sample="); final String sampleName = np.getWordRespectCase(); np.matchIgnoreCase("newName="); String newName = np.getWordRespectCase(); np.matchIgnoreCase(";"); (((Director) getDir()).getDocument()).renameSample(sampleName, newName); } public void actionPerformed(ActionEvent event) { SamplesViewer viewer = (SamplesViewer) getViewer(); String sampleName = viewer.getSamplesTableView().getASelectedSample(); String newName = null; if (Platform.isFxApplicationThread()) { TextInputDialog dialog = new TextInputDialog(sampleName); dialog.setTitle("Rename sample"); dialog.setHeaderText("Enter new sample name:"); Optional<String> result = dialog.showAndWait(); if (result.isPresent()) { newName = result.get().trim(); } } else if (javax.swing.SwingUtilities.isEventDispatchThread()) { newName = JOptionPane.showInputDialog(getViewer().getFrame(), "Enter new sample name", sampleName); } if (newName != null && !newName.equals(sampleName)) { if (viewer.getSampleAttributeTable().getSampleOrder().contains(newName)) { int count = 1; while (viewer.getSampleAttributeTable().getSampleOrder().contains(newName + "." + count)) count++; newName += "." + count; } execute("rename sample='" + sampleName + "' newName='" + newName + "';" + "labelBy attribute='" + SampleAttributeTable.SAMPLE_ID + "' samples=all;"); } } public boolean isApplicable() { SamplesViewer viewer = (SamplesViewer) getViewer(); return !viewer.getDocument().getMeganFile().hasDataConnector() && (viewer.getSamplesTableView().getCountSelectedSamples() == 1); } public String getName() { return "Rename..."; } public String getAltName() { return "Rename Sample..."; } public String getDescription() { return "Rename selected sample"; } public ImageIcon getIcon() { return null; } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_R, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | java.awt.event.InputEvent.SHIFT_DOWN_MASK); } }
4,159
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
MoveSamplesDownCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/samples/MoveSamplesDownCommand.java
/* * MoveSamplesDownCommand.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.samplesviewer.commands.samples; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.Collection; /** * * delete command * * Daniel Huson, 9.2015 */ public class MoveSamplesDownCommand 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) { final SamplesViewer viewer = ((SamplesViewer) getViewer()); final Collection<String> samples = viewer.getSamplesTableView().getSelectedSamples(); if (samples.size() > 0) { final StringBuilder buf = new StringBuilder(); buf.append("move sample="); for (String attributeName : samples) { buf.append(" '").append(attributeName).append("'"); } buf.append(" direction=down;"); executeImmediately(buf.toString()); } } public boolean isApplicable() { if (getViewer() instanceof SamplesViewer) { SamplesViewer viewer = (SamplesViewer) getViewer(); return viewer.getSamplesTableView().getCountSelectedSamples() > 0 && !viewer.getSamplesTableView().getSelectedSamplesIndices().contains(Math.max(0, viewer.getSamplesTableView().getSampleCount() - 1)); } else return false; } public String getName() { return "Move Down"; } public String getDescription() { return "Move selected samples"; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Down16.gif"); } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_D, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()); } }
3,007
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ExpandAttributesCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/attributes/ExpandAttributesCommand.java
/* * ExpandAttributesCommand.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.samplesviewer.commands.attributes; import javafx.application.Platform; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.window.NotificationsInSwing; 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; import java.util.Optional; import java.util.Set; import java.util.TreeSet; /** * * make a new attribute * * Daniel Huson, 19.2015 */ public class ExpandAttributesCommand extends CommandBase implements ICommand { public String getSyntax() { return "expand attribute=<name>;"; } /** * parses the given command and executes it */ public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("expand attribute="); final String attribute = np.getWordRespectCase(); np.matchIgnoreCase(";"); final Director dir = (Director) getDir(); final Document doc = dir.getDocument(); final SamplesViewer samplesViewer = (SamplesViewer) getDir().getViewerByClass(SamplesViewer.class); if (samplesViewer != null) { // todo: sync to document... // ((SamplesViewer) getViewer()).getSamplesTableView().syncFromDocument(); } final int count = doc.getSampleAttributeTable().expandAttribute(attribute, true); if (count > 0 && samplesViewer != null) samplesViewer.getSamplesTableView().syncFromDocumentToView(); if (count == 0) NotificationsInSwing.showWarning(getViewer().getFrame(), "Expand attribute failed"); else NotificationsInSwing.showInformation(getViewer().getFrame(), "Expand " + attribute + "' added " + count + " columns"); } public void actionPerformed(ActionEvent event) { final SamplesViewer viewer = ((SamplesViewer) getViewer()); final String attributeName = viewer.getSamplesTableView().getASelectedAttribute(); if (attributeName != null) { final Set<Object> states = new TreeSet<>(viewer.getSampleAttributeTable().getSamples2Values(attributeName).values()); boolean ok = false; if (Platform.isFxApplicationThread()) { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("MEGAN Expand Dialog"); alert.setHeaderText("Expanding '" + attributeName + "' will add " + states.size() + " new columns"); alert.setContentText("Proceed?"); Optional<ButtonType> result = alert.showAndWait(); if (result.isPresent() && result.get() == ButtonType.OK) { ok = true; // ... user chose OK } } else if (SwingUtilities.isEventDispatchThread()) { int result = JOptionPane.showConfirmDialog(getViewer().getFrame(), "Expanding '" + attributeName + "' will add " + states.size() + " new columns, proceed?"); if (result == JOptionPane.YES_OPTION) ok = true; } if (ok) executeImmediately("expand attribute='" + attributeName + "';"); } } public boolean isApplicable() { return getViewer() instanceof SamplesViewer && ((SamplesViewer) getViewer()).getSamplesTableView().getSelectedAttributes().size() == 1; } public String getName() { return "Expand..."; } public String getDescription() { return "Expands an attribute by adding one 0/1 column per value"; } public ImageIcon getIcon() { return null; // ResourceManager.getIcon("sun/ColumnInsertAfter16.gif"); } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
4,816
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
LabelSamplesByCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/attributes/LabelSamplesByCommand.java
/* * LabelSamplesByCommand.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.samplesviewer.commands.attributes; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.event.ActionEvent; /** * label by command * Daniel Huson, 9.2105 */ public class LabelSamplesByCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } /** * parses the given command and executes it */ public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { final SamplesViewer viewer = ((SamplesViewer) getViewer()); final String attribute = viewer.getSamplesTableView().getASelectedAttribute(); if (attribute != null) execute("labelBy attribute='" + attribute + "';"); } public boolean isApplicable() { return getViewer() instanceof SamplesViewer && ((SamplesViewer) getViewer()).getSamplesTableView().getCountSelectedAttributes() == 1; } public String getName() { return "Use to Label Samples"; } public String getDescription() { return "Label samples by this attribute"; } public ImageIcon getIcon() { return ResourceManager.getIcon("Labels16.gif"); } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
2,332
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
GroupByCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/attributes/GroupByCommand.java
/* * GroupByCommand.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.samplesviewer.commands.attributes; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.event.ActionEvent; /** * * group by command * * Daniel Huson, 9.2105 */ public class GroupByCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } /** * parses the given command and executes it */ public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { final SamplesViewer viewer = ((SamplesViewer) getViewer()); final String attribute = viewer.getSamplesTableView().getASelectedAttribute(); if (attribute != null) execute("groupBy attribute='" + attribute + "';show window=groups;"); } public boolean isApplicable() { return getViewer() instanceof SamplesViewer && ((SamplesViewer) getViewer()).getSamplesTableView().getCountSelectedAttributes() == 1; } public String getName() { return "Use to Group Samples"; } public String getDescription() { return "Group samples by this attribute"; } public ImageIcon getIcon() { return ResourceManager.getIcon("JoinNodes16.gif"); } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
2,344
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
NewAttributeCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/attributes/NewAttributeCommand.java
/* * NewAttributeCommand.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.samplesviewer.commands.attributes; import javafx.application.Platform; import javafx.scene.control.TextInputDialog; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.Optional; /** * * make a new attribute * * Daniel Huson, 19.2015 */ public class NewAttributeCommand extends CommandBase implements ICommand { public String getSyntax() { return "new attribute=<name> position=<number>;"; } /** * parses the given command and executes it */ public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("new attribute="); String attribute = np.getWordRespectCase(); np.matchIgnoreCase("position="); int position = np.getInt(); np.matchIgnoreCase(";"); final SamplesViewer viewer = ((SamplesViewer) getViewer()); viewer.getSamplesTableView().addNewColumn(position, attribute); } public void actionPerformed(ActionEvent event) { final SamplesViewer viewer = ((SamplesViewer) getViewer()); final int index; final String selectedAttribute = viewer.getSamplesTableView().getASelectedAttribute(); if (selectedAttribute != null) index = viewer.getSamplesTableView().getAttributes().indexOf(selectedAttribute); else index = viewer.getSamplesTableView().getSampleCount(); String name = null; if (Platform.isFxApplicationThread()) { TextInputDialog dialog = new TextInputDialog("Attribute"); dialog.setTitle("New attribute"); dialog.setHeaderText("Enter attribute name:"); Optional<String> result = dialog.showAndWait(); if (result.isPresent()) { name = result.get().trim(); } } else if (javax.swing.SwingUtilities.isEventDispatchThread()) { name = JOptionPane.showInputDialog(getViewer().getFrame(), "Enter new attribute name", "Untitled"); } if (name != null) executeImmediately("new attribute='" + name + "' position=" + index + ";"); } public boolean isApplicable() { return getViewer() instanceof SamplesViewer; } public String getName() { return "New Column..."; } public String getDescription() { return "Create a new attribute (column) in the data table"; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/ColumnInsertAfter16.gif"); } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_J, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()); } }
3,799
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ShapeSamplesByCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/attributes/ShapeSamplesByCommand.java
/* * ShapeSamplesByCommand.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.samplesviewer.commands.attributes; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.event.ActionEvent; /** * choose shape by attribute * * Daniel Huson, 9.2015 */ public class ShapeSamplesByCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } /** * parses the given command and executes it */ public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { final SamplesViewer viewer = ((SamplesViewer) getViewer()); final String attribute = viewer.getSamplesTableView().getASelectedAttribute(); if (attribute != null) execute("shapeBy attribute='" + attribute + "';"); } public boolean isApplicable() { return getViewer() instanceof SamplesViewer && ((SamplesViewer) getViewer()).getSamplesTableView().getCountSelectedAttributes() == 1; } public String getName() { return "Use to Shape Samples"; } public String getDescription() { return "Shape samples by this attribute"; } public ImageIcon getIcon() { return ResourceManager.getIcon("Circle16.gif"); } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
2,343
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ColorSamplesByCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/attributes/ColorSamplesByCommand.java
/* * ColorSamplesByCommand.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.samplesviewer.commands.attributes; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.event.ActionEvent; /** * * selection command * * Daniel Huson, 11.2010 */ public class ColorSamplesByCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } /** * parses the given command and executes it */ public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { final SamplesViewer viewer = ((SamplesViewer) getViewer()); final String attribute = viewer.getSamplesTableView().getASelectedAttribute(); if (attribute != null) execute("colorBy attribute='" + attribute + "';"); } public boolean isApplicable() { return getViewer() instanceof SamplesViewer && ((SamplesViewer) getViewer()).getSamplesTableView().getCountSelectedAttributes() == 1; } public String getName() { return "Use to Color Samples"; } public String getDescription() { return "Color samples by this attribute"; } public ImageIcon getIcon() { return ResourceManager.getIcon("YellowSquare16.gif"); } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
2,344
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DrawNoneCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/format/DrawNoneCommand.java
/* * DrawNoneCommand.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.samplesviewer.commands.format; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.Collection; /** * draw selected nodes as nothing * Daniel Huson, 3.2013 */ public class DrawNoneCommand extends CommandBase implements ICommand { /** * apply */ public void apply(NexusStreamParser np) { } /** * get command-line usage description * * @return usage */ public String getSyntax() { 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; } public boolean isApplicable() { final SamplesViewer samplesViewer = ((SamplesViewer) getViewer()); return samplesViewer != null && samplesViewer.getSamplesTableView().getCountSelectedSamples() > 0; } /** * get the name to be used as a menu label * * @return name */ public String getName() { return "None"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "No node shape"; } /** * 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; } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { final SamplesViewer samplesViewer = ((SamplesViewer) getViewer()); final Collection<String> samples = samplesViewer.getSamplesTableView().getSelectedSamples(); if (samples.size() > 0) execute("set nodeShape=none sample='" + StringUtils.toString(samples, "' '") + "';"); } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
3,157
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DrawDiamondsCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/format/DrawDiamondsCommand.java
/* * DrawDiamondsCommand.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.samplesviewer.commands.format; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.Collection; /** * draw selected nodes as diamonds * Daniel Huson, 3.2013 */ public class DrawDiamondsCommand extends CommandBase implements ICommand { /** * apply */ public void apply(NexusStreamParser np) { } /** * get command-line usage description * * @return usage */ public String getSyntax() { 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; } public boolean isApplicable() { final SamplesViewer samplesViewer = ((SamplesViewer) getViewer()); return samplesViewer != null && samplesViewer.getSamplesTableView().getCountSelectedSamples() > 0; } /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Diamond"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Diamond node shape"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("BlueDiamond16.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) { final SamplesViewer samplesViewer = ((SamplesViewer) getViewer()); final Collection<String> samples = samplesViewer.getSamplesTableView().getSelectedSamples(); if (samples.size() > 0) execute("set nodeShape=diamond sample='" + StringUtils.toString(samples, "' '") + "';"); } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
3,258
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/samplesviewer/commands/format/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.samplesviewer.commands.format; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.Collection; /** * draw selected nodes as circles * Daniel Huson, 3.2013 */ public class DrawCirclesCommand extends CommandBase implements ICommand { /** * apply */ public void apply(NexusStreamParser np) { } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { 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() { final SamplesViewer samplesViewer = ((SamplesViewer) getViewer()); return samplesViewer != null && samplesViewer.getSamplesTableView().getCountSelectedSamples() > 0; } /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Circle"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Circle node shape"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("BlueCircle16.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) { final SamplesViewer samplesViewer = ((SamplesViewer) getViewer()); final Collection<String> samples = samplesViewer.getSamplesTableView().getSelectedSamples(); if (samples.size() > 0) execute("set nodeShape=circle sample='" + StringUtils.toString(samples, "' '") + "';"); } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
3,415
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DrawTrianglesCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/format/DrawTrianglesCommand.java
/* * DrawTrianglesCommand.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.samplesviewer.commands.format; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.Collection; /** * draw selected nodes as triangles * Daniel Huson, 3.2013 */ public class DrawTrianglesCommand extends CommandBase implements ICommand { /** * apply */ public void apply(NexusStreamParser np) { } /** * get command-line usage description * * @return usage */ public String getSyntax() { 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; } public boolean isApplicable() { final SamplesViewer samplesViewer = ((SamplesViewer) getViewer()); return samplesViewer != null && samplesViewer.getSamplesTableView().getCountSelectedSamples() > 0; } /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Triangle"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Triangle node shape"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("BlueTriangle16.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) { final SamplesViewer samplesViewer = ((SamplesViewer) getViewer()); final Collection<String> samples = samplesViewer.getSamplesTableView().getSelectedSamples(); if (samples.size() > 0) execute("set nodeShape=triangle sample='" + StringUtils.toString(samples, "' '") + "';"); } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
3,265
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DrawSquaresCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/samplesviewer/commands/format/DrawSquaresCommand.java
/* * DrawSquaresCommand.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.samplesviewer.commands.format; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.Collection; /** * draw selected nodes as squares * Daniel Huson, 3.2013 */ public class DrawSquaresCommand extends CommandBase implements ICommand { /** * apply */ public void apply(NexusStreamParser np) { } /** * get command-line usage description * * @return usage */ public String getSyntax() { 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; } public boolean isApplicable() { final SamplesViewer samplesViewer = ((SamplesViewer) getViewer()); return samplesViewer != null && samplesViewer.getSamplesTableView().getCountSelectedSamples() > 0; } /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Square"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Square node shape"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("BlueSquare16.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) { final SamplesViewer samplesViewer = ((SamplesViewer) getViewer()); final Collection<String> samples = samplesViewer.getSamplesTableView().getSelectedSamples(); if (samples.size() > 0) execute("set nodeShape=square sample='" + StringUtils.toString(samples, "' '") + "';"); } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
3,251
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
GroupsViewer.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/groups/GroupsViewer.java
/* * GroupsViewer.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.groups; import jloda.swing.commands.CommandManager; import jloda.swing.director.IDirectableViewer; import jloda.swing.director.IDirector; import jloda.swing.director.ProjectManager; import jloda.swing.util.ProgramProperties; import jloda.swing.util.StatusBar; import jloda.swing.util.ToolBar; import jloda.swing.window.MenuBar; import megan.clusteranalysis.ClusterViewer; import megan.core.Director; import megan.core.SelectionSet; import megan.main.MeganProperties; import megan.viewer.MainViewer; import javax.swing.*; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.util.Collection; import java.util.Set; /** * Viewer for selecting groups * Daniel Huson, 8.2014 */ public class GroupsViewer implements IDirectableViewer, Printable { private boolean uptodate = true; private boolean locked = false; private final JFrame frame; private final StatusBar statusBar; private final Director dir; private final CommandManager commandManager; private final MenuBar menuBar; private final GroupsPanel groupsPanel; private final SelectionSet.SelectionListener selectionListener; private boolean ignoreNextUpdateAll = false; /** * constructor * */ public GroupsViewer(final Director dir, JFrame parent) { this.dir = dir; commandManager = new CommandManager(dir, this, new String[]{"megan.commands", "megan.groups.commands"}, !ProgramProperties.isUseGUI()); frame = new JFrame(); menuBar = new MenuBar(this, GUIConfiguration.getMenuConfiguration(), commandManager); frame.setJMenuBar(menuBar); MeganProperties.addPropertiesListListener(menuBar.getRecentFilesListener()); MeganProperties.notifyListChange(ProgramProperties.RECENTFILES); ProjectManager.addAnotherWindowWithWindowMenu(dir, menuBar.getWindowMenu()); setTitle(); frame.setIconImages(ProgramProperties.getProgramIconImages()); frame.setJMenuBar(menuBar); frame.getContentPane().setLayout(new BorderLayout()); final JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BorderLayout()); frame.add(mainPanel, BorderLayout.CENTER); JToolBar toolBar = new ToolBar(this, GUIConfiguration.getToolBarConfiguration(), commandManager); mainPanel.add(toolBar, BorderLayout.NORTH); groupsPanel = new GroupsPanel(dir.getDocument(), this); mainPanel.add(groupsPanel, BorderLayout.CENTER); selectionListener = groupsPanel::selectSamples; dir.getDocument().getSampleSelection().addSampleSelectionListener(selectionListener); groupsPanel.setGroupsChangedListener(() -> { for (IDirectableViewer viewer : dir.getViewers()) { if (viewer instanceof ClusterViewer) { ClusterViewer cv = (ClusterViewer) viewer; if (cv.getPcoaTab() == cv.getSelectedComponent()) { cv.updateView(IDirector.ALL); } } } }); frame.addWindowListener(new WindowAdapter() { public void windowActivated(WindowEvent event) { MainViewer.setLastActiveFrame(frame); updateView(IDirector.ENABLE_STATE); } public void windowDeactivated(WindowEvent event) { Set<String> selected = groupsPanel.getSelectedSamples(); if (selected.size() != 0) { ProjectManager.getPreviouslySelectedNodeLabels().clear(); ProjectManager.getPreviouslySelectedNodeLabels().addAll(selected); } } public void windowClosing(WindowEvent e) { if (dir.getDocument().getProgressListener() != null) dir.getDocument().getProgressListener().setUserCancelled(true); if (MainViewer.getLastActiveFrame() == frame) MainViewer.setLastActiveFrame(null); } }); statusBar = new StatusBar(); mainPanel.add(statusBar, BorderLayout.SOUTH); Dimension preferredSize = new Dimension(300, 700); frame.setSize(preferredSize); frame.setLocationRelativeTo(parent); frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); frame.setVisible(true); } public Director getDir() { return dir; } public JFrame getFrame() { return this.frame; } /** * gets the title * * @return title */ public String getTitle() { return this.frame.getTitle(); } /** * is viewer uptodate? * * @return uptodate */ public boolean isUptoDate() { return this.uptodate; } /** * ask view to destroy itself */ public void destroyView() { dir.getDocument().getSampleSelection().removeSampleSelectionListener(selectionListener); MeganProperties.removePropertiesListListener(menuBar.getRecentFilesListener()); dir.removeViewer(this); frame.dispose(); } /** * ask view to prevent user input */ public void lockUserInput() { locked = true; commandManager.setEnableCritical(false); menuBar.setEnableRecentFileMenuItems(false); } /** * set uptodate state * */ public void setUptoDate(boolean flag) { this.uptodate = flag; } /** * ask view to allow user input */ public void unlockUserInput() { commandManager.setEnableCritical(true); menuBar.setEnableRecentFileMenuItems(true); locked = false; } /** * is viewer currently locked? * * @return true, if locked */ public boolean isLocked() { return locked; } /** * ask view to rescan itself. This is method is wrapped into a runnable object * and put in the swing event queue to avoid concurrent modifications. * * @param what what should be updated? Possible values: Director.ALL or Director.TITLE */ public void updateView(String what) { this.uptodate = false; if (what.equals(IDirector.ALL)) { if (ignoreNextUpdateAll) ignoreNextUpdateAll = false; else groupsPanel.syncDocumentToPanel(); } statusBar.setText2(String.format("Samples=%d Groups=%d", groupsPanel.getNumberOfSamples(), groupsPanel.getNumberOfGroups())); commandManager.updateEnableState(); this.setTitle(); this.uptodate = true; } /** * set the title of the window */ private void setTitle() { String newTitle = "Sample Groups - " + this.dir.getDocument().getTitle(); /* if (dir.getDocument().isDirty()) newTitle += "*"; */ if (this.dir.getID() == 1) newTitle += " - " + ProgramProperties.getProgramVersion(); else newTitle += " - [" + this.dir.getID() + "] - " + ProgramProperties.getProgramVersion(); if (!this.frame.getTitle().equals(newTitle)) { this.frame.setTitle(newTitle); ProjectManager.updateWindowMenus(); } } /** * gets the associated command manager * * @return command manager */ public CommandManager getCommandManager() { return commandManager; } /** * Print the graph associated with this viewer. * * @param gc0 the graphics context. * @param format page format * @param pagenumber page index */ public int print(Graphics gc0, PageFormat format, int pagenumber) { if (pagenumber == 0) { Graphics2D gc = ((Graphics2D) gc0); Dimension dim = frame.getContentPane().getSize(); int image_w = dim.width; int image_h = dim.height; double paper_x = format.getImageableX() + 1; double paper_y = format.getImageableY() + 1; double paper_w = format.getImageableWidth() - 2; double paper_h = format.getImageableHeight() - 2; double scale_x = paper_w / image_w; double scale_y = paper_h / image_h; double scale = Math.min(scale_x, scale_y); double shift_x = paper_x + (paper_w - scale * image_w) / 2.0; double shift_y = paper_y + (paper_h - scale * image_h) / 2.0; gc.translate(shift_x, shift_y); gc.scale(scale, scale); gc.setStroke(new BasicStroke(1.0f)); gc.setColor(Color.BLACK); frame.getContentPane().paint(gc); return Printable.PAGE_EXISTS; } else return Printable.NO_SUCH_PAGE; } public void setIgnoreNextUpdateAll(boolean ignoreNextUpdateAll) { this.ignoreNextUpdateAll = ignoreNextUpdateAll; } /** * get name for this type of viewer * * @return name */ public String getClassName() { return "AttributesWindow"; } public GroupsPanel getGroupsPanel() { return groupsPanel; } public void selectFromPrevious(Collection<String> previous) { getGroupsPanel().selectSamples(previous, true); ignoreNextUpdateAll = true; // update would clobber selection } }
10,310
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
GroupsPanel.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/groups/GroupsPanel.java
/* * GroupsPanel.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.groups; import jloda.swing.director.IDirectableViewer; import jloda.swing.director.IDirector; import jloda.swing.util.ActionJList; import jloda.swing.util.ProgramProperties; import jloda.util.NumberUtils; import jloda.util.Pair; import megan.core.Document; import javax.swing.*; import javax.swing.border.Border; import javax.swing.border.LineBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.*; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.List; import java.util.*; /** * List of groups * Created by huson on 8/7/14. */ public class GroupsPanel extends JPanel { private final Document document; private final IDirectableViewer viewer; private final ActionJList<Group> jList; private final DefaultListModel<Group> listModel; private final static String NOT_GROUPED = "Ungrouped"; private IGroupsChangedListener groupsChangedListener; private final static Color panelBackgroundColor = UIManager.getColor("Panel.background"); private final static Color backgroundColor = new Color(230, 230, 230); private boolean inSelectSamples = false; // prevents bouncing while selecting private int numberOfGroups = 0; /** * constructor * */ public GroupsPanel(Document document, IDirectableViewer viewer) { super(new BorderLayout()); super.setBorder(BorderFactory.createTitledBorder("Groups")); this.document = document; this.viewer = viewer; listModel = new DefaultListModel<>(); jList = new ActionJList<>(listModel); add(new JScrollPane(jList), BorderLayout.CENTER); jList.setCellRenderer(new MyCellRenderer()); jList.setTransferHandler(new GroupTransferHandler(jList)); jList.setDropMode(DropMode.INSERT); jList.setDragEnabled(true); MySelectionListener mySelectionListener = new MySelectionListener(); jList.getSelectionModel().addListSelectionListener(mySelectionListener); jList.addMouseListener(new MyMouseListener()); syncDocumentToPanel(); } /** * sync document to list */ public void syncDocumentToPanel() { ArrayList<Group> list = new ArrayList(document.getNumberOfSamples()); String[] names = document.getSampleNamesAsArray(); Set<String> groups = new HashSet<>(); for (String name : names) { String groupId = document.getSampleAttributeTable().getGroupId(name); if (groupId == null) groupId = NOT_GROUPED; else groups.add(groupId); list.add(new Group(groupId, name)); } numberOfGroups = groups.size(); java.util.Collections.sort(list); listModel.clear(); String previousId = ""; for (Group group : list) { if (!previousId.equals(group.getGroupId())) listModel.addElement(new Group(group.getGroupId())); // add separator listModel.addElement(group); previousId = group.getGroupId(); } if (!Objects.equals(previousId, NOT_GROUPED)) listModel.addElement(new Group(NOT_GROUPED)); // add separator for ungrouped updateGroupSizes(); } /** * sync current state of list to document */ private void syncListToDocument() { updateGroupSizes(); String groupId = null; for (int i = 0; i < listModel.getSize(); i++) { Group group = listModel.elementAt(i); if (group.isGroupHeader()) { groupId = group.getGroupId(); if (Objects.equals(groupId, NOT_GROUPED)) groupId = null; } else { document.getSampleAttributeTable().putGroupId(group.getSampleName(), groupId); } } if (groupsChangedListener != null) groupsChangedListener.changed(); } /** * updates the group size */ private void updateGroupSizes() { int ungroupedCount = 0; Group currentGroup = null; int count = 0; for (int i = 0; i < listModel.getSize(); i++) { Group group = listModel.getElementAt(i); if (group.isGroupHeader()) { if (currentGroup == null) ungroupedCount = count; else { if (Objects.equals(currentGroup.getGroupId(), NOT_GROUPED)) currentGroup.setSize(count + ungroupedCount); else currentGroup.setSize(count); } count = 0; currentGroup = group; } else count++; } if (count > 0 && currentGroup != null) { if (Objects.equals(currentGroup.getGroupId(), NOT_GROUPED)) currentGroup.setSize(count + ungroupedCount); else currentGroup.setSize(count); } } public void selectAll() { if (!inSelectSamples) { inSelectSamples = true; try { for (int i = 0; i < listModel.getSize(); i++) { jList.setSelectionInterval(i, i); } } finally { inSelectSamples = false; } } } public void selectNone() { if (!inSelectSamples) { inSelectSamples = true; jList.clearSelection(); inSelectSamples = false; } } /** * returns two selected group ids, if exactly two are selected, else null * * @return two selected groups or null */ public Pair<String, String> getTwoSelectedGroups() { String firstId = null; int firstCount = 0; boolean groupHeader1 = false; String secondId = null; int secondCount = 0; boolean groupHeader2 = false; for (Group group : jList.getSelectedValuesList()) { if (Objects.equals(group.getGroupId(), NOT_GROUPED)) return null; if (firstId == null) { firstId = group.getGroupId(); firstCount++; if (group.isGroupHeader()) groupHeader1 = true; } else if (group.getGroupId().equals(firstId)) { firstCount++; if (group.isGroupHeader()) groupHeader1 = true; } else if (secondId == null) { secondId = group.getGroupId(); secondCount++; if (group.isGroupHeader()) groupHeader2 = true; } else if (group.getGroupId().equals(secondId)) { secondCount++; if (group.isGroupHeader()) groupHeader2 = true; } else // a third group is selected return null; } // if group header not selected then all nodes in group must be selected: if (!groupHeader1 || !groupHeader2) { for (int i = 0; i < listModel.getSize(); i++) { Group group = listModel.get(i); if (!groupHeader1 && !group.isGroupHeader() && group.getGroupId().equals(firstId) && !jList.isSelectedIndex(i)) return null; if (!groupHeader2 && !group.isGroupHeader() && group.getGroupId().equals(secondId) && !jList.isSelectedIndex(i)) return null; } } if (firstId != null && secondId != null) return new Pair<>(firstId, secondId); else return null; } class MySelectionListener implements ListSelectionListener { public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting()) { // The mouse button has not yet been released } else { if (!inSelectSamples) { inSelectSamples = true; try { document.getSampleSelection().clear(); document.getSampleSelection().setSelected(getSelectedSamples(), true); if (viewer != null) viewer.updateView(IDirector.ENABLE_STATE); } finally { inSelectSamples = false; } } } } } /** * get all currently selected samples * * @return selected */ public Set<String> getSelectedSamples() { Set<String> selected = new HashSet<>(); for (Group group : jList.getSelectedValuesList()) if (!group.isGroupHeader()) selected.add(group.getSampleName()); return selected; } /** * replace the selection state of the named samples * */ public void selectSamples(Collection<String> samples, boolean select) { if (!inSelectSamples) { inSelectSamples = true; try { BitSet toSelect = new BitSet(); for (int i = 0; i < listModel.getSize(); i++) { Group group = listModel.get(i); if (!group.isGroupHeader()) { boolean contained = samples.contains(group.getSampleName()); if (contained && select || !contained && jList.isSelectedIndex(i)) toSelect.set(i); } } jList.clearSelection(); for (int i = toSelect.nextSetBit(0); i != -1; i = toSelect.nextSetBit(i + 1)) { jList.addSelectionInterval(i, i); } } finally { inSelectSamples = false; } } } public int getNumberOfSamples() { return document.getNumberOfSamples(); } public int getNumberOfGroups() { return numberOfGroups; } class MyMouseListener extends MouseAdapter { public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { showPopupMenu(e); } } public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { showPopupMenu(e); } } @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { // double click on a group header selects that group int index = jList.locationToIndex(e.getPoint()); if (index != -1) { final Group groupHeader = listModel.get(index); if (groupHeader.isGroupHeader()) { for (int i = 0; i < listModel.getSize(); i++) { if (i != index) { final Group group = listModel.get(i); if (!group.isGroupHeader() && group.getGroupId().equals(groupHeader.getGroupId())) { jList.addSelectionInterval(i, i); } } } } } } } } private void showPopupMenu(final MouseEvent e) { final int index = jList.locationToIndex(e.getPoint()); //select the item final Group group = listModel.getElementAt(index); if (group.isGroupHeader()) { JPopupMenu menu = new JPopupMenu(); AbstractAction selectGroupAction = new AbstractAction("Select Group") { @Override public void actionPerformed(ActionEvent e) { for (int i = 0; i < listModel.getSize(); i++) { Group aGroup = listModel.elementAt(i); if (!aGroup.isGroupHeader() && aGroup.getGroupId().equals(group.getGroupId())) jList.addSelectionInterval(i, i); } jList.removeSelectionInterval(index, index); } }; selectGroupAction.setEnabled(group.isGroupHeader()); menu.add(selectGroupAction); menu.addSeparator(); { AbstractAction deleteAction = new AbstractAction("Delete Group" + (!Objects.equals(group.getGroupId(), NOT_GROUPED) ? " " + group.getGroupId() : "")) { @Override public void actionPerformed(ActionEvent e) { listModel.remove(index); syncListToDocument(); } }; deleteAction.setEnabled(!Objects.equals(group.getGroupId(), NOT_GROUPED)); menu.add(deleteAction); } AbstractAction newAction = new AbstractAction("Add New Group") { @Override public void actionPerformed(ActionEvent e) { addNewGroup(index); } }; menu.add(newAction); menu.show(e.getComponent(), e.getX(), e.getY()); } } /** * add a new group * */ public void addNewGroup(int index) { if (index == -1) index = listModel.getSize(); BitSet used = new BitSet(); int insertHere = 0; for (int i = 0; i < listModel.getSize(); i++) { Group group = listModel.elementAt(i); if (group.isGroupHeader() && !Objects.equals(group.getGroupId(), NOT_GROUPED)) { if (NumberUtils.isInteger(group.getGroupId())) used.set((NumberUtils.parseInt(group.getGroupId()))); } if (Objects.equals(group.getGroupId(), NOT_GROUPED)) insertHere = i; } if (index + 1 < insertHere) insertHere = index + 1; listModel.insertElementAt(new Group("" + used.nextClearBit(1)), insertHere); jList.removeSelectionInterval(index, index); syncListToDocument(); } /** * cell renderer */ static class MyCellRenderer implements ListCellRenderer<Group> { private final JPanel p = new JPanel(new BorderLayout()); private final JLabel label = new JLabel("", JLabel.CENTER); private final LineBorder selectedBorder = (LineBorder) BorderFactory.createLineBorder(ProgramProperties.SELECTION_COLOR_DARKER); private final Border raisedBorder = BorderFactory.createRaisedBevelBorder(); MyCellRenderer() { label.setOpaque(true); } @Override public Component getListCellRendererComponent(JList<? extends Group> list, Group value, int index, boolean isSelected, boolean cellHasFocus) { // icon.setIcon(value.icon); if (value.isGroupHeader()) { String groupId = value.getGroupId(); if (!Objects.equals(groupId, NOT_GROUPED)) { label.setText("Group " + value.getGroupId() + ":"); p.setToolTipText("Group " + value.getGroupId() + ", size: " + value.getSize()); } else { label.setText("Not grouped:"); p.setToolTipText("Not grouped: " + value.getSize()); } p.setBorder(raisedBorder); p.setBackground(isSelected ? ProgramProperties.SELECTION_COLOR : panelBackgroundColor); label.setBackground(isSelected ? ProgramProperties.SELECTION_COLOR : panelBackgroundColor); label.setBorder(isSelected ? selectedBorder : null); } else { p.setToolTipText("Sample: " + value.getSampleName()); label.setText(value.getSampleName()); p.setBorder(isSelected ? selectedBorder : null); p.setBackground(isSelected ? ProgramProperties.SELECTION_COLOR : backgroundColor); label.setBackground(isSelected ? ProgramProperties.SELECTION_COLOR : backgroundColor); label.setBorder(null); } p.add(label, BorderLayout.SOUTH); return p; } } /** * get listener for groups changed events * */ public IGroupsChangedListener getGroupsChangedListener() { return groupsChangedListener; } /** * set listener for groups changed events * */ public void setGroupsChangedListener(IGroupsChangedListener groupsChangedListener) { this.groupsChangedListener = groupsChangedListener; } /** * groups changed listener interface */ interface IGroupsChangedListener { void changed(); } public class GroupTransferHandler extends TransferHandler { private final JList list; private final Set<Group> selected = new HashSet<>(); public GroupTransferHandler(JList list) { this.list = list; } @Override public boolean canImport(TransferSupport support) { boolean canImport = false; if (support.isDataFlavorSupported(GroupTransferable.GROUP_DATA_FLAVOR)) { JList.DropLocation dl = (JList.DropLocation) support.getDropLocation(); if (dl.getIndex() != -1) { canImport = true; } } return canImport; } @Override protected void exportDone(JComponent source, Transferable data, int action) { try { List<Group> dropped = (List) data.getTransferData(GroupTransferable.GROUP_DATA_FLAVOR); for (Group group : dropped) { ((DefaultListModel<Group>) list.getModel()).removeElement(group); } for (Group group : selected) { int index = listModel.indexOf(group); if (index != -1) jList.addSelectionInterval(index, index); } selected.clear(); syncListToDocument(); } catch (Exception ex) { ex.printStackTrace(); } } @Override public boolean importData(TransferSupport support) { boolean accepted = false; if (support.isDrop()) { if (support.isDataFlavorSupported(GroupTransferable.GROUP_DATA_FLAVOR)) { JList.DropLocation dl = (JList.DropLocation) support.getDropLocation(); DefaultListModel<Group> model = (DefaultListModel<Group>) list.getModel(); int index = dl.getIndex(); boolean insert = dl.isInsert(); Transferable t = support.getTransferable(); try { List<Group> dropped = (List) t.getTransferData(GroupTransferable.GROUP_DATA_FLAVOR); selected.addAll(dropped); for (Group group : dropped) { if (insert) { if (index >= model.getSize()) { model.addElement(group); } else { if (model.removeElement(group)) model.add(index, group); // this is wierd model.add(index, group); } } else { model.addElement(group); } } accepted = true; } catch (Exception e) { e.printStackTrace(); } } } return accepted; } @Override public int getSourceActions(JComponent c) { return COPY_OR_MOVE; } @Override protected Transferable createTransferable(JComponent c) { return new GroupTransferable(list.getSelectedValuesList()); } } public static class GroupTransferable implements Transferable { static final DataFlavor GROUP_DATA_FLAVOR = new DataFlavor(Group.class, "GroupList"); private final List<Group> groups; public GroupTransferable(List<Group> groups) { this.groups = new ArrayList<>(groups.size()); Stack<Group> stack = new Stack<>(); stack.addAll(groups); while (stack.size() > 0) this.groups.add(stack.pop()); // in reverse order } @Override public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[]{GROUP_DATA_FLAVOR}; } @Override public boolean isDataFlavorSupported(DataFlavor flavor) { return GROUP_DATA_FLAVOR.equals(flavor); } @Override public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException { Object value; if (GROUP_DATA_FLAVOR.equals(flavor)) { value = groups; } else { throw new UnsupportedFlavorException(flavor); } return value; } } } class Group implements Comparable<Group> { private final String groupId; private int size; private final String name; public Group(String groupId) { this.groupId = groupId; this.name = null; } public Group(String groupId, String name) { this.groupId = groupId; this.name = name; } public String toString() { return name; } public String getGroupId() { return groupId; } public String getSampleName() { return name; } public boolean isGroupHeader() { return name == null; } public int compareTo(Group b) { int v = this.getGroupId().compareTo(b.getGroupId()); if (v == 0) { v = this.getSampleName().compareTo(b.getSampleName()); } return v; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } }
23,328
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
GUIConfiguration.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/groups/GUIConfiguration.java
/* * GUIConfiguration.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.groups; import jloda.swing.window.MenuConfiguration; import megan.chart.data.ChartCommandHelper; import megan.classification.data.ClassificationCommandHelper; /** * configuration for menu and toolbar * Daniel Huson, 7.2010 */ class GUIConfiguration { /** * get the menu configuration * * @return menu configuration */ public static MenuConfiguration getMenuConfiguration() { MenuConfiguration menuConfig = new MenuConfiguration(); menuConfig.defineMenuBar("File;Edit;Window;Help;"); menuConfig.defineMenu("File", "New...;|;Open...;@Open Recent;|;Open From Server...;|;Compare...;|;Import From BLAST...;@Import;Meganize DAA File...;|;Export Image...;Export Legend...;|;Page Setup...;Print...;|Close;|;Quit;"); menuConfig.defineMenu("Open Recent", ";"); menuConfig.defineMenu("Import", "Import Text (CSV) Format...;Import BIOM Format...;|;Import Metadata...;"); menuConfig.defineMenu("Edit", "Cut;Copy;Paste;|;Find...;Find Again;|;Select All;Select None;|;From Previous Window;|;Add New Group;"); // menuConfig.defineMenu("Options", "Taxonomy Contrasts...;|;SEED Contrasts...;EGGNOG Contrasts...;KEGG Contrasts...;"); menuConfig.defineMenu("Window", "Close All Other Windows...;|;Reset Window Location;Set Window Size...;|;Message Window...;|;" + "Inspector Window...;|;Main Viewer...;" + ClassificationCommandHelper.getOpenViewerMenuString() + "|;Samples Viewer...;|;" + ChartCommandHelper.getOpenChartMenuString() + "|;Chart Microbial Attributes...;|;"); menuConfig.defineMenu("Help", "About...;How to Cite...;|;Community Website...;Reference Manual...;|;Check For Updates...;"); return menuConfig; } /** * gets the toolbar configuration * * @return toolbar configuration */ public static String getToolBarConfiguration() { return "Open...;Print...;Export Image...;|;Find...;|;Main Viewer...;" + ClassificationCommandHelper.getOpenViewerMenuString() + "|;Samples Viewer...;|;Add New Group;"; } }
2,918
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/groups/commands/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.groups.commands; 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.InputEvent; import java.awt.event.KeyEvent; /** * * selection command * * Daniel Huson, 8.2014 */ 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 samples=none;"); } public boolean isApplicable() { return true; } public String getName() { return "Select None"; } public String getDescription() { return "Deselect samples"; } 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() | InputEvent.SHIFT_DOWN_MASK); } }
2,132
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
AddNewGroupCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/groups/commands/AddNewGroupCommand.java
/* * AddNewGroupCommand.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.groups.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.groups.GroupsViewer; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; /** * * selection command * * Daniel Huson, 8.2014 */ public class AddNewGroupCommand extends CommandBase implements ICommand { public String getSyntax() { return "add group"; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase(getSyntax()); if (getViewer() instanceof GroupsViewer) { GroupsViewer viewer = (GroupsViewer) getViewer(); viewer.getGroupsPanel().addNewGroup(-1); } } public void actionPerformed(ActionEvent event) { executeImmediately(getSyntax()); } public boolean isApplicable() { return true; } public String getName() { return "Add New Group"; } public String getDescription() { return "Add a new group"; } public ImageIcon getIcon() { return ResourceManager.getIcon("NewGroup16.gif"); } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_G, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()); } }
2,350
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SelectAllCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/groups/commands/SelectAllCommand.java
/* * SelectAllCommand.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.groups.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.groups.GroupsViewer; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; /** * * selection command * * Daniel Huson, 8.2014 */ public class SelectAllCommand extends CommandBase implements ICommand { public String getSyntax() { return "select samples={all|none|invert}"; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("select samples="); String what = np.getWordMatchesIgnoringCase("all none"); np.matchRespectCase(";"); if (getViewer() instanceof GroupsViewer) { GroupsViewer viewer = (GroupsViewer) getViewer(); if (what.equalsIgnoreCase("all")) viewer.getGroupsPanel().selectAll(); else if (what.equals("none")) viewer.getGroupsPanel().selectNone(); } } public void actionPerformed(ActionEvent event) { execute("select samples=all;"); } public boolean isApplicable() { return true; } public String getName() { return "Select All"; } public String getDescription() { return "Select samples"; } 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()); } }
2,608
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ComputeContrastsCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/groups/commands/ComputeContrastsCommand.java
/* * ComputeContrastsCommand.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.groups.commands; import contrasts.Contrasts; import jloda.graph.Graph; import jloda.graph.Node; import jloda.graph.NodeData; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ProgramProperties; import jloda.util.Basic; import jloda.util.Pair; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.classification.Classification; import megan.classification.ClassificationManager; import megan.core.Director; import megan.core.Document; import megan.data.IName2IdMap; import megan.groups.GroupsViewer; import megan.viewer.ClassificationViewer; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.List; import java.util.*; /** * * compute contrasts command * * Daniel Huson, 8.2014 */ public class ComputeContrastsCommand extends CommandBase implements ICommand { public String getSyntax() { return "compute contrasts data={" + StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), ",") + "}"; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("compute contrasts data="); final String viewerName = np.getWordMatchesIgnoringCase(StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), " ")); np.matchIgnoreCase(";"); if (getViewer() instanceof GroupsViewer) { final GroupsViewer viewer = (GroupsViewer) getViewer(); final Document doc = viewer.getDir().getDocument(); final Pair<String, String> twoGroupIds = viewer.getGroupsPanel().getTwoSelectedGroups(); if (twoGroupIds != null) { ArrayList<String> first = new ArrayList<>(); for (String sample : doc.getSampleNames()) { if (doc.getSampleAttributeTable().getGroupId(sample).equals(twoGroupIds.getFirst())) first.add(sample); } ArrayList<String> second = new ArrayList<>(); for (String sample : doc.getSampleNames()) { if (doc.getSampleAttributeTable().getGroupId(sample).equals(twoGroupIds.getSecond())) second.add(sample); } final String[] samples = doc.getSampleNamesAsArray(); if (first.size() > 0 && second.size() > 0) { // compute data map for contrasts: Map<String, Map<String, Double>> data = new HashMap<>(); int numberOfNodes = 0; final IName2IdMap name2IdMap; final ClassificationViewer classificationViewer = (ClassificationViewer) ((Director) getDir()).getViewerByClassName(viewerName); final Graph graph = classificationViewer.getGraph(); name2IdMap = classificationViewer.getClassification().getName2IdMap(); for (Node v = graph.getFirstNode(); v != null; v = graph.getNextNode(v)) { int classId = (Integer) v.getInfo(); if (classId > 0) { NodeData nd = (NodeData) v.getData(); for (int t = 0; t < samples.length; t++) { String sample = samples[t]; Map<String, Double> classId2Counts = data.computeIfAbsent(sample, k -> new HashMap<>()); classId2Counts.put(name2IdMap.get(classId), (double) (v.getOutDegree() > 0 ? nd.getAssigned()[t] : nd.getSummarized()[t])); } numberOfNodes++; } } final Contrasts contrasts = new Contrasts(); try { Basic.hideSystemErr(); contrasts.apply(data); } finally { Basic.restoreSystemErr(); } executeImmediately("show window=message;"); System.out.println("\nContrasts for " + viewerName + " assignments on " + numberOfNodes + " nodes:"); System.out.println("Group " + twoGroupIds.getFirst() + ": " + StringUtils.toString(first, ",")); System.out.println("Group " + twoGroupIds.getSecond() + ": " + StringUtils.toString(second, ",")); System.out.println("Results for group " + twoGroupIds.getFirst() + " vs group " + twoGroupIds.getSecond() + ":"); Map<String, Double> results = contrasts.getSplitScores(first.toArray(new String[0]), second.toArray(new String[0])); SortedSet<Pair<Double, String>> sorted = new TreeSet<>(); System.out.printf("%-20s\tScore%n", viewerName); for (String taxon : results.keySet()) { double value = results.get(taxon); // clamp to range -1 1 if (value < -1) value = -1; else if (value > 1) value = 1; sorted.add(new Pair<>(-value, taxon)); // negative sign to sort from high to low... } System.out.println("Number of results: " + sorted.size()); System.out.println("--------------------------------------"); for (Pair<Double, String> pair : sorted) { if ((-pair.getFirst()) >= 0) System.out.printf("%-20s\t %1.4f%n", pair.getSecond(), (-pair.getFirst())); else System.out.printf("%-20s\t%1.4f%n", pair.getSecond(), (-pair.getFirst())); } System.out.println("--------------------------------------"); } } viewer.setIgnoreNextUpdateAll(true); // this prevents loss of selection } } public void actionPerformed(ActionEvent event) { List<String> openViewers = new ArrayList<>(); for (String name : ClassificationManager.getAllSupportedClassifications()) { if (((Director) getDir()).getViewerByClassName(name) != null) openViewers.add(name); } if (!openViewers.contains(Classification.Taxonomy)) openViewers.add(Classification.Taxonomy); if (openViewers.size() == 1) { execute("compute contrasts data=" + openViewers.get(0) + ";"); } else if (openViewers.size() > 1) { String[] choices = openViewers.toArray(new String[0]); String result = (String) JOptionPane.showInputDialog(getViewer().getFrame(), "Choose viewer", "Choose viewer", JOptionPane.PLAIN_MESSAGE, ProgramProperties.getProgramIcon(), choices, choices[0]); if (result != null) execute("compute contrasts data=" + result + ";"); } } public boolean isApplicable() { return (getViewer() instanceof GroupsViewer) && (((GroupsViewer) getViewer()).getGroupsPanel().getTwoSelectedGroups() != null); } public String getName() { return "Compute Contrasts..."; } public String getDescription() { return "Computes contrasts on two selected groups"; } public ImageIcon getIcon() { return null; } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_R, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()); } }
8,327
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
BlastService.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/blastclient/BlastService.java
/* * BlastService.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.blastclient; import javafx.concurrent.Service; import javafx.concurrent.Task; import jloda.util.Pair; import java.util.Collection; import java.util.Collections; /** * blast service * Created by huson on 1/18/17. */ public class BlastService extends Service<String> { private Collection<Pair<String, String>> queries; private RemoteBlastClient.BlastProgram program; private String database; @Override protected Task<String> createTask() { return new Task<>() { @Override protected String call() throws Exception { final RemoteBlastClient remoteBlastClient = new RemoteBlastClient(); remoteBlastClient.setDatabase(getDatabase()); remoteBlastClient.setProgram(getProgram()); updateMessage("Contacting NCBI..."); remoteBlastClient.startRemoteSearch(getQueries()); long estimatedTime = 2000L * remoteBlastClient.getEstimatedTime(); // double... final long startTime = System.currentTimeMillis(); updateProgress(0, estimatedTime); updateMessage("Request id: " + remoteBlastClient.getRequestId() + "\nEstimated time: " + (estimatedTime / 1100) + "s\nSearching...\n"); RemoteBlastClient.Status status = null; do { if (status != null) { Thread.sleep(5000); } status = remoteBlastClient.getRemoteStatus(); final long time = System.currentTimeMillis() - startTime; while (0.9 * time > estimatedTime) estimatedTime *= 1.2; updateProgress(time, estimatedTime); if (isCancelled()) { break; } } while (status == RemoteBlastClient.Status.searching); updateMessage("Search completed"); final StringBuilder buf = new StringBuilder(); switch (status) { case hitsFound: for (String line : remoteBlastClient.getRemoteAlignments()) { buf.append(line).append("\n"); } break; case noHitsFound: updateMessage("No hits found"); break; case failed: updateMessage("Failed"); System.err.println("Remote BLAST failed. Lookup details for RID=" + remoteBlastClient.getRequestId() + " on NCBI BLAST website https://blast.ncbi.nlm.nih.gov"); break; default: updateMessage("Status: " + status); } return buf.toString(); } }; } private Collection<Pair<String, String>> getQueries() { return queries; } public void setQueries(Collection<Pair<String, String>> queries) { this.queries = queries; } public void setQuery(String name, String sequence) { setQueries(Collections.singletonList(new Pair<>(name, sequence))); } private RemoteBlastClient.BlastProgram getProgram() { return program; } public void setProgram(RemoteBlastClient.BlastProgram program) { this.program = program; } private String getDatabase() { return database; } public void setDatabase(String database) { this.database = database; } }
4,440
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
BlastProgram.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/blastclient/BlastProgram.java
/* * BlastProgram.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.blastclient; import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.text.Font; import javafx.stage.Stage; /** * simple Blast GUI * Created by huson on 1/18/17. */ public class BlastProgram extends Application { @Override public void start(Stage primaryStage) { final TextField queryField = new TextField(); queryField.setFont(Font.font("Courier New")); queryField.setPromptText("Query"); queryField.setPrefColumnCount(80); final ChoiceBox<String> programChoice = new ChoiceBox<>(); programChoice.setMinWidth(100); final ChoiceBox<String> databaseChoice = new ChoiceBox<>(); databaseChoice.setMinWidth(100); programChoice.setOnAction(e -> { databaseChoice.getItems().setAll(RemoteBlastClient.getDatabaseNames( RemoteBlastClient.BlastProgram.valueOf(programChoice.getValue()))); databaseChoice.getSelectionModel().select(databaseChoice.getItems().get(0)); }); for (RemoteBlastClient.BlastProgram program : RemoteBlastClient.BlastProgram.values()) { programChoice.getItems().add(program.toString()); } programChoice.getSelectionModel().select(RemoteBlastClient.BlastProgram.blastx.toString()); final HBox topPane = new HBox(); topPane.setSpacing(5); topPane.getChildren().addAll(new VBox(new Label("Query:"), queryField), new VBox(new Label("Program:"), programChoice), new VBox(new Label("Database:"), databaseChoice)); final TextArea alignmentArea = new TextArea(); alignmentArea.setFont(Font.font("Courier New")); alignmentArea.setPromptText("Enter a query and then press Apply to compute alignments"); alignmentArea.setEditable(false); final ProgressBar progressBar = new ProgressBar(); progressBar.setVisible(false); final Button loadExampleButton = new Button("Load Example"); loadExampleButton.setOnAction(e -> queryField.setText("TAATTAGCCATAAAGAAAAACTGGCGCTGGAGAAAGATATTCTCTGGAGCGTCGGGCGAGCGATAATTCAGCTGATTATTGTCGGCTATGTGCTGAAGTAT")); loadExampleButton.disableProperty().bind(queryField.textProperty().isNotEmpty()); final Button cancelButton = new Button("Cancel"); final Button applyButton = new Button("Apply"); final ButtonBar bottomBar = new ButtonBar(); bottomBar.getButtons().addAll(progressBar, loadExampleButton, new Label(" "), cancelButton, applyButton); final BorderPane root = new BorderPane(); root.setTop(topPane); root.setCenter(alignmentArea); root.setBottom(bottomBar); root.setPadding(new Insets(5, 5, 5, 5)); final BlastService blastService = new BlastService(); blastService.messageProperty().addListener((observable, oldValue, newValue) -> alignmentArea.setText(alignmentArea.getText() + newValue + "\n")); blastService.setOnScheduled(e -> { progressBar.setVisible(true); progressBar.progressProperty().bind(blastService.progressProperty()); alignmentArea.clear(); }); blastService.setOnSucceeded(e -> { if (blastService.getValue().length() > 0) alignmentArea.setText(blastService.getValue()); else alignmentArea.setText(alignmentArea.getText() + "*** No hits found ***\n"); progressBar.progressProperty().unbind(); progressBar.setVisible(false); }); blastService.setOnCancelled(e -> { progressBar.progressProperty().unbind(); alignmentArea.setText(alignmentArea.getText() + "*** Canceled ***\n"); progressBar.setVisible(false); }); blastService.setOnFailed(e -> { progressBar.progressProperty().unbind(); alignmentArea.setText(alignmentArea.getText() + "*** Failed ***\n"); progressBar.setVisible(false); }); queryField.disableProperty().bind(blastService.runningProperty()); cancelButton.setOnAction(e -> blastService.cancel()); cancelButton.disableProperty().bind(blastService.runningProperty().not()); applyButton.setOnAction(e -> { blastService.setProgram(RemoteBlastClient.BlastProgram.valueOf(programChoice.getValue())); blastService.setDatabase(databaseChoice.getValue()); blastService.setQuery("read", queryField.getText()); blastService.restart(); }); applyButton.disableProperty().bind(queryField.textProperty().isEmpty().or(blastService.runningProperty())); Scene scene = new Scene(root, 800, 600); primaryStage.setScene(scene); primaryStage.setTitle("NCBI Blast Client"); primaryStage.show(); } }
5,832
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
RemoteBlastClient.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/blastclient/RemoteBlastClient.java
/* * RemoteBlastClient.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.blastclient; import jloda.util.Pair; import jloda.util.StringUtils; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.*; /** * Remotely blast sequences using the NCBI web service * Author: Daniel Huson 1/11/17. */ public class RemoteBlastClient { public enum BlastProgram { blastn, blastx, blastp; // blastn, blastx, blastp, megablast, discomegablast, rpsblast, tblastn, tblastx; // todo: these don't appear to work public static BlastProgram valueOfIgnoreCase(String name) { for (BlastProgram blastProgram : values()) { if (blastProgram.toString().equalsIgnoreCase(name)) return blastProgram; } return null; } } public enum Status {stopped, searching, hitsFound, noHitsFound, failed, unknown} private static final boolean verbose = false; private final static String baseURL = "https://blast.ncbi.nlm.nih.gov/blast/Blast.cgi"; private BlastProgram program; private String database; // make sure you use a correct database name. If the database does not exist, then this will // not cause an error, but no alignments will be found private String requestId; private int estimatedTime; private int actualTime; private long startTime; /** * constructor */ public RemoteBlastClient() { program = BlastProgram.blastx; database = "nr"; requestId = null; estimatedTime = -1; actualTime = -1; startTime = -1; } /** * launch the search * */ public void startRemoteSearch(Collection<Pair<String, String>> queries) throws IOException { if (queries.size() == 0) return; final StringBuilder query = new StringBuilder(); for (Pair<String, String> pair : queries) { query.append(">").append(StringUtils.swallowLeadingGreaterSign(pair.getFirst().trim())).append("\n").append(pair.getSecond().trim()).append("\n"); } requestId = null; estimatedTime = -1; actualTime = -1; startTime = System.currentTimeMillis(); final Map<String, Object> params = new HashMap<>(); params.put("CMD", "Put"); params.put("PROGRAM", program.toString()); params.put("DATABASE", database); params.put("QUERY", query.toString()); final String response = postRequest(baseURL, params); requestId = parseRequestId(response); if (requestId == null) throw new IOException("Failed to obtain valid requestId"); estimatedTime = parseEstimatedTime(response); } /** * request the current status * * @return status */ public Status getRemoteStatus() { if (requestId == null) return Status.failed; try { final Map<String, Object> params = new HashMap<>(); params.put("CMD", "Get"); params.put("FORMAT_OBJECT", "SearchInfo"); params.put("RID", requestId); final String response = getRequest(baseURL, params); Status status = Status.unknown; boolean thereAreNoHits = false; boolean thereAreHits = false; for (String aLine : getLinesBetween(response, "QBlastInfoBegin", "QBlastInfoEnd")) { if (aLine.contains("Status=")) { switch (aLine.replaceAll("Status=", "").trim()) { case "WAITING" -> status = Status.searching; case "FAILED" -> status = Status.failed; case "READY" -> { actualTime = (int) ((System.currentTimeMillis() - startTime) / 1000); status = Status.hitsFound; // will check whether hits really found } case "UNKNOWN" -> status = Status.unknown; } } else if (aLine.contains("ThereAreHits=no")) thereAreNoHits = true; else if (aLine.contains("ThereAreHits=yes")) thereAreHits = true; } if (status == Status.hitsFound && thereAreNoHits) status = Status.noHitsFound; if (status == Status.hitsFound && !thereAreHits) status = Status.failed; return status; } catch (IOException e) { e.printStackTrace(); return Status.unknown; } } /** * request the alignments * * @return gets the alignments */ public String[] getRemoteAlignments() { try { final Map<String, Object> params = new HashMap<>(); params.put("CMD", "Get"); params.put("FORMAT_TYPE", "Text"); params.put("RID", requestId); return getLinesBetween(getRequest(baseURL, params), "<PRE>", null); } catch (IOException e) { e.printStackTrace(); return null; } } /** * get the blast program * * @return blast program */ public BlastProgram getProgram() { return program; } /** * set the blast program * */ public void setProgram(BlastProgram program) { this.program = program; } /** * get the database * * @return database */ public String getDatabase() { return database; } /** * set the database * */ public void setDatabase(String database) { this.database = database; } /** * get estimated time in seconds * * @return time or -1 */ public int getEstimatedTime() { return estimatedTime; } public int getActualTime() { return actualTime; } public String getRequestId() { return requestId; } /** * get the request id from a response text * * @return request id or null */ private static String parseRequestId(String response) { for (String aLine : getLinesBetween(response, "QBlastInfoBegin", "QBlastInfoEnd")) { if (aLine.contains(" RID = ")) { return aLine.replaceAll(" RID = ", "").trim(); } } return null; } /** * get the estimated time * * @return time or -1 */ private static Integer parseEstimatedTime(String response) { for (String aLine : getLinesBetween(response, "QBlastInfoBegin", "QBlastInfoEnd")) { if (aLine.contains(" RTOE = ")) { return Integer.parseInt(aLine.replaceAll(" RTOE = ", "").trim()); } } return -1; } /** * get a delimited set of lines * * @param afterLineEndingOnThis start reporting lines after seeing a line ending on this, or from beginning, if null * @param beforeLineStartingWithThis stop reporting lines upon seeing a line starting on this, or a the end, if null * @return delimited text */ private static String[] getLinesBetween(String text, String afterLineEndingOnThis, String beforeLineStartingWithThis) { final ArrayList<String> lines = new ArrayList<>(); boolean reporting = (afterLineEndingOnThis == null); try (BufferedReader reader = new BufferedReader(new StringReader(text))) { String aLine; while ((aLine = reader.readLine()) != null) { if (reporting) { if (beforeLineStartingWithThis != null && aLine.startsWith(beforeLineStartingWithThis)) reporting = false; else lines.add(aLine); } else if (afterLineEndingOnThis != null && aLine.endsWith(afterLineEndingOnThis)) { reporting = true; } } } catch (Exception e) { e.printStackTrace(); } return lines.toArray(new String[0]); } /** * get request * * @return response */ private static String getRequest(String baseURL, Map<String, Object> parameters) throws IOException { final StringBuilder urlString = new StringBuilder(); urlString.append(baseURL); boolean first = true; for (Map.Entry<String, Object> param : parameters.entrySet()) { if (first) { urlString.append("?"); first = false; } else urlString.append("&"); urlString.append(URLEncoder.encode(param.getKey(), StandardCharsets.UTF_8)); urlString.append('='); urlString.append(URLEncoder.encode(String.valueOf(param.getValue()), StandardCharsets.UTF_8)); } if (verbose) { System.err.println("GET " + baseURL); } final URL url = new URL(urlString.toString()); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", "text/plain"); connection.setRequestProperty("charset", "utf-8"); connection.setDoOutput(true); connection.connect(); final StringBuilder response = new StringBuilder(); try (Reader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) { for (int c; (c = in.read()) >= 0; ) { response.append((char) c); } } if (verbose) System.err.println("Response " + response); return response.toString(); } /** * post request * * @return response */ private static String postRequest(String baseURL, Map<String, Object> parameters) throws IOException { final StringBuilder postData = new StringBuilder(); for (Map.Entry<String, Object> param : parameters.entrySet()) { if (postData.length() != 0) postData.append('&'); postData.append(URLEncoder.encode(param.getKey(), StandardCharsets.UTF_8)); postData.append('='); postData.append(URLEncoder.encode(String.valueOf(param.getValue()), StandardCharsets.UTF_8)); } byte[] postDataBytes = postData.toString().getBytes(StandardCharsets.UTF_8); if (verbose) { System.err.println("POST " + baseURL); System.err.println(postData); } final URL url = new URL(baseURL); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length)); connection.setDoOutput(true); connection.getOutputStream().write(postDataBytes); final StringBuilder response = new StringBuilder(); try (Reader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) { for (int c; (c = in.read()) >= 0; ) { response.append((char) c); } } if (verbose) System.err.println("Response " + response); return response.toString(); } public static String[] getDatabaseNames(String blastProgram) { return getDatabaseNames(Objects.requireNonNull(BlastProgram.valueOfIgnoreCase(blastProgram))); } public static String[] getDatabaseNames(BlastProgram blastProgram) { return switch (blastProgram) { case blastp, blastx -> new String[]{"nr", "refseq_protein", "SMARTBLAST/landmark", "swissprot", "pat", "pdb", "env_nr", "tsa_nr"}; default -> new String[]{"nr", "refseq_rna", "refseq_genomic", "refseq_representative_genomes", "genomic/9606/RefSeqGene", "est", "gss", "htgs", "pat", "pdb", "alu", "dbsts", "chromosome", "Whole_Genome_Shotgun_contigs", "tsa_nt", "rRNA_typestrains/prokaryotic_16S_ribosomal_RNA", "sra"}; }; } }
13,193
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
RemoteBlastDialog.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/blastclient/RemoteBlastDialog.java
/* * RemoteBlastDialog.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.blastclient; import jloda.swing.director.IDirectableViewer; import jloda.swing.util.ChooseFileDialog; import jloda.swing.util.FastaFileFilter; import jloda.swing.window.NotificationsInSwing; import jloda.util.*; import megan.core.Director; import megan.core.MeganFile; import megan.util.IReadsProvider; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Collection; import java.util.Objects; /** * displays a dialog to setup remote blast run on NCBI * Daniel Huson, 3/14/17. */ public class RemoteBlastDialog { /** * displays a configuration screen and sets up the command string * * @param providedReadsFile if not null, we use this file and ignore the readsProvider * @return command string or null */ public static String apply(final IDirectableViewer viewer, Director dir, final IReadsProvider readsProvider, final String providedReadsFile, String queryName) { if (readsProvider == null && providedReadsFile == null) return null; // no reads provided... final MeganFile meganFile = dir.getDocument().getMeganFile(); final String lastDir = (meganFile.isMeganServerFile() ? ProgramProperties.get("RemoteBlastDir", System.getProperty("user.dir")) : new File(meganFile.getFileName()).getParent()); final File lastOpenFile = new File(lastDir, ProgramProperties.get("RemoteBlastFile", FileUtils.replaceFileSuffix(dir.getDocument().getTitle(), "-" + StringUtils.toCleanName(queryName) + ".fasta"))); final boolean needToSaveReads = (providedReadsFile == null); final JDialog dialog = new JDialog(viewer.getFrame(), "Setup Remote NCBI Blast - MEGAN", true); dialog.setLocationRelativeTo(viewer.getFrame()); dialog.setSize(500, 180); dialog.getContentPane().setLayout(new BorderLayout()); final Single<String> result = new Single<>(); final Dimension labelDim = new Dimension(100, 30); final Dimension minLineDim = new Dimension(100, 30); final Dimension maxLineDim = new Dimension(10000, 30); final JPanel topPanel = new JPanel(); topPanel.setBorder(BorderFactory.createEmptyBorder(3, 6, 3, 6)); topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.X_AXIS)); dialog.getContentPane().add(topPanel, BorderLayout.NORTH); final JPanel leftPanel = new JPanel(); leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS)); topPanel.add(leftPanel); final JPanel rightPanel = new JPanel(); rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS)); topPanel.add(rightPanel); final JTextField fileNameField = new JTextField(needToSaveReads ? lastOpenFile.getPath() : providedReadsFile); { final JLabel readsFileLabel = new JLabel("Reads file:"); readsFileLabel.setMinimumSize(labelDim); readsFileLabel.setMaximumSize(labelDim); leftPanel.add(readsFileLabel); final JPanel aLine = new JPanel(); aLine.setLayout(new BoxLayout(aLine, BoxLayout.X_AXIS)); aLine.setMinimumSize(minLineDim); aLine.setMaximumSize(maxLineDim); fileNameField.setEditable(needToSaveReads); aLine.add(fileNameField); final JButton browseButton = new JButton(new AbstractAction("Browse...") { @Override public void actionPerformed(ActionEvent e) { final File readsFile = ChooseFileDialog.chooseFileToSave(viewer.getFrame(), new File(fileNameField.getText()), new FastaFileFilter(), new FastaFileFilter(), null, "Save READS file", ".fasta"); if (readsFile != null) { fileNameField.setText(readsFile.getPath()); } } }); browseButton.setEnabled(needToSaveReads); aLine.add(browseButton); rightPanel.add(aLine); fileNameField.setToolTipText("Reads will be saved to this file"); } final JCheckBox longReadsCheckBox = new JCheckBox(); { final JLabel longReadsLabel = new JLabel("Long reads:"); longReadsLabel.setMinimumSize(labelDim); longReadsLabel.setMaximumSize(labelDim); leftPanel.add(longReadsLabel); final JPanel aLine = new JPanel(); aLine.setLayout(new BoxLayout(aLine, BoxLayout.X_AXIS)); aLine.setMinimumSize(minLineDim); aLine.setMaximumSize(maxLineDim); aLine.add(longReadsCheckBox); longReadsCheckBox.setSelected(dir.getDocument().isLongReads()); rightPanel.add(aLine); longReadsCheckBox.setToolTipText("Are these long reads that are expected to contain more than one gene?"); } final JComboBox<RemoteBlastClient.BlastProgram> blastModeCBox = new JComboBox<>(); { final JLabel blastModeLabel = new JLabel("Blast Mode:"); blastModeLabel.setMinimumSize(labelDim); blastModeLabel.setMaximumSize(labelDim); leftPanel.add(blastModeLabel); final JPanel aLine = new JPanel(); aLine.setLayout(new BoxLayout(aLine, BoxLayout.X_AXIS)); aLine.setMinimumSize(minLineDim); aLine.setMaximumSize(maxLineDim); blastModeCBox.setEditable(false); final String previousMode = ProgramProperties.get("RemoteBlastMode", RemoteBlastClient.BlastProgram.blastn.toString()); for (RemoteBlastClient.BlastProgram mode : RemoteBlastClient.BlastProgram.values()) { blastModeCBox.addItem(mode); if (mode.toString().equalsIgnoreCase(previousMode)) blastModeCBox.setSelectedItem(mode); } aLine.add(blastModeCBox); aLine.add(Box.createHorizontalGlue()); rightPanel.add(aLine); blastModeCBox.setToolTipText("BLAST mode to be run at NCBI"); } final JComboBox<String> blastDataBaseCBox = new JComboBox<>(); { final JLabel blastDBLabel = new JLabel("Blast DB:"); blastDBLabel.setMinimumSize(labelDim); blastDBLabel.setMaximumSize(labelDim); leftPanel.add(blastDBLabel); final JPanel aLine = new JPanel(); aLine.setLayout(new BoxLayout(aLine, BoxLayout.X_AXIS)); aLine.setMinimumSize(minLineDim); aLine.setMaximumSize(maxLineDim); blastDataBaseCBox.setEditable(false); aLine.add(blastDataBaseCBox); aLine.add(Box.createHorizontalGlue()); rightPanel.add(aLine); blastModeCBox.addItemListener(e -> { blastDataBaseCBox.removeAllItems(); for (String item : RemoteBlastClient.getDatabaseNames(RemoteBlastClient.BlastProgram.valueOfIgnoreCase(blastModeCBox.getSelectedItem().toString()))) { blastDataBaseCBox.addItem(item); } }); final String previousDB = ProgramProperties.get("RemoteBlastDB", "nr"); for (String item : RemoteBlastClient.getDatabaseNames((RemoteBlastClient.BlastProgram) Objects.requireNonNull(blastModeCBox.getSelectedItem()))) { blastDataBaseCBox.addItem(item); if (item.equalsIgnoreCase(previousDB)) blastDataBaseCBox.setSelectedItem(item); } blastDataBaseCBox.setToolTipText("Blast database to be used at NCBI"); } final JPanel bottomPanel = new JPanel(); bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.X_AXIS)); bottomPanel.setBorder(BorderFactory.createEtchedBorder()); bottomPanel.add(Box.createHorizontalGlue()); final JButton cancelButton = new JButton(new AbstractAction("Cancel") { @Override public void actionPerformed(ActionEvent e) { dialog.setVisible(false); } }); bottomPanel.add(cancelButton); final JButton applyButton = new JButton(new AbstractAction("Apply") { @Override public void actionPerformed(ActionEvent e) { try { final String readsFile = fileNameField.getText().trim(); ProgramProperties.put("RemoteBlastDir", (new File(readsFile)).getParent()); if (readsFile.length() > 0) { if (needToSaveReads) { int maxNumberRemoteBlastReads = ProgramProperties.get("MaxNumberRemoteBlastReads", 100); final Collection<Pair<String, String>> pairs = readsProvider.getReads(maxNumberRemoteBlastReads + 1); if (pairs.size() > maxNumberRemoteBlastReads) { System.err.println("Number of reads (" + readsProvider.isReadsAvailable() + ") exceeds MaxNumberRemoteBlastReads (" + maxNumberRemoteBlastReads + ")"); System.err.println("Use 'setprop MaxNumberRemoteBlastReads=X' to change limit to X"); } int count = 0; try (BufferedWriter w = new BufferedWriter(new FileWriter(readsFile))) { for (Pair<String, String> pair : pairs) { w.write(String.format(">%s\n%s\n", pair.getFirst(), pair.getSecond())); if (++count == maxNumberRemoteBlastReads) break; } } catch (IOException ex) { NotificationsInSwing.showError("Write file failed: " + ex.getMessage()); return; } System.err.println("Reads written to: " + readsFile); } ProgramProperties.put("RemoteBlastDir", (new File(readsFile)).getParent()); if (blastDataBaseCBox.getSelectedItem() != null) ProgramProperties.put("RemoteBlastDB", blastDataBaseCBox.getSelectedItem().toString()); if (blastModeCBox.getSelectedItem() != null) ProgramProperties.put("RemoteBlastMode", blastModeCBox.getSelectedItem().toString()); result.set("remoteBlastNCBI readsFile='" + fileNameField.getText().trim() + "' longReads=" + longReadsCheckBox.isSelected() + " blastMode=" + blastModeCBox.getSelectedItem() + " blastDB='" + blastDataBaseCBox.getSelectedItem() + "';"); } } finally { dialog.setVisible(false); } } }); fileNameField.addActionListener(e -> applyButton.setEnabled(fileNameField.getText().trim().length() > 0)); bottomPanel.add(applyButton); dialog.getContentPane().add(bottomPanel, BorderLayout.SOUTH); dialog.setVisible(true); return result.get(); } }
12,153
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
MetadataChart.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/MetadataChart.java
/* * MetadataChart.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.chart; import jloda.swing.util.ProgramProperties; import jloda.util.Basic; import jloda.util.CanceledException; import jloda.util.Pair; import megan.chart.data.DefaultChartData; import megan.chart.data.IChartData; import megan.chart.drawers.BarChartDrawer; import megan.chart.gui.ChartViewer; import megan.core.Director; import megan.core.Document; import megan.core.SampleAttributeTable; import megan.dialogs.input.InputDialog; import megan.main.MeganProperties; import megan.viewer.MainViewer; import java.awt.*; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.List; import java.util.*; /** * a metadata attribute chart * Daniel Huson, 10.2017 */ public class MetadataChart extends ChartViewer { private boolean inSync = false; private final String cName; /** * constructor * */ public MetadataChart(final Director dir, MainViewer parent) { super(parent, dir, dir.getDocument().getSampleLabelGetter(), new DefaultChartData(), ProgramProperties.isUseGUI()); cName = "MetaData"; MeganProperties.addPropertiesListListener(getJMenuBar().getRecentFilesListener()); MeganProperties.notifyListChange(ProgramProperties.RECENTFILES); getToolbar().addSeparator(new Dimension(5, 10)); getToolbar().add(getCommandManager().getButton("Sync")); chooseDrawer(BarChartDrawer.NAME); setChartTitle("Meta Data Chart for " + dir.getDocument().getTitle()); final IChartData chartData = (IChartData) getChartData(); String name = dir.getDocument().getTitle(); if (name.length() > 20) { chartData.setDataSetName(name.substring(0, 20)); name = name.substring(0, 20) + "..."; } getChartData().setDataSetName(name); setWindowTitle(cName + " Chart"); chartData.setSeriesLabel("Samples"); chartData.setClassesLabel(cName); chartData.setCountsLabel("Counts"); setClassLabelAngle(Math.PI / 4); addWindowListener(new WindowAdapter() { public void windowActivated(WindowEvent event) { final InputDialog inputDialog = InputDialog.getInstance(); if (inputDialog != null) inputDialog.setViewer(dir, MetadataChart.this); } }); try { sync(); } catch (CanceledException e) { Basic.caught(e); } int[] geometry = ProgramProperties.get(cName + "ChartGeometry", new int[]{100, 100, 800, 600}); setSize(geometry[2], geometry[3]); setVisible(true); getFrame().addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent e) { ProgramProperties.put(cName + "ChartGeometry", new int[]{ getLocation().x, getLocation().y, getSize().width, getSize().height}); } }); } /** * synchronize chart to reflect latest user selection in taxon chart */ public void sync() throws CanceledException { if (!inSync) { inSync = true; final IChartData chartData = (IChartData) getChartData(); chartData.clear(); final Document doc = dir.getDocument(); final SampleAttributeTable attributeTable = doc.getSampleAttributeTable(); setChartTitle("Meta Data Chart for " + dir.getDocument().getTitle()); final int numberOfSamples = doc.getNumberOfSamples(); if (numberOfSamples > 0) { final ArrayList<String> sampleNames = new ArrayList<>(doc.getSampleNames()); chartData.setAllSeries(sampleNames); final Map<String, float[]> attribute2sample2value = attributeTable.getNumericalAttributes(sampleNames, false); final Set<String> classNames = new TreeSet<>(); for (String attribute : attributeTable.getAttributeOrder()) { if (!attributeTable.isSecretAttribute(attribute) && !attributeTable.isHiddenAttribute(attribute)) { final float[] values = attribute2sample2value.get(attribute); if (values != null) { // is a numerical attribute int t = 0; for (String sample : attributeTable.getSampleOrder()) { chartData.putValue(sample, attribute, values[t++]); classNames.add(attribute); } } else { // no numerical attribute final Map<String, Integer> attributeValue2count = new HashMap<>(); long total = 0; for (String sample : attributeTable.getSampleOrder()) { final Object value = attributeTable.get(sample, attribute); final String key = attribute + ":" + value; attributeValue2count.merge(key, 1, Integer::sum); total++; } final Set<String> topAttributeValues = getTopFive(attributeValue2count); long covered = 0; for (String top : topAttributeValues) { covered += attributeValue2count.get(top); } if (covered > 0.5 * total) { for (String sample : attributeTable.getSampleOrder()) { final Object value = attributeTable.get(sample, attribute); final String key = attribute + ":" + value; if (topAttributeValues.contains(key)) { chartData.putValue(sample, key, 1); classNames.add(key); } else { chartData.putValue(sample, attribute + ":other", 1); classNames.add(attribute + ":other"); } } } } } } chartData.setClassNames(classNames); } super.sync(); inSync = false; } } /** * get the top five attributes * * @return top five */ private Set<String> getTopFive(Map<String, Integer> attributeValue2count) { final List<Pair<Integer, String>> count2attribute = new ArrayList<>(attributeValue2count.size()); for (String key : attributeValue2count.keySet()) { count2attribute.add(new Pair<>(-attributeValue2count.get(key), key)); } count2attribute.sort(new Pair<>()); final Set<String> result = new HashSet<>(); for (int i = 0; i < Math.min(10, count2attribute.size()); i++) result.add(count2attribute.get(i).getSecond()); return result; } /** * ask view to destroy itself */ public void destroyView() throws CanceledException { MeganProperties.removePropertiesListListener(getJMenuBar().getRecentFilesListener()); super.destroyView(); } /** * get name for this type of parent * * @return name */ public String getClassName() { return getClassName(cName); } public String getCName() { return cName; } private static String getClassName(String cName) { return cName + "Chart"; } }
8,678
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DiversityPlotViewer.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/DiversityPlotViewer.java
/* * DiversityPlotViewer.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.chart; import jloda.swing.util.ProgramProperties; import jloda.util.CanceledException; import jloda.util.Pair; import jloda.util.Single; import jloda.util.StringUtils; import megan.alignment.AlignmentViewer; import megan.alignment.WordCountAnalysis; import megan.chart.data.DefaultPlot2DData; import megan.chart.data.IPlot2DData; import megan.chart.drawers.Plot2DDrawer; import megan.chart.gui.ChartViewer; import megan.core.Director; import megan.dialogs.input.InputDialog; import megan.main.MeganProperties; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Comparator; import java.util.LinkedList; import java.util.SortedMap; import java.util.TreeMap; /** * a diversity chart * Daniel Huson, 6.2012 */ public class DiversityPlotViewer extends ChartViewer { private final AlignmentViewer alignmentViewer; private final int kmer; private final int step; private final int mindepth; private boolean inSync = false; /** * constructor * */ public DiversityPlotViewer(final Director dir, AlignmentViewer alignmentViewer, int kmer, int step, int mindepth) throws CanceledException { super(dir.getMainViewer(), dir, dir.getDocument().getSampleLabelGetter(), new DefaultPlot2DData(), ProgramProperties.isUseGUI()); this.alignmentViewer = alignmentViewer; this.kmer = kmer; this.step = step; this.mindepth = mindepth; getToolbar().addSeparator(new Dimension(5, 10)); getToolbar().add(getCommandManager().getButton("Sync")); MeganProperties.addPropertiesListListener(getJMenuBar().getRecentFilesListener()); MeganProperties.notifyListChange(ProgramProperties.RECENTFILES); chooseDrawer(Plot2DDrawer.NAME); IPlot2DData chartData = new DefaultPlot2DData(); setChartTitle("Diversity plot for " + alignmentViewer.getSelectedReference()); String name = StringUtils.swallowLeadingGreaterSign(alignmentViewer.getSelectedReference()); if (name.length() > 20) { chartData.setDataSetName(name.substring(0, 20)); name = name.substring(0, 20) + "..."; } else chartData.setDataSetName(name); setWindowTitle("Diversity plot for '" + name + "'"); getChartDrawer().setClassLabelAngle(0); sync(); int[] geometry = ProgramProperties.get(MeganProperties.TAXA_CHART_WINDOW_GEOMETRY, new int[]{100, 100, 800, 600}); setSize(geometry[2], geometry[3]); addWindowListener(new WindowAdapter() { public void windowActivated(WindowEvent event) { InputDialog inputDialog = InputDialog.getInstance(); if (inputDialog != null) inputDialog.setViewer(dir, DiversityPlotViewer.this); } }); } /** * synchronize chart to reflect latest user selection in taxon chart */ public void sync() throws CanceledException { if (!inSync) { inSync = true; String dataSetName = "Data"; ((Plot2DDrawer) getChartDrawer()).setShowLines(dataSetName, false); ((Plot2DDrawer) getChartDrawer()).setShowDots(dataSetName, true); ((Plot2DDrawer) getChartDrawer()).setUseJitter(dataSetName, true); getChartColorManager().setSampleColor(dataSetName, Color.GRAY); setShowLegend("none"); String graphName = "Menten Kinetics"; ((Plot2DDrawer) getChartDrawer()).setShowLines(graphName, true); ((Plot2DDrawer) getChartDrawer()).setShowDots(graphName, false); IPlot2DData chartData = (IPlot2DData) getChartData(); chartData.clear(); LinkedList<Pair<Number, Number>> values = new LinkedList<>(); SortedMap<Number, Number> rank2percentage = new TreeMap<>(Comparator.comparingDouble(Number::doubleValue)); WordCountAnalysis.apply(alignmentViewer.getAlignment(), kmer, step, mindepth, dir.getDocument().getProgressListener(), values, rank2percentage); Single<Integer> extrapolatedCount = new Single<>(); LinkedList<Pair<Number, Number>> mentenKinetics = WordCountAnalysis.computeMentenKinetics(values, extrapolatedCount); chartData.setDataForSeries(graphName, mentenKinetics); getChartColorManager().setSampleColor(graphName, Color.BLUE); if (extrapolatedCount.get() != null && extrapolatedCount.get() > 0) { LinkedList<Pair<Number, Number>> exCount = new LinkedList<>(); Pair<Number, Number> range = chartData.getRangeX(); exCount.add(new Pair<>(range.getFirst(), extrapolatedCount.get())); exCount.add(new Pair<>(range.getSecond(), extrapolatedCount.get())); chartData.setDataForSeries("Extrapolation", exCount); ((Plot2DDrawer) getChartDrawer()).setShowLines("Extrapolation", true); ((Plot2DDrawer) getChartDrawer()).setShowDots("Extrapolation", false); getChartColorManager().setSampleColor("Extrapolation", ProgramProperties.SELECTION_COLOR_ADDITIONAL_TEXT); } double predicted = 0; if (mentenKinetics.size() > 0) predicted = mentenKinetics.getLast().getSecond().doubleValue(); chartData.setDataForSeries(dataSetName, values); getStatusbar().setText1("Size: " + values.size()); Pair<Float, Float> averageNandK = WordCountAnalysis.computeAverageNandK(values); getStatusbar().setText2(String.format("Average diversity ratio: %.1f/%.1f = %.1f. Distinct genomes: min=%d extrapolation=%d", averageNandK.getSecond(), averageNandK.getFirst(), averageNandK.getFirst() > 0 ? averageNandK.getSecond() / averageNandK.getFirst() : 0, (int) Math.round(predicted), extrapolatedCount.get())); getChartData().setSeriesLabel("Number of sequences (n)"); getChartData().setCountsLabel("Number of distinct sequences (k)"); super.sync(); inSync = false; } } /** * ask view to destroy itself */ public void destroyView() throws CanceledException { MeganProperties.removePropertiesListListener(getJMenuBar().getRecentFilesListener()); super.destroyView(); } /** * get name for this type of viewer * * @return name */ public String getClassName() { return "DiversityPlotViewer"; } }
7,391
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
IMultiChartDrawable.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/IMultiChartDrawable.java
/* * IMultiChartDrawable.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.chart; import java.awt.*; /** * drawers that fulfill this interface can be used in a multi chart drawer * Daniel Huson, 4.2015 */ public interface IMultiChartDrawable extends IChartDrawer { void setWidth(int width); int getWidth(); void setHeight(int height); int getHeight(); void setMargins(int leftMargin, int topMargin, int rightMargin, int bottomMargin); void setGraphics(Graphics graphics); Graphics getGraphics(); /** * copy all user parameters from the given base drawer * */ void setValues(IMultiChartDrawable baseDrawer); /** * creates an instance that is then used to draw a particular panel * * @return instance */ IMultiChartDrawable createInstance(); }
1,585
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
AttributesChart.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/AttributesChart.java
/* * AttributesChart.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.chart; import jloda.swing.util.ProgramProperties; import jloda.util.Basic; import jloda.util.CanceledException; import megan.chart.data.DefaultChartData; import megan.chart.data.IChartData; import megan.chart.drawers.BarChartDrawer; import megan.chart.gui.ChartViewer; import megan.core.Director; import megan.core.Document; import megan.dialogs.attributes.MicrobialAttributes; import megan.dialogs.input.InputDialog; import megan.main.MeganProperties; import megan.viewer.MainViewer; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; /** * a taxa chart * Daniel Huson, 6.2012 */ public class AttributesChart extends ChartViewer { private boolean inSync = false; /** * constructor * */ public AttributesChart(final Director dir) { super(dir.getMainViewer(), dir, dir.getDocument().getSampleLabelGetter(), new DefaultChartData(), ProgramProperties.isUseGUI()); MeganProperties.addPropertiesListListener(getJMenuBar().getRecentFilesListener()); MeganProperties.notifyListChange(ProgramProperties.RECENTFILES); getToolbar().addSeparator(new Dimension(5, 10)); getToolbar().add(getCommandManager().getButton("Sync")); chooseDrawer(BarChartDrawer.NAME); setChartTitle("Microbial Attributes for " + dir.getDocument().getTitle()); IChartData chartData = (IChartData) getChartData(); String name = dir.getDocument().getTitle(); if (name.length() > 20) chartData.setDataSetName(name.substring(0, 20)); else getChartData().setDataSetName(name); setWindowTitle("Microbial Attributes Chart"); chartData.setSeriesLabel("Samples"); chartData.setClassesLabel("Microbial Attributes"); chartData.setCountsLabel(dir.getDocument().getReadAssignmentMode().getDisplayLabel()); setClassLabelAngle(Math.PI / 4); //setShowLegend(true); addWindowListener(new WindowAdapter() { public void windowActivated(WindowEvent event) { InputDialog inputDialog = InputDialog.getInstance(); if (inputDialog != null) inputDialog.setViewer(dir, AttributesChart.this); } }); try { sync(); } catch (CanceledException e) { Basic.caught(e); } setVisible(true); } /** * synchronize chart to reflect latest user selection in taxon chart */ public void sync() throws CanceledException { if (!inSync) { inSync = true; IChartData chartData = (IChartData) getChartData(); chartData.clear(); MicrobialAttributes attributes = MicrobialAttributes.getInstance(); Document doc = dir.getDocument(); MainViewer mainViewer = dir.getMainViewer(); int numberOfDatasets = doc.getNumberOfSamples(); if (numberOfDatasets > 0) { final Map<String, Map<String, Integer>> dataset2AttributeState2Value = attributes.getDataSet2AttributeState2Value(mainViewer); chartData.setAllSeries(doc.getSampleNames()); SortedSet<String> classNames = new TreeSet<>(); for (String series : dataset2AttributeState2Value.keySet()) { Map<String, Integer> attributeState2value = dataset2AttributeState2Value.get(series); for (String attributeState : attributeState2value.keySet()) { classNames.add(attributeState); Integer value = attributeState2value.get(attributeState); if (value == null) value = 0; chartData.putValue(series, attributeState, value); } } chartData.setClassNames(classNames); } super.sync(); inSync = false; } } /** * ask view to destroy itself */ public void destroyView() throws CanceledException { super.destroyView(); } /** * get name for this type of viewer * * @return name */ public String getClassName() { return "MicrobialAttributesChart"; } }
5,207
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z